]> git.donarmstrong.com Git - mothur.git/blob - unifracunweightedcommand.cpp
957a4aaab458d5f65256d8f9bf43579ad383d493
[mothur.git] / unifracunweightedcommand.cpp
1 /*
2  *  unifracunweightedcommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 2/9/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "unifracunweightedcommand.h"
11
12 /***********************************************************/
13 UnifracUnweightedCommand::UnifracUnweightedCommand(string option) {
14         try {
15                 globaldata = GlobalData::getInstance();
16                 abort = false;
17                 Groups.clear();
18                 
19                 //allow user to run help
20                 if(option == "help") { help(); abort = true; }
21                 
22                 else {
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)));
26                         
27                         OptionParser parser(option);
28                         map<string,string> parameters = parser.getParameters();
29                         
30                         ValidParameters validParameter;
31                 
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;  }
35                         }
36                         
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.unweighted command."); mothurOutEndLine(); abort = true;  }
39                         
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"){  
42                                 outputDir = ""; 
43                                 outputDir += hasPath(globaldata->inputFileName); //if user entered a file with a path then preserve it  
44                         }
45                                                         
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 = ""; }
50                         else { 
51                                 splitAtDash(groups, Groups);
52                                 globaldata->Groups = Groups;
53                         }
54                                 
55                         itersString = validParameter.validFile(parameters, "iters", false);                             if (itersString == "not found") { itersString = "1000"; }
56                         convert(itersString, iters); 
57                         
58                         string temp = validParameter.validFile(parameters, "distance", false);                  if (temp == "not found") { temp = "false"; }
59                         phylip = isTrue(temp);
60                         
61                         temp = validParameter.validFile(parameters, "random", false);                                   if (temp == "not found") { temp = "true"; }
62                         random = isTrue(temp);
63                         
64                         if (!random) {  iters = 0;  } //turn off random calcs
65                         
66                         //if user selects distance = true and no groups it won't calc the pairwise
67                         if ((phylip) && (Groups.size() == 0)) {
68                                 groups = "all";
69                                 splitAtDash(groups, Groups);
70                                 globaldata->Groups = Groups;
71                         }
72                 
73                         if (abort == false) {
74                                 T = globaldata->gTree;
75                                 tmap = globaldata->gTreemap;
76                                 sumFile = outputDir + getSimpleName(globaldata->getTreeFile()) + ".uwsummary";
77                                 openOutputFile(sumFile, outSum);
78                                 
79                                 util = new SharedUtil();
80                                 util->setGroups(globaldata->Groups, tmap->namesOfGroups, allGroups, numGroups, "unweighted");   //sets the groups the user wants to analyze
81                                 util->getCombos(groupComb, globaldata->Groups, numComp);
82                                 
83                                 if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
84                                 
85                                 unweighted = new Unweighted(tmap);
86                                 
87                         }
88                         
89                 }
90                 
91         }
92         catch(exception& e) {
93                 errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
94                 exit(1);
95         }
96 }
97
98 //**********************************************************************************************************************
99
100 void UnifracUnweightedCommand::help(){
101         try {
102                 mothurOut("The unifrac.unweighted command can only be executed after a successful read.tree command.\n");
103                 mothurOut("The unifrac.unweighted command parameters are groups, iters, distance and random.  No parameters are required.\n");
104                 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");
105                 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");
106                 mothurOut("The distance parameter allows you to create a distance file from the results. The default is false.\n");
107                 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");
108                 mothurOut("The unifrac.unweighted command should be in the following format: unifrac.unweighted(groups=yourGroups, iters=yourIters).\n");
109                 mothurOut("Example unifrac.unweighted(groups=A-B-C, iters=500).\n");
110                 mothurOut("The default value for groups is all the groups in your groupfile, and iters is 1000.\n");
111                 mothurOut("The unifrac.unweighted command output two files: .unweighted and .uwsummary their descriptions are in the manual.\n");
112                 mothurOut("Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n");
113         }
114         catch(exception& e) {
115                 errorOut(e, "UnifracUnweightedCommand", "help");
116                 exit(1);
117         }
118 }
119
120
121 /***********************************************************/
122 int UnifracUnweightedCommand::execute() {
123         try {
124                 
125                 if (abort == true) { return 0; }
126                 
127                 userData.resize(numComp,0);  //data[0] = unweightedscore 
128                 randomData.resize(numComp,0); //data[0] = unweightedscore
129                 //create new tree with same num nodes and leaves as users
130                 
131                 outSum << "Tree#" << '\t' << "Groups" << '\t'  <<  "UWScore" <<'\t' << "UWSig" <<  endl;
132                 mothurOut("Tree#\tGroups\tUWScore\tUWSig"); mothurOutEndLine();
133                 
134                 //get pscores for users trees
135                 for (int i = 0; i < T.size(); i++) {
136                         counter = 0;
137                         
138                         if (random)  {  output = new ColumnFile(outputDir + getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".unweighted", itersString);  }
139                         
140                         //get unweighted for users tree
141                         rscoreFreq.resize(numComp);  
142                         rCumul.resize(numComp);  
143                         utreeScores.resize(numComp);  
144                         UWScoreSig.resize(numComp); 
145
146                         userData = unweighted->getValues(T[i]);  //userData[0] = unweightedscore
147                         
148                         //output scores for each combination
149                         for(int k = 0; k < numComp; k++) {
150                                 //saves users score
151                                 utreeScores[k].push_back(userData[k]);
152                                 
153                                 //add users score to validscores
154                                 validScores[userData[k]] = userData[k];
155                         }
156                         
157                         //get unweighted scores for random trees
158                         for (int j = 0; j < iters; j++) {
159                                 //we need a different getValues because when we swap the labels we only want to swap those in each pairwise comparison
160                                 randomData = unweighted->getValues(T[i], "", "");
161                         
162                                 for(int k = 0; k < numComp; k++) {      
163                                         //add trees unweighted score to map of scores
164                                         map<float,float>::iterator it = rscoreFreq[k].find(randomData[k]);
165                                         if (it != rscoreFreq[k].end()) {//already have that score
166                                                 rscoreFreq[k][randomData[k]]++;
167                                         }else{//first time we have seen this score
168                                                 rscoreFreq[k][randomData[k]] = 1;
169                                         }
170                                 
171                                         //add randoms score to validscores
172                                         validScores[randomData[k]] = randomData[k];
173                                 }
174                         }
175                 
176                         for(int a = 0; a < numComp; a++) {
177                                 float rcumul = 1.0000;
178                                 //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
179                                 for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
180                                         //make rscoreFreq map and rCumul
181                                         map<float,float>::iterator it2 = rscoreFreq[a].find(it->first);
182                                         rCumul[a][it->first] = rcumul;
183                                         //get percentage of random trees with that info
184                                         if (it2 != rscoreFreq[a].end()) {  rscoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
185                                         else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
186                                 }
187                                 
188                                 if (random) {   UWScoreSig[a].push_back(rCumul[a][userData[a]]);        }
189                                 else            {       UWScoreSig[a].push_back(0.0);                                           }
190                         }
191                 
192                         //print output files
193                         printUWSummaryFile(i);
194                         if (random)  {  printUnweightedFile();  delete output;  }
195                         if (phylip) {   createPhylipFile(i);            }
196                         
197                         rscoreFreq.clear(); 
198                         rCumul.clear();  
199                         validScores.clear(); 
200                         utreeScores.clear();  
201                         UWScoreSig.clear(); 
202                 }
203                 
204                 //reset groups parameter
205                 globaldata->Groups.clear(); 
206                 outSum.close();
207                 
208                 return 0;
209                 
210         }
211         catch(exception& e) {
212                 errorOut(e, "UnifracUnweightedCommand", "execute");
213                 exit(1);
214         }
215 }
216 /***********************************************************/
217 void UnifracUnweightedCommand::printUnweightedFile() {
218         try {
219                 vector<double> data;
220                 vector<string> tags;
221                 
222                 tags.push_back("Score");
223                 tags.push_back("RandFreq"); tags.push_back("RandCumul");
224                         
225                 for(int a = 0; a < numComp; a++) {
226                         output->initFile(groupComb[a], tags);
227                         //print each line
228                         for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
229                                 data.push_back(it->first);  data.push_back(rscoreFreq[a][it->first]); data.push_back(rCumul[a][it->first]);                                             
230                                 output->output(data);
231                                 data.clear();
232                         } 
233                         output->resetFile();
234                 }
235         }
236         catch(exception& e) {
237                 errorOut(e, "UnifracUnweightedCommand", "printUnweightedFile");
238                 exit(1);
239         }
240 }
241
242 /***********************************************************/
243 void UnifracUnweightedCommand::printUWSummaryFile(int i) {
244         try {
245                                 
246                 //format output
247                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
248                         
249                 //print each line
250
251                 for(int a = 0; a < numComp; a++) {
252                         outSum << i+1 << '\t';
253                         mothurOut(toString(i+1) + "\t");
254                         
255                         if (random) {
256                                 if (UWScoreSig[a][0] > (1/(float)iters)) {
257                                         outSum << setprecision(6) << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl;
258                                         cout << setprecision(6)  << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << UWScoreSig[a][0] << endl; 
259                                         mothurOutJustToLog(groupComb[a]  + "\t" + toString(utreeScores[a][0])  + "\t" + toString(UWScoreSig[a][0])); mothurOutEndLine(); 
260                                 }else {
261                                         outSum << setprecision(6) << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl;
262                                         cout << setprecision(6)  << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << setprecision(itersString.length()) << "<" << (1/float(iters)) << endl; 
263                                         mothurOutJustToLog(groupComb[a]  + "\t" + toString(utreeScores[a][0])  + "\t<" + toString((1/float(iters)))); mothurOutEndLine();
264                                 }
265                         }else{
266                                 outSum << setprecision(6) << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl;
267                                 cout << setprecision(6)  << groupComb[a]  << '\t' << utreeScores[a][0] << '\t' << "0.00" << endl; 
268                                 mothurOutJustToLog(groupComb[a]  + "\t" + toString(utreeScores[a][0])  + "\t0.00"); mothurOutEndLine();
269                         }
270                 }
271                 
272         }
273         catch(exception& e) {
274                 errorOut(e, "UnifracUnweightedCommand", "printUWSummaryFile");
275                 exit(1);
276         }
277 }
278 /***********************************************************/
279 void UnifracUnweightedCommand::createPhylipFile(int i) {
280         try {
281                 string phylipFileName = outputDir + getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".unweighted.dist";
282                 ofstream out;
283                 openOutputFile(phylipFileName, out);
284                         
285                 //output numSeqs
286                 out << globaldata->Groups.size() << endl;
287                         
288                 //make matrix with scores in it
289                 vector< vector<float> > dists;  dists.resize(globaldata->Groups.size());
290                 for (int i = 0; i < globaldata->Groups.size(); i++) {
291                         dists[i].resize(globaldata->Groups.size(), 0.0);
292                 }
293                 
294                 //flip it so you can print it
295                 int count = 0;
296                 for (int r=0; r<globaldata->Groups.size(); r++) { 
297                         for (int l = r+1; l < globaldata->Groups.size(); l++) {
298                                 dists[r][l] = (1.0 - utreeScores[count][0]);
299                                 dists[l][r] = (1.0 - utreeScores[count][0]);
300                                 count++;
301                         }
302                 }
303                 
304                 //output to file
305                 for (int r=0; r<globaldata->Groups.size(); r++) { 
306                         //output name
307                         string name = globaldata->Groups[r];
308                         if (name.length() < 10) { //pad with spaces to make compatible
309                                 while (name.length() < 10) {  name += " ";  }
310                         }
311                         out << name << '\t';
312                         
313                         //output distances
314                         for (int l = 0; l < r; l++) {   out  << dists[r][l] << '\t';  }
315                         out << endl;
316                 }
317                 out.close();
318         }
319         catch(exception& e) {
320                 errorOut(e, "UnifracUnweightedCommand", "createPhylipFile");
321                 exit(1);
322         }
323 }
324 /***********************************************************/
325
326
327