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 count, string tax, float c, string t, bool l){
18 m = MothurOut::getInstance();
27 /***********************************************************************/
29 SplitMatrix::SplitMatrix(string ffile, string name, string count, string tax, float c, float cu, string t, int p, bool cl, string output){
30 m = MothurOut::getInstance();
35 cutoff = c; //tax level cutoff
36 distCutoff = cu; //for fasta method if you are creating distance matrix you need a cutoff for that
43 /***********************************************************************/
45 int SplitMatrix::split(){
48 if (method == "distance") {
50 }else if ((method == "classify") || (method == "fasta")) {
53 m->mothurOut("Unknown splitting method, aborting split."); m->mothurOutEndLine();
54 map<string, string> temp;
55 if (namefile != "") { temp[distFile] = namefile; }
56 else { temp[distFile] = countfile; }
57 dists.push_back(temp);
63 m->errorOut(e, "SplitMatrix", "split");
67 /***********************************************************************/
68 int SplitMatrix::splitDistance(){
71 if (large) { splitDistanceLarge(); }
72 else { splitDistanceRAM(); }
78 m->errorOut(e, "SplitMatrix", "splitDistance");
83 /***********************************************************************/
84 int SplitMatrix::splitClassify(){
88 map<string, int> seqGroup;
89 map<string, int>::iterator it;
90 map<string, int>::iterator it2;
94 //build tree from users taxonomy file
95 PhyloTree* phylo = new PhyloTree();
97 map<string, string> temp;
98 m->readTax(taxFile, temp);
100 for (map<string, string>::iterator itTemp = temp.begin(); itTemp != temp.end();) {
101 phylo->addSeqToTree(itTemp->first, itTemp->second);
102 temp.erase(itTemp++);
105 phylo->assignHeirarchyIDs(0);
107 //make sure the cutoff is not greater than maxlevel
108 if (cutoff > phylo->getMaxLevel()) { m->mothurOut("splitcutoff is greater than the longest taxonomy, using " + toString(phylo->getMaxLevel())); m->mothurOutEndLine(); cutoff = phylo->getMaxLevel(); }
110 //for each node in tree
111 for (int i = 0; i < phylo->getNumNodes(); i++) {
113 //is this node within the cutoff
114 TaxNode taxon = phylo->get(i);
116 if (taxon.level == cutoff) {//if yes, then create group containing this nodes sequences
117 if (taxon.accessions.size() > 1) { //if this taxon just has one seq its a singleton
118 for (int j = 0; j < taxon.accessions.size(); j++) {
119 seqGroup[taxon.accessions[j]] = numGroups;
128 if (method == "classify") {
129 splitDistanceFileByTax(seqGroup, numGroups);
131 createDistanceFilesFromTax(seqGroup, numGroups);
137 catch(exception& e) {
138 m->errorOut(e, "SplitMatrix", "splitClassify");
142 /***********************************************************************/
143 int SplitMatrix::createDistanceFilesFromTax(map<string, int>& seqGroup, int numGroups){
145 map<string, int> copyGroups = seqGroup;
146 map<string, int>::iterator it;
149 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
150 m->mothurRemove((fastafile + "." + toString(i) + ".temp"));
154 m->openInputFile(fastafile, in);
159 Sequence query(in); m->gobble(in);
160 if (query.getName() != "") {
162 it = seqGroup.find(query.getName());
164 //save names in case no namefile is given
165 if ((namefile == "") && (countfile == "")) { names.insert(query.getName()); }
167 if (it != seqGroup.end()) { //not singleton
168 m->openOutputFileAppend((fastafile + "." + toString(it->second) + ".temp"), outFile);
169 query.printSequence(outFile);
172 copyGroups.erase(query.getName());
178 //warn about sequence in groups that are not in fasta file
179 for(it = copyGroups.begin(); it != copyGroups.end(); it++) {
180 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();
186 //process each distance file
187 for (int i = 0; i < numGroups; i++) {
190 if (classic) { options = "fasta=" + (fastafile + "." + toString(i) + ".temp") + ", processors=" + toString(processors) + ", output=lt"; }
191 else { options = "fasta=" + (fastafile + "." + toString(i) + ".temp") + ", processors=" + toString(processors) + ", cutoff=" + toString(distCutoff); }
192 if (outputDir != "") { options += ", outputdir=" + outputDir; }
194 Command* command = new DistanceCommand(options);
199 m->mothurRemove((fastafile + "." + toString(i) + ".temp"));
201 //remove old names files just in case
202 if (namefile != "") { m->mothurRemove((namefile + "." + toString(i) + ".temp")); }
203 else { m->mothurRemove((countfile + "." + toString(i) + ".temp")); }
206 vector<string> tempDistFiles;
207 for(int i=0;i<numGroups;i++){
208 if (outputDir == "") { outputDir = m->hasPath(fastafile); }
209 string tempDistFile = "";
210 if (classic) { tempDistFile = outputDir + m->getRootName(m->getSimpleName((fastafile + "." + toString(i) + ".temp"))) + "phylip.dist";}
211 else { tempDistFile = outputDir + m->getRootName(m->getSimpleName((fastafile + "." + toString(i) + ".temp"))) + "dist"; }
212 tempDistFiles.push_back(tempDistFile);
215 splitNames(seqGroup, numGroups, tempDistFiles);
217 if (m->control_pressed) { for (int i = 0; i < dists.size(); i++) { m->mothurRemove((dists[i].begin()->first)); m->mothurRemove((dists[i].begin()->second)); } dists.clear(); }
221 catch(exception& e) {
222 m->errorOut(e, "SplitMatrix", "createDistanceFilesFromTax");
226 /***********************************************************************/
227 int SplitMatrix::splitDistanceFileByTax(map<string, int>& seqGroup, int numGroups){
229 map<string, int>::iterator it;
230 map<string, int>::iterator it2;
234 m->openInputFile(distFile, dFile);
237 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
238 m->mothurRemove((distFile + "." + toString(i) + ".temp"));
241 //for buffering the io to improve speed
242 //allow for 10 dists to be stored, then output.
243 vector<string> outputs; outputs.resize(numGroups, "");
244 vector<int> numOutputs; numOutputs.resize(numGroups, 0);
246 //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
247 //this can occur if we have converted the phylip to column, since we reduce the size at that step by using the cutoff value
248 vector<bool> validDistances; validDistances.resize(numGroups, false);
255 if (m->control_pressed) { dFile.close(); for (int i = 0; i < numGroups; i++) { m->mothurRemove((distFile + "." + toString(i) + ".temp")); } }
257 dFile >> seqA >> seqB >> dist; m->gobble(dFile);
259 //if both sequences are in the same group then they are within the cutoff
260 it = seqGroup.find(seqA);
261 it2 = seqGroup.find(seqB);
263 if ((it != seqGroup.end()) && (it2 != seqGroup.end())) { //they are both not singletons
264 if (it->second == it2->second) { //they are from the same group so add the distance
265 if (numOutputs[it->second] > 30) {
266 m->openOutputFileAppend((distFile + "." + toString(it->second) + ".temp"), outFile);
267 outFile << outputs[it->second] << seqA << '\t' << seqB << '\t' << dist << endl;
269 outputs[it->second] = "";
270 numOutputs[it->second] = 0;
271 validDistances[it->second] = true;
273 outputs[it->second] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
274 numOutputs[it->second]++;
281 string inputFile = namefile;
282 if (countfile != "") { inputFile = countfile; }
284 vector<string> tempDistFiles;
285 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
286 string tempDistFile = distFile + "." + toString(i) + ".temp";
287 tempDistFiles.push_back(tempDistFile);
288 m->mothurRemove((inputFile + "." + toString(i) + ".temp"));
290 //write out any remaining buffers
291 if (numOutputs[i] > 0) {
292 m->openOutputFileAppend((distFile + "." + toString(i) + ".temp"), outFile);
293 outFile << outputs[i];
297 validDistances[i] = true;
301 splitNames(seqGroup, numGroups, tempDistFiles);
303 if (m->control_pressed) {
304 for (int i = 0; i < dists.size(); i++) {
305 m->mothurRemove((dists[i].begin()->first));
306 m->mothurRemove((dists[i].begin()->second));
313 catch(exception& e) {
314 m->errorOut(e, "SplitMatrix", "splitDistanceFileByTax");
318 /***********************************************************************/
319 int SplitMatrix::splitDistanceLarge(){
321 vector<set<string> > groups;
323 //for buffering the io to improve speed
324 //allow for 30 dists to be stored, then output.
325 vector<string> outputs;
326 vector<int> numOutputs;
327 vector<bool> wroteOutPut;
333 m->openInputFile(distFile, dFile);
339 dFile >> seqA >> seqB >> dist;
341 if (m->control_pressed) { dFile.close(); for(int i=0;i<numGroups;i++){ if(groups[i].size() > 0){ m->mothurRemove((distFile + "." + toString(i) + ".temp")); } } return 0; }
344 //cout << "in cutoff: " << dist << endl;
349 for(int i=0;i<numGroups;i++){
350 set<string>::iterator aIt = groups[i].find(seqA);
351 set<string>::iterator bIt = groups[i].find(seqB);
353 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]
354 groups[i].insert(seqB);
358 //cout << "in aIt: " << groupID << endl;
361 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]
362 groups[i].insert(seqA);
366 // cout << "in bIt: " << groupID << endl;
370 if(groupIDA != -1 && groupIDB != -1){//both ifs above have been executed, so we need to decide who to assign them to
371 if(groupIDA < groupIDB){
372 // cout << "A: " << groupIDA << "\t" << groupIDB << endl;
373 groups[groupIDA].insert(groups[groupIDB].begin(), groups[groupIDB].end()); //merge two groups into groupIDA
374 groups[groupIDB].clear();
378 // cout << "B: " << groupIDA << "\t" << groupIDB << endl;
379 groups[groupIDB].insert(groups[groupIDA].begin(), groups[groupIDA].end()); //merge two groups into groupIDB
380 groups[groupIDA].clear();
387 //windows is gonna gag on the reuse of outFile, will need to make it local...
389 if(groupIDA == -1 && groupIDB == -1){ //we need a new group
390 set<string> newGroup;
391 newGroup.insert(seqA);
392 newGroup.insert(seqB);
393 groups.push_back(newGroup);
395 string tempOut = seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
396 outputs.push_back(tempOut);
397 numOutputs.push_back(1);
398 wroteOutPut.push_back(false);
403 string fileName = distFile + "." + toString(groupID) + ".temp";
405 //have we reached the max buffer size
406 if (numOutputs[groupID] > 60) { //write out sequence
407 outFile.open(fileName.c_str(), ios::app);
408 outFile << outputs[groupID] << seqA << '\t' << seqB << '\t' << dist << endl;
411 outputs[groupID] = "";
412 numOutputs[groupID] = 0;
413 wroteOutPut[groupID] = true;
415 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
416 numOutputs[groupID]++;
419 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
420 string row, column, distance;
421 if(groupIDA<groupIDB){
424 numOutputs[groupID] += numOutputs[groupIDB];
425 outputs[groupID] += outputs[groupIDB];
427 outputs[groupIDB] = "";
428 numOutputs[groupIDB] = 0;
430 //if groupB is written to file it is above buffer size so read and write to new merged file
431 if (wroteOutPut[groupIDB]) {
432 string fileName2 = distFile + "." + toString(groupIDB) + ".temp";
433 ifstream fileB(fileName2.c_str(), ios::ate);
435 outFile.open(fileName.c_str(), ios::app);
440 size = fileB.tellg();
442 fileB.seekg (0, ios::beg);
444 int numRead = size / 1024;
445 int lastRead = size % 1024;
447 for (int i = 0; i < numRead; i++) {
449 memblock = new char [1024];
451 fileB.read (memblock, 1024);
453 string temp = memblock;
454 outFile << temp.substr(0, 1024);
459 memblock = new char [lastRead];
461 fileB.read (memblock, lastRead);
463 //not sure why but it will read more than lastRead char...??
464 string temp = memblock;
465 outFile << temp.substr(0, lastRead);
469 m->mothurRemove(fileName2);
471 //write out the merged memory
472 if (numOutputs[groupID] > 60) {
473 outFile << outputs[groupID];
474 outputs[groupID] = "";
475 numOutputs[groupID] = 0;
480 wroteOutPut[groupID] = true;
481 wroteOutPut[groupIDB] = false;
482 }else{ } //just merge b's memory with a's memory
485 numOutputs[groupID] += numOutputs[groupIDA];
486 outputs[groupID] += outputs[groupIDA];
488 outputs[groupIDA] = "";
489 numOutputs[groupIDA] = 0;
491 if (wroteOutPut[groupIDA]) {
492 string fileName2 = distFile + "." + toString(groupIDA) + ".temp";
493 ifstream fileB(fileName2.c_str(), ios::ate);
495 outFile.open(fileName.c_str(), ios::app);
500 size = fileB.tellg();
502 fileB.seekg (0, ios::beg);
504 int numRead = size / 1024;
505 int lastRead = size % 1024;
507 for (int i = 0; i < numRead; i++) {
509 memblock = new char [1024];
511 fileB.read (memblock, 1024);
512 string temp = memblock;
513 outFile << temp.substr(0, 1024);
518 memblock = new char [lastRead];
520 fileB.read (memblock, lastRead);
522 //not sure why but it will read more than lastRead char...??
523 string temp = memblock;
524 outFile << temp.substr(0, lastRead);
529 m->mothurRemove(fileName2);
531 //write out the merged memory
532 if (numOutputs[groupID] > 60) {
533 outFile << outputs[groupID];
534 outputs[groupID] = "";
535 numOutputs[groupID] = 0;
540 wroteOutPut[groupID] = true;
541 wroteOutPut[groupIDA] = false;
542 }else { } //just merge memory
551 vector<string> tempDistFiles;
552 for (int i = 0; i < numGroups; i++) {
553 string fileName = distFile + "." + toString(i) + ".temp";
554 tempDistFiles.push_back(fileName);
555 //remove old names files just in case
557 if (numOutputs[i] > 0) {
558 outFile.open(fileName.c_str(), ios::app);
559 outFile << outputs[i];
564 map<string, int> seqGroup;
565 for (int i = 0; i < groups.size(); i++) {
566 for (set<string>::iterator itNames = groups[i].begin(); itNames != groups[i].end();) {
567 seqGroup[*itNames] = i;
568 groups[i].erase(itNames++);
572 splitNames(seqGroup, numGroups, tempDistFiles);
576 catch(exception& e) {
577 m->errorOut(e, "SplitMatrix", "splitDistanceLarge");
581 //********************************************************************************************************************
582 int SplitMatrix::splitNames(map<string, int>& seqGroup, int numGroups, vector<string>& tempDistFiles){
585 map<string, int>::iterator it;
587 string inputFile = namefile;
588 if (countfile != "") { inputFile = countfile; }
590 for(int i=0;i<numGroups;i++){ m->mothurRemove((inputFile + "." + toString(i) + ".temp")); }
592 singleton = inputFile + ".extra.temp";
593 ofstream remainingNames;
594 m->openOutputFile(singleton, remainingNames);
596 bool wroteExtra = false;
598 ifstream bigNameFile;
599 m->openInputFile(inputFile, bigNameFile);
603 if (countfile != "") { headers = m->getline(bigNameFile); m->gobble(bigNameFile); }
605 string name, nameList;
606 while(!bigNameFile.eof()){
607 bigNameFile >> name >> nameList;
608 m->getline(bigNameFile); m->gobble(bigNameFile); //extra getline is for rest of countfile line if groups are given.
610 //did this sequence get assigned a group
611 it = seqGroup.find(name);
613 if (it != seqGroup.end()) {
614 m->openOutputFileAppend((inputFile + "." + toString(it->second) + ".temp"), outFile);
615 outFile << name << '\t' << nameList << endl;
619 remainingNames << name << '\t' << nameList << endl;
624 for(int i=0;i<numGroups;i++){
625 string tempNameFile = inputFile + "." + toString(i) + ".temp";
626 string tempDistFile = tempDistFiles[i];
628 //if there are valid distances
630 fileHandle.open(tempDistFile.c_str());
632 m->gobble(fileHandle);
633 if (!fileHandle.eof()) { //check
634 map<string, string> temp;
635 if (countfile != "") {
638 string newtempNameFile = tempNameFile + "2";
639 m->openOutputFile(newtempNameFile, out);
640 out << headers << endl;
642 m->appendFiles(tempNameFile, newtempNameFile);
643 m->mothurRemove(tempNameFile);
644 m->renameFile(newtempNameFile, tempNameFile);
646 temp[tempDistFile] = tempNameFile;
647 dists.push_back(temp);
650 m->openInputFile(tempNameFile, in);
653 in >> name >> nameList; m->gobble(in);
655 remainingNames << name << '\t' << nameList << endl;
658 m->mothurRemove(tempNameFile);
664 remainingNames.close();
667 m->mothurRemove(singleton);
669 }else if (countfile != "") {
672 string newtempNameFile = singleton + "2";
673 m->openOutputFile(newtempNameFile, out);
674 out << headers << endl;
676 m->appendFiles(singleton, newtempNameFile);
677 m->mothurRemove(singleton);
678 m->renameFile(newtempNameFile, singleton);
683 catch(exception& e) {
684 m->errorOut(e, "SplitMatrix", "splitNames");
688 //********************************************************************************************************************
689 int SplitMatrix::splitDistanceRAM(){
691 vector<set<string> > groups;
692 vector<string> outputs;
697 m->openInputFile(distFile, dFile);
703 dFile >> seqA >> seqB >> dist;
705 if (m->control_pressed) { dFile.close(); for(int i=0;i<numGroups;i++){ if(groups[i].size() > 0){ m->mothurRemove((distFile + "." + toString(i) + ".temp")); } } return 0; }
708 //cout << "in cutoff: " << dist << endl;
713 for(int i=0;i<numGroups;i++){
714 set<string>::iterator aIt = groups[i].find(seqA);
715 set<string>::iterator bIt = groups[i].find(seqB);
717 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]
718 groups[i].insert(seqB);
722 //cout << "in aIt: " << groupID << endl;
725 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]
726 groups[i].insert(seqA);
730 // cout << "in bIt: " << groupID << endl;
734 if(groupIDA != -1 && groupIDB != -1){//both ifs above have been executed, so we need to decide who to assign them to
735 if(groupIDA < groupIDB){
736 // cout << "A: " << groupIDA << "\t" << groupIDB << endl;
737 groups[groupIDA].insert(groups[groupIDB].begin(), groups[groupIDB].end()); //merge two groups into groupIDA
738 groups[groupIDB].clear();
742 // cout << "B: " << groupIDA << "\t" << groupIDB << endl;
743 groups[groupIDB].insert(groups[groupIDA].begin(), groups[groupIDA].end()); //merge two groups into groupIDB
744 groups[groupIDA].clear();
751 //windows is gonna gag on the reuse of outFile, will need to make it local...
753 if(groupIDA == -1 && groupIDB == -1){ //we need a new group
754 set<string> newGroup;
755 newGroup.insert(seqA);
756 newGroup.insert(seqB);
757 groups.push_back(newGroup);
759 string tempOut = seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
760 outputs.push_back(tempOut);
765 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
767 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
768 string row, column, distance;
769 if(groupIDA<groupIDB){
771 outputs[groupID] += outputs[groupIDB];
772 outputs[groupIDB] = "";
774 outputs[groupID] += outputs[groupIDA];
775 outputs[groupIDA] = "";
784 vector<string> tempDistFiles;
785 for (int i = 0; i < numGroups; i++) {
786 string fileName = distFile + "." + toString(i) + ".temp";
787 tempDistFiles.push_back(fileName);
788 if (outputs[i] != "") {
790 outFile.open(fileName.c_str(), ios::ate);
791 outFile << outputs[i];
796 map<string, int> seqGroup;
797 for (int i = 0; i < groups.size(); i++) {
798 for (set<string>::iterator itNames = groups[i].begin(); itNames != groups[i].end();) {
799 seqGroup[*itNames] = i;
800 groups[i].erase(itNames++);
804 splitNames(seqGroup, numGroups, tempDistFiles);
808 catch(exception& e) {
809 m->errorOut(e, "SplitMatrix", "splitDistanceRAM");
813 //********************************************************************************************************************
814 //sorts biggest to smallest
815 inline bool compareFileSizes(map<string, string> left, map<string, string> right){
820 //get num bytes in file
821 string filename = left.begin()->first;
822 pFile = fopen (filename.c_str(),"rb");
823 string error = "Error opening " + filename;
824 if (pFile==NULL) perror (error.c_str());
826 fseek (pFile, 0, SEEK_END);
827 leftsize=ftell (pFile);
834 //get num bytes in file
835 filename = right.begin()->first;
836 pFile2 = fopen (filename.c_str(),"rb");
837 error = "Error opening " + filename;
838 if (pFile2==NULL) perror (error.c_str());
840 fseek (pFile2, 0, SEEK_END);
841 rightsize=ftell (pFile2);
845 return (leftsize > rightsize);
847 /***********************************************************************/
848 //returns map of distance files -> namefile sorted by distance file size
849 vector< map< string, string> > SplitMatrix::getDistanceFiles(){
852 sort(dists.begin(), dists.end(), compareFileSizes);
856 catch(exception& e) {
857 m->errorOut(e, "SplitMatrix", "getDistanceFiles");
861 /***********************************************************************/
862 SplitMatrix::~SplitMatrix(){}
863 /***********************************************************************/