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 //initialize outputTypes
28 vector<string> tempOutNames;
29 outputTypes["unweighted"] = tempOutNames;
30 outputTypes["uwsummary"] = tempOutNames;
31 outputTypes["phylip"] = tempOutNames;
34 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
38 //**********************************************************************************************************************
39 vector<string> UnifracUnweightedCommand::getRequiredParameters(){
41 vector<string> myArray;
45 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredParameters");
49 //**********************************************************************************************************************
50 vector<string> UnifracUnweightedCommand::getRequiredFiles(){
52 string Array[] = {"tree","group"};
53 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
58 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredFiles");
62 /***********************************************************/
63 UnifracUnweightedCommand::UnifracUnweightedCommand(string option) {
65 globaldata = GlobalData::getInstance();
69 //allow user to run help
70 if(option == "help") { help(); abort = true; }
73 //valid paramters for this command
74 string Array[] = {"groups","iters","distance","random", "processors","outputdir","inputdir"};
75 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
77 OptionParser parser(option);
78 map<string,string> parameters = parser.getParameters();
80 ValidParameters validParameter;
82 //check to make sure all parameters are valid for command
83 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
84 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
87 //initialize outputTypes
88 vector<string> tempOutNames;
89 outputTypes["unweighted"] = tempOutNames;
90 outputTypes["uwsummary"] = tempOutNames;
91 outputTypes["phylip"] = tempOutNames;
93 if (globaldata->gTree.size() == 0) {//no trees were read
94 m->mothurOut("You must execute the read.tree command, before you may execute the unifrac.unweighted command."); m->mothurOutEndLine(); abort = true; }
96 //if the user changes the output directory command factory will send this info to us in the output parameter
97 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
99 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
102 //check for optional parameter and set defaults
103 // ...at some point should added some additional type checking...
104 groups = validParameter.validFile(parameters, "groups", false);
105 if (groups == "not found") { groups = ""; }
107 m->splitAtDash(groups, Groups);
108 globaldata->Groups = Groups;
111 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
112 convert(itersString, iters);
114 string temp = validParameter.validFile(parameters, "distance", false); if (temp == "not found") { temp = "false"; }
115 phylip = m->isTrue(temp);
117 temp = validParameter.validFile(parameters, "random", false); if (temp == "not found") { temp = "f"; }
118 random = m->isTrue(temp);
120 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
121 convert(temp, processors);
123 if (!random) { iters = 0; } //turn off random calcs
125 //if user selects distance = true and no groups it won't calc the pairwise
126 if ((phylip) && (Groups.size() == 0)) {
128 m->splitAtDash(groups, Groups);
129 globaldata->Groups = Groups;
132 if (abort == false) {
133 T = globaldata->gTree;
134 tmap = globaldata->gTreemap;
135 sumFile = outputDir + m->getSimpleName(globaldata->getTreeFile()) + ".uwsummary";
136 outputNames.push_back(sumFile); outputTypes["uwsummary"].push_back(sumFile);
137 m->openOutputFile(sumFile, outSum);
139 util = new SharedUtil();
140 util->setGroups(globaldata->Groups, tmap->namesOfGroups, allGroups, numGroups, "unweighted"); //sets the groups the user wants to analyze
141 util->getCombos(groupComb, globaldata->Groups, numComp);
143 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
145 unweighted = new Unweighted(tmap);
152 catch(exception& e) {
153 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
158 //**********************************************************************************************************************
160 void UnifracUnweightedCommand::help(){
162 m->mothurOut("The unifrac.unweighted command can only be executed after a successful read.tree command.\n");
163 m->mothurOut("The unifrac.unweighted command parameters are groups, iters, distance, processors and random. No parameters are required.\n");
164 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");
165 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");
166 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
167 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");
168 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
169 m->mothurOut("The unifrac.unweighted command should be in the following format: unifrac.unweighted(groups=yourGroups, iters=yourIters).\n");
170 m->mothurOut("Example unifrac.unweighted(groups=A-B-C, iters=500).\n");
171 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
172 m->mothurOut("The unifrac.unweighted command output two files: .unweighted and .uwsummary their descriptions are in the manual.\n");
173 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
175 catch(exception& e) {
176 m->errorOut(e, "UnifracUnweightedCommand", "help");
182 /***********************************************************/
183 int UnifracUnweightedCommand::execute() {
186 if (abort == true) { return 0; }
188 int start = time(NULL);
190 userData.resize(numComp,0); //data[0] = unweightedscore
191 randomData.resize(numComp,0); //data[0] = unweightedscore
192 //create new tree with same num nodes and leaves as users
194 outSum << "Tree#" << '\t' << "Groups" << '\t' << "UWScore" <<'\t' << "UWSig" << endl;
195 m->mothurOut("Tree#\tGroups\tUWScore\tUWSig"); m->mothurOutEndLine();
197 //get pscores for users trees
198 for (int i = 0; i < T.size(); i++) {
199 if (m->control_pressed) {
201 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
208 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted", itersString);
209 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted");
210 outputTypes["unweighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted");
214 //get unweighted for users tree
215 rscoreFreq.resize(numComp);
216 rCumul.resize(numComp);
217 utreeScores.resize(numComp);
218 UWScoreSig.resize(numComp);
220 userData = unweighted->getValues(T[i], processors, outputDir); //userData[0] = unweightedscore
222 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; }
224 //output scores for each combination
225 for(int k = 0; k < numComp; k++) {
227 utreeScores[k].push_back(userData[k]);
229 //add users score to validscores
230 validScores[userData[k]] = userData[k];
233 //get unweighted scores for random trees - if random is false iters = 0
234 for (int j = 0; j < iters; j++) {
236 //we need a different getValues because when we swap the labels we only want to swap those in each pairwise comparison
237 randomData = unweighted->getValues(T[i], "", "", processors, outputDir);
239 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; }
241 for(int k = 0; k < numComp; k++) {
242 //add trees unweighted score to map of scores
243 map<float,float>::iterator it = rscoreFreq[k].find(randomData[k]);
244 if (it != rscoreFreq[k].end()) {//already have that score
245 rscoreFreq[k][randomData[k]]++;
246 }else{//first time we have seen this score
247 rscoreFreq[k][randomData[k]] = 1;
250 //add randoms score to validscores
251 validScores[randomData[k]] = randomData[k];
255 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();
258 for(int a = 0; a < numComp; a++) {
259 float rcumul = 1.0000;
262 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
263 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
264 //make rscoreFreq map and rCumul
265 map<float,float>::iterator it2 = rscoreFreq[a].find(it->first);
266 rCumul[a][it->first] = rcumul;
267 //get percentage of random trees with that info
268 if (it2 != rscoreFreq[a].end()) { rscoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
269 else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
271 UWScoreSig[a].push_back(rCumul[a][userData[a]]);
272 }else { UWScoreSig[a].push_back(0.0); }
276 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; }
279 printUWSummaryFile(i);
280 if (random) { printUnweightedFile(); delete output; }
281 if (phylip) { createPhylipFile(i); }
293 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
295 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.unweighted."); m->mothurOutEndLine();
297 m->mothurOutEndLine();
298 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
299 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
300 m->mothurOutEndLine();
305 catch(exception& e) {
306 m->errorOut(e, "UnifracUnweightedCommand", "execute");
310 /***********************************************************/
311 void UnifracUnweightedCommand::printUnweightedFile() {
316 tags.push_back("Score");
317 tags.push_back("RandFreq"); tags.push_back("RandCumul");
319 for(int a = 0; a < numComp; a++) {
320 output->initFile(groupComb[a], tags);
322 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
323 data.push_back(it->first); data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
324 output->output(data);
330 catch(exception& e) {
331 m->errorOut(e, "UnifracUnweightedCommand", "printUnweightedFile");
336 /***********************************************************/
337 void UnifracUnweightedCommand::printUWSummaryFile(int i) {
341 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
345 for(int a = 0; a < numComp; a++) {
346 outSum << i+1 << '\t';
347 m->mothurOut(toString(i+1) + "\t");
350 if (UWScoreSig[a][0] > (1/(float)iters)) {
351 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
352 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
353 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t" + toString(UWScoreSig[a][0])+ "\n");
355 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
356 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
357 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t<" + toString((1/float(iters))) + "\n");
360 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
361 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
362 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t0.00\n");
367 catch(exception& e) {
368 m->errorOut(e, "UnifracUnweightedCommand", "printUWSummaryFile");
372 /***********************************************************/
373 void UnifracUnweightedCommand::createPhylipFile(int i) {
375 string phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted.dist";
376 outputNames.push_back(phylipFileName); outputTypes["phylip"].push_back(phylipFileName);
379 m->openOutputFile(phylipFileName, out);
382 out << globaldata->Groups.size() << endl;
384 //make matrix with scores in it
385 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
386 for (int i = 0; i < globaldata->Groups.size(); i++) {
387 dists[i].resize(globaldata->Groups.size(), 0.0);
390 //flip it so you can print it
392 for (int r=0; r<globaldata->Groups.size(); r++) {
393 for (int l = r+1; l < globaldata->Groups.size(); l++) {
394 dists[r][l] = utreeScores[count][0];
395 dists[l][r] = utreeScores[count][0];
401 for (int r=0; r<globaldata->Groups.size(); r++) {
403 string name = globaldata->Groups[r];
404 if (name.length() < 10) { //pad with spaces to make compatible
405 while (name.length() < 10) { name += " "; }
410 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
415 catch(exception& e) {
416 m->errorOut(e, "UnifracUnweightedCommand", "createPhylipFile");
420 /***********************************************************/