]> git.donarmstrong.com Git - mothur.git/blob - matrixoutputcommand.cpp
fixed bug in pre.cluster with output file name change and other bugs while testing...
[mothur.git] / matrixoutputcommand.cpp
1 /*
2  *  matrixoutputcommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 5/20/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "matrixoutputcommand.h"
11 #include "subsample.h"
12
13 //**********************************************************************************************************************
14 vector<string> MatrixOutputCommand::setParameters(){    
15         try {
16                 CommandParameter pshared("shared", "InputTypes", "", "", "none", "none", "none","phylip",false,true,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,true); 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,true); 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);
27                 
28                 vector<string> myArray;
29                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
30                 return myArray;
31         }
32         catch(exception& e) {
33                 m->errorOut(e, "MatrixOutputCommand", "setParameters");
34                 exit(1);
35         }
36 }
37 //**********************************************************************************************************************
38 string MatrixOutputCommand::getHelpString(){    
39         try {
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";
56                 return helpString;
57         }
58         catch(exception& e) {
59                 m->errorOut(e, "MatrixOutputCommand", "getHelpString");
60                 exit(1);
61         }
62 }
63 //**********************************************************************************************************************
64 string MatrixOutputCommand::getOutputPattern(string type) {
65     try {
66         string pattern = "";
67         
68         if (type == "phylip") {  pattern = "[filename],[calc],[distance],[outputtag],dist-[filename],[calc],[distance],[outputtag],[tag2],dist"; } 
69         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
70         
71         return pattern;
72     }
73     catch(exception& e) {
74         m->errorOut(e, "MatrixOutputCommand", "getOutputPattern");
75         exit(1);
76     }
77 }
78 //**********************************************************************************************************************
79 MatrixOutputCommand::MatrixOutputCommand(){     
80         try {
81                 abort = true; calledHelp = true; 
82                 setParameters();
83                 vector<string> tempOutNames;
84                 outputTypes["phylip"] = tempOutNames;
85         }
86         catch(exception& e) {
87                 m->errorOut(e, "MatrixOutputCommand", "MatrixOutputCommand");
88                 exit(1);
89         }
90 }
91 //**********************************************************************************************************************
92
93 MatrixOutputCommand::MatrixOutputCommand(string option)  {
94         try {
95                 abort = false; calledHelp = false;   
96                 allLines = 1;
97                                 
98                 //allow user to run help
99                 if(option == "help") {  help(); abort = true; calledHelp = true; }
100                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
101                 
102                 else {
103                         vector<string> myArray = setParameters();
104                         
105                         OptionParser parser(option);
106                         map<string,string> parameters  = parser.getParameters();
107                         map<string,string>::iterator it;
108                         
109                         ValidParameters validParameter;
110                 
111                         //check to make sure all parameters are valid for command
112                         for (it = parameters.begin(); it != parameters.end(); it++) { 
113                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
114                         }
115                         
116                         //initialize outputTypes
117                         vector<string> tempOutNames;
118                         outputTypes["phylip"] = tempOutNames;
119                         
120                         //if the user changes the input directory command factory will send this info to us in the output parameter 
121                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
122                         if (inputDir == "not found"){   inputDir = "";          }
123                         else {
124                                 string path;
125                                 it = parameters.find("shared");
126                                 //user has given a template file
127                                 if(it != parameters.end()){ 
128                                         path = m->hasPath(it->second);
129                                         //if the user has not given a path then, add inputdir. else leave path alone.
130                                         if (path == "") {       parameters["shared"] = inputDir + it->second;           }
131                                 }
132                         }
133                         
134                         sharedfile = validParameter.validFile(parameters, "shared", true);
135                         if (sharedfile == "not found") {                        
136                                 //if there is a current shared file, use it
137                                 sharedfile = m->getSharedFile(); 
138                                 if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
139                                 else {  m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
140                         }else if (sharedfile == "not open") { sharedfile = ""; abort = true; }
141                         else { m->setSharedFile(sharedfile); }
142                         
143                         //if the user changes the output directory command factory will send this info to us in the output parameter 
144                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
145                                 outputDir = ""; 
146                                 outputDir += m->hasPath(sharedfile); //if user entered a file with a path then preserve it      
147                         }
148                         
149                         //check for optional parameter and set defaults
150                         // ...at some point should added some additional type checking...
151                         label = validParameter.validFile(parameters, "label", false);                   
152                         if (label == "not found") { label = ""; }
153                         else { 
154                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
155                                 else { allLines = 1;  }
156                         }
157                         
158                         output = validParameter.validFile(parameters, "output", false);         if(output == "not found"){      output = "lt"; }
159                         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"; }
160             
161             mode = validParameter.validFile(parameters, "mode", false);         if(mode == "not found"){        mode = "average"; }
162                         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"; }
163                         
164                         groups = validParameter.validFile(parameters, "groups", false);                 
165                         if (groups == "not found") { groups = ""; }
166                         else { 
167                                 m->splitAtDash(groups, Groups);
168                                 m->setGroups(Groups);
169                         }
170                         
171                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
172                         m->setProcessors(temp);
173                         m->mothurConvert(temp, processors); 
174                                 
175                         calc = validParameter.validFile(parameters, "calc", false);                     
176                         if (calc == "not found") { calc = "jclass-thetayc";  }
177                         else { 
178                                  if (calc == "default")  {  calc = "jclass-thetayc";  }
179                         }
180                         m->splitAtDash(calc, Estimators);
181                         if (m->inUsersGroups("citation", Estimators)) { 
182                                 ValidCalculators validCalc; validCalc.printCitations(Estimators); 
183                                 //remove citation from list of calcs
184                                 for (int i = 0; i < Estimators.size(); i++) { if (Estimators[i] == "citation") {  Estimators.erase(Estimators.begin()+i); break; } }
185                         }
186             
187             temp = validParameter.validFile(parameters, "iters", false);                        if (temp == "not found") { temp = "1000"; }
188                         m->mothurConvert(temp, iters); 
189             
190             temp = validParameter.validFile(parameters, "subsample", false);            if (temp == "not found") { temp = "F"; }
191                         if (m->isNumeric1(temp)) { m->mothurConvert(temp, subsampleSize); subsample = true; }
192             else {  
193                 if (m->isTrue(temp)) { subsample = true; subsampleSize = -1; }  //we will set it to smallest group later 
194                 else { subsample = false; }
195             }
196             
197             if (subsample == false) { iters = 0; }
198             
199                         if (abort == false) {
200                         
201                                 ValidCalculators validCalculator;
202                                 
203                                 int i;
204                                 for (i=0; i<Estimators.size(); i++) {
205                                         if (validCalculator.isValidCalculator("matrix", Estimators[i]) == true) { 
206                                                 if (Estimators[i] == "sharedsobs") { 
207                                                         matrixCalculators.push_back(new SharedSobsCS());
208                                                 }else if (Estimators[i] == "sharedchao") { 
209                                                         matrixCalculators.push_back(new SharedChao1());
210                                                 }else if (Estimators[i] == "sharedace") { 
211                                                         matrixCalculators.push_back(new SharedAce());
212                                                 }else if (Estimators[i] == "jabund") {  
213                                                         matrixCalculators.push_back(new JAbund());
214                                                 }else if (Estimators[i] == "sorabund") { 
215                                                         matrixCalculators.push_back(new SorAbund());
216                                                 }else if (Estimators[i] == "jclass") { 
217                                                         matrixCalculators.push_back(new Jclass());
218                                                 }else if (Estimators[i] == "sorclass") { 
219                                                         matrixCalculators.push_back(new SorClass());
220                                                 }else if (Estimators[i] == "jest") { 
221                                                         matrixCalculators.push_back(new Jest());
222                                                 }else if (Estimators[i] == "sorest") { 
223                                                         matrixCalculators.push_back(new SorEst());
224                                                 }else if (Estimators[i] == "thetayc") { 
225                                                         matrixCalculators.push_back(new ThetaYC());
226                                                 }else if (Estimators[i] == "thetan") { 
227                                                         matrixCalculators.push_back(new ThetaN());
228                                                 }else if (Estimators[i] == "kstest") { 
229                                                         matrixCalculators.push_back(new KSTest());
230                                                 }else if (Estimators[i] == "sharednseqs") { 
231                                                         matrixCalculators.push_back(new SharedNSeqs());
232                                                 }else if (Estimators[i] == "ochiai") { 
233                                                         matrixCalculators.push_back(new Ochiai());
234                                                 }else if (Estimators[i] == "anderberg") { 
235                                                         matrixCalculators.push_back(new Anderberg());
236                                                 }else if (Estimators[i] == "kulczynski") { 
237                                                         matrixCalculators.push_back(new Kulczynski());
238                                                 }else if (Estimators[i] == "kulczynskicody") { 
239                                                         matrixCalculators.push_back(new KulczynskiCody());
240                                                 }else if (Estimators[i] == "lennon") { 
241                                                         matrixCalculators.push_back(new Lennon());
242                                                 }else if (Estimators[i] == "morisitahorn") { 
243                                                         matrixCalculators.push_back(new MorHorn());
244                                                 }else if (Estimators[i] == "braycurtis") { 
245                                                         matrixCalculators.push_back(new BrayCurtis());
246                                                 }else if (Estimators[i] == "whittaker") { 
247                                                         matrixCalculators.push_back(new Whittaker());
248                                                 }else if (Estimators[i] == "odum") { 
249                                                         matrixCalculators.push_back(new Odum());
250                                                 }else if (Estimators[i] == "canberra") { 
251                                                         matrixCalculators.push_back(new Canberra());
252                                                 }else if (Estimators[i] == "structeuclidean") { 
253                                                         matrixCalculators.push_back(new StructEuclidean());
254                                                 }else if (Estimators[i] == "structchord") { 
255                                                         matrixCalculators.push_back(new StructChord());
256                                                 }else if (Estimators[i] == "hellinger") { 
257                                                         matrixCalculators.push_back(new Hellinger());
258                                                 }else if (Estimators[i] == "manhattan") { 
259                                                         matrixCalculators.push_back(new Manhattan());
260                                                 }else if (Estimators[i] == "structpearson") { 
261                                                         matrixCalculators.push_back(new StructPearson());
262                                                 }else if (Estimators[i] == "soergel") { 
263                                                         matrixCalculators.push_back(new Soergel());
264                                                 }else if (Estimators[i] == "spearman") { 
265                                                         matrixCalculators.push_back(new Spearman());
266                                                 }else if (Estimators[i] == "structkulczynski") { 
267                                                         matrixCalculators.push_back(new StructKulczynski());
268                                                 }else if (Estimators[i] == "speciesprofile") { 
269                                                         matrixCalculators.push_back(new SpeciesProfile());
270                                                 }else if (Estimators[i] == "hamming") { 
271                                                         matrixCalculators.push_back(new Hamming());
272                                                 }else if (Estimators[i] == "structchi2") { 
273                                                         matrixCalculators.push_back(new StructChi2());
274                                                 }else if (Estimators[i] == "gower") { 
275                                                         matrixCalculators.push_back(new Gower());
276                                                 }else if (Estimators[i] == "memchi2") { 
277                                                         matrixCalculators.push_back(new MemChi2());
278                                                 }else if (Estimators[i] == "memchord") { 
279                                                         matrixCalculators.push_back(new MemChord());
280                                                 }else if (Estimators[i] == "memeuclidean") { 
281                                                         matrixCalculators.push_back(new MemEuclidean());
282                                                 }else if (Estimators[i] == "mempearson") { 
283                                                         matrixCalculators.push_back(new MemPearson());
284                                                 }
285                                         }
286                                 }
287                                 
288                         }
289                 }
290                 
291         }
292         catch(exception& e) {
293                 m->errorOut(e, "MatrixOutputCommand", "MatrixOutputCommand");
294                 exit(1);
295         }
296 }
297
298 //**********************************************************************************************************************
299
300 MatrixOutputCommand::~MatrixOutputCommand(){}
301
302 //**********************************************************************************************************************
303
304 int MatrixOutputCommand::execute(){
305         try {
306                 
307                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
308                         
309                 //if the users entered no valid calculators don't execute command
310                 if (matrixCalculators.size() == 0) { m->mothurOut("No valid calculators."); m->mothurOutEndLine();  return 0; }
311                         
312                 input = new InputData(sharedfile, "sharedfile");
313                 lookup = input->getSharedRAbundVectors();
314                 string lastLabel = lookup[0]->getLabel();
315                 
316                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
317                 set<string> processedLabels;
318                 set<string> userLabels = labels;
319                                         
320                 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;}
321         
322         if (subsample) { 
323             if (subsampleSize == -1) { //user has not set size, set size = smallest samples size
324                 subsampleSize = lookup[0]->getNumSeqs();
325                 for (int i = 1; i < lookup.size(); i++) {
326                     int thisSize = lookup[i]->getNumSeqs();
327                     
328                     if (thisSize < subsampleSize) {     subsampleSize = thisSize;       }
329                 }
330             }else {
331                 m->clearGroups();
332                 Groups.clear();
333                 vector<SharedRAbundVector*> temp;
334                 for (int i = 0; i < lookup.size(); i++) {
335                     if (lookup[i]->getNumSeqs() < subsampleSize) { 
336                         m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
337                         delete lookup[i];
338                     }else { 
339                         Groups.push_back(lookup[i]->getGroup()); 
340                         temp.push_back(lookup[i]);
341                     }
342                 } 
343                 lookup = temp;
344                 m->setGroups(Groups);
345             }
346             
347             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; }
348         }
349         
350                 numGroups = lookup.size();
351         lines.resize(processors);
352                 for (int i = 0; i < processors; i++) {
353                         lines[i].start = int (sqrt(float(i)/float(processors)) * numGroups);
354                         lines[i].end = int (sqrt(float(i+1)/float(processors)) * numGroups);
355                 }       
356         
357                 if (m->control_pressed) { delete input; for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } m->clearGroups(); return 0;  }
358                                 
359                 //as long as you are not at the end of the file or done wih the lines you want
360                 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
361                 
362                         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;  }
363                 
364                         if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){                  
365                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
366                                 process(lookup);
367                                 
368                                 processedLabels.insert(lookup[0]->getLabel());
369                                 userLabels.erase(lookup[0]->getLabel());
370                         }
371                         
372                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
373                                 string saveLabel = lookup[0]->getLabel();
374                                 
375                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
376                                 lookup = input->getSharedRAbundVectors(lastLabel);
377
378                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
379                                 process(lookup);
380                                 
381                                 processedLabels.insert(lookup[0]->getLabel());
382                                 userLabels.erase(lookup[0]->getLabel());
383                                 
384                                 //restore real lastlabel to save below
385                                 lookup[0]->setLabel(saveLabel);
386                         }
387
388                         lastLabel = lookup[0]->getLabel();                      
389                         
390                         //get next line to process
391                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
392                         lookup = input->getSharedRAbundVectors();
393                 }
394                 
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;  }
396
397                 //output error messages about any remaining user labels
398                 set<string>::iterator it;
399                 bool needToRun = false;
400                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
401                         m->mothurOut("Your file does not include the label " + *it);  
402                         if (processedLabels.count(lastLabel) != 1) {
403                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
404                                 needToRun = true;
405                         }else {
406                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
407                         }
408                 }
409                 
410                 if (m->control_pressed) { outputTypes.clear(); delete input;  for (int i = 0; i < outputNames.size(); i++) {    m->mothurRemove(outputNames[i]); } m->clearGroups(); return 0;  }
411
412                 //run last label if you need to
413                 if (needToRun == true)  {
414                         for (int i = 0; i < lookup.size(); i++) {  if (lookup[i] != NULL) {  delete lookup[i]; }  } 
415                         lookup = input->getSharedRAbundVectors(lastLabel);
416
417                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
418                         process(lookup);
419                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
420                 }
421                 
422                 if (m->control_pressed) { outputTypes.clear();  delete input;  for (int i = 0; i < outputNames.size(); i++) {   m->mothurRemove(outputNames[i]); } m->clearGroups(); return 0;  }
423                 
424                 //reset groups parameter
425                 m->clearGroups();  
426                 
427                 //set phylip file as new current phylipfile
428                 string current = "";
429                 itTypes = outputTypes.find("phylip");
430                 if (itTypes != outputTypes.end()) {
431                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
432                 }
433                 
434                 m->mothurOutEndLine();
435                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
436                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
437                 m->mothurOutEndLine();
438
439
440                 return 0;
441         }
442         catch(exception& e) {
443                 m->errorOut(e, "MatrixOutputCommand", "execute");
444                 exit(1);
445         }
446 }
447 /***********************************************************/
448 void MatrixOutputCommand::printSims(ostream& out, vector< vector<double> >& simMatrix) {
449         try {
450                 
451                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
452                 
453                 //output num seqs
454                 out << simMatrix.size() << endl;
455                 
456                 if (output == "lt") {
457                         for (int b = 0; b < simMatrix.size(); b++)      {
458                                 out << lookup[b]->getGroup() << '\t';
459                                 for (int n = 0; n < b; n++)     {
460                                         out << simMatrix[b][n] << '\t'; 
461                                 }
462                                 out << endl;
463                         }
464                 }else{
465                         for (int b = 0; b < simMatrix.size(); b++)      {
466                                 out << lookup[b]->getGroup() << '\t';
467                                 for (int n = 0; n < simMatrix[b].size(); n++)   {
468                                         out << simMatrix[b][n] << '\t'; 
469                                 }
470                                 out << endl;
471                         }
472                 }
473         }
474         catch(exception& e) {
475                 m->errorOut(e, "MatrixOutputCommand", "printSims");
476                 exit(1);
477         }
478 }
479 /***********************************************************/
480 int MatrixOutputCommand::process(vector<SharedRAbundVector*> thisLookup){
481         try {
482                 vector< vector< vector<seqDist> > > calcDistsTotals;  //each iter, one for each calc, then each groupCombos dists. this will be used to make .dist files
483         vector< vector<seqDist>  > calcDists; calcDists.resize(matrixCalculators.size());               
484                   
485         for (int thisIter = 0; thisIter < iters+1; thisIter++) {
486             map<string, string> variables; 
487             variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(sharedfile));
488             variables["[distance]"] = thisLookup[0]->getLabel();
489             variables["[tag2]"] = "";
490             
491             vector<SharedRAbundVector*> thisItersLookup = thisLookup;
492             
493             if (subsample && (thisIter != 0)) {
494                 SubSample sample;
495                 vector<string> tempLabels; //dont need since we arent printing the sampled sharedRabunds
496                 
497                 //make copy of lookup so we don't get access violations
498                 vector<SharedRAbundVector*> newLookup;
499                 for (int k = 0; k < thisItersLookup.size(); k++) {
500                     SharedRAbundVector* temp = new SharedRAbundVector();
501                     temp->setLabel(thisItersLookup[k]->getLabel());
502                     temp->setGroup(thisItersLookup[k]->getGroup());
503                     newLookup.push_back(temp);
504                 }
505                 
506                 //for each bin
507                 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
508                     if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
509                     for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
510                 }
511                 
512                 tempLabels = sample.getSample(newLookup, subsampleSize);
513                 thisItersLookup = newLookup;
514             }
515         
516             if(processors == 1){
517                 driver(thisItersLookup, 0, numGroups, calcDists);
518             }else{
519                 int process = 1;
520                 vector<int> processIDS;
521                 
522                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
523                 //loop through and create all the processes you want
524                 while (process != processors) {
525                     int pid = fork();
526                     
527                     if (pid > 0) {
528                         processIDS.push_back(pid); 
529                         process++;
530                     }else if (pid == 0){
531                         
532                         driver(thisItersLookup, lines[process].start, lines[process].end, calcDists);   
533                         
534                         string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(getpid()) + ".dist";
535                         ofstream outtemp;
536                         m->openOutputFile(tempdistFileName, outtemp);
537                             
538                         for (int i = 0; i < calcDists.size(); i++) {
539                             outtemp << calcDists[i].size() << endl;
540                                 
541                             for (int j = 0; j < calcDists[i].size(); j++) {
542                                 outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl;
543                             }
544                         }
545                         outtemp.close();
546                                         
547                         exit(0);
548                     }else { 
549                         m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
550                         for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
551                         exit(0);
552                     }
553                 }
554                 
555                 //parent do your part
556                 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);   
557                             
558                 //force parent to wait until all the processes are done
559                 for (int i = 0; i < processIDS.size(); i++) {
560                     int temp = processIDS[i];
561                     wait(&temp);
562                 }
563                 
564                 for (int i = 0; i < processIDS.size(); i++) {
565                     string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(processIDS[i]) +  ".dist";
566                     ifstream intemp;
567                     m->openInputFile(tempdistFileName, intemp);
568                         
569                     for (int k = 0; k < calcDists.size(); k++) {
570                         int size = 0;
571                         intemp >> size; m->gobble(intemp);
572                             
573                         for (int j = 0; j < size; j++) {
574                             int seq1 = 0;
575                             int seq2 = 0;
576                             float dist = 1.0;
577                                 
578                             intemp >> seq1 >> seq2 >> dist;   m->gobble(intemp);
579                                 
580                             seqDist tempDist(seq1, seq2, dist);
581                             calcDists[k].push_back(tempDist);
582                         }
583                     }
584                     intemp.close();
585                     m->mothurRemove(tempdistFileName);
586                 }
587                 #else
588                 //////////////////////////////////////////////////////////////////////////////////////////////////////
589                 //Windows version shared memory, so be careful when passing variables through the distSharedData struct. 
590                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
591                 //Taking advantage of shared memory to pass results vectors.
592                 //////////////////////////////////////////////////////////////////////////////////////////////////////
593                 
594                 vector<distSharedData*> pDataArray; 
595                 DWORD   dwThreadIdArray[processors-1];
596                 HANDLE  hThreadArray[processors-1]; 
597                 
598                 //Create processor worker threads.
599                 for( int i=1; i<processors; i++ ){
600                     
601                     //make copy of lookup so we don't get access violations
602                     vector<SharedRAbundVector*> newLookup;
603                     for (int k = 0; k < thisItersLookup.size(); k++) {
604                         SharedRAbundVector* temp = new SharedRAbundVector();
605                         temp->setLabel(thisItersLookup[k]->getLabel());
606                         temp->setGroup(thisItersLookup[k]->getGroup());
607                         newLookup.push_back(temp);
608                     }
609                     
610                     //for each bin
611                     for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
612                         if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
613                         for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
614                     }
615                     
616                     // Allocate memory for thread data.
617                     distSharedData* tempSum = new distSharedData(m, lines[i].start, lines[i].end, Estimators, newLookup);
618                     pDataArray.push_back(tempSum);
619                     processIDS.push_back(i);
620                     
621                     hThreadArray[i-1] = CreateThread(NULL, 0, MyDistSharedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
622                 }
623                 
624                 //parent do your part
625                 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);   
626                            
627                 //Wait until all threads have terminated.
628                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
629                 
630                 //Close all thread handles and free memory allocations.
631                 for(int i=0; i < pDataArray.size(); i++){
632                     for (int j = 0; j < pDataArray[i]->thisLookup.size(); j++) {  delete pDataArray[i]->thisLookup[j];  } 
633                     
634                     for (int k = 0; k < calcDists.size(); k++) {
635                         int size = pDataArray[i]->calcDists[k].size();
636                         for (int j = 0; j < size; j++) {    calcDists[k].push_back(pDataArray[i]->calcDists[k][j]);    }
637                     }
638                     
639                     CloseHandle(hThreadArray[i]);
640                     delete pDataArray[i];
641                 }
642
643                 #endif
644             }
645             
646             if (subsample && (thisIter != 0)) {  
647                 if((thisIter) % 100 == 0){      m->mothurOut(toString(thisIter)); m->mothurOutEndLine();                }
648                 calcDistsTotals.push_back(calcDists);
649                 for (int i = 0; i < calcDists.size(); i++) {
650                     for (int j = 0; j < calcDists[i].size(); j++) {
651                         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");  }
652                     } 
653                 }
654                 //clean up memory
655                 for (int i = 0; i < thisItersLookup.size(); i++) { delete thisItersLookup[i]; }
656                 thisItersLookup.clear();
657             }else { //print results for whole dataset
658                 for (int i = 0; i < calcDists.size(); i++) {
659                     if (m->control_pressed) { break; }
660                     
661                     //initialize matrix
662                     vector< vector<double> > matrix; //square matrix to represent the distance
663                     matrix.resize(thisLookup.size());
664                     for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
665                     
666                     for (int j = 0; j < calcDists[i].size(); j++) {
667                         int row = calcDists[i][j].seq1;
668                         int column = calcDists[i][j].seq2;
669                         double dist = calcDists[i][j].dist;
670                         
671                         matrix[row][column] = dist;
672                         matrix[column][row] = dist;
673                     }
674                     
675                     variables["[outputtag]"] = output;
676                     variables["[calc]"] = matrixCalculators[i]->getName();
677                     string distFileName = getOutputFileName("phylip",variables);
678                     outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
679                     
680                     ofstream outDist;
681                     m->openOutputFile(distFileName, outDist);
682                     outDist.setf(ios::fixed, ios::floatfield); outDist.setf(ios::showpoint);
683                     
684                     printSims(outDist, matrix);
685                     
686                     outDist.close();
687                 }
688             }
689             for (int i = 0; i < calcDists.size(); i++) {  calcDists[i].clear(); }
690                 }
691                 
692         if (iters != 0) {
693             //we need to find the average distance and standard deviation for each groups distance
694             
695             vector< vector<seqDist>  > calcAverages; calcAverages.resize(matrixCalculators.size()); 
696             for (int i = 0; i < calcAverages.size(); i++) {  //initialize sums to zero.
697                 calcAverages[i].resize(calcDistsTotals[0][i].size());
698                 
699                 for (int j = 0; j < calcAverages[i].size(); j++) {
700                     calcAverages[i][j].seq1 = calcDistsTotals[0][i][j].seq1;
701                     calcAverages[i][j].seq2 = calcDistsTotals[0][i][j].seq2;
702                     calcAverages[i][j].dist = 0.0;
703                 }
704             }
705             if (mode == "average") {
706                 for (int thisIter = 0; thisIter < iters; thisIter++) { //sum all groups dists for each calculator
707                     for (int i = 0; i < calcAverages.size(); i++) {  //initialize sums to zero.
708                         for (int j = 0; j < calcAverages[i].size(); j++) {
709                             calcAverages[i][j].dist += calcDistsTotals[thisIter][i][j].dist;
710                             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");  }
711                         }
712                     }
713                 }
714                 
715                 for (int i = 0; i < calcAverages.size(); i++) {  //finds average.
716                     for (int j = 0; j < calcAverages[i].size(); j++) {
717                         calcAverages[i][j].dist /= (float) iters;
718                     }
719                 }
720             }else { //find median
721                 for (int i = 0; i < calcAverages.size(); i++) { //for each calc
722                     for (int j = 0; j < calcAverages[i].size(); j++) {  //for each comparison
723                         vector<double> dists;
724                         for (int thisIter = 0; thisIter < iters; thisIter++) { //for each subsample
725                             dists.push_back(calcDistsTotals[thisIter][i][j].dist);
726                         }
727                         sort(dists.begin(), dists.end());
728                         calcAverages[i][j].dist = dists[(iters/2)];
729                     }
730                 }
731             }
732             //find standard deviation
733             vector< vector<seqDist>  > stdDev; stdDev.resize(matrixCalculators.size());
734             for (int i = 0; i < stdDev.size(); i++) {  //initialize sums to zero.
735                 stdDev[i].resize(calcDistsTotals[0][i].size());
736                 
737                 for (int j = 0; j < stdDev[i].size(); j++) {
738                     stdDev[i][j].seq1 = calcDistsTotals[0][i][j].seq1;
739                     stdDev[i][j].seq2 = calcDistsTotals[0][i][j].seq2;
740                     stdDev[i][j].dist = 0.0;
741                 }
742             }
743             
744             for (int thisIter = 0; thisIter < iters; thisIter++) { //compute the difference of each dist from the mean, and square the result of each
745                 for (int i = 0; i < stdDev.size(); i++) {  
746                     for (int j = 0; j < stdDev[i].size(); j++) {
747                         stdDev[i][j].dist += ((calcDistsTotals[thisIter][i][j].dist - calcAverages[i][j].dist) * (calcDistsTotals[thisIter][i][j].dist - calcAverages[i][j].dist));
748                     }
749                 }
750             }
751
752             for (int i = 0; i < stdDev.size(); i++) {  //finds average.
753                 for (int j = 0; j < stdDev[i].size(); j++) {
754                     stdDev[i][j].dist /= (float) iters;
755                     stdDev[i][j].dist = sqrt(stdDev[i][j].dist);
756                 }
757             }
758             
759             //print results
760             for (int i = 0; i < calcDists.size(); i++) {
761                 vector< vector<double> > matrix; //square matrix to represent the distance
762                 matrix.resize(thisLookup.size());
763                 for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
764                 
765                 vector< vector<double> > stdmatrix; //square matrix to represent the stdDev
766                 stdmatrix.resize(thisLookup.size());
767                 for (int k = 0; k < thisLookup.size(); k++) {  stdmatrix[k].resize(thisLookup.size(), 0.0); }
768
769             
770                 for (int j = 0; j < calcAverages[i].size(); j++) {
771                     int row = calcAverages[i][j].seq1;
772                     int column = calcAverages[i][j].seq2;
773                     float dist = calcAverages[i][j].dist;
774                     float stdDist = stdDev[i][j].dist;
775                     
776                     matrix[row][column] = dist;
777                     matrix[column][row] = dist;
778                     stdmatrix[row][column] = stdDist;
779                     stdmatrix[column][row] = stdDist;
780                 }
781                 
782                 map<string, string> variables; 
783                 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(sharedfile));
784                 variables["[distance]"] = thisLookup[0]->getLabel();
785                 variables["[outputtag]"] = output;
786                 variables["[tag2]"] = "ave";
787                 variables["[calc]"] = matrixCalculators[i]->getName();
788                 string distFileName = getOutputFileName("phylip",variables);
789                 outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
790                 ofstream outAve;
791                 m->openOutputFile(distFileName, outAve);
792                 outAve.setf(ios::fixed, ios::floatfield); outAve.setf(ios::showpoint);
793                 
794                 printSims(outAve, matrix);
795                 
796                 outAve.close();
797                 
798                 variables["[tag2]"] = "std";
799                 distFileName = getOutputFileName("phylip",variables);
800                 outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName);
801                 ofstream outSTD;
802                 m->openOutputFile(distFileName, outSTD);
803                 outSTD.setf(ios::fixed, ios::floatfield); outSTD.setf(ios::showpoint);
804                 
805                 printSims(outSTD, stdmatrix);
806                 
807                 outSTD.close();
808
809             }
810         }
811                 
812                 return 0;
813         }
814         catch(exception& e) {
815                 m->errorOut(e, "MatrixOutputCommand", "process");
816                 exit(1);
817         }
818 }
819 /**************************************************************************************************/
820 int MatrixOutputCommand::driver(vector<SharedRAbundVector*> thisLookup, int start, int end, vector< vector<seqDist> >& calcDists) { 
821         try {
822                 vector<SharedRAbundVector*> subset;
823         
824                 for (int k = start; k < end; k++) { // pass cdd each set of groups to compare
825                         
826                         for (int l = 0; l < k; l++) {
827                                 
828                                 if (k != l) { //we dont need to similiarity of a groups to itself
829                                         subset.clear(); //clear out old pair of sharedrabunds
830                                         //add new pair of sharedrabunds
831                                         subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]); 
832                                         
833                                         for(int i=0;i<matrixCalculators.size();i++) {
834                                                 
835                                                 //if this calc needs all groups to calculate the pair load all groups
836                                                 if (matrixCalculators[i]->getNeedsAll()) { 
837                                                         //load subset with rest of lookup for those calcs that need everyone to calc for a pair
838                                                         for (int w = 0; w < thisLookup.size(); w++) {
839                                                                 if ((w != k) && (w != l)) { subset.push_back(thisLookup[w]); }
840                                                         }
841                                                 }
842                                                 
843                                                 vector<double> tempdata = matrixCalculators[i]->getValues(subset); //saves the calculator outputs
844                                                 
845                                                 if (m->control_pressed) { return 1; }
846                                                 
847                                                 seqDist temp(l, k, tempdata[0]);
848                                                 calcDists[i].push_back(temp);
849                                         }
850                                 }
851                         }
852                 }
853                 
854                 return 0;
855         }
856         catch(exception& e) {
857                 m->errorOut(e, "MatrixOutputCommand", "driver");
858                 exit(1);
859         }
860 }
861 /***********************************************************/
862
863
864