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