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