]> git.donarmstrong.com Git - mothur.git/blob - treegroupscommand.cpp
removed read.dist, read.otu, read.tree and globaldata. added current to defaults...
[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 "sharedsobscollectsummary.h"
12 #include "sharedchao1.h"
13 #include "sharedace.h"
14 #include "sharednseqs.h"
15 #include "sharedjabund.h"
16 #include "sharedsorabund.h"
17 #include "sharedjclass.h"
18 #include "sharedsorclass.h"
19 #include "sharedjest.h"
20 #include "sharedsorest.h"
21 #include "sharedthetayc.h"
22 #include "sharedthetan.h"
23 #include "sharedkstest.h"
24 #include "whittaker.h"
25 #include "sharedochiai.h"
26 #include "sharedanderbergs.h"
27 #include "sharedkulczynski.h"
28 #include "sharedkulczynskicody.h"
29 #include "sharedlennon.h"
30 #include "sharedmorisitahorn.h"
31 #include "sharedbraycurtis.h"
32 #include "sharedjackknife.h"
33 #include "whittaker.h"
34 #include "odum.h"
35 #include "canberra.h"
36 #include "structeuclidean.h"
37 #include "structchord.h"
38 #include "hellinger.h"
39 #include "manhattan.h"
40 #include "structpearson.h"
41 #include "soergel.h"
42 #include "spearman.h"
43 #include "structkulczynski.h"
44 #include "structchi2.h"
45 #include "speciesprofile.h"
46 #include "hamming.h"
47 #include "gower.h"
48 #include "memchi2.h"
49 #include "memchord.h"
50 #include "memeuclidean.h"
51 #include "mempearson.h"
52
53 //**********************************************************************************************************************
54 vector<string> TreeGroupCommand::setParameters(){       
55         try {
56                 CommandParameter pshared("shared", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "none",false,false); parameters.push_back(pshared);
57                 CommandParameter pphylip("phylip", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "none",false,false); parameters.push_back(pphylip);
58                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "ColumnName",false,false); parameters.push_back(pname);
59                 CommandParameter pcolumn("column", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "ColumnName",false,false); parameters.push_back(pcolumn);          
60                 CommandParameter pcutoff("cutoff", "Number", "", "10", "", "", "",false,false); parameters.push_back(pcutoff);
61                 CommandParameter pprecision("precision", "Number", "", "100", "", "", "",false,false); parameters.push_back(pprecision);                
62                 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
63                 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
64                 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);
65                 CommandParameter poutput("output", "Multiple", "lt-square", "lt", "", "", "",false,false); parameters.push_back(poutput);
66                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
67                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
68                 
69                 vector<string> myArray;
70                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
71                 return myArray;
72         }
73         catch(exception& e) {
74                 m->errorOut(e, "TreeGroupCommand", "setParameters");
75                 exit(1);
76         }
77 }
78 //**********************************************************************************************************************
79 string TreeGroupCommand::getHelpString(){       
80         try {
81                 string helpString = "";
82                 ValidCalculators validCalculator;
83                 helpString += "The tree.shared command creates a .tre to represent the similiarity between groups or sequences.\n";
84                 helpString += "The tree.shared command parameters are shared, groups, calc, phylip, column, name, cutoff, precision and label.\n";
85                 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n";
86                 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";
87                 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";
88                 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";
89                 helpString += "The tree.shared command should be in the following format: tree.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels).\n";
90                 helpString += "Example tree.shared(groups=A-B-C, calc=jabund-sorabund).\n";
91                 helpString += "The default value for groups is all the groups in your groupfile.\n";
92                 helpString += "The default value for calc is jclass-thetayc.\n";
93                 helpString += "The tree.shared command outputs a .tre file for each calculator you specify at each distance you choose.\n";
94                 helpString += validCalculator.printCalc("treegroup");
95                 helpString += "Or the tree.shared command can be in the following format: tree.shared(phylip=yourPhylipFile).\n";
96                 helpString += "Example tree.shared(phylip=abrecovery.dist).\n";
97                 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n\n";
98                 return helpString;
99         }
100         catch(exception& e) {
101                 m->errorOut(e, "TreeGroupCommand", "getHelpString");
102                 exit(1);
103         }
104 }
105 //**********************************************************************************************************************
106 TreeGroupCommand::TreeGroupCommand(){   
107         try {
108                 abort = true; calledHelp = true;
109                 setParameters();
110                 //initialize outputTypes
111                 vector<string> tempOutNames;
112                 outputTypes["tree"] = tempOutNames;
113         }
114         catch(exception& e) {
115                 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
116                 exit(1);
117         }
118 }
119 //**********************************************************************************************************************
120
121 TreeGroupCommand::TreeGroupCommand(string option)  {
122         try {
123                 abort = false; calledHelp = false;   
124                 allLines = 1;
125                 
126                 //allow user to run help
127                 if(option == "help") { help(); abort = true; calledHelp = true; }
128                 
129                 else {
130                         vector<string> myArray = setParameters();
131                         
132                         OptionParser parser(option);
133                         map<string, string> parameters = parser. getParameters();
134                         
135                         ValidParameters validParameter;
136                         map<string, string>::iterator it;
137                 
138                         //check to make sure all parameters are valid for command
139                         for (it = parameters.begin(); it != parameters.end(); it++) { 
140                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
141                         }
142                         
143                         //initialize outputTypes
144                         vector<string> tempOutNames;
145                         outputTypes["tree"] = tempOutNames;
146                         
147                         //if the user changes the input directory command factory will send this info to us in the output parameter 
148                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
149                         if (inputDir == "not found"){   inputDir = "";          }
150                         else {
151                                 string path;
152                                 it = parameters.find("phylip");
153                                 //user has given a template file
154                                 if(it != parameters.end()){ 
155                                         path = m->hasPath(it->second);
156                                         //if the user has not given a path then, add inputdir. else leave path alone.
157                                         if (path == "") {       parameters["phylip"] = inputDir + it->second;           }
158                                 }
159                                 
160                                 it = parameters.find("column");
161                                 //user has given a template file
162                                 if(it != parameters.end()){ 
163                                         path = m->hasPath(it->second);
164                                         //if the user has not given a path then, add inputdir. else leave path alone.
165                                         if (path == "") {       parameters["column"] = inputDir + it->second;           }
166                                 }
167                                 
168                                 it = parameters.find("name");
169                                 //user has given a template file
170                                 if(it != parameters.end()){ 
171                                         path = m->hasPath(it->second);
172                                         //if the user has not given a path then, add inputdir. else leave path alone.
173                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
174                                 }
175                         }
176                         
177                         //check for required parameters
178                         phylipfile = validParameter.validFile(parameters, "phylip", true);
179                         if (phylipfile == "not open") { phylipfile = ""; abort = true; }
180                         else if (phylipfile == "not found") { phylipfile = ""; }        
181                         else {  inputfile = phylipfile;  format = "phylip";     }
182                         
183                         columnfile = validParameter.validFile(parameters, "column", true);
184                         if (columnfile == "not open") { columnfile = ""; abort = true; }        
185                         else if (columnfile == "not found") { columnfile = ""; }
186                         else {  inputfile = columnfile; format = "column";      }
187                         
188                         sharedfile = validParameter.validFile(parameters, "shared", true);
189                         if (sharedfile == "not open") { sharedfile = ""; abort = true; }        
190                         else if (sharedfile == "not found") { sharedfile = ""; }
191                         else {  inputfile = sharedfile; format = "sharedfile";  }
192                         
193                         namefile = validParameter.validFile(parameters, "name", true);
194                         if (namefile == "not open") { abort = true; }   
195                         else if (namefile == "not found") { namefile = ""; }
196                         
197                         if ((phylipfile == "") && (columnfile == "") && (sharedfile == "")) { 
198                                 //is there are current file available for either of these?
199                                 //give priority to shared, then column, then phylip
200                                 sharedfile = m->getSharedFile(); 
201                                 if (sharedfile != "") {  inputfile = sharedfile; format = "sharedfile"; m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
202                                 else { 
203                                         columnfile = m->getColumnFile(); 
204                                         if (columnfile != "") { inputfile = columnfile; format = "column";  m->mothurOut("Using " + columnfile + " as input file for the column parameter."); m->mothurOutEndLine(); }
205                                         else { 
206                                                 phylipfile = m->getPhylipFile(); 
207                                                 if (phylipfile != "") { inputfile = phylipfile;  format = "phylip";  m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
208                                                 else { 
209                                                         m->mothurOut("No valid current files. You must provide a shared, phylip or column file."); m->mothurOutEndLine(); 
210                                                         abort = true;
211                                                 }
212                                         }
213                                 }
214                         }
215                         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; }
216                         
217                         if (columnfile != "") {
218                                 if (namefile == "") { 
219                                         namefile = m->getNameFile(); 
220                                         if (namefile != "") {  m->mothurOut("Using " + namefile + " as input file for the name parameter."); m->mothurOutEndLine(); }
221                                         else { 
222                                                 m->mothurOut("You need to provide a namefile if you are going to use the column format."); m->mothurOutEndLine(); 
223                                                 abort = true; 
224                                         }       
225                                 }
226                         }
227                         
228                         //check for optional parameter and set defaults
229                         // ...at some point should added some additional type checking...
230                         label = validParameter.validFile(parameters, "label", false);                   
231                         if (label == "not found") { label = ""; }
232                         else { 
233                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
234                                 else { allLines = 1;  }
235                         }
236                         
237                         groups = validParameter.validFile(parameters, "groups", false);                 
238                         if (groups == "not found") { groups = ""; }
239                         else { 
240                                 m->splitAtDash(groups, Groups);
241                                 m->Groups = Groups;
242                         }
243                                 
244                         calc = validParameter.validFile(parameters, "calc", false);                     
245                         if (calc == "not found") { calc = "jclass-thetayc";  }
246                         else { 
247                                  if (calc == "default")  {  calc = "jclass-thetayc";  }
248                         }
249                         m->splitAtDash(calc, Estimators);
250
251                         string temp;
252                         temp = validParameter.validFile(parameters, "precision", false);                        if (temp == "not found") { temp = "100"; }
253                         convert(temp, precision); 
254                         
255                         temp = validParameter.validFile(parameters, "cutoff", false);                   if (temp == "not found") { temp = "10"; }
256                         convert(temp, cutoff); 
257                         cutoff += (5 / (precision * 10.0));
258                         
259                         //if the user changes the output directory command factory will send this info to us in the output parameter 
260                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
261                                 outputDir = ""; 
262                                 outputDir += m->hasPath(inputfile); //if user entered a file with a path then preserve it       
263                         }
264                 }
265
266         }
267         catch(exception& e) {
268                 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
269                 exit(1);
270         }
271 }
272 //**********************************************************************************************************************
273
274 TreeGroupCommand::~TreeGroupCommand(){
275         if (abort == false) {
276                 if (format == "sharedfile") {  delete input; }
277                 else { delete readMatrix;  delete matrix; delete list; }
278                 delete tmap;  
279         }
280         
281 }
282
283 //**********************************************************************************************************************
284
285 int TreeGroupCommand::execute(){
286         try {
287         
288                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
289                 
290                 if (format == "sharedfile") {
291                         
292                         ValidCalculators validCalculator;
293                 
294                         for (int i=0; i<Estimators.size(); i++) {
295                                 if (validCalculator.isValidCalculator("treegroup", Estimators[i]) == true) { 
296                                         if (Estimators[i] == "sharedsobs") { 
297                                                 treeCalculators.push_back(new SharedSobsCS());
298                                         }else if (Estimators[i] == "sharedchao") { 
299                                                 treeCalculators.push_back(new SharedChao1());
300                                         }else if (Estimators[i] == "sharedace") { 
301                                                 treeCalculators.push_back(new SharedAce());
302                                         }else if (Estimators[i] == "jabund") {  
303                                                 treeCalculators.push_back(new JAbund());
304                                         }else if (Estimators[i] == "sorabund") { 
305                                                 treeCalculators.push_back(new SorAbund());
306                                         }else if (Estimators[i] == "jclass") { 
307                                                 treeCalculators.push_back(new Jclass());
308                                         }else if (Estimators[i] == "sorclass") { 
309                                                 treeCalculators.push_back(new SorClass());
310                                         }else if (Estimators[i] == "jest") { 
311                                                 treeCalculators.push_back(new Jest());
312                                         }else if (Estimators[i] == "sorest") { 
313                                                 treeCalculators.push_back(new SorEst());
314                                         }else if (Estimators[i] == "thetayc") { 
315                                                 treeCalculators.push_back(new ThetaYC());
316                                         }else if (Estimators[i] == "thetan") { 
317                                                 treeCalculators.push_back(new ThetaN());
318                                         }else if (Estimators[i] == "kstest") { 
319                                                 treeCalculators.push_back(new KSTest());
320                                         }else if (Estimators[i] == "sharednseqs") { 
321                                                 treeCalculators.push_back(new SharedNSeqs());
322                                         }else if (Estimators[i] == "ochiai") { 
323                                                 treeCalculators.push_back(new Ochiai());
324                                         }else if (Estimators[i] == "anderberg") { 
325                                                 treeCalculators.push_back(new Anderberg());
326                                         }else if (Estimators[i] == "kulczynski") { 
327                                                 treeCalculators.push_back(new Kulczynski());
328                                         }else if (Estimators[i] == "kulczynskicody") { 
329                                                 treeCalculators.push_back(new KulczynskiCody());
330                                         }else if (Estimators[i] == "lennon") { 
331                                                 treeCalculators.push_back(new Lennon());
332                                         }else if (Estimators[i] == "morisitahorn") { 
333                                                 treeCalculators.push_back(new MorHorn());
334                                         }else if (Estimators[i] == "braycurtis") { 
335                                                 treeCalculators.push_back(new BrayCurtis());
336                                         }else if (Estimators[i] == "whittaker") { 
337                                                 treeCalculators.push_back(new Whittaker());
338                                         }else if (Estimators[i] == "odum") { 
339                                                 treeCalculators.push_back(new Odum());
340                                         }else if (Estimators[i] == "canberra") { 
341                                                 treeCalculators.push_back(new Canberra());
342                                         }else if (Estimators[i] == "structeuclidean") { 
343                                                 treeCalculators.push_back(new StructEuclidean());
344                                         }else if (Estimators[i] == "structchord") { 
345                                                 treeCalculators.push_back(new StructChord());
346                                         }else if (Estimators[i] == "hellinger") { 
347                                                 treeCalculators.push_back(new Hellinger());
348                                         }else if (Estimators[i] == "manhattan") { 
349                                                 treeCalculators.push_back(new Manhattan());
350                                         }else if (Estimators[i] == "structpearson") { 
351                                                 treeCalculators.push_back(new StructPearson());
352                                         }else if (Estimators[i] == "soergel") { 
353                                                 treeCalculators.push_back(new Soergel());
354                                         }else if (Estimators[i] == "spearman") { 
355                                                 treeCalculators.push_back(new Spearman());
356                                         }else if (Estimators[i] == "structkulczynski") { 
357                                                 treeCalculators.push_back(new StructKulczynski());
358                                         }else if (Estimators[i] == "speciesprofile") { 
359                                                 treeCalculators.push_back(new SpeciesProfile());
360                                         }else if (Estimators[i] == "hamming") { 
361                                                 treeCalculators.push_back(new Hamming());
362                                         }else if (Estimators[i] == "structchi2") { 
363                                                 treeCalculators.push_back(new StructChi2());
364                                         }else if (Estimators[i] == "gower") { 
365                                                 treeCalculators.push_back(new Gower());
366                                         }else if (Estimators[i] == "memchi2") { 
367                                                 treeCalculators.push_back(new MemChi2());
368                                         }else if (Estimators[i] == "memchord") { 
369                                                 treeCalculators.push_back(new MemChord());
370                                         }else if (Estimators[i] == "memeuclidean") { 
371                                                 treeCalculators.push_back(new MemEuclidean());
372                                         }else if (Estimators[i] == "mempearson") { 
373                                                 treeCalculators.push_back(new MemPearson());
374                                         }
375                                 }
376                         }
377                         
378                         //if the users entered no valid calculators don't execute command
379                         if (treeCalculators.size() == 0) { m->mothurOut("You have given no valid calculators."); m->mothurOutEndLine(); return 0; }
380                         
381                         input = new InputData(sharedfile, "sharedfile");
382                         lookup = input->getSharedRAbundVectors();
383                         lastLabel = lookup[0]->getLabel();
384                         
385                         if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups.  I cannot run the command."); m->mothurOutEndLine(); return 0; }
386                         
387                         //used in tree constructor 
388                         m->runParse = false;
389                         
390                         //create treemap class from groupmap for tree class to use
391                         tmap = new TreeMap();
392                         tmap->makeSim(m->namesOfGroups);
393                         
394                         //clear globaldatas old tree names if any
395                         m->Treenames.clear();
396                         
397                         //fills globaldatas tree names
398                         m->Treenames = m->Groups;
399                 
400                         if (m->control_pressed) { return 0; }
401                         
402                         //create tree file
403                         makeSimsShared();
404                         
405                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0; }
406                 }else{
407                         //read in dist file
408                         filename = inputfile;
409                 
410                         if (format == "column") { readMatrix = new ReadColumnMatrix(filename); }        
411                         else if (format == "phylip") { readMatrix = new ReadPhylipMatrix(filename); }
412                                 
413                         readMatrix->setCutoff(cutoff);
414         
415                         if(namefile != ""){     
416                                 nameMap = new NameAssignment(namefile);
417                                 nameMap->readMap();
418                         }
419                         else{
420                                 nameMap = NULL;
421                         }
422         
423                         readMatrix->read(nameMap);
424                         list = readMatrix->getListVector();
425                         matrix = readMatrix->getMatrix();
426
427                         //make treemap
428                         tmap = new TreeMap();
429                         
430                         if (m->control_pressed) { return 0; }
431                         
432                         tmap->makeSim(list);
433                         
434                         m->Groups = tmap->namesOfGroups;
435                 
436                         //clear globaldatas old tree names if any
437                         m->Treenames.clear();
438                 
439                         //fills globaldatas tree names
440                         m->Treenames = m->Groups;
441                         
442                         //used in tree constructor 
443                         m->runParse = false;
444                         
445                         if (m->control_pressed) { return 0; }
446                         
447                         makeSimsDist();
448                         
449                         if (m->control_pressed) { return 0; }
450
451                         //create a new filename
452                         outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + "tre";   
453                         outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
454                                 
455                         createTree();
456                         
457                         if (m->control_pressed) { return 0; }
458
459                         m->mothurOut("Tree complete. "); m->mothurOutEndLine();
460                         
461                 }
462                                 
463                 //reset groups parameter
464                 m->Groups.clear(); 
465                 
466                 //set tree file as new current treefile
467                 string current = "";
468                 itTypes = outputTypes.find("tree");
469                 if (itTypes != outputTypes.end()) {
470                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTreeFile(current); }
471                 }
472                 
473                 m->mothurOutEndLine();
474                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
475                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
476                 m->mothurOutEndLine();
477
478                 return 0;
479         }
480         catch(exception& e) {
481                 m->errorOut(e, "TreeGroupCommand", "execute");
482                 exit(1);
483         }
484 }
485 //**********************************************************************************************************************
486
487 int TreeGroupCommand::createTree(){
488         try {
489                 //create tree
490                 t = new Tree(tmap);
491                 
492                 //do merges and create tree structure by setting parents and children
493                 //there are numGroups - 1 merges to do
494                 for (int i = 0; i < (numGroups - 1); i++) {
495                         float largest = -1000.0;
496                         
497                         if (m->control_pressed) { delete t; return 1; }
498                         
499                         int row, column;
500                         //find largest value in sims matrix by searching lower triangle
501                         for (int j = 1; j < simMatrix.size(); j++) {
502                                 for (int k = 0; k < j; k++) {
503                                         if (simMatrix[j][k] > largest) {  largest = simMatrix[j][k]; row = j; column = k;  }
504                                 }
505                         }
506
507                         //set non-leaf node info and update leaves to know their parents
508                         //non-leaf
509                         t->tree[numGroups + i].setChildren(index[row], index[column]);
510                         
511                         //parents
512                         t->tree[index[row]].setParent(numGroups + i);
513                         t->tree[index[column]].setParent(numGroups + i);
514                         
515                         //blength = distance / 2;
516                         float blength = ((1.0 - largest) / 2);
517                         
518                         //branchlengths
519                         t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
520                         t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
521                         
522                         //set your length to leaves to your childs length plus branchlength
523                         t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
524                         
525                         
526                         //update index 
527                         index[row] = numGroups+i;
528                         index[column] = numGroups+i;
529                         
530                         //remove highest value that caused the merge.
531                         simMatrix[row][column] = -1000.0;
532                         simMatrix[column][row] = -1000.0;
533                         
534                         //merge values in simsMatrix
535                         for (int n = 0; n < simMatrix.size(); n++)      {
536                                 //row becomes merge of 2 groups
537                                 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
538                                 simMatrix[n][row] = simMatrix[row][n];
539                                 //delete column
540                                 simMatrix[column][n] = -1000.0;
541                                 simMatrix[n][column] = -1000.0;
542                         }
543                 }
544                 
545                 //adjust tree to make sure root to tip length is .5
546                 int root = t->findRoot();
547                 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
548                 
549                 //assemble tree
550                 t->assembleTree();
551                 
552                 if (m->control_pressed) { delete t; return 1; }
553                 
554                 //print newick file
555                 t->createNewickFile(outputFile);
556                 
557                 //delete tree
558                 delete t;
559                 
560                 if (m->control_pressed) { remove(outputFile.c_str()); outputNames.pop_back(); return 1; }
561                 
562                 return 0;
563         
564         }
565         catch(exception& e) {
566                 m->errorOut(e, "TreeGroupCommand", "createTree");
567                 exit(1);
568         }
569 }
570 /***********************************************************/
571 void TreeGroupCommand::printSims(ostream& out) {
572         try {
573                 
574                 //output column headers
575                 //out << '\t';
576                 //for (int i = 0; i < lookup.size(); i++) {     out << lookup[i]->getGroup() << '\t';           }
577                 //out << endl;
578                 
579                 
580                 for (int m = 0; m < simMatrix.size(); m++)      {
581                         //out << lookup[m]->getGroup() << '\t';
582                         for (int n = 0; n < simMatrix.size(); n++)      {
583                                 out << simMatrix[m][n] << '\t'; 
584                         }
585                         out << endl;
586                 }
587
588         }
589         catch(exception& e) {
590                 m->errorOut(e, "TreeGroupCommand", "printSims");
591                 exit(1);
592         }
593 }
594 /***********************************************************/
595 int TreeGroupCommand::makeSimsDist() {
596         try {
597                 numGroups = list->size();
598                 
599                 //initialize index
600                 index.clear();
601                 for (int g = 0; g < numGroups; g++) {   index[g] = g;   }
602                 
603                 //initialize simMatrix
604                 simMatrix.clear();
605                 simMatrix.resize(numGroups);
606                 for (int k = 0; k < simMatrix.size(); k++)      {
607                         for (int j = 0; j < simMatrix.size(); j++)      {
608                                 simMatrix[k].push_back(0.0);
609                         }
610                 }
611                 
612                 //go through sparse matrix and fill sims
613                 //go through each cell in the sparsematrix
614                 for(MatData currentCell = matrix->begin(); currentCell != matrix->end(); currentCell++){
615                         //similairity = -(distance-1)
616                         simMatrix[currentCell->row][currentCell->column] = -(currentCell->dist -1.0);   
617                         simMatrix[currentCell->column][currentCell->row] = -(currentCell->dist -1.0);   
618                         
619                         if (m->control_pressed) { return 1; }
620                         
621                 }
622
623                 return 0;
624         }
625         catch(exception& e) {
626                 m->errorOut(e, "TreeGroupCommand", "makeSimsDist");
627                 exit(1);
628         }
629 }
630
631 /***********************************************************/
632 int TreeGroupCommand::makeSimsShared() {
633         try {
634                 set<string> processedLabels;
635                 set<string> userLabels = labels;
636                 
637                 //as long as you are not at the end of the file or done wih the lines you want
638                 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
639                         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; }
640                 
641                         if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){                  
642                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
643                                 process(lookup);
644                                 
645                                 processedLabels.insert(lookup[0]->getLabel());
646                                 userLabels.erase(lookup[0]->getLabel());
647                         }
648                         
649                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
650                                 string saveLabel = lookup[0]->getLabel();
651                         
652                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
653                                 lookup = input->getSharedRAbundVectors(lastLabel);
654
655                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
656                                 process(lookup);
657                                         
658                                 processedLabels.insert(lookup[0]->getLabel());
659                                 userLabels.erase(lookup[0]->getLabel());
660                                 
661                                 //restore real lastlabel to save below
662                                 lookup[0]->setLabel(saveLabel);
663                         }
664
665                         lastLabel = lookup[0]->getLabel();                      
666                         
667                         //get next line to process
668                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
669                         lookup = input->getSharedRAbundVectors();
670                 }
671                 
672                 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; }
673
674                 //output error messages about any remaining user labels
675                 set<string>::iterator it;
676                 bool needToRun = false;
677                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
678                         m->mothurOut("Your file does not include the label " + *it); 
679                         if (processedLabels.count(lastLabel) != 1) {
680                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
681                                 needToRun = true;
682                         }else {
683                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
684                         }
685                 }
686                 
687                 //run last label if you need to
688                 if (needToRun == true)  {
689                         for (int i = 0; i < lookup.size(); i++) {  if (lookup[i] != NULL) {             delete lookup[i]; }             } 
690                         lookup = input->getSharedRAbundVectors(lastLabel);
691
692                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
693                         process(lookup);
694                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }         
695                 }
696                 
697                 for(int i = 0 ; i < treeCalculators.size(); i++) {  delete treeCalculators[i]; }
698                 
699                 return 0;
700         }
701         catch(exception& e) {
702                 m->errorOut(e, "TreeGroupCommand", "makeSimsShared");
703                 exit(1);
704         }
705 }
706
707 /***********************************************************/
708 int TreeGroupCommand::process(vector<SharedRAbundVector*> thisLookup) {
709         try{
710                                 EstOutput data;
711                                 vector<SharedRAbundVector*> subset;
712                                 numGroups = thisLookup.size();
713                                 
714                                 //for each calculator                                                                                           
715                                 for(int i = 0 ; i < treeCalculators.size(); i++) {
716                                         //initialize simMatrix
717                                         simMatrix.clear();
718                                         simMatrix.resize(numGroups);
719                                         for (int k = 0; k < simMatrix.size(); k++)      {
720                                                 for (int j = 0; j < simMatrix.size(); j++)      {
721                                                         simMatrix[k].push_back(0.0);
722                                                 }
723                                         }
724                 
725                                         //initialize index
726                                         index.clear();
727                                         for (int g = 0; g < numGroups; g++) {   index[g] = g;   }
728                 
729                                         //create a new filename
730                                         outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".tre";                                
731                                         outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
732                                                                                                 
733                                         for (int k = 0; k < thisLookup.size(); k++) { 
734                                                 for (int l = k; l < thisLookup.size(); l++) {
735                                                         if (k != l) { //we dont need to similiarity of a groups to itself
736                                                                 //get estimated similarity between 2 groups
737                                                                 
738                                                                 subset.clear(); //clear out old pair of sharedrabunds
739                                                                 //add new pair of sharedrabunds
740                                                                 subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]); 
741                                                                 
742                                                                 //if this calc needs all groups to calculate the pair load all groups
743                                                                 if (treeCalculators[i]->getNeedsAll()) { 
744                                                                         //load subset with rest of lookup for those calcs that need everyone to calc for a pair
745                                                                         for (int w = 0; w < thisLookup.size(); w++) {
746                                                                                 if ((w != k) && (w != l)) { subset.push_back(thisLookup[w]); }
747                                                                         }
748                                                                 }
749                                                                 
750                                                                 data = treeCalculators[i]->getValues(subset); //saves the calculator outputs
751                                                 //cout << thisLookup[k]->getGroup() << '\t' << thisLookup[l]->getGroup() << '\t' << (1.0 - data[0]) << endl;
752                                                                 if (m->control_pressed) { return 1; }
753                                                                 
754                                                                 //save values in similarity matrix
755                                                                 simMatrix[k][l] = data[0];
756                                                                 simMatrix[l][k] = data[0];
757                                                         }
758                                                 }
759                                         }
760                                         
761                                         //createdistance file from simMatrix
762                                         /*string o = outputDir + m->getRootName(m->getSimpleName(globaldata->inputFileName)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".dist";
763                                         ofstream outDist;
764                                         m->openOutputFile(o, outDist);
765                                         outDist << simMatrix.size() << endl;
766                                         for (int k = 0; k < simMatrix.size(); k++) {
767                                                 outDist << thisLookup[k]->getGroup() << '\t';
768                                                 for (int l = 0; l < k; l++) {
769                                                         outDist << (1.0-simMatrix[k][l]) << '\t';
770                                                 }
771                                                 outDist << endl;
772                                         }
773                                         outDist.close();*/
774
775                                         
776                                         if (m->control_pressed) { return 1; }
777                                         //creates tree from similarity matrix and write out file
778                                         createTree();
779                                         
780                                         if (m->control_pressed) { return 1; }
781                                 }
782                                 
783                                 return 0;
784
785         }
786         catch(exception& e) {
787                 m->errorOut(e, "TreeGroupCommand", "process");
788                 exit(1);
789         }
790 }
791 /***********************************************************/
792
793         
794