2 * cooccurrencecommand.cpp
5 * Created by kiverson on 1/2/12.
6 * Copyright 2012 Schloss Lab. All rights reserved.
10 #include "cooccurrencecommand.h"
12 //**********************************************************************************************************************
13 vector<string> CooccurrenceCommand::setParameters() {
15 CommandParameter pshared("shared", "InputTypes", "", "", "none", "none", "none","summary",false,true,true); parameters.push_back(pshared);
16 CommandParameter pmetric("metric", "Multiple", "cscore-checker-combo-vratio", "cscore", "", "", "","",false,false); parameters.push_back(pmetric);
17 CommandParameter pmatrix("matrixmodel", "Multiple", "sim1-sim2-sim3-sim4-sim5-sim6-sim7-sim8-sim9", "sim2", "", "", "","",false,false); parameters.push_back(pmatrix);
18 CommandParameter pruns("iters", "Number", "", "1000", "", "", "","",false,false); parameters.push_back(pruns);
19 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
20 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
21 CommandParameter plabel("label", "String", "", "", "", "", "","",false,false); parameters.push_back(plabel);
22 CommandParameter pgroups("groups", "String", "", "", "", "", "","",false,false); parameters.push_back(pgroups);
24 vector<string> myArray;
25 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
29 m->errorOut(e, "CooccurrenceCommand", "setParameters");
33 //**********************************************************************************************************************
34 string CooccurrenceCommand::getHelpString(){
36 string helpString = "The cooccurrence command calculates four metrics and tests their significance to assess whether presence-absence patterns are different than what one would expect by chance.";
37 helpString += "The cooccurrence command parameters are shared, metric, matrixmodel, iters, label and groups.";
38 helpString += "The matrixmodel parameter options are sim1, sim2, sim3, sim4, sim5, sim6, sim7, sim8 and sim9. Default=sim2";
39 helpString += "The metric parameter options are cscore, checker, combo and vratio. Default=cscore";
40 helpString += "The label parameter is used to analyze specific labels in your input.\n";
41 helpString += "The groups parameter allows you to specify which of the groups you would like analyzed.\n";
42 helpString += "The cooccurrence command should be in the following format: \n";
43 helpString += "cooccurrence(shared=yourSharedFile) \n";
44 helpString += "Example cooccurrence(shared=final.an.shared).\n";
45 helpString += "Note: No spaces between parameter labels (i.e. shared), '=' and parameters (i.e.yourShared).\n";
49 m->errorOut(e, "CooccurrenceCommand", "getHelpString");
53 //**********************************************************************************************************************
54 string CooccurrenceCommand::getOutputPattern(string type) {
58 if (type == "summary") { pattern = "[filename],cooccurence.summary"; }
59 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
64 m->errorOut(e, "CooccurrenceCommand", "getOutputPattern");
68 //**********************************************************************************************************************
69 CooccurrenceCommand::CooccurrenceCommand(){
71 abort = true; calledHelp = true;
73 vector<string> tempOutNames;
74 outputTypes["summary"] = tempOutNames;
78 m->errorOut(e, "CooccurrenceCommand", "CooccurrenceCommand");
82 //**********************************************************************************************************************
83 CooccurrenceCommand::CooccurrenceCommand(string option) {
85 abort = false; calledHelp = false;
88 //allow user to run help
89 if(option == "help") { help(); abort = true; calledHelp = true; }
90 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
93 vector<string> myArray = setParameters();
95 OptionParser parser(option);
96 map<string,string> parameters = parser.getParameters();
97 map<string,string>::iterator it;
99 ValidParameters validParameter;
101 //check to make sure all parameters are valid for command
102 for (it = parameters.begin(); it != parameters.end(); it++) {
103 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
107 //if the user changes the input directory command factory will send this info to us in the output parameter
108 string inputDir = validParameter.validFile(parameters, "inputdir", false);
109 if (inputDir == "not found"){ inputDir = ""; }
112 it = parameters.find("shared");
113 //user has given a template file
114 if(it != parameters.end()){
115 path = m->hasPath(it->second);
116 //if the user has not given a path then, add inputdir. else leave path alone.
117 if (path == "") { parameters["shared"] = inputDir + it->second; }
121 vector<string> tempOutNames;
122 outputTypes["summary"] = tempOutNames;
124 //check for optional parameter and set defaults
125 // ...at some point should added some additional type checking...
126 label = validParameter.validFile(parameters, "label", false);
127 if (label == "not found") { label = ""; }
129 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
130 else { allLines = 1; }
134 sharedfile = validParameter.validFile(parameters, "shared", true);
135 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
136 else if (sharedfile == "not found") {
137 //if there is a current shared file, use it
138 sharedfile = m->getSharedFile();
139 if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
140 else { m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
141 }else { m->setSharedFile(sharedfile); }
144 //if the user changes the output directory command factory will send this info to us in the output parameter
145 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = m->hasPath(sharedfile); }
148 metric = validParameter.validFile(parameters, "metric", false); if (metric == "not found") { metric = "cscore"; }
150 if ((metric != "cscore") && (metric != "checker") && (metric != "combo") && (metric != "vratio")) {
151 m->mothurOut("[ERROR]: " + metric + " is not a valid metric option for the cooccurrence command. Choices are cscore, checker, combo, vratio."); m->mothurOutEndLine(); abort = true;
154 matrix = validParameter.validFile(parameters, "matrixmodel", false); if (matrix == "not found") { matrix = "sim2"; }
156 if ((matrix != "sim1") && (matrix != "sim2") && (matrix != "sim3") && (matrix != "sim4") && (matrix != "sim5" ) && (matrix != "sim6" ) && (matrix != "sim7" ) && (matrix != "sim8" ) && (matrix != "sim9" )) {
157 m->mothurOut("[ERROR]: " + matrix + " is not a valid matrix option for the cooccurrence command. Choices are sim1, sim2, sim3, sim4, sim5, sim6, sim7, sim8, sim9."); m->mothurOutEndLine(); abort = true;
160 groups = validParameter.validFile(parameters, "groups", false);
161 if (groups == "not found") { groups = ""; }
163 m->splitAtDash(groups, Groups);
165 m->setGroups(Groups);
167 string temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
168 m->mothurConvert(temp, runs);
173 catch(exception& e) {
174 m->errorOut(e, "CooccurrenceCommand", "CooccurrenceCommand");
178 //**********************************************************************************************************************
180 int CooccurrenceCommand::execute(){
183 if (abort == true) { if (calledHelp) { return 0; } return 2; }
185 InputData* input = new InputData(sharedfile, "sharedfile");
186 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
187 string lastLabel = lookup[0]->getLabel();
189 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
190 set<string> processedLabels;
191 set<string> userLabels = labels;
194 map<string, string> variables;
195 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(sharedfile));
196 string outputFileName = getOutputFileName("summary", variables);
197 m->openOutputFile(outputFileName, out);
198 outputNames.push_back(outputFileName); outputTypes["summary"].push_back(outputFileName);
199 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
200 out << "metric\tlabel\tScore\tzScore\tstandardDeviation\tnp_Pvalue\n";
202 //as long as you are not at the end of the file or done wih the lines you want
203 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
205 if (m->control_pressed) { for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } delete input; out.close(); m->mothurRemove(outputFileName); return 0; }
207 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
209 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
211 getCooccurrence(lookup, out);
213 processedLabels.insert(lookup[0]->getLabel());
214 userLabels.erase(lookup[0]->getLabel());
217 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
218 string saveLabel = lookup[0]->getLabel();
220 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
221 lookup = input->getSharedRAbundVectors(lastLabel);
222 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
223 getCooccurrence(lookup, out);
225 processedLabels.insert(lookup[0]->getLabel());
226 userLabels.erase(lookup[0]->getLabel());
228 //restore real lastlabel to save below
229 lookup[0]->setLabel(saveLabel);
232 lastLabel = lookup[0]->getLabel();
233 //prevent memory leak
234 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; lookup[i] = NULL; }
236 if (m->control_pressed) { outputTypes.clear(); delete input; out.close(); m->mothurRemove(outputFileName); return 0; }
238 //get next line to process
239 lookup = input->getSharedRAbundVectors();
242 if (m->control_pressed) { delete input; out.close(); m->mothurRemove(outputFileName); return 0; }
244 //output error messages about any remaining user labels
245 set<string>::iterator it;
246 bool needToRun = false;
247 for (it = userLabels.begin(); it != userLabels.end(); it++) {
248 m->mothurOut("Your file does not include the label " + *it);
249 if (processedLabels.count(lastLabel) != 1) {
250 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
253 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
257 //run last label if you need to
258 if (needToRun == true) {
259 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
260 lookup = input->getSharedRAbundVectors(lastLabel);
262 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
264 getCooccurrence(lookup, out);
266 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
271 //reset groups parameter
275 m->mothurOutEndLine();
276 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
277 m->mothurOut(outputFileName); m->mothurOutEndLine();
278 m->mothurOutEndLine();
282 catch(exception& e) {
283 m->errorOut(e, "CooccurrenceCommand", "execute");
287 //**********************************************************************************************************************
289 int CooccurrenceCommand::getCooccurrence(vector<SharedRAbundVector*>& thisLookUp, ofstream& out){
291 int numOTUS = thisLookUp[0]->getNumBins();
294 m->mothurOut("Not enough OTUs for co-occurrence analysis, skipping"); m->mothurOutEndLine();
298 vector< vector<int> > co_matrix; co_matrix.resize(thisLookUp[0]->getNumBins());
299 for (int i = 0; i < thisLookUp[0]->getNumBins(); i++) { co_matrix[i].resize((thisLookUp.size()), 0); }
300 vector<int> columntotal; columntotal.resize(thisLookUp.size(), 0);
301 vector<int> rowtotal; rowtotal.resize(numOTUS, 0);
303 for (int i = 0; i < thisLookUp.size(); i++) { //nrows in the shared file
304 for (int j = 0; j < thisLookUp[i]->getNumBins(); j++) { //cols of original shared file
305 if (m->control_pressed) { return 0; }
306 int abund = thisLookUp[i]->getAbundance(j);
316 //nrows is ncols of inital matrix. All the functions need this value. They assume the transposition has already taken place and nrows and ncols refer to that matrix.
317 //comatrix and initmatrix are still vectors of vectors of ints as in the original script. The abundancevector is only what was read in ie not a co-occurrence matrix!
318 int nrows = numOTUS;//rows of inital matrix
319 int ncols = thisLookUp.size();//groups
320 double initscore = 0.0;
322 vector<double> stats;
323 vector<double> probabilityMatrix; probabilityMatrix.resize(ncols * nrows, 0);
324 vector<vector<int> > nullmatrix(nrows, vector<int>(ncols, 0));
328 int n = accumulate( columntotal.begin(), columntotal.end(), 0 );
330 //============================================================
332 //generate a probability matrix. Only do this once.
335 if (matrix == "sim1") {
336 for(int i=0;i<nrows;i++) {
337 for(int j=0;j<ncols;j++) {
338 probabilityMatrix[ncols * i + j] = start + 1/double(nrows*ncols);
339 start = start + 1/double(nrows*ncols);
343 //don't need a prob matrix because we just shuffle the rows, may use this in the future
344 else if (matrix == "sim2") { }
345 // for(int i=0;i<nrows;i++) {
347 // for(int j=0;j<ncols;j++) {
348 // probabilityMatrix[ncols * i + j] = start + 1/double(ncols);
349 // start = start + 1/double(ncols);
354 else if (matrix == "sim3") {
355 for(int j=0;j<ncols;j++) {
357 for(int i=0;i<nrows;i++) {
358 probabilityMatrix[ncols * i + j] = start + 1/double(nrows);
359 start = start + 1/double(nrows);
364 else if (matrix == "sim4") {
365 for(int i=0;i<nrows;i++) {
367 for(int j=0;j<ncols;j++) {
368 probabilityMatrix[ncols * i + j] = start + columntotal[j]/double(n);
369 start = start + columntotal[j]/double(n);
374 else if (matrix == "sim5") {
375 for(int j=0;j<ncols;j++) {
377 for(int i=0;i<nrows;i++) {
378 probabilityMatrix[ncols * i + j] = start + rowtotal[i]/double(n);
379 start = start + rowtotal[i]/double(n);
384 else if (matrix == "sim6") {
385 for(int i=0;i<nrows;i++) {
386 for(int j=0;j<ncols;j++) {
387 probabilityMatrix[ncols * i + j] = start + columntotal[j]/double(n*nrows);
388 start = start + columntotal[j]/double(n*nrows);
394 else if (matrix == "sim7") {
395 for(int i=0;i<nrows;i++) {
396 for(int j=0;j<ncols;j++) {
397 probabilityMatrix[ncols * i + j] = start + rowtotal[i]/double(n*ncols);
398 start = start + rowtotal[i]/double(n*ncols);
403 else if (matrix == "sim8") {
404 for(int i=0;i<nrows;i++) {
405 for(int j=0;j<ncols;j++) {
406 probabilityMatrix[ncols * i + j] = start + (rowtotal[i]*columntotal[j])/double(n*n);
407 start = start + (rowtotal[i]*columntotal[j])/double(n*n);
411 else if (matrix == "sim9" || matrix == "sim2") { }
413 m->mothurOut("[ERROR]: No model selected! \n");
414 m->control_pressed = true;
418 //co_matrix is the transposed shared file, initmatrix is the original shared file
419 if (metric == "cscore") { initscore = trial.calc_c_score(co_matrix, rowtotal, ncols, nrows); }
420 else if (metric == "checker") { initscore = trial.calc_checker(co_matrix, rowtotal, ncols, nrows); }
421 else if (metric == "vratio") { initscore = trial.calc_vratio(nrows, ncols, rowtotal, columntotal); }
422 else if (metric == "combo") { initscore = trial.calc_combo(nrows, ncols, co_matrix); }
423 else { m->mothurOut("[ERROR]: No metric selected!\n"); m->control_pressed = true; return 1; }
425 m->mothurOut("Initial c score: " + toString(initscore)); m->mothurOutEndLine();
433 if(matrix == "sim9") {
434 for(int i=0;i<10000;i++) trial.swap_checkerboards (co_matrix, ncols, nrows);
437 //populate null matrix from probability matrix, do this a lot.
438 for(int k=0;k<runs;k++){
440 //zero-fill the null matrix
441 nullmatrix.assign(nrows, vector<int>(ncols, 0));
443 if(matrix == "sim1" || matrix == "sim6" || matrix == "sim8" || matrix == "sim7") {
446 if (m->control_pressed) { return 0; }
449 randnum = rand() / double(RAND_MAX);
450 for(int i=0;i<nrows;i++) {
451 for(int j=0;j<ncols;j++) {
452 current = probabilityMatrix[ncols * i + j];
453 if(randnum <= current && randnum > previous) {
454 nullmatrix[i][j] = 1;
456 if (count > n) break;
466 else if (matrix == "sim2") {
467 for(int i=0;i<nrows;i++) {
468 random_shuffle( co_matrix[i].begin(), co_matrix[i].end() );
470 //do this for the scoring since those all have nullmatrix as a parameter
471 //nullmatrix gets cleared at the begining of each run
472 nullmatrix = co_matrix;
475 else if(matrix == "sim4") {
476 for(int i=0;i<nrows;i++) {
478 while(count < rowtotal[i]) {
480 if (m->control_pressed) { return 0; }
481 randnum = rand() / double(RAND_MAX);
482 for(int j=0;j<ncols;j++) {
483 current = probabilityMatrix[ncols * i + j];
484 if(randnum <= current && randnum > previous && nullmatrix[i][j] != 1) {
485 nullmatrix[i][j] = 1;
496 else if(matrix == "sim3" || matrix == "sim5") {
498 for(int j=0;j<ncols;j++) {
500 while(count < columntotal[j]) {
501 if (m->control_pressed) { return 0; }
502 randnum = rand() / double(RAND_MAX);
503 for(int i=0;i<nrows;i++) {
504 current = probabilityMatrix[ncols * i + j];
505 if(randnum <= current && randnum > previous && nullmatrix[i][j] != 1) {
506 nullmatrix[i][j] = 1;
517 //swap_checkerboards takes the original matrix and swaps checkerboards
518 else if(matrix == "sim9") {
519 trial.swap_checkerboards (co_matrix, ncols, nrows);
520 nullmatrix = co_matrix;
523 m->mothurOut("[ERROR]: No null model selected!\n\n"); m->control_pressed = true;
527 //run metric on null matrix and add score to the stats vector
528 if (metric == "cscore"){
529 stats.push_back(trial.calc_c_score(nullmatrix, rowtotal, ncols, nrows));
531 else if (metric == "checker") {
532 stats.push_back(trial.calc_checker(nullmatrix, rowtotal, ncols, nrows));
534 else if (metric == "vratio") {
535 stats.push_back(trial.calc_vratio(nrows, ncols, rowtotal, columntotal));
537 else if (metric == "combo") {
538 stats.push_back(trial.calc_combo(nrows, ncols, nullmatrix));
541 m->mothurOut("[ERROR]: No metric selected!\n\n"); m->control_pressed = true;
550 for (int i=0; i<stats.size();i++) { total+=stats[i]; }
552 double nullMean = double (total/(double)stats.size());
554 m->mothurOutEndLine(); m->mothurOut("average metric score: " + toString(nullMean)); m->mothurOutEndLine();
556 //calc_p_value is not a statistical p-value, it's just the average that are either > or < the initscore.
557 //All it does is show what is expected in a competitively structured community
558 //zscore is output so p-value can be looked up in a ztable
560 if (metric == "cscore" || metric == "checker") { pvalue = trial.calc_pvalue_greaterthan (stats, initscore); }
561 else{ pvalue = trial.calc_pvalue_lessthan (stats, initscore); }
563 double sd = trial.getSD(runs, stats, nullMean);
565 double zscore = trial.get_zscore(sd, nullMean, initscore);
567 m->mothurOut("zscore: " + toString(zscore)); m->mothurOutEndLine();
568 m->mothurOut("standard deviation: " + toString(sd)); m->mothurOutEndLine();
569 m->mothurOut("non-parametric p-value: " + toString(pvalue)); m->mothurOutEndLine();
570 out << metric << '\t' << thisLookUp[0]->getLabel() << '\t' << nullMean << '\t' << zscore << '\t' << sd << '\t' << pvalue << endl;
574 catch(exception& e) {
575 m->errorOut(e, "CooccurrenceCommand", "Cooccurrence");
579 //**********************************************************************************************************************