]> git.donarmstrong.com Git - mothur.git/blob - bootstrapsharedcommand.cpp
d174cdd7ddced16a34aeea406ae6397fca26496f
[mothur.git] / bootstrapsharedcommand.cpp
1 /*
2  *  bootstrapsharedcommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 4/16/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
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"
21
22
23 //**********************************************************************************************************************
24
25 BootSharedCommand::BootSharedCommand(string option) {
26         try {
27                 globaldata = GlobalData::getInstance();
28                 abort = false;
29                 allLines = 1;
30                 labels.clear();
31                 Groups.clear();
32                 Estimators.clear();
33                 
34                 //allow user to run help
35                 if(option == "help") { help(); abort = true; }
36                 
37                 else {
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)));
41                         
42                         OptionParser parser(option);
43                         map<string,string> parameters = parser.getParameters();
44                         
45                         ValidParameters validParameter;
46                 
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;  }
50                         }
51                         
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"){  
54                                 outputDir = ""; 
55                                 outputDir += hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it  
56                         }
57
58                         
59                         //make sure the user has already run the read.otu command
60                         if (globaldata->getSharedFile() == "") {
61                                 if (globaldata->getListFile() == "") { m->mothurOut("You must read a list and a group, or a shared before you can use the bootstrap.shared command."); m->mothurOutEndLine(); abort = true; }
62                                 else if (globaldata->getGroupFile() == "") { m->mothurOut("You must read a list and a group, or a shared before you can use the bootstrap.shared command."); m->mothurOutEndLine(); abort = true; }
63                         }
64                         
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 = ""; }
69                         else { 
70                                 if(label != "all") {  splitAtDash(label, labels);  allLines = 0;  }
71                                 else { allLines = 1;  }
72                         }
73                         
74                         //if the user has not specified any labels use the ones from read.otu
75                         if(label == "") {  
76                                 allLines = globaldata->allLines; 
77                                 labels = globaldata->labels; 
78                         }
79                                 
80                         groups = validParameter.validFile(parameters, "groups", false);                 
81                         if (groups == "not found") { groups = ""; }
82                         else { 
83                                 splitAtDash(groups, Groups);
84                                 globaldata->Groups = Groups;
85                         }
86                                 
87                         calc = validParameter.validFile(parameters, "calc", false);                     
88                         if (calc == "not found") { calc = "jclass-thetayc";  }
89                         else { 
90                                  if (calc == "default")  {  calc = "jclass-thetayc";  }
91                         }
92                         splitAtDash(calc, Estimators);
93
94                         string temp;
95                         temp = validParameter.validFile(parameters, "iters", false);  if (temp == "not found") { temp = "1000"; }
96                         convert(temp, iters); 
97                                 
98                         if (abort == false) {
99                         
100                                 //used in tree constructor 
101                                 globaldata->runParse = false;
102                         
103                                 validCalculator = new ValidCalculators();
104                                 
105                                 int i;
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());
128                                                 }
129                                         }
130                                 }
131                                 
132                                 delete validCalculator;
133                                 
134                                 ofstream* tempo;
135                                 for (int i=0; i < treeCalculators.size(); i++) {
136                                         tempo = new ofstream;
137                                         out.push_back(tempo);
138                                 }
139                                 
140                                 //make a vector of tree* for each calculator
141                                 trees.resize(treeCalculators.size());
142                         }
143                 }
144
145         }
146         catch(exception& e) {
147                 m->errorOut(e, "BootSharedCommand", "BootSharedCommand");
148                 exit(1);
149         }
150 }
151
152 //**********************************************************************************************************************
153
154 void BootSharedCommand::help(){
155         try {
156                 m->mothurOut("The bootstrap.shared command can only be executed after a successful read.otu command.\n");
157                 m->mothurOut("The bootstrap.shared command parameters are groups, calc, iters and label.\n");
158                 m->mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n");
159                 m->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                 m->mothurOut("The bootstrap.shared command should be in the following format: bootstrap.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels, iters=yourIters).\n");
161                 m->mothurOut("Example bootstrap.shared(groups=A-B-C, calc=jabund-sorabund, iters=100).\n");
162                 m->mothurOut("The default value for groups is all the groups in your groupfile.\n");
163                 m->mothurOut("The default value for calc is jclass-thetayc. The default for iters is 1000.\n");
164         }
165         catch(exception& e) {
166                 m->errorOut(e, "BootSharedCommand", "help");
167                 exit(1);
168         }
169 }
170
171 //**********************************************************************************************************************
172
173 BootSharedCommand::~BootSharedCommand(){
174         //made new in execute
175         if (abort == false) {
176                 delete input; globaldata->ginput = NULL;
177                 delete read;
178                 delete util;
179                 globaldata->gorder = NULL;
180         }
181 }
182
183 //**********************************************************************************************************************
184
185 int BootSharedCommand::execute(){
186         try {
187         
188                 if (abort == true) {    return 0;       }
189         
190                 util = new SharedUtil();        
191         
192                 //read first line
193                 read = new ReadOTUFile(globaldata->inputFileName);      
194                 read->read(&*globaldata); 
195                 input = globaldata->ginput;
196                 order = input->getSharedOrderVector();
197                 string lastLabel = order->getLabel();
198                 
199                 //if the users entered no valid calculators don't execute command
200                 if (treeCalculators.size() == 0) { return 0; }
201
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;
205                                 
206                 //set users groups
207                 util->setGroups(globaldata->Groups, globaldata->gGroupmap->namesOfGroups, "treegroup");
208                 numGroups = globaldata->Groups.size();
209                 
210                 //clear globaldatas old tree names if any
211                 globaldata->Treenames.clear();
212                 
213                 //fills globaldatas tree names
214                 globaldata->Treenames = globaldata->Groups;
215                 
216                 //create treemap class from groupmap for tree class to use
217                 tmap = new TreeMap();
218                 tmap->makeSim(globaldata->gGroupmap);
219                 globaldata->gTreemap = tmap;
220                         
221                 while((order != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
222                         if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str());  } globaldata->Groups.clear(); return 0;        } 
223         
224                         if(allLines == 1 || labels.count(order->getLabel()) == 1){                      
225                                 
226                                 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
227                                 int error = process(order);
228                                 if (error == 1) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str());  } globaldata->Groups.clear(); return 0;        } 
229                                 
230                                 processedLabels.insert(order->getLabel());
231                                 userLabels.erase(order->getLabel());
232                         }
233                         
234                         //you have a label the user want that is smaller than this label and the last label has not already been processed
235                         if ((anyLabelsToProcess(order->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
236                                 string saveLabel = order->getLabel();
237                                 
238                                 delete order;
239                                 order = input->getSharedOrderVector(lastLabel);                                                                                                 
240                                 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
241                                 int error = process(order);
242                                 if (error == 1) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str());  } globaldata->Groups.clear(); return 0;        } 
243
244                                 processedLabels.insert(order->getLabel());
245                                 userLabels.erase(order->getLabel());
246                                 
247                                 //restore real lastlabel to save below
248                                 order->setLabel(saveLabel);
249                         }
250                         
251                         
252                         lastLabel = order->getLabel();                  
253
254                         //get next line to process
255                         delete order;
256                         order = input->getSharedOrderVector();
257                 }
258                 
259                 
260                 if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str());  } globaldata->Groups.clear(); return 0;        } 
261
262                 //output error messages about any remaining user labels
263                 set<string>::iterator it;
264                 bool needToRun = false;
265                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
266                         m->mothurOut("Your file does not include the label " + *it); 
267                         if (processedLabels.count(lastLabel) != 1) {
268                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
269                                 needToRun = true;
270                         }else {
271                                 m->mothurOut(". Please refer to " + lastLabel + ".");  m->mothurOutEndLine();
272                         }
273                 }
274                 
275                 if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str());  } globaldata->Groups.clear(); return 0;        } 
276
277                 //run last line if you need to
278                 if (needToRun == true)  {
279                                 if (order != NULL) {    delete order;   }
280                                 order = input->getSharedOrderVector(lastLabel);                                                                                                 
281                                 m->mothurOut(order->getLabel()); m->mothurOutEndLine();
282                                 int error = process(order);
283                                 if (error == 1) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str());  } globaldata->Groups.clear(); return 0;        } 
284                                 
285                                 delete order;
286
287                 }
288                 
289                 if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str());  } globaldata->Groups.clear(); return 0;        } 
290
291                 //reset groups parameter
292                 globaldata->Groups.clear();  
293                 
294                 m->mothurOutEndLine();
295                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
296                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
297                 m->mothurOutEndLine();
298
299
300                 return 0;
301         }
302         catch(exception& e) {
303                 m->errorOut(e, "BootSharedCommand", "execute");
304                 exit(1);
305         }
306 }
307 //**********************************************************************************************************************
308
309 int BootSharedCommand::createTree(ostream* out, Tree* t){
310         try {
311                 
312                 //do merges and create tree structure by setting parents and children
313                 //there are numGroups - 1 merges to do
314                 for (int i = 0; i < (numGroups - 1); i++) {
315                 
316                         if (m->control_pressed) {  return 1; }
317                 
318                         float largest = -1000.0;
319                         int row, column;
320                         //find largest value in sims matrix by searching lower triangle
321                         for (int j = 1; j < simMatrix.size(); j++) {
322                                 for (int k = 0; k < j; k++) {
323                                         if (simMatrix[j][k] > largest) {  largest = simMatrix[j][k]; row = j; column = k;  }
324                                 }
325                         }
326
327                         //set non-leaf node info and update leaves to know their parents
328                         //non-leaf
329                         t->tree[numGroups + i].setChildren(index[row], index[column]);
330                 
331                         //parents
332                         t->tree[index[row]].setParent(numGroups + i);
333                         t->tree[index[column]].setParent(numGroups + i);
334                         
335                         //blength = distance / 2;
336                         float blength = ((1.0 - largest) / 2);
337                         
338                         //branchlengths
339                         t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
340                         t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
341                 
342                         //set your length to leaves to your childs length plus branchlength
343                         t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
344                         
345                 
346                         //update index 
347                         index[row] = numGroups+i;
348                         index[column] = numGroups+i;
349                         
350                         //zero out highest value that caused the merge.
351                         simMatrix[row][column] = -1000.0;
352                         simMatrix[column][row] = -1000.0;
353                 
354                         //merge values in simsMatrix
355                         for (int n = 0; n < simMatrix.size(); n++)      {
356                                 //row becomes merge of 2 groups
357                                 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
358                                 simMatrix[n][row] = simMatrix[row][n];
359                                 //delete column
360                                 simMatrix[column][n] = -1000.0;
361                                 simMatrix[n][column] = -1000.0;
362                         }
363                 }
364                 
365                 //adjust tree to make sure root to tip length is .5
366                 int root = t->findRoot();
367                 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
368
369                 //assemble tree
370                 t->assembleTree();
371                 
372                 if (m->control_pressed) { return 1; }
373         
374                 //print newick file
375                 t->print(*out);
376                 
377                 return 0;
378         
379         }
380         catch(exception& e) {
381                 m->errorOut(e, "BootSharedCommand", "createTree");
382                 exit(1);
383         }
384 }
385 /***********************************************************/
386 void BootSharedCommand::printSims() {
387         try {
388                 m->mothurOut("simsMatrix"); m->mothurOutEndLine(); 
389                 for (int k = 0; k < simMatrix.size(); k++)      {
390                         for (int n = 0; n < simMatrix.size(); n++)      {
391                                 m->mothurOut(toString(simMatrix[k][n]));  m->mothurOut("\t"); 
392                         }
393                         m->mothurOutEndLine(); 
394                 }
395
396         }
397         catch(exception& e) {
398                 m->errorOut(e, "BootSharedCommand", "printSims");
399                 exit(1);
400         }
401 }
402 /***********************************************************/
403 int BootSharedCommand::process(SharedOrderVector* order) {
404         try{
405                                 EstOutput data;
406                                 vector<SharedRAbundVector*> subset;
407                                                                 
408                                 //open an ostream for each calc to print to
409                                 for (int z = 0; z < treeCalculators.size(); z++) {
410                                         //create a new filename
411                                         outputFile = outputDir + getRootName(getSimpleName(globaldata->inputFileName)) + treeCalculators[z]->getName() + ".boot" + order->getLabel() + ".tre";
412                                         openOutputFile(outputFile, *(out[z]));
413                                         outputNames.push_back(outputFile);
414                                 }
415                                 
416                                 m->mothurOut("Generating bootstrap trees..."); cout.flush();
417                                 
418                                 //create a file for each calculator with the 1000 trees in it.
419                                 for (int p = 0; p < iters; p++) {
420                                         
421                                         if (m->control_pressed) {  return 1; }
422                                         
423                                         util->getSharedVectorswithReplacement(globaldata->Groups, lookup, order);  //fills group vectors from order vector.
424
425                                 
426                                         //for each calculator                                                                                           
427                                         for(int i = 0 ; i < treeCalculators.size(); i++) {
428                                                 
429                                                 if (m->control_pressed) {  return 1; }
430                                                 
431                                                 //initialize simMatrix
432                                                 simMatrix.clear();
433                                                 simMatrix.resize(numGroups);
434                                                 for (int o = 0; o < simMatrix.size(); o++)      {
435                                                         for (int j = 0; j < simMatrix.size(); j++)      {
436                                                                 simMatrix[o].push_back(0.0);
437                                                         }
438                                                 }
439                                 
440                                                 //initialize index
441                                                 index.clear();
442                                                 for (int g = 0; g < numGroups; g++) {   index[g] = g;   }
443                                                         
444                                                 for (int k = 0; k < lookup.size(); k++) { // pass cdd each set of groups to commpare
445                                                         for (int l = k; l < lookup.size(); l++) {
446                                                                 if (k != l) { //we dont need to similiarity of a groups to itself
447                                                                         subset.clear(); //clear out old pair of sharedrabunds
448                                                                         //add new pair of sharedrabunds
449                                                                         subset.push_back(lookup[k]); subset.push_back(lookup[l]); 
450                                                                         
451                                                                         //get estimated similarity between 2 groups
452                                                                         data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
453                                                                         //save values in similarity matrix
454                                                                         simMatrix[k][l] = data[0];
455                                                                         simMatrix[l][k] = data[0];
456                                                                 }
457                                                         }
458                                                 }
459                                                 
460                                                 tempTree = new Tree();
461                                                 
462                                                 if (m->control_pressed) {   delete tempTree; return 1; }
463                                                 
464                                                 //creates tree from similarity matrix and write out file
465                                                 createTree(out[i], tempTree);
466                                                 
467                                                 if (m->control_pressed) {   delete tempTree; return 1; }
468                                                 
469                                                 //save trees for consensus command.
470                                                 trees[i].push_back(tempTree);
471                                         }
472                                 }
473                                 
474                                 m->mothurOut("\tDone."); m->mothurOutEndLine();
475                                 //delete globaldata's tree
476                                 //for (int m = 0; m < globaldata->gTree.size(); m++) {  delete globaldata->gTree[m];  }
477                                 //globaldata->gTree.clear();
478                                 
479                                 
480                                 //create consensus trees for each bootstrapped tree set
481                                 for (int k = 0; k < trees.size(); k++) {
482                                         
483                                         m->mothurOut("Generating consensus tree for " + treeCalculators[k]->getName()); m->mothurOutEndLine();
484                                         
485                                         if (m->control_pressed) {  return 1; }
486                                         
487                                         //set global data to calc trees
488                                         globaldata->gTree = trees[k];
489                                         
490                                         string filename = outputDir + getRootName(getSimpleName(globaldata->inputFileName)) + treeCalculators[k]->getName() + ".boot" + order->getLabel();
491                                         consensus = new ConcensusCommand(filename);
492                                         consensus->execute();
493                                         delete consensus;
494                                         
495                                         outputNames.push_back(filename + ".cons.pairs");
496                                         outputNames.push_back(filename + ".cons.tre");
497                                         
498                                         //delete globaldata's tree
499                                         //for (int m = 0; m < globaldata->gTree.size(); m++) {  delete globaldata->gTree[m];  }
500                                         //globaldata->gTree.clear();
501                                         
502                                 }
503                                 
504                                 
505                                         
506                                 //close ostream for each calc
507                                 for (int z = 0; z < treeCalculators.size(); z++) { out[z]->close(); }
508                                 
509                                 return 0;
510         
511         }
512         catch(exception& e) {
513                 m->errorOut(e, "BootSharedCommand", "process");
514                 exit(1);
515         }
516 }
517 /***********************************************************/
518
519
520