]> git.donarmstrong.com Git - mothur.git/blob - unifracweightedcommand.cpp
added checks for ^C to quit command instead of program
[mothur.git] / unifracweightedcommand.cpp
1 /*
2  *  unifracweightedcommand.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 "unifracweightedcommand.h"
11
12 /***********************************************************/
13 UnifracWeightedCommand::UnifracWeightedCommand(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.weighted 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 += 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                                 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 = isTrue(temp);
60                 
61                         temp = validParameter.validFile(parameters, "random", false);                                   if (temp == "not found") { temp = "true"; }
62                         random = isTrue(temp);
63                         
64                         if (!random) {  iters = 0;  } //turn off random calcs
65
66                         
67                         if (abort == false) {
68                                 T = globaldata->gTree;
69                                 tmap = globaldata->gTreemap;
70                                 sumFile = outputDir + getSimpleName(globaldata->getTreeFile()) + ".wsummary";
71                                 openOutputFile(sumFile, outSum);
72                                 outputNames.push_back(sumFile);
73                                 
74                                 util = new SharedUtil();
75                                 string s; //to make work with setgroups
76                                 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted");     //sets the groups the user wants to analyze
77                                 util->getCombos(groupComb, globaldata->Groups, numComp);
78                                 
79                                 weighted = new Weighted(tmap);
80                                 
81                         }
82                 }
83                 
84                 
85         }
86         catch(exception& e) {
87                 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
88                 exit(1);
89         }
90 }
91 //**********************************************************************************************************************
92
93 void UnifracWeightedCommand::help(){
94         try {
95                 m->mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
96                 m->mothurOut("The unifrac.weighted command parameters are groups, iters, distance and random.  No parameters are required.\n");
97                 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 2 valid groups.\n");
98                 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");
99                 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
100                 m->mothurOut("The random parameter allows you to shut off the comparison to random trees. The default is true, meaning compare your trees with randomly generated trees.\n");
101                 m->mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
102                 m->mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
103                 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
104                 m->mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
105                 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
106         }
107         catch(exception& e) {
108                 m->errorOut(e, "UnifracWeightedCommand", "help");
109                 exit(1);
110         }
111 }
112
113 /***********************************************************/
114 int UnifracWeightedCommand::execute() {
115         try {
116         
117                 if (abort == true) { return 0; }
118                 
119                 Progress* reading;
120                 if (random) {   reading = new Progress("Comparing to random:", iters);  }
121                 
122                 //get weighted for users tree
123                 userData.resize(numComp,0);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
124                 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
125                                 
126                 //create new tree with same num nodes and leaves as users
127                 randT = new Tree();
128                 
129                 //get weighted scores for users trees
130                 for (int i = 0; i < T.size(); i++) {
131                         
132                         if (m->control_pressed) { 
133                                 delete randT;
134                                 if (random) { delete reading; }
135                                 outSum.close();
136                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  }
137                                 return 0; 
138                         }
139
140                         counter = 0;
141                         rScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
142                         uScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
143                         
144                         if (random) {  
145                                 output = new ColumnFile(outputDir + getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted", itersString);  
146                                 outputNames.push_back(outputDir + getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted");
147                         } 
148
149                         userData = weighted->getValues(T[i]);  //userData[0] = weightedscore
150                         
151                         if (m->control_pressed) { 
152                                 delete randT;
153                                 if (random) { delete reading; delete output; }
154                                 outSum.close();
155                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  }
156                                 return 0; 
157                         }
158
159                         
160                         //save users score
161                         for (int s=0; s<numComp; s++) {
162                                 //add users score to vector of user scores
163                                 uScores[s].push_back(userData[s]);
164                                 
165                                 //save users tree score for summary file
166                                 utreeScores.push_back(userData[s]);
167                         }
168                         
169                         //get scores for random trees
170                         for (int j = 0; j < iters; j++) {
171                                 int count = 0;
172                                 for (int r=0; r<numGroups; r++) { 
173                                         for (int l = r+1; l < numGroups; l++) {
174                                                 //copy T[i]'s info.
175                                                 randT->getCopy(T[i]);
176                                                  
177                                                 //create a random tree with same topology as T[i], but different labels
178                                                 randT->assembleRandomUnifracTree(globaldata->Groups[r], globaldata->Groups[l]);
179                                                 
180                                                 if (m->control_pressed) { 
181                                                         delete randT;
182                                                         if (random) { delete reading; delete output; }
183                                                         outSum.close();
184                                                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  }
185                                                         return 0; 
186                                                 }
187
188
189                                                 //get wscore of random tree
190                                                 randomData = weighted->getValues(randT, globaldata->Groups[r], globaldata->Groups[l]);
191                                                 
192                                                 if (m->control_pressed) { 
193                                                         delete randT;
194                                                         if (random) { delete reading; delete output; }
195                                                         outSum.close();
196                                                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  }
197                                                         return 0; 
198                                                 }
199                                                 
200                                                 //save scores
201                                                 rScores[count].push_back(randomData[0]);
202                                                 count++;
203                                         }
204                                 }
205                                 
206                                 //update progress bar
207                                 reading->update(j);
208
209                         }
210
211                         //removeValidScoresDuplicates(); 
212                         //find the signifigance of the score for summary file
213                         if (random) {
214                                 for (int f = 0; f < numComp; f++) {
215                                         //sort random scores
216                                         sort(rScores[f].begin(), rScores[f].end());
217                                         
218                                         //the index of the score higher than yours is returned 
219                                         //so if you have 1000 random trees the index returned is 100 
220                                         //then there are 900 trees with a score greater then you. 
221                                         //giving you a signifigance of 0.900
222                                         int index = findIndex(userData[f], f);    if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
223                                         
224                                         //the signifigance is the number of trees with the users score or higher 
225                                         WScoreSig.push_back((iters-index)/(float)iters);
226                                 }
227                                 
228                                 //out << "Tree# " << i << endl;
229                                 calculateFreqsCumuls();
230                                 printWeightedFile();
231                                 
232                                 delete output;
233                         }
234                         
235                         //clear data
236                         rScores.clear();
237                         uScores.clear();
238                         validScores.clear();
239                 }
240                 
241                 
242                 if (m->control_pressed) { 
243                                 delete randT;
244                                 if (random) { delete reading;  }
245                                 outSum.close();
246                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  }
247                                 return 0; 
248                 }
249                 
250                 //finish progress bar
251                 if (random) {   reading->finish();      delete reading;         }
252                 
253                 printWSummaryFile();
254                 
255                 if (phylip) {   createPhylipFile();             }
256
257                 //clear out users groups
258                 globaldata->Groups.clear();
259                 
260                 delete randT;
261                 
262                 if (m->control_pressed) { 
263                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  }
264                         return 0; 
265                 }
266                 
267                 m->mothurOutEndLine();
268                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
269                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
270                 m->mothurOutEndLine();
271                 
272                 return 0;
273                 
274         }
275         catch(exception& e) {
276                 m->errorOut(e, "UnifracWeightedCommand", "execute");
277                 exit(1);
278         }
279 }
280 /***********************************************************/
281 void UnifracWeightedCommand::printWeightedFile() {
282         try {
283                 vector<double> data;
284                 vector<string> tags;
285                 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
286                 
287                 for(int a = 0; a < numComp; a++) {
288                         output->initFile(groupComb[a], tags);
289                         //print each line
290                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
291                                 data.push_back(it->first);  data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]); 
292                                 output->output(data);
293                                 data.clear();
294                         } 
295                         output->resetFile();
296                 }
297         }
298         catch(exception& e) {
299                 m->errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
300                 exit(1);
301         }
302 }
303
304
305 /***********************************************************/
306 void UnifracWeightedCommand::printWSummaryFile() {
307         try {
308                 //column headers
309                 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" <<  endl;
310                 m->mothurOut("Tree#\tGroups\tWScore\tWSig"); m->mothurOutEndLine(); 
311                 
312                 //format output
313                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
314                 
315                 //print each line
316                 int count = 0;
317                 for (int i = 0; i < T.size(); i++) { 
318                         for (int j = 0; j < numComp; j++) {
319                                 if (random) {
320                                         if (WScoreSig[count] > (1/(float)iters)) {
321                                                 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
322                                                 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
323                                                 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" +  toString(WScoreSig[count])); m->mothurOutEndLine();  
324                                         }else{
325                                                 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
326                                                 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
327                                                 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" +  toString((1/float(iters)))); m->mothurOutEndLine();  
328                                         }
329                                 }else{
330                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl; 
331                                         cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl; 
332                                         m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00"); m->mothurOutEndLine(); 
333                                 }
334                                 count++;
335                         }
336                 }
337                 outSum.close();
338         }
339         catch(exception& e) {
340                 m->errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
341                 exit(1);
342         }
343 }
344 /***********************************************************/
345 void UnifracWeightedCommand::createPhylipFile() {
346         try {
347                 int count = 0;
348                 //for each tree
349                 for (int i = 0; i < T.size(); i++) { 
350                 
351                         string phylipFileName = outputDir + getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted.dist";
352                         outputNames.push_back(phylipFileName);
353                         ofstream out;
354                         openOutputFile(phylipFileName, out);
355                         
356                         //output numSeqs
357                         out << globaldata->Groups.size() << endl;
358                         
359                         //make matrix with scores in it
360                         vector< vector<float> > dists;  dists.resize(globaldata->Groups.size());
361                         for (int i = 0; i < globaldata->Groups.size(); i++) {
362                                 dists[i].resize(globaldata->Groups.size(), 0.0);
363                         }
364                         
365                         //flip it so you can print it
366                         for (int r=0; r<globaldata->Groups.size(); r++) { 
367                                 for (int l = r+1; l < globaldata->Groups.size(); l++) {
368                                         dists[r][l] = (1.0 - utreeScores[count]);
369                                         dists[l][r] = (1.0 - utreeScores[count]);
370                                         count++;
371                                 }
372                         }
373
374                         //output to file
375                         for (int r=0; r<globaldata->Groups.size(); r++) { 
376                                 //output name
377                                 string name = globaldata->Groups[r];
378                                 if (name.length() < 10) { //pad with spaces to make compatible
379                                         while (name.length() < 10) {  name += " ";  }
380                                 }
381                                 out << name << '\t';
382                                 
383                                 //output distances
384                                 for (int l = 0; l < r; l++) {   out  << dists[r][l] << '\t';  }
385                                 out << endl;
386                         }
387                         out.close();
388                 }
389         }
390         catch(exception& e) {
391                 m->errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
392                 exit(1);
393         }
394 }
395 /***********************************************************/
396 int UnifracWeightedCommand::findIndex(float score, int index) {
397         try{
398                 for (int i = 0; i < rScores[index].size(); i++) {
399                         if (rScores[index][i] >= score) {       return i;       }
400                 }
401                 return rScores[index].size();
402         }
403         catch(exception& e) {
404                 m->errorOut(e, "UnifracWeightedCommand", "findIndex");
405                 exit(1);
406         }
407 }
408
409 /***********************************************************/
410
411 void UnifracWeightedCommand::calculateFreqsCumuls() {
412         try {
413                 //clear out old tree values
414                 rScoreFreq.clear();
415                 rScoreFreq.resize(numComp);
416                 rCumul.clear();
417                 rCumul.resize(numComp);
418                 validScores.clear();
419         
420                 //calculate frequency
421                 for (int f = 0; f < numComp; f++) {
422                         for (int i = 0; i < rScores[f].size(); i++) { //looks like 0,0,1,1,1,2,4,7...  you want to make a map that say rScoreFreq[0] = 2, rScoreFreq[1] = 3...
423                                 validScores[rScores[f][i]] = rScores[f][i];
424                                 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
425                                 if (it != rScoreFreq[f].end()) {
426                                         rScoreFreq[f][rScores[f][i]]++;
427                                 }else{
428                                         rScoreFreq[f][rScores[f][i]] = 1;
429                                 }
430                         }
431                 }
432                 
433                 //calculate rcumul
434                 for(int a = 0; a < numComp; a++) {
435                         float rcumul = 1.0000;
436                         //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
437                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
438                                 //make rscoreFreq map and rCumul
439                                 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
440                                 rCumul[a][it->first] = rcumul;
441                                 //get percentage of random trees with that info
442                                 if (it2 != rScoreFreq[a].end()) {  rScoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
443                                 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
444                         }
445                 }
446
447         }
448         catch(exception& e) {
449                 m->errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
450                 exit(1);
451         }
452 }
453
454 /***********************************************************/
455
456
457
458
459