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();
29 //initialize outputTypes
30 vector<string> tempOutNames;
31 outputTypes["unweighted"] = tempOutNames;
32 outputTypes["uwsummary"] = tempOutNames;
33 outputTypes["phylip"] = tempOutNames;
34 outputTypes["column"] = tempOutNames;
37 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
41 //**********************************************************************************************************************
42 vector<string> UnifracUnweightedCommand::getRequiredParameters(){
44 vector<string> myArray;
48 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredParameters");
52 //**********************************************************************************************************************
53 vector<string> UnifracUnweightedCommand::getRequiredFiles(){
55 string Array[] = {"tree","group"};
56 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
61 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredFiles");
65 /***********************************************************/
66 UnifracUnweightedCommand::UnifracUnweightedCommand(string option) {
68 globaldata = GlobalData::getInstance();
72 //allow user to run help
73 if(option == "help") { help(); abort = true; }
76 //valid paramters for this command
77 string Array[] = {"groups","iters","distance","random", "processors","outputdir","inputdir"};
78 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
80 OptionParser parser(option);
81 map<string,string> parameters = parser.getParameters();
83 ValidParameters validParameter;
85 //check to make sure all parameters are valid for command
86 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
87 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
90 //initialize outputTypes
91 vector<string> tempOutNames;
92 outputTypes["unweighted"] = tempOutNames;
93 outputTypes["uwsummary"] = tempOutNames;
94 outputTypes["phylip"] = tempOutNames;
95 outputTypes["column"] = tempOutNames;
97 if (globaldata->gTree.size() == 0) {//no trees were read
98 m->mothurOut("You must execute the read.tree command, before you may execute the unifrac.unweighted command."); m->mothurOutEndLine(); abort = true; }
100 //if the user changes the output directory command factory will send this info to us in the output parameter
101 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
103 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
106 //check for optional parameter and set defaults
107 // ...at some point should added some additional type checking...
108 groups = validParameter.validFile(parameters, "groups", false);
109 if (groups == "not found") { groups = ""; }
111 m->splitAtDash(groups, Groups);
112 globaldata->Groups = Groups;
115 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
116 convert(itersString, iters);
118 string temp = validParameter.validFile(parameters, "distance", false);
119 if (temp == "not found") { phylip = false; outputForm = ""; }
121 if ((temp == "lt") || (temp == "column") || (temp == "square")) { phylip = true; outputForm = temp; }
122 else { m->mothurOut("Options for distance are: lt, square, or column. Using lt."); m->mothurOutEndLine(); phylip = true; outputForm = "lt"; }
125 temp = validParameter.validFile(parameters, "random", false); if (temp == "not found") { temp = "f"; }
126 random = m->isTrue(temp);
128 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
129 convert(temp, processors);
131 if (!random) { iters = 0; } //turn off random calcs
133 //if user selects distance = true and no groups it won't calc the pairwise
134 if ((phylip) && (Groups.size() == 0)) {
136 m->splitAtDash(groups, Groups);
137 globaldata->Groups = Groups;
140 if (abort == false) {
141 T = globaldata->gTree;
142 tmap = globaldata->gTreemap;
143 sumFile = outputDir + m->getSimpleName(globaldata->getTreeFile()) + ".uwsummary";
144 outputNames.push_back(sumFile); outputTypes["uwsummary"].push_back(sumFile);
145 m->openOutputFile(sumFile, outSum);
147 util = new SharedUtil();
148 util->setGroups(globaldata->Groups, tmap->namesOfGroups, allGroups, numGroups, "unweighted"); //sets the groups the user wants to analyze
149 util->getCombos(groupComb, globaldata->Groups, numComp);
151 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
153 unweighted = new Unweighted(tmap);
160 catch(exception& e) {
161 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
166 //**********************************************************************************************************************
168 void UnifracUnweightedCommand::help(){
170 m->mothurOut("The unifrac.unweighted command can only be executed after a successful read.tree command.\n");
171 m->mothurOut("The unifrac.unweighted command parameters are groups, iters, distance, processors and random. No parameters are required.\n");
172 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");
173 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");
174 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");
175 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");
176 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
177 m->mothurOut("The unifrac.unweighted command should be in the following format: unifrac.unweighted(groups=yourGroups, iters=yourIters).\n");
178 m->mothurOut("Example unifrac.unweighted(groups=A-B-C, iters=500).\n");
179 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
180 m->mothurOut("The unifrac.unweighted command output two files: .unweighted and .uwsummary their descriptions are in the manual.\n");
181 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
183 catch(exception& e) {
184 m->errorOut(e, "UnifracUnweightedCommand", "help");
190 /***********************************************************/
191 int UnifracUnweightedCommand::execute() {
194 if (abort == true) { return 0; }
196 int start = time(NULL);
198 userData.resize(numComp,0); //data[0] = unweightedscore
199 randomData.resize(numComp,0); //data[0] = unweightedscore
200 //create new tree with same num nodes and leaves as users
202 outSum << "Tree#" << '\t' << "Groups" << '\t' << "UWScore" <<'\t' << "UWSig" << endl;
203 m->mothurOut("Tree#\tGroups\tUWScore\tUWSig"); m->mothurOutEndLine();
205 //get pscores for users trees
206 for (int i = 0; i < T.size(); i++) {
207 if (m->control_pressed) {
209 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
216 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted", itersString);
217 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted");
218 outputTypes["unweighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted");
222 //get unweighted for users tree
223 rscoreFreq.resize(numComp);
224 rCumul.resize(numComp);
225 utreeScores.resize(numComp);
226 UWScoreSig.resize(numComp);
228 userData = unweighted->getValues(T[i], processors, outputDir); //userData[0] = unweightedscore
230 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; }
232 //output scores for each combination
233 for(int k = 0; k < numComp; k++) {
235 utreeScores[k].push_back(userData[k]);
237 //add users score to validscores
238 validScores[userData[k]] = userData[k];
241 //get unweighted scores for random trees - if random is false iters = 0
242 for (int j = 0; j < iters; j++) {
244 //we need a different getValues because when we swap the labels we only want to swap those in each pairwise comparison
245 randomData = unweighted->getValues(T[i], "", "", processors, outputDir);
247 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; }
249 for(int k = 0; k < numComp; k++) {
250 //add trees unweighted score to map of scores
251 map<float,float>::iterator it = rscoreFreq[k].find(randomData[k]);
252 if (it != rscoreFreq[k].end()) {//already have that score
253 rscoreFreq[k][randomData[k]]++;
254 }else{//first time we have seen this score
255 rscoreFreq[k][randomData[k]] = 1;
258 //add randoms score to validscores
259 validScores[randomData[k]] = randomData[k];
263 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();
266 for(int a = 0; a < numComp; a++) {
267 float rcumul = 1.0000;
270 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
271 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
272 //make rscoreFreq map and rCumul
273 map<float,float>::iterator it2 = rscoreFreq[a].find(it->first);
274 rCumul[a][it->first] = rcumul;
275 //get percentage of random trees with that info
276 if (it2 != rscoreFreq[a].end()) { rscoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
277 else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
279 UWScoreSig[a].push_back(rCumul[a][userData[a]]);
280 }else { UWScoreSig[a].push_back(0.0); }
284 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; }
287 printUWSummaryFile(i);
288 if (random) { printUnweightedFile(); delete output; }
289 if (phylip) { createPhylipFile(i); }
301 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
303 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.unweighted."); m->mothurOutEndLine();
305 m->mothurOutEndLine();
306 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
307 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
308 m->mothurOutEndLine();
313 catch(exception& e) {
314 m->errorOut(e, "UnifracUnweightedCommand", "execute");
318 /***********************************************************/
319 void UnifracUnweightedCommand::printUnweightedFile() {
324 tags.push_back("Score");
325 tags.push_back("RandFreq"); tags.push_back("RandCumul");
327 for(int a = 0; a < numComp; a++) {
328 output->initFile(groupComb[a], tags);
330 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
331 data.push_back(it->first); data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
332 output->output(data);
338 catch(exception& e) {
339 m->errorOut(e, "UnifracUnweightedCommand", "printUnweightedFile");
344 /***********************************************************/
345 void UnifracUnweightedCommand::printUWSummaryFile(int i) {
349 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
353 for(int a = 0; a < numComp; a++) {
354 outSum << i+1 << '\t';
355 m->mothurOut(toString(i+1) + "\t");
358 if (UWScoreSig[a][0] > (1/(float)iters)) {
359 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
360 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
361 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t" + toString(UWScoreSig[a][0])+ "\n");
363 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
364 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
365 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t<" + toString((1/float(iters))) + "\n");
368 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
369 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
370 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t0.00\n");
375 catch(exception& e) {
376 m->errorOut(e, "UnifracUnweightedCommand", "printUWSummaryFile");
380 /***********************************************************/
381 void UnifracUnweightedCommand::createPhylipFile(int i) {
383 string phylipFileName;
384 if ((outputForm == "lt") || (outputForm == "square")) {
385 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted.phylip.dist";
386 outputNames.push_back(phylipFileName); outputTypes["phylip"].push_back(phylipFileName);
388 phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted.column.dist";
389 outputNames.push_back(phylipFileName); outputTypes["column"].push_back(phylipFileName);
393 m->openOutputFile(phylipFileName, out);
395 if ((outputForm == "lt") || (outputForm == "square")) {
397 out << globaldata->Groups.size() << endl;
400 //make matrix with scores in it
401 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
402 for (int i = 0; i < globaldata->Groups.size(); i++) {
403 dists[i].resize(globaldata->Groups.size(), 0.0);
406 //flip it so you can print it
408 for (int r=0; r<globaldata->Groups.size(); r++) {
409 for (int l = 0; l < r; l++) {
410 dists[r][l] = utreeScores[count][0];
411 dists[l][r] = utreeScores[count][0];
417 for (int r=0; r<globaldata->Groups.size(); r++) {
419 string name = globaldata->Groups[r];
420 if (name.length() < 10) { //pad with spaces to make compatible
421 while (name.length() < 10) { name += " "; }
424 if (outputForm == "lt") {
428 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
430 }else if (outputForm == "square") {
434 for (int l = 0; l < globaldata->Groups.size(); l++) { out << dists[r][l] << '\t'; }
438 for (int l = 0; l < r; l++) {
439 string otherName = globaldata->Groups[l];
440 if (otherName.length() < 10) { //pad with spaces to make compatible
441 while (otherName.length() < 10) { otherName += " "; }
444 out << name << '\t' << otherName << dists[r][l] << endl;
450 catch(exception& e) {
451 m->errorOut(e, "UnifracUnweightedCommand", "createPhylipFile");
455 /***********************************************************/