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
411 outFile.open(fileName.c_str(), ios::app);
412 outFile << outputs[groupID] << seqA << '\t' << seqB << '\t' << dist << endl;
415 outputs[groupID] = "";
416 numOutputs[groupID] = 0;
417 wroteOutPut[groupID] = true;
419 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
420 numOutputs[groupID]++;
423 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
424 string row, column, distance;
425 if(groupIDA<groupIDB){
428 numOutputs[groupID] += numOutputs[groupIDB];
429 outputs[groupID] += outputs[groupIDB];
431 outputs[groupIDB] = "";
432 numOutputs[groupIDB] = 0;
434 //if groupB is written to file it is above buffer size so read and write to new merged file
435 if (wroteOutPut[groupIDB]) {
436 string fileName2 = distFile + "." + toString(groupIDB) + ".temp";
437 ifstream fileB(fileName2.c_str(), ios::ate);
439 outFile.open(fileName.c_str(), ios::app);
444 size = fileB.tellg();
446 fileB.seekg (0, ios::beg);
448 int numRead = size / 1024;
449 int lastRead = size % 1024;
451 for (int i = 0; i < numRead; i++) {
453 memblock = new char [1024];
455 fileB.read (memblock, 1024);
457 string temp = memblock;
458 outFile << temp.substr(0, 1024);
463 memblock = new char [lastRead];
465 fileB.read (memblock, lastRead);
467 //not sure why but it will read more than lastRead char...??
468 string temp = memblock;
469 outFile << temp.substr(0, lastRead);
473 m->mothurRemove(fileName2);
475 //write out the merged memory
476 if (numOutputs[groupID] > 60) {
477 outFile << outputs[groupID];
478 outputs[groupID] = "";
479 numOutputs[groupID] = 0;
484 wroteOutPut[groupID] = true;
485 wroteOutPut[groupIDB] = false;
486 }else{ } //just merge b's memory with a's memory
489 numOutputs[groupID] += numOutputs[groupIDA];
490 outputs[groupID] += outputs[groupIDA];
492 outputs[groupIDA] = "";
493 numOutputs[groupIDA] = 0;
495 if (wroteOutPut[groupIDA]) {
496 string fileName2 = distFile + "." + toString(groupIDA) + ".temp";
497 ifstream fileB(fileName2.c_str(), ios::ate);
499 outFile.open(fileName.c_str(), ios::app);
504 size = fileB.tellg();
506 fileB.seekg (0, ios::beg);
508 int numRead = size / 1024;
509 int lastRead = size % 1024;
511 for (int i = 0; i < numRead; i++) {
513 memblock = new char [1024];
515 fileB.read (memblock, 1024);
516 string temp = memblock;
517 outFile << temp.substr(0, 1024);
522 memblock = new char [lastRead];
524 fileB.read (memblock, lastRead);
526 //not sure why but it will read more than lastRead char...??
527 string temp = memblock;
528 outFile << temp.substr(0, lastRead);
533 m->mothurRemove(fileName2);
535 //write out the merged memory
536 if (numOutputs[groupID] > 60) {
537 outFile << outputs[groupID];
538 outputs[groupID] = "";
539 numOutputs[groupID] = 0;
544 wroteOutPut[groupID] = true;
545 wroteOutPut[groupIDA] = false;
546 }else { } //just merge memory
555 vector<string> tempDistFiles;
556 for (int i = 0; i < numGroups; i++) {
557 string fileName = distFile + "." + toString(i) + ".temp";
558 tempDistFiles.push_back(fileName);
559 //remove old names files just in case
561 if (numOutputs[i] > 0) {
562 outFile.open(fileName.c_str(), ios::app);
563 outFile << outputs[i];
568 map<string, int> seqGroup;
569 for (int i = 0; i < groups.size(); i++) {
570 for (set<string>::iterator itNames = groups[i].begin(); itNames != groups[i].end();) {
571 seqGroup[*itNames] = i;
572 groups[i].erase(itNames++);
576 splitNames(seqGroup, numGroups, tempDistFiles);
580 catch(exception& e) {
581 m->errorOut(e, "SplitMatrix", "splitDistanceLarge");
585 //********************************************************************************************************************
586 int SplitMatrix::splitNames(map<string, int>& seqGroup, int numGroups, vector<string>& tempDistFiles){
589 map<string, int>::iterator it;
591 string inputFile = namefile;
592 if (countfile != "") { inputFile = countfile; }
594 for(int i=0;i<numGroups;i++){ m->mothurRemove((inputFile + "." + toString(i) + ".temp")); }
596 singleton = inputFile + ".extra.temp";
597 ofstream remainingNames;
598 m->openOutputFile(singleton, remainingNames);
600 bool wroteExtra = false;
602 ifstream bigNameFile;
603 m->openInputFile(inputFile, bigNameFile);
607 if (countfile != "") { headers = m->getline(bigNameFile); m->gobble(bigNameFile); }
609 string name, nameList;
610 while(!bigNameFile.eof()){
611 bigNameFile >> name >> nameList;
612 m->getline(bigNameFile); m->gobble(bigNameFile); //extra getline is for rest of countfile line if groups are given.
614 //did this sequence get assigned a group
615 it = seqGroup.find(name);
617 if (it != seqGroup.end()) {
618 m->openOutputFileAppend((inputFile + "." + toString(it->second) + ".temp"), outFile);
619 outFile << name << '\t' << nameList << endl;
623 remainingNames << name << '\t' << nameList << endl;
628 for(int i=0;i<numGroups;i++){
629 string tempNameFile = inputFile + "." + toString(i) + ".temp";
630 string tempDistFile = tempDistFiles[i];
632 //if there are valid distances
634 fileHandle.open(tempDistFile.c_str());
636 m->gobble(fileHandle);
637 if (!fileHandle.eof()) { //check
638 map<string, string> temp;
639 if (countfile != "") {
642 string newtempNameFile = tempNameFile + "2";
643 m->openOutputFile(newtempNameFile, out);
644 out << "Representative_Sequence\ttotal" << endl;
646 m->appendFiles(tempNameFile, newtempNameFile);
647 m->mothurRemove(tempNameFile);
648 m->renameFile(newtempNameFile, tempNameFile);
650 temp[tempDistFile] = tempNameFile;
651 dists.push_back(temp);
654 m->openInputFile(tempNameFile, in);
657 in >> name >> nameList; m->gobble(in);
659 remainingNames << name << '\t' << nameList << endl;
662 m->mothurRemove(tempNameFile);
668 remainingNames.close();
671 m->mothurRemove(singleton);
673 }else if (countfile != "") {
676 string newtempNameFile = singleton + "2";
677 m->openOutputFile(newtempNameFile, out);
678 out << "Representative_Sequence\ttotal" << endl;
680 m->appendFiles(singleton, newtempNameFile);
681 m->mothurRemove(singleton);
682 m->renameFile(newtempNameFile, singleton);
687 catch(exception& e) {
688 m->errorOut(e, "SplitMatrix", "splitNames");
692 //********************************************************************************************************************
693 int SplitMatrix::splitDistanceRAM(){
695 vector<set<string> > groups;
696 vector<string> outputs;
701 m->openInputFile(distFile, dFile);
707 dFile >> seqA >> seqB >> dist;
709 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; }
712 //cout << "in cutoff: " << dist << endl;
717 for(int i=0;i<numGroups;i++){
718 set<string>::iterator aIt = groups[i].find(seqA);
719 set<string>::iterator bIt = groups[i].find(seqB);
721 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]
722 groups[i].insert(seqB);
726 //cout << "in aIt: " << groupID << endl;
729 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]
730 groups[i].insert(seqA);
734 // cout << "in bIt: " << groupID << endl;
738 if(groupIDA != -1 && groupIDB != -1){//both ifs above have been executed, so we need to decide who to assign them to
739 if(groupIDA < groupIDB){
740 // cout << "A: " << groupIDA << "\t" << groupIDB << endl;
741 groups[groupIDA].insert(groups[groupIDB].begin(), groups[groupIDB].end()); //merge two groups into groupIDA
742 groups[groupIDB].clear();
746 // cout << "B: " << groupIDA << "\t" << groupIDB << endl;
747 groups[groupIDB].insert(groups[groupIDA].begin(), groups[groupIDA].end()); //merge two groups into groupIDB
748 groups[groupIDA].clear();
755 //windows is gonna gag on the reuse of outFile, will need to make it local...
757 if(groupIDA == -1 && groupIDB == -1){ //we need a new group
758 set<string> newGroup;
759 newGroup.insert(seqA);
760 newGroup.insert(seqB);
761 groups.push_back(newGroup);
763 string tempOut = seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
764 outputs.push_back(tempOut);
769 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
771 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
772 string row, column, distance;
773 if(groupIDA<groupIDB){
775 outputs[groupID] += outputs[groupIDB];
776 outputs[groupIDB] = "";
778 outputs[groupID] += outputs[groupIDA];
779 outputs[groupIDA] = "";
788 vector<string> tempDistFiles;
789 for (int i = 0; i < numGroups; i++) {
790 string fileName = distFile + "." + toString(i) + ".temp";
791 tempDistFiles.push_back(fileName);
792 if (outputs[i] != "") {
794 outFile.open(fileName.c_str(), ios::ate);
795 outFile << outputs[i];
800 map<string, int> seqGroup;
801 for (int i = 0; i < groups.size(); i++) {
802 for (set<string>::iterator itNames = groups[i].begin(); itNames != groups[i].end();) {
803 seqGroup[*itNames] = i;
804 groups[i].erase(itNames++);
808 splitNames(seqGroup, numGroups, tempDistFiles);
812 catch(exception& e) {
813 m->errorOut(e, "SplitMatrix", "splitDistanceRAM");
817 //********************************************************************************************************************
818 //sorts biggest to smallest
819 inline bool compareFileSizes(map<string, string> left, map<string, string> right){
824 //get num bytes in file
825 string filename = left.begin()->first;
826 pFile = fopen (filename.c_str(),"rb");
827 string error = "Error opening " + filename;
828 if (pFile==NULL) perror (error.c_str());
830 fseek (pFile, 0, SEEK_END);
831 leftsize=ftell (pFile);
838 //get num bytes in file
839 filename = right.begin()->first;
840 pFile2 = fopen (filename.c_str(),"rb");
841 error = "Error opening " + filename;
842 if (pFile2==NULL) perror (error.c_str());
844 fseek (pFile2, 0, SEEK_END);
845 rightsize=ftell (pFile2);
849 return (leftsize > rightsize);
851 /***********************************************************************/
852 //returns map of distance files -> namefile sorted by distance file size
853 vector< map< string, string> > SplitMatrix::getDistanceFiles(){
856 sort(dists.begin(), dists.end(), compareFileSizes);
860 catch(exception& e) {
861 m->errorOut(e, "SplitMatrix", "getDistanceFiles");
865 /***********************************************************************/
866 SplitMatrix::~SplitMatrix(){}
867 /***********************************************************************/