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