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"
14 /***********************************************************************/
16 SplitMatrix::SplitMatrix(string distfile, string name, string tax, float c, string t, bool l){
17 m = MothurOut::getInstance();
25 /***********************************************************************/
27 SplitMatrix::SplitMatrix(string ffile, string name, string tax, float c, string t, int p, string output){
28 m = MothurOut::getInstance();
38 /***********************************************************************/
40 int SplitMatrix::split(){
43 if (method == "distance") {
45 }else if ((method == "classify") || (method == "fasta")) {
48 m->mothurOut("Unknown splitting method, aborting split."); m->mothurOutEndLine();
49 map<string, string> temp;
50 temp[distFile] = namefile;
51 dists.push_back(temp);
57 m->errorOut(e, "SplitMatrix", "split");
61 /***********************************************************************/
62 int SplitMatrix::splitDistance(){
65 if (large) { splitDistanceLarge(); }
66 else { splitDistanceRAM(); }
70 m->errorOut(e, "SplitMatrix", "splitDistance");
75 /***********************************************************************/
76 int SplitMatrix::splitClassify(){
80 map<string, int> seqGroup;
81 map<string, int>::iterator it;
82 map<string, int>::iterator it2;
86 //build tree from users taxonomy file
87 PhyloTree* phylo = new PhyloTree();
90 m->openInputFile(taxFile, in);
92 //read in users taxonomy file and add sequences to tree
95 in >> seqname >> tax; m->gobble(in);
96 phylo->addSeqToTree(seqname, tax);
100 phylo->assignHeirarchyIDs(0);
102 //make sure the cutoff is not greater than maxlevel
103 if (cutoff > phylo->getMaxLevel()) { m->mothurOut("splitcutoff is greater than the longest taxonomy, using " + toString(phylo->getMaxLevel())); m->mothurOutEndLine(); cutoff = phylo->getMaxLevel(); }
105 //for each node in tree
106 for (int i = 0; i < phylo->getNumNodes(); i++) {
108 //is this node within the cutoff
109 TaxNode taxon = phylo->get(i);
111 if (taxon.level == cutoff) {//if yes, then create group containing this nodes sequences
112 if (taxon.accessions.size() > 1) { //if this taxon just has one seq its a singleton
113 for (int j = 0; j < taxon.accessions.size(); j++) {
114 seqGroup[taxon.accessions[j]] = numGroups;
123 if (method == "classify") {
124 splitDistanceFileByTax(seqGroup, numGroups);
126 createDistanceFilesFromTax(seqGroup, numGroups);
132 catch(exception& e) {
133 m->errorOut(e, "SplitMatrix", "splitClassify");
137 /***********************************************************************/
138 int SplitMatrix::createDistanceFilesFromTax(map<string, int>& seqGroup, int numGroups){
140 map<string, int> copyGroups = seqGroup;
141 map<string, int>::iterator it;
144 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
145 remove((fastafile + "." + toString(i) + ".temp").c_str());
149 m->openInputFile(fastafile, in);
154 Sequence query(in); m->gobble(in);
155 if (query.getName() != "") {
157 it = seqGroup.find(query.getName());
159 //save names in case no namefile is given
160 if (namefile == "") { names.insert(query.getName()); }
162 if (it != seqGroup.end()) { //not singleton
163 m->openOutputFileAppend((fastafile + "." + toString(it->second) + ".temp"), outFile);
164 query.printSequence(outFile);
167 copyGroups.erase(query.getName());
173 //warn about sequence in groups that are not in fasta file
174 for(it = copyGroups.begin(); it != copyGroups.end(); it++) {
175 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();
181 //process each distance file
182 for (int i = 0; i < numGroups; i++) {
184 string options = "fasta=" + (fastafile + "." + toString(i) + ".temp") + ", processors=" + toString(processors) + ", cutoff=" + toString(cutoff);
186 Command* command = new DistanceCommand(options);
190 remove((fastafile + "." + toString(i) + ".temp").c_str());
192 //remove old names files just in case
193 remove((namefile + "." + toString(i) + ".temp").c_str());
196 singleton = namefile + ".extra.temp";
197 ofstream remainingNames;
198 m->openOutputFile(singleton, remainingNames);
200 bool wroteExtra = false;
202 ifstream bigNameFile;
203 m->openInputFile(namefile, bigNameFile);
205 string name, nameList;
206 while(!bigNameFile.eof()){
207 bigNameFile >> name >> nameList; m->gobble(bigNameFile);
209 //did this sequence get assigned a group
210 it = seqGroup.find(name);
212 if (it != seqGroup.end()) {
213 m->openOutputFileAppend((namefile + "." + toString(it->second) + ".temp"), outFile);
214 outFile << name << '\t' << nameList << endl;
218 remainingNames << name << '\t' << nameList << endl;
223 for(int i=0;i<numGroups;i++){
224 string tempNameFile = namefile + "." + toString(i) + ".temp";
225 string tempDistFile = outputDir + m->getRootName(m->getSimpleName((fastafile + "." + toString(i) + ".temp"))) + "dist";
227 //if there are valid distances
229 fileHandle.open(tempDistFile.c_str());
231 m->gobble(fileHandle);
232 if (!fileHandle.eof()) { //check for blank file - this could occur if all dists in group are above cutoff
233 map<string, string> temp;
234 temp[tempDistFile] = tempNameFile;
235 dists.push_back(temp);
238 m->openInputFile(tempNameFile, in);
241 in >> name >> nameList; m->gobble(in);
243 remainingNames << name << '\t' << nameList << endl;
246 remove(tempNameFile.c_str());
252 remainingNames.close();
254 remove(singleton.c_str());
258 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(); }
262 catch(exception& e) {
263 m->errorOut(e, "SplitMatrix", "createDistanceFilesFromTax");
267 /***********************************************************************/
268 int SplitMatrix::splitDistanceFileByTax(map<string, int>& seqGroup, int numGroups){
270 map<string, int>::iterator it;
271 map<string, int>::iterator it2;
274 m->openInputFile(distFile, dFile);
277 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
278 remove((distFile + "." + toString(i) + ".temp").c_str());
281 //for buffering the io to improve speed
282 //allow for 10 dists to be stored, then output.
283 vector<string> outputs; outputs.resize(numGroups, "");
284 vector<int> numOutputs; numOutputs.resize(numGroups, 0);
286 //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
287 //this can occur if we have converted the phylip to column, since we reduce the size at that step by using the cutoff value
288 vector<bool> validDistances; validDistances.resize(numGroups, false);
295 if (m->control_pressed) { dFile.close(); for (int i = 0; i < numGroups; i++) { remove((distFile + "." + toString(i) + ".temp").c_str()); } }
297 dFile >> seqA >> seqB >> dist; m->gobble(dFile);
299 //if both sequences are in the same group then they are within the cutoff
300 it = seqGroup.find(seqA);
301 it2 = seqGroup.find(seqB);
303 if ((it != seqGroup.end()) && (it2 != seqGroup.end())) { //they are both not singletons
304 if (it->second == it2->second) { //they are from the same group so add the distance
305 if (numOutputs[it->second] > 30) {
306 m->openOutputFileAppend((distFile + "." + toString(it->second) + ".temp"), outFile);
307 outFile << outputs[it->second] << seqA << '\t' << seqB << '\t' << dist << endl;
309 outputs[it->second] = "";
310 numOutputs[it->second] = 0;
311 validDistances[it->second] = true;
313 outputs[it->second] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
314 numOutputs[it->second]++;
321 for (int i = 0; i < numGroups; i++) { //remove old temp files, just in case
322 remove((namefile + "." + toString(i) + ".temp").c_str());
324 //write out any remaining buffers
325 if (numOutputs[i] > 0) {
326 m->openOutputFileAppend((distFile + "." + toString(i) + ".temp"), outFile);
327 outFile << outputs[i];
331 validDistances[i] = true;
335 ifstream bigNameFile;
336 m->openInputFile(namefile, bigNameFile);
338 singleton = namefile + ".extra.temp";
339 ofstream remainingNames;
340 m->openOutputFile(singleton, remainingNames);
342 bool wroteExtra = false;
344 string name, nameList;
345 while(!bigNameFile.eof()){
346 bigNameFile >> name >> nameList; m->gobble(bigNameFile);
348 //did this sequence get assigned a group
349 it = seqGroup.find(name);
351 if (it != seqGroup.end()) {
352 m->openOutputFileAppend((namefile + "." + toString(it->second) + ".temp"), outFile);
353 outFile << name << '\t' << nameList << endl;
357 remainingNames << name << '\t' << nameList << endl;
362 for(int i=0;i<numGroups;i++){
363 string tempNameFile = namefile + "." + toString(i) + ".temp";
364 string tempDistFile = distFile + "." + toString(i) + ".temp";
366 //if there are valid distances
367 if (validDistances[i]) {
368 map<string, string> temp;
369 temp[tempDistFile] = tempNameFile;
370 dists.push_back(temp);
373 m->openInputFile(tempNameFile, in);
376 in >> name >> nameList; m->gobble(in);
378 remainingNames << name << '\t' << nameList << endl;
381 remove(tempNameFile.c_str());
385 remainingNames.close();
388 remove(singleton.c_str());
392 if (m->control_pressed) {
393 for (int i = 0; i < dists.size(); i++) {
394 remove((dists[i].begin()->first).c_str());
395 remove((dists[i].begin()->second).c_str());
402 catch(exception& e) {
403 m->errorOut(e, "SplitMatrix", "splitDistanceFileByTax");
407 /***********************************************************************/
408 int SplitMatrix::splitDistanceLarge(){
410 vector<set<string> > groups;
412 //for buffering the io to improve speed
413 //allow for 30 dists to be stored, then output.
414 vector<string> outputs;
415 vector<int> numOutputs;
416 vector<bool> wroteOutPut;
422 m->openInputFile(distFile, dFile);
428 dFile >> seqA >> seqB >> dist;
430 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; }
433 //cout << "in cutoff: " << dist << endl;
438 for(int i=0;i<numGroups;i++){
439 set<string>::iterator aIt = groups[i].find(seqA);
440 set<string>::iterator bIt = groups[i].find(seqB);
442 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]
443 groups[i].insert(seqB);
447 //cout << "in aIt: " << groupID << endl;
450 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]
451 groups[i].insert(seqA);
455 // cout << "in bIt: " << groupID << endl;
459 if(groupIDA != -1 && groupIDB != -1){//both ifs above have been executed, so we need to decide who to assign them to
460 if(groupIDA < groupIDB){
461 // cout << "A: " << groupIDA << "\t" << groupIDB << endl;
462 groups[groupIDA].insert(groups[groupIDB].begin(), groups[groupIDB].end()); //merge two groups into groupIDA
463 groups[groupIDB].clear();
467 // cout << "B: " << groupIDA << "\t" << groupIDB << endl;
468 groups[groupIDB].insert(groups[groupIDA].begin(), groups[groupIDA].end()); //merge two groups into groupIDB
469 groups[groupIDA].clear();
476 //windows is gonna gag on the reuse of outFile, will need to make it local...
478 if(groupIDA == -1 && groupIDB == -1){ //we need a new group
479 set<string> newGroup;
480 newGroup.insert(seqA);
481 newGroup.insert(seqB);
482 groups.push_back(newGroup);
484 string tempOut = seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
485 outputs.push_back(tempOut);
486 numOutputs.push_back(1);
487 wroteOutPut.push_back(false);
492 string fileName = distFile + "." + toString(groupID) + ".temp";
494 //have we reached the max buffer size
495 if (numOutputs[groupID] > 60) { //write out sequence
496 outFile.open(fileName.c_str(), ios::app);
497 outFile << outputs[groupID] << seqA << '\t' << seqB << '\t' << dist << endl;
500 outputs[groupID] = "";
501 numOutputs[groupID] = 0;
502 wroteOutPut[groupID] = true;
504 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
505 numOutputs[groupID]++;
508 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
509 string row, column, distance;
510 if(groupIDA<groupIDB){
513 numOutputs[groupID] += numOutputs[groupIDB];
514 outputs[groupID] += outputs[groupIDB];
516 outputs[groupIDB] = "";
517 numOutputs[groupIDB] = 0;
519 //if groupB is written to file it is above buffer size so read and write to new merged file
520 if (wroteOutPut[groupIDB]) {
521 string fileName2 = distFile + "." + toString(groupIDB) + ".temp";
522 ifstream fileB(fileName2.c_str(), ios::ate);
524 outFile.open(fileName.c_str(), ios::app);
529 size = fileB.tellg();
531 fileB.seekg (0, ios::beg);
533 int numRead = size / 1024;
534 int lastRead = size % 1024;
536 for (int i = 0; i < numRead; i++) {
538 memblock = new char [1024];
540 fileB.read (memblock, 1024);
542 string temp = memblock;
543 outFile << temp.substr(0, 1024);
548 memblock = new char [lastRead];
550 fileB.read (memblock, lastRead);
552 //not sure why but it will read more than lastRead char...??
553 string temp = memblock;
554 outFile << temp.substr(0, lastRead);
558 remove(fileName2.c_str());
560 //write out the merged memory
561 if (numOutputs[groupID] > 60) {
562 outFile << outputs[groupID];
563 outputs[groupID] = "";
564 numOutputs[groupID] = 0;
569 wroteOutPut[groupID] = true;
570 wroteOutPut[groupIDB] = false;
571 }else{ } //just merge b's memory with a's memory
574 numOutputs[groupID] += numOutputs[groupIDA];
575 outputs[groupID] += outputs[groupIDA];
577 outputs[groupIDA] = "";
578 numOutputs[groupIDA] = 0;
580 if (wroteOutPut[groupIDA]) {
581 string fileName2 = distFile + "." + toString(groupIDA) + ".temp";
582 ifstream fileB(fileName2.c_str(), ios::ate);
584 outFile.open(fileName.c_str(), ios::app);
589 size = fileB.tellg();
591 fileB.seekg (0, ios::beg);
593 int numRead = size / 1024;
594 int lastRead = size % 1024;
596 for (int i = 0; i < numRead; i++) {
598 memblock = new char [1024];
600 fileB.read (memblock, 1024);
601 string temp = memblock;
602 outFile << temp.substr(0, 1024);
607 memblock = new char [lastRead];
609 fileB.read (memblock, lastRead);
611 //not sure why but it will read more than lastRead char...??
612 string temp = memblock;
613 outFile << temp.substr(0, lastRead);
618 remove(fileName2.c_str());
620 //write out the merged memory
621 if (numOutputs[groupID] > 60) {
622 outFile << outputs[groupID];
623 outputs[groupID] = "";
624 numOutputs[groupID] = 0;
629 wroteOutPut[groupID] = true;
630 wroteOutPut[groupIDA] = false;
631 }else { } //just merge memory
640 for (int i = 0; i < numGroups; i++) {
641 if (numOutputs[i] > 0) {
642 string fileName = distFile + "." + toString(i) + ".temp";
643 outFile.open(fileName.c_str(), ios::app);
644 outFile << outputs[i];
653 catch(exception& e) {
654 m->errorOut(e, "SplitMatrix", "splitDistanceLarge");
658 //********************************************************************************************************************
659 int SplitMatrix::splitNames(vector<set<string> >& groups){
661 int numGroups = groups.size();
663 ifstream bigNameFile(namefile.c_str());
665 cerr << "Error: We can't open the name file\n";
669 map<string, string> nameMap;
670 string name, nameList;
672 bigNameFile >> name >> nameList;
673 nameMap[name] = nameList;
674 m->gobble(bigNameFile);
678 for(int i=0;i<numGroups;i++){ //parse names file to match distance files
679 int numSeqsInGroup = groups[i].size();
681 if(numSeqsInGroup > 0){
682 string fileName = namefile + "." + toString(i) + ".temp";
683 ofstream smallNameFile(fileName.c_str(), ios::ate);
685 for(set<string>::iterator gIt=groups[i].begin();gIt!=groups[i].end();gIt++){
686 map<string,string>::iterator nIt = nameMap.find(*gIt);
687 if (nIt != nameMap.end()) {
688 smallNameFile << nIt->first << '\t' << nIt->second << endl;
691 m->mothurOut((*gIt) + " is in your distance file and not in your namefile. Please correct."); m->mothurOutEndLine(); exit(1);
694 smallNameFile.close();
698 //names of singletons
699 if (nameMap.size() != 0) {
700 singleton = namefile + ".extra.temp";
701 ofstream remainingNames(singleton.c_str(), ios::ate);
702 for(map<string,string>::iterator nIt=nameMap.begin();nIt!=nameMap.end();nIt++){
703 remainingNames << nIt->first << '\t' << nIt->second << endl;
705 remainingNames.close();
706 }else { singleton = "none"; }
708 for(int i=0;i<numGroups;i++){
709 if(groups[i].size() > 0){
710 string tempNameFile = namefile + "." + toString(i) + ".temp";
711 string tempDistFile = distFile + "." + toString(i) + ".temp";
713 map<string, string> temp;
714 temp[tempDistFile] = tempNameFile;
715 dists.push_back(temp);
719 if (m->control_pressed) {
720 for (int i = 0; i < dists.size(); i++) {
721 remove((dists[i].begin()->first).c_str());
722 remove((dists[i].begin()->second).c_str());
729 catch(exception& e) {
730 m->errorOut(e, "SplitMatrix", "splitNames");
734 //********************************************************************************************************************
735 int SplitMatrix::splitDistanceRAM(){
737 vector<set<string> > groups;
738 vector<string> outputs;
743 m->openInputFile(distFile, dFile);
749 dFile >> seqA >> seqB >> dist;
751 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; }
754 //cout << "in cutoff: " << dist << endl;
759 for(int i=0;i<numGroups;i++){
760 set<string>::iterator aIt = groups[i].find(seqA);
761 set<string>::iterator bIt = groups[i].find(seqB);
763 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]
764 groups[i].insert(seqB);
768 //cout << "in aIt: " << groupID << endl;
771 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]
772 groups[i].insert(seqA);
776 // cout << "in bIt: " << groupID << endl;
780 if(groupIDA != -1 && groupIDB != -1){//both ifs above have been executed, so we need to decide who to assign them to
781 if(groupIDA < groupIDB){
782 // cout << "A: " << groupIDA << "\t" << groupIDB << endl;
783 groups[groupIDA].insert(groups[groupIDB].begin(), groups[groupIDB].end()); //merge two groups into groupIDA
784 groups[groupIDB].clear();
788 // cout << "B: " << groupIDA << "\t" << groupIDB << endl;
789 groups[groupIDB].insert(groups[groupIDA].begin(), groups[groupIDA].end()); //merge two groups into groupIDB
790 groups[groupIDA].clear();
797 //windows is gonna gag on the reuse of outFile, will need to make it local...
799 if(groupIDA == -1 && groupIDB == -1){ //we need a new group
800 set<string> newGroup;
801 newGroup.insert(seqA);
802 newGroup.insert(seqB);
803 groups.push_back(newGroup);
805 string tempOut = seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
806 outputs.push_back(tempOut);
811 outputs[groupID] += seqA + '\t' + seqB + '\t' + toString(dist) + '\n';
813 if(groupIDA != -1 && groupIDB != -1){ //merge distance files of two groups you merged above
814 string row, column, distance;
815 if(groupIDA<groupIDB){
817 outputs[groupID] += outputs[groupIDB];
818 outputs[groupIDB] = "";
820 outputs[groupID] += outputs[groupIDA];
821 outputs[groupIDA] = "";
830 for (int i = 0; i < numGroups; i++) {
831 if (outputs[i] != "") {
833 string fileName = distFile + "." + toString(i) + ".temp";
834 outFile.open(fileName.c_str(), ios::ate);
835 outFile << outputs[i];
844 catch(exception& e) {
845 m->errorOut(e, "SplitMatrix", "splitDistanceRAM");
849 //********************************************************************************************************************
850 //sorts biggest to smallest
851 inline bool compareFileSizes(map<string, string> left, map<string, string> right){
856 //get num bytes in file
857 string filename = left.begin()->first;
858 pFile = fopen (filename.c_str(),"rb");
859 string error = "Error opening " + filename;
860 if (pFile==NULL) perror (error.c_str());
862 fseek (pFile, 0, SEEK_END);
863 leftsize=ftell (pFile);
870 //get num bytes in file
871 filename = right.begin()->first;
872 pFile2 = fopen (filename.c_str(),"rb");
873 error = "Error opening " + filename;
874 if (pFile2==NULL) perror (error.c_str());
876 fseek (pFile2, 0, SEEK_END);
877 rightsize=ftell (pFile2);
881 return (leftsize > rightsize);
883 /***********************************************************************/
884 //returns map of distance files -> namefile sorted by distance file size
885 vector< map< string, string> > SplitMatrix::getDistanceFiles(){
888 sort(dists.begin(), dists.end(), compareFileSizes);
892 catch(exception& e) {
893 m->errorOut(e, "SplitMatrix", "getDistanceFiles");
897 /***********************************************************************/
898 SplitMatrix::~SplitMatrix(){}
899 /***********************************************************************/