]> git.donarmstrong.com Git - mothur.git/blob - removelineagecommand.cpp
changes while setting up test files
[mothur.git] / removelineagecommand.cpp
1 /*
2  *  removelineagecommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 9/24/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "removelineagecommand.h"
11 #include "sequence.hpp"
12 #include "listvector.hpp"
13
14 //**********************************************************************************************************************
15 vector<string> RemoveLineageCommand::setParameters(){   
16         try {
17                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "FNGLT", "none",false,false); parameters.push_back(pfasta);
18                 CommandParameter pname("name", "InputTypes", "", "", "none", "FNGLT", "none",false,false); parameters.push_back(pname);
19                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "FNGLT", "none",false,false); parameters.push_back(pgroup);
20                 CommandParameter plist("list", "InputTypes", "", "", "none", "FNGLT", "none",false,false); parameters.push_back(plist);
21                 CommandParameter ptaxonomy("taxonomy", "InputTypes", "", "", "none", "FNGLT", "none",false,true); parameters.push_back(ptaxonomy);
22                 CommandParameter palignreport("alignreport", "InputTypes", "", "", "none", "FNGLT", "none",false,false); parameters.push_back(palignreport);
23                 CommandParameter ptaxon("taxon", "String", "", "", "", "", "",false,true); parameters.push_back(ptaxon);
24                 CommandParameter pdups("dups", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(pdups);
25                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
26                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
27                 
28                 vector<string> myArray;
29                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
30                 return myArray;
31         }
32         catch(exception& e) {
33                 m->errorOut(e, "RemoveLineageCommand", "setParameters");
34                 exit(1);
35         }
36 }
37 //**********************************************************************************************************************
38 string RemoveLineageCommand::getHelpString(){   
39         try {
40                 string helpString = "";
41                 helpString += "The remove.lineage command reads a taxonomy file and any of the following file types: fasta, name, group, list or alignreport file.\n";
42                 helpString += "It outputs a file containing only the sequences from the taxonomy file that are not from the taxon you requested to be removed.\n";
43                 helpString += "The remove.lineage command parameters are taxon, fasta, name, group, list, taxonomy, alignreport and dups.  You must provide taxonomy unless you have a valid current taxonomy file.\n";
44                 helpString += "The dups parameter allows you to add the entire line from a name file if you add any name from the line. default=false. \n";
45                 helpString += "The taxon parameter allows you to select the taxons you would like to remove, and is required.\n";
46                 helpString += "You may enter your taxons with confidence scores, doing so will remove only those sequences that belong to the taxonomy and whose cofidence scores fall below the scores you give.\n";
47                 helpString += "If they belong to the taxonomy and have confidences above those you provide the sequence will not be removed.\n";
48                 helpString += "The remove.lineage command should be in the following format: remove.lineage(taxonomy=yourTaxonomyFile, taxon=yourTaxons).\n";
49                 helpString += "Example remove.lineage(taxonomy=amazon.silva.taxonomy, taxon=Bacteria;Firmicutes;Bacilli;Lactobacillales;).\n";
50                 helpString += "Note: If you are running mothur in script mode you must wrap the taxon in ' characters so mothur will ignore the ; in the taxon.\n";
51                 helpString += "Example remove.lineage(taxonomy=amazon.silva.taxonomy, taxon='Bacteria;Firmicutes;Bacilli;Lactobacillales;').\n";
52                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
53                 return helpString;
54         }
55         catch(exception& e) {
56                 m->errorOut(e, "RemoveLineageCommand", "getHelpString");
57                 exit(1);
58         }
59 }
60
61
62 //**********************************************************************************************************************
63 RemoveLineageCommand::RemoveLineageCommand(){   
64         try {
65                 abort = true; calledHelp = true; 
66                 setParameters();
67                 vector<string> tempOutNames;
68                 outputTypes["fasta"] = tempOutNames;
69                 outputTypes["taxonomy"] = tempOutNames;
70                 outputTypes["name"] = tempOutNames;
71                 outputTypes["group"] = tempOutNames;
72                 outputTypes["alignreport"] = tempOutNames;
73                 outputTypes["list"] = tempOutNames;
74         }
75         catch(exception& e) {
76                 m->errorOut(e, "RemoveLineageCommand", "RemoveLineageCommand");
77                 exit(1);
78         }
79 }
80 //**********************************************************************************************************************
81 RemoveLineageCommand::RemoveLineageCommand(string option)  {
82         try {
83                 abort = false; calledHelp = false;   
84                                 
85                 //allow user to run help
86                 if(option == "help") { help(); abort = true; calledHelp = true; }
87                 
88                 else {
89                         vector<string> myArray = setParameters();       
90                         
91                         OptionParser parser(option);
92                         map<string,string> parameters = parser.getParameters();
93                         
94                         ValidParameters validParameter;
95                         map<string,string>::iterator it;
96                         
97                         //check to make sure all parameters are valid for command
98                         for (it = parameters.begin(); it != parameters.end(); it++) { 
99                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
100                         }
101                         
102                         //initialize outputTypes
103                         vector<string> tempOutNames;
104                         outputTypes["fasta"] = tempOutNames;
105                         outputTypes["taxonomy"] = tempOutNames;
106                         outputTypes["name"] = tempOutNames;
107                         outputTypes["group"] = tempOutNames;
108                         outputTypes["alignreport"] = tempOutNames;
109                         outputTypes["list"] = tempOutNames;
110                         
111                         //if the user changes the output directory command factory will send this info to us in the output parameter 
112                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
113                         
114                         //if the user changes the input directory command factory will send this info to us in the output parameter 
115                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
116                         if (inputDir == "not found"){   inputDir = "";          }
117                         else {
118                                 string path;
119                                 it = parameters.find("alignreport");
120                                 //user has given a template file
121                                 if(it != parameters.end()){ 
122                                         path = m->hasPath(it->second);
123                                         //if the user has not given a path then, add inputdir. else leave path alone.
124                                         if (path == "") {       parameters["alignreport"] = inputDir + it->second;              }
125                                 }
126                                 
127                                 it = parameters.find("fasta");
128                                 //user has given a template file
129                                 if(it != parameters.end()){ 
130                                         path = m->hasPath(it->second);
131                                         //if the user has not given a path then, add inputdir. else leave path alone.
132                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
133                                 }
134                                 
135                                 it = parameters.find("list");
136                                 //user has given a template file
137                                 if(it != parameters.end()){ 
138                                         path = m->hasPath(it->second);
139                                         //if the user has not given a path then, add inputdir. else leave path alone.
140                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
141                                 }
142                                 
143                                 it = parameters.find("name");
144                                 //user has given a template file
145                                 if(it != parameters.end()){ 
146                                         path = m->hasPath(it->second);
147                                         //if the user has not given a path then, add inputdir. else leave path alone.
148                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
149                                 }
150                                 
151                                 it = parameters.find("group");
152                                 //user has given a template file
153                                 if(it != parameters.end()){ 
154                                         path = m->hasPath(it->second);
155                                         //if the user has not given a path then, add inputdir. else leave path alone.
156                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
157                                 }
158                                 
159                                 it = parameters.find("taxonomy");
160                                 //user has given a template file
161                                 if(it != parameters.end()){ 
162                                         path = m->hasPath(it->second);
163                                         //if the user has not given a path then, add inputdir. else leave path alone.
164                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
165                                 }
166                         }
167
168                         
169                         //check for required parameters                 
170                         fastafile = validParameter.validFile(parameters, "fasta", true);
171                         if (fastafile == "not open") { abort = true; }
172                         else if (fastafile == "not found") {  fastafile = "";  }        
173                         
174                         namefile = validParameter.validFile(parameters, "name", true);
175                         if (namefile == "not open") { abort = true; }
176                         else if (namefile == "not found") {  namefile = "";  }  
177                         
178                         groupfile = validParameter.validFile(parameters, "group", true);
179                         if (groupfile == "not open") { abort = true; }
180                         else if (groupfile == "not found") {  groupfile = "";  }        
181                         
182                         alignfile = validParameter.validFile(parameters, "alignreport", true);
183                         if (alignfile == "not open") { abort = true; }
184                         else if (alignfile == "not found") {  alignfile = "";  }
185                         
186                         listfile = validParameter.validFile(parameters, "list", true);
187                         if (listfile == "not open") { abort = true; }
188                         else if (listfile == "not found") {  listfile = "";  }
189                         
190                         taxfile = validParameter.validFile(parameters, "taxonomy", true);
191                         if (taxfile == "not open") { abort = true; }
192                         else if (taxfile == "not found") {              
193                                 taxfile = m->getTaxonomyFile(); 
194                                 if (taxfile != "") { m->mothurOut("Using " + taxfile + " as input file for the taxonomy parameter."); m->mothurOutEndLine(); }
195                                 else {  m->mothurOut("You have no current taxonomy file and the taxonomy parameter is required."); m->mothurOutEndLine(); abort = true; }
196                         }
197                         
198                         string usedDups = "true";
199                         string temp = validParameter.validFile(parameters, "dups", false);      
200                         if (temp == "not found") { 
201                                 if (namefile != "") {  temp = "true";                                   }
202                                 else                            {  temp = "false"; usedDups = "";       }
203                         }
204                         dups = m->isTrue(temp);
205                         
206                         taxons = validParameter.validFile(parameters, "taxon", false);  
207                         if (taxons == "not found") { taxons = "";  m->mothurOut("No taxons given, please correct."); m->mothurOutEndLine();  abort = true;  }
208                         else { 
209                                 //rip off quotes
210                                 if (taxons[0] == '\'') {  taxons = taxons.substr(1); }
211                                 if (taxons[(taxons.length()-1)] == '\'') {  taxons = taxons.substr(0, (taxons.length()-1)); }
212                         }
213                         
214                         
215                         if ((fastafile == "") && (namefile == "") && (groupfile == "") && (alignfile == "") && (listfile == "") && (taxfile == ""))  { m->mothurOut("You must provide one of the following: fasta, name, group, alignreport, taxonomy or listfile."); m->mothurOutEndLine(); abort = true; }
216                 
217                         if ((usedDups != "") && (namefile == "")) {  m->mothurOut("You may only use dups with the name option."); m->mothurOutEndLine();  abort = true; }                       
218
219                 }
220
221         }
222         catch(exception& e) {
223                 m->errorOut(e, "RemoveLineageCommand", "RemoveLineageCommand");
224                 exit(1);
225         }
226 }
227 //**********************************************************************************************************************
228
229 int RemoveLineageCommand::execute(){
230         try {
231                 
232                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
233                 
234                 if (m->control_pressed) { return 0; }
235                 
236                 //read through the correct file and output lines you want to keep
237                 if (taxfile != "")                      {               readTax();              }  //fills the set of names to remove
238                 if (namefile != "")                     {               readName();             }
239                 if (fastafile != "")            {               readFasta();    }
240                 if (groupfile != "")            {               readGroup();    }
241                 if (alignfile != "")            {               readAlign();    }
242                 if (listfile != "")                     {               readList();             }
243                 
244                 
245                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0; }
246                 
247                 if (outputNames.size() != 0) {
248                         m->mothurOutEndLine();
249                         m->mothurOut("Output File Names: "); m->mothurOutEndLine();
250                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
251                         m->mothurOutEndLine();
252                         
253                         //set fasta file as new current fastafile
254                         string current = "";
255                         itTypes = outputTypes.find("fasta");
256                         if (itTypes != outputTypes.end()) {
257                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
258                         }
259                         
260                         itTypes = outputTypes.find("name");
261                         if (itTypes != outputTypes.end()) {
262                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
263                         }
264                         
265                         itTypes = outputTypes.find("group");
266                         if (itTypes != outputTypes.end()) {
267                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
268                         }
269                         
270                         itTypes = outputTypes.find("list");
271                         if (itTypes != outputTypes.end()) {
272                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
273                         }
274                         
275                         itTypes = outputTypes.find("taxonomy");
276                         if (itTypes != outputTypes.end()) {
277                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTaxonomyFile(current); }
278                         }
279                 }
280                 
281                 return 0;               
282         }
283
284         catch(exception& e) {
285                 m->errorOut(e, "RemoveLineageCommand", "execute");
286                 exit(1);
287         }
288 }
289
290 //**********************************************************************************************************************
291 int RemoveLineageCommand::readFasta(){
292         try {
293                 string thisOutputDir = outputDir;
294                 if (outputDir == "") {  thisOutputDir += m->hasPath(fastafile);  }
295                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(fastafile)) + "pick" + m->getExtension(fastafile);
296                 
297                 ofstream out;
298                 m->openOutputFile(outputFileName, out);
299                 
300                 ifstream in;
301                 m->openInputFile(fastafile, in);
302                 string name;
303                 
304                 bool wroteSomething = false;
305                 
306                 while(!in.eof()){
307                         if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
308                         
309                         Sequence currSeq(in);
310                         name = currSeq.getName();
311                         
312                         if (name != "") {
313                                 //if this name is in the accnos file
314                                 if (names.count(name) == 0) {
315                                         wroteSomething = true;
316                                         
317                                         currSeq.printSequence(out);
318                                 }
319                         }
320                         m->gobble(in);
321                 }
322                 in.close();     
323                 out.close();
324                 
325                 if (wroteSomething == false) {  m->mothurOut("Your fasta file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
326                 outputNames.push_back(outputFileName); outputTypes["fasta"].push_back(outputFileName); 
327                 
328                 return 0;
329                 
330         }
331         catch(exception& e) {
332                 m->errorOut(e, "RemoveLineageCommand", "readFasta");
333                 exit(1);
334         }
335 }
336 //**********************************************************************************************************************
337 int RemoveLineageCommand::readList(){
338         try {
339                 string thisOutputDir = outputDir;
340                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
341                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "pick" +  m->getExtension(listfile);
342                 
343                 ofstream out;
344                 m->openOutputFile(outputFileName, out);
345                 
346                 ifstream in;
347                 m->openInputFile(listfile, in);
348                 
349                 bool wroteSomething = false;
350                 
351                 while(!in.eof()){
352                         //read in list vector
353                         ListVector list(in);
354                         
355                         //make a new list vector
356                         ListVector newList;
357                         newList.setLabel(list.getLabel());
358                         
359                         //for each bin
360                         for (int i = 0; i < list.getNumBins(); i++) {
361                                 if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
362                         
363                                 //parse out names that are in accnos file
364                                 string binnames = list.get(i);
365                                 
366                                 string newNames = "";
367                                 while (binnames.find_first_of(',') != -1) { 
368                                         string name = binnames.substr(0,binnames.find_first_of(','));
369                                         binnames = binnames.substr(binnames.find_first_of(',')+1, binnames.length());
370                                         
371                                         //if that name is in the .accnos file, add it
372                                         if (names.count(name) == 0) {  newNames += name + ",";  }
373                                 }
374                         
375                                 //get last name
376                                 if (names.count(binnames) == 0) {  newNames += binnames + ",";  }
377
378                                 //if there are names in this bin add to new list
379                                 if (newNames != "") {  
380                                         newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
381                                         newList.push_back(newNames);    
382                                 }
383                         }
384                                 
385                         //print new listvector
386                         if (newList.getNumBins() != 0) {
387                                 wroteSomething = true;
388                                 newList.print(out);
389                         }
390                         
391                         m->gobble(in);
392                 }
393                 in.close();     
394                 out.close();
395                 
396                 if (wroteSomething == false) {  m->mothurOut("Your list file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
397                 outputNames.push_back(outputFileName); outputTypes["list"].push_back(outputFileName); 
398                                 
399                 return 0;
400
401         }
402         catch(exception& e) {
403                 m->errorOut(e, "RemoveLineageCommand", "readList");
404                 exit(1);
405         }
406 }
407 //**********************************************************************************************************************
408 int RemoveLineageCommand::readName(){
409         try {
410                 string thisOutputDir = outputDir;
411                 if (outputDir == "") {  thisOutputDir += m->hasPath(namefile);  }
412                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(namefile)) + "pick" + m->getExtension(namefile);
413
414                 ofstream out;
415                 m->openOutputFile(outputFileName, out);
416
417                 ifstream in;
418                 m->openInputFile(namefile, in);
419                 string name, firstCol, secondCol;
420                 
421                 bool wroteSomething = false;
422                 
423                 while(!in.eof()){
424                         if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
425
426                         in >> firstCol;                         
427                         in >> secondCol;                        
428
429                         vector<string> parsedNames;
430                         m->splitAtComma(secondCol, parsedNames);
431                         
432                         vector<string> validSecond;  validSecond.clear();
433                         for (int i = 0; i < parsedNames.size(); i++) {
434                                 if (names.count(parsedNames[i]) == 0) {
435                                         validSecond.push_back(parsedNames[i]);
436                                 }
437                         }
438                         
439                         if ((dups) && (validSecond.size() != parsedNames.size())) {  //if dups is true and we want to get rid of anyone, get rid of everyone
440                                 for (int i = 0; i < parsedNames.size(); i++) {  names.insert(parsedNames[i]);  }
441                         }else {
442                                         //if the name in the first column is in the set then print it and any other names in second column also in set
443                                 if (names.count(firstCol) == 0) {
444                                         
445                                         wroteSomething = true;
446                                         
447                                         out << firstCol << '\t';
448                                         
449                                         //you know you have at least one valid second since first column is valid
450                                         for (int i = 0; i < validSecond.size()-1; i++) {  out << validSecond[i] << ',';  }
451                                         out << validSecond[validSecond.size()-1] << endl;
452                                         
453                                         //make first name in set you come to first column and then add the remaining names to second column
454                                 }else {
455                                         
456                                         //you want part of this row
457                                         if (validSecond.size() != 0) {
458                                                 
459                                                 wroteSomething = true;
460                                                 
461                                                 out << validSecond[0] << '\t';
462                                                 
463                                                 //you know you have at least one valid second since first column is valid
464                                                 for (int i = 0; i < validSecond.size()-1; i++) {  out << validSecond[i] << ',';  }
465                                                 out << validSecond[validSecond.size()-1] << endl;
466                                         }
467                                 }
468                         }
469                         m->gobble(in);
470                 }
471                 in.close();
472                 out.close();
473
474                 if (wroteSomething == false) {  m->mothurOut("Your name file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
475                 outputNames.push_back(outputFileName); outputTypes["name"].push_back(outputFileName);
476                                 
477                 return 0;
478         }
479         catch(exception& e) {
480                 m->errorOut(e, "RemoveLineageCommand", "readName");
481                 exit(1);
482         }
483 }
484
485 //**********************************************************************************************************************
486 int RemoveLineageCommand::readGroup(){
487         try {
488                 string thisOutputDir = outputDir;
489                 if (outputDir == "") {  thisOutputDir += m->hasPath(groupfile);  }
490                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "pick" + m->getExtension(groupfile);
491                 
492                 ofstream out;
493                 m->openOutputFile(outputFileName, out);
494
495                 ifstream in;
496                 m->openInputFile(groupfile, in);
497                 string name, group;
498                 
499                 bool wroteSomething = false;
500                 
501                 while(!in.eof()){
502                         if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
503                         
504                         in >> name;                             //read from first column
505                         in >> group;                    //read from second column
506                         
507                         //if this name is in the accnos file
508                         if (names.count(name) == 0) {
509                                 wroteSomething = true;
510                                 out << name << '\t' << group << endl;
511                         }
512                                         
513                         m->gobble(in);
514                 }
515                 in.close();
516                 out.close();
517                 
518                 if (wroteSomething == false) {  m->mothurOut("Your group file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
519                 outputNames.push_back(outputFileName); outputTypes["group"].push_back(outputFileName);
520                 
521                 return 0;
522         }
523         catch(exception& e) {
524                 m->errorOut(e, "RemoveLineageCommand", "readGroup");
525                 exit(1);
526         }
527 }
528 //**********************************************************************************************************************
529 int RemoveLineageCommand::readTax(){
530         try {
531                 string thisOutputDir = outputDir;
532                 if (outputDir == "") {  thisOutputDir += m->hasPath(taxfile);  }
533                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(taxfile)) + "pick" + m->getExtension(taxfile);
534                 ofstream out;
535                 m->openOutputFile(outputFileName, out);
536                 
537                 ifstream in;
538                 m->openInputFile(taxfile, in);
539                 string name, tax;
540                 
541                 bool wroteSomething = false;
542                 
543                 bool taxonsHasConfidence = false;
544                 vector< map<string, float> > searchTaxons;
545                 string noConfidenceTaxons = taxons;
546                 int hasConPos = taxons.find_first_of('(');
547                 if (hasConPos != string::npos) {  
548                         taxonsHasConfidence = true; 
549                         searchTaxons = getTaxons(taxons); 
550                         noConfidenceTaxons = removeConfidences(taxons);
551                 }
552                 
553                 
554                 while(!in.eof()){
555
556                         if (m->control_pressed) { in.close(); out.close(); remove(outputFileName.c_str());  return 0; }
557
558                         in >> name;                             //read from first column
559                         in >> tax;                      //read from second column
560                         
561                         string newtax = tax;
562                         
563                         //if the users file contains confidence scores we want to ignore them when searching for the taxons, unless the taxon has them
564                         if (!taxonsHasConfidence) {
565                                 
566                                 int hasConfidences = tax.find_first_of('(');
567                                 if (hasConfidences != string::npos) { 
568                                         newtax = removeConfidences(tax);
569                                 }
570                                 
571                                 int pos = newtax.find(taxons);
572                                 
573                                 if (pos == string::npos) { 
574                                         wroteSomething = true;
575                                         out << name << '\t' << tax << endl;
576                                 }else{ //this sequence contains the taxon the user wants to remove
577                                         names.insert(name);
578                                 }
579                                 
580                         }else{//if taxons has them and you don't them remove taxons
581                                 int hasConfidences = tax.find_first_of('(');
582                                 if (hasConfidences == string::npos) { 
583                                 
584                                         int pos = newtax.find(noConfidenceTaxons);
585                                         
586                                         if (pos == string::npos) { 
587                                                 wroteSomething = true;
588                                                 out << name << '\t' << tax << endl;
589                                         }else{ //this sequence contains the taxon the user wants to remove
590                                                 names.insert(name);
591                                         }
592                                 }else { //both have confidences so we want to make sure the users confidences are greater then or equal to the taxons
593                                         //first remove confidences from both and see if the taxonomy exists
594                                 
595                                         string noNewTax = tax;
596                                         int hasConfidences = tax.find_first_of('(');
597                                         if (hasConfidences != string::npos) { 
598                                                 noNewTax = removeConfidences(tax);
599                                         }
600                                         
601                                         int pos = noNewTax.find(noConfidenceTaxons);
602                                         
603                                         if (pos != string::npos) { //if yes, then are the confidences okay
604                                                 
605                                                 bool remove = false;
606                                                 vector< map<string, float> > usersTaxon = getTaxons(newtax);
607                                                 
608                                                 //the usersTaxon is most likely longer than the searchTaxons, and searchTaxon[0] may relate to userTaxon[4]
609                                                 //we want to "line them up", so we will find the the index where the searchstring starts
610                                                 int index = 0;
611                                                 for (int i = 0; i < usersTaxon.size(); i++) {
612                                                         
613                                                         if (usersTaxon[i].begin()->first == searchTaxons[0].begin()->first) { 
614                                                                 index = i;  
615                                                                 int spot = 0;
616                                                                 bool goodspot = true;
617                                                                 //is this really the start, or are we dealing with a taxon of the same name?
618                                                                 while ((spot < searchTaxons.size()) && ((i+spot) < usersTaxon.size())) {
619                                                                         if (usersTaxon[i+spot].begin()->first != searchTaxons[spot].begin()->first) { goodspot = false; break; }
620                                                                         else { spot++; }
621                                                                 }
622                                                                 
623                                                                 if (goodspot) { break; }
624                                                         }
625                                                 }
626                                                 
627                                                 for (int i = 0; i < searchTaxons.size(); i++) {
628                                                         
629                                                         if ((i+index) < usersTaxon.size()) { //just in case, should never be false
630                                                                 if (usersTaxon[i+index].begin()->second < searchTaxons[i].begin()->second) { //is the users cutoff less than the search taxons
631                                                                         remove = true;
632                                                                         break;
633                                                                 }
634                                                         }else {
635                                                                 remove = true;
636                                                                 break;
637                                                         }
638                                                 }
639                                                 
640                                                 //passed the test so remove you
641                                                 if (remove) {
642                                                         names.insert(name);
643                                                 }else {
644                                                         wroteSomething = true;
645                                                         out << name << '\t' << tax << endl;
646                                                 }
647                                         }else {
648                                                 wroteSomething = true;
649                                                 out << name << '\t' << tax << endl;
650                                         }
651                                 }
652                         }
653                         
654                         
655                         
656                         
657                         m->gobble(in);
658                 }
659                 in.close();
660                 out.close();
661                 
662                 if (!wroteSomething) { m->mothurOut("Your taxonomy file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
663                 outputNames.push_back(outputFileName); outputTypes["taxonomy"].push_back(outputFileName);
664                         
665                 return 0;
666
667         }
668         catch(exception& e) {
669                 m->errorOut(e, "RemoveLineageCommand", "readTax");
670                 exit(1);
671         }
672 }
673 /**************************************************************************************************/
674 vector< map<string, float> > RemoveLineageCommand::getTaxons(string tax) {
675         try {
676                 
677                 vector< map<string, float> > t;
678                 string taxon = "";
679                 int taxLength = tax.length();
680                 for(int i=0;i<taxLength;i++){
681                         if(tax[i] == ';'){
682                                 
683                                 int openParen = taxon.find_first_of('(');
684                                 int closeParen = taxon.find_last_of(')');
685                                 
686                                 string newtaxon, confidence;
687                                 if ((openParen != string::npos) && (closeParen != string::npos)) {
688                                         newtaxon = taxon.substr(0, openParen); //rip off confidence
689                                         confidence = taxon.substr((openParen+1), (closeParen-openParen-1));  
690                                 }else{
691                                         newtaxon = taxon;
692                                         confidence = "0";
693                                 }
694                                 float con = 0;
695                                 convert(confidence, con);
696                                 
697                                 map<string, float> temp;
698                                 temp[newtaxon] = con;
699                                 t.push_back(temp);
700                                 
701                                 taxon = "";
702                         }
703                         else{
704                                 taxon += tax[i];
705                         }
706                 }
707                 
708                 return t;
709         }
710         catch(exception& e) {
711                 m->errorOut(e, "RemoveLineageCommand", "getTaxons");
712                 exit(1);
713         }
714 }
715 /**************************************************************************************************/
716 string RemoveLineageCommand::removeConfidences(string tax) {
717         try {
718                 
719                 string taxon = "";
720                 int taxLength = tax.length();
721                 for(int i=0;i<taxLength;i++){
722                         if(tax[i] == ';'){
723                                 taxon = taxon.substr(0, taxon.find_first_of('(')); //rip off confidence
724                                 taxon += ";";
725                         }
726                         else{
727                                 taxon += tax[i];
728                         }
729                 }
730                                 
731                 return taxon;
732         }
733         catch(exception& e) {
734                 m->errorOut(e, "RemoveLineageCommand", "removeConfidences");
735                 exit(1);
736         }
737 }
738 //**********************************************************************************************************************
739 //alignreport file has a column header line then all other lines contain 16 columns.  we just want the first column since that contains the name
740 int RemoveLineageCommand::readAlign(){
741         try {
742                 string thisOutputDir = outputDir;
743                 if (outputDir == "") {  thisOutputDir += m->hasPath(alignfile);  }
744                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(alignfile)) + "pick.align.report";
745                 
746                 ofstream out;
747                 m->openOutputFile(outputFileName, out);
748
749                 ifstream in;
750                 m->openInputFile(alignfile, in);
751                 string name, junk;
752                 
753                 bool wroteSomething = false;
754                 
755                 //read column headers
756                 for (int i = 0; i < 16; i++) {  
757                         if (!in.eof())  {       in >> junk;      out << junk << '\t';   }
758                         else                    {       break;                  }
759                 }
760                 out << endl;
761                 
762                 while(!in.eof()){
763                         if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
764                         
765                         in >> name;                             //read from first column
766                         
767                         //if this name is in the accnos file
768                         if (names.count(name) == 0) {
769                                 wroteSomething = true;
770                                 
771                                 out << name << '\t';
772                                 
773                                 //read rest
774                                 for (int i = 0; i < 15; i++) {  
775                                         if (!in.eof())  {       in >> junk;      out << junk << '\t';   }
776                                         else                    {       break;                  }
777                                 }
778                                 out << endl;
779                                 
780                         }else {//still read just don't do anything with it
781                                 
782                                 //read rest
783                                 for (int i = 0; i < 15; i++) {  
784                                         if (!in.eof())  {       in >> junk;             }
785                                         else                    {       break;                  }
786                                 }
787                         }
788                         
789                         m->gobble(in);
790                 }
791                 in.close();
792                 out.close();
793                 
794                 if (wroteSomething == false) {  m->mothurOut("Your align file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
795                 outputNames.push_back(outputFileName); outputTypes["alignreport"].push_back(outputFileName);
796                 
797                 return 0;
798                 
799         }
800         catch(exception& e) {
801                 m->errorOut(e, "RemoveLineageCommand", "readAlign");
802                 exit(1);
803         }
804 }
805 //**********************************************************************************************************************
806