]> git.donarmstrong.com Git - mothur.git/blob - getlineagecommand.cpp
added get.lineage and remove.lineage commands
[mothur.git] / getlineagecommand.cpp
1 /*
2  *  getlineagecommand.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 "getlineagecommand.h"
11 #include "sequence.hpp"
12 #include "listvector.hpp"
13
14 //**********************************************************************************************************************
15
16 GetLineageCommand::GetLineageCommand(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, "GetLineageCommand", "GetLineageCommand");
144                 exit(1);
145         }
146 }
147 //**********************************************************************************************************************
148
149 void GetLineageCommand::help(){
150         try {
151                 m->mothurOut("The get.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 from the taxon requested.\n");
153                 m->mothurOut("The get.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 get.\n");
156                 m->mothurOut("The get.lineage command should be in the following format: get.lineage(taxonomy=yourTaxonomyFile, taxon=yourTaxons).\n");
157                 m->mothurOut("Example get.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 get.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, "GetLineageCommand", "help");
164                 exit(1);
165         }
166 }
167
168 //**********************************************************************************************************************
169
170 int GetLineageCommand::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 get
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, "GetLineageCommand", "execute");
200                 exit(1);
201         }
202 }
203
204 //**********************************************************************************************************************
205 int GetLineageCommand::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                 ofstream out;
211                 m->openOutputFile(outputFileName, out);
212                 
213                 
214                 ifstream in;
215                 m->openInputFile(fastafile, in);
216                 string name;
217                 
218                 bool wroteSomething = false;
219                 
220                 while(!in.eof()){
221                 
222                         if (m->control_pressed) { in.close(); out.close(); remove(outputFileName.c_str());  return 0; }
223                         
224                         Sequence currSeq(in);
225                         name = currSeq.getName();
226                         
227                         if (name != "") {
228                                 //if this name is in the accnos file
229                                 if (names.count(name) != 0) {
230                                         wroteSomething = true;
231                                         
232                                         currSeq.printSequence(out);
233                                 }
234                         }
235                         m->gobble(in);
236                 }
237                 in.close();     
238                 out.close();
239                 
240                 if (wroteSomething == false) { m->mothurOut("Your file does not contain any sequence from the .accnos file."); m->mothurOutEndLine();  }
241                 outputNames.push_back(outputFileName); 
242                 
243                 return 0;
244
245         }
246         catch(exception& e) {
247                 m->errorOut(e, "GetLineageCommand", "readFasta");
248                 exit(1);
249         }
250 }
251 //**********************************************************************************************************************
252 int GetLineageCommand::readList(){
253         try {
254                 string thisOutputDir = outputDir;
255                 if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
256                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "pick" +  m->getExtension(listfile);
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                         
267                         if (m->control_pressed) { in.close(); out.close(); remove(outputFileName.c_str());  return 0; }
268
269                         //read in list vector
270                         ListVector list(in);
271                         
272                         //make a new list vector
273                         ListVector newList;
274                         newList.setLabel(list.getLabel());
275                         
276                         //for each bin
277                         for (int i = 0; i < list.getNumBins(); i++) {
278                         
279                                 //parse out names that are in accnos file
280                                 string binnames = list.get(i);
281                                 
282                                 string newNames = "";
283                                 while (binnames.find_first_of(',') != -1) { 
284                                         string name = binnames.substr(0,binnames.find_first_of(','));
285                                         binnames = binnames.substr(binnames.find_first_of(',')+1, binnames.length());
286                                         
287                                         //if that name is in the .accnos file, add it
288                                         if (names.count(name) != 0) {  newNames += name + ",";  }
289                                 }
290                         
291                                 //get last name
292                                 if (names.count(binnames) != 0) {  newNames += binnames + ",";  }
293
294                                 //if there are names in this bin add to new list
295                                 if (newNames != "") { 
296                                         newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
297                                         newList.push_back(newNames);    
298                                 }
299                         }
300                                 
301                         //print new listvector
302                         if (newList.getNumBins() != 0) {
303                                 wroteSomething = true;
304                                 newList.print(out);
305                         }
306                         
307                         m->gobble(in);
308                 }
309                 in.close();     
310                 out.close();
311                 
312                 if (wroteSomething == false) { m->mothurOut("Your file does not contain any sequence from the .accnos file."); m->mothurOutEndLine();  }
313                 outputNames.push_back(outputFileName); 
314                 
315                 return 0;
316
317         }
318         catch(exception& e) {
319                 m->errorOut(e, "GetLineageCommand", "readList");
320                 exit(1);
321         }
322 }
323 //**********************************************************************************************************************
324 int GetLineageCommand::readName(){
325         try {
326                 string thisOutputDir = outputDir;
327                 if (outputDir == "") {  thisOutputDir += m->hasPath(namefile);  }
328                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(namefile)) + "pick" +  m->getExtension(namefile);
329                 ofstream out;
330                 m->openOutputFile(outputFileName, out);
331                 
332
333                 ifstream in;
334                 m->openInputFile(namefile, in);
335                 string name, firstCol, secondCol;
336                 
337                 bool wroteSomething = false;
338                 
339                 
340                 while(!in.eof()){
341                 
342                         if (m->control_pressed) { in.close(); out.close(); remove(outputFileName.c_str());  return 0; }
343
344                         in >> firstCol;                         
345                         in >> secondCol;
346                         
347                         string hold = "";
348                         if (dups) { hold = secondCol; }
349                         
350                         vector<string> parsedNames;
351                         //parse second column saving each name
352                         while (secondCol.find_first_of(',') != -1) { 
353                                 name = secondCol.substr(0,secondCol.find_first_of(','));
354                                 secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
355                                 parsedNames.push_back(name);
356                         }
357                         
358                         //get name after last ,
359                         parsedNames.push_back(secondCol);
360                         
361                         vector<string> validSecond;
362                         for (int i = 0; i < parsedNames.size(); i++) {
363                                 if (names.count(parsedNames[i]) != 0) {
364                                         validSecond.push_back(parsedNames[i]);
365                                 }
366                         }
367
368                         if ((dups) && (validSecond.size() != 0)) { //dups = true and we want to add someone, then add everyone
369                                 for (int i = 0; i < parsedNames.size(); i++) {  names.insert(parsedNames[i]);  }
370                                 out << firstCol << '\t' << hold << endl;
371                                 wroteSomething = true;
372                         }else {
373                                 //if the name in the first column is in the set then print it and any other names in second column also in set
374                                 if (names.count(firstCol) != 0) {
375                                 
376                                         wroteSomething = true;
377                                         
378                                         out << firstCol << '\t';
379                                         
380                                         //you know you have at least one valid second since first column is valid
381                                         for (int i = 0; i < validSecond.size()-1; i++) {  out << validSecond[i] << ',';  }
382                                         out << validSecond[validSecond.size()-1] << endl;
383                                         
384                                 
385                                 //make first name in set you come to first column and then add the remaining names to second column
386                                 }else {
387                                         //you want part of this row
388                                         if (validSecond.size() != 0) {
389                                         
390                                                 wroteSomething = true;
391                                                 
392                                                 out << validSecond[0] << '\t';
393                                         
394                                                 //you know you have at least one valid second since first column is valid
395                                                 for (int i = 0; i < validSecond.size()-1; i++) {  out << validSecond[i] << ',';  }
396                                                 out << validSecond[validSecond.size()-1] << endl;
397                                         }
398                                 }
399                         }
400                         m->gobble(in);
401                 }
402                 in.close();
403                 out.close();
404                 
405                 if (wroteSomething == false) { m->mothurOut("Your file does not contain any sequence from the .accnos file."); m->mothurOutEndLine();  }
406                 outputNames.push_back(outputFileName); 
407                 
408                 return 0;
409                 
410         }
411         catch(exception& e) {
412                 m->errorOut(e, "GetLineageCommand", "readName");
413                 exit(1);
414         }
415 }
416
417 //**********************************************************************************************************************
418 int GetLineageCommand::readGroup(){
419         try {
420                 string thisOutputDir = outputDir;
421                 if (outputDir == "") {  thisOutputDir += m->hasPath(groupfile);  }
422                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(groupfile)) + "pick" + m->getExtension(groupfile);
423                 ofstream out;
424                 m->openOutputFile(outputFileName, out);
425                 
426
427                 ifstream in;
428                 m->openInputFile(groupfile, in);
429                 string name, group;
430                 
431                 bool wroteSomething = false;
432                 
433                 while(!in.eof()){
434
435                         if (m->control_pressed) { in.close(); out.close(); remove(outputFileName.c_str());  return 0; }
436
437
438                         in >> name;                             //read from first column
439                         in >> group;                    //read from second column
440                         
441                         //if this name is in the accnos file
442                         if (names.count(name) != 0) {
443                                 wroteSomething = true;
444                                 
445                                 out << name << '\t' << group << endl;
446                         }
447                                         
448                         m->gobble(in);
449                 }
450                 in.close();
451                 out.close();
452                 
453                 if (wroteSomething == false) { m->mothurOut("Your file does not contain any sequence from the .accnos file."); m->mothurOutEndLine();  }
454                 outputNames.push_back(outputFileName); 
455                 
456                 return 0;
457
458         }
459         catch(exception& e) {
460                 m->errorOut(e, "GetLineageCommand", "readGroup");
461                 exit(1);
462         }
463 }
464 //**********************************************************************************************************************
465 int GetLineageCommand::readTax(){
466         try {
467                 string thisOutputDir = outputDir;
468                 if (outputDir == "") {  thisOutputDir += m->hasPath(taxfile);  }
469                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(taxfile)) + "pick" + m->getExtension(taxfile);
470                 ofstream out;
471                 m->openOutputFile(outputFileName, out);
472                 
473                 ifstream in;
474                 m->openInputFile(taxfile, in);
475                 string name, tax;
476                 
477                 bool wroteSomething = false;
478                 
479                 while(!in.eof()){
480
481                         if (m->control_pressed) { in.close(); out.close(); remove(outputFileName.c_str());  return 0; }
482
483                         in >> name;                             //read from first column
484                         in >> tax;                      //read from second column
485                         
486                         string newtax = tax;
487                         
488                         //if the users file contains confidence scores we want to ignore them when searching for the taxons
489                         int hasConfidences = tax.find_first_of('(');
490                         if (hasConfidences != string::npos) { 
491                                 newtax = removeConfidences(tax);
492                         }
493                         
494                         int pos = newtax.find(taxons);
495                         
496                         if (pos != string::npos) { //this sequence contains the taxon the user wants
497                                 names.insert(name);
498                                 out << name << '\t' << tax << endl;
499                         }
500                         
501                         m->gobble(in);
502                 }
503                 in.close();
504                 out.close();
505                 
506                 if (names.size() == 0) { m->mothurOut("Your taxonomy file does not contain any sequences from " + taxons + "."); m->mothurOutEndLine();  }
507                 outputNames.push_back(outputFileName); 
508                         
509                 return 0;
510
511         }
512         catch(exception& e) {
513                 m->errorOut(e, "GetLineageCommand", "readTax");
514                 exit(1);
515         }
516 }
517 /**************************************************************************************************/
518 string GetLineageCommand::removeConfidences(string tax) {
519         try {
520                 
521                 string taxon = "";
522                 int taxLength = tax.length();
523                 for(int i=0;i<taxLength;i++){
524                         if(tax[i] == ';'){
525                                 taxon = taxon.substr(0, taxon.find_first_of('(')); //rip off confidence
526                                 taxon += ";";
527                         }
528                         else{
529                                 taxon += tax[i];
530                         }
531                 }
532                                 
533                 return taxon;
534         }
535         catch(exception& e) {
536                 m->errorOut(e, "GetLineageCommand", "removeConfidences");
537                 exit(1);
538         }
539 }
540 //**********************************************************************************************************************
541 //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
542 int GetLineageCommand::readAlign(){
543         try {
544                 string thisOutputDir = outputDir;
545                 if (outputDir == "") {  thisOutputDir += m->hasPath(alignfile);  }
546                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(alignfile)) + "pick.align.report";
547                 ofstream out;
548                 m->openOutputFile(outputFileName, out);
549                 
550
551                 ifstream in;
552                 m->openInputFile(alignfile, in);
553                 string name, junk;
554                 
555                 bool wroteSomething = false;
556                 
557                 //read column headers
558                 for (int i = 0; i < 16; i++) {  
559                         if (!in.eof())  {       in >> junk;      out << junk << '\t';   }
560                         else                    {       break;                  }
561                 }
562                 out << endl;
563                 
564                 while(!in.eof()){
565                 
566                         if (m->control_pressed) { in.close(); out.close(); remove(outputFileName.c_str());  return 0; }
567
568
569                         in >> name;                             //read from first column
570                         
571                         //if this name is in the accnos file
572                         if (names.count(name) != 0) {
573                                 wroteSomething = true;
574                                 
575                                 out << name << '\t';
576                                 
577                                 //read rest
578                                 for (int i = 0; i < 15; i++) {  
579                                         if (!in.eof())  {       in >> junk;      out << junk << '\t';   }
580                                         else                    {       break;                  }
581                                 }
582                                 out << endl;
583                                 
584                         }else {//still read just don't do anything with it
585                                 //read rest
586                                 for (int i = 0; i < 15; i++) {  
587                                         if (!in.eof())  {       in >> junk;             }
588                                         else                    {       break;                  }
589                                 }
590                         }
591                         
592                         m->gobble(in);
593                 }
594                 in.close();
595                 out.close();
596                 
597                 if (wroteSomething == false) { m->mothurOut("Your file does not contain any sequence from the .accnos file."); m->mothurOutEndLine();  }
598                 outputNames.push_back(outputFileName); 
599                 
600                 return 0;
601                 
602         }
603         catch(exception& e) {
604                 m->errorOut(e, "GetLineageCommand", "readAlign");
605                 exit(1);
606         }
607 }
608 //**********************************************************************************************************************
609
610
611
612