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