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