]> git.donarmstrong.com Git - mothur.git/blob - treegroupscommand.cpp
Merge remote-tracking branch 'mothur/master'
[mothur.git] / treegroupscommand.cpp
1 /*
2  *  treegroupscommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 4/8/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "treegroupscommand.h"
11 #include "subsample.h"
12 #include "consensus.h"
13
14 //**********************************************************************************************************************
15 vector<string> TreeGroupCommand::setParameters(){       
16         try {
17                 CommandParameter pshared("shared", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "none",false,false); parameters.push_back(pshared);
18                 CommandParameter pphylip("phylip", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "none",false,false); parameters.push_back(pphylip);
19                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "ColumnName",false,false); parameters.push_back(pname);
20                 CommandParameter pcolumn("column", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "ColumnName",false,false); parameters.push_back(pcolumn);  
21         CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
22         CommandParameter psubsample("subsample", "String", "", "", "", "", "",false,false); parameters.push_back(psubsample);
23         CommandParameter pcutoff("cutoff", "Number", "", "10", "", "", "",false,false); parameters.push_back(pcutoff);
24                 CommandParameter pprecision("precision", "Number", "", "100", "", "", "",false,false); parameters.push_back(pprecision);                
25                 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
26                 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
27                 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);
28                 
29         CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
30 //CommandParameter poutput("output", "Multiple", "lt-square", "lt", "", "", "",false,false); parameters.push_back(poutput);
31                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
32                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
33                 
34                 vector<string> myArray;
35                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
36                 return myArray;
37         }
38         catch(exception& e) {
39                 m->errorOut(e, "TreeGroupCommand", "setParameters");
40                 exit(1);
41         }
42 }
43 //**********************************************************************************************************************
44 string TreeGroupCommand::getHelpString(){       
45         try {
46                 string helpString = "";
47                 ValidCalculators validCalculator;
48                 helpString += "The tree.shared command creates a .tre to represent the similiarity between groups or sequences.\n";
49                 helpString += "The tree.shared command parameters are shared, groups, calc, phylip, column, name, cutoff, precision, processors, subsample, iters and label.\n";
50                 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n";
51                 helpString += "The group names are separated by dashes. The label allow you to select what distance levels you would like trees created for, and are also separated by dashes.\n";
52                 helpString += "The phylip or column parameter are required if you do not provide a sharedfile, and only one may be used.  If you use a column file the name filename is required. \n";
53                 helpString += "If you do not provide a cutoff value 10.00 is assumed. If you do not provide a precision value then 100 is assumed.\n";
54                 helpString += "The tree.shared command should be in the following format: tree.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels).\n";
55         helpString += "The iters parameter allows you to choose the number of times you would like to run the subsample.\n";
56         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. The subsample parameter may only be used with a shared file.\n";
57                 helpString += "Example tree.shared(groups=A-B-C, calc=jabund-sorabund).\n";
58                 helpString += "The default value for groups is all the groups in your groupfile.\n";
59                 helpString += "The default value for calc is jclass-thetayc.\n";
60                 helpString += "The tree.shared command outputs a .tre file for each calculator you specify at each distance you choose.\n";
61                 helpString += validCalculator.printCalc("treegroup");
62                 helpString += "Or the tree.shared command can be in the following format: tree.shared(phylip=yourPhylipFile).\n";
63                 helpString += "Example tree.shared(phylip=abrecovery.dist).\n";
64                 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
65                 return helpString;
66         }
67         catch(exception& e) {
68                 m->errorOut(e, "TreeGroupCommand", "getHelpString");
69                 exit(1);
70         }
71 }
72 //**********************************************************************************************************************
73 TreeGroupCommand::TreeGroupCommand(){   
74         try {
75                 abort = true; calledHelp = true;
76                 setParameters();
77                 //initialize outputTypes
78                 vector<string> tempOutNames;
79                 outputTypes["tree"] = tempOutNames;
80         }
81         catch(exception& e) {
82                 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
83                 exit(1);
84         }
85 }
86 //**********************************************************************************************************************
87
88 TreeGroupCommand::TreeGroupCommand(string option)  {
89         try {
90                 abort = false; calledHelp = false;   
91                 allLines = 1;
92                 
93                 //allow user to run help
94                 if(option == "help") { help(); abort = true; calledHelp = true; }
95                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
96                 
97                 else {
98                         vector<string> myArray = setParameters();
99                         
100                         OptionParser parser(option);
101                         map<string, string> parameters = parser. getParameters();
102                         
103                         ValidParameters validParameter;
104                         map<string, string>::iterator it;
105                 
106                         //check to make sure all parameters are valid for command
107                         for (it = parameters.begin(); it != parameters.end(); it++) { 
108                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
109                         }
110                         
111                         //initialize outputTypes
112                         vector<string> tempOutNames;
113                         outputTypes["tree"] = tempOutNames;
114                         
115                         //if the user changes the input directory command factory will send this info to us in the output parameter 
116                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
117                         if (inputDir == "not found"){   inputDir = "";          }
118                         else {
119                                 string path;
120                                 it = parameters.find("phylip");
121                                 //user has given a template file
122                                 if(it != parameters.end()){ 
123                                         path = m->hasPath(it->second);
124                                         //if the user has not given a path then, add inputdir. else leave path alone.
125                                         if (path == "") {       parameters["phylip"] = inputDir + it->second;           }
126                                 }
127                                 
128                                 it = parameters.find("column");
129                                 //user has given a template file
130                                 if(it != parameters.end()){ 
131                                         path = m->hasPath(it->second);
132                                         //if the user has not given a path then, add inputdir. else leave path alone.
133                                         if (path == "") {       parameters["column"] = inputDir + it->second;           }
134                                 }
135                                 
136                                 it = parameters.find("name");
137                                 //user has given a template file
138                                 if(it != parameters.end()){ 
139                                         path = m->hasPath(it->second);
140                                         //if the user has not given a path then, add inputdir. else leave path alone.
141                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
142                                 }
143                         }
144                         
145                         //check for required parameters
146                         phylipfile = validParameter.validFile(parameters, "phylip", true);
147                         if (phylipfile == "not open") { phylipfile = ""; abort = true; }
148                         else if (phylipfile == "not found") { phylipfile = ""; }        
149                         else {  inputfile = phylipfile;  format = "phylip"; m->setPhylipFile(phylipfile);       }
150                         
151                         columnfile = validParameter.validFile(parameters, "column", true);
152                         if (columnfile == "not open") { columnfile = ""; abort = true; }        
153                         else if (columnfile == "not found") { columnfile = ""; }
154                         else {  inputfile = columnfile; format = "column";      m->setColumnFile(columnfile); }
155                         
156                         sharedfile = validParameter.validFile(parameters, "shared", true);
157                         if (sharedfile == "not open") { sharedfile = ""; abort = true; }        
158                         else if (sharedfile == "not found") { sharedfile = ""; }
159                         else {  inputfile = sharedfile; format = "sharedfile";  m->setSharedFile(sharedfile); }
160                         
161                         namefile = validParameter.validFile(parameters, "name", true);
162                         if (namefile == "not open") { abort = true; }   
163                         else if (namefile == "not found") { namefile = ""; }
164                         else { m->setNameFile(namefile); }
165                         
166                         if ((phylipfile == "") && (columnfile == "") && (sharedfile == "")) { 
167                                 //is there are current file available for either of these?
168                                 //give priority to shared, then column, then phylip
169                                 sharedfile = m->getSharedFile(); 
170                                 if (sharedfile != "") {  inputfile = sharedfile; format = "sharedfile"; m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
171                                 else { 
172                                         columnfile = m->getColumnFile(); 
173                                         if (columnfile != "") { inputfile = columnfile; format = "column";  m->mothurOut("Using " + columnfile + " as input file for the column parameter."); m->mothurOutEndLine(); }
174                                         else { 
175                                                 phylipfile = m->getPhylipFile(); 
176                                                 if (phylipfile != "") { inputfile = phylipfile;  format = "phylip";  m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
177                                                 else { 
178                                                         m->mothurOut("No valid current files. You must provide a shared, phylip or column file."); m->mothurOutEndLine(); 
179                                                         abort = true;
180                                                 }
181                                         }
182                                 }
183                         }
184                         else if ((phylipfile != "") && (columnfile != "")) { m->mothurOut("When running the tree.shared command with a distance file you may not use both the column and the phylip parameters."); m->mothurOutEndLine(); abort = true; }
185                         
186                         if (columnfile != "") {
187                                 if (namefile == "") { 
188                                         namefile = m->getNameFile(); 
189                                         if (namefile != "") {  m->mothurOut("Using " + namefile + " as input file for the name parameter."); m->mothurOutEndLine(); }
190                                         else { 
191                                                 m->mothurOut("You need to provide a namefile if you are going to use the column format."); m->mothurOutEndLine(); 
192                                                 abort = true; 
193                                         }       
194                                 }
195                         }
196                         
197                         //check for optional parameter and set defaults
198                         // ...at some point should added some additional type checking...
199                         label = validParameter.validFile(parameters, "label", false);                   
200                         if (label == "not found") { label = ""; }
201                         else { 
202                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
203                                 else { allLines = 1;  }
204                         }
205                         
206                         groups = validParameter.validFile(parameters, "groups", false);                 
207                         if (groups == "not found") { groups = ""; }
208                         else { 
209                                 m->splitAtDash(groups, Groups);
210                                 m->setGroups(Groups);
211                         }
212                                 
213                         calc = validParameter.validFile(parameters, "calc", false);                     
214                         if (calc == "not found") { calc = "jclass-thetayc";  }
215                         else { 
216                                  if (calc == "default")  {  calc = "jclass-thetayc";  }
217                         }
218                         m->splitAtDash(calc, Estimators);
219                         if (m->inUsersGroups("citation", Estimators)) { 
220                                 ValidCalculators validCalc; validCalc.printCitations(Estimators); 
221                                 //remove citation from list of calcs
222                                 for (int i = 0; i < Estimators.size(); i++) { if (Estimators[i] == "citation") {  Estimators.erase(Estimators.begin()+i); break; } }
223                         }
224
225                         string temp;
226                         temp = validParameter.validFile(parameters, "precision", false);                        if (temp == "not found") { temp = "100"; }
227                         m->mothurConvert(temp, precision); 
228                         
229                         temp = validParameter.validFile(parameters, "cutoff", false);                   if (temp == "not found") { temp = "10"; }
230                         m->mothurConvert(temp, cutoff); 
231                         cutoff += (5 / (precision * 10.0));
232                         
233             temp = validParameter.validFile(parameters, "processors", false);   if (temp == "not found"){       temp = m->getProcessors();      }
234                         m->setProcessors(temp);
235                         m->mothurConvert(temp, processors); 
236             
237             temp = validParameter.validFile(parameters, "iters", false);                        if (temp == "not found") { temp = "1000"; }
238                         m->mothurConvert(temp, iters); 
239             
240             temp = validParameter.validFile(parameters, "subsample", false);            if (temp == "not found") { temp = "F"; }
241                         if (m->isNumeric1(temp)) { m->mothurConvert(temp, subsampleSize); subsample = true; }
242             else {  
243                 if (m->isTrue(temp)) { subsample = true; subsampleSize = -1; }  //we will set it to smallest group later 
244                 else { subsample = false; }
245             }
246             
247             if (subsample == false) { iters = 1; }
248             
249             if (subsample && (format != "sharedfile")) { m->mothurOut("[ERROR]: the subsample parameter can only be used with a shared file.\n"); abort=true; }
250             
251                         //if the user changes the output directory command factory will send this info to us in the output parameter 
252                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
253                                 outputDir = ""; 
254                                 outputDir += m->hasPath(inputfile); //if user entered a file with a path then preserve it       
255                         }
256                 }
257
258         }
259         catch(exception& e) {
260                 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
261                 exit(1);
262         }
263 }
264 //**********************************************************************************************************************
265
266 TreeGroupCommand::~TreeGroupCommand(){
267         if (abort == false) {
268                 if (format == "sharedfile") {  delete input; }
269                 else { delete readMatrix;  delete matrix; delete list; }
270                 delete tmap;  
271         }
272         
273 }
274
275 //**********************************************************************************************************************
276
277 int TreeGroupCommand::execute(){
278         try {
279         
280                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
281                 
282                 if (format == "sharedfile") {
283                         
284                         ValidCalculators validCalculator;
285                 
286                         for (int i=0; i<Estimators.size(); i++) {
287                                 if (validCalculator.isValidCalculator("treegroup", Estimators[i]) == true) { 
288                                         if (Estimators[i] == "sharedsobs") { 
289                                                 treeCalculators.push_back(new SharedSobsCS());
290                                         }else if (Estimators[i] == "sharedchao") { 
291                                                 treeCalculators.push_back(new SharedChao1());
292                                         }else if (Estimators[i] == "sharedace") { 
293                                                 treeCalculators.push_back(new SharedAce());
294                                         }else if (Estimators[i] == "jabund") {  
295                                                 treeCalculators.push_back(new JAbund());
296                                         }else if (Estimators[i] == "sorabund") { 
297                                                 treeCalculators.push_back(new SorAbund());
298                                         }else if (Estimators[i] == "jclass") { 
299                                                 treeCalculators.push_back(new Jclass());
300                                         }else if (Estimators[i] == "sorclass") { 
301                                                 treeCalculators.push_back(new SorClass());
302                                         }else if (Estimators[i] == "jest") { 
303                                                 treeCalculators.push_back(new Jest());
304                                         }else if (Estimators[i] == "sorest") { 
305                                                 treeCalculators.push_back(new SorEst());
306                                         }else if (Estimators[i] == "thetayc") { 
307                                                 treeCalculators.push_back(new ThetaYC());
308                                         }else if (Estimators[i] == "thetan") { 
309                                                 treeCalculators.push_back(new ThetaN());
310                                         }else if (Estimators[i] == "kstest") { 
311                                                 treeCalculators.push_back(new KSTest());
312                                         }else if (Estimators[i] == "sharednseqs") { 
313                                                 treeCalculators.push_back(new SharedNSeqs());
314                                         }else if (Estimators[i] == "ochiai") { 
315                                                 treeCalculators.push_back(new Ochiai());
316                                         }else if (Estimators[i] == "anderberg") { 
317                                                 treeCalculators.push_back(new Anderberg());
318                                         }else if (Estimators[i] == "kulczynski") { 
319                                                 treeCalculators.push_back(new Kulczynski());
320                                         }else if (Estimators[i] == "kulczynskicody") { 
321                                                 treeCalculators.push_back(new KulczynskiCody());
322                                         }else if (Estimators[i] == "lennon") { 
323                                                 treeCalculators.push_back(new Lennon());
324                                         }else if (Estimators[i] == "morisitahorn") { 
325                                                 treeCalculators.push_back(new MorHorn());
326                                         }else if (Estimators[i] == "braycurtis") { 
327                                                 treeCalculators.push_back(new BrayCurtis());
328                                         }else if (Estimators[i] == "whittaker") { 
329                                                 treeCalculators.push_back(new Whittaker());
330                                         }else if (Estimators[i] == "odum") { 
331                                                 treeCalculators.push_back(new Odum());
332                                         }else if (Estimators[i] == "canberra") { 
333                                                 treeCalculators.push_back(new Canberra());
334                                         }else if (Estimators[i] == "structeuclidean") { 
335                                                 treeCalculators.push_back(new StructEuclidean());
336                                         }else if (Estimators[i] == "structchord") { 
337                                                 treeCalculators.push_back(new StructChord());
338                                         }else if (Estimators[i] == "hellinger") { 
339                                                 treeCalculators.push_back(new Hellinger());
340                                         }else if (Estimators[i] == "manhattan") { 
341                                                 treeCalculators.push_back(new Manhattan());
342                                         }else if (Estimators[i] == "structpearson") { 
343                                                 treeCalculators.push_back(new StructPearson());
344                                         }else if (Estimators[i] == "soergel") { 
345                                                 treeCalculators.push_back(new Soergel());
346                                         }else if (Estimators[i] == "spearman") { 
347                                                 treeCalculators.push_back(new Spearman());
348                                         }else if (Estimators[i] == "structkulczynski") { 
349                                                 treeCalculators.push_back(new StructKulczynski());
350                                         }else if (Estimators[i] == "speciesprofile") { 
351                                                 treeCalculators.push_back(new SpeciesProfile());
352                                         }else if (Estimators[i] == "hamming") { 
353                                                 treeCalculators.push_back(new Hamming());
354                                         }else if (Estimators[i] == "structchi2") { 
355                                                 treeCalculators.push_back(new StructChi2());
356                                         }else if (Estimators[i] == "gower") { 
357                                                 treeCalculators.push_back(new Gower());
358                                         }else if (Estimators[i] == "memchi2") { 
359                                                 treeCalculators.push_back(new MemChi2());
360                                         }else if (Estimators[i] == "memchord") { 
361                                                 treeCalculators.push_back(new MemChord());
362                                         }else if (Estimators[i] == "memeuclidean") { 
363                                                 treeCalculators.push_back(new MemEuclidean());
364                                         }else if (Estimators[i] == "mempearson") { 
365                                                 treeCalculators.push_back(new MemPearson());
366                                         }
367                                 }
368                         }
369                         
370                         //if the users entered no valid calculators don't execute command
371                         if (treeCalculators.size() == 0) { m->mothurOut("You have given no valid calculators."); m->mothurOutEndLine(); return 0; }
372                         
373                         input = new InputData(sharedfile, "sharedfile");
374                         lookup = input->getSharedRAbundVectors();
375                         lastLabel = lookup[0]->getLabel();
376                         
377                         if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups.  I cannot run the command."); m->mothurOutEndLine(); return 0; }
378                         
379                         //used in tree constructor 
380                         m->runParse = false;
381                         
382                         //create treemap class from groupmap for tree class to use
383                         tmap = new TreeMap();
384                         tmap->makeSim(m->getAllGroups());
385                         
386                         //clear globaldatas old tree names if any
387                         m->Treenames.clear();
388                         
389                         //fills globaldatas tree names
390                         m->Treenames = m->getGroups();
391                 
392                         if (m->control_pressed) { return 0; }
393                         
394                         //create tree file
395                         makeSimsShared();
396                         
397                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);  } return 0; }
398                 }else{
399                         //read in dist file
400                         filename = inputfile;
401                 
402                         if (format == "column") { readMatrix = new ReadColumnMatrix(filename); }        
403                         else if (format == "phylip") { readMatrix = new ReadPhylipMatrix(filename); }
404                                 
405                         readMatrix->setCutoff(cutoff);
406         
407                         if(namefile != ""){     
408                                 nameMap = new NameAssignment(namefile);
409                                 nameMap->readMap();
410                         }
411                         else{
412                                 nameMap = NULL;
413                         }
414         
415                         readMatrix->read(nameMap);
416                         list = readMatrix->getListVector();
417                         matrix = readMatrix->getMatrix();
418
419                         //make treemap
420                         tmap = new TreeMap();
421                         
422                         if (m->control_pressed) { return 0; }
423                         
424                         tmap->makeSim(list);
425                         
426                         vector<string> namesGroups = tmap->getNamesOfGroups();
427                         m->setGroups(namesGroups);
428                 
429                         //clear globaldatas old tree names if any
430                         m->Treenames.clear();
431                 
432                         //fills globaldatas tree names
433                         m->Treenames = m->getGroups();
434                         
435                         //used in tree constructor 
436                         m->runParse = false;
437                         
438                         if (m->control_pressed) { return 0; }
439                         
440                         vector< vector<double> > matrix = makeSimsDist();
441                         
442                         if (m->control_pressed) { return 0; }
443
444                         //create a new filename
445                         string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + "tre";    
446                         outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
447                                 
448                         Tree* newTree = createTree(matrix);
449             
450             if (newTree != NULL) {  writeTree(outputFile, newTree); delete newTree; }
451                         
452                         if (m->control_pressed) { return 0; }
453
454                         m->mothurOut("Tree complete. "); m->mothurOutEndLine();
455                         
456                 }
457                                 
458                 //reset groups parameter
459                 m->clearGroups(); 
460                 
461                 //set tree file as new current treefile
462                 string current = "";
463                 itTypes = outputTypes.find("tree");
464                 if (itTypes != outputTypes.end()) {
465                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTreeFile(current); }
466                 }
467                 
468                 m->mothurOutEndLine();
469                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
470                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
471                 m->mothurOutEndLine();
472
473                 return 0;
474         }
475         catch(exception& e) {
476                 m->errorOut(e, "TreeGroupCommand", "execute");
477                 exit(1);
478         }
479 }
480 //**********************************************************************************************************************
481
482 Tree* TreeGroupCommand::createTree(vector< vector<double> >& simMatrix){
483         try {
484                 //create tree
485                 t = new Tree(tmap, simMatrix);
486         
487         if (m->control_pressed) { delete t; t = NULL; return t; }
488                 
489         //assemble tree
490         map<string, string> empty;
491                 t->assembleTree(empty);
492
493                 return t;
494         }
495         catch(exception& e) {
496                 m->errorOut(e, "TreeGroupCommand", "createTree");
497                 exit(1);
498         }
499 }
500 /***********************************************************/
501 int TreeGroupCommand::writeTree(string out, Tree* T) {
502         try {
503                 
504         //print newick file
505                 t->createNewickFile(out);
506                 
507         if (m->control_pressed) { m->mothurRemove(out); outputNames.pop_back(); return 1; }
508         
509         return 0;
510         
511         }
512         catch(exception& e) {
513                 m->errorOut(e, "TreeGroupCommand", "printSims");
514                 exit(1);
515         }
516 }
517
518 /***********************************************************/
519 void TreeGroupCommand::printSims(ostream& out, vector< vector<double> >& simMatrix) {
520         try {
521                 
522         for (int m = 0; m < simMatrix.size(); m++)      {
523                         //out << lookup[m]->getGroup() << '\t';
524                         for (int n = 0; n < simMatrix.size(); n++)      {
525                                 out << simMatrix[m][n] << '\t'; 
526                         }
527                         out << endl;
528                 }
529
530         }
531         catch(exception& e) {
532                 m->errorOut(e, "TreeGroupCommand", "printSims");
533                 exit(1);
534         }
535 }
536 /***********************************************************/
537 vector< vector<double> > TreeGroupCommand::makeSimsDist() {
538         try {
539                 numGroups = list->size();
540                 
541                 //initialize simMatrix
542                 vector< vector<double> > simMatrix;
543                 simMatrix.resize(numGroups);
544                 for (int k = 0; k < simMatrix.size(); k++)      {
545                         for (int j = 0; j < simMatrix.size(); j++)      {
546                                 simMatrix[k].push_back(0.0);
547                         }
548                 }
549                 
550                 //go through sparse matrix and fill sims
551                 //go through each cell in the sparsematrix
552                 for(MatData currentCell = matrix->begin(); currentCell != matrix->end(); currentCell++){
553                         //similairity = -(distance-1)
554                         simMatrix[currentCell->row][currentCell->column] = -(currentCell->dist -1.0);   
555                         simMatrix[currentCell->column][currentCell->row] = -(currentCell->dist -1.0);   
556                         
557                         if (m->control_pressed) { return simMatrix; }
558                         
559                 }
560
561                 return simMatrix;
562         }
563         catch(exception& e) {
564                 m->errorOut(e, "TreeGroupCommand", "makeSimsDist");
565                 exit(1);
566         }
567 }
568
569 /***********************************************************/
570 int TreeGroupCommand::makeSimsShared() {
571         try {
572         
573         if (subsample) { 
574             if (subsampleSize == -1) { //user has not set size, set size = smallest samples size
575                 subsampleSize = lookup[0]->getNumSeqs();
576                 for (int i = 1; i < lookup.size(); i++) {
577                     int thisSize = lookup[i]->getNumSeqs();
578                     
579                     if (thisSize < subsampleSize) {     subsampleSize = thisSize;       }
580                 }
581             }else {
582                 m->clearGroups();
583                 Groups.clear();
584                 vector<SharedRAbundVector*> temp;
585                 for (int i = 0; i < lookup.size(); i++) {
586                     if (lookup[i]->getNumSeqs() < subsampleSize) { 
587                         m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
588                         delete lookup[i];
589                     }else { 
590                         Groups.push_back(lookup[i]->getGroup()); 
591                         temp.push_back(lookup[i]);
592                     }
593                 } 
594                 lookup = temp;
595                 m->setGroups(Groups);
596             }
597             
598             if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups.  I cannot run the command."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
599         }
600         
601         numGroups = lookup.size();
602                 lines.resize(processors);
603                 for (int i = 0; i < processors; i++) {
604                         lines[i].start = int (sqrt(float(i)/float(processors)) * numGroups);
605                         lines[i].end = int (sqrt(float(i+1)/float(processors)) * numGroups);
606                 }       
607         
608                 set<string> processedLabels;
609                 set<string> userLabels = labels;
610                 
611                 //as long as you are not at the end of the file or done wih the lines you want
612                 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
613                         if (m->control_pressed) { for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } for(int i = 0 ; i < treeCalculators.size(); i++) {  delete treeCalculators[i]; } return 1; }
614                 
615                         if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){                  
616                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
617                                 process(lookup);
618                                 
619                                 processedLabels.insert(lookup[0]->getLabel());
620                                 userLabels.erase(lookup[0]->getLabel());
621                         }
622                         
623                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
624                                 string saveLabel = lookup[0]->getLabel();
625                         
626                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
627                                 lookup = input->getSharedRAbundVectors(lastLabel);
628
629                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
630                                 process(lookup);
631                                         
632                                 processedLabels.insert(lookup[0]->getLabel());
633                                 userLabels.erase(lookup[0]->getLabel());
634                                 
635                                 //restore real lastlabel to save below
636                                 lookup[0]->setLabel(saveLabel);
637                         }
638
639                         lastLabel = lookup[0]->getLabel();                      
640                         
641                         //get next line to process
642                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
643                         lookup = input->getSharedRAbundVectors();
644                 }
645                 
646                 if (m->control_pressed) { for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } for(int i = 0 ; i < treeCalculators.size(); i++) {  delete treeCalculators[i]; } return 1; }
647
648                 //output error messages about any remaining user labels
649                 set<string>::iterator it;
650                 bool needToRun = false;
651                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
652                         m->mothurOut("Your file does not include the label " + *it); 
653                         if (processedLabels.count(lastLabel) != 1) {
654                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
655                                 needToRun = true;
656                         }else {
657                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
658                         }
659                 }
660                 
661                 //run last label if you need to
662                 if (needToRun == true)  {
663                         for (int i = 0; i < lookup.size(); i++) {  if (lookup[i] != NULL) {             delete lookup[i]; }             } 
664                         lookup = input->getSharedRAbundVectors(lastLabel);
665
666                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
667                         process(lookup);
668                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }         
669                 }
670                 
671                 for(int i = 0 ; i < treeCalculators.size(); i++) {  delete treeCalculators[i]; }
672                 
673                 return 0;
674         }
675         catch(exception& e) {
676                 m->errorOut(e, "TreeGroupCommand", "makeSimsShared");
677                 exit(1);
678         }
679 }
680
681 /***********************************************************/
682 int TreeGroupCommand::process(vector<SharedRAbundVector*> thisLookup) {
683         try{
684                 vector< vector< vector<seqDist> > > calcDistsTotals;  //each iter, one for each calc, then each groupCombos dists. this will be used to make .dist files
685         vector< vector<seqDist>  > calcDists; calcDists.resize(treeCalculators.size());                 
686         
687         for (int thisIter = 0; thisIter < iters; thisIter++) {
688             
689             vector<SharedRAbundVector*> thisItersLookup = thisLookup;
690             
691             if (subsample) {
692                 SubSample sample;
693                 vector<string> tempLabels; //dont need since we arent printing the sampled sharedRabunds
694                 
695                 //make copy of lookup so we don't get access violations
696                 vector<SharedRAbundVector*> newLookup;
697                 for (int k = 0; k < thisItersLookup.size(); k++) {
698                     SharedRAbundVector* temp = new SharedRAbundVector();
699                     temp->setLabel(thisItersLookup[k]->getLabel());
700                     temp->setGroup(thisItersLookup[k]->getGroup());
701                     newLookup.push_back(temp);
702                 }
703                 
704                 //for each bin
705                 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
706                     if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
707                     for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
708                 }
709                 
710                 tempLabels = sample.getSample(newLookup, subsampleSize);
711                 thisItersLookup = newLookup;
712             }
713             
714             if(processors == 1){
715                 driver(thisItersLookup, 0, numGroups, calcDists);
716             }else{
717                 int process = 1;
718                 vector<int> processIDS;
719                 
720 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
721                 //loop through and create all the processes you want
722                 while (process != processors) {
723                     int pid = fork();
724                     
725                     if (pid > 0) {
726                         processIDS.push_back(pid); 
727                         process++;
728                     }else if (pid == 0){
729                         
730                         driver(thisItersLookup, lines[process].start, lines[process].end, calcDists);   
731                         
732                         string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(getpid()) + ".dist";
733                         ofstream outtemp;
734                         m->openOutputFile(tempdistFileName, outtemp);
735                         
736                         for (int i = 0; i < calcDists.size(); i++) {
737                             outtemp << calcDists[i].size() << endl;
738                             
739                             for (int j = 0; j < calcDists[i].size(); j++) {
740                                 outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl;
741                             }
742                         }
743                         outtemp.close();
744                         
745                         exit(0);
746                     }else { 
747                         m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
748                         for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
749                         exit(0);
750                     }
751                 }
752                 
753                 //parent do your part
754                 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);   
755                 
756                 //force parent to wait until all the processes are done
757                 for (int i = 0; i < processIDS.size(); i++) {
758                     int temp = processIDS[i];
759                     wait(&temp);
760                 }
761                 
762                 for (int i = 0; i < processIDS.size(); i++) {
763                     string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(processIDS[i]) +  ".dist";
764                     ifstream intemp;
765                     m->openInputFile(tempdistFileName, intemp);
766                     
767                     for (int k = 0; k < calcDists.size(); k++) {
768                         int size = 0;
769                         intemp >> size; m->gobble(intemp);
770                         
771                         for (int j = 0; j < size; j++) {
772                             int seq1 = 0;
773                             int seq2 = 0;
774                             float dist = 1.0;
775                             
776                             intemp >> seq1 >> seq2 >> dist;   m->gobble(intemp);
777                             
778                             seqDist tempDist(seq1, seq2, dist);
779                             calcDists[k].push_back(tempDist);
780                         }
781                     }
782                     intemp.close();
783                     m->mothurRemove(tempdistFileName);
784                 }
785 #else
786                 //////////////////////////////////////////////////////////////////////////////////////////////////////
787                 //Windows version shared memory, so be careful when passing variables through the treeSharedData struct. 
788                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
789                 //Taking advantage of shared memory to pass results vectors.
790                 //////////////////////////////////////////////////////////////////////////////////////////////////////
791                 
792                 vector<treeSharedData*> pDataArray; 
793                 DWORD   dwThreadIdArray[processors-1];
794                 HANDLE  hThreadArray[processors-1]; 
795                 
796                 //Create processor worker threads.
797                 for( int i=1; i<processors; i++ ){
798                     
799                     //make copy of lookup so we don't get access violations
800                     vector<SharedRAbundVector*> newLookup;
801                     for (int k = 0; k < thisItersLookup.size(); k++) {
802                         SharedRAbundVector* temp = new SharedRAbundVector();
803                         temp->setLabel(thisItersLookup[k]->getLabel());
804                         temp->setGroup(thisItersLookup[k]->getGroup());
805                         newLookup.push_back(temp);
806                     }
807                     
808                     //for each bin
809                     for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
810                         if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
811                         for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
812                     }
813                     
814                     // Allocate memory for thread data.
815                     treeSharedData* tempSum = new treeSharedData(m, lines[i].start, lines[i].end, Estimators, newLookup);
816                     pDataArray.push_back(tempSum);
817                     processIDS.push_back(i);
818                     
819                     hThreadArray[i-1] = CreateThread(NULL, 0, MyTreeSharedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
820                 }
821                 
822                 //parent do your part
823                 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);   
824                 
825                 //Wait until all threads have terminated.
826                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
827                 
828                 //Close all thread handles and free memory allocations.
829                 for(int i=0; i < pDataArray.size(); i++){
830                     for (int j = 0; j < pDataArray[i]->thisLookup.size(); j++) {  delete pDataArray[i]->thisLookup[j];  } 
831                     
832                     for (int k = 0; k < calcDists.size(); k++) {
833                         int size = pDataArray[i]->calcDists[k].size();
834                         for (int j = 0; j < size; j++) {    calcDists[k].push_back(pDataArray[i]->calcDists[k][j]);    }
835                     }
836                     
837                     CloseHandle(hThreadArray[i]);
838                     delete pDataArray[i];
839                 }
840                 
841 #endif
842             }
843             
844             calcDistsTotals.push_back(calcDists);
845             
846             if (subsample) {  
847                 
848                 //clean up memory
849                 for (int i = 0; i < thisItersLookup.size(); i++) { delete thisItersLookup[i]; }
850                 thisItersLookup.clear();
851                 for (int i = 0; i < calcDists.size(); i++) {  calcDists[i].clear(); }
852             }
853                 }
854                 
855         if (iters != 1) {
856             //we need to find the average distance and standard deviation for each groups distance
857             
858             vector< vector<seqDist>  > calcAverages; calcAverages.resize(treeCalculators.size()); 
859             for (int i = 0; i < calcAverages.size(); i++) {  //initialize sums to zero.
860                 calcAverages[i].resize(calcDistsTotals[0][i].size());
861                 
862                 for (int j = 0; j < calcAverages[i].size(); j++) {
863                     calcAverages[i][j].seq1 = calcDists[i][j].seq1;
864                     calcAverages[i][j].seq2 = calcDists[i][j].seq2;
865                     calcAverages[i][j].dist = 0.0;
866                 }
867             }
868             
869             for (int thisIter = 0; thisIter < iters; thisIter++) { //sum all groups dists for each calculator
870                 for (int i = 0; i < calcAverages.size(); i++) {  //initialize sums to zero.
871                     for (int j = 0; j < calcAverages[i].size(); j++) {
872                         calcAverages[i][j].dist += calcDistsTotals[thisIter][i][j].dist;
873                     }
874                 }
875             }
876             
877             for (int i = 0; i < calcAverages.size(); i++) {  //finds average.
878                 for (int j = 0; j < calcAverages[i].size(); j++) {
879                     calcAverages[i][j].dist /= (float) iters;
880                 }
881             }
882             
883             //create average tree for each calc
884             for (int i = 0; i < calcDists.size(); i++) {
885                 vector< vector<double> > matrix; //square matrix to represent the distance
886                 matrix.resize(thisLookup.size());
887                 for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
888                 
889                 for (int j = 0; j < calcAverages[i].size(); j++) {
890                     int row = calcAverages[i][j].seq1;
891                     int column = calcAverages[i][j].seq2;
892                     float dist = calcAverages[i][j].dist;
893                     
894                     matrix[row][column] = dist;
895                     matrix[column][row] = dist;
896                 }
897                 
898                 //create a new filename
899                 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".ave.tre";                             
900                 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
901                 
902                 //creates tree from similarity matrix and write out file
903                 Tree* newTree = createTree(matrix);
904                 if (newTree != NULL) { writeTree(outputFile, newTree); }                
905             }
906             
907             //create all trees for each calc and find their consensus tree
908             for (int i = 0; i < calcDists.size(); i++) {
909                 if (m->control_pressed) { break; }
910                 
911                 //create a new filename
912                 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".all.tre";                             
913                 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
914                 
915                 ofstream outAll;
916                 m->openOutputFile(outputFile, outAll);
917                 
918                 vector<Tree*> trees; 
919                 for (int myIter = 0; myIter < iters; myIter++) {
920                     
921                     if(m->control_pressed) { break; }
922                     
923                     //initialize matrix
924                     vector< vector<double> > matrix; //square matrix to represent the distance
925                     matrix.resize(thisLookup.size());
926                     for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
927                     
928                     for (int j = 0; j < calcDistsTotals[myIter][i].size(); j++) {
929                         int row = calcDistsTotals[myIter][i][j].seq1;
930                         int column = calcDistsTotals[myIter][i][j].seq2;
931                         double dist = calcDistsTotals[myIter][i][j].dist;
932                         
933                         matrix[row][column] = dist;
934                         matrix[column][row] = dist;
935                     }
936                     
937                     //creates tree from similarity matrix and write out file
938                     Tree* newTree = createTree(matrix);
939                     if (newTree != NULL) { 
940                         newTree->print(outAll);
941                         trees.push_back(newTree);
942                     }
943                 }
944                 outAll.close();
945                 if (m->control_pressed) { for (int k = 0; k < trees.size(); k++) { delete trees[k]; } }
946                 
947                 Consensus consensus;
948                 //clear old tree names if any
949                 m->Treenames.clear(); m->Treenames = m->getGroups(); //may have changed if subsample eliminated groups
950                 Tree* conTree = consensus.getTree(trees);
951                 
952                 //create a new filename
953                 string conFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".cons.tre";                               
954                 outputNames.push_back(conFile); outputTypes["tree"].push_back(conFile); 
955                 ofstream outTree;
956                 m->openOutputFile(conFile, outTree);
957                 
958                 if (conTree != NULL) { conTree->print(outTree, "boot"); delete conTree; }
959             }
960
961         }else {
962             
963             for (int i = 0; i < calcDists.size(); i++) {
964                 if (m->control_pressed) { break; }
965                 
966                 //initialize matrix
967                 vector< vector<double> > matrix; //square matrix to represent the distance
968                 matrix.resize(thisLookup.size());
969                 for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
970                 
971                 for (int j = 0; j < calcDists[i].size(); j++) {
972                     int row = calcDists[i][j].seq1;
973                     int column = calcDists[i][j].seq2;
974                     double dist = calcDists[i][j].dist;
975                     
976                     matrix[row][column] = dist;
977                     matrix[column][row] = dist;
978                 }
979                 
980                 //create a new filename
981                 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".tre";                         
982                 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
983                 
984                 //creates tree from similarity matrix and write out file
985                 Tree* newTree = createTree(matrix);
986                 if (newTree != NULL) { writeTree(outputFile, newTree); delete newTree; }
987             }
988         }
989                 
990                 return 0;
991         }
992         catch(exception& e) {
993                 m->errorOut(e, "TreeGroupCommand", "process");
994                 exit(1);
995         }
996 }
997 /**************************************************************************************************/
998 int TreeGroupCommand::driver(vector<SharedRAbundVector*> thisLookup, int start, int end, vector< vector<seqDist> >& calcDists) { 
999         try {
1000                 vector<SharedRAbundVector*> subset;
1001                 for (int k = start; k < end; k++) { // pass cdd each set of groups to compare
1002                         
1003                         for (int l = 0; l < k; l++) {
1004                                 
1005                                 if (k != l) { //we dont need to similiarity of a groups to itself
1006                                         subset.clear(); //clear out old pair of sharedrabunds
1007                                         //add new pair of sharedrabunds
1008                                         subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]); 
1009                                         
1010                                         for(int i=0;i<treeCalculators.size();i++) {
1011                                                 
1012                                                 //if this calc needs all groups to calculate the pair load all groups
1013                                                 if (treeCalculators[i]->getNeedsAll()) { 
1014                                                         //load subset with rest of lookup for those calcs that need everyone to calc for a pair
1015                                                         for (int w = 0; w < thisLookup.size(); w++) {
1016                                                                 if ((w != k) && (w != l)) { subset.push_back(thisLookup[w]); }
1017                                                         }
1018                                                 }
1019                                                 
1020                                                 vector<double> tempdata = treeCalculators[i]->getValues(subset); //saves the calculator outputs
1021                                                 
1022                                                 if (m->control_pressed) { return 1; }
1023                                                 
1024                                                 seqDist temp(l, k, -(tempdata[0]-1.0));
1025                                                 calcDists[i].push_back(temp);
1026                                         }
1027                                 }
1028                         }
1029                 }
1030                 
1031                 return 0;
1032         }
1033         catch(exception& e) {
1034                 m->errorOut(e, "TreeGroupCommand", "driver");
1035                 exit(1);
1036         }
1037 }
1038 /***********************************************************/
1039
1040         
1041