-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjects.cpp
1902 lines (1652 loc) · 56.3 KB
/
objects.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "objects.h"
MG_LCA::MG_LCA( string inD):
gene2Tax(0), gene2Cat(0), geneCats(0, "") , TaxLvls(0,"")
{
if (inD == "") { cerr << "path to MG_LCA is not correct!"; exit(33); }
//read in dir with .LCA files..
std::string path(inD);
std::string ext(".LCA");
struct stat sb;
if (stat(path.c_str(), &sb) != 0) {
cerr << "Path " << path << " does not exist!\n";
exit(88);
}
for (auto& p : fs::recursive_directory_iterator(path))
{
if (p.path().extension() != ext) {
continue;
}
std::cout << p.path().stem().string() << ' ';
//std::cout << p.path() << '\n';
geneCats.push_back(p.path().stem().string());
addLCA(p.path().string(), p.path().stem().string());
}
report();
}
void MG_LCA::addMGs(string in) {
std::ifstream infile(in);
if (!infile) { cerr << "Could not find -MGfile " << in << endl; return; }
std::string line;
int cnt = -1;
int fndGenes(0), newGenes(0);
vector<string> emptyTax(TaxLvls.size(), "?");
SmplOccur catCheck;
for (auto ct : geneCats) { catCheck[ct] = 1; }
while (std::getline(infile, line)) {
if (line.substr(0, 1) == "#" || line.length() == 0) {
continue;
}
//TIGR03723 165 1273130,1273131,1273132,1273133,
stringstream ss(line); string category, geneCnt, genesCSV;
getline(ss, category, '\t');
getline(ss, geneCnt, '\t');
getline(ss, genesCSV, '\t');
stringstream ss2(genesCSV);
vector<genetype> curLine(0); string segments;
while (getline(ss2, segments, ',')) {
curLine.push_back((genetype)atoi(segments.c_str()));
}
if (atoi(geneCnt.c_str()) != curLine.size()) {
cerr << category<<": Expected "<< atoi(geneCnt.c_str()) << " genes, found " << curLine.size() << endl;
}
//now transfer new info
auto catFnd = catCheck.find(category);
if (catFnd == catCheck.end()) {
cerr << "Found new MG category (unexpected)! :" << category << " .. adding\n";
geneCats.push_back(category);
}
for (auto gn : curLine) {
auto found = gene2Tax.find(gn);
if (found == gene2Tax.end()){//new gene!! add this
newGenes++;
gene2Tax[gn] = emptyTax;
gene2Cat[gn] = category;
}else {
fndGenes++;
}
}
}
infile.close();
cout << "Found " << fndGenes << " known MGs, added " << newGenes <<" marker genes"<< endl;
}
bool MG_LCA::hasTax(genetype gene,int lvl) {
assert(lvl < 7);
auto g2t = gene2Tax.find(gene);
if (g2t != gene2Tax.end() && g2t->second[lvl] != "?") {
return true;
}
return false;
}
bool MG_LCA::getTax(genetype gene, vector<string>& out, string& cls) {
auto g2t = gene2Tax.find(gene);
if (g2t != gene2Tax.end()) {
out = g2t->second;
cls = gene2Cat.find(gene)->second;
return true;
}
return false;
}
void MG_LCA::report() {
cout << "\nMarker Gene LCAs read.. Found " << gene2Tax.size() << " genes representing " << geneCats.size();
cout << " MG categories with " << TaxLvls.size() << " taxonomic levels.\n";
}
bool MG_LCA::addLCA(string in, string cat) {
std::ifstream infile(in);
if (!infile) { return false; }
std::string line;
int cnt = -1;
while (std::getline(infile, line))
{
cnt++;
std::istringstream iss(line);
//genetype a;
string catcher; vector<string> tmp;
if (cnt == 0) {
if (TaxLvls.size() == 0) {
getline(iss, catcher, '\t');
while (getline(iss ,catcher,'\t')) {
tmp.push_back(catcher);
}
TaxLvls = tmp;
}
continue;
}
if (!getline(iss, catcher, '\t')) {
cerr << "Couldn't read line: " << line<<endl;
continue;
} // error
genetype gene = (genetype)stoi(catcher);
while (getline(iss, catcher, '\t')) {
tmp.push_back(catcher);
}
gene2Tax[gene] = tmp;
gene2Cat[gene] = cat;
// process pair (a,b)
}
infile.close();
return true;
}
MFmap::MFmap(string mapF):smplRid(0), smpls(0), mapGr(0),
smplLoc(0),smplN(0),curr(0),oldFolderStructure(false)
{
stringstream ss2(mapF.c_str()); string segments;
while (getline(ss2, segments, ',')) {
string baseP = ""; //SmplOccurMult CntMapGrps ;
read_map(segments, baseP);
//read_abundances(CntMapGrps, baseP, opts->calcCoverage, opts->calcCovMedian, opts->oldMapStyle);
}
}
void MFmap::read_map(const string mapF, string& baseP) {
ifstream in;
int map2folderIdx = 0; if (oldFolderStructure) { map2folderIdx = 1; }
curr++;//keep track of different maps and inPaths
in.open(mapF.c_str());
if (!in) {
cerr << "Couldn't open mapping file " << mapF << endl;
exit(56);
}
cout << "Reading map " << mapF << endl;// " on path " << baseP[curr] << endl;
string line(""); int cnt(-1); int assGrpN(-1);
//mapping group params
int mapGrpN(-1); //bool fillMapGrp(false);
int artiCntAssGrps(0); int skSmplCol(-1);
string baseP1 = ""; string baseP2 = "";//#OutPath #RunID
//string baseP = "";
//1st part: just read headers
while (getline(in, line)) {
cnt++; int sbcnt(-1);
stringstream ss(line); string segments;
if (line.substr(0, 1) == "#") { //read column position of smpl id, path & assGrps
//if (cnt > 0) { continue; }
if (cnt == 0) {
while (getline(ss, segments, '\t')) {
sbcnt++;
if (sbcnt == 0 && segments != "#SmplID") {
cerr << "Map has to start with tag \"#SmplID\"\n"; exit(83);
}
if (sbcnt == 1 && !(segments == "Path" || segments == "SmplPrefix")) {
cerr << "Map has to have tag \"Path\" || \"SmplPrefix\" as second entry\n";
exit(83);
}
if (segments == "AssmblGrps") {
assGrpN = sbcnt;
cout << "Found Assembly groups in map\n";
}
if (segments == "MapGrps") {
mapGrpN = sbcnt;
//fillMapGrp = true;
cout << "Found Mapping groups in map\n";
}
if (segments == "ExcludeAssembly") {
skSmplCol = sbcnt;
cout << "Samples can be excluded from assembly\n";
}
}
}
while (getline(ss, segments, '\t')) {
if (segments == "#OutPath") {
getline(ss, segments, '\t'); baseP1 = segments;
}
if (segments == "#RunID") {
getline(ss, segments, '\t'); baseP2 = segments;
}
}
continue;
}
}
if (baseP2 == "") { cerr << "No #RunID specified in map!?"; exit(123); }
if (baseP1 == "") { cerr << "No #OutPath specified in map!?"; exit(123); }
baseP = baseP1 + "/" + baseP2 + "/";
//2nd part: read samples
in.clear(); // clear fail and eof bits
in.seekg(0, std::ios::beg); // back to the start!
//cnt = 0;
while (getline(in, line)) {
//cnt++;
if (line.substr(0, 1) == "#" || line.length()==0) {
continue;
}
stringstream ss(line); string segments;
vector<string> curLine(0);
while (getline(ss, segments, '\t')) {
curLine.push_back(segments);
}
if (curLine.size() == 0) { continue; }
if (skSmplCol > -1 && curLine[skSmplCol] == "1") { continue; }
string smpID = curLine[0];
if (smpID == "") { continue; }//empty sample.. skip
if (assGrpN >= 0 && curLine.size() <= assGrpN) {
curLine.resize(assGrpN + 1, "");
}
//getline(ss, segments, '\t');
//idx 1 for old folder structure, 0 for new folder structure
string subDir = curLine[map2folderIdx];
//assembly groups
string assGrp("");
if (assGrpN != -1) {
//handles assembly groups from here
assGrp = curLine[assGrpN];
}
else {//simulate CntAssGrps
assGrp = to_string(artiCntAssGrps);
artiCntAssGrps++;
}
if (CntAssGrps.find(assGrp) != CntAssGrps.end()) {
CntAssGrps[assGrp].push_back((int)smplLoc.size());
}
else {
CntAssGrps[assGrp] = vector<int>(1, (int)smplLoc.size());
}
if (assGrp != "" && CntAssGrps[assGrp].size() > 1) {
string nsmpID = smpID + "M" + std::to_string(CntAssGrps[assGrp].size());
if (smpls.find(nsmpID) != smpls.end()) {
cerr << "Double sample ID: " << nsmpID << endl;
exit(12);
}
smpls[nsmpID] = CntAssGrps[assGrp];//(int)smplLoc.size();
smplRid[nsmpID] = smpID;
smplAltId[smpID] = nsmpID;
} else {
if (smpls.find(smpID) != smpls.end()) {
cerr << "Double sample ID: " << smpID << endl;
exit(12);
}
smpls[smpID] = vector<int>(1, (int)smplLoc.size());
smplRid[smpID] = smpID;
smplAltId[smpID] = smpID;
}
assmblGr.push_back(assGrp);
//mapping groups
string mapGrp("");
if (mapGrpN != -1) {
mapGrp = curLine[mapGrpN];
}
if (mapGrp != "" && CntMapGrps.find(mapGrp) != CntMapGrps.end()) {
(CntMapGrps)[mapGrp].push_back((int)smplLoc.size());
}
else if (mapGrp != "") {
(CntMapGrps)[mapGrp] = vector<int>(1, (int)smplLoc.size());
}
mapGr.push_back(mapGrp);
//useSmpl.push_back(true);
smplLoc.push_back(baseP + "/" + subDir + "/");
smplIDs.push_back(smpID);
}
in.close();
smplN = smplLoc.size();
cout << "read Map with " << smplN << " samples\n";
//getAllSmpls(true, true); int x = 0;//DEBUG
}
float MAG::LCAscore2(SmplOccur& taxs, string& bester, int minAssigns) {
float hiSc (0), totSc(0), qCnt(0);
bester = "";
float ret (0.f);
for (auto tx : taxs) {
//completely ignore "?" cats..
if (tx.first == "?") { continue; }// qCnt += (float)tx.second;}
totSc +=(float) tx.second;
if (tx.second > (float)hiSc) {
hiSc = (float)tx.second;
bester = tx.first;
}
}
//needs to have enough evidence..
if (totSc >= (float)minAssigns) {
ret = hiSc / (totSc- qCnt);
}
if (qCnt > 5.f && totSc < float(minAssigns)) {
ret = 1.f;//well at least consistent for "unknown"..
bester = "?";
}
return ret;
}
void MAG::getTopTaxa(int lvl, float& frac, string& nm) {
frac = LCAscores[lvl];
nm = majorityTax[lvl];
/*SmplOccur tmp;
tmp = TaxAssignments[lvl];
float hiCnt(0.f); float totalC(0.f); string hiTax("");
float qCnt(0.f);
for (auto tax : tmp) {
totalC += (float)tax.second;
if (tax.first == "?") {
qCnt += (float)tax.second;
} else if (tax.second > hiCnt) {
hiCnt = (float) tax.second; hiTax = tax.first;
}
}
nm = hiTax;
frac = hiCnt / (totalC - qCnt);
*/
}
void MAG::calcLCAscore(MG_LCA* lca,options* opts) {
vector<string> dummy; string cls;
if (TaxAssignments.size() == 0) {
TaxAssignments.resize(lca->maxTaxLvl());
majorityTax.resize(lca->maxTaxLvl(),"");
LCAscores.resize(lca->maxTaxLvl(),-1.f);
}
for (auto gn : genes) {
genetype gene = gn.first;
if (lca->getTax(gene, dummy, cls)) {
//genus level assignments of gene
for (size_t k = 0; k < lca->maxTaxLvl(); k++) {
auto genf = TaxAssignments[k].find(dummy[k]);
if (genf != TaxAssignments[k].end()) {
genf->second++;
}else { TaxAssignments[k][dummy[k]] = 1; }
}
gn.second = true;
foundMGs++;
auto mgfnd = markerGenes.find(gene);
if (mgfnd == markerGenes.end()) { markerGenes[gene] = 1; }
else { mgfnd->second++; }
auto g2cl = mkgene2type.find(cls);
if (g2cl == mkgene2type.end()) {
mkgene2type[cls] = vector<genetype>(1, gene);
}
else {
g2cl->second.push_back(gene);
}
}
}
int minAssigns = opts->minMGassigned2tax;
//calc actual score by best hit
for (size_t k = 0; k < lca->maxTaxLvl(); k++) {
string tmp("");
LCAscores[k] = LCAscore2(TaxAssignments[k], tmp, minAssigns);
majorityTax[k] = tmp;
}
//genLCAscore = LCAscore2(TaxAssignments[5]);
}
vector<string> MFmap::getAllSmpls(bool onlyAssmbled, bool assmGrpID ) {
if (!onlyAssmbled && !assmGrpID) {
return smplIDs;
}
SmplOccur currCntAsGr;// = map->getAssmGrpCnts();
vector<string> ret;
for (size_t i = 0; i < smplIDs.size(); i++) {
string assmblGrp = getAssmblGrp(i);
if (onlyAssmbled && assmblGrp != "") {
SmplOccurIT cMGcnts = currCntAsGr.find(assmblGrp);
if (cMGcnts == currCntAsGr.end()) {
currCntAsGr[assmblGrp] = 1;
}
else { (*cMGcnts).second++; }
if (AssmblGrpSize(assmblGrp) != (uint)currCntAsGr[assmblGrp]) {
continue;
}
}
if (assmGrpID) {
ret.push_back(smplAltId[smplIDs[i]]);
}
}
//DEBUG
//for (auto smpl : ret) { cout << "\""<< smpl << "\"" << endl; }//exit(0);
return ret;
}
void MAG::storeBestHit(float bestMtchFrac, MGS* matchMGS, float uniq) {
bestMatchFrac = bestMtchFrac;
uniqFrac = uniq;
if (matchMGS==nullptr){
bestMGS = "";
} else {
bestMGS = matchMGS->getID();
}
}
int MAG::hitGenes(geneCnter& x) {
int ret = 0;
for (auto zz : x) {
if (genes.find(zz.first) != genes.end()) {
ret++;
}
}
return ret;
}
void MAG::assignTier(options* op) {
int maxTierRds = op->maxTier();
selfTier = 100;
for (uint T = 0; T < maxTierRds; T++) {
if (getComple() > op->complTiers[T] && getConta() < op->contaTiers[T]
&& (LCAscores.size()==0 || LCAscores[6] < 0 || LCAscores[6] > op->LCAcomplTier[T])
) {
selfTier = T;
break;
}
}
}
float MAG::MGoverlap(MAG* other) {
if (markerGenes.size() == 0) { return 0.f; }
int shrdGenes = other->hitGenes(markerGenes);
return shrdGenes / (float)markerGenes.size();
}
//case for Canopies: we don't have info on ctgs..
void MAG::setGenes(vector<genetype> x) {
assert(genes.size() == 0);
for (auto g : x) {
genes[g] = false;
}
vector < pair<int, genetype> > yy (x.size());
for (int i = 0; i < (int)x.size(); i++) {
yy[i] = pair<int, genetype>(i, x[i]);
}
ctg2Gene["Ctg???"] = yy;
foundGenes = genes.size();
}
void MAG::addGene(genetype Gn, string Ctg,int num){
auto found = ctg2Gene.find(Ctg);
if (found == ctg2Gene.end()) {
ctg2Gene[Ctg] = vector< pair<int, genetype >>(1, pair<int,genetype>(num,Gn));
} else {
found->second.push_back(pair<int, genetype>(num, Gn));
}
auto f2 = genes.find(Gn);
if (f2 == genes.end()){
genes[Gn] = false;
}
foundGenes++;
}
float MAG::compoundScore(int maxGenes, int maxN50) {
compndScore = 0.f; float cnter(0.f);
compndScore += (getComple()/100.f); cnter+=1.f;//
if (getLCAscore() >= 0.f) {
compndScore += ((getLCAscore() + getLCAscore(5)) / 2.f); cnter += 1.f;
}
if (maxGenes > 0 && maxN50 > 0) {
compndScore += float(foundGenes / maxGenes) + float(ctg_N50 / maxN50) / 2.f; cnter += 1.f;
}
compndScore -= (2.f * cnter * getConta() / 100.f);
compndScore /= cnter;
return compndScore;
}
string MAG::getAssignedMGSname(bool retAlt) {
if (retAlt) {
if (altMGShits == nullptr) { return ""; }
return altMGShits->getID();
} else {
if (mgsAssign == nullptr) { return ""; }
return mgsAssign->getID();
}
}
string MAG::printMGbyCat(vector<string>& cats) {
string str;
for (string cat : cats) {
auto found = mkgene2type.find(cat);
if (found == mkgene2type.end()) {
str += "\t";
} else {
str += to_string(found->second[0]);
for (size_t ii = 1; ii < found->second.size(); ii++) {
str += "," + to_string(found->second[ii]);
}
str += "\t";
}
}
return str;
}
string MAG::printGenes(bool includeMGs ) {
string outStr = "";
for (auto ctg : ctg2Gene) {
vector< pair<int, genetype>> gens = ctg.second;
sort(gens.begin(), gens.end(), [](const pair<int, genetype>& a, const pair<int, genetype>& b) { return(a.first < b.first); });
int lastG(0);
for (auto gg:gens){
int diff = gg.first- lastG;
for (int x = 0; x < (diff-1); x++) {
outStr += "?,";
}
if (!includeMGs && genes.find(gg.second)->second) {
outStr += "?,";//do nothing..
}else {
outStr += to_string(gg.second) + ",";
}
lastG = gg.first;
//break;//DEBUG
}
outStr += ",";
//break;
}
outStr = outStr.substr(0, (outStr.length() - 2));
return outStr ;
}
string MAG::formatMAG(vector<string>& cats, MG_LCA* lcaL, bool isCtr, bool MGs_with_others) {
stringstream of;
//MAG\tMGS\tRepresentative4MGS\tMatch2MGS\tUniqueness\tAssociatedMGS\tCompleteness
//bool MGs_with_others(true);if (cats.size() > 0) { MGs_with_others = false; }
of << getUniqName() << "\t" << getAssignedMGSname(false) << "\t";
if (isCtr) { of << "*\t"; }else { of << "\t"; }//centre of MAG?
of << MGSmatch << "\t" << uniqScore << "\t" << getAssignedMGSname(true) << "\t";
of << getComple() << "\t" << getConta() << "\t" << getLCAscore() << "\t" << getN50();
of << "\t" << getFoundGenes(0) << "\t" << getGC() << "\t" << getCodingDens();
of << "\t" << getCentreScore() << "\t" << getCompoundScore() << "\t";
//add tax here
size_t sizTax = lcaL->getTaxLvls().size();
if (majorityTax.size() == sizTax) {
for (size_t x = 0; x < majorityTax.size(); x++) {
of << majorityTax[x] << "\t";
}
}
else {
for (size_t x = 0; x < sizTax; x++) {//just inserrt empty
of << "\t";
}
}
if (cats.size()>0) {
of<<printMGbyCat(cats);
}
of << printGenes(MGs_with_others) ;
return of.str();
}
MAGs::MAGs(MFmap* map,options* opt):
smplN(0), MGSs(0), maxTier(opt->maxTier()), opts(opt), lcaO(nullptr)
{
string path2Bins = opts->path2Bins;
string path2Assmbl = opts->path2Assmbl;
string file2Assmbl = opts->file2Assmbl;
smplN = map->totalSmpls();
string qualSuffix = opts->qualSuffix;
uint geneN = 0;
uint preMapSize(smplN);
cout << "Reading Bins from " << smplN << " samples\n";
//read the gene abundances sample-wise in
SmplOccur currCntAsGr;// = map->getAssmGrpCnts();
uint smplsIncl = 0;
for (uint i = 0; i < smplN; i++) {
smplsIncl++;
//only include last sample of mapping group..
string assmblGrp = map->getAssmblGrp(i);
if (assmblGrp != "") {
SmplOccurIT cMGcnts = currCntAsGr.find(assmblGrp);
if (cMGcnts == currCntAsGr.end()) {currCntAsGr[assmblGrp] = 1;
}else {(*cMGcnts).second++;}
if (map->AssmblGrpSize(assmblGrp) == (uint)currCntAsGr[assmblGrp]) {
string gFile(map->SmplPath(i) + path2Assmbl + path2Bins + map->SmplIds(i));
if (!file_exists(gFile)) {
gFile = map->SmplPath(i) + path2Assmbl + file2Assmbl;
if (file_exists(gFile)) {
ifstream inf(gFile); getline(inf, gFile);
gFile += path2Bins + map->SmplIds(i);
}
}
//cout << "Assmgrp:"<<gFile << endl;
cout << "Assmgrp:";
readBinnerOut(gFile, gFile + qualSuffix, map->SmplIdsAlt(i));
}
}
else {
string gFile(map->SmplPath(i) + path2Assmbl + path2Bins + map->SmplIds(i));
//cout << gFile << endl;
readBinnerOut(gFile, gFile + qualSuffix, map->SmplIds(i));
}
}
cout << "Including " << smplsIncl << " samples\n";// , using "<< geneN<<" genes\n";
}
MAGs::~MAGs() {
for (auto mag : MAGlist) {
delete mag.second;
}
}
bool MAGs::readBinnerOut(string bFile, string qFile, string sample) {
std::ifstream infile(bFile);
if (!infile) {
cerr << "Could not find bin file " << bFile << endl;
return false;
}
std::string line;
int cnt = 0; int binCnt(0);
string lastBin = ""; vector<string> contigs;
MAGlst locMAGlist;
//vector<string> bins;//DEBUG
while (std::getline(infile, line)) {
cnt++;
std::istringstream iss(line);
string ctg, bin;
if (!(iss >> ctg >> bin)) { continue; }
if (bin != lastBin) {
if (lastBin != "") {//create this bin..
string uniID = sample + "__" + lastBin;
auto res = locMAGlist.find(uniID);
if (res == locMAGlist.end()) {
locMAGlist[uniID] = new MAG(lastBin, sample, contigs);
binCnt++;
}
else {
cerr << "MAG uniq ID: " << uniID << " was found twice!!";
}
//bins.push_back(lastBin);//DEBUG
}
lastBin = bin; contigs.clear();
}
size_t pos = ctg.find("__");
if (pos != std::string::npos) {
contigs.push_back(ctg.substr(pos + 2));
}
else {
cerr << "Wrongly formatted contig:" << ctg << endl;
}
//contigs.push_back(ctg);
}
//remaining Bin..
if (lastBin != "") {
locMAGlist[(sample + "__" + lastBin)] = new MAG(lastBin, sample, contigs);
binCnt++;
}
infile.close();
readMAGqual(qFile, sample, locMAGlist);
//now transfer into big list..
int passed(0); int passedContig(0);
for (auto MG : locMAGlist) {
if (opts->processOnlyHQ) { MG.second->assignTier(opts); }
else { MG.second->assignTier((uint)0); }
if ( passTier(MG.second)) { passed++; passedContig += MG.second->NContigs(); }
MAGlist[MG.first] = MG.second;
}
cout << sample << ":: passed " << passed<< "/" << binCnt << " MAGs with " << passedContig <<"/" << cnt << " contigs total.\n";
return true;
}
bool MAGs::readMAGqual(const string& qFile, string& sample, MAGlst& locMAGlist){
ifstream infile(qFile);
if (!infile) { cerr << "Could not open " << qFile << " !"; }
vector<string> inTmp(20, "");
bool isCM2(true);
float Conta, Compl, GC, codingDens;
int Ngenes, GenomeSize, N50;
string bin; string line; int cnt(0);
while (std::getline(infile, line)) {
cnt++;
std::istringstream iss(line);
string tmp; size_t cc = 0;
while (getline(iss, tmp,'\t')) {
inTmp[cc] = tmp;
cc++;
if (cc > 19) { break; }
}
if (inTmp[0] == "Name") { continue; }//header in .cm2 file..
if (isCM2) {
if (cc < 2) { cerr << "On .cm2 line:\n" << line << "\nless than 2 elements were found!\nAborting\n"; exit(61); }
bin = inTmp[0];
string uniID = sample + "__" + bin;
auto res = locMAGlist.find(uniID);
if (res == locMAGlist.end()) {
cerr << "Could not find MAG " << uniID << " in ref Bin! Cannot add qual info.\n";
continue;
}
Compl = atof(inTmp[1].c_str());
Conta = atof(inTmp[2].c_str());
res->second->setCompl(Compl); res->second->setConta(Conta);
if (cc > 5) {
GC = atof(inTmp[9].c_str());
Ngenes = atoi(inTmp[10].c_str());
GenomeSize = atoi(inTmp[8].c_str());
codingDens = atof(inTmp[5].c_str());
N50 = atoi(inTmp[6].c_str());
res->second->setGC(GC); res->second->setN50(N50);
res->second->setNgenes(Ngenes); res->second->setGenomeSize(GenomeSize);
res->second->setcodingDens(codingDens);
}
}
}
infile.close();
return true;
}
void MAGs::readCanopies() {
string inF1 = opts->canopyFile;
if (inF1 == "") { return; }
string qFile = inF1 + ".cm2";
ifstream in(inF1.c_str());
if (!in) { cerr << "Could not open canpy file : " << inF1; exit(523); }
std::string line;
int cnt = -1; int binCnt(0);
string lastBin = ""; vector<genetype> genes;
MAGlst locMAGlist;
//vector<string> bins;//DEBUG
string sample("Cano");
vector<string>emptyVec(0, "");
while (std::getline(in, line)) {
cnt++;
std::istringstream iss(line);
string bin;
genetype gene;
if (!(iss >> bin >> gene)) { continue; }
if (bin != lastBin) {
if (lastBin != "") {//create this bin..
string uniID = sample + "__" + lastBin;
auto res = locMAGlist.find(uniID);
if (res == locMAGlist.end()) {
MAG* cano = new MAG(lastBin, sample, emptyVec);
cano->setCanopy(true); cano->setGenes(genes);
cano->setGC(-1);
cano->setN50(1000);//some average gene size
locMAGlist[uniID] = cano;
binCnt++;
}
else {
cerr << "MAG uniq ID: " << uniID << " was found twice!!";
}
//bins.push_back(lastBin);//DEBUG
}
lastBin = bin; genes.clear();
}
genes.push_back(gene);
//contigs.push_back(ctg);
}
//remaining Bin..
MAG* cano = new MAG(lastBin, sample, emptyVec);
cano->setCanopy(true); cano->setGenes(genes);
locMAGlist[(sample + "__" + lastBin)] = cano;
//bins.push_back(lastBin);//DEBUG
binCnt++;
in.close();
readMAGqual(qFile, sample, locMAGlist);
//now transfer into big list..
int passed(0), passedGenes(0);
for (auto MG : locMAGlist) {
if (opts->processOnlyHQ) { MG.second->assignTier(opts); }
else { MG.second->assignTier((uint)0); }
if (passTier(MG.second)) { passed++; passedGenes += MG.second->NGenes(); }
MAGlist[MG.first] = MG.second;
}
cout << sample << ":: passed " << passed<< "/" << binCnt << " MGS with " << passedGenes<<"/" <<cnt << " genes total.\n";
}
void MAGs::reportMGS() {
float avgMAGsInMGS(0.f);
float avgUni(0.f), avgUniAll(0.f);
for (auto mgs : MGSs) {
avgMAGsInMGS+=(float)mgs->size();
avgUni += mgs->getUniqness(0);
avgUniAll += mgs->getUniqness(2);
}
int totMAGs = (int)avgMAGsInMGS;
avgMAGsInMGS /= (float)MGSs.size();
avgUni /= (float)MGSs.size();
avgUniAll /= (float)MGSs.size();
//calc how many MAGs are without match
int mgsMAG(0), badMAG(0);
vector<int> goodMAG(maxTier, 0);
for (auto mag : MAGlist) {
if (mag.second == nullptr || mag.second->getAssignedMGS() != nullptr) {
mgsMAG++;
continue;
}
if (passTier(mag.second)) {
goodMAG[mag.second->qualTier()]++;
} else {
badMAG++;
}
}
cout << "\n\n-----------------------------------------------------------------\n";
cout << "Found " << MGSs.size() << " MGS with " << totMAGs << " MAGs (avg " << round(avgMAGsInMGS * 100) / 100 << " MAGs/MGS).\n";
cout << round(avgUni * 100) / 100 << "/" << round(avgUniAll * 100) / 100 << " avg MG/ALL Uniqueness.\n";
cout << mgsMAG << " MAGs in MGS, unassigned ";
string goodMAGstr1(to_string(goodMAG[0])); string goodMAGstr2("T0"); int goodSum(0);
for (int i = 1; i < maxTier; i++) {
goodMAGstr1 += "," + to_string(goodMAG[i]);
goodMAGstr2 += ",T" + to_string(i);
goodSum += goodMAG[i];
}
cout << goodSum << " ("<<goodMAGstr1 << " in " << goodMAGstr2 << ") high qual MAGs";
cout<< " and " << badMAG << " low qual MAGs.\n";
cout << "-----------------------------------------------------------------\n\n";
}
void MAGs::report() {
float avgGenesFnd(0.f), avgGenesExpec(0.f), avgCont(0.f),avgComp(0.f);
float avgMGgenes(0.f), avgLCA(0.f), avgLCAg(0.f);
float cnt(0);
int LCAmiss(0);
for (auto mag : MAGlist) {
avgGenesFnd += (float)mag.second->getFoundGenes();
avgGenesExpec += (float)mag.second->getFoundGenes(false);
avgCont += (float)mag.second->getConta();
avgComp += (float)mag.second->getComple();
float MGgenes = (float)mag.second->getFoundGenes(2);
float lcaloc = (float)mag.second->getLCAscore();
if (MGgenes == 0.f) { LCAmiss++;
} else {
avgLCA += lcaloc;
avgLCAg += (float)mag.second->getLCAscore(5);
avgMGgenes += MGgenes;
}
cnt += 1.f;
}
avgGenesFnd /= cnt; avgCont /= cnt; avgGenesExpec /= cnt;
avgComp /= cnt;
avgLCA /= (cnt- LCAmiss); avgMGgenes /= (cnt - LCAmiss); avgLCAg /= (cnt - LCAmiss);
cout << "Found "<< MAGlist.size() << " total MAGs across " << smplN << " Samples.\n";
cout << "These had on average:\n";
cout << " - " << avgGenesFnd << " genes asigned (" << avgGenesExpec << " expected, "<< avgMGgenes<< " MG genes)\n";
cout << " - " << avgCont << " Contamination\n";
cout << " - " << avgComp << " Completeness\n";
cout << " - " << avgLCA << " species, " << avgLCAg << " genus LCA ("<< LCAmiss<<" missing)\n";
}
void MAGs::createMAGsByCtg(MFmap* maps) {
assert(MAGsbyCtg.size() == 0);
cout << "Creating MAG by contig list..";
maxTier = opts->maxTier();
uint skippedMAGs(0), MAGkept(0);
//first create dummy samples
for (string smpl : maps->getAllSmpls(true,true)) {
MAGlst local;
MAGsbyCtg[smpl] = local;
}
//string ctg = "";
for (auto MG : MAGlist) {
if (!passTier(MG.second)) {
//cerr << MG.second->qualTier() << " ";//DEBUG
skippedMAGs++; continue;
}
MAGkept++;
string smplID = MG.second->getSmplID();
auto smplFnd = MAGsbyCtg.find(smplID);
MAGlst local;
if (smplFnd != MAGsbyCtg.end()){
local = smplFnd->second;
}
for (string ctg : MG.second->getContigs()) {
local[ctg] = MG.second;
}
//create anew
if (smplFnd == MAGsbyCtg.end()) {
MAGsbyCtg[smplID] = local;
} else {
smplFnd->second = local;
}
}
cout << "done with " <<MAGkept<< " MAGs.";
if (skippedMAGs) {
cout << " Skipped " << skippedMAGs << " MAGs due to low qual.";
}
cout << endl;
}
void MAGs::addLCAscores(MG_LCA* lcas ) {
lcaO = lcas;
cout << "Calculating LCA completeness scores..\n";
size_t lcacnt(0); int LCAassigned = 0;
for (auto mags : MAGlist) {
if (!passTier(mags.second)) { continue; }
mags.second->calcLCAscore(lcaO, opts);
if (mags.second->getLCAscore() > 0.f) { LCAassigned++; }
lcacnt++;
}
cout << "Done calculating. "<< LCAassigned<<"/"<< lcacnt << " MAGs with LCA scores. \n";
}
void MAGs::removeCtgInfo(){
MAGsbyCtg.clear();
for (auto mag : MAGlist) {