forked from BenLangmead/bowtie2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpat.h
1617 lines (1454 loc) · 39 KB
/
pat.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2011, Ben Langmead <[email protected]>
*
* This file is part of Bowtie 2.
*
* Bowtie 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Bowtie 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Bowtie 2. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PAT_H_
#define PAT_H_
#include <cassert>
#include <cmath>
#include <stdexcept>
#include <vector>
#include <string>
#include <cstring>
#include <ctype.h>
#include <fstream>
#include "alphabet.h"
#include "assert_helpers.h"
#include "tokenize.h"
#include "random_source.h"
#include "threading.h"
#include "filebuf.h"
#include "qual.h"
#include "search_globals.h"
#include "sstring.h"
#include "ds.h"
#include "read.h"
#include "util.h"
/**
* Classes and routines for reading reads from various input sources.
*/
using namespace std;
/**
* Calculate a per-read random seed based on a combination of
* the read data (incl. sequence, name, quals) and the global
* seed in '_randSeed'.
*/
static inline uint32_t genRandSeed(const BTDnaString& qry,
const BTString& qual,
const BTString& name,
uint32_t seed)
{
// Calculate a per-read random seed based on a combination of
// the read data (incl. sequence, name, quals) and the global
// seed
uint32_t rseed = (seed + 101) * 59 * 61 * 67 * 71 * 73 * 79 * 83;
size_t qlen = qry.length();
// Throw all the characters of the read into the random seed
for(size_t i = 0; i < qlen; i++) {
int p = (int)qry[i];
assert_leq(p, 4);
size_t off = ((i & 15) << 1);
rseed ^= (p << off);
}
// Throw all the quality values for the read into the random
// seed
for(size_t i = 0; i < qlen; i++) {
int p = (int)qual[i];
assert_leq(p, 255);
size_t off = ((i & 3) << 3);
rseed ^= (p << off);
}
// Throw all the characters in the read name into the random
// seed
size_t namelen = name.length();
for(size_t i = 0; i < namelen; i++) {
int p = (int)name[i];
if(p == '/') break;
assert_leq(p, 255);
size_t off = ((i & 3) << 3);
rseed ^= (p << off);
}
return rseed;
}
/**
* Parameters affecting how reads and read in.
*/
struct PatternParams {
PatternParams(
int format_,
bool fileParallel_,
uint32_t seed_,
bool useSpinlock_,
bool solexa64_,
bool phred64_,
bool intQuals_,
bool fuzzy_,
int sampleLen_,
int sampleFreq_,
uint32_t skip_) :
format(format_),
fileParallel(fileParallel_),
seed(seed_),
useSpinlock(useSpinlock_),
solexa64(solexa64_),
phred64(phred64_),
intQuals(intQuals_),
fuzzy(fuzzy_),
sampleLen(sampleLen_),
sampleFreq(sampleFreq_),
skip(skip_) { }
int format; // file format
bool fileParallel; // true -> wrap files with separate PairedPatternSources
uint32_t seed; // pseudo-random seed
bool useSpinlock; // use spin locks instead of pthreads
bool solexa64; // true -> qualities are on solexa64 scale
bool phred64; // true -> qualities are on phred64 scale
bool intQuals; // true -> qualities are space-separated numbers
bool fuzzy; // true -> try to parse fuzzy fastq
int sampleLen; // length of sampled reads for FastaContinuous...
int sampleFreq; // frequency of sampled reads for FastaContinuous...
uint32_t skip; // skip the first 'skip' patterns
};
/**
* Encapsulates a synchronized source of patterns; usually a file.
* Optionally reverses reads and quality strings before returning them,
* though that is usually more efficiently done by the concrete
* subclass. Concrete subclasses should delimit critical sections with
* calls to lock() and unlock().
*/
class PatternSource {
public:
PatternSource(const PatternParams& p) :
seed_(p.seed),
readCnt_(0),
numWrappers_(0),
doLocking_(true),
useSpinlock_(p.useSpinlock),
mutex()
{
}
virtual ~PatternSource() { }
/**
* Call this whenever this PatternSource is wrapped by a new
* WrappedPatternSourcePerThread. This helps us keep track of
* whether locks will be contended.
*/
void addWrapper() {
lock();
numWrappers_++;
unlock();
}
/**
* The main member function for dispensing patterns.
*
* Returns true iff a pair was parsed succesfully.
*/
virtual bool nextReadPair(
Read& ra,
Read& rb,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done,
bool& paired,
bool fixName);
/**
* The main member function for dispensing patterns.
*/
virtual bool nextRead(
Read& r,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done);
/**
* Implementation to be provided by concrete subclasses. An
* implementation for this member is only relevant for formats that
* can read in a pair of reads in a single transaction with a
* single input source. If paired-end input is given as a pair of
* parallel files, this member should throw an error and exit.
*/
virtual bool nextReadPairImpl(
Read& ra,
Read& rb,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done,
bool& paired) = 0;
/**
* Implementation to be provided by concrete subclasses. An
* implementation for this member is only relevant for formats
* where individual input sources look like single-end-read
* sources, e.g., formats where paired-end reads are specified in
* parallel read files.
*/
virtual bool nextReadImpl(
Read& r,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done) = 0;
/// Reset state to start over again with the first read
virtual void reset() { readCnt_ = 0; }
/**
* Concrete subclasses call lock() to enter a critical region.
* What constitutes a critical region depends on the subclass.
*/
void lock() {
if(!doLocking_) return; // no contention
mutex.lock();
}
/**
* Concrete subclasses call unlock() to exit a critical region
* What constitutes a critical region depends on the subclass.
*/
void unlock() {
if(!doLocking_) return; // no contention
mutex.unlock();
}
/**
* Return a new dynamically allocated PatternSource for the given
* format, using the given list of strings as the filenames to read
* from or as the sequences themselves (i.e. if -c was used).
*/
static PatternSource* patsrcFromStrings(
const PatternParams& p,
const EList<string>& qs);
/**
* Return the number of reads attempted.
*/
TReadId readCnt() const { return readCnt_ - 1; }
protected:
uint32_t seed_;
/// The number of reads read by this PatternSource
TReadId readCnt_;
int numWrappers_; /// # threads that own a wrapper for this PatternSource
bool doLocking_; /// override whether to lock (true = don't override)
/// User can ask to use the normal pthreads-style lock even if
/// spinlocks is enabled and compiled in. This is sometimes better
/// if we expect bad I/O latency on some reads.
bool useSpinlock_;
MUTEX_T mutex;
};
/**
* Abstract parent class for synhconized sources of paired-end reads
* (and possibly also single-end reads).
*/
class PairedPatternSource {
public:
PairedPatternSource(const PatternParams& p) : mutex_m(), seed_(p.seed) {}
virtual ~PairedPatternSource() { }
virtual void addWrapper() = 0;
virtual void reset() = 0;
virtual bool nextReadPair(
Read& ra,
Read& rb,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done,
bool& paired,
bool fixName) = 0;
virtual pair<TReadId, TReadId> readCnt() const = 0;
/**
* Lock this PairedPatternSource, usually because one of its shared
* fields is being updated.
*/
void lock() {
mutex_m.lock();
}
/**
* Unlock this PairedPatternSource.
*/
void unlock() {
mutex_m.unlock();
}
/**
* Given the values for all of the various arguments used to specify
* the read and quality input, create a list of pattern sources to
* dispense them.
*/
static PairedPatternSource* setupPatternSources(
const EList<string>& si, // singles, from argv
const EList<string>& m1, // mate1's, from -1 arg
const EList<string>& m2, // mate2's, from -2 arg
const EList<string>& m12, // both mates on each line, from --12 arg
const EList<string>& q, // qualities associated with singles
const EList<string>& q1, // qualities associated with m1
const EList<string>& q2, // qualities associated with m2
const PatternParams& p, // read-in params
bool verbose); // be talkative?
protected:
static void free_EList_pmembers(const EList<PatternSource*>&);
MUTEX_T mutex_m; /// mutex for syncing over critical regions
uint32_t seed_;
};
/**
* Encapsulates a synchronized source of both paired-end reads and
* unpaired reads, where the paired-end must come from parallel files.
*/
class PairedSoloPatternSource : public PairedPatternSource {
public:
PairedSoloPatternSource(
const EList<PatternSource*>* src,
const PatternParams& p) :
PairedPatternSource(p),
cur_(0),
src_(src)
{
assert(src_ != NULL);
for(size_t i = 0; i < src_->size(); i++) {
assert((*src_)[i] != NULL);
}
}
virtual ~PairedSoloPatternSource() {
free_EList_pmembers(*src_);
delete src_;
}
/**
* Call this whenever this PairedPatternSource is wrapped by a new
* WrappedPatternSourcePerThread. This helps us keep track of
* whether locks within PatternSources will be contended.
*/
virtual void addWrapper() {
for(size_t i = 0; i < src_->size(); i++) {
(*src_)[i]->addWrapper();
}
}
/**
* Reset this object and all the PatternSources under it so that
* the next call to nextReadPair gets the very first read pair.
*/
virtual void reset() {
for(size_t i = 0; i < src_->size(); i++) {
(*src_)[i]->reset();
}
cur_ = 0;
}
/**
* The main member function for dispensing pairs of reads or
* singleton reads. Returns true iff ra and rb contain a new
* pair; returns false if ra contains a new unpaired read.
*/
virtual bool nextReadPair(
Read& ra,
Read& rb,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done,
bool& paired,
bool fixName);
/**
* Return the number of reads attempted.
*/
virtual pair<TReadId, TReadId> readCnt() const {
uint64_t ret = 0llu;
for(size_t i = 0; i < src_->size(); i++) ret += (*src_)[i]->readCnt();
return make_pair(ret, 0llu);
}
protected:
volatile uint32_t cur_; // current element in parallel srca_, srcb_ vectors
const EList<PatternSource*>* src_; /// PatternSources for paired-end reads
};
/**
* Encapsulates a synchronized source of both paired-end reads and
* unpaired reads, where the paired-end must come from parallel files.
*/
class PairedDualPatternSource : public PairedPatternSource {
public:
PairedDualPatternSource(
const EList<PatternSource*>* srca,
const EList<PatternSource*>* srcb,
const PatternParams& p) :
PairedPatternSource(p), cur_(0), srca_(srca), srcb_(srcb)
{
assert(srca_ != NULL);
assert(srcb_ != NULL);
// srca_ and srcb_ must be parallel
assert_eq(srca_->size(), srcb_->size());
for(size_t i = 0; i < srca_->size(); i++) {
// Can't have NULL first-mate sources. Second-mate sources
// can be NULL, in the case when the corresponding first-
// mate source is unpaired.
assert((*srca_)[i] != NULL);
for(size_t j = 0; j < srcb_->size(); j++) {
assert_neq((*srca_)[i], (*srcb_)[j]);
}
}
}
virtual ~PairedDualPatternSource() {
free_EList_pmembers(*srca_);
delete srca_;
free_EList_pmembers(*srcb_);
delete srcb_;
}
/**
* Call this whenever this PairedPatternSource is wrapped by a new
* WrappedPatternSourcePerThread. This helps us keep track of
* whether locks within PatternSources will be contended.
*/
virtual void addWrapper() {
for(size_t i = 0; i < srca_->size(); i++) {
(*srca_)[i]->addWrapper();
if((*srcb_)[i] != NULL) {
(*srcb_)[i]->addWrapper();
}
}
}
/**
* Reset this object and all the PatternSources under it so that
* the next call to nextReadPair gets the very first read pair.
*/
virtual void reset() {
for(size_t i = 0; i < srca_->size(); i++) {
(*srca_)[i]->reset();
if((*srcb_)[i] != NULL) {
(*srcb_)[i]->reset();
}
}
cur_ = 0;
}
/**
* The main member function for dispensing pairs of reads or
* singleton reads. Returns true iff ra and rb contain a new
* pair; returns false if ra contains a new unpaired read.
*/
virtual bool nextReadPair(
Read& ra,
Read& rb,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done,
bool& paired,
bool fixName);
/**
* Return the number of reads attempted.
*/
virtual pair<TReadId, TReadId> readCnt() const;
protected:
volatile uint32_t cur_; // current element in parallel srca_, srcb_ vectors
const EList<PatternSource*>* srca_; /// PatternSources for 1st mates and/or unpaired reads
const EList<PatternSource*>* srcb_; /// PatternSources for 2nd mates
};
/**
* Encapsulates a single thread's interaction with the PatternSource.
* Most notably, this class holds the buffers into which the
* PatterSource will write sequences. This class is *not* threadsafe
* - it doesn't need to be since there's one per thread. PatternSource
* is thread-safe.
*/
class PatternSourcePerThread {
public:
PatternSourcePerThread() :
buf1_(), buf2_(), rdid_(0xffffffff), endid_(0xffffffff) { }
virtual ~PatternSourcePerThread() { }
/**
* Read the next read pair.
*/
virtual bool nextReadPair(
bool& success,
bool& done,
bool& paired,
bool fixName)
{
return success;
}
Read& bufa() { return buf1_; }
Read& bufb() { return buf2_; }
const Read& bufa() const { return buf1_; }
const Read& bufb() const { return buf2_; }
TReadId rdid() const { return rdid_; }
TReadId endid() const { return endid_; }
virtual void reset() { rdid_ = endid_ = 0xffffffff; }
/**
* Return the length of mate 1 or mate 2.
*/
size_t length(int mate) const {
return (mate == 1) ? buf1_.length() : buf2_.length();
}
protected:
Read buf1_; // read buffer for mate a
Read buf2_; // read buffer for mate b
TReadId rdid_; // index of read just read
TReadId endid_; // index of read just read
};
/**
* Abstract parent factory for PatternSourcePerThreads.
*/
class PatternSourcePerThreadFactory {
public:
virtual ~PatternSourcePerThreadFactory() { }
virtual PatternSourcePerThread* create() const = 0;
virtual EList<PatternSourcePerThread*>* create(uint32_t n) const = 0;
/// Free memory associated with a pattern source
virtual void destroy(PatternSourcePerThread* patsrc) const {
assert(patsrc != NULL);
// Free the PatternSourcePerThread
delete patsrc;
}
/// Free memory associated with a pattern source list
virtual void destroy(EList<PatternSourcePerThread*>* patsrcs) const {
assert(patsrcs != NULL);
// Free all of the PatternSourcePerThreads
for(size_t i = 0; i < patsrcs->size(); i++) {
if((*patsrcs)[i] != NULL) {
delete (*patsrcs)[i];
(*patsrcs)[i] = NULL;
}
}
// Free the vector
delete patsrcs;
}
};
/**
* A per-thread wrapper for a PairedPatternSource.
*/
class WrappedPatternSourcePerThread : public PatternSourcePerThread {
public:
WrappedPatternSourcePerThread(PairedPatternSource& __patsrc) :
patsrc_(__patsrc)
{
patsrc_.addWrapper();
}
/**
* Get the next paired or unpaired read from the wrapped
* PairedPatternSource.
*/
virtual bool nextReadPair(
bool& success,
bool& done,
bool& paired,
bool fixName);
private:
/// Container for obtaining paired reads from PatternSources
PairedPatternSource& patsrc_;
};
/**
* Abstract parent factory for PatternSourcePerThreads.
*/
class WrappedPatternSourcePerThreadFactory : public PatternSourcePerThreadFactory {
public:
WrappedPatternSourcePerThreadFactory(PairedPatternSource& patsrc) :
patsrc_(patsrc) { }
/**
* Create a new heap-allocated WrappedPatternSourcePerThreads.
*/
virtual PatternSourcePerThread* create() const {
return new WrappedPatternSourcePerThread(patsrc_);
}
/**
* Create a new heap-allocated vector of heap-allocated
* WrappedPatternSourcePerThreads.
*/
virtual EList<PatternSourcePerThread*>* create(uint32_t n) const {
EList<PatternSourcePerThread*>* v = new EList<PatternSourcePerThread*>;
for(size_t i = 0; i < n; i++) {
v->push_back(new WrappedPatternSourcePerThread(patsrc_));
assert(v->back() != NULL);
}
return v;
}
private:
/// Container for obtaining paired reads from PatternSources
PairedPatternSource& patsrc_;
};
/// Skip to the end of the current string of newline chars and return
/// the first character after the newline chars, or -1 for EOF
static inline int getOverNewline(FileBuf& in) {
int c;
while(isspace(c = in.get()));
return c;
}
/// Skip to the end of the current string of newline chars such that
/// the next call to get() returns the first character after the
/// whitespace
static inline int peekOverNewline(FileBuf& in) {
while(true) {
int c = in.peek();
if(c != '\r' && c != '\n') {
return c;
}
in.get();
}
}
/// Skip to the end of the current line; return the first character
/// of the next line or -1 for EOF
static inline int getToEndOfLine(FileBuf& in) {
while(true) {
int c = in.get(); if(c < 0) return -1;
if(c == '\n' || c == '\r') {
while(c == '\n' || c == '\r') {
c = in.get(); if(c < 0) return -1;
}
// c now holds first character of next line
return c;
}
}
}
/// Skip to the end of the current line such that the next call to
/// get() returns the first character on the next line
static inline int peekToEndOfLine(FileBuf& in) {
while(true) {
int c = in.get(); if(c < 0) return c;
if(c == '\n' || c == '\r') {
c = in.peek();
while(c == '\n' || c == '\r') {
in.get(); if(c < 0) return c; // consume \r or \n
c = in.peek();
}
// next get() gets first character of next line
return c;
}
}
}
extern void wrongQualityFormat(const BTString& read_name);
extern void tooFewQualities(const BTString& read_name);
extern void tooManyQualities(const BTString& read_name);
/**
* Encapsulates a source of patterns which is an in-memory vector.
*/
class VectorPatternSource : public PatternSource {
public:
VectorPatternSource(
const EList<string>& v,
const PatternParams& p);
virtual ~VectorPatternSource() { }
virtual bool nextReadImpl(
Read& r,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done);
/**
* This is unused, but implementation is given for completeness.
*/
virtual bool nextReadPairImpl(
Read& ra,
Read& rb,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done,
bool& paired);
virtual void reset() {
PatternSource::reset();
cur_ = skip_;
paired_ = false;
}
private:
size_t cur_;
uint32_t skip_;
bool paired_;
EList<BTDnaString> v_; // forward sequences
EList<BTString> quals_; // forward qualities
EList<BTString> names_; // names
EList<int> trimmed3_; // names
EList<int> trimmed5_; // names
};
/**
*
*/
class BufferedFilePatternSource : public PatternSource {
public:
BufferedFilePatternSource(
const EList<string>& infiles,
const PatternParams& p) :
PatternSource(p),
infiles_(infiles),
filecur_(0),
fb_(),
skip_(p.skip),
first_(true)
{
assert_gt(infiles.size(), 0);
errs_.resize(infiles_.size());
errs_.fill(0, infiles_.size(), false);
assert(!fb_.isOpen());
open(); // open first file in the list
filecur_++;
}
virtual ~BufferedFilePatternSource() {
if(fb_.isOpen()) fb_.close();
}
/**
* Fill Read with the sequence, quality and name for the next
* read in the list of read files. This function gets called by
* all the search threads, so we must handle synchronization.
*/
virtual bool nextReadImpl(
Read& r,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done)
{
// We'll be manipulating our file handle/filecur_ state
lock();
while(true) {
do { read(r, rdid, endid, success, done); }
while(!success && !done);
if(!success && filecur_ < infiles_.size()) {
assert(done);
open();
resetForNextFile(); // reset state to handle a fresh file
filecur_++;
continue;
}
break;
}
assert(r.repOk());
// Leaving critical region
unlock();
return success;
}
/**
*
*/
virtual bool nextReadPairImpl(
Read& ra,
Read& rb,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done,
bool& paired)
{
// We'll be manipulating our file handle/filecur_ state
lock();
while(true) {
do { readPair(ra, rb, rdid, endid, success, done, paired); }
while(!success && !done);
if(!success && filecur_ < infiles_.size()) {
assert(done);
open();
resetForNextFile(); // reset state to handle a fresh file
filecur_++;
continue;
}
break;
}
assert(ra.repOk());
assert(rb.repOk());
// Leaving critical region
unlock();
return success;
}
/**
* Reset state so that we read start reading again from the
* beginning of the first file. Should only be called by the
* master thread.
*/
virtual void reset() {
PatternSource::reset();
filecur_ = 0,
open();
filecur_++;
}
protected:
/// Read another pattern from the input file; this is overridden
/// to deal with specific file formats
virtual bool read(
Read& r,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done) = 0;
/// Read another pattern pair from the input file; this is
/// overridden to deal with specific file formats
virtual bool readPair(
Read& ra,
Read& rb,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done,
bool& paired) = 0;
/// Reset state to handle a fresh file
virtual void resetForNextFile() { }
void open() {
if(fb_.isOpen()) fb_.close();
while(filecur_ < infiles_.size()) {
// Open read
FILE *in;
if(infiles_[filecur_] == "-") {
in = stdin;
} else if((in = fopen(infiles_[filecur_].c_str(), "rb")) == NULL) {
if(!errs_[filecur_]) {
cerr << "Warning: Could not open read file \"" << infiles_[filecur_].c_str() << "\" for reading; skipping..." << endl;
errs_[filecur_] = true;
}
filecur_++;
continue;
}
fb_.newFile(in);
return;
}
cerr << "Error: No input read files were valid" << endl;
exit(1);
return;
}
EList<string> infiles_; // filenames for read files
EList<bool> errs_; // whether we've already printed an error for each file
size_t filecur_; // index into infiles_ of next file to read
FileBuf fb_; // read file currently being read from
TReadId skip_; // number of reads to skip
bool first_;
};
/**
* Parse a single quality string from fb and store qualities in r.
* Assume the next character obtained via fb.get() is the first
* character of the quality string. When returning, the next
* character returned by fb.peek() or fb.get() should be the first
* character of the following line.
*/
int parseQuals(
Read& r,
FileBuf& fb,
int firstc,
int readLen,
int trim3,
int trim5,
bool intQuals,
bool phred64,
bool solexa64);
/**
* Synchronized concrete pattern source for a list of FASTA or CSFASTA
* (if color = true) files.
*/
class FastaPatternSource : public BufferedFilePatternSource {
public:
FastaPatternSource(const EList<string>& infiles,
const PatternParams& p) :
BufferedFilePatternSource(infiles, p),
first_(true)
{ }
virtual void reset() {
first_ = true;
BufferedFilePatternSource::reset();
}
protected:
/**
* Scan to the next FASTA record (starting with >) and return the first
* character of the record (which will always be >).
*/
static int skipToNextFastaRecord(FileBuf& in) {
int c;
while((c = in.get()) != '>') {
if(in.eof()) return -1;
}
return c;
}
/// Called when we have to bail without having parsed a read.
void bail(Read& r) {
r.reset();
fb_.resetLastN();
}
/// Read another pattern from a FASTA input file
virtual bool read(
Read& r,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done);
/// Read another pair of patterns from a FASTA input file
virtual bool readPair(
Read& ra,
Read& rb,
TReadId& rdid,
TReadId& endid,
bool& success,
bool& done,
bool& paired)
{
// (For now, we shouldn't ever be here)
cerr << "In FastaPatternSource.readPair()" << endl;
throw 1;
return false;
}
virtual void resetForNextFile() {
first_ = true;
}
private:
bool first_;
};
/**
* Tokenize a line of space-separated integer quality values.