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){
485 t = new Tree(tmap, simMatrix);
487 if (m->control_pressed) { delete t; t = NULL; return t; }
490 map<string, string> empty;
491 t->assembleTree(empty);
495 catch(exception& e) {
496 m->errorOut(e, "TreeGroupCommand", "createTree");
500 /***********************************************************/
501 int TreeGroupCommand::writeTree(string out, Tree* T) {
505 t->createNewickFile(out);
507 if (m->control_pressed) { m->mothurRemove(out); outputNames.pop_back(); return 1; }
512 catch(exception& e) {
513 m->errorOut(e, "TreeGroupCommand", "printSims");
518 /***********************************************************/
519 void TreeGroupCommand::printSims(ostream& out, vector< vector<double> >& simMatrix) {
522 for (int m = 0; m < simMatrix.size(); m++) {
523 //out << lookup[m]->getGroup() << '\t';
524 for (int n = 0; n < simMatrix.size(); n++) {
525 out << simMatrix[m][n] << '\t';
531 catch(exception& e) {
532 m->errorOut(e, "TreeGroupCommand", "printSims");
536 /***********************************************************/
537 vector< vector<double> > TreeGroupCommand::makeSimsDist() {
539 numGroups = list->size();
541 //initialize simMatrix
542 vector< vector<double> > simMatrix;
543 simMatrix.resize(numGroups);
544 for (int k = 0; k < simMatrix.size(); k++) {
545 for (int j = 0; j < simMatrix.size(); j++) {
546 simMatrix[k].push_back(0.0);
550 //go through sparse matrix and fill sims
551 //go through each cell in the sparsematrix
552 for(MatData currentCell = matrix->begin(); currentCell != matrix->end(); currentCell++){
553 //similairity = -(distance-1)
554 simMatrix[currentCell->row][currentCell->column] = -(currentCell->dist -1.0);
555 simMatrix[currentCell->column][currentCell->row] = -(currentCell->dist -1.0);
557 if (m->control_pressed) { return simMatrix; }
563 catch(exception& e) {
564 m->errorOut(e, "TreeGroupCommand", "makeSimsDist");
569 /***********************************************************/
570 int TreeGroupCommand::makeSimsShared() {
574 if (subsampleSize == -1) { //user has not set size, set size = smallest samples size
575 subsampleSize = lookup[0]->getNumSeqs();
576 for (int i = 1; i < lookup.size(); i++) {
577 int thisSize = lookup[i]->getNumSeqs();
579 if (thisSize < subsampleSize) { subsampleSize = thisSize; }
584 vector<SharedRAbundVector*> temp;
585 for (int i = 0; i < lookup.size(); i++) {
586 if (lookup[i]->getNumSeqs() < subsampleSize) {
587 m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
590 Groups.push_back(lookup[i]->getGroup());
591 temp.push_back(lookup[i]);
595 m->setGroups(Groups);
598 if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups. I cannot run the command."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
601 numGroups = lookup.size();
602 lines.resize(processors);
603 for (int i = 0; i < processors; i++) {
604 lines[i].start = int (sqrt(float(i)/float(processors)) * numGroups);
605 lines[i].end = int (sqrt(float(i+1)/float(processors)) * numGroups);
608 set<string> processedLabels;
609 set<string> userLabels = labels;
611 //as long as you are not at the end of the file or done wih the lines you want
612 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
613 if (m->control_pressed) { for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } for(int i = 0 ; i < treeCalculators.size(); i++) { delete treeCalculators[i]; } return 1; }
615 if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){
616 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
619 processedLabels.insert(lookup[0]->getLabel());
620 userLabels.erase(lookup[0]->getLabel());
623 if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
624 string saveLabel = lookup[0]->getLabel();
626 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
627 lookup = input->getSharedRAbundVectors(lastLabel);
629 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
632 processedLabels.insert(lookup[0]->getLabel());
633 userLabels.erase(lookup[0]->getLabel());
635 //restore real lastlabel to save below
636 lookup[0]->setLabel(saveLabel);
639 lastLabel = lookup[0]->getLabel();
641 //get next line to process
642 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
643 lookup = input->getSharedRAbundVectors();
646 if (m->control_pressed) { for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; } for(int i = 0 ; i < treeCalculators.size(); i++) { delete treeCalculators[i]; } return 1; }
648 //output error messages about any remaining user labels
649 set<string>::iterator it;
650 bool needToRun = false;
651 for (it = userLabels.begin(); it != userLabels.end(); it++) {
652 m->mothurOut("Your file does not include the label " + *it);
653 if (processedLabels.count(lastLabel) != 1) {
654 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
657 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
661 //run last label if you need to
662 if (needToRun == true) {
663 for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }
664 lookup = input->getSharedRAbundVectors(lastLabel);
666 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
668 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
671 for(int i = 0 ; i < treeCalculators.size(); i++) { delete treeCalculators[i]; }
675 catch(exception& e) {
676 m->errorOut(e, "TreeGroupCommand", "makeSimsShared");
681 /***********************************************************/
682 int TreeGroupCommand::process(vector<SharedRAbundVector*> thisLookup) {
684 vector< vector< vector<seqDist> > > calcDistsTotals; //each iter, one for each calc, then each groupCombos dists. this will be used to make .dist files
685 vector< vector<seqDist> > calcDists; calcDists.resize(treeCalculators.size());
687 for (int thisIter = 0; thisIter < iters; thisIter++) {
689 vector<SharedRAbundVector*> thisItersLookup = thisLookup;
693 vector<string> tempLabels; //dont need since we arent printing the sampled sharedRabunds
695 //make copy of lookup so we don't get access violations
696 vector<SharedRAbundVector*> newLookup;
697 for (int k = 0; k < thisItersLookup.size(); k++) {
698 SharedRAbundVector* temp = new SharedRAbundVector();
699 temp->setLabel(thisItersLookup[k]->getLabel());
700 temp->setGroup(thisItersLookup[k]->getGroup());
701 newLookup.push_back(temp);
705 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
706 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
707 for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
710 tempLabels = sample.getSample(newLookup, subsampleSize);
711 thisItersLookup = newLookup;
715 driver(thisItersLookup, 0, numGroups, calcDists);
718 vector<int> processIDS;
720 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
721 //loop through and create all the processes you want
722 while (process != processors) {
726 processIDS.push_back(pid);
730 driver(thisItersLookup, lines[process].start, lines[process].end, calcDists);
732 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(getpid()) + ".dist";
734 m->openOutputFile(tempdistFileName, outtemp);
736 for (int i = 0; i < calcDists.size(); i++) {
737 outtemp << calcDists[i].size() << endl;
739 for (int j = 0; j < calcDists[i].size(); j++) {
740 outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl;
747 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
748 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
753 //parent do your part
754 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);
756 //force parent to wait until all the processes are done
757 for (int i = 0; i < processIDS.size(); i++) {
758 int temp = processIDS[i];
762 for (int i = 0; i < processIDS.size(); i++) {
763 string tempdistFileName = m->getRootName(m->getSimpleName(sharedfile)) + toString(processIDS[i]) + ".dist";
765 m->openInputFile(tempdistFileName, intemp);
767 for (int k = 0; k < calcDists.size(); k++) {
769 intemp >> size; m->gobble(intemp);
771 for (int j = 0; j < size; j++) {
776 intemp >> seq1 >> seq2 >> dist; m->gobble(intemp);
778 seqDist tempDist(seq1, seq2, dist);
779 calcDists[k].push_back(tempDist);
783 m->mothurRemove(tempdistFileName);
786 //////////////////////////////////////////////////////////////////////////////////////////////////////
787 //Windows version shared memory, so be careful when passing variables through the treeSharedData struct.
788 //Above fork() will clone, so memory is separate, but that's not the case with windows,
789 //Taking advantage of shared memory to pass results vectors.
790 //////////////////////////////////////////////////////////////////////////////////////////////////////
792 vector<treeSharedData*> pDataArray;
793 DWORD dwThreadIdArray[processors-1];
794 HANDLE hThreadArray[processors-1];
796 //Create processor worker threads.
797 for( int i=1; i<processors; i++ ){
799 //make copy of lookup so we don't get access violations
800 vector<SharedRAbundVector*> newLookup;
801 for (int k = 0; k < thisItersLookup.size(); k++) {
802 SharedRAbundVector* temp = new SharedRAbundVector();
803 temp->setLabel(thisItersLookup[k]->getLabel());
804 temp->setGroup(thisItersLookup[k]->getGroup());
805 newLookup.push_back(temp);
809 for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) {
810 if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; }
811 for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); }
814 // Allocate memory for thread data.
815 treeSharedData* tempSum = new treeSharedData(m, lines[i].start, lines[i].end, Estimators, newLookup);
816 pDataArray.push_back(tempSum);
817 processIDS.push_back(i);
819 hThreadArray[i-1] = CreateThread(NULL, 0, MyTreeSharedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
822 //parent do your part
823 driver(thisItersLookup, lines[0].start, lines[0].end, calcDists);
825 //Wait until all threads have terminated.
826 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
828 //Close all thread handles and free memory allocations.
829 for(int i=0; i < pDataArray.size(); i++){
830 for (int j = 0; j < pDataArray[i]->thisLookup.size(); j++) { delete pDataArray[i]->thisLookup[j]; }
832 for (int k = 0; k < calcDists.size(); k++) {
833 int size = pDataArray[i]->calcDists[k].size();
834 for (int j = 0; j < size; j++) { calcDists[k].push_back(pDataArray[i]->calcDists[k][j]); }
837 CloseHandle(hThreadArray[i]);
838 delete pDataArray[i];
844 calcDistsTotals.push_back(calcDists);
849 for (int i = 0; i < thisItersLookup.size(); i++) { delete thisItersLookup[i]; }
850 thisItersLookup.clear();
851 for (int i = 0; i < calcDists.size(); i++) { calcDists[i].clear(); }
856 //we need to find the average distance and standard deviation for each groups distance
858 vector< vector<seqDist> > calcAverages; calcAverages.resize(treeCalculators.size());
859 for (int i = 0; i < calcAverages.size(); i++) { //initialize sums to zero.
860 calcAverages[i].resize(calcDistsTotals[0][i].size());
862 for (int j = 0; j < calcAverages[i].size(); j++) {
863 calcAverages[i][j].seq1 = calcDists[i][j].seq1;
864 calcAverages[i][j].seq2 = calcDists[i][j].seq2;
865 calcAverages[i][j].dist = 0.0;
869 for (int thisIter = 0; thisIter < iters; thisIter++) { //sum all groups dists for each calculator
870 for (int i = 0; i < calcAverages.size(); i++) { //initialize sums to zero.
871 for (int j = 0; j < calcAverages[i].size(); j++) {
872 calcAverages[i][j].dist += calcDistsTotals[thisIter][i][j].dist;
877 for (int i = 0; i < calcAverages.size(); i++) { //finds average.
878 for (int j = 0; j < calcAverages[i].size(); j++) {
879 calcAverages[i][j].dist /= (float) iters;
883 //create average tree for each calc
884 for (int i = 0; i < calcDists.size(); i++) {
885 vector< vector<double> > matrix; //square matrix to represent the distance
886 matrix.resize(thisLookup.size());
887 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
889 for (int j = 0; j < calcAverages[i].size(); j++) {
890 int row = calcAverages[i][j].seq1;
891 int column = calcAverages[i][j].seq2;
892 float dist = calcAverages[i][j].dist;
894 matrix[row][column] = dist;
895 matrix[column][row] = dist;
898 //create a new filename
899 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".ave.tre";
900 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
902 //creates tree from similarity matrix and write out file
903 Tree* newTree = createTree(matrix);
904 if (newTree != NULL) { writeTree(outputFile, newTree); }
907 //create all trees for each calc and find their consensus tree
908 for (int i = 0; i < calcDists.size(); i++) {
909 if (m->control_pressed) { break; }
911 //create a new filename
912 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".all.tre";
913 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
916 m->openOutputFile(outputFile, outAll);
919 for (int myIter = 0; myIter < iters; myIter++) {
921 if(m->control_pressed) { break; }
924 vector< vector<double> > matrix; //square matrix to represent the distance
925 matrix.resize(thisLookup.size());
926 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
928 for (int j = 0; j < calcDistsTotals[myIter][i].size(); j++) {
929 int row = calcDistsTotals[myIter][i][j].seq1;
930 int column = calcDistsTotals[myIter][i][j].seq2;
931 double dist = calcDistsTotals[myIter][i][j].dist;
933 matrix[row][column] = dist;
934 matrix[column][row] = dist;
937 //creates tree from similarity matrix and write out file
938 Tree* newTree = createTree(matrix);
939 if (newTree != NULL) {
940 newTree->print(outAll);
941 trees.push_back(newTree);
945 if (m->control_pressed) { for (int k = 0; k < trees.size(); k++) { delete trees[k]; } }
948 //clear old tree names if any
949 m->Treenames.clear(); m->Treenames = m->getGroups(); //may have changed if subsample eliminated groups
950 Tree* conTree = consensus.getTree(trees);
952 //create a new filename
953 string conFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".cons.tre";
954 outputNames.push_back(conFile); outputTypes["tree"].push_back(conFile);
956 m->openOutputFile(conFile, outTree);
958 if (conTree != NULL) { conTree->print(outTree, "boot"); delete conTree; }
963 for (int i = 0; i < calcDists.size(); i++) {
964 if (m->control_pressed) { break; }
967 vector< vector<double> > matrix; //square matrix to represent the distance
968 matrix.resize(thisLookup.size());
969 for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); }
971 for (int j = 0; j < calcDists[i].size(); j++) {
972 int row = calcDists[i][j].seq1;
973 int column = calcDists[i][j].seq2;
974 double dist = calcDists[i][j].dist;
976 matrix[row][column] = dist;
977 matrix[column][row] = dist;
980 //create a new filename
981 string outputFile = outputDir + m->getRootName(m->getSimpleName(inputfile)) + treeCalculators[i]->getName() + "." + thisLookup[0]->getLabel() + ".tre";
982 outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile);
984 //creates tree from similarity matrix and write out file
985 Tree* newTree = createTree(matrix);
986 if (newTree != NULL) { writeTree(outputFile, newTree); delete newTree; }
992 catch(exception& e) {
993 m->errorOut(e, "TreeGroupCommand", "process");
997 /**************************************************************************************************/
998 int TreeGroupCommand::driver(vector<SharedRAbundVector*> thisLookup, int start, int end, vector< vector<seqDist> >& calcDists) {
1000 vector<SharedRAbundVector*> subset;
1001 for (int k = start; k < end; k++) { // pass cdd each set of groups to compare
1003 for (int l = 0; l < k; l++) {
1005 if (k != l) { //we dont need to similiarity of a groups to itself
1006 subset.clear(); //clear out old pair of sharedrabunds
1007 //add new pair of sharedrabunds
1008 subset.push_back(thisLookup[k]); subset.push_back(thisLookup[l]);
1010 for(int i=0;i<treeCalculators.size();i++) {
1012 //if this calc needs all groups to calculate the pair load all groups
1013 if (treeCalculators[i]->getNeedsAll()) {
1014 //load subset with rest of lookup for those calcs that need everyone to calc for a pair
1015 for (int w = 0; w < thisLookup.size(); w++) {
1016 if ((w != k) && (w != l)) { subset.push_back(thisLookup[w]); }
1020 vector<double> tempdata = treeCalculators[i]->getValues(subset); //saves the calculator outputs
1022 if (m->control_pressed) { return 1; }
1024 seqDist temp(l, k, -(tempdata[0]-1.0));
1025 calcDists[i].push_back(temp);
1033 catch(exception& e) {
1034 m->errorOut(e, "TreeGroupCommand", "driver");
1038 /***********************************************************/