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;
36 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
40 //**********************************************************************************************************************
41 vector<string> UnifracUnweightedCommand::getRequiredParameters(){
43 vector<string> myArray;
47 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredParameters");
51 //**********************************************************************************************************************
52 vector<string> UnifracUnweightedCommand::getRequiredFiles(){
54 string Array[] = {"tree","group"};
55 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
60 m->errorOut(e, "UnifracUnweightedCommand", "getRequiredFiles");
64 /***********************************************************/
65 UnifracUnweightedCommand::UnifracUnweightedCommand(string option) {
67 globaldata = GlobalData::getInstance();
71 //allow user to run help
72 if(option == "help") { help(); abort = true; }
75 //valid paramters for this command
76 string Array[] = {"groups","iters","distance","random", "processors","outputdir","inputdir"};
77 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
79 OptionParser parser(option);
80 map<string,string> parameters = parser.getParameters();
82 ValidParameters validParameter;
84 //check to make sure all parameters are valid for command
85 for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) {
86 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
89 //initialize outputTypes
90 vector<string> tempOutNames;
91 outputTypes["unweighted"] = tempOutNames;
92 outputTypes["uwsummary"] = tempOutNames;
93 outputTypes["phylip"] = tempOutNames;
95 if (globaldata->gTree.size() == 0) {//no trees were read
96 m->mothurOut("You must execute the read.tree command, before you may execute the unifrac.unweighted command."); m->mothurOutEndLine(); abort = true; }
98 //if the user changes the output directory command factory will send this info to us in the output parameter
99 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
101 outputDir += m->hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it
104 //check for optional parameter and set defaults
105 // ...at some point should added some additional type checking...
106 groups = validParameter.validFile(parameters, "groups", false);
107 if (groups == "not found") { groups = ""; }
109 m->splitAtDash(groups, Groups);
110 globaldata->Groups = Groups;
113 itersString = validParameter.validFile(parameters, "iters", false); if (itersString == "not found") { itersString = "1000"; }
114 convert(itersString, iters);
116 string temp = validParameter.validFile(parameters, "distance", false); if (temp == "not found") { temp = "false"; }
117 phylip = m->isTrue(temp);
119 temp = validParameter.validFile(parameters, "random", false); if (temp == "not found") { temp = "f"; }
120 random = m->isTrue(temp);
122 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
123 convert(temp, processors);
125 if (!random) { iters = 0; } //turn off random calcs
127 //if user selects distance = true and no groups it won't calc the pairwise
128 if ((phylip) && (Groups.size() == 0)) {
130 m->splitAtDash(groups, Groups);
131 globaldata->Groups = Groups;
134 if (abort == false) {
135 T = globaldata->gTree;
136 tmap = globaldata->gTreemap;
137 sumFile = outputDir + m->getSimpleName(globaldata->getTreeFile()) + ".uwsummary";
138 outputNames.push_back(sumFile); outputTypes["uwsummary"].push_back(sumFile);
139 m->openOutputFile(sumFile, outSum);
141 util = new SharedUtil();
142 util->setGroups(globaldata->Groups, tmap->namesOfGroups, allGroups, numGroups, "unweighted"); //sets the groups the user wants to analyze
143 util->getCombos(groupComb, globaldata->Groups, numComp);
145 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
147 unweighted = new Unweighted(tmap);
154 catch(exception& e) {
155 m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
160 //**********************************************************************************************************************
162 void UnifracUnweightedCommand::help(){
164 m->mothurOut("The unifrac.unweighted command can only be executed after a successful read.tree command.\n");
165 m->mothurOut("The unifrac.unweighted command parameters are groups, iters, distance, processors and random. No parameters are required.\n");
166 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");
167 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");
168 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
169 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");
170 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
171 m->mothurOut("The unifrac.unweighted command should be in the following format: unifrac.unweighted(groups=yourGroups, iters=yourIters).\n");
172 m->mothurOut("Example unifrac.unweighted(groups=A-B-C, iters=500).\n");
173 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
174 m->mothurOut("The unifrac.unweighted command output two files: .unweighted and .uwsummary their descriptions are in the manual.\n");
175 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
177 catch(exception& e) {
178 m->errorOut(e, "UnifracUnweightedCommand", "help");
184 /***********************************************************/
185 int UnifracUnweightedCommand::execute() {
188 if (abort == true) { return 0; }
190 int start = time(NULL);
192 userData.resize(numComp,0); //data[0] = unweightedscore
193 randomData.resize(numComp,0); //data[0] = unweightedscore
194 //create new tree with same num nodes and leaves as users
196 outSum << "Tree#" << '\t' << "Groups" << '\t' << "UWScore" <<'\t' << "UWSig" << endl;
197 m->mothurOut("Tree#\tGroups\tUWScore\tUWSig"); m->mothurOutEndLine();
199 //get pscores for users trees
200 for (int i = 0; i < T.size(); i++) {
201 if (m->control_pressed) {
203 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
210 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted", itersString);
211 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted");
212 outputTypes["unweighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted");
216 //get unweighted for users tree
217 rscoreFreq.resize(numComp);
218 rCumul.resize(numComp);
219 utreeScores.resize(numComp);
220 UWScoreSig.resize(numComp);
222 userData = unweighted->getValues(T[i], processors, outputDir); //userData[0] = unweightedscore
224 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; }
226 //output scores for each combination
227 for(int k = 0; k < numComp; k++) {
229 utreeScores[k].push_back(userData[k]);
231 //add users score to validscores
232 validScores[userData[k]] = userData[k];
235 //get unweighted scores for random trees - if random is false iters = 0
236 for (int j = 0; j < iters; j++) {
238 //we need a different getValues because when we swap the labels we only want to swap those in each pairwise comparison
239 randomData = unweighted->getValues(T[i], "", "", processors, outputDir);
241 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; }
243 for(int k = 0; k < numComp; k++) {
244 //add trees unweighted score to map of scores
245 map<float,float>::iterator it = rscoreFreq[k].find(randomData[k]);
246 if (it != rscoreFreq[k].end()) {//already have that score
247 rscoreFreq[k][randomData[k]]++;
248 }else{//first time we have seen this score
249 rscoreFreq[k][randomData[k]] = 1;
252 //add randoms score to validscores
253 validScores[randomData[k]] = randomData[k];
257 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();
260 for(int a = 0; a < numComp; a++) {
261 float rcumul = 1.0000;
264 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
265 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
266 //make rscoreFreq map and rCumul
267 map<float,float>::iterator it2 = rscoreFreq[a].find(it->first);
268 rCumul[a][it->first] = rcumul;
269 //get percentage of random trees with that info
270 if (it2 != rscoreFreq[a].end()) { rscoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
271 else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
273 UWScoreSig[a].push_back(rCumul[a][userData[a]]);
274 }else { UWScoreSig[a].push_back(0.0); }
278 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; }
281 printUWSummaryFile(i);
282 if (random) { printUnweightedFile(); delete output; }
283 if (phylip) { createPhylipFile(i); }
295 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
297 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.unweighted."); m->mothurOutEndLine();
299 m->mothurOutEndLine();
300 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
301 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
302 m->mothurOutEndLine();
307 catch(exception& e) {
308 m->errorOut(e, "UnifracUnweightedCommand", "execute");
312 /***********************************************************/
313 void UnifracUnweightedCommand::printUnweightedFile() {
318 tags.push_back("Score");
319 tags.push_back("RandFreq"); tags.push_back("RandCumul");
321 for(int a = 0; a < numComp; a++) {
322 output->initFile(groupComb[a], tags);
324 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
325 data.push_back(it->first); data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
326 output->output(data);
332 catch(exception& e) {
333 m->errorOut(e, "UnifracUnweightedCommand", "printUnweightedFile");
338 /***********************************************************/
339 void UnifracUnweightedCommand::printUWSummaryFile(int i) {
343 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
347 for(int a = 0; a < numComp; a++) {
348 outSum << i+1 << '\t';
349 m->mothurOut(toString(i+1) + "\t");
352 if (UWScoreSig[a][0] > (1/(float)iters)) {
353 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
354 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
355 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t" + toString(UWScoreSig[a][0])+ "\n");
357 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
358 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
359 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t<" + toString((1/float(iters))) + "\n");
362 outSum << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
363 cout << setprecision(6) << groupComb[a] << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
364 m->mothurOutJustToLog(groupComb[a] + "\t" + toString(utreeScores[a][0]) + "\t0.00\n");
369 catch(exception& e) {
370 m->errorOut(e, "UnifracUnweightedCommand", "printUWSummaryFile");
374 /***********************************************************/
375 void UnifracUnweightedCommand::createPhylipFile(int i) {
377 string phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".unweighted.dist";
378 outputNames.push_back(phylipFileName); outputTypes["phylip"].push_back(phylipFileName);
381 m->openOutputFile(phylipFileName, out);
384 out << globaldata->Groups.size() << endl;
386 //make matrix with scores in it
387 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
388 for (int i = 0; i < globaldata->Groups.size(); i++) {
389 dists[i].resize(globaldata->Groups.size(), 0.0);
392 //flip it so you can print it
394 for (int r=0; r<globaldata->Groups.size(); r++) {
395 for (int l = r+1; l < globaldata->Groups.size(); l++) {
396 dists[r][l] = utreeScores[count][0];
397 dists[l][r] = utreeScores[count][0];
403 for (int r=0; r<globaldata->Groups.size(); r++) {
405 string name = globaldata->Groups[r];
406 if (name.length() < 10) { //pad with spaces to make compatible
407 while (name.length() < 10) { name += " "; }
412 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
417 catch(exception& e) {
418 m->errorOut(e, "UnifracUnweightedCommand", "createPhylipFile");
422 /***********************************************************/