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 "subsample.h"
13 //**********************************************************************************************************************
14 vector<string> MatrixOutputCommand::setParameters(){
16 CommandParameter pshared("shared", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pshared);
17 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
18 CommandParameter psubsample("subsample", "String", "", "", "", "", "",false,false); parameters.push_back(psubsample);
19 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
20 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);
21 CommandParameter poutput("output", "Multiple", "lt-square", "lt", "", "", "",false,false); parameters.push_back(poutput);
22 CommandParameter pmode("mode", "Multiple", "average-median", "average", "", "", "",false,false); parameters.push_back(pmode);
23 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
24 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
25 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
26 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
28 vector<string> myArray;
29 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
33 m->errorOut(e, "MatrixOutputCommand", "setParameters");
37 //**********************************************************************************************************************
38 string MatrixOutputCommand::getHelpString(){
40 string helpString = "";
41 ValidCalculators validCalculator;
42 helpString += "The dist.shared command parameters are shared, groups, calc, output, processors, subsample, iters, mode, and label. shared is a required, unless you have a valid current file.\n";
43 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n";
44 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";
45 helpString += "The iters parameter allows you to choose the number of times you would like to run the subsample.\n";
46 helpString += "The subsample parameter allows you to enter the size pergroup of the sample or you can set subsample=T and mothur will use the size of your smallest group.\n";
47 helpString += "The dist.shared command should be in the following format: dist.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels).\n";
48 helpString += "The output parameter allows you to specify format of your distance matrix. Options are lt, and square. The default is lt.\n";
49 helpString += "The mode parameter allows you to specify if you want the average or the median values reported when subsampling. Options are average, and median. The default is average.\n";
50 helpString += "Example dist.shared(groups=A-B-C, calc=jabund-sorabund).\n";
51 helpString += "The default value for groups is all the groups in your groupfile.\n";
52 helpString += "The default value for calc is jclass and thetayc.\n";
53 helpString += validCalculator.printCalc("matrix");
54 helpString += "The dist.shared command outputs a .dist file for each calculator you specify at each distance you choose.\n";
55 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
59 m->errorOut(e, "MatrixOutputCommand", "getHelpString");
63 //**********************************************************************************************************************
64 string MatrixOutputCommand::getOutputFileNameTag(string type, string inputName=""){
66 string outputFileName = "";
67 map<string, vector<string> >::iterator it;
69 //is this a type this command creates
70 it = outputTypes.find(type);
71 if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
73 if (type == "phylip") { outputFileName = "dist"; }
74 else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; }
76 return outputFileName;
79 m->errorOut(e, "MatrixOutputCommand", "getOutputFileNameTag");
83 //**********************************************************************************************************************
84 MatrixOutputCommand::MatrixOutputCommand(){
86 abort = true; calledHelp = true;
88 vector<string> tempOutNames;
89 outputTypes["phylip"] = tempOutNames;
92 m->errorOut(e, "MatrixOutputCommand", "MatrixOutputCommand");
96 //**********************************************************************************************************************
98 MatrixOutputCommand::MatrixOutputCommand(string option) {
100 abort = false; calledHelp = false;
103 //allow user to run help
104 if(option == "help") { help(); abort = true; calledHelp = true; }
105 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
108 vector<string> myArray = setParameters();
110 OptionParser parser(option);
111 map<string,string> parameters = parser.getParameters();
112 map<string,string>::iterator it;
114 ValidParameters validParameter;
116 //check to make sure all parameters are valid for command
117 for (it = parameters.begin(); it != parameters.end(); it++) {
118 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
121 //initialize outputTypes
122 vector<string> tempOutNames;
123 outputTypes["phylip"] = tempOutNames;
125 //if the user changes the input directory command factory will send this info to us in the output parameter
126 string inputDir = validParameter.validFile(parameters, "inputdir", false);
127 if (inputDir == "not found"){ inputDir = ""; }
130 it = parameters.find("shared");
131 //user has given a template file
132 if(it != parameters.end()){
133 path = m->hasPath(it->second);
134 //if the user has not given a path then, add inputdir. else leave path alone.
135 if (path == "") { parameters["shared"] = inputDir + it->second; }
139 sharedfile = validParameter.validFile(parameters, "shared", true);
140 if (sharedfile == "not found") {
141 //if there is a current shared file, use it
142 sharedfile = m->getSharedFile();
143 if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
144 else { m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
145 }else if (sharedfile == "not open") { sharedfile = ""; abort = true; }
146 else { m->setSharedFile(sharedfile); }
148 //if the user changes the output directory command factory will send this info to us in the output parameter
149 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
151 outputDir += m->hasPath(sharedfile); //if user entered a file with a path then preserve it
154 //check for optional parameter and set defaults
155 // ...at some point should added some additional type checking...
156 label = validParameter.validFile(parameters, "label", false);
157 if (label == "not found") { label = ""; }
159 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
160 else { allLines = 1; }
163 output = validParameter.validFile(parameters, "output", false); if(output == "not found"){ output = "lt"; }
164 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"; }
166 mode = validParameter.validFile(parameters, "mode", false); if(mode == "not found"){ mode = "average"; }
167 if ((mode != "average") && (mode != "median")) { m->mothurOut(mode + " is not a valid mode. Options are average and medina. I will use average."); m->mothurOutEndLine(); output = "average"; }
169 groups = validParameter.validFile(parameters, "groups", false);
170 if (groups == "not found") { groups = ""; }
172 m->splitAtDash(groups, Groups);
173 m->setGroups(Groups);
176 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
177 m->setProcessors(temp);
178 m->mothurConvert(temp, processors);
180 calc = validParameter.validFile(parameters, "calc", false);
181 if (calc == "not found") { calc = "jclass-thetayc"; }
183 if (calc == "default") { calc = "jclass-thetayc"; }
185 m->splitAtDash(calc, Estimators);
186 if (m->inUsersGroups("citation", Estimators)) {
187 ValidCalculators validCalc; validCalc.printCitations(Estimators);
188 //remove citation from list of calcs
189 for (int i = 0; i < Estimators.size(); i++) { if (Estimators[i] == "citation") { Estimators.erase(Estimators.begin()+i); break; } }
192 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
193 m->mothurConvert(temp, iters);
195 temp = validParameter.validFile(parameters, "subsample", false); if (temp == "not found") { temp = "F"; }
196 if (m->isNumeric1(temp)) { m->mothurConvert(temp, subsampleSize); subsample = true; }
198 if (m->isTrue(temp)) { subsample = true; subsampleSize = -1; } //we will set it to smallest group later
199 else { subsample = false; }
202 if (subsample == false) { iters = 0; }
204 if (abort == false) {
206 ValidCalculators validCalculator;
209 for (i=0; i<Estimators.size(); i++) {
210 if (validCalculator.isValidCalculator("matrix", Estimators[i]) == true) {
211 if (Estimators[i] == "sharedsobs") {
212 matrixCalculators.push_back(new SharedSobsCS());
213 }else if (Estimators[i] == "sharedchao") {
214 matrixCalculators.push_back(new SharedChao1());
215 }else if (Estimators[i] == "sharedace") {
216 matrixCalculators.push_back(new SharedAce());
217 }else if (Estimators[i] == "jabund") {
218 matrixCalculators.push_back(new JAbund());
219 }else if (Estimators[i] == "sorabund") {
220 matrixCalculators.push_back(new SorAbund());
221 }else if (Estimators[i] == "jclass") {
222 matrixCalculators.push_back(new Jclass());
223 }else if (Estimators[i] == "sorclass") {
224 matrixCalculators.push_back(new SorClass());
225 }else if (Estimators[i] == "jest") {
226 matrixCalculators.push_back(new Jest());
227 }else if (Estimators[i] == "sorest") {
228 matrixCalculators.push_back(new SorEst());
229 }else if (Estimators[i] == "thetayc") {
230 matrixCalculators.push_back(new ThetaYC());
231 }else if (Estimators[i] == "thetan") {
232 matrixCalculators.push_back(new ThetaN());
233 }else if (Estimators[i] == "kstest") {
234 matrixCalculators.push_back(new KSTest());
235 }else if (Estimators[i] == "sharednseqs") {
236 matrixCalculators.push_back(new SharedNSeqs());
237 }else if (Estimators[i] == "ochiai") {
238 matrixCalculators.push_back(new Ochiai());
239 }else if (Estimators[i] == "anderberg") {
240 matrixCalculators.push_back(new Anderberg());
241 }else if (Estimators[i] == "kulczynski") {
242 matrixCalculators.push_back(new Kulczynski());
243 }else if (Estimators[i] == "kulczynskicody") {
244 matrixCalculators.push_back(new KulczynskiCody());
245 }else if (Estimators[i] == "lennon") {
246 matrixCalculators.push_back(new Lennon());
247 }else if (Estimators[i] == "morisitahorn") {
248 matrixCalculators.push_back(new MorHorn());
249 }else if (Estimators[i] == "braycurtis") {
250 matrixCalculators.push_back(new BrayCurtis());
251 }else if (Estimators[i] == "whittaker") {
252 matrixCalculators.push_back(new Whittaker());
253 }else if (Estimators[i] == "odum") {
254 matrixCalculators.push_back(new Odum());
255 }else if (Estimators[i] == "canberra") {
256 matrixCalculators.push_back(new Canberra());
257 }else if (Estimators[i] == "structeuclidean") {
258 matrixCalculators.push_back(new StructEuclidean());
259 }else if (Estimators[i] == "structchord") {
260 matrixCalculators.push_back(new StructChord());
261 }else if (Estimators[i] == "hellinger") {
262 matrixCalculators.push_back(new Hellinger());
263 }else if (Estimators[i] == "manhattan") {
264 matrixCalculators.push_back(new Manhattan());
265 }else if (Estimators[i] == "structpearson") {
266 matrixCalculators.push_back(new StructPearson());
267 }else if (Estimators[i] == "soergel") {
268 matrixCalculators.push_back(new Soergel());
269 }else if (Estimators[i] == "spearman") {
270 matrixCalculators.push_back(new Spearman());
271 }else if (Estimators[i] == "structkulczynski") {
272 matrixCalculators.push_back(new StructKulczynski());
273 }else if (Estimators[i] == "speciesprofile") {
274 matrixCalculators.push_back(new SpeciesProfile());
275 }else if (Estimators[i] == "hamming") {
276 matrixCalculators.push_back(new Hamming());
277 }else if (Estimators[i] == "structchi2") {
278 matrixCalculators.push_back(new StructChi2());
279 }else if (Estimators[i] == "gower") {
280 matrixCalculators.push_back(new Gower());
281 }else if (Estimators[i] == "memchi2") {
282 matrixCalculators.push_back(new MemChi2());
283 }else if (Estimators[i] == "memchord") {
284 matrixCalculators.push_back(new MemChord());
285 }else if (Estimators[i] == "memeuclidean") {
286 matrixCalculators.push_back(new MemEuclidean());
287 }else if (Estimators[i] == "mempearson") {
288 matrixCalculators.push_back(new MemPearson());
297 catch(exception& e) {
298 m->errorOut(e, "MatrixOutputCommand", "MatrixOutputCommand");
303 //**********************************************************************************************************************
305 MatrixOutputCommand::~MatrixOutputCommand(){}
307 //**********************************************************************************************************************
309 int MatrixOutputCommand::execute(){
312 if (abort == true) { if (calledHelp) { return 0; } return 2; }
314 //if the users entered no valid calculators don't execute command
315 if (matrixCalculators.size() == 0) { m->mothurOut("No valid calculators."); m->mothurOutEndLine(); return 0; }
317 input = new InputData(sharedfile, "sharedfile");
318 lookup = input->getSharedRAbundVectors();
319 string lastLabel = lookup[0]->getLabel();
321 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
322 set<string> processedLabels;
323 set<string> userLabels = labels;
325 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;}
328 if (subsampleSize == -1) { //user has not set size, set size = smallest samples size
329 subsampleSize = lookup[0]->getNumSeqs();
330 for (int i = 1; i < lookup.size(); i++) {
331 int thisSize = lookup[i]->getNumSeqs();
333 if (thisSize < subsampleSize) { subsampleSize = thisSize; }
338 vector<SharedRAbundVector*> temp;
339 for (int i = 0; i < lookup.size(); i++) {
340 if (lookup[i]->getNumSeqs() < subsampleSize) {
341 m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
344 Groups.push_back(lookup[i]->getGroup());
345 temp.push_back(lookup[i]);
349 m->setGroups(Groups);
352 if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups. I cannot run the command."); m->mothurOutEndLine(); m->control_pressed = true; delete input; return 0; }
355 numGroups = lookup.size();
356 lines.resize(processors);
357 for (int i = 0; i < processors; i++) {
358 lines[i].start = int (sqrt(float(i)/float(processors)) * numGroups);
359 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numGroups);
362 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } m->clearGroups(); return 0; }
364 //as long as you are not at the end of the file or done wih the lines you want
365 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
367 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++) { m->mothurRemove(outputNames[i]); } m->clearGroups(); return 0; }
369 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
370 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
373 processedLabels.insert(lookup[0]->getLabel());
374 userLabels.erase(lookup[0]->getLabel());
377 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
378 string saveLabel = lookup[0]->getLabel();
380 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
381 lookup = input->getSharedRAbundVectors(lastLabel);
383 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
386 processedLabels.insert(lookup[0]->getLabel());
387 userLabels.erase(lookup[0]->getLabel());
389 //restore real lastlabel to save below
390 lookup[0]->setLabel(saveLabel);
393 lastLabel = lookup[0]->getLabel();
395 //get next line to process
396 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
397 lookup = input->getSharedRAbundVectors();
400 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } m->clearGroups(); return 0; }
402 //output error messages about any remaining user labels
403 set<string>::iterator it;
404 bool needToRun = false;
405 for (it = userLabels.begin(); it != userLabels.end(); it++) {
406 m->mothurOut("Your file does not include the label " + *it);
407 if (processedLabels.count(lastLabel) != 1) {
408 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
411 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
415 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } m->clearGroups(); return 0; }
417 //run last label if you need to
418 if (needToRun == true) {
419 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
420 lookup = input->getSharedRAbundVectors(lastLabel);
422 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
424 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
427 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } m->clearGroups(); return 0; }
429 //reset groups parameter
432 //set phylip file as new current phylipfile
434 itTypes = outputTypes.find("phylip");
435 if (itTypes != outputTypes.end()) {
436 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
439 m->mothurOutEndLine();
440 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
441 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
442 m->mothurOutEndLine();
447 catch(exception& e) {
448 m->errorOut(e, "MatrixOutputCommand", "execute");
452 /***********************************************************/
453 void MatrixOutputCommand::printSims(ostream& out, vector< vector<double> >& simMatrix) {
456 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
459 out << simMatrix.size() << endl;
461 if (output == "lt") {
462 for (int b = 0; b < simMatrix.size(); b++) {
463 out << lookup[b]->getGroup() << '\t';
464 for (int n = 0; n < b; n++) {
465 out << simMatrix[b][n] << '\t';
470 for (int b = 0; b < simMatrix.size(); b++) {
471 out << lookup[b]->getGroup() << '\t';
472 for (int n = 0; n < simMatrix[b].size(); n++) {
473 out << simMatrix[b][n] << '\t';
479 catch(exception& e) {
480 m->errorOut(e, "MatrixOutputCommand", "printSims");
484 /***********************************************************/
485 int MatrixOutputCommand::process(vector<SharedRAbundVector*> thisLookup){
487 vector< vector< vector<seqDist> > > calcDistsTotals; //each iter, one for each calc, then each groupCombos dists. this will be used to make .dist files
488 vector< vector<seqDist> > calcDists; calcDists.resize(matrixCalculators.size());
490 for (int thisIter = 0; thisIter < iters+1; thisIter++) {
492 vector<SharedRAbundVector*> thisItersLookup = thisLookup;
494 if (subsample && (thisIter != 0)) {
496 vector<string> tempLabels; //dont need since we arent printing the sampled sharedRabunds
498 //make copy of lookup so we don't get access violations
499 vector<SharedRAbundVector*> newLookup;
500 for (int k = 0; k < thisItersLookup.size(); k++) {
501 SharedRAbundVector* temp = new SharedRAbundVector();
502 temp->setLabel(thisItersLookup[k]->getLabel());
503 temp->setGroup(thisItersLookup[k]->getGroup());
504 newLookup.push_back(temp);
508 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
509 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
510 for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
513 tempLabels = sample.getSample(newLookup, subsampleSize);
514 thisItersLookup = newLookup;
518 driver(thisItersLookup, 0, numGroups, calcDists);
521 vector<int> processIDS;
523 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
524 //loop through and create all the processes you want
525 while (process != processors) {
529 processIDS.push_back(pid);
533 driver(thisItersLookup, lines[process].start, lines[process].end, calcDists);
535 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(getpid()) + ".dist";
537 m->openOutputFile(tempdistFileName, outtemp);
539 for (int i = 0; i < calcDists.size(); i++) {
540 outtemp << calcDists[i].size() << endl;
542 for (int j = 0; j < calcDists[i].size(); j++) {
543 outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl;
550 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
551 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
556 //parent do your part
557 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);
559 //force parent to wait until all the processes are done
560 for (int i = 0; i < processIDS.size(); i++) {
561 int temp = processIDS[i];
565 for (int i = 0; i < processIDS.size(); i++) {
566 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(processIDS[i]) + ".dist";
568 m->openInputFile(tempdistFileName, intemp);
570 for (int k = 0; k < calcDists.size(); k++) {
572 intemp >> size; m->gobble(intemp);
574 for (int j = 0; j < size; j++) {
579 intemp >> seq1 >> seq2 >> dist; m->gobble(intemp);
581 seqDist tempDist(seq1, seq2, dist);
582 calcDists[k].push_back(tempDist);
586 m->mothurRemove(tempdistFileName);
589 //////////////////////////////////////////////////////////////////////////////////////////////////////
590 //Windows version shared memory, so be careful when passing variables through the distSharedData struct.
591 //Above fork() will clone, so memory is separate, but that's not the case with windows,
592 //Taking advantage of shared memory to pass results vectors.
593 //////////////////////////////////////////////////////////////////////////////////////////////////////
595 vector<distSharedData*> pDataArray;
596 DWORD dwThreadIdArray[processors-1];
597 HANDLE hThreadArray[processors-1];
599 //Create processor worker threads.
600 for( int i=1; i<processors; i++ ){
602 //make copy of lookup so we don't get access violations
603 vector<SharedRAbundVector*> newLookup;
604 for (int k = 0; k < thisItersLookup.size(); k++) {
605 SharedRAbundVector* temp = new SharedRAbundVector();
606 temp->setLabel(thisItersLookup[k]->getLabel());
607 temp->setGroup(thisItersLookup[k]->getGroup());
608 newLookup.push_back(temp);
612 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
613 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
614 for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
617 // Allocate memory for thread data.
618 distSharedData* tempSum = new distSharedData(m, lines[i].start, lines[i].end, Estimators, newLookup);
619 pDataArray.push_back(tempSum);
620 processIDS.push_back(i);
622 hThreadArray[i-1] = CreateThread(NULL, 0, MyDistSharedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
625 //parent do your part
626 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);
628 //Wait until all threads have terminated.
629 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
631 //Close all thread handles and free memory allocations.
632 for(int i=0; i < pDataArray.size(); i++){
633 for (int j = 0; j < pDataArray[i]->thisLookup.size(); j++) { delete pDataArray[i]->thisLookup[j]; }
635 for (int k = 0; k < calcDists.size(); k++) {
636 int size = pDataArray[i]->calcDists[k].size();
637 for (int j = 0; j < size; j++) { calcDists[k].push_back(pDataArray[i]->calcDists[k][j]); }
640 CloseHandle(hThreadArray[i]);
641 delete pDataArray[i];
647 if (subsample && (thisIter != 0)) {
648 if((thisIter) % 100 == 0){ m->mothurOut(toString(thisIter)); m->mothurOutEndLine(); }
649 calcDistsTotals.push_back(calcDists);
650 for (int i = 0; i < calcDists.size(); i++) {
651 for (int j = 0; j < calcDists[i].size(); j++) {
652 if (m->debug) { m->mothurOut("[DEBUG]: Results: iter = " + toString(thisIter) + ", " + thisLookup[calcDists[i][j].seq1]->getGroup() + " - " + thisLookup[calcDists[i][j].seq2]->getGroup() + " distance = " + toString(calcDists[i][j].dist) + ".\n"); }
656 for (int i = 0; i < thisItersLookup.size(); i++) { delete thisItersLookup[i]; }
657 thisItersLookup.clear();
658 }else { //print results for whole dataset
659 for (int i = 0; i < calcDists.size(); i++) {
660 if (m->control_pressed) { break; }
663 vector< vector<double> > matrix; //square matrix to represent the distance
664 matrix.resize(thisLookup.size());
665 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
667 for (int j = 0; j < calcDists[i].size(); j++) {
668 int row = calcDists[i][j].seq1;
669 int column = calcDists[i][j].seq2;
670 double dist = calcDists[i][j].dist;
672 matrix[row][column] = dist;
673 matrix[column][row] = dist;
676 string distFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + matrixCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + "." + output + "." + getOutputFileNameTag("phylip");
677 outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
680 m->openOutputFile(distFileName, outDist);
681 outDist.setf(ios::fixed, ios::floatfield); outDist.setf(ios::showpoint);
683 printSims(outDist, matrix);
688 for (int i = 0; i < calcDists.size(); i++) { calcDists[i].clear(); }
692 //we need to find the average distance and standard deviation for each groups distance
694 vector< vector<seqDist> > calcAverages; calcAverages.resize(matrixCalculators.size());
695 for (int i = 0; i < calcAverages.size(); i++) { //initialize sums to zero.
696 calcAverages[i].resize(calcDistsTotals[0][i].size());
698 for (int j = 0; j < calcAverages[i].size(); j++) {
699 calcAverages[i][j].seq1 = calcDistsTotals[0][i][j].seq1;
700 calcAverages[i][j].seq2 = calcDistsTotals[0][i][j].seq2;
701 calcAverages[i][j].dist = 0.0;
704 if (mode == "average") {
705 for (int thisIter = 0; thisIter < iters; thisIter++) { //sum all groups dists for each calculator
706 for (int i = 0; i < calcAverages.size(); i++) { //initialize sums to zero.
707 for (int j = 0; j < calcAverages[i].size(); j++) {
708 calcAverages[i][j].dist += calcDistsTotals[thisIter][i][j].dist;
709 if (m->debug) { m->mothurOut("[DEBUG]: Totaling for average calc: iter = " + toString(thisIter) + ", " + thisLookup[calcDistsTotals[thisIter][i][j].seq1]->getGroup() + " - " + thisLookup[calcDistsTotals[thisIter][i][j].seq2]->getGroup() + " distance = " + toString(calcDistsTotals[thisIter][i][j].dist) + ". New total = " + toString(calcAverages[i][j].dist) + ".\n"); }
714 for (int i = 0; i < calcAverages.size(); i++) { //finds average.
715 for (int j = 0; j < calcAverages[i].size(); j++) {
716 calcAverages[i][j].dist /= (float) iters;
719 }else { //find median
720 for (int i = 0; i < calcAverages.size(); i++) { //for each calc
721 for (int j = 0; j < calcAverages[i].size(); j++) { //for each comparison
722 vector<double> dists;
723 for (int thisIter = 0; thisIter < iters; thisIter++) { //for each subsample
724 dists.push_back(calcDistsTotals[thisIter][i][j].dist);
726 sort(dists.begin(), dists.end());
727 calcAverages[i][j].dist = dists[(iters/2)];
731 //find standard deviation
732 vector< vector<seqDist> > stdDev; stdDev.resize(matrixCalculators.size());
733 for (int i = 0; i < stdDev.size(); i++) { //initialize sums to zero.
734 stdDev[i].resize(calcDistsTotals[0][i].size());
736 for (int j = 0; j < stdDev[i].size(); j++) {
737 stdDev[i][j].seq1 = calcDistsTotals[0][i][j].seq1;
738 stdDev[i][j].seq2 = calcDistsTotals[0][i][j].seq2;
739 stdDev[i][j].dist = 0.0;
743 for (int thisIter = 0; thisIter < iters; thisIter++) { //compute the difference of each dist from the mean, and square the result of each
744 for (int i = 0; i < stdDev.size(); i++) {
745 for (int j = 0; j < stdDev[i].size(); j++) {
746 stdDev[i][j].dist += ((calcDistsTotals[thisIter][i][j].dist - calcAverages[i][j].dist) * (calcDistsTotals[thisIter][i][j].dist - calcAverages[i][j].dist));
751 for (int i = 0; i < stdDev.size(); i++) { //finds average.
752 for (int j = 0; j < stdDev[i].size(); j++) {
753 stdDev[i][j].dist /= (float) iters;
754 stdDev[i][j].dist = sqrt(stdDev[i][j].dist);
759 for (int i = 0; i < calcDists.size(); i++) {
760 vector< vector<double> > matrix; //square matrix to represent the distance
761 matrix.resize(thisLookup.size());
762 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
764 vector< vector<double> > stdmatrix; //square matrix to represent the stdDev
765 stdmatrix.resize(thisLookup.size());
766 for (int k = 0; k < thisLookup.size(); k++) { stdmatrix[k].resize(thisLookup.size(), 0.0); }
769 for (int j = 0; j < calcAverages[i].size(); j++) {
770 int row = calcAverages[i][j].seq1;
771 int column = calcAverages[i][j].seq2;
772 float dist = calcAverages[i][j].dist;
773 float stdDist = stdDev[i][j].dist;
775 matrix[row][column] = dist;
776 matrix[column][row] = dist;
777 stdmatrix[row][column] = stdDist;
778 stdmatrix[column][row] = stdDist;
781 string distFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + matrixCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + "." + output + ".ave." + getOutputFileNameTag("phylip");
782 outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
784 m->openOutputFile(distFileName, outAve);
785 outAve.setf(ios::fixed, ios::floatfield); outAve.setf(ios::showpoint);
787 printSims(outAve, matrix);
791 distFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + matrixCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + "." + output + ".std." + getOutputFileNameTag("phylip");
792 outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
794 m->openOutputFile(distFileName, outSTD);
795 outSTD.setf(ios::fixed, ios::floatfield); outSTD.setf(ios::showpoint);
797 printSims(outSTD, stdmatrix);
806 catch(exception& e) {
807 m->errorOut(e, "MatrixOutputCommand", "process");
811 /**************************************************************************************************/
812 int MatrixOutputCommand::driver(vector<SharedRAbundVector*> thisLookup, int start, int end, vector< vector<seqDist> >& calcDists) {
814 vector<SharedRAbundVector*> subset;
816 for (int k = start; k < end; k++) { // pass cdd each set of groups to compare
818 for (int l = 0; l < k; l++) {
820 if (k != l) { //we dont need to similiarity of a groups to itself
821 subset.clear(); //clear out old pair of sharedrabunds
822 //add new pair of sharedrabunds
823 subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]);
825 for(int i=0;i<matrixCalculators.size();i++) {
827 //if this calc needs all groups to calculate the pair load all groups
828 if (matrixCalculators[i]->getNeedsAll()) {
829 //load subset with rest of lookup for those calcs that need everyone to calc for a pair
830 for (int w = 0; w < thisLookup.size(); w++) {
831 if ((w != k) && (w != l)) { subset.push_back(thisLookup[w]); }
835 vector<double> tempdata = matrixCalculators[i]->getValues(subset); //saves the calculator outputs
837 if (m->control_pressed) { return 1; }
839 seqDist temp(l, k, tempdata[0]);
840 calcDists[i].push_back(temp);
848 catch(exception& e) {
849 m->errorOut(e, "MatrixOutputCommand", "driver");
853 /***********************************************************/