]> git.donarmstrong.com Git - mothur.git/blob - indicatorcommand.cpp
added [ERROR] flag if command aborts
[mothur.git] / indicatorcommand.cpp
1 /*
2  *  indicatorcommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 11/12/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "indicatorcommand.h"
11 #include "sharedutilities.h"
12
13 //**********************************************************************************************************************
14 vector<string> IndicatorCommand::getValidParameters(){  
15         try {
16                 string Array[] =  {"tree","shared","relabund","design","label","groups","outputdir","inputdir"};
17                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
18                 return myArray;
19         }
20         catch(exception& e) {
21                 m->errorOut(e, "IndicatorCommand", "getValidParameters");
22                 exit(1);
23         }
24 }
25 //**********************************************************************************************************************
26 vector<string> IndicatorCommand::getRequiredParameters(){       
27         try {
28                 string Array[] =  {"tree"};
29                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
30                 return myArray;
31         }
32         catch(exception& e) {
33                 m->errorOut(e, "IndicatorCommand", "getRequiredParameters");
34                 exit(1);
35         }
36 }
37 //**********************************************************************************************************************
38 IndicatorCommand::IndicatorCommand(){   
39         try {
40                 abort = true; calledHelp = true; 
41                 vector<string> tempOutNames;
42                 outputTypes["tree"] = tempOutNames;
43                 outputTypes["summary"] = tempOutNames;
44         }
45         catch(exception& e) {
46                 m->errorOut(e, "IndicatorCommand", "IndicatorCommand");
47                 exit(1);
48         }
49 }
50
51 //**********************************************************************************************************************
52 vector<string> IndicatorCommand::getRequiredFiles(){    
53         try {
54                 vector<string> myArray;
55                 return myArray;
56         }
57         catch(exception& e) {
58                 m->errorOut(e, "IndicatorCommand", "getRequiredFiles");
59                 exit(1);
60         }
61 }
62 //**********************************************************************************************************************
63 IndicatorCommand::IndicatorCommand(string option)  {
64         try {
65                 globaldata = GlobalData::getInstance();
66                 abort = false; calledHelp = false;   
67                 
68                 //allow user to run help
69                 if(option == "help") { help(); abort = true; calledHelp = true; }
70                 
71                 else {
72                         //valid paramters for this command
73                         string Array[] =  {"tree","shared","design","relabund","groups","label","outputdir","inputdir"};
74                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
75                         
76                         OptionParser parser(option);
77                         map<string, string> parameters = parser.getParameters();
78                         
79                         ValidParameters validParameter;
80                         map<string, string>::iterator it;
81                         
82                         //check to make sure all parameters are valid for command
83                         for (it = parameters.begin(); it != parameters.end(); it++) { 
84                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
85                         }
86                         
87                         globaldata->newRead();
88                         
89                         vector<string> tempOutNames;
90                         outputTypes["tree"] = tempOutNames;
91                         outputTypes["summary"] = tempOutNames;
92                         
93                         //if the user changes the input directory command factory will send this info to us in the output parameter 
94                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
95                         if (inputDir == "not found"){   inputDir = "";          }
96                         else {
97                                 string path;
98                                 it = parameters.find("tree");
99                                 //user has given a template file
100                                 if(it != parameters.end()){ 
101                                         path = m->hasPath(it->second);
102                                         //if the user has not given a path then, add inputdir. else leave path alone.
103                                         if (path == "") {       parameters["tree"] = inputDir + it->second;             }
104                                 }
105                                 
106                                 it = parameters.find("shared");
107                                 //user has given a template file
108                                 if(it != parameters.end()){ 
109                                         path = m->hasPath(it->second);
110                                         //if the user has not given a path then, add inputdir. else leave path alone.
111                                         if (path == "") {       parameters["shared"] = inputDir + it->second;           }
112                                 }
113                                 
114                                 it = parameters.find("relabund");
115                                 //user has given a template file
116                                 if(it != parameters.end()){ 
117                                         path = m->hasPath(it->second);
118                                         //if the user has not given a path then, add inputdir. else leave path alone.
119                                         if (path == "") {       parameters["relabund"] = inputDir + it->second;         }
120                                 }
121                                 
122                                 it = parameters.find("design");
123                                 //user has given a template file
124                                 if(it != parameters.end()){ 
125                                         path = m->hasPath(it->second);
126                                         //if the user has not given a path then, add inputdir. else leave path alone.
127                                         if (path == "") {       parameters["design"] = inputDir + it->second;           }
128                                 }
129                         }
130                         
131                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
132
133                         //check for required parameters
134                         treefile = validParameter.validFile(parameters, "tree", true);
135                         if (treefile == "not open") { abort = true; }
136                         else if (treefile == "not found") { treefile = ""; m->mothurOut("tree is a required parameter for the indicator command."); m->mothurOutEndLine(); abort = true;  }     
137                         else {  globaldata->setTreeFile(treefile);  globaldata->setFormat("tree");      }
138                         
139                         sharedfile = validParameter.validFile(parameters, "shared", true);
140                         if (sharedfile == "not open") { abort = true; }
141                         else if (sharedfile == "not found") { sharedfile = ""; }
142                         else { inputFileName = sharedfile; }
143                         
144                         relabundfile = validParameter.validFile(parameters, "relabund", true);
145                         if (relabundfile == "not open") { abort = true; }
146                         else if (relabundfile == "not found") { relabundfile = ""; }
147                         else { inputFileName = relabundfile; }
148                         
149                         designfile = validParameter.validFile(parameters, "design", true);
150                         if (designfile == "not open") { abort = true; }
151                         else if (designfile == "not found") { designfile = ""; }
152                         
153                         groups = validParameter.validFile(parameters, "groups", false);                 
154                         if (groups == "not found") { groups = "";  Groups.push_back("all"); }
155                         else { m->splitAtDash(groups, Groups);  }                       
156                         globaldata->Groups = Groups;
157                         
158                         label = validParameter.validFile(parameters, "label", false);                   
159                         if (label == "not found") { label = ""; m->mothurOut("You did not provide a label, I will use the first label in your inputfile."); m->mothurOutEndLine(); label=""; }  
160                         
161                         if ((relabundfile == "") && (sharedfile == "")) { m->mothurOut("You must provide either a shared or relabund file."); m->mothurOutEndLine(); abort = true;  }
162                         
163                         if ((relabundfile != "") && (sharedfile != "")) { m->mothurOut("You may not use both a shared and relabund file."); m->mothurOutEndLine(); abort = true;  }
164                         
165                 }
166         }
167         catch(exception& e) {
168                 m->errorOut(e, "IndicatorCommand", "IndicatorCommand");         
169                 exit(1);
170         }
171 }
172 //**********************************************************************************************************************
173
174 void IndicatorCommand::help(){
175         try {
176                 m->mothurOut("The indicator command reads a shared or relabund file and a tree file, and outputs a .indicator.tre and .indicator.summary file. \n");
177                 m->mothurOut("The new tree contains labels at each internal node.  The label is the node number so you can relate the tree to the summary file.\n");
178                 m->mothurOut("The summary file lists the indicator value for each OTU for each node.\n");
179                 m->mothurOut("The indicator command parameters are tree, groups, shared, relabund, design and label. The tree parameter is required as well as either shared or relabund.\n");
180                 m->mothurOut("The design parameter allows you to provide a design file to relate the tree to the shared or relabund file.\n");          
181                 m->mothurOut("The groups parameter allows you to specify which of the groups in your shared or relabund you would like analyzed, or if you provide a design file the groups in your design file.  The groups may be entered separated by dashes.\n");
182                 m->mothurOut("The label parameter indicates at what distance your tree relates to the shared or relabund.\n");
183                 m->mothurOut("The indicator command should be used in the following format: indicator(tree=test.tre, shared=test.shared, label=0.03)\n");
184                 m->mothurOut("Note: No spaces between parameter labels (i.e. tree), '=' and parameters (i.e.yourTreefile).\n\n"); 
185         }
186         catch(exception& e) {
187                 m->errorOut(e, "IndicatorCommand", "help");     
188                 exit(1);
189         }
190 }
191
192 //**********************************************************************************************************************
193
194 IndicatorCommand::~IndicatorCommand(){}
195
196 //**********************************************************************************************************************
197
198 int IndicatorCommand::execute(){
199         try {
200                 
201                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
202         
203                 //read designfile if given and set up globaldatas groups for read of sharedfiles
204                 if (designfile != "") {
205                         designMap = new GroupMap(designfile);
206                         designMap->readDesignMap();
207                         
208                         //fill Groups - checks for "all" and for any typo groups
209                         SharedUtil* util = new SharedUtil();
210                         util->setGroups(Groups, designMap->namesOfGroups);
211                         delete util;
212                         
213                         //loop through the Groups and fill Globaldata's Groups with the design file info
214                         globaldata->Groups = designMap->getNamesSeqs(Groups);
215                 }
216         
217                 /***************************************************/
218                 // use smart distancing to get right sharedRabund  //
219                 /***************************************************/
220                 if (sharedfile != "") {  
221                         getShared(); 
222                         if (m->control_pressed) { if (designfile != "") { delete designMap; } for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } return 0; }
223                         if (lookup[0] == NULL) { m->mothurOut("[ERROR] reading shared file."); m->mothurOutEndLine(); return 0; }
224                 }else { 
225                         getSharedFloat(); 
226                         if (m->control_pressed) {  if (designfile != "") { delete designMap; } for (int i = 0; i < lookupFloat.size(); i++) {  delete lookupFloat[i];  } return 0; }
227                         if (lookupFloat[0] == NULL) { m->mothurOut("[ERROR] reading relabund file."); m->mothurOutEndLine(); return 0; }
228                 }
229                 
230                 //reset Globaldatas groups if needed
231                 if (designfile != "") { globaldata->Groups = Groups; }
232                         
233                 /***************************************************/
234                 //    reading tree info                                                    //
235                 /***************************************************/
236                 string groupfile = ""; 
237                 Tree* tree = new Tree(treefile); delete tree;  //extracts names from tree to make faked out groupmap
238          
239                 globaldata->setGroupFile(groupfile); 
240                 treeMap = new TreeMap();
241                 bool mismatch = false;
242                         
243                 for (int i = 0; i < globaldata->Treenames.size(); i++) { 
244                         //sanity check - is this a group that is not in the sharedfile?
245                         if (designfile == "") {
246                                 if (!(m->inUsersGroups(globaldata->Treenames[i], globaldata->gGroupmap->namesOfGroups))) {
247                                         m->mothurOut("[ERROR]: " + globaldata->Treenames[i] + " is not a group in your shared or relabund file."); m->mothurOutEndLine();
248                                         mismatch = true;
249                                 }
250                                 treeMap->addSeq(globaldata->Treenames[i], "Group1"); 
251                         }else{
252                                 vector<string> myGroups; myGroups.push_back(globaldata->Treenames[i]);
253                                 vector<string> myNames = designMap->getNamesSeqs(myGroups);
254                                 
255                                 for(int k = 0; k < myNames.size(); k++) {
256                                         if (!(m->inUsersGroups(myNames[k], globaldata->gGroupmap->namesOfGroups))) {
257                                                 m->mothurOut("[ERROR]: " + myNames[k] + " is not a group in your shared or relabund file."); m->mothurOutEndLine();
258                                                 mismatch = true;
259                                         }
260                                 }
261                                 treeMap->addSeq(globaldata->Treenames[i], "Group1");
262                         }
263                 }
264                 
265                 if ((designfile != "") && (globaldata->Treenames.size() != Groups.size())) { m->mothurOut("[ERROR]: You design file does not match your tree, aborting."); m->mothurOutEndLine(); mismatch = true; }
266                                 
267                 if (mismatch) { //cleanup and exit
268                         if (designfile != "") { delete designMap; }
269                         if (sharedfile != "") {  for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } }
270                         else { for (int i = 0; i < lookupFloat.size(); i++) {  delete lookupFloat[i];  } }
271                         delete treeMap;
272                         return 0;
273                 }
274                         
275                 globaldata->gTreemap = treeMap;
276          
277                 read = new ReadNewickTree(treefile);
278                 int readOk = read->read(); 
279                 
280                 if (readOk != 0) { m->mothurOut("Read Terminated."); m->mothurOutEndLine(); globaldata->gTree.clear(); delete globaldata->gTreemap; delete read; return 0; }
281                 
282                 vector<Tree*> T = globaldata->gTree;
283                 
284                 delete read;
285                 
286                 if (m->control_pressed) { 
287                         if (designfile != "") { delete designMap; }
288                         if (sharedfile != "") {  for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } }
289                         else { for (int i = 0; i < lookupFloat.size(); i++) {  delete lookupFloat[i];  } }
290                         for (int i = 0; i < T.size(); i++) {  delete T[i];  } globaldata->gTree.clear(); delete globaldata->gTreemap; return 0; 
291                 }
292                         
293                 T[0]->assembleTree();
294                                 
295                 /***************************************************/
296                 //    create ouptut tree - respecting pickedGroups //
297                 /***************************************************/
298                 Tree* outputTree = new Tree(globaldata->Groups.size()); 
299                 
300                 outputTree->getSubTree(T[0], globaldata->Groups);
301                 outputTree->assembleTree();
302                         
303                 //no longer need original tree, we have output tree to use and label
304                 for (int i = 0; i < T.size(); i++) {  delete T[i];  } globaldata->gTree.clear();
305                 
306                                 
307                 if (m->control_pressed) { 
308                         if (designfile != "") { delete designMap; }
309                         if (sharedfile != "") {  for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } }
310                         else { for (int i = 0; i < lookupFloat.size(); i++) {  delete lookupFloat[i];  } }
311                         delete outputTree; delete globaldata->gTreemap;  return 0; 
312                 }
313                 
314                 /***************************************************/
315                 //              get indicator species values                       //
316                 /***************************************************/
317                 GetIndicatorSpecies(outputTree);
318                 
319                 if (designfile != "") { delete designMap; }
320                 
321                 if (m->control_pressed) {  
322                         if (sharedfile != "") {  for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } }
323                         else { for (int i = 0; i < lookupFloat.size(); i++) {  delete lookupFloat[i];  } }
324                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); }
325                         delete outputTree; delete globaldata->gTreemap;  return 0; 
326                 }
327                 
328                 m->mothurOutEndLine();
329                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
330                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
331                 m->mothurOutEndLine();
332                                 
333                 return 0;
334         }
335         catch(exception& e) {
336                 m->errorOut(e, "IndicatorCommand", "execute");  
337                 exit(1);
338         }
339 }
340 //**********************************************************************************************************************
341 //traverse tree finding indicator species values for each otu at each node
342 //label node with otu number that has highest indicator value
343 //report all otu values to file
344 int IndicatorCommand::GetIndicatorSpecies(Tree*& T){
345         try {
346                 
347                 string thisOutputDir = outputDir;
348                 if (outputDir == "") {  thisOutputDir += m->hasPath(inputFileName);  }
349                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(inputFileName)) + "indicator.summary";
350                 outputNames.push_back(outputFileName); outputTypes["summary"].push_back(outputFileName);
351                 
352                 ofstream out;
353                 m->openOutputFile(outputFileName, out);
354                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
355                 
356                 int numBins = 0;
357                 if (sharedfile != "") { numBins = lookup[0]->getNumBins(); }
358                 else { numBins = lookupFloat[0]->getNumBins(); }
359                 
360                 //print headings
361                 out << "TreeNode\t";
362                 for (int i = 0; i < numBins; i++) { out << "OTU-" << (i+1) << '\t'; }
363                 out << endl;
364                 
365                 string treeOutputDir = outputDir;
366                 if (outputDir == "") {  treeOutputDir += m->hasPath(treefile);  }
367                 string outputTreeFileName = treeOutputDir + m->getRootName(m->getSimpleName(treefile)) + "indicator.tre";
368                 
369                 
370                 //create a map from tree node index to names of descendants, save time later to know which sharedRabund you need
371                 map<int, set<string> > nodeToDescendants;
372                 map<int, set<int> > descendantNodes;
373                 for (int i = 0; i < T->getNumNodes(); i++) {
374                         if (m->control_pressed) { return 0; }
375                         
376                         nodeToDescendants[i] = getDescendantList(T, i, nodeToDescendants, descendantNodes);
377                 }
378                 
379                 //you need the distances to leaf to decide grouping below
380                 //this will also set branch lengths if the tree does not include them
381                 map<int, float> distToRoot = getDistToRoot(T);
382                         
383                 //for each node
384                 for (int i = T->getNumLeaves(); i < T->getNumNodes(); i++) {
385                                 
386                         if (m->control_pressed) { out.close(); return 0; }
387                         
388                         /*****************************************************/
389                         //create vectors containing rabund info                          //
390                         /*****************************************************/
391                         
392                         vector<float> indicatorValues; //size of numBins
393                         
394                         if (sharedfile != "") {
395                                 vector< vector<SharedRAbundVector*> > groupings;
396                                 
397                                 //get nodes that will be a valid grouping
398                                 //you are valid if you are not one of my descendants
399                                 //AND your distToRoot is >= mine
400                                 //AND you were not added as part of a larger grouping. Largest nodes are added first.
401                                 
402                                 set<string> groupsAlreadyAdded;
403                                 //create a grouping with my grouping
404                                 vector<SharedRAbundVector*> subset;
405                                 int count = 0;
406                                 int doneCount = nodeToDescendants[i].size();
407                                 for (int k = 0; k < lookup.size(); k++) {
408                                         //is this descendant of i
409                                         if ((nodeToDescendants[i].count(lookup[k]->getGroup()) != 0)) { 
410                                                 subset.push_back(lookup[k]);
411                                                 groupsAlreadyAdded.insert(lookup[k]->getGroup());
412                                                 count++;
413                                         }
414                                         if (count == doneCount) { break; } //quit once you get the rabunds for this grouping
415                                 }
416                                 if (subset.size() != 0) { groupings.push_back(subset); }
417                                 
418                                 
419                                 for (int j = (T->getNumNodes()-1); j >= 0; j--) {
420         
421                                         
422                                         if ((descendantNodes[i].count(j) == 0) && (distToRoot[j] >= distToRoot[i])) { 
423                                                 vector<SharedRAbundVector*> subset;
424                                                 int count = 0;
425                                                 int doneCount = nodeToDescendants[j].size();
426                                                 for (int k = 0; k < lookup.size(); k++) {
427                                                         //is this descendant of j, and we didn't already add this as part of a larger grouping
428                                                         if ((nodeToDescendants[j].count(lookup[k]->getGroup()) != 0) && (groupsAlreadyAdded.count(lookup[k]->getGroup()) == 0)) { 
429                                                                 subset.push_back(lookup[k]);
430                                                                 groupsAlreadyAdded.insert(lookup[k]->getGroup());
431                                                                 count++;
432                                                         }
433                                                         if (count == doneCount) { break; } //quit once you get the rabunds for this grouping
434                                                 }
435                                                 
436                                                 //if subset.size == 0 then the node was added as part of a larger grouping
437                                                 if (subset.size() != 0) { groupings.push_back(subset); }
438                                         }
439                                 }
440                                 
441                                 if (groupsAlreadyAdded.size() != lookup.size()) {  m->mothurOut("[ERROR]: could not make proper groupings."); m->mothurOutEndLine(); }
442                                                                 
443                                 indicatorValues = getValues(groupings);
444                                 
445                         }else {
446                                 vector< vector<SharedRAbundFloatVector*> > groupings;
447                                 
448                                 //get nodes that will be a valid grouping
449                                 //you are valid if you are not one of my descendants
450                                 //AND your distToRoot is >= mine
451                                 //AND you were not added as part of a larger grouping. Largest nodes are added first.
452                                 
453                                 set<string> groupsAlreadyAdded;
454                                 //create a grouping with my grouping
455                                 vector<SharedRAbundFloatVector*> subset;
456                                 int count = 0;
457                                 int doneCount = nodeToDescendants[i].size();
458                                 for (int k = 0; k < lookupFloat.size(); k++) {
459                                         //is this descendant of i
460                                         if ((nodeToDescendants[i].count(lookupFloat[k]->getGroup()) != 0)) { 
461                                                 subset.push_back(lookupFloat[k]);
462                                                 groupsAlreadyAdded.insert(lookupFloat[k]->getGroup());
463                                                 count++;
464                                         }
465                                         if (count == doneCount) { break; } //quit once you get the rabunds for this grouping
466                                 }
467                                 if (subset.size() != 0) { groupings.push_back(subset); }
468                                 
469                                 for (int j = (T->getNumNodes()-1); j >= 0; j--) {
470                                         if ((descendantNodes[i].count(j) == 0) && (distToRoot[j] >= distToRoot[i])) {
471                                                 vector<SharedRAbundFloatVector*> subset;
472                                                 int count = 0;
473                                                 int doneCount = nodeToDescendants[j].size();
474                                                 for (int k = 0; k < lookupFloat.size(); k++) {
475                                                         //is this descendant of j, and we didn't already add this as part of a larger grouping
476                                                         if ((nodeToDescendants[j].count(lookupFloat[k]->getGroup()) != 0) && (groupsAlreadyAdded.count(lookupFloat[k]->getGroup()) == 0)) { 
477                                                                 subset.push_back(lookupFloat[k]);
478                                                                 groupsAlreadyAdded.insert(lookupFloat[k]->getGroup());
479                                                                 count++;
480                                                         }
481                                                         if (count == doneCount) { break; } //quit once you get the rabunds for this grouping
482                                                 }
483                                                 
484                                                 //if subset.size == 0 then the node was added as part of a larger grouping
485                                                 if (subset.size() != 0) { groupings.push_back(subset); }
486                                         }
487                                 }
488                                 
489                                 if (groupsAlreadyAdded.size() != lookupFloat.size()) { m->mothurOut("[ERROR]: could not make proper groupings."); m->mothurOutEndLine(); }
490                                 
491                                 indicatorValues = getValues(groupings);
492                         }
493                         
494                         if (m->control_pressed) { out.close(); return 0; }
495                         
496                         
497                         /******************************************************/
498                         //output indicator values to table form + label tree  //
499                         /*****************************************************/
500                         out << (i+1) << '\t';
501                         for (int j = 0; j < indicatorValues.size(); j++) {
502                                 
503                                 if (m->control_pressed) { out.close(); return 0; }
504                                 
505                                 out << indicatorValues[j] << '\t';
506                         }
507                         out << endl;
508                         
509                         T->tree[i].setLabel((i+1));
510                         
511                 }
512                 out.close();
513         
514                 ofstream outTree;
515                 m->openOutputFile(outputTreeFileName, outTree);
516                 outputNames.push_back(outputTreeFileName); outputTypes["tree"].push_back(outputTreeFileName);
517                 
518                 T->print(outTree, "both");
519                 outTree.close();
520         
521                 return 0;
522         }
523         catch(exception& e) {
524                 m->errorOut(e, "IndicatorCommand", "GetIndicatorSpecies");      
525                 exit(1);
526         }
527 }
528 //**********************************************************************************************************************
529 vector<float> IndicatorCommand::getValues(vector< vector<SharedRAbundFloatVector*> >& groupings){
530         try {
531                 vector<float> values;
532                 
533                 //for each otu
534                 for (int i = 0; i < groupings[0][0]->getNumBins(); i++) {
535                         
536                         if (m->control_pressed) { return values; }
537                         
538                         vector<float> terms; 
539                         float AijDenominator = 0.0;
540                         vector<float> Bij;
541                         //get overall abundance of each grouping
542                         for (int j = 0; j < groupings.size(); j++) {
543                                 
544                                 float totalAbund = 0;
545                                 int numNotZero = 0;
546                                 for (int k = 0; k < groupings[j].size(); k++) { 
547                                         totalAbund += groupings[j][k]->getAbundance(i); 
548                                         if (groupings[j][k]->getAbundance(i) != 0) { numNotZero++; }
549                                 }
550                                 
551                                 float Aij = (totalAbund / (float) groupings[j].size());
552                                 terms.push_back(Aij);
553                                 
554                                 //percentage of sites represented
555                                 Bij.push_back(numNotZero / (float) groupings[j].size());
556                                 
557                                 AijDenominator += Aij;
558                         }
559                         
560                         float maxIndVal = 0.0;
561                         for (int j = 0; j < terms.size(); j++) { 
562                                 float thisAij = (terms[j] / AijDenominator); 
563                                 float thisValue = thisAij * Bij[j] * 100.0;
564                                 
565                                 //save largest
566                                 if (thisValue > maxIndVal) { maxIndVal = thisValue; }
567                         }
568                         
569                         values.push_back(maxIndVal);
570                 }
571                 
572                 return values;
573         }
574         catch(exception& e) {
575                 m->errorOut(e, "IndicatorCommand", "getValues");        
576                 exit(1);
577         }
578 }
579 //**********************************************************************************************************************
580 //same as above, just data type difference
581 vector<float> IndicatorCommand::getValues(vector< vector<SharedRAbundVector*> >& groupings){
582         try {
583                 vector<float> values;
584                 
585         /*for (int j = 0; j < groupings.size(); j++) {          
586                 cout << "grouping " << j << endl;
587                 for (int k = 0; k < groupings[j].size(); k++) { 
588                         cout << groupings[j][k]->getGroup() << endl;
589                 }
590         }*/
591                 //for each otu
592                 for (int i = 0; i < groupings[0][0]->getNumBins(); i++) {
593                         vector<float> terms; 
594                         float AijDenominator = 0.0;
595                         vector<float> Bij;
596                         //get overall abundance of each grouping
597                         for (int j = 0; j < groupings.size(); j++) {
598         
599                                 int totalAbund = 0.0;
600                                 int numNotZero = 0;
601                                 for (int k = 0; k < groupings[j].size(); k++) { 
602                                         totalAbund += groupings[j][k]->getAbundance(i); 
603                                         if (groupings[j][k]->getAbundance(i) != 0.0) { numNotZero++; }
604                                         
605                                 }
606                                         
607                                 float Aij = (totalAbund / (float) groupings[j].size());
608                                 terms.push_back(Aij);
609                                 
610                                 //percentage of sites represented
611                                 Bij.push_back(numNotZero / (float) groupings[j].size());
612                                 
613                                 AijDenominator += Aij;
614                         }
615                         
616                         float maxIndVal = 0.0;
617                         for (int j = 0; j < terms.size(); j++) { 
618                                 float thisAij = (terms[j] / AijDenominator); 
619                                 float thisValue = thisAij * Bij[j] * 100.0;
620                                         
621                                 //save largest
622                                 if (thisValue > maxIndVal) { maxIndVal = thisValue; }
623                         }
624                         
625                         values.push_back(maxIndVal);
626                 }
627                 
628                 return values;
629         }
630         catch(exception& e) {
631                 m->errorOut(e, "IndicatorCommand", "getValues");        
632                 exit(1);
633         }
634 }
635 //**********************************************************************************************************************
636 //you need the distances to root to decide groupings
637 //this will also set branch lengths if the tree does not include them
638 map<int, float> IndicatorCommand::getDistToRoot(Tree*& T){
639         try {
640                 map<int, float> dists;
641                 
642                 bool hasBranchLengths = false;
643                 for (int i = 0; i < T->getNumNodes(); i++) { 
644                         if (T->tree[i].getBranchLength() > 0.0) {  hasBranchLengths = true; break; }
645                 }
646                 
647                 //set branchlengths if needed
648                 if (!hasBranchLengths) { 
649                         for (int i = 0; i < T->getNumNodes(); i++) {
650                                 
651                                 int lc = T->tree[i].getLChild();
652                                 int rc = T->tree[i].getRChild();
653                                 
654                                 if (lc == -1) { // you are a leaf
655                                         //if you are a leaf set you priliminary length to 1.0, this may adjust later
656                                         T->tree[i].setBranchLength(1.0);
657                                         dists[i] = 1.0;
658                                 }else{ // you are an internal node
659                                         //look at your children's length to leaf
660                                         float ldist = dists[lc];
661                                         float rdist = dists[rc];
662                                         
663                                         float greater = ldist;
664                                         if (rdist > greater) { greater = rdist; dists[i] = ldist + 1.0;}
665                                         else { dists[i] = rdist + 1.0; }
666                                         
667                                         
668                                         //branch length = difference + 1
669                                         T->tree[lc].setBranchLength((abs(ldist-greater) + 1.0));
670                                         T->tree[rc].setBranchLength((abs(rdist-greater) + 1.0));
671                                 }
672                         }
673                 }
674                         
675                 dists.clear();
676                 
677                 for (int i = 0; i < T->getNumNodes(); i++) {
678                         
679                         double sum = 0.0;
680                         int index = i;
681                         
682                         while(T->tree[index].getParent() != -1){
683                                 if (T->tree[index].getBranchLength() != -1) {
684                                         sum += abs(T->tree[index].getBranchLength()); 
685                                 }
686                                 index = T->tree[index].getParent();
687                         }
688                         
689                         dists[i] = sum;
690                 }
691                 
692                 return dists;
693         }
694         catch(exception& e) {
695                 m->errorOut(e, "IndicatorCommand", "getLengthToLeaf");  
696                 exit(1);
697         }
698 }
699 //**********************************************************************************************************************
700 set<string> IndicatorCommand::getDescendantList(Tree*& T, int i, map<int, set<string> > descendants, map<int, set<int> >& nodes){
701         try {
702                 set<string> names;
703                 
704                 set<string>::iterator it;
705                 
706                 int lc = T->tree[i].getLChild();
707                 int rc = T->tree[i].getRChild();
708                 
709                 if (lc == -1) { //you are a leaf your only descendant is yourself
710                         set<int> temp; temp.insert(i);
711                         nodes[i] = temp;
712                         
713                         if (designfile == "") {
714                                 names.insert(T->tree[i].getName());
715                         }else {
716                                 vector<string> myGroup; myGroup.push_back(T->tree[i].getName());
717                                 vector<string> myReps = designMap->getNamesSeqs(myGroup);
718                                 for (int k = 0; k < myReps.size(); k++) {
719                                         names.insert(myReps[k]);
720                                 }
721                         }
722                         
723                 }else{ //your descedants are the combination of your childrens descendants
724                         names = descendants[lc];
725                         nodes[i] = nodes[lc];
726                         for (it = descendants[rc].begin(); it != descendants[rc].end(); it++) {
727                                 names.insert(*it);
728                         }
729                         for (set<int>::iterator itNum = nodes[rc].begin(); itNum != nodes[rc].end(); itNum++) {
730                                 nodes[i].insert(*itNum);
731                         }
732                         //you are your own descendant
733                         nodes[i].insert(i);
734                 }
735                 
736                 return names;
737         }
738         catch(exception& e) {
739                 m->errorOut(e, "IndicatorCommand", "getDescendantList");        
740                 exit(1);
741         }
742 }
743 //**********************************************************************************************************************
744 int IndicatorCommand::getShared(){
745         try {
746                 InputData* input = new InputData(sharedfile, "sharedfile");
747                 lookup = input->getSharedRAbundVectors();
748                 string lastLabel = lookup[0]->getLabel();
749                 
750                 if (label == "") { label = lastLabel; delete input; return 0; }
751                 
752                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
753                 set<string> labels; labels.insert(label);
754                 set<string> processedLabels;
755                 set<string> userLabels = labels;
756                 
757                 //as long as you are not at the end of the file or done wih the lines you want
758                 while((lookup[0] != NULL) && (userLabels.size() != 0)) {
759                         if (m->control_pressed) {  delete input; return 0;  }
760                         
761                         if(labels.count(lookup[0]->getLabel()) == 1){
762                                 processedLabels.insert(lookup[0]->getLabel());
763                                 userLabels.erase(lookup[0]->getLabel());
764                                 break;
765                         }
766                         
767                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
768                                 string saveLabel = lookup[0]->getLabel();
769                                 
770                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
771                                 lookup = input->getSharedRAbundVectors(lastLabel);
772                                 
773                                 processedLabels.insert(lookup[0]->getLabel());
774                                 userLabels.erase(lookup[0]->getLabel());
775                                 
776                                 //restore real lastlabel to save below
777                                 lookup[0]->setLabel(saveLabel);
778                                 break;
779                         }
780                         
781                         lastLabel = lookup[0]->getLabel();                      
782                         
783                         //get next line to process
784                         //prevent memory leak
785                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
786                         lookup = input->getSharedRAbundVectors();
787                 }
788                 
789                 
790                 if (m->control_pressed) { delete input; return 0;  }
791                 
792                 //output error messages about any remaining user labels
793                 set<string>::iterator it;
794                 bool needToRun = false;
795                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
796                         m->mothurOut("Your file does not include the label " + *it); 
797                         if (processedLabels.count(lastLabel) != 1) {
798                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
799                                 needToRun = true;
800                         }else {
801                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
802                         }
803                 }
804                 
805                 //run last label if you need to
806                 if (needToRun == true)  {
807                         for (int i = 0; i < lookup.size(); i++) {  if (lookup[i] != NULL) {     delete lookup[i];       } } 
808                         lookup = input->getSharedRAbundVectors(lastLabel);
809                 }       
810                 
811                 delete input;
812                 return 0;
813         }
814         catch(exception& e) {
815                 m->errorOut(e, "IndicatorCommand", "getShared");        
816                 exit(1);
817         }
818 }
819 //**********************************************************************************************************************
820 int IndicatorCommand::getSharedFloat(){
821         try {
822                 InputData* input = new InputData(relabundfile, "relabund");
823                 lookupFloat = input->getSharedRAbundFloatVectors();
824                 string lastLabel = lookupFloat[0]->getLabel();
825                 
826                 if (label == "") { label = lastLabel; delete input; return 0; }
827                 
828                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
829                 set<string> labels; labels.insert(label);
830                 set<string> processedLabels;
831                 set<string> userLabels = labels;
832                 
833                 //as long as you are not at the end of the file or done wih the lines you want
834                 while((lookupFloat[0] != NULL) && (userLabels.size() != 0)) {
835                         
836                         if (m->control_pressed) {  delete input; return 0;  }
837                         
838                         if(labels.count(lookupFloat[0]->getLabel()) == 1){
839                                 processedLabels.insert(lookupFloat[0]->getLabel());
840                                 userLabels.erase(lookupFloat[0]->getLabel());
841                                 break;
842                         }
843                         
844                         if ((m->anyLabelsToProcess(lookupFloat[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
845                                 string saveLabel = lookupFloat[0]->getLabel();
846                                 
847                                 for (int i = 0; i < lookupFloat.size(); i++) {  delete lookupFloat[i];  } 
848                                 lookupFloat = input->getSharedRAbundFloatVectors(lastLabel);
849                                 
850                                 processedLabels.insert(lookupFloat[0]->getLabel());
851                                 userLabels.erase(lookupFloat[0]->getLabel());
852                                 
853                                 //restore real lastlabel to save below
854                                 lookupFloat[0]->setLabel(saveLabel);
855                                 break;
856                         }
857                         
858                         lastLabel = lookupFloat[0]->getLabel();                 
859                         
860                         //get next line to process
861                         //prevent memory leak
862                         for (int i = 0; i < lookupFloat.size(); i++) {  delete lookupFloat[i];  } 
863                         lookupFloat = input->getSharedRAbundFloatVectors();
864                 }
865                 
866                 
867                 if (m->control_pressed) { delete input; return 0;  }
868                 
869                 //output error messages about any remaining user labels
870                 set<string>::iterator it;
871                 bool needToRun = false;
872                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
873                         m->mothurOut("Your file does not include the label " + *it); 
874                         if (processedLabels.count(lastLabel) != 1) {
875                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
876                                 needToRun = true;
877                         }else {
878                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
879                         }
880                 }
881                 
882                 //run last label if you need to
883                 if (needToRun == true)  {
884                         for (int i = 0; i < lookupFloat.size(); i++) {  if (lookupFloat[i] != NULL) {   delete lookupFloat[i];  } } 
885                         lookupFloat = input->getSharedRAbundFloatVectors(lastLabel);
886                 }       
887                 
888                 delete input;
889                 return 0;
890         }
891         catch(exception& e) {
892                 m->errorOut(e, "IndicatorCommand", "getShared");        
893         exit(1);
894         }
895 }               
896 /*****************************************************************/
897
898