-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcomputeReadAttributes.cpp
1676 lines (1598 loc) · 77.8 KB
/
computeReadAttributes.cpp
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
#include <iostream>
#include <seqan/file.h>
#include <seqan/bam_io.h>
#include <set>
#include <map>
#include <string>
#include <seqan/align.h>
#include <seqan/sequence.h>
#include <seqan/seq_io.h>
#include <math.h>
#include <algorithm>
#include <fstream>
#include <sys/stat.h>
#include <ctime>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
using namespace seqan;
namespace std
{
template <>
struct hash<seqan::String<Dna5> >
{
std::size_t
operator()(seqan::String<Dna5> const & s) const
{
std::size_t seed = 42;
for (char c : s)
seed ^= c + 0x9e3779b9 + (c << 6) + (c >> 2);
return seed;
}
};
}
namespace computeReadAttributes
{
//Structure to store marker information
struct STRinfo {
CharString chrom;
int STRstart;
int STRend;
Dna5String motif;
float refRepeatNum; //Number of repeats in reference sequence
Dna5String refBf;
Dna5String refAf;
CharString refRepSeq;
float refRepPurity;
unsigned minFlankLeft;
unsigned minFlankRight;
unsigned refLenBp;
std::unordered_set<Dna5String> hash8beforeSet;
std::unordered_set<Dna5String> hash8afterSet;
vector<float> motifFrqs;
string MFLrefRepSeqMFR;
} ;
//Structure to store marker information
struct STRinfoSmall {
CharString chrom;
int STRstart;
int STRend;
CharString motif;
float refRepeatNum; //Number of repeats in reference sequence
} ;
//So I can map from STRinfoSmall in finalMap
bool operator<(const STRinfoSmall & Left, const STRinfoSmall & Right)
{
return Left.STRstart < Right.STRstart;
}
bool operator ==(const STRinfoSmall & Left, const STRinfoSmall & Right)
{
return Left.chrom == Right.chrom && Left.STRstart == Right.STRstart && Left.STRend == Right.STRend && Left.motif == Right.motif && Left.refRepeatNum == Right.refRepeatNum;
}
//structure to store read information
struct ReadInfo {
int STRend;
CharString motif;
float refRepeatNum; //Number of repeats in reference sequence
float numOfRepeats;
float ratioBf;
float ratioAf;
unsigned locationShift;
float purity;
float ratioOver20In;
unsigned mateEditDist;
CharString repSeq; //Repeat sequence in read
CharString readName;
} ;
//structure to store read information
struct ReadPairInfo {
float numOfRepeats;
float ratioBf;
float ratioAf;
unsigned locationShift;
float purity;
float ratioOver20In;
unsigned mateEditDist;
CharString repSeq; //Repeat sequence in read
CharString readName;
} ;
} // namespace computeReadAttributes
namespace std
{
template <>
struct hash<seqan::String<char> >
{
std::size_t
operator()(seqan::String<char> const & s) const
{
std::size_t seed = 42;
for (char c : s)
seed ^= c + 0x9e3779b9 + (c << 6) + (c >> 2);
return seed;
}
};
template <>
struct hash<seqan::Pair<int> >
{
std::size_t
operator()(seqan::Pair<int> const & p) const
{
std::size_t seed = 42;
seed ^= p.i1 + 0x9e3779b9 + (p.i1 << 6) + (p.i1 >> 2);
seed ^= p.i2 + 0x9e3779b9 + (p.i2 << 6) + (p.i2 >> 2);
return seed;
}
};
template <>
struct hash<computeReadAttributes::STRinfoSmall >
{
std::size_t
operator()(computeReadAttributes::STRinfoSmall const & p) const
{
std::size_t seed = 42;
for (char c : p.chrom)
seed ^= c + 0x9e3779b9 + (c << 6) + (c >> 2);
seed ^= p.STRstart + 0x9e3779b9 + (p.STRstart << 6) + (p.STRstart >> 2);
seed ^= p.STRend + 0x9e3779b9 + (p.STRend << 6) + (p.STRend >> 2);
return seed;
}
};
template <>
struct hash<seqan::Triple<CharString, CharString, int> >
{
std::size_t
operator()(seqan::Triple<CharString, CharString, int> const & p) const
{
std::size_t seed = 42;
for (char c : p.i1)
seed ^= c + 0x9e3779b9 + (c << 6) + (c >> 2);
for (char c : p.i2)
seed ^= c + 0x9e3779b9 + (c << 6) + (c >> 2);
seed ^= p.i3 + 0x9e3779b9 + (p.i3 << 6) + (p.i3 >> 2);
return seed;
}
};
} // namespace std
namespace computeReadAttributes
{
//Vector to check how many repeats I need to find in a read w.r.t. motif length
std::vector<unsigned> repeatNumbers (6);
//Vector to store my repeat purity demands w.r.t motif length.
std::vector<Pair<float> > purityDemands (6);
string chroms[23] = { "chr1", "chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr8", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrX" };
//map storing a set of all hamming distance 1 sequences for each motif
unordered_map<Dna5String, std::unordered_set<Dna5String> > motifToPermutations;
//For repeating a motif n times
Dna5String repeat(Dna5String s, int n) {
Dna5String ret;
for (int i = 0; i < n; i++) {
append(ret,s);
}
return ret;
}
//Create all one error permutations of motif passed
std::unordered_set<Dna5String> createPermutations(Dna5String motifRepeat)
{
std::unordered_set<Dna5String> permutations;
permutations.insert(motifRepeat);
Dna5String bases = "ATCGN";
for (unsigned i = 0; i < length(motifRepeat); ++i)
{
Dna5String motifCopy = motifRepeat;
for(unsigned j = 0; j < length(bases); ++j)
{
motifCopy[i] = bases[j];
if(motifCopy[i] != motifRepeat[i])
permutations.insert(motifCopy);
}
erase(motifCopy,i);
permutations.insert(motifCopy);
}
return permutations;
}
//Primitive pattern search, just searches for first and last occurence of #repeats*motif or hammingDistance1(#repeats*motif) without considering what's between them
Pair<Pair<int>, float> findPatternPrim(Dna5String motif, BamAlignmentRecord& record, const unsigned motifLength)
{
//unsigned motifLength = length(motif);
Dna5String pattern = repeat(motif,repeatNumbers[motifLength-1]);
std::unordered_set<Dna5String> permutations = motifToPermutations[motif];
unsigned patternLength = length(pattern);
int startCoordinate = length(record.seq);
int endCoordinate = 0;
unsigned index = 0;
while(index+patternLength <= length(record.seq))
{
if (permutations.find(infixWithLength(record.seq, index, patternLength)) != permutations.end())
{
if (startCoordinate == length(record.seq))
startCoordinate = index;
endCoordinate = index + patternLength;
index = index + motifLength;
}
else
{
if (permutations.find(infixWithLength(record.seq, index, patternLength-1)) != permutations.end())
{
if (startCoordinate == length(record.seq))
startCoordinate = index;
endCoordinate = index + patternLength - 1;
if (prefix(pattern, motifLength) == prefix(infixWithLength(record.seq, index, patternLength-1), motifLength))
index = index + motifLength;
else
index = index + motifLength - 1;
}
else
index = index + 1;
}
}
float numOfRepeats = (float)(endCoordinate-startCoordinate)/(float)motifLength;
if (endCoordinate == length(record.seq))
endCoordinate -= 1;
return Pair<Pair<int>, int>(Pair<int>(startCoordinate,endCoordinate), numOfRepeats);
}
//Check if read sequence contains motif and return start and end coordinates and number of repeats
Pair<Pair<int>, int> findPattern(Dna5String & pattern, Dna5String & readSequence, int motifLength)
{
unsigned patternLength = length(pattern);
std::unordered_set<Dna5String> permutations = createPermutations(pattern);
int startCoordinate = length(readSequence);
int endCoordinate = 0;
unsigned moves = 0;
int currentStart = length(readSequence);
int currentEnd = 0;
unsigned currentMoves = 0;
unsigned index = 0;
unsigned errors = 0;
while(index+patternLength <= length(readSequence))
{
Dna5String theSubString = infixWithLength(readSequence, index, patternLength);
Dna5String theSubStringMini = infixWithLength(readSequence, index, patternLength-1);
if (permutations.find(theSubString) != permutations.end())
{
if (startCoordinate == length(readSequence))
{
startCoordinate = index;
errors = 0;
moves = 0;
}
endCoordinate = index + patternLength;
index = index + motifLength;
errors = 0;
moves += 1;
}
else
{
if (permutations.find(theSubStringMini) != permutations.end())
{
if (startCoordinate == length(readSequence))
{
startCoordinate = index;
errors = 0;
moves = 0;
}
endCoordinate = index + patternLength - 1;
if (prefix(pattern, motifLength) == prefix(theSubStringMini, motifLength))
index = index + motifLength;
else
index = index + motifLength - 1;
errors = 0;
moves += 1;
}
else
{
index = index + 1;
++errors;
}
}
if (startCoordinate != length(readSequence) && errors > floor((float)motifLength/(float)2))
{
if (endCoordinate - startCoordinate > currentEnd - currentStart)
{
currentStart = startCoordinate;
currentEnd = endCoordinate;
currentMoves = moves;
}
startCoordinate = length(readSequence);
endCoordinate = 0;
}
}
unsigned numOfRepeats = moves + repeatNumbers[motifLength-1] - 1;
if (endCoordinate - startCoordinate > currentEnd - currentStart)
return Pair<Pair<int>, int>(Pair<int>(startCoordinate,endCoordinate), numOfRepeats);
else
return Pair<Pair<int>, int>(Pair<int>(currentStart,currentEnd), numOfRepeats);
}
//Compute the actual number of repeats/expected number of repeats based on length
float getPurity(Dna5String & motif, CharString & STRsequence)
{
//cout << "getPurity( " << motif << "," << STRsequence << ")\n";
unsigned motifLength = length(motif);
unsigned expectReps = length(STRsequence)/motifLength;
unsigned result = 0;
unsigned index = 0;
while(index+motifLength <= length(STRsequence))
{
//Dna5String theSubString = infixWithLength(STRsequence, index, motifLength);
//cout << "Checking: " << theSubString << "\n";
if (infixWithLength(STRsequence, index, motifLength) == motif)
{
result++;
index = index + motifLength;
}
else
{
index = index + 1;
}
}
return min (1.0f, (float)result/(float)expectReps);
}
//Finds ratio of bases in a sequence with PHRED score higher than 20
float findRatioOver20(CharString sequence)
{
unsigned numOver20 = 0;
int numVal;
for (unsigned i = 0; i<length(sequence); ++i)
{
numVal = sequence[i] - 33;
if(numVal>=20)
++numOver20;
}
return (float)numOver20/(float)(length(sequence));
}
//Get value of a tag (ATH! does not work if tag-value is not numeric)
int getTagValue(BamAlignmentRecord& record, CharString tagName)
{
int returnValue;
unsigned myIdx = 0;
BamTagsDict tagsDict(record.tags);
bool keyFound = findTagKey(myIdx, tagsDict, tagName);
if (!keyFound)
{
cerr << "ERROR: Unknown key!" << tagName << " in read: " << record.qName << endl;
returnValue = 999;
return returnValue;
}
else
{
bool ok = extractTagValue(returnValue, tagsDict, myIdx);
if (!ok)
{
cerr << "ERROR: There was an error extracting" << tagName << "from tags!\n";
returnValue = 999;
return returnValue;
}
else
return returnValue;
}
}
unsigned checkForAndRemoveSoftClippingAfter(BamAlignmentRecord& record)
{
unsigned nRemoved = 0;
String<CigarElement<> > cigarString = record.cigar;
CharString cigarOperation = cigarString[length(cigarString)-1].operation;
string cigarOperationStr = toCString(cigarOperation);
if (cigarOperationStr.compare("S")==0)
{
nRemoved = cigarString[length(cigarString)-1].count;
for (unsigned i = 0; i<cigarString[length(cigarString)-1].count; ++i)
{
eraseBack(record.seq);
eraseBack(record.qual);
}
eraseBack(record.cigar);
}
return nRemoved;
}
unsigned checkForAndRemoveSoftClippingBefore(BamAlignmentRecord& record)
{
unsigned nRemoved = 0;
String<CigarElement<> > cigarString = record.cigar;
CharString cigarOperation = cigarString[0].operation;
string cigarOperationStr = toCString(cigarOperation);
if (cigarOperationStr.compare("S")==0)
{
nRemoved = cigarString[0].count;
erase(record.seq, 0, cigarString[0].count);
erase(record.qual, 0, cigarString[0].count);
erase(record.cigar, 0);
}
return nRemoved;
}
//Computes all sorts of quality indicators for the given read w.r.t. the given microsatellite
unsigned noFrontAlign = 0, noBackAlign = 0, frontAlign = 0, backAlign = 0;
Pair<Triple<CharString, CharString, int>,ReadInfo> computeReadInfo(BamAlignmentRecord& record, STRinfo& markerInfo, Pair<Pair<int>, float> coordinates, int minFlank, int maxRepeatLength)
{
//Type definition for alignment structure
typedef Dna5String TSequence;
typedef Align<TSequence,ArrayGaps> TAlign;
typedef Row<TAlign>::Type TRow;
//cout << "Looking at read: " << record.qName << endl;
//cout << "coordinates.i1.i1: " << coordinates.i1.i1 << " coordinates.i1.i2: " << coordinates.i1.i2 << "\n";
//Variables for sequence-parts
Dna5String before, after, before_8, after_8;
CharString qualString = record.qual;
ReadInfo mapValue;
int oldStartCoord = coordinates.i1.i1;
unsigned motifLength = length(markerInfo.motif), readLength = length(record.seq);
//Create key for storing readInfo in map
Triple<CharString, CharString, int> mapKey = Triple<CharString, CharString, int>(record.qName, markerInfo.chrom, markerInfo.STRstart);
//Insert values into mapValue in returnPair
mapValue.STRend = markerInfo.STRend;
mapValue.motif = markerInfo.motif;
mapValue.refRepeatNum = markerInfo.refRepeatNum;
int scoreBf = 0, scoreAf = 0, startCoord = 0, endCoord = 0, leftFlank = 0, rightFlank = 0;
float rBf = 0.0, rAf = 0.0;
//check if 8-mer in front of and behind repeat in read match reference with edit-distance max 1
//This is the best case scenario, then I skip flanking alignment
before_8 = infix(record.seq, max(0,coordinates.i1.i1-8), coordinates.i1.i1);
//cout << "Made before guy of length: " << length(before_8) << ".\n";
after_8 = infix(record.seq, min(coordinates.i1.i2+1, (int)(readLength-1)),min(coordinates.i1.i2+9,(int)readLength));
//cout << "Made after guy of length: " << length(after_8) << ".\n";
bool doBeforeAlign = true, doAfterAlign = true;
if (length(before_8) == 8)
{
//check this marker's 8mer edit distance 1 hash table for before_8
if (markerInfo.hash8beforeSet.find(before_8) != markerInfo.hash8beforeSet.end())
{
//Skip alignment and set startCoord same as coordinates
doBeforeAlign = false;
startCoord = coordinates.i1.i1;
scoreBf = 8;
before = before_8;
leftFlank = coordinates.i1.i1;
rBf = 1.0f;
//cout << "Found 8 mer in before map.\n";
}
}
if (length(after_8) == 8)
{
//check this marker's 8mer edit distance 1 hash table for after_8
if (markerInfo.hash8afterSet.find(after_8) != markerInfo.hash8afterSet.end())
{
//Skip alignment and set endCoord same as coordinates
doAfterAlign = false;
endCoord = coordinates.i1.i2 - coordinates.i1.i1;
scoreAf = 8;
after = after_8;
rightFlank = readLength - coordinates.i1.i2;
rAf = 1.0f;
//cout << "Found 8 mer in after map.\n";
}
}
if (markerInfo.minFlankLeft > 8)
doBeforeAlign = true;
if (markerInfo.minFlankRight > 8)
doAfterAlign = true;
//If I need to realign in front of repeat
//cout << "doBeforeAlign: " << doBeforeAlign << " do AfterAlign: " << doAfterAlign << "\n";
if (doBeforeAlign)
{
TAlign alignBefore;
resize(rows(alignBefore), 2);
before = prefix(record.seq, coordinates.i1.i2+1);
assignSource(row(alignBefore,0), suffix(markerInfo.refBf,1000-length(before)-1));
assignSource(row(alignBefore,1),before);
scoreBf = globalAlignment(alignBefore, Score<int,Simple>(1,-2,-1,-5), AlignConfig<true, false, true, false>());
int viewPosition = toViewPosition(row(alignBefore,0),length(source(row(alignBefore,0)))-1);
startCoord = toSourcePosition(row(alignBefore,1),viewPosition)+1;
if (startCoord == 1 && isGap(row(alignBefore,1),viewPosition))
startCoord -= 1;
leftFlank = startCoord;
//Check wether the alignment score fails our criteria, if it does then we see if we can remove soft clipped sequence and realign.
/*if ((float)scoreBf/(float)(startCoord+1) < 0.6 && !hasFlagUnmapped(record))
{
unsigned nRemoved = checkForAndRemoveSoftClippingBefore(record);
coordinates.i1.i2 -= nRemoved;
coordinates.i1.i1 -= nRemoved;
oldStartCoord = max((int)0, (int)oldStartCoord - (int)nRemoved);
if (nRemoved>0 && nRemoved <= coordinates.i1.i1+nRemoved)
{
before = prefix(record.seq, coordinates.i1.i2+1);
assignSource(row(alignBefore,1),before);
scoreBf = globalAlignment(alignBefore, Score<int,Simple>(1,-2,-1,-5), AlignConfig<true, false, true, false>());
viewPosition = toViewPosition(row(alignBefore,0),length(source(row(alignBefore,0)))-1);
startCoord = toSourcePosition(row(alignBefore,1),viewPosition)+1;
if (startCoord == 1 && isGap(row(alignBefore,1),viewPosition))
startCoord -= 1;
leftFlank = startCoord;
}
}*/
//cout << "Finished before alignment\n";
rBf = (float)scoreBf/(float)(startCoord+1);
++frontAlign;
/*CharString ref_cs = suffix(markerInfo.refBf,1000-length(before)-1);
const string ref = toCString(ref_cs);
CharString query_cs = before;
const string query = toCString(query_cs);
int32_t maskLen = strlen(query.c_str())/2;
maskLen = maskLen < 15 ? 15 : maskLen;
// Declares a default Aligner
StripedSmithWaterman::Aligner aligner(1,2,5,1);
// Declares a default filter
StripedSmithWaterman::Filter filter;
// Declares an alignment that stores the result
StripedSmithWaterman::Alignment alignment;
// Aligns the query to the ref
aligner.Align(query.c_str(), ref.c_str(), ref.size(), filter, &alignment, maskLen);
cout << "SeqAn\t" << scoreBf << "\tSW\t" << alignment.sw_score << "\tdelta\t" << alignment.sw_score - scoreBf<< "\n";
cout << "SeqAnSt\t" << startCoord << "\tSW\t" << alignment.query_end << "\tdelta\t" << alignment.query_end - startCoord<< "\n";
cout << "findPattern\t" << coordinates.i1.i1 << "-" << coordinates.i1.i2 << "\n";*/
}
else
++noFrontAlign;
//If I need to realign behind repeat
if (doAfterAlign)
{
TAlign alignAfter;
resize(rows(alignAfter), 2);
after = suffix(record.seq, coordinates.i1.i1);
assignSource(row(alignAfter,0), prefix(markerInfo.refAf,length(after)+1));
assignSource(row(alignAfter,1),after);
scoreAf = globalAlignment(alignAfter, Score<int,Simple>(1,-2,-1,-5), AlignConfig<false, true, false, true>());
endCoord = toSourcePosition(row(alignAfter,1),toViewPosition(row(alignAfter,0),0))-1;
rightFlank = length(source(row(alignAfter,1)))-endCoord - 1;
//Check wether the alignment score fails our criteria, if it does then we see if we can remove soft clipped sequence and realign.
/*if ((float)scoreAf/(float)(length(after)-endCoord) < 0.6 && !hasFlagUnmapped(record))
{
unsigned readLength = length(record.seq);
unsigned nRemoved = checkForAndRemoveSoftClippingAfter(record);
if (nRemoved>0 && readLength - nRemoved > coordinates.i1.i2)
{
//redefine after region and realign
after = suffix(record.seq, coordinates.i1.i1);
assignSource(row(alignAfter,1),after);
scoreAf = globalAlignment(alignAfter, Score<int,Simple>(1,-2,-1,-5), AlignConfig<false, true, false, true>());
endCoord = toSourcePosition(row(alignAfter,1),toViewPosition(row(alignAfter,0),0))-1;
rightFlank = length(source(row(alignAfter,1)))-endCoord - 1;
}
}*/
rAf = (float)scoreAf/(float)(length(after)-endCoord-1);
++backAlign;
}
else
++noBackAlign;
/*bool debug = true;
if (debug)
{
int flankSum = leftFlank + rightFlank;
cout << "FlankSum: " << flankSum << " leftFlank: " << leftFlank << " rightFlank: " << rightFlank << endl;
if (leftFlank > 0)
cout << "AlignmentScore before: " << (float)scoreBf/(float)startCoord << endl;
if (rightFlank > 0)
cout << "AlignmentScore after: " << (float)scoreAf/(float)(length(after)-endCoord-1) << endl;
cout << "Start coord: " << startCoord << endl;
cout << "Old start coord: " << oldStartCoord << endl;
cout << "End coord: " << endCoord << endl;
//cout << "Infix command is: infix(" << startCoord << "," << oldStartCoord+endCoord+1 << ")" << endl;
//cout << "Repeat purity: " << getPurity(markerInfo.motif,infix(record.seq, startCoord, oldStartCoord+endCoord+1)) << endl;
}*/
float refRepPurity = markerInfo.refRepPurity;
bool startOk = false;
bool endOk = false;
bool purityOk = false;
int flankSum = leftFlank + rightFlank;
if ((startCoord >= oldStartCoord + endCoord) || (((oldStartCoord+endCoord+1)-startCoord < maxRepeatLength) && (leftFlank < markerInfo.minFlankLeft || rightFlank < markerInfo.minFlankRight)))
{
//cout << "Failing flanking and start/end coord check." << endl;
coordinates.i1.i1 = startCoord;
coordinates.i1.i2 = endCoord;
mapValue.ratioBf = 0;
mapValue.ratioAf = 0;
mapValue.numOfRepeats = 666;
//Debugging code
//cout << "Infix command is: infix(" << coordinates.i1.i1 << "," << oldStartCoord+coordinates.i1.i2+1 << ")" << endl;
mapValue.ratioOver20In = 0;
mapValue.purity = 0;
mapValue.repSeq = "";
mapValue.locationShift = 100;
return Pair<Triple<CharString, CharString, int>,ReadInfo>(mapKey,mapValue);
}
mapValue.repSeq = infix(record.seq, startCoord, oldStartCoord+endCoord+1);
float readPurity = getPurity(markerInfo.motif, mapValue.repSeq);
unsigned startCoord1 = startCoord, endCoord1 = oldStartCoord+endCoord+1;
/*cout << "Read purity: " << readPurity << "\n";
cout << "Reference purity: " << refRepPurity << "\n";
cout << "Purity minimum: " << purityDemands[motifLength-1].i1 << "*" << refRepPurity << "=" << purityDemands[motifLength-1].i1*refRepPurity << "\n";*/
if (readPurity < purityDemands[motifLength-1].i1*refRepPurity)
{
//cout << "Failing read purity check" << endl;
coordinates.i1.i1 = startCoord;
coordinates.i1.i2 = endCoord;
mapValue.ratioBf = 0;
mapValue.ratioAf = 0;
mapValue.numOfRepeats = 666;
//Debugging code
//cout << "Infix command is: infix(" << coordinates.i1.i1 << "," << oldStartCoord+coordinates.i1.i2+1 << ")" << endl;
mapValue.ratioOver20In = 0;
mapValue.purity = 0;
mapValue.repSeq = "";
mapValue.locationShift = 100;
return Pair<Triple<CharString, CharString, int>,ReadInfo>(mapKey,mapValue);
}
else
purityOk = true;
//Check if a minimum number of repeats have been found and whether the flanking area is sufficient for both start and end coordinates
if ((readLength - leftFlank - rightFlank >=length(markerInfo.motif)*repeatNumbers[length(markerInfo.motif)-1]) && (leftFlank>=minFlank))
startOk = true;
if ((endCoord >= length(markerInfo.motif)*repeatNumbers[length(markerInfo.motif)-1]-1)&&(rightFlank >= minFlank))
endOk = true;
//I allow only marker specific minimum number of aligning bases on either side if I have more than 2*minFlank aligned bases in total.
if (flankSum >= 2*minFlank && leftFlank >= markerInfo.minFlankLeft && rightFlank >= markerInfo.minFlankRight)
{
startOk = true;
endOk = true;
}
/*if (debug)
{
cout << "Start ok: " << startOk << endl;
cout << "End ok: " << endOk << endl;
cout << "Purity ok: " << purityOk << endl;
}*/
if (((oldStartCoord+endCoord+1)-startCoord >= maxRepeatLength) && (leftFlank < markerInfo.minFlankLeft) && (flankSum>=2*minFlank) && (rAf>0.7) && (readPurity>(purityDemands[motifLength-1].i2*refRepPurity)))
{
//cout << "Am making greater than allele on left end." << endl;
coordinates.i1.i1 = startCoord;
coordinates.i1.i2 = endCoord;
mapValue.ratioBf = 0;
mapValue.ratioAf = rAf;
//cout << "Infix command is: infix(" << coordinates.i1.i1 << "," << oldStartCoord+coordinates.i1.i2+1 << ")" << endl;
mapValue.numOfRepeats = (float)maxRepeatLength/(float)length(markerInfo.motif);
mapValue.ratioOver20In = findRatioOver20(infix(qualString, coordinates.i1.i1, oldStartCoord+coordinates.i1.i2+1));
//cout << "getPurity( " << markerInfo.motif << "," << infix(record.seq, startCoord, oldStartCoord+endCoord+1) << ")\n";
if (startCoord1!=coordinates.i1.i1 || endCoord1 != oldStartCoord+coordinates.i1.i2+1)
{
mapValue.repSeq = infix(record.seq, coordinates.i1.i1, oldStartCoord+coordinates.i1.i2+1);
mapValue.purity = getPurity(markerInfo.motif,mapValue.repSeq);
}
else
mapValue.purity = readPurity;
}
else
{
if (((oldStartCoord+endCoord+1)-startCoord >= maxRepeatLength) && (rightFlank < markerInfo.minFlankRight) && (flankSum>=2*minFlank) && (rBf>0.7) && (readPurity>(purityDemands[motifLength-1].i2*refRepPurity)))
{
//cout << "Am making greater than allele on right end." << endl;
coordinates.i1.i1 = startCoord;
coordinates.i1.i2 = endCoord;
mapValue.ratioBf = rBf;
mapValue.ratioAf = 0;
//cout << "Infix command is: infix(" << coordinates.i1.i1 << "," << oldStartCoord+coordinates.i1.i2+1 << ")" << endl;
mapValue.numOfRepeats = (float)maxRepeatLength/(float)length(markerInfo.motif);
mapValue.ratioOver20In = findRatioOver20(infix(qualString, coordinates.i1.i1, oldStartCoord+coordinates.i1.i2+1));
if (startCoord1!=coordinates.i1.i1 || endCoord1 != oldStartCoord+coordinates.i1.i2+1)
{
mapValue.repSeq = infix(record.seq, coordinates.i1.i1, oldStartCoord+coordinates.i1.i2+1);
mapValue.purity = getPurity(markerInfo.motif,mapValue.repSeq);
}
else
mapValue.purity = readPurity;
}
else
{
if (rightFlank < markerInfo.minFlankRight && leftFlank < markerInfo.minFlankLeft && readPurity>(purityDemands[motifLength-1].i2*refRepPurity) && (oldStartCoord+endCoord+1)-startCoord >= maxRepeatLength && readLength>=maxRepeatLength)
{
//cout << "Am making a SUPER allele." << endl;
coordinates.i1.i1 = 0;
coordinates.i1.i2 = readLength-1;
mapValue.ratioBf = 0.0;
mapValue.ratioAf = 0.0;
//cout << "Infix command is: infix(" << 0 << "," << length(record.seq)-1 << ")" << endl;
mapValue.numOfRepeats = (float)maxRepeatLength/(float)length(markerInfo.motif);
mapValue.ratioOver20In = findRatioOver20(record.seq);
if (length(mapValue.repSeq) != endCoord1-startCoord1)
{
mapValue.repSeq = record.seq;
mapValue.purity = getPurity(markerInfo.motif,mapValue.repSeq);
}
else
mapValue.purity = readPurity;
}
else
{
//If both coordinates are ok, the distance between them is > motifLength * min#ofMotifs and alignment scores on both end are ok then the read is useful.
if (startOk && endOk && purityOk && startCoord < oldStartCoord + endCoord && rBf>0.6 && rAf>0.6)
{
coordinates.i1.i1 = startCoord;
coordinates.i1.i2 = endCoord;
mapValue.ratioBf = rBf;
mapValue.ratioAf = rAf;
//Debugging code
//cout << "Infix command is: infix(" << coordinates.i1.i1 << "," << oldStartCoord+coordinates.i1.i2+1 << ")" << endl;
mapValue.repSeq = infix(record.seq, coordinates.i1.i1, oldStartCoord+coordinates.i1.i2+1);
mapValue.numOfRepeats = (float)length(mapValue.repSeq)/(float)length(markerInfo.motif);
if (length(mapValue.repSeq)>=maxRepeatLength)
mapValue.numOfRepeats = (float)maxRepeatLength/(float)length(markerInfo.motif);
//If I find less repeats than the required minimum (depending on the motif length) then I don't use the read
if (ceil(mapValue.numOfRepeats) < repeatNumbers[length(markerInfo.motif)-1])
{
//cout << "Not enough repeats." << endl;
mapValue.numOfRepeats = 666;
}
mapValue.ratioOver20In = findRatioOver20(infix(qualString, coordinates.i1.i1, oldStartCoord+coordinates.i1.i2+1));
if (startCoord1 != coordinates.i1.i1 || endCoord1 != oldStartCoord+coordinates.i1.i2+1)
mapValue.purity = getPurity(markerInfo.motif,mapValue.repSeq);
else
mapValue.purity = readPurity;
//cout << "Processed read: " << record.qName << " into map and reported: " << mapValue.numOfRepeats << ".\n";
}
//Otherwise I can't use the read so I set numOfRepeats to 666
else
{
//cout << "Failing alignment score requirements" << endl;
//cout << "Setting num of repeats to 666 in the last else statement." << endl;
coordinates.i1.i1 = startCoord;
coordinates.i1.i2 = endCoord;
mapValue.ratioBf = 0;
mapValue.ratioAf = 0;
mapValue.numOfRepeats = 666;
//Debugging code
//cout << "Infix command is: infix(" << coordinates.i1.i1 << "," << oldStartCoord+coordinates.i1.i2+1 << ")" << endl;
mapValue.repSeq = "";
mapValue.ratioOver20In = 0;
mapValue.purity = 0;
}
}
}
};
//Debugging code
/*cout << "Motif: " << mapValue.motif << " Start: " << markerInfo.STRstart << endl;
cout << "Before: " << prefix(before, coordinates.i1.i1) << endl;
cout << "Aligned to: " << suffix(source(row(alignBefore,0)),toSourcePosition(row(alignBefore,0),toViewPosition(row(alignBefore,1),0))) << endl;
cout << "Repeat: " << mapValue.repSeq << endl;
cout << "After: " << suffix(after, coordinates.i1.i2+1) << endl;
cout << "Aligned to: " << prefix(source(row(alignAfter,0)),toSourcePosition(row(alignAfter,0),toViewPosition(row(alignAfter,1),length(source(row(alignAfter,1)))))) << endl;
cout << "Number of repeats: " << mapValue.numOfRepeats << endl;
if (mapValue.numOfRepeats == 666)
{
if (!startOk)
{
cout << "Enough repeats according to start? " << ((length(source(row(alignBefore,1)))-(startCoord+1)) >= (length(markerInfo.motif)*repeatNumbers[length(markerInfo.motif)-1])) << endl;
cout << "Enough flanking area in front? " << (startCoord>=minFlank) << endl;
}
if (!endOk)
{
cout << "Enough repeats according to end? " << (endCoord >= length(markerInfo.motif)*repeatNumbers[length(markerInfo.motif)-1]-1) << endl;
cout << "Enough flanking area behind ?" << (length(source(row(alignAfter,1)))-endCoord >= minFlank) << endl;
}
cout << "Start and end not overlapping? " << ((startCoord + length(markerInfo.motif)*repeatNumbers[length(markerInfo.motif)-1])< (startCoord + endCoord)) << endl;
}*/
//Check location shift
mapValue.locationShift = abs(oldStartCoord - startCoord);
/*if (mapValue.numOfRepeats != 666)
cout << "Used this read and gave: " << mapValue.numOfRepeats << "repeats.\n";
else
cout << "Didn't use this read." << endl;*/
return Pair<Triple<CharString, CharString, int>,ReadInfo>(mapKey,mapValue);
}
String<STRinfo> readMarkerinfo(CharString & markerInfoFile, int minFlank, CharString & attributeDirectory, unordered_map<Pair<int>, Pair<String<long int> ,FILE*> > & startAndEndToStreamAndOffsets, unsigned nPns)
{
String<STRinfo> markers;
float freq;
STRinfo currInfo;
//Read all markers into memory
ifstream markerFile(toCString(markerInfoFile));
while (!markerFile.eof())
{
string chromString;
markerFile >> chromString;
if (chromString.length() == 0)
break;
currInfo.chrom = chromString;
markerFile >> currInfo.STRstart;
markerFile >> currInfo.STRend;
string motifString;
markerFile >> motifString;
currInfo.motif = motifString;
motifToPermutations[currInfo.motif] = createPermutations(repeat(currInfo.motif,repeatNumbers[length(currInfo.motif)-1]));
markerFile >> currInfo.refRepeatNum;
string refBfString;
markerFile >> refBfString;
currInfo.refBf = refBfString;
string refAfString;
markerFile >> refAfString;
currInfo.refAf = refAfString;
string refRepSeq;
markerFile >> refRepSeq;
currInfo.refLenBp = refRepSeq.length();
currInfo.refRepSeq = refRepSeq;
currInfo.refRepeatNum = (float)refRepSeq.length()/(float)motifString.length();
markerFile >> currInfo.minFlankLeft;
markerFile >> currInfo.minFlankRight;
currInfo.MFLrefRepSeqMFR = refBfString.substr(1000-currInfo.minFlankLeft, currInfo.minFlankLeft);
currInfo.MFLrefRepSeqMFR += refRepSeq;
currInfo.MFLrefRepSeqMFR += refAfString.substr(0,currInfo.minFlankRight);
markerFile >> currInfo.refRepPurity;
markerFile >> freq;
currInfo.motifFrqs.push_back(freq);
markerFile >> freq;
currInfo.motifFrqs.push_back(freq);
markerFile >> freq;
currInfo.motifFrqs.push_back(freq);
markerFile >> freq;
currInfo.motifFrqs.push_back(freq);
currInfo.hash8beforeSet = createPermutations(suffix(currInfo.refBf,992));
currInfo.hash8afterSet = createPermutations(prefix(currInfo.refAf,8));
//Make output file for current marker
CharString currAttributeDirectory = attributeDirectory;
append(currAttributeDirectory, to_string(currInfo.STRstart));
append(currAttributeDirectory, "_");
append(currAttributeDirectory, currInfo.motif);
//cout << "Outputfile: " << currAttributeDirectory << "\n";
Pair<int> mapKey = Pair<int>(currInfo.STRstart, currInfo.STRend);
FILE *fp;
fp = fopen(toCString(currAttributeDirectory), "w+");
startAndEndToStreamAndOffsets[mapKey].i2 = fp;
if (startAndEndToStreamAndOffsets[mapKey].i2 == NULL)
cerr << "Couldn't make ofstream for marker @ " << currAttributeDirectory << "\n";
else
{
if (fseek(startAndEndToStreamAndOffsets[mapKey].i2, nPns*(11), SEEK_SET) != 0)
cerr << "Could not reserve index space at front of " << currAttributeDirectory << "\n";
else
{
resize(startAndEndToStreamAndOffsets[mapKey].i1, nPns, 0);
fprintf(startAndEndToStreamAndOffsets[mapKey].i2, "\r\n");
}
}
appendValue(markers, currInfo);
}
return markers;
}
String<Pair<CharString> > readBamList(CharString & bamListFile)
{
String<Pair<CharString> > PnsAndBams;
Pair<CharString> currPnAndBam;
//Read all Pns and their bamFiles
ifstream bamList(toCString(bamListFile));
while (!bamList.eof())
{
string PN_ID;
bamList >> PN_ID;
if (PN_ID.length() == 0)
break;
currPnAndBam.i1 = PN_ID;
string bamPath;
bamList >> bamPath;
currPnAndBam.i2 = bamPath;
appendValue(PnsAndBams, currPnAndBam);
}
return PnsAndBams;
}
vector<string> splitString(string &s, char delim) {
vector<string> elems;
stringstream ss(s);
string next;
while(getline(ss, next, delim)) {
elems.push_back(next);
}
return elems;
}
void readExpansions(CharString & expansionFile, unordered_map<string, String<Triple<vector<float>,unsigned,unsigned> > > & chromToMotifAndIntervals)
{
Triple<vector<float>, unsigned, unsigned> motifStartEnd;
string chrom, length, line;
vector<string> words;
ifstream expansions(toCString(expansionFile));
while (getline(expansions, line))
{
words = splitString(line, ' ');
chrom = words[0];
motifStartEnd.i2 = stoi (words[1]);
motifStartEnd.i3 = stoi (words[2]);
motifStartEnd.i1.resize(words.size()-5);
transform (words.begin() + 5, words.end(), motifStartEnd.i1.begin(), [](std::string const & str){return std::stof(str);});
appendValue(chromToMotifAndIntervals[chrom], motifStartEnd);
}
cout << "Finished reading expansions.\n";
return;
}
bool compareMotifs(const std::vector<float> & expansionBpFreqs, const std::vector<float> & motifBpFreqs)
{
unsigned nMotifs = expansionBpFreqs.size() / 4;
for (unsigned i = 0; i < nMotifs; i++)
{
if (std::equal(expansionBpFreqs.cbegin()+(i*4), expansionBpFreqs.cbegin()+(i*4)+4, motifBpFreqs.cbegin()))
return true;
if (std::equal(expansionBpFreqs.cbegin()+(i*4), expansionBpFreqs.cbegin()+(i*4)+4, motifBpFreqs.crbegin()))
return true;
}
return false;
}
bool chromIsReal(CharString chrom)
{
string * p = std::find (chroms, chroms+22, toCString(chrom));
if (p != chroms+22)
return true;
else
return false;
}
/*unsigned storeReadsAtExpansions(CharString & bamPath, const char* reference, map<string, String<Triple<string,unsigned,unsigned> > > & chromToMotifAndIntervals, map <CharString, Triple<BamAlignmentRecord, string, unsigned> > & readNameToExpansion)
{
HtsFile hts_file(toCString(bamPath), "r", reference);
if (!loadIndex(hts_file))
{
std::cerr << "ERROR: Could not read index file for " << bamPath << "\n";
return 1;
}
for (auto chrom: chromToMotifAndIntervals)
{
for (auto interval: chrom.second)
{
Triple<string, unsigned, unsigned> key = Triple<string, unsigned, unsigned>(chrom.first, interval.i2, interval.i3);
string motif = interval.i1;
CharString chromosome = chrom.first;
cout << "Checking possibly expanded reads at " << chromosome << ":" << interval.i2 << "-" << interval.i3 << endl;
if (!setRegion(hts_file, toCString(chromosome), (int) interval.i2, (int) interval.i3))
{
std::cerr << "ERROR: Could not jump to " << chromosome << ":" << interval.i2 << "\n";
return 1;
}
BamAlignmentRecord record;
while (readRegion(record, hts_file))
{
if (hasFlagQCNoPass(record) || hasFlagDuplicate(record) || hasFlagNextUnmapped(record) || hasFlagUnmapped(record) || chromIsReal(hts_file.hdr->target_name[record.rNextId]))
continue;
if (record.rID != record.rNextId || abs(record.tLen) > 100000)
{