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