]> git.donarmstrong.com Git - mothur.git/blob - bootstrapsharedcommand.cpp
9e3a82de0bfaff9807c653ce0986f96f59b67cba
[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
25 BootSharedCommand::BootSharedCommand(string option){
26         try {
27                 globaldata = GlobalData::getInstance();
28                 abort = false;
29                 allLines = 1;
30                 lines.clear();
31                 labels.clear();
32                 Groups.clear();
33                 Estimators.clear();
34                 
35                 //allow user to run help
36                 if(option == "help") { help(); abort = true; }
37                 
38                 else {
39                         //valid paramters for this command
40                         string Array[] =  {"line","label","calc","groups","iters"};
41                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
42                         
43                         parser = new OptionParser();
44                         parser->parse(option, parameters);  delete parser;
45                         
46                         ValidParameters* validParameter = new ValidParameters();
47                 
48                         //check to make sure all parameters are valid for command
49                         for (it = parameters.begin(); it != parameters.end(); it++) { 
50                                 if (validParameter->isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
51                         }
52                         
53                         //make sure the user has already run the read.otu command
54                         if (globaldata->getSharedFile() == "") {
55                                 if (globaldata->getListFile() == "") { cout << "You must read a list and a group, or a shared before you can use the bootstrap.shared command." << endl; abort = true; }
56                                 else if (globaldata->getGroupFile() == "") { cout << "You must read a list and a group, or a shared before you can use the bootstrap.shared command." << endl; abort = true; }
57                         }
58                         
59                         //check for optional parameter and set defaults
60                         // ...at some point should added some additional type checking...
61                         line = validParameter->validFile(parameters, "line", false);                            
62                         if (line == "not found") { line = "";  }
63                         else { 
64                                 if(line != "all") {  splitAtDash(line, lines);  allLines = 0;  }
65                                 else { allLines = 1;  }
66                         }
67                         
68                         label = validParameter->validFile(parameters, "label", false);                  
69                         if (label == "not found") { label = ""; }
70                         else { 
71                                 if(label != "all") {  splitAtDash(label, labels);  allLines = 0;  }
72                                 else { allLines = 1;  }
73                         }
74                         
75                         //make sure user did not use both the line and label parameters
76                         if ((line != "") && (label != "")) { cout << "You cannot use both the line and label parameters at the same time. " << endl; abort = true; }
77                         //if the user has not specified any line or labels use the ones from read.otu
78                         else if((line == "") && (label == "")) {  
79                                 allLines = globaldata->allLines; 
80                                 labels = globaldata->labels; 
81                                 lines = globaldata->lines;
82                         }
83                                 
84                         groups = validParameter->validFile(parameters, "groups", false);                        
85                         if (groups == "not found") { groups = ""; }
86                         else { 
87                                 splitAtDash(groups, Groups);
88                                 globaldata->Groups = Groups;
89                         }
90                                 
91                         calc = validParameter->validFile(parameters, "calc", false);                    
92                         if (calc == "not found") { calc = "jclass-thetayc";  }
93                         else { 
94                                  if (calc == "default")  {  calc = "jclass-thetayc";  }
95                         }
96                         splitAtDash(calc, Estimators);
97
98                         string temp;
99                         temp = validParameter->validFile(parameters, "iters", false);                   if (temp == "not found") { temp = "1000"; }
100                         convert(temp, iters); 
101         
102                         delete validParameter;
103                         
104                         if (abort == false) {
105                         
106                                 validCalculator = new ValidCalculators();
107                                 
108                                 int i;
109                                 for (i=0; i<Estimators.size(); i++) {
110                                         if (validCalculator->isValidCalculator("boot", Estimators[i]) == true) { 
111                                                 if (Estimators[i] == "jabund") {        
112                                                         treeCalculators.push_back(new JAbund());
113                                                 }else if (Estimators[i] == "sorabund") { 
114                                                         treeCalculators.push_back(new SorAbund());
115                                                 }else if (Estimators[i] == "jclass") { 
116                                                         treeCalculators.push_back(new Jclass());
117                                                 }else if (Estimators[i] == "sorclass") { 
118                                                         treeCalculators.push_back(new SorClass());
119                                                 }else if (Estimators[i] == "jest") { 
120                                                         treeCalculators.push_back(new Jest());
121                                                 }else if (Estimators[i] == "sorest") { 
122                                                         treeCalculators.push_back(new SorEst());
123                                                 }else if (Estimators[i] == "thetayc") { 
124                                                         treeCalculators.push_back(new ThetaYC());
125                                                 }else if (Estimators[i] == "thetan") { 
126                                                         treeCalculators.push_back(new ThetaN());
127                                                 }else if (Estimators[i] == "morisitahorn") { 
128                                                         treeCalculators.push_back(new MorHorn());
129                                                 }else if (Estimators[i] == "braycurtis") { 
130                                                         treeCalculators.push_back(new BrayCurtis());
131                                                 }
132                                         }
133                                 }
134                                 
135                                 delete validCalculator;
136                                 
137                                 ofstream* tempo;
138                                 for (int i=0; i < treeCalculators.size(); i++) {
139                                         tempo = new ofstream;
140                                         out.push_back(tempo);
141                                 }       
142                         }
143                 }
144
145         }
146         catch(exception& e) {
147                 cout << "Standard Error: " << e.what() << " has occurred in the BootSharedCommand class Function BootSharedCommand. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
148                 exit(1);
149         }
150         catch(...) {
151                 cout << "An unknown error has occurred in the BootSharedCommand class function BootSharedCommand. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
152                 exit(1);
153         }       
154 }
155
156 //**********************************************************************************************************************
157
158 void BootSharedCommand::help(){
159         try {
160                 cout << "The bootstrap.shared command can only be executed after a successful read.otu command." << "\n";
161                 cout << "The bootstrap.shared command parameters are groups, calc, iters, line and label.  You may not use line and label at the same time." << "\n";
162                 cout << "The groups parameter allows you to specify which of the groups in your groupfile you would like included used." << "\n";
163                 cout << "The group names are separated by dashes. The line and label allow you to select what distance levels you would like trees created for, and are also separated by dashes." << "\n";
164                 cout << "The bootstrap.shared command should be in the following format: bootstrap.shared(groups=yourGroups, calc=yourCalcs, line=yourLines, label=yourLabels, iters=yourIters)." << "\n";
165                 cout << "Example bootstrap.shared(groups=A-B-C, line=1-3-5, calc=jabund-sorabund, iters=100)." << "\n";
166                 cout << "The default value for groups is all the groups in your groupfile." << "\n";
167                 cout << "The default value for calc is jclass-thetayc. The default for iters is 1000." << "\n";
168         }
169         catch(exception& e) {
170                 cout << "Standard Error: " << e.what() << " has occurred in the BootSharedCommand class Function help. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
171                 exit(1);
172         }
173         catch(...) {
174                 cout << "An unknown error has occurred in the BootSharedCommand class function help. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
175                 exit(1);
176         }       
177 }
178
179 //**********************************************************************************************************************
180
181 BootSharedCommand::~BootSharedCommand(){
182         //made new in execute
183         if (abort == false) {
184                 delete input;
185                 delete read;
186                 delete util;
187         }
188 }
189
190 //**********************************************************************************************************************
191
192 int BootSharedCommand::execute(){
193         try {
194         
195                 if (abort == true) {    return 0;       }
196         
197                 int count = 1;
198                 util = new SharedUtil();        
199         
200                 //read first line
201                 read = new ReadOTUFile(globaldata->inputFileName);      
202                 read->read(&*globaldata); 
203                 input = globaldata->ginput;
204                 order = input->getSharedOrderVector();
205                 SharedOrderVector* lastOrder = order;
206                 
207                 //if the users entered no valid calculators don't execute command
208                 if (treeCalculators.size() == 0) { return 0; }
209
210                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
211                 set<string> processedLabels;
212                 set<string> userLabels = labels;
213                 set<int> userLines = lines;
214                                 
215                 //set users groups
216                 util->setGroups(globaldata->Groups, globaldata->gGroupmap->namesOfGroups, "treegroup");
217                 numGroups = globaldata->Groups.size();
218                 
219                 //clear globaldatas old tree names if any
220                 globaldata->Treenames.clear();
221                 
222                 //fills globaldatas tree names
223                 globaldata->Treenames = globaldata->Groups;
224                 
225                 //create treemap class from groupmap for tree class to use
226                 tmap = new TreeMap();
227                 tmap->makeSim(globaldata->gGroupmap);
228                 globaldata->gTreemap = tmap;
229                         
230                 while((order != NULL) && ((allLines == 1) || (userLabels.size() != 0) || (userLines.size() != 0))) {
231                 
232                         if(allLines == 1 || lines.count(count) == 1 || labels.count(order->getLabel()) == 1){                   
233                                 
234                                 cout << order->getLabel() << '\t' << count << endl;
235                                 process(order);
236                                 
237                                 processedLabels.insert(order->getLabel());
238                                 userLabels.erase(order->getLabel());
239                                 userLines.erase(count);
240                         }
241                         
242                         //you have a label the user want that is smaller than this line and the last line has not already been processed
243                         if ((anyLabelsToProcess(order->getLabel(), userLabels, "") == true) && (processedLabels.count(lastOrder->getLabel()) != 1)) {
244                                                                                         
245                                 cout << lastOrder->getLabel() << '\t' << count << endl;
246                                 process(lastOrder);
247
248                                 processedLabels.insert(lastOrder->getLabel());
249                                 userLabels.erase(lastOrder->getLabel());
250                         }
251                         
252                         if (count != 1) { delete lastOrder; }
253                         lastOrder = order;                      
254
255                         //get next line to process
256                         order = input->getSharedOrderVector();
257                         count++;
258                 }
259                 
260                 //output error messages about any remaining user labels
261                 set<string>::iterator it;
262                 bool needToRun = false;
263                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
264                         cout << "Your file does not include the label "<< *it; 
265                         if (processedLabels.count(lastOrder->getLabel()) != 1) {
266                                 cout << ". I will use " << lastOrder->getLabel() << "." << endl;
267                                 needToRun = true;
268                         }else {
269                                 cout << ". Please refer to " << lastOrder->getLabel() << "." << endl;
270                         }
271                 }
272                 
273                 //run last line if you need to
274                 if (needToRun == true)  {
275                         process(lastOrder);                     
276                         cout << lastOrder->getLabel() << '\t' << count << endl;
277                 }
278                 
279                 delete lastOrder;
280
281                 //reset groups parameter
282                 globaldata->Groups.clear();  
283
284                 return 0;
285         }
286         catch(exception& e) {
287                 cout << "Standard Error: " << e.what() << " has occurred in the BootSharedCommand class Function execute. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
288                 exit(1);
289         }
290         catch(...) {
291                 cout << "An unknown error has occurred in the BootSharedCommand class function execute. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
292                 exit(1);
293         }               
294 }
295 //**********************************************************************************************************************
296
297 void BootSharedCommand::createTree(ostream* out){
298         try {
299                 //create tree
300                 t = new Tree();
301                 
302                 //do merges and create tree structure by setting parents and children
303                 //there are numGroups - 1 merges to do
304                 for (int i = 0; i < (numGroups - 1); i++) {
305                 
306                         float largest = -1.0;
307                         int row, column;
308                         //find largest value in sims matrix by searching lower triangle
309                         for (int j = 1; j < simMatrix.size(); j++) {
310                                 for (int k = 0; k < j; k++) {
311                                         if (simMatrix[j][k] > largest) {  largest = simMatrix[j][k]; row = j; column = k;  }
312                                 }
313                         }
314
315                         //set non-leaf node info and update leaves to know their parents
316                         //non-leaf
317                         t->tree[numGroups + i].setChildren(index[row], index[column]);
318                 
319                         //parents
320                         t->tree[index[row]].setParent(numGroups + i);
321                         t->tree[index[column]].setParent(numGroups + i);
322                         
323                         //blength = distance / 2;
324                         float blength = ((1.0 - largest) / 2);
325                         
326                         //branchlengths
327                         t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
328                         t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
329                 
330                         //set your length to leaves to your childs length plus branchlength
331                         t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
332                         
333                 
334                         //update index 
335                         index[row] = numGroups+i;
336                         index[column] = numGroups+i;
337                         
338                         //zero out highest value that caused the merge.
339                         simMatrix[row][column] = -1.0;
340                         simMatrix[column][row] = -1.0;
341                 
342                         //merge values in simsMatrix
343                         for (int n = 0; n < simMatrix.size(); n++)      {
344                                 //row becomes merge of 2 groups
345                                 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
346                                 simMatrix[n][row] = simMatrix[row][n];
347                                 //delete column
348                                 simMatrix[column][n] = -1.0;
349                                 simMatrix[n][column] = -1.0;
350                         }
351                 }
352
353                 //assemble tree
354                 t->assembleTree();
355         
356                 //print newick file
357                 t->print(*out);
358         
359                 //delete tree
360                 delete t;
361         
362         }
363         catch(exception& e) {
364                 cout << "Standard Error: " << e.what() << " has occurred in the BootSharedCommand class Function createTree. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
365                 exit(1);
366         }
367         catch(...) {
368                 cout << "An unknown error has occurred in the BootSharedCommand class function createTree. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
369                 exit(1);
370         }
371 }
372 /***********************************************************/
373 void BootSharedCommand::printSims() {
374         try {
375                 cout << "simsMatrix" << endl;
376                 for (int m = 0; m < simMatrix.size(); m++)      {
377                         for (int n = 0; n < simMatrix.size(); n++)      {
378                                 cout << simMatrix[m][n] << '\t'; 
379                         }
380                         cout << endl;
381                 }
382
383         }
384         catch(exception& e) {
385                 cout << "Standard Error: " << e.what() << " has occurred in the BootSharedCommand class Function printSims. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
386                 exit(1);
387         }
388         catch(...) {
389                 cout << "An unknown error has occurred in the BootSharedCommand class function printSims. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
390                 exit(1);
391         }               
392 }
393 /***********************************************************/
394 void BootSharedCommand::process(SharedOrderVector* order) {
395         try{
396                                 EstOutput data;
397                                 vector<SharedRAbundVector*> subset;
398                                 
399                                 //open an ostream for each calc to print to
400                                 for (int z = 0; z < treeCalculators.size(); z++) {
401                                         //create a new filename
402                                         outputFile = getRootName(globaldata->inputFileName) + treeCalculators[z]->getName() + ".boot" + order->getLabel() + ".tre";
403                                         openOutputFile(outputFile, *(out[z]));
404                                 }
405                                 
406                                 //create a file for each calculator with the 1000 trees in it.
407                                 for (int p = 0; p < iters; p++) {
408                                         
409                                         util->getSharedVectorswithReplacement(Groups, lookup, order);  //fills group vectors from order vector.
410                                 
411                                         //for each calculator                                                                                           
412                                         for(int i = 0 ; i < treeCalculators.size(); i++) {
413                                         
414                                                 //initialize simMatrix
415                                                 simMatrix.clear();
416                                                 simMatrix.resize(numGroups);
417                                                 for (int m = 0; m < simMatrix.size(); m++)      {
418                                                         for (int j = 0; j < simMatrix.size(); j++)      {
419                                                                 simMatrix[m].push_back(0.0);
420                                                         }
421                                                 }
422                                 
423                                                 //initialize index
424                                                 index.clear();
425                                                 for (int g = 0; g < numGroups; g++) {   index[g] = g;   }
426                                                         
427                                                 for (int k = 0; k < lookup.size(); k++) { // pass cdd each set of groups to commpare
428                                                         for (int l = k; l < lookup.size(); l++) {
429                                                                 if (k != l) { //we dont need to similiarity of a groups to itself
430                                                                         subset.clear(); //clear out old pair of sharedrabunds
431                                                                         //add new pair of sharedrabunds
432                                                                         subset.push_back(lookup[k]); subset.push_back(lookup[l]); 
433                                                                         
434                                                                         //get estimated similarity between 2 groups
435                                                                         data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
436                                                                         //save values in similarity matrix
437                                                                         simMatrix[k][l] = data[0];
438                                                                         simMatrix[l][k] = data[0];
439                                                                 }
440                                                         }
441                                                 }
442                                 
443                                                 //creates tree from similarity matrix and write out file
444                                                 createTree(out[i]);
445                                         }
446                                 }
447                                 //close ostream for each calc
448                                 for (int z = 0; z < treeCalculators.size(); z++) { out[z]->close(); }
449
450         }
451         catch(exception& e) {
452                 cout << "Standard Error: " << e.what() << " has occurred in the BootSharedCommand class Function process. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
453                 exit(1);
454         }
455         catch(...) {
456                 cout << "An unknown error has occurred in the BootSharedCommand class function process. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
457                 exit(1);
458         }               
459 }
460 /***********************************************************/
461
462
463