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