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