Repository navigation
Expand file tree
/
Copy pathmappingInference.cpp
More file actions
6992 lines (6189 loc) · 314 KB
/
Copy pathmappingInference.cpp
File metadata and controls
6992 lines (6189 loc) · 314 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) 2015-2016 Deniz Yorukoglu. All rights reserved.*/
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<assert.h>
#include<stdlib.h>
#include<time.h>
#include<sys/time.h>
#include<cmath>
#include<stdio.h>
#include<string.h>
#include<tr1/unordered_map>
#include<algorithm>
#include<vector>
#include<limits.h>
using namespace std;
//limits
#ifdef ED_THREE
#define MAX_EDITS 3
#define MAX_DOUBLE_EDITS 6
#define MAX_NUM_HOM_EDITS 3
#elif ED_FOUR
#define MAX_EDITS 4
#define MAX_DOUBLE_EDITS 8
#define MAX_NUM_HOM_EDITS 4
#elif ED_FIVE
#define MAX_EDITS 5
#define MAX_DOUBLE_EDITS 10
#define MAX_NUM_HOM_EDITS 5
#elif ED_SIX
#define MAX_EDITS 6
#define MAX_DOUBLE_EDITS 12
#define MAX_NUM_HOM_EDITS 6
#else
#define MAX_EDITS 2
#define MAX_DOUBLE_EDITS 4
#define MAX_NUM_HOM_EDITS 2
#endif
#ifdef CHR_SHORT
#define MAX_NUM_CHRS 65530
#else
#define MAX_NUM_CHRS 250
#endif
#define MAX_LINE_LEN 200
#define MAX_CHR_NAME_LEN 50
#define MAX_READ_LEN 250
#define MAX_RETURNED_LINKSLIST 5000
#define NUM_MAX_SAMPLES 50000
#define COLLAPSED 123
#define UNCOLLAPSED 124
#define MAX_ID_DIGIT_LEN 10
#define MAX_READ_FILE_NAME_LEN 250
#define MAX_READ_NAME_LENGTH 50
#define MAX_READ_GROUP_ID_LENGTH 250
//alphabet properties for read name econding
#define IDENTITY_ALPHABET_START 33
#define IDENTITY_ALPHABET_END 126
#define IDENTITY_ALPHABET_SIZE 94
//flag values (arbitrary)
#define MISSING_SPLIT_OFFSET 32 //indicates that the first split is missing (value is high so that 2*DOUBLE_ERROR cannot exceed the value)
#define DOUBLE_MISSING_SPLIT_OFFSET 64 //indicates that the second split is missing
#define FASTA 5
#define SAM 6
#define PAIRED_MODE 22
#define SINGLE_MODE 11
#define NO_SPLIT 66
#define HALF_SPLIT 77
#define THREEWAY_SPLIT 88
//Mapping Modes
#define ALL_MAPPING_MODE 101
// In the case of best mapping without indels BEST is same as BEST_SENSITIVE
#define BEST_MAPPING_MODE 102
#define BEST_FAST_MAPPING_MODE 106
#define BEST_SENSITIVE_MAPPING_MODE 103
#define UNIQUE_MAPPING_MODE 104
#define STRATUM_MAPPING_MODE 105
// Distance metric encoding
#define HAMMING 444
#define LEVENSHTEIN 555
int distanceMetric = HAMMING;
int mappingMode;
int mappingQualityPrintFlag;
int printReadGroupsFlag;
char RevCompChar[256];
void SetupRevCompChar()
{
RevCompChar['A'] = 'T';
RevCompChar['T'] = 'A';
RevCompChar['C'] = 'G';
RevCompChar['G'] = 'C';
RevCompChar['N'] = 'N';
//for insertions
RevCompChar['a'] = 't';
RevCompChar['t'] = 'a';
RevCompChar['c'] = 'g';
RevCompChar['g'] = 'c';
RevCompChar['n'] = 'n';
//for deletion
RevCompChar['D'] = 'D';
}
#define INVALID_REF_CHAR 'X'
bool ValidChar[256];
void SetupValidChar()
{
//Any character other than the ones below will be turned into undefined character 'X' similar to 'N'
ValidChar['A'] = 1;
ValidChar['C'] = 1;
ValidChar['G'] = 1;
ValidChar['T'] = 1;
ValidChar['a'] = 1;
ValidChar['c'] = 1;
ValidChar['g'] = 1;
ValidChar['t'] = 1;
}
string ReverseComplementString(string str) //This is a debug function -- no need to optimize
{
string retStr = str;
for(int i=0; i<(int)str.length(); i++)
{
retStr[i] = RevCompChar[(unsigned char) str[str.length() - i -1]];
}
return retStr;
}
int DebugCountStringDiff(const string& str1, const string& str2)
{
assert(str1.length() == str2.length());
int diffCount = 0;
for(int i = 0; i<(int)str1.length(); i++)
{
if(str1[i] != str2[i])
{
diffCount++;
}
}
return diffCount;
}
int numMismatchesPerReadMer; //The actual value of the mismatch per readMer during the run (as opposed to the maximum possible value defined above)
int doubleNumMismatchesPerReadMer;
int tripleNumMismatchesPerReadMer;
int numHomTableMismatches; //The number of mismatches used to generate the homology table (as opposed to the maximum vlaue defined above)
int globalMapCountLimit = 0; //If not zero, then all mappings will only report this many mappings
unsigned int minFragmentSize, maxFragmentSize; //size interval for the fragments
double getTime()
{
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec+t.tv_usec/1000000.0;
}
//MD is the edit script printed in SAM format
char singleMDstr[50];
char leftMDstr[50];
char rightMDstr[50];
//fast output writing to a buffer with delimiter
inline void writeStr(char*& str, char arr[], char del)
{
int pos = 0;
while(arr[pos] != '\0')
{
str[pos] = arr[pos];
pos++;
}
str[pos] = del;
str += pos + 1;
}
//fast output writing to a buffer
inline void writeStr(char*& str, char arr[])
{
int pos = 0;
while(arr[pos] != '\0')
{
str[pos] = arr[pos];
pos++;
}
str += pos;
}
//Assumes value is between 0 and 1000 exclusive
inline void writeIntToStr(char*& str, int val, char del)
{
//assert(val > 0);
if(val < 10)
{
str[0] = val + '0';
str[1] = del;
str += 2;
}
else if(val < 100)
{
str[0] = val / 10 + '0';
str[1] = val % 10 + '0';
str[2] = del;
str += 3;
}
else if(val < 1000)
{
str[0] = (val/100) + '0';
str[1] = (val%100)/10 + '0';
str[2] = val % 10 + '0';
str[3] = del;
str += 4;
}
else
{
cout << "ERROR: SAM flags for read length should be within (0,1000)" << endl;
exit(96);
}
}
short itoa10(int value, char* result)
{
short len = 0;
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do
{
tmp_value = value;
value /= 10;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * 10)];
len++;
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr)
{
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return len;
}
#define LTOA_BUFSIZE (sizeof(long) * 8 + 1)
//Modified from Robert B. Stout's ltoa function implementation
char *ltoa10(long N, char* str)
{
register int i = 2;
long uarg;
char *tail, *head = str, buf[LTOA_BUFSIZE];
tail = &buf[LTOA_BUFSIZE - 1]; /* last character position */
*tail-- = '\0';
if (N < 0L)
{
*head++ = '-';
uarg = -N;
}
else uarg = N;
if (uarg)
{
for (i = 1; uarg; ++i)
{
register ldiv_t r;
r = ldiv(uarg, 10);
*tail-- = (char)(r.rem + ((9L < r.rem) ?
('A' - 10L) : '0'));
uarg = r.quot;
}
}
else *tail-- = '0';
memcpy(head, ++tail, i);
return str;
}
unsigned char inputMode; //paired or single end
unsigned char splitMode; //full read-mer or half-split
//Data variables for reference
char* fullRef[MAX_NUM_CHRS+2];
unsigned int chrLens[MAX_NUM_CHRS+2];
char chrNames[MAX_NUM_CHRS+2][MAX_CHR_NAME_LEN+2];
int numChrs;
int readLen; //readMer len (k-mer len)
int finalReadLen; //The effective full read length to be used apart from printing (twice readmer length if half-split is applied, etc.) -- Can differ from input readLen
int inputReadLen; //The actual read length from input
unsigned char idDigitLen; //length of the encoded read name (per read)
#define VALSTR_LIMIT 512
char valStr[VALSTR_LIMIT+2][5]; //Valstr is used for temporary char space for integers when printing them to buffer
void SetUpValStr()
{
for(int i=0; i<=VALSTR_LIMIT; i++)
{
itoa10(i, valStr[i]);
}
}
//=================================
struct medit //multi-edit: stores a list of substitions with their offsets
{
unsigned char edits[MAX_EDITS];
unsigned char pos[MAX_EDITS];
unsigned char numEdits;
//Edits:
// A C G T -> mismatches
// D -> deletions in the read (gap in the reference in alignment)
// a c g t -> insertions in the read (gap in the read in alignment)
};
struct doubleMedit
{
doubleMedit(){};
doubleMedit(struct medit& myMedit)
{
numEdits = myMedit.numEdits;
for(int i=0; i<MAX_EDITS; i++)
{
edits[i] = myMedit.edits[i];
pos[i] = myMedit.pos[i];
}
}
unsigned char edits[MAX_DOUBLE_EDITS];
unsigned char pos[MAX_DOUBLE_EDITS];
unsigned char numEdits;
//Edits:
// A C G T -> mismatches
// D -> deletions in the read (gap in the reference in alignment)
// a c g t -> insertions in the read (gap in the read in alignment)
};
int GetIndelLengthModifier(const medit& med) //returns #deletions - #insertions in medit, this determines whether the alignment region of the readmer in the reference will get longer or shorter
{
int offset = 0;
for(int i=0; i<med.numEdits; i++)
{
if(med.edits[i] >= 'a')
{
offset--;
}
else if(med.edits[i] == 'D')
{
offset++;
}
}
return offset;
}
//Checks whether two medits are equal
bool equals(const medit& m1, const medit& m2)
{
if(m1.numEdits == m2.numEdits)
{
for(unsigned char i=0; i<m1.numEdits; i++)
{
if(m1.edits[i] != m2.edits[i] || m1.pos[i] != m2.pos[i])
{
return 0;
}
}
}
else
{
return 0;
}
return 1;
}
unsigned char meditEditCountLimit; //Different from EDIT_MAX_LENGTH that shows capacity, this represents a variable limit on the size of current medits (which might differ based on splits and length, but mostly will stay static)
medit dummyMedit;
//=====================================
//Data types for storing read links (in the future handle these gracefully by not loading all)
struct link //A link contains the position in the reference it points to with the direction of homology as well as the edits (medit format)
{
link(){};
#ifdef CHR_SHORT
link(unsigned int y, medit z, unsigned short x, bool t): chrPos(y), edit(z), chrCode(x), dir(t) {}
#else
link(unsigned int y, medit z, unsigned char x, bool t): chrPos(y), edit(z), chrCode(x), dir(t) {}
#endif
unsigned int chrPos;
medit edit;
#ifdef CHR_SHORT
unsigned short chrCode;
#else
unsigned char chrCode;
#endif
char dir;
bool operator() (const link& a, const link& b) //For sorting
{
return ( (unsigned long long) a.chrCode * UINT_MAX + a.chrPos < (unsigned long long) b.chrCode * UINT_MAX + b.chrPos);
}
} linkObject;
link* links; //each read / mate or split gets one index, directionality doesn't get a new index, but are encoded in bool
unsigned int linksSize; //total number of links currently stored in memory
link dummyLink;
struct mergedLink //A link contains the position in the reference it points to with the direction of homology as well as the edits (medit format)
{
mergedLink(){};
mergedLink(struct link& myLink)
{
chrPos = myLink.chrPos; chrCode = myLink.chrCode; dir = myLink.dir; edit = doubleMedit(myLink.edit);
}
#ifdef CHR_SHORT
mergedLink(unsigned int y, medit z, unsigned short x, bool t)
#else
mergedLink(unsigned int y, medit z, unsigned char x, bool t)
#endif
{
chrPos = y; chrCode = x; dir = t; edit = doubleMedit(z);
}
#ifdef CHR_SHORT
mergedLink(unsigned int y, doubleMedit z, unsigned short x, bool t): chrPos(y), edit(z), chrCode(x), dir(t) {}
#else
mergedLink(unsigned int y, doubleMedit z, unsigned char x, bool t): chrPos(y), edit(z), chrCode(x), dir(t) {}
#endif
unsigned int chrPos;
doubleMedit edit;
#ifdef CHR_SHORT
unsigned short chrCode;
#else
unsigned char chrCode;
#endif
char dir;
bool operator() (const mergedLink& a, const mergedLink& b) //For sorting
{
return ( (unsigned long long) a.chrCode * UINT_MAX + a.chrPos < (unsigned long long) b.chrCode * UINT_MAX + b.chrPos);
}
} mergedLinkObject;
bool sortByErrors(const mergedLink &lhs, const mergedLink &rhs)
{
return lhs.edit.numEdits < rhs.edit.numEdits;
}
////////////////////////////////////
//Data types for storing inexact homology information [extended to multi edit homologies on 11/7/2013]
//Atomic unit of Inexact Homology Table -- format similar to links, but here homologies also have blockLength and edits are not explicitly specified since they are already in fullRef
struct emHomItem //multipleError homologies
{
unsigned int chrPos; //pos in chr for the target
unsigned char offsetList[MAX_NUM_HOM_EDITS]; //list of offset positions that represent the substitutions in homology -- offsets are always in the forward direction of the source position
unsigned int blockLen : 7; //How long the homology is continued as a block: e.g if blockLen is 3, then A ~ B, A+1 ~ B+1, A+2 ~ B+2 for forward homologies, A~B, A+1 ~ B-1, A+2 ~ B-2 for reverseComplement homologies
unsigned int dir : 1; //direction of homology
#ifdef CHR_SHORT
unsigned short chrCode;
#else
unsigned char chrCode; //chromosome of the target
#endif
};
struct emHomClassNode //for each equiv class representative (described below), this stores the list of inexact homology links it has
{
emHomItem* list; //list of inexact homologies for this position
unsigned int chrPos; //pos in chr of source
unsigned int listSize; //number of homologies for this pos
#ifdef CHR_SHORT
unsigned short chrCode;
#else
unsigned char chrCode; //chr of source
#endif
unsigned char maxRevLookup; //max number indices to go back to find all emHoms relevant to this pos (this is required since, due to blockLengths > 1, previous positions might contain homologies relevant to this guy)
};
emHomClassNode* emHomClassList; //1-based list of all equivalence class representatives with their inexact homology info
unsigned int emHomClassListSize; //total number of these
///////////////////////////////////////
//Data types for storing equivalence classes (perfect homology)
//Atomic unit of exact homology table
struct eqItem
{
unsigned int chrPos; //position of the target
char dir; //direction of homology
#ifdef CHR_SHORT
unsigned short chrCode;
#else
unsigned char chrCode; //chromosome of the target
#endif
};
//Equivalence class representative that contains exact homology links to the other members of the class
struct equivClassNode
{
eqItem* list; //list of links other members of the class
unsigned int blockLen; //length of block for the entire class (unlike inexact homologies for which the block length is per link), each region in the class has perfect homologie for the entire blockLength
unsigned int chrPos; //position of class rep
unsigned int listSize; //total number of non-rep members of the class
#ifdef CHR_SHORT
unsigned short chrCode;
#else
unsigned char chrCode; //chromosome of the class rep
#endif
};
equivClassNode* equivClassList; //1-based list of all equivalence class representatives with their exact homologies
unsigned int equivClassListSize; //total number of these (this can be different than emHomClassListSize, since for inexact any position in an equivalence class of itself if it has at least one inexact homology, but those are not reprented in this list since they are unnecessary for euqivalence purposes)
/////////////////////////////
std::tr1::unordered_map<unsigned int, unsigned int> equivHub[MAX_NUM_CHRS+2];
std::tr1::unordered_map<unsigned int, unsigned int> homHub[MAX_NUM_CHRS+2];
////////////////////////////
int GetChrCode(const string& chrStr)
{
for(int i=1; i<=numChrs; i++)
{
if(chrStr == chrNames[i])
{
return i;
}
}
assert(0);
}
//Updated to extend homologies to multiEdit homologies on 11/7/2013
void LoadInexactHomologies(char* inexactTableFileName, int readLen, int numHomTableMismatches)
{
cout << "Loading inexact homology maps.." << endl;
//open itemCounts file that contains the length of the files.
ifstream finItemCounts((string(inexactTableFileName) + ".itemCount").c_str());
if(!finItemCounts.is_open())
{
cout << "Could not find inexact homology table item counts file: " << string(inexactTableFileName) + ".itemCount" << endl;
exit(89);
}
finItemCounts >> emHomClassListSize;
emHomClassList = (emHomClassNode *) calloc ((emHomClassListSize+2), sizeof(emHomClassNode)); //Format is a list of main inexact homology blocks pointing to a list of inexact homology links from that position
int bufferListCap = 10000;
int bufferListSize = 0;
emHomItem* bufferList = (emHomItem *) malloc ((bufferListCap+2) * sizeof(emHomItem));
FILE* finBin = fopen(inexactTableFileName, "rb");
if(!finBin)
{
cout << "Could not find inexact homology table: " << inexactTableFileName << endl;
exit(90);
}
for(unsigned int i=1; i<=emHomClassListSize; i++)
{
size_t tempSize = fread(&(emHomClassList[i].chrCode), sizeof(emHomClassNode::chrCode), 1, finBin);
tempSize &= fread(&(emHomClassList[i].chrPos), sizeof(emHomClassNode::chrPos), 1, finBin);
bufferListSize = 0;
char curDir; //The type of these parameters are important since they are the types in the homology table
short curBlockLen; //In order to change them, the homology table data types shoudl also be upgraded
while(true)
{
tempSize &= fread(&(curDir), sizeof(unsigned char), 1, finBin);
if(curDir == -1)
{
//End of list -- copy buffer to emHomClassList and quit
emHomClassList[i].list = (emHomItem *) malloc ((bufferListSize) * sizeof(emHomItem));
for(int k=0; k<bufferListSize; k++)
{
emHomClassList[i].list[k] = bufferList[k];
}
emHomClassList[i].listSize = bufferListSize;
bufferListSize = 0;
break;
}
bufferList[bufferListSize].dir = curDir;
tempSize &= fread(&(bufferList[bufferListSize].chrCode), sizeof(emHomItem::chrCode), 1, finBin);
tempSize &= fread(&(bufferList[bufferListSize].chrPos), sizeof(emHomItem::chrPos), 1, finBin);
for(unsigned char k=0; k<numHomTableMismatches; k++)
{
tempSize &= fread(&(bufferList[bufferListSize].offsetList[k]), sizeof(unsigned char), 1, finBin);
}
tempSize &= fread(&curBlockLen, sizeof(short), 1, finBin);
bufferList[bufferListSize].blockLen = curBlockLen;
bufferListSize++;
if(bufferListSize > bufferListCap) //resize bufferList
{
emHomItem* oldBufferList = bufferList;
bufferListCap *= 2;
bufferList = (emHomItem *) malloc ((bufferListCap+2)*sizeof(emHomItem));
for(int k=0; k<bufferListSize; k++)
{
bufferList[k] = oldBufferList[k];
}
free(oldBufferList);
}
}
}
free(bufferList);
//Assigning reverse lookups
//TODO(denizy) Move these look up values to pre-processing
unsigned int lookInd = 2;
for(unsigned int i=1; i <= emHomClassListSize && lookInd <= emHomClassListSize; i++)
{
unsigned int curChrCode = emHomClassList[i].chrCode;
unsigned int curChrPos = emHomClassList[i].chrPos;
unsigned int lookChrPosLimit = curChrPos + emHomClassList[i].list[0].blockLen - 1; //first item in the list always the longest
while(emHomClassList[lookInd].chrCode == curChrCode && emHomClassList[lookInd].chrPos <= lookChrPosLimit)
{
emHomClassList[lookInd].maxRevLookup = lookInd - i;
lookInd++;
}
}
}
//Load the compact exact homology table to memory (format is a list of equivalence class representative linked to other items in the class
void LoadEquivClasses(char* perfTableFileName)
{
//open itemCounts file that contains the length of the files.
ifstream finItemCounts((string(perfTableFileName) + ".itemCount").c_str());
if(!finItemCounts.is_open())
{
cout << "Homology Table item count file doesn't exist: " << string(perfTableFileName) + ".itemCount" << endl;
exit(87);
}
finItemCounts >> equivClassListSize;
equivClassList = (equivClassNode *) malloc ((equivClassListSize+2)*sizeof(equivClassNode));
int bufferListCap = 10000;
int bufferListSize = 0;
eqItem* bufferList = (eqItem *) malloc ((bufferListCap+2)*sizeof(eqItem));
FILE* finBin = fopen(perfTableFileName, "rb");
if(!finBin)
{
cout << "Homology Table file doesn't exist: " << perfTableFileName << endl;
exit(88);
}
for(unsigned int i=1; i<=equivClassListSize; i++)
{
size_t tempSize = fread(&(equivClassList[i].chrCode), sizeof(equivClassNode::chrCode), 1, finBin);
tempSize &= fread(&(equivClassList[i].chrPos), sizeof(equivClassNode::chrPos), 1, finBin);
bufferListSize = 0;
while(true)
{
tempSize &= fread(&(bufferList[bufferListSize].dir), sizeof(unsigned char), 1, finBin);
if(bufferList[bufferListSize].dir == -1)
{
//End of list -- read the block length, copy buffer to equivClassList and quit
tempSize &= fread(&(equivClassList[i].blockLen), sizeof(unsigned int), 1, finBin);
equivClassList[i].list = (eqItem *) malloc ((bufferListSize) * sizeof(eqItem));
for(int k=0; k<bufferListSize; k++)
{
equivClassList[i].list[k] = bufferList[k];
}
equivClassList[i].listSize = bufferListSize;
bufferListSize = 0;
break;
}
tempSize &= fread(&(bufferList[bufferListSize].chrCode), sizeof(eqItem::chrCode), 1, finBin);
tempSize &= fread(&(bufferList[bufferListSize].chrPos), sizeof(eqItem::chrPos), 1, finBin);
bufferListSize++;
if(bufferListSize > bufferListCap) //resize bufferList
{
eqItem* oldBufferList = bufferList;
bufferListCap *= 2;
bufferList = (eqItem *) malloc ((bufferListCap+2)*sizeof(eqItem));
for(int k=0; k<bufferListSize; k++)
{
bufferList[k] = oldBufferList[k];
}
free(oldBufferList);
}
}
}
free(bufferList);
}
//Convert edit offsets and characters to their reverse complements
void ConvertToRevCompMedit(medit& curMedit, int readLen)
{
unsigned char midPoint = (curMedit.numEdits + 1) / 2; //+1 since we want mid item to be reverse complemented too
for(unsigned char k=0; k<midPoint; k++)
{
unsigned char secondPos = curMedit.numEdits-k-1;
unsigned char temppos1 = readLen - curMedit.pos[secondPos] + 1;
unsigned char tempch1 = RevCompChar[curMedit.edits[secondPos]];
if(tempch1 >= 'a' && tempch1 <= 't') //Indels should be incremented extra
temppos1++;
curMedit.edits[secondPos] = RevCompChar[curMedit.edits[k]];
curMedit.pos[secondPos] = readLen - curMedit.pos[k] + 1;
if(curMedit.edits[k] >= 'a' && curMedit.edits[k] <= 't')
{
curMedit.pos[secondPos]++;
}
curMedit.pos[k] = temppos1;
curMedit.edits[k] = tempch1;
}
}
void ConvertToRevCompMedit(doubleMedit& curMedit, int readLen)
{
unsigned char midPoint = (curMedit.numEdits + 1) / 2; //+1 since we want mid item to be reverse complemented too
for(unsigned char k=0; k<midPoint; k++)
{
unsigned char secondPos = curMedit.numEdits-k-1;
unsigned char temppos1 = readLen - curMedit.pos[secondPos] + 1;
unsigned char tempch1 = RevCompChar[curMedit.edits[secondPos]];
if(tempch1 >= 'a' && tempch1 <= 't') //Indels should be incremented extra
temppos1++;
curMedit.edits[secondPos] = RevCompChar[curMedit.edits[k]];
curMedit.pos[secondPos] = readLen - curMedit.pos[k] + 1;
if(curMedit.edits[k] >= 'a' && curMedit.edits[k] <= 't')
{
curMedit.pos[secondPos]++;
}
curMedit.pos[k] = temppos1;
curMedit.edits[k] = tempch1;
}
}
string DebugPrintMedit(const medit& d, double Code)
{
bool problemMeditFLAG = 0;
stringstream sout;
unsigned char numEdits = d.numEdits % MISSING_SPLIT_OFFSET;
sout << "numEdits: " << (int) d.numEdits << " : ";
if(numEdits > MAX_EDITS)
{
cout << "!!!WARNING: NumEdits higher than allowed" << endl;
cout << "original num edits: " << (int) d.numEdits << endl;
cout << "mod num Edits: " << (int) numEdits << endl;
}
for(int i=0; i<numEdits; i++)
{
if((int) d.pos[i] == 0)
{
cout << "!!!!PROBLEM medit!!!!!" << endl;
problemMeditFLAG = 1;
}
sout << "(" << (int) d.pos[i] << "," << d.edits[i] << ") ";
}
sout << " Key: " << Code;
if(problemMeditFLAG == 1)
{
cout << "here is problem medit: '" << sout.str() << "'" << endl;
for(int i=0; i<numEdits; i++)
{
cout << "Edit " << i << ": " << (int) d.pos[i] << "\t'" << d.edits[i] << "' int: " << (int) d.edits[i] << endl;
}
problemMeditFLAG = 0;
assert(0);
}
for(int i=1; i<numEdits; i++)
{
if(d.pos[i] < d.pos[i-1])
{
cout << "CORRUPT_ORDER: Here is corrupted medit for position order: '" << sout.str() << "'" << endl;
assert(0);
}
if(d.pos[i] == d.pos[i-1] && d.edits[i-1] < 91)
{
cout << "CORRUPT_EQUALITY: Here is the corrupted medit: '" << sout.str() << "'" << endl;
assert(0);
}
}
return sout.str();
}
string DebugPrintMedit(const doubleMedit& d, double Code)
{
bool problemMeditFLAG = 0;
stringstream sout;
unsigned char numEdits = d.numEdits % MISSING_SPLIT_OFFSET;
sout << "numEdits: " << (int) d.numEdits << " : ";
if(numEdits > MAX_DOUBLE_EDITS)
{
cout << "!!!WARNING: NumEdits higher than allowed" << endl;
cout << "original num edits: " << (int) d.numEdits << endl;
cout << "mod num Edits: " << (int) numEdits << endl;
}
for(int i=0; i<numEdits; i++)
{
if((int) d.pos[i] == 0)
{
cout << "!!!!PROBLEM medit!!!!!" << endl;
problemMeditFLAG = 1;
}
sout << "(" << (int) d.pos[i] << "," << d.edits[i] << ") ";
}
sout << " Key: " << Code;
if(problemMeditFLAG == 1)
{
cout << "here is problem medit: '" << sout.str() << "'" << endl;
for(int i=0; i<numEdits; i++)
{
cout << "Edit " << i << ": " << (int) d.pos[i] << "\t'" << d.edits[i] << "' int: " << (int) d.edits[i] << endl;
}
problemMeditFLAG = 0;
assert(0);
}
for(int i=1; i<numEdits; i++)
{
if(d.pos[i] < d.pos[i-1])
{
cout << "CORRUPT_ORDER: Here is corrupted medit for position order: '" << sout.str() << "'" << endl;
assert(0);
}
if(d.pos[i] == d.pos[i-1] && d.edits[i-1] < 91)
{
cout << "CORRUPT_EQUALITY: Here is the corrupted medit: '" << sout.str() << "'" << endl;
assert(0);
}
}
return sout.str();
}
//Create MD edit script from medit while replacing the character for the reference (since medit is the edits in the read and the MD string is the edits in the reference)
void GetMDStrFromMeditWithCharReplacement(const doubleMedit& curMedit, char replacedChars[], int finalReadLen, char outarr[])
{
//Alignment dir is assumed to be forward
char* md = outarr;
unsigned char numEdits = curMedit.numEdits;
if(numEdits==0)
{
writeStr(md, valStr[finalReadLen], '\0');
}
else
{
int numInsertionsWithinBlock = 0; //This resets whenever a non-insertion variation is seen
int distanceFromVal = 1;
for(int k=0; k<=numEdits; k++)
{
unsigned char curPosVal = finalReadLen + 1;
if(k < numEdits)
{
if(curMedit.edits[k] >= 'a' && curMedit.edits[k] <= 't') //insertions are not reported in MD str
{
numInsertionsWithinBlock++;
continue;
}
curPosVal = curMedit.pos[k];
}
unsigned char diffMD = curPosVal - distanceFromVal;// + numDeletionsWithinBlock;
if(k == numEdits)
{
diffMD -= numInsertionsWithinBlock;
}
distanceFromVal += diffMD + 1; //this will be the position that we start for the next character
if(diffMD > 0)
{
if((md-1)[0] == '0')
{
md--;
}
writeStr(md, valStr[diffMD]);
}
if(k < numEdits)
{
if(curMedit.edits[k] == 'D')
{
md[0] = '^'; md++;
md[0] = replacedChars[k]; md++;
md[0] = '0'; md++; //to make sure that the next character will not be confused with a mismatch
numInsertionsWithinBlock--;
}
else
{
md[0] = replacedChars[k];
if(md[0] == 'X') //X is to make sure to penalize N-N alignments, but the final MD string should be N
{
md[0] = 'N';
}
md++;
}
}
}
}
md[0] = '\0';
}
//Construct medit from a given editstring (the way it's represented in the links)
medit GetMedit(const string& editStr, bool& successful)
{
medit curMedit = dummyMedit;
int fullOffset = 0;
int editLen = editStr.length();
for(int i=0; i<editLen; i++)
{
int curOffset = 0;
while(i<editLen && editStr[i]<= '9')
{
curOffset *= 10;
curOffset += editStr[i] - '0';
i++;
}
if(i>=editLen)
{
break;
}
fullOffset += curOffset;
if(curMedit.numEdits >= MAX_EDITS)
{
successful = 0;
break;
}
curMedit.pos[curMedit.numEdits] = fullOffset + 1;
curMedit.edits[curMedit.numEdits] = editStr[i];
curMedit.numEdits++;
if(editStr[i] >= 'A' && editStr[i] <= 'T') //Includes Deletions 'D' and all mismatches 'ACGTN'
fullOffset++;
}
return curMedit;
}
//Go through fai file and load all chromosomes to memory (1 char per nucleotide) - 1 based chromosome ids, 1 based position indices
void LoadMultiChrReference(char* refFile, int refLineLen)
{
string refFileName = refFile;