5 * Created by westcott on 10/13/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
11 #include "rabundvector.hpp"
12 #include "listvector.hpp"
13 #include "sparsematrix.hpp"
15 /***********************************************************************/
16 HCluster::HCluster(RAbundVector* rav, ListVector* lv, string ms, string d, NameAssignment* n, float c) : rabund(rav), list(lv), method(ms), distfile(d), nameMap(n), cutoff(c) {
18 m = MothurOut::getInstance();
21 numSeqs = list->getNumSeqs();
23 //initialize cluster array
24 for (int i = 0; i < numSeqs; i++) {
25 clusterNode temp(1, -1, i);
26 clusterArray.push_back(temp);
29 if ((method == "furthest") || (method == "nearest")) {
30 m->openInputFile(distfile, filehandle);
36 m->errorOut(e, "HCluster", "HCluster");
40 /***********************************************************************/
42 void HCluster::clusterBins(){
44 //cout << smallCol << '\t' << smallRow << '\t' << smallDist << '\t' << rabund->get(clusterArray[smallRow].smallChild) << '\t' << rabund->get(clusterArray[smallCol].smallChild);
46 rabund->set(clusterArray[smallCol].smallChild, rabund->get(clusterArray[smallRow].smallChild)+rabund->get(clusterArray[smallCol].smallChild));
47 rabund->set(clusterArray[smallRow].smallChild, 0);
48 rabund->setLabel(toString(smallDist));
50 //cout << '\t' << rabund->get(clusterArray[smallRow].smallChild) << '\t' << rabund->get(clusterArray[smallCol].smallChild) << endl;
53 m->errorOut(e, "HCluster", "clusterBins");
60 /***********************************************************************/
62 void HCluster::clusterNames(){
64 ///cout << smallCol << '\t' << smallRow << '\t' << smallDist << '\t' << list->get(clusterArray[smallRow].smallChild) << '\t' << list->get(clusterArray[smallCol].smallChild);
65 if (mapWanted) { updateMap(); }
67 list->set(clusterArray[smallCol].smallChild, list->get(clusterArray[smallRow].smallChild)+','+list->get(clusterArray[smallCol].smallChild));
68 list->set(clusterArray[smallRow].smallChild, "");
69 list->setLabel(toString(smallDist));
71 //cout << '\t' << list->get(clusterArray[smallRow].smallChild) << '\t' << list->get(clusterArray[smallCol].smallChild) << endl;
75 m->errorOut(e, "HCluster", "clusterNames");
80 /***********************************************************************/
81 int HCluster::getUpmostParent(int node){
83 while (clusterArray[node].parent != -1) {
84 node = clusterArray[node].parent;
90 m->errorOut(e, "HCluster", "getUpmostParent");
94 /***********************************************************************/
95 void HCluster::printInfo(){
98 cout << "link table" << endl;
99 for (itActive = activeLinks.begin(); itActive!= activeLinks.end(); itActive++) {
100 cout << itActive->first << " = " << itActive->second << endl;
103 for (int i = 0; i < linkTable.size(); i++) {
105 for (it = linkTable[i].begin(); it != linkTable[i].end(); it++) {
106 cout << it->first << '-' << it->second << '\t' ;
110 cout << endl << "clusterArray" << endl;
112 for (int i = 0; i < clusterArray.size(); i++) {
113 cout << i << '\t' << clusterArray[i].numSeq << '\t' << clusterArray[i].parent << '\t' << clusterArray[i].smallChild << endl;
119 catch(exception& e) {
120 m->errorOut(e, "HCluster", "getUpmostParent");
124 /***********************************************************************/
125 int HCluster::makeActive() {
129 itActive = activeLinks.find(smallRow);
130 it2Active = activeLinks.find(smallCol);
132 if ((itActive == activeLinks.end()) && (it2Active == activeLinks.end())) { //both are not active so add them
133 int size = linkTable.size();
134 map<int, int> temp; map<int, int> temp2;
136 //add link to eachother
137 temp[smallRow] = 1; // 1 2
138 temp2[smallCol] = 1; // 1 0 1
140 linkTable.push_back(temp);
141 linkTable.push_back(temp2);
144 activeLinks[smallRow] = size;
145 activeLinks[smallCol] = size+1;
147 }else if ((itActive != activeLinks.end()) && (it2Active == activeLinks.end())) { //smallRow is active, smallCol is not
148 int size = linkTable.size();
149 int alreadyActiveRow = itActive->second;
152 //add link to eachother
153 temp[smallRow] = 1; // 6 2 3 5
154 linkTable.push_back(temp); // 6 0 1 2 0
155 linkTable[alreadyActiveRow][smallCol] = 1; // 2 1 0 1 1
159 activeLinks[smallCol] = size;
161 }else if ((itActive == activeLinks.end()) && (it2Active != activeLinks.end())) { //smallCol is active, smallRow is not
162 int size = linkTable.size();
163 int alreadyActiveCol = it2Active->second;
166 //add link to eachother
167 temp[smallCol] = 1; // 6 2 3 5
168 linkTable.push_back(temp); // 6 0 1 2 0
169 linkTable[alreadyActiveCol][smallRow] = 1; // 2 1 0 1 1
173 activeLinks[smallRow] = size;
175 }else { //both are active so add one
176 int row = itActive->second;
177 int col = it2Active->second;
180 linkTable[row][smallCol]++;
181 linkTable[col][smallRow]++;
182 linkValue = linkTable[row][smallCol];
187 catch(exception& e) {
188 m->errorOut(e, "HCluster", "makeActive");
192 /***********************************************************************/
193 void HCluster::updateArrayandLinkTable() {
195 //if cluster was made update clusterArray and linkTable
196 int size = clusterArray.size();
199 clusterNode temp(clusterArray[smallRow].numSeq + clusterArray[smallCol].numSeq, -1, clusterArray[smallCol].smallChild);
200 clusterArray.push_back(temp);
203 clusterArray[smallRow].parent = size;
204 clusterArray[smallCol].parent = size;
206 if (method == "furthest") {
208 //update linkTable by merging clustered rows and columns
209 int rowSpot = activeLinks[smallRow];
210 int colSpot = activeLinks[smallCol];
213 for (int i = 0; i < linkTable.size(); i++) {
214 //check if they are in map
215 it = linkTable[i].find(smallRow);
216 it2 = linkTable[i].find(smallCol);
218 if ((it!=linkTable[i].end()) && (it2!=linkTable[i].end())) { //they are both there
219 linkTable[i][size] = linkTable[i][smallRow]+linkTable[i][smallCol];
220 linkTable[i].erase(smallCol); //delete col row
221 linkTable[i].erase(smallRow); //delete col row
222 }else if ((it==linkTable[i].end()) && (it2!=linkTable[i].end())) { //only col
223 linkTable[i][size] = linkTable[i][smallCol];
224 linkTable[i].erase(smallCol); //delete col
225 }else if ((it!=linkTable[i].end()) && (it2==linkTable[i].end())) { //only row
226 linkTable[i][size] = linkTable[i][smallRow];
227 linkTable[i].erase(smallRow); //delete col
232 for (it = linkTable[rowSpot].begin(); it != linkTable[rowSpot].end(); it++) {
233 it2 = linkTable[colSpot].find(it->first); //does the col also have this
235 if (it2 == linkTable[colSpot].end()) { //not there so add it
236 linkTable[colSpot][it->first] = it->second;
238 linkTable[colSpot][it->first] = it->second + it2->second;
242 linkTable[colSpot].erase(size);
243 linkTable.erase(linkTable.begin()+rowSpot); //delete row
246 activeLinks.erase(smallRow);
247 activeLinks.erase(smallCol);
248 activeLinks[size] = colSpot;
250 //adjust everybody elses spot since you deleted - time vs. space
251 for (itActive = activeLinks.begin(); itActive != activeLinks.end(); itActive++) {
252 if (itActive->second > rowSpot) { activeLinks[itActive->first]--; }
256 catch(exception& e) {
257 m->errorOut(e, "HCluster", "updateArrayandLinkTable");
261 /***********************************************************************/
262 double HCluster::update(int row, int col, float distance){
264 bool cluster = false;
267 smallDist = distance;
269 //find upmost parent of row and col
270 smallRow = getUpmostParent(smallRow);
271 smallCol = getUpmostParent(smallCol);
273 //you don't want to cluster with yourself
274 if (smallRow != smallCol) {
276 if ((method == "furthest") || (method == "nearest")) {
278 if (method == "nearest") { cluster = true; }
279 else{ //assume furthest
280 //are they active in the link table
281 int linkValue = makeActive(); //after this point this nodes info is active in linkTable
282 if (linkValue == (clusterArray[smallRow].numSeq * clusterArray[smallCol].numSeq)) { cluster = true; }
286 updateArrayandLinkTable();
292 updateArrayandLinkTable();
302 catch(exception& e) {
303 m->errorOut(e, "HCluster", "update");
307 /***********************************************************************/
308 void HCluster::setMapWanted(bool ms) {
313 for (int i = 0; i < list->getNumBins(); i++) {
316 string names = list->get(i);
317 while (names.find_first_of(',') != -1) {
319 string name = names.substr(0,names.find_first_of(','));
320 //save name and bin number
322 names = names.substr(names.find_first_of(',')+1, names.length());
330 catch(exception& e) {
331 m->errorOut(e, "HCluster", "setMapWanted");
335 /***********************************************************************/
336 void HCluster::updateMap() {
338 //update location of seqs in smallRow since they move to smallCol now
339 string names = list->get(clusterArray[smallRow].smallChild);
340 while (names.find_first_of(',') != -1) {
342 string name = names.substr(0,names.find_first_of(','));
343 //save name and bin number
344 seq2Bin[name] = clusterArray[smallCol].smallChild;
345 names = names.substr(names.find_first_of(',')+1, names.length());
349 seq2Bin[names] = clusterArray[smallCol].smallChild;
351 catch(exception& e) {
352 m->errorOut(e, "HCluster", "updateMap");
356 //**********************************************************************************************************************
357 vector<seqDist> HCluster::getSeqs(){
359 vector<seqDist> sameSeqs;
361 if ((method == "furthest") || (method == "nearest")) {
362 sameSeqs = getSeqsFNNN();
364 sameSeqs = getSeqsAN();
369 catch(exception& e) {
370 m->errorOut(e, "HCluster", "getSeqs");
374 //**********************************************************************************************************************
375 vector<seqDist> HCluster::getSeqsFNNN(){
377 string firstName, secondName;
378 float distance, prevDistance;
379 vector<seqDist> sameSeqs;
382 //if you are not at the beginning of the file
384 sameSeqs.push_back(next);
385 prevDistance = next.dist;
390 while (!filehandle.eof()) {
392 filehandle >> firstName >> secondName >> distance; m->gobble(filehandle);
395 if (prevDistance == -1) { prevDistance = distance; }
397 map<string,int>::iterator itA = nameMap->find(firstName);
398 map<string,int>::iterator itB = nameMap->find(secondName);
399 if(itA == nameMap->end()){ m->mothurOut("AAError: Sequence '" + firstName + "' was not found in the names file, please correct\n"); exit(1); }
400 if(itB == nameMap->end()){ m->mothurOut("ABError: Sequence '" + secondName + "' was not found in the names file, please correct\n"); exit(1); }
403 if (distance > cutoff) { break; }
405 if (distance != -1) { //-1 means skip me
407 //are the distances the same
408 if (distance == prevDistance) { //save in vector
409 seqDist temp(itA->second, itB->second, distance);
410 sameSeqs.push_back(temp);
413 next.seq1 = itA->second;
414 next.seq2 = itB->second;
415 next.dist = distance;
422 //rndomize matching dists
423 random_shuffle(sameSeqs.begin(), sameSeqs.end());
427 catch(exception& e) {
428 m->errorOut(e, "HCluster", "getSeqsFNNN");
432 //**********************************************************************************************************************
433 vector<seqDist> HCluster::getSeqsAN(){
435 int firstName, secondName;
437 vector<seqDist> sameSeqs;
440 m->openInputFile(distfile, filehandle, "no error");
442 //is the smallest value in mergedMin or the distfile?
443 float mergedMinDist = 10000;
444 float distance = 10000;
445 if (mergedMin.size() > 0) { mergedMinDist = mergedMin[0].dist; }
447 if (!filehandle.eof()) {
448 filehandle >> firstName >> secondName >> distance; m->gobble(filehandle);
450 if (prevDistance == -1) { prevDistance = distance; }
451 if (distance != -1) { //-1 means skip me
452 seqDist temp(firstName, secondName, distance);
453 sameSeqs.push_back(temp);
454 }else{ distance = 10000; }
457 if (mergedMinDist < distance) { //get minimum distance from mergedMin
458 //remove distance we saved from file
460 prevDistance = mergedMinDist;
462 for (int i = 0; i < mergedMin.size(); i++) {
463 if (mergedMin[i].dist == prevDistance) {
464 sameSeqs.push_back(mergedMin[i]);
467 }else{ //get minimum from file
469 while (!filehandle.eof()) {
471 filehandle >> firstName >> secondName >> distance; m->gobble(filehandle);
473 if (prevDistance == -1) { prevDistance = distance; }
475 if (distance != -1) { //-1 means skip me
476 //are the distances the same
477 if (distance == prevDistance) { //save in vector
478 seqDist temp(firstName, secondName, distance);
479 sameSeqs.push_back(temp);
488 //randomize matching dists
489 random_shuffle(sameSeqs.begin(), sameSeqs.end());
491 //can only return one value since once these are merged the other distances in sameSeqs may have changed
492 vector<seqDist> temp;
493 if (sameSeqs.size() > 0) { temp.push_back(sameSeqs[0]); }
497 catch(exception& e) {
498 m->errorOut(e, "HCluster", "getSeqsAN");
503 /***********************************************************************/
504 int HCluster::combineFile() {
506 //int bufferSize = 64000; //512k - this should be a variable that the user can set to optimize code to their hardware
508 //inputBuffer = new char[bufferSize];
511 string tempDistFile = distfile + ".temp";
513 m->openOutputFile(tempDistFile, out);
516 //in = fopen(distfile.c_str(), "rb");
519 m->openInputFile(distfile, in, "no error");
524 vector< map<int, float> > smallRowColValues;
525 smallRowColValues.resize(2); //0 = row, 1 = col
528 //go through file pulling out distances related to rows merging
529 //if mergedMin contains distances add those back into file
532 //while ((numRead = fread(inputBuffer, 1, bufferSize, in)) != 0) {
533 //cout << "number of char read = " << numRead << endl;
534 //cout << inputBuffer << endl;
535 //if (numRead < bufferSize) { done = true; }
537 //parse input into individual distances
539 //string outputString = "";
540 //while(spot < numRead) {
541 //cout << "spot = " << spot << endl;
542 // seqDist nextDist = getNextDist(inputBuffer, spot, bufferSize);
544 //you read a partial distance
545 // if (nextDist.seq1 == -1) { break; }
547 //first = nextDist.seq1; second = nextDist.seq2; dist = nextDist.dist;
548 //cout << "next distance = " << first << '\t' << second << '\t' << dist << endl;
549 //since file is sorted and mergedMin is sorted
550 //you can put the smallest distance from each through the code below and keep the file sorted
552 in >> first >> second >> dist; m->gobble(in);
554 if (m->control_pressed) { in.close(); out.close(); remove(tempDistFile.c_str()); return 0; }
556 //while there are still values in mergedMin that are smaller than the distance read from file
557 while (count < mergedMin.size()) {
559 //is the distance in mergedMin smaller than from the file
560 if (mergedMin[count].dist < dist) {
561 //is this a distance related to the columns merging?
562 //if yes, save in memory
563 if ((mergedMin[count].seq1 == smallRow) && (mergedMin[count].seq2 == smallCol)) { //do nothing this is the smallest distance from last time
564 }else if (mergedMin[count].seq1 == smallCol) {
565 smallRowColValues[1][mergedMin[count].seq2] = mergedMin[count].dist;
566 }else if (mergedMin[count].seq2 == smallCol) {
567 smallRowColValues[1][mergedMin[count].seq1] = mergedMin[count].dist;
568 }else if (mergedMin[count].seq1 == smallRow) {
569 smallRowColValues[0][mergedMin[count].seq2] = mergedMin[count].dist;
570 }else if (mergedMin[count].seq2 == smallRow) {
571 smallRowColValues[0][mergedMin[count].seq1] = mergedMin[count].dist;
572 }else { //if no, write to temp file
573 //outputString += toString(mergedMin[count].seq1) + '\t' + toString(mergedMin[count].seq2) + '\t' + toString(mergedMin[count].dist) + '\n';
574 //if (mergedMin[count].dist < cutoff) {
575 out << mergedMin[count].seq1 << '\t' << mergedMin[count].seq2 << '\t' << mergedMin[count].dist << endl;
582 //is this a distance related to the columns merging?
583 //if yes, save in memory
584 if ((first == smallRow) && (second == smallCol)) { //do nothing this is the smallest distance from last time
585 }else if (first == smallCol) {
586 smallRowColValues[1][second] = dist;
587 }else if (second == smallCol) {
588 smallRowColValues[1][first] = dist;
589 }else if (first == smallRow) {
590 smallRowColValues[0][second] = dist;
591 }else if (second == smallRow) {
592 smallRowColValues[0][first] = dist;
594 }else { //if no, write to temp file
595 //outputString += toString(first) + '\t' + toString(second) + '\t' + toString(dist) + '\n';
596 //if (dist < cutoff) {
597 out << first << '\t' << second << '\t' << dist << endl;
602 //out << outputString;
603 //if(done) { break; }
608 //if values in mergedMin are larger than the the largest in file then
609 while (count < mergedMin.size()) {
610 //is this a distance related to the columns merging?
611 //if yes, save in memory
612 if ((mergedMin[count].seq1 == smallRow) && (mergedMin[count].seq2 == smallCol)) { //do nothing this is the smallest distance from last time
613 }else if (mergedMin[count].seq1 == smallCol) {
614 smallRowColValues[1][mergedMin[count].seq2] = mergedMin[count].dist;
615 }else if (mergedMin[count].seq2 == smallCol) {
616 smallRowColValues[1][mergedMin[count].seq1] = mergedMin[count].dist;
617 }else if (mergedMin[count].seq1 == smallRow) {
618 smallRowColValues[0][mergedMin[count].seq2] = mergedMin[count].dist;
619 }else if (mergedMin[count].seq2 == smallRow) {
620 smallRowColValues[0][mergedMin[count].seq1] = mergedMin[count].dist;
622 }else { //if no, write to temp file
623 //if (mergedMin[count].dist < cutoff) {
624 out << mergedMin[count].seq1 << '\t' << mergedMin[count].seq2 << '\t' << mergedMin[count].dist << endl;
632 //rename tempfile to distfile
633 remove(distfile.c_str());
634 rename(tempDistFile.c_str(), distfile.c_str());
635 //cout << "remove = "<< renameOK << " rename = " << ok << endl;
637 //merge clustered rows averaging the distances
638 map<int, float>::iterator itMerge;
639 map<int, float>::iterator it2Merge;
640 for(itMerge = smallRowColValues[0].begin(); itMerge != smallRowColValues[0].end(); itMerge++) {
641 //does smallRowColValues[1] have a distance to this seq too?
642 it2Merge = smallRowColValues[1].find(itMerge->first);
645 if (it2Merge != smallRowColValues[1].end()) { //if yes, then average
647 if (method == "average") {
648 int total = clusterArray[smallRow].numSeq + clusterArray[smallCol].numSeq;
649 average = ((clusterArray[smallRow].numSeq * itMerge->second) + (clusterArray[smallCol].numSeq * it2Merge->second)) / (float) total;
651 average = ((itMerge->second * 1.0) + (it2Merge->second * 1.0)) / (float) 2.0;
654 smallRowColValues[1].erase(it2Merge);
656 seqDist temp(clusterArray[smallRow].parent, itMerge->first, average);
657 mergedMin.push_back(temp);
659 //can't find value so update cutoff
660 if (cutoff > itMerge->second) { cutoff = itMerge->second; }
665 for(itMerge = smallRowColValues[1].begin(); itMerge != smallRowColValues[1].end(); itMerge++) {
666 if (cutoff > itMerge->second) { cutoff = itMerge->second; }
670 sort(mergedMin.begin(), mergedMin.end(), compareSequenceDistance);
674 catch(exception& e) {
675 m->errorOut(e, "HCluster", "combineFile");
679 /***********************************************************************
680 seqDist HCluster::getNextDist(char* buffer, int& index, int size){
683 int indexBefore = index;
684 string first, second, distance;
685 first = ""; second = ""; distance = "";
687 //cout << "partial = " << partialDist << endl;
688 if (partialDist != "") { //read what you can, you know it is less than a whole distance.
689 for (int i = 0; i < partialDist.size(); i++) {
691 if (partialDist[i] == '\t') { tabCount++; }
692 else { first += partialDist[i]; }
693 }else if (tabCount == 1) {
694 if (partialDist[i] == '\t') { tabCount++; }
695 else { second += partialDist[i]; }
696 }else if (tabCount == 2) {
697 distance += partialDist[i];
703 //try to get another distance
704 bool gotDist = false;
705 while (index < size) {
706 if ((buffer[index] == 10) || (buffer[index] == 13)) { //newline in unix or windows
710 while (index < size) {
711 if (isspace(buffer[index])) { index++; }
717 if (buffer[index] == '\t') { tabCount++; }
718 else { first += buffer[index]; }
719 }else if (tabCount == 1) {
720 if (buffer[index] == '\t') { tabCount++; }
721 else { second += buffer[index]; }
722 }else if (tabCount == 2) {
723 distance += buffer[index];
729 //there was not a whole distance in the buffer, ie. buffer = "1 2 0.01 2 3 0."
730 //then you want to save the partial distance.
732 for (int i = indexBefore; i < size; i++) {
733 partialDist += buffer[i];
736 next.seq1 = -1; next.seq2 = -1; next.dist = 0.0;
738 int firstname, secondname;
741 convert(first, firstname);
742 convert(second, secondname);
743 convert(distance, dist);
745 next.seq1 = firstname; next.seq2 = secondname; next.dist = dist;
750 catch(exception& e) {
751 m->errorOut(e, "HCluster", "getNextDist");
755 /***********************************************************************/
756 int HCluster::processFile() {
758 string firstName, secondName;
762 m->openInputFile(distfile, in, "no error");
765 string outTemp = distfile + ".temp";
766 m->openOutputFile(outTemp, out);
770 if (m->control_pressed) { in.close(); out.close(); remove(outTemp.c_str()); return 0; }
772 in >> firstName >> secondName >> distance; m->gobble(in);
774 map<string,int>::iterator itA = nameMap->find(firstName);
775 map<string,int>::iterator itB = nameMap->find(secondName);
776 if(itA == nameMap->end()){ m->mothurOut("AAError: Sequence '" + firstName + "' was not found in the names file, please correct\n"); exit(1); }
777 if(itB == nameMap->end()){ m->mothurOut("ABError: Sequence '" + secondName + "' was not found in the names file, please correct\n"); exit(1); }
780 if (distance > cutoff) { break; }
782 if (distance != -1) { //-1 means skip me
783 out << itA->second << '\t' << itB->second << '\t' << distance << endl;
790 remove(distfile.c_str());
791 rename(outTemp.c_str(), distfile.c_str());
795 catch(exception& e) {
796 m->errorOut(e, "HCluster", "processFile");
800 /***********************************************************************/