5 * Created by Sarah Westcott on 3/9/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
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. */
16 #include "libshuffcommand.h"
18 #include "slibshuff.h"
19 #include "dlibshuff.h"
23 //**********************************************************************************************************************
24 vector<string> LibShuffCommand::setParameters(){
26 CommandParameter pphylip("phylip", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pphylip);
27 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pgroup);
28 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
29 CommandParameter piters("iters", "Number", "", "10000", "", "", "",false,false); parameters.push_back(piters);
30 CommandParameter pstep("step", "Number", "", "0.01", "", "", "",false,false); parameters.push_back(pstep);
31 CommandParameter pcutoff("cutoff", "Number", "", "1.0", "", "", "",false,false); parameters.push_back(pcutoff);
32 CommandParameter pform("form", "Multiple", "discrete-integral", "integral", "", "", "",false,false); parameters.push_back(pform);
33 CommandParameter psim("sim", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psim);
34 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
35 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
37 vector<string> myArray;
38 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
42 m->errorOut(e, "LibShuffCommand", "setParameters");
46 //**********************************************************************************************************************
47 string LibShuffCommand::getHelpString(){
49 string helpString = "";
50 helpString += "The libshuff command parameters are phylip, group, sim, groups, iters, step, form and cutoff. phylip and group parameters are required, unless you have valid current files.\n";
51 helpString += "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";
52 helpString += "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";
53 helpString += "The step parameter allows you to specify change in distance you would like between each output if you are using the discrete form.\n";
54 helpString += "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";
55 helpString += "The libshuff command should be in the following format: libshuff(groups=yourGroups, iters=yourIters, cutOff=yourCutOff, form=yourForm, step=yourStep).\n";
56 helpString += "Example libshuff(groups=A-B-C, iters=500, form=discrete, step=0.01, cutOff=2.0).\n";
57 helpString += "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";
58 helpString += "The libshuff command output two files: .coverage and .slsummary their descriptions are in the manual.\n";
59 helpString += "Note: No spaces between parameter labels (i.e. iters), '=' and parameters (i.e.yourIters).\n";
63 m->errorOut(e, "LibShuffCommand", "getHelpString");
67 //**********************************************************************************************************************
68 string LibShuffCommand::getOutputFileNameTag(string type, string inputName=""){
70 string outputFileName = "";
71 map<string, vector<string> >::iterator it;
73 //is this a type this command creates
74 it = outputTypes.find(type);
75 if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
77 if (type == "coverage") { outputFileName = "libshuff.coverage"; }
78 else if (type == "libshuffsummary") { outputFileName = "libshuff.summary"; }
79 else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; }
81 return outputFileName;
84 m->errorOut(e, "LibShuffCommand", "getOutputFileNameTag");
88 //**********************************************************************************************************************
89 LibShuffCommand::LibShuffCommand(){
91 abort = true; calledHelp = true;
93 vector<string> tempOutNames;
94 outputTypes["coverage"] = tempOutNames;
95 outputTypes["libshuffsummary"] = tempOutNames;
98 m->errorOut(e, "LibShuffCommand", "LibShuffCommand");
103 //**********************************************************************************************************************
104 LibShuffCommand::LibShuffCommand(string option) {
106 abort = false; calledHelp = false;
108 //allow user to run help
109 if(option == "help") { help(); abort = true; calledHelp = true; }
110 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
113 vector<string> myArray = setParameters();
115 OptionParser parser(option);
116 map<string, string> parameters = parser.getParameters();
117 map<string,string>::iterator it;
119 ValidParameters validParameter;
121 //check to make sure all parameters are valid for command
122 for (it = parameters.begin(); it != parameters.end(); it++) {
123 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
126 //initialize outputTypes
127 vector<string> tempOutNames;
128 outputTypes["coverage"] = tempOutNames;
129 outputTypes["libshuffsummary"] = tempOutNames;
131 string inputDir = validParameter.validFile(parameters, "inputdir", false);
132 if (inputDir == "not found"){ inputDir = ""; }
135 it = parameters.find("phylip");
136 //user has given a template file
137 if(it != parameters.end()){
138 path = m->hasPath(it->second);
139 //if the user has not given a path then, add inputdir. else leave path alone.
140 if (path == "") { parameters["phylip"] = inputDir + it->second; }
143 it = parameters.find("group");
144 //user has given a template file
145 if(it != parameters.end()){
146 path = m->hasPath(it->second);
147 //if the user has not given a path then, add inputdir. else leave path alone.
148 if (path == "") { parameters["group"] = inputDir + it->second; }
152 //check for required parameters
153 phylipfile = validParameter.validFile(parameters, "phylip", true);
154 if (phylipfile == "not open") { phylipfile = ""; abort = true; }
155 else if (phylipfile == "not found") {
156 phylipfile = m->getPhylipFile();
157 if (phylipfile != "") { m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
159 m->mothurOut("You must provide a phylip file."); m->mothurOutEndLine();
162 }else { m->setPhylipFile(phylipfile); }
164 //check for required parameters
165 groupfile = validParameter.validFile(parameters, "group", true);
166 if (groupfile == "not open") { groupfile = ""; abort = true; }
167 else if (groupfile == "not found") {
168 groupfile = m->getGroupFile();
169 if (groupfile != "") { m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine(); }
171 m->mothurOut("You must provide a group file."); m->mothurOutEndLine();
174 }else { m->setGroupFile(groupfile); }
176 //if the user changes the output directory command factory will send this info to us in the output parameter
177 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
179 outputDir += m->hasPath(phylipfile); //if user entered a file with a path then preserve it
182 //check for optional parameter and set defaults
183 // ...at some point should added some additional type checking...
184 groups = validParameter.validFile(parameters, "groups", false);
185 if (groups == "not found") { groups = ""; savegroups = groups; }
188 m->splitAtDash(groups, Groups);
189 m->setGroups(Groups);
193 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "10000"; }
194 m->mothurConvert(temp, iters);
196 temp = validParameter.validFile(parameters, "cutoff", false); if (temp == "not found") { temp = "1.0"; }
197 m->mothurConvert(temp, cutOff);
199 temp = validParameter.validFile(parameters, "step", false); if (temp == "not found") { temp = "0.01"; }
200 m->mothurConvert(temp, step);
202 temp = validParameter.validFile(parameters, "sim", false); if (temp == "not found") { temp = "F"; }
203 sim = m->isTrue(temp);
205 userform = validParameter.validFile(parameters, "form", false); if (userform == "not found") { userform = "integral"; }
210 catch(exception& e) {
211 m->errorOut(e, "LibShuffCommand", "LibShuffCommand");
215 //**********************************************************************************************************************
217 int LibShuffCommand::execute(){
220 if (abort == true) { if (calledHelp) { return 0; } return 2; }
223 groupMap = new GroupMap(groupfile);
224 int error = groupMap->readMap();
225 if (error == 1) { delete groupMap; return 0; }
228 m->openInputFile(phylipfile, in);
229 matrix = new FullMatrix(in, groupMap, sim); //reads the matrix file
232 if (m->control_pressed) { delete groupMap; delete matrix; return 0; }
234 //if files don't match...
235 if (matrix->getNumSeqs() < groupMap->getNumSeqs()) {
236 m->mothurOut("Your distance file contains " + toString(matrix->getNumSeqs()) + " sequences, and your group file contains " + toString(groupMap->getNumSeqs()) + " sequences."); m->mothurOutEndLine();
237 //create new group file
238 if(outputDir == "") { outputDir += m->hasPath(groupfile); }
240 string newGroupFile = outputDir + m->getRootName(m->getSimpleName(groupfile)) + "editted.groups";
241 outputNames.push_back(newGroupFile);
243 m->openOutputFile(newGroupFile, outGroups);
245 for (int i = 0; i < matrix->getNumSeqs(); i++) {
246 if (m->control_pressed) { delete groupMap; delete matrix; outGroups.close(); m->mothurRemove(newGroupFile); return 0; }
248 Names temp = matrix->getRowInfo(i);
249 outGroups << temp.seqName << '\t' << temp.groupName << endl;
253 m->mothurOut(newGroupFile + " is a new group file containing only the sequence that are in your distance file. I will read this file instead."); m->mothurOutEndLine();
257 groupfile = newGroupFile;
259 groupMap = new GroupMap(groupfile);
262 if (m->control_pressed) { delete groupMap; delete matrix; m->mothurRemove(newGroupFile); return 0; }
266 setGroups(); //set the groups to be analyzed and sorts them
268 if (numGroups < 2) { m->mothurOut("[ERROR]: libshuff requires at least 2 groups, you only have " + toString(numGroups) + ", aborting."); m->mothurOutEndLine(); m->control_pressed = true; }
270 if (m->control_pressed) { delete groupMap; delete matrix; return 0; }
272 /********************************************************************************************/
273 //this is needed because when we read the matrix we sort it into groups in alphabetical order
274 //the rest of the command and the classes used in this command assume specific order
275 /********************************************************************************************/
276 matrix->setGroups(groupMap->getNamesOfGroups());
278 for (int i = 0; i < (groupMap->getNamesOfGroups()).size(); i++) { sizes.push_back(groupMap->getNumSeqs((groupMap->getNamesOfGroups())[i])); }
279 matrix->setSizes(sizes);
282 if(userform == "discrete"){
283 form = new DLibshuff(matrix, iters, step, cutOff);
286 form = new SLibshuff(matrix, iters, cutOff);
289 savedDXYValues = form->evaluateAll();
290 savedMinValues = form->getSavedMins();
292 if (m->control_pressed) { delete form; m->clearGroups(); delete matrix; delete groupMap; return 0; }
294 pValueCounts.resize(numGroups);
295 for(int i=0;i<numGroups;i++){
296 pValueCounts[i].assign(numGroups, 0);
299 if (m->control_pressed) { outputTypes.clear(); delete form; m->clearGroups(); delete matrix; delete groupMap; return 0; }
301 Progress* reading = new Progress();
303 for(int i=0;i<numGroups-1;i++) {
304 for(int j=i+1;j<numGroups;j++) {
306 if (m->control_pressed) { outputTypes.clear(); delete form; m->clearGroups(); delete matrix; delete groupMap; delete reading; return 0; }
308 reading->newLine(groupNames[i]+'-'+groupNames[j], iters);
309 int spoti = groupMap->groupIndex[groupNames[i]]; //neccessary in case user selects groups so you know where they are in the matrix
310 int spotj = groupMap->groupIndex[groupNames[j]];
312 for(int p=0;p<iters;p++) {
314 if (m->control_pressed) { outputTypes.clear(); delete form; m->clearGroups(); delete matrix; delete groupMap; delete reading; return 0; }
316 form->randomizeGroups(spoti,spotj);
317 if(form->evaluatePair(spoti,spotj) >= savedDXYValues[spoti][spotj]) { pValueCounts[i][j]++; }
318 if(form->evaluatePair(spotj,spoti) >= savedDXYValues[spotj][spoti]) { pValueCounts[j][i]++; }
320 if (m->control_pressed) { outputTypes.clear(); delete form; m->clearGroups(); delete matrix; delete groupMap; delete reading; return 0; }
324 form->resetGroup(spoti);
325 form->resetGroup(spotj);
329 if (m->control_pressed) { outputTypes.clear(); delete form; m->clearGroups(); delete matrix; delete groupMap; delete reading; return 0; }
334 m->mothurOutEndLine();
338 //clear out users groups
342 delete matrix; delete groupMap;
344 if (m->control_pressed) { outputTypes.clear(); for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
346 m->mothurOutEndLine();
347 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
348 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
349 m->mothurOutEndLine();
353 catch(exception& e) {
354 m->errorOut(e, "LibShuffCommand", "execute");
359 //**********************************************************************************************************************
361 int LibShuffCommand::printCoverageFile() {
365 summaryFile = outputDir + m->getRootName(m->getSimpleName(phylipfile)) + getOutputFileNameTag("coverage");
366 m->openOutputFile(summaryFile, outCov);
367 outputNames.push_back(summaryFile); outputTypes["coverage"].push_back(summaryFile);
368 outCov.setf(ios::fixed, ios::floatfield); outCov.setf(ios::showpoint);
369 //cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
371 map<double,vector<int> > allDistances;
372 map<double,vector<int> >::iterator it;
374 vector<vector<int> > indices(numGroups);
375 int numIndices = numGroups * numGroups;
378 for(int i=0;i<numGroups;i++){
379 indices[i].assign(numGroups,0);
380 for(int j=0;j<numGroups;j++){
381 indices[i][j] = index++;
383 int spoti = groupMap->groupIndex[groupNames[i]]; //neccessary in case user selects groups so you know where they are in the matrix
384 int spotj = groupMap->groupIndex[groupNames[j]];
386 for(int k=0;k<savedMinValues[spoti][spotj].size();k++){
388 if(m->control_pressed) { outCov.close(); return 0; }
390 if(allDistances[savedMinValues[spoti][spotj][k]].size() != 0){
391 allDistances[savedMinValues[spoti][spotj][k]][indices[i][j]]++;
394 allDistances[savedMinValues[spoti][spotj][k]].assign(numIndices, 0);
395 allDistances[savedMinValues[spoti][spotj][k]][indices[i][j]] = 1;
400 it=allDistances.begin();
402 //cout << setprecision(8);
404 vector<int> prevRow = it->second;
407 for(;it!=allDistances.end();it++){
408 for(int i=0;i<it->second.size();i++){
409 it->second[i] += prevRow[i];
411 prevRow = it->second;
414 vector<int> lastRow = allDistances.rbegin()->second;
415 outCov << setprecision(8);
418 for (int i = 0; i < numGroups; i++){
419 outCov << '\t' << groupNames[i];
421 for (int i=0;i<numGroups;i++){
422 for(int j=i+1;j<numGroups;j++){
423 if(m->control_pressed) { outCov.close(); return 0; }
424 outCov << '\t' << groupNames[i] << '-' << groupNames[j] << '\t';
425 outCov << groupNames[j] << '-' << groupNames[i];
430 for(it=allDistances.begin();it!=allDistances.end();it++){
431 outCov << it->first << '\t';
432 for(int i=0;i<numGroups;i++){
433 outCov << it->second[indices[i][i]]/(float)lastRow[indices[i][i]] << '\t';
435 for(int i=0;i<numGroups;i++){
436 for(int j=i+1;j<numGroups;j++){
437 if(m->control_pressed) { outCov.close(); return 0; }
439 outCov << it->second[indices[i][j]]/(float)lastRow[indices[i][j]] << '\t';
440 outCov << it->second[indices[j][i]]/(float)lastRow[indices[j][i]] << '\t';
449 catch(exception& e) {
450 m->errorOut(e, "LibShuffCommand", "printCoverageFile");
455 //**********************************************************************************************************************
457 int LibShuffCommand::printSummaryFile() {
461 summaryFile = outputDir + m->getRootName(m->getSimpleName(phylipfile)) + getOutputFileNameTag("libshuffsummary");
462 m->openOutputFile(summaryFile, outSum);
463 outputNames.push_back(summaryFile); outputTypes["libshuffsummary"].push_back(summaryFile);
465 outSum.setf(ios::fixed, ios::floatfield); outSum.setf(ios::showpoint);
466 cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
468 cout << setw(20) << left << "Comparison" << '\t' << setprecision(8) << "dCXYScore" << '\t' << "Significance" << endl;
469 m->mothurOutJustToLog("Comparison\tdCXYScore\tSignificance"); m->mothurOutEndLine();
470 outSum << setw(20) << left << "Comparison" << '\t' << setprecision(8) << "dCXYScore" << '\t' << "Significance" << endl;
472 int precision = (int)log10(iters);
473 for(int i=0;i<numGroups;i++){
474 for(int j=i+1;j<numGroups;j++){
475 if(m->control_pressed) { outSum.close(); return 0; }
477 int spoti = groupMap->groupIndex[groupNames[i]]; //neccessary in case user selects groups so you know where they are in the matrix
478 int spotj = groupMap->groupIndex[groupNames[j]];
480 if(pValueCounts[i][j]){
481 cout << setw(20) << left << groupNames[i]+'-'+groupNames[j] << '\t' << setprecision(8) << savedDXYValues[spoti][spotj] << '\t' << setprecision(precision) << pValueCounts[i][j]/(float)iters << endl;
482 m->mothurOutJustToLog(groupNames[i]+"-"+groupNames[j] + "\t" + toString(savedDXYValues[spoti][spotj]) + "\t" + toString((pValueCounts[i][j]/(float)iters))); m->mothurOutEndLine();
483 outSum << setw(20) << left << groupNames[i]+'-'+groupNames[j] << '\t' << setprecision(8) << savedDXYValues[spoti][spotj] << '\t' << setprecision(precision) << pValueCounts[i][j]/(float)iters << endl;
486 cout << setw(20) << left << groupNames[i]+'-'+groupNames[j] << '\t' << setprecision(8) << savedDXYValues[spoti][spotj] << '\t' << '<' <<setprecision(precision) << 1/(float)iters << endl;
487 m->mothurOutJustToLog(groupNames[i]+"-"+groupNames[j] + "\t" + toString(savedDXYValues[spoti][spotj]) + "\t" + toString((1/(float)iters))); m->mothurOutEndLine();
488 outSum << setw(20) << left << groupNames[i]+'-'+groupNames[j] << '\t' << setprecision(8) << savedDXYValues[spoti][spotj] << '\t' << '<' <<setprecision(precision) << 1/(float)iters << endl;
490 if(pValueCounts[j][i]){
491 cout << setw(20) << left << groupNames[j]+'-'+groupNames[i] << '\t' << setprecision(8) << savedDXYValues[spotj][spoti] << '\t' << setprecision (precision) << pValueCounts[j][i]/(float)iters << endl;
492 m->mothurOutJustToLog(groupNames[j]+"-"+groupNames[i] + "\t" + toString(savedDXYValues[spotj][spoti]) + "\t" + toString((pValueCounts[j][i]/(float)iters))); m->mothurOutEndLine();
493 outSum << setw(20) << left << groupNames[j]+'-'+groupNames[i] << '\t' << setprecision(8) << savedDXYValues[spotj][spoti] << '\t' << setprecision (precision) << pValueCounts[j][i]/(float)iters << endl;
496 cout << setw(20) << left << groupNames[j]+'-'+groupNames[i] << '\t' << setprecision(8) << savedDXYValues[spotj][spoti] << '\t' << '<' <<setprecision (precision) << 1/(float)iters << endl;
497 m->mothurOutJustToLog(groupNames[j]+"-"+groupNames[i] + "\t" + toString(savedDXYValues[spotj][spoti]) + "\t" + toString((1/(float)iters))); m->mothurOutEndLine();
498 outSum << setw(20) << left << groupNames[j]+'-'+groupNames[i] << '\t' << setprecision(8) << savedDXYValues[spotj][spoti] << '\t' << '<' <<setprecision (precision) << 1/(float)iters << endl;
506 catch(exception& e) {
507 m->errorOut(e, "LibShuffCommand", "printSummaryFile");
512 //**********************************************************************************************************************
514 void LibShuffCommand::setGroups() {
516 vector<string> myGroups = m->getGroups();
517 //if the user has not entered specific groups to analyze then do them all
518 if (m->getNumGroups() == 0) {
519 numGroups = groupMap->getNumGroups();
520 for (int i=0; i < numGroups; i++) {
521 myGroups.push_back((groupMap->getNamesOfGroups())[i]);
524 if (savegroups != "all") {
525 //check that groups are valid
526 for (int i = 0; i < myGroups.size(); i++) {
527 if (groupMap->isValidGroup(myGroups[i]) != true) {
528 m->mothurOut(myGroups[i] + " is not a valid group, and will be disregarded."); m->mothurOutEndLine();
529 // erase the invalid group from globaldata->Groups
530 myGroups.erase(myGroups.begin()+i);
534 //if the user only entered invalid groups
535 if ((myGroups.size() == 0) || (myGroups.size() == 1)) {
536 numGroups = groupMap->getNumGroups();
537 for (int i=0; i < numGroups; i++) {
538 myGroups.push_back((groupMap->getNamesOfGroups())[i]);
540 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();
541 } else { numGroups = myGroups.size(); }
542 } else { //users wants all groups
543 numGroups = groupMap->getNumGroups();
545 for (int i=0; i < numGroups; i++) {
546 myGroups.push_back((groupMap->getNamesOfGroups())[i]);
551 //sort so labels match
552 sort(myGroups.begin(), myGroups.end());
555 //sort(groupMap->namesOfGroups.begin(), groupMap->namesOfGroups.end());
557 for (int i = 0; i < (groupMap->getNamesOfGroups()).size(); i++) { groupMap->groupIndex[(groupMap->getNamesOfGroups())[i]] = i; }
559 groupNames = myGroups;
560 m->setGroups(myGroups);
563 catch(exception& e) {
564 m->errorOut(e, "LibShuffCommand", "setGroups");
569 /***********************************************************/