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 vector<string> UnifracWeightedCommand::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, "UnifracWeightedCommand", "getValidParameters");
24 //**********************************************************************************************************************
25 UnifracWeightedCommand::UnifracWeightedCommand(){
27 //initialize outputTypes
28 vector<string> tempOutNames;
29 outputTypes["weighted"] = tempOutNames;
30 outputTypes["wsummary"] = tempOutNames;
31 outputTypes["phylip"] = tempOutNames;
34 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
38 //**********************************************************************************************************************
39 vector<string> UnifracWeightedCommand::getRequiredParameters(){
41 vector<string> myArray;
45 m->errorOut(e, "UnifracWeightedCommand", "getRequiredParameters");
49 //**********************************************************************************************************************
50 vector<string> UnifracWeightedCommand::getRequiredFiles(){
52 string Array[] = {"tree","group"};
53 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
58 m->errorOut(e, "UnifracWeightedCommand", "getRequiredFiles");
62 /***********************************************************/
63 UnifracWeightedCommand::UnifracWeightedCommand(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["weighted"] = tempOutNames;
90 outputTypes["wsummary"] = 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.weighted 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
126 if (abort == false) {
127 T = globaldata->gTree;
128 tmap = globaldata->gTreemap;
129 sumFile = outputDir + m->getSimpleName(globaldata->getTreeFile()) + ".wsummary";
130 m->openOutputFile(sumFile, outSum);
131 outputNames.push_back(sumFile); outputTypes["wsummary"].push_back(sumFile);
133 util = new SharedUtil();
134 string s; //to make work with setgroups
135 util->setGroups(globaldata->Groups, tmap->namesOfGroups, s, numGroups, "weighted"); //sets the groups the user wants to analyze
136 util->getCombos(groupComb, globaldata->Groups, numComp);
138 weighted = new Weighted(tmap);
145 catch(exception& e) {
146 m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
150 //**********************************************************************************************************************
152 void UnifracWeightedCommand::help(){
154 m->mothurOut("The unifrac.weighted command can only be executed after a successful read.tree command.\n");
155 m->mothurOut("The unifrac.weighted command parameters are groups, iters, distance, processors and random. No parameters are required.\n");
156 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");
157 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");
158 m->mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
159 m->mothurOut("The random parameter allows you to shut off the comparison to random trees. The default is false, meaning don't compare your trees with randomly generated trees.\n");
160 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
161 m->mothurOut("The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n");
162 m->mothurOut("Example unifrac.weighted(groups=A-B-C, iters=500).\n");
163 m->mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
164 m->mothurOut("The unifrac.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n");
165 m->mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
167 catch(exception& e) {
168 m->errorOut(e, "UnifracWeightedCommand", "help");
173 /***********************************************************/
174 int UnifracWeightedCommand::execute() {
177 if (abort == true) { return 0; }
179 int start = time(NULL);
181 //get weighted for users tree
182 userData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
183 randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
185 //get weighted scores for users trees
186 for (int i = 0; i < T.size(); i++) {
188 if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
191 rScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
192 uScores.resize(numComp); //data[0] = weightedscore AB, data[1] = weightedscore AC...
195 output = new ColumnFile(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted", itersString);
196 outputNames.push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted");
197 outputTypes["weighted"].push_back(outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted");
200 userData = weighted->getValues(T[i], processors, outputDir); //userData[0] = weightedscore
202 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; }
205 for (int s=0; s<numComp; s++) {
206 //add users score to vector of user scores
207 uScores[s].push_back(userData[s]);
209 //save users tree score for summary file
210 utreeScores.push_back(userData[s]);
215 //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
216 vector< vector<string> > namesOfGroupCombos;
217 for (int a=0; a<numGroups; a++) {
218 for (int l = 0; l < a; l++) {
219 vector<string> groups; groups.push_back(globaldata->Groups[a]); groups.push_back(globaldata->Groups[l]);
220 namesOfGroupCombos.push_back(groups);
226 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
228 int numPairs = namesOfGroupCombos.size();
229 int numPairsPerProcessor = numPairs / processors;
231 for (int i = 0; i < processors; i++) {
232 int startPos = i * numPairsPerProcessor;
233 if(i == processors - 1){
234 numPairsPerProcessor = numPairs - i * numPairsPerProcessor;
236 lines.push_back(linePair(startPos, numPairsPerProcessor));
242 //get scores for random trees
243 for (int j = 0; j < iters; j++) {
245 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
247 driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
249 createProcesses(T[i], namesOfGroupCombos, rScores);
252 driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
255 if (m->control_pressed) { delete output; outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
258 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();
262 //find the signifigance of the score for summary file
263 for (int f = 0; f < numComp; f++) {
265 sort(rScores[f].begin(), rScores[f].end());
267 //the index of the score higher than yours is returned
268 //so if you have 1000 random trees the index returned is 100
269 //then there are 900 trees with a score greater then you.
270 //giving you a signifigance of 0.900
271 int index = findIndex(userData[f], f); if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
273 //the signifigance is the number of trees with the users score or higher
274 WScoreSig.push_back((iters-index)/(float)iters);
277 //out << "Tree# " << i << endl;
278 calculateFreqsCumuls();
292 if (m->control_pressed) { outSum.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
296 if (phylip) { createPhylipFile(); }
298 //clear out users groups
299 globaldata->Groups.clear();
302 if (m->control_pressed) {
303 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
307 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.weighted."); m->mothurOutEndLine();
309 m->mothurOutEndLine();
310 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
311 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
312 m->mothurOutEndLine();
317 catch(exception& e) {
318 m->errorOut(e, "UnifracWeightedCommand", "execute");
322 /**************************************************************************************************/
324 int UnifracWeightedCommand::createProcesses(Tree* t, vector< vector<string> > namesOfGroupCombos, vector< vector<double> >& scores) {
326 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
329 vector<int> processIDS;
333 //loop through and create all the processes you want
334 while (process != processors) {
338 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
341 driver(t, namesOfGroupCombos, lines[process].start, lines[process].num, scores);
343 //pass numSeqs to parent
345 string tempFile = outputDir + toString(getpid()) + ".weightedcommand.results.temp";
346 m->openOutputFile(tempFile, out);
347 for (int i = lines[process].start; i < (lines[process].start + lines[process].num); i++) { out << scores[i][(scores[i].size()-1)] << '\t'; } out << endl;
351 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
354 driver(t, namesOfGroupCombos, lines[0].start, lines[0].num, scores);
356 //force parent to wait until all the processes are done
357 for (int i=0;i<(processors-1);i++) {
358 int temp = processIDS[i];
362 //get data created by processes
363 for (int i=0;i<(processors-1);i++) {
366 string s = outputDir + toString(processIDS[i]) + ".weightedcommand.results.temp";
367 m->openInputFile(s, in);
370 for (int j = lines[(i+1)].start; j < (lines[(i+1)].start + lines[(i+1)].num); j++) { in >> tempScore; scores[j].push_back(tempScore); }
378 catch(exception& e) {
379 m->errorOut(e, "UnifracWeightedCommand", "createProcesses");
384 /**************************************************************************************************/
385 int UnifracWeightedCommand::driver(Tree* t, vector< vector<string> > namesOfGroupCombos, int start, int num, vector< vector<double> >& scores) {
387 Tree* randT = new Tree();
389 for (int h = start; h < (start+num); h++) {
391 if (m->control_pressed) { return 0; }
393 //initialize weighted score
394 string groupA = namesOfGroupCombos[h][0];
395 string groupB = namesOfGroupCombos[h][1];
400 //create a random tree with same topology as T[i], but different labels
401 randT->assembleRandomUnifracTree(groupA, groupB);
403 if (m->control_pressed) { delete randT; return 0; }
405 //get wscore of random tree
406 EstOutput randomData = weighted->getValues(randT, groupA, groupB);
408 if (m->control_pressed) { delete randT; return 0; }
411 scores[h].push_back(randomData[0]);
419 catch(exception& e) {
420 m->errorOut(e, "UnifracWeightedCommand", "driver");
424 /***********************************************************/
425 void UnifracWeightedCommand::printWeightedFile() {
429 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
431 for(int a = 0; a < numComp; a++) {
432 output->initFile(groupComb[a], tags);
434 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
435 data.push_back(it->first); data.push_back(rScoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);
436 output->output(data);
442 catch(exception& e) {
443 m->errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
449 /***********************************************************/
450 void UnifracWeightedCommand::printWSummaryFile() {
453 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" << endl;
454 m->mothurOut("Tree#\tGroups\tWScore\tWSig"); m->mothurOutEndLine();
457 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
461 for (int i = 0; i < T.size(); i++) {
462 for (int j = 0; j < numComp; j++) {
464 if (WScoreSig[count] > (1/(float)iters)) {
465 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
466 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << WScoreSig[count] << endl;
467 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t" + toString(WScoreSig[count]) + "\n");
469 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
470 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
471 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t<" + toString((1/float(iters))) + "\n");
474 outSum << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
475 cout << setprecision(6) << i+1 << '\t' << groupComb[j] << '\t' << utreeScores[count] << '\t' << "0.00" << endl;
476 m->mothurOutJustToLog(toString(i+1) +"\t" + groupComb[j] +"\t" + toString(utreeScores[count]) +"\t0.00\n");
483 catch(exception& e) {
484 m->errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
488 /***********************************************************/
489 void UnifracWeightedCommand::createPhylipFile() {
493 for (int i = 0; i < T.size(); i++) {
495 string phylipFileName = outputDir + m->getSimpleName(globaldata->getTreeFile()) + toString(i+1) + ".weighted.dist";
496 outputNames.push_back(phylipFileName);
497 outputTypes["phylip"].push_back(phylipFileName);
499 m->openOutputFile(phylipFileName, out);
502 out << globaldata->Groups.size() << endl;
504 //make matrix with scores in it
505 vector< vector<float> > dists; dists.resize(globaldata->Groups.size());
506 for (int i = 0; i < globaldata->Groups.size(); i++) {
507 dists[i].resize(globaldata->Groups.size(), 0.0);
510 //flip it so you can print it
511 for (int r=0; r<globaldata->Groups.size(); r++) {
512 for (int l = r+1; l < globaldata->Groups.size(); l++) {
513 dists[r][l] = utreeScores[count];
514 dists[l][r] = utreeScores[count];
520 for (int r=0; r<globaldata->Groups.size(); r++) {
522 string name = globaldata->Groups[r];
523 if (name.length() < 10) { //pad with spaces to make compatible
524 while (name.length() < 10) { name += " "; }
529 for (int l = 0; l < r; l++) { out << dists[r][l] << '\t'; }
535 catch(exception& e) {
536 m->errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
540 /***********************************************************/
541 int UnifracWeightedCommand::findIndex(float score, int index) {
543 for (int i = 0; i < rScores[index].size(); i++) {
544 if (rScores[index][i] >= score) { return i; }
546 return rScores[index].size();
548 catch(exception& e) {
549 m->errorOut(e, "UnifracWeightedCommand", "findIndex");
554 /***********************************************************/
556 void UnifracWeightedCommand::calculateFreqsCumuls() {
558 //clear out old tree values
560 rScoreFreq.resize(numComp);
562 rCumul.resize(numComp);
565 //calculate frequency
566 for (int f = 0; f < numComp; f++) {
567 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...
568 validScores[rScores[f][i]] = rScores[f][i];
569 map<float,float>::iterator it = rScoreFreq[f].find(rScores[f][i]);
570 if (it != rScoreFreq[f].end()) {
571 rScoreFreq[f][rScores[f][i]]++;
573 rScoreFreq[f][rScores[f][i]] = 1;
579 for(int a = 0; a < numComp; a++) {
580 float rcumul = 1.0000;
581 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
582 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) {
583 //make rscoreFreq map and rCumul
584 map<float,float>::iterator it2 = rScoreFreq[a].find(it->first);
585 rCumul[a][it->first] = rcumul;
586 //get percentage of random trees with that info
587 if (it2 != rScoreFreq[a].end()) { rScoreFreq[a][it->first] /= iters; rcumul-= it2->second; }
588 else { rScoreFreq[a][it->first] = 0.0000; } //no random trees with that score
593 catch(exception& e) {
594 m->errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
599 /***********************************************************/