2 * treegroupscommand.cpp
5 * Created by Sarah Westcott on 4/8/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
10 #include "treegroupscommand.h"
11 #include "subsample.h"
12 #include "consensus.h"
14 //**********************************************************************************************************************
15 vector<string> TreeGroupCommand::setParameters(){
17 CommandParameter pshared("shared", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "none",false,false); parameters.push_back(pshared);
18 CommandParameter pphylip("phylip", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "none",false,false); parameters.push_back(pphylip);
19 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "ColumnName",false,false); parameters.push_back(pname);
20 CommandParameter pcolumn("column", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "ColumnName",false,false); parameters.push_back(pcolumn);
21 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
22 CommandParameter psubsample("subsample", "String", "", "", "", "", "",false,false); parameters.push_back(psubsample);
23 CommandParameter pcutoff("cutoff", "Number", "", "10", "", "", "",false,false); parameters.push_back(pcutoff);
24 CommandParameter pprecision("precision", "Number", "", "100", "", "", "",false,false); parameters.push_back(pprecision);
25 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
26 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
27 CommandParameter pcalc("calc", "Multiple", "sharedsobs-sharedchao-sharedace-jabund-sorabund-jclass-sorclass-jest-sorest-thetayc-thetan-kstest-sharednseqs-ochiai-anderberg-kulczynski-kulczynskicody-lennon-morisitahorn-braycurtis-whittaker-odum-canberra-structeuclidean-structchord-hellinger-manhattan-structpearson-soergel-spearman-structkulczynski-speciesprofile-hamming-structchi2-gower-memchi2-memchord-memeuclidean-mempearson", "jclass-thetayc", "", "", "",true,false); parameters.push_back(pcalc);
29 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
30 CommandParameter poutput("output", "Multiple", "lt-square", "lt", "", "", "",false,false); parameters.push_back(poutput);
31 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
32 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
34 vector<string> myArray;
35 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
39 m->errorOut(e, "TreeGroupCommand", "setParameters");
43 //**********************************************************************************************************************
44 string TreeGroupCommand::getHelpString(){
46 string helpString = "";
47 ValidCalculators validCalculator;
48 helpString += "The tree.shared command creates a .tre to represent the similiarity between groups or sequences.\n";
49 helpString += "The tree.shared command parameters are shared, groups, calc, phylip, column, name, cutoff, precision, processors, subsample, iters and label.\n";
50 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included used.\n";
51 helpString += "The group names are separated by dashes. The label allow you to select what distance levels you would like trees created for, and are also separated by dashes.\n";
52 helpString += "The phylip or column parameter are required if you do not provide a sharedfile, and only one may be used. If you use a column file the name filename is required. \n";
53 helpString += "If you do not provide a cutoff value 10.00 is assumed. If you do not provide a precision value then 100 is assumed.\n";
54 helpString += "The tree.shared command should be in the following format: tree.shared(groups=yourGroups, calc=yourCalcs, label=yourLabels).\n";
55 helpString += "The iters parameter allows you to choose the number of times you would like to run the subsample.\n";
56 helpString += "The subsample parameter allows you to enter the size pergroup of the sample or you can set subsample=T and mothur will use the size of your smallest group. The subsample parameter may only be used with a shared file.\n";
57 helpString += "Example tree.shared(groups=A-B-C, calc=jabund-sorabund).\n";
58 helpString += "The default value for groups is all the groups in your groupfile.\n";
59 helpString += "The default value for calc is jclass-thetayc.\n";
60 helpString += "The tree.shared command outputs a .tre file for each calculator you specify at each distance you choose.\n";
61 helpString += validCalculator.printCalc("treegroup");
62 helpString += "Or the tree.shared command can be in the following format: tree.shared(phylip=yourPhylipFile).\n";
63 helpString += "Example tree.shared(phylip=abrecovery.dist).\n";
64 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
68 m->errorOut(e, "TreeGroupCommand", "getHelpString");
72 //**********************************************************************************************************************
73 TreeGroupCommand::TreeGroupCommand(){
75 abort = true; calledHelp = true;
77 //initialize outputTypes
78 vector<string> tempOutNames;
79 outputTypes["tree"] = tempOutNames;
82 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
86 //**********************************************************************************************************************
88 TreeGroupCommand::TreeGroupCommand(string option) {
90 abort = false; calledHelp = false;
93 //allow user to run help
94 if(option == "help") { help(); abort = true; calledHelp = true; }
95 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
98 vector<string> myArray = setParameters();
100 OptionParser parser(option);
101 map<string, string> parameters = parser. getParameters();
103 ValidParameters validParameter;
104 map<string, string>::iterator it;
106 //check to make sure all parameters are valid for command
107 for (it = parameters.begin(); it != parameters.end(); it++) {
108 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
111 //initialize outputTypes
112 vector<string> tempOutNames;
113 outputTypes["tree"] = tempOutNames;
115 //if the user changes the input directory command factory will send this info to us in the output parameter
116 string inputDir = validParameter.validFile(parameters, "inputdir", false);
117 if (inputDir == "not found"){ inputDir = ""; }
120 it = parameters.find("phylip");
121 //user has given a template file
122 if(it != parameters.end()){
123 path = m->hasPath(it->second);
124 //if the user has not given a path then, add inputdir. else leave path alone.
125 if (path == "") { parameters["phylip"] = inputDir + it->second; }
128 it = parameters.find("column");
129 //user has given a template file
130 if(it != parameters.end()){
131 path = m->hasPath(it->second);
132 //if the user has not given a path then, add inputdir. else leave path alone.
133 if (path == "") { parameters["column"] = inputDir + it->second; }
136 it = parameters.find("name");
137 //user has given a template file
138 if(it != parameters.end()){
139 path = m->hasPath(it->second);
140 //if the user has not given a path then, add inputdir. else leave path alone.
141 if (path == "") { parameters["name"] = inputDir + it->second; }
145 //check for required parameters
146 phylipfile = validParameter.validFile(parameters, "phylip", true);
147 if (phylipfile == "not open") { phylipfile = ""; abort = true; }
148 else if (phylipfile == "not found") { phylipfile = ""; }
149 else { inputfile = phylipfile; format = "phylip"; m->setPhylipFile(phylipfile); }
151 columnfile = validParameter.validFile(parameters, "column", true);
152 if (columnfile == "not open") { columnfile = ""; abort = true; }
153 else if (columnfile == "not found") { columnfile = ""; }
154 else { inputfile = columnfile; format = "column"; m->setColumnFile(columnfile); }
156 sharedfile = validParameter.validFile(parameters, "shared", true);
157 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
158 else if (sharedfile == "not found") { sharedfile = ""; }
159 else { inputfile = sharedfile; format = "sharedfile"; m->setSharedFile(sharedfile); }
161 namefile = validParameter.validFile(parameters, "name", true);
162 if (namefile == "not open") { abort = true; }
163 else if (namefile == "not found") { namefile = ""; }
164 else { m->setNameFile(namefile); }
166 if ((phylipfile == "") && (columnfile == "") && (sharedfile == "")) {
167 //is there are current file available for either of these?
168 //give priority to shared, then column, then phylip
169 sharedfile = m->getSharedFile();
170 if (sharedfile != "") { inputfile = sharedfile; format = "sharedfile"; m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
172 columnfile = m->getColumnFile();
173 if (columnfile != "") { inputfile = columnfile; format = "column"; m->mothurOut("Using " + columnfile + " as input file for the column parameter."); m->mothurOutEndLine(); }
175 phylipfile = m->getPhylipFile();
176 if (phylipfile != "") { inputfile = phylipfile; format = "phylip"; m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
178 m->mothurOut("No valid current files. You must provide a shared, phylip or column file."); m->mothurOutEndLine();
184 else if ((phylipfile != "") && (columnfile != "")) { m->mothurOut("When running the tree.shared command with a distance file you may not use both the column and the phylip parameters."); m->mothurOutEndLine(); abort = true; }
186 if (columnfile != "") {
187 if (namefile == "") {
188 namefile = m->getNameFile();
189 if (namefile != "") { m->mothurOut("Using " + namefile + " as input file for the name parameter."); m->mothurOutEndLine(); }
191 m->mothurOut("You need to provide a namefile if you are going to use the column format."); m->mothurOutEndLine();
197 //check for optional parameter and set defaults
198 // ...at some point should added some additional type checking...
199 label = validParameter.validFile(parameters, "label", false);
200 if (label == "not found") { label = ""; }
202 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
203 else { allLines = 1; }
206 groups = validParameter.validFile(parameters, "groups", false);
207 if (groups == "not found") { groups = ""; }
209 m->splitAtDash(groups, Groups);
210 m->setGroups(Groups);
213 calc = validParameter.validFile(parameters, "calc", false);
214 if (calc == "not found") { calc = "jclass-thetayc"; }
216 if (calc == "default") { calc = "jclass-thetayc"; }
218 m->splitAtDash(calc, Estimators);
219 if (m->inUsersGroups("citation", Estimators)) {
220 ValidCalculators validCalc; validCalc.printCitations(Estimators);
221 //remove citation from list of calcs
222 for (int i = 0; i < Estimators.size(); i++) { if (Estimators[i] == "citation") { Estimators.erase(Estimators.begin()+i); break; } }
226 temp = validParameter.validFile(parameters, "precision", false); if (temp == "not found") { temp = "100"; }
227 m->mothurConvert(temp, precision);
229 temp = validParameter.validFile(parameters, "cutoff", false); if (temp == "not found") { temp = "10"; }
230 m->mothurConvert(temp, cutoff);
231 cutoff += (5 / (precision * 10.0));
233 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
234 m->setProcessors(temp);
235 m->mothurConvert(temp, processors);
237 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
238 m->mothurConvert(temp, iters);
240 temp = validParameter.validFile(parameters, "subsample", false); if (temp == "not found") { temp = "F"; }
241 if (m->isNumeric1(temp)) { m->mothurConvert(temp, subsampleSize); subsample = true; }
243 if (m->isTrue(temp)) { subsample = true; subsampleSize = -1; } //we will set it to smallest group later
244 else { subsample = false; }
247 if (subsample == false) { iters = 1; }
249 if (subsample && (format != "sharedfile")) { m->mothurOut("[ERROR]: the subsample parameter can only be used with a shared file.\n"); abort=true; }
251 //if the user changes the output directory command factory will send this info to us in the output parameter
252 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
254 outputDir += m->hasPath(inputfile); //if user entered a file with a path then preserve it
259 catch(exception& e) {
260 m->errorOut(e, "TreeGroupCommand", "TreeGroupCommand");
264 //**********************************************************************************************************************
266 TreeGroupCommand::~TreeGroupCommand(){
267 if (abort == false) {
268 if (format == "sharedfile") { delete input; }
269 else { delete readMatrix; delete matrix; delete list; }
275 //**********************************************************************************************************************
277 int TreeGroupCommand::execute(){
280 if (abort == true) { if (calledHelp) { return 0; } return 2; }
282 if (format == "sharedfile") {
284 ValidCalculators validCalculator;
286 for (int i=0; i<Estimators.size(); i++) {
287 if (validCalculator.isValidCalculator("treegroup", Estimators[i]) == true) {
288 if (Estimators[i] == "sharedsobs") {
289 treeCalculators.push_back(new SharedSobsCS());
290 }else if (Estimators[i] == "sharedchao") {
291 treeCalculators.push_back(new SharedChao1());
292 }else if (Estimators[i] == "sharedace") {
293 treeCalculators.push_back(new SharedAce());
294 }else if (Estimators[i] == "jabund") {
295 treeCalculators.push_back(new JAbund());
296 }else if (Estimators[i] == "sorabund") {
297 treeCalculators.push_back(new SorAbund());
298 }else if (Estimators[i] == "jclass") {
299 treeCalculators.push_back(new Jclass());
300 }else if (Estimators[i] == "sorclass") {
301 treeCalculators.push_back(new SorClass());
302 }else if (Estimators[i] == "jest") {
303 treeCalculators.push_back(new Jest());
304 }else if (Estimators[i] == "sorest") {
305 treeCalculators.push_back(new SorEst());
306 }else if (Estimators[i] == "thetayc") {
307 treeCalculators.push_back(new ThetaYC());
308 }else if (Estimators[i] == "thetan") {
309 treeCalculators.push_back(new ThetaN());
310 }else if (Estimators[i] == "kstest") {
311 treeCalculators.push_back(new KSTest());
312 }else if (Estimators[i] == "sharednseqs") {
313 treeCalculators.push_back(new SharedNSeqs());
314 }else if (Estimators[i] == "ochiai") {
315 treeCalculators.push_back(new Ochiai());
316 }else if (Estimators[i] == "anderberg") {
317 treeCalculators.push_back(new Anderberg());
318 }else if (Estimators[i] == "kulczynski") {
319 treeCalculators.push_back(new Kulczynski());
320 }else if (Estimators[i] == "kulczynskicody") {
321 treeCalculators.push_back(new KulczynskiCody());
322 }else if (Estimators[i] == "lennon") {
323 treeCalculators.push_back(new Lennon());
324 }else if (Estimators[i] == "morisitahorn") {
325 treeCalculators.push_back(new MorHorn());
326 }else if (Estimators[i] == "braycurtis") {
327 treeCalculators.push_back(new BrayCurtis());
328 }else if (Estimators[i] == "whittaker") {
329 treeCalculators.push_back(new Whittaker());
330 }else if (Estimators[i] == "odum") {
331 treeCalculators.push_back(new Odum());
332 }else if (Estimators[i] == "canberra") {
333 treeCalculators.push_back(new Canberra());
334 }else if (Estimators[i] == "structeuclidean") {
335 treeCalculators.push_back(new StructEuclidean());
336 }else if (Estimators[i] == "structchord") {
337 treeCalculators.push_back(new StructChord());
338 }else if (Estimators[i] == "hellinger") {
339 treeCalculators.push_back(new Hellinger());
340 }else if (Estimators[i] == "manhattan") {
341 treeCalculators.push_back(new Manhattan());
342 }else if (Estimators[i] == "structpearson") {
343 treeCalculators.push_back(new StructPearson());
344 }else if (Estimators[i] == "soergel") {
345 treeCalculators.push_back(new Soergel());
346 }else if (Estimators[i] == "spearman") {
347 treeCalculators.push_back(new Spearman());
348 }else if (Estimators[i] == "structkulczynski") {
349 treeCalculators.push_back(new StructKulczynski());
350 }else if (Estimators[i] == "speciesprofile") {
351 treeCalculators.push_back(new SpeciesProfile());
352 }else if (Estimators[i] == "hamming") {
353 treeCalculators.push_back(new Hamming());
354 }else if (Estimators[i] == "structchi2") {
355 treeCalculators.push_back(new StructChi2());
356 }else if (Estimators[i] == "gower") {
357 treeCalculators.push_back(new Gower());
358 }else if (Estimators[i] == "memchi2") {
359 treeCalculators.push_back(new MemChi2());
360 }else if (Estimators[i] == "memchord") {
361 treeCalculators.push_back(new MemChord());
362 }else if (Estimators[i] == "memeuclidean") {
363 treeCalculators.push_back(new MemEuclidean());
364 }else if (Estimators[i] == "mempearson") {
365 treeCalculators.push_back(new MemPearson());
370 //if the users entered no valid calculators don't execute command
371 if (treeCalculators.size() == 0) { m->mothurOut("You have given no valid calculators."); m->mothurOutEndLine(); return 0; }
373 input = new InputData(sharedfile, "sharedfile");
374 lookup = input->getSharedRAbundVectors();
375 lastLabel = lookup[0]->getLabel();
377 if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups. I cannot run the command."); m->mothurOutEndLine(); return 0; }
379 //used in tree constructor
382 //create treemap class from groupmap for tree class to use
383 tmap = new TreeMap();
384 tmap->makeSim(m->getAllGroups());
386 //clear globaldatas old tree names if any
387 m->Treenames.clear();
389 //fills globaldatas tree names
390 m->Treenames = m->getGroups();
392 if (m->control_pressed) { return 0; }
397 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
400 filename = inputfile;
402 if (format == "column") { readMatrix = new ReadColumnMatrix(filename); }
403 else if (format == "phylip") { readMatrix = new ReadPhylipMatrix(filename); }
405 readMatrix->setCutoff(cutoff);
408 nameMap = new NameAssignment(namefile);
415 readMatrix->read(nameMap);
416 list = readMatrix->getListVector();
417 matrix = readMatrix->getMatrix();
420 tmap = new TreeMap();
422 if (m->control_pressed) { return 0; }
426 vector<string> namesGroups = tmap->getNamesOfGroups();
427 m->setGroups(namesGroups);
429 //clear globaldatas old tree names if any
430 m->Treenames.clear();
432 //fills globaldatas tree names
433 m->Treenames = m->getGroups();
435 //used in tree constructor
438 if (m->control_pressed) { return 0; }
440 vector< vector<double> > matrix = makeSimsDist();
442 if (m->control_pressed) { return 0; }
444 //create a new filename
445 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + "tre";
446 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
448 Tree* newTree = createTree(matrix);
450 if (newTree != NULL) { writeTree(outputFile, newTree); delete newTree; }
452 if (m->control_pressed) { return 0; }
454 m->mothurOut("Tree complete. "); m->mothurOutEndLine();
458 //reset groups parameter
461 //set tree file as new current treefile
463 itTypes = outputTypes.find("tree");
464 if (itTypes != outputTypes.end()) {
465 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTreeFile(current); }
468 m->mothurOutEndLine();
469 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
470 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
471 m->mothurOutEndLine();
475 catch(exception& e) {
476 m->errorOut(e, "TreeGroupCommand", "execute");
480 //**********************************************************************************************************************
482 Tree* TreeGroupCommand::createTree(vector< vector<double> >& simMatrix){
488 map<int, int> index; //maps row in simMatrix to vector index in the tree
489 for (int g = 0; g < numGroups; g++) { index[g] = g; }
491 //do merges and create tree structure by setting parents and children
492 //there are numGroups - 1 merges to do
493 for (int i = 0; i < (numGroups - 1); i++) {
494 float largest = -1000.0;
496 if (m->control_pressed) { delete t; t = NULL; return t; }
499 //find largest value in sims matrix by searching lower triangle
500 for (int j = 1; j < simMatrix.size(); j++) {
501 for (int k = 0; k < j; k++) {
502 if (simMatrix[j][k] > largest) { largest = simMatrix[j][k]; row = j; column = k; }
506 //set non-leaf node info and update leaves to know their parents
508 t->tree[numGroups + i].setChildren(index[row], index[column]);
511 t->tree[index[row]].setParent(numGroups + i);
512 t->tree[index[column]].setParent(numGroups + i);
514 //blength = distance / 2;
515 float blength = ((1.0 - largest) / 2);
518 t->tree[index[row]].setBranchLength(blength - t->tree[index[row]].getLengthToLeaves());
519 t->tree[index[column]].setBranchLength(blength - t->tree[index[column]].getLengthToLeaves());
521 //set your length to leaves to your childs length plus branchlength
522 t->tree[numGroups + i].setLengthToLeaves(t->tree[index[row]].getLengthToLeaves() + t->tree[index[row]].getBranchLength());
526 index[row] = numGroups+i;
527 index[column] = numGroups+i;
529 //remove highest value that caused the merge.
530 simMatrix[row][column] = -1000.0;
531 simMatrix[column][row] = -1000.0;
533 //merge values in simsMatrix
534 for (int n = 0; n < simMatrix.size(); n++) {
535 //row becomes merge of 2 groups
536 simMatrix[row][n] = (simMatrix[row][n] + simMatrix[column][n]) / 2;
537 simMatrix[n][row] = simMatrix[row][n];
539 simMatrix[column][n] = -1000.0;
540 simMatrix[n][column] = -1000.0;
544 //adjust tree to make sure root to tip length is .5
545 int root = t->findRoot();
546 t->tree[root].setBranchLength((0.5 - t->tree[root].getLengthToLeaves()));
551 if (m->control_pressed) { delete t; t = NULL; return t; }
556 catch(exception& e) {
557 m->errorOut(e, "TreeGroupCommand", "createTree");
561 /***********************************************************/
562 int TreeGroupCommand::writeTree(string out, Tree* T) {
566 t->createNewickFile(out);
568 if (m->control_pressed) { m->mothurRemove(out); outputNames.pop_back(); return 1; }
573 catch(exception& e) {
574 m->errorOut(e, "TreeGroupCommand", "printSims");
579 /***********************************************************/
580 void TreeGroupCommand::printSims(ostream& out, vector< vector<double> >& simMatrix) {
583 for (int m = 0; m < simMatrix.size(); m++) {
584 //out << lookup[m]->getGroup() << '\t';
585 for (int n = 0; n < simMatrix.size(); n++) {
586 out << simMatrix[m][n] << '\t';
592 catch(exception& e) {
593 m->errorOut(e, "TreeGroupCommand", "printSims");
597 /***********************************************************/
598 vector< vector<double> > TreeGroupCommand::makeSimsDist() {
600 numGroups = list->size();
602 //initialize simMatrix
603 vector< vector<double> > simMatrix;
604 simMatrix.resize(numGroups);
605 for (int k = 0; k < simMatrix.size(); k++) {
606 for (int j = 0; j < simMatrix.size(); j++) {
607 simMatrix[k].push_back(0.0);
611 //go through sparse matrix and fill sims
612 //go through each cell in the sparsematrix
613 for(MatData currentCell = matrix->begin(); currentCell != matrix->end(); currentCell++){
614 //similairity = -(distance-1)
615 simMatrix[currentCell->row][currentCell->column] = -(currentCell->dist -1.0);
616 simMatrix[currentCell->column][currentCell->row] = -(currentCell->dist -1.0);
618 if (m->control_pressed) { return simMatrix; }
624 catch(exception& e) {
625 m->errorOut(e, "TreeGroupCommand", "makeSimsDist");
630 /***********************************************************/
631 int TreeGroupCommand::makeSimsShared() {
634 numGroups = lookup.size();
635 lines.resize(processors);
636 for (int i = 0; i < processors; i++) {
637 lines[i].start = int (sqrt(float(i)/float(processors)) * numGroups);
638 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numGroups);
642 if (subsampleSize == -1) { //user has not set size, set size = smallest samples size
643 subsampleSize = lookup[0]->getNumSeqs();
644 for (int i = 1; i < lookup.size(); i++) {
645 int thisSize = lookup[i]->getNumSeqs();
647 if (thisSize < subsampleSize) { subsampleSize = thisSize; }
652 vector<SharedRAbundVector*> temp;
653 for (int i = 0; i < lookup.size(); i++) {
654 if (lookup[i]->getNumSeqs() < subsampleSize) {
655 m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
658 Groups.push_back(lookup[i]->getGroup());
659 temp.push_back(lookup[i]);
663 m->setGroups(Groups);
667 set<string> processedLabels;
668 set<string> userLabels = labels;
670 //as long as you are not at the end of the file or done wih the lines you want
671 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
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; }
674 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
675 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
678 processedLabels.insert(lookup[0]->getLabel());
679 userLabels.erase(lookup[0]->getLabel());
682 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
683 string saveLabel = lookup[0]->getLabel();
685 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
686 lookup = input->getSharedRAbundVectors(lastLabel);
688 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
691 processedLabels.insert(lookup[0]->getLabel());
692 userLabels.erase(lookup[0]->getLabel());
694 //restore real lastlabel to save below
695 lookup[0]->setLabel(saveLabel);
698 lastLabel = lookup[0]->getLabel();
700 //get next line to process
701 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
702 lookup = input->getSharedRAbundVectors();
705 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; }
707 //output error messages about any remaining user labels
708 set<string>::iterator it;
709 bool needToRun = false;
710 for (it = userLabels.begin(); it != userLabels.end(); it++) {
711 m->mothurOut("Your file does not include the label " + *it);
712 if (processedLabels.count(lastLabel) != 1) {
713 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
716 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
720 //run last label if you need to
721 if (needToRun == true) {
722 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
723 lookup = input->getSharedRAbundVectors(lastLabel);
725 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
727 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
730 for(int i = 0 ; i < treeCalculators.size(); i++) { delete treeCalculators[i]; }
734 catch(exception& e) {
735 m->errorOut(e, "TreeGroupCommand", "makeSimsShared");
740 /***********************************************************/
741 int TreeGroupCommand::process(vector<SharedRAbundVector*> thisLookup) {
743 vector< vector< vector<seqDist> > > calcDistsTotals; //each iter, one for each calc, then each groupCombos dists. this will be used to make .dist files
744 vector< vector<seqDist> > calcDists; calcDists.resize(treeCalculators.size());
746 for (int thisIter = 0; thisIter < iters; thisIter++) {
748 vector<SharedRAbundVector*> thisItersLookup = thisLookup;
752 vector<string> tempLabels; //dont need since we arent printing the sampled sharedRabunds
754 //make copy of lookup so we don't get access violations
755 vector<SharedRAbundVector*> newLookup;
756 for (int k = 0; k < thisItersLookup.size(); k++) {
757 SharedRAbundVector* temp = new SharedRAbundVector();
758 temp->setLabel(thisItersLookup[k]->getLabel());
759 temp->setGroup(thisItersLookup[k]->getGroup());
760 newLookup.push_back(temp);
764 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
765 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
766 for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
769 tempLabels = sample.getSample(newLookup, subsampleSize);
770 thisItersLookup = newLookup;
774 driver(thisItersLookup, 0, numGroups, calcDists);
777 vector<int> processIDS;
779 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
780 //loop through and create all the processes you want
781 while (process != processors) {
785 processIDS.push_back(pid);
789 driver(thisItersLookup, lines[process].start, lines[process].end, calcDists);
791 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(getpid()) + ".dist";
793 m->openOutputFile(tempdistFileName, outtemp);
795 for (int i = 0; i < calcDists.size(); i++) {
796 outtemp << calcDists[i].size() << endl;
798 for (int j = 0; j < calcDists[i].size(); j++) {
799 outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl;
806 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
807 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
812 //parent do your part
813 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);
815 //force parent to wait until all the processes are done
816 for (int i = 0; i < processIDS.size(); i++) {
817 int temp = processIDS[i];
821 for (int i = 0; i < processIDS.size(); i++) {
822 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(processIDS[i]) + ".dist";
824 m->openInputFile(tempdistFileName, intemp);
826 for (int k = 0; k < calcDists.size(); k++) {
828 intemp >> size; m->gobble(intemp);
830 for (int j = 0; j < size; j++) {
835 intemp >> seq1 >> seq2 >> dist; m->gobble(intemp);
837 seqDist tempDist(seq1, seq2, dist);
838 calcDists[k].push_back(tempDist);
842 m->mothurRemove(tempdistFileName);
845 //////////////////////////////////////////////////////////////////////////////////////////////////////
846 //Windows version shared memory, so be careful when passing variables through the treeSharedData struct.
847 //Above fork() will clone, so memory is separate, but that's not the case with windows,
848 //Taking advantage of shared memory to pass results vectors.
849 //////////////////////////////////////////////////////////////////////////////////////////////////////
851 vector<treeSharedData*> pDataArray;
852 DWORD dwThreadIdArray[processors-1];
853 HANDLE hThreadArray[processors-1];
855 //Create processor worker threads.
856 for( int i=1; i<processors; i++ ){
858 //make copy of lookup so we don't get access violations
859 vector<SharedRAbundVector*> newLookup;
860 for (int k = 0; k < thisItersLookup.size(); k++) {
861 SharedRAbundVector* temp = new SharedRAbundVector();
862 temp->setLabel(thisItersLookup[k]->getLabel());
863 temp->setGroup(thisItersLookup[k]->getGroup());
864 newLookup.push_back(temp);
868 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
869 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
870 for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
873 // Allocate memory for thread data.
874 treeSharedData* tempSum = new treeSharedData(m, lines[i].start, lines[i].end, Estimators, newLookup);
875 pDataArray.push_back(tempSum);
876 processIDS.push_back(i);
878 hThreadArray[i-1] = CreateThread(NULL, 0, MyTreeSharedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
881 //parent do your part
882 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);
884 //Wait until all threads have terminated.
885 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
887 //Close all thread handles and free memory allocations.
888 for(int i=0; i < pDataArray.size(); i++){
889 for (int j = 0; j < pDataArray[i]->thisLookup.size(); j++) { delete pDataArray[i]->thisLookup[j]; }
891 for (int k = 0; k < calcDists.size(); k++) {
892 int size = pDataArray[i]->calcDists[k].size();
893 for (int j = 0; j < size; j++) { calcDists[k].push_back(pDataArray[i]->calcDists[k][j]); }
896 CloseHandle(hThreadArray[i]);
897 delete pDataArray[i];
903 calcDistsTotals.push_back(calcDists);
908 for (int i = 0; i < thisItersLookup.size(); i++) { delete thisItersLookup[i]; }
909 thisItersLookup.clear();
910 for (int i = 0; i < calcDists.size(); i++) { calcDists[i].clear(); }
915 //we need to find the average distance and standard deviation for each groups distance
917 vector< vector<seqDist> > calcAverages; calcAverages.resize(treeCalculators.size());
918 for (int i = 0; i < calcAverages.size(); i++) { //initialize sums to zero.
919 calcAverages[i].resize(calcDistsTotals[0][i].size());
921 for (int j = 0; j < calcAverages[i].size(); j++) {
922 calcAverages[i][j].seq1 = calcDists[i][j].seq1;
923 calcAverages[i][j].seq2 = calcDists[i][j].seq2;
924 calcAverages[i][j].dist = 0.0;
928 for (int thisIter = 0; thisIter < iters; thisIter++) { //sum all groups dists for each calculator
929 for (int i = 0; i < calcAverages.size(); i++) { //initialize sums to zero.
930 for (int j = 0; j < calcAverages[i].size(); j++) {
931 calcAverages[i][j].dist += calcDistsTotals[thisIter][i][j].dist;
936 for (int i = 0; i < calcAverages.size(); i++) { //finds average.
937 for (int j = 0; j < calcAverages[i].size(); j++) {
938 calcAverages[i][j].dist /= (float) iters;
942 //create average tree for each calc
943 for (int i = 0; i < calcDists.size(); i++) {
944 vector< vector<double> > matrix; //square matrix to represent the distance
945 matrix.resize(thisLookup.size());
946 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
948 for (int j = 0; j < calcAverages[i].size(); j++) {
949 int row = calcAverages[i][j].seq1;
950 int column = calcAverages[i][j].seq2;
951 float dist = calcAverages[i][j].dist;
953 matrix[row][column] = dist;
954 matrix[column][row] = dist;
957 //create a new filename
958 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".ave.tre";
959 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
961 //creates tree from similarity matrix and write out file
962 Tree* newTree = createTree(matrix);
963 if (newTree != NULL) { writeTree(outputFile, newTree); }
966 //create all trees for each calc and find their consensus tree
967 for (int i = 0; i < calcDists.size(); i++) {
968 if (m->control_pressed) { break; }
970 //create a new filename
971 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".all.tre";
972 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
975 m->openOutputFile(outputFile, outAll);
978 for (int myIter = 0; myIter < iters; myIter++) {
980 if(m->control_pressed) { break; }
983 vector< vector<double> > matrix; //square matrix to represent the distance
984 matrix.resize(thisLookup.size());
985 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
987 for (int j = 0; j < calcDistsTotals[myIter][i].size(); j++) {
988 int row = calcDistsTotals[myIter][i][j].seq1;
989 int column = calcDistsTotals[myIter][i][j].seq2;
990 double dist = calcDistsTotals[myIter][i][j].dist;
992 matrix[row][column] = dist;
993 matrix[column][row] = dist;
996 //creates tree from similarity matrix and write out file
997 Tree* newTree = createTree(matrix);
998 if (newTree != NULL) {
999 newTree->print(outAll);
1000 trees.push_back(newTree);
1004 if (m->control_pressed) { for (int k = 0; k < trees.size(); k++) { delete trees[k]; } }
1006 Consensus consensus;
1007 Tree* conTree = consensus.getTree(trees, tmap);
1009 //create a new filename
1010 string conFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".cons.tre";
1011 outputNames.push_back(conFile); outputTypes["tree"].push_back(outputFile);
1013 m->openOutputFile(conFile, outTree);
1015 if (conTree != NULL) { conTree->print(outTree, "boot"); delete conTree; }
1020 for (int i = 0; i < calcDists.size(); i++) {
1021 if (m->control_pressed) { break; }
1024 vector< vector<double> > matrix; //square matrix to represent the distance
1025 matrix.resize(thisLookup.size());
1026 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
1028 for (int j = 0; j < calcDists[i].size(); j++) {
1029 int row = calcDists[i][j].seq1;
1030 int column = calcDists[i][j].seq2;
1031 double dist = calcDists[i][j].dist;
1033 matrix[row][column] = dist;
1034 matrix[column][row] = dist;
1037 //create a new filename
1038 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".tre";
1039 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
1041 //creates tree from similarity matrix and write out file
1042 Tree* newTree = createTree(matrix);
1043 if (newTree != NULL) { writeTree(outputFile, newTree); delete newTree; }
1049 catch(exception& e) {
1050 m->errorOut(e, "TreeGroupCommand", "process");
1054 /**************************************************************************************************/
1055 int TreeGroupCommand::driver(vector<SharedRAbundVector*> thisLookup, int start, int end, vector< vector<seqDist> >& calcDists) {
1057 vector<SharedRAbundVector*> subset;
1058 for (int k = start; k < end; k++) { // pass cdd each set of groups to compare
1060 for (int l = 0; l < k; l++) {
1062 if (k != l) { //we dont need to similiarity of a groups to itself
1063 subset.clear(); //clear out old pair of sharedrabunds
1064 //add new pair of sharedrabunds
1065 subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]);
1067 for(int i=0;i<treeCalculators.size();i++) {
1069 //if this calc needs all groups to calculate the pair load all groups
1070 if (treeCalculators[i]->getNeedsAll()) {
1071 //load subset with rest of lookup for those calcs that need everyone to calc for a pair
1072 for (int w = 0; w < thisLookup.size(); w++) {
1073 if ((w != k) && (w != l)) { subset.push_back(thisLookup[w]); }
1077 vector<double> tempdata = treeCalculators[i]->getValues(subset); //saves the calculator outputs
1079 if (m->control_pressed) { return 1; }
1081 seqDist temp(l, k, -(tempdata[0]-1.0));
1082 calcDists[i].push_back(temp);
1090 catch(exception& e) {
1091 m->errorOut(e, "TreeGroupCommand", "driver");
1095 /***********************************************************/