2 * unifracunweightedcommand.cpp
5 * Created by Sarah Westcott on 2/9/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "unifracunweightedcommand.h"
12 //**********************************************************************************************************************
13 vector<string> UnifracUnweightedCommand::getValidParameters(){
15 string Array[] = {"groups","iters","distance","random", "processors","outputdir","inputdir"};
16 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
20 m->errorOut(e, "UnifracUnweightedCommand", "getValidParameters");
24 //**********************************************************************************************************************
25 UnifracUnweightedCommand::UnifracUnweightedCommand(){
27 globaldata = GlobalData::getInstance();
28 abort = true; calledHelp = true;
29 vector<string> tempOutNames;
30 outputTypes["unweighted"] = tempOutNames;
31 outputTypes["uwsummary"] = tempOutNames;
32 outputTypes["phylip"] = tempOutNames;
33 outputTypes["column"] = tempOutNames;
36 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
40 //**********************************************************************************************************************
41 vector<string> UnifracUnweightedCommand::getRequiredParameters(){
43 vector<string> myArray;
47 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredParameters");
51 //**********************************************************************************************************************
52 vector<string> UnifracUnweightedCommand::getRequiredFiles(){
54 string Array[] = {"tree","group"};
55 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
60 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredFiles");
64 /***********************************************************/
65 UnifracUnweightedCommand::UnifracUnweightedCommand(string option) {
67 globaldata = GlobalData::getInstance();
68 abort = false; calledHelp = false;
71 //allow user to run help
72 if(option == "help") { help(); abort = true; calledHelp = true; }
75 //valid paramters for this command
76 string Array[] = {"groups","iters","distance","random", "processors","outputdir","inputdir"};
77 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
79 OptionParser parser(option);
80 map<string,string> parameters = parser.getParameters();
82 ValidParameters validParameter;
84 //check to make sure all parameters are valid for command
85 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
86 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
89 //initialize outputTypes
90 vector<string> tempOutNames;
91 outputTypes["unweighted"] = tempOutNames;
92 outputTypes["uwsummary"] = tempOutNames;
93 outputTypes["phylip"] = tempOutNames;
94 outputTypes["column"] = tempOutNames;
96 if (globaldata->gTree.size() == 0) {//no trees were read
97 m->mothurOut("You must execute the read.tree command, before you may execute the unifrac.unweighted command."); m->mothurOutEndLine(); abort = true; }
99 //if the user changes the output directory command factory will send this info to us in the output parameter
100 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
102 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
105 //check for optional parameter and set defaults
106 // ...at some point should added some additional type checking...
107 groups = validParameter.validFile(parameters, "groups", false);
108 if (groups == "not found") { groups = ""; }
110 m->splitAtDash(groups, Groups);
111 globaldata->Groups = Groups;
114 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
115 convert(itersString, iters);
117 string temp = validParameter.validFile(parameters, "distance", false);
118 if (temp == "not found") { phylip = false; outputForm = ""; }
120 if ((temp == "lt") || (temp == "column") || (temp == "square")) { phylip = true; outputForm = temp; }
121 else { m->mothurOut("Options for distance are: lt, square, or column. Using lt."); m->mothurOutEndLine(); phylip = true; outputForm = "lt"; }
124 temp = validParameter.validFile(parameters, "random", false); if (temp == "not found") { temp = "f"; }
125 random = m->isTrue(temp);
127 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
128 convert(temp, processors);
130 if (!random) { iters = 0; } //turn off random calcs
132 //if user selects distance = true and no groups it won't calc the pairwise
133 if ((phylip) && (Groups.size() == 0)) {
135 m->splitAtDash(groups, Groups);
136 globaldata->Groups = Groups;
139 if (abort == false) {
140 T = globaldata->gTree;
141 tmap = globaldata->gTreemap;
142 sumFile = outputDir + m->getSimpleName(globaldata->getTreeFile()) + ".uwsummary";
143 outputNames.push_back(sumFile); outputTypes["uwsummary"].push_back(sumFile);
144 m->openOutputFile(sumFile, outSum);
146 util = new SharedUtil();
147 util->setGroups(globaldata->Groups, tmap->namesOfGroups, allGroups, numGroups, "unweighted"); //sets the groups the user wants to analyze
148 util->getCombos(groupComb, globaldata->Groups, numComp);
150 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
152 unweighted = new Unweighted(tmap);
159 catch(exception& e) {
160 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
165 //**********************************************************************************************************************
167 void UnifracUnweightedCommand::help(){
169 m->mothurOut("The unifrac.unweighted command can only be executed after a successful read.tree command.\n");
170 m->mothurOut("The unifrac.unweighted command parameters are groups, iters, distance, processors and random. No parameters are required.\n");
171 m->mothurOut("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");
172 m->mothurOut("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");
173 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false. You may set distance to lt, square or column.\n");
174 m->mothurOut("The random parameter allows you to shut off the comparison to random trees. The default is false, meaning compare don't your trees with randomly generated trees.\n");
175 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
176 m->mothurOut("The unifrac.unweighted command should be in the following format: unifrac.unweighted(groups=yourGroups, iters=yourIters).\n");
177 m->mothurOut("Example unifrac.unweighted(groups=A-B-C, iters=500).\n");
178 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
179 m->mothurOut("The unifrac.unweighted command output two files: .unweighted and .uwsummary their descriptions are in the manual.\n");
180 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
182 catch(exception& e) {
183 m->errorOut(e, "UnifracUnweightedCommand", "help");
189 /***********************************************************/
190 int UnifracUnweightedCommand::execute() {
193 if (abort == true) { if (calledHelp) { return 0; } return 2; }
195 int start = time(NULL);
197 userData.resize(numComp,0); //data[0] = unweightedscore
198 randomData.resize(numComp,0); //data[0] = unweightedscore
199 //create new tree with same num nodes and leaves as users
201 outSum << "Tree#" << '\t' << "Groups" << '\t' << "UWScore" <<'\t' << "UWSig" << endl;
202 m->mothurOut("Tree#\tGroups\tUWScore\tUWSig"); m->mothurOutEndLine();
204 //get pscores for users trees
205 for (int i = 0; i < T.size(); i++) {
206 if (m->control_pressed) {
208 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
215 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted", itersString);
216 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted");
217 outputTypes["unweighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted");
221 //get unweighted for users tree
222 rscoreFreq.resize(numComp);
223 rCumul.resize(numComp);
224 utreeScores.resize(numComp);
225 UWScoreSig.resize(numComp);
227 userData = unweighted->getValues(T[i], processors, outputDir); //userData[0] = unweightedscore
229 if (m->control_pressed) { if (random) { delete output; } outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }return 0; }
231 //output scores for each combination
232 for(int k = 0; k < numComp; k++) {
234 utreeScores[k].push_back(userData[k]);
236 //add users score to validscores
237 validScores[userData[k]] = userData[k];
240 //get unweighted scores for random trees - if random is false iters = 0
241 for (int j = 0; j < iters; j++) {
243 //we need a different getValues because when we swap the labels we only want to swap those in each pairwise comparison
244 randomData = unweighted->getValues(T[i], "", "", processors, outputDir);
246 if (m->control_pressed) { if (random) { delete output; } outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
248 for(int k = 0; k < numComp; k++) {
249 //add trees unweighted score to map of scores
250 map<float,float>::iterator it = rscoreFreq[k].find(randomData[k]);
251 if (it != rscoreFreq[k].end()) {//already have that score
252 rscoreFreq[k][randomData[k]]++;
253 }else{//first time we have seen this score
254 rscoreFreq[k][randomData[k]] = 1;
257 //add randoms score to validscores
258 validScores[randomData[k]] = randomData[k];
262 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();
265 for(int a = 0; a < numComp; a++) {
266 float rcumul = 1.0000;
269 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
270 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
271 //make rscoreFreq map and rCumul
272 map<float,float>::iterator it2 = rscoreFreq[a].find(it->first);
273 rCumul[a][it->first] = rcumul;
274 //get percentage of random trees with that info
275 if (it2 != rscoreFreq[a].end()) { rscoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
276 else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
278 UWScoreSig[a].push_back(rCumul[a][userData[a]]);
279 }else { UWScoreSig[a].push_back(0.0); }
283 if (m->control_pressed) { if (random) { delete output; } outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
286 printUWSummaryFile(i);
287 if (random) { printUnweightedFile(); delete output; }
288 if (phylip) { createPhylipFile(i); }
300 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
302 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.unweighted."); m->mothurOutEndLine();
304 m->mothurOutEndLine();
305 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
306 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
307 m->mothurOutEndLine();
312 catch(exception& e) {
313 m->errorOut(e, "UnifracUnweightedCommand", "execute");
317 /***********************************************************/
318 void UnifracUnweightedCommand::printUnweightedFile() {
323 tags.push_back("Score");
324 tags.push_back("RandFreq"); tags.push_back("RandCumul");
326 for(int a = 0; a < numComp; a++) {
327 output->initFile(groupComb[a], tags);
329 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
330 data.push_back(it->first); data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
331 output->output(data);
337 catch(exception& e) {
338 m->errorOut(e, "UnifracUnweightedCommand", "printUnweightedFile");
343 /***********************************************************/
344 void UnifracUnweightedCommand::printUWSummaryFile(int i) {
348 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
352 for(int a = 0; a < numComp; a++) {
353 outSum << i+1 << '\t';
354 m->mothurOut(toString(i+1) + "\t");
357 if (UWScoreSig[a][0] > (1/(float)iters)) {
358 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
359 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
360 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t" + toString(UWScoreSig[a][0])+ "\n");
362 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
363 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
364 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t<" + toString((1/float(iters))) + "\n");
367 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
368 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
369 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t0.00\n");
374 catch(exception& e) {
375 m->errorOut(e, "UnifracUnweightedCommand", "printUWSummaryFile");
379 /***********************************************************/
380 void UnifracUnweightedCommand::createPhylipFile(int i) {
382 string phylipFileName;
383 if ((outputForm == "lt") || (outputForm == "square")) {
384 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted.phylip.dist";
385 outputNames.push_back(phylipFileName); outputTypes["phylip"].push_back(phylipFileName);
387 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted.column.dist";
388 outputNames.push_back(phylipFileName); outputTypes["column"].push_back(phylipFileName);
392 m->openOutputFile(phylipFileName, out);
394 if ((outputForm == "lt") || (outputForm == "square")) {
396 out << globaldata->Groups.size() << endl;
399 //make matrix with scores in it
400 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
401 for (int i = 0; i < globaldata->Groups.size(); i++) {
402 dists[i].resize(globaldata->Groups.size(), 0.0);
405 //flip it so you can print it
407 for (int r=0; r<globaldata->Groups.size(); r++) {
408 for (int l = 0; l < r; l++) {
409 dists[r][l] = utreeScores[count][0];
410 dists[l][r] = utreeScores[count][0];
416 for (int r=0; r<globaldata->Groups.size(); r++) {
418 string name = globaldata->Groups[r];
419 if (name.length() < 10) { //pad with spaces to make compatible
420 while (name.length() < 10) { name += " "; }
423 if (outputForm == "lt") {
427 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
429 }else if (outputForm == "square") {
433 for (int l = 0; l < globaldata->Groups.size(); l++) { out << dists[r][l] << '\t'; }
437 for (int l = 0; l < r; l++) {
438 string otherName = globaldata->Groups[l];
439 if (otherName.length() < 10) { //pad with spaces to make compatible
440 while (otherName.length() < 10) { otherName += " "; }
443 out << name << '\t' << otherName << dists[r][l] << endl;
449 catch(exception& e) {
450 m->errorOut(e, "UnifracUnweightedCommand", "createPhylipFile");
454 /***********************************************************/