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