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