2 * unifracweightedcommand.cpp
5 * Created by Sarah Westcott on 2/9/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "unifracweightedcommand.h"
12 /***********************************************************/
13 UnifracWeightedCommand::UnifracWeightedCommand(string option) {
15 globaldata = GlobalData::getInstance();
19 //allow user to run help
20 if(option == "help") { help(); abort = true; }
23 //valid paramters for this command
24 string Array[] = {"groups","iters","distance","random","outputdir","inputdir"};
25 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
27 OptionParser parser(option);
28 map<string,string> parameters=parser.getParameters();
30 ValidParameters validParameter;
32 //check to make sure all parameters are valid for command
33 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
34 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
37 if (globaldata->gTree.size() == 0) {//no trees were read
38 m->mothurOut("You must execute the read.tree command, before you may execute the unifrac.weighted command."); m->mothurOutEndLine(); abort = true; }
40 //if the user changes the output directory command factory will send this info to us in the output parameter
41 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
43 outputDir += hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
46 //check for optional parameter and set defaults
47 // ...at some point should added some additional type checking...
48 groups = validParameter.validFile(parameters, "groups", false);
49 if (groups == "not found") { groups = ""; }
51 splitAtDash(groups, Groups);
52 globaldata->Groups = Groups;
55 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
56 convert(itersString, iters);
58 string temp = validParameter.validFile(parameters, "distance", false); if (temp == "not found") { temp = "false"; }
59 phylip = isTrue(temp);
61 temp = validParameter.validFile(parameters, "random", false); if (temp == "not found") { temp = "true"; }
62 random = isTrue(temp);
64 if (!random) { iters = 0; } //turn off random calcs
68 T = globaldata->gTree;
69 tmap = globaldata->gTreemap;
70 sumFile = outputDir + getSimpleName(globaldata->getTreeFile()) + ".wsummary";
71 openOutputFile(sumFile, outSum);
72 outputNames.push_back(sumFile);
74 util = new SharedUtil();
75 string s; //to make work with setgroups
76 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted"); //sets the groups the user wants to analyze
77 util->getCombos(groupComb, globaldata->Groups, numComp);
79 weighted = new Weighted(tmap);
87 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
91 //**********************************************************************************************************************
93 void UnifracWeightedCommand::help(){
95 m->mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
96 m->mothurOut("The unifrac.weighted command parameters are groups, iters, distance and random. No parameters are required.\n");
97 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 2 valid groups.\n");
98 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");
99 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
100 m->mothurOut("The random parameter allows you to shut off the comparison to random trees. The default is true, meaning compare your trees with randomly generated trees.\n");
101 m->mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
102 m->mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
103 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
104 m->mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
105 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
107 catch(exception& e) {
108 m->errorOut(e, "UnifracWeightedCommand", "help");
113 /***********************************************************/
114 int UnifracWeightedCommand::execute() {
117 if (abort == true) { return 0; }
120 if (random) { reading = new Progress("Comparing to random:", iters); }
122 //get weighted for users tree
123 userData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
124 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
126 //create new tree with same num nodes and leaves as users
129 //get weighted scores for users trees
130 for (int i = 0; i < T.size(); i++) {
132 if (m->control_pressed) {
134 if (random) { delete reading; }
136 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
141 rScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
142 uScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
145 output = new ColumnFile(outputDir + getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted", itersString);
146 outputNames.push_back(outputDir + getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted");
149 userData = weighted->getValues(T[i]); //userData[0] = weightedscore
151 if (m->control_pressed) {
153 if (random) { delete reading; delete output; }
155 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
161 for (int s=0; s<numComp; s++) {
162 //add users score to vector of user scores
163 uScores[s].push_back(userData[s]);
165 //save users tree score for summary file
166 utreeScores.push_back(userData[s]);
169 //get scores for random trees
170 for (int j = 0; j < iters; j++) {
172 for (int r=0; r<numGroups; r++) {
173 for (int l = r+1; l < numGroups; l++) {
175 randT->getCopy(T[i]);
177 //create a random tree with same topology as T[i], but different labels
178 randT->assembleRandomUnifracTree(globaldata->Groups[r], globaldata->Groups[l]);
180 if (m->control_pressed) {
182 if (random) { delete reading; delete output; }
184 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
189 //get wscore of random tree
190 randomData = weighted->getValues(randT, globaldata->Groups[r], globaldata->Groups[l]);
192 if (m->control_pressed) {
194 if (random) { delete reading; delete output; }
196 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
201 rScores[count].push_back(randomData[0]);
206 //update progress bar
211 //removeValidScoresDuplicates();
212 //find the signifigance of the score for summary file
214 for (int f = 0; f < numComp; f++) {
216 sort(rScores[f].begin(), rScores[f].end());
218 //the index of the score higher than yours is returned
219 //so if you have 1000 random trees the index returned is 100
220 //then there are 900 trees with a score greater then you.
221 //giving you a signifigance of 0.900
222 int index = findIndex(userData[f], f); if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
224 //the signifigance is the number of trees with the users score or higher
225 WScoreSig.push_back((iters-index)/(float)iters);
228 //out << "Tree# " << i << endl;
229 calculateFreqsCumuls();
242 if (m->control_pressed) {
244 if (random) { delete reading; }
246 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
250 //finish progress bar
251 if (random) { reading->finish(); delete reading; }
255 if (phylip) { createPhylipFile(); }
257 //clear out users groups
258 globaldata->Groups.clear();
262 if (m->control_pressed) {
263 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
267 m->mothurOutEndLine();
268 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
269 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
270 m->mothurOutEndLine();
275 catch(exception& e) {
276 m->errorOut(e, "UnifracWeightedCommand", "execute");
280 /***********************************************************/
281 void UnifracWeightedCommand::printWeightedFile() {
285 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
287 for(int a = 0; a < numComp; a++) {
288 output->initFile(groupComb[a], tags);
290 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
291 data.push_back(it->first); data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
292 output->output(data);
298 catch(exception& e) {
299 m->errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
305 /***********************************************************/
306 void UnifracWeightedCommand::printWSummaryFile() {
309 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" << endl;
310 m->mothurOut("Tree#\tGroups\tWScore\tWSig"); m->mothurOutEndLine();
313 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
317 for (int i = 0; i < T.size(); i++) {
318 for (int j = 0; j < numComp; j++) {
320 if (WScoreSig[count] > (1/(float)iters)) {
321 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
322 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
323 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" + toString(WScoreSig[count])); m->mothurOutEndLine();
325 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
326 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
327 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" + toString((1/float(iters)))); m->mothurOutEndLine();
330 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
331 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
332 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00"); m->mothurOutEndLine();
339 catch(exception& e) {
340 m->errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
344 /***********************************************************/
345 void UnifracWeightedCommand::createPhylipFile() {
349 for (int i = 0; i < T.size(); i++) {
351 string phylipFileName = outputDir + getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted.dist";
352 outputNames.push_back(phylipFileName);
354 openOutputFile(phylipFileName, out);
357 out << globaldata->Groups.size() << endl;
359 //make matrix with scores in it
360 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
361 for (int i = 0; i < globaldata->Groups.size(); i++) {
362 dists[i].resize(globaldata->Groups.size(), 0.0);
365 //flip it so you can print it
366 for (int r=0; r<globaldata->Groups.size(); r++) {
367 for (int l = r+1; l < globaldata->Groups.size(); l++) {
368 dists[r][l] = utreeScores[count];
369 dists[l][r] = utreeScores[count];
375 for (int r=0; r<globaldata->Groups.size(); r++) {
377 string name = globaldata->Groups[r];
378 if (name.length() < 10) { //pad with spaces to make compatible
379 while (name.length() < 10) { name += " "; }
384 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
390 catch(exception& e) {
391 m->errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
395 /***********************************************************/
396 int UnifracWeightedCommand::findIndex(float score, int index) {
398 for (int i = 0; i < rScores[index].size(); i++) {
399 if (rScores[index][i] >= score) { return i; }
401 return rScores[index].size();
403 catch(exception& e) {
404 m->errorOut(e, "UnifracWeightedCommand", "findIndex");
409 /***********************************************************/
411 void UnifracWeightedCommand::calculateFreqsCumuls() {
413 //clear out old tree values
415 rScoreFreq.resize(numComp);
417 rCumul.resize(numComp);
420 //calculate frequency
421 for (int f = 0; f < numComp; f++) {
422 for (int i = 0; i < rScores[f].size(); i++) { //looks like 0,0,1,1,1,2,4,7... you want to make a map that say rScoreFreq[0] = 2, rScoreFreq[1] = 3...
423 validScores[rScores[f][i]] = rScores[f][i];
424 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
425 if (it != rScoreFreq[f].end()) {
426 rScoreFreq[f][rScores[f][i]]++;
428 rScoreFreq[f][rScores[f][i]] = 1;
434 for(int a = 0; a < numComp; a++) {
435 float rcumul = 1.0000;
436 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
437 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
438 //make rscoreFreq map and rCumul
439 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
440 rCumul[a][it->first] = rcumul;
441 //get percentage of random trees with that info
442 if (it2 != rScoreFreq[a].end()) { rScoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
443 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
448 catch(exception& e) {
449 m->errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
454 /***********************************************************/