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