]> git.donarmstrong.com Git - mothur.git/blob - summarycommand.cpp
changes while testing
[mothur.git] / summarycommand.cpp
1 /*
2  *  summarycommand.cpp
3  *  Dotur
4  *
5  *  Created by Sarah Westcott on 1/2/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "summarycommand.h"
11 #include "ace.h"
12 #include "sobs.h"
13 #include "nseqs.h"
14 #include "chao1.h"
15 #include "bootstrap.h"
16 #include "simpson.h"
17 #include "simpsoneven.h"
18 #include "invsimpson.h"
19 #include "npshannon.h"
20 #include "shannon.h"
21 #include "heip.h"
22 #include "smithwilson.h"
23 #include "shannoneven.h"
24 #include "jackknife.h"
25 #include "geom.h"
26 #include "logsd.h"
27 #include "qstat.h"
28 #include "bergerparker.h"
29 #include "bstick.h"
30 #include "goodscoverage.h"
31 #include "coverage.h"
32 #include "efron.h"
33 #include "boneh.h"
34 #include "solow.h"
35 #include "shen.h"
36 #include "subsample.h"
37
38 //**********************************************************************************************************************
39 vector<string> SummaryCommand::setParameters(){ 
40         try {
41                 CommandParameter plist("list", "InputTypes", "", "", "LRSS", "LRSS", "none","summary",false,false,true); parameters.push_back(plist);
42                 CommandParameter prabund("rabund", "InputTypes", "", "", "LRSS", "LRSS", "none","summary",false,false); parameters.push_back(prabund);
43                 CommandParameter psabund("sabund", "InputTypes", "", "", "LRSS", "LRSS", "none","summary",false,false); parameters.push_back(psabund);
44                 CommandParameter pshared("shared", "InputTypes", "", "", "LRSS", "LRSS", "none","summary",false,false,true); parameters.push_back(pshared);
45         CommandParameter psubsample("subsample", "String", "", "", "", "", "","",false,false); parameters.push_back(psubsample);
46         CommandParameter piters("iters", "Number", "", "1000", "", "", "","",false,false); parameters.push_back(piters);
47                 CommandParameter plabel("label", "String", "", "", "", "", "","",false,false); parameters.push_back(plabel);
48                 CommandParameter pcalc("calc", "Multiple", "sobs-chao-nseqs-coverage-ace-jack-shannon-shannoneven-npshannon-heip-smithwilson-simpson-simpsoneven-invsimpson-bootstrap-geometric-qstat-logseries-bergerparker-bstick-goodscoverage-efron-boneh-solow-shen", "sobs-chao-ace-jack-shannon-npshannon-simpson", "", "", "","",true,false,true); parameters.push_back(pcalc);
49                 CommandParameter pabund("abund", "Number", "", "10", "", "", "","",false,false); parameters.push_back(pabund);
50                 CommandParameter psize("size", "Number", "", "0", "", "", "","",false,false); parameters.push_back(psize);
51                 CommandParameter pgroupmode("groupmode", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(pgroupmode);
52                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
53                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
54                 
55                 vector<string> myArray;
56                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
57                 return myArray;
58         }
59         catch(exception& e) {
60                 m->errorOut(e, "SummaryCommand", "setParameters");
61                 exit(1);
62         }
63 }
64 //**********************************************************************************************************************
65 string SummaryCommand::getHelpString(){ 
66         try {
67                 string helpString = "";
68                 ValidCalculators validCalculator;
69                 helpString += "The summary.single command parameters are list, sabund, rabund, shared, subsample, iters, label, calc, abund and groupmode.  list, sabund, rabund or shared is required unless you have a valid current file.\n";
70                 helpString += "The summary.single command should be in the following format: \n";
71                 helpString += "summary.single(label=yourLabel, calc=yourEstimators).\n";
72                 helpString += "Example summary.single(label=unique-.01-.03, calc=sobs-chao-ace-jack-bootstrap-shannon-npshannon-simpson).\n";
73                 helpString += validCalculator.printCalc("summary");
74         helpString += "The subsample parameter allows you to enter the size of the sample or you can set subsample=T and mothur will use the size of your smallest group in the case of a shared file. With a list, sabund or rabund file you must provide a subsample size.\n";
75         helpString += "The iters parameter allows you to choose the number of times you would like to run the subsample.\n";
76                 helpString += "The default value calc is sobs-chao-ace-jack-shannon-npshannon-simpson\n";
77                 helpString += "If you are running summary.single with a shared file and would like your summary results collated in one file, set groupmode=t. (Default=true).\n";
78                 helpString += "The label parameter is used to analyze specific labels in your input.\n";
79                 helpString += "Note: No spaces between parameter labels (i.e. label), '=' and parameters (i.e.yourLabels).\n";
80                 return helpString;
81         }
82         catch(exception& e) {
83                 m->errorOut(e, "SummaryCommand", "getHelpString");
84                 exit(1);
85         }
86 }
87 //**********************************************************************************************************************
88 string SummaryCommand::getOutputPattern(string type) {
89     try {
90         string pattern = "";
91         
92         if (type == "summary") {  pattern = "[filename],summary-[filename],[tag],summary"; } 
93         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
94         
95         return pattern;
96     }
97     catch(exception& e) {
98         m->errorOut(e, "SummaryCommand", "getOutputPattern");
99         exit(1);
100     }
101 }
102 //**********************************************************************************************************************
103 SummaryCommand::SummaryCommand(){       
104         try {
105                 abort = true; calledHelp = true; 
106                 setParameters();
107                 vector<string> tempOutNames;
108                 outputTypes["summary"] = tempOutNames;
109         }
110         catch(exception& e) {
111                 m->errorOut(e, "SummaryCommand", "SummaryCommand");
112                 exit(1);
113         }
114 }
115 //**********************************************************************************************************************
116
117 SummaryCommand::SummaryCommand(string option)  {
118         try {
119                 abort = false; calledHelp = false;   
120                 allLines = 1;
121                                 
122                 //allow user to run help
123                 if(option == "help") {  help();  abort = true; calledHelp = true; }
124                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
125                 
126                 else {
127                         vector<string> myArray = setParameters();
128                         
129                         OptionParser parser(option);
130                         map<string,string> parameters = parser.getParameters();
131                         map<string,string>::iterator it;
132                         
133                         ValidParameters validParameter;
134                         
135                         //check to make sure all parameters are valid for command
136                         for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) { 
137                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
138                         }
139                         
140                         //initialize outputTypes
141                         vector<string> tempOutNames;
142                         outputTypes["summary"] = tempOutNames;
143                         
144                         //if the user changes the input directory command factory will send this info to us in the output parameter 
145                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
146                         if (inputDir == "not found"){   inputDir = "";          }
147                         else {
148                                 string path;
149                                 it = parameters.find("shared");
150                                 //user has given a template file
151                                 if(it != parameters.end()){ 
152                                         path = m->hasPath(it->second);
153                                         //if the user has not given a path then, add inputdir. else leave path alone.
154                                         if (path == "") {       parameters["shared"] = inputDir + it->second;           }
155                                 }
156                                 
157                                 it = parameters.find("rabund");
158                                 //user has given a template file
159                                 if(it != parameters.end()){ 
160                                         path = m->hasPath(it->second);
161                                         //if the user has not given a path then, add inputdir. else leave path alone.
162                                         if (path == "") {       parameters["rabund"] = inputDir + it->second;           }
163                                 }
164                                 
165                                 it = parameters.find("sabund");
166                                 //user has given a template file
167                                 if(it != parameters.end()){ 
168                                         path = m->hasPath(it->second);
169                                         //if the user has not given a path then, add inputdir. else leave path alone.
170                                         if (path == "") {       parameters["sabund"] = inputDir + it->second;           }
171                                 }
172                                 
173                                 it = parameters.find("list");
174                                 //user has given a template file
175                                 if(it != parameters.end()){ 
176                                         path = m->hasPath(it->second);
177                                         //if the user has not given a path then, add inputdir. else leave path alone.
178                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
179                                 }
180                         }
181                         
182                         //check for required parameters
183                         listfile = validParameter.validFile(parameters, "list", true);
184                         if (listfile == "not open") { listfile = ""; abort = true; }
185                         else if (listfile == "not found") { listfile = ""; }
186                         else {  format = "list"; inputfile = listfile; m->setListFile(listfile); }
187                         
188                         sabundfile = validParameter.validFile(parameters, "sabund", true);
189                         if (sabundfile == "not open") { sabundfile = ""; abort = true; }        
190                         else if (sabundfile == "not found") { sabundfile = ""; }
191                         else {  format = "sabund"; inputfile = sabundfile; m->setSabundFile(sabundfile); }
192                         
193                         rabundfile = validParameter.validFile(parameters, "rabund", true);
194                         if (rabundfile == "not open") { rabundfile = ""; abort = true; }        
195                         else if (rabundfile == "not found") { rabundfile = ""; }
196                         else {  format = "rabund"; inputfile = rabundfile; m->setRabundFile(rabundfile); }
197                         
198                         sharedfile = validParameter.validFile(parameters, "shared", true);
199                         if (sharedfile == "not open") { sharedfile = ""; abort = true; }        
200                         else if (sharedfile == "not found") { sharedfile = ""; }
201                         else {  format = "sharedfile"; inputfile = sharedfile; m->setSharedFile(sharedfile); }
202                         
203                         if ((sharedfile == "") && (listfile == "") && (rabundfile == "") && (sabundfile == "")) { 
204                                 //is there are current file available for any of these?
205                                 //give priority to shared, then list, then rabund, then sabund
206                                 //if there is a current shared file, use it
207                                 sharedfile = m->getSharedFile(); 
208                                 if (sharedfile != "") { inputfile = sharedfile; format = "sharedfile"; m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
209                                 else { 
210                                         listfile = m->getListFile(); 
211                                         if (listfile != "") { inputfile = listfile; format = "list"; m->mothurOut("Using " + listfile + " as input file for the list parameter."); m->mothurOutEndLine(); }
212                                         else { 
213                                                 rabundfile = m->getRabundFile(); 
214                                                 if (rabundfile != "") { inputfile = rabundfile; format = "rabund"; m->mothurOut("Using " + rabundfile + " as input file for the rabund parameter."); m->mothurOutEndLine(); }
215                                                 else { 
216                                                         sabundfile = m->getSabundFile(); 
217                                                         if (sabundfile != "") { inputfile = sabundfile; format = "sabund"; m->mothurOut("Using " + sabundfile + " as input file for the sabund parameter."); m->mothurOutEndLine(); }
218                                                         else { 
219                                                                 m->mothurOut("No valid current files. You must provide a list, sabund, rabund or shared file before you can use the collect.single command."); m->mothurOutEndLine(); 
220                                                                 abort = true;
221                                                         }
222                                                 }
223                                         }
224                                 }
225                         }
226                         
227                         //if the user changes the output directory command factory will send this info to us in the output parameter 
228                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = m->hasPath(inputfile);              }
229
230                         //check for optional parameter and set defaults
231                         // ...at some point should added some additional type checking...
232                         label = validParameter.validFile(parameters, "label", false);                   
233                         if (label == "not found") { label = ""; }
234                         else { 
235                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
236                                 else { allLines = 1;  }
237                         }
238                                 
239                         calc = validParameter.validFile(parameters, "calc", false);                     
240                         if (calc == "not found") { calc = "sobs-chao-ace-jack-shannon-npshannon-simpson";  }
241                         else { 
242                                  if (calc == "default")  {  calc = "sobs-chao-ace-jack-shannon-npshannon-simpson";  }
243                         }
244                         m->splitAtDash(calc, Estimators);
245                         if (m->inUsersGroups("citation", Estimators)) { 
246                                 ValidCalculators validCalc; validCalc.printCitations(Estimators); 
247                                 //remove citation from list of calcs
248                                 for (int i = 0; i < Estimators.size(); i++) { if (Estimators[i] == "citation") {  Estimators.erase(Estimators.begin()+i); break; } }
249                         }
250
251                         string temp;
252                         temp = validParameter.validFile(parameters, "abund", false);            if (temp == "not found") { temp = "10"; }
253                         m->mothurConvert(temp, abund); 
254                         
255                         temp = validParameter.validFile(parameters, "size", false);                     if (temp == "not found") { temp = "0"; }
256                         m->mothurConvert(temp, size); 
257                         
258                         temp = validParameter.validFile(parameters, "groupmode", false);                if (temp == "not found") { temp = "T"; }
259                         groupMode = m->isTrue(temp);
260                         
261             temp = validParameter.validFile(parameters, "iters", false);                        if (temp == "not found") { temp = "1000"; }
262                         m->mothurConvert(temp, iters);
263             
264             temp = validParameter.validFile(parameters, "subsample", false);            if (temp == "not found") { temp = "F"; }
265                         if (m->isNumeric1(temp)) { m->mothurConvert(temp, subsampleSize); subsample = true; }
266             else {  
267                 if (m->isTrue(temp)) { subsample = true; subsampleSize = -1; }  //we will set it to smallest group later 
268                 else { subsample = false; subsampleSize = -1; }
269             }
270             
271             if (subsample == false) { iters = 0; }
272             else {
273                 //if you did not set a samplesize and are not using a sharedfile
274                 if ((subsampleSize == -1) && (format != "sharedfile"))  { m->mothurOut("[ERROR]: If you want to subsample with a list, rabund or sabund file, you must provide the sample size.  You can do this by setting subsample=yourSampleSize.\n");  abort=true; }
275             }
276
277                 }
278         }
279         catch(exception& e) {
280                 m->errorOut(e, "SummaryCommand", "SummaryCommand");
281                 exit(1);
282         }
283 }
284 //**********************************************************************************************************************
285
286 int SummaryCommand::execute(){
287         try {
288         
289                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
290                 
291                 if ((format != "sharedfile")) { inputFileNames.push_back(inputfile);  }
292                 else {  inputFileNames = parseSharedFile(sharedfile);  format = "rabund"; }
293                 
294                 if (m->control_pressed) { return 0; }
295                 
296                 int numLines = 0;
297                 int numCols = 0;
298                 map<string, string> groupIndex;
299         
300                 for (int p = 0; p < inputFileNames.size(); p++) {
301                         
302                         numLines = 0;
303                         numCols = 0;
304                         
305             map<string, string> variables; 
306             variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(inputFileNames[p]));
307                         string fileNameRoot = getOutputFileName("summary",variables);
308             variables["[tag]"] = "ave-std";
309             string fileNameAve = getOutputFileName("summary",variables);
310             outputNames.push_back(fileNameRoot); outputTypes["summary"].push_back(fileNameRoot);
311             
312                         if (inputFileNames.size() > 1) {
313                                 m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[p]); m->mothurOutEndLine(); m->mothurOutEndLine();
314                 groupIndex[fileNameRoot] = groups[p];
315                         }
316                         
317                         sumCalculators.clear();
318                         
319                         ValidCalculators validCalculator;
320                         
321                         for (int i=0; i<Estimators.size(); i++) {
322                                 if (validCalculator.isValidCalculator("summary", Estimators[i]) == true) { 
323                                         if(Estimators[i] == "sobs"){
324                                                 sumCalculators.push_back(new Sobs());
325                                         }else if(Estimators[i] == "chao"){
326                                                 sumCalculators.push_back(new Chao1());
327                                         }else if(Estimators[i] == "coverage"){
328                                                 sumCalculators.push_back(new Coverage());
329                                         }else if(Estimators[i] == "geometric"){
330                                                 sumCalculators.push_back(new Geom());
331                                         }else if(Estimators[i] == "logseries"){
332                                                 sumCalculators.push_back(new LogSD());
333                                         }else if(Estimators[i] == "qstat"){
334                                                 sumCalculators.push_back(new QStat());
335                                         }else if(Estimators[i] == "bergerparker"){
336                                                 sumCalculators.push_back(new BergerParker());
337                                         }else if(Estimators[i] == "bstick"){
338                                                 sumCalculators.push_back(new BStick());
339                                         }else if(Estimators[i] == "ace"){
340                                                 if(abund < 5)
341                                                         abund = 10;
342                                                 sumCalculators.push_back(new Ace(abund));
343                                         }else if(Estimators[i] == "jack"){
344                                                 sumCalculators.push_back(new Jackknife());
345                                         }else if(Estimators[i] == "shannon"){
346                                                 sumCalculators.push_back(new Shannon());
347                                         }else if(Estimators[i] == "shannoneven"){
348                                                 sumCalculators.push_back(new ShannonEven());
349                                         }else if(Estimators[i] == "npshannon"){
350                                                 sumCalculators.push_back(new NPShannon());
351                                         }else if(Estimators[i] == "heip"){
352                                                 sumCalculators.push_back(new Heip());
353                                         }else if(Estimators[i] == "smithwilson"){
354                                                 sumCalculators.push_back(new SmithWilson());
355                                         }else if(Estimators[i] == "simpson"){
356                                                 sumCalculators.push_back(new Simpson());
357                                         }else if(Estimators[i] == "simpsoneven"){
358                                                 sumCalculators.push_back(new SimpsonEven());
359                                         }else if(Estimators[i] == "invsimpson"){
360                                                 sumCalculators.push_back(new InvSimpson());
361                                         }else if(Estimators[i] == "bootstrap"){
362                                                 sumCalculators.push_back(new Bootstrap());
363                                         }else if (Estimators[i] == "nseqs") { 
364                                                 sumCalculators.push_back(new NSeqs());
365                                         }else if (Estimators[i] == "goodscoverage") { 
366                                                 sumCalculators.push_back(new GoodsCoverage());
367                                         }else if (Estimators[i] == "efron") { 
368                                                 sumCalculators.push_back(new Efron(size));
369                                         }else if (Estimators[i] == "boneh") { 
370                                                 sumCalculators.push_back(new Boneh(size));
371                                         }else if (Estimators[i] == "solow") { 
372                                                 sumCalculators.push_back(new Solow(size));
373                                         }else if (Estimators[i] == "shen") { 
374                                                 sumCalculators.push_back(new Shen(size, abund));
375                                         }
376                                 }
377                         }
378                         
379                         //if the users entered no valid calculators don't execute command
380                         if (sumCalculators.size() == 0) {  for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]);  } return 0; }
381                         
382                         ofstream outputFileHandle;
383                         m->openOutputFile(fileNameRoot, outputFileHandle);
384                         outputFileHandle << "label";
385             
386             ofstream outAve;
387             if (subsample) {
388                 m->openOutputFile(fileNameAve, outAve);
389                 outputNames.push_back(fileNameAve); outputTypes["summary"].push_back(fileNameAve);
390                 outAve << "label\tmethod"; 
391                 outAve.setf(ios::fixed, ios::floatfield); outAve.setf(ios::showpoint);
392                 if (inputFileNames.size() > 1) {
393                     groupIndex[fileNameAve] = groups[p];
394                 }
395             }
396                 
397                         input = new InputData(inputFileNames[p], format);
398                         sabund = input->getSAbundVector();
399                         string lastLabel = sabund->getLabel();
400                 
401                         for(int i=0;i<sumCalculators.size();i++){
402                                 if(sumCalculators[i]->getCols() == 1){
403                                         outputFileHandle << '\t' << sumCalculators[i]->getName();
404                     if (subsample) { outAve << '\t' << sumCalculators[i]->getName();  }
405                                         numCols++;
406                                 }
407                                 else{
408                                         outputFileHandle << '\t' << sumCalculators[i]->getName() << "\t" << sumCalculators[i]->getName() << "_lci\t" << sumCalculators[i]->getName() << "_hci";
409                     if (subsample) { outAve << '\t' << sumCalculators[i]->getName() << "\t" << sumCalculators[i]->getName() << "_lci\t" << sumCalculators[i]->getName() << "_hci";  }
410                                         numCols += 3;
411                                 }
412                         }
413                         outputFileHandle << endl;
414             if (subsample) {  outAve << endl; }
415                         
416                         //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
417                         set<string> processedLabels;
418                         set<string> userLabels = labels;
419                         
420             
421             
422                         if (m->control_pressed) {  outputFileHandle.close(); outAve.close(); for (int i = 0; i < outputNames.size(); i++) {     m->mothurRemove(outputNames[i]);  } for(int i=0;i<sumCalculators.size();i++){  delete sumCalculators[i]; }  delete sabund;  delete input;  return 0;  }
423                         
424                         while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
425                                 
426                                 if (m->control_pressed) { outputFileHandle.close(); outAve.close();  for (int i = 0; i < outputNames.size(); i++) {     m->mothurRemove(outputNames[i]);  } for(int i=0;i<sumCalculators.size();i++){  delete sumCalculators[i]; }  delete sabund;  delete input;  return 0;  }
427                                 
428                                 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){                     
429                                         
430                                         m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
431                                         processedLabels.insert(sabund->getLabel());
432                                         userLabels.erase(sabund->getLabel());
433                                         
434                     process(sabund, outputFileHandle, outAve);
435                     
436                     if (m->control_pressed) { outputFileHandle.close(); outAve.close();  for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]);  } for(int i=0;i<sumCalculators.size();i++){  delete sumCalculators[i]; }  delete sabund;  delete input;  return 0;  }
437                                         numLines++;
438                                 }
439                                 
440                                 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
441                                         string saveLabel = sabund->getLabel();
442                                         
443                                         delete sabund;
444                                         sabund = input->getSAbundVector(lastLabel);
445                                         
446                                         m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
447                                         processedLabels.insert(sabund->getLabel());
448                                         userLabels.erase(sabund->getLabel());
449                                         
450                     process(sabund, outputFileHandle, outAve);
451                     
452                     if (m->control_pressed) { outputFileHandle.close(); outAve.close(); for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  } for(int i=0;i<sumCalculators.size();i++){  delete sumCalculators[i]; }  delete sabund;  delete input;  return 0;  }
453                                         numLines++;
454                                         
455                                         //restore real lastlabel to save below
456                                         sabund->setLabel(saveLabel);
457                                 }               
458                                 
459                                 lastLabel = sabund->getLabel();                 
460                                 
461                                 delete sabund;
462                                 sabund = input->getSAbundVector();
463                         }
464                         
465                         if (m->control_pressed) {  outputFileHandle.close(); outAve.close();  for (int i = 0; i < outputNames.size(); i++) {    m->mothurRemove(outputNames[i]);  } for(int i=0;i<sumCalculators.size();i++){  delete sumCalculators[i]; }   delete input;  return 0;  }
466
467                         //output error messages about any remaining user labels
468                         set<string>::iterator it;
469                         bool needToRun = false;
470                         for (it = userLabels.begin(); it != userLabels.end(); it++) {  
471                                 m->mothurOut("Your file does not include the label " + *it); 
472                                 if (processedLabels.count(lastLabel) != 1) {
473                                         m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
474                                         needToRun = true;
475                                 }else {
476                                         m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
477                                 }
478                         }
479                         
480                         //run last label if you need to
481                         if (needToRun == true)  {
482                                 if (sabund != NULL) {   delete sabund;  }
483                                 sabund = input->getSAbundVector(lastLabel);
484                                 
485                                 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
486                 process(sabund, outputFileHandle, outAve);
487                 
488                 if (m->control_pressed) { outputFileHandle.close(); outAve.close(); for (int i = 0; i < outputNames.size(); i++) {      m->mothurRemove(outputNames[i]);  } for(int i=0;i<sumCalculators.size();i++){  delete sumCalculators[i]; }  delete sabund;  delete input;  return 0;  }
489                                 numLines++;
490                                 delete sabund;
491                         }
492                         
493                         outputFileHandle.close();
494             if (subsample) { outAve.close(); }
495                         
496                         if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]);  } for(int i=0;i<sumCalculators.size();i++){  delete sumCalculators[i]; }   delete input;  return 0;  }
497
498                         
499                         delete input;  
500                         for(int i=0;i<sumCalculators.size();i++){  delete sumCalculators[i]; }
501                 }
502                 
503                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);  }  return 0;  }
504                 
505                 //create summary file containing all the groups data for each label - this function just combines the info from the files already created.
506                 if ((sharedfile != "") && (groupMode)) {   vector<string> comboNames = createGroupSummaryFile(numLines, numCols, outputNames, groupIndex);  for (int i = 0; i < comboNames.size(); i++) { outputNames.push_back(comboNames[i]); } }
507                 
508                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);  }  return 0;  }
509                 
510                 m->mothurOutEndLine();
511                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
512                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
513                 m->mothurOutEndLine();
514                 
515                 return 0;
516         }
517         catch(exception& e) {
518                 m->errorOut(e, "SummaryCommand", "execute");
519                 exit(1);
520         }
521 }
522 //**********************************************************************************************************************
523 int SummaryCommand::process(SAbundVector*& sabund, ofstream& outputFileHandle, ofstream& outAve) {
524     try {
525         
526         //calculator -> data -> values
527         vector< vector< vector<double> > >  results; results.resize(sumCalculators.size());
528         
529         outputFileHandle << sabund->getLabel();
530         
531         SubSample sample;
532         for (int thisIter = 0; thisIter < iters+1; thisIter++) {
533             
534             SAbundVector* thisIterSabund = sabund;
535             
536             //we want the summary results for the whole dataset, then the subsampling
537             if ((thisIter > 0) && subsample) { //subsample sabund and run it
538                 //copy sabund since getSample destroys it
539                 RAbundVector rabund = sabund->getRAbundVector();
540                 SAbundVector* newSabund = new SAbundVector();
541                 *newSabund = rabund.getSAbundVector();
542                 
543                 sample.getSample(newSabund, subsampleSize);
544                 thisIterSabund = newSabund;
545             }
546             
547             for(int i=0;i<sumCalculators.size();i++){
548                 vector<double> data = sumCalculators[i]->getValues(thisIterSabund);
549                
550                 if (m->control_pressed) {  return 0;  }
551                 
552                 if (thisIter == 0) {
553                     outputFileHandle << '\t';
554                     sumCalculators[i]->print(outputFileHandle);
555                 }else {
556                     //some of the calc have hci and lci need to make room for that
557                     if (results[i].size() == 0) {  results[i].resize(data.size());  }
558                     //save results for ave and std.
559                     for (int j = 0; j < data.size(); j++) {
560                         if (m->control_pressed) {  return 0;  }
561                         results[i][j].push_back(data[j]); 
562                     }
563                 }
564             }
565             
566             //cleanup memory
567             if ((thisIter > 0) && subsample) { delete thisIterSabund; }
568         }
569         outputFileHandle << endl;
570      
571         if (subsample) {
572             outAve << sabund->getLabel() << '\t' << "ave\t"; 
573             //find ave and std for this label and output
574             //will need to modify the createGroupSummary to combine results and not mess with the .summary file.
575             
576             //calcs -> values
577             vector< vector<double> >  calcAverages; calcAverages.resize(sumCalculators.size()); 
578             for (int i = 0; i < calcAverages.size(); i++) {  calcAverages[i].resize(results[i].size(), 0);  }
579             
580             for (int thisIter = 0; thisIter < iters; thisIter++) { //sum all groups dists for each calculator
581                 for (int i = 0; i < calcAverages.size(); i++) {  //initialize sums to zero.
582                     for (int j = 0; j < calcAverages[i].size(); j++) {
583                         calcAverages[i][j] += results[i][j][thisIter];
584                     }
585                 }
586             }
587             
588             for (int i = 0; i < calcAverages.size(); i++) {  //finds average.
589                 for (int j = 0; j < calcAverages[i].size(); j++) {
590                     calcAverages[i][j] /= (float) iters;
591                     outAve << calcAverages[i][j] << '\t';
592                 }
593             }
594             
595             //find standard deviation
596             vector< vector<double>  > stdDev; stdDev.resize(sumCalculators.size());
597             for (int i = 0; i < stdDev.size(); i++) {  stdDev[i].resize(results[i].size(), 0);  }
598             
599             for (int thisIter = 0; thisIter < iters; thisIter++) { //compute the difference of each dist from the mean, and square the result of each
600                 for (int i = 0; i < stdDev.size(); i++) {  
601                     for (int j = 0; j < stdDev[i].size(); j++) {
602                         stdDev[i][j] += ((results[i][j][thisIter] - calcAverages[i][j]) * (results[i][j][thisIter] - calcAverages[i][j]));
603                     }
604                 }
605             }
606             
607             outAve << endl << sabund->getLabel() << '\t' << "std\t"; 
608             for (int i = 0; i < stdDev.size(); i++) {  //finds average.
609                 for (int j = 0; j < stdDev[i].size(); j++) {
610                     stdDev[i][j] /= (float) iters;
611                     stdDev[i][j] = sqrt(stdDev[i][j]);
612                     outAve << stdDev[i][j] << '\t';
613                 }
614             }
615             outAve << endl;  
616         }
617         
618         return 0;
619     }
620     catch(exception& e) {
621         m->errorOut(e, "SummaryCommand", "process");
622         exit(1);
623     }
624 }
625 //**********************************************************************************************************************
626 vector<string> SummaryCommand::parseSharedFile(string filename) {
627         try {
628                 vector<string> filenames;
629                 
630                 map<string, ofstream*> filehandles;
631                 map<string, ofstream*>::iterator it3;
632                 
633                 input = new InputData(filename, "sharedfile");
634                 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
635                 
636                 string sharedFileRoot = m->getRootName(filename);
637                 
638         /******************************************************/
639         if (subsample) { 
640             if (subsampleSize == -1) { //user has not set size, set size = smallest samples size
641                 subsampleSize = lookup[0]->getNumSeqs();
642                 for (int i = 1; i < lookup.size(); i++) {
643                     int thisSize = lookup[i]->getNumSeqs();
644                     
645                     if (thisSize < subsampleSize) {     subsampleSize = thisSize;       }
646                 }
647             }else {
648                 m->clearGroups();
649                 vector<string> Groups;
650                 vector<SharedRAbundVector*> temp;
651                 for (int i = 0; i < lookup.size(); i++) {
652                     if (lookup[i]->getNumSeqs() < subsampleSize) { 
653                         m->mothurOut(lookup[i]->getGroup() + " contains " + toString(lookup[i]->getNumSeqs()) + ". Eliminating."); m->mothurOutEndLine();
654                         delete lookup[i];
655                     }else { 
656                         Groups.push_back(lookup[i]->getGroup()); 
657                         temp.push_back(lookup[i]);
658                     }
659                 } 
660                 lookup = temp;
661                 m->setGroups(Groups);
662             }
663             
664             if (lookup.size() < 1) { m->mothurOut("You have not provided enough valid groups.  I cannot run the command."); m->mothurOutEndLine(); m->control_pressed = true; delete input; return filenames; }
665         }
666         
667                 
668                 /******************************************************/
669         
670         //clears file before we start to write to it below
671                 for (int i=0; i<lookup.size(); i++) {
672                         m->mothurRemove((sharedFileRoot + lookup[i]->getGroup() + ".rabund"));
673                         filenames.push_back((sharedFileRoot + lookup[i]->getGroup() + ".rabund"));
674                 }
675         
676                 ofstream* temp;
677                 for (int i=0; i<lookup.size(); i++) {
678                         temp = new ofstream;
679                         filehandles[lookup[i]->getGroup()] = temp;
680                         groups.push_back(lookup[i]->getGroup());
681                 }
682
683                 while(lookup[0] != NULL) {
684                 
685                         for (int i = 0; i < lookup.size(); i++) {
686                                 RAbundVector rav = lookup[i]->getRAbundVector();
687                                 m->openOutputFileAppend(sharedFileRoot + lookup[i]->getGroup() + ".rabund", *(filehandles[lookup[i]->getGroup()]));
688                                 rav.print(*(filehandles[lookup[i]->getGroup()]));
689                                 (*(filehandles[lookup[i]->getGroup()])).close();
690                         }
691                 
692                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
693                         lookup = input->getSharedRAbundVectors();
694                 }
695                 
696                 //free memory
697                 for (it3 = filehandles.begin(); it3 != filehandles.end(); it3++) {
698                         delete it3->second;
699                 }
700                 
701                 delete input;
702
703                 return filenames;
704         }
705         catch(exception& e) {
706                 m->errorOut(e, "SummaryCommand", "parseSharedFile");
707                 exit(1);
708         }
709 }
710 //**********************************************************************************************************************
711 vector<string> SummaryCommand::createGroupSummaryFile(int numLines, int numCols, vector<string>& outputNames, map<string, string> groupIndex) {
712         try {
713                                 
714                 //open each groups summary file
715         vector<string> newComboNames;
716                 
717                 map<string, map<string, vector<string> > > files;
718         map<string, string> filesTypesLabels;
719         map<string, int> filesTypesNumLines;
720                 for (int i=0; i<outputNames.size(); i++) {
721                         vector<string> thisFilesLines;
722             
723                         ifstream temp;
724                         m->openInputFile(outputNames[i], temp);
725                         
726                         //read through first line - labels
727             string labelsLine = m->getline(temp);
728             vector<string> theseLabels = m->splitWhiteSpace(labelsLine);
729             
730             string newLabel = "";
731             for (int j = 0; j < theseLabels.size(); j++) { 
732                  if (j == 1) {  newLabel += "group\t" + theseLabels[j] + '\t';
733                 }else{  newLabel += theseLabels[j] + '\t';      }
734             }
735                         
736                         m->gobble(temp);
737                         
738             int stop = numLines;
739             if (theseLabels.size() != numCols+1) {  stop = numLines*2; }
740                         //for each label
741                         for (int k = 0; k < stop; k++) {
742                                 
743                                 string thisLine = "";
744                                 string tempLabel;
745                                         
746                                 for (int j = 0; j < theseLabels.size(); j++) {  
747                                         temp >> tempLabel; 
748                                                 
749                                         //save for later
750                                         if (j == 1) { thisLine += groupIndex[outputNames[i]] + "\t" + tempLabel + "\t"; }
751                                         else{  thisLine += tempLabel + "\t";    }
752                                 }
753                                         
754                                 thisLine += "\n";
755                                 
756                                 thisFilesLines.push_back(thisLine);
757                                         
758                                 m->gobble(temp);
759                         }
760             
761             string extension = m->getExtension(outputNames[i]);
762             if (theseLabels.size() != numCols+1) { extension = ".ave-std" + extension;  }
763             string combineFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + "groups" + extension;
764                         m->mothurRemove(combineFileName); //remove old file
765             filesTypesLabels[extension] = newLabel;
766             filesTypesNumLines[extension] = stop;
767             
768             map<string, map<string, vector<string> > >::iterator itFiles = files.find(extension);
769             if (itFiles != files.end()) { //add new files info to existing type
770                 files[extension][outputNames[i]] = thisFilesLines;
771             }else {
772                 map<string, vector<string> > thisFile;
773                 thisFile[outputNames[i]] = thisFilesLines;
774                 files[extension] = thisFile;
775             }
776                         
777                         temp.close();
778                         m->mothurRemove(outputNames[i]);
779                 }
780                 
781         
782         for (map<string, map<string, vector<string> > >::iterator itFiles = files.begin(); itFiles != files.end(); itFiles++) {
783             
784             if (m->control_pressed) { break; }
785             
786             string extension = itFiles->first;
787             map<string, vector<string> > thisType = itFiles->second;
788             string combineFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + "groups" + extension;
789             newComboNames.push_back(combineFileName);
790             //open combined file
791             ofstream out;
792             m->openOutputFile(combineFileName, out);
793             
794             //output label line to new file
795             out <<  filesTypesLabels[extension] << endl;
796                 
797             //for each label
798             for (int k = 0; k < filesTypesNumLines[extension]; k++) {
799                 
800                 //grab summary data for each group
801                 for (map<string, vector<string> >::iterator itType = thisType.begin(); itType != thisType.end(); itType++) {
802                     out << (itType->second)[k];
803                 }
804             }   
805                 
806             outputNames.clear();
807                 
808             out.close();
809         }
810                 
811                 //return combine file name
812                 return newComboNames;
813                 
814         }
815         catch(exception& e) {
816                 m->errorOut(e, "SummaryCommand", "createGroupSummaryFile");
817                 exit(1);
818         }
819 }
820 //**********************************************************************************************************************