]> git.donarmstrong.com Git - mothur.git/blob - parsimonycommand.cpp
merged pat's trim seqs edits with sarah's major overhaul of global data; also added...
[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(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[] =  {"random","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                         randomtree = validParameter.validFile(parameters, "random", false);             if (randomtree == "not found") { randomtree = ""; }
38                         
39                         //are you trying to use parsimony without reading a tree or saying you want random distribution
40                         if (randomtree == "")  {
41                                 if (globaldata->gTree.size() == 0) {
42                                         cout << "You must read a treefile and a groupfile or set the randomtree parameter to the output filename you wish, before you may execute the parsimony command." << endl; abort = true;  }
43                         }
44                                                 
45                         //check for optional parameter and set defaults
46                         // ...at some point should added some additional type checking...
47                         groups = validParameter.validFile(parameters, "groups", false);                 
48                         if (groups == "not found") { groups = ""; }
49                         else { 
50                                 splitAtDash(groups, Groups);
51                                 globaldata->Groups = Groups;
52                         }
53                                 
54                         itersString = validParameter.validFile(parameters, "iters", false);                     if (itersString == "not found") { itersString = "1000"; }
55                         convert(itersString, iters); 
56                                                 
57                         if (abort == false) {
58                                 //randomtree will tell us if user had their own treefile or if they just want the random distribution
59                                 //user has entered their own tree
60                                 if (randomtree == "") { 
61                                         T = globaldata->gTree;
62                                         tmap = globaldata->gTreemap;
63                                         output = new ColumnFile(globaldata->getTreeFile()  +  ".parsimony", itersString);
64                                         sumFile = globaldata->getTreeFile() + ".psummary";
65                                         openOutputFile(sumFile, outSum);
66                                 }else { //user wants random distribution
67                                         savetmap = globaldata->gTreemap;
68                                         getUserInput();
69                                         output = new ColumnFile(randomtree, itersString);
70                                 }
71                                 
72                                 //set users groups to analyze
73                                 util = new SharedUtil();
74                                 util->setGroups(globaldata->Groups, tmap->namesOfGroups, allGroups, numGroups, "unweighted");   //sets the groups the user wants to analyze
75                                 util->getCombos(groupComb, globaldata->Groups, numComp);
76                                 
77                                 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
78                                 
79                                 pars = new Parsimony(tmap);
80                                 counter = 0;
81                                 
82                         }
83                         
84                 }
85
86         }
87         catch(exception& e) {
88                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function ParsimonyCommand. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
89                 exit(1);
90         }
91         catch(...) {
92                 cout << "An unknown error has occurred in the ParsimonyCommand class function ParsimonyCommand. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
93                 exit(1);
94         }
95 }
96
97 //**********************************************************************************************************************
98
99 void ParsimonyCommand::help(){
100         try {
101                 cout << "The parsimony command can only be executed after a successful read.tree command, unless you use the random parameter." << "\n";
102                 cout << "The parsimony command parameters are random, groups and iters.  No parameters are required." << "\n";
103                 cout << "The groups parameter allows you to specify which of the groups in your groupfile you would like analyzed.  You must enter at least 1 valid group." << "\n";
104                 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";
105                 cout << "The parsimony command should be in the following format: parsimony(random=yourOutputFilename, groups=yourGroups, iters=yourIters)." << "\n";
106                 cout << "Example parsimony(random=out, iters=500)." << "\n";
107                 cout << "The default value for random is "" (meaning you want to use the trees in your inputfile, randomtree=out means you just want the random distribution of trees outputted to out.rd_parsimony)," << "\n";
108                 cout << "and iters is 1000.  The parsimony command output two files: .parsimony and .psummary their descriptions are in the manual." << "\n";
109                 cout << "Note: No spaces between parameter labels (i.e. random), '=' and parameters (i.e.yourOutputFilename)." << "\n" << "\n";
110         }
111         catch(exception& e) {
112                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function help. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
113                 exit(1);
114         }
115         catch(...) {
116                 cout << "An unknown error has occurred in the ParsimonyCommand class function help. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
117                 exit(1);
118         }       
119 }
120
121
122 /***********************************************************/
123 int ParsimonyCommand::execute() {
124         try {
125         
126                 if (abort == true) { return 0; }
127         
128                 Progress* reading;
129                 reading = new Progress("Comparing to random:", iters);
130                 
131                 //get pscore for users tree
132                 userData.resize(numComp,0);  //data = AB, AC, BC, ABC.
133                 randomData.resize(numComp,0);  //data = AB, AC, BC, ABC.
134                 rscoreFreq.resize(numComp);  
135                 uscoreFreq.resize(numComp);  
136                 rCumul.resize(numComp);  
137                 uCumul.resize(numComp);  
138                 userTreeScores.resize(numComp);  
139                 UScoreSig.resize(numComp); 
140                                 
141                 if (randomtree == "") {
142                         //get pscores for users trees
143                         for (int i = 0; i < T.size(); i++) {
144                                 userData = pars->getValues(T[i]);  //data = AB, AC, BC, ABC.
145
146                                 //output scores for each combination
147                                 for(int k = 0; k < numComp; k++) {
148
149                                         //update uscoreFreq
150                                         map<int,double>::iterator it = uscoreFreq[k].find(userData[k]);
151                                         if (it == uscoreFreq[k].end()) {//new score
152                                                 uscoreFreq[k][userData[k]] = 1;
153                                         }else{ uscoreFreq[k][userData[k]]++; }
154                                         
155                                         //add users score to valid scores
156                                         validScores[userData[k]] = userData[k];
157                                         
158                                         //save score for summary file
159                                         userTreeScores[k].push_back(userData[k]);
160                                 }
161                         }
162                         
163                         //get pscores for random trees
164                         for (int j = 0; j < iters; j++) {
165                                 //create new tree with same num nodes and leaves as users
166                                 randT = new Tree();
167
168                                 //create random relationships between nodes
169                                 randT->assembleRandomTree();
170
171                                 //get pscore of random tree
172                                 randomData = pars->getValues(randT);
173                                         
174                                 for(int r = 0; r < numComp; r++) {
175                                         //add trees pscore to map of scores
176                                         map<int,double>::iterator it = rscoreFreq[r].find(randomData[r]);
177                                         if (it != rscoreFreq[r].end()) {//already have that score
178                                                 rscoreFreq[r][randomData[r]]++;
179                                         }else{//first time we have seen this score
180                                                 rscoreFreq[r][randomData[r]] = 1;
181                                         }
182                         
183                                         //add randoms score to validscores
184                                         validScores[randomData[r]] = randomData[r];
185                                 }
186                                 
187                                 //update progress bar
188                                 reading->update(j);
189                                 
190                                 delete randT;
191                         }
192
193                 }else {
194                         //get pscores for random trees
195                         for (int j = 0; j < iters; j++) {
196                                 //create new tree with same num nodes and leaves as users
197                                 randT = new Tree();
198                                 //create random relationships between nodes
199
200                                 randT->assembleRandomTree();
201
202                                 //get pscore of random tree
203                                 randomData = pars->getValues(randT);
204                         
205                                 for(int r = 0; r < numComp; r++) {
206                                         //add trees pscore to map of scores
207                                         map<int,double>::iterator it = rscoreFreq[r].find(randomData[r]);
208                                         if (it != rscoreFreq[r].end()) {//already have that score
209                                                 rscoreFreq[r][randomData[r]]++;
210                                         }else{//first time we have seen this score
211                                                 rscoreFreq[r][randomData[r]] = 1;
212                                         }
213                         
214                                         //add randoms score to validscores
215                                         validScores[randomData[r]] = randomData[r];
216                                 }
217                                 
218                                 //update progress bar
219                                 reading->update(j);
220                                 
221                                 delete randT;
222                         }
223                 }
224
225                 for(int a = 0; a < numComp; a++) {
226                         float rcumul = 0.0000;
227                         float ucumul = 0.0000;
228                         //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
229                         for (map<int,double>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
230                                 if (randomtree == "") {
231                                         map<int,double>::iterator it2 = uscoreFreq[a].find(it->first);
232                                         //user data has that score 
233                                         if (it2 != uscoreFreq[a].end()) { uscoreFreq[a][it->first] /= T.size(); ucumul+= it2->second;  }
234                                         else { uscoreFreq[a][it->first] = 0.0000; } //no user trees with that score
235                                         //make uCumul map
236                                         uCumul[a][it->first] = ucumul;
237                                 }
238                         
239                                 //make rscoreFreq map and rCumul
240                                 map<int,double>::iterator it2 = rscoreFreq[a].find(it->first);
241                                 //get percentage of random trees with that info
242                                 if (it2 != rscoreFreq[a].end()) {  rscoreFreq[a][it->first] /= iters; rcumul+= it2->second;  }
243                                 else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
244                                 rCumul[a][it->first] = rcumul;
245                         }
246                         
247                         //find the signifigance of each user trees score when compared to the random trees and save for printing the summary file
248                         for (int h = 0; h < userTreeScores[a].size(); h++) {
249                                 UScoreSig[a].push_back(rCumul[a][userTreeScores[a][h]]);
250                         }
251                 }
252                 
253                 //finish progress bar
254                 reading->finish();
255                 delete reading;
256
257                 
258                 printParsimonyFile();
259                 if (randomtree == "") { printUSummaryFile(); }
260                 
261                 //reset globaldata's treemap if you just did random distrib
262                 if (randomtree != "") {
263                         //memory leak prevention
264                         //if (globaldata->gTreemap != NULL) { delete globaldata->gTreemap;  }
265                         globaldata->gTreemap = savetmap;
266                 }
267                 
268                 //reset groups parameter
269                 globaldata->Groups.clear(); 
270                 
271                 return 0;
272                 
273         }
274         catch(exception& e) {
275                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function execute. 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 execute. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
280                 exit(1);
281         }
282 }
283
284 /***********************************************************/
285 void ParsimonyCommand::printParsimonyFile() {
286         try {
287                 vector<double> data;
288                 vector<string> tags;
289                 
290                 if (randomtree == "") {
291                         tags.push_back("Score"); tags.push_back("UserFreq"); tags.push_back("UserCumul"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
292                 }else {
293                         tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
294                 }
295
296                 for(int a = 0; a < numComp; a++) {
297                         output->initFile(groupComb[a], tags);
298                         //print each line
299                         for (map<int,double>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
300                                 if (randomtree == "") {
301                                         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]); 
302                                 }else{
303                                         data.push_back(it->first);  data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]); 
304                                 }
305                                 output->output(data);
306                                 data.clear();
307                         } 
308                         output->resetFile();
309                 }
310         }
311         catch(exception& e) {
312                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function printParsimonyFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
313                 exit(1);
314         }
315         catch(...) {
316                 cout << "An unknown error has occurred in the ParsimonyCommand class function printParsimonyFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
317                 exit(1);
318         }
319 }
320 /***********************************************************/
321 void ParsimonyCommand::printUSummaryFile() {
322         try {
323                 //column headers
324                 outSum << "Tree#" << '\t' << "Groups" << '\t'  <<  "ParsScore" << '\t' << "ParsSig" <<  endl;
325                 cout << "Tree#" << '\t' << "Groups" << '\t'  <<  "ParsScore" << '\t' << "ParsSig" <<  endl;
326                 
327                 //format output
328                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
329                 
330                 
331                 //print each line
332                 for (int i = 0; i< T.size(); i++) {
333                         for(int a = 0; a < numComp; a++) {
334                                 if (UScoreSig[a][i] > (1/(float)iters)) {
335                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[a]  << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << UScoreSig[a][i] << endl;
336                                         cout << setprecision(6) << i+1 << '\t' << groupComb[a]  << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << UScoreSig[a][i] << endl;
337                                 }else {
338                                         outSum << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length())  << '\t' << "<" << (1/float(iters)) << endl;
339                                         cout << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << "<" << (1/float(iters)) << endl;
340                                 }
341                         }
342                 }
343                 
344                 outSum.close();
345         }
346         catch(exception& e) {
347                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function printUSummaryFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
348                 exit(1);
349         }
350         catch(...) {
351                 cout << "An unknown error has occurred in the ParsimonyCommand class function printUSummaryFile. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
352                 exit(1);
353         }
354 }
355
356 /***********************************************************/
357 void ParsimonyCommand::getUserInput() {
358         try {
359         
360                 //create treemap
361                 tmap = new TreeMap();
362
363                 cout << "Please enter the number of groups you would like to analyze: ";
364                 cin >> numGroups;
365                         
366                 int num, count;
367                 count = 1;
368                 numEachGroup.resize(numGroups, 0);  
369                 
370                 for (int i = 1; i <= numGroups; i++) {
371                         cout << "Please enter the number of sequences in group " << i <<  ": ";
372                         cin >> num;
373                                 
374                         //set tmaps seqsPerGroup
375                         tmap->seqsPerGroup[toString(i)] = num;
376                         tmap->namesOfGroups.push_back(toString(i));
377                         
378                         //set tmaps namesOfSeqs
379                         for (int j = 0; j < num; j++) {
380                                 tmap->namesOfSeqs.push_back(toString(count));
381                                 tmap->treemap[toString(count)].groupname = toString(i);
382                                 count++;
383                         }
384                 }
385                 
386                 //clears buffer so next command doesn't have error
387                 string s;       
388                 getline(cin, s);
389                 
390                 //save tmap for later
391                 //memory leak prevention
392                 //if (globaldata->gTreemap != NULL) { delete globaldata->gTreemap;  }
393                 globaldata->gTreemap = tmap;
394                 globaldata->Treenames = tmap->namesOfSeqs; 
395                 
396         }
397         catch(exception& e) {
398                 cout << "Standard Error: " << e.what() << " has occurred in the ParsimonyCommand class Function getUserInput. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
399                 exit(1);
400         }
401         catch(...) {
402                 cout << "An unknown error has occurred in the ParsimonyCommand class function getUserInput. Please contact Pat Schloss at pschloss@microbio.umass.edu." << "\n";
403                 exit(1);
404         }
405 }
406
407 /***********************************************************/
408
409