2 * bootstrapsharedcommand.cpp
5 * Created by Sarah Westcott on 4/16/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "bootstrapsharedcommand.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"
23 //**********************************************************************************************************************
24 vector<string> BootSharedCommand::setParameters(){
26 CommandParameter pshared("shared", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pshared);
27 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
28 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
29 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
30 CommandParameter pcalc("calc", "Multiple", "jabund-sorabund-jclass-sorclass-jest-sorest-thetayc-thetan-morisitahorn-braycurtis", "jclass-thetayc", "", "", "",true,false); parameters.push_back(pcalc);
31 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
32 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
34 vector<string> myArray;
35 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
39 m->errorOut(e, "BootSharedCommand", "setParameters");
43 //**********************************************************************************************************************
44 string BootSharedCommand::getHelpString(){
46 string helpString = "";
47 helpString += "The bootstrap.shared command parameters are shared, groups, calc, iters and label. shared is required.\n";
48 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n";
49 helpString += "The group names are separated by dashes. The label parameter allows you to select what distance levels you would like trees created for, and is also separated by dashes.\n";
50 helpString += "The bootstrap.shared command should be in the following format: bootstrap.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels, iters=yourIters).\n";
51 helpString += "Example bootstrap.shared(groups=A-B-C, calc=jabund-sorabund, iters=100).\n";
52 helpString += "The default value for groups is all the groups in your groupfile.\n";
53 helpString += "The default value for calc is jclass-thetayc. The default for iters is 1000.\n";
57 m->errorOut(e, "BootSharedCommand", "getHelpString");
61 //**********************************************************************************************************************
62 BootSharedCommand::BootSharedCommand(){
64 abort = true; calledHelp = true;
66 vector<string> tempOutNames;
67 outputTypes["tree"] = tempOutNames;
70 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
74 //**********************************************************************************************************************
75 BootSharedCommand::BootSharedCommand(string option) {
77 abort = false; calledHelp = false;
79 //allow user to run help
80 if(option == "help") { help(); abort = true; calledHelp = true; }
81 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
84 vector<string> myArray = setParameters();
86 OptionParser parser(option);
87 map<string,string> parameters = parser.getParameters();
88 map<string,string>::iterator it;
90 ValidParameters validParameter;
92 //check to make sure all parameters are valid for command
93 for (it = parameters.begin(); it != parameters.end(); it++) {
94 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
97 //initialize outputTypes
98 vector<string> tempOutNames;
99 outputTypes["tree"] = tempOutNames;
101 //if the user changes the input directory command factory will send this info to us in the output parameter
102 string inputDir = validParameter.validFile(parameters, "inputdir", false);
103 if (inputDir == "not found"){ inputDir = ""; }
106 it = parameters.find("shared");
107 //user has given a template file
108 if(it != parameters.end()){
109 path = m->hasPath(it->second);
110 //if the user has not given a path then, add inputdir. else leave path alone.
111 if (path == "") { parameters["shared"] = inputDir + it->second; }
115 sharedfile = validParameter.validFile(parameters, "shared", true);
116 if (sharedfile == "not found") { m->mothurOut("shared is a required parameter."); m->mothurOutEndLine(); sharedfile = ""; abort = true; }
117 else if (sharedfile == "not open") { sharedfile = ""; abort = true; }
119 //if the user changes the output directory command factory will send this info to us in the output parameter
120 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
122 outputDir += m->hasPath(sharedfile); //if user entered a file with a path then preserve it
125 //check for optional parameter and set defaults
126 // ...at some point should added some additional type checking...
127 label = validParameter.validFile(parameters, "label", false);
128 if (label == "not found") { label = ""; }
130 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
131 else { allLines = 1; }
134 groups = validParameter.validFile(parameters, "groups", false);
135 if (groups == "not found") { groups = ""; }
137 m->splitAtDash(groups, Groups);
141 calc = validParameter.validFile(parameters, "calc", false);
142 if (calc == "not found") { calc = "jclass-thetayc"; }
144 if (calc == "default") { calc = "jclass-thetayc"; }
146 m->splitAtDash(calc, Estimators);
149 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
150 convert(temp, iters);
152 if (abort == false) {
154 //used in tree constructor
157 validCalculator = new ValidCalculators();
160 //NOTE: if you add a calc to this if statement you must add it to the setParameters function
161 //or it will not be visible in the gui
163 for (i=0; i<Estimators.size(); i++) {
164 if (validCalculator->isValidCalculator("boot", Estimators[i]) == true) {
165 if (Estimators[i] == "jabund") {
166 treeCalculators.push_back(new JAbund());
167 }else if (Estimators[i] == "sorabund") {
168 treeCalculators.push_back(new SorAbund());
169 }else if (Estimators[i] == "jclass") {
170 treeCalculators.push_back(new Jclass());
171 }else if (Estimators[i] == "sorclass") {
172 treeCalculators.push_back(new SorClass());
173 }else if (Estimators[i] == "jest") {
174 treeCalculators.push_back(new Jest());
175 }else if (Estimators[i] == "sorest") {
176 treeCalculators.push_back(new SorEst());
177 }else if (Estimators[i] == "thetayc") {
178 treeCalculators.push_back(new ThetaYC());
179 }else if (Estimators[i] == "thetan") {
180 treeCalculators.push_back(new ThetaN());
181 }else if (Estimators[i] == "morisitahorn") {
182 treeCalculators.push_back(new MorHorn());
183 }else if (Estimators[i] == "braycurtis") {
184 treeCalculators.push_back(new BrayCurtis());
189 delete validCalculator;
192 for (int i=0; i < treeCalculators.size(); i++) {
193 tempo = new ofstream;
194 out.push_back(tempo);
197 //make a vector of tree* for each calculator
198 trees.resize(treeCalculators.size());
203 catch(exception& e) {
204 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
208 //**********************************************************************************************************************
209 BootSharedCommand::~BootSharedCommand(){}
210 //**********************************************************************************************************************
212 int BootSharedCommand::execute(){
215 if (abort == true) { if (calledHelp) { return 0; } return 2; }
217 m->mothurOut("bootstrap.shared command is no longer available."); m->mothurOutEndLine();
220 input = new InputData(sharedfile, "sharedfile");
221 order = input->getSharedOrderVector();
222 string lastLabel = order->getLabel();
224 //if the users entered no valid calculators don't execute command
225 if (treeCalculators.size() == 0) { return 0; }
227 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
228 set<string> processedLabels;
229 set<string> userLabels = labels;
232 util = new SharedUtil();
233 util->setGroups(m->Groups, m->namesOfGroups, "treegroup");
235 numGroups = m->Groups.size();
237 //clear globaldatas old tree names if any
238 globaldata->Treenames.clear();
240 //fills globaldatas tree names
241 globaldata->Treenames = m->Groups;
243 //create treemap class from groupmap for tree class to use
244 tmap = new TreeMap();
245 tmap->makeSim(globaldata->gGroupmap);
246 globaldata->gTreemap = tmap;
248 while((order != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
249 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input;delete util; return 0; }
251 if(allLines == 1 || labels.count(order->getLabel()) == 1){
253 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
254 int error = process(order);
255 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input;delete util; return 0; }
257 processedLabels.insert(order->getLabel());
258 userLabels.erase(order->getLabel());
261 //you have a label the user want that is smaller than this label and the last label has not already been processed
262 if ((m->anyLabelsToProcess(order->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
263 string saveLabel = order->getLabel();
266 order = input->getSharedOrderVector(lastLabel);
267 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
268 int error = process(order);
269 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input;delete util; return 0; }
271 processedLabels.insert(order->getLabel());
272 userLabels.erase(order->getLabel());
274 //restore real lastlabel to save below
275 order->setLabel(saveLabel);
279 lastLabel = order->getLabel();
281 //get next line to process
283 order = input->getSharedOrderVector();
287 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input; delete util; return 0; }
289 //output error messages about any remaining user labels
290 set<string>::iterator it;
291 bool needToRun = false;
292 for (it = userLabels.begin(); it != userLabels.end(); it++) {
293 m->mothurOut("Your file does not include the label " + *it);
294 if (processedLabels.count(lastLabel) != 1) {
295 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
298 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
302 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input; delete util; return 0; }
304 //run last line if you need to
305 if (needToRun == true) {
306 if (order != NULL) { delete order; }
307 order = input->getSharedOrderVector(lastLabel);
308 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
309 int error = process(order);
310 if (error == 1) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear(); delete input; delete util; return 0; }
316 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } globaldata->Groups.clear();delete input; delete util; return 0; }
318 //reset groups parameter
319 globaldata->Groups.clear();
321 //set first tree file as new current treefile
322 string currentTree = "";
323 itTypes = outputTypes.find("tree");
324 if (itTypes != outputTypes.end()) {
325 if ((itTypes->second).size() != 0) { currentTree = (itTypes->second)[0]; m->setTreeFile(currentTree); }
331 m->mothurOutEndLine();
332 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
333 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
334 m->mothurOutEndLine();
339 catch(exception& e) {
340 m->errorOut(e, "BootSharedCommand", "execute");
344 //**********************************************************************************************************************
346 int BootSharedCommand::createTree(ostream* out, Tree* t){
349 //do merges and create tree structure by setting parents and children
350 //there are numGroups - 1 merges to do
351 for (int i = 0; i < (numGroups - 1); i++) {
353 if (m->control_pressed) { return 1; }
355 float largest = -1000.0;
357 //find largest value in sims matrix by searching lower triangle
358 for (int j = 1; j < simMatrix.size(); j++) {
359 for (int k = 0; k < j; k++) {
360 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
364 //set non-leaf node info and update leaves to know their parents
366 t->tree[numGroups + i].setChildren(index[row], index[column]);
369 t->tree[index[row]].setParent(numGroups + i);
370 t->tree[index[column]].setParent(numGroups + i);
372 //blength = distance / 2;
373 float blength = ((1.0 - largest) / 2);
376 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
377 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
379 //set your length to leaves to your childs length plus branchlength
380 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
384 index[row] = numGroups+i;
385 index[column] = numGroups+i;
387 //zero out highest value that caused the merge.
388 simMatrix[row][column] = -1000.0;
389 simMatrix[column][row] = -1000.0;
391 //merge values in simsMatrix
392 for (int n = 0; n < simMatrix.size(); n++) {
393 //row becomes merge of 2 groups
394 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
395 simMatrix[n][row] = simMatrix[row][n];
397 simMatrix[column][n] = -1000.0;
398 simMatrix[n][column] = -1000.0;
402 //adjust tree to make sure root to tip length is .5
403 int root = t->findRoot();
404 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
409 if (m->control_pressed) { return 1; }
417 catch(exception& e) {
418 m->errorOut(e, "BootSharedCommand", "createTree");
422 /***********************************************************/
423 void BootSharedCommand::printSims() {
425 m->mothurOut("simsMatrix"); m->mothurOutEndLine();
426 for (int k = 0; k < simMatrix.size(); k++) {
427 for (int n = 0; n < simMatrix.size(); n++) {
428 m->mothurOut(toString(simMatrix[k][n])); m->mothurOut("\t");
430 m->mothurOutEndLine();
434 catch(exception& e) {
435 m->errorOut(e, "BootSharedCommand", "printSims");
439 /***********************************************************/
440 int BootSharedCommand::process(SharedOrderVector* order) {
443 vector<SharedRAbundVector*> subset;
445 //open an ostream for each calc to print to
446 for (int z = 0; z < treeCalculators.size(); z++) {
447 //create a new filename
448 outputFile = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + treeCalculators[z]->getName() + ".boot" + order->getLabel() + ".tre";
449 m->openOutputFile(outputFile, *(out[z]));
450 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
453 m->mothurOut("Generating bootstrap trees..."); cout.flush();
455 //create a file for each calculator with the 1000 trees in it.
456 for (int p = 0; p < iters; p++) {
458 if (m->control_pressed) { return 1; }
460 util->getSharedVectorswithReplacement(m->Groups, lookup, order); //fills group vectors from order vector.
463 //for each calculator
464 for(int i = 0 ; i < treeCalculators.size(); i++) {
466 if (m->control_pressed) { return 1; }
468 //initialize simMatrix
470 simMatrix.resize(numGroups);
471 for (int o = 0; o < simMatrix.size(); o++) {
472 for (int j = 0; j < simMatrix.size(); j++) {
473 simMatrix[o].push_back(0.0);
479 for (int g = 0; g < numGroups; g++) { index[g] = g; }
481 for (int k = 0; k < lookup.size(); k++) { // pass cdd each set of groups to commpare
482 for (int l = k; l < lookup.size(); l++) {
483 if (k != l) { //we dont need to similiarity of a groups to itself
484 subset.clear(); //clear out old pair of sharedrabunds
485 //add new pair of sharedrabunds
486 subset.push_back(lookup[k]); subset.push_back(lookup[l]);
488 //get estimated similarity between 2 groups
489 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
490 //save values in similarity matrix
491 simMatrix[k][l] = data[0];
492 simMatrix[l][k] = data[0];
497 tempTree = new Tree();
499 if (m->control_pressed) { delete tempTree; return 1; }
501 //creates tree from similarity matrix and write out file
502 createTree(out[i], tempTree);
504 if (m->control_pressed) { delete tempTree; return 1; }
506 //save trees for consensus command.
507 trees[i].push_back(tempTree);
511 m->mothurOut("\tDone."); m->mothurOutEndLine();
514 //create consensus trees for each bootstrapped tree set
515 for (int k = 0; k < trees.size(); k++) {
517 m->mothurOut("Generating consensus tree for " + treeCalculators[k]->getName()); m->mothurOutEndLine();
519 if (m->control_pressed) { return 1; }
521 //set global data to calc trees
522 globaldata->gTree = trees[k];
524 string filename = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + treeCalculators[k]->getName() + ".boot" + order->getLabel();
525 consensus = new ConcensusCommand(filename);
526 consensus->execute();
529 outputNames.push_back(filename + ".cons.pairs");
530 outputNames.push_back(filename + ".cons.tre");
536 //close ostream for each calc
537 for (int z = 0; z < treeCalculators.size(); z++) { out[z]->close(); }
542 catch(exception& e) {
543 m->errorOut(e, "BootSharedCommand", "process");
547 /***********************************************************/