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