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 mothurOut("You must execute the read.tree command, before you may execute the unifrac.weighted command."); 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);
73 util = new SharedUtil();
74 string s; //to make work with setgroups
75 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted"); //sets the groups the user wants to analyze
76 util->getCombos(groupComb, globaldata->Groups, numComp);
78 weighted = new Weighted(tmap);
86 errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
90 //**********************************************************************************************************************
92 void UnifracWeightedCommand::help(){
94 mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
95 mothurOut("The unifrac.weighted command parameters are groups, iters, distance and random. No parameters are required.\n");
96 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");
97 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");
98 mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
99 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");
100 mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
101 mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
102 mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
103 mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
104 mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
106 catch(exception& e) {
107 errorOut(e, "UnifracWeightedCommand", "help");
112 /***********************************************************/
113 int UnifracWeightedCommand::execute() {
116 if (abort == true) { return 0; }
119 if (random) { reading = new Progress("Comparing to random:", iters); }
121 //get weighted for users tree
122 userData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
123 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
125 //create new tree with same num nodes and leaves as users
128 //get weighted scores for users trees
129 for (int i = 0; i < T.size(); i++) {
131 rScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
132 uScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
134 if (random) { output = new ColumnFile(outputDir + getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted", itersString); }
136 userData = weighted->getValues(T[i]); //userData[0] = weightedscore
139 for (int s=0; s<numComp; s++) {
140 //add users score to vector of user scores
141 uScores[s].push_back(userData[s]);
143 //save users tree score for summary file
144 utreeScores.push_back(userData[s]);
147 //get scores for random trees
148 for (int j = 0; j < iters; j++) {
150 for (int r=0; r<numGroups; r++) {
151 for (int l = r+1; l < numGroups; l++) {
153 randT->getCopy(T[i]);
155 //create a random tree with same topology as T[i], but different labels
156 randT->assembleRandomUnifracTree(globaldata->Groups[r], globaldata->Groups[l]);
157 //get wscore of random tree
158 randomData = weighted->getValues(randT, globaldata->Groups[r], globaldata->Groups[l]);
161 rScores[count].push_back(randomData[0]);
166 //update progress bar
171 //removeValidScoresDuplicates();
172 //find the signifigance of the score for summary file
174 for (int f = 0; f < numComp; f++) {
176 sort(rScores[f].begin(), rScores[f].end());
178 //the index of the score higher than yours is returned
179 //so if you have 1000 random trees the index returned is 100
180 //then there are 900 trees with a score greater then you.
181 //giving you a signifigance of 0.900
182 int index = findIndex(userData[f], f); if (index == -1) { mothurOut("error in UnifracWeightedCommand"); mothurOutEndLine(); exit(1); } //error code
184 //the signifigance is the number of trees with the users score or higher
185 WScoreSig.push_back((iters-index)/(float)iters);
188 //out << "Tree# " << i << endl;
189 calculateFreqsCumuls();
201 //finish progress bar
202 if (random) { reading->finish(); delete reading; }
206 if (phylip) { createPhylipFile(); }
208 //clear out users groups
209 globaldata->Groups.clear();
216 catch(exception& e) {
217 errorOut(e, "UnifracWeightedCommand", "execute");
221 /***********************************************************/
222 void UnifracWeightedCommand::printWeightedFile() {
226 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
228 for(int a = 0; a < numComp; a++) {
229 output->initFile(groupComb[a], tags);
231 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
232 data.push_back(it->first); data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
233 output->output(data);
239 catch(exception& e) {
240 errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
246 /***********************************************************/
247 void UnifracWeightedCommand::printWSummaryFile() {
250 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" << endl;
251 mothurOut("Tree#\tGroups\tWScore\tWSig"); mothurOutEndLine();
254 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
258 for (int i = 0; i < T.size(); i++) {
259 for (int j = 0; j < numComp; j++) {
261 if (WScoreSig[count] > (1/(float)iters)) {
262 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
263 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
264 mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" + toString(WScoreSig[count])); mothurOutEndLine();
266 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
267 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
268 mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" + toString((1/float(iters)))); mothurOutEndLine();
271 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
272 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
273 mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00"); mothurOutEndLine();
280 catch(exception& e) {
281 errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
285 /***********************************************************/
286 void UnifracWeightedCommand::createPhylipFile() {
290 for (int i = 0; i < T.size(); i++) {
292 string phylipFileName = outputDir + getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted.dist";
294 openOutputFile(phylipFileName, out);
297 out << globaldata->Groups.size() << endl;
299 //make matrix with scores in it
300 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
301 for (int i = 0; i < globaldata->Groups.size(); i++) {
302 dists[i].resize(globaldata->Groups.size(), 0.0);
305 //flip it so you can print it
306 for (int r=0; r<globaldata->Groups.size(); r++) {
307 for (int l = r+1; l < globaldata->Groups.size(); l++) {
308 dists[r][l] = (1.0 - utreeScores[count]);
309 dists[l][r] = (1.0 - utreeScores[count]);
315 for (int r=0; r<globaldata->Groups.size(); r++) {
317 string name = globaldata->Groups[r];
318 if (name.length() < 10) { //pad with spaces to make compatible
319 while (name.length() < 10) { name += " "; }
324 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
330 catch(exception& e) {
331 errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
335 /***********************************************************/
336 int UnifracWeightedCommand::findIndex(float score, int index) {
338 for (int i = 0; i < rScores[index].size(); i++) {
339 if (rScores[index][i] >= score) { return i; }
341 return rScores[index].size();
343 catch(exception& e) {
344 errorOut(e, "UnifracWeightedCommand", "findIndex");
349 /***********************************************************/
351 void UnifracWeightedCommand::calculateFreqsCumuls() {
353 //clear out old tree values
355 rScoreFreq.resize(numComp);
357 rCumul.resize(numComp);
360 //calculate frequency
361 for (int f = 0; f < numComp; f++) {
362 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...
363 validScores[rScores[f][i]] = rScores[f][i];
364 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
365 if (it != rScoreFreq[f].end()) {
366 rScoreFreq[f][rScores[f][i]]++;
368 rScoreFreq[f][rScores[f][i]] = 1;
374 for(int a = 0; a < numComp; a++) {
375 float rcumul = 1.0000;
376 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
377 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
378 //make rscoreFreq map and rCumul
379 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
380 rCumul[a][it->first] = rcumul;
381 //get percentage of random trees with that info
382 if (it2 != rScoreFreq[a].end()) { rScoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
383 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
388 catch(exception& e) {
389 errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
394 /***********************************************************/