5 * Created by Sarah Westcott on 1/26/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "parsimonycommand.h"
12 //**********************************************************************************************************************
13 vector<string> ParsimonyCommand::setParameters(){
15 CommandParameter ptree("tree", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptree);
16 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
17 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
18 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
19 CommandParameter prandom("random", "String", "", "", "", "", "",false,false); parameters.push_back(prandom);
20 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
21 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
22 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
23 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
25 vector<string> myArray;
26 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
30 m->errorOut(e, "ParsimonyCommand", "setParameters");
34 //**********************************************************************************************************************
35 string ParsimonyCommand::getHelpString(){
37 string helpString = "";
38 helpString += "The parsimony command parameters are tree, group, name, random, groups, processors and iters. tree parameter is required unless you have valid current tree file or are using random.\n";
39 helpString += "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";
40 helpString += "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";
41 helpString += "The parsimony command should be in the following format: parsimony(random=yourOutputFilename, groups=yourGroups, iters=yourIters).\n";
42 helpString += "The processors parameter allows you to specify the number of processors to use. The default is 1.\n";
43 helpString += "Example parsimony(random=out, iters=500).\n";
44 helpString += "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";
45 helpString += "and iters is 1000. The parsimony command output two files: .parsimony and .psummary their descriptions are in the manual.\n";
46 helpString += "Note: No spaces between parameter labels (i.e. random), '=' and parameters (i.e.yourOutputFilename).\n";
50 m->errorOut(e, "ParsimonyCommand", "getHelpString");
55 //**********************************************************************************************************************
56 ParsimonyCommand::ParsimonyCommand(){
58 abort = true; calledHelp = true;
60 vector<string> tempOutNames;
61 outputTypes["parsimony"] = tempOutNames;
62 outputTypes["psummary"] = tempOutNames;
65 m->errorOut(e, "ParsimonyCommand", "ParsimonyCommand");
69 /***********************************************************/
70 ParsimonyCommand::ParsimonyCommand(string option) {
72 abort = false; calledHelp = false;
75 //allow user to run help
76 if(option == "help") { help(); abort = true; calledHelp = true; }
79 vector<string> myArray = setParameters();
81 OptionParser parser(option);
82 map<string, string> parameters = parser.getParameters();
83 map<string,string>::iterator it;
85 ValidParameters validParameter;
87 //check to make sure all parameters are valid for command
88 for (it = parameters.begin(); it != parameters.end(); it++) {
89 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
92 //initialize outputTypes
93 vector<string> tempOutNames;
94 outputTypes["parsimony"] = tempOutNames;
95 outputTypes["psummary"] = tempOutNames;
97 //if the user changes the input directory command factory will send this info to us in the output parameter
98 string inputDir = validParameter.validFile(parameters, "inputdir", false);
99 if (inputDir == "not found"){ inputDir = ""; }
102 it = parameters.find("tree");
103 //user has given a template file
104 if(it != parameters.end()){
105 path = m->hasPath(it->second);
106 //if the user has not given a path then, add inputdir. else leave path alone.
107 if (path == "") { parameters["tree"] = inputDir + it->second; }
110 it = parameters.find("group");
111 //user has given a template file
112 if(it != parameters.end()){
113 path = m->hasPath(it->second);
114 //if the user has not given a path then, add inputdir. else leave path alone.
115 if (path == "") { parameters["group"] = inputDir + it->second; }
118 it = parameters.find("name");
119 //user has given a template file
120 if(it != parameters.end()){
121 path = m->hasPath(it->second);
122 //if the user has not given a path then, add inputdir. else leave path alone.
123 if (path == "") { parameters["name"] = inputDir + it->second; }
129 m->namesOfGroups.clear();
130 m->Treenames.clear();
133 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
135 randomtree = validParameter.validFile(parameters, "random", false); if (randomtree == "not found") { randomtree = ""; }
137 //are you trying to use parsimony without reading a tree or saying you want random distribution
138 if (randomtree == "") {
139 //check for required parameters
140 treefile = validParameter.validFile(parameters, "tree", true);
141 if (treefile == "not open") { abort = true; }
142 else if (treefile == "not found") { //if there is a current design file, use it
143 treefile = m->getTreeFile();
144 if (treefile != "") { m->mothurOut("Using " + treefile + " as input file for the tree parameter."); m->mothurOutEndLine(); }
145 else { m->mothurOut("You have no current tree file and the tree parameter is required."); m->mothurOutEndLine(); abort = true; }
148 //check for required parameters
149 groupfile = validParameter.validFile(parameters, "group", true);
150 if (groupfile == "not open") { abort = true; }
151 else if (groupfile == "not found") { groupfile = ""; }
153 namefile = validParameter.validFile(parameters, "name", true);
154 if (namefile == "not open") { abort = true; }
155 else if (namefile == "not found") { namefile = ""; }
158 //if the user changes the output directory command factory will send this info to us in the output parameter
159 string outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; if (randomtree == "") { outputDir += m->hasPath(treefile); } }
161 //check for optional parameter and set defaults
162 // ...at some point should added some additional type checking...
163 groups = validParameter.validFile(parameters, "groups", false);
164 if (groups == "not found") { groups = ""; m->Groups.clear(); }
166 m->splitAtDash(groups, Groups);
170 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
171 convert(itersString, iters);
173 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
174 m->setProcessors(temp);
175 convert(temp, processors);
180 catch(exception& e) {
181 m->errorOut(e, "ParsimonyCommand", "ParsimonyCommand");
185 /***********************************************************/
186 int ParsimonyCommand::execute() {
189 if (abort == true) { if (calledHelp) { return 0; } return 2; }
192 //randomtree will tell us if user had their own treefile or if they just want the random distribution
193 //user has entered their own tree
194 if (randomtree == "") {
196 m->setTreeFile(treefile);
198 if (groupfile != "") {
199 //read in group map info.
200 tmap = new TreeMap(groupfile);
202 }else{ //fake out by putting everyone in one group
203 Tree* tree = new Tree(treefile); delete tree; //extracts names from tree to make faked out groupmap
204 tmap = new TreeMap();
206 for (int i = 0; i < m->Treenames.size(); i++) { tmap->addSeq(m->Treenames[i], "Group1"); }
209 if (namefile != "") { readNamesFile(); }
211 read = new ReadNewickTree(treefile);
212 int readOk = read->read(tmap);
214 if (readOk != 0) { m->mothurOut("Read Terminated."); m->mothurOutEndLine(); delete tmap; delete read; return 0; }
216 read->AssembleTrees();
217 T = read->getTrees();
220 //make sure all files match
221 //if you provide a namefile we will use the numNames in the namefile as long as the number of unique match the tree names size.
223 if (namefile != "") {
224 if (numUniquesInName == m->Treenames.size()) { numNamesInTree = nameMap.size(); }
225 else { numNamesInTree = m->Treenames.size(); }
226 }else { numNamesInTree = m->Treenames.size(); }
229 //output any names that are in group file but not in tree
230 if (numNamesInTree < tmap->getNumSeqs()) {
231 for (int i = 0; i < tmap->namesOfSeqs.size(); i++) {
232 //is that name in the tree?
234 for (int j = 0; j < m->Treenames.size(); j++) {
235 if (tmap->namesOfSeqs[i] == m->Treenames[j]) { break; } //found it
239 if (m->control_pressed) {
240 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
241 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
246 //then you did not find it so report it
247 if (count == m->Treenames.size()) {
248 //if it is in your namefile then don't remove
249 map<string, string>::iterator it = nameMap.find(tmap->namesOfSeqs[i]);
251 if (it == nameMap.end()) {
252 m->mothurOut(tmap->namesOfSeqs[i] + " is in your groupfile and not in your tree. It will be disregarded."); m->mothurOutEndLine();
253 tmap->removeSeq(tmap->namesOfSeqs[i]);
254 i--; //need this because removeSeq removes name from namesOfSeqs
260 if(outputDir == "") { outputDir += m->hasPath(treefile); }
261 output = new ColumnFile(outputDir + m->getSimpleName(treefile) + ".parsimony", itersString);
262 outputNames.push_back(outputDir + m->getSimpleName(treefile) + ".parsimony");
263 outputTypes["parsimony"].push_back(outputDir + m->getSimpleName(treefile) + ".parsimony");
265 sumFile = outputDir + m->getSimpleName(treefile) + ".psummary";
266 m->openOutputFile(sumFile, outSum);
267 outputNames.push_back(sumFile);
268 outputTypes["psummary"].push_back(sumFile);
269 }else { //user wants random distribution
272 if(outputDir == "") { outputDir += m->hasPath(randomtree); }
273 output = new ColumnFile(outputDir+ m->getSimpleName(randomtree), itersString);
274 outputNames.push_back(outputDir+ m->getSimpleName(randomtree));
275 outputTypes["parsimony"].push_back(outputDir+ m->getSimpleName(randomtree));
278 //set users groups to analyze
279 util = new SharedUtil();
280 util->setGroups(m->Groups, tmap->namesOfGroups, allGroups, numGroups, "parsimony"); //sets the groups the user wants to analyze
281 util->getCombos(groupComb, m->Groups, numComp);
284 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
286 pars = new Parsimony(tmap);
290 reading = new Progress("Comparing to random:", iters);
292 if (m->control_pressed) {
293 delete reading; delete pars; delete output;
294 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
295 if (randomtree == "") { outSum.close(); }
296 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
302 //get pscore for users tree
303 userData.resize(numComp,0); //data = AB, AC, BC, ABC.
304 randomData.resize(numComp,0); //data = AB, AC, BC, ABC.
305 rscoreFreq.resize(numComp);
306 uscoreFreq.resize(numComp);
307 rCumul.resize(numComp);
308 uCumul.resize(numComp);
309 userTreeScores.resize(numComp);
310 UScoreSig.resize(numComp);
312 if (randomtree == "") {
313 //get pscores for users trees
314 for (int i = 0; i < T.size(); i++) {
315 userData = pars->getValues(T[i], processors, outputDir); //data = AB, AC, BC, ABC.
317 if (m->control_pressed) {
318 delete reading; delete pars; delete output;
319 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
320 if (randomtree == "") { outSum.close(); }
321 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
327 //output scores for each combination
328 for(int k = 0; k < numComp; k++) {
331 map<int,double>::iterator it = uscoreFreq[k].find(userData[k]);
332 if (it == uscoreFreq[k].end()) {//new score
333 uscoreFreq[k][userData[k]] = 1;
334 }else{ uscoreFreq[k][userData[k]]++; }
336 //add users score to valid scores
337 validScores[userData[k]] = userData[k];
339 //save score for summary file
340 userTreeScores[k].push_back(userData[k]);
344 //get pscores for random trees
345 for (int j = 0; j < iters; j++) {
347 //create new tree with same num nodes and leaves as users
348 randT = new Tree(tmap);
350 //create random relationships between nodes
351 randT->assembleRandomTree();
353 //get pscore of random tree
354 randomData = pars->getValues(randT, processors, outputDir);
356 if (m->control_pressed) {
357 delete reading; delete pars; delete output; delete randT;
358 if (randomtree == "") { outSum.close(); }
359 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
360 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
365 for(int r = 0; r < numComp; r++) {
366 //add trees pscore to map of scores
367 map<int,double>::iterator it = rscoreFreq[r].find(randomData[r]);
368 if (it != rscoreFreq[r].end()) {//already have that score
369 rscoreFreq[r][randomData[r]]++;
370 }else{//first time we have seen this score
371 rscoreFreq[r][randomData[r]] = 1;
374 //add randoms score to validscores
375 validScores[randomData[r]] = randomData[r];
378 //update progress bar
385 //get pscores for random trees
386 for (int j = 0; j < iters; j++) {
388 //create new tree with same num nodes and leaves as users
389 randT = new Tree(tmap);
390 //create random relationships between nodes
392 randT->assembleRandomTree();
394 if (m->control_pressed) {
395 delete reading; delete pars; delete output; delete randT;
397 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
403 //get pscore of random tree
404 randomData = pars->getValues(randT, processors, outputDir);
406 if (m->control_pressed) {
407 delete reading; delete pars; delete output; delete randT;
409 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
414 for(int r = 0; r < numComp; r++) {
415 //add trees pscore to map of scores
416 map<int,double>::iterator it = rscoreFreq[r].find(randomData[r]);
417 if (it != rscoreFreq[r].end()) {//already have that score
418 rscoreFreq[r][randomData[r]]++;
419 }else{//first time we have seen this score
420 rscoreFreq[r][randomData[r]] = 1;
423 //add randoms score to validscores
424 validScores[randomData[r]] = randomData[r];
427 //update progress bar
434 for(int a = 0; a < numComp; a++) {
435 float rcumul = 0.0000;
436 float ucumul = 0.0000;
437 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
438 for (map<int,double>::iterator it = validScores.begin(); it != validScores.end(); it++) {
439 if (randomtree == "") {
440 map<int,double>::iterator it2 = uscoreFreq[a].find(it->first);
441 //user data has that score
442 if (it2 != uscoreFreq[a].end()) { uscoreFreq[a][it->first] /= T.size(); ucumul+= it2->second; }
443 else { uscoreFreq[a][it->first] = 0.0000; } //no user trees with that score
445 uCumul[a][it->first] = ucumul;
448 //make rscoreFreq map and rCumul
449 map<int,double>::iterator it2 = rscoreFreq[a].find(it->first);
450 //get percentage of random trees with that info
451 if (it2 != rscoreFreq[a].end()) { rscoreFreq[a][it->first] /= iters; rcumul+= it2->second; }
452 else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
453 rCumul[a][it->first] = rcumul;
456 //find the signifigance of each user trees score when compared to the random trees and save for printing the summary file
457 for (int h = 0; h < userTreeScores[a].size(); h++) {
458 UScoreSig[a].push_back(rCumul[a][userTreeScores[a][h]]);
462 if (m->control_pressed) {
463 delete reading; delete pars; delete output;
464 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
465 if (randomtree == "") { outSum.close(); }
466 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
471 //finish progress bar
476 printParsimonyFile();
477 if (randomtree == "") { printUSummaryFile(); }
479 //reset groups parameter
482 delete pars; delete output;
483 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
485 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear(); return 0;}
487 m->mothurOutEndLine();
488 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
489 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
490 m->mothurOutEndLine();
496 catch(exception& e) {
497 m->errorOut(e, "ParsimonyCommand", "execute");
502 /***********************************************************/
503 void ParsimonyCommand::printParsimonyFile() {
508 if (randomtree == "") {
509 tags.push_back("Score"); tags.push_back("UserFreq"); tags.push_back("UserCumul"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
511 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
514 for(int a = 0; a < numComp; a++) {
515 output->initFile(groupComb[a], tags);
517 for (map<int,double>::iterator it = validScores.begin(); it != validScores.end(); it++) {
518 if (randomtree == "") {
519 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]);
521 data.push_back(it->first); data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
523 output->output(data);
529 catch(exception& e) {
530 m->errorOut(e, "ParsimonyCommand", "printParsimonyFile");
534 /***********************************************************/
535 int ParsimonyCommand::printUSummaryFile() {
538 outSum << "Tree#" << '\t' << "Groups" << '\t' << "ParsScore" << '\t' << "ParsSig" << endl;
539 m->mothurOut("Tree#\tGroups\tParsScore\tParsSig"); m->mothurOutEndLine();
542 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
546 for (int i = 0; i< T.size(); i++) {
547 for(int a = 0; a < numComp; a++) {
548 if (m->control_pressed) { outSum.close(); return 0; }
549 if (UScoreSig[a][i] > (1/(float)iters)) {
550 outSum << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << UScoreSig[a][i] << endl;
551 cout << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << UScoreSig[a][i] << endl;
552 m->mothurOutJustToLog(toString(i+1) + "\t" + groupComb[a] + "\t" + toString(userTreeScores[a][i]) + "\t" + toString(UScoreSig[a][i])); m->mothurOutEndLine();
554 outSum << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << "<" << (1/float(iters)) << endl;
555 cout << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << "<" << (1/float(iters)) << endl;
556 m->mothurOutJustToLog(toString(i+1) + "\t" + groupComb[a] + "\t" + toString(userTreeScores[a][i]) + "\t" + toString((1/float(iters)))); m->mothurOutEndLine();
564 catch(exception& e) {
565 m->errorOut(e, "ParsimonyCommand", "printUSummaryFile");
570 /***********************************************************/
571 void ParsimonyCommand::getUserInput() {
575 tmap = new TreeMap();
577 m->mothurOut("Please enter the number of groups you would like to analyze: ");
579 m->mothurOutJustToLog(toString(numGroups)); m->mothurOutEndLine();
583 numEachGroup.resize(numGroups, 0);
585 for (int i = 1; i <= numGroups; i++) {
586 m->mothurOut("Please enter the number of sequences in group " + toString(i) + ": ");
588 m->mothurOutJustToLog(toString(num)); m->mothurOutEndLine();
590 //set tmaps seqsPerGroup
591 tmap->seqsPerGroup[toString(i)] = num;
592 tmap->namesOfGroups.push_back(toString(i));
594 //set tmaps namesOfSeqs
595 for (int j = 0; j < num; j++) {
596 tmap->namesOfSeqs.push_back(toString(count));
597 tmap->treemap[toString(count)].groupname = toString(i);
602 //clears buffer so next command doesn't have error
606 m->Treenames = tmap->namesOfSeqs;
609 catch(exception& e) {
610 m->errorOut(e, "ParsimonyCommand", "getUserInput");
614 /*****************************************************************/
615 int ParsimonyCommand::readNamesFile() {
618 numUniquesInName = 0;
621 m->openInputFile(namefile, in);
623 string first, second;
624 map<string, string>::iterator itNames;
627 in >> first >> second; m->gobble(in);
631 itNames = m->names.find(first);
632 if (itNames == m->names.end()) {
633 m->names[first] = second;
635 //we need a list of names in your namefile to use above when removing extra seqs above so we don't remove them
636 vector<string> dupNames;
637 m->splitAtComma(second, dupNames);
639 for (int i = 0; i < dupNames.size(); i++) {
640 nameMap[dupNames[i]] = dupNames[i];
641 if ((groupfile == "") && (i != 0)) { tmap->addSeq(dupNames[i], "Group1"); }
643 }else { m->mothurOut(first + " has already been seen in namefile, disregarding names file."); m->mothurOutEndLine(); in.close(); m->names.clear(); namefile = ""; return 1; }
649 catch(exception& e) {
650 m->errorOut(e, "ParsimonyCommand", "readNamesFile");
654 /***********************************************************/