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 //**********************************************************************************************************************
25 BootSharedCommand::BootSharedCommand(string option){
27 globaldata = GlobalData::getInstance();
34 //allow user to run help
35 if(option == "help") { help(); abort = true; }
38 //valid paramters for this command
39 string Array[] = {"label","calc","groups","iters","outputdir","inputdir"};
40 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
42 OptionParser parser(option);
43 map<string,string> parameters = parser.getParameters();
45 ValidParameters validParameter;
47 //check to make sure all parameters are valid for command
48 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
49 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
52 //if the user changes the output directory command factory will send this info to us in the output parameter
53 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
55 outputDir += hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
59 //make sure the user has already run the read.otu command
60 if (globaldata->getSharedFile() == "") {
61 if (globaldata->getListFile() == "") { mothurOut("You must read a list and a group, or a shared before you can use the bootstrap.shared command."); mothurOutEndLine(); abort = true; }
62 else if (globaldata->getGroupFile() == "") { mothurOut("You must read a list and a group, or a shared before you can use the bootstrap.shared command."); mothurOutEndLine(); abort = true; }
65 //check for optional parameter and set defaults
66 // ...at some point should added some additional type checking...
67 label = validParameter.validFile(parameters, "label", false);
68 if (label == "not found") { label = ""; }
70 if(label != "all") { splitAtDash(label, labels); allLines = 0; }
71 else { allLines = 1; }
74 //if the user has not specified any labels use the ones from read.otu
76 allLines = globaldata->allLines;
77 labels = globaldata->labels;
80 groups = validParameter.validFile(parameters, "groups", false);
81 if (groups == "not found") { groups = ""; }
83 splitAtDash(groups, Groups);
84 globaldata->Groups = Groups;
87 calc = validParameter.validFile(parameters, "calc", false);
88 if (calc == "not found") { calc = "jclass-thetayc"; }
90 if (calc == "default") { calc = "jclass-thetayc"; }
92 splitAtDash(calc, Estimators);
95 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
100 //used in tree constructor
101 globaldata->runParse = false;
103 validCalculator = new ValidCalculators();
106 for (i=0; i<Estimators.size(); i++) {
107 if (validCalculator->isValidCalculator("boot", Estimators[i]) == true) {
108 if (Estimators[i] == "jabund") {
109 treeCalculators.push_back(new JAbund());
110 }else if (Estimators[i] == "sorabund") {
111 treeCalculators.push_back(new SorAbund());
112 }else if (Estimators[i] == "jclass") {
113 treeCalculators.push_back(new Jclass());
114 }else if (Estimators[i] == "sorclass") {
115 treeCalculators.push_back(new SorClass());
116 }else if (Estimators[i] == "jest") {
117 treeCalculators.push_back(new Jest());
118 }else if (Estimators[i] == "sorest") {
119 treeCalculators.push_back(new SorEst());
120 }else if (Estimators[i] == "thetayc") {
121 treeCalculators.push_back(new ThetaYC());
122 }else if (Estimators[i] == "thetan") {
123 treeCalculators.push_back(new ThetaN());
124 }else if (Estimators[i] == "morisitahorn") {
125 treeCalculators.push_back(new MorHorn());
126 }else if (Estimators[i] == "braycurtis") {
127 treeCalculators.push_back(new BrayCurtis());
132 delete validCalculator;
135 for (int i=0; i < treeCalculators.size(); i++) {
136 tempo = new ofstream;
137 out.push_back(tempo);
140 //make a vector of tree* for each calculator
141 trees.resize(treeCalculators.size());
146 catch(exception& e) {
147 errorOut(e, "BootSharedCommand", "BootSharedCommand");
152 //**********************************************************************************************************************
154 void BootSharedCommand::help(){
156 mothurOut("The bootstrap.shared command can only be executed after a successful read.otu command.\n");
157 mothurOut("The bootstrap.shared command parameters are groups, calc, iters and label.\n");
158 mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n");
159 mothurOut("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");
160 mothurOut("The bootstrap.shared command should be in the following format: bootstrap.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels, iters=yourIters).\n");
161 mothurOut("Example bootstrap.shared(groups=A-B-C, calc=jabund-sorabund, iters=100).\n");
162 mothurOut("The default value for groups is all the groups in your groupfile.\n");
163 mothurOut("The default value for calc is jclass-thetayc. The default for iters is 1000.\n");
165 catch(exception& e) {
166 errorOut(e, "BootSharedCommand", "help");
171 //**********************************************************************************************************************
173 BootSharedCommand::~BootSharedCommand(){
174 //made new in execute
175 if (abort == false) {
176 delete input; globaldata->ginput = NULL;
179 globaldata->gorder = NULL;
183 //**********************************************************************************************************************
185 int BootSharedCommand::execute(){
188 if (abort == true) { return 0; }
190 util = new SharedUtil();
193 read = new ReadOTUFile(globaldata->inputFileName);
194 read->read(&*globaldata);
195 input = globaldata->ginput;
196 order = input->getSharedOrderVector();
197 string lastLabel = order->getLabel();
199 //if the users entered no valid calculators don't execute command
200 if (treeCalculators.size() == 0) { return 0; }
202 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
203 set<string> processedLabels;
204 set<string> userLabels = labels;
207 util->setGroups(globaldata->Groups, globaldata->gGroupmap->namesOfGroups, "treegroup");
208 numGroups = globaldata->Groups.size();
210 //clear globaldatas old tree names if any
211 globaldata->Treenames.clear();
213 //fills globaldatas tree names
214 globaldata->Treenames = globaldata->Groups;
216 //create treemap class from groupmap for tree class to use
217 tmap = new TreeMap();
218 tmap->makeSim(globaldata->gGroupmap);
219 globaldata->gTreemap = tmap;
221 while((order != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
223 if(allLines == 1 || labels.count(order->getLabel()) == 1){
225 mothurOut(order->getLabel()); mothurOutEndLine();
228 processedLabels.insert(order->getLabel());
229 userLabels.erase(order->getLabel());
232 //you have a label the user want that is smaller than this label and the last label has not already been processed
233 if ((anyLabelsToProcess(order->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
234 string saveLabel = order->getLabel();
237 order = input->getSharedOrderVector(lastLabel);
238 mothurOut(order->getLabel()); mothurOutEndLine();
241 processedLabels.insert(order->getLabel());
242 userLabels.erase(order->getLabel());
244 //restore real lastlabel to save below
245 order->setLabel(saveLabel);
249 lastLabel = order->getLabel();
251 //get next line to process
253 order = input->getSharedOrderVector();
256 //output error messages about any remaining user labels
257 set<string>::iterator it;
258 bool needToRun = false;
259 for (it = userLabels.begin(); it != userLabels.end(); it++) {
260 mothurOut("Your file does not include the label " + *it);
261 if (processedLabels.count(lastLabel) != 1) {
262 mothurOut(". I will use " + lastLabel + "."); mothurOutEndLine();
265 mothurOut(". Please refer to " + lastLabel + "."); mothurOutEndLine();
269 //run last line if you need to
270 if (needToRun == true) {
271 if (order != NULL) { delete order; }
272 order = input->getSharedOrderVector(lastLabel);
273 mothurOut(order->getLabel()); mothurOutEndLine();
279 //reset groups parameter
280 globaldata->Groups.clear();
284 catch(exception& e) {
285 errorOut(e, "BootSharedCommand", "execute");
289 //**********************************************************************************************************************
291 void BootSharedCommand::createTree(ostream* out, Tree* t){
294 //do merges and create tree structure by setting parents and children
295 //there are numGroups - 1 merges to do
296 for (int i = 0; i < (numGroups - 1); i++) {
298 float largest = -1000.0;
300 //find largest value in sims matrix by searching lower triangle
301 for (int j = 1; j < simMatrix.size(); j++) {
302 for (int k = 0; k < j; k++) {
303 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
307 //set non-leaf node info and update leaves to know their parents
309 t->tree[numGroups + i].setChildren(index[row], index[column]);
312 t->tree[index[row]].setParent(numGroups + i);
313 t->tree[index[column]].setParent(numGroups + i);
315 //blength = distance / 2;
316 float blength = ((1.0 - largest) / 2);
319 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
320 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
322 //set your length to leaves to your childs length plus branchlength
323 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
327 index[row] = numGroups+i;
328 index[column] = numGroups+i;
330 //zero out highest value that caused the merge.
331 simMatrix[row][column] = -1000.0;
332 simMatrix[column][row] = -1000.0;
334 //merge values in simsMatrix
335 for (int n = 0; n < simMatrix.size(); n++) {
336 //row becomes merge of 2 groups
337 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
338 simMatrix[n][row] = simMatrix[row][n];
340 simMatrix[column][n] = -1000.0;
341 simMatrix[n][column] = -1000.0;
345 //adjust tree to make sure root to tip length is .5
346 int root = t->findRoot();
347 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
356 catch(exception& e) {
357 errorOut(e, "BootSharedCommand", "createTree");
361 /***********************************************************/
362 void BootSharedCommand::printSims() {
364 mothurOut("simsMatrix"); mothurOutEndLine();
365 for (int m = 0; m < simMatrix.size(); m++) {
366 for (int n = 0; n < simMatrix.size(); n++) {
367 mothurOut(simMatrix[m][n]); mothurOut("\t");
373 catch(exception& e) {
374 errorOut(e, "BootSharedCommand", "printSims");
378 /***********************************************************/
379 void BootSharedCommand::process(SharedOrderVector* order) {
382 vector<SharedRAbundVector*> subset;
384 //open an ostream for each calc to print to
385 for (int z = 0; z < treeCalculators.size(); z++) {
386 //create a new filename
387 outputFile = outputDir + getRootName(getSimpleName(globaldata->inputFileName)) + treeCalculators[z]->getName() + ".boot" + order->getLabel() + ".tre";
388 openOutputFile(outputFile, *(out[z]));
391 mothurOut("Generating bootstrap trees..."); cout.flush();
393 //create a file for each calculator with the 1000 trees in it.
394 for (int p = 0; p < iters; p++) {
396 util->getSharedVectorswithReplacement(globaldata->Groups, lookup, order); //fills group vectors from order vector.
399 //for each calculator
400 for(int i = 0 ; i < treeCalculators.size(); i++) {
402 //initialize simMatrix
404 simMatrix.resize(numGroups);
405 for (int m = 0; m < simMatrix.size(); m++) {
406 for (int j = 0; j < simMatrix.size(); j++) {
407 simMatrix[m].push_back(0.0);
413 for (int g = 0; g < numGroups; g++) { index[g] = g; }
415 for (int k = 0; k < lookup.size(); k++) { // pass cdd each set of groups to commpare
416 for (int l = k; l < lookup.size(); l++) {
417 if (k != l) { //we dont need to similiarity of a groups to itself
418 subset.clear(); //clear out old pair of sharedrabunds
419 //add new pair of sharedrabunds
420 subset.push_back(lookup[k]); subset.push_back(lookup[l]);
422 //get estimated similarity between 2 groups
423 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
424 //save values in similarity matrix
425 simMatrix[k][l] = data[0];
426 simMatrix[l][k] = data[0];
431 tempTree = new Tree();
433 //creates tree from similarity matrix and write out file
434 createTree(out[i], tempTree);
436 //save trees for consensus command.
437 trees[i].push_back(tempTree);
441 mothurOut("\tDone."); mothurOutEndLine();
442 //delete globaldata's tree
443 //for (int m = 0; m < globaldata->gTree.size(); m++) { delete globaldata->gTree[m]; }
444 //globaldata->gTree.clear();
447 //create consensus trees for each bootstrapped tree set
448 for (int k = 0; k < trees.size(); k++) {
450 mothurOut("Generating consensus tree for " + treeCalculators[k]->getName()); mothurOutEndLine();
452 //set global data to calc trees
453 globaldata->gTree = trees[k];
455 string filename = getRootName(getSimpleName(globaldata->inputFileName)) + treeCalculators[k]->getName() + ".boot" + order->getLabel();
456 consensus = new ConcensusCommand(filename);
457 consensus->execute();
460 //delete globaldata's tree
461 //for (int m = 0; m < globaldata->gTree.size(); m++) { delete globaldata->gTree[m]; }
462 //globaldata->gTree.clear();
468 //close ostream for each calc
469 for (int z = 0; z < treeCalculators.size(); z++) { out[z]->close(); }
472 catch(exception& e) {
473 errorOut(e, "BootSharedCommand", "process");
477 /***********************************************************/