5 * Created by Pat Schloss on 6/6/09.
6 * Copyright 2009 Patrick D. Schloss. All rights reserved.
10 #include "trimseqscommand.h"
12 //***************************************************************************************************************
14 TrimSeqsCommand::TrimSeqsCommand(string option) {
19 //allow user to run help
20 if(option == "help") { help(); abort = true; }
23 //valid paramters for this command
24 string AlignArray[] = {"fasta", "flip", "oligos", "maxambig", "maxhomop", "minlength", "maxlength", "qfile",
25 "qthreshold", "qaverage", "allfiles", "qtrim", "outputdir","inputdir"};
27 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
29 OptionParser parser(option);
30 map<string,string> parameters = parser.getParameters();
32 ValidParameters validParameter;
33 map<string,string>::iterator it;
35 //check to make sure all parameters are valid for command
36 for (it = parameters.begin(); it != parameters.end(); it++) {
37 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
40 //if the user changes the input directory command factory will send this info to us in the output parameter
41 string inputDir = validParameter.validFile(parameters, "inputdir", false);
42 if (inputDir == "not found"){ inputDir = ""; }
45 it = parameters.find("fasta");
46 //user has given a template file
47 if(it != parameters.end()){
48 path = hasPath(it->second);
49 //if the user has not given a path then, add inputdir. else leave path alone.
50 if (path == "") { parameters["fasta"] = inputDir + it->second; }
53 it = parameters.find("oligos");
54 //user has given a template file
55 if(it != parameters.end()){
56 path = hasPath(it->second);
57 //if the user has not given a path then, add inputdir. else leave path alone.
58 if (path == "") { parameters["oligos"] = inputDir + it->second; }
61 it = parameters.find("qfile");
62 //user has given a template file
63 if(it != parameters.end()){
64 path = hasPath(it->second);
65 //if the user has not given a path then, add inputdir. else leave path alone.
66 if (path == "") { parameters["qfile"] = inputDir + it->second; }
71 //check for required parameters
72 fastaFile = validParameter.validFile(parameters, "fasta", true);
73 if (fastaFile == "not found") { m->mothurOut("fasta is a required parameter for the screen.seqs command."); m->mothurOutEndLine(); abort = true; }
74 else if (fastaFile == "not open") { abort = true; }
76 //if the user changes the output directory command factory will send this info to us in the output parameter
77 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
79 outputDir += hasPath(fastaFile); //if user entered a file with a path then preserve it
82 //check for optional parameter and set defaults
83 // ...at some point should added some additional type checking...
85 temp = validParameter.validFile(parameters, "flip", false);
86 if (temp == "not found"){ flip = 0; }
87 else if(isTrue(temp)) { flip = 1; }
89 temp = validParameter.validFile(parameters, "oligos", true);
90 if (temp == "not found"){ oligoFile = ""; }
91 else if(temp == "not open"){ abort = true; }
92 else { oligoFile = temp; }
94 temp = validParameter.validFile(parameters, "maxambig", false); if (temp == "not found") { temp = "-1"; }
95 convert(temp, maxAmbig);
97 temp = validParameter.validFile(parameters, "maxhomop", false); if (temp == "not found") { temp = "0"; }
98 convert(temp, maxHomoP);
100 temp = validParameter.validFile(parameters, "minlength", false); if (temp == "not found") { temp = "0"; }
101 convert(temp, minLength);
103 temp = validParameter.validFile(parameters, "maxlength", false); if (temp == "not found") { temp = "0"; }
104 convert(temp, maxLength);
106 temp = validParameter.validFile(parameters, "qfile", true);
107 if (temp == "not found") { qFileName = ""; }
108 else if(temp == "not open") { abort = true; }
109 else { qFileName = temp; }
111 temp = validParameter.validFile(parameters, "qthreshold", false); if (temp == "not found") { temp = "0"; }
112 convert(temp, qThreshold);
114 temp = validParameter.validFile(parameters, "qtrim", false); if (temp == "not found") { temp = "F"; }
115 qtrim = isTrue(temp);
117 temp = validParameter.validFile(parameters, "qaverage", false); if (temp == "not found") { temp = "0"; }
118 convert(temp, qAverage);
120 temp = validParameter.validFile(parameters, "allfiles", false); if (temp == "not found") { temp = "F"; }
121 allFiles = isTrue(temp);
123 if(allFiles && oligoFile == ""){
124 m->mothurOut("You selected allfiles, but didn't enter an oligos file. Ignoring the allfiles request."); m->mothurOutEndLine();
126 if((qAverage != 0 && qThreshold != 0) && qFileName == ""){
127 m->mothurOut("You didn't provide a quality file name, quality criteria will be ignored."); m->mothurOutEndLine();
131 if(!flip && oligoFile=="" && !maxLength && !minLength && (maxAmbig==-1) && !maxHomoP && qFileName == ""){
132 m->mothurOut("You didn't set any options... quiting command."); m->mothurOutEndLine();
138 catch(exception& e) {
139 m->errorOut(e, "TrimSeqsCommand", "TrimSeqsCommand");
143 //**********************************************************************************************************************
145 void TrimSeqsCommand::help(){
147 m->mothurOut("The trim.seqs command reads a fastaFile and creates .....\n");
148 m->mothurOut("The trim.seqs command parameters are fasta, flip, oligos, maxambig, maxhomop, minlength, maxlength, qfile, qthreshold, qaverage, qtrim and allfiles.\n");
149 m->mothurOut("The fasta parameter is required.\n");
150 m->mothurOut("The flip parameter .... The default is 0.\n");
151 m->mothurOut("The oligos parameter .... The default is "".\n");
152 m->mothurOut("The maxambig parameter .... The default is -1.\n");
153 m->mothurOut("The maxhomop parameter .... The default is 0.\n");
154 m->mothurOut("The minlength parameter .... The default is 0.\n");
155 m->mothurOut("The maxlength parameter .... The default is 0.\n");
156 m->mothurOut("The qfile parameter .....\n");
157 m->mothurOut("The qthreshold parameter .... The default is 0.\n");
158 m->mothurOut("The qaverage parameter .... The default is 0.\n");
159 m->mothurOut("The allfiles parameter .... The default is F.\n");
160 m->mothurOut("The qtrim parameter .... The default is F.\n");
161 m->mothurOut("The trim.seqs command should be in the following format: \n");
162 m->mothurOut("trim.seqs(fasta=yourFastaFile, flip=yourFlip, oligos=yourOligos, maxambig=yourMaxambig, \n");
163 m->mothurOut("maxhomop=yourMaxhomop, minlength=youMinlength, maxlength=yourMaxlength) \n");
164 m->mothurOut("Example trim.seqs(fasta=abrecovery.fasta, flip=..., oligos=..., maxambig=..., maxhomop=..., minlength=..., maxlength=...).\n");
165 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n");
166 m->mothurOut("For more details please check out the wiki http://www.mothur.org/wiki/Trim.seqs .\n\n");
169 catch(exception& e) {
170 m->errorOut(e, "TrimSeqsCommand", "help");
176 //***************************************************************************************************************
178 TrimSeqsCommand::~TrimSeqsCommand(){ /* do nothing */ }
180 //***************************************************************************************************************
182 int TrimSeqsCommand::execute(){
185 if (abort == true) { return 0; }
187 vector<string> outputNames;
189 numFPrimers = 0; //this needs to be initialized
193 openInputFile(fastaFile, inFASTA);
196 string trimSeqFile = outputDir + getRootName(getSimpleName(fastaFile)) + "trim.fasta";
197 openOutputFile(trimSeqFile, outFASTA);
198 outputNames.push_back(trimSeqFile);
201 vector<ofstream*> fastaFileNames;
203 string groupFile = outputDir + getRootName(getSimpleName(fastaFile)) + "groups";
204 openOutputFile(groupFile, outGroups);
205 outputNames.push_back(groupFile);
206 getOligos(fastaFileNames);
210 string scrapSeqFile = outputDir + getRootName(getSimpleName(fastaFile)) + "scrap.fasta";
211 openOutputFile(scrapSeqFile, scrapFASTA);
212 outputNames.push_back(scrapSeqFile);
215 if(qFileName != "") { openInputFile(qFileName, qFile); }
219 while(!inFASTA.eof()){
220 Sequence currSeq(inFASTA);
222 string origSeq = currSeq.getUnaligned();
225 string trashCode = "";
228 if(qThreshold != 0) { success = stripQualThreshold(currSeq, qFile); }
229 else if(qAverage != 0) { success = cullQualAverage(currSeq, qFile); }
230 if ((!qtrim) && (origSeq.length() != currSeq.getUnaligned().length())) {
231 success = 0; //if you don't want to trim and the sequence does not meet quality requirements, move to scrap
233 if(!success) { trashCode += 'q'; }
236 if(barcodes.size() != 0){
237 success = stripBarcode(currSeq, group);
238 if(!success){ trashCode += 'b'; }
241 if(numFPrimers != 0){
242 success = stripForward(currSeq);
243 if(!success){ trashCode += 'f'; }
246 if(numRPrimers != 0){
247 success = stripReverse(currSeq);
248 if(!success){ trashCode += 'r'; }
251 if(minLength > 0 || maxLength > 0){
252 success = cullLength(currSeq);
253 if(!success){ trashCode += 'l'; }
256 success = cullHomoP(currSeq);
257 if(!success){ trashCode += 'h'; }
260 success = cullAmbigs(currSeq);
261 if(!success){ trashCode += 'n'; }
264 if(flip){ currSeq.reverseComplement(); } // should go last
266 if(trashCode.length() == 0){
267 currSeq.setAligned(currSeq.getUnaligned()); //this is because of a modification we made to the sequence class to fix a bug. all seqs have an aligned version, which is the version that gets printed.
268 currSeq.printSequence(outFASTA);
269 if(barcodes.size() != 0){
270 outGroups << currSeq.getName() << '\t' << groupVector[group] << endl;
273 currSeq.printSequence(*fastaFileNames[group]);
278 currSeq.setName(currSeq.getName() + '|' + trashCode);
279 currSeq.setUnaligned(origSeq);
280 currSeq.printSequence(scrapFASTA);
289 if(qFileName != "") { qFile.close(); }
291 for(int i=0;i<fastaFileNames.size();i++){
292 fastaFileNames[i]->close();
293 delete fastaFileNames[i];
296 for(int i=0;i<fastaFileNames.size();i++){
298 openInputFile(getRootName(fastaFile) + groupVector[i] + ".fasta", inFASTA);
300 openOutputFile(outputDir + getRootName(getSimpleName(fastaFile)) + groupVector[i] + ".groups", outGroups);
301 outputNames.push_back(outputDir + getRootName(getSimpleName(fastaFile)) + groupVector[i] + ".groups");
303 while(!inFASTA.eof()){
304 if(inFASTA.get() == '>'){
306 outGroups << seqName << '\t' << groupVector[i] << endl;
308 while (!inFASTA.eof()) { char c = inFASTA.get(); if (c == 10 || c == 13){ break; } }
314 m->mothurOutEndLine();
315 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
316 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
317 m->mothurOutEndLine();
321 catch(exception& e) {
322 m->errorOut(e, "TrimSeqsCommand", "execute");
327 //***************************************************************************************************************
329 void TrimSeqsCommand::getOligos(vector<ofstream*>& outFASTAVec){
332 openInputFile(oligoFile, inOligos);
336 string type, oligo, group;
339 while(!inOligos.eof()){
343 while (!inOligos.eof()) { char c = inOligos.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
348 for(int i=0;i<oligo.length();i++){
349 oligo[i] = toupper(oligo[i]);
350 if(oligo[i] == 'U') { oligo[i] = 'T'; }
353 if(type == "forward"){
354 forPrimer.push_back(oligo);
356 else if(type == "reverse"){
357 Sequence oligoRC("reverse", oligo);
358 oligoRC.reverseComplement();
359 revPrimer.push_back(oligoRC.getUnaligned());
361 else if(type == "barcode"){
363 barcodes[oligo]=index++;
364 groupVector.push_back(group);
367 outFASTAVec.push_back(new ofstream((outputDir + getRootName(getSimpleName(fastaFile)) + group + ".fasta").c_str(), ios::ate));
375 numFPrimers = forPrimer.size();
376 numRPrimers = revPrimer.size();
379 catch(exception& e) {
380 m->errorOut(e, "TrimSeqsCommand", "getOligos");
386 //***************************************************************************************************************
388 bool TrimSeqsCommand::stripBarcode(Sequence& seq, int& group){
390 string rawSequence = seq.getUnaligned();
391 bool success = 0; //guilty until proven innocent
393 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
394 string oligo = it->first;
395 if(rawSequence.length() < oligo.length()){ //let's just assume that the barcodes are the same length
400 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
402 seq.setUnaligned(rawSequence.substr(oligo.length()));
410 catch(exception& e) {
411 m->errorOut(e, "TrimSeqsCommand", "stripBarcode");
417 //***************************************************************************************************************
419 bool TrimSeqsCommand::stripForward(Sequence& seq){
421 string rawSequence = seq.getUnaligned();
422 bool success = 0; //guilty until proven innocent
424 for(int i=0;i<numFPrimers;i++){
425 string oligo = forPrimer[i];
427 if(rawSequence.length() < oligo.length()){
432 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
433 seq.setUnaligned(rawSequence.substr(oligo.length()));
442 catch(exception& e) {
443 m->errorOut(e, "TrimSeqsCommand", "stripForward");
448 //***************************************************************************************************************
450 bool TrimSeqsCommand::stripReverse(Sequence& seq){
452 string rawSequence = seq.getUnaligned();
453 bool success = 0; //guilty until proven innocent
455 for(int i=0;i<numRPrimers;i++){
456 string oligo = revPrimer[i];
458 if(rawSequence.length() < oligo.length()){
463 if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
464 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
472 catch(exception& e) {
473 m->errorOut(e, "TrimSeqsCommand", "stripReverse");
478 //***************************************************************************************************************
480 bool TrimSeqsCommand::cullLength(Sequence& seq){
483 int length = seq.getNumBases();
484 bool success = 0; //guilty until proven innocent
486 if(length >= minLength && maxLength == 0) { success = 1; }
487 else if(length >= minLength && length <= maxLength) { success = 1; }
488 else { success = 0; }
493 catch(exception& e) {
494 m->errorOut(e, "TrimSeqsCommand", "cullLength");
500 //***************************************************************************************************************
502 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
504 int longHomoP = seq.getLongHomoPolymer();
505 bool success = 0; //guilty until proven innocent
507 if(longHomoP <= maxHomoP){ success = 1; }
508 else { success = 0; }
512 catch(exception& e) {
513 m->errorOut(e, "TrimSeqsCommand", "cullHomoP");
519 //***************************************************************************************************************
521 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
523 int numNs = seq.getAmbigBases();
524 bool success = 0; //guilty until proven innocent
526 if(numNs <= maxAmbig) { success = 1; }
527 else { success = 0; }
531 catch(exception& e) {
532 m->errorOut(e, "TrimSeqsCommand", "cullAmbigs");
538 //***************************************************************************************************************
540 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
543 int length = oligo.length();
545 for(int i=0;i<length;i++){
547 if(oligo[i] != seq[i]){
548 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C') { success = 0; }
549 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { success = 0; }
550 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { success = 0; }
551 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { success = 0; }
552 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { success = 0; }
553 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
554 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { success = 0; }
555 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
556 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
557 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
558 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { success = 0; }
559 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
561 if(success == 0) { break; }
570 catch(exception& e) {
571 m->errorOut(e, "TrimSeqsCommand", "compareDNASeq");
577 //***************************************************************************************************************
579 bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
581 string rawSequence = seq.getUnaligned();
582 int seqLength = rawSequence.length();
586 if (name.length() != 0) { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta and qual file"); m->mothurOutEndLine(); } }
587 while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
592 for(int i=0;i<seqLength;i++){
595 if(score <= qThreshold){
600 for(int i=end+1;i<seqLength;i++){
604 seq.setUnaligned(rawSequence.substr(0,end));
608 catch(exception& e) {
609 m->errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
614 //***************************************************************************************************************
616 bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
618 string rawSequence = seq.getUnaligned();
619 int seqLength = seq.getNumBases();
620 bool success = 0; //guilty until proven innocent
624 if (name[0] == '>') { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); } }
626 while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
631 for(int i=0;i<seqLength;i++){
635 average /= seqLength;
637 if(average >= qAverage) { success = 1; }
638 else { success = 0; }
642 catch(exception& e) {
643 m->errorOut(e, "TrimSeqsCommand", "cullQualAverage");
648 //***************************************************************************************************************