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