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 m, string d, NameAssignment* n, float c) : rabund(rav), list(lv), method(m), distfile(d), nameMap(n), cutoff(c) {
20 numSeqs = list->getNumSeqs();
22 //initialize cluster array
23 for (int i = 0; i < numSeqs; i++) {
24 clusterNode temp(1, -1, i);
25 clusterArray.push_back(temp);
28 if (method != "average") {
29 openInputFile(distfile, filehandle);
35 errorOut(e, "HCluster", "HCluster");
39 /***********************************************************************/
41 void HCluster::clusterBins(){
43 //cout << smallCol << '\t' << smallRow << '\t' << smallDist << '\t' << rabund->get(clusterArray[smallRow].smallChild) << '\t' << rabund->get(clusterArray[smallCol].smallChild);
45 rabund->set(clusterArray[smallCol].smallChild, rabund->get(clusterArray[smallRow].smallChild)+rabund->get(clusterArray[smallCol].smallChild));
46 rabund->set(clusterArray[smallRow].smallChild, 0);
47 rabund->setLabel(toString(smallDist));
49 //cout << '\t' << rabund->get(clusterArray[smallRow].smallChild) << '\t' << rabund->get(clusterArray[smallCol].smallChild) << endl;
52 errorOut(e, "HCluster", "clusterBins");
59 /***********************************************************************/
61 void HCluster::clusterNames(){
63 ///cout << smallCol << '\t' << smallRow << '\t' << smallDist << '\t' << list->get(clusterArray[smallRow].smallChild) << '\t' << list->get(clusterArray[smallCol].smallChild);
64 if (mapWanted) { updateMap(); }
66 list->set(clusterArray[smallCol].smallChild, list->get(clusterArray[smallRow].smallChild)+','+list->get(clusterArray[smallCol].smallChild));
67 list->set(clusterArray[smallRow].smallChild, "");
68 list->setLabel(toString(smallDist));
70 //cout << '\t' << list->get(clusterArray[smallRow].smallChild) << '\t' << list->get(clusterArray[smallCol].smallChild) << endl;
74 errorOut(e, "HCluster", "clusterNames");
79 /***********************************************************************/
80 int HCluster::getUpmostParent(int node){
82 while (clusterArray[node].parent != -1) {
83 node = clusterArray[node].parent;
89 errorOut(e, "HCluster", "getUpmostParent");
93 /***********************************************************************/
94 void HCluster::printInfo(){
97 cout << "link table" << endl;
98 for (itActive = activeLinks.begin(); itActive!= activeLinks.end(); itActive++) {
99 cout << itActive->first << " = " << itActive->second << endl;
102 for (int i = 0; i < linkTable.size(); i++) {
104 for (it = linkTable[i].begin(); it != linkTable[i].end(); it++) {
105 cout << it->first << '-' << it->second << '\t' ;
109 cout << endl << "clusterArray" << endl;
111 for (int i = 0; i < clusterArray.size(); i++) {
112 cout << i << '\t' << clusterArray[i].numSeq << '\t' << clusterArray[i].parent << '\t' << clusterArray[i].smallChild << endl;
118 catch(exception& e) {
119 errorOut(e, "HCluster", "getUpmostParent");
123 /***********************************************************************/
124 int HCluster::makeActive() {
128 itActive = activeLinks.find(smallRow);
129 it2Active = activeLinks.find(smallCol);
131 if ((itActive == activeLinks.end()) && (it2Active == activeLinks.end())) { //both are not active so add them
132 int size = linkTable.size();
133 map<int, int> temp; map<int, int> temp2;
135 //add link to eachother
136 temp[smallRow] = 1; // 1 2
137 temp2[smallCol] = 1; // 1 0 1
139 linkTable.push_back(temp);
140 linkTable.push_back(temp2);
143 activeLinks[smallRow] = size;
144 activeLinks[smallCol] = size+1;
146 }else if ((itActive != activeLinks.end()) && (it2Active == activeLinks.end())) { //smallRow is active, smallCol is not
147 int size = linkTable.size();
148 int alreadyActiveRow = itActive->second;
151 //add link to eachother
152 temp[smallRow] = 1; // 6 2 3 5
153 linkTable.push_back(temp); // 6 0 1 2 0
154 linkTable[alreadyActiveRow][smallCol] = 1; // 2 1 0 1 1
158 activeLinks[smallCol] = size;
160 }else if ((itActive == activeLinks.end()) && (it2Active != activeLinks.end())) { //smallCol is active, smallRow is not
161 int size = linkTable.size();
162 int alreadyActiveCol = it2Active->second;
165 //add link to eachother
166 temp[smallCol] = 1; // 6 2 3 5
167 linkTable.push_back(temp); // 6 0 1 2 0
168 linkTable[alreadyActiveCol][smallRow] = 1; // 2 1 0 1 1
172 activeLinks[smallRow] = size;
174 }else { //both are active so add one
175 int row = itActive->second;
176 int col = it2Active->second;
179 linkTable[row][smallCol]++;
180 linkTable[col][smallRow]++;
181 linkValue = linkTable[row][smallCol];
186 catch(exception& e) {
187 errorOut(e, "HCluster", "makeActive");
191 /***********************************************************************/
192 void HCluster::updateArrayandLinkTable() {
194 //if cluster was made update clusterArray and linkTable
195 int size = clusterArray.size();
198 clusterNode temp(clusterArray[smallRow].numSeq + clusterArray[smallCol].numSeq, -1, clusterArray[smallCol].smallChild);
199 clusterArray.push_back(temp);
202 clusterArray[smallRow].parent = size;
203 clusterArray[smallCol].parent = size;
205 if (method == "furthest") {
207 //update linkTable by merging clustered rows and columns
208 int rowSpot = activeLinks[smallRow];
209 int colSpot = activeLinks[smallCol];
212 for (int i = 0; i < linkTable.size(); i++) {
213 //check if they are in map
214 it = linkTable[i].find(smallRow);
215 it2 = linkTable[i].find(smallCol);
217 if ((it!=linkTable[i].end()) && (it2!=linkTable[i].end())) { //they are both there
218 linkTable[i][size] = linkTable[i][smallRow]+linkTable[i][smallCol];
219 linkTable[i].erase(smallCol); //delete col row
220 linkTable[i].erase(smallRow); //delete col row
221 }else if ((it==linkTable[i].end()) && (it2!=linkTable[i].end())) { //only col
222 linkTable[i][size] = linkTable[i][smallCol];
223 linkTable[i].erase(smallCol); //delete col
224 }else if ((it!=linkTable[i].end()) && (it2==linkTable[i].end())) { //only row
225 linkTable[i][size] = linkTable[i][smallRow];
226 linkTable[i].erase(smallRow); //delete col
231 for (it = linkTable[rowSpot].begin(); it != linkTable[rowSpot].end(); it++) {
232 it2 = linkTable[colSpot].find(it->first); //does the col also have this
234 if (it2 == linkTable[colSpot].end()) { //not there so add it
235 linkTable[colSpot][it->first] = it->second;
237 linkTable[colSpot][it->first] = it->second + it2->second;
241 linkTable[colSpot].erase(size);
242 linkTable.erase(linkTable.begin()+rowSpot); //delete row
245 activeLinks.erase(smallRow);
246 activeLinks.erase(smallCol);
247 activeLinks[size] = colSpot;
249 //adjust everybody elses spot since you deleted - time vs. space
250 for (itActive = activeLinks.begin(); itActive != activeLinks.end(); itActive++) {
251 if (itActive->second > rowSpot) { activeLinks[itActive->first]--; }
255 catch(exception& e) {
256 errorOut(e, "HCluster", "updateArrayandLinkTable");
260 /***********************************************************************/
261 bool HCluster::update(int row, int col, float distance){
263 bool cluster = false;
266 smallDist = distance;
268 //find upmost parent of row and col
269 smallRow = getUpmostParent(smallRow);
270 smallCol = getUpmostParent(smallCol);
272 //you don't want to cluster with yourself
273 if (smallRow != smallCol) {
275 if (method != "average") {
277 if (method == "nearest") { cluster = true; }
278 else{ //assume furthest
279 //are they active in the link table
280 int linkValue = makeActive(); //after this point this nodes info is active in linkTable
281 if (linkValue == (clusterArray[smallRow].numSeq * clusterArray[smallCol].numSeq)) { cluster = true; }
285 updateArrayandLinkTable();
291 updateArrayandLinkTable();
301 catch(exception& e) {
302 errorOut(e, "HCluster", "update");
306 /***********************************************************************/
307 void HCluster::setMapWanted(bool m) {
312 for (int i = 0; i < list->getNumBins(); i++) {
315 string names = list->get(i);
316 while (names.find_first_of(',') != -1) {
318 string name = names.substr(0,names.find_first_of(','));
319 //save name and bin number
321 names = names.substr(names.find_first_of(',')+1, names.length());
329 catch(exception& e) {
330 errorOut(e, "HCluster", "setMapWanted");
334 /***********************************************************************/
335 void HCluster::updateMap() {
337 //update location of seqs in smallRow since they move to smallCol now
338 string names = list->get(clusterArray[smallRow].smallChild);
339 while (names.find_first_of(',') != -1) {
341 string name = names.substr(0,names.find_first_of(','));
342 //save name and bin number
343 seq2Bin[name] = clusterArray[smallCol].smallChild;
344 names = names.substr(names.find_first_of(',')+1, names.length());
348 seq2Bin[names] = clusterArray[smallCol].smallChild;
350 catch(exception& e) {
351 errorOut(e, "HCluster", "updateMap");
355 //**********************************************************************************************************************
356 vector<seqDist> HCluster::getSeqs(){
358 vector<seqDist> sameSeqs;
360 if(method != "average") {
361 sameSeqs = getSeqsFNNN();
363 sameSeqs = getSeqsAN();
368 catch(exception& e) {
369 errorOut(e, "HCluster", "getSeqs");
373 //**********************************************************************************************************************
374 vector<seqDist> HCluster::getSeqsFNNN(){
376 string firstName, secondName;
377 float distance, prevDistance;
378 vector<seqDist> sameSeqs;
381 //if you are not at the beginning of the file
383 sameSeqs.push_back(next);
384 prevDistance = next.dist;
389 while (!filehandle.eof()) {
391 filehandle >> firstName >> secondName >> distance; gobble(filehandle);
394 if (prevDistance == -1) { prevDistance = distance; }
396 map<string,int>::iterator itA = nameMap->find(firstName);
397 map<string,int>::iterator itB = nameMap->find(secondName);
398 if(itA == nameMap->end()){ cerr << "AAError: Sequence '" << firstName << "' was not found in the names file, please correct\n"; exit(1); }
399 if(itB == nameMap->end()){ cerr << "ABError: Sequence '" << secondName << "' was not found in the names file, please correct\n"; exit(1); }
402 if (distance > cutoff) { break; }
404 if (distance != -1) { //-1 means skip me
406 //are the distances the same
407 if (distance == prevDistance) { //save in vector
408 seqDist temp(itA->second, itB->second, distance);
409 sameSeqs.push_back(temp);
412 next.seq1 = itA->second;
413 next.seq2 = itB->second;
414 next.dist = distance;
421 //rndomize matching dists
422 random_shuffle(sameSeqs.begin(), sameSeqs.end());
426 catch(exception& e) {
427 errorOut(e, "HCluster", "getSeqsFNNN");
431 //**********************************************************************************************************************
432 //don't need cutoff since processFile removes all distance above cutoff and changes names to indexes
433 vector<seqDist> HCluster::getSeqsAN(){
435 int firstName, secondName;
437 vector<seqDist> sameSeqs;
440 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; 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);
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; 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 errorOut(e, "HCluster", "getSeqsAN");
503 /***********************************************************************/
504 void 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 openOutputFile(tempDistFile, out);
516 //in = fopen(distfile.c_str(), "rb");
519 openInputFile(distfile, in);
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; gobble(in);
554 //while there are still values in mergedMin that are smaller than the distance read from file
555 while (count < mergedMin.size()) {
557 //is the distance in mergedMin smaller than from the file
558 if (mergedMin[count].dist < dist) {
559 //is this a distance related to the columns merging?
560 //if yes, save in memory
561 if ((mergedMin[count].seq1 == smallRow) && (mergedMin[count].seq2 == smallCol)) { //do nothing this is the smallest distance from last time
562 }else if (mergedMin[count].seq1 == smallCol) {
563 smallRowColValues[1][mergedMin[count].seq2] = mergedMin[count].dist;
564 }else if (mergedMin[count].seq2 == smallCol) {
565 smallRowColValues[1][mergedMin[count].seq1] = mergedMin[count].dist;
566 }else if (mergedMin[count].seq1 == smallRow) {
567 smallRowColValues[0][mergedMin[count].seq2] = mergedMin[count].dist;
568 }else if (mergedMin[count].seq2 == smallRow) {
569 smallRowColValues[0][mergedMin[count].seq1] = mergedMin[count].dist;
570 }else { //if no, write to temp file
571 //outputString += toString(mergedMin[count].seq1) + '\t' + toString(mergedMin[count].seq2) + '\t' + toString(mergedMin[count].dist) + '\n';
572 out << mergedMin[count].seq1 << '\t' << mergedMin[count].seq2 << '\t' << mergedMin[count].dist << endl;
578 //is this a distance related to the columns merging?
579 //if yes, save in memory
580 if ((first == smallRow) && (second == smallCol)) { //do nothing this is the smallest distance from last time
581 }else if (first == smallCol) {
582 smallRowColValues[1][second] = dist;
583 }else if (second == smallCol) {
584 smallRowColValues[1][first] = dist;
585 }else if (first == smallRow) {
586 smallRowColValues[0][second] = dist;
587 }else if (second == smallRow) {
588 smallRowColValues[0][first] = dist;
590 }else { //if no, write to temp file
591 //outputString += toString(first) + '\t' + toString(second) + '\t' + toString(dist) + '\n';
592 out << first << '\t' << second << '\t' << dist << endl;
596 //out << outputString;
597 //if(done) { break; }
602 //if values in mergedMin are larger than the the largest in file then
603 while (count < mergedMin.size()) {
604 //is this a distance related to the columns merging?
605 //if yes, save in memory
606 if ((mergedMin[count].seq1 == smallRow) && (mergedMin[count].seq2 == smallCol)) { //do nothing this is the smallest distance from last time
607 }else if (mergedMin[count].seq1 == smallCol) {
608 smallRowColValues[1][mergedMin[count].seq2] = mergedMin[count].dist;
609 }else if (mergedMin[count].seq2 == smallCol) {
610 smallRowColValues[1][mergedMin[count].seq1] = mergedMin[count].dist;
611 }else if (mergedMin[count].seq1 == smallRow) {
612 smallRowColValues[0][mergedMin[count].seq2] = mergedMin[count].dist;
613 }else if (mergedMin[count].seq2 == smallRow) {
614 smallRowColValues[0][mergedMin[count].seq1] = mergedMin[count].dist;
616 }else { //if no, write to temp file
617 out << mergedMin[count].seq1 << '\t' << mergedMin[count].seq2 << '\t' << mergedMin[count].dist << endl;
624 //rename tempfile to distfile
625 int renameOK = remove(distfile.c_str());
626 int ok = rename(tempDistFile.c_str(), distfile.c_str());
627 //cout << "remove = "<< renameOK << " rename = " << ok << endl;
629 //merge clustered rows averaging the distances
630 map<int, float>::iterator itMerge;
631 map<int, float>::iterator it2Merge;
632 for(itMerge = smallRowColValues[0].begin(); itMerge != smallRowColValues[0].end(); itMerge++) {
633 //does smallRowColValues[1] have a distance to this seq too?
634 it2Merge = smallRowColValues[1].find(itMerge->first);
637 if (it2Merge != smallRowColValues[1].end()) { //if yes, then average
639 int total = clusterArray[smallRow].numSeq + clusterArray[smallCol].numSeq;
640 average = ((clusterArray[smallRow].numSeq * itMerge->second) + (clusterArray[smallCol].numSeq * it2Merge->second)) / (float) total;
641 smallRowColValues[1].erase(it2Merge);
643 seqDist temp(clusterArray[smallRow].parent, itMerge->first, average);
644 mergedMin.push_back(temp);
649 sort(mergedMin.begin(), mergedMin.end(), compareSequenceDistance);
651 catch(exception& e) {
652 errorOut(e, "HCluster", "combineFile");
656 /***********************************************************************
657 seqDist HCluster::getNextDist(char* buffer, int& index, int size){
660 int indexBefore = index;
661 string first, second, distance;
662 first = ""; second = ""; distance = "";
664 //cout << "partial = " << partialDist << endl;
665 if (partialDist != "") { //read what you can, you know it is less than a whole distance.
666 for (int i = 0; i < partialDist.size(); i++) {
668 if (partialDist[i] == '\t') { tabCount++; }
669 else { first += partialDist[i]; }
670 }else if (tabCount == 1) {
671 if (partialDist[i] == '\t') { tabCount++; }
672 else { second += partialDist[i]; }
673 }else if (tabCount == 2) {
674 distance += partialDist[i];
680 //try to get another distance
681 bool gotDist = false;
682 while (index < size) {
683 if ((buffer[index] == 10) || (buffer[index] == 13)) { //newline in unix or windows
687 while (index < size) {
688 if (isspace(buffer[index])) { index++; }
694 if (buffer[index] == '\t') { tabCount++; }
695 else { first += buffer[index]; }
696 }else if (tabCount == 1) {
697 if (buffer[index] == '\t') { tabCount++; }
698 else { second += buffer[index]; }
699 }else if (tabCount == 2) {
700 distance += buffer[index];
706 //there was not a whole distance in the buffer, ie. buffer = "1 2 0.01 2 3 0."
707 //then you want to save the partial distance.
709 for (int i = indexBefore; i < size; i++) {
710 partialDist += buffer[i];
713 next.seq1 = -1; next.seq2 = -1; next.dist = 0.0;
715 int firstname, secondname;
718 convert(first, firstname);
719 convert(second, secondname);
720 convert(distance, dist);
722 next.seq1 = firstname; next.seq2 = secondname; next.dist = dist;
727 catch(exception& e) {
728 errorOut(e, "HCluster", "getNextDist");
732 /***********************************************************************/
733 void HCluster::processFile() {
735 string firstName, secondName;
739 openInputFile(distfile, in);
742 string outTemp = distfile + ".temp";
743 openOutputFile(outTemp, out);
748 in >> firstName >> secondName >> distance; gobble(in);
750 map<string,int>::iterator itA = nameMap->find(firstName);
751 map<string,int>::iterator itB = nameMap->find(secondName);
752 if(itA == nameMap->end()){ cerr << "AAError: Sequence '" << firstName << "' was not found in the names file, please correct\n"; exit(1); }
753 if(itB == nameMap->end()){ cerr << "ABError: Sequence '" << secondName << "' was not found in the names file, please correct\n"; exit(1); }
756 if (distance > cutoff) { break; }
758 if (distance != -1) { //-1 means skip me
759 out << itA->second << '\t' << itB->second << '\t' << distance << endl;
766 remove(distfile.c_str());
767 rename(outTemp.c_str(), distfile.c_str());
769 catch(exception& e) {
770 errorOut(e, "HCluster", "processFile");
774 /***********************************************************************/