5 * Created by westcott on 5/19/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "splitmatrix.h"
11 #include "phylotree.h"
12 #include "distancecommand.h"
13 #include "seqsummarycommand.h"
15 /***********************************************************************/
17 SplitMatrix::SplitMatrix(string distfile, string name, string tax, float c, string t, bool l){
18 m = MothurOut::getInstance();
26 /***********************************************************************/
28 SplitMatrix::SplitMatrix(string ffile, string name, string tax, float c, float cu, string t, int p, string output){
29 m = MothurOut::getInstance();
33 cutoff = c; //tax level cutoff
34 distCutoff = cu; //for fasta method if you are creating distance matrix you need a cutoff for that
40 /***********************************************************************/
42 int SplitMatrix::split(){
45 if (method == "distance") {
47 }else if ((method == "classify") || (method == "fasta")) {
50 m->mothurOut("Unknown splitting method, aborting split."); m->mothurOutEndLine();
51 map<string, string> temp;
52 temp[distFile] = namefile;
53 dists.push_back(temp);
59 m->errorOut(e, "SplitMatrix", "split");
63 /***********************************************************************/
64 int SplitMatrix::splitDistance(){
67 if (large) { splitDistanceLarge(); }
68 else { splitDistanceRAM(); }
74 m->errorOut(e, "SplitMatrix", "splitDistance");
79 /***********************************************************************/
80 int SplitMatrix::splitClassify(){
84 map<string, int> seqGroup;
85 map<string, int>::iterator it;
86 map<string, int>::iterator it2;
90 //build tree from users taxonomy file
91 PhyloTree* phylo = new PhyloTree();
94 m->openInputFile(taxFile, in);
96 //read in users taxonomy file and add sequences to tree
99 in >> seqname >> tax; m->gobble(in);
100 phylo->addSeqToTree(seqname, tax);
104 phylo->assignHeirarchyIDs(0);
106 //make sure the cutoff is not greater than maxlevel
107 if (cutoff > phylo->getMaxLevel()) { m->mothurOut("splitcutoff is greater than the longest taxonomy, using " + toString(phylo->getMaxLevel())); m->mothurOutEndLine(); cutoff = phylo->getMaxLevel(); }
109 //for each node in tree
110 for (int i = 0; i < phylo->getNumNodes(); i++) {
112 //is this node within the cutoff
113 TaxNode taxon = phylo->get(i);
115 if (taxon.level == cutoff) {//if yes, then create group containing this nodes sequences
116 if (taxon.accessions.size() > 1) { //if this taxon just has one seq its a singleton
117 for (int j = 0; j < taxon.accessions.size(); j++) {
118 seqGroup[taxon.accessions[j]] = numGroups;
127 if (method == "classify") {
128 splitDistanceFileByTax(seqGroup, numGroups);
130 createDistanceFilesFromTax(seqGroup, numGroups);
136 catch(exception& e) {
137 m->errorOut(e, "SplitMatrix", "splitClassify");
141 /***********************************************************************/
142 int SplitMatrix::createDistanceFilesFromTax(map<string, int>& seqGroup, int numGroups){
144 map<string, int> copyGroups = seqGroup;
145 map<string, int>::iterator it;
148 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
149 remove((fastafile + "." + toString(i) + ".temp").c_str());
153 m->openInputFile(fastafile, in);
158 Sequence query(in); m->gobble(in);
159 if (query.getName() != "") {
161 it = seqGroup.find(query.getName());
163 //save names in case no namefile is given
164 if (namefile == "") { names.insert(query.getName()); }
166 if (it != seqGroup.end()) { //not singleton
167 m->openOutputFileAppend((fastafile + "." + toString(it->second) + ".temp"), outFile);
168 query.printSequence(outFile);
171 copyGroups.erase(query.getName());
177 //warn about sequence in groups that are not in fasta file
178 for(it = copyGroups.begin(); it != copyGroups.end(); it++) {
179 m->mothurOut("ERROR: " + it->first + " is missing from your fastafile. This could happen if your taxonomy file is not unique and your fastafile is, or it could indicate and error."); m->mothurOutEndLine();
185 //process each distance file
186 for (int i = 0; i < numGroups; i++) {
188 string options = "fasta=" + (fastafile + "." + toString(i) + ".temp") + ", processors=" + toString(processors) + ", cutoff=" + toString(distCutoff);
190 Command* command = new DistanceCommand(options);
195 remove((fastafile + "." + toString(i) + ".temp").c_str());
197 //remove old names files just in case
198 remove((namefile + "." + toString(i) + ".temp").c_str());
201 singleton = namefile + ".extra.temp";
202 ofstream remainingNames;
203 m->openOutputFile(singleton, remainingNames);
205 bool wroteExtra = false;
207 ifstream bigNameFile;
208 m->openInputFile(namefile, bigNameFile);
210 string name, nameList;
211 while(!bigNameFile.eof()){
212 bigNameFile >> name >> nameList; m->gobble(bigNameFile);
214 //did this sequence get assigned a group
215 it = seqGroup.find(name);
217 if (it != seqGroup.end()) {
218 m->openOutputFileAppend((namefile + "." + toString(it->second) + ".temp"), outFile);
219 outFile << name << '\t' << nameList << endl;
223 remainingNames << name << '\t' << nameList << endl;
228 for(int i=0;i<numGroups;i++){
229 string tempNameFile = namefile + "." + toString(i) + ".temp";
230 if (outputDir == "") { outputDir = m->hasPath(fastafile); }
231 string tempDistFile = outputDir + m->getRootName(m->getSimpleName((fastafile + "." + toString(i) + ".temp"))) + "dist";
233 //if there are valid distances
235 fileHandle.open(tempDistFile.c_str());
237 m->gobble(fileHandle);
238 if (!fileHandle.eof()) { //check for blank file - this could occur if all dists in group are above cutoff
239 map<string, string> temp;
240 temp[tempDistFile] = tempNameFile;
241 dists.push_back(temp);
244 m->openInputFile(tempNameFile, in);
247 in >> name >> nameList; m->gobble(in);
249 remainingNames << name << '\t' << nameList << endl;
252 remove(tempNameFile.c_str());
258 remainingNames.close();
260 remove(singleton.c_str());
264 if (m->control_pressed) { for (int i = 0; i < dists.size(); i++) { remove((dists[i].begin()->first).c_str()); remove((dists[i].begin()->second).c_str()); } dists.clear(); }
268 catch(exception& e) {
269 m->errorOut(e, "SplitMatrix", "createDistanceFilesFromTax");
273 /***********************************************************************/
274 int SplitMatrix::splitDistanceFileByTax(map<string, int>& seqGroup, int numGroups){
276 map<string, int>::iterator it;
277 map<string, int>::iterator it2;
280 m->openInputFile(distFile, dFile);
283 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
284 remove((distFile + "." + toString(i) + ".temp").c_str());
287 //for buffering the io to improve speed
288 //allow for 10 dists to be stored, then output.
289 vector<string> outputs; outputs.resize(numGroups, "");
290 vector<int> numOutputs; numOutputs.resize(numGroups, 0);
292 //you can have a group made, but their may be no distances in the file for this group if the taxonomy file and distance file don't match
293 //this can occur if we have converted the phylip to column, since we reduce the size at that step by using the cutoff value
294 vector<bool> validDistances; validDistances.resize(numGroups, false);
301 if (m->control_pressed) { dFile.close(); for (int i = 0; i < numGroups; i++) { remove((distFile + "." + toString(i) + ".temp").c_str()); } }
303 dFile >> seqA >> seqB >> dist; m->gobble(dFile);
305 //if both sequences are in the same group then they are within the cutoff
306 it = seqGroup.find(seqA);
307 it2 = seqGroup.find(seqB);
309 if ((it != seqGroup.end()) && (it2 != seqGroup.end())) { //they are both not singletons
310 if (it->second == it2->second) { //they are from the same group so add the distance
311 if (numOutputs[it->second] > 30) {
312 m->openOutputFileAppend((distFile + "." + toString(it->second) + ".temp"), outFile);
313 outFile << outputs[it->second] << seqA << '\t' << seqB << '\t' << dist << endl;
315 outputs[it->second] = "";
316 numOutputs[it->second] = 0;
317 validDistances[it->second] = true;
319 outputs[it->second] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
320 numOutputs[it->second]++;
327 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
328 remove((namefile + "." + toString(i) + ".temp").c_str());
330 //write out any remaining buffers
331 if (numOutputs[i] > 0) {
332 m->openOutputFileAppend((distFile + "." + toString(i) + ".temp"), outFile);
333 outFile << outputs[i];
337 validDistances[i] = true;
341 ifstream bigNameFile;
342 m->openInputFile(namefile, bigNameFile);
344 singleton = namefile + ".extra.temp";
345 ofstream remainingNames;
346 m->openOutputFile(singleton, remainingNames);
348 bool wroteExtra = false;
350 string name, nameList;
351 while(!bigNameFile.eof()){
352 bigNameFile >> name >> nameList; m->gobble(bigNameFile);
354 //did this sequence get assigned a group
355 it = seqGroup.find(name);
357 if (it != seqGroup.end()) {
358 m->openOutputFileAppend((namefile + "." + toString(it->second) + ".temp"), outFile);
359 outFile << name << '\t' << nameList << endl;
363 remainingNames << name << '\t' << nameList << endl;
368 for(int i=0;i<numGroups;i++){
369 string tempNameFile = namefile + "." + toString(i) + ".temp";
370 string tempDistFile = distFile + "." + toString(i) + ".temp";
372 //if there are valid distances
373 if (validDistances[i]) {
374 map<string, string> temp;
375 temp[tempDistFile] = tempNameFile;
376 dists.push_back(temp);
379 m->openInputFile(tempNameFile, in);
382 in >> name >> nameList; m->gobble(in);
384 remainingNames << name << '\t' << nameList << endl;
387 remove(tempNameFile.c_str());
391 remainingNames.close();
394 remove(singleton.c_str());
398 if (m->control_pressed) {
399 for (int i = 0; i < dists.size(); i++) {
400 remove((dists[i].begin()->first).c_str());
401 remove((dists[i].begin()->second).c_str());
408 catch(exception& e) {
409 m->errorOut(e, "SplitMatrix", "splitDistanceFileByTax");
413 /***********************************************************************/
414 int SplitMatrix::splitDistanceLarge(){
416 vector<set<string> > groups;
418 //for buffering the io to improve speed
419 //allow for 30 dists to be stored, then output.
420 vector<string> outputs;
421 vector<int> numOutputs;
422 vector<bool> wroteOutPut;
428 m->openInputFile(distFile, dFile);
434 dFile >> seqA >> seqB >> dist;
436 if (m->control_pressed) { dFile.close(); for(int i=0;i<numGroups;i++){ if(groups[i].size() > 0){ remove((distFile + "." + toString(i) + ".temp").c_str()); } } return 0; }
439 //cout << "in cutoff: " << dist << endl;
444 for(int i=0;i<numGroups;i++){
445 set<string>::iterator aIt = groups[i].find(seqA);
446 set<string>::iterator bIt = groups[i].find(seqB);
448 if(groupIDA == -1 && aIt != groups[i].end()){//seqA is not already assigned to a group and is in group[i], so assign seqB to group[i]
449 groups[i].insert(seqB);
453 //cout << "in aIt: " << groupID << endl;
456 else if(groupIDB == -1 && bIt != groups[i].end()){//seqB is not already assigned to a group and is in group[i], so assign seqA to group[i]
457 groups[i].insert(seqA);
461 // cout << "in bIt: " << groupID << endl;
465 if(groupIDA != -1 && groupIDB != -1){//both ifs above have been executed, so we need to decide who to assign them to
466 if(groupIDA < groupIDB){
467 // cout << "A: " << groupIDA << "\t" << groupIDB << endl;
468 groups[groupIDA].insert(groups[groupIDB].begin(), groups[groupIDB].end()); //merge two groups into groupIDA
469 groups[groupIDB].clear();
473 // cout << "B: " << groupIDA << "\t" << groupIDB << endl;
474 groups[groupIDB].insert(groups[groupIDA].begin(), groups[groupIDA].end()); //merge two groups into groupIDB
475 groups[groupIDA].clear();
482 //windows is gonna gag on the reuse of outFile, will need to make it local...
484 if(groupIDA == -1 && groupIDB == -1){ //we need a new group
485 set<string> newGroup;
486 newGroup.insert(seqA);
487 newGroup.insert(seqB);
488 groups.push_back(newGroup);
490 string tempOut = seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
491 outputs.push_back(tempOut);
492 numOutputs.push_back(1);
493 wroteOutPut.push_back(false);
498 string fileName = distFile + "." + toString(groupID) + ".temp";
500 //have we reached the max buffer size
501 if (numOutputs[groupID] > 60) { //write out sequence
502 outFile.open(fileName.c_str(), ios::app);
503 outFile << outputs[groupID] << seqA << '\t' << seqB << '\t' << dist << endl;
506 outputs[groupID] = "";
507 numOutputs[groupID] = 0;
508 wroteOutPut[groupID] = true;
510 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
511 numOutputs[groupID]++;
514 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
515 string row, column, distance;
516 if(groupIDA<groupIDB){
519 numOutputs[groupID] += numOutputs[groupIDB];
520 outputs[groupID] += outputs[groupIDB];
522 outputs[groupIDB] = "";
523 numOutputs[groupIDB] = 0;
525 //if groupB is written to file it is above buffer size so read and write to new merged file
526 if (wroteOutPut[groupIDB]) {
527 string fileName2 = distFile + "." + toString(groupIDB) + ".temp";
528 ifstream fileB(fileName2.c_str(), ios::ate);
530 outFile.open(fileName.c_str(), ios::app);
535 size = fileB.tellg();
537 fileB.seekg (0, ios::beg);
539 int numRead = size / 1024;
540 int lastRead = size % 1024;
542 for (int i = 0; i < numRead; i++) {
544 memblock = new char [1024];
546 fileB.read (memblock, 1024);
548 string temp = memblock;
549 outFile << temp.substr(0, 1024);
554 memblock = new char [lastRead];
556 fileB.read (memblock, lastRead);
558 //not sure why but it will read more than lastRead char...??
559 string temp = memblock;
560 outFile << temp.substr(0, lastRead);
564 remove(fileName2.c_str());
566 //write out the merged memory
567 if (numOutputs[groupID] > 60) {
568 outFile << outputs[groupID];
569 outputs[groupID] = "";
570 numOutputs[groupID] = 0;
575 wroteOutPut[groupID] = true;
576 wroteOutPut[groupIDB] = false;
577 }else{ } //just merge b's memory with a's memory
580 numOutputs[groupID] += numOutputs[groupIDA];
581 outputs[groupID] += outputs[groupIDA];
583 outputs[groupIDA] = "";
584 numOutputs[groupIDA] = 0;
586 if (wroteOutPut[groupIDA]) {
587 string fileName2 = distFile + "." + toString(groupIDA) + ".temp";
588 ifstream fileB(fileName2.c_str(), ios::ate);
590 outFile.open(fileName.c_str(), ios::app);
595 size = fileB.tellg();
597 fileB.seekg (0, ios::beg);
599 int numRead = size / 1024;
600 int lastRead = size % 1024;
602 for (int i = 0; i < numRead; i++) {
604 memblock = new char [1024];
606 fileB.read (memblock, 1024);
607 string temp = memblock;
608 outFile << temp.substr(0, 1024);
613 memblock = new char [lastRead];
615 fileB.read (memblock, lastRead);
617 //not sure why but it will read more than lastRead char...??
618 string temp = memblock;
619 outFile << temp.substr(0, lastRead);
624 remove(fileName2.c_str());
626 //write out the merged memory
627 if (numOutputs[groupID] > 60) {
628 outFile << outputs[groupID];
629 outputs[groupID] = "";
630 numOutputs[groupID] = 0;
635 wroteOutPut[groupID] = true;
636 wroteOutPut[groupIDA] = false;
637 }else { } //just merge memory
646 for (int i = 0; i < numGroups; i++) {
647 if (numOutputs[i] > 0) {
648 string fileName = distFile + "." + toString(i) + ".temp";
649 outFile.open(fileName.c_str(), ios::app);
650 outFile << outputs[i];
659 catch(exception& e) {
660 m->errorOut(e, "SplitMatrix", "splitDistanceLarge");
664 //********************************************************************************************************************
665 int SplitMatrix::splitNames(vector<set<string> >& groups){
667 int numGroups = groups.size();
669 ifstream bigNameFile(namefile.c_str());
671 cerr << "Error: We can't open the name file\n";
675 map<string, string> nameMap;
676 string name, nameList;
678 bigNameFile >> name >> nameList;
679 nameMap[name] = nameList;
680 m->gobble(bigNameFile);
684 for(int i=0;i<numGroups;i++){ //parse names file to match distance files
685 int numSeqsInGroup = groups[i].size();
687 if(numSeqsInGroup > 0){
688 string fileName = namefile + "." + toString(i) + ".temp";
689 ofstream smallNameFile(fileName.c_str(), ios::ate);
691 for(set<string>::iterator gIt=groups[i].begin();gIt!=groups[i].end();gIt++){
692 map<string,string>::iterator nIt = nameMap.find(*gIt);
693 if (nIt != nameMap.end()) {
694 smallNameFile << nIt->first << '\t' << nIt->second << endl;
697 m->mothurOut((*gIt) + " is in your distance file and not in your namefile. Please correct."); m->mothurOutEndLine(); exit(1);
700 smallNameFile.close();
704 //names of singletons
705 if (nameMap.size() != 0) {
706 singleton = namefile + ".extra.temp";
707 ofstream remainingNames(singleton.c_str(), ios::ate);
708 for(map<string,string>::iterator nIt=nameMap.begin();nIt!=nameMap.end();nIt++){
709 remainingNames << nIt->first << '\t' << nIt->second << endl;
711 remainingNames.close();
712 }else { singleton = "none"; }
714 for(int i=0;i<numGroups;i++){
715 if(groups[i].size() > 0){
716 string tempNameFile = namefile + "." + toString(i) + ".temp";
717 string tempDistFile = distFile + "." + toString(i) + ".temp";
719 map<string, string> temp;
720 temp[tempDistFile] = tempNameFile;
721 dists.push_back(temp);
725 if (m->control_pressed) {
726 for (int i = 0; i < dists.size(); i++) {
727 remove((dists[i].begin()->first).c_str());
728 remove((dists[i].begin()->second).c_str());
735 catch(exception& e) {
736 m->errorOut(e, "SplitMatrix", "splitNames");
740 //********************************************************************************************************************
741 int SplitMatrix::splitDistanceRAM(){
743 vector<set<string> > groups;
744 vector<string> outputs;
749 m->openInputFile(distFile, dFile);
755 dFile >> seqA >> seqB >> dist;
757 if (m->control_pressed) { dFile.close(); for(int i=0;i<numGroups;i++){ if(groups[i].size() > 0){ remove((distFile + "." + toString(i) + ".temp").c_str()); } } return 0; }
760 //cout << "in cutoff: " << dist << endl;
765 for(int i=0;i<numGroups;i++){
766 set<string>::iterator aIt = groups[i].find(seqA);
767 set<string>::iterator bIt = groups[i].find(seqB);
769 if(groupIDA == -1 && aIt != groups[i].end()){//seqA is not already assigned to a group and is in group[i], so assign seqB to group[i]
770 groups[i].insert(seqB);
774 //cout << "in aIt: " << groupID << endl;
777 else if(groupIDB == -1 && bIt != groups[i].end()){//seqB is not already assigned to a group and is in group[i], so assign seqA to group[i]
778 groups[i].insert(seqA);
782 // cout << "in bIt: " << groupID << endl;
786 if(groupIDA != -1 && groupIDB != -1){//both ifs above have been executed, so we need to decide who to assign them to
787 if(groupIDA < groupIDB){
788 // cout << "A: " << groupIDA << "\t" << groupIDB << endl;
789 groups[groupIDA].insert(groups[groupIDB].begin(), groups[groupIDB].end()); //merge two groups into groupIDA
790 groups[groupIDB].clear();
794 // cout << "B: " << groupIDA << "\t" << groupIDB << endl;
795 groups[groupIDB].insert(groups[groupIDA].begin(), groups[groupIDA].end()); //merge two groups into groupIDB
796 groups[groupIDA].clear();
803 //windows is gonna gag on the reuse of outFile, will need to make it local...
805 if(groupIDA == -1 && groupIDB == -1){ //we need a new group
806 set<string> newGroup;
807 newGroup.insert(seqA);
808 newGroup.insert(seqB);
809 groups.push_back(newGroup);
811 string tempOut = seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
812 outputs.push_back(tempOut);
817 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
819 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
820 string row, column, distance;
821 if(groupIDA<groupIDB){
823 outputs[groupID] += outputs[groupIDB];
824 outputs[groupIDB] = "";
826 outputs[groupID] += outputs[groupIDA];
827 outputs[groupIDA] = "";
836 for (int i = 0; i < numGroups; i++) {
837 if (outputs[i] != "") {
839 string fileName = distFile + "." + toString(i) + ".temp";
840 outFile.open(fileName.c_str(), ios::ate);
841 outFile << outputs[i];
850 catch(exception& e) {
851 m->errorOut(e, "SplitMatrix", "splitDistanceRAM");
855 //********************************************************************************************************************
856 //sorts biggest to smallest
857 inline bool compareFileSizes(map<string, string> left, map<string, string> right){
862 //get num bytes in file
863 string filename = left.begin()->first;
864 pFile = fopen (filename.c_str(),"rb");
865 string error = "Error opening " + filename;
866 if (pFile==NULL) perror (error.c_str());
868 fseek (pFile, 0, SEEK_END);
869 leftsize=ftell (pFile);
876 //get num bytes in file
877 filename = right.begin()->first;
878 pFile2 = fopen (filename.c_str(),"rb");
879 error = "Error opening " + filename;
880 if (pFile2==NULL) perror (error.c_str());
882 fseek (pFile2, 0, SEEK_END);
883 rightsize=ftell (pFile2);
887 return (leftsize > rightsize);
889 /***********************************************************************/
890 //returns map of distance files -> namefile sorted by distance file size
891 vector< map< string, string> > SplitMatrix::getDistanceFiles(){
894 sort(dists.begin(), dists.end(), compareFileSizes);
898 catch(exception& e) {
899 m->errorOut(e, "SplitMatrix", "getDistanceFiles");
903 /***********************************************************************/
904 SplitMatrix::~SplitMatrix(){}
905 /***********************************************************************/