]> git.donarmstrong.com Git - mothur.git/blob - libshuffcommand.cpp
created mothurOut class to handle logfiles
[mothur.git] / libshuffcommand.cpp
1 /*
2  *  libshuffcommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 3/9/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 /* This class is designed to implement an integral form of the Cramer-von Mises statistic.
11         you may refer to the "Integration of Microbial Ecology and Statistics: A Test To Compare Gene Libraries" 
12         paper in Applied and Environmental Microbiology, Sept. 2004, p. 5485-5492 0099-2240/04/$8.00+0  
13         DOI: 10.1128/AEM.70.9.5485-5492.2004 Copyright 2004 American Society for Microbiology for more information. */
14
15
16 #include "libshuffcommand.h"
17 #include "libshuff.h"
18 #include "slibshuff.h"
19 #include "dlibshuff.h"
20
21 //**********************************************************************************************************************
22
23 LibShuffCommand::LibShuffCommand(string option)  {
24         try {
25                 globaldata = GlobalData::getInstance();
26                 abort = false;
27                 Groups.clear();
28                 
29                 //allow user to run help
30                 if(option == "help") { help(); abort = true; }
31                 
32                 else {
33                         //valid paramters for this command
34                         string Array[] =  {"iters","groups","step","form","cutoff","outputdir","inputdir"};
35                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
36                         
37                         OptionParser parser(option);
38                         map<string, string> parameters = parser.getParameters();
39                         
40                         ValidParameters validParameter;
41                 
42                         //check to make sure all parameters are valid for command
43                         for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) { 
44                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
45                         }
46                         
47                         //if the user changes the output directory command factory will send this info to us in the output parameter 
48                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
49                                 outputDir = ""; 
50                                 outputDir += hasPath(globaldata->getPhylipFile()); //if user entered a file with a path then preserve it        
51                         }
52                         
53                         //make sure the user has already run the read.dist command
54                         if ((globaldata->gMatrix == NULL) || (globaldata->gGroupmap == NULL)) {
55                                 m->mothurOut("You must read in a matrix and groupfile using the read.dist command, before you use the libshuff command. "); m->mothurOutEndLine(); abort = true;; 
56                         }
57                                                 
58                         //check for optional parameter and set defaults
59                         // ...at some point should added some additional type checking...
60                         groups = validParameter.validFile(parameters, "groups", false);                 
61                         if (groups == "not found") { groups = ""; savegroups = groups; }
62                         else { 
63                                 savegroups = groups;
64                                 splitAtDash(groups, Groups);
65                                 globaldata->Groups = Groups;
66                         }
67                                 
68                         string temp;
69                         temp = validParameter.validFile(parameters, "iters", false);                            if (temp == "not found") { temp = "10000"; }
70                         convert(temp, iters); 
71                         
72                         temp = validParameter.validFile(parameters, "cutoff", false);                           if (temp == "not found") { temp = "1.0"; }
73                         convert(temp, cutOff); 
74                         
75                         temp = validParameter.validFile(parameters, "step", false);                             if (temp == "not found") { temp = "0.01"; }
76                         convert(temp, step); 
77         
78                         userform = validParameter.validFile(parameters, "form", false);                 if (userform == "not found") { userform = "integral"; }
79                         
80                         if (abort == false) {
81                 
82                                 matrix = globaldata->gMatrix;                           //get the distance matrix
83                                 setGroups();                                                            //set the groups to be analyzed and sorts them
84         
85                                 /********************************************************************************************/
86                                 //this is needed because when we read the matrix we sort it into groups in alphabetical order
87                                 //the rest of the command and the classes used in this command assume specific order
88                                 /********************************************************************************************/
89                                 matrix->setGroups(globaldata->gGroupmap->namesOfGroups);
90                                 vector<int> sizes;
91                                 for (int i = 0; i < globaldata->gGroupmap->namesOfGroups.size(); i++) {   sizes.push_back(globaldata->gGroupmap->getNumSeqs(globaldata->gGroupmap->namesOfGroups[i]));  }
92                                 matrix->setSizes(sizes);
93                         
94
95                                 if(userform == "discrete"){
96                                         form = new DLibshuff(matrix, iters, step, cutOff);
97                                 }
98                                 else{
99                                         form = new SLibshuff(matrix, iters, cutOff);
100                                 }
101                         }
102                         
103                 }
104                 
105         }
106         catch(exception& e) {
107                 m->errorOut(e, "LibShuffCommand", "LibShuffCommand");
108                 exit(1);
109         }
110 }
111 //**********************************************************************************************************************
112
113 void LibShuffCommand::help(){
114         try {
115                 m->mothurOut("The libshuff command can only be executed after a successful read.dist command including a groupfile.\n");
116                 m->mothurOut("The libshuff command parameters are groups, iters, step, form and cutoff.  No parameters are required.\n");
117                 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");
118                 m->mothurOut("The group names are separated by dashes.  The iters parameter allows you to specify how many random matrices you would like compared to your matrix.\n");
119                 m->mothurOut("The step parameter allows you to specify change in distance you would like between each output if you are using the discrete form.\n");
120                 m->mothurOut("The form parameter allows you to specify if you would like to analyze your matrix using the discrete or integral form. Your options are integral or discrete.\n");
121                 m->mothurOut("The libshuff command should be in the following format: libshuff(groups=yourGroups, iters=yourIters, cutOff=yourCutOff, form=yourForm, step=yourStep).\n");
122                 m->mothurOut("Example libshuff(groups=A-B-C, iters=500, form=discrete, step=0.01, cutOff=2.0).\n");
123                 m->mothurOut("The default value for groups is all the groups in your groupfile, iters is 10000, cutoff is 1.0, form is integral and step is 0.01.\n");
124                 m->mothurOut("The libshuff command output two files: .coverage and .slsummary their descriptions are in the manual.\n");
125                 m->mothurOut("Note: No spaces between parameter labels (i.e. iters), '=' and parameters (i.e.yourIters).\n\n");
126         }
127         catch(exception& e) {
128                 m->errorOut(e, "LibShuffCommand", "help");
129                 exit(1);
130         }
131 }
132
133 //**********************************************************************************************************************
134
135 int LibShuffCommand::execute(){
136         try {
137                 
138                 if (abort == true) {    return 0;       }
139         
140                 savedDXYValues = form->evaluateAll();
141                 savedMinValues = form->getSavedMins();
142         
143                 pValueCounts.resize(numGroups);
144                 for(int i=0;i<numGroups;i++){
145                         pValueCounts[i].assign(numGroups, 0);
146                 }
147                 
148                 Progress* reading = new Progress();
149                 
150                 for(int i=0;i<numGroups-1;i++) {
151                         for(int j=i+1;j<numGroups;j++) {
152                                 reading->newLine(groupNames[i]+'-'+groupNames[j], iters);
153                                 int spoti = globaldata->gGroupmap->groupIndex[groupNames[i]]; //neccessary in case user selects groups so you know where they are in the matrix
154                                 int spotj = globaldata->gGroupmap->groupIndex[groupNames[j]];
155         
156                                 for(int p=0;p<iters;p++) {              
157                                         form->randomizeGroups(spoti,spotj); 
158                                         if(form->evaluatePair(spoti,spotj) >= savedDXYValues[spoti][spotj])     {       pValueCounts[i][j]++;   }
159                                         if(form->evaluatePair(spotj,spoti) >= savedDXYValues[spotj][spoti])     {       pValueCounts[j][i]++;   }
160                                         reading->update(p);                     
161                                 }
162                                 form->resetGroup(spoti);
163                                 form->resetGroup(spotj);
164                         }
165                 }
166                 reading->finish();
167                 delete reading;
168
169                 m->mothurOutEndLine();
170                 printSummaryFile();
171                 printCoverageFile();
172                 
173                 //clear out users groups
174                 globaldata->Groups.clear();
175                 delete form;
176                 
177                 //delete globaldata's copy of the gmatrix to free up memory
178                 delete globaldata->gMatrix;  globaldata->gMatrix = NULL;
179                 
180                 m->mothurOutEndLine();
181                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
182                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
183                 m->mothurOutEndLine();
184                 
185                 return 0;
186         }
187         catch(exception& e) {
188                 m->errorOut(e, "LibShuffCommand", "execute");
189                 exit(1);
190         }
191 }
192
193 //**********************************************************************************************************************
194
195 void LibShuffCommand::printCoverageFile() {
196         try {
197
198                 ofstream outCov;
199                 summaryFile = outputDir + getRootName(getSimpleName(globaldata->getPhylipFile())) + "libshuff.coverage";
200                 openOutputFile(summaryFile, outCov);
201                 outputNames.push_back(summaryFile);
202                 outCov.setf(ios::fixed, ios::floatfield); outCov.setf(ios::showpoint);
203                 //cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
204                 
205                 map<double,vector<int> > allDistances;
206                 map<double,vector<int> >::iterator it;
207
208                 vector<vector<int> > indices(numGroups);
209                 int numIndices = numGroups * numGroups;
210                 
211                 int index = 0;
212                 for(int i=0;i<numGroups;i++){
213                         indices[i].assign(numGroups,0);
214                         for(int j=0;j<numGroups;j++){
215                                 indices[i][j] = index++;
216                                 
217                                 int spoti = globaldata->gGroupmap->groupIndex[groupNames[i]]; //neccessary in case user selects groups so you know where they are in the matrix
218                                 int spotj = globaldata->gGroupmap->groupIndex[groupNames[j]];
219                                 
220                                 for(int k=0;k<savedMinValues[spoti][spotj].size();k++){
221                                         if(allDistances[savedMinValues[spoti][spotj][k]].size() != 0){
222                                                 allDistances[savedMinValues[spoti][spotj][k]][indices[i][j]]++;
223                                         }
224                                         else{
225                                                 allDistances[savedMinValues[spoti][spotj][k]].assign(numIndices, 0);
226                                                 allDistances[savedMinValues[spoti][spotj][k]][indices[i][j]] = 1;
227                                         }
228                                 }
229                         }
230                 }
231                 it=allDistances.begin();
232                 
233                 //cout << setprecision(8);
234
235                 vector<int> prevRow = it->second;
236                 it++;
237                 
238                 for(;it!=allDistances.end();it++){
239                         for(int i=0;i<it->second.size();i++){
240                                 it->second[i] += prevRow[i];
241                         }
242                         prevRow = it->second;
243                 }
244                 
245                 vector<int> lastRow = allDistances.rbegin()->second;
246                 outCov << setprecision(8);
247                 
248                 outCov << "dist";
249                 for (int i = 0; i < numGroups; i++){
250                         outCov << '\t' << groupNames[i];
251                 }
252                 for (int i=0;i<numGroups;i++){
253                         for(int j=i+1;j<numGroups;j++){
254                                 outCov << '\t' << groupNames[i] << '-' << groupNames[j] << '\t';
255                                 outCov << groupNames[j] << '-' << groupNames[i];
256                         }
257                 }
258                 outCov << endl;
259                 
260                 for(it=allDistances.begin();it!=allDistances.end();it++){
261                         outCov << it->first << '\t';
262                         for(int i=0;i<numGroups;i++){
263                                 outCov << it->second[indices[i][i]]/(float)lastRow[indices[i][i]] << '\t';
264                         }
265                         for(int i=0;i<numGroups;i++){
266                                 for(int j=i+1;j<numGroups;j++){
267                                         outCov << it->second[indices[i][j]]/(float)lastRow[indices[i][j]] << '\t';
268                                         outCov << it->second[indices[j][i]]/(float)lastRow[indices[j][i]] << '\t';
269                                 }
270                         }
271                         outCov << endl;
272                 }
273                 outCov.close();
274         }
275         catch(exception& e) {
276                 m->errorOut(e, "LibShuffCommand", "printCoverageFile");
277                 exit(1);
278         }
279
280
281 //**********************************************************************************************************************
282
283 void LibShuffCommand::printSummaryFile() {
284         try {
285
286                 ofstream outSum;
287                 summaryFile = outputDir + getRootName(getSimpleName(globaldata->getPhylipFile())) + "libshuff.summary";
288                 openOutputFile(summaryFile, outSum);
289                 outputNames.push_back(summaryFile);
290
291                 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
292                 cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
293                 
294                 cout << setw(20) << left << "Comparison" << '\t' << setprecision(8) << "dCXYScore" << '\t' << "Significance" << endl;
295                 m->mothurOutJustToLog("Comparison\tdCXYScore\tSignificance"); m->mothurOutEndLine();
296                 outSum << setw(20) << left << "Comparison" << '\t' << setprecision(8) << "dCXYScore" << '\t' << "Significance" << endl;
297         
298                 int precision = (int)log10(iters);
299                 for(int i=0;i<numGroups;i++){
300                         for(int j=i+1;j<numGroups;j++){
301                                 int spoti = globaldata->gGroupmap->groupIndex[groupNames[i]]; //neccessary in case user selects groups so you know where they are in the matrix
302                                 int spotj = globaldata->gGroupmap->groupIndex[groupNames[j]];
303                                 
304                                 if(pValueCounts[i][j]){
305                                         cout << setw(20) << left << groupNames[i]+'-'+groupNames[j] << '\t' << setprecision(8) << savedDXYValues[spoti][spotj] << '\t' << setprecision(precision) << pValueCounts[i][j]/(float)iters << endl;
306                                         m->mothurOutJustToLog(groupNames[i]+"-"+groupNames[j] + "\t" + toString(savedDXYValues[spoti][spotj]) + "\t" + toString((pValueCounts[i][j]/(float)iters))); m->mothurOutEndLine();
307                                         outSum << setw(20) << left << groupNames[i]+'-'+groupNames[j] << '\t' << setprecision(8) << savedDXYValues[spoti][spotj] << '\t' << setprecision(precision) << pValueCounts[i][j]/(float)iters << endl;
308                                 }
309                                 else{
310                                         cout << setw(20) << left << groupNames[i]+'-'+groupNames[j] << '\t' << setprecision(8) << savedDXYValues[spoti][spotj] << '\t' << '<' <<setprecision(precision) << 1/(float)iters << endl;
311                                         m->mothurOutJustToLog(groupNames[i]+"-"+groupNames[j] + "\t" + toString(savedDXYValues[spoti][spotj]) + "\t" + toString((1/(float)iters))); m->mothurOutEndLine();
312                                         outSum << setw(20) << left << groupNames[i]+'-'+groupNames[j] << '\t' << setprecision(8) << savedDXYValues[spoti][spotj] << '\t' << '<' <<setprecision(precision) << 1/(float)iters << endl;
313                                 }
314                                 if(pValueCounts[j][i]){
315                                         cout << setw(20) << left << groupNames[j]+'-'+groupNames[i] << '\t' << setprecision(8) << savedDXYValues[spotj][spoti] << '\t' << setprecision (precision) << pValueCounts[j][i]/(float)iters << endl;
316                                         m->mothurOutJustToLog(groupNames[j]+"-"+groupNames[i] + "\t" + toString(savedDXYValues[spotj][spoti]) + "\t" + toString((pValueCounts[j][i]/(float)iters))); m->mothurOutEndLine();
317                                         outSum << setw(20) << left << groupNames[j]+'-'+groupNames[i] << '\t' << setprecision(8) << savedDXYValues[spotj][spoti] << '\t' << setprecision (precision) << pValueCounts[j][i]/(float)iters << endl;
318                                 }
319                                 else{
320                                         cout << setw(20) << left << groupNames[j]+'-'+groupNames[i] << '\t' << setprecision(8) << savedDXYValues[spotj][spoti] << '\t' << '<' <<setprecision (precision) << 1/(float)iters << endl;
321                                         m->mothurOutJustToLog(groupNames[j]+"-"+groupNames[i] + "\t" + toString(savedDXYValues[spotj][spoti]) + "\t" + toString((1/(float)iters))); m->mothurOutEndLine();
322                                         outSum << setw(20) << left << groupNames[j]+'-'+groupNames[i] << '\t' << setprecision(8) << savedDXYValues[spotj][spoti] << '\t' << '<' <<setprecision (precision) << 1/(float)iters << endl;
323                                 }
324                         }
325                 }
326                 
327                 outSum.close();
328         }
329         catch(exception& e) {
330                 m->errorOut(e, "LibShuffCommand", "printSummaryFile");
331                 exit(1);
332         }
333
334
335 //**********************************************************************************************************************
336
337 void LibShuffCommand::setGroups() {
338         try {
339                 //if the user has not entered specific groups to analyze then do them all
340                 if (globaldata->Groups.size() == 0) {
341                         numGroups = globaldata->gGroupmap->getNumGroups();
342                         for (int i=0; i < numGroups; i++) { 
343                                 globaldata->Groups.push_back(globaldata->gGroupmap->namesOfGroups[i]);
344                         }
345                 } else {
346                         if (savegroups != "all") {
347                                 //check that groups are valid
348                                 for (int i = 0; i < globaldata->Groups.size(); i++) {
349                                         if (globaldata->gGroupmap->isValidGroup(globaldata->Groups[i]) != true) {
350                                                 m->mothurOut(globaldata->Groups[i] + " is not a valid group, and will be disregarded."); m->mothurOutEndLine();
351                                                 // erase the invalid group from globaldata->Groups
352                                                 globaldata->Groups.erase(globaldata->Groups.begin()+i);
353                                         }
354                                 }
355                         
356                                 //if the user only entered invalid groups
357                                 if ((globaldata->Groups.size() == 0) || (globaldata->Groups.size() == 1)) { 
358                                         numGroups = globaldata->gGroupmap->getNumGroups();
359                                         for (int i=0; i < numGroups; i++) { 
360                                                 globaldata->Groups.push_back(globaldata->gGroupmap->namesOfGroups[i]);
361                                         }
362                                         m->mothurOut("When using the groups parameter you must have at least 2 valid groups. I will run the command using all the groups in your groupfile."); m->mothurOutEndLine();
363                                 } else { numGroups = globaldata->Groups.size(); }
364                         } else { //users wants all groups
365                                 numGroups = globaldata->gGroupmap->getNumGroups();
366                                 globaldata->Groups.clear();
367                                 for (int i=0; i < numGroups; i++) { 
368                                         globaldata->Groups.push_back(globaldata->gGroupmap->namesOfGroups[i]);
369                                 }
370                         }
371                 }
372
373                 //sort so labels match
374                 sort(globaldata->Groups.begin(), globaldata->Groups.end());
375                 
376                 //sort
377                 sort(globaldata->gGroupmap->namesOfGroups.begin(), globaldata->gGroupmap->namesOfGroups.end());
378                 
379                 for (int i = 0; i < globaldata->gGroupmap->namesOfGroups.size(); i++) {  globaldata->gGroupmap->groupIndex[globaldata->gGroupmap->namesOfGroups[i]] = i;  }
380
381                 groupNames = globaldata->Groups;
382
383         }
384         catch(exception& e) {
385                 m->errorOut(e, "LibShuffCommand", "setGroups");
386                 exit(1);
387         }
388 }
389
390 /***********************************************************/