]> git.donarmstrong.com Git - mothur.git/blob - treegroupscommand.cpp
added tree reader class to handle reading trees. Reworked the tree map to tree class...
[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         numGroups = lookup.size();
574                 lines.resize(processors);
575                 for (int i = 0; i < processors; i++) {
576                         lines[i].start = int (sqrt(float(i)/float(processors)) * numGroups);
577                         lines[i].end = int (sqrt(float(i+1)/float(processors)) * numGroups);
578                 }       
579         
580         if (subsample) { 
581             if (subsampleSize == -1) { //user has not set size, set size = smallest samples size
582                 subsampleSize = lookup[0]->getNumSeqs();
583                 for (int i = 1; i < lookup.size(); i++) {
584                     int thisSize = lookup[i]->getNumSeqs();
585                     
586                     if (thisSize < subsampleSize) {     subsampleSize = thisSize;       }
587                 }
588             }else {
589                 m->clearGroups();
590                 Groups.clear();
591                 vector<SharedRAbundVector*> temp;
592                 for (int i = 0; i < lookup.size(); i++) {
593                     if (lookup[i]->getNumSeqs() < subsampleSize) { 
594                         m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
595                         delete lookup[i];
596                     }else { 
597                         Groups.push_back(lookup[i]->getGroup()); 
598                         temp.push_back(lookup[i]);
599                     }
600                 } 
601                 lookup = temp;
602                 m->setGroups(Groups);
603             }
604         }
605         
606                 set<string> processedLabels;
607                 set<string> userLabels = labels;
608                 
609                 //as long as you are not at the end of the file or done wih the lines you want
610                 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
611                         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; }
612                 
613                         if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){                  
614                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
615                                 process(lookup);
616                                 
617                                 processedLabels.insert(lookup[0]->getLabel());
618                                 userLabels.erase(lookup[0]->getLabel());
619                         }
620                         
621                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
622                                 string saveLabel = lookup[0]->getLabel();
623                         
624                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
625                                 lookup = input->getSharedRAbundVectors(lastLabel);
626
627                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
628                                 process(lookup);
629                                         
630                                 processedLabels.insert(lookup[0]->getLabel());
631                                 userLabels.erase(lookup[0]->getLabel());
632                                 
633                                 //restore real lastlabel to save below
634                                 lookup[0]->setLabel(saveLabel);
635                         }
636
637                         lastLabel = lookup[0]->getLabel();                      
638                         
639                         //get next line to process
640                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
641                         lookup = input->getSharedRAbundVectors();
642                 }
643                 
644                 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; }
645
646                 //output error messages about any remaining user labels
647                 set<string>::iterator it;
648                 bool needToRun = false;
649                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
650                         m->mothurOut("Your file does not include the label " + *it); 
651                         if (processedLabels.count(lastLabel) != 1) {
652                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
653                                 needToRun = true;
654                         }else {
655                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
656                         }
657                 }
658                 
659                 //run last label if you need to
660                 if (needToRun == true)  {
661                         for (int i = 0; i < lookup.size(); i++) {  if (lookup[i] != NULL) {             delete lookup[i]; }             } 
662                         lookup = input->getSharedRAbundVectors(lastLabel);
663
664                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
665                         process(lookup);
666                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }         
667                 }
668                 
669                 for(int i = 0 ; i < treeCalculators.size(); i++) {  delete treeCalculators[i]; }
670                 
671                 return 0;
672         }
673         catch(exception& e) {
674                 m->errorOut(e, "TreeGroupCommand", "makeSimsShared");
675                 exit(1);
676         }
677 }
678
679 /***********************************************************/
680 int TreeGroupCommand::process(vector<SharedRAbundVector*> thisLookup) {
681         try{
682                 vector< vector< vector<seqDist> > > calcDistsTotals;  //each iter, one for each calc, then each groupCombos dists. this will be used to make .dist files
683         vector< vector<seqDist>  > calcDists; calcDists.resize(treeCalculators.size());                 
684         
685         for (int thisIter = 0; thisIter < iters; thisIter++) {
686             
687             vector<SharedRAbundVector*> thisItersLookup = thisLookup;
688             
689             if (subsample) {
690                 SubSample sample;
691                 vector<string> tempLabels; //dont need since we arent printing the sampled sharedRabunds
692                 
693                 //make copy of lookup so we don't get access violations
694                 vector<SharedRAbundVector*> newLookup;
695                 for (int k = 0; k < thisItersLookup.size(); k++) {
696                     SharedRAbundVector* temp = new SharedRAbundVector();
697                     temp->setLabel(thisItersLookup[k]->getLabel());
698                     temp->setGroup(thisItersLookup[k]->getGroup());
699                     newLookup.push_back(temp);
700                 }
701                 
702                 //for each bin
703                 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
704                     if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
705                     for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
706                 }
707                 
708                 tempLabels = sample.getSample(newLookup, subsampleSize);
709                 thisItersLookup = newLookup;
710             }
711             
712             if(processors == 1){
713                 driver(thisItersLookup, 0, numGroups, calcDists);
714             }else{
715                 int process = 1;
716                 vector<int> processIDS;
717                 
718 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
719                 //loop through and create all the processes you want
720                 while (process != processors) {
721                     int pid = fork();
722                     
723                     if (pid > 0) {
724                         processIDS.push_back(pid); 
725                         process++;
726                     }else if (pid == 0){
727                         
728                         driver(thisItersLookup, lines[process].start, lines[process].end, calcDists);   
729                         
730                         string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(getpid()) + ".dist";
731                         ofstream outtemp;
732                         m->openOutputFile(tempdistFileName, outtemp);
733                         
734                         for (int i = 0; i < calcDists.size(); i++) {
735                             outtemp << calcDists[i].size() << endl;
736                             
737                             for (int j = 0; j < calcDists[i].size(); j++) {
738                                 outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl;
739                             }
740                         }
741                         outtemp.close();
742                         
743                         exit(0);
744                     }else { 
745                         m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
746                         for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
747                         exit(0);
748                     }
749                 }
750                 
751                 //parent do your part
752                 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);   
753                 
754                 //force parent to wait until all the processes are done
755                 for (int i = 0; i < processIDS.size(); i++) {
756                     int temp = processIDS[i];
757                     wait(&temp);
758                 }
759                 
760                 for (int i = 0; i < processIDS.size(); i++) {
761                     string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(processIDS[i]) +  ".dist";
762                     ifstream intemp;
763                     m->openInputFile(tempdistFileName, intemp);
764                     
765                     for (int k = 0; k < calcDists.size(); k++) {
766                         int size = 0;
767                         intemp >> size; m->gobble(intemp);
768                         
769                         for (int j = 0; j < size; j++) {
770                             int seq1 = 0;
771                             int seq2 = 0;
772                             float dist = 1.0;
773                             
774                             intemp >> seq1 >> seq2 >> dist;   m->gobble(intemp);
775                             
776                             seqDist tempDist(seq1, seq2, dist);
777                             calcDists[k].push_back(tempDist);
778                         }
779                     }
780                     intemp.close();
781                     m->mothurRemove(tempdistFileName);
782                 }
783 #else
784                 //////////////////////////////////////////////////////////////////////////////////////////////////////
785                 //Windows version shared memory, so be careful when passing variables through the treeSharedData struct. 
786                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
787                 //Taking advantage of shared memory to pass results vectors.
788                 //////////////////////////////////////////////////////////////////////////////////////////////////////
789                 
790                 vector<treeSharedData*> pDataArray; 
791                 DWORD   dwThreadIdArray[processors-1];
792                 HANDLE  hThreadArray[processors-1]; 
793                 
794                 //Create processor worker threads.
795                 for( int i=1; i<processors; i++ ){
796                     
797                     //make copy of lookup so we don't get access violations
798                     vector<SharedRAbundVector*> newLookup;
799                     for (int k = 0; k < thisItersLookup.size(); k++) {
800                         SharedRAbundVector* temp = new SharedRAbundVector();
801                         temp->setLabel(thisItersLookup[k]->getLabel());
802                         temp->setGroup(thisItersLookup[k]->getGroup());
803                         newLookup.push_back(temp);
804                     }
805                     
806                     //for each bin
807                     for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
808                         if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) {  delete newLookup[j];  } return 0; }
809                         for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
810                     }
811                     
812                     // Allocate memory for thread data.
813                     treeSharedData* tempSum = new treeSharedData(m, lines[i].start, lines[i].end, Estimators, newLookup);
814                     pDataArray.push_back(tempSum);
815                     processIDS.push_back(i);
816                     
817                     hThreadArray[i-1] = CreateThread(NULL, 0, MyTreeSharedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
818                 }
819                 
820                 //parent do your part
821                 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);   
822                 
823                 //Wait until all threads have terminated.
824                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
825                 
826                 //Close all thread handles and free memory allocations.
827                 for(int i=0; i < pDataArray.size(); i++){
828                     for (int j = 0; j < pDataArray[i]->thisLookup.size(); j++) {  delete pDataArray[i]->thisLookup[j];  } 
829                     
830                     for (int k = 0; k < calcDists.size(); k++) {
831                         int size = pDataArray[i]->calcDists[k].size();
832                         for (int j = 0; j < size; j++) {    calcDists[k].push_back(pDataArray[i]->calcDists[k][j]);    }
833                     }
834                     
835                     CloseHandle(hThreadArray[i]);
836                     delete pDataArray[i];
837                 }
838                 
839 #endif
840             }
841             
842             calcDistsTotals.push_back(calcDists);
843             
844             if (subsample) {  
845                 
846                 //clean up memory
847                 for (int i = 0; i < thisItersLookup.size(); i++) { delete thisItersLookup[i]; }
848                 thisItersLookup.clear();
849                 for (int i = 0; i < calcDists.size(); i++) {  calcDists[i].clear(); }
850             }
851                 }
852                 
853         if (iters != 1) {
854             //we need to find the average distance and standard deviation for each groups distance
855             
856             vector< vector<seqDist>  > calcAverages; calcAverages.resize(treeCalculators.size()); 
857             for (int i = 0; i < calcAverages.size(); i++) {  //initialize sums to zero.
858                 calcAverages[i].resize(calcDistsTotals[0][i].size());
859                 
860                 for (int j = 0; j < calcAverages[i].size(); j++) {
861                     calcAverages[i][j].seq1 = calcDists[i][j].seq1;
862                     calcAverages[i][j].seq2 = calcDists[i][j].seq2;
863                     calcAverages[i][j].dist = 0.0;
864                 }
865             }
866             
867             for (int thisIter = 0; thisIter < iters; thisIter++) { //sum all groups dists for each calculator
868                 for (int i = 0; i < calcAverages.size(); i++) {  //initialize sums to zero.
869                     for (int j = 0; j < calcAverages[i].size(); j++) {
870                         calcAverages[i][j].dist += calcDistsTotals[thisIter][i][j].dist;
871                     }
872                 }
873             }
874             
875             for (int i = 0; i < calcAverages.size(); i++) {  //finds average.
876                 for (int j = 0; j < calcAverages[i].size(); j++) {
877                     calcAverages[i][j].dist /= (float) iters;
878                 }
879             }
880             
881             //create average tree for each calc
882             for (int i = 0; i < calcDists.size(); i++) {
883                 vector< vector<double> > matrix; //square matrix to represent the distance
884                 matrix.resize(thisLookup.size());
885                 for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
886                 
887                 for (int j = 0; j < calcAverages[i].size(); j++) {
888                     int row = calcAverages[i][j].seq1;
889                     int column = calcAverages[i][j].seq2;
890                     float dist = calcAverages[i][j].dist;
891                     
892                     matrix[row][column] = dist;
893                     matrix[column][row] = dist;
894                 }
895                 
896                 //create a new filename
897                 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".ave.tre";                             
898                 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
899                 
900                 //creates tree from similarity matrix and write out file
901                 Tree* newTree = createTree(matrix);
902                 if (newTree != NULL) { writeTree(outputFile, newTree); }                
903             }
904             
905             //create all trees for each calc and find their consensus tree
906             for (int i = 0; i < calcDists.size(); i++) {
907                 if (m->control_pressed) { break; }
908                 
909                 //create a new filename
910                 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".all.tre";                             
911                 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
912                 
913                 ofstream outAll;
914                 m->openOutputFile(outputFile, outAll);
915                 
916                 vector<Tree*> trees; 
917                 for (int myIter = 0; myIter < iters; myIter++) {
918                     
919                     if(m->control_pressed) { break; }
920                     
921                     //initialize matrix
922                     vector< vector<double> > matrix; //square matrix to represent the distance
923                     matrix.resize(thisLookup.size());
924                     for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
925                     
926                     for (int j = 0; j < calcDistsTotals[myIter][i].size(); j++) {
927                         int row = calcDistsTotals[myIter][i][j].seq1;
928                         int column = calcDistsTotals[myIter][i][j].seq2;
929                         double dist = calcDistsTotals[myIter][i][j].dist;
930                         
931                         matrix[row][column] = dist;
932                         matrix[column][row] = dist;
933                     }
934                     
935                     //creates tree from similarity matrix and write out file
936                     Tree* newTree = createTree(matrix);
937                     if (newTree != NULL) { 
938                         newTree->print(outAll);
939                         trees.push_back(newTree);
940                     }
941                 }
942                 outAll.close();
943                 if (m->control_pressed) { for (int k = 0; k < trees.size(); k++) { delete trees[k]; } }
944                 
945                 Consensus consensus;
946                 //clear old tree names if any
947                 m->Treenames.clear(); m->Treenames = m->getGroups(); //may have changed if subsample eliminated groups
948                 Tree* conTree = consensus.getTree(trees);
949                 
950                 //create a new filename
951                 string conFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".cons.tre";                               
952                 outputNames.push_back(conFile); outputTypes["tree"].push_back(conFile); 
953                 ofstream outTree;
954                 m->openOutputFile(conFile, outTree);
955                 
956                 if (conTree != NULL) { conTree->print(outTree, "boot"); delete conTree; }
957             }
958
959         }else {
960             
961             for (int i = 0; i < calcDists.size(); i++) {
962                 if (m->control_pressed) { break; }
963                 
964                 //initialize matrix
965                 vector< vector<double> > matrix; //square matrix to represent the distance
966                 matrix.resize(thisLookup.size());
967                 for (int k = 0; k < thisLookup.size(); k++) {  matrix[k].resize(thisLookup.size(), 0.0); }
968                 
969                 for (int j = 0; j < calcDists[i].size(); j++) {
970                     int row = calcDists[i][j].seq1;
971                     int column = calcDists[i][j].seq2;
972                     double dist = calcDists[i][j].dist;
973                     
974                     matrix[row][column] = dist;
975                     matrix[column][row] = dist;
976                 }
977                 
978                 //create a new filename
979                 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".tre";                         
980                 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
981                 
982                 //creates tree from similarity matrix and write out file
983                 Tree* newTree = createTree(matrix);
984                 if (newTree != NULL) { writeTree(outputFile, newTree); delete newTree; }
985             }
986         }
987                 
988                 return 0;
989         }
990         catch(exception& e) {
991                 m->errorOut(e, "TreeGroupCommand", "process");
992                 exit(1);
993         }
994 }
995 /**************************************************************************************************/
996 int TreeGroupCommand::driver(vector<SharedRAbundVector*> thisLookup, int start, int end, vector< vector<seqDist> >& calcDists) { 
997         try {
998                 vector<SharedRAbundVector*> subset;
999                 for (int k = start; k < end; k++) { // pass cdd each set of groups to compare
1000                         
1001                         for (int l = 0; l < k; l++) {
1002                                 
1003                                 if (k != l) { //we dont need to similiarity of a groups to itself
1004                                         subset.clear(); //clear out old pair of sharedrabunds
1005                                         //add new pair of sharedrabunds
1006                                         subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]); 
1007                                         
1008                                         for(int i=0;i<treeCalculators.size();i++) {
1009                                                 
1010                                                 //if this calc needs all groups to calculate the pair load all groups
1011                                                 if (treeCalculators[i]->getNeedsAll()) { 
1012                                                         //load subset with rest of lookup for those calcs that need everyone to calc for a pair
1013                                                         for (int w = 0; w < thisLookup.size(); w++) {
1014                                                                 if ((w != k) && (w != l)) { subset.push_back(thisLookup[w]); }
1015                                                         }
1016                                                 }
1017                                                 
1018                                                 vector<double> tempdata = treeCalculators[i]->getValues(subset); //saves the calculator outputs
1019                                                 
1020                                                 if (m->control_pressed) { return 1; }
1021                                                 
1022                                                 seqDist temp(l, k, -(tempdata[0]-1.0));
1023                                                 calcDists[i].push_back(temp);
1024                                         }
1025                                 }
1026                         }
1027                 }
1028                 
1029                 return 0;
1030         }
1031         catch(exception& e) {
1032                 m->errorOut(e, "TreeGroupCommand", "driver");
1033                 exit(1);
1034         }
1035 }
1036 /***********************************************************/
1037
1038         
1039