-
Notifications
You must be signed in to change notification settings - Fork 1
/
Validator.h
executable file
·1229 lines (1006 loc) · 40.4 KB
/
Validator.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Validator.h
*
* Created on: 12 Aug 2015
* Author: dilthey
*/
#ifndef VALIDATOR_H_
#define VALIDATOR_H_
#include <vector>
#include <string>
#include <set>
#include <iostream>
#include <fstream>
#include <omp.h>
#include <assert.h>
#include "hash/deBruijn/DeBruijnGraph.h"
#include "Utilities.h"
typedef std::vector< std::vector<std::string> > diploidGenomeString;
diploidGenomeString VCF2GenomeString(std::string chromosomeID, int positionStart, int positionStop, std::string VCFpath, std::vector<std::vector<int> >& ret_graph_referencePositions, bool ignoreVCF, bool onlyPASS, const map<string, string>& referenceGenome);
diploidGenomeString compressGenomeString(diploidGenomeString gS);
std::vector<double> kMer_PP(size_t observedCoverage, size_t upperBound, double coverage);
template<int m, int k, int colours>
void evaluate_dGS(diploidGenomeString& gS, diploidGenomeString& gS_unresolved, const std::set<std::string>& kMers_reference, DeBruijnGraph<m, k, colours>* graph, std::set<std::string>* kMers_in_dGS, std::set<std::string>* kMers_in_dGS_in_sample, std::map<std::string, double>* kMers_in_dGS_optimality, std::string nameForSummary, ofstream& summaryFileStream, std::string pathForSpatialSummary, std::vector<std::vector<int> > chromotypes_referencePositions);
template<int m, int k>
void validateCompleteVCF(std::string VCFfile, std::string referenceGenomePath, std::string deBruijnGraph, int cortex_height, int cortex_width, int maximumHaplotypePairs, std::string outputDirectory, int threads, bool onlyPASS, std::string regions);
template<int m, int k, int colours>
std::pair<diploidGenomeString, diploidGenomeString> greedilyResolveDiploidKMerString(diploidGenomeString& original_gS, DeBruijnGraph<m, k, colours>* graph, int maximumHaplotypePairs);
template<int m, int k>
void validateCompleteVCF(std::string VCFfile, std::string referenceGenomePath, std::string deBruijnGraph, int cortex_height, int cortex_width, int maximumHaplotypePairs, std::string outputDirectory, int threads, bool onlyPASS, std::string regions)
{
omp_set_num_threads(threads);
int kMer_size = k;
std::string configFileOutputPath= outputDirectory + "/validationDetails.txt";
ofstream configOutputStream;
configOutputStream.open(configFileOutputPath.c_str());
if(! configOutputStream.is_open())
{
throw std::runtime_error("validateCompleteVCF(..): Want top open config summary file for writing, but can't! Path:\n"+configFileOutputPath);
}
configOutputStream << "k = " << kMer_size << "\n";
configOutputStream << "deBruijnGraph" << " = " << deBruijnGraph << "\n";
configOutputStream << "VCF" << " = " << VCFfile << "\n";
configOutputStream << "referenceGenome" << " = " << referenceGenomePath << "\n";
configOutputStream << "maximumHaplotypePairs" << " = " << maximumHaplotypePairs << "\n";
configOutputStream << "onlyPASS" << " = " << onlyPASS << "\n";
configOutputStream << "threads" << " = " << threads << "\n";
configOutputStream.close();
map<string, string> referenceGenome = Utilities::readFASTA(referenceGenomePath);
std::vector<std::string> chromosomes;
if(regions.length() == 0)
{
std::cout << "Take regions from reference genome " << referenceGenomePath << ".\n";
for(std::map<string, string>::iterator refRegionIt = referenceGenome.begin(); refRegionIt != referenceGenome.end(); refRegionIt++)
{
chromosomes.push_back(refRegionIt->first);
}
}
else
{
chromosomes = Utilities::split(regions, ",");
for(int chrI = 0; chrI < chromosomes.size(); chrI++)
{
std::string regionID = chromosomes.at(chrI);
if(! referenceGenome.count(regionID))
{
std::cerr << "Region " << regionID << " not present in reference genome, abort!\n" << std::flush;
}
assert(referenceGenome.count(regionID));
}
}
std::cout << "Regions: " << Utilities::join(chromosomes, ", ") << "\n\n" << std::flush;
std::cout << Utilities::timestamp() << "Allocate Cortex graph object with height = " << cortex_height << ", width = " << cortex_width << " ...\n" << std::flush;
DeBruijnGraph<m, k, 1> myGraph(cortex_height, cortex_width);
std::cout << Utilities::timestamp() << "Cortex graph object allocated, loading binary...\n" << std::flush;
myGraph.loadMultiColourBinary(deBruijnGraph);
std::cout << Utilities::timestamp() << "\tdone\n" << std::flush;
std::cout << "\tTotal coverage: " << myGraph.totalCoverage() << "\n";
std::string summaryFilePath = outputDirectory + "/summaryPerChromosome.txt";
ofstream summaryFileStream;
summaryFileStream.open(summaryFilePath.c_str());
assert(summaryFileStream.is_open());
std::vector<std::string> headerFields;
headerFields.push_back("Method");
headerFields.push_back("Total characters");
headerFields.push_back("Total non-gap characters");
headerFields.push_back("# kMers");
headerFields.push_back("# kMers invalid");
headerFields.push_back("# kMers present");
headerFields.push_back("Unweighted optimality");
headerFields.push_back("Coverage-weighted optimality");
summaryFileStream << Utilities::join(headerFields, "\t") << "\n";
for(unsigned int chromosomeI = 0; chromosomeI < chromosomes.size(); chromosomeI++)
{
std::string chromosome = chromosomes.at(chromosomeI);
std::cout << Utilities::timestamp() << " " << "Chromosome " << chromosome << ", convert VCF to diploidGS...\n" << std::flush;
std::vector<std::vector<int> > VCF_chromotypes_referencePositions;
diploidGenomeString VCF_chromotypes = VCF2GenomeString(chromosome, -1, -1, VCFfile, VCF_chromotypes_referencePositions, false, onlyPASS, referenceGenome);
std::cout << Utilities::timestamp() << " " << "\n\tdone\n" << std::flush;
std::cout << Utilities::timestamp() << " " << "Chromosome " << chromosome << ", compress VCF diploidGS...\n" << std::flush;
diploidGenomeString VCF_chromotypes_compressed = compressGenomeString(VCF_chromotypes);
std::cout << Utilities::timestamp() << " " << "\n\tdone\n" << std::flush;
std::cout << Utilities::timestamp() << " " << "Chromosome " << chromosome << ", resolve chromotypes from VCF..\n" << std::flush;
diploidGenomeString VCF_chromotypes_resolved = greedilyResolveDiploidKMerString<m, k, 1>(VCF_chromotypes_compressed, &myGraph, maximumHaplotypePairs).second;
std::cout << Utilities::timestamp() << " " << "\n\tdone\n" << std::flush;
std::set<std::string> set_kMers_reference;
std::set<std::string> set_kMers_VCF;
std::set<std::string> set_kMers_VCF_present;
std::map<std::string, double> set_kMers_VCF_optimalities;
std::cout << Utilities::timestamp() << " " << "Chromosome " << chromosome << ", evaluate VCF chromotypes\n" << std::flush;
evaluate_dGS(VCF_chromotypes_resolved, VCF_chromotypes_compressed, set_kMers_reference, &myGraph, 0, 0, 0, "fromVCF_"+chromosome, summaryFileStream, outputDirectory, VCF_chromotypes_referencePositions);
std::cout << Utilities::timestamp() << "\n\tdone" << "\n\n" << std::flush;
std::cout << Utilities::timestamp() << " " << "Chromosome " << chromosome << ", convert VCF (reference-only) to diploidGS...\n" << std::flush;
std::vector<std::vector<int> > reference_chromotypes_referencePositions;
std::cout << "Get non-modified diploidGS for reference genome...\n" << std::flush;
diploidGenomeString gS_ref = VCF2GenomeString(chromosome, -1, -1, VCFfile, reference_chromotypes_referencePositions, true, onlyPASS, referenceGenome);
std::cout << "\tdone\n" << std::flush;
std::cout << Utilities::timestamp() << " " << "Chromosome " << chromosome << ", compress VCF (reference-only) diploidGS...\n" << std::flush;
diploidGenomeString gS_ref_compressed = compressGenomeString(gS_ref);
std::cout << Utilities::timestamp() << " " << "\n\tdone\n" << std::flush;
set_kMers_reference.clear();
set_kMers_VCF.clear();
set_kMers_VCF_present.clear();
set_kMers_VCF_optimalities.clear();
std::cout << Utilities::timestamp() << " " << "Chromosome " << chromosome << ", evaluate VCF (reference-only) chromotypes\n" << std::flush;
evaluate_dGS(gS_ref_compressed, gS_ref_compressed, set_kMers_reference, &myGraph, 0, 0, 0, "referenceOnly_"+chromosome, summaryFileStream, outputDirectory, reference_chromotypes_referencePositions);
std::cout << Utilities::timestamp() << "\n\tdone" << "\n\n" << std::flush;
}
}
template<int m, int k, int colours>
void evaluate_dGS(diploidGenomeString& gS, diploidGenomeString& gS_unresolved, const std::set<std::string>& kMers_reference, DeBruijnGraph<m, k, colours>* graph, std::set<std::string>* kMers_in_dGS, std::set<std::string>* kMers_in_dGS_in_sample, std::map<std::string, double>* kMers_in_dGS_optimality, std::string nameForSummary, ofstream& summaryFileStream, std::string pathForSpatialSummary, std::vector<std::vector<int> > chromotypes_referencePositions)
{
// We only want to deal with completely resolved genomestrings up to level k
// That is, we want genomestrings which
// - have all subsequent homozygous stretches connected
// - have at least k homozygous characters between any two heterozygous positions
// - so that if we connect them together, all k-mers are totally determined
size_t totalLevels = 0;
for(unsigned int l = 0; l < gS.size(); l++)
{
if(gS.at(l).size() == 1)
{
if(!((l == 0) || (gS.at(l-1).size() != 1)))
{
std::cerr << "!((l == 0) || (gS.at(l-1).size() != 1)), l = " << l << ", gS.at(l-1).size() = " << gS.at(l-1).size() << ", gS.size()= " << gS.size() << "\n" << std::flush;
}
if(!((l == (gS.size() - 1)) || (gS.at(l+1).size() != 1)))
{
std::cerr << "!((l == (gS.size() - 1)) || (gS.at(l+1).size() != 1)), l = " << l << ", gS.at(l+1).size() = " << gS.at(l+1).size() << ", gS.size()= " << gS.size() << "\n" << std::flush;
}
assert((l == 0) || (gS.at(l-1).size() != 1));
assert((l == (gS.size() - 1)) || (gS.at(l+1).size() != 1));
}
unsigned int requiredSpace = gS.at(l).at(0).size();
totalLevels += requiredSpace;
}
std::vector<std::vector<std::string> > uncompressed_chromotypes;
std::vector<int> uncompressed_chromotypes_nGaps;
uncompressed_chromotypes.reserve(totalLevels);
uncompressed_chromotypes_nGaps.reserve(totalLevels);
for(unsigned int outerI = 0; outerI < gS.size(); outerI++)
{
std::vector<std::string>& segment = gS.at(outerI);
assert((segment.size() == 1) || (segment.size() == 2));
if(segment.size() == 2)
{
assert(segment.at(0).size() == segment.at(1).size());
}
unsigned int requiredSpace = segment.at(0).size();
for(unsigned int posInSegment = 0; posInSegment < requiredSpace; posInSegment++)
{
std::vector<std::string> posVector;
std::vector<double> posCoverageVector;
std::vector<double> posSupportVector;
std::vector<double> posInsertionsVector;
if(segment.size() == 2)
{
posVector.push_back(segment.at(0).substr(posInSegment, 1));
posVector.push_back(segment.at(1).substr(posInSegment, 1));
posCoverageVector.push_back(0);
posCoverageVector.push_back(0);
posSupportVector.push_back(0);
posSupportVector.push_back(0);
posInsertionsVector.push_back(0);
posInsertionsVector.push_back(0);
}
else
{
posVector.push_back(segment.at(0).substr(posInSegment, 1));
posCoverageVector.push_back(0);
posSupportVector.push_back(0);
posInsertionsVector.push_back(0);
}
uncompressed_chromotypes.push_back(posVector);
int numGaps = 0;
if(segment.size() == 2)
{
if(segment.at(0).substr(posInSegment, 1) == "_")
{
numGaps++;
}
if(segment.at(1).substr(posInSegment, 1) == "_")
{
numGaps++;
}
}
else
{
if(segment.at(0).substr(posInSegment, 1) == "_")
{
numGaps = 2;
}
}
uncompressed_chromotypes_nGaps.push_back(numGaps);
}
}
assert(uncompressed_chromotypes.size() == uncompressed_chromotypes_nGaps.size());
std::vector<int> uncompressed_chromotypes_referencePositions;
uncompressed_chromotypes_referencePositions.reserve(totalLevels);
for(unsigned int outerI = 0; outerI < chromotypes_referencePositions.size(); outerI++)
{
for(unsigned int posInSegment = 0; posInSegment < chromotypes_referencePositions.at(outerI).size(); posInSegment++)
{
uncompressed_chromotypes_referencePositions.push_back(chromotypes_referencePositions.at(outerI).at(posInSegment));
}
}
if(!(uncompressed_chromotypes.size() == uncompressed_chromotypes_referencePositions.size()))
{
std::cerr << "! (uncompressed_chromotypes.size() == uncompressed_chromotypes_referencePositions.size())" << "\n";
std::cerr << "uncompressed_chromotypes.size()" << ": " << uncompressed_chromotypes.size() << "\n";
std::cerr << "uncompressed_chromotypes_referencePositions.size()" << ": " << uncompressed_chromotypes_referencePositions.size() << "\n\n" << std::flush;
std::cerr << "gS.size()" << ": " << gS.size() << "\n";
std::cerr << "chromotypes_referencePositions.size()" << ": " << chromotypes_referencePositions.size() << "\n\n";
std::cerr << std::flush;
}
assert(uncompressed_chromotypes.size() == uncompressed_chromotypes_referencePositions.size());
std::vector<int> uncompressed_chromotypes_diploid;
std::vector<int> uncompressed_chromotypes_losePhasing;
uncompressed_chromotypes_diploid.reserve(totalLevels);
uncompressed_chromotypes_losePhasing.reserve(totalLevels);
for(unsigned int outerI = 0; outerI < gS_unresolved.size(); outerI++)
{
std::vector<std::string>& segment = gS_unresolved.at(outerI);
assert((segment.size() == 1) || (segment.size() == 2));
if(segment.size() == 2)
{
assert(segment.at(0).size() == segment.at(1).size());
}
for(unsigned int posInString = 0; posInString < segment.at(0).length(); posInString++)
{
uncompressed_chromotypes_diploid.push_back(segment.size() - 1);
if((posInString == 0) && (segment.size() == 2))
{
uncompressed_chromotypes_losePhasing.push_back(1);
}
else
{
uncompressed_chromotypes_losePhasing.push_back(0);
}
}
}
if(!(uncompressed_chromotypes.size() == uncompressed_chromotypes_diploid.size()))
{
std::cerr << "! uncompressed_chromotypes.size() == uncompressed_chromotypes_diploid.size()" << "\n";
std::cerr << "uncompressed_chromotypes.size()" << ": " << uncompressed_chromotypes.size() << "\n";
std::cerr << "uncompressed_chromotypes_diploid.size()" << ": " << uncompressed_chromotypes_diploid.size() << "\n\n" << std::flush;
std::cerr << "gS.size()" << ": " << gS.size() << "\n";
std::cerr << "uncompressed_chromotypes_referencePositions.size()" << ": " << uncompressed_chromotypes_referencePositions.size() << "\n\n";
std::cerr << std::flush;
}
assert(uncompressed_chromotypes.size() == uncompressed_chromotypes_diploid.size());
assert(uncompressed_chromotypes.size() == uncompressed_chromotypes_losePhasing.size());
std::string s1; std::string s2;
s1.reserve(totalLevels);
s2.reserve(totalLevels);
for(unsigned int l = 0; l < gS.size(); l++)
{
if(gS.at(l).size() == 1)
{
s1.append(gS.at(l).at(0));
s2.append(gS.at(l).at(0));
unsigned int nonGap_characters = 0;
for(unsigned int i = 0; i < gS.at(l).at(0).size(); i++)
{
if(gS.at(l).at(0).at(i) != '_')
{
nonGap_characters++;
}
}
if((l != 0) && (l != (gS.size() - 1)))
{
assert(nonGap_characters >= k);
}
}
else
{
assert(gS.at(l).size() == 2);
assert((l == 0) || (gS.at(l-1).size() == 1));
assert((l == (gS.size() - 1)) || (gS.at(l+1).size() == 1));
s1.append(gS.at(l).at(0));
s2.append(gS.at(l).at(1));
}
}
// now count k-Mers
size_t total_characters = 0;
size_t total_nonGap_characters = 0;
std::map<std::string, int> kMer_counts;
size_t kMersCannotEvaluate = 0;
std::vector<int> inducedkMers;
std::vector<int> inducedkMers_OK;
std::vector<int> inducedkMers_invalid;
std::vector<int> inducedkMers_inReference;
std::string filenameForSpatialSummary = pathForSpatialSummary + "/spatialSummary_" + nameForSummary + ".txt";
ofstream spatialSummaryStream;
spatialSummaryStream.open(filenameForSpatialSummary.c_str());
assert(spatialSummaryStream.is_open());
spatialSummaryStream <<
"Level" << "\t" <<
"ReferenceCoordinate" << "\t" <<
"kMersInduced" << "\t" <<
"kMersInvalid" << "\t" <<
"kMersOK" << "\t" <<
"InducedkMersInReference" << "\t" <<
"DiploidChromotype" << "\t" <<
"ChromotypeLostPhase" << "\t" <<
"GapsAtLevel" << "\n";
auto partitionStringIntokMers_overGaps = [](std::string s, int kMerSize) -> std::vector<std::string> {
std::vector<std::string> forReturn;
forReturn.reserve((int)s.length() - kMerSize);
for(int i = 0; i <= ((int)s.length() - kMerSize); i++)
{
std::string C = s.substr(i, 1);
if(C == "_")
{
forReturn.push_back(std::string(""));
}
else
{
int foundMoreNonGaps = 0;
int currentStop = i;
while((currentStop < ((int)s.length()-1)) && (foundMoreNonGaps < (kMerSize-1)))
{
currentStop++;
std::string justAddedC = s.substr(currentStop,1);
if(justAddedC != "_")
{
foundMoreNonGaps++;
}
}
if(foundMoreNonGaps == (kMerSize-1))
{
std::string kMer = C + s.substr(i+1, (currentStop-(i+1)+1));
kMer.erase(std::remove_if(kMer.begin(),kMer.end(), [&](char c){return ((c == '_') ? true : false);}), kMer.end());
assert((int)kMer.length() == kMerSize);
forReturn.push_back(kMer);
}
else
{
forReturn.push_back(std::string(""));
}
}
}
assert(forReturn.size() == (s.length() - kMerSize + 1));
return forReturn;
};
std::string testString = "AHCCHDHRHJSKSJSKKSKLSSOMCSNCSDKDKDKDKDKCMCMCKWL";
std::vector<std::string> kMers_1 = partitionStringIntokMers(testString, 5);
std::vector<std::string> kMers_2 = partitionStringIntokMers_overGaps(testString, 5);
assert(kMers_1.size() == kMers_2.size());
for(unsigned int i = 0; i < kMers_1.size(); i++)
{
assert(kMers_1.at(i) == kMers_2.at(i));
}
auto processString = [&](std::string s) {
for(size_t i = 0; i < s.length(); i++)
{
total_characters++;
if(s.at(i) != '_')
{
total_nonGap_characters++;
}
}
//s.erase(std::remove_if(s.begin(),s.end(), [&](char c){return ((c == '_') ? true : false);}), s.end());
std::vector<std::string> kMers = partitionStringIntokMers_overGaps(s, k);
for(size_t i = 0; i < kMers.size(); i++)
{
std::string kMer = kMers.at(i);
bool containsGap = (kMer.length() == 0);
bool kMerOK = true;
for(unsigned int kI = 0; kI < kMer.length(); kI++)
{
char kMerC = kMer.at(kI);
assert(kMerC != '_');
if(!((kMerC == 'A') || (kMerC == 'C') || (kMerC == 'G') || (kMerC == 'T')))
{
kMerOK = false;
break;
}
}
if(containsGap)
{
// nothing
}
else
{
inducedkMers.at(i)++;
if(kMerOK)
{
if(kMer_counts.count(kMer) == 0)
kMer_counts[kMer] = 0;
kMer_counts[kMer]++;
if(graph->kMerinGraph(kMer))
{
inducedkMers_OK.at(i)++;
}
}
else
{
kMersCannotEvaluate++;
inducedkMers_invalid.at(i)++;
}
if(kMers_reference.size() == 0)
{
}
else
{
if(kMers_reference.count(kMer))
{
inducedkMers_inReference.at(i)++;
}
}
}
}
};
assert(s1.length() > k);
inducedkMers.resize(s1.length()-k+1,0);
inducedkMers_invalid.resize(s1.length()-k+1,0);
inducedkMers_OK.resize(s1.length()-k+1,0);
inducedkMers_inReference.resize(s1.length()-k+1,0);
assert(s1.length() == s2.length());
processString(s1);
processString(s2);
for(unsigned int level = 0; level < inducedkMers.size(); level++)
{
spatialSummaryStream <<
level << "\t" <<
uncompressed_chromotypes_referencePositions.at(level) << "\t" <<
inducedkMers.at(level) << "\t" <<
inducedkMers_invalid.at(level) << "\t" <<
inducedkMers_OK.at(level) << "\t" <<
inducedkMers_inReference.at(level) << "\t" <<
uncompressed_chromotypes_diploid.at(level) << "\t" <<
uncompressed_chromotypes_losePhasing.at(level) << "\t" <<
uncompressed_chromotypes_nGaps.at(level) << "\n";
}
spatialSummaryStream.close();
size_t total_kMers_present = 0;
size_t maximumkMerCount = 0;
size_t maximumAllowedkMerCount = 100;
for(std::map<std::string, int>::iterator kMerIt = kMer_counts.begin(); kMerIt != kMer_counts.end(); kMerIt++)
{
std::string kMer = kMerIt->first;
int kMerCount = kMerIt->second;
if(kMers_in_dGS != 0)
{
kMers_in_dGS->insert(kMer);
}
if(graph->kMerinGraph(kMer))
{
total_kMers_present++;
if(kMers_in_dGS_in_sample != 0)
{
kMers_in_dGS_in_sample->insert(kMer);
}
}
if(kMerCount > maximumkMerCount)
maximumkMerCount = kMerCount;
}
double haploidGenomeSize = 3.2e9;
size_t graph_totalCoverage = graph->totalCoverage();
double averageCoverage = double(graph_totalCoverage)/(2.0 * haploidGenomeSize);
std::cout << "Estimate coverage posterior probabilties for max count of " << maximumkMerCount << ", assuming WG average coverage of " << averageCoverage << " [total coverage on graph: " << graph_totalCoverage << "]\n";
if(maximumkMerCount > maximumAllowedkMerCount)
{
maximumkMerCount = maximumAllowedkMerCount;
std::cout << "Restrict maximum kMer count (underlying) to " << maximumAllowedkMerCount << " - all kMers with higher underlying numbers will be ignored!" << "\n" << std::flush;
}
if(averageCoverage == 0)
{
averageCoverage = 1;
}
assert(averageCoverage != 0);
std::map<size_t, std::vector<double> > _pp_cache;
auto getPPs = [&](size_t observedCoverage) -> std::vector<double> {
if(_pp_cache.count(observedCoverage) > 0)
{
return _pp_cache.at(observedCoverage);
}
else
{
std::vector<double> forReturn = kMer_PP(observedCoverage, maximumkMerCount, averageCoverage);
if(observedCoverage < (2 * averageCoverage))
{
_pp_cache[observedCoverage] = forReturn;
}
return forReturn;
}
};
double expected_kMer_presence = 0;
double expected_kMer_presence_sum = 0;
for(std::map<std::string, int>::iterator kMerIt = kMer_counts.begin(); kMerIt != kMer_counts.end(); kMerIt++)
{
std::string kMer = kMerIt->first;
int kMerCount = kMerIt->second;
int kMerCoverage = graph->kMer_getCoverage(kMer);
std::vector<double> pps;
if(kMerCount <= maximumAllowedkMerCount)
{
pps = getPPs(kMerCoverage);
double expected_missing = 0;
for(int i = 0; i < kMerCount; i++)
{
int e_missing = kMerCount - i;
double e_p = pps.at(i);
expected_missing += e_missing * e_p;
}
assert(expected_missing >= 0);
assert(expected_missing <= kMerCount);
double this_kMer_presence = (kMerCount - expected_missing);
expected_kMer_presence += this_kMer_presence;
expected_kMer_presence_sum += kMerCount;
if(kMers_in_dGS_optimality != 0)
{
(*kMers_in_dGS_optimality)[kMer] = (double)this_kMer_presence / (double)kMerCount;
}
}
}
assert(expected_kMer_presence >= 0);
assert(expected_kMer_presence <= expected_kMer_presence_sum);
assert(expected_kMer_presence_sum > 0);
double unweighted_optimality = (kMer_counts.size() != 0) ? (double(total_kMers_present)/double(kMer_counts.size())) : 1;
double weighted_probabilistic_optimality = expected_kMer_presence / expected_kMer_presence_sum;
std::cout << "evaluate_dGS(..):\n";
std::cout << "\tLength of gS: " << gS.size() << "\n";
std::cout << "\tTotal characters: " << total_characters << ", of which non-gap: " << total_nonGap_characters << "\n";
std::cout << "\tTotal kMers: " << kMer_counts.size() << "\n";
std::cout << "\tTotal invalid kMers (driven by non-A/C/G/T): " << kMersCannotEvaluate << "\n";
std::cout << "\tTotal kMers present: " << total_kMers_present << "\n";
std::cout << "\tUnweighted optimality: " << unweighted_optimality << "\n";
std::cout << "\tWeighted probabilistic optimality: " << weighted_probabilistic_optimality << "\n";
std::vector<std::string> fieldsForPrinting;
fieldsForPrinting.push_back(nameForSummary);
fieldsForPrinting.push_back(Utilities::ItoStr(total_characters));
fieldsForPrinting.push_back(Utilities::ItoStr(total_nonGap_characters));
fieldsForPrinting.push_back(Utilities::ItoStr(kMer_counts.size()));
fieldsForPrinting.push_back(Utilities::ItoStr(kMersCannotEvaluate));
fieldsForPrinting.push_back(Utilities::ItoStr(total_kMers_present));
fieldsForPrinting.push_back(Utilities::DtoStr(unweighted_optimality));
fieldsForPrinting.push_back(Utilities::DtoStr(weighted_probabilistic_optimality));
summaryFileStream << Utilities::join(fieldsForPrinting, "\t") << "\n";
}
template<int m, int k, int colours>
std::pair<diploidGenomeString, diploidGenomeString> greedilyResolveDiploidKMerString(diploidGenomeString& original_gS, DeBruijnGraph<m, k, colours>* graph, int maximumHaplotypePairs)
{
int threads = 40;
omp_set_num_threads(threads);
unsigned int _compartmentI;
size_t gS_length_before = original_gS.size();
std::vector<std::pair<std::string, std::string> > openPairs;
std::pair<std::string, std::string> resolved;
std::pair<std::string, std::string> resolved_noGaps;
diploidGenomeString resolved_gS;
int addedHomozygousSeq = 0;
auto evaluateSequence = [&](std::string seq) -> double {
seq.erase(std::remove_if(seq.begin(),seq.end(), [&](char c){return ((c == '_') ? true : false);}), seq.end());
std::vector<std::string> kMers = partitionStringIntokMers(seq, k);
std::map<std::string, int> kMers_table;
for(unsigned int i = 0; i < kMers.size(); i++)
{
std::string kMer = kMers.at(i);
if(kMers_table.count(kMer) == 0)
{
kMers_table[kMer] = 0;
}
kMers_table[kMer]++;
}
double optimality_sum = 0;
double optimality_score = 0;
for(std::map<std::string, int>::iterator kMerIt = kMers_table.begin(); kMerIt != kMers_table.end(); kMerIt++)
{
std::string kMerSeq = kMerIt->first;
bool kMerOK = true;
for(unsigned int kI = 0; kI < kMerSeq.length(); kI++)
{
char kMerC = kMerSeq.at(kI);
if(!((kMerC == 'A') || (kMerC == 'C') || (kMerC == 'G') || (kMerC == 'T')))
{
kMerOK = false;
break;
}
}
if(kMerOK)
{
int count = kMerIt->second;
bool present = graph->kMerinGraph(kMerSeq);
if(present)
optimality_score += count;
optimality_sum += count;
}
}
if(optimality_sum == 0)
{
return 1;
}
else
{
return optimality_score/optimality_sum;
}
};
auto evaluateSequence2 = [&](std::string seq, int& optimality_sum, int& optimality_score) -> void {
seq.erase(std::remove_if(seq.begin(),seq.end(), [&](char c){return ((c == '_') ? true : false);}), seq.end());
std::vector<std::string> kMers = partitionStringIntokMers(seq, k);
std::map<std::string, int> kMers_table;
for(unsigned int i = 0; i < kMers.size(); i++)
{
std::string kMer = kMers.at(i);
if(kMers_table.count(kMer) == 0)
{
kMers_table[kMer] = 0;
}
kMers_table[kMer]++;
}
optimality_sum = 0;
optimality_score = 0;
for(std::map<std::string, int>::iterator kMerIt = kMers_table.begin(); kMerIt != kMers_table.end(); kMerIt++)
{
std::string kMerSeq = kMerIt->first;
bool kMerOK = true;
for(unsigned int kI = 0; kI < kMerSeq.length(); kI++)
{
char kMerC = kMerSeq.at(kI);
if(!((kMerC == 'A') || (kMerC == 'C') || (kMerC == 'G') || (kMerC == 'T')))
{
kMerOK = false;
break;
}
}
if(kMerOK)
{
// int count = kMerIt->second;
bool present = graph->kMerinGraph(kMerSeq);
if(present)
optimality_score += 1;
optimality_sum += 1;
}
}
};
auto evaluateAndReduce = [&]() {
assert(resolved.first.length() == resolved.second.length());
size_t size_before = openPairs.size();
if(openPairs.size() > 0)
{
std::vector<double> optimality;
optimality.resize(openPairs.size());
long long max_i = optimality.size() - 1;
long long chunk_size = max_i / threads;
#pragma omp parallel
{
assert(omp_get_num_threads() == threads);
long long thisThread = omp_get_thread_num();
long long firstPair = thisThread * chunk_size;
long long lastPair = (thisThread+1) * chunk_size - 1;
if((thisThread == (threads-1)) && (lastPair < max_i))
{
lastPair = max_i;
}
for(long long i = firstPair; i <= lastPair; i++)
{
int copyCharactersFromPrevious = k;
if((copyCharactersFromPrevious > resolved_noGaps.first.length()) || (copyCharactersFromPrevious > resolved_noGaps.second.length()))
{
copyCharactersFromPrevious = (resolved_noGaps.first.length() < resolved_noGaps.second.length()) ? resolved_noGaps.first.length() : resolved_noGaps.second.length() ;
}
std::string previous_first = resolved_noGaps.first.substr(resolved_noGaps.first.length() - copyCharactersFromPrevious, copyCharactersFromPrevious);
std::string previous_second = resolved_noGaps.second.substr(resolved_noGaps.second.length() - copyCharactersFromPrevious, copyCharactersFromPrevious);
assert(previous_first.length() == copyCharactersFromPrevious);
assert(previous_second.length() == copyCharactersFromPrevious);
assert(previous_first == previous_second);
std::string seq_evaluate_1 = previous_first + openPairs.at(i).first;
std::string seq_evaluate_2 = previous_second + openPairs.at(i).second;
int optimality_sum_seq1 = 0;
int optimality_score_seq1 = 0;
int optimality_sum_seq2 = 0;
int optimality_score_seq2 = 0;
evaluateSequence2(seq_evaluate_1, optimality_sum_seq1, optimality_score_seq1);
evaluateSequence2(seq_evaluate_2, optimality_sum_seq2, optimality_score_seq2);
double O = 1;
if((optimality_sum_seq1 + optimality_sum_seq2) > 0)
{
O = (double)(optimality_score_seq1 + optimality_score_seq2)/(double)(optimality_sum_seq1 + optimality_sum_seq2);
}
optimality.at(i) = O;
}
}
double maxOptimality; size_t whereOptimality;
for(size_t i = 0; i < optimality.size(); i++)
{
if((i == 0) || (maxOptimality < optimality.at(i)))
{
maxOptimality = optimality.at(i);
whereOptimality = i;
}
}
if(maxOptimality == 0)
{
std::vector<std::pair<std::string, std::string> > new_openPairs;
new_openPairs.push_back(openPairs.at(0));
openPairs = new_openPairs;
}
else
{
std::vector<std::pair<std::string, std::string> > new_openPairs;
if(optimality.size() <= maximumHaplotypePairs)
{
for(size_t i = 0; i < optimality.size(); i++)
{
if((optimality.at(i)/maxOptimality) > 0.9)
{
new_openPairs.push_back(openPairs.at(i));
}
}
}
else
{
std::vector<unsigned int> optimality_sort_indices;
optimality_sort_indices.resize(optimality.size());
for(unsigned int i = 0; i < optimality_sort_indices.size(); i++)
{
optimality_sort_indices.at(i) = i;
}
std::sort(optimality_sort_indices.begin(), optimality_sort_indices.end(), [&](unsigned int a, unsigned int b) -> bool {
return (optimality.at(b) < optimality.at(a));
}
);
assert(optimality_sort_indices.size() == optimality.size());
unsigned int maxIndex = maximumHaplotypePairs/2;
for(unsigned int optimalityI = 0; optimalityI <= maxIndex; optimalityI++)
{
unsigned int realOptimalityI = optimality_sort_indices.at(optimalityI);
double realOptimality = optimality.at(realOptimalityI);
if(optimalityI > 0)
{
unsigned int previous_OptimalityI = optimality_sort_indices.at(optimalityI - 1);
double previous_Optimality = optimality.at(previous_OptimalityI);
assert(previous_Optimality >= realOptimality);
}
new_openPairs.push_back(openPairs.at(realOptimalityI));
}
}
openPairs = new_openPairs;
}
size_t size_after = openPairs.size();
if(((double)size_after/(double)size_before) > 0.5)
{
std::cerr << "\nevaluateAndReduce(..): Not very effective. Reduction from " << size_before << " to " << size_after << ", maxOptimality = " << maxOptimality << " -- but does this really matter??\n" << std::flush;
// std::cerr << "\t" << "resolved.first.length(): " << resolved.first.length() << "\n";
// std::cerr << "\t" << "openPairs.at(0).first.length(): " << openPairs.at(0).first.length() << " // " << openPairs.at(0).first << "\n" << std::flush;
// assert(size_after > 100);
// std::vector<std::pair<std::string, std::string> > new_openPairs;
// for(size_t i = 0; i < openPairs.size(); i++)
// {
// if(Utilities::randomDouble() < 0.1)
// {
// new_openPairs.push_back(openPairs.at(i));
// }
// }
// openPairs = new_openPairs;
// std::cerr << "Random reduction to " << openPairs.size() << " elements. " << "\n" << std::flush;
}
}
};
auto evaluateAndResolve = [&]() {
assert(resolved.first.length() == resolved.second.length());
if(openPairs.size() > 0)
{
std::vector<double> optimality;
optimality.resize(openPairs.size());
long long max_i = optimality.size() - 1;
long long chunk_size = max_i / threads;
#pragma omp parallel
{
assert(omp_get_num_threads() == threads);
long long thisThread = omp_get_thread_num();
long long firstPair = thisThread * chunk_size;
long long lastPair = (thisThread+1) * chunk_size - 1;
if((thisThread == (threads-1)) && (lastPair < max_i))
{
lastPair = max_i;
}
for(long long i = firstPair; i <= lastPair; i++)
{
int copyCharactersFromPrevious = k;
if((copyCharactersFromPrevious > resolved_noGaps.first.length()) || (copyCharactersFromPrevious > resolved_noGaps.second.length()))
{
copyCharactersFromPrevious = (resolved_noGaps.first.length() < resolved_noGaps.second.length()) ? resolved_noGaps.first.length() : resolved_noGaps.second.length() ;
}
std::string previous_first = resolved_noGaps.first.substr(resolved_noGaps.first.length() - copyCharactersFromPrevious, copyCharactersFromPrevious);
std::string previous_second = resolved_noGaps.second.substr(resolved_noGaps.second.length() - copyCharactersFromPrevious, copyCharactersFromPrevious);
assert(previous_first.length() == copyCharactersFromPrevious);
assert(previous_second.length() == copyCharactersFromPrevious);
assert(previous_first == previous_second);
std::string seq_evaluate_1 = previous_first + openPairs.at(i).first;
std::string seq_evaluate_2 = previous_second + openPairs.at(i).second;
double O = evaluateSequence(seq_evaluate_1) + evaluateSequence(seq_evaluate_2);
optimality.at(i) = O;
}
}
double maxOptimality; size_t whereOptimality;
for(size_t i = 0; i < optimality.size(); i++)
{
if((i == 0) || (maxOptimality < optimality.at(i)))
{
maxOptimality = optimality.at(i);
whereOptimality = i;
}
}
resolved.first.append(openPairs.at(whereOptimality).first);