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