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