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