]> git.donarmstrong.com Git - mothur.git/blob - unifracweightedcommand.cpp
added set.dir command and modified commands to redirect input and output, removed...
[mothur.git] / unifracweightedcommand.cpp
1 /*
2  *  unifracweightedcommand.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 "unifracweightedcommand.h"
11
12 /***********************************************************/
13 UnifracWeightedCommand::UnifracWeightedCommand(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.weighted 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                         
67                         if (abort == false) {
68                                 T = globaldata->gTree;
69                                 tmap = globaldata->gTreemap;
70                                 sumFile = outputDir + getSimpleName(globaldata->getTreeFile()) + ".wsummary";
71                                 openOutputFile(sumFile, outSum);
72                                 
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);
77                                 
78                                 weighted = new Weighted(tmap);
79                                 
80                         }
81                 }
82                 
83                 
84         }
85         catch(exception& e) {
86                 errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
87                 exit(1);
88         }
89 }
90 //**********************************************************************************************************************
91
92 void UnifracWeightedCommand::help(){
93         try {
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");
105         }
106         catch(exception& e) {
107                 errorOut(e, "UnifracWeightedCommand", "help");
108                 exit(1);
109         }
110 }
111
112 /***********************************************************/
113 int UnifracWeightedCommand::execute() {
114         try {
115         
116                 if (abort == true) { return 0; }
117                 
118                 Progress* reading;
119                 if (random) {   reading = new Progress("Comparing to random:", iters);  }
120                 
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...
124                                 
125                 //create new tree with same num nodes and leaves as users
126                 randT = new Tree();
127                 
128                 //get weighted scores for users trees
129                 for (int i = 0; i < T.size(); i++) {
130                         counter = 0;
131                         rScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
132                         uScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
133                         
134                         if (random) {  output = new ColumnFile(outputDir + getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted", itersString);  } 
135
136                         userData = weighted->getValues(T[i]);  //userData[0] = weightedscore
137                         
138                         //save users score
139                         for (int s=0; s<numComp; s++) {
140                                 //add users score to vector of user scores
141                                 uScores[s].push_back(userData[s]);
142                                 
143                                 //save users tree score for summary file
144                                 utreeScores.push_back(userData[s]);
145                         }
146                         
147                         //get scores for random trees
148                         for (int j = 0; j < iters; j++) {
149                                 int count = 0;
150                                 for (int r=0; r<numGroups; r++) { 
151                                         for (int l = r+1; l < numGroups; l++) {
152                                                 //copy T[i]'s info.
153                                                 randT->getCopy(T[i]);
154                                                  
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]);
159                                                 
160                                                 //save scores
161                                                 rScores[count].push_back(randomData[0]);
162                                                 count++;
163                                         }
164                                 }
165                                 
166                                 //update progress bar
167                                 reading->update(j);
168
169                         }
170
171                         //removeValidScoresDuplicates(); 
172                         //find the signifigance of the score for summary file
173                         if (random) {
174                                 for (int f = 0; f < numComp; f++) {
175                                         //sort random scores
176                                         sort(rScores[f].begin(), rScores[f].end());
177                                         
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
183                                         
184                                         //the signifigance is the number of trees with the users score or higher 
185                                         WScoreSig.push_back((iters-index)/(float)iters);
186                                 }
187                                 
188                                 //out << "Tree# " << i << endl;
189                                 calculateFreqsCumuls();
190                                 printWeightedFile();
191                                 
192                                 delete output;
193                         }
194                         
195                         //clear data
196                         rScores.clear();
197                         uScores.clear();
198                         validScores.clear();
199                 }
200                 
201                 //finish progress bar
202                 if (random) {   reading->finish();      delete reading;         }
203                 
204                 printWSummaryFile();
205                 
206                 if (phylip) {   createPhylipFile();             }
207
208                 //clear out users groups
209                 globaldata->Groups.clear();
210                 
211                 delete randT;
212                 
213                 return 0;
214                 
215         }
216         catch(exception& e) {
217                 errorOut(e, "UnifracWeightedCommand", "execute");
218                 exit(1);
219         }
220 }
221 /***********************************************************/
222 void UnifracWeightedCommand::printWeightedFile() {
223         try {
224                 vector<double> data;
225                 vector<string> tags;
226                 tags.push_back("Score"); tags.push_back("RandFreq"); tags.push_back("RandCumul");
227                 
228                 for(int a = 0; a < numComp; a++) {
229                         output->initFile(groupComb[a], tags);
230                         //print each line
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);
234                                 data.clear();
235                         } 
236                         output->resetFile();
237                 }
238         }
239         catch(exception& e) {
240                 errorOut(e, "UnifracWeightedCommand", "printWeightedFile");
241                 exit(1);
242         }
243 }
244
245
246 /***********************************************************/
247 void UnifracWeightedCommand::printWSummaryFile() {
248         try {
249                 //column headers
250                 outSum << "Tree#" << '\t' << "Groups" << '\t' << "WScore" << '\t' << "WSig" <<  endl;
251                 mothurOut("Tree#\tGroups\tWScore\tWSig"); mothurOutEndLine(); 
252                 
253                 //format output
254                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
255                 
256                 //print each line
257                 int count = 0;
258                 for (int i = 0; i < T.size(); i++) { 
259                         for (int j = 0; j < numComp; j++) {
260                                 if (random) {
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();  
265                                         }else{
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();  
269                                         }
270                                 }else{
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(); 
274                                 }
275                                 count++;
276                         }
277                 }
278                 outSum.close();
279         }
280         catch(exception& e) {
281                 errorOut(e, "UnifracWeightedCommand", "printWSummaryFile");
282                 exit(1);
283         }
284 }
285 /***********************************************************/
286 void UnifracWeightedCommand::createPhylipFile() {
287         try {
288                 int count = 0;
289                 //for each tree
290                 for (int i = 0; i < T.size(); i++) { 
291                 
292                         string phylipFileName = outputDir + getSimpleName(globaldata->getTreeFile())  + toString(i+1) + ".weighted.dist";
293                         ofstream out;
294                         openOutputFile(phylipFileName, out);
295                         
296                         //output numSeqs
297                         out << globaldata->Groups.size() << endl;
298                         
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);
303                         }
304                         
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]);
310                                         count++;
311                                 }
312                         }
313
314                         //output to file
315                         for (int r=0; r<globaldata->Groups.size(); r++) { 
316                                 //output name
317                                 string name = globaldata->Groups[r];
318                                 if (name.length() < 10) { //pad with spaces to make compatible
319                                         while (name.length() < 10) {  name += " ";  }
320                                 }
321                                 out << name << '\t';
322                                 
323                                 //output distances
324                                 for (int l = 0; l < r; l++) {   out  << dists[r][l] << '\t';  }
325                                 out << endl;
326                         }
327                         out.close();
328                 }
329         }
330         catch(exception& e) {
331                 errorOut(e, "UnifracWeightedCommand", "createPhylipFile");
332                 exit(1);
333         }
334 }
335 /***********************************************************/
336 int UnifracWeightedCommand::findIndex(float score, int index) {
337         try{
338                 for (int i = 0; i < rScores[index].size(); i++) {
339                         if (rScores[index][i] >= score) {       return i;       }
340                 }
341                 return rScores[index].size();
342         }
343         catch(exception& e) {
344                 errorOut(e, "UnifracWeightedCommand", "findIndex");
345                 exit(1);
346         }
347 }
348
349 /***********************************************************/
350
351 void UnifracWeightedCommand::calculateFreqsCumuls() {
352         try {
353                 //clear out old tree values
354                 rScoreFreq.clear();
355                 rScoreFreq.resize(numComp);
356                 rCumul.clear();
357                 rCumul.resize(numComp);
358                 validScores.clear();
359         
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]]++;
367                                 }else{
368                                         rScoreFreq[f][rScores[f][i]] = 1;
369                                 }
370                         }
371                 }
372                 
373                 //calculate rcumul
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
384                         }
385                 }
386
387         }
388         catch(exception& e) {
389                 errorOut(e, "UnifracWeightedCommand", "calculateFreqsCums");
390                 exit(1);
391         }
392 }
393
394 /***********************************************************/
395
396
397
398
399