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