]> git.donarmstrong.com Git - mothur.git/blob - parsimonycommand.cpp
86f8d013c59449b96009ba07859be7e0985cc141
[mothur.git] / parsimonycommand.cpp
1 /*
2  *  parsimonycommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 1/26/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "parsimonycommand.h"
11
12 /***********************************************************/
13 ParsimonyCommand::ParsimonyCommand() {
14         try {
15                 globaldata = GlobalData::getInstance();
16                 
17                 //randomtree will tell us if user had their own treefile or if they just want the random distribution
18                 randomtree = globaldata->getRandomTree();
19                 
20                 //user has entered their own tree
21                 if (randomtree == "") { 
22                         T = globaldata->gTree;
23                         tmap = globaldata->gTreemap;
24                         parsFile = globaldata->getTreeFile() + ".parsimony";
25                         parsFileout = globaldata->getTreeFile() + "temp" + ".parsimony";
26                         sumFile = globaldata->getTreeFile() + ".psummary";
27                         openOutputFile(sumFile, outSum);
28                 }else { //user wants random distribution
29                         savetmap = globaldata->gTreemap;
30                         getUserInput();
31                         parsFile = randomtree;
32                         parsFileout = globaldata->getTreeFile() + "temp";
33                 }
34                 
35                 //set users groups to analyze
36                 setGroups();
37                 convert(globaldata->getIters(), iters);  //how many random trees to generate
38                 pars = new Parsimony(tmap);
39                 counter = 0;
40
41         }
42         catch(exception& e) {
43                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function ParsimonyCommand. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
44                 exit(1);
45         }
46         catch(...) {
47                 cout << "An unknown error has occurred in the ParsimonyCommand class function ParsimonyCommand. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
48                 exit(1);
49         }
50 }
51 /***********************************************************/
52 int ParsimonyCommand::execute() {
53         try {
54                 Progress* reading;
55                 reading = new Progress("Comparing to random:", iters);
56                 
57                 //get pscore for users tree
58                 userData.resize(numComp,0);  //data = AB, AC, BC, ABC.
59                 randomData.resize(numComp,0);  //data = AB, AC, BC, ABC.
60                 rscoreFreq.resize(numComp);  
61                 uscoreFreq.resize(numComp);  
62                 rCumul.resize(numComp);  
63                 uCumul.resize(numComp);  
64                 userTreeScores.resize(numComp);  
65                 UScoreSig.resize(numComp); 
66                                 
67                 if (randomtree == "") {
68                         //get pscores for users trees
69                         for (int i = 0; i < T.size(); i++) {
70                                 userData = pars->getValues(T[i]);  //data = AB, AC, BC, ABC.
71
72                                 //output scores for each combination
73                                 for(int k = 0; k < numComp; k++) {
74
75                                         //update uscoreFreq
76                                         it = uscoreFreq[k].find(userData[k]);
77                                         if (it == uscoreFreq[k].end()) {//new score
78                                                 uscoreFreq[k][userData[k]] = 1;
79                                         }else{ uscoreFreq[k][userData[k]]++; }
80                                         
81                                         //add users score to valid scores
82                                         validScores[userData[k]] = userData[k];
83                                         
84                                         //save score for summary file
85                                         userTreeScores[k].push_back(userData[k]);
86                                 }
87                         }
88                         
89                         //get pscores for random trees
90                         for (int j = 0; j < iters; j++) {
91                                 //create new tree with same num nodes and leaves as users
92                                 randT = new Tree();
93
94                                 //create random relationships between nodes
95                                 randT->assembleRandomTree();
96
97                                 //get pscore of random tree
98                                 randomData = pars->getValues(randT);
99                                         
100                                 for(int r = 0; r < numComp; r++) {
101                                         //add trees pscore to map of scores
102                                         it2 = rscoreFreq[r].find(randomData[r]);
103                                         if (it2 != rscoreFreq[r].end()) {//already have that score
104                                                 rscoreFreq[r][randomData[r]]++;
105                                         }else{//first time we have seen this score
106                                                 rscoreFreq[r][randomData[r]] = 1;
107                                         }
108                         
109                                         //add randoms score to validscores
110                                         validScores[randomData[r]] = randomData[r];
111                                 }
112                                 
113                                 //update progress bar
114                                 reading->update(j);
115                                 
116                                 delete randT;
117                         }
118
119                 }else {
120                         //get pscores for random trees
121                         for (int j = 0; j < iters; j++) {
122                                 //create new tree with same num nodes and leaves as users
123                                 randT = new Tree();
124                                 //create random relationships between nodes
125
126                                 randT->assembleRandomTree();
127
128                                 //get pscore of random tree
129                                 randomData = pars->getValues(randT);
130                         
131                                 for(int r = 0; r < numComp; r++) {
132                                         //add trees pscore to map of scores
133                                         it2 = rscoreFreq[r].find(randomData[r]);
134                                         if (it2 != rscoreFreq[r].end()) {//already have that score
135                                                 rscoreFreq[r][randomData[r]]++;
136                                         }else{//first time we have seen this score
137                                                 rscoreFreq[r][randomData[r]] = 1;
138                                         }
139                         
140                                         //add randoms score to validscores
141                                         validScores[randomData[r]] = randomData[r];
142                                 }
143                                 
144                                 //update progress bar
145                                 reading->update(j);
146                                 
147                                 delete randT;
148                         }
149                 }
150
151                 for(int a = 0; a < numComp; a++) {
152                         float rcumul = 0.0000;
153                         float ucumul = 0.0000;
154                         //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
155                         for (it = validScores.begin(); it != validScores.end(); it++) { 
156                                 if (randomtree == "") {
157                                         it2 = uscoreFreq[a].find(it->first);
158                                         //user data has that score 
159                                         if (it2 != uscoreFreq[a].end()) { uscoreFreq[a][it->first] /= T.size(); ucumul+= it2->second;  }
160                                         else { uscoreFreq[a][it->first] = 0.0000; } //no user trees with that score
161                                         //make uCumul map
162                                         uCumul[a][it->first] = ucumul;
163                                 }
164                         
165                                 //make rscoreFreq map and rCumul
166                                 it2 = rscoreFreq[a].find(it->first);
167                                 //get percentage of random trees with that info
168                                 if (it2 != rscoreFreq[a].end()) {  rscoreFreq[a][it->first] /= iters; rcumul+= it2->second;  }
169                                 else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
170                                 rCumul[a][it->first] = rcumul;
171                         }
172                         
173                         //find the signifigance of each user trees score when compared to the random trees and save for printing the summary file
174                         for (int h = 0; h < userTreeScores[a].size(); h++) {
175                                 UScoreSig[a].push_back(rCumul[a][userTreeScores[a][h]]);
176                         }
177                 }
178                 
179                 //finish progress bar
180                 reading->finish();
181                 delete reading;
182
183                 
184                 printParsimonyFile();
185                 if (randomtree == "") { printUSummaryFile(); }
186                 
187                 //reset globaldata's treemap if you just did random distrib
188                 if (randomtree != "") {
189                         //memory leak prevention
190                         //if (globaldata->gTreemap != NULL) { delete globaldata->gTreemap;  }
191                         globaldata->gTreemap = savetmap;
192                 }
193                 
194                 //reset randomTree parameter to ""
195                 globaldata->setRandomTree("");
196                 //reset groups parameter
197                 globaldata->Groups.clear();  globaldata->setGroups("");
198                 
199                 return 0;
200                 
201         }
202         catch(exception& e) {
203                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function execute. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
204                 exit(1);
205         }
206         catch(...) {
207                 cout << "An unknown error has occurred in the ParsimonyCommand class function execute. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
208                 exit(1);
209         }
210 }
211
212 /***********************************************************/
213 void ParsimonyCommand::printParsimonyFile() {
214         try {
215                 vector<double> data;
216                 
217                 //format output
218                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
219
220                 for(int a = 0; a < numComp; a++) {
221                         initFile(groupComb[a]);
222                         //print each line
223                         for (it = validScores.begin(); it != validScores.end(); it++) { 
224                                 if (randomtree == "") {
225                                         data.push_back(it->first);  data.push_back(uscoreFreq[a][it->first]); data.push_back(uCumul[a][it->first]); data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]); 
226                                 }else{
227                                         data.push_back(it->first);  data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]); 
228                                 }
229                                 output(data);
230                                 data.clear();
231                         } 
232                         resetFile();
233                 }
234                 
235                 out.close();
236                 inFile.close();
237                 remove(parsFileout.c_str());
238         }
239         catch(exception& e) {
240                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function printParsimonyFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
241                 exit(1);
242         }
243         catch(...) {
244                 cout << "An unknown error has occurred in the ParsimonyCommand class function printParsimonyFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
245                 exit(1);
246         }
247 }
248 /***********************************************************/
249 void ParsimonyCommand::printUSummaryFile() {
250         try {
251                 //column headers
252                 outSum << "Tree#" << '\t' << "Groups" << '\t'  <<  "ParsScore" << '\t' << "ParsSig" <<  endl;
253                 cout << "Tree#" << '\t' << "Groups" << '\t'  <<  "ParsScore" << '\t' << "ParsSig" <<  endl;
254                 
255                 //format output
256                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
257                 
258                 
259                 //print each line
260                 for (int i = 0; i< T.size(); i++) {
261                         for(int a = 0; a < numComp; a++) {
262                                 if (UScoreSig[a][i] > (1/(float)iters)) {
263                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[a]  << '\t' << userTreeScores[a][i] << setprecision(globaldata->getIters().length()) << '\t' << UScoreSig[a][i] << endl;
264                                         cout << setprecision(6) << i+1 << '\t' << groupComb[a]  << '\t' << userTreeScores[a][i] << setprecision(globaldata->getIters().length()) << '\t' << UScoreSig[a][i] << endl;
265                                 }else {
266                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(globaldata->getIters().length())  << '\t' << "<" << (1/float(iters)) << endl;
267                                         cout << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(globaldata->getIters().length()) << '\t' << "<" << (1/float(iters)) << endl;
268                                 }
269                         }
270                 }
271                 
272                 outSum.close();
273         }
274         catch(exception& e) {
275                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function printUSummaryFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
276                 exit(1);
277         }
278         catch(...) {
279                 cout << "An unknown error has occurred in the ParsimonyCommand class function printUSummaryFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
280                 exit(1);
281         }
282 }
283
284 /***********************************************************/
285 void ParsimonyCommand::getUserInput() {
286         try {
287         
288                 //create treemap
289                 tmap = new TreeMap();
290
291                 cout << "Please enter the number of groups you would like to analyze: ";
292                 cin >> numGroups;
293                         
294                 int num, count;
295                 count = 1;
296                 numEachGroup.resize(numGroups, 0);  
297                 
298                 for (int i = 1; i <= numGroups; i++) {
299                         cout << "Please enter the number of sequences in group " << i <<  ": ";
300                         cin >> num;
301                                 
302                         //set tmaps seqsPerGroup
303                         tmap->seqsPerGroup[toString(i)] = num;
304                         tmap->namesOfGroups.push_back(toString(i));
305                         
306                         //set tmaps namesOfSeqs
307                         for (int j = 0; j < num; j++) {
308                                 tmap->namesOfSeqs.push_back(toString(count));
309                                 tmap->treemap[toString(count)].groupname = toString(i);
310                                 count++;
311                         }
312                 }
313                 
314                 //clears buffer so next command doesn't have error
315                 string s;       
316                 getline(cin, s);
317                 
318                 //save tmap for later
319                 //memory leak prevention
320                 //if (globaldata->gTreemap != NULL) { delete globaldata->gTreemap;  }
321                 globaldata->gTreemap = tmap;
322                 
323         }
324         catch(exception& e) {
325                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function getUserInput. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
326                 exit(1);
327         }
328         catch(...) {
329                 cout << "An unknown error has occurred in the ParsimonyCommand class function getUserInput. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
330                 exit(1);
331         }
332 }
333 /***********************************************************/
334
335 void ParsimonyCommand::setGroups() {
336         try {
337                 string allGroups = "";
338                 numGroups = 0;
339                 //if the user has not entered specific groups to analyze then do them all
340                 if (globaldata->Groups.size() != 0) {
341                         if (globaldata->Groups[0] != "all") {
342                                 //check that groups are valid
343                                 for (int i = 0; i < globaldata->Groups.size(); i++) {
344                                         if (tmap->isValidGroup(globaldata->Groups[i]) != true) {
345                                                 cout << globaldata->Groups[i] << " is not a valid group, and will be disregarded." << endl;
346                                                 // erase the invalid group from globaldata->Groups
347                                                 globaldata->Groups.erase(globaldata->Groups.begin()+i);
348                                         }
349                                 }
350                         
351                                 //if the user only entered invalid groups
352                                 if (globaldata->Groups.size() == 0) { 
353                                         cout << "When using the groups parameter you must have at least 1 valid group. I will run the command using all the groups in your groupfile." << endl; 
354                                         for (int i = 0; i < tmap->namesOfGroups.size(); i++) {
355                                                 if (tmap->namesOfGroups[i] != "xxx") {
356                                                         allGroups += tmap->namesOfGroups[i] + "-";
357                                                         globaldata->Groups.push_back(tmap->namesOfGroups[i]);
358                                                         numGroups++;
359                                                 }
360                                         }
361                                         allGroups = allGroups.substr(0, allGroups.length()-1);
362                                 }else {
363                                         for (int i = 0; i < globaldata->Groups.size(); i++) {
364                                                 allGroups += globaldata->Groups[i] + "-";
365                                                 numGroups++;
366                                         }
367                                         allGroups = allGroups.substr(0, allGroups.length()-1);
368                                 }
369                         }else{//user has enter "all" and wants the default groups
370                                 globaldata->Groups.clear();
371                                 for (int i = 0; i < tmap->namesOfGroups.size(); i++) {
372                                         if (tmap->namesOfGroups[i] != "xxx") {
373                                                 globaldata->Groups.push_back(tmap->namesOfGroups[i]);
374                                                 numGroups++;
375                                                 allGroups += tmap->namesOfGroups[i] + "-";
376                                         }
377                                 }
378                                 allGroups = allGroups.substr(0, allGroups.length()-1);
379                                 globaldata->setGroups("");
380                         }
381                 }else {
382                         for (int i = 0; i < tmap->namesOfGroups.size(); i++) {
383                                 if (tmap->namesOfGroups[i] != "xxx") {
384                                         allGroups += tmap->namesOfGroups[i] + "-";
385                                 }
386                         }
387                         allGroups = allGroups.substr(0, allGroups.length()-1);
388                         numGroups = 1;
389                 }
390                 
391                 //calculate number of comparsions
392                 numComp = 0;
393                 for (int r=0; r<numGroups; r++) { 
394                         for (int l = r+1; l < numGroups; l++) {
395                                 groupComb.push_back(globaldata->Groups[r]+ "-" +globaldata->Groups[l]);
396                                 numComp++;
397                         }
398                 }
399                 
400                 //ABC
401                 if (numComp != 1) {
402                         groupComb.push_back(allGroups);
403                         numComp++;
404                 }
405                 
406         }
407         catch(exception& e) {
408                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function setGroups. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
409                 exit(1);
410         }
411         catch(...) {
412                 cout << "An unknown error has occurred in the ParsimonyCommand class function setGroups. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
413                 exit(1);
414         }               
415
416 }
417 /*****************************************************************/
418
419 void ParsimonyCommand::initFile(string label){
420         try {
421                 if(counter != 0){
422                         openOutputFile(parsFileout, out);
423                         openInputFile(parsFile, inFile);
424
425                         string inputBuffer;
426                         getline(inFile, inputBuffer);
427                         
428                         if (randomtree == "") {
429                                 out <<  inputBuffer << '\t' << label + "Score" << '\t' << label + "UserFreq" << '\t' << label + "UserCumul" << '\t' << label + "RandFreq" << '\t' << label + "RandCumul" << endl;
430                         }else {
431                                 out <<  inputBuffer << '\t' << "Score" << '\t' << "RandFreq" << '\t' << "RandCumul" << endl;
432                         }
433                 }else{
434                         openOutputFile(parsFileout, out);
435                         //column headers
436                         if (randomtree == "") {
437                                 out << label + "Score" << '\t' << label + "UserFreq" << '\t' << label + "UserCumul" << '\t' << label + "RandFreq" << '\t' << label + "RandCumul" << endl;
438                         }else {
439                                 out << "Score" << '\t' << "RandFreq" << '\t' << "RandCumul" << endl;
440                         }
441                 }
442
443                 out.setf(ios::fixed, ios::floatfield);
444                 out.setf(ios::showpoint);
445         }
446         catch(exception& e) {
447                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function initFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
448                 exit(1);
449         }
450         catch(...) {
451                 cout << "An unknown error has occurred in the ParsimonyCommand class function initFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
452                 exit(1);
453         }
454 }
455
456 /***********************************************************************/
457
458 void ParsimonyCommand::output(vector<double> data){
459         try {
460                 if(counter != 0){               
461                         string inputBuffer;
462                         getline(inFile, inputBuffer);
463                 
464                         if (randomtree == "") {
465                                 out << inputBuffer << '\t' << setprecision(6) << data[0] << setprecision(globaldata->getIters().length())  << '\t' << data[1] << '\t' << data[2] << '\t' << data[3] << '\t' << data[4] << endl;
466                         }else{
467                                 out << inputBuffer << '\t' << setprecision(6) << data[0] << setprecision(globaldata->getIters().length())  << '\t' << data[1] << '\t' << data[2] << endl;
468                         }
469                 }
470                 else{
471                         if (randomtree == "") {
472                                 out << setprecision(6) << data[0] << setprecision(globaldata->getIters().length())  << '\t' << data[1] << '\t' << data[2] << '\t' << data[3] << '\t' << data[4] << endl;
473                         }else{
474                                 out << setprecision(6) << data[0] << setprecision(globaldata->getIters().length())  << '\t' << data[1] << '\t' << data[2] << endl;
475                         }
476                 }
477
478         }
479         catch(exception& e) {
480                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function output. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
481                 exit(1);
482         }
483         catch(...) {
484                 cout << "An unknown error has occurred in the ParsimonyCommand class function output. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
485                 exit(1);
486         }
487 }
488
489 /***********************************************************************/
490
491 void ParsimonyCommand::resetFile(){
492         try {
493                 if(counter != 0){
494                         out.close();
495                         inFile.close();
496                 }
497                 else{
498                         out.close();
499                 }
500                 counter = 1;
501                 
502                 remove(parsFile.c_str());
503                 rename(parsFileout.c_str(), parsFile.c_str());
504         }
505         catch(exception& e) {
506                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function resetFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
507                 exit(1);
508         }
509         catch(...) {
510                 cout << "An unknown error has occurred in the ParsimonyCommand class function resetFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
511                 exit(1);
512         }       
513 }
514
515