-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathStreamReader.cpp
More file actions
1240 lines (1059 loc) · 36.4 KB
/
StreamReader.cpp
File metadata and controls
1240 lines (1059 loc) · 36.4 KB
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 (C) 2019 Guilherme De Sena Brandine and
* Andrew D. Smith
* Authors: Guilherme De Sena Brandine, Andrew Smith
*
* This program 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.
*
* This program 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.
*/
#include "StreamReader.hpp"
#include <algorithm>
#include <cstring>
#include <fstream>
#include <string>
#include <vector>
// this is faster than std::min
template <class T>
inline T
min8(const T a, const T b) {
return (a < b) ? a : b;
}
/****************************************************/
/***************** STREAMREADER *********************/
/****************************************************/
size_t
get_tile_split_position(FalcoConfig &config) {
const std::string &filename = config.filename;
// Count colons to know the formatting pattern
size_t num_colon = 0;
// If reading from stdin (stdin:<prefix>), we cannot open the file to
// inspect read names; assume no tile information.
if (filename.rfind("stdin:", 0) == 0)
return 0;
if (config.is_sam) {
std::ifstream sam_file(filename);
if (!sam_file)
throw std::runtime_error("cannot load sam file : " + filename);
std::string line;
while (std::getline(sam_file, line) && line.size() > 0 && line[0] == '@')
continue;
size_t tabPos = line.find('\t');
line = line.substr(0, tabPos);
for (char c : line)
num_colon += (c == ':');
}
#ifdef USE_HTS
else if (config.is_bam) {
htsFile *hts = hts_open(std::data(filename), "r");
if (!hts)
throw std::runtime_error("cannot load bam file : " + filename);
sam_hdr_t *hdr = sam_hdr_read(hts);
if (hdr == nullptr)
throw std::runtime_error("cannot read header from bam file : " +
filename);
bam1_t *b = bam_init1();
if (sam_read1(hts, hdr, b) < -1) {
hts_close(hts);
sam_hdr_destroy(hdr);
bam_destroy1(b);
throw std::runtime_error("cannot read entry from bam file : " + filename);
}
else {
std::string first_entry_name(bam_get_qname(b));
const auto lim(end(first_entry_name));
for (auto itr(begin(first_entry_name)); itr != lim; ++itr) {
num_colon += (*itr == ':');
}
hts_close(hts);
sam_hdr_destroy(hdr);
bam_destroy1(b);
}
}
#endif
else if (config.is_fastq_gz) {
gzFile in = gzopen(std::data(filename), "rb");
if (!in)
throw std::runtime_error("problem reading input file: " + filename);
// Read the first line of the file
char buffer[1024];
gzgets(in, buffer, sizeof(buffer));
gzclose(in);
for (char *itr = buffer; *itr != '\0'; ++itr) {
num_colon += (*itr == ':');
}
}
else {
std::ifstream in(filename);
if (!in.good())
throw std::runtime_error("problem reading input file: " + filename);
// Read the first line of the file
std::string first_line;
std::getline(in, first_line);
in.close();
const auto lim(end(first_line));
for (auto itr(begin(first_line)); itr != lim; ++itr) {
num_colon += (*itr == ':');
}
}
// Copied from fastqc
if (num_colon >= 6)
return 4;
else if (num_colon >= 4)
return 2;
return 0; // no tile information on read name
}
// function to turn a vector into array for adapter hashes and fast lookup
std::array<size_t, Constants::max_adapters>
make_adapters(const std::vector<size_t> &adapter_hashes) {
if (adapter_hashes.size() > Constants::max_adapters)
throw std::runtime_error(
"Number of adapters is larger than 128, which hinders "
"visualziation and speed of falco. Please keep it to "
"under 128");
std::array<size_t, Constants::max_adapters> ans;
for (size_t i = 0; i < adapter_hashes.size(); ++i)
ans[i] = adapter_hashes[i];
return ans;
}
StreamReader::StreamReader(FalcoConfig &config, const size_t _buffer_size,
const char _field_separator,
const char _line_separator) :
// I have to pass the config skips as const to read them fast
do_sequence_hash(config.do_duplication || config.do_overrepresented),
do_kmer(config.do_kmer), do_adapter(config.do_adapter),
do_adapter_optimized(config.do_adapter_optimized),
do_sliding_window(do_adapter_optimized || do_kmer),
do_n_content(config.do_n_content), do_quality_base(config.do_quality_base),
do_sequence(config.do_sequence), do_gc_sequence(config.do_gc_sequence),
do_quality_sequence(config.do_quality_sequence), do_tile(config.do_tile),
do_sequence_length(config.do_sequence_length),
// Here are the usual stream reader configs
field_separator(_field_separator), line_separator(_line_separator),
buffer_size(_buffer_size), read_step(config.read_step),
tile_split_point(get_tile_split_position(config)),
tile_ignore(!do_tile || tile_split_point == 0),
// Here are the const adapters
do_adapters_slow(config.do_adapter && !config.do_adapter_optimized),
adapter_seqs(config.adapter_seqs),
num_adapters(config.adapter_hashes.size()), adapter_size(config.adapter_size),
// for case size == 32 expr (1ull << 64) -1 gives 0.
// We need to set mask as all 64 bits 1 => use SIZE_MAX in this case
adapter_mask(adapter_size == 32 ? SIZE_MAX
: (1ull << (2 * adapter_size)) - 1),
adapters(make_adapters(config.adapter_hashes)), filename(config.filename) {
// Allocates buffer to temporarily store reads
buffer = new char[buffer_size + 1]; // +1 for the \0
buffer[buffer_size] = '\0';
// duplication init
continue_storing_sequences = true;
// Tile init
tile_cur = 0;
// keep track of which reads to do tile
next_read = 0;
next_tile_read = 0;
next_kmer_read = 0;
do_tile_read = true;
// GS: test
leftover_ind = 0;
}
// Makes sure that any subclass deletes the buffer
StreamReader::~StreamReader() { delete[] buffer; }
/*******************************************************/
/*************** BUFFER MANAGEMENT *********************/
/*******************************************************/
// puts base either on buffer or leftover
void
StreamReader::put_base_in_buffer() {
base_from_buffer = *cur_char;
if (still_in_buffer) {
buffer[read_pos] = base_from_buffer;
}
else {
if (leftover_ind == leftover_buffer.size())
leftover_buffer.push_back(base_from_buffer);
else
leftover_buffer[leftover_ind] = base_from_buffer;
}
}
// Gets base from either buffer or leftover
void
StreamReader::get_base_from_buffer() {
base_from_buffer =
still_in_buffer ? buffer[read_pos] : leftover_buffer[leftover_ind];
}
/*******************************************************/
/*************** FAST FOWARD ***************************/
/*******************************************************/
// Keeps going forward while the current character is a separator
inline void
StreamReader::skip_separator() {
for (; *cur_char == field_separator; ++cur_char) {
}
}
// Skips lines that are not relevant
inline void
StreamReader::read_fast_forward_line() {
for (; *cur_char != field_separator; ++cur_char) {
}
}
inline void
StreamReader::read_fast_forward_line_eof() {
for (; (*cur_char != field_separator) && (*cur_char != line_separator) &&
!is_eof();
++cur_char) {
}
}
/*******************************************************/
/*************** TILE PROCESSING ***********************/
/*******************************************************/
// Parse the comment
void
StreamReader::get_tile_value() {
tile_cur = 0;
size_t num_colon = 0;
for (; *cur_char != field_separator; ++cur_char) {
num_colon += (*cur_char == ':');
if (num_colon == tile_split_point) {
++cur_char; // skip colon
// parse till next colon or \n
for (; (*cur_char != ':') && (*cur_char != field_separator); ++cur_char)
tile_cur = tile_cur * 10 + (*cur_char - '0');
// now fast forward until last \n
for (; *cur_char != field_separator; ++cur_char)
;
return;
}
}
}
// Gets the tile from the sequence name (if applicable)
void
StreamReader::read_tile_line(FastqStats &stats) {
do_tile_read = (do_read && stats.num_reads == next_tile_read);
if (!do_tile_read) {
read_fast_forward_line();
return;
}
// if there is no tile information in the fastq header, fast
// forward this line
if (tile_ignore) {
read_fast_forward_line();
return;
}
// Fast forward if this is not a tile line
if (stats.num_reads != next_tile_read) {
read_fast_forward_line();
return;
}
get_tile_value();
// allocate vector for tile if it doesn't exist
if (stats.tile_position_quality.find(tile_cur) ==
end(stats.tile_position_quality)) {
stats.tile_position_quality[tile_cur] =
std::vector<double>(stats.max_read_length, 0.0);
// stats.tile_position_quality.find(tile_cur)->second[0] = 0;
stats.tile_position_count[tile_cur] =
std::vector<size_t>(stats.max_read_length, 0);
}
}
/*******************************************************/
/*************** SEQUENCE PROCESSING *******************/
/*******************************************************/
// This is probably the most important function for speed, so it must be really
// optimized at all times
void
StreamReader::process_sequence_base_from_buffer(FastqStats &stats) {
// I will count the Ns even if asked to ignore, as checking ifs take time
if (base_from_buffer == 'N') {
++stats.n_base_count[read_pos];
num_bases_after_n = 1; // start over the current kmer
}
// ATGC bases
else {
// increments basic statistic counts
cur_gc_count += (actg_to_2bit(base_from_buffer) & 1);
++stats.base_count[(read_pos << Constants::bit_shift_base) |
actg_to_2bit(base_from_buffer)];
if (do_sliding_window) {
// Update k-mer sequence
cur_kmer = ((cur_kmer << Constants::bit_shift_base) |
actg_to_2bit(base_from_buffer));
// registers k-mer if seen at least k nucleotides since the last n
if (do_kmer && do_kmer_read &&
(num_bases_after_n >= Constants::kmer_size)) {
++stats.kmer_count[(read_pos << Constants::bit_shift_kmer) |
(cur_kmer & Constants::kmer_mask)];
++stats.pos_kmer_count[read_pos];
}
// GS: slow, need to use fsm
if (do_adapter_optimized && (num_bases_after_n == adapter_size)) {
cur_kmer &= adapter_mask;
for (size_t i = 0; i != num_adapters; ++i) {
if (cur_kmer == adapters[i] && !adapters_found[i]) {
++stats
.pos_adapter_count[(read_pos << Constants::bit_shift_adapter) |
i];
adapters_found[i] = true;
}
}
}
num_bases_after_n += (num_bases_after_n != adapter_size);
}
}
}
// slower version of process_sequence_base_from_buffer that dynamically
// allocates if base position is not already cached
void
StreamReader::process_sequence_base_from_leftover(FastqStats &stats) {
if (base_from_buffer == 'N') {
++stats.long_n_base_count[leftover_ind];
num_bases_after_n = 1; // start over the current kmer
}
// ATGC bases
else {
// increments basic statistic counts
cur_gc_count += (actg_to_2bit(base_from_buffer) & 1);
++stats.long_base_count[(leftover_ind << Constants::bit_shift_base) |
actg_to_2bit(base_from_buffer)];
// WE WILL NOT DO KMER STATS OUTSIDE OF BUFFER
}
}
// Gets statistics after reading the entire sequence line
void
StreamReader::postprocess_sequence_line(FastqStats &stats) {
// Updates basic statistics total GC
stats.total_gc += cur_gc_count;
// read length frequency histogram
if (do_sequence_length) {
if (still_in_buffer) {
stats.empty_reads += (read_pos == 0);
if (read_pos != 0)
++stats.read_length_freq[read_pos - 1];
}
else
++stats.long_read_length_freq[leftover_ind - 1];
}
// Updates maximum read length if applicable
stats.max_read_length =
((read_pos > stats.max_read_length) ? (read_pos) : (stats.max_read_length));
// FastQC's gc model summarized, if requested
if (do_gc_sequence && read_pos != 0) {
// If we haven't passed the short base threshold, we use the cached models
if (still_in_buffer) {
// if we haven't passed the truncation point, use the current values,
// otherwise we have truncated previously
if (next_truncation == 100) {
truncated_length = read_pos;
truncated_gc_count = cur_gc_count;
}
for (const auto &v :
stats.gc_models[truncated_length].models[truncated_gc_count]) {
stats.gc_count[v.percent] += v.increment;
}
// if the read length is too large, we just use the discrete percentage
}
else {
++stats.gc_count[100 * cur_gc_count / read_pos];
}
}
}
// Reads the line that has the biological sequence
void
StreamReader::read_sequence_line(FastqStats &stats) {
if (!do_read) {
read_fast_forward_line();
return;
}
// restart line counters
read_pos = 0;
cur_gc_count = 0;
truncated_gc_count = 0;
num_bases_after_n = 1;
still_in_buffer = true;
next_truncation = 100;
do_kmer_read = (stats.num_reads == next_kmer_read);
adapters_found.reset();
if (do_adapters_slow) {
const std::string seq_line_str = cur_char;
for (size_t i = 0; i != num_adapters; ++i) {
const size_t adapt_index = seq_line_str.find(adapter_seqs[i], 0);
if (adapt_index < stats.SHORT_READ_THRESHOLD) {
++stats.pos_adapter_count[((adapt_index + adapter_seqs[i].length() - 1)
<< Constants::bit_shift_adapter) |
i];
}
}
}
/*********************************************************/
/********** THIS LOOP MUST BE ALWAYS OPTIMIZED ***********/
/*********************************************************/
for (; *cur_char != field_separator; ++cur_char, ++read_pos) {
// if we reached the buffer size, stop using it and start using leftover
if (read_pos == buffer_size) {
still_in_buffer = false;
leftover_ind = 0;
}
// Make sure we have memory space to process new base
if (!still_in_buffer) {
if (leftover_ind == stats.num_extra_bases) {
stats.allocate_new_base(tile_ignore);
}
}
// puts base either on buffer or leftover
put_base_in_buffer();
// statistics updated base by base
// use buffer
if (still_in_buffer) {
process_sequence_base_from_buffer(stats);
}
// use dynamic allocation
else {
process_sequence_base_from_leftover(stats);
// Increase leftover pos if no longer in buffer
++leftover_ind;
}
// Truncate GC counts to multiples of 100
if (do_gc_sequence && read_pos == next_truncation) {
truncated_gc_count = cur_gc_count;
truncated_length = read_pos;
next_truncation += 100;
}
}
// statistics summarized after the read
postprocess_sequence_line(stats);
}
/*******************************************************/
/*************** QUALITY PROCESSING ********************/
/*******************************************************/
// Process quality value the fast way from buffer
void
StreamReader::process_quality_base_from_buffer(FastqStats &stats) {
// Average quality in position
++stats.position_quality_count[(read_pos << Constants::bit_shift_quality) |
quality_value];
// Tile processing
if (!tile_ignore && do_tile_read && tile_cur != 0) {
// allocate more base space if necessary
if (stats.tile_position_quality[tile_cur].size() == read_pos) {
stats.tile_position_quality[tile_cur].push_back(0.0);
stats.tile_position_count[tile_cur].push_back(0);
}
stats.tile_position_quality[tile_cur][read_pos] += quality_value;
++stats.tile_position_count[tile_cur][read_pos];
}
}
// Slow version of function above
void
StreamReader::process_quality_base_from_leftover(FastqStats &stats) {
// Average quality in position
++stats.long_position_quality_count[(leftover_ind
<< Constants::bit_shift_quality) |
quality_value];
// Tile processing
if (!tile_ignore) {
if (do_tile_read && tile_cur != 0) {
stats.tile_position_quality[tile_cur][read_pos] += quality_value;
++stats.tile_position_count[tile_cur][read_pos];
}
}
}
// Reads the quality line of each base.
void
StreamReader::read_quality_line(FastqStats &stats) {
// MN: Below, the second condition tests whether the quality score in sam
// file only consists of '*', which indicates that no quality score is
// available
if (!do_read || (*cur_char == '*' && (*(cur_char + 1) == field_separator ||
*(cur_char + 1) == field_separator))) {
read_fast_forward_line_eof();
return;
}
// reset quality counts
read_pos = 0;
cur_quality = 0;
still_in_buffer = true;
// For quality, we do not look for the separator, but rather for an explicit
// newline or EOF in case the file does not end with newline or we are getting
// decompressed strings from a stream
for (; (*cur_char != field_separator) && (*cur_char != line_separator) &&
!is_eof();
++cur_char) {
if (read_pos == buffer_size) {
still_in_buffer = false;
leftover_ind = 0;
}
get_base_from_buffer();
// update lowest quality
stats.lowest_char = min8(
stats.lowest_char,
((*cur_char == 9) ? (std::numeric_limits<char>::max()) : (*cur_char)));
// Converts quality ascii to zero-based
quality_value = *cur_char - Constants::quality_zero;
// Fast bases from buffer
if (still_in_buffer) {
process_quality_base_from_buffer(stats);
}
// Slow bases from dynamic allocation
else {
process_quality_base_from_leftover(stats);
++leftover_ind;
}
// Sums quality value so we can bin the average at the end
cur_quality += quality_value;
// Flag to start reading and writing outside of buffer
++read_pos;
}
// Average quality approximated to the nearest integer. Used to make a
// histogram in the end of the summary.
if (read_pos != 0)
++stats.quality_count[cur_quality / read_pos]; // avg quality histogram
}
/*******************************************************/
/*************** POST LINE PROCESSING ******************/
/*******************************************************/
/*************** THIS IS VERY SLOW ********************/
// if reads are >75pb, truncate to 50 akin to FastQC
inline size_t
get_truncate_point(const size_t read_pos) {
return (read_pos <= Constants::unique_reads_max_length)
? read_pos
: Constants::unique_reads_truncate;
}
void
StreamReader::postprocess_fastq_record(FastqStats &stats) {
if (do_sequence_hash) {
buffer[get_truncate_point(read_pos)] = '\0';
sequence_to_hash = std::string(buffer);
// New sequence found
if (stats.sequence_count.count(sequence_to_hash) == 0) {
if (continue_storing_sequences) {
stats.sequence_count.insert({{sequence_to_hash, 1}});
stats.count_at_limit = stats.num_reads;
++stats.num_unique_seen;
// if we reached the cutoff of 100k, stop storing
if (stats.num_unique_seen == Constants::unique_reads_stop_counting)
continue_storing_sequences = false;
}
}
else {
++stats.sequence_count[sequence_to_hash];
stats.count_at_limit += continue_storing_sequences;
}
}
// counts tile if applicable
if (!tile_ignore) {
if (do_tile_read) {
next_tile_read += num_reads_for_tile;
}
}
next_kmer_read += do_kmer_read * num_reads_for_kmer;
}
inline bool
StreamReader::check_bytes_read(const size_t read_num) {
return ((read_num & check_bytes_read_mask) == 0);
}
/*******************************************************/
/*************** READ FASTQ RECORD *********************/
/*******************************************************/
char
get_line_separator(const std::string &filename) {
// If filename indicates stdin (stdin:<prefix>) assume standard newline
if (filename.rfind("stdin:", 0) == 0) {
return '\n';
}
FILE *fp = fopen(filename.c_str(), "r");
if (fp == NULL)
throw std::runtime_error("bad input file: " + filename);
while (!feof(fp)) {
const char c = fgetc(fp);
if (c == '\n' || c == '\r') {
fclose(fp);
return c;
}
}
fclose(fp);
return '\n';
}
// Set fastq field_separator as line_separator
FastqReader::FastqReader(FalcoConfig &_config, const size_t _buffer_size) :
StreamReader(_config, _buffer_size, get_line_separator(_config.filename),
get_line_separator(_config.filename)) {
filebuf = new char[RESERVE_SIZE];
}
size_t
get_file_size(const std::string &filename) {
// For stdin-mode inputs (stdin:<prefix>) we cannot determine size; return 1
if (filename.rfind("stdin:", 0) == 0) {
return 1;
}
FILE *fp = fopen(filename.c_str(), "r");
if (fp == NULL)
throw std::runtime_error("bad input file: " + filename);
fseek(fp, 0L, SEEK_END);
const size_t ret = static_cast<size_t>(ftell(fp));
fclose(fp);
return ret;
}
// Load fastq with zlib
size_t
FastqReader::load() {
// If filename indicates stdin (stdin:<prefix>) then use stdin as input
if (filename.rfind("stdin:", 0) == 0) {
fileobj = stdin;
return 1; // unknown size
}
fileobj = fopen(filename.c_str(), "r");
if (fileobj == NULL)
throw std::runtime_error("Cannot open FASTQ file : " + filename);
return get_file_size(filename);
}
// straightforward
inline bool
FastqReader::is_eof() {
return feof(fileobj);
}
FastqReader::~FastqReader() {
delete[] filebuf;
// Only close if it's not stdin
if (fileobj && fileobj != stdin)
fclose(fileobj);
}
// Parses fastq gz by reading line by line into the gzbuf
bool
FastqReader::read_entry(FastqStats &stats, size_t &num_bytes_read) {
cur_char = fgets(filebuf, RESERVE_SIZE, fileobj);
// need to check here if we did not hit eof
if (is_eof())
return false;
do_read = (stats.num_reads == next_read);
read_tile_line(stats);
skip_separator();
cur_char = fgets(filebuf, RESERVE_SIZE, fileobj);
read_sequence_line(stats);
skip_separator();
cur_char = fgets(filebuf, RESERVE_SIZE, fileobj);
read_fast_forward_line();
skip_separator();
cur_char = fgets(filebuf, RESERVE_SIZE, fileobj);
read_quality_line(stats);
skip_separator();
if (do_read)
postprocess_fastq_record(stats);
next_read += do_read * read_step;
// Successful read, increment number in stats
++stats.num_reads;
// Returns if file should keep being checked
if (check_bytes_read(stats.num_reads))
num_bytes_read = ftell(fileobj);
return (!is_eof() && cur_char != 0);
}
/*******************************************************/
/*************** READ FASTQ GZ RCORD *******************/
/*******************************************************/
// the gz fastq constructor is the same as the fastq
GzFastqReader::GzFastqReader(FalcoConfig &_config, const size_t _buffer_size) :
StreamReader(_config, _buffer_size, '\n', '\n') {
gzbuf = new char[RESERVE_SIZE];
}
// Load fastq with zlib
size_t
GzFastqReader::load() {
// We do not support reading compressed streams from stdin via this API.
// Users should decompress upstream (e.g. with zcat) and pass contents
// with the std:<prefix> convention. If filename indicates stdin, throw
// an informative error.
if (filename.rfind("stdin:", 0) == 0) {
throw std::runtime_error(
"Compressed stdin not supported: pipe decompressed data (e.g. zcat) "
"and use stdin:<prefix> as filename");
}
fileobj = gzopen(filename.c_str(), "r");
if (fileobj == Z_NULL)
throw std::runtime_error("Cannot open gzip FASTQ file : " + filename);
return get_file_size(filename);
}
// straightforward
inline bool
GzFastqReader::is_eof() {
return gzeof(fileobj);
}
GzFastqReader::~GzFastqReader() {
delete[] gzbuf;
gzclose_r(fileobj);
}
// Parses fastq gz by reading line by line into the gzbuf
bool
GzFastqReader::read_entry(FastqStats &stats, size_t &num_bytes_read) {
cur_char = gzgets(fileobj, gzbuf, RESERVE_SIZE);
// need to check here if we did not hit eof
if (is_eof()) {
return false;
}
do_read = (stats.num_reads == next_read);
read_tile_line(stats);
skip_separator();
cur_char = gzgets(fileobj, gzbuf, RESERVE_SIZE);
read_sequence_line(stats);
skip_separator();
cur_char = gzgets(fileobj, gzbuf, RESERVE_SIZE);
read_fast_forward_line();
skip_separator();
cur_char = gzgets(fileobj, gzbuf, RESERVE_SIZE);
read_quality_line(stats);
skip_separator();
if (do_read)
postprocess_fastq_record(stats);
next_read += do_read * read_step;
// Successful read, increment number in stats
++stats.num_reads;
// Returns if file should keep being checked
if (check_bytes_read(stats.num_reads))
num_bytes_read = gzoffset(fileobj);
return !is_eof();
}
/*******************************************************/
/*************** READ SAM RECORD ***********************/
/*******************************************************/
// set sam separator as tab
SamReader::SamReader(FalcoConfig &_config, const size_t _buffer_size) :
StreamReader(_config, _buffer_size, '\t',
get_line_separator(_config.filename)) {
filebuf = new char[RESERVE_SIZE];
}
size_t
SamReader::load() {
fileobj = fopen(filename.c_str(), "r");
if (fileobj == NULL)
throw std::runtime_error("Cannot open SAM file : " + filename);
// skip sam header
char first_char_in_line;
while (!is_eof() && ((first_char_in_line = fgetc(fileobj)) == '@')) {
ungetc(first_char_in_line, fileobj);
cur_char = fgets(filebuf, RESERVE_SIZE, fileobj);
}
return get_file_size(filename);
}
inline bool
SamReader::is_eof() {
return feof(fileobj);
}
bool
SamReader::read_entry(FastqStats &stats, size_t &num_bytes_read) {
cur_char = fgets(filebuf, RESERVE_SIZE, fileobj);
if (is_eof())
return false;
do_read = (stats.num_reads == next_read);
read_tile_line(stats);
skip_separator();
for (size_t i = 0; i < 8; ++i) {
read_fast_forward_line();
skip_separator();
}
// field 10
read_sequence_line(stats);
skip_separator();
// field 11
read_quality_line(stats);
if (do_read)
postprocess_fastq_record(stats);
next_read += do_read * read_step;
++stats.num_reads;
// skips all tags after quality until newline
for (; *cur_char != line_separator && !is_eof(); ++cur_char)
if (check_bytes_read(stats.num_reads))
num_bytes_read = ftell(fileobj);
// Returns if file should keep being checked
return (!is_eof() && cur_char != 0);
}
SamReader::~SamReader() {
delete[] filebuf;
fclose(fileobj);
}
#ifdef USE_HTS
// puts base either on buffer or leftover
void
BamReader::put_base_in_buffer(const size_t pos) {
base_from_buffer = seq_nt16_str[bam_seqi(cur_char, pos)];
if (still_in_buffer) {
buffer[read_pos] = base_from_buffer;
}
else {
if (leftover_ind == leftover_buffer.size())
leftover_buffer.push_back(base_from_buffer);
else
leftover_buffer[leftover_ind] = base_from_buffer;
}
}
// Specially made to work directly with bam1_t
void
BamReader::read_sequence_line(FastqStats &stats) {
if (!do_read)
return;
// restart line counters
read_pos = 0;
cur_gc_count = 0;
truncated_gc_count = 0;
num_bases_after_n = 1;
still_in_buffer = true;
next_truncation = 100;
do_kmer_read = (stats.num_reads == next_kmer_read);
adapters_found.reset();
const size_t seq_len = b->core.l_qseq;
// MN: TODO: make sure everything works in this scope
if (do_adapters_slow) {
std::string seq_line_str(seq_len, '\0');
for (size_t i = 0; i < seq_len; i++) {
seq_line_str[i] = seq_nt16_str[bam_seqi(cur_char, i)];
}
for (size_t i = 0; i != num_adapters; ++i) {
const size_t adapt_index = seq_line_str.find(adapter_seqs[i], 0);
if (adapt_index < stats.SHORT_READ_THRESHOLD) {
++stats.pos_adapter_count[((adapt_index + adapter_seqs[i].length() - 1)
<< Constants::bit_shift_adapter) |
i];
}
}
}
/*********************************************************/
/********** THIS LOOP MUST BE ALWAYS OPTIMIZED ***********/
/*********************************************************/
// In the following loop, cur_char does not change, but rather i changes
// and we access bases using bam_seqi(cur_char, i) in
// put_base_in_buffer.
for (size_t i = 0; i < seq_len; i++, ++read_pos) {
// if we reached the buffer size, stop using it and start using leftover
if (read_pos == buffer_size) {
still_in_buffer = false;
leftover_ind = 0;
}
// Make sure we have memory space to process new base
if (!still_in_buffer) {
if (leftover_ind == stats.num_extra_bases) {
stats.allocate_new_base(tile_ignore);
}
}
// puts base either on buffer or leftover
BamReader::put_base_in_buffer(i);
// statistics updated base by base
// use buffer
if (still_in_buffer) {
process_sequence_base_from_buffer(stats);
}
// use dynamic allocation
else {
process_sequence_base_from_leftover(stats);
// Increase leftover pos if no longer in buffer
++leftover_ind;
}
// Truncate GC counts to multiples of 100