-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils_popdel.h
1561 lines (1525 loc) · 63.7 KB
/
utils_popdel.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
#ifndef UTILS_POPDEL_H_
#define UTILS_POPDEL_H_
#include<ctime>
#include <unordered_set>
#include <seqan/basic.h>
#include <seqan/seq_io.h>
#include <seqan/bam_io.h>
using namespace seqan;
// =======================================================================================
// Typedefs
// =======================================================================================
typedef __uint32 TEntryIdType; // Type for id in ChromosomeProfileEndEntry;
typedef String<int> TProfile; // Profile values of a single RG in a single window
typedef String<TProfile> TReadGroupProfiles; // Profiles per ReadGroups in a single Window
typedef String<TReadGroupProfiles> TWindowProfiles; // 3D Array: Window, Readgroup, ProfileValues
typedef Iterator<TWindowProfiles>::Type TWindowIter;
typedef String<TEntryIdType> TReadGroupIndices;
typedef String<TReadGroupIndices> TRGs;
// =======================================================================================
// Classes
// =======================================================================================
// =======================================================================================
// Class Dad
// =======================================================================================
// Class for counting how the insertSizes of a read group overlap the different histograms.
struct Dad
{
unsigned ref; // only in ref hist (or left of it).
unsigned both; // in both hists.
unsigned between; // between both hists, but in neither of them.
unsigned alt; // only in alternative hist.
unsigned right; // right of alternative hist.
Dad() : ref(0), both(0), between(0), alt(0), right(0){}
Dad(unsigned re, unsigned bo, unsigned be, unsigned al, unsigned ri) :
ref(re),
both(bo),
between(be),
alt(al),
right(ri){}
inline void reset()
{
ref = both = between = alt = right = 0u;
}
};
// Object storing all information associated with a deletion call
// =======================================================================================
// Class Call
// =======================================================================================
// Object storing all information associated with a deletion call
struct Call
{
__uint32 initialLength; // Estimate for deletion length at initialization.
__uint32 iterations; // Number of iterations performed.
__uint32 deletionLength; // Final estimate for deletion length.
double likelihoodRatio; // Likelihood ratio calculated for this deletion.
String<Triple<unsigned> > lads; // Likelihood based counts of pairs supporting: i1: Ref, i2: Ambiguous, i3: Del. One per Sample.
String<Dad> dads; // distribution based counts of pairs supporting:
// 0: Ref, 1: both, 2: between but none, 3: Del., 4: bigger than del. One per Sample.
String<Pair<unsigned> > firstLast;// Pos of the lowest first and the highest last win of all active reads.
double frequency; // Allele-frequency of the deletion across all samples.
unsigned windowPosition; // Position of the window.
unsigned position; // Assumed start-position (window) of the variant.
unsigned endPosition; // Assumed end-position (window) of the variant.
unsigned significantWindows; // Number of significant windows that where merged into this variant.
String<Triple<unsigned> > gtLikelihoods; // PHRED-scaled GT likelihhods of each sample. Order: HomRef, Het, HomDel.
unsigned char filter; // 8 Bits indicating the failed filters. 1 at the position indicates failed filter.
bool isOutside; // True if the window the call is bases on lies outside of the deletion area.
// (right to left) 1.: LR ratio test failed, 2.: High coverage, 3.:Sample Number
Call() :
initialLength(0),
iterations(0),
deletionLength(0),
likelihoodRatio(0.0),
frequency(0.0),
windowPosition(0),
position(0),
endPosition(0),
significantWindows(0),
filter(0),
isOutside(false){}
Call(__uint32 initLen,
__uint32 itNum,
__uint32 delLen,
double llr,
double f,
unsigned wPos,
unsigned pos,
unsigned endPos = 0) :
initialLength(initLen),
iterations(itNum),
deletionLength(delLen),
likelihoodRatio(llr),
frequency(f),
windowPosition(wPos),
position(pos),
endPosition(endPos),
significantWindows(0),
isOutside(false){}
void reset(void)
{
initialLength = 0;
iterations = 0;
deletionLength = 0;
likelihoodRatio = 0;
clear(lads);
clear(dads);
frequency = 0;
windowPosition = 0;
position = 0;
endPosition = 0;
significantWindows = 0;
filter = 0;
isOutside = false;
}
};
// =======================================================================================
// Functions
// =======================================================================================
// =======================================================================================
// Function setLRFilter()
// =======================================================================================
// Set the bit for the likelihood ratio filter.
inline void setLRFilter(Call & call)
{
call.filter |= 1; // 0001
}
// =======================================================================================
// Function checkLRPass()
// =======================================================================================
// Return true if the likelihood ratio filter has been passed, false otherwise.
inline bool checkLRPass(const Call & call)
{
return !(call.filter & 1); // 0001
}
// =======================================================================================
// Function setCoverageFilter()
// =======================================================================================
// Set the bit for the high coverage filter.
inline void setCoverageFilter(Call & call)
{
call.filter |= 2; // 0010
}
// =======================================================================================
// Function checkCoveragePass()
// =======================================================================================
// Return true if the high coverage filter has been passed, false otherwise.
inline bool checkCoveragePass(const Call & call)
{
return !(call.filter & 2); // 0010
}
// =======================================================================================
// Function setSampleFilter()
// =======================================================================================
// Set the bit for the sample number filter.
inline void setSampleFilter(Call & call)
{
call.filter |= 4; // 0100
}
// =======================================================================================
// Function checkSamplePass()
// =======================================================================================
// Return true if the sample number filter has been passed, false otherwise.
inline bool checkSamplePass(const Call & call)
{
return !(call.filter & 4); // 0100
}
// =======================================================================================
// Function setGT0Filter()
// =======================================================================================
// Set the bit for the sample number filter.
inline void setGT0Filter(Call & call)
{
call.filter |= 8; // 1000
}
// =======================================================================================
// Function checkGT0Pass()
// =======================================================================================
// Return true if the sample number filter has been passed, false otherwise.
inline bool checkGT0Pass(const Call & call)
{
return !(call.filter & 8); // 1000
}
// =======================================================================================
// Function setRelWinCovFilter()
// =======================================================================================
// Return true if the realtive window coverage filter has been passed, false otherwise.
inline void setRelWinCovFilter(Call & call)
{
call.filter |= 16; // 10000
}
// =======================================================================================
// Function checkRelWinCovPass()
// =======================================================================================
// Return true if the realtive window coverage filter has been passed, false otherwise.
inline bool checkRelWinCovPass(const Call & call)
{
return !(call.filter & 16); // 10000
}
// =======================================================================================
// Function checkAllPass()
// =======================================================================================
// Return true if all filters have been passed, false otherwise.
inline bool checkAllPass(const Call & call)
{
return checkCoveragePass(call) &&
checkLRPass(call) &&
checkSamplePass(call) &&
checkGT0Pass(call) &&
checkRelWinCovPass(call);
}
// Reset all filters.
inline void resetFilters(Call & call)
{
call.filter = 0;
}
// =======================================================================================
// Function markInvalidCall()
// =======================================================================================
// Marks a call as invalid by setting its filter to maxValue<unsigned>().
inline void markInvalidCall(Call & call)
{
call.filter = maxValue<unsigned char>();
}
// =======================================================================================
// Function checkDelSizeSimilar()
// =======================================================================================
// Return true if the two delSizes a and b are within f percent of each other or within +-2 sddev.
inline bool checkDelSizeSimilar(const unsigned & a, const unsigned & b, const double & stddev, const double f = 0.5)
{
unsigned l;
unsigned r;
if (a < b)
{
l = a;
r = b;
}
else
{
l = b;
r = a;
}
if (l + 2 * stddev >= r)
return true;
else
{
return l >= f * r;
}
}
inline bool isInDelRange(const Call & a, const Call & b, const double & stddev, const double f = 4)
{
SEQAN_ASSERT_GEQ(b.position, a.position);
return (b.position - a.position < (std::min(a.deletionLength, b.deletionLength) + f * stddev));
}
// =======================================================================================
// Function checkAndExtend()
// =======================================================================================
// Return true if the range given by endPos - beginPos of one of the calls needs extension to fit the the estimated del.
// Return false otherwise.
// If true is returned, the endPosition of a is updated to match the endPosition of b.
inline bool checkAndExtend(Call & a, Call & b, const double & stddev)
{
unsigned aSpan = a.endPosition - a.position;
unsigned bSpan = b.endPosition - b.position;
if ((aSpan < a.deletionLength || bSpan < b.deletionLength) && isInDelRange(a, b, stddev))
{
a.endPosition = b.endPosition;
return true;
}
else return false;
}
// =======================================================================================
// Function checkEnoughOverlap()
// =======================================================================================
// Return true if the calls a and b overlap for at least for f-percent of the smaller variant's number of windows.
inline bool checkEnoughOverlap(const Call & a, const Call & b, const double & stddev, const double f = 0.25)
{
unsigned aSpan = a.endPosition - a.position;
unsigned bSpan = b.endPosition - b.position;
unsigned minLen = std::min(aSpan, bSpan);
unsigned left = std::max(a.position, b.position);
unsigned right = std::min(a.position + aSpan, b.position + bSpan);
int overlap = (right - left);
if (overlap >= f * minLen)
return true;
else if (overlap + 2 * stddev >= minLen)
return true;
else
return false;
}
// =======================================================================================
// Function areSimilar()
// =======================================================================================
// Return true, if the two given SupportStretch are similar enough to be merged.
// If checkAndExtedIs true, the endPosition of a is updated to match the endPosition of b.
inline bool similar(Call & a, Call & b, const double & stddev)
{
if (checkDelSizeSimilar(a.deletionLength, b.deletionLength, stddev))
{
if (checkEnoughOverlap(a, b, stddev))
return true;
else
return checkAndExtend(a, b, stddev);
}
else
{
return false;
}
}
// =======================================================================================
// Function lowerCall()
// =======================================================================================
// Return true if the first Call comes not after the second, false otherwise.
// The First the positions are compared and for equal positions the shorter variant comes before the longer.
// If both are equal, the element with the higher LR is prefered.
inline bool lowerCall(const Call & l, const Call & r)
{
if (l.position < r.position)
return true;
else if (l.position > r.position)
return false;
else if (l.deletionLength < r.deletionLength)
return true;
else if (l.deletionLength > r.deletionLength)
return false;
else if (l.likelihoodRatio > r.likelihoodRatio)
return true;
else
return false;
}
inline void setFreqFromGTs(Call & call)
{
unsigned alleleCount = 0;
for (Iterator<String<Triple<unsigned> > >::Type it = begin(call.gtLikelihoods); it != end(call.gtLikelihoods); ++it)
{
if (it->i1 == 0)
{
continue;
}
else if (it->i2 == 0)
{
alleleCount += 1;
continue;
}
else
{
alleleCount += 2;
}
}
call.frequency = static_cast<double>(alleleCount) / (length(call.gtLikelihoods) * 2);
}
// =======================================================================================
// Function addToLADlist()
// =======================================================================================
// Add the LAD of sample s to the target LAD-list.
inline void addToLADlist(String<Triple<String<unsigned> > > & target,
const String<Triple<unsigned> > & source,
const unsigned s)
{
SEQAN_ASSERT_EQ(length(target), length(source));
SEQAN_ASSERT_LT(s, length(target));
appendValue(target[s].i1, source[s].i1);
appendValue(target[s].i2, source[s].i2);
appendValue(target[s].i3, source[s].i3);
}
// =======================================================================================
// Function addToDADlist()
// =======================================================================================
// Add the LAD of sample s to the target DAD-list.
inline void addToDADlist(String<String<String<unsigned>, Array<5> > > & target,
const String<Dad> & source,
const unsigned s)
{
SEQAN_ASSERT_EQ(length(target), length(source));
SEQAN_ASSERT_LT(s, length(target));
appendValue(target[s][0], source[s].ref);
appendValue(target[s][1], source[s].both);
appendValue(target[s][2], source[s].between);
appendValue(target[s][3], source[s].alt);
appendValue(target[s][4], source[s].right);
}
// =======================================================================================
// Function getMedianLAD()
// =======================================================================================
// Return the median LAD and clear the input list of LADs.
inline Triple<unsigned> getMedianLAD(Triple<String<unsigned> > & lads)
{
unsigned m = length(lads.i1) / 2;
std::sort(begin(lads.i1), end(lads.i1));
std::sort(begin(lads.i2), end(lads.i2));
std::sort(begin(lads.i3), end(lads.i3));
Triple<unsigned> res = Triple<unsigned>(lads.i1[m], lads.i2[m], lads.i3[m]);
clear(lads.i1);
clear(lads.i2);
clear(lads.i3);
return res;
}
// =======================================================================================
// Function getMedianDAD()
// =======================================================================================
// Return the median DAD and clear the input list of DADs.
inline Dad getMedianDAD(String<String<unsigned>, Array<5> > & dads)
{
unsigned m = length(dads[0]) / 2;
for (unsigned i = 0; i < 5u; ++i)
std::sort(begin(dads[i]), end(dads[i]));
Dad res = Dad(dads[0][m], dads[1][m], dads[2][m], dads[3][m], dads[4][m]);
for (unsigned i = 0; i < 5u; ++i)
clear(dads[i]);
return res;
}
// =======================================================================================
// Function skipFailedWindows()
// =======================================================================================
// Advance currentIt as far as needed to skip over all calls that fail any filters.
// Return false if all calls fail, true otherwise.
inline bool skipFailedCalls(Iterator<String<Call> >::Type & currentIt,
const Iterator<const String<Call> >::Type & last)
{
while (!checkAllPass(*currentIt)) // Skip all windows that did not pass all filters.
{
if (currentIt == last)
return false;
else
++currentIt;
}
return currentIt != last;
}
// =======================================================================================
// Function setGenotypes()
// =======================================================================================
// Looks at the windows that are within the deletion length and estimates the genotype for each sample.
// Also sets the LADs and DADs.
// Resets "genotypes"
// Return true on success, false if no genotype could be set (due to lack of windows)
inline bool setGenotypes(const Iterator<String<Call>, Standard >::Type & start,
const Iterator<const String<Call>, Standard >::Type end,
String<Triple<String<unsigned> > > & lads,
String<String<String<unsigned>, Array<5> > > & dads,
String<Triple<unsigned> > & genotypes)
{
unsigned genotypeWinCount = 0;
for (Iterator<String<Call>, Standard >::Type gtIt = start; gtIt < end; ++gtIt)
{
if (gtIt->windowPosition > start->position &&
gtIt->windowPosition - 30 < start->position + start->deletionLength)
{ // Only consider genotype likelihoods of windows within the deletion range
for (unsigned s = 0; s < length(genotypes); ++s)
{
genotypes[s].i1 += gtIt->gtLikelihoods[s].i1;
genotypes[s].i2 += gtIt->gtLikelihoods[s].i2;
genotypes[s].i3 += gtIt->gtLikelihoods[s].i3;
addToLADlist(lads, gtIt->lads, s);
addToDADlist(dads, gtIt->dads, s);
}
++genotypeWinCount;
}
}
if (genotypeWinCount == 0)
return false;
// Now get the final genotype likelihoods
for (unsigned s = 0; s < length(genotypes); ++s)
{
double minGt = std::min(std::min(genotypes[s].i1, genotypes[s].i2), genotypes[s].i3);
double ref = static_cast<double>(genotypes[s].i1 - minGt) / genotypeWinCount;
double het = static_cast<double>(genotypes[s].i2 - minGt) / genotypeWinCount;
double hom = static_cast<double>(genotypes[s].i3 - minGt) / genotypeWinCount;
genotypes[s] = Triple<unsigned> (0, 0, 0);
start->gtLikelihoods[s].i1 = std::round(ref);
start->gtLikelihoods[s].i2 = std::round(het);
start->gtLikelihoods[s].i3 = std::round(hom);
start->lads[s] = getMedianLAD(lads[s]);
start->dads[s] = getMedianDAD(dads[s]);
// Avoid genotypes with nearly equal likelihoods. TODO: A bit hacky. Find better solution.
if (start->gtLikelihoods[s].i2 == start->gtLikelihoods[s].i3)
{
if (het > hom)
++(start->gtLikelihoods[s].i2);
else
++(start->gtLikelihoods[s].i3);
}
else if (start->gtLikelihoods[s].i1 == start->gtLikelihoods[s].i2)
{
if (ref > het)
++(start->gtLikelihoods[s].i1);
else
++(start->gtLikelihoods[s].i2);
}
}
return true;
}
// =======================================================================================
// Function getStartPosition()
// =======================================================================================
// Return the median of the collected stat position estimates as the final start position.
// startPositions is cleared during this process.
inline unsigned getStartPosition(String<unsigned> & startPositions)
{
SEQAN_ASSERT(!empty(startPositions));
std::sort(begin(startPositions), end(startPositions));
unsigned start = startPositions[length(startPositions) / 2];
clear(startPositions);
return start;
}
// =======================================================================================
// Function getDeletionLength()
// =======================================================================================
// Return the median of the collected sizes estimates as the final value for the deletion length.
// sizeEstimates is cleared during this process.
inline unsigned getDeletionLength(String<unsigned> & sizeEstimates)
{
SEQAN_ASSERT(!empty(sizeEstimates));
std::sort(begin(sizeEstimates), end(sizeEstimates));
unsigned len = sizeEstimates[length(sizeEstimates) / 2];
clear(sizeEstimates);
return len;
}
inline void mergeWindowRange(const Iterator<String<Call>, Standard >::Type & start,
const Iterator<String<Call>, Standard >::Type & last,
String<Triple<String<unsigned> > > & lads,
String<String<String<unsigned>, Array<5> > > & dads,
String<Triple<unsigned> > & genotypes,
String<unsigned> & startPositions,
String<unsigned> & sizeEstimates,
long double & lr,
unsigned & callCount,
unsigned & winCount,
unsigned & significantWindows,
const double & r)
{
start->position = getStartPosition(startPositions);
start->deletionLength = getDeletionLength(sizeEstimates);
start->likelihoodRatio = lr / winCount;
if (setGenotypes(start, last, lads, dads, genotypes))
{
setFreqFromGTs(*start);
start->significantWindows = significantWindows;
if (30.0 * significantWindows / start->deletionLength < r)
setRelWinCovFilter(*start);
winCount = 1;
significantWindows = 1;
lr = 0.0;
++callCount;
}
else
{
markInvalidCall(*start);
}
}
// =======================================================================================
// Function unifyCalls()
// =======================================================================================
// Unifies duplicate calls in c.
// Return false if the string of calls is empty, true otherwise.
inline bool unifyCalls(String<Call> & calls, const double & stddev, const double & r, const bool outputFailed = false)
{
if (length(calls) <= 1u)
return false;
std::sort(begin(calls), end(calls), lowerCall);
Iterator<String<Call> >::Type currentIt = begin(calls, Standard());
const Iterator<String<Call>, Standard >::Type last = end(calls) - 1;
if (!outputFailed)
if (!skipFailedCalls(currentIt, last))
return false;
const Iterator<String<Call> >::Type firstGoodWin = currentIt;
String<Triple<unsigned> > genotypes;
resize(genotypes, length(currentIt->gtLikelihoods), Triple<unsigned>(0, 0, 0));
String<unsigned> startPositions;
String<unsigned> sizeEstimates;
String<Triple<String<unsigned> > > lads;
resize(lads, length(currentIt->lads));
String<String<String<unsigned>, Array<5> > > dads;
resize(dads, length(currentIt->dads));
for (Iterator<String<String<String<unsigned>, Array<5> > > >::Type it = begin(dads); it != end(dads); ++it)
resize(*it, 5, Exact());
append(startPositions, currentIt->position);
append(sizeEstimates, currentIt->deletionLength);
unsigned callCount = 1;
unsigned winCount = 1;
unsigned significantWindows = 1;
long double lr = currentIt->likelihoodRatio;
Iterator<String<Call>, Standard >::Type it = firstGoodWin + 1;
while (true)
{
if (similar(*currentIt, *it, stddev))
{
if (checkAllPass(*it))
{
appendValue(startPositions, it->position);
appendValue(sizeEstimates, it->deletionLength);
++significantWindows;
}
++winCount;
lr += it->likelihoodRatio;
markInvalidCall(*it);
if (it == last)
{
if (!empty(startPositions))
mergeWindowRange(currentIt, it, lads, dads, genotypes, startPositions, sizeEstimates, lr, callCount, winCount, significantWindows, r);
break;
}
}
else
{
if (winCount != 1 && !empty(startPositions))
mergeWindowRange(currentIt, it, lads, dads, genotypes, startPositions, sizeEstimates, lr, callCount, winCount, significantWindows, r);
else
markInvalidCall(*currentIt);
currentIt = it;
}
if (it != last)
{
++it;
}
else
{
if (winCount == 1)
{
--callCount;
markInvalidCall(*currentIt);
}
break;
}
}
String<Call> tmp;
reserve(tmp, callCount, Exact());
it = firstGoodWin;
for (; it <= last; ++it)
{
if (it->filter != maxValue<unsigned char>())
appendValue(tmp, *it);
}
move(calls, tmp);
return true;
}
// =======================================================================================
// Function sum()
// =======================================================================================
// Return the sum of the two values in a pair of doubles.
inline double sum(const Pair<double> & p)
{
return (p.i1 + p.i2);
}
// Return the sum of all three values in a triple of unsigned integers.
inline unsigned sum(const Triple<unsigned> & t)
{
return (t.i1 + t.i2 + t.i3);
}
inline long double sum(const Triple<long double> & t)
{
return (t.i1 + t.i2 + t.i3);
}
// =======================================================================================
// Function allTrue()
// =======================================================================================
// Return true, if all bools in the string are true.
inline bool allTrue(const String<bool> & s)
{
for (Iterator<const String<bool> >::Type it = begin(s, Standard()); it != end(s); ++it)
{
if (!*it)
return false;
}
return true;
}
// =======================================================================================
// Function setNoDataSamples()
// =======================================================================================
// Sets all genotypes for samples marked in lowCoverageSamples to 0.
inline void setNoDataSamples(Call & currentCall, const String<bool> & lowCoverageSamples)
{
for (unsigned i = 0; i < length(lowCoverageSamples); ++i)
{
if (lowCoverageSamples[i])
{
currentCall.gtLikelihoods[i].i1 = 0;
currentCall.gtLikelihoods[i].i2 = 0;
currentCall.gtLikelihoods[i].i3 = 0;
}
}
}
// =======================================================================================
// Function checkSampleNumber()
// =======================================================================================
// Checks if the number of samples with data at the current position is high enough.
// Return true if so, false otherwise.
inline bool checkSampleNumber(const String<bool> & lowCoverageSamples, const double & threshold)
{
SEQAN_ASSERT(!empty(lowCoverageSamples));
unsigned total = length(lowCoverageSamples);
unsigned dataSample = total;
for (unsigned i = 0; i < total; ++i)
if (lowCoverageSamples[i])
--dataSample;
return static_cast<double>(dataSample) / total >= threshold;
}
inline int32_t max(const String<int32_t> & s)
{
int32_t currentMax = 0;
for (Iterator<const String<int32_t>, Standard>::Type it = begin(s, Standard()); it != end(s); ++it)
{
if (*it > currentMax)
currentMax = *it;
}
return currentMax;
}
// =======================================================================================
// Function printStatus()
// =======================================================================================
// Print the status message plus date and time.
void printStatus(const char * message)
{
time_t now = time(0); //Get the current date and time.
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "[PopDel %Y-%m-%d %X] ", &tstruct);
std::cout << buf << message << std::endl; //Print time and message.
}
// Wrapper for calling printStatuts with ostringstream instead of CString.
void printStatus(std::ostringstream & message)
{
std::string msg = message.str();
printStatus(toCString(msg));
}
// =======================================================================================
// Function getIndexFileName()
// =======================================================================================
// Check if the alignment file is a BAM or CRAM file and append .bai or .crai accoordingly.
inline String<char> getIndexFileName(const HtsFile & file)
{
const htsFormat & format = file.fp->format;
String<char> indexFileName = file.filename;
if (format.format == htsExactFormat::bam)
{
append(indexFileName, ".bai");
}
else if (format.format == htsExactFormat::cram)
{
append(indexFileName, ".crai");
}
else
{
std::ostringstream msg;
msg << "[PopDel] Could not determine file type from file name for \'" << file.filename << "\'."
<< " Please make sure that the file name ends with \'.bam\' or \'.cram\'. Terminating.";
SEQAN_THROW(IOError(toCString(msg.str())));
}
return indexFileName;
}
// =======================================================================================
// Function loadBai()
// =======================================================================================
// Load the index belonging to the given BAM/CRAM-file
// Return false on errors, true otherwise.
inline bool loadBaiCrai(HtsFileIn & infile)
{
String<char> indexPathIn = getIndexFileName(infile);
if (!loadIndex(infile, toCString(indexPathIn)))
{
CharString message = "[PopDel] ERROR: Could not load the index file \'";
message += indexPathIn;
message += "\'.";
SEQAN_THROW(IOError(toCString(message)));
return false;
}
return true;
}
// =======================================================================================
// Function parseGenomicRegion()
// =======================================================================================
// Wrapper aroung SeqAns parse() function to guarantee conformity with samtools style regions.
// Return false on parsing errors, true otherwise.
template<typename TString>
inline bool parseGenomicRegion(GenomicRegion & reg, const TString & s)
{
reg = GenomicRegion(); // Necessary to reset reg, because parse() does not guarantee to overwrite all old entries.
if (length(s) == 0)
{
std::ostringstream msg;
msg << "[PopDel] ERROR: Empty genomic region.";
printStatus(msg);
return false;
}
try
{
parse(reg, s); //Try regular parsing first.
if (!isalnum(reg.seqName[length(reg.seqName) - 1]))
{
std::ostringstream msg;
msg << "[PopDel] ERROR: Invalid genomic region \'" << s << "\'.";
printStatus(msg);
return false;
}
return true;
}
catch(...)
{
unsigned lastCol = 0; // Store the last occurenc of ':'.
unsigned i = 0;
for (i = 0; i < length(s); ++i)
{
if (s[i] == ':')
lastCol = i;
}
if (lastCol == i - 1) // last char in s i ':' -> invalid
{
std::ostringstream msg;
msg << "[PopDel] ERROR: Invalid genomic region \'" << s << "\'.";
printStatus(msg);
return false;
}
if (!isdigit(s[lastCol + 1])) // First character after last ':' not a digit -> all seqName.
{
if (!isalnum(s[length(s) - 1])) // Is last char of s valid?
{
std::ostringstream msg;
msg << "[PopDel] ERROR: Invalid genomic region \'" << s << "\'.";
printStatus(msg);
return false;
}
reg.seqName = s;
return true;
}
typename Prefix<const TString>::Type first = prefix(s, lastCol); // Prefix up to last :
typename Suffix<const TString>::Type last = suffix(s, lastCol + 1); // Suffix from last :
CharString dummy = "x:";
append(dummy, last);
try
{
parse(reg, dummy);
}
catch(...)
{
std::ostringstream msg;
msg << "[PopDel] ERROR: Invalid genomic region \'" << s << "\'.";
printStatus(msg);
return false;
}
if (!isalnum(first[length(first) - 1]))
{
std::ostringstream msg;
msg << "[PopDel] ERROR: Invalid genomic region \'" << s << "\'.";
printStatus(msg);
return false;
}
reg.seqName = first;
return true;
}
}
// =======================================================================================
// Function loadFilenames()
// =======================================================================================
// Load multiple filenames from a single file. Removes path to file containing the filenames from set.
void loadFilenames(String<CharString> & files)
{
SEQAN_ASSERT_EQ(length(files), 1u);
CharString inputfilename = files[0];
clear(files);
// Open infile.
std::ifstream infile(toCString(inputfilename));
if (!infile.is_open())
{
std::ostringstream msg;
msg << "[PopDel] Could not open file \'" << inputfilename << "\' for reading.";
SEQAN_THROW(IOError(toCString(msg.str())));
}
// Read file names from infile.
std::string filename;
std::unordered_set<std::string> tmpSet;
while (infile >> filename)
{ //First add them to a set to avoid duplicates.
if (tmpSet.insert(filename).second)
{
appendValue(files, filename);
}
else
{
std::ostringstream msg;
msg << "WARNING: duplicate file " << filename << ". Ignoring additional occurences.";
printStatus(msg);
}
}
// Print status message.
std::ostringstream msg;
msg << "Loaded " << length(files) << " filenames from \'" << inputfilename << "\'.";
printStatus(msg);
}
// =======================================================================================
// Function _getReadGroup()
// =======================================================================================
// Extract the read-group encoded in tags.
// Return the read-group as a CharString.
inline CharString getReadGroup(CharString & tags)
{
BamTagsDict dict(tags); // TODO: Catch if RG tag doen't exist. Error message.
unsigned key = 0;
findTagKey(key, dict, "RG"); //TODO faster access if position in dict is known
CharString rg = "";
extractTagValue(rg, dict, key);
return rg;
}
// Extract the read-group encoded in tags
// Return its rank in the header by extracting it from in the map of read groups.
inline unsigned getReadGroup(CharString & tags,
const std::map<CharString, unsigned> & readGroups,
bool merge = false)
{
if (merge)
return readGroups.begin()->second;
CharString rg = getReadGroup(tags);
SEQAN_ASSERT_NEQ(readGroups.count(rg), 0u);
return readGroups.at(rg);
}
inline bool getRgIdFromKstring(CharString & id, const kstring_t & k)
{
SEQAN_ASSERT(empty(id));
SEQAN_ASSERT_GT(k.l, 7u);
SEQAN_ASSERT_EQ(k.s[0], '@');
SEQAN_ASSERT_EQ(k.s[1], 'R');
SEQAN_ASSERT_EQ(k.s[2], 'G');
SEQAN_ASSERT_EQ(k.s[3], '\t');
SEQAN_ASSERT_EQ(k.s[4], 'I');
SEQAN_ASSERT_EQ(k.s[5], 'D');
SEQAN_ASSERT_EQ(k.s[6], ':');
unsigned i = 7;
while (i < k.l && k.s[i] != '\t')
{
appendValue(id, k.s[i]);
++i;
}
return !empty(id);
}
// =======================================================================================
// Function _getReadGroups()
// =======================================================================================
// Extract all read group IDs and their rank in the header and write them to map.
// Return the number of read groups in the header.
inline unsigned getReadGroups(std::map<CharString, unsigned> & readGroups, HtsFile & file, bool merge = false)
{
readGroups.clear();
int good = 0;
int pos = 0;
while (true)
{
kstring_t kstring = KS_INITIALIZE;
good = sam_hdr_find_line_pos(file.hdr, "RG", pos, &kstring);
if (good == 0)
{
CharString id = "";
if (getRgIdFromKstring(id, kstring))
{
if (merge)
readGroups[id] = 0u;
else
readGroups[id] = static_cast<unsigned>(pos);
++pos;
}
else
{
std::ostringstream msg;
msg << "[PopDel] Error while trying to parse ID from @RG tag. Terminating";
SEQAN_THROW(ParseError(toCString(msg.str())));
}
}
else
{
ks_free(&kstring);
break;
}
ks_free(&kstring);
}
return readGroups.size();