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