-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathModule.cpp
More file actions
2206 lines (1934 loc) · 67.2 KB
/
Module.cpp
File metadata and controls
2206 lines (1934 loc) · 67.2 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 "Module.hpp"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <sstream>
/******************* AUX FUNCTIONS *******************************************/
// convert string to uppercase, to be used in making the short summaries where
// PASS, WARN and FAIL are uppercased
static inline std::string
toupper(const std::string &s) {
std::string out{s};
std::transform(std::cbegin(out), std::cend(out), std::begin(out),
[](const auto c) { return std::toupper(c); });
return out;
}
/*****************************************************************************/
/******************* BASEGROUPS COPIED FROM FASTQC ***************************/
/*****************************************************************************/
/************* NO BASE GROUP ****************/
void
make_default_base_groups(std::vector<BaseGroup> &base_groups,
const std::size_t num_bases) {
base_groups.clear();
for (std::size_t i = 0; i < num_bases; ++i)
base_groups.push_back({i, i});
}
/************* EXP BASE GROUP **************/
void
make_exponential_base_groups(std::vector<BaseGroup> &base_groups,
const std::size_t &num_bases) {
std::size_t starting_base{};
std::size_t end_base{};
std::size_t interval{1};
base_groups.clear();
while (starting_base < num_bases) {
end_base = starting_base + interval - 1;
if (end_base >= num_bases)
end_base = num_bases;
base_groups.push_back({starting_base, end_base});
starting_base += interval;
if (starting_base == 9 && num_bases > 75)
interval = 5;
if (starting_base == 49 && num_bases > 200)
interval = 10;
if (starting_base == 99 && num_bases > 300)
interval = 50;
if (starting_base == 499 && num_bases > 1000)
interval = 100;
if (starting_base == 1000 && num_bases > 2000)
interval = 500;
}
}
/************* LINEAR BASE GROUP *************/
// aux function to get linear interval
std::size_t
get_linear_interval(const std::size_t num_bases) {
// The the first 9bp as individual residues since odd stuff
// can happen there, then we find a grouping value which gives
// us a total set of groups below 75. We limit the intervals
// we try to sensible whole numbers.
std::vector<std::size_t> baseValues = {2, 5, 10};
std::size_t multiplier = 1;
while (true) {
for (std::size_t b = 0; b < std::size(baseValues); b++) {
std::size_t interval = baseValues[b] * multiplier;
std::size_t group_count = 9 + ((num_bases - 9) / interval);
if ((num_bases - 9) % interval != 0)
group_count++;
if (group_count < 75)
return interval;
}
multiplier *= 10;
if (multiplier == 10000000)
throw std::runtime_error(
"Couldn't find a sensible interval grouping for len =" +
std::to_string(num_bases));
}
}
void
make_linear_base_groups(std::vector<BaseGroup> &base_groups,
const std::size_t num_bases) {
// lengths not larger than 75bp just return everything
if (num_bases <= 75) {
make_default_base_groups(base_groups, num_bases);
return;
}
// determine the interval to use
const std::size_t interval = get_linear_interval(num_bases);
std::size_t starting_base{1};
while (starting_base <= num_bases) {
const auto end_base = [&] {
std::size_t end_base = starting_base + interval - 1;
if (starting_base < 10)
end_base = starting_base;
if (starting_base == 10 && interval > 10)
end_base = interval - 1;
if (end_base > num_bases)
end_base = num_bases;
return end_base;
}();
assert(starting_base > 0u && end_base > 0u);
base_groups.push_back({starting_base - 1ul, end_base - 1ul});
starting_base = [&] {
if (starting_base < 10)
starting_base++;
else if (starting_base == 10 && interval > 10)
starting_base = interval;
else
starting_base += interval;
return starting_base;
}();
}
}
template <class T>
T &
operator<<(T &out, const BaseGroup &group) {
if (group.start == group.end)
out << group.start + 1;
else
out << group.start + 1 << "-" << group.end + 1;
return out;
}
// FastQC extrapolation of counts to the full file size
double
get_corrected_count(std::size_t count_at_limit, std::size_t num_reads,
std::size_t dup_level, std::size_t num_obs) {
// See if we can bail out early (ADS: can we know if num_reads <=
// count_at_limit always holds?)
if (count_at_limit == num_reads)
return num_obs;
// If there aren't enough sequences left to hide another sequence with this
// count the we can also skip the calculation
if (num_reads - num_obs < count_at_limit)
return num_obs;
// If not then we need to see what the likelihood is that we had another
// sequence with this number of observations which we would have missed. We'll
// start by working out the probability of NOT seeing a sequence with this
// duplication level within the first count_at_limit sequences of num_obs.
// This is easier than calculating the probability of seeing it.
double p_not_seeing = 1.0;
// To save doing long calculations which are never going to produce anything
// meaningful we'll set a limit to our p-value calculation. This is the
// probability below which we won't increase our count by 0.01 of an
// observation. Once we're below this we stop caring about the corrected
// value since it's going to be so close to the observed value thatwe can just
// return that instead.
const double limit_of_caring = 1.0 - (num_obs / (num_obs + 0.01));
for (std::size_t i = 0; i < count_at_limit; ++i) {
p_not_seeing *= static_cast<double>((num_reads - i) - dup_level) /
static_cast<double>(num_reads - i);
if (p_not_seeing < limit_of_caring) {
p_not_seeing = 0;
break;
}
}
// Now we can assume that the number we observed can be scaled up by this
// proportion
return num_obs /
std::max(std::numeric_limits<double>::min(), 1.0 - p_not_seeing);
}
// Function to calculate the deviation of a histogram with 100 bins from a
// theoretical normal distribution with same mode and standard deviation
double
sum_deviation_from_normal(const std::array<double, 101> &gc_count,
std::array<double, 101> &theoretical) {
/******************* BEGIN COPIED FROM FASTQC **********************/
const std::size_t num_gc_bins = 101;
// Sum of all gc counts in all histogram bins
double total_count = 0.0;
// We use the mode to calculate the theoretical distribution
// so that we cope better with skewed distributions.
std::size_t first_mode = 0;
double mode_count = 0.0;
for (std::size_t i = 0; i < num_gc_bins; ++i) {
total_count += gc_count[i];
if (gc_count[i] > mode_count) {
mode_count = gc_count[i];
first_mode = i;
}
}
// The mode might not be a very good measure of the centre
// of the distribution either due to duplicated vales or
// several very similar values next to each other. We therefore
// average over adjacent points which stay above 95% of the modal
// value
double mode = 0;
std::size_t mode_duplicates = 0;
bool fell_off_top = true;
for (std::size_t i = first_mode; i < num_gc_bins; ++i) {
if (gc_count[i] > gc_count[first_mode] - (gc_count[first_mode] / 10.0)) {
mode += i;
mode_duplicates++;
}
else {
fell_off_top = false;
break;
}
}
bool fell_off_bottom = true;
for (int i = first_mode - 1; i >= 0; --i) {
if (gc_count[i] > gc_count[first_mode] - (gc_count[first_mode] / 10.0)) {
mode += i;
mode_duplicates++;
}
else {
fell_off_bottom = false;
break;
}
}
if (fell_off_bottom || fell_off_top) {
// If the distribution is so skewed that 95% of the mode
// is off the 0-100% scale then we keep the mode as the
// centre of the model
mode = first_mode;
}
else {
// ADS: check if we need to avoid divide-by-zero here
mode /= std::max(1ul, mode_duplicates);
}
// We can now work out a theoretical distribution
double stdev = 0.0;
for (std::size_t i = 0; i < num_gc_bins; ++i) {
stdev += (i - mode) * (i - mode) * gc_count[i];
}
// ADS: check if we need to avoid divide-by-zero here
stdev =
stdev / std::max(std::numeric_limits<double>::min(), total_count - 1.0);
stdev = sqrt(stdev);
/******************* END COPIED FROM FASTQC **********************/
// theoretical sampling from a normal distribution with mean = mode and stdev
// = stdev to the mode from the sampled gc content from the data
double ans = 0.0, theoretical_sum = 0.0, z;
theoretical.fill(0);
// ADS: lonely magic below; what is the 100?
for (std::size_t i = 0; i <= 100; ++i) {
z = i - mode;
// ADS: check if we need to avoid divide-by-zero here
theoretical[i] = std::exp(-(z * z) / (2.0 * stdev * stdev));
theoretical_sum += theoretical[i];
}
// Normalize theoretical so it sums to the total of readsq
for (std::size_t i = 0; i <= 100; ++i) {
// ADS: check if we need to avoid divide-by-zero here
theoretical[i] =
theoretical[i] * total_count /
std::max(std::numeric_limits<double>::min(), theoretical_sum);
}
for (std::size_t i = 0; i <= 100; ++i) {
ans += std::fabs(gc_count[i] - theoretical[i]);
}
// Fractional deviation (ADS: check if we need to avoid
// divide-by-zero here)
return 100.0 * ans /
std::max(std::numeric_limits<double>::min(), total_count);
}
/***************************************************************/
/********************* ABSTRACT MODULE *************************/
/***************************************************************/
Module::Module(const std::string &module_name) : module_name{module_name} {
// make placeholders
placeholder = module_name;
// removes spaces
placeholder.erase(
std::remove_if(std::begin(placeholder), std::end(placeholder),
[](const auto c) { return std::isspace(c); }),
std::cend(placeholder));
// lowercases it
std::transform(std::cbegin(placeholder), std::cend(placeholder),
std::begin(placeholder),
[](const auto c) { return std::tolower(c); });
// makes html placeholders
placeholder_name = "{{" + placeholder + "name" + "}}";
placeholder_data = "{{" + placeholder + "data" + "}}";
placeholder_cs = "{{" + placeholder + "cs" + "}}";
placeholder_ce = "{{" + placeholder + "ce" + "}}";
placeholder_grade = "{{pass" + placeholder + "}}";
grade = "pass";
summarized = false;
}
Module::~Module() {}
void
Module::write(std::ostream &os) {
if (!summarized)
throw std::runtime_error("Attempted to write module before summarizing : " +
module_name);
os << ">>" << module_name << "\t" << grade << "\n";
write_module(os);
os << ">>END_MODULE\n";
}
void
Module::write_short_summary(std::ostream &os, const std::string &filename) {
if (!summarized)
throw std::runtime_error("Attempted to write module before summarizing : " +
module_name);
os << toupper(grade) << "\t" << module_name << "\t" << filename << "\n";
}
// Guarantees the summarized flag is only set to true when module
// data has been summarized
void
Module::summarize(FastqStats &stats) {
summarize_module(stats);
make_grade();
html_data = make_html_data();
summarized = true;
}
/***************************************************************/
/********************* SUMMARIZE FUNCTIONS *********************/
/***************************************************************/
/******************* BASIC STATISTICS **************************/
const std::string ModuleBasicStatistics::module_name = "Basic Statistics";
ModuleBasicStatistics::ModuleBasicStatistics(const FalcoConfig &config) :
Module(ModuleBasicStatistics::module_name) {
is_nanopore = config.nanopore;
filename_stripped = config.filename_stripped;
}
void
ModuleBasicStatistics::summarize_module(FastqStats &stats) {
// total sequences and bases
total_sequences = stats.num_reads;
total_bases = stats.total_bases;
// min and max read length
min_read_length = stats.min_read_length;
max_read_length = stats.max_read_length;
// These seem to always be the same on FastQC
// File type
file_type = "Conventional base calls";
if (is_nanopore) {
file_encoding = "Oxford Nanopore";
// stats.encoding_offset = ?
}
else {
// File encoding
const char lowest_char = stats.lowest_char;
// copied from FastQC:
static const std::size_t SANGER_ENCODING_OFFSET = 33;
static const char ILLUMINA_1_3_ENCODING_OFFSET = 64;
if (lowest_char < 33) {
throw std::runtime_error("No known encoding with chars < 33. Yours was " +
std::to_string(lowest_char) + ")");
}
else if (lowest_char < 64) {
file_encoding = "Sanger / Illumina 1.9";
stats.encoding_offset = SANGER_ENCODING_OFFSET - Constants::quality_zero;
}
else if (lowest_char == ILLUMINA_1_3_ENCODING_OFFSET + 1) {
file_encoding = "Illumina 1.3";
stats.encoding_offset =
ILLUMINA_1_3_ENCODING_OFFSET - Constants::quality_zero;
}
else if (lowest_char <= 126) {
file_encoding = "Illumina 1.5";
stats.encoding_offset =
ILLUMINA_1_3_ENCODING_OFFSET - Constants::quality_zero;
}
// found a char but it's not the default one
else if (lowest_char != stats.lowest_char) {
throw std::runtime_error(
"No known encodings with chars > 126 (Yours was " +
std::to_string(lowest_char) + ")");
}
}
// Poor quality reads
num_poor = 0;
// Average read length
avg_read_length = 0;
std::size_t total_bases_for_mean = 0;
for (std::size_t i = 0; i < max_read_length; ++i) {
if (i < FastqStats::SHORT_READ_THRESHOLD)
total_bases_for_mean += i * stats.read_length_freq[i];
else
total_bases_for_mean +=
i * stats.long_read_length_freq[i - FastqStats::SHORT_READ_THRESHOLD];
}
avg_read_length = total_bases_for_mean / std::max(1ul, total_sequences);
// counts bases G and C in each base position
// GC %
// GS: TODO delete gc calculation during stream and do it using the total G
// counts in all bases
avg_gc =
100.0 * stats.total_gc / std::max(1.0, static_cast<double>(total_bases));
}
void
ModuleBasicStatistics::make_grade() {} // always a pass
void
ModuleBasicStatistics::write_module(std::ostream &os) {
static constexpr auto mega = 1'000'000;
os << "#Measure\tValue\n";
os << "Filename\t" << filename_stripped << "\n";
os << "File type\t" << file_type << "\n";
os << "Encoding\t" << file_encoding << "\n";
os << "Total Sequences\t" << total_sequences << "\n";
// clang-format off
os << "Total Bases\t"
<< (total_bases > mega ? total_bases / mega : total_bases)
<< (total_bases > mega ? " Mbp\n" : " bp\n");
// clang-format on
os << "Sequences flagged as poor quality\t" << num_poor << "\n";
os << "Sequence length\t";
os << min_read_length;
if (min_read_length != max_read_length)
os << "-" << max_read_length;
os << "\n";
const auto default_precision{os.precision()};
// clang-format off
os << "%GC\t"
<< std::setprecision(1)
<< std::fixed
<< avg_gc << '\n'
<< std::defaultfloat
<< std::setprecision(default_precision);
// clang-format on
}
std::string
ModuleBasicStatistics::make_html_data() {
std::ostringstream data;
data << "<table><thead><tr><th>Measure</th><th>Value"
<< "</th></tr></thead><tbody>";
data << "<tr><td>Filename</td><td>" << filename_stripped << "</td></tr>";
data << "<tr><td>File type</td><td>" << file_type << "</td></tr>";
data << "<tr><td>Encoding</td><td>" << file_encoding << "</td></tr>";
data << "<tr><td>Total Sequences</td><td>" << total_sequences << "</td></tr>";
data << "<tr><td>Sequences Flagged As Poor Quality</td><td>" << num_poor
<< "</td></tr>";
data << "<tr><td>Sequence length</td><td>";
if (min_read_length != max_read_length) {
data << min_read_length << " - " << max_read_length;
}
else {
data << max_read_length;
}
data << "</td></tr>";
data << "<tr><td>%GC:</td><td>" << avg_gc << "</td></tr>";
data << "</tbody></table>";
return data.str();
}
void
ModuleBasicStatistics::read_data_line(const std::string &line) {
std::string lhs, rhs;
std::istringstream iss(line);
// get text before and after tab
std::getline(iss, lhs, '\t');
std::getline(iss, rhs, '\t');
if (lhs == "Filename")
filename_stripped = rhs;
else if (lhs == "File type")
file_type = rhs;
else if (lhs == "Encoding")
file_encoding = rhs;
else if (lhs == "Total Sequences")
total_sequences = std::atoi(std::data(rhs));
else if (lhs == "Sequences flagged as poor quality")
num_poor = std::atoi(std::data(rhs));
else if (lhs == "Sequence length") {
// non-constant sequence length
if (rhs.find("-") != std::string::npos) {
std::istringstream seq_iss(rhs);
std::string min_l, max_l;
std::getline(seq_iss, min_l, '-');
std::getline(seq_iss, max_l, '-');
min_read_length = std::atoi(std::data(min_l));
max_read_length = std::atoi(std::data(max_l));
}
}
else if (lhs == "%GC")
avg_gc = std::atoi(std::data(rhs));
else {
throw std::runtime_error("malformed basic statistic" + lhs);
}
}
/******************* PER BASE SEQUENCE QUALITY **********************/
const std::string ModulePerBaseSequenceQuality::module_name =
"Per base sequence quality";
ModulePerBaseSequenceQuality::ModulePerBaseSequenceQuality(
const FalcoConfig &config) :
Module(ModulePerBaseSequenceQuality::module_name) {
auto base_lower = config.limits.find("quality_base_lower");
auto base_median = config.limits.find("quality_base_median");
base_lower_warn = (base_lower->second).find("warn")->second;
base_lower_error = (base_lower->second).find("error")->second;
base_median_warn = (base_median->second).find("warn")->second;
base_median_error = (base_median->second).find("error")->second;
do_group = !config.nogroup;
}
void
ModulePerBaseSequenceQuality::summarize_module(FastqStats &stats) {
// Quality quantiles for base positions
double ldecile_thresh, lquartile_thresh, median_thresh, uquartile_thresh,
udecile_thresh;
std::size_t cur_ldecile = 0, cur_lquartile = 0, cur_median = 0,
cur_uquartile = 0, cur_udecile = 0;
std::size_t ldecile_group_sum = 0, lquartile_group_sum = 0,
median_group_sum = 0, uquartile_group_sum = 0,
udecile_group_sum = 0;
double mean_group_sum;
std::size_t cur;
std::size_t cur_sum;
std::size_t counts;
double cur_mean;
num_bases = stats.max_read_length;
// first, do the groups
if (do_group) {
make_linear_base_groups(base_groups, num_bases);
}
else
make_default_base_groups(base_groups, num_bases);
num_groups = std::size(base_groups);
// Reserves space I know I will use
group_mean = std::vector<double>(num_groups, 0.0);
group_ldecile = std::vector<double>(num_groups, 0.0);
group_lquartile = std::vector<double>(num_groups, 0.0);
group_median = std::vector<double>(num_groups, 0.0);
group_uquartile = std::vector<double>(num_groups, 0.0);
group_udecile = std::vector<double>(num_groups, 0.0);
// temp
std::vector<std::size_t> histogram(128, 0);
std::size_t bases_in_group = 0;
for (std::size_t group = 0; group < num_groups; ++group) {
mean_group_sum = 0;
ldecile_group_sum = 0;
lquartile_group_sum = 0;
median_group_sum = 0;
uquartile_group_sum = 0;
udecile_group_sum = 0;
// Find quantiles for each base group
for (std::size_t i = base_groups[group].start; i <= base_groups[group].end;
++i) {
// reset group values
bases_in_group = 0;
for (std::size_t j = 0; j < 128; ++j)
histogram[j] = 0;
for (std::size_t j = 0; j < FastqStats::kNumQualityValues; ++j) {
// get value
if (i < FastqStats::SHORT_READ_THRESHOLD) {
cur =
stats
.position_quality_count[(i << FastqStats::kBitShiftQuality) | j];
}
else {
cur = stats.long_position_quality_count
[((i - FastqStats::SHORT_READ_THRESHOLD)
<< FastqStats::kBitShiftQuality) |
j];
}
// Add to Phred histogram
histogram[j] += cur;
}
// Number of bases seen in position i
if (i < FastqStats::SHORT_READ_THRESHOLD) {
bases_in_group += stats.cumulative_read_length_freq[i];
}
else {
bases_in_group +=
stats
.long_cumulative_read_length_freq[i -
FastqStats::SHORT_READ_THRESHOLD];
}
ldecile_thresh = 0.1 * bases_in_group;
lquartile_thresh = 0.25 * bases_in_group;
median_thresh = 0.5 * bases_in_group;
uquartile_thresh = 0.75 * bases_in_group;
udecile_thresh = 0.9 * bases_in_group;
// now go again through the counts in each quality value to find the
// quantiles
cur_sum = 0;
counts = 0;
for (std::size_t j = 0; j < FastqStats::kNumQualityValues; ++j) {
// Finds in which bin of the histogram reads are
cur = histogram[j];
if (counts < ldecile_thresh && counts + cur >= ldecile_thresh)
cur_ldecile = j;
if (counts < lquartile_thresh && counts + cur >= lquartile_thresh)
cur_lquartile = j;
if (counts < median_thresh && counts + cur >= median_thresh)
cur_median = j;
if (counts < uquartile_thresh && counts + cur >= uquartile_thresh)
cur_uquartile = j;
if (counts < udecile_thresh && counts + cur >= udecile_thresh)
cur_udecile = j;
cur_sum += cur * j;
counts += cur;
}
cur_mean =
static_cast<double>(cur_sum) / static_cast<double>(bases_in_group);
const std::size_t offset = stats.encoding_offset;
mean_group_sum += cur_mean - offset;
ldecile_group_sum += cur_ldecile - offset;
lquartile_group_sum += cur_lquartile - offset;
median_group_sum += cur_median - offset;
uquartile_group_sum += cur_uquartile - offset;
udecile_group_sum += cur_udecile - offset;
}
const std::size_t base_positions =
base_groups[group].end - base_groups[group].start + 1;
assert(base_positions != static_cast<std::size_t>(0));
group_mean[group] = mean_group_sum / base_positions;
group_ldecile[group] =
static_cast<double>(ldecile_group_sum) / base_positions;
group_lquartile[group] =
static_cast<double>(lquartile_group_sum) / base_positions;
group_median[group] =
static_cast<double>(median_group_sum) / base_positions;
group_uquartile[group] =
static_cast<double>(uquartile_group_sum) / base_positions;
group_udecile[group] =
static_cast<double>(udecile_group_sum) / base_positions;
}
}
void
ModulePerBaseSequenceQuality::make_grade() {
num_warn = 0;
num_error = 0;
for (std::size_t i = 0; i < num_groups; ++i) {
// there was enough data to make this assessment
if (group_lquartile[i] > 0) {
if (grade != "fail") {
if (group_lquartile[i] < base_lower_error ||
group_median[i] < base_median_error) {
num_error++;
}
else if (group_lquartile[i] < base_lower_warn ||
group_median[i] < base_median_warn) {
num_warn++;
}
}
}
}
if (num_error > 0)
grade = "fail";
else if (num_warn > 0)
grade = "warn";
}
void
ModulePerBaseSequenceQuality::write_module(std::ostream &os) {
os << "#Base\tMean\tMedian\tLower Quartile\tUpper Quartile"
<< "\t10th Percentile\t90th Percentile\n";
// GS: TODO make base groups
for (std::size_t i = 0; i < num_groups; ++i) {
os << base_groups[i] << "\t" << group_mean[i] << "\t" << group_median[i]
<< "\t" << group_lquartile[i] << "\t" << group_uquartile[i] << "\t"
<< group_ldecile[i] << "\t" << group_udecile[i] << "\n";
}
}
// Plotly data
std::string
ModulePerBaseSequenceQuality::make_html_data() {
std::ostringstream data;
for (std::size_t i = 0; i < num_groups; ++i) {
data << "{y : [";
data << group_ldecile[i] << ", " << group_lquartile[i] << ", "
<< group_median[i] << ", " << group_uquartile[i] << ", "
<< group_udecile[i] << "], ";
data << "type : 'box', name : ' ";
if (base_groups[i].start == base_groups[i].end)
data << base_groups[i].start + 1;
else
data << base_groups[i].start + 1 << "-" << base_groups[i].end + 1;
data << "bp', ";
data << "marker : {color : '";
// I will color the boxplot based on whether it passed or failed
if (group_median[i] < base_median_error ||
group_lquartile[i] < base_lower_error)
data << "red";
else if (group_median[i] < base_median_warn ||
group_lquartile[i] < base_lower_warn)
data << "yellow";
else
data << "green";
data << "'}}";
if (i < num_bases - 1) {
data << ", ";
}
}
return data.str();
}
void
ModulePerBaseSequenceQuality::read_data_line(
[[maybe_unused]] const std::string &line) {}
/************** PER TILE SEQUENCE QUALITY ********************/
const std::string ModulePerTileSequenceQuality::module_name =
"Per tile sequence quality";
ModulePerTileSequenceQuality::ModulePerTileSequenceQuality(
const FalcoConfig &config) :
Module(ModulePerTileSequenceQuality::module_name) {
auto grade_tile = config.limits.find("tile")->second;
grade_warn = grade_tile.find("warn")->second;
grade_error = grade_tile.find("error")->second;
}
void
ModulePerTileSequenceQuality::summarize_module(FastqStats &stats) {
max_read_length = stats.max_read_length;
tile_position_quality = stats.tile_position_quality;
// First I calculate the number of counts for each position
std::vector<std::size_t> position_counts(max_read_length, 0);
for (auto v : stats.tile_position_quality) {
for (std::size_t i = 0; i < std::size(v.second); ++i) {
position_counts[i] += stats.tile_position_count.find(v.first)->second[i];
}
}
// Now I calculate the sum of all tile qualities in each position
std::vector<double> mean_in_base(max_read_length, 0.0);
for (auto v : tile_position_quality) {
for (std::size_t i = 0; i < std::size(v.second); ++i) {
mean_in_base[i] += v.second[i];
}
}
// Now transform sum into mean
for (std::size_t i = 0; i < max_read_length; ++i)
if (position_counts[i] > 0.0)
mean_in_base[i] = mean_in_base[i] / position_counts[i];
else
mean_in_base[i] = 0.0;
for (auto &v : tile_position_quality) {
const std::size_t lim = std::size(v.second);
for (std::size_t i = 0; i < lim; ++i) {
// transform sum of all qualities in mean
const auto itr = stats.tile_position_count.find(v.first);
if (itr == std::cend(stats.tile_position_count))
throw std::runtime_error(
"failure ModulePerTileSequenceQuality::summarize_module");
const std::size_t count_at_pos = itr->second[i];
if (count_at_pos > 0)
v.second[i] = v.second[i] / count_at_pos;
// subtract the global mean
v.second[i] -= mean_in_base[i];
}
}
// sorts tiles
tiles_sorted.clear();
for (auto v : tile_position_quality)
tiles_sorted.push_back(v.first);
std::sort(tiles_sorted.begin(), tiles_sorted.end());
}
void
ModulePerTileSequenceQuality::make_grade() {
grade = "pass";
for (auto &v : tile_position_quality) {
for (std::size_t i = 0; i < std::size(v.second); ++i) {
if (grade != "fail") {
if (v.second[i] <= -grade_error) {
grade = "fail";
}
else if (v.second[i] <= -grade_warn) {
grade = "warn";
}
}
}
}
}
void
ModulePerTileSequenceQuality::write_module(std::ostream &os) {
// prints tiles sorted by value
os << "#Tile\tBase\tMean\n";
for (std::size_t i = 0; i < std::size(tiles_sorted); ++i) {
for (std::size_t j = 0; j < max_read_length; ++j) {
if (std::size(tile_position_quality[tiles_sorted[i]]) >= j) {
os << tiles_sorted[i] << "\t" << j + 1 << "\t"
<< tile_position_quality[tiles_sorted[i]][j];
os << "\n";
}
}
}
}
inline double
round_quantile(const double val, const double num_quantiles) {
// ADS: check if we need to worry about divide by zero here
return static_cast<int>(val * num_quantiles) / num_quantiles;
}
std::string
ModulePerTileSequenceQuality::make_html_data() {
// find quantiles based on data for a standardized color scale
double min_val = std::numeric_limits<double>::max();
double max_val = std::numeric_limits<double>::min();
std::ostringstream data;
data << "{x : [";
for (std::size_t i = 0; i < max_read_length; ++i) {
data << i + 1;
if (i < max_read_length - 1)
data << ",";
}
// Y : Tile
data << "], y: [";
bool first_seen = false;
for (std::size_t i = 0; i < std::size(tiles_sorted); ++i) {
if (!first_seen)
first_seen = true;
else
data << ",";
data << tiles_sorted[i];
}
// Z: quality z score
data << "], z: [";
first_seen = false;
for (std::size_t i = 0; i < std::size(tiles_sorted); ++i) {
if (!first_seen)
first_seen = true;
else
data << ", ";
// start new array with all counts
data << "[";
for (std::size_t j = 0; j < max_read_length; ++j) {
const double val = tile_position_quality[tiles_sorted[i]][j];
data << val;
if (j < max_read_length - 1)
data << ",";
max_val = std::max(max_val, val);
min_val = std::min(min_val, val);
}
data << "]";
}
data << "]";
data << ", type : 'heatmap',";
// fixed color scale
data << "colorscale: [";
// We will now discretize the quantiles so plotly understands
// the color scheme
static const double num_quantiles = 20.0;
// ADS: not sure if we need to worry about divide by zero here?
double mid_point =
round_quantile(min_val / (min_val - max_val), num_quantiles);
// - 10: red
data << "[0.0, 'rgb(210,65,83)'],";
// 0: light blue
data << "[" << mid_point << ", 'rgb(178,236,254)'],";
// + 10: dark blue
data << "[1.0, 'rgb(34,57,212)']";
data << "],";
data << "showscale : true";
data << "}";
return data.str();
}
/******************* PER SEQUENCE QUALITY SCORE **********************/
const std::string ModulePerSequenceQualityScores::module_name =
"Per sequence quality scores";
ModulePerSequenceQualityScores::ModulePerSequenceQualityScores(
const FalcoConfig &config) :
Module(ModulePerSequenceQualityScores::module_name) {
mode_val = 0;
mode_ind = 0;
offset = 0;
auto mode_limits = config.limits.find("quality_sequence");
mode_warn = (mode_limits->second).find("warn")->second;
mode_error = (mode_limits->second).find("error")->second;
}
void
ModulePerSequenceQualityScores::summarize_module(FastqStats &stats) {
// Need to copy this to write later
quality_count = stats.quality_count;
offset = stats.encoding_offset;
// get mode for grade
for (std::size_t i = 0; i < FastqStats::kNumQualityValues; ++i) {
if (stats.quality_count[i] > mode_val) {
mode_val = stats.quality_count[i];
mode_ind = i - offset;
}
}
}
void
ModulePerSequenceQualityScores::make_grade() {