2 * treegroupscommand.cpp
5 * Created by Sarah Westcott on 4/8/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "treegroupscommand.h"
11 #include "sharedjabund.h"
12 #include "sharedsorabund.h"
13 #include "sharedjclass.h"
14 #include "sharedsorclass.h"
15 #include "sharedjest.h"
16 #include "sharedsorest.h"
17 #include "sharedthetayc.h"
18 #include "sharedthetan.h"
19 #include "sharedmorisitahorn.h"
20 #include "sharedbraycurtis.h"
22 //**********************************************************************************************************************
23 vector<string> TreeGroupCommand::getValidParameters(){
25 string Array[] = {"label","calc","groups", "phylip", "column", "name", "precision","cutoff","outputdir","inputdir"};
26 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
30 m->errorOut(e, "TreeGroupCommand", "getValidParameters");
34 //**********************************************************************************************************************
35 TreeGroupCommand::TreeGroupCommand(){
37 //initialize outputTypes
38 vector<string> tempOutNames;
39 outputTypes["tree"] = tempOutNames;
42 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
46 //**********************************************************************************************************************
47 vector<string> TreeGroupCommand::getRequiredParameters(){
49 vector<string> myArray;
53 m->errorOut(e, "TreeGroupCommand", "getRequiredParameters");
57 //**********************************************************************************************************************
58 vector<string> TreeGroupCommand::getRequiredFiles(){
60 string Array[] = {"phylip","column","shared","or"};
61 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
65 m->errorOut(e, "TreeGroupCommand", "getRequiredFiles");
69 //**********************************************************************************************************************
71 TreeGroupCommand::TreeGroupCommand(string option) {
73 globaldata = GlobalData::getInstance();
80 //allow user to run help
81 if(option == "help") { validCalculator = new ValidCalculators(); help(); abort = true; }
84 //valid paramters for this command
85 string Array[] = {"label","calc","groups", "phylip", "column", "name", "precision","cutoff","outputdir","inputdir"};
86 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
88 OptionParser parser(option);
89 map<string, string> parameters = parser. getParameters();
91 ValidParameters validParameter;
92 map<string, string>::iterator it;
94 //check to make sure all parameters are valid for command
95 for (it = parameters.begin(); it != parameters.end(); it++) {
96 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
99 //initialize outputTypes
100 vector<string> tempOutNames;
101 outputTypes["tree"] = tempOutNames;
103 //if the user changes the input directory command factory will send this info to us in the output parameter
104 string inputDir = validParameter.validFile(parameters, "inputdir", false);
105 if (inputDir == "not found"){ inputDir = ""; }
108 it = parameters.find("phylip");
109 //user has given a template file
110 if(it != parameters.end()){
111 path = m->hasPath(it->second);
112 //if the user has not given a path then, add inputdir. else leave path alone.
113 if (path == "") { parameters["phylip"] = inputDir + it->second; }
116 it = parameters.find("column");
117 //user has given a template file
118 if(it != parameters.end()){
119 path = m->hasPath(it->second);
120 //if the user has not given a path then, add inputdir. else leave path alone.
121 if (path == "") { parameters["column"] = inputDir + it->second; }
124 it = parameters.find("name");
125 //user has given a template file
126 if(it != parameters.end()){
127 path = m->hasPath(it->second);
128 //if the user has not given a path then, add inputdir. else leave path alone.
129 if (path == "") { parameters["name"] = inputDir + it->second; }
133 format = globaldata->getFormat();
135 //required parameters
136 phylipfile = validParameter.validFile(parameters, "phylip", true);
137 if (phylipfile == "not open") { abort = true; }
138 else if (phylipfile == "not found") { phylipfile = ""; }
139 else { globaldata->newRead(); format = "phylip"; globaldata->setPhylipFile(phylipfile); }
141 columnfile = validParameter.validFile(parameters, "column", true);
142 if (columnfile == "not open") { abort = true; }
143 else if (columnfile == "not found") { columnfile = ""; }
144 else { globaldata->newRead(); format = "column"; globaldata->setColumnFile(columnfile); }
146 namefile = validParameter.validFile(parameters, "name", true);
147 if (namefile == "not open") { abort = true; }
148 else if (namefile == "not found") { namefile = ""; }
149 else { globaldata->setNameFile(namefile); }
151 //error checking on files
152 if ((globaldata->getSharedFile() == "") && ((phylipfile == "") && (columnfile == ""))) { m->mothurOut("You must run the read.otu command or provide a distance file before running the tree.shared command."); m->mothurOutEndLine(); abort = true; }
153 else if ((phylipfile != "") && (columnfile != "")) { m->mothurOut("When running the tree.shared command with a distance file you may not use both the column and the phylip parameters."); m->mothurOutEndLine(); abort = true; }
155 if (columnfile != "") {
156 if (namefile == "") { m->mothurOut("You need to provide a namefile if you are going to use the column format."); m->mothurOutEndLine(); abort = true; }
159 //check for optional parameter and set defaults
160 // ...at some point should added some additional type checking...
161 label = validParameter.validFile(parameters, "label", false);
162 if (label == "not found") { label = ""; }
164 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
165 else { allLines = 1; }
168 //if the user has not specified any labels use the ones from read.otu
170 allLines = globaldata->allLines;
171 labels = globaldata->labels;
174 groups = validParameter.validFile(parameters, "groups", false);
175 if (groups == "not found") { groups = ""; }
177 m->splitAtDash(groups, Groups);
178 globaldata->Groups = Groups;
181 calc = validParameter.validFile(parameters, "calc", false);
182 if (calc == "not found") { calc = "jclass-thetayc"; }
184 if (calc == "default") { calc = "jclass-thetayc"; }
186 m->splitAtDash(calc, Estimators);
189 temp = validParameter.validFile(parameters, "precision", false); if (temp == "not found") { temp = "100"; }
190 convert(temp, precision);
192 temp = validParameter.validFile(parameters, "cutoff", false); if (temp == "not found") { temp = "10"; }
193 convert(temp, cutoff);
194 cutoff += (5 / (precision * 10.0));
196 //if the user changes the output directory command factory will send this info to us in the output parameter
197 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
199 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
203 if (abort == false) {
205 validCalculator = new ValidCalculators();
207 if (format == "sharedfile") {
209 for (i=0; i<Estimators.size(); i++) {
210 if (validCalculator->isValidCalculator("treegroup", Estimators[i]) == true) {
211 if (Estimators[i] == "jabund") {
212 treeCalculators.push_back(new JAbund());
213 }else if (Estimators[i] == "sorabund") {
214 treeCalculators.push_back(new SorAbund());
215 }else if (Estimators[i] == "jclass") {
216 treeCalculators.push_back(new Jclass());
217 }else if (Estimators[i] == "sorclass") {
218 treeCalculators.push_back(new SorClass());
219 }else if (Estimators[i] == "jest") {
220 treeCalculators.push_back(new Jest());
221 }else if (Estimators[i] == "sorest") {
222 treeCalculators.push_back(new SorEst());
223 }else if (Estimators[i] == "thetayc") {
224 treeCalculators.push_back(new ThetaYC());
225 }else if (Estimators[i] == "thetan") {
226 treeCalculators.push_back(new ThetaN());
227 }else if (Estimators[i] == "morisitahorn") {
228 treeCalculators.push_back(new MorHorn());
229 }else if (Estimators[i] == "braycurtis") {
230 treeCalculators.push_back(new BrayCurtis());
239 catch(exception& e) {
240 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
245 //**********************************************************************************************************************
247 void TreeGroupCommand::help(){
249 m->mothurOut("The tree.shared command creates a .tre to represent the similiarity between groups or sequences.\n");
250 m->mothurOut("The tree.shared command can only be executed after a successful read.otu command or by providing a distance file.\n");
251 m->mothurOut("The tree.shared command parameters are groups, calc, phylip, column, name, cutoff, precision and label.\n");
252 m->mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n");
253 m->mothurOut("The group names are separated by dashes. The label allow you to select what distance levels you would like trees created for, and are also separated by dashes.\n");
254 m->mothurOut("The phylip or column parameter are required if you do not run the read.otu command first, and only one may be used. If you use a column file the name filename is required. \n");
255 m->mothurOut("If you do not provide a cutoff value 10.00 is assumed. If you do not provide a precision value then 100 is assumed.\n");
256 m->mothurOut("The tree.shared command should be in the following format: tree.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels).\n");
257 m->mothurOut("Example tree.shared(groups=A-B-C, calc=jabund-sorabund).\n");
258 m->mothurOut("The default value for groups is all the groups in your groupfile.\n");
259 m->mothurOut("The default value for calc is jclass-thetayc.\n");
260 m->mothurOut("The tree.shared command outputs a .tre file for each calculator you specify at each distance you choose.\n");
261 validCalculator->printCalc("treegroup", cout);
262 m->mothurOut("Or the tree.shared command can be in the following format: tree.shared(phylip=yourPhylipFile).\n");
263 m->mothurOut("Example tree.shared(phylip=abrecovery.dist).\n");
264 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
266 catch(exception& e) {
267 m->errorOut(e, "TreeGroupCommand", "help");
273 //**********************************************************************************************************************
275 TreeGroupCommand::~TreeGroupCommand(){
276 globaldata->Groups.clear();
277 if (abort == false) {
279 if (format == "sharedfile") { delete read; delete input; globaldata->ginput = NULL; }
280 else { delete readMatrix; delete matrix; delete list; }
281 delete tmap; globaldata->gTreemap = NULL;
282 delete validCalculator;
287 //**********************************************************************************************************************
289 int TreeGroupCommand::execute(){
292 if (abort == true) { return 0; }
294 if (format == "sharedfile") {
295 //if the users entered no valid calculators don't execute command
296 if (treeCalculators.size() == 0) { m->mothurOut("You have given no valid calculators."); m->mothurOutEndLine(); return 0; }
298 if (globaldata->gGroupmap != NULL) { delete globaldata->gGroupmap; globaldata->gGroupmap = NULL; }
300 read = new ReadOTUFile(globaldata->inputFileName);
301 read->read(&*globaldata);
303 input = globaldata->ginput;
304 lookup = input->getSharedRAbundVectors();
305 lastLabel = lookup[0]->getLabel();
307 if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups. I cannot run the command."); m->mothurOutEndLine(); return 0; }
309 //used in tree constructor
310 globaldata->runParse = false;
312 //create treemap class from groupmap for tree class to use
313 tmap = new TreeMap();
314 tmap->makeSim(globaldata->gGroupmap);
315 globaldata->gTreemap = tmap;
317 //clear globaldatas old tree names if any
318 globaldata->Treenames.clear();
320 //fills globaldatas tree names
321 globaldata->Treenames = globaldata->Groups;
323 if (m->control_pressed) { return 0; }
328 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
331 filename = globaldata->inputFileName;
333 if (format == "column") { readMatrix = new ReadColumnMatrix(filename); }
334 else if (format == "phylip") { readMatrix = new ReadPhylipMatrix(filename); }
336 readMatrix->setCutoff(cutoff);
339 nameMap = new NameAssignment(namefile);
346 readMatrix->read(nameMap);
347 list = readMatrix->getListVector();
348 matrix = readMatrix->getMatrix();
351 tmap = new TreeMap();
353 if (m->control_pressed) { return 0; }
356 globaldata->gTreemap = tmap;
358 globaldata->Groups = tmap->namesOfGroups;
360 //clear globaldatas old tree names if any
361 globaldata->Treenames.clear();
363 //fills globaldatas tree names
364 globaldata->Treenames = globaldata->Groups;
366 //used in tree constructor
367 globaldata->runParse = false;
369 if (m->control_pressed) { return 0; }
373 if (m->control_pressed) { return 0; }
375 //create a new filename
376 outputFile = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + "tre";
377 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
381 if (m->control_pressed) { return 0; }
383 m->mothurOut("Tree complete. "); m->mothurOutEndLine();
387 //reset groups parameter
388 globaldata->Groups.clear();
390 m->mothurOutEndLine();
391 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
392 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
393 m->mothurOutEndLine();
397 catch(exception& e) {
398 m->errorOut(e, "TreeGroupCommand", "execute");
402 //**********************************************************************************************************************
404 int TreeGroupCommand::createTree(){
409 //do merges and create tree structure by setting parents and children
410 //there are numGroups - 1 merges to do
411 for (int i = 0; i < (numGroups - 1); i++) {
412 float largest = -1000.0;
414 if (m->control_pressed) { delete t; return 1; }
417 //find largest value in sims matrix by searching lower triangle
418 for (int j = 1; j < simMatrix.size(); j++) {
419 for (int k = 0; k < j; k++) {
420 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
424 //set non-leaf node info and update leaves to know their parents
426 t->tree[numGroups + i].setChildren(index[row], index[column]);
429 t->tree[index[row]].setParent(numGroups + i);
430 t->tree[index[column]].setParent(numGroups + i);
432 //blength = distance / 2;
433 float blength = ((1.0 - largest) / 2);
436 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
437 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
439 //set your length to leaves to your childs length plus branchlength
440 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
444 index[row] = numGroups+i;
445 index[column] = numGroups+i;
447 //remove highest value that caused the merge.
448 simMatrix[row][column] = -1000.0;
449 simMatrix[column][row] = -1000.0;
451 //merge values in simsMatrix
452 for (int n = 0; n < simMatrix.size(); n++) {
453 //row becomes merge of 2 groups
454 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
455 simMatrix[n][row] = simMatrix[row][n];
457 simMatrix[column][n] = -1000.0;
458 simMatrix[n][column] = -1000.0;
462 //adjust tree to make sure root to tip length is .5
463 int root = t->findRoot();
464 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
469 if (m->control_pressed) { delete t; return 1; }
472 t->createNewickFile(outputFile);
477 if (m->control_pressed) { remove(outputFile.c_str()); outputNames.pop_back(); return 1; }
482 catch(exception& e) {
483 m->errorOut(e, "TreeGroupCommand", "createTree");
487 /***********************************************************/
488 void TreeGroupCommand::printSims(ostream& out) {
491 //output column headers
493 //for (int i = 0; i < lookup.size(); i++) { out << lookup[i]->getGroup() << '\t'; }
497 for (int m = 0; m < simMatrix.size(); m++) {
498 //out << lookup[m]->getGroup() << '\t';
499 for (int n = 0; n < simMatrix.size(); n++) {
500 out << simMatrix[m][n] << '\t';
506 catch(exception& e) {
507 m->errorOut(e, "TreeGroupCommand", "printSims");
511 /***********************************************************/
512 int TreeGroupCommand::makeSimsDist() {
514 numGroups = list->size();
518 for (int g = 0; g < numGroups; g++) { index[g] = g; }
520 //initialize simMatrix
522 simMatrix.resize(numGroups);
523 for (int k = 0; k < simMatrix.size(); k++) {
524 for (int j = 0; j < simMatrix.size(); j++) {
525 simMatrix[k].push_back(0.0);
529 //go through sparse matrix and fill sims
530 //go through each cell in the sparsematrix
531 for(MatData currentCell = matrix->begin(); currentCell != matrix->end(); currentCell++){
532 //similairity = -(distance-1)
533 simMatrix[currentCell->row][currentCell->column] = -(currentCell->dist -1.0);
534 simMatrix[currentCell->column][currentCell->row] = -(currentCell->dist -1.0);
536 if (m->control_pressed) { return 1; }
542 catch(exception& e) {
543 m->errorOut(e, "TreeGroupCommand", "makeSimsDist");
548 /***********************************************************/
549 int TreeGroupCommand::makeSimsShared() {
551 set<string> processedLabels;
552 set<string> userLabels = labels;
554 //as long as you are not at the end of the file or done wih the lines you want
555 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
556 if (m->control_pressed) { for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } for(int i = 0 ; i < treeCalculators.size(); i++) { delete treeCalculators[i]; } return 1; }
558 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
559 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
562 processedLabels.insert(lookup[0]->getLabel());
563 userLabels.erase(lookup[0]->getLabel());
566 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
567 string saveLabel = lookup[0]->getLabel();
569 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
570 lookup = input->getSharedRAbundVectors(lastLabel);
572 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
575 processedLabels.insert(lookup[0]->getLabel());
576 userLabels.erase(lookup[0]->getLabel());
578 //restore real lastlabel to save below
579 lookup[0]->setLabel(saveLabel);
582 lastLabel = lookup[0]->getLabel();
584 //get next line to process
585 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
586 lookup = input->getSharedRAbundVectors();
589 if (m->control_pressed) { for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } for(int i = 0 ; i < treeCalculators.size(); i++) { delete treeCalculators[i]; } return 1; }
591 //output error messages about any remaining user labels
592 set<string>::iterator it;
593 bool needToRun = false;
594 for (it = userLabels.begin(); it != userLabels.end(); it++) {
595 m->mothurOut("Your file does not include the label " + *it);
596 if (processedLabels.count(lastLabel) != 1) {
597 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
600 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
604 //run last label if you need to
605 if (needToRun == true) {
606 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
607 lookup = input->getSharedRAbundVectors(lastLabel);
609 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
611 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
614 for(int i = 0 ; i < treeCalculators.size(); i++) { delete treeCalculators[i]; }
618 catch(exception& e) {
619 m->errorOut(e, "TreeGroupCommand", "makeSimsShared");
624 /***********************************************************/
625 int TreeGroupCommand::process(vector<SharedRAbundVector*> thisLookup) {
628 vector<SharedRAbundVector*> subset;
629 numGroups = thisLookup.size();
631 //for each calculator
632 for(int i = 0 ; i < treeCalculators.size(); i++) {
633 //initialize simMatrix
635 simMatrix.resize(numGroups);
636 for (int k = 0; k < simMatrix.size(); k++) {
637 for (int j = 0; j < simMatrix.size(); j++) {
638 simMatrix[k].push_back(0.0);
644 for (int g = 0; g < numGroups; g++) { index[g] = g; }
646 //create a new filename
647 outputFile = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".tre";
648 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
650 for (int k = 0; k < thisLookup.size(); k++) {
651 for (int l = k; l < thisLookup.size(); l++) {
652 if (k != l) { //we dont need to similiarity of a groups to itself
653 //get estimated similarity between 2 groups
655 subset.clear(); //clear out old pair of sharedrabunds
656 //add new pair of sharedrabunds
657 subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]);
659 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
660 //cout << thisLookup[k]->getGroup() << '\t' << thisLookup[l]->getGroup() << '\t' << (1.0 - data[0]) << endl;
661 if (m->control_pressed) { return 1; }
663 //save values in similarity matrix
664 simMatrix[k][l] = data[0];
665 simMatrix[l][k] = data[0];
670 if (m->control_pressed) { return 1; }
671 //creates tree from similarity matrix and write out file
674 if (m->control_pressed) { return 1; }
680 catch(exception& e) {
681 m->errorOut(e, "TreeGroupCommand", "process");
685 /***********************************************************/