]> git.donarmstrong.com Git - mothur.git/blob - removelineagecommand.cpp
d3160194fa5bea985ae0fd96e7cad8de3e73020a
[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
16 RemoveLineageCommand::RemoveLineageCommand(string option)  {
17         try {
18                 abort = false;
19                                 
20                 //allow user to run help
21                 if(option == "help") { help(); abort = true; }
22                 
23                 else {
24                         //valid paramters for this command
25                         string Array[] =  {"fasta","name", "group", "alignreport", "taxon", "dups", "list","taxonomy","outputdir","inputdir"};
26                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
27                         
28                         OptionParser parser(option);
29                         map<string,string> parameters = parser.getParameters();
30                         
31                         ValidParameters validParameter;
32                         map<string,string>::iterator it;
33                         
34                         //check to make sure all parameters are valid for command
35                         for (it = parameters.begin(); it != parameters.end(); it++) { 
36                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
37                         }
38                         
39                         //if the user changes the output directory command factory will send this info to us in the output parameter 
40                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
41                         
42                         //if the user changes the input directory command factory will send this info to us in the output parameter 
43                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
44                         if (inputDir == "not found"){   inputDir = "";          }
45                         else {
46                                 string path;
47                                 it = parameters.find("alignreport");
48                                 //user has given a template file
49                                 if(it != parameters.end()){ 
50                                         path = m->hasPath(it->second);
51                                         //if the user has not given a path then, add inputdir. else leave path alone.
52                                         if (path == "") {       parameters["alignreport"] = inputDir + it->second;              }
53                                 }
54                                 
55                                 it = parameters.find("fasta");
56                                 //user has given a template file
57                                 if(it != parameters.end()){ 
58                                         path = m->hasPath(it->second);
59                                         //if the user has not given a path then, add inputdir. else leave path alone.
60                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
61                                 }
62                                 
63                                 it = parameters.find("list");
64                                 //user has given a template file
65                                 if(it != parameters.end()){ 
66                                         path = m->hasPath(it->second);
67                                         //if the user has not given a path then, add inputdir. else leave path alone.
68                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
69                                 }
70                                 
71                                 it = parameters.find("name");
72                                 //user has given a template file
73                                 if(it != parameters.end()){ 
74                                         path = m->hasPath(it->second);
75                                         //if the user has not given a path then, add inputdir. else leave path alone.
76                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
77                                 }
78                                 
79                                 it = parameters.find("group");
80                                 //user has given a template file
81                                 if(it != parameters.end()){ 
82                                         path = m->hasPath(it->second);
83                                         //if the user has not given a path then, add inputdir. else leave path alone.
84                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
85                                 }
86                                 
87                                 it = parameters.find("taxonomy");
88                                 //user has given a template file
89                                 if(it != parameters.end()){ 
90                                         path = m->hasPath(it->second);
91                                         //if the user has not given a path then, add inputdir. else leave path alone.
92                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
93                                 }
94                         }
95
96                         
97                         //check for required parameters                 
98                         fastafile = validParameter.validFile(parameters, "fasta", true);
99                         if (fastafile == "not open") { abort = true; }
100                         else if (fastafile == "not found") {  fastafile = "";  }        
101                         
102                         namefile = validParameter.validFile(parameters, "name", true);
103                         if (namefile == "not open") { abort = true; }
104                         else if (namefile == "not found") {  namefile = "";  }  
105                         
106                         groupfile = validParameter.validFile(parameters, "group", true);
107                         if (groupfile == "not open") { abort = true; }
108                         else if (groupfile == "not found") {  groupfile = "";  }        
109                         
110                         alignfile = validParameter.validFile(parameters, "alignreport", true);
111                         if (alignfile == "not open") { abort = true; }
112                         else if (alignfile == "not found") {  alignfile = "";  }
113                         
114                         listfile = validParameter.validFile(parameters, "list", true);
115                         if (listfile == "not open") { abort = true; }
116                         else if (listfile == "not found") {  listfile = "";  }
117                         
118                         taxfile = validParameter.validFile(parameters, "taxonomy", true);
119                         if (taxfile == "not open") { abort = true; }
120                         else if (taxfile == "not found") {  taxfile = ""; m->mothurOut("The taxonomy parameter is required for the get.lineage command."); m->mothurOutEndLine();  abort = true; }
121                         
122                         string usedDups = "true";
123                         string temp = validParameter.validFile(parameters, "dups", false);      if (temp == "not found") { temp = "false"; usedDups = ""; }
124                         dups = m->isTrue(temp);
125                         
126                         taxons = validParameter.validFile(parameters, "taxon", false);  
127                         if (taxons == "not found") { taxons = "";  m->mothurOut("No taxons given, please correct."); m->mothurOutEndLine();  abort = true;  }
128                         else { 
129                                 //rip off quotes
130                                 if (taxons[0] == '\'') {  taxons = taxons.substr(1); }
131                                 if (taxons[(taxons.length()-1)] == '\'') {  taxons = taxons.substr(0, (taxons.length()-1)); }
132                         }
133                         
134                         
135                         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; }
136                 
137                         if ((usedDups != "") && (namefile == "")) {  m->mothurOut("You may only use dups with the name option."); m->mothurOutEndLine();  abort = true; }                       
138
139                 }
140
141         }
142         catch(exception& e) {
143                 m->errorOut(e, "RemoveLineageCommand", "RemoveLineageCommand");
144                 exit(1);
145         }
146 }
147 //**********************************************************************************************************************
148
149 void RemoveLineageCommand::help(){
150         try {
151                 m->mothurOut("The remove.lineage command reads a taxonomy file and any of the following file types: fasta, name, group, list or alignreport file.\n");
152                 m->mothurOut("It outputs a file containing only the sequences from the taxonomy file that are not from the taxon you requested to be removed.\n");
153                 m->mothurOut("The remove.lineage command parameters are taxon, fasta, name, group, list, taxonomy, alignreport and dups.  You must provide taxonomy and taxon.\n");
154                 m->mothurOut("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");
155                 m->mothurOut("The taxon parameter allows you to select the taxons you would like to remove.\n");
156                 m->mothurOut("The remove.lineage command should be in the following format: remove.lineage(taxonomy=yourTaxonomyFile, taxon=yourTaxons).\n");
157                 m->mothurOut("Example remove.lineage(taxonomy=amazon.silva.taxonomy, taxon=Bacteria;Firmicutes;Bacilli;Lactobacillales;).\n");
158                 m->mothurOut("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");
159                 m->mothurOut("Example remove.lineage(taxonomy=amazon.silva.taxonomy, taxon='Bacteria;Firmicutes;Bacilli;Lactobacillales;').\n");
160                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
161         }
162         catch(exception& e) {
163                 m->errorOut(e, "RemoveLineageCommand", "help");
164                 exit(1);
165         }
166 }
167
168 //**********************************************************************************************************************
169
170 int RemoveLineageCommand::execute(){
171         try {
172                 
173                 if (abort == true) { return 0; }
174                 
175                 if (m->control_pressed) { return 0; }
176                 
177                 //read through the correct file and output lines you want to keep
178                 if (taxfile != "")                      {               readTax();              }  //fills the set of names to remove
179                 if (namefile != "")                     {               readName();             }
180                 if (fastafile != "")            {               readFasta();    }
181                 if (groupfile != "")            {               readGroup();    }
182                 if (alignfile != "")            {               readAlign();    }
183                 if (listfile != "")                     {               readList();             }
184                 
185                 
186                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0; }
187                 
188                 if (outputNames.size() != 0) {
189                         m->mothurOutEndLine();
190                         m->mothurOut("Output File Names: "); m->mothurOutEndLine();
191                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
192                         m->mothurOutEndLine();
193                 }
194                 
195                 return 0;               
196         }
197
198         catch(exception& e) {
199                 m->errorOut(e, "RemoveLineageCommand", "execute");
200                 exit(1);
201         }
202 }
203
204 //**********************************************************************************************************************
205 int RemoveLineageCommand::readFasta(){
206         try {
207                 string thisOutputDir = outputDir;
208                 if (outputDir == "") {  thisOutputDir += m->hasPath(fastafile);  }
209                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(fastafile)) + "pick" + m->getExtension(fastafile);
210                 
211                 ofstream out;
212                 m->openOutputFile(outputFileName, out);
213                 
214                 ifstream in;
215                 m->openInputFile(fastafile, in);
216                 string name;
217                 
218                 bool wroteSomething = false;
219                 
220                 while(!in.eof()){
221                         if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
222                         
223                         Sequence currSeq(in);
224                         name = currSeq.getName();
225                         
226                         if (name != "") {
227                                 //if this name is in the accnos file
228                                 if (names.count(name) == 0) {
229                                         wroteSomething = true;
230                                         
231                                         currSeq.printSequence(out);
232                                 }
233                         }
234                         m->gobble(in);
235                 }
236                 in.close();     
237                 out.close();
238                 
239                 if (wroteSomething == false) {  m->mothurOut("Your fasta file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
240                 outputNames.push_back(outputFileName); 
241                 
242                 return 0;
243                 
244         }
245         catch(exception& e) {
246                 m->errorOut(e, "RemoveLineageCommand", "readFasta");
247                 exit(1);
248         }
249 }
250 //**********************************************************************************************************************
251 int RemoveLineageCommand::readList(){
252         try {
253                 string thisOutputDir = outputDir;
254                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
255                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "pick" +  m->getExtension(listfile);
256                 
257                 ofstream out;
258                 m->openOutputFile(outputFileName, out);
259                 
260                 ifstream in;
261                 m->openInputFile(listfile, in);
262                 
263                 bool wroteSomething = false;
264                 
265                 while(!in.eof()){
266                         //read in list vector
267                         ListVector list(in);
268                         
269                         //make a new list vector
270                         ListVector newList;
271                         newList.setLabel(list.getLabel());
272                         
273                         //for each bin
274                         for (int i = 0; i < list.getNumBins(); i++) {
275                                 if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
276                         
277                                 //parse out names that are in accnos file
278                                 string binnames = list.get(i);
279                                 
280                                 string newNames = "";
281                                 while (binnames.find_first_of(',') != -1) { 
282                                         string name = binnames.substr(0,binnames.find_first_of(','));
283                                         binnames = binnames.substr(binnames.find_first_of(',')+1, binnames.length());
284                                         
285                                         //if that name is in the .accnos file, add it
286                                         if (names.count(name) == 0) {  newNames += name + ",";  }
287                                 }
288                         
289                                 //get last name
290                                 if (names.count(binnames) == 0) {  newNames += binnames + ",";  }
291
292                                 //if there are names in this bin add to new list
293                                 if (newNames != "") {  
294                                         newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
295                                         newList.push_back(newNames);    
296                                 }
297                         }
298                                 
299                         //print new listvector
300                         if (newList.getNumBins() != 0) {
301                                 wroteSomething = true;
302                                 newList.print(out);
303                         }
304                         
305                         m->gobble(in);
306                 }
307                 in.close();     
308                 out.close();
309                 
310                 if (wroteSomething == false) {  m->mothurOut("Your list file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
311                 outputNames.push_back(outputFileName); 
312                                 
313                 return 0;
314
315         }
316         catch(exception& e) {
317                 m->errorOut(e, "RemoveLineageCommand", "readList");
318                 exit(1);
319         }
320 }
321 //**********************************************************************************************************************
322 int RemoveLineageCommand::readName(){
323         try {
324                 string thisOutputDir = outputDir;
325                 if (outputDir == "") {  thisOutputDir += m->hasPath(namefile);  }
326                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(namefile)) + "pick" + m->getExtension(namefile);
327
328                 ofstream out;
329                 m->openOutputFile(outputFileName, out);
330
331                 ifstream in;
332                 m->openInputFile(namefile, in);
333                 string name, firstCol, secondCol;
334                 
335                 bool wroteSomething = false;
336                 
337                 while(!in.eof()){
338                         if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
339
340                         in >> firstCol;                         
341                         in >> secondCol;                        
342
343                         vector<string> parsedNames;
344                         //parse second column saving each name
345                         while (secondCol.find_first_of(',') != -1) { 
346                                 name = secondCol.substr(0,secondCol.find_first_of(','));
347                                 secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
348                                 parsedNames.push_back(name);
349                         }
350                         
351                         //get name after last ,
352                         parsedNames.push_back(secondCol);
353
354                         vector<string> validSecond;  validSecond.clear();
355                         for (int i = 0; i < parsedNames.size(); i++) {
356                                 if (names.count(parsedNames[i]) == 0) {
357                                         validSecond.push_back(parsedNames[i]);
358                                 }
359                         }
360                         
361                         if ((dups) && (validSecond.size() != parsedNames.size())) {  //if dups is true and we want to get rid of anyone, get rid of everyone
362                                 for (int i = 0; i < parsedNames.size(); i++) {  names.insert(parsedNames[i]);  }
363                         }else {
364                                         //if the name in the first column is in the set then print it and any other names in second column also in set
365                                 if (names.count(firstCol) == 0) {
366                                         
367                                         wroteSomething = true;
368                                         
369                                         out << firstCol << '\t';
370                                         
371                                         //you know you have at least one valid second since first column is valid
372                                         for (int i = 0; i < validSecond.size()-1; i++) {  out << validSecond[i] << ',';  }
373                                         out << validSecond[validSecond.size()-1] << endl;
374                                         
375                                         //make first name in set you come to first column and then add the remaining names to second column
376                                 }else {
377                                         
378                                         //you want part of this row
379                                         if (validSecond.size() != 0) {
380                                                 
381                                                 wroteSomething = true;
382                                                 
383                                                 out << validSecond[0] << '\t';
384                                                 
385                                                 //you know you have at least one valid second since first column is valid
386                                                 for (int i = 0; i < validSecond.size()-1; i++) {  out << validSecond[i] << ',';  }
387                                                 out << validSecond[validSecond.size()-1] << endl;
388                                         }
389                                 }
390                         }
391                         m->gobble(in);
392                 }
393                 in.close();
394                 out.close();
395
396                 if (wroteSomething == false) {  m->mothurOut("Your name file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
397                 outputNames.push_back(outputFileName); 
398                                 
399                 return 0;
400         }
401         catch(exception& e) {
402                 m->errorOut(e, "RemoveLineageCommand", "readName");
403                 exit(1);
404         }
405 }
406
407 //**********************************************************************************************************************
408 int RemoveLineageCommand::readGroup(){
409         try {
410                 string thisOutputDir = outputDir;
411                 if (outputDir == "") {  thisOutputDir += m->hasPath(groupfile);  }
412                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "pick" + m->getExtension(groupfile);
413                 
414                 ofstream out;
415                 m->openOutputFile(outputFileName, out);
416
417                 ifstream in;
418                 m->openInputFile(groupfile, in);
419                 string name, group;
420                 
421                 bool wroteSomething = false;
422                 
423                 while(!in.eof()){
424                         if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
425                         
426                         in >> name;                             //read from first column
427                         in >> group;                    //read from second column
428                         
429                         //if this name is in the accnos file
430                         if (names.count(name) == 0) {
431                                 wroteSomething = true;
432                                 out << name << '\t' << group << endl;
433                         }
434                                         
435                         m->gobble(in);
436                 }
437                 in.close();
438                 out.close();
439                 
440                 if (wroteSomething == false) {  m->mothurOut("Your group file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
441                 outputNames.push_back(outputFileName); 
442                 
443                 return 0;
444         }
445         catch(exception& e) {
446                 m->errorOut(e, "RemoveLineageCommand", "readGroup");
447                 exit(1);
448         }
449 }
450 //**********************************************************************************************************************
451 int RemoveLineageCommand::readTax(){
452         try {
453                 string thisOutputDir = outputDir;
454                 if (outputDir == "") {  thisOutputDir += m->hasPath(taxfile);  }
455                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(taxfile)) + "pick" + m->getExtension(taxfile);
456                 ofstream out;
457                 m->openOutputFile(outputFileName, out);
458                 
459                 ifstream in;
460                 m->openInputFile(taxfile, in);
461                 string name, tax;
462                 
463                 bool wroteSomething = false;
464                 
465                 while(!in.eof()){
466
467                         if (m->control_pressed) { in.close(); out.close(); remove(outputFileName.c_str());  return 0; }
468
469                         in >> name;                             //read from first column
470                         in >> tax;                      //read from second column
471                         
472                         string newtax = tax;
473                         
474                         //if the users file contains confidence scores we want to ignore them when searching for the taxons
475                         int hasConfidences = tax.find_first_of('(');
476                         if (hasConfidences != string::npos) { 
477                                 newtax = removeConfidences(tax);
478                         }
479                         
480                         int pos = newtax.find(taxons);
481                         
482                         if (pos == string::npos) { 
483                                 wroteSomething = true;
484                                 out << name << '\t' << tax << endl;
485                         }else{ //this sequence contains the taxon the user wants to remove
486                                 names.insert(name);
487                         }
488                         
489                         m->gobble(in);
490                 }
491                 in.close();
492                 out.close();
493                 
494                 if (!wroteSomething) { m->mothurOut("Your taxonomy file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
495                 outputNames.push_back(outputFileName); 
496                         
497                 return 0;
498
499         }
500         catch(exception& e) {
501                 m->errorOut(e, "RemoveLineageCommand", "readTax");
502                 exit(1);
503         }
504 }
505 /**************************************************************************************************/
506 string RemoveLineageCommand::removeConfidences(string tax) {
507         try {
508                 
509                 string taxon = "";
510                 int taxLength = tax.length();
511                 for(int i=0;i<taxLength;i++){
512                         if(tax[i] == ';'){
513                                 taxon = taxon.substr(0, taxon.find_first_of('(')); //rip off confidence
514                                 taxon += ";";
515                         }
516                         else{
517                                 taxon += tax[i];
518                         }
519                 }
520                                 
521                 return taxon;
522         }
523         catch(exception& e) {
524                 m->errorOut(e, "RemoveLineageCommand", "removeConfidences");
525                 exit(1);
526         }
527 }
528 //**********************************************************************************************************************
529 //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
530 int RemoveLineageCommand::readAlign(){
531         try {
532                 string thisOutputDir = outputDir;
533                 if (outputDir == "") {  thisOutputDir += m->hasPath(alignfile);  }
534                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(alignfile)) + "pick.align.report";
535                 
536                 ofstream out;
537                 m->openOutputFile(outputFileName, out);
538
539                 ifstream in;
540                 m->openInputFile(alignfile, in);
541                 string name, junk;
542                 
543                 bool wroteSomething = false;
544                 
545                 //read column headers
546                 for (int i = 0; i < 16; i++) {  
547                         if (!in.eof())  {       in >> junk;      out << junk << '\t';   }
548                         else                    {       break;                  }
549                 }
550                 out << endl;
551                 
552                 while(!in.eof()){
553                         if (m->control_pressed) { in.close();  out.close();  remove(outputFileName.c_str());  return 0; }
554                         
555                         in >> name;                             //read from first column
556                         
557                         //if this name is in the accnos file
558                         if (names.count(name) == 0) {
559                                 wroteSomething = true;
560                                 
561                                 out << name << '\t';
562                                 
563                                 //read rest
564                                 for (int i = 0; i < 15; i++) {  
565                                         if (!in.eof())  {       in >> junk;      out << junk << '\t';   }
566                                         else                    {       break;                  }
567                                 }
568                                 out << endl;
569                                 
570                         }else {//still read just don't do anything with it
571                                 
572                                 //read rest
573                                 for (int i = 0; i < 15; i++) {  
574                                         if (!in.eof())  {       in >> junk;             }
575                                         else                    {       break;                  }
576                                 }
577                         }
578                         
579                         m->gobble(in);
580                 }
581                 in.close();
582                 out.close();
583                 
584                 if (wroteSomething == false) {  m->mothurOut("Your align file contains only sequences from " + taxons + "."); m->mothurOutEndLine();  }
585                 outputNames.push_back(outputFileName); 
586                 
587                 return 0;
588                 
589         }
590         catch(exception& e) {
591                 m->errorOut(e, "RemoveLineageCommand", "readAlign");
592                 exit(1);
593         }
594 }
595 //**********************************************************************************************************************
596