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(){
38 globaldata = GlobalData::getInstance();
39 //initialize outputTypes
40 vector<string> tempOutNames;
41 outputTypes["tree"] = tempOutNames;
44 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
48 //**********************************************************************************************************************
49 vector<string> TreeGroupCommand::getRequiredParameters(){
51 vector<string> myArray;
55 m->errorOut(e, "TreeGroupCommand", "getRequiredParameters");
59 //**********************************************************************************************************************
60 vector<string> TreeGroupCommand::getRequiredFiles(){
62 string Array[] = {"phylip","column","shared","or"};
63 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
67 m->errorOut(e, "TreeGroupCommand", "getRequiredFiles");
71 //**********************************************************************************************************************
73 TreeGroupCommand::TreeGroupCommand(string option) {
75 globaldata = GlobalData::getInstance();
82 //allow user to run help
83 if(option == "help") { validCalculator = new ValidCalculators(); help(); abort = true; }
86 //valid paramters for this command
87 string Array[] = {"label","calc","groups", "phylip", "column", "name", "precision","cutoff","outputdir","inputdir"};
88 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
90 OptionParser parser(option);
91 map<string, string> parameters = parser. getParameters();
93 ValidParameters validParameter;
94 map<string, string>::iterator it;
96 //check to make sure all parameters are valid for command
97 for (it = parameters.begin(); it != parameters.end(); it++) {
98 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
101 //initialize outputTypes
102 vector<string> tempOutNames;
103 outputTypes["tree"] = tempOutNames;
105 //if the user changes the input directory command factory will send this info to us in the output parameter
106 string inputDir = validParameter.validFile(parameters, "inputdir", false);
107 if (inputDir == "not found"){ inputDir = ""; }
110 it = parameters.find("phylip");
111 //user has given a template file
112 if(it != parameters.end()){
113 path = m->hasPath(it->second);
114 //if the user has not given a path then, add inputdir. else leave path alone.
115 if (path == "") { parameters["phylip"] = inputDir + it->second; }
118 it = parameters.find("column");
119 //user has given a template file
120 if(it != parameters.end()){
121 path = m->hasPath(it->second);
122 //if the user has not given a path then, add inputdir. else leave path alone.
123 if (path == "") { parameters["column"] = inputDir + it->second; }
126 it = parameters.find("name");
127 //user has given a template file
128 if(it != parameters.end()){
129 path = m->hasPath(it->second);
130 //if the user has not given a path then, add inputdir. else leave path alone.
131 if (path == "") { parameters["name"] = inputDir + it->second; }
135 format = globaldata->getFormat();
137 //required parameters
138 phylipfile = validParameter.validFile(parameters, "phylip", true);
139 if (phylipfile == "not open") { abort = true; }
140 else if (phylipfile == "not found") { phylipfile = ""; }
141 else { globaldata->newRead(); format = "phylip"; globaldata->setPhylipFile(phylipfile); }
143 columnfile = validParameter.validFile(parameters, "column", true);
144 if (columnfile == "not open") { abort = true; }
145 else if (columnfile == "not found") { columnfile = ""; }
146 else { globaldata->newRead(); format = "column"; globaldata->setColumnFile(columnfile); }
148 namefile = validParameter.validFile(parameters, "name", true);
149 if (namefile == "not open") { abort = true; }
150 else if (namefile == "not found") { namefile = ""; }
151 else { globaldata->setNameFile(namefile); }
153 //error checking on files
154 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; }
155 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; }
157 if (columnfile != "") {
158 if (namefile == "") { m->mothurOut("You need to provide a namefile if you are going to use the column format."); m->mothurOutEndLine(); abort = true; }
161 //check for optional parameter and set defaults
162 // ...at some point should added some additional type checking...
163 label = validParameter.validFile(parameters, "label", false);
164 if (label == "not found") { label = ""; }
166 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
167 else { allLines = 1; }
170 //if the user has not specified any labels use the ones from read.otu
172 allLines = globaldata->allLines;
173 labels = globaldata->labels;
176 groups = validParameter.validFile(parameters, "groups", false);
177 if (groups == "not found") { groups = ""; }
179 m->splitAtDash(groups, Groups);
180 globaldata->Groups = Groups;
183 calc = validParameter.validFile(parameters, "calc", false);
184 if (calc == "not found") { calc = "jclass-thetayc"; }
186 if (calc == "default") { calc = "jclass-thetayc"; }
188 m->splitAtDash(calc, Estimators);
191 temp = validParameter.validFile(parameters, "precision", false); if (temp == "not found") { temp = "100"; }
192 convert(temp, precision);
194 temp = validParameter.validFile(parameters, "cutoff", false); if (temp == "not found") { temp = "10"; }
195 convert(temp, cutoff);
196 cutoff += (5 / (precision * 10.0));
198 //if the user changes the output directory command factory will send this info to us in the output parameter
199 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
201 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
205 if (abort == false) {
207 validCalculator = new ValidCalculators();
209 if (format == "sharedfile") {
211 for (i=0; i<Estimators.size(); i++) {
212 if (validCalculator->isValidCalculator("treegroup", Estimators[i]) == true) {
213 if (Estimators[i] == "jabund") {
214 treeCalculators.push_back(new JAbund());
215 }else if (Estimators[i] == "sorabund") {
216 treeCalculators.push_back(new SorAbund());
217 }else if (Estimators[i] == "jclass") {
218 treeCalculators.push_back(new Jclass());
219 }else if (Estimators[i] == "sorclass") {
220 treeCalculators.push_back(new SorClass());
221 }else if (Estimators[i] == "jest") {
222 treeCalculators.push_back(new Jest());
223 }else if (Estimators[i] == "sorest") {
224 treeCalculators.push_back(new SorEst());
225 }else if (Estimators[i] == "thetayc") {
226 treeCalculators.push_back(new ThetaYC());
227 }else if (Estimators[i] == "thetan") {
228 treeCalculators.push_back(new ThetaN());
229 }else if (Estimators[i] == "morisitahorn") {
230 treeCalculators.push_back(new MorHorn());
231 }else if (Estimators[i] == "braycurtis") {
232 treeCalculators.push_back(new BrayCurtis());
241 catch(exception& e) {
242 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
247 //**********************************************************************************************************************
249 void TreeGroupCommand::help(){
251 m->mothurOut("The tree.shared command creates a .tre to represent the similiarity between groups or sequences.\n");
252 m->mothurOut("The tree.shared command can only be executed after a successful read.otu command or by providing a distance file.\n");
253 m->mothurOut("The tree.shared command parameters are groups, calc, phylip, column, name, cutoff, precision and label.\n");
254 m->mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n");
255 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");
256 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");
257 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");
258 m->mothurOut("The tree.shared command should be in the following format: tree.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels).\n");
259 m->mothurOut("Example tree.shared(groups=A-B-C, calc=jabund-sorabund).\n");
260 m->mothurOut("The default value for groups is all the groups in your groupfile.\n");
261 m->mothurOut("The default value for calc is jclass-thetayc.\n");
262 m->mothurOut("The tree.shared command outputs a .tre file for each calculator you specify at each distance you choose.\n");
263 validCalculator->printCalc("treegroup", cout);
264 m->mothurOut("Or the tree.shared command can be in the following format: tree.shared(phylip=yourPhylipFile).\n");
265 m->mothurOut("Example tree.shared(phylip=abrecovery.dist).\n");
266 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
268 catch(exception& e) {
269 m->errorOut(e, "TreeGroupCommand", "help");
275 //**********************************************************************************************************************
277 TreeGroupCommand::~TreeGroupCommand(){
278 globaldata->Groups.clear();
279 if (abort == false) {
281 if (format == "sharedfile") { delete read; delete input; globaldata->ginput = NULL; }
282 else { delete readMatrix; delete matrix; delete list; }
283 delete tmap; globaldata->gTreemap = NULL;
284 delete validCalculator;
289 //**********************************************************************************************************************
291 int TreeGroupCommand::execute(){
294 if (abort == true) { return 0; }
296 if (format == "sharedfile") {
297 //if the users entered no valid calculators don't execute command
298 if (treeCalculators.size() == 0) { m->mothurOut("You have given no valid calculators."); m->mothurOutEndLine(); return 0; }
300 if (globaldata->gGroupmap != NULL) { delete globaldata->gGroupmap; globaldata->gGroupmap = NULL; }
302 read = new ReadOTUFile(globaldata->inputFileName);
303 read->read(&*globaldata);
305 input = globaldata->ginput;
306 lookup = input->getSharedRAbundVectors();
307 lastLabel = lookup[0]->getLabel();
309 if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups. I cannot run the command."); m->mothurOutEndLine(); return 0; }
311 //used in tree constructor
312 globaldata->runParse = false;
314 //create treemap class from groupmap for tree class to use
315 tmap = new TreeMap();
316 tmap->makeSim(globaldata->gGroupmap);
317 globaldata->gTreemap = tmap;
319 //clear globaldatas old tree names if any
320 globaldata->Treenames.clear();
322 //fills globaldatas tree names
323 globaldata->Treenames = globaldata->Groups;
325 if (m->control_pressed) { return 0; }
330 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
333 filename = globaldata->inputFileName;
335 if (format == "column") { readMatrix = new ReadColumnMatrix(filename); }
336 else if (format == "phylip") { readMatrix = new ReadPhylipMatrix(filename); }
338 readMatrix->setCutoff(cutoff);
341 nameMap = new NameAssignment(namefile);
348 readMatrix->read(nameMap);
349 list = readMatrix->getListVector();
350 matrix = readMatrix->getMatrix();
353 tmap = new TreeMap();
355 if (m->control_pressed) { return 0; }
358 globaldata->gTreemap = tmap;
360 globaldata->Groups = tmap->namesOfGroups;
362 //clear globaldatas old tree names if any
363 globaldata->Treenames.clear();
365 //fills globaldatas tree names
366 globaldata->Treenames = globaldata->Groups;
368 //used in tree constructor
369 globaldata->runParse = false;
371 if (m->control_pressed) { return 0; }
375 if (m->control_pressed) { return 0; }
377 //create a new filename
378 outputFile = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + "tre";
379 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
383 if (m->control_pressed) { return 0; }
385 m->mothurOut("Tree complete. "); m->mothurOutEndLine();
389 //reset groups parameter
390 globaldata->Groups.clear();
392 m->mothurOutEndLine();
393 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
394 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
395 m->mothurOutEndLine();
399 catch(exception& e) {
400 m->errorOut(e, "TreeGroupCommand", "execute");
404 //**********************************************************************************************************************
406 int TreeGroupCommand::createTree(){
411 //do merges and create tree structure by setting parents and children
412 //there are numGroups - 1 merges to do
413 for (int i = 0; i < (numGroups - 1); i++) {
414 float largest = -1000.0;
416 if (m->control_pressed) { delete t; return 1; }
419 //find largest value in sims matrix by searching lower triangle
420 for (int j = 1; j < simMatrix.size(); j++) {
421 for (int k = 0; k < j; k++) {
422 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
426 //set non-leaf node info and update leaves to know their parents
428 t->tree[numGroups + i].setChildren(index[row], index[column]);
431 t->tree[index[row]].setParent(numGroups + i);
432 t->tree[index[column]].setParent(numGroups + i);
434 //blength = distance / 2;
435 float blength = ((1.0 - largest) / 2);
438 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
439 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
441 //set your length to leaves to your childs length plus branchlength
442 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
446 index[row] = numGroups+i;
447 index[column] = numGroups+i;
449 //remove highest value that caused the merge.
450 simMatrix[row][column] = -1000.0;
451 simMatrix[column][row] = -1000.0;
453 //merge values in simsMatrix
454 for (int n = 0; n < simMatrix.size(); n++) {
455 //row becomes merge of 2 groups
456 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
457 simMatrix[n][row] = simMatrix[row][n];
459 simMatrix[column][n] = -1000.0;
460 simMatrix[n][column] = -1000.0;
464 //adjust tree to make sure root to tip length is .5
465 int root = t->findRoot();
466 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
471 if (m->control_pressed) { delete t; return 1; }
474 t->createNewickFile(outputFile);
479 if (m->control_pressed) { remove(outputFile.c_str()); outputNames.pop_back(); return 1; }
484 catch(exception& e) {
485 m->errorOut(e, "TreeGroupCommand", "createTree");
489 /***********************************************************/
490 void TreeGroupCommand::printSims(ostream& out) {
493 //output column headers
495 //for (int i = 0; i < lookup.size(); i++) { out << lookup[i]->getGroup() << '\t'; }
499 for (int m = 0; m < simMatrix.size(); m++) {
500 //out << lookup[m]->getGroup() << '\t';
501 for (int n = 0; n < simMatrix.size(); n++) {
502 out << simMatrix[m][n] << '\t';
508 catch(exception& e) {
509 m->errorOut(e, "TreeGroupCommand", "printSims");
513 /***********************************************************/
514 int TreeGroupCommand::makeSimsDist() {
516 numGroups = list->size();
520 for (int g = 0; g < numGroups; g++) { index[g] = g; }
522 //initialize simMatrix
524 simMatrix.resize(numGroups);
525 for (int k = 0; k < simMatrix.size(); k++) {
526 for (int j = 0; j < simMatrix.size(); j++) {
527 simMatrix[k].push_back(0.0);
531 //go through sparse matrix and fill sims
532 //go through each cell in the sparsematrix
533 for(MatData currentCell = matrix->begin(); currentCell != matrix->end(); currentCell++){
534 //similairity = -(distance-1)
535 simMatrix[currentCell->row][currentCell->column] = -(currentCell->dist -1.0);
536 simMatrix[currentCell->column][currentCell->row] = -(currentCell->dist -1.0);
538 if (m->control_pressed) { return 1; }
544 catch(exception& e) {
545 m->errorOut(e, "TreeGroupCommand", "makeSimsDist");
550 /***********************************************************/
551 int TreeGroupCommand::makeSimsShared() {
553 set<string> processedLabels;
554 set<string> userLabels = labels;
556 //as long as you are not at the end of the file or done wih the lines you want
557 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
558 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; }
560 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
561 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
564 processedLabels.insert(lookup[0]->getLabel());
565 userLabels.erase(lookup[0]->getLabel());
568 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
569 string saveLabel = lookup[0]->getLabel();
571 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
572 lookup = input->getSharedRAbundVectors(lastLabel);
574 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
577 processedLabels.insert(lookup[0]->getLabel());
578 userLabels.erase(lookup[0]->getLabel());
580 //restore real lastlabel to save below
581 lookup[0]->setLabel(saveLabel);
584 lastLabel = lookup[0]->getLabel();
586 //get next line to process
587 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
588 lookup = input->getSharedRAbundVectors();
591 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; }
593 //output error messages about any remaining user labels
594 set<string>::iterator it;
595 bool needToRun = false;
596 for (it = userLabels.begin(); it != userLabels.end(); it++) {
597 m->mothurOut("Your file does not include the label " + *it);
598 if (processedLabels.count(lastLabel) != 1) {
599 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
602 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
606 //run last label if you need to
607 if (needToRun == true) {
608 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
609 lookup = input->getSharedRAbundVectors(lastLabel);
611 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
613 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
616 for(int i = 0 ; i < treeCalculators.size(); i++) { delete treeCalculators[i]; }
620 catch(exception& e) {
621 m->errorOut(e, "TreeGroupCommand", "makeSimsShared");
626 /***********************************************************/
627 int TreeGroupCommand::process(vector<SharedRAbundVector*> thisLookup) {
630 vector<SharedRAbundVector*> subset;
631 numGroups = thisLookup.size();
633 //for each calculator
634 for(int i = 0 ; i < treeCalculators.size(); i++) {
635 //initialize simMatrix
637 simMatrix.resize(numGroups);
638 for (int k = 0; k < simMatrix.size(); k++) {
639 for (int j = 0; j < simMatrix.size(); j++) {
640 simMatrix[k].push_back(0.0);
646 for (int g = 0; g < numGroups; g++) { index[g] = g; }
648 //create a new filename
649 outputFile = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".tre";
650 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
652 for (int k = 0; k < thisLookup.size(); k++) {
653 for (int l = k; l < thisLookup.size(); l++) {
654 if (k != l) { //we dont need to similiarity of a groups to itself
655 //get estimated similarity between 2 groups
657 subset.clear(); //clear out old pair of sharedrabunds
658 //add new pair of sharedrabunds
659 subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]);
661 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
662 //cout << thisLookup[k]->getGroup() << '\t' << thisLookup[l]->getGroup() << '\t' << (1.0 - data[0]) << endl;
663 if (m->control_pressed) { return 1; }
665 //save values in similarity matrix
666 simMatrix[k][l] = data[0];
667 simMatrix[l][k] = data[0];
672 if (m->control_pressed) { return 1; }
673 //creates tree from similarity matrix and write out file
676 if (m->control_pressed) { return 1; }
682 catch(exception& e) {
683 m->errorOut(e, "TreeGroupCommand", "process");
687 /***********************************************************/