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 MatrixOutputCommand::MatrixOutputCommand(){
66 abort = true; calledHelp = true;
68 vector<string> tempOutNames;
69 outputTypes["phylip"] = tempOutNames;
72 m->errorOut(e, "MatrixOutputCommand", "MatrixOutputCommand");
76 //**********************************************************************************************************************
78 MatrixOutputCommand::MatrixOutputCommand(string option) {
80 abort = false; calledHelp = false;
83 //allow user to run help
84 if(option == "help") { help(); abort = true; calledHelp = true; }
85 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
88 vector<string> myArray = setParameters();
90 OptionParser parser(option);
91 map<string,string> parameters = parser.getParameters();
92 map<string,string>::iterator it;
94 ValidParameters validParameter;
96 //check to make sure all parameters are valid for command
97 for (it = parameters.begin(); it != parameters.end(); it++) {
98 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
101 //initialize outputTypes
102 vector<string> tempOutNames;
103 outputTypes["phylip"] = tempOutNames;
105 //if the user changes the input directory command factory will send this info to us in the output parameter
106 string inputDir = validParameter.validFile(parameters, "inputdir", false);
107 if (inputDir == "not found"){ inputDir = ""; }
110 it = parameters.find("shared");
111 //user has given a template file
112 if(it != parameters.end()){
113 path = m->hasPath(it->second);
114 //if the user has not given a path then, add inputdir. else leave path alone.
115 if (path == "") { parameters["shared"] = inputDir + it->second; }
119 sharedfile = validParameter.validFile(parameters, "shared", true);
120 if (sharedfile == "not found") {
121 //if there is a current shared file, use it
122 sharedfile = m->getSharedFile();
123 if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
124 else { m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
125 }else if (sharedfile == "not open") { sharedfile = ""; abort = true; }
126 else { m->setSharedFile(sharedfile); }
128 //if the user changes the output directory command factory will send this info to us in the output parameter
129 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
131 outputDir += m->hasPath(sharedfile); //if user entered a file with a path then preserve it
134 //check for optional parameter and set defaults
135 // ...at some point should added some additional type checking...
136 label = validParameter.validFile(parameters, "label", false);
137 if (label == "not found") { label = ""; }
139 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
140 else { allLines = 1; }
143 output = validParameter.validFile(parameters, "output", false); if(output == "not found"){ output = "lt"; }
144 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"; }
146 mode = validParameter.validFile(parameters, "mode", false); if(mode == "not found"){ mode = "average"; }
147 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"; }
149 groups = validParameter.validFile(parameters, "groups", false);
150 if (groups == "not found") { groups = ""; }
152 m->splitAtDash(groups, Groups);
153 m->setGroups(Groups);
156 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
157 m->setProcessors(temp);
158 m->mothurConvert(temp, processors);
160 calc = validParameter.validFile(parameters, "calc", false);
161 if (calc == "not found") { calc = "jclass-thetayc"; }
163 if (calc == "default") { calc = "jclass-thetayc"; }
165 m->splitAtDash(calc, Estimators);
166 if (m->inUsersGroups("citation", Estimators)) {
167 ValidCalculators validCalc; validCalc.printCitations(Estimators);
168 //remove citation from list of calcs
169 for (int i = 0; i < Estimators.size(); i++) { if (Estimators[i] == "citation") { Estimators.erase(Estimators.begin()+i); break; } }
172 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
173 m->mothurConvert(temp, iters);
175 temp = validParameter.validFile(parameters, "subsample", false); if (temp == "not found") { temp = "F"; }
176 if (m->isNumeric1(temp)) { m->mothurConvert(temp, subsampleSize); subsample = true; }
178 if (m->isTrue(temp)) { subsample = true; subsampleSize = -1; } //we will set it to smallest group later
179 else { subsample = false; }
182 if (subsample == false) { iters = 1; }
184 if (abort == false) {
186 ValidCalculators validCalculator;
189 for (i=0; i<Estimators.size(); i++) {
190 if (validCalculator.isValidCalculator("matrix", Estimators[i]) == true) {
191 if (Estimators[i] == "sharedsobs") {
192 matrixCalculators.push_back(new SharedSobsCS());
193 }else if (Estimators[i] == "sharedchao") {
194 matrixCalculators.push_back(new SharedChao1());
195 }else if (Estimators[i] == "sharedace") {
196 matrixCalculators.push_back(new SharedAce());
197 }else if (Estimators[i] == "jabund") {
198 matrixCalculators.push_back(new JAbund());
199 }else if (Estimators[i] == "sorabund") {
200 matrixCalculators.push_back(new SorAbund());
201 }else if (Estimators[i] == "jclass") {
202 matrixCalculators.push_back(new Jclass());
203 }else if (Estimators[i] == "sorclass") {
204 matrixCalculators.push_back(new SorClass());
205 }else if (Estimators[i] == "jest") {
206 matrixCalculators.push_back(new Jest());
207 }else if (Estimators[i] == "sorest") {
208 matrixCalculators.push_back(new SorEst());
209 }else if (Estimators[i] == "thetayc") {
210 matrixCalculators.push_back(new ThetaYC());
211 }else if (Estimators[i] == "thetan") {
212 matrixCalculators.push_back(new ThetaN());
213 }else if (Estimators[i] == "kstest") {
214 matrixCalculators.push_back(new KSTest());
215 }else if (Estimators[i] == "sharednseqs") {
216 matrixCalculators.push_back(new SharedNSeqs());
217 }else if (Estimators[i] == "ochiai") {
218 matrixCalculators.push_back(new Ochiai());
219 }else if (Estimators[i] == "anderberg") {
220 matrixCalculators.push_back(new Anderberg());
221 }else if (Estimators[i] == "kulczynski") {
222 matrixCalculators.push_back(new Kulczynski());
223 }else if (Estimators[i] == "kulczynskicody") {
224 matrixCalculators.push_back(new KulczynskiCody());
225 }else if (Estimators[i] == "lennon") {
226 matrixCalculators.push_back(new Lennon());
227 }else if (Estimators[i] == "morisitahorn") {
228 matrixCalculators.push_back(new MorHorn());
229 }else if (Estimators[i] == "braycurtis") {
230 matrixCalculators.push_back(new BrayCurtis());
231 }else if (Estimators[i] == "whittaker") {
232 matrixCalculators.push_back(new Whittaker());
233 }else if (Estimators[i] == "odum") {
234 matrixCalculators.push_back(new Odum());
235 }else if (Estimators[i] == "canberra") {
236 matrixCalculators.push_back(new Canberra());
237 }else if (Estimators[i] == "structeuclidean") {
238 matrixCalculators.push_back(new StructEuclidean());
239 }else if (Estimators[i] == "structchord") {
240 matrixCalculators.push_back(new StructChord());
241 }else if (Estimators[i] == "hellinger") {
242 matrixCalculators.push_back(new Hellinger());
243 }else if (Estimators[i] == "manhattan") {
244 matrixCalculators.push_back(new Manhattan());
245 }else if (Estimators[i] == "structpearson") {
246 matrixCalculators.push_back(new StructPearson());
247 }else if (Estimators[i] == "soergel") {
248 matrixCalculators.push_back(new Soergel());
249 }else if (Estimators[i] == "spearman") {
250 matrixCalculators.push_back(new Spearman());
251 }else if (Estimators[i] == "structkulczynski") {
252 matrixCalculators.push_back(new StructKulczynski());
253 }else if (Estimators[i] == "speciesprofile") {
254 matrixCalculators.push_back(new SpeciesProfile());
255 }else if (Estimators[i] == "hamming") {
256 matrixCalculators.push_back(new Hamming());
257 }else if (Estimators[i] == "structchi2") {
258 matrixCalculators.push_back(new StructChi2());
259 }else if (Estimators[i] == "gower") {
260 matrixCalculators.push_back(new Gower());
261 }else if (Estimators[i] == "memchi2") {
262 matrixCalculators.push_back(new MemChi2());
263 }else if (Estimators[i] == "memchord") {
264 matrixCalculators.push_back(new MemChord());
265 }else if (Estimators[i] == "memeuclidean") {
266 matrixCalculators.push_back(new MemEuclidean());
267 }else if (Estimators[i] == "mempearson") {
268 matrixCalculators.push_back(new MemPearson());
277 catch(exception& e) {
278 m->errorOut(e, "MatrixOutputCommand", "MatrixOutputCommand");
283 //**********************************************************************************************************************
285 MatrixOutputCommand::~MatrixOutputCommand(){}
287 //**********************************************************************************************************************
289 int MatrixOutputCommand::execute(){
292 if (abort == true) { if (calledHelp) { return 0; } return 2; }
294 //if the users entered no valid calculators don't execute command
295 if (matrixCalculators.size() == 0) { m->mothurOut("No valid calculators."); m->mothurOutEndLine(); return 0; }
297 input = new InputData(sharedfile, "sharedfile");
298 lookup = input->getSharedRAbundVectors();
299 string lastLabel = lookup[0]->getLabel();
301 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
302 set<string> processedLabels;
303 set<string> userLabels = labels;
305 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;}
308 if (subsampleSize == -1) { //user has not set size, set size = smallest samples size
309 subsampleSize = lookup[0]->getNumSeqs();
310 for (int i = 1; i < lookup.size(); i++) {
311 int thisSize = lookup[i]->getNumSeqs();
313 if (thisSize < subsampleSize) { subsampleSize = thisSize; }
318 vector<SharedRAbundVector*> temp;
319 for (int i = 0; i < lookup.size(); i++) {
320 if (lookup[i]->getNumSeqs() < subsampleSize) {
321 m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
324 Groups.push_back(lookup[i]->getGroup());
325 temp.push_back(lookup[i]);
329 m->setGroups(Groups);
332 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; }
335 numGroups = lookup.size();
336 lines.resize(processors);
337 for (int i = 0; i < processors; i++) {
338 lines[i].start = int (sqrt(float(i)/float(processors)) * numGroups);
339 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numGroups);
342 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } m->clearGroups(); return 0; }
344 //as long as you are not at the end of the file or done wih the lines you want
345 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
347 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; }
349 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
350 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
353 processedLabels.insert(lookup[0]->getLabel());
354 userLabels.erase(lookup[0]->getLabel());
357 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
358 string saveLabel = lookup[0]->getLabel();
360 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
361 lookup = input->getSharedRAbundVectors(lastLabel);
363 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
366 processedLabels.insert(lookup[0]->getLabel());
367 userLabels.erase(lookup[0]->getLabel());
369 //restore real lastlabel to save below
370 lookup[0]->setLabel(saveLabel);
373 lastLabel = lookup[0]->getLabel();
375 //get next line to process
376 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
377 lookup = input->getSharedRAbundVectors();
380 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } m->clearGroups(); return 0; }
382 //output error messages about any remaining user labels
383 set<string>::iterator it;
384 bool needToRun = false;
385 for (it = userLabels.begin(); it != userLabels.end(); it++) {
386 m->mothurOut("Your file does not include the label " + *it);
387 if (processedLabels.count(lastLabel) != 1) {
388 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
391 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
395 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } m->clearGroups(); return 0; }
397 //run last label if you need to
398 if (needToRun == true) {
399 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
400 lookup = input->getSharedRAbundVectors(lastLabel);
402 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
404 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
407 if (m->control_pressed) { outputTypes.clear(); delete input; for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } m->clearGroups(); return 0; }
409 //reset groups parameter
412 //set phylip file as new current phylipfile
414 itTypes = outputTypes.find("phylip");
415 if (itTypes != outputTypes.end()) {
416 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
419 m->mothurOutEndLine();
420 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
421 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
422 m->mothurOutEndLine();
427 catch(exception& e) {
428 m->errorOut(e, "MatrixOutputCommand", "execute");
432 /***********************************************************/
433 void MatrixOutputCommand::printSims(ostream& out, vector< vector<double> >& simMatrix) {
436 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
439 out << simMatrix.size() << endl;
441 if (output == "lt") {
442 for (int b = 0; b < simMatrix.size(); b++) {
443 out << lookup[b]->getGroup() << '\t';
444 for (int n = 0; n < b; n++) {
445 out << simMatrix[b][n] << '\t';
450 for (int b = 0; b < simMatrix.size(); m++) {
451 out << lookup[b]->getGroup() << '\t';
452 for (int n = 0; n < simMatrix[b].size(); n++) {
453 out << simMatrix[b][n] << '\t';
459 catch(exception& e) {
460 m->errorOut(e, "MatrixOutputCommand", "printSims");
464 /***********************************************************/
465 int MatrixOutputCommand::process(vector<SharedRAbundVector*> thisLookup){
467 vector< vector< vector<seqDist> > > calcDistsTotals; //each iter, one for each calc, then each groupCombos dists. this will be used to make .dist files
468 vector< vector<seqDist> > calcDists; calcDists.resize(matrixCalculators.size());
470 for (int thisIter = 0; thisIter < iters+1; thisIter++) {
472 vector<SharedRAbundVector*> thisItersLookup = thisLookup;
474 if (subsample && (thisIter != 0)) {
476 vector<string> tempLabels; //dont need since we arent printing the sampled sharedRabunds
478 //make copy of lookup so we don't get access violations
479 vector<SharedRAbundVector*> newLookup;
480 for (int k = 0; k < thisItersLookup.size(); k++) {
481 SharedRAbundVector* temp = new SharedRAbundVector();
482 temp->setLabel(thisItersLookup[k]->getLabel());
483 temp->setGroup(thisItersLookup[k]->getGroup());
484 newLookup.push_back(temp);
488 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
489 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
490 for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
493 tempLabels = sample.getSample(newLookup, subsampleSize);
494 thisItersLookup = newLookup;
498 driver(thisItersLookup, 0, numGroups, calcDists);
501 vector<int> processIDS;
503 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
504 //loop through and create all the processes you want
505 while (process != processors) {
509 processIDS.push_back(pid);
513 driver(thisItersLookup, lines[process].start, lines[process].end, calcDists);
515 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(getpid()) + ".dist";
517 m->openOutputFile(tempdistFileName, outtemp);
519 for (int i = 0; i < calcDists.size(); i++) {
520 outtemp << calcDists[i].size() << endl;
522 for (int j = 0; j < calcDists[i].size(); j++) {
523 outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl;
530 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
531 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
536 //parent do your part
537 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);
539 //force parent to wait until all the processes are done
540 for (int i = 0; i < processIDS.size(); i++) {
541 int temp = processIDS[i];
545 for (int i = 0; i < processIDS.size(); i++) {
546 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(processIDS[i]) + ".dist";
548 m->openInputFile(tempdistFileName, intemp);
550 for (int k = 0; k < calcDists.size(); k++) {
552 intemp >> size; m->gobble(intemp);
554 for (int j = 0; j < size; j++) {
559 intemp >> seq1 >> seq2 >> dist; m->gobble(intemp);
561 seqDist tempDist(seq1, seq2, dist);
562 calcDists[k].push_back(tempDist);
566 m->mothurRemove(tempdistFileName);
569 //////////////////////////////////////////////////////////////////////////////////////////////////////
570 //Windows version shared memory, so be careful when passing variables through the distSharedData struct.
571 //Above fork() will clone, so memory is separate, but that's not the case with windows,
572 //Taking advantage of shared memory to pass results vectors.
573 //////////////////////////////////////////////////////////////////////////////////////////////////////
575 vector<distSharedData*> pDataArray;
576 DWORD dwThreadIdArray[processors-1];
577 HANDLE hThreadArray[processors-1];
579 //Create processor worker threads.
580 for( int i=1; i<processors; i++ ){
582 //make copy of lookup so we don't get access violations
583 vector<SharedRAbundVector*> newLookup;
584 for (int k = 0; k < thisItersLookup.size(); k++) {
585 SharedRAbundVector* temp = new SharedRAbundVector();
586 temp->setLabel(thisItersLookup[k]->getLabel());
587 temp->setGroup(thisItersLookup[k]->getGroup());
588 newLookup.push_back(temp);
592 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
593 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
594 for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
597 // Allocate memory for thread data.
598 distSharedData* tempSum = new distSharedData(m, lines[i].start, lines[i].end, Estimators, newLookup);
599 pDataArray.push_back(tempSum);
600 processIDS.push_back(i);
602 hThreadArray[i-1] = CreateThread(NULL, 0, MyDistSharedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
605 //parent do your part
606 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);
608 //Wait until all threads have terminated.
609 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
611 //Close all thread handles and free memory allocations.
612 for(int i=0; i < pDataArray.size(); i++){
613 for (int j = 0; j < pDataArray[i]->thisLookup.size(); j++) { delete pDataArray[i]->thisLookup[j]; }
615 for (int k = 0; k < calcDists.size(); k++) {
616 int size = pDataArray[i]->calcDists[k].size();
617 for (int j = 0; j < size; j++) { calcDists[k].push_back(pDataArray[i]->calcDists[k][j]); }
620 CloseHandle(hThreadArray[i]);
621 delete pDataArray[i];
627 if (subsample && (thisIter != 0)) {
628 if((thisIter) % 100 == 0){ m->mothurOut(toString(thisIter)); m->mothurOutEndLine(); }
629 calcDistsTotals.push_back(calcDists);
630 for (int i = 0; i < calcDists.size(); i++) {
631 for (int j = 0; j < calcDists[i].size(); j++) {
632 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"); }
636 for (int i = 0; i < thisItersLookup.size(); i++) { delete thisItersLookup[i]; }
637 thisItersLookup.clear();
638 }else { //print results for whole dataset
639 for (int i = 0; i < calcDists.size(); i++) {
640 if (m->control_pressed) { break; }
643 vector< vector<double> > matrix; //square matrix to represent the distance
644 matrix.resize(thisLookup.size());
645 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
647 for (int j = 0; j < calcDists[i].size(); j++) {
648 int row = calcDists[i][j].seq1;
649 int column = calcDists[i][j].seq2;
650 double dist = calcDists[i][j].dist;
652 matrix[row][column] = dist;
653 matrix[column][row] = dist;
656 string distFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + matrixCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + "." + output + ".dist";
657 outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
659 m->openOutputFile(distFileName, outDist);
660 outDist.setf(ios::fixed, ios::floatfield); outDist.setf(ios::showpoint);
662 printSims(outDist, matrix);
667 for (int i = 0; i < calcDists.size(); i++) { calcDists[i].clear(); }
671 //we need to find the average distance and standard deviation for each groups distance
673 vector< vector<seqDist> > calcAverages; calcAverages.resize(matrixCalculators.size());
674 for (int i = 0; i < calcAverages.size(); i++) { //initialize sums to zero.
675 calcAverages[i].resize(calcDistsTotals[0][i].size());
677 for (int j = 0; j < calcAverages[i].size(); j++) {
678 calcAverages[i][j].seq1 = calcDistsTotals[0][i][j].seq1;
679 calcAverages[i][j].seq2 = calcDistsTotals[0][i][j].seq2;
680 calcAverages[i][j].dist = 0.0;
683 if (mode == "average") {
684 for (int thisIter = 0; thisIter < iters; thisIter++) { //sum all groups dists for each calculator
685 for (int i = 0; i < calcAverages.size(); i++) { //initialize sums to zero.
686 for (int j = 0; j < calcAverages[i].size(); j++) {
687 calcAverages[i][j].dist += calcDistsTotals[thisIter][i][j].dist;
688 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"); }
693 for (int i = 0; i < calcAverages.size(); i++) { //finds average.
694 for (int j = 0; j < calcAverages[i].size(); j++) {
695 calcAverages[i][j].dist /= (float) iters;
698 }else { //find median
699 for (int i = 0; i < calcAverages.size(); i++) { //for each calc
700 for (int j = 0; j < calcAverages[i].size(); j++) { //for each comparison
701 vector<double> dists;
702 for (int thisIter = 0; thisIter < iters; thisIter++) { //for each subsample
703 dists.push_back(calcDistsTotals[thisIter][i][j].dist);
705 sort(dists.begin(), dists.end());
706 calcAverages[i][j].dist = dists[(iters/2)];
710 //find standard deviation
711 vector< vector<seqDist> > stdDev; stdDev.resize(matrixCalculators.size());
712 for (int i = 0; i < stdDev.size(); i++) { //initialize sums to zero.
713 stdDev[i].resize(calcDistsTotals[0][i].size());
715 for (int j = 0; j < stdDev[i].size(); j++) {
716 stdDev[i][j].seq1 = calcDistsTotals[0][i][j].seq1;
717 stdDev[i][j].seq2 = calcDistsTotals[0][i][j].seq2;
718 stdDev[i][j].dist = 0.0;
722 for (int thisIter = 0; thisIter < iters; thisIter++) { //compute the difference of each dist from the mean, and square the result of each
723 for (int i = 0; i < stdDev.size(); i++) {
724 for (int j = 0; j < stdDev[i].size(); j++) {
725 stdDev[i][j].dist += ((calcDistsTotals[thisIter][i][j].dist - calcAverages[i][j].dist) * (calcDistsTotals[thisIter][i][j].dist - calcAverages[i][j].dist));
730 for (int i = 0; i < stdDev.size(); i++) { //finds average.
731 for (int j = 0; j < stdDev[i].size(); j++) {
732 stdDev[i][j].dist /= (float) iters;
733 stdDev[i][j].dist = sqrt(stdDev[i][j].dist);
738 for (int i = 0; i < calcDists.size(); i++) {
739 vector< vector<double> > matrix; //square matrix to represent the distance
740 matrix.resize(thisLookup.size());
741 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
743 vector< vector<double> > stdmatrix; //square matrix to represent the stdDev
744 stdmatrix.resize(thisLookup.size());
745 for (int k = 0; k < thisLookup.size(); k++) { stdmatrix[k].resize(thisLookup.size(), 0.0); }
748 for (int j = 0; j < calcAverages[i].size(); j++) {
749 int row = calcAverages[i][j].seq1;
750 int column = calcAverages[i][j].seq2;
751 float dist = calcAverages[i][j].dist;
752 float stdDist = stdDev[i][j].dist;
754 matrix[row][column] = dist;
755 matrix[column][row] = dist;
756 stdmatrix[row][column] = stdDist;
757 stdmatrix[column][row] = stdDist;
760 string distFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + matrixCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + "." + output + ".ave.dist";
761 outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
763 m->openOutputFile(distFileName, outAve);
764 outAve.setf(ios::fixed, ios::floatfield); outAve.setf(ios::showpoint);
766 printSims(outAve, matrix);
770 distFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + matrixCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + "." + output + ".std.dist";
771 outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
773 m->openOutputFile(distFileName, outSTD);
774 outSTD.setf(ios::fixed, ios::floatfield); outSTD.setf(ios::showpoint);
776 printSims(outSTD, stdmatrix);
785 catch(exception& e) {
786 m->errorOut(e, "MatrixOutputCommand", "process");
790 /**************************************************************************************************/
791 int MatrixOutputCommand::driver(vector<SharedRAbundVector*> thisLookup, int start, int end, vector< vector<seqDist> >& calcDists) {
793 vector<SharedRAbundVector*> subset;
795 for (int k = start; k < end; k++) { // pass cdd each set of groups to compare
797 for (int l = 0; l < k; l++) {
799 if (k != l) { //we dont need to similiarity of a groups to itself
800 subset.clear(); //clear out old pair of sharedrabunds
801 //add new pair of sharedrabunds
802 subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]);
804 for(int i=0;i<matrixCalculators.size();i++) {
806 //if this calc needs all groups to calculate the pair load all groups
807 if (matrixCalculators[i]->getNeedsAll()) {
808 //load subset with rest of lookup for those calcs that need everyone to calc for a pair
809 for (int w = 0; w < thisLookup.size(); w++) {
810 if ((w != k) && (w != l)) { subset.push_back(thisLookup[w]); }
814 vector<double> tempdata = matrixCalculators[i]->getValues(subset); //saves the calculator outputs
816 if (m->control_pressed) { return 1; }
818 seqDist temp(l, k, tempdata[0]);
819 calcDists[i].push_back(temp);
827 catch(exception& e) {
828 m->errorOut(e, "MatrixOutputCommand", "driver");
832 /***********************************************************/