]> git.donarmstrong.com Git - mothur.git/blob - unifracunweightedcommand.cpp
added get.otus and remove.otus commands
[mothur.git] / unifracunweightedcommand.cpp
1 /*
2  *  unifracunweightedcommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 2/9/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "unifracunweightedcommand.h"
11
12 //**********************************************************************************************************************
13 vector<string> UnifracUnweightedCommand::getValidParameters(){  
14         try {
15                 string Array[] =  {"groups","iters","distance","random", "processors","outputdir","inputdir"};
16                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
17                 return myArray;
18         }
19         catch(exception& e) {
20                 m->errorOut(e, "UnifracUnweightedCommand", "getValidParameters");
21                 exit(1);
22         }
23 }
24 //**********************************************************************************************************************
25 UnifracUnweightedCommand::UnifracUnweightedCommand(){   
26         try {
27                 globaldata = GlobalData::getInstance();
28                 abort = true;
29                 //initialize outputTypes
30                 vector<string> tempOutNames;
31                 outputTypes["unweighted"] = tempOutNames;
32                 outputTypes["uwsummary"] = tempOutNames;
33                 outputTypes["phylip"] = tempOutNames;
34                 outputTypes["column"] = tempOutNames;
35         }
36         catch(exception& e) {
37                 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
38                 exit(1);
39         }
40 }
41 //**********************************************************************************************************************
42 vector<string> UnifracUnweightedCommand::getRequiredParameters(){       
43         try {
44                 vector<string> myArray;
45                 return myArray;
46         }
47         catch(exception& e) {
48                 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredParameters");
49                 exit(1);
50         }
51 }
52 //**********************************************************************************************************************
53 vector<string> UnifracUnweightedCommand::getRequiredFiles(){    
54         try {
55                 string Array[] =  {"tree","group"};
56                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
57
58                 return myArray;
59         }
60         catch(exception& e) {
61                 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredFiles");
62                 exit(1);
63         }
64 }
65 /***********************************************************/
66 UnifracUnweightedCommand::UnifracUnweightedCommand(string option)  {
67         try {
68                 globaldata = GlobalData::getInstance();
69                 abort = false;
70                 Groups.clear();
71                         
72                 //allow user to run help
73                 if(option == "help") { help(); abort = true; }
74                 
75                 else {
76                         //valid paramters for this command
77                         string Array[] =  {"groups","iters","distance","random", "processors","outputdir","inputdir"};
78                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
79                         
80                         OptionParser parser(option);
81                         map<string,string> parameters = parser.getParameters();
82                         
83                         ValidParameters validParameter;
84                 
85                         //check to make sure all parameters are valid for command
86                         for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) { 
87                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
88                         }
89                         
90                         //initialize outputTypes
91                         vector<string> tempOutNames;
92                         outputTypes["unweighted"] = tempOutNames;
93                         outputTypes["uwsummary"] = tempOutNames;
94                         outputTypes["phylip"] = tempOutNames;
95                         outputTypes["column"] = tempOutNames;
96                         
97                         if (globaldata->gTree.size() == 0) {//no trees were read
98                                 m->mothurOut("You must execute the read.tree command, before you may execute the unifrac.unweighted command."); m->mothurOutEndLine(); abort = true;  }
99                         
100                         //if the user changes the output directory command factory will send this info to us in the output parameter 
101                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
102                                 outputDir = ""; 
103                                 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it       
104                         }
105                                                         
106                         //check for optional parameter and set defaults
107                         // ...at some point should added some additional type checking...
108                         groups = validParameter.validFile(parameters, "groups", false);                 
109                         if (groups == "not found") { groups = ""; }
110                         else { 
111                                 m->splitAtDash(groups, Groups);
112                                 globaldata->Groups = Groups;
113                         }
114                                 
115                         itersString = validParameter.validFile(parameters, "iters", false);                             if (itersString == "not found") { itersString = "1000"; }
116                         convert(itersString, iters); 
117                         
118                         string temp = validParameter.validFile(parameters, "distance", false);                  
119                         if (temp == "not found") { phylip = false; outputForm = ""; }
120                         else{
121                                 if ((temp == "lt") || (temp == "column") || (temp == "square")) {  phylip = true;  outputForm = temp; }
122                                 else { m->mothurOut("Options for distance are: lt, square, or column. Using lt."); m->mothurOutEndLine(); phylip = true; outputForm = "lt"; }
123                         }
124                         
125                         temp = validParameter.validFile(parameters, "random", false);                                   if (temp == "not found") { temp = "f"; }
126                         random = m->isTrue(temp);
127                         
128                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = "1";                             }
129                         convert(temp, processors); 
130                         
131                         if (!random) {  iters = 0;  } //turn off random calcs
132                         
133                         //if user selects distance = true and no groups it won't calc the pairwise
134                         if ((phylip) && (Groups.size() == 0)) {
135                                 groups = "all";
136                                 m->splitAtDash(groups, Groups);
137                                 globaldata->Groups = Groups;
138                         }
139                 
140                         if (abort == false) {
141                                 T = globaldata->gTree;
142                                 tmap = globaldata->gTreemap;
143                                 sumFile = outputDir + m->getSimpleName(globaldata->getTreeFile()) + ".uwsummary";
144                                 outputNames.push_back(sumFile); outputTypes["uwsummary"].push_back(sumFile);
145                                 m->openOutputFile(sumFile, outSum);
146                                 
147                                 util = new SharedUtil();
148                                 util->setGroups(globaldata->Groups, tmap->namesOfGroups, allGroups, numGroups, "unweighted");   //sets the groups the user wants to analyze
149                                 util->getCombos(groupComb, globaldata->Groups, numComp);
150                                 
151                                 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
152                                 
153                                 unweighted = new Unweighted(tmap);
154                                 
155                         }
156                         
157                 }
158                 
159         }
160         catch(exception& e) {
161                 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
162                 exit(1);
163         }
164 }
165
166 //**********************************************************************************************************************
167
168 void UnifracUnweightedCommand::help(){
169         try {
170                 m->mothurOut("The unifrac.unweighted command can only be executed after a successful read.tree command.\n");
171                 m->mothurOut("The unifrac.unweighted command parameters are groups, iters, distance, processors and random.  No parameters are required.\n");
172                 m->mothurOut("The groups parameter allows you to specify which of the groups in your groupfile you would like analyzed.  You must enter at least 1 valid group.\n");
173                 m->mothurOut("The group names are separated by dashes.  The iters parameter allows you to specify how many random trees you would like compared to your tree.\n");
174                 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false. You may set distance to lt, square or column.\n");
175                 m->mothurOut("The random parameter allows you to shut off the comparison to random trees. The default is false, meaning compare don't your trees with randomly generated trees.\n");
176                 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
177                 m->mothurOut("The unifrac.unweighted command should be in the following format: unifrac.unweighted(groups=yourGroups, iters=yourIters).\n");
178                 m->mothurOut("Example unifrac.unweighted(groups=A-B-C, iters=500).\n");
179                 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
180                 m->mothurOut("The unifrac.unweighted command output two files: .unweighted and .uwsummary their descriptions are in the manual.\n");
181                 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
182         }
183         catch(exception& e) {
184                 m->errorOut(e, "UnifracUnweightedCommand", "help");
185                 exit(1);
186         }
187 }
188
189
190 /***********************************************************/
191 int UnifracUnweightedCommand::execute() {
192         try {
193                 
194                 if (abort == true) { return 0; }
195                 
196                 int start = time(NULL);
197                 
198                 userData.resize(numComp,0);  //data[0] = unweightedscore 
199                 randomData.resize(numComp,0); //data[0] = unweightedscore
200                 //create new tree with same num nodes and leaves as users
201                 
202                 outSum << "Tree#" << '\t' << "Groups" << '\t'  <<  "UWScore" <<'\t' << "UWSig" <<  endl;
203                 m->mothurOut("Tree#\tGroups\tUWScore\tUWSig"); m->mothurOutEndLine();
204                 
205                 //get pscores for users trees
206                 for (int i = 0; i < T.size(); i++) {
207                         if (m->control_pressed) { 
208                                 outSum.close();
209                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  }
210                                 return 0; 
211                         }
212                         
213                         counter = 0;
214                         
215                         if (random)  {  
216                                 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".unweighted", itersString);
217                                 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".unweighted");
218                                 outputTypes["unweighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".unweighted");
219                         }
220                         
221                         
222                         //get unweighted for users tree
223                         rscoreFreq.resize(numComp);  
224                         rCumul.resize(numComp);  
225                         utreeScores.resize(numComp);  
226                         UWScoreSig.resize(numComp); 
227
228                         userData = unweighted->getValues(T[i], processors, outputDir);  //userData[0] = unweightedscore
229                 
230                         if (m->control_pressed) { if (random) { delete output;  } outSum.close();  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str());  }return 0; }
231                         
232                         //output scores for each combination
233                         for(int k = 0; k < numComp; k++) {
234                                 //saves users score
235                                 utreeScores[k].push_back(userData[k]);
236                                 
237                                 //add users score to validscores
238                                 validScores[userData[k]] = userData[k];
239                         }
240                 
241                         //get unweighted scores for random trees - if random is false iters = 0
242                         for (int j = 0; j < iters; j++) {
243                 
244                                 //we need a different getValues because when we swap the labels we only want to swap those in each pairwise comparison
245                                 randomData = unweighted->getValues(T[i], "", "", processors, outputDir);
246                                 
247                                 if (m->control_pressed) { if (random) { delete output;  } outSum.close(); for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0; }
248                         
249                                 for(int k = 0; k < numComp; k++) {      
250                                         //add trees unweighted score to map of scores
251                                         map<float,float>::iterator it = rscoreFreq[k].find(randomData[k]);
252                                         if (it != rscoreFreq[k].end()) {//already have that score
253                                                 rscoreFreq[k][randomData[k]]++;
254                                         }else{//first time we have seen this score
255                                                 rscoreFreq[k][randomData[k]] = 1;
256                                         }
257                                 
258                                         //add randoms score to validscores
259                                         validScores[randomData[k]] = randomData[k];
260                                 }
261                                 
262                                 //report progress
263                                 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();  
264                         }
265         
266                         for(int a = 0; a < numComp; a++) {
267                                 float rcumul = 1.0000;
268                                 
269                                 if (random) {
270                                         //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
271                                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
272                                                 //make rscoreFreq map and rCumul
273                                                 map<float,float>::iterator it2 = rscoreFreq[a].find(it->first);
274                                                 rCumul[a][it->first] = rcumul;
275                                                 //get percentage of random trees with that info
276                                                 if (it2 != rscoreFreq[a].end()) {  rscoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
277                                                 else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
278                                         }
279                                         UWScoreSig[a].push_back(rCumul[a][userData[a]]);
280                                 }else           {       UWScoreSig[a].push_back(0.0);                                           }
281         
282                         }
283                         
284                         if (m->control_pressed) { if (random) { delete output;  } outSum.close(); for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0;  }
285                         
286                         //print output files
287                         printUWSummaryFile(i);
288                         if (random)  {  printUnweightedFile();  delete output;  }
289                         if (phylip) {   createPhylipFile(i);            }
290                         
291                         rscoreFreq.clear(); 
292                         rCumul.clear();  
293                         validScores.clear(); 
294                         utreeScores.clear();  
295                         UWScoreSig.clear(); 
296                 }
297                 
298
299                 outSum.close();
300                 
301                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  }      return 0; }
302                 
303                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.unweighted."); m->mothurOutEndLine();
304                 
305                 m->mothurOutEndLine();
306                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
307                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
308                 m->mothurOutEndLine();
309                 
310                 return 0;
311                 
312         }
313         catch(exception& e) {
314                 m->errorOut(e, "UnifracUnweightedCommand", "execute");
315                 exit(1);
316         }
317 }
318 /***********************************************************/
319 void UnifracUnweightedCommand::printUnweightedFile() {
320         try {
321                 vector<double> data;
322                 vector<string> tags;
323                 
324                 tags.push_back("Score");
325                 tags.push_back("RandFreq"); tags.push_back("RandCumul");
326                         
327                 for(int a = 0; a < numComp; a++) {
328                         output->initFile(groupComb[a], tags);
329                         //print each line
330                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
331                                 data.push_back(it->first);  data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);                                             
332                                 output->output(data);
333                                 data.clear();
334                         } 
335                         output->resetFile();
336                 }
337         }
338         catch(exception& e) {
339                 m->errorOut(e, "UnifracUnweightedCommand", "printUnweightedFile");
340                 exit(1);
341         }
342 }
343
344 /***********************************************************/
345 void UnifracUnweightedCommand::printUWSummaryFile(int i) {
346         try {
347                                 
348                 //format output
349                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
350                         
351                 //print each line
352
353                 for(int a = 0; a < numComp; a++) {
354                         outSum << i+1 << '\t';
355                         m->mothurOut(toString(i+1) + "\t");
356                         
357                         if (random) {
358                                 if (UWScoreSig[a][0] > (1/(float)iters)) {
359                                         outSum << setprecision(6) << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
360                                         cout << setprecision(6)  << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl; 
361                                         m->mothurOutJustToLog(groupComb[a]  + "\t" + toString(utreeScores[a][0])  + "\t" + toString(UWScoreSig[a][0])+ "\n"); 
362                                 }else {
363                                         outSum << setprecision(6) << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
364                                         cout << setprecision(6)  << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
365                                         m->mothurOutJustToLog(groupComb[a]  + "\t" + toString(utreeScores[a][0])  + "\t<" + toString((1/float(iters))) + "\n"); 
366                                 }
367                         }else{
368                                 outSum << setprecision(6) << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
369                                 cout << setprecision(6)  << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl; 
370                                 m->mothurOutJustToLog(groupComb[a]  + "\t" + toString(utreeScores[a][0])  + "\t0.00\n");
371                         }
372                 }
373                 
374         }
375         catch(exception& e) {
376                 m->errorOut(e, "UnifracUnweightedCommand", "printUWSummaryFile");
377                 exit(1);
378         }
379 }
380 /***********************************************************/
381 void UnifracUnweightedCommand::createPhylipFile(int i) {
382         try {
383                 string phylipFileName;
384                 if ((outputForm == "lt") || (outputForm == "square")) {
385                         phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".unweighted.phylip.dist";
386                         outputNames.push_back(phylipFileName); outputTypes["phylip"].push_back(phylipFileName); 
387                 }else { //column
388                         phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".unweighted.column.dist";
389                         outputNames.push_back(phylipFileName); outputTypes["column"].push_back(phylipFileName); 
390                 }
391                 
392                 ofstream out;
393                 m->openOutputFile(phylipFileName, out);
394                 
395                 if ((outputForm == "lt") || (outputForm == "square")) {
396                         //output numSeqs
397                         out << globaldata->Groups.size() << endl;
398                 }
399                 
400                 //make matrix with scores in it
401                 vector< vector<float> > dists;  dists.resize(globaldata->Groups.size());
402                 for (int i = 0; i < globaldata->Groups.size(); i++) {
403                         dists[i].resize(globaldata->Groups.size(), 0.0);
404                 }
405                 
406                 //flip it so you can print it
407                 int count = 0;
408                 for (int r=0; r<globaldata->Groups.size(); r++) { 
409                         for (int l = r+1; l < globaldata->Groups.size(); l++) {
410                                 dists[r][l] = utreeScores[count][0];
411                                 dists[l][r] = utreeScores[count][0];
412                                 count++;
413                         }
414                 }
415                 
416                 //output to file
417                 for (int r=0; r<globaldata->Groups.size(); r++) { 
418                         //output name
419                         string name = globaldata->Groups[r];
420                         if (name.length() < 10) { //pad with spaces to make compatible
421                                 while (name.length() < 10) {  name += " ";  }
422                         }
423                         
424                         if (outputForm == "lt") {
425                                 out << name << '\t';
426                         
427                                 //output distances
428                                 for (int l = 0; l < r; l++) {   out  << dists[r][l] << '\t';  }
429                                 out << endl;
430                         }else if (outputForm == "square") {
431                                 out << name << '\t';
432                                 
433                                 //output distances
434                                 for (int l = 0; l < globaldata->Groups.size(); l++) {   out  << dists[r][l] << '\t';  }
435                                 out << endl;
436                         }else{
437                                 //output distances
438                                 for (int l = 0; l < r; l++) {   
439                                         string otherName = globaldata->Groups[l];
440                                         if (otherName.length() < 10) { //pad with spaces to make compatible
441                                                 while (otherName.length() < 10) {  otherName += " ";  }
442                                         }
443                                         
444                                         out  << name << '\t' << otherName << dists[r][l] << endl;  
445                                 }
446                         }
447                 }
448                 out.close();
449         }
450         catch(exception& e) {
451                 m->errorOut(e, "UnifracUnweightedCommand", "createPhylipFile");
452                 exit(1);
453         }
454 }
455 /***********************************************************/
456
457
458