]> git.donarmstrong.com Git - mothur.git/blob - unifracweightedcommand.cpp
fixed bug in read.tree
[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() {
14         try {
15                 globaldata = GlobalData::getInstance();
16                 
17                 T = globaldata->gTree;
18                 tmap = globaldata->gTreemap;
19                 sumFile = globaldata->getTreeFile() + ".wsummary";
20                 openOutputFile(sumFile, outSum);
21                                 
22                 setGroups();    //sets the groups the user wants to analyze                     
23                 convert(globaldata->getIters(), iters);  //how many random trees to generate
24                 weighted = new Weighted(tmap);
25
26         }
27         catch(exception& e) {
28                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function UnifracWeightedCommand. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
29                 exit(1);
30         }
31         catch(...) {
32                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function UnifracWeightedCommand. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
33                 exit(1);
34         }
35 }
36 /***********************************************************/
37 int UnifracWeightedCommand::execute() {
38         try {
39                 
40                 //get weighted for users tree
41                 userData.resize(numComp,0);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
42                 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
43                                 
44                 //create new tree with same num nodes and leaves as users
45                 randT = new Tree();
46                 
47                 //get weighted scores for users trees
48                 for (int i = 0; i < T.size(); i++) {
49                         counter = 0;
50                         rScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
51                         uScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
52                         weightedFile = globaldata->getTreeFile()  + toString(i+1) + ".weighted";
53                         weightedFileout = globaldata->getTreeFile() + "temp." + toString(i+1) + ".weighted";
54
55                         userData = weighted->getValues(T[i]);  //userData[0] = weightedscore
56                         
57                         //save users score
58                         for (int s=0; s<numComp; s++) {
59                                 //add users score to vector of user scores
60                                 uScores[s].push_back(userData[s]);
61                                 
62                                 //save users tree score for summary file
63                                 utreeScores.push_back(userData[s]);
64                         }
65                         
66                         //get scores for random trees
67                         for (int j = 0; j < iters; j++) {
68                                 int count = 0;
69                                 for (int r=0; r<numGroups; r++) { 
70                                         for (int l = r+1; l < numGroups; l++) {
71                                                 //copy T[i]'s info.
72                                                 randT->getCopy(T[i]);
73                                                  
74                                                 //create a random tree with same topology as T[i], but different labels
75                                                 randT->assembleRandomUnifracTree(globaldata->Groups[r], globaldata->Groups[l]);
76                                                 //get wscore of random tree
77                                                 randomData = weighted->getValues(randT, globaldata->Groups[r], globaldata->Groups[l]);
78                                                 
79                                                 //save scores
80                                                 rScores[count].push_back(randomData[0]);
81                                                 count++;
82                                         }
83                                 }
84                         }
85
86                         //removeValidScoresDuplicates(); 
87                         //find the signifigance of the score for summary file
88                         for (int f = 0; f < numComp; f++) {
89                                 //sort random scores
90                                 sort(rScores[f].begin(), rScores[f].end());
91                                 
92                                 //the index of the score higher than yours is returned 
93                                 //so if you have 1000 random trees the index returned is 100 
94                                 //then there are 900 trees with a score greater then you. 
95                                 //giving you a signifigance of 0.900
96                                 int index = findIndex(userData[f], f);    if (index == -1) { cout << "error in UnifracWeightedCommand" << endl; exit(1); } //error code
97                         
98                                 //the signifigance is the number of trees with the users score or higher 
99                                 WScoreSig.push_back((iters-index)/(float)iters);
100                         }
101                         
102                         //out << "Tree# " << i << endl;
103                         calculateFreqsCumuls();
104                         printWeightedFile();
105                         
106                         //clear data
107                         rScores.clear();
108                         uScores.clear();
109                         validScores.clear();
110                 }
111                 
112                 printWSummaryFile();
113                 
114                 //clear out users groups
115                 globaldata->Groups.clear();
116                 
117                 delete randT;
118                 
119                 return 0;
120                 
121         }
122         catch(exception& e) {
123                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function execute. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
124                 exit(1);
125         }
126         catch(...) {
127                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function execute. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
128                 exit(1);
129         }
130 }
131 /***********************************************************/
132 void UnifracWeightedCommand::printWeightedFile() {
133         try {
134                 vector<double> data;
135                 
136                 for(int a = 0; a < numComp; a++) {
137                         initFile(groupComb[a]);
138                         //print each line
139                         for (it = validScores.begin(); it != validScores.end(); it++) { 
140                                 data.push_back(it->first);  data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]); 
141                                 output(data);
142                                 data.clear();
143                         } 
144                         resetFile();
145                 }
146                 
147                 out.close();
148                 inFile.close();
149                 remove(weightedFileout.c_str());
150                 
151         }
152         catch(exception& e) {
153                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function printWeightedFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
154                 exit(1);
155         }
156         catch(...) {
157                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function printWeightedFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
158                 exit(1);
159         }
160 }
161
162
163 /***********************************************************/
164 void UnifracWeightedCommand::printWSummaryFile() {
165         try {
166                 //column headers
167                 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" <<  endl;
168                 cout << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" <<  endl;
169                 
170                 //format output
171                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
172                 
173                 //print each line
174                 int count = 0;
175                 for (int i = 0; i < T.size(); i++) { 
176                         for (int j = 0; j < numComp; j++) {
177                                 if (WScoreSig[count] > (1/(float)iters)) {
178                                         outSum << setprecision(6) << i+1 << '\t' << '\t' << groupComb[j] << '\t' << '\t'  << utreeScores[count] << '\t' << setprecision(globaldata->getIters().length()) << WScoreSig[count] << endl; 
179                                         cout << setprecision(6) << i+1 << '\t' << '\t' << groupComb[j] << '\t' << '\t'  << utreeScores[count] << '\t' << setprecision(globaldata->getIters().length()) << WScoreSig[count] << endl; 
180                                 }else{
181                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(globaldata->getIters().length()) << "<" << (1/float(iters)) << endl; 
182                                         cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(globaldata->getIters().length()) << "<" << (1/float(iters)) << endl; 
183                                 }
184                                 count++;
185                         }
186                 }
187                 outSum.close();
188         }
189         catch(exception& e) {
190                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function printWeightedFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
191                 exit(1);
192         }
193         catch(...) {
194                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function printWeightedFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
195                 exit(1);
196         }
197 }
198
199 /***********************************************************/
200 int UnifracWeightedCommand::findIndex(float score, int index) {
201         try{
202                 for (int i = 0; i < rScores[index].size(); i++) {
203                         if (rScores[index][i] >= score) {       return i;       }
204                 }
205                 return rScores[index].size();
206         }
207         catch(exception& e) {
208                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function findIndex. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
209                 exit(1);
210         }
211         catch(...) {
212                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function findIndex. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
213                 exit(1);
214         }
215 }
216
217 /***********************************************************/
218 void UnifracWeightedCommand::setGroups() {
219         try {
220                 //if the user has not entered specific groups to analyze then do them all
221                 if (globaldata->Groups.size() == 0) {
222                         numGroups = tmap->getNumGroups();
223                         for (int i=0; i < numGroups; i++) { 
224                                 globaldata->Groups.push_back(tmap->namesOfGroups[i]);
225                         }
226                 }else {
227                         if (globaldata->getGroups() != "all") {
228                                 //check that groups are valid
229                                 for (int i = 0; i < globaldata->Groups.size(); i++) {
230                                         if (tmap->isValidGroup(globaldata->Groups[i]) != true) {
231                                                 cout << globaldata->Groups[i] << " is not a valid group, and will be disregarded." << endl;
232                                                 // erase the invalid group from globaldata->Groups
233                                                 globaldata->Groups.erase (globaldata->Groups.begin()+i);
234                                         }
235                                 }
236                         
237                                 //if the user only entered invalid groups
238                                 if (globaldata->Groups.size() == 0) { 
239                                         numGroups = tmap->getNumGroups();
240                                         for (int i=0; i < numGroups; i++) { 
241                                                 globaldata->Groups.push_back(tmap->namesOfGroups[i]);
242                                         }
243                                         cout << "When using the groups parameter you must have at least 2 valid groups. I will run the command using all the groups in your groupfile." << endl; 
244                                 }else if (globaldata->Groups.size() == 1) { 
245                                         cout << "When using the groups parameter you must have at least 2 valid groups. I will run the command using all the groups in your groupfile." << endl;
246                                         numGroups = tmap->getNumGroups();
247                                         globaldata->Groups.clear();
248                                         for (int i=0; i < numGroups; i++) { 
249                                                 globaldata->Groups.push_back(tmap->namesOfGroups[i]);
250                                         }
251                                 }else { numGroups = globaldata->Groups.size(); }
252                         }else { //users wants all groups
253                                 numGroups = tmap->getNumGroups();
254                                 globaldata->Groups.clear();
255                                 globaldata->setGroups("");
256                                 for (int i=0; i < numGroups; i++) { 
257                                         globaldata->Groups.push_back(tmap->namesOfGroups[i]);
258                                 }
259                         }
260                 }
261                 
262                 //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
263                 numComp = 0;
264                 for (int i=0; i<numGroups; i++) { 
265                         numComp += i; 
266                         for (int l = i+1; l < numGroups; l++) {
267                                 //set group comparison labels
268                                 groupComb.push_back(globaldata->Groups[i] + "-" + globaldata->Groups[l]);
269                         }
270                 }
271         }
272         catch(exception& e) {
273                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function setGroups. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
274                 exit(1);
275         }
276         catch(...) {
277                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function setGroups. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
278                 exit(1);
279         }
280 }
281
282 /***********************************************************/
283
284 void UnifracWeightedCommand::calculateFreqsCumuls() {
285         try {
286                 //clear out old tree values
287                 rScoreFreq.clear();
288                 rScoreFreq.resize(numComp);
289                 rCumul.clear();
290                 rCumul.resize(numComp);
291                 validScores.clear();
292         
293                 //calculate frequency
294                 for (int f = 0; f < numComp; f++) {
295                         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...
296                                 validScores[rScores[f][i]] = rScores[f][i];
297                                 it = rScoreFreq[f].find(rScores[f][i]);
298                                 if (it != rScoreFreq[f].end()) {
299                                         rScoreFreq[f][rScores[f][i]]++;
300                                 }else{
301                                         rScoreFreq[f][rScores[f][i]] = 1;
302                                 }
303                         }
304                 }
305                 
306                 //calculate rcumul
307                 for(int a = 0; a < numComp; a++) {
308                         float rcumul = 1.0000;
309                         //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
310                         for (it = validScores.begin(); it != validScores.end(); it++) {
311                                 //make rscoreFreq map and rCumul
312                                 it2 = rScoreFreq[a].find(it->first);
313                                 rCumul[a][it->first] = rcumul;
314                                 //get percentage of random trees with that info
315                                 if (it2 != rScoreFreq[a].end()) {  rScoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
316                                 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
317                         }
318                 }
319
320         }
321         catch(exception& e) {
322                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function calculateFreqsCums. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
323                 exit(1);
324         }
325         catch(...) {
326                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function calculateFreqsCums. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
327                 exit(1);
328         }
329
330 }
331
332 /*****************************************************************/
333
334 void UnifracWeightedCommand::initFile(string label){
335         try {
336                 if(counter != 0){
337                         openOutputFile(weightedFileout, out);
338                         openInputFile(weightedFile, inFile);
339
340                         string inputBuffer;
341                         getline(inFile, inputBuffer);
342                 
343                         out     <<  inputBuffer << '\t' << label + "RandFreq" << '\t' << label + "RandCumul" << endl;           
344                 }else{
345                         openOutputFile(weightedFileout, out);
346                         out     << label + "Score" << '\t' << label + "RandFreq" << '\t' << label + "RandCumul" << endl;
347                 }
348
349                 out.setf(ios::fixed, ios::floatfield);
350                 out.setf(ios::showpoint);
351         }
352         catch(exception& e) {
353                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function initFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
354                 exit(1);
355         }
356         catch(...) {
357                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function initFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
358                 exit(1);
359         }
360 }
361
362 /***********************************************************************/
363
364 void UnifracWeightedCommand::output(vector<double> data){
365         try {
366                 if(counter != 0){               
367                         string inputBuffer;
368                         getline(inFile, inputBuffer);
369
370                         out << inputBuffer << '\t' << setprecision(6) << data[0] << setprecision(globaldata->getIters().length())  << '\t' << data[1] << '\t' << data[2] << endl;
371                 }
372                 else{
373                         out << setprecision(6) << data[0] << setprecision(globaldata->getIters().length())  << '\t' << data[1] << '\t' << data[2] << endl;
374
375                 }
376                 
377         }
378         catch(exception& e) {
379                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function output. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
380                 exit(1);
381         }
382         catch(...) {
383                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function output. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
384                 exit(1);
385         }
386 };
387
388 /***********************************************************************/
389
390 void UnifracWeightedCommand::resetFile(){
391         try {
392                 if(counter != 0){
393                         out.close();
394                         inFile.close();
395                 }
396                 else{
397                         out.close();
398                 }
399                 counter = 1;
400                 
401                 remove(weightedFile.c_str());
402                 rename(weightedFileout.c_str(), weightedFile.c_str());
403         }
404         catch(exception& e) {
405                 cout << "Standard Error: " << e.what() << " has occurred in the UnifracWeightedCommand class Function resetFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
406                 exit(1);
407         }
408         catch(...) {
409                 cout << "An unknown error has occurred in the UnifracWeightedCommand class function resetFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
410                 exit(1);
411         }       
412 }
413