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