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 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
196 Command* command = new DistanceCommand(options);
198 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
203 m->mothurRemove((fastafile + "." + toString(i) + ".temp"));
205 //remove old names files just in case
206 if (namefile != "") { m->mothurRemove((namefile + "." + toString(i) + ".temp")); }
207 else { m->mothurRemove((countfile + "." + toString(i) + ".temp")); }
210 vector<string> tempDistFiles;
211 for(int i=0;i<numGroups;i++){
212 if (outputDir == "") { outputDir = m->hasPath(fastafile); }
213 string tempDistFile = "";
214 if (classic) { tempDistFile = outputDir + m->getRootName(m->getSimpleName((fastafile + "." + toString(i) + ".temp"))) + "phylip.dist";}
215 else { tempDistFile = outputDir + m->getRootName(m->getSimpleName((fastafile + "." + toString(i) + ".temp"))) + "dist"; }
216 tempDistFiles.push_back(tempDistFile);
219 splitNames(seqGroup, numGroups, tempDistFiles);
221 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(); }
225 catch(exception& e) {
226 m->errorOut(e, "SplitMatrix", "createDistanceFilesFromTax");
230 /***********************************************************************/
231 int SplitMatrix::splitDistanceFileByTax(map<string, int>& seqGroup, int numGroups){
233 map<string, int>::iterator it;
234 map<string, int>::iterator it2;
238 m->openInputFile(distFile, dFile);
241 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
242 m->mothurRemove((distFile + "." + toString(i) + ".temp"));
245 //for buffering the io to improve speed
246 //allow for 10 dists to be stored, then output.
247 vector<string> outputs; outputs.resize(numGroups, "");
248 vector<int> numOutputs; numOutputs.resize(numGroups, 0);
250 //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
251 //this can occur if we have converted the phylip to column, since we reduce the size at that step by using the cutoff value
252 vector<bool> validDistances; validDistances.resize(numGroups, false);
259 if (m->control_pressed) { dFile.close(); for (int i = 0; i < numGroups; i++) { m->mothurRemove((distFile + "." + toString(i) + ".temp")); } }
261 dFile >> seqA >> seqB >> dist; m->gobble(dFile);
263 //if both sequences are in the same group then they are within the cutoff
264 it = seqGroup.find(seqA);
265 it2 = seqGroup.find(seqB);
267 if ((it != seqGroup.end()) && (it2 != seqGroup.end())) { //they are both not singletons
268 if (it->second == it2->second) { //they are from the same group so add the distance
269 if (numOutputs[it->second] > 30) {
270 m->openOutputFileAppend((distFile + "." + toString(it->second) + ".temp"), outFile);
271 outFile << outputs[it->second] << seqA << '\t' << seqB << '\t' << dist << endl;
273 outputs[it->second] = "";
274 numOutputs[it->second] = 0;
275 validDistances[it->second] = true;
277 outputs[it->second] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
278 numOutputs[it->second]++;
285 string inputFile = namefile;
286 if (countfile != "") { inputFile = countfile; }
288 vector<string> tempDistFiles;
289 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
290 string tempDistFile = distFile + "." + toString(i) + ".temp";
291 tempDistFiles.push_back(tempDistFile);
292 m->mothurRemove((inputFile + "." + toString(i) + ".temp"));
294 //write out any remaining buffers
295 if (numOutputs[i] > 0) {
296 m->openOutputFileAppend((distFile + "." + toString(i) + ".temp"), outFile);
297 outFile << outputs[i];
301 validDistances[i] = true;
305 splitNames(seqGroup, numGroups, tempDistFiles);
307 if (m->control_pressed) {
308 for (int i = 0; i < dists.size(); i++) {
309 m->mothurRemove((dists[i].begin()->first));
310 m->mothurRemove((dists[i].begin()->second));
317 catch(exception& e) {
318 m->errorOut(e, "SplitMatrix", "splitDistanceFileByTax");
322 /***********************************************************************/
323 int SplitMatrix::splitDistanceLarge(){
325 vector<set<string> > groups;
327 //for buffering the io to improve speed
328 //allow for 30 dists to be stored, then output.
329 vector<string> outputs;
330 vector<int> numOutputs;
331 vector<bool> wroteOutPut;
337 m->openInputFile(distFile, dFile);
343 dFile >> seqA >> seqB >> dist;
345 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; }
348 //cout << "in cutoff: " << dist << endl;
353 for(int i=0;i<numGroups;i++){
354 set<string>::iterator aIt = groups[i].find(seqA);
355 set<string>::iterator bIt = groups[i].find(seqB);
357 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]
358 groups[i].insert(seqB);
362 //cout << "in aIt: " << groupID << endl;
365 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]
366 groups[i].insert(seqA);
370 // cout << "in bIt: " << groupID << endl;
374 if(groupIDA != -1 && groupIDB != -1){//both ifs above have been executed, so we need to decide who to assign them to
375 if(groupIDA < groupIDB){
376 // cout << "A: " << groupIDA << "\t" << groupIDB << endl;
377 groups[groupIDA].insert(groups[groupIDB].begin(), groups[groupIDB].end()); //merge two groups into groupIDA
378 groups[groupIDB].clear();
382 // cout << "B: " << groupIDA << "\t" << groupIDB << endl;
383 groups[groupIDB].insert(groups[groupIDA].begin(), groups[groupIDA].end()); //merge two groups into groupIDB
384 groups[groupIDA].clear();
391 //windows is gonna gag on the reuse of outFile, will need to make it local...
393 if(groupIDA == -1 && groupIDB == -1){ //we need a new group
394 set<string> newGroup;
395 newGroup.insert(seqA);
396 newGroup.insert(seqB);
397 groups.push_back(newGroup);
399 string tempOut = seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
400 outputs.push_back(tempOut);
401 numOutputs.push_back(1);
402 wroteOutPut.push_back(false);
407 string fileName = distFile + "." + toString(groupID) + ".temp";
409 //have we reached the max buffer size
410 if (numOutputs[groupID] > 60) { //write out sequence
412 outFile.open(fileName.c_str(), ios::app);
413 outFile << outputs[groupID] << seqA << '\t' << seqB << '\t' << dist << endl;
416 outputs[groupID] = "";
417 numOutputs[groupID] = 0;
418 wroteOutPut[groupID] = true;
420 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
421 numOutputs[groupID]++;
424 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
425 string row, column, distance;
426 if(groupIDA<groupIDB){
429 numOutputs[groupID] += numOutputs[groupIDB];
430 outputs[groupID] += outputs[groupIDB];
432 outputs[groupIDB] = "";
433 numOutputs[groupIDB] = 0;
435 //if groupB is written to file it is above buffer size so read and write to new merged file
436 if (wroteOutPut[groupIDB]) {
437 string fileName2 = distFile + "." + toString(groupIDB) + ".temp";
438 /*ifstream fileB(fileName2.c_str(), ios::ate);
440 outFile.open(fileName.c_str(), ios::app);
445 size = fileB.tellg();
447 fileB.seekg (0, ios::beg);
449 int numRead = size / 1024;
450 int lastRead = size % 1024;
452 for (int i = 0; i < numRead; i++) {
454 memblock = new char [1024];
456 fileB.read (memblock, 1024);
458 string temp = memblock;
459 outFile << temp.substr(0, 1024);
464 memblock = new char [lastRead];
466 fileB.read (memblock, lastRead);
468 //not sure why but it will read more than lastRead char...??
469 string temp = memblock;
470 outFile << temp.substr(0, lastRead);
474 m->appendFiles(fileName2, fileName);
475 m->mothurRemove(fileName2);
478 //write out the merged memory
479 if (numOutputs[groupID] > 60) {
481 m->openOutputFile(fileName, tempOut);
482 tempOut << outputs[groupID];
483 outputs[groupID] = "";
484 numOutputs[groupID] = 0;
490 wroteOutPut[groupID] = true;
491 wroteOutPut[groupIDB] = false;
492 }else{ } //just merge b's memory with a's memory
495 numOutputs[groupID] += numOutputs[groupIDA];
496 outputs[groupID] += outputs[groupIDA];
498 outputs[groupIDA] = "";
499 numOutputs[groupIDA] = 0;
501 if (wroteOutPut[groupIDA]) {
502 string fileName2 = distFile + "." + toString(groupIDA) + ".temp";
503 /*ifstream fileB(fileName2.c_str(), ios::ate);
505 outFile.open(fileName.c_str(), ios::app);
510 size = fileB.tellg();
512 fileB.seekg (0, ios::beg);
514 int numRead = size / 1024;
515 int lastRead = size % 1024;
517 for (int i = 0; i < numRead; i++) {
519 memblock = new char [1024];
521 fileB.read (memblock, 1024);
522 string temp = memblock;
523 outFile << temp.substr(0, 1024);
528 memblock = new char [lastRead];
530 fileB.read (memblock, lastRead);
532 //not sure why but it will read more than lastRead char...??
533 string temp = memblock;
534 outFile << temp.substr(0, lastRead);
539 m->appendFiles(fileName2, fileName);
540 m->mothurRemove(fileName2);
542 //write out the merged memory
543 if (numOutputs[groupID] > 60) {
545 m->openOutputFile(fileName, tempOut);
546 tempOut << outputs[groupID];
547 outputs[groupID] = "";
548 numOutputs[groupID] = 0;
554 wroteOutPut[groupID] = true;
555 wroteOutPut[groupIDA] = false;
556 }else { } //just merge memory
565 vector<string> tempDistFiles;
566 for (int i = 0; i < numGroups; i++) {
567 string fileName = distFile + "." + toString(i) + ".temp";
568 tempDistFiles.push_back(fileName);
569 //remove old names files just in case
571 if (numOutputs[i] > 0) {
573 outFile.open(fileName.c_str(), ios::app);
574 outFile << outputs[i];
579 map<string, int> seqGroup;
580 for (int i = 0; i < groups.size(); i++) {
581 for (set<string>::iterator itNames = groups[i].begin(); itNames != groups[i].end();) {
582 seqGroup[*itNames] = i;
583 groups[i].erase(itNames++);
587 splitNames(seqGroup, numGroups, tempDistFiles);
591 catch(exception& e) {
592 m->errorOut(e, "SplitMatrix", "splitDistanceLarge");
596 //********************************************************************************************************************
597 int SplitMatrix::splitNames(map<string, int>& seqGroup, int numGroups, vector<string>& tempDistFiles){
600 map<string, int>::iterator it;
602 string inputFile = namefile;
603 if (countfile != "") { inputFile = countfile; }
605 for(int i=0;i<numGroups;i++){ m->mothurRemove((inputFile + "." + toString(i) + ".temp")); }
607 singleton = inputFile + ".extra.temp";
608 ofstream remainingNames;
609 m->openOutputFile(singleton, remainingNames);
611 bool wroteExtra = false;
613 ifstream bigNameFile;
614 m->openInputFile(inputFile, bigNameFile);
618 if (countfile != "") { headers = m->getline(bigNameFile); m->gobble(bigNameFile); }
620 string name, nameList;
621 while(!bigNameFile.eof()){
622 bigNameFile >> name >> nameList;
623 m->getline(bigNameFile); m->gobble(bigNameFile); //extra getline is for rest of countfile line if groups are given.
625 //did this sequence get assigned a group
626 it = seqGroup.find(name);
628 if (it != seqGroup.end()) {
629 m->openOutputFileAppend((inputFile + "." + toString(it->second) + ".temp"), outFile);
630 outFile << name << '\t' << nameList << endl;
634 remainingNames << name << '\t' << nameList << endl;
639 for(int i=0;i<numGroups;i++){
640 string tempNameFile = inputFile + "." + toString(i) + ".temp";
641 string tempDistFile = tempDistFiles[i];
643 //if there are valid distances
645 fileHandle.open(tempDistFile.c_str());
647 m->gobble(fileHandle);
648 if (!fileHandle.eof()) { //check
649 map<string, string> temp;
650 if (countfile != "") {
653 string newtempNameFile = tempNameFile + "2";
654 m->openOutputFile(newtempNameFile, out);
655 out << "Representative_Sequence\ttotal" << endl;
657 m->appendFiles(tempNameFile, newtempNameFile);
658 m->mothurRemove(tempNameFile);
659 m->renameFile(newtempNameFile, tempNameFile);
661 temp[tempDistFile] = tempNameFile;
662 dists.push_back(temp);
665 m->openInputFile(tempNameFile, in);
668 in >> name >> nameList; m->gobble(in);
670 remainingNames << name << '\t' << nameList << endl;
673 m->mothurRemove(tempNameFile);
679 remainingNames.close();
682 m->mothurRemove(singleton);
684 }else if (countfile != "") {
687 string newtempNameFile = singleton + "2";
688 m->openOutputFile(newtempNameFile, out);
689 out << "Representative_Sequence\ttotal" << endl;
691 m->appendFiles(singleton, newtempNameFile);
692 m->mothurRemove(singleton);
693 m->renameFile(newtempNameFile, singleton);
698 catch(exception& e) {
699 m->errorOut(e, "SplitMatrix", "splitNames");
703 //********************************************************************************************************************
704 int SplitMatrix::splitDistanceRAM(){
706 vector<set<string> > groups;
707 vector<string> outputs;
712 m->openInputFile(distFile, dFile);
718 dFile >> seqA >> seqB >> dist;
720 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; }
723 //cout << "in cutoff: " << dist << endl;
728 for(int i=0;i<numGroups;i++){
729 set<string>::iterator aIt = groups[i].find(seqA);
730 set<string>::iterator bIt = groups[i].find(seqB);
732 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]
733 groups[i].insert(seqB);
737 //cout << "in aIt: " << groupID << endl;
740 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]
741 groups[i].insert(seqA);
745 // cout << "in bIt: " << groupID << endl;
749 if(groupIDA != -1 && groupIDB != -1){//both ifs above have been executed, so we need to decide who to assign them to
750 if(groupIDA < groupIDB){
751 // cout << "A: " << groupIDA << "\t" << groupIDB << endl;
752 groups[groupIDA].insert(groups[groupIDB].begin(), groups[groupIDB].end()); //merge two groups into groupIDA
753 groups[groupIDB].clear();
757 // cout << "B: " << groupIDA << "\t" << groupIDB << endl;
758 groups[groupIDB].insert(groups[groupIDA].begin(), groups[groupIDA].end()); //merge two groups into groupIDB
759 groups[groupIDA].clear();
766 //windows is gonna gag on the reuse of outFile, will need to make it local...
768 if(groupIDA == -1 && groupIDB == -1){ //we need a new group
769 set<string> newGroup;
770 newGroup.insert(seqA);
771 newGroup.insert(seqB);
772 groups.push_back(newGroup);
774 string tempOut = seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
775 outputs.push_back(tempOut);
780 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
782 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
783 string row, column, distance;
784 if(groupIDA<groupIDB){
786 outputs[groupID] += outputs[groupIDB];
787 outputs[groupIDB] = "";
789 outputs[groupID] += outputs[groupIDA];
790 outputs[groupIDA] = "";
799 vector<string> tempDistFiles;
800 for (int i = 0; i < numGroups; i++) {
801 string fileName = distFile + "." + toString(i) + ".temp";
802 tempDistFiles.push_back(fileName);
803 if (outputs[i] != "") {
805 outFile.open(fileName.c_str(), ios::ate);
806 outFile << outputs[i];
811 map<string, int> seqGroup;
812 for (int i = 0; i < groups.size(); i++) {
813 for (set<string>::iterator itNames = groups[i].begin(); itNames != groups[i].end();) {
814 seqGroup[*itNames] = i;
815 groups[i].erase(itNames++);
819 splitNames(seqGroup, numGroups, tempDistFiles);
823 catch(exception& e) {
824 m->errorOut(e, "SplitMatrix", "splitDistanceRAM");
828 //********************************************************************************************************************
829 //sorts biggest to smallest
830 inline bool compareFileSizes(map<string, string> left, map<string, string> right){
835 //get num bytes in file
836 string filename = left.begin()->first;
837 pFile = fopen (filename.c_str(),"rb");
838 string error = "Error opening " + filename;
839 if (pFile==NULL) perror (error.c_str());
841 fseek (pFile, 0, SEEK_END);
842 leftsize=ftell (pFile);
849 //get num bytes in file
850 filename = right.begin()->first;
851 pFile2 = fopen (filename.c_str(),"rb");
852 error = "Error opening " + filename;
853 if (pFile2==NULL) perror (error.c_str());
855 fseek (pFile2, 0, SEEK_END);
856 rightsize=ftell (pFile2);
860 return (leftsize > rightsize);
862 /***********************************************************************/
863 //returns map of distance files -> namefile sorted by distance file size
864 vector< map< string, string> > SplitMatrix::getDistanceFiles(){
867 sort(dists.begin(), dists.end(), compareFileSizes);
871 catch(exception& e) {
872 m->errorOut(e, "SplitMatrix", "getDistanceFiles");
876 /***********************************************************************/
877 SplitMatrix::~SplitMatrix(){}
878 /***********************************************************************/