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