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"};
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 //check for optional parameter and set defaults
41 // ...at some point should added some additional type checking...
42 groups = validParameter.validFile(parameters, "groups", false);
43 if (groups == "not found") { groups = ""; }
45 splitAtDash(groups, Groups);
46 globaldata->Groups = Groups;
49 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
50 convert(itersString, iters);
52 string temp = validParameter.validFile(parameters, "distance", false); if (temp == "not found") { temp = "false"; }
53 phylip = isTrue(temp);
55 temp = validParameter.validFile(parameters, "random", false); if (temp == "not found") { temp = "true"; }
56 random = isTrue(temp);
58 if (!random) { iters = 0; } //turn off random calcs
62 T = globaldata->gTree;
63 tmap = globaldata->gTreemap;
64 sumFile = globaldata->getTreeFile() + ".wsummary";
65 openOutputFile(sumFile, outSum);
67 util = new SharedUtil();
68 string s; //to make work with setgroups
69 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted"); //sets the groups the user wants to analyze
70 util->getCombos(groupComb, globaldata->Groups, numComp);
72 weighted = new Weighted(tmap);
80 errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
84 //**********************************************************************************************************************
86 void UnifracWeightedCommand::help(){
88 mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
89 mothurOut("The unifrac.weighted command parameters are groups, iters, distance and random. No parameters are required.\n");
90 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");
91 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");
92 mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
93 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");
94 mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
95 mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
96 mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
97 mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
98 mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
100 catch(exception& e) {
101 errorOut(e, "UnifracWeightedCommand", "help");
106 /***********************************************************/
107 int UnifracWeightedCommand::execute() {
110 if (abort == true) { return 0; }
113 if (random) { reading = new Progress("Comparing to random:", iters); }
115 //get weighted for users tree
116 userData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
117 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
119 //create new tree with same num nodes and leaves as users
122 //get weighted scores for users trees
123 for (int i = 0; i < T.size(); i++) {
125 rScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
126 uScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
128 if (random) { output = new ColumnFile(globaldata->getTreeFile() + toString(i+1) + ".weighted", itersString); }
130 userData = weighted->getValues(T[i]); //userData[0] = weightedscore
133 for (int s=0; s<numComp; s++) {
134 //add users score to vector of user scores
135 uScores[s].push_back(userData[s]);
137 //save users tree score for summary file
138 utreeScores.push_back(userData[s]);
141 //get scores for random trees
142 for (int j = 0; j < iters; j++) {
144 for (int r=0; r<numGroups; r++) {
145 for (int l = r+1; l < numGroups; l++) {
147 randT->getCopy(T[i]);
149 //create a random tree with same topology as T[i], but different labels
150 randT->assembleRandomUnifracTree(globaldata->Groups[r], globaldata->Groups[l]);
151 //get wscore of random tree
152 randomData = weighted->getValues(randT, globaldata->Groups[r], globaldata->Groups[l]);
155 rScores[count].push_back(randomData[0]);
160 //update progress bar
165 //removeValidScoresDuplicates();
166 //find the signifigance of the score for summary file
168 for (int f = 0; f < numComp; f++) {
170 sort(rScores[f].begin(), rScores[f].end());
172 //the index of the score higher than yours is returned
173 //so if you have 1000 random trees the index returned is 100
174 //then there are 900 trees with a score greater then you.
175 //giving you a signifigance of 0.900
176 int index = findIndex(userData[f], f); if (index == -1) { mothurOut("error in UnifracWeightedCommand"); mothurOutEndLine(); exit(1); } //error code
178 //the signifigance is the number of trees with the users score or higher
179 WScoreSig.push_back((iters-index)/(float)iters);
182 //out << "Tree# " << i << endl;
183 calculateFreqsCumuls();
195 //finish progress bar
196 if (random) { reading->finish(); delete reading; }
200 if (phylip) { createPhylipFile(); }
202 //clear out users groups
203 globaldata->Groups.clear();
210 catch(exception& e) {
211 errorOut(e, "UnifracWeightedCommand", "execute");
215 /***********************************************************/
216 void UnifracWeightedCommand::printWeightedFile() {
220 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
222 for(int a = 0; a < numComp; a++) {
223 output->initFile(groupComb[a], tags);
225 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
226 data.push_back(it->first); data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
227 output->output(data);
233 catch(exception& e) {
234 errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
240 /***********************************************************/
241 void UnifracWeightedCommand::printWSummaryFile() {
244 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" << endl;
245 mothurOut("Tree#\tGroups\tWScore\tWSig"); mothurOutEndLine();
248 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
252 for (int i = 0; i < T.size(); i++) {
253 for (int j = 0; j < numComp; j++) {
255 if (WScoreSig[count] > (1/(float)iters)) {
256 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
257 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
258 mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" + toString(WScoreSig[count])); mothurOutEndLine();
260 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
261 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
262 mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" + toString((1/float(iters)))); mothurOutEndLine();
265 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
266 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
267 mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00"); mothurOutEndLine();
274 catch(exception& e) {
275 errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
279 /***********************************************************/
280 void UnifracWeightedCommand::createPhylipFile() {
284 for (int i = 0; i < T.size(); i++) {
286 string phylipFileName = globaldata->getTreeFile() + toString(i+1) + ".weighted.dist";
288 openOutputFile(phylipFileName, out);
291 out << globaldata->Groups.size() << endl;
293 //make matrix with scores in it
294 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
295 for (int i = 0; i < globaldata->Groups.size(); i++) {
296 dists[i].resize(globaldata->Groups.size(), 0.0);
299 //flip it so you can print it
300 for (int r=0; r<globaldata->Groups.size(); r++) {
301 for (int l = r+1; l < globaldata->Groups.size(); l++) {
302 dists[r][l] = (1.0 - utreeScores[count]);
303 dists[l][r] = (1.0 - utreeScores[count]);
309 for (int r=0; r<globaldata->Groups.size(); r++) {
311 string name = globaldata->Groups[r];
312 if (name.length() < 10) { //pad with spaces to make compatible
313 while (name.length() < 10) { name += " "; }
318 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
324 catch(exception& e) {
325 errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
329 /***********************************************************/
330 int UnifracWeightedCommand::findIndex(float score, int index) {
332 for (int i = 0; i < rScores[index].size(); i++) {
333 if (rScores[index][i] >= score) { return i; }
335 return rScores[index].size();
337 catch(exception& e) {
338 errorOut(e, "UnifracWeightedCommand", "findIndex");
343 /***********************************************************/
345 void UnifracWeightedCommand::calculateFreqsCumuls() {
347 //clear out old tree values
349 rScoreFreq.resize(numComp);
351 rCumul.resize(numComp);
354 //calculate frequency
355 for (int f = 0; f < numComp; f++) {
356 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...
357 validScores[rScores[f][i]] = rScores[f][i];
358 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
359 if (it != rScoreFreq[f].end()) {
360 rScoreFreq[f][rScores[f][i]]++;
362 rScoreFreq[f][rScores[f][i]] = 1;
368 for(int a = 0; a < numComp; a++) {
369 float rcumul = 1.0000;
370 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
371 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
372 //make rscoreFreq map and rCumul
373 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
374 rCumul[a][it->first] = rcumul;
375 //get percentage of random trees with that info
376 if (it2 != rScoreFreq[a].end()) { rScoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
377 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
382 catch(exception& e) {
383 errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
388 /***********************************************************/