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