]> git.donarmstrong.com Git - mothur.git/blob - unifracweightedcommand.cpp
added logfile feature
[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"};
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                                 mothurOut("You must execute the read.tree command, before you may execute the unifrac.weighted command."); mothurOutEndLine(); abort = true;  }
39                                                                                 
40                         //check for optional parameter and set defaults
41                         // ...at some point should added some additional type checking...
42                         groups = validParameter.validFile(parameters, "groups", false);                 
43                         if (groups == "not found") { groups = ""; }
44                         else { 
45                                 splitAtDash(groups, Groups);
46                                 globaldata->Groups = Groups;
47                         }
48                                 
49                         itersString = validParameter.validFile(parameters, "iters", false);                     if (itersString == "not found") { itersString = "1000"; }
50                         convert(itersString, iters); 
51                 
52                         
53                         if (abort == false) {
54                                 T = globaldata->gTree;
55                                 tmap = globaldata->gTreemap;
56                                 sumFile = globaldata->getTreeFile() + ".wsummary";
57                                 openOutputFile(sumFile, outSum);
58                                 
59                                 util = new SharedUtil();
60                                 string s; //to make work with setgroups
61                                 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted");     //sets the groups the user wants to analyze
62                                 util->getCombos(groupComb, globaldata->Groups, numComp);
63                                 
64                                 weighted = new Weighted(tmap);
65                                 
66                         }
67                 }
68                 
69                 
70         }
71         catch(exception& e) {
72                 errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
73                 exit(1);
74         }
75 }
76 //**********************************************************************************************************************
77
78 void UnifracWeightedCommand::help(){
79         try {
80                 mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
81                 mothurOut("The unifrac.weighted command parameters are groups and iters.  No parameters are required.\n");
82                 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");
83                 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");
84                 mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
85                 mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
86                 mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
87                 mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
88                 mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
89         }
90         catch(exception& e) {
91                 errorOut(e, "UnifracWeightedCommand", "help");
92                 exit(1);
93         }
94 }
95
96 /***********************************************************/
97 int UnifracWeightedCommand::execute() {
98         try {
99         
100                 if (abort == true) { return 0; }
101                 
102                 Progress* reading;
103                 reading = new Progress("Comparing to random:", iters);
104                 
105                 //get weighted for users tree
106                 userData.resize(numComp,0);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
107                 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
108                                 
109                 //create new tree with same num nodes and leaves as users
110                 randT = new Tree();
111                 
112                 //get weighted scores for users trees
113                 for (int i = 0; i < T.size(); i++) {
114                         counter = 0;
115                         rScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
116                         uScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
117                         
118                         output = new ColumnFile(globaldata->getTreeFile()  + toString(i+1) + ".weighted", itersString);
119
120                         userData = weighted->getValues(T[i]);  //userData[0] = weightedscore
121                         
122                         //save users score
123                         for (int s=0; s<numComp; s++) {
124                                 //add users score to vector of user scores
125                                 uScores[s].push_back(userData[s]);
126                                 
127                                 //save users tree score for summary file
128                                 utreeScores.push_back(userData[s]);
129                         }
130                         
131                         //get scores for random trees
132                         for (int j = 0; j < iters; j++) {
133                                 int count = 0;
134                                 for (int r=0; r<numGroups; r++) { 
135                                         for (int l = r+1; l < numGroups; l++) {
136                                                 //copy T[i]'s info.
137                                                 randT->getCopy(T[i]);
138                                                  
139                                                 //create a random tree with same topology as T[i], but different labels
140                                                 randT->assembleRandomUnifracTree(globaldata->Groups[r], globaldata->Groups[l]);
141                                                 //get wscore of random tree
142                                                 randomData = weighted->getValues(randT, globaldata->Groups[r], globaldata->Groups[l]);
143                                                 
144                                                 //save scores
145                                                 rScores[count].push_back(randomData[0]);
146                                                 count++;
147                                         }
148                                 }
149                                 
150                                 //update progress bar
151                                 reading->update(j);
152
153                         }
154
155                         //removeValidScoresDuplicates(); 
156                         //find the signifigance of the score for summary file
157                         for (int f = 0; f < numComp; f++) {
158                                 //sort random scores
159                                 sort(rScores[f].begin(), rScores[f].end());
160                                 
161                                 //the index of the score higher than yours is returned 
162                                 //so if you have 1000 random trees the index returned is 100 
163                                 //then there are 900 trees with a score greater then you. 
164                                 //giving you a signifigance of 0.900
165                                 int index = findIndex(userData[f], f);    if (index == -1) { mothurOut("error in UnifracWeightedCommand"); mothurOutEndLine(); exit(1); } //error code
166                         
167                                 //the signifigance is the number of trees with the users score or higher 
168                                 WScoreSig.push_back((iters-index)/(float)iters);
169                         }
170                         
171                         //out << "Tree# " << i << endl;
172                         calculateFreqsCumuls();
173                         printWeightedFile();
174                         
175                         delete output;
176                         
177                         //clear data
178                         rScores.clear();
179                         uScores.clear();
180                         validScores.clear();
181                 }
182                 
183                 //finish progress bar
184                 reading->finish();
185                 delete reading;
186                 
187                 printWSummaryFile();
188                 
189                 //clear out users groups
190                 globaldata->Groups.clear();
191                 
192                 delete randT;
193                 
194                 return 0;
195                 
196         }
197         catch(exception& e) {
198                 errorOut(e, "UnifracWeightedCommand", "execute");
199                 exit(1);
200         }
201 }
202 /***********************************************************/
203 void UnifracWeightedCommand::printWeightedFile() {
204         try {
205                 vector<double> data;
206                 vector<string> tags;
207                 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
208                 
209                 for(int a = 0; a < numComp; a++) {
210                         output->initFile(groupComb[a], tags);
211                         //print each line
212                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
213                                 data.push_back(it->first);  data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]); 
214                                 output->output(data);
215                                 data.clear();
216                         } 
217                         output->resetFile();
218                 }
219         }
220         catch(exception& e) {
221                 errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
222                 exit(1);
223         }
224 }
225
226
227 /***********************************************************/
228 void UnifracWeightedCommand::printWSummaryFile() {
229         try {
230                 //column headers
231                 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" <<  endl;
232                 mothurOut("Tree#\tGroups\tWScore\tWSig"); mothurOutEndLine(); 
233                 
234                 //format output
235                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
236                 
237                 //print each line
238                 int count = 0;
239                 for (int i = 0; i < T.size(); i++) { 
240                         for (int j = 0; j < numComp; j++) {
241                                 if (WScoreSig[count] > (1/(float)iters)) {
242                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
243                                         cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl; 
244                                         mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" +  toString(WScoreSig[count])); mothurOutEndLine();  
245                                 }else{
246                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
247                                         cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
248                                         mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" +  toString((1/float(iters)))); mothurOutEndLine();  
249                                 }
250                                 count++;
251                         }
252                 }
253                 outSum.close();
254         }
255         catch(exception& e) {
256                 errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
257                 exit(1);
258         }
259 }
260
261 /***********************************************************/
262 int UnifracWeightedCommand::findIndex(float score, int index) {
263         try{
264                 for (int i = 0; i < rScores[index].size(); i++) {
265                         if (rScores[index][i] >= score) {       return i;       }
266                 }
267                 return rScores[index].size();
268         }
269         catch(exception& e) {
270                 errorOut(e, "UnifracWeightedCommand", "findIndex");
271                 exit(1);
272         }
273 }
274
275 /***********************************************************/
276
277 void UnifracWeightedCommand::calculateFreqsCumuls() {
278         try {
279                 //clear out old tree values
280                 rScoreFreq.clear();
281                 rScoreFreq.resize(numComp);
282                 rCumul.clear();
283                 rCumul.resize(numComp);
284                 validScores.clear();
285         
286                 //calculate frequency
287                 for (int f = 0; f < numComp; f++) {
288                         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...
289                                 validScores[rScores[f][i]] = rScores[f][i];
290                                 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
291                                 if (it != rScoreFreq[f].end()) {
292                                         rScoreFreq[f][rScores[f][i]]++;
293                                 }else{
294                                         rScoreFreq[f][rScores[f][i]] = 1;
295                                 }
296                         }
297                 }
298                 
299                 //calculate rcumul
300                 for(int a = 0; a < numComp; a++) {
301                         float rcumul = 1.0000;
302                         //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
303                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
304                                 //make rscoreFreq map and rCumul
305                                 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
306                                 rCumul[a][it->first] = rcumul;
307                                 //get percentage of random trees with that info
308                                 if (it2 != rScoreFreq[a].end()) {  rScoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
309                                 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
310                         }
311                 }
312
313         }
314         catch(exception& e) {
315                 errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
316                 exit(1);
317         }
318 }
319
320 /***********************************************************/
321
322
323
324
325