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