-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMocoLoco.cpp
More file actions
1799 lines (1580 loc) · 58.3 KB
/
MocoLoco.cpp
File metadata and controls
1799 lines (1580 loc) · 58.3 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
#include "MocoLoco.h"
#include "Profiling.h"
#include <sys/resource.h>
int main(int argc, char *argv[]) {
Timer timer;
//This refers to profiling function
// Instrumentor::Get().BeginSession("MocoLoco");
// {
// If arguments number is 1 means that no input file has been inserted -
// display help
if (argc == 1) {
display_help();
}
// Collect all the parameters given as input
command_line_parser(argc, argv);
//If multifasta is not provided the input file is BED file and twobit file
//is opened, otherwise if the input is multifasta the tb variable has value 0
(MFASTA_FILE.empty()) ? tb = twobit_open(TWOBIT_FILE.c_str()) : tb = 0;
//In BedClass is created a vector of structures with sequence and coordinates
BedClass B(BED_FILE, MFASTA_FILE, tb);
//If the input file is a BED file the tool check in which position there is
//the best score of similarity with the matrix of primary motif
if(MFASTA_FILE.empty()){
//The JasparClass read the Jaspar file in input
JasparClass J(JASPAR_FILE);
//The MatrixClass return a matrix from the Jaspar file
MatrixClass mat(J.ReturnJaspar());
//For each sequence
for (unsigned int i = 0; i < B.bed_v.size(); i++) {
//Initially the ScoreClass is performed only in the forward strand
//and it returns a vector with all the scores for each position
ScoreClass score(mat.ReturnMatrix(), B.bed_v[i].Sequence,
B.bed_v[i].Start);
//If the analysis is performed only in single strand only the
//max score is stored in a new vector and then the sequence
//is centered to the position with max score
if(DS == false){
Best_vector.emplace_back(score.MaxScore);
Centering(B.bed_v[i], score.CenteredStart,
mat.ReturnMatrix()[0].size());
}
//If the anlysis is performed in double strand also the reverse
//strand is analysed
else{
ScoreClass score_rev(mat.ReturnInverseMatrix(), B.bed_v[i].Sequence,
B.bed_v[i].Start);
if(score_rev.MaxScore > score.MaxScore){
Best_vector.emplace_back(score_rev.MaxScore);
Centering(B.bed_v[i], score_rev.CenteredStart,
mat.ReturnInverseMatrix()[0].size());
//When the unidirection option is present the reverse strand must
//be transformed into forward strand and it is recentered
if(direction){
ReCentering(score_rev.CenteredStart, B.bed_v[i],
mat.ReturnInverseMatrix()[0].size());
}
}
else{
Best_vector.emplace_back(score.MaxScore);
Centering(B.bed_v[i], score.CenteredStart,
mat.ReturnMatrix()[0].size());
}
}
}
if(cleaning){
//Function to delete sequences with low primary motif scores
ClearingGEP(B.bed_v, Best_vector);
}
twobit_close(tb);
print_GEP(B.bed_v);
}
// Vector len contains all the lengths of sequences for each kmer
for(unsigned int i = 0; i < kmers_vector.size(); i++){
len.emplace_back(B.bed_v[0].Sequence.size() - kmers_vector[i] + 1);
}
//In MapClass all the maps used for the tool are created, we have horizontal and vertical maps
MapClass M(B.bed_v);
//For each kmer
for (unsigned int i = 0; i < kmers_vector.size(); i++) {
vector<PvalueClass> P_vector;
vector<string> seed_oligo;
//For each position in the sequence
for (unsigned int j = 0; j < len[i]; j++) {
double Pval = 0;
unsigned int counter = 0;
// Loop for eventually other matrixes that are hidden by the best motif
while(counter < max_matrix) {
cout << "Position: " << j << endl;
//For each oligo present in the vertical map
for (multimap<int, string>::iterator it =
M.vector_positions_occurrences[i][j].begin();
it != M.vector_positions_occurrences[i][j].end(); it++) {
//In the PvalueClass to each oligo is associated its pvalue
PvalueClass P(B.bed_v, it, M.vector_map_hor[i], i);
P_vector.push_back(P);
}
//The element in P_vector are ordered on the basis of pvalues
//otherwise the normal ordering (by occurrences in vertical map)
//is maintained
(ordering == "p") ? sort(begin(P_vector), end(P_vector), comp) :
sort(begin(P_vector), end(P_vector), comp_occ);
// Debug for PValueClass
// DVector(P_vector, j);
if(max_matrix > P_vector.size()){
max_matrix = P_vector.size();
}
//Creation of clusters of oligos at hamming distance
//and creation of PWM for each position
HammingClass H(P_vector[0].oligo,
M.vector_map_ver[i],
M.vector_positions_occurrences[i][j],
M.vector_map_hor[i], j, i);
// Perform the expectation maximization algorithm
// (https://en.wikipedia.org/wiki/Expectation–maximization_algorithm)
if (!exp_max.empty()){
EMClass E(H.cluster_map, H.PWM_hamming,
M.vector_map_hor[i]);
}
//If the frequence of seed oligo is higher than a threshold
//the z_score is calculated
if(H.freq1 >= freq_vector[i]){
z_test_class Z(H.PWM_hamming, B.bed_v,
j + 1, len[i]);
Pval = Z.Zpvalue_bonf;
//If it is the first cycle of while loop or if the pval is lower
//than a certain threshold the z_score and PWM are calculated
if(Pval <= (z_pval_threshold * len[i])){
seed_oligo.emplace_back(P_vector[0].oligo);
Z_TEST_VECTOR.emplace_back(Z);
H_HAMMING_VECTOR.emplace_back(H);
}
}
P_vector.clear();
counter++;
}
}
Z_TEST_MATRIX.emplace_back(Z_TEST_VECTOR);
H_HAMMING_MATRIX.emplace_back(H_HAMMING_VECTOR);
Z_TEST_VECTOR.clear();
H_HAMMING_VECTOR.clear();
//Outfile functions
Outfile_PWM_matrixes(i, seed_oligo);
Outfile_Z_score_values(i, seed_oligo);
seed_oligo.clear();
}
RAM_usage();
return 0;
// }
// Instrumentor::Get().EndSession();
}
//This function read Bed or Multifasta file in input and create the BedClass
void BedClass::ReadBed(string BED_FILE, string MFASTA_FILE, TwoBit *tb) {
// PROFILE_FUNCTION();
string line;
vector<string> sequences;
if(MFASTA_FILE.empty()){
ifstream in(BED_FILE);
//Ignore empty line or header
while (getline(in, line)) {
if (line.empty() || line[0] == '#') {
continue;
}
//istringstream is a string class object which is used to stream the string
//into different variables and similarly files can be stream into strings
istringstream mystream(line);
bed_s bed_in;
mystream >> bed_in.Chromosome >> bed_in.Start >> bed_in.End;
if (bed_in.Start > bed_in.End) {
cerr << "Error, start coordinate is higher than end coordinate\n\n";
}
else {
int center = (bed_in.Start + bed_in.End) / 2;
bed_in.Start = center - half_length;
bed_in.End = center + half_length + overhead;
bed_in.Sequence =
twobit_sequence(tb, bed_in.Chromosome.c_str(), bed_in.Start,
bed_in.End - 1);
bed_v.push_back(bed_in);
}
}
}
else{
string file_name = MFASTA_FILE;
alias_file =
alias_file + file_name.erase(0, file_name.find_last_of("_") + 1);
alias_file =
file_name.erase(file_name.find_last_of("."), file_name.size()) +
"_";
ifstream file(MFASTA_FILE);
string current_sequence;
bool first_line = true;
while (getline(file, line)) {
if (line[0] == '>' && !first_line) {
sequences.emplace_back(current_sequence);
current_sequence.clear();
}
else if (!first_line) {
if (line[0] != ' ' && line.size() != 0) {
// Before to save the sequence in current_sequence variable the FASTA
// characters are capitalized
transform(line.begin(), line.end(), line.begin(), ::toupper);
current_sequence = current_sequence + line;
}
}
// After the first cicle the first line flag is set to 0
first_line = false;
}
sequences.emplace_back(current_sequence);
}
for (unsigned int i = 0; i < sequences.size(); i ++){
if (sequences[0].size() != sequences[i].size()){
cerr << "ERROR! The length of fasta sequences isn't equal in all the file!\n\nCheck it out!\n\n";
}
bed_s bed_in;
bed_in.Chromosome = "MULTIFASTA";
bed_in.Start = 0;
bed_in.End = 0;
bed_in.Sequence = sequences[i];
bed_v.push_back(bed_in);
}
}
void JasparClass::ReadJaspar(string JASPAR_FILE) {
// PROFILE_FUNCTION();
ifstream file(JASPAR_FILE);
string line;
// For each line of the JASPAR file
while (getline(file, line)) {
// If the line Start with '>' character save the words into matrix_name
// string and into tf_name string
if (line[0] == '>') {
istringstream mystream(line);
// mystream >> matrix_name >> tf_name;
}
// If the line does not Start with '>' delete the '[',']' and 'A,T,C,G'
// characters, extract the scores and save them into a scores matrix
else {
// Deleting from line the first character (A,T,C,G), the '[' and the ']'
// characters
line.erase(0, line.find('[') + 1);
line.erase(line.find(']'));
vector<double> scores_line;
istringstream mystream(line);
// For each words (number) in line put the current number in num variables
for (double num; mystream >> num;) {
scores_line.emplace_back(num);
}
mJasparMatrix.emplace_back(scores_line);
}
}
file.close();
}
//These are functions that return variable because they are private in their classes
vector<vector<double>> JasparClass::ReturnJaspar() { return mJasparMatrix; }
vector<vector<double>>& MatrixClass::ReturnMatrix() { return mLogMatrix; }
vector<vector<double>>& MatrixClass::ReturnInverseMatrix() { return mInverseLogMatrix; }
void MatrixClass::MatrixNormalization(double psdcount, vector<double> col_sum,
vector<vector<double>> &mJasparMatrix) {
// PROFILE_FUNCTION();
for (unsigned int x = 0; x < mJasparMatrix.size(); x++) {
for (unsigned int i = 0; i < mJasparMatrix[x].size(); i++) {
double *ptr = &mJasparMatrix[x][i];
*ptr = (*ptr / col_sum[i] + psdcount);
}
}
}
vector<double> MatrixClass::ColSum(vector<vector<double>> &mJasparMatrix) {
// PROFILE_FUNCTION();
vector<double> col_sum;
for (unsigned int i = 0; i < mJasparMatrix[0].size(); i++) {
double sum = 0;
for (unsigned int j = 0; j < 4; j++) {
sum += mJasparMatrix[j][i];
}
col_sum.emplace_back(sum);
}
return col_sum;
}
void MatrixClass::MatrixLog(vector<vector<double>> &mJasparMatrix) {
// PROFILE_FUNCTION();
for (unsigned int x = 0; x < mJasparMatrix.size(); x++) {
for (unsigned int i = 0; i < mJasparMatrix[x].size(); i++) {
double *ptr = &mJasparMatrix[x][i];
*ptr = log(mJasparMatrix[x][i]);
}
}
mLogMatrix = mJasparMatrix;
}
//This function find the maximum and minimum value for each column of the matrix
void ScoreClass::FindMinMax(vector<vector<double>> &matrix) {
// PROFILE_FUNCTION();
vector<double> max_sum;
for (unsigned int i = 0; i < matrix[0].size(); i++) {
vector<double> column;
for (unsigned int j = 0; j < matrix.size(); j++) {
column.emplace_back(matrix[j][i]);
}
mMinColumnSum.emplace_back(*min_element(column.begin(), column.end()));
max_sum.emplace_back(*max_element(column.begin(), column.end()));
}
double min = accumulate(mMinColumnSum.begin(), mMinColumnSum.end(), 0.0);
double max = accumulate(max_sum.begin(), max_sum.end(), 0.0);
mVectorMinMax.emplace_back(min);
mVectorMinMax.emplace_back(max);
}
//Here the score for each kmer is calculated by using the normalized log matrix values
vector<double> ScoreClass::Shifting(vector<vector<double>> &matrix,
string &sequence) {
// PROFILE_FUNCTION();
int max = 0;
max = sequence.size() - matrix[0].size();
vector<double> seq_scores;
for (int s_iterator = 0; s_iterator <= max; s_iterator++) {
double sum_scores = 0;
// For each oligo in the current sequence a score is calculated
for (unsigned int i = 0; i < matrix[0].size(); i++) {
switch (sequence[i + s_iterator]) {
case 'A':
sum_scores += matrix[0][i];
break;
case 'C':
sum_scores += matrix[1][i];
break;
case 'G':
sum_scores += matrix[2][i];
break;
case 'T':
sum_scores += matrix[3][i];
break;
default: // Case if there is N
sum_scores += mMinColumnSum[i];
break;
}
}
// Best score normalization with normalization formula
sum_scores = 1 + (sum_scores - mVectorMinMax[1]) / (mVectorMinMax[1] - mVectorMinMax[0]);
seq_scores.emplace_back(sum_scores);
}
return seq_scores;
}
void MatrixClass::InversemLogMatrix() {
// PROFILE_FUNCTION();
mInverseLogMatrix = mLogMatrix;
reverse(mInverseLogMatrix.begin(), mInverseLogMatrix.end());
for (int i = 0; i < 4; i++) {
reverse(mInverseLogMatrix[i].begin(), mInverseLogMatrix[i].end());
}
}
unsigned int ScoreClass::BestScore(vector<double> &ScoreVector){
// PROFILE_FUNCTION();
//The MaxScore for the vector with all scores is stored
MaxScore = *max_element(ScoreVector.begin(), ScoreVector.end());
int match = -25;
for (int j = 0; j < ScoreVector.size(); j++) {
//If in the vector there is a value equal to MaxScore
if (ScoreVector[j] == MaxScore) {
/*We check if the distance of the position of max score from the center
is less than the previous value the new position is accepted as position
with max score*/
if (abs(j-half_length) < abs(match-half_length)){
match = j;
}
}
}
return match;
}
//This function refers to an option of MocoLoco where all the sequences are
//switched to the forward strand
void ReCentering(unsigned int center, BedClass::bed_s &GEP,
unsigned int matrix_size){
// PROFILE_FUNCTION();
ReverseString(GEP.Sequence, reverse_bases);
GEP.Sequence = reverse_bases;
//if the matrix is even the center is the same
//but if the matrix is odd and the sequence is switched we need to shift the center
if(matrix_size % 2 == 0){
unsigned int center_oligo =
(center + matrix_size / 2);
GEP.Start = center_oligo - half_length;
GEP.End = center_oligo + half_length;
}
else{
unsigned int center_oligo =
(center + matrix_size / 2) + 1;
GEP.Start = center_oligo - half_length;
GEP.End = center_oligo + half_length;
}
GEP.Sequence =
twobit_sequence(tb, GEP.Chromosome.c_str(), GEP.Start,
GEP.End - 1);
ReverseString(GEP.Sequence, reverse_bases);
GEP.Sequence = reverse_bases;
}
void Centering(BedClass::bed_s &GEP, unsigned int start_coord,
unsigned int matrix_size){
// PROFILE_FUNCTION();
unsigned int center_oligo =
start_coord + (matrix_size / 2);
GEP.Start = center_oligo - half_length;
GEP.End = center_oligo + half_length;
GEP.Sequence =
twobit_sequence(tb, GEP.Chromosome.c_str(), GEP.Start,
GEP.End - 1);
}
void ReverseString(string bases, string &reverse_bases) {
// PROFILE_FUNCTION();
reverse_bases.clear();
// For any character of the string insert into another string (called reverse
// bases) the complementary character
for (int i = bases.length() - 1; i >= 0; i--) {
char base;
base = bases[i];
switch (base) {
case 'A':
reverse_bases.append("T");
break;
case 'T':
reverse_bases.append("A");
break;
case 'G':
reverse_bases.append("C");
break;
case 'C':
reverse_bases.append("G");
break;
case 'N':
reverse_bases.append("N");
break;
}
}
}
void MapClass::MainMapVector(vector<BedClass::bed_s> &GEP) {
// PROFILE_FUNCTION();
for (unsigned int i = 0; i < kmers_vector.size(); i++) {
for (unsigned int j = 0; j < GEP.size(); j++) {
CountOccurrencesHor(GEP[j].Sequence, kmers_vector[i]);
CountOccurrencesVer(GEP[j].Sequence, kmers_vector[i]);
}
vector_map_hor.push_back(horizontal_map);
horizontal_map.clear();
vector_map_ver.push_back(vertical_map);
vertical_map.clear();
}
}
void MapClass::CountOccurrencesHor(string &sequence, unsigned int k) {
// PROFILE_FUNCTION();
for (unsigned int i = 0; i < (sequence.size() - k + 1); i++) {
string oligo = sequence.substr(i, k);
string oligo_rc;
ReverseString(oligo, oligo_rc);
unordered_map<string, HorizontalClass>::iterator it = horizontal_map.find(oligo);
unordered_map<string, HorizontalClass>::iterator it_rc = horizontal_map.find(oligo_rc);
if (it != horizontal_map.end()) {
it->second.horizontal_count++;
if (DS) {
it->second.horizontal_count_rc++;
}
} else if (it_rc != horizontal_map.end()) {
if (!it_rc->second.palindrome) {
it_rc->second.horizontal_count_rc++;
if (DS) {
it_rc->second.horizontal_count++;
}
}
} else {
HorizontalClass Hor;
Hor.oligo = oligo, Hor.oligo_rc = oligo_rc;
Hor.palindrome = bool(oligo == oligo_rc);
Hor.horizontal_count = 1, Hor.horizontal_count_rc = 0;
if (DS) {
Hor.horizontal_count_rc = 1, Hor.horizontal_count = 1;
}
horizontal_map.emplace(oligo, Hor);
}
}
}
void MapClass::CountOccurrencesVer(string &sequence, unsigned int k) {
// PROFILE_FUNCTION();
for (unsigned int i = 0; i < (sequence.size() - k + 1); i++) {
// unsigned int tot_freq = 0;
string oligo = sequence.substr(i, k);
string oligo_rc;
ReverseString(oligo, oligo_rc);
unordered_map<string, VerticalClass>::iterator it = vertical_map.find(oligo);
unordered_map<string, VerticalClass>::iterator it_rc = vertical_map.find(oligo_rc);
if (it != vertical_map.end()) {
it->second.vertical_count[i]++;
if(DS){
it->second.vertical_count_rc[i]++;
}
} else if (it_rc != vertical_map.end()) {
if (!it_rc->second.palindrome) {
it_rc->second.vertical_count_rc[i]++;
if (DS) {
it_rc->second.vertical_count[i]++;
}
}
} else {
VerticalClass Ver;
Ver.oligo = oligo, Ver.oligo_rc = oligo_rc;
Ver.palindrome = bool(oligo == oligo_rc);
Ver.vertical_count.resize(((sequence.size() - k) + 1), 0);
Ver.vertical_count_rc.resize(((sequence.size() - k) + 1), 0);
Ver.vertical_count[i] = 1;
if (DS) {
Ver.vertical_count_rc[i] = 1;
}
vertical_map.emplace(oligo, Ver);
}
}
}
void MapClass::VerticalMapVector() {
// PROFILE_FUNCTION();
for (unsigned int i = 0; i < kmers_vector.size(); i++) {
for (unsigned int j = 0; j < len[i]; j++) {
multimap<int, string, greater<int>> pos;
for (unordered_map<string, VerticalClass>::iterator it =
vector_map_ver[i].begin();
it != vector_map_ver[i].end(); it++) {
if (it->second.vertical_count[j] > 0) {
pos.emplace(it->second.vertical_count[j], it->first);
}
if (!it->second.palindrome && it->second.vertical_count_rc[j] > 0) {
pos.emplace(it->second.vertical_count_rc[j], it->second.oligo_rc);
}
}
positions_occurrences.push_back(pos);
pos.clear();
}
vector_positions_occurrences.push_back(positions_occurrences);
positions_occurrences.clear();
}
}
// Debug function
void MapClass::DVerticalMapVector() {
// // PROFILE_FUNCTION();
for (unsigned int i = 0; i < kmers_vector.size(); i++) {
cout << "I: " << i << endl;
for (unsigned int j = 0; j < vector_positions_occurrences[i].size(); j++) {
cout << "J: " << j << endl;
int sum = 0;
for (multimap<int, string>::iterator it =
vector_positions_occurrences[i][j].begin();
it != vector_positions_occurrences[i][j].end(); it++) {
cout << it->first << " " << it->second << endl;
sum = sum + it->first;
}
cout << "SOMMA TOTALE VERTICAL: " << sum << endl << endl;
}
}
}
// Debug function
void MapClass::DMainMapVectorDS() {
// // PROFILE_FUNCTION();
for (unsigned int i = 0; i < kmers_vector.size(); i++) {
for (unordered_map<string, HorizontalClass>::iterator it =
vector_map_hor[i].begin();
it != vector_map_hor[i].end(); it++) {
cout << it->first << " " << it->second.horizontal_count
<< "\t" << it->second.oligo_rc
<< " " << it->second.horizontal_count_rc << " "
<< " " << boolalpha << it->second.palindrome << noboolalpha << endl;
}
cout << "\n\n VERTICAL MAP: \n\n" << endl;
for (unordered_map<string, VerticalClass>::iterator it =
vector_map_ver[i].begin();
it != vector_map_ver[i].end(); it++) {
cout << it->first << " " << it->second.vertical_count[0]
<< "\t" << it->second.oligo_rc << " "
<< it->second.vertical_count_rc[0] << " "
<< " " << boolalpha << it->second.palindrome << noboolalpha << endl;
}
}
}
// Debug function
void MapClass::DMainMapVectorSS() {
// // PROFILE_FUNCTION();
for (unsigned int i = 0; i < kmers_vector.size(); i++) {
for (unordered_map<string, HorizontalClass>::iterator it =
vector_map_hor[i].begin();
it != vector_map_hor[i].end(); it++) {
cout << it->first << " " << it->second.horizontal_count << "\t"
<< it->second.oligo_rc << " " << it->second.horizontal_count_rc << " "
<< " " << boolalpha << it->second.palindrome << noboolalpha << endl;
}
for (unordered_map<string, VerticalClass>::iterator it =
vector_map_ver[i].begin();
it != vector_map_ver[i].end(); it++) {
cout << it->first << " " << it->second.vertical_count[21]
<< "\t" << it->second.oligo_rc << " "
<< it->second.vertical_count_rc[21] << " "
<< " " << boolalpha << it->second.palindrome << noboolalpha << endl;
}
}
}
// Function where K, N1, N2 and T are calculated in order to obtain the p value
void PvalueClass::TKN1Calc(vector<BedClass::bed_s> &GEP,
multimap<int, string>::iterator &it,
unordered_map<string, HorizontalClass> &vector_map_hor,
unsigned int i) {
// PROFILE_FUNCTION();
// T is the number of sequences
unsigned int T = GEP.size();
// For each oligo in the multimap of vertical occurrences T, N1, N2 and K are
// calculated.
// Remember N1 is the number of horizontal occurrences of oligo, T is the
// total number of sequences, N2 is the total number of oligos in all
// sequences minus N1 and K is the vertical occurrences of the oligo.
N1 = 0;
K = it->first;
oligo = it->second;
string oligo_rc;
ReverseString(oligo, oligo_rc);
unordered_map<string, HorizontalClass>::iterator itBigMap =
vector_map_hor.find(oligo);
unordered_map<string, HorizontalClass>::iterator itBigMap_rc =
vector_map_hor.find(oligo_rc);
if (itBigMap == vector_map_hor.end()) {
if (!itBigMap_rc->second.palindrome) {
N1 = itBigMap_rc->second.horizontal_count_rc;
}
} else {
N1 = itBigMap->second.horizontal_count;
}
// Calculation of total number of oligos in the multifasta
tot_oligos = T * len[i];
// Calculation of N2
N2 = tot_oligos - N1;
// Using the gsl library for the hypergeometric p_value
pvalue = gsl_cdf_hypergeometric_Q(K, N1, N2, T);
if (pvalue == 0) {
pvalue = 1e-300;
}
}
void HammingClass::PWMHammingCalc() {
// PROFILE_FUNCTION();
// Vector for each bases initialized to count, position by position, the
// occurrences of that base
vector<double> vec_A, vec_C, vec_G, vec_T;
// For each bases (position) of oligo
for (unsigned int i = 0; i < hamming_seed[0].size();i++){
double counter_A = 0;
double counter_C = 0;
double counter_G = 0;
double counter_T = 0;
// For each oligo in similar oligos vector
for (unsigned int j = 0; j < hamming_seed.size(); j++) {
cluster_map.insert(pair<string, double>(
hamming_seed[j], vert_vector[j]));
// cout << "Hamming seed: " << hamming_seed[j] << "\tOcc: " << vert_vector[j] << endl;
switch (hamming_seed[j][i]) {
// Increment base counters of the oligo occurrences
case 'A':
counter_A += vert_vector[j];
break;
case 'C':
counter_C += vert_vector[j];
break;
case 'G':
counter_G += vert_vector[j];
break;
case 'T':
counter_T += vert_vector[j];
break;
}
}
// Fill base vectors
vec_A.emplace_back(counter_A);
vec_C.emplace_back(counter_C);
vec_G.emplace_back(counter_G);
vec_T.emplace_back(counter_T);
}
// Build the PWM matrix
PWM_hamming.emplace_back(vec_A);
PWM_hamming.emplace_back(vec_C);
PWM_hamming.emplace_back(vec_G);
PWM_hamming.emplace_back(vec_T);
}
//Debug function
void HammingClass::DPWMHamming(vector<vector<double>> &PWM_hamming){
// // PROFILE_FUNCTION();
for (unsigned short int i = 0; i < PWM_hamming.size(); i++) {
for (unsigned short int j = 0; j < PWM_hamming[i].size(); j++) {
cout << PWM_hamming[i][j] << "\t";
}
cout << endl;
}
cout << endl;
}
void HammingClass::CheckSeed(string seed,
unordered_map<string, VerticalClass> &map_vertical,
multimap<int, string, greater<int>> &pos,
unsigned int position, unsigned int d) {
// PROFILE_FUNCTION();
for (multimap<int, string>::iterator it = pos.begin(); it != pos.end();
it++) {
hamming_v_occ = 0;
tot_freq += it->first;
string oligo = it->second;
if (oligo == seed){
seed_vertical = it->first;
}
unsigned int i = 0, count = 0;
// Here the hamming distance is calculated
while (seed[i] != '\0') {
if (seed[i] != oligo[i]){
count++;
}
i++;
}
// If the hamming distance is less or equal the distance by the user
// the oligo is added to the cluster and all the occurrences of the oligos present in the
// cluster are set to zero (for secondary matrix analysis)
if (count <= distance_vector[d]) {
string reverse_o;
ReverseString(oligo, reverse_o);
unordered_map<string, VerticalClass>::iterator it_ver = map_vertical.find(oligo);
unordered_map<string, VerticalClass>::iterator it_ver_rc = map_vertical.find(reverse_o);
if (it_ver != map_vertical.end()) {
hamming_v_occ += it_ver->second.vertical_count[position];
} else {
hamming_v_occ += it_ver_rc->second.vertical_count_rc[position];
}
vert_vector.push_back(hamming_v_occ);
hamming_seed.push_back(oligo);
//If double strand analysis also the reverse seed oligo is stored
if(DS){
hamming_seed_rev.push_back(reverse_o);
}
}
}
}
void HammingClass::Freq1Calc() {
// PROFILE_FUNCTION();
double cluster_occ = accumulate(vert_vector.begin(), vert_vector.end(),
decltype(vert_vector)::value_type(0));
freq1 = static_cast<double>(cluster_occ) / static_cast<double>(tot_freq);
}
void HammingClass::HoccCalc(unordered_map<string, HorizontalClass> &map_horizontal) {
// PROFILE_FUNCTION();
hamming_H_occ = 0;
for (unsigned int i = 0; i < hamming_seed.size(); i++) {
string oligo = hamming_seed[i];
string reverse_o;
ReverseString(oligo, reverse_o);
unordered_map<string, HorizontalClass>::iterator it = map_horizontal.find(oligo);
unordered_map<string, HorizontalClass>::iterator itrc = map_horizontal.find(reverse_o);
if (it != map_horizontal.end()) {
hamming_H_occ += it->second.horizontal_count;
} else {
hamming_H_occ += itrc->second.horizontal_count_rc;
}
}
}
void HammingClass::Freq2Calc() {
// PROFILE_FUNCTION();
freq2 = static_cast<double>(seed_vertical) / static_cast<double>(hamming_H_occ);
}
//Useful for secondary matrixes, this function clear the oligos used for the
//previous matrixes
void HammingClass::ClearVertical(multimap<int, string, greater<int>> &pos,
unordered_map<string, VerticalClass> &map_vertical, unsigned int j){
// PROFILE_FUNCTION();
for(unsigned int i = 0; i < hamming_seed.size(); i++){
for(multimap<int, string, greater<int>>::iterator it = pos.begin();
it != pos.end(); ++it){
string oligo = it->second;
if(oligo == hamming_seed[i]){
pos.erase(it);
break;
}
}
}
for(unsigned int i = 0; i < hamming_seed_rev.size(); i++){
for(multimap<int, string, greater<int>>::iterator it = pos.begin();
it != pos.end(); ++it){
string oligo = it->second;
if(oligo == hamming_seed_rev[i]){
pos.erase(it);
break;
}
}
}
}
void EMClass::EM_Ipwm(vector<vector<double>> &PWM_hamming) {
// PROFILE_FUNCTION();
double sum = 0;
double corr = 0;
for (unsigned int j = 0; j < PWM_hamming.size(); j++) {
sum = sum + PWM_hamming[j][0];
}
corr = sqrt(sum);
for (unsigned int x = 0; x < PWM_hamming.size(); x++) {
for (unsigned int y = 0; y < PWM_hamming[0].size(); y++) {
PWM_hamming[x][y] = PWM_hamming[x][y] + corr;
}
}
sum = 0;
for (unsigned int j = 0; j < PWM_hamming.size(); j++) {
sum += PWM_hamming[j][0];
}
for (unsigned short int i = 0; i < PWM_hamming.size(); i++) {
for (unsigned short int j = 0; j < PWM_hamming[i].size(); j++) {
PWM_hamming[i][j] = PWM_hamming[i][j] / sum;
}
}
}
/*
This function is about the expectation step of the expectation-maximization
algorithm where we obtain the likelihood ratio for each oligo in the vertical
map
*/
void EMClass::EM_Epart(map<string,double> &cluster_map, vector<vector<double>> &PWM_hamming,
unordered_map<string, HorizontalClass> &map_horizontal) {
// PROFILE_FUNCTION();
unsigned int sum_hor = 0;
for (map<string, double>::iterator it = cluster_map.begin();
it != cluster_map.end(); it++) {
unordered_map<string, HorizontalClass>::iterator occ_oligo_it =
map_horizontal.begin();
unordered_map<string, HorizontalClass>::iterator occ_oligo_it_rev =
map_horizontal.begin();
occ_oligo_it = map_horizontal.find(it->first);
string oligo_rc;
ReverseString(it->first, oligo_rc);
occ_oligo_it_rev = map_horizontal.find(oligo_rc);
if (occ_oligo_it != map_horizontal.end()) {
sum_hor = sum_hor + occ_oligo_it->second.horizontal_count;
}
if (occ_oligo_it_rev != map_horizontal.end()) {
sum_hor = sum_hor + occ_oligo_it_rev->second.horizontal_count_rc;
}
}
vector<double> LR;
vector<string> oligo;
// In this cycle for each element in vertical map we calculate the probability
// that this oligo is present in the hamming matrix
for (map<string, double>::iterator it = cluster_map.begin();
it != cluster_map.end(); it++) {
unordered_map<string, HorizontalClass>::iterator occ_oligo_it =
map_horizontal.begin();
unordered_map<string, HorizontalClass>::iterator occ_oligo_it_rev =
map_horizontal.begin();
string similar_oligo = it->first;
double P_oligo = 1;
double P_bg = 0;
double horizontal_occurences = 0;
double likelihood_ratio = 0;
occ_oligo_it = map_horizontal.find(it->first);
string oligo_rc;
ReverseString(it->first, oligo_rc);
occ_oligo_it_rev = map_horizontal.find(oligo_rc);
if (occ_oligo_it != map_horizontal.end()) {
horizontal_occurences = horizontal_occurences + occ_oligo_it->second.horizontal_count;
}
if (occ_oligo_it_rev != map_horizontal.end()) {
horizontal_occurences = horizontal_occurences + occ_oligo_it_rev->second.horizontal_count_rc;
}
P_bg = horizontal_occurences / sum_hor;
for (unsigned int k = 0; k < PWM_hamming[0].size(); k++) {
switch (it->first[k]) {
case 'A':
P_oligo *= PWM_hamming[0][k];
break;
case 'C':
P_oligo *= PWM_hamming[1][k];
break;
case 'G':
P_oligo *= PWM_hamming[2][k];
break;
case 'T':
P_oligo *= PWM_hamming[3][k];
break;
default: // Case if there is N
P_oligo *= 1;
break;
}
}
likelihood_ratio = P_oligo / P_bg;
LR.emplace_back(likelihood_ratio);
oligo.emplace_back(similar_oligo);
/*
*The like_ratio_map is a map where for each oligo present in the vertical
*map we couple the likelihood ratio previously calculated with the ratio
*between the probability to have the oligo in the PWM_hamming and the
*background probability
*/
}
double sum = 0;
double Nsites = ceil((cluster_map.size() / 2) + 1);
for (unsigned int i = 0; i < cluster_map.size(); i++) {
sum += LR[i];
}
for (unsigned int i = 0; i < cluster_map.size(); i++) {
LR[i] = LR[i] / sum;
LR[i] = LR[i] * Nsites;
// cout << "Oligo: "<< oligo[i] << "\tLR: " << LR[i] << endl;