2 * matrixoutputcommand.cpp
5 * Created by Sarah Westcott on 5/20/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "matrixoutputcommand.h"
11 #include "sharedsobscollectsummary.h"
12 #include "sharedchao1.h"
13 #include "sharedace.h"
14 #include "sharednseqs.h"
15 #include "sharedjabund.h"
16 #include "sharedsorabund.h"
17 #include "sharedjclass.h"
18 #include "sharedsorclass.h"
19 #include "sharedjest.h"
20 #include "sharedsorest.h"
21 #include "sharedthetayc.h"
22 #include "sharedthetan.h"
23 #include "sharedkstest.h"
24 #include "whittaker.h"
25 #include "sharedochiai.h"
26 #include "sharedanderbergs.h"
27 #include "sharedkulczynski.h"
28 #include "sharedkulczynskicody.h"
29 #include "sharedlennon.h"
30 #include "sharedmorisitahorn.h"
31 #include "sharedbraycurtis.h"
32 #include "sharedjackknife.h"
33 #include "whittaker.h"
36 #include "structeuclidean.h"
37 #include "structchord.h"
38 #include "hellinger.h"
39 #include "manhattan.h"
40 #include "structpearson.h"
43 #include "structkulczynski.h"
44 #include "structchi2.h"
45 #include "speciesprofile.h"
50 #include "memeuclidean.h"
51 #include "mempearson.h"
53 //**********************************************************************************************************************
54 vector<string> MatrixOutputCommand::setParameters(){
56 CommandParameter pshared("shared", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pshared);
57 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
58 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
59 CommandParameter pcalc("calc", "Multiple", "sharedsobs-sharedchao-sharedace-jabund-sorabund-jclass-sorclass-jest-sorest-thetayc-thetan-kstest-sharednseqs-ochiai-anderberg-kulczynski-kulczynskicody-lennon-morisitahorn-braycurtis-whittaker-odum-canberra-structeuclidean-structchord-hellinger-manhattan-structpearson-soergel-spearman-structkulczynski-speciesprofile-hamming-structchi2-gower-memchi2-memchord-memeuclidean-mempearson", "jclass-thetayc", "", "", "",true,false); parameters.push_back(pcalc);
60 CommandParameter poutput("output", "Multiple", "lt-square", "lt", "", "", "",false,false); parameters.push_back(poutput);
61 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
62 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
63 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
65 vector<string> myArray;
66 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
70 m->errorOut(e, "MatrixOutputCommand", "setParameters");
74 //**********************************************************************************************************************
75 string MatrixOutputCommand::getHelpString(){
77 string helpString = "";
78 ValidCalculators validCalculator;
79 helpString += "The dist.shared command parameters are shared, groups, calc, output, processors and label. shared is a required, unless you have a valid current file.\n";
80 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n";
81 helpString += "The group names are separated by dashes. The label parameter allows you to select what distance levels you would like distance matrices created for, and is also separated by dashes.\n";
82 helpString += "The dist.shared command should be in the following format: dist.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels).\n";
83 helpString += "The output parameter allows you to specify format of your distance matrix. Options are lt, and square. The default is lt.\n";
84 helpString += "Example dist.shared(groups=A-B-C, calc=jabund-sorabund).\n";
85 helpString += "The default value for groups is all the groups in your groupfile.\n";
86 helpString += "The default value for calc is jclass and thetayc.\n";
87 helpString += validCalculator.printCalc("matrix");
88 helpString += "The dist.shared command outputs a .dist file for each calculator you specify at each distance you choose.\n";
89 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
93 m->errorOut(e, "MatrixOutputCommand", "getHelpString");
97 //**********************************************************************************************************************
98 MatrixOutputCommand::MatrixOutputCommand(){
100 abort = true; calledHelp = true;
102 vector<string> tempOutNames;
103 outputTypes["phylip"] = tempOutNames;
105 catch(exception& e) {
106 m->errorOut(e, "MatrixOutputCommand", "MatrixOutputCommand");
110 //**********************************************************************************************************************
112 MatrixOutputCommand::MatrixOutputCommand(string option) {
114 abort = false; calledHelp = false;
117 //allow user to run help
118 if(option == "help") { help(); abort = true; calledHelp = true; }
119 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
122 vector<string> myArray = setParameters();
124 OptionParser parser(option);
125 map<string,string> parameters = parser.getParameters();
126 map<string,string>::iterator it;
128 ValidParameters validParameter;
130 //check to make sure all parameters are valid for command
131 for (it = parameters.begin(); it != parameters.end(); it++) {
132 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
135 //initialize outputTypes
136 vector<string> tempOutNames;
137 outputTypes["phylip"] = tempOutNames;
139 //if the user changes the input directory command factory will send this info to us in the output parameter
140 string inputDir = validParameter.validFile(parameters, "inputdir", false);
141 if (inputDir == "not found"){ inputDir = ""; }
144 it = parameters.find("shared");
145 //user has given a template file
146 if(it != parameters.end()){
147 path = m->hasPath(it->second);
148 //if the user has not given a path then, add inputdir. else leave path alone.
149 if (path == "") { parameters["shared"] = inputDir + it->second; }
153 sharedfile = validParameter.validFile(parameters, "shared", true);
154 if (sharedfile == "not found") {
155 //if there is a current shared file, use it
156 sharedfile = m->getSharedFile();
157 if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
158 else { m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
159 }else if (sharedfile == "not open") { sharedfile = ""; abort = true; }
161 //if the user changes the output directory command factory will send this info to us in the output parameter
162 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
164 outputDir += m->hasPath(sharedfile); //if user entered a file with a path then preserve it
167 //check for optional parameter and set defaults
168 // ...at some point should added some additional type checking...
169 label = validParameter.validFile(parameters, "label", false);
170 if (label == "not found") { label = ""; }
172 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
173 else { allLines = 1; }
176 output = validParameter.validFile(parameters, "output", false); if(output == "not found"){ output = "lt"; }
177 if ((output != "lt") && (output != "square")) { m->mothurOut(output + " is not a valid output form. Options are lt and square. I will use lt."); m->mothurOutEndLine(); output = "lt"; }
179 groups = validParameter.validFile(parameters, "groups", false);
180 if (groups == "not found") { groups = ""; }
182 m->splitAtDash(groups, Groups);
186 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
187 m->setProcessors(temp);
188 convert(temp, processors);
190 calc = validParameter.validFile(parameters, "calc", false);
191 if (calc == "not found") { calc = "jclass-thetayc"; }
193 if (calc == "default") { calc = "jclass-thetayc"; }
195 m->splitAtDash(calc, Estimators);
196 if (m->inUsersGroups("citation", Estimators)) {
197 ValidCalculators validCalc; validCalc.printCitations(Estimators);
198 //remove citation from list of calcs
199 for (int i = 0; i < Estimators.size(); i++) { if (Estimators[i] == "citation") { Estimators.erase(Estimators.begin()+i); break; } }
202 if (abort == false) {
204 ValidCalculators validCalculator;
207 for (i=0; i<Estimators.size(); i++) {
208 if (validCalculator.isValidCalculator("matrix", Estimators[i]) == true) {
209 if (Estimators[i] == "sharedsobs") {
210 matrixCalculators.push_back(new SharedSobsCS());
211 }else if (Estimators[i] == "sharedchao") {
212 matrixCalculators.push_back(new SharedChao1());
213 }else if (Estimators[i] == "sharedace") {
214 matrixCalculators.push_back(new SharedAce());
215 }else if (Estimators[i] == "jabund") {
216 matrixCalculators.push_back(new JAbund());
217 }else if (Estimators[i] == "sorabund") {
218 matrixCalculators.push_back(new SorAbund());
219 }else if (Estimators[i] == "jclass") {
220 matrixCalculators.push_back(new Jclass());
221 }else if (Estimators[i] == "sorclass") {
222 matrixCalculators.push_back(new SorClass());
223 }else if (Estimators[i] == "jest") {
224 matrixCalculators.push_back(new Jest());
225 }else if (Estimators[i] == "sorest") {
226 matrixCalculators.push_back(new SorEst());
227 }else if (Estimators[i] == "thetayc") {
228 matrixCalculators.push_back(new ThetaYC());
229 }else if (Estimators[i] == "thetan") {
230 matrixCalculators.push_back(new ThetaN());
231 }else if (Estimators[i] == "kstest") {
232 matrixCalculators.push_back(new KSTest());
233 }else if (Estimators[i] == "sharednseqs") {
234 matrixCalculators.push_back(new SharedNSeqs());
235 }else if (Estimators[i] == "ochiai") {
236 matrixCalculators.push_back(new Ochiai());
237 }else if (Estimators[i] == "anderberg") {
238 matrixCalculators.push_back(new Anderberg());
239 }else if (Estimators[i] == "kulczynski") {
240 matrixCalculators.push_back(new Kulczynski());
241 }else if (Estimators[i] == "kulczynskicody") {
242 matrixCalculators.push_back(new KulczynskiCody());
243 }else if (Estimators[i] == "lennon") {
244 matrixCalculators.push_back(new Lennon());
245 }else if (Estimators[i] == "morisitahorn") {
246 matrixCalculators.push_back(new MorHorn());
247 }else if (Estimators[i] == "braycurtis") {
248 matrixCalculators.push_back(new BrayCurtis());
249 }else if (Estimators[i] == "whittaker") {
250 matrixCalculators.push_back(new Whittaker());
251 }else if (Estimators[i] == "odum") {
252 matrixCalculators.push_back(new Odum());
253 }else if (Estimators[i] == "canberra") {
254 matrixCalculators.push_back(new Canberra());
255 }else if (Estimators[i] == "structeuclidean") {
256 matrixCalculators.push_back(new StructEuclidean());
257 }else if (Estimators[i] == "structchord") {
258 matrixCalculators.push_back(new StructChord());
259 }else if (Estimators[i] == "hellinger") {
260 matrixCalculators.push_back(new Hellinger());
261 }else if (Estimators[i] == "manhattan") {
262 matrixCalculators.push_back(new Manhattan());
263 }else if (Estimators[i] == "structpearson") {
264 matrixCalculators.push_back(new StructPearson());
265 }else if (Estimators[i] == "soergel") {
266 matrixCalculators.push_back(new Soergel());
267 }else if (Estimators[i] == "spearman") {
268 matrixCalculators.push_back(new Spearman());
269 }else if (Estimators[i] == "structkulczynski") {
270 matrixCalculators.push_back(new StructKulczynski());
271 }else if (Estimators[i] == "speciesprofile") {
272 matrixCalculators.push_back(new SpeciesProfile());
273 }else if (Estimators[i] == "hamming") {
274 matrixCalculators.push_back(new Hamming());
275 }else if (Estimators[i] == "structchi2") {
276 matrixCalculators.push_back(new StructChi2());
277 }else if (Estimators[i] == "gower") {
278 matrixCalculators.push_back(new Gower());
279 }else if (Estimators[i] == "memchi2") {
280 matrixCalculators.push_back(new MemChi2());
281 }else if (Estimators[i] == "memchord") {
282 matrixCalculators.push_back(new MemChord());
283 }else if (Estimators[i] == "memeuclidean") {
284 matrixCalculators.push_back(new MemEuclidean());
285 }else if (Estimators[i] == "mempearson") {
286 matrixCalculators.push_back(new MemPearson());
295 catch(exception& e) {
296 m->errorOut(e, "MatrixOutputCommand", "MatrixOutputCommand");
301 //**********************************************************************************************************************
303 MatrixOutputCommand::~MatrixOutputCommand(){}
305 //**********************************************************************************************************************
307 int MatrixOutputCommand::execute(){
310 if (abort == true) { if (calledHelp) { return 0; } return 2; }
312 //if the users entered no valid calculators don't execute command
313 if (matrixCalculators.size() == 0) { m->mothurOut("No valid calculators."); m->mothurOutEndLine(); return 0; }
315 input = new InputData(sharedfile, "sharedfile");
316 lookup = input->getSharedRAbundVectors();
317 string lastLabel = lookup[0]->getLabel();
319 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
320 set<string> processedLabels;
321 set<string> userLabels = labels;
323 if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups. I cannot run the command."); m->mothurOutEndLine(); delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } return 0;}
325 numGroups = lookup.size();
326 lines.resize(processors);
327 for (int i = 0; i < processors; i++) {
328 lines[i].start = int (sqrt(float(i)/float(processors)) * numGroups);
329 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numGroups);
330 cout << i << '\t' << lines[i].start << '\t' << lines[i].end << endl;
333 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } m->Groups.clear(); return 0; }
335 //as long as you are not at the end of the file or done wih the lines you want
336 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
338 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } m->Groups.clear(); return 0; }
340 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
341 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
344 processedLabels.insert(lookup[0]->getLabel());
345 userLabels.erase(lookup[0]->getLabel());
348 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
349 string saveLabel = lookup[0]->getLabel();
351 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
352 lookup = input->getSharedRAbundVectors(lastLabel);
354 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
357 processedLabels.insert(lookup[0]->getLabel());
358 userLabels.erase(lookup[0]->getLabel());
360 //restore real lastlabel to save below
361 lookup[0]->setLabel(saveLabel);
364 lastLabel = lookup[0]->getLabel();
366 //get next line to process
367 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
368 lookup = input->getSharedRAbundVectors();
371 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } m->Groups.clear(); return 0; }
373 //output error messages about any remaining user labels
374 set<string>::iterator it;
375 bool needToRun = false;
376 for (it = userLabels.begin(); it != userLabels.end(); it++) {
377 m->mothurOut("Your file does not include the label " + *it);
378 if (processedLabels.count(lastLabel) != 1) {
379 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
382 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
386 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } m->Groups.clear(); return 0; }
388 //run last label if you need to
389 if (needToRun == true) {
390 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
391 lookup = input->getSharedRAbundVectors(lastLabel);
393 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
395 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
398 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } m->Groups.clear(); return 0; }
400 //reset groups parameter
403 //set phylip file as new current phylipfile
405 itTypes = outputTypes.find("phylip");
406 if (itTypes != outputTypes.end()) {
407 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
410 m->mothurOutEndLine();
411 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
412 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
413 m->mothurOutEndLine();
418 catch(exception& e) {
419 m->errorOut(e, "MatrixOutputCommand", "execute");
423 /***********************************************************/
424 void MatrixOutputCommand::printSims(ostream& out, vector< vector<float> >& simMatrix) {
427 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
430 out << simMatrix.size() << endl;
432 if (output == "lt") {
433 for (int m = 0; m < simMatrix.size(); m++) {
434 out << lookup[m]->getGroup() << '\t';
435 for (int n = 0; n < m; n++) {
436 out << simMatrix[m][n] << '\t';
441 for (int m = 0; m < simMatrix.size(); m++) {
442 out << lookup[m]->getGroup() << '\t';
443 for (int n = 0; n < simMatrix[m].size(); n++) {
444 out << simMatrix[m][n] << '\t';
450 catch(exception& e) {
451 m->errorOut(e, "MatrixOutputCommand", "printSims");
455 /***********************************************************/
456 int MatrixOutputCommand::process(vector<SharedRAbundVector*> thisLookup){
459 vector<SharedRAbundVector*> subset;
460 vector< vector<seqDist> > calcDists; calcDists.resize(matrixCalculators.size()); //one for each calc, this will be used to make .dist files
462 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
464 driver(thisLookup, 0, numGroups, calcDists);
467 vector<int> processIDS;
469 //loop through and create all the processes you want
470 while (process != processors) {
474 processIDS.push_back(pid);
477 driver(thisLookup, lines[process].start, lines[process].end, calcDists);
479 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(getpid()) + ".dist";
481 m->openOutputFile(tempdistFileName, outtemp);
483 for (int i = 0; i < calcDists.size(); i++) {
484 outtemp << calcDists[i].size() << endl;
486 for (int j = 0; j < calcDists[i].size(); j++) {
487 outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl;
494 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
495 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
500 //parent do your part
501 driver(thisLookup, lines[0].start, lines[0].end, calcDists);
503 //force parent to wait until all the processes are done
504 for (int i = 0; i < processIDS.size(); i++) {
505 int temp = processIDS[i];
509 for (int i = 0; i < processIDS.size(); i++) {
510 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(processIDS[i]) + ".dist";
512 m->openInputFile(tempdistFileName, intemp);
514 for (int k = 0; k < calcDists.size(); k++) {
516 intemp >> size; m->gobble(intemp);
518 for (int j = 0; j < size; j++) {
523 intemp >> seq1 >> seq2 >> dist; m->gobble(intemp);
525 seqDist tempDist(seq1, seq2, dist);
526 calcDists[k].push_back(tempDist);
530 remove(tempdistFileName.c_str());
535 driver(thisLookup, 0, numGroups, calcDists);
538 for (int i = 0; i < calcDists.size(); i++) {
539 if (m->control_pressed) { break; }
542 vector< vector<float> > matrix; //square matrix to represent the distance
543 matrix.resize(thisLookup.size());
544 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
546 for (int j = 0; j < calcDists[i].size(); j++) {
547 int row = calcDists[i][j].seq1;
548 int column = calcDists[i][j].seq2;
549 float dist = calcDists[i][j].dist;
551 matrix[row][column] = dist;
552 matrix[column][row] = dist;
555 string distFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + matrixCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + "." + output + ".dist";
556 outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
558 m->openOutputFile(distFileName, outDist);
559 outDist.setf(ios::fixed, ios::floatfield); outDist.setf(ios::showpoint);
561 printSims(outDist, matrix);
568 catch(exception& e) {
569 m->errorOut(e, "MatrixOutputCommand", "process");
573 /**************************************************************************************************/
574 int MatrixOutputCommand::driver(vector<SharedRAbundVector*> thisLookup, int start, int end, vector< vector<seqDist> >& calcDists) {
577 vector<SharedRAbundVector*> subset;
578 for (int k = start; k < end; k++) { // pass cdd each set of groups to compare
580 for (int l = 0; l < k; l++) {
582 if (k != l) { //we dont need to similiarity of a groups to itself
583 subset.clear(); //clear out old pair of sharedrabunds
584 //add new pair of sharedrabunds
585 subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]);
587 for(int i=0;i<matrixCalculators.size();i++) {
589 //if this calc needs all groups to calculate the pair load all groups
590 if (matrixCalculators[i]->getNeedsAll()) {
591 //load subset with rest of lookup for those calcs that need everyone to calc for a pair
592 for (int w = 0; w < thisLookup.size(); w++) {
593 if ((w != k) && (w != l)) { subset.push_back(thisLookup[w]); }
597 vector<double> tempdata = matrixCalculators[i]->getValues(subset); //saves the calculator outputs
599 if (m->control_pressed) { return 1; }
601 seqDist temp(l, k, (1.0 - tempdata[0]));
602 calcDists[i].push_back(temp);
610 catch(exception& e) {
611 m->errorOut(e, "MatrixOutputCommand", "driver");
615 /***********************************************************/