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