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 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
131 randomtree = validParameter.validFile(parameters, "random", false); if (randomtree == "not found") { randomtree = ""; }
133 //are you trying to use parsimony without reading a tree or saying you want random distribution
134 if (randomtree == "") {
135 //check for required parameters
136 treefile = validParameter.validFile(parameters, "tree", true);
137 if (treefile == "not open") { abort = true; }
138 else if (treefile == "not found") { //if there is a current design file, use it
139 treefile = m->getTreeFile();
140 if (treefile != "") { m->mothurOut("Using " + treefile + " as input file for the tree parameter."); m->mothurOutEndLine(); }
141 else { m->mothurOut("You have no current tree file and the tree parameter is required."); m->mothurOutEndLine(); abort = true; }
144 //check for required parameters
145 groupfile = validParameter.validFile(parameters, "group", true);
146 if (groupfile == "not open") { abort = true; }
147 else if (groupfile == "not found") { groupfile = ""; }
149 namefile = validParameter.validFile(parameters, "name", true);
150 if (namefile == "not open") { abort = true; }
151 else if (namefile == "not found") { namefile = ""; }
154 //if the user changes the output directory command factory will send this info to us in the output parameter
155 string outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; if (randomtree == "") { outputDir += m->hasPath(treefile); } }
157 //check for optional parameter and set defaults
158 // ...at some point should added some additional type checking...
159 groups = validParameter.validFile(parameters, "groups", false);
160 if (groups == "not found") { groups = ""; m->Groups.clear(); }
162 m->splitAtDash(groups, Groups);
166 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
167 convert(itersString, iters);
169 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
170 m->setProcessors(temp);
171 convert(temp, processors);
176 catch(exception& e) {
177 m->errorOut(e, "ParsimonyCommand", "ParsimonyCommand");
181 /***********************************************************/
182 int ParsimonyCommand::execute() {
185 if (abort == true) { if (calledHelp) { return 0; } return 2; }
188 //randomtree will tell us if user had their own treefile or if they just want the random distribution
189 //user has entered their own tree
190 if (randomtree == "") {
191 if (groupfile != "") {
192 //read in group map info.
193 tmap = new TreeMap(groupfile);
195 }else{ //fake out by putting everyone in one group
196 Tree* tree = new Tree(treefile); delete tree; //extracts names from tree to make faked out groupmap
197 tmap = new TreeMap();
199 for (int i = 0; i < m->Treenames.size(); i++) { tmap->addSeq(m->Treenames[i], "Group1"); }
202 if (namefile != "") { readNamesFile(); }
204 read = new ReadNewickTree(treefile);
205 int readOk = read->read(tmap);
207 if (readOk != 0) { m->mothurOut("Read Terminated."); m->mothurOutEndLine(); delete tmap; delete read; return 0; }
209 read->AssembleTrees();
210 T = read->getTrees();
213 //make sure all files match
214 //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.
216 if (namefile != "") {
217 if (numUniquesInName == m->Treenames.size()) { numNamesInTree = nameMap.size(); }
218 else { numNamesInTree = m->Treenames.size(); }
219 }else { numNamesInTree = m->Treenames.size(); }
222 //output any names that are in group file but not in tree
223 if (numNamesInTree < tmap->getNumSeqs()) {
224 for (int i = 0; i < tmap->namesOfSeqs.size(); i++) {
225 //is that name in the tree?
227 for (int j = 0; j < m->Treenames.size(); j++) {
228 if (tmap->namesOfSeqs[i] == m->Treenames[j]) { break; } //found it
232 if (m->control_pressed) {
233 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
234 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
239 //then you did not find it so report it
240 if (count == m->Treenames.size()) {
241 //if it is in your namefile then don't remove
242 map<string, string>::iterator it = nameMap.find(tmap->namesOfSeqs[i]);
244 if (it == nameMap.end()) {
245 m->mothurOut(tmap->namesOfSeqs[i] + " is in your groupfile and not in your tree. It will be disregarded."); m->mothurOutEndLine();
246 tmap->removeSeq(tmap->namesOfSeqs[i]);
247 i--; //need this because removeSeq removes name from namesOfSeqs
253 if(outputDir == "") { outputDir += m->hasPath(treefile); }
254 output = new ColumnFile(outputDir + m->getSimpleName(treefile) + ".parsimony", itersString);
255 outputNames.push_back(outputDir + m->getSimpleName(treefile) + ".parsimony");
256 outputTypes["parsimony"].push_back(outputDir + m->getSimpleName(treefile) + ".parsimony");
258 sumFile = outputDir + m->getSimpleName(treefile) + ".psummary";
259 m->openOutputFile(sumFile, outSum);
260 outputNames.push_back(sumFile);
261 outputTypes["psummary"].push_back(sumFile);
262 }else { //user wants random distribution
265 if(outputDir == "") { outputDir += m->hasPath(randomtree); }
266 output = new ColumnFile(outputDir+ m->getSimpleName(randomtree), itersString);
267 outputNames.push_back(outputDir+ m->getSimpleName(randomtree));
268 outputTypes["parsimony"].push_back(outputDir+ m->getSimpleName(randomtree));
271 //set users groups to analyze
272 util = new SharedUtil();
273 util->setGroups(m->Groups, tmap->namesOfGroups, allGroups, numGroups, "parsimony"); //sets the groups the user wants to analyze
274 util->getCombos(groupComb, m->Groups, numComp);
277 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
279 pars = new Parsimony(tmap);
283 reading = new Progress("Comparing to random:", iters);
285 if (m->control_pressed) {
286 delete reading; delete pars; delete output;
287 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
288 if (randomtree == "") { outSum.close(); }
289 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
295 //get pscore for users tree
296 userData.resize(numComp,0); //data = AB, AC, BC, ABC.
297 randomData.resize(numComp,0); //data = AB, AC, BC, ABC.
298 rscoreFreq.resize(numComp);
299 uscoreFreq.resize(numComp);
300 rCumul.resize(numComp);
301 uCumul.resize(numComp);
302 userTreeScores.resize(numComp);
303 UScoreSig.resize(numComp);
305 if (randomtree == "") {
306 //get pscores for users trees
307 for (int i = 0; i < T.size(); i++) {
308 userData = pars->getValues(T[i], processors, outputDir); //data = AB, AC, BC, ABC.
310 if (m->control_pressed) {
311 delete reading; delete pars; delete output;
312 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
313 if (randomtree == "") { outSum.close(); }
314 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
320 //output scores for each combination
321 for(int k = 0; k < numComp; k++) {
324 map<int,double>::iterator it = uscoreFreq[k].find(userData[k]);
325 if (it == uscoreFreq[k].end()) {//new score
326 uscoreFreq[k][userData[k]] = 1;
327 }else{ uscoreFreq[k][userData[k]]++; }
329 //add users score to valid scores
330 validScores[userData[k]] = userData[k];
332 //save score for summary file
333 userTreeScores[k].push_back(userData[k]);
337 //get pscores for random trees
338 for (int j = 0; j < iters; j++) {
340 //create new tree with same num nodes and leaves as users
341 randT = new Tree(tmap);
343 //create random relationships between nodes
344 randT->assembleRandomTree();
346 //get pscore of random tree
347 randomData = pars->getValues(randT, processors, outputDir);
349 if (m->control_pressed) {
350 delete reading; delete pars; delete output; delete randT;
351 if (randomtree == "") { outSum.close(); }
352 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
353 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
358 for(int r = 0; r < numComp; r++) {
359 //add trees pscore to map of scores
360 map<int,double>::iterator it = rscoreFreq[r].find(randomData[r]);
361 if (it != rscoreFreq[r].end()) {//already have that score
362 rscoreFreq[r][randomData[r]]++;
363 }else{//first time we have seen this score
364 rscoreFreq[r][randomData[r]] = 1;
367 //add randoms score to validscores
368 validScores[randomData[r]] = randomData[r];
371 //update progress bar
378 //get pscores for random trees
379 for (int j = 0; j < iters; j++) {
381 //create new tree with same num nodes and leaves as users
382 randT = new Tree(tmap);
383 //create random relationships between nodes
385 randT->assembleRandomTree();
387 if (m->control_pressed) {
388 delete reading; delete pars; delete output; delete randT;
390 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
396 //get pscore of random tree
397 randomData = pars->getValues(randT, processors, outputDir);
399 if (m->control_pressed) {
400 delete reading; delete pars; delete output; delete randT;
402 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
407 for(int r = 0; r < numComp; r++) {
408 //add trees pscore to map of scores
409 map<int,double>::iterator it = rscoreFreq[r].find(randomData[r]);
410 if (it != rscoreFreq[r].end()) {//already have that score
411 rscoreFreq[r][randomData[r]]++;
412 }else{//first time we have seen this score
413 rscoreFreq[r][randomData[r]] = 1;
416 //add randoms score to validscores
417 validScores[randomData[r]] = randomData[r];
420 //update progress bar
427 for(int a = 0; a < numComp; a++) {
428 float rcumul = 0.0000;
429 float ucumul = 0.0000;
430 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
431 for (map<int,double>::iterator it = validScores.begin(); it != validScores.end(); it++) {
432 if (randomtree == "") {
433 map<int,double>::iterator it2 = uscoreFreq[a].find(it->first);
434 //user data has that score
435 if (it2 != uscoreFreq[a].end()) { uscoreFreq[a][it->first] /= T.size(); ucumul+= it2->second; }
436 else { uscoreFreq[a][it->first] = 0.0000; } //no user trees with that score
438 uCumul[a][it->first] = ucumul;
441 //make rscoreFreq map and rCumul
442 map<int,double>::iterator it2 = rscoreFreq[a].find(it->first);
443 //get percentage of random trees with that info
444 if (it2 != rscoreFreq[a].end()) { rscoreFreq[a][it->first] /= iters; rcumul+= it2->second; }
445 else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
446 rCumul[a][it->first] = rcumul;
449 //find the signifigance of each user trees score when compared to the random trees and save for printing the summary file
450 for (int h = 0; h < userTreeScores[a].size(); h++) {
451 UScoreSig[a].push_back(rCumul[a][userTreeScores[a][h]]);
455 if (m->control_pressed) {
456 delete reading; delete pars; delete output;
457 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
458 if (randomtree == "") { outSum.close(); }
459 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear();
464 //finish progress bar
469 printParsimonyFile();
470 if (randomtree == "") { printUSummaryFile(); }
472 //reset groups parameter
475 delete pars; delete output;
476 delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }
478 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } outputTypes.clear(); return 0;}
480 m->mothurOutEndLine();
481 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
482 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
483 m->mothurOutEndLine();
489 catch(exception& e) {
490 m->errorOut(e, "ParsimonyCommand", "execute");
495 /***********************************************************/
496 void ParsimonyCommand::printParsimonyFile() {
501 if (randomtree == "") {
502 tags.push_back("Score"); tags.push_back("UserFreq"); tags.push_back("UserCumul"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
504 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
507 for(int a = 0; a < numComp; a++) {
508 output->initFile(groupComb[a], tags);
510 for (map<int,double>::iterator it = validScores.begin(); it != validScores.end(); it++) {
511 if (randomtree == "") {
512 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]);
514 data.push_back(it->first); data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
516 output->output(data);
522 catch(exception& e) {
523 m->errorOut(e, "ParsimonyCommand", "printParsimonyFile");
527 /***********************************************************/
528 int ParsimonyCommand::printUSummaryFile() {
531 outSum << "Tree#" << '\t' << "Groups" << '\t' << "ParsScore" << '\t' << "ParsSig" << endl;
532 m->mothurOut("Tree#\tGroups\tParsScore\tParsSig"); m->mothurOutEndLine();
535 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
539 for (int i = 0; i< T.size(); i++) {
540 for(int a = 0; a < numComp; a++) {
541 if (m->control_pressed) { outSum.close(); return 0; }
542 if (UScoreSig[a][i] > (1/(float)iters)) {
543 outSum << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << UScoreSig[a][i] << endl;
544 cout << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << UScoreSig[a][i] << endl;
545 m->mothurOutJustToLog(toString(i+1) + "\t" + groupComb[a] + "\t" + toString(userTreeScores[a][i]) + "\t" + toString(UScoreSig[a][i])); m->mothurOutEndLine();
547 outSum << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << "<" << (1/float(iters)) << endl;
548 cout << setprecision(6) << i+1 << '\t' << groupComb[a] << '\t' << userTreeScores[a][i] << setprecision(itersString.length()) << '\t' << "<" << (1/float(iters)) << endl;
549 m->mothurOutJustToLog(toString(i+1) + "\t" + groupComb[a] + "\t" + toString(userTreeScores[a][i]) + "\t" + toString((1/float(iters)))); m->mothurOutEndLine();
557 catch(exception& e) {
558 m->errorOut(e, "ParsimonyCommand", "printUSummaryFile");
563 /***********************************************************/
564 void ParsimonyCommand::getUserInput() {
568 tmap = new TreeMap();
570 m->mothurOut("Please enter the number of groups you would like to analyze: ");
572 m->mothurOutJustToLog(toString(numGroups)); m->mothurOutEndLine();
576 numEachGroup.resize(numGroups, 0);
578 for (int i = 1; i <= numGroups; i++) {
579 m->mothurOut("Please enter the number of sequences in group " + toString(i) + ": ");
581 m->mothurOutJustToLog(toString(num)); m->mothurOutEndLine();
583 //set tmaps seqsPerGroup
584 tmap->seqsPerGroup[toString(i)] = num;
585 tmap->namesOfGroups.push_back(toString(i));
587 //set tmaps namesOfSeqs
588 for (int j = 0; j < num; j++) {
589 tmap->namesOfSeqs.push_back(toString(count));
590 tmap->treemap[toString(count)].groupname = toString(i);
595 //clears buffer so next command doesn't have error
599 m->Treenames = tmap->namesOfSeqs;
602 catch(exception& e) {
603 m->errorOut(e, "ParsimonyCommand", "getUserInput");
607 /*****************************************************************/
608 int ParsimonyCommand::readNamesFile() {
611 numUniquesInName = 0;
614 m->openInputFile(namefile, in);
616 string first, second;
617 map<string, string>::iterator itNames;
620 in >> first >> second; m->gobble(in);
624 itNames = m->names.find(first);
625 if (itNames == m->names.end()) {
626 m->names[first] = second;
628 //we need a list of names in your namefile to use above when removing extra seqs above so we don't remove them
629 vector<string> dupNames;
630 m->splitAtComma(second, dupNames);
632 for (int i = 0; i < dupNames.size(); i++) {
633 nameMap[dupNames[i]] = dupNames[i];
634 if ((groupfile == "") && (i != 0)) { tmap->addSeq(dupNames[i], "Group1"); }
636 }else { m->mothurOut(first + " has already been seen in namefile, disregarding names file."); m->mothurOutEndLine(); in.close(); m->names.clear(); namefile = ""; return 1; }
642 catch(exception& e) {
643 m->errorOut(e, "ParsimonyCommand", "readNamesFile");
647 /***********************************************************/