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