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 numFPrimers = 0; //this needs to be initialized
191 openInputFile(fastaFile, inFASTA);
194 string trimSeqFile = outputDir + getRootName(getSimpleName(fastaFile)) + "trim.fasta";
195 openOutputFile(trimSeqFile, outFASTA);
196 outputNames.push_back(trimSeqFile);
199 vector<ofstream*> fastaFileNames;
201 string groupFile = outputDir + getRootName(getSimpleName(fastaFile)) + "groups";
202 openOutputFile(groupFile, outGroups);
203 outputNames.push_back(groupFile);
204 getOligos(fastaFileNames);
208 string scrapSeqFile = outputDir + getRootName(getSimpleName(fastaFile)) + "scrap.fasta";
209 openOutputFile(scrapSeqFile, scrapFASTA);
210 outputNames.push_back(scrapSeqFile);
213 if(qFileName != "") { openInputFile(qFileName, qFile); }
217 while(!inFASTA.eof()){
219 if (m->control_pressed) {
224 if(qFileName != "") { qFile.close(); }
225 for(int i=0;i<fastaFileNames.size();i++){
226 fastaFileNames[i]->close();
227 delete fastaFileNames[i];
229 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
234 Sequence currSeq(inFASTA);
236 string origSeq = currSeq.getUnaligned();
239 string trashCode = "";
242 if(qThreshold != 0) { success = stripQualThreshold(currSeq, qFile); }
243 else if(qAverage != 0) { success = cullQualAverage(currSeq, qFile); }
244 if ((!qtrim) && (origSeq.length() != currSeq.getUnaligned().length())) {
245 success = 0; //if you don't want to trim and the sequence does not meet quality requirements, move to scrap
247 if(!success) { trashCode += 'q'; }
250 if(barcodes.size() != 0){
251 success = stripBarcode(currSeq, group);
252 if(!success){ trashCode += 'b'; }
255 if(numFPrimers != 0){
256 success = stripForward(currSeq);
257 if(!success){ trashCode += 'f'; }
260 if(numRPrimers != 0){
261 success = stripReverse(currSeq);
262 if(!success){ trashCode += 'r'; }
265 if(minLength > 0 || maxLength > 0){
266 success = cullLength(currSeq);
267 if(!success){ trashCode += 'l'; }
270 success = cullHomoP(currSeq);
271 if(!success){ trashCode += 'h'; }
274 success = cullAmbigs(currSeq);
275 if(!success){ trashCode += 'n'; }
278 if(flip){ currSeq.reverseComplement(); } // should go last
280 if(trashCode.length() == 0){
281 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.
282 currSeq.printSequence(outFASTA);
283 if(barcodes.size() != 0){
284 outGroups << currSeq.getName() << '\t' << groupVector[group] << endl;
287 currSeq.printSequence(*fastaFileNames[group]);
292 currSeq.setName(currSeq.getName() + '|' + trashCode);
293 currSeq.setUnaligned(origSeq);
294 currSeq.printSequence(scrapFASTA);
303 if(qFileName != "") { qFile.close(); }
305 for(int i=0;i<fastaFileNames.size();i++){
306 fastaFileNames[i]->close();
307 delete fastaFileNames[i];
310 for(int i=0;i<fastaFileNames.size();i++){
312 openInputFile(getRootName(fastaFile) + groupVector[i] + ".fasta", inFASTA);
314 openOutputFile(outputDir + getRootName(getSimpleName(fastaFile)) + groupVector[i] + ".groups", outGroups);
315 outputNames.push_back(outputDir + getRootName(getSimpleName(fastaFile)) + groupVector[i] + ".groups");
317 while(!inFASTA.eof()){
318 if(inFASTA.get() == '>'){
320 outGroups << seqName << '\t' << groupVector[i] << endl;
322 while (!inFASTA.eof()) { char c = inFASTA.get(); if (c == 10 || c == 13){ break; } }
328 if (m->control_pressed) {
329 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
333 m->mothurOutEndLine();
334 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
335 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
336 m->mothurOutEndLine();
340 catch(exception& e) {
341 m->errorOut(e, "TrimSeqsCommand", "execute");
346 //***************************************************************************************************************
348 void TrimSeqsCommand::getOligos(vector<ofstream*>& outFASTAVec){
351 openInputFile(oligoFile, inOligos);
355 string type, oligo, group;
358 while(!inOligos.eof()){
362 while (!inOligos.eof()) { char c = inOligos.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
367 for(int i=0;i<oligo.length();i++){
368 oligo[i] = toupper(oligo[i]);
369 if(oligo[i] == 'U') { oligo[i] = 'T'; }
372 if(type == "forward"){
373 forPrimer.push_back(oligo);
375 else if(type == "reverse"){
376 Sequence oligoRC("reverse", oligo);
377 oligoRC.reverseComplement();
378 revPrimer.push_back(oligoRC.getUnaligned());
380 else if(type == "barcode"){
382 barcodes[oligo]=index++;
383 groupVector.push_back(group);
386 outFASTAVec.push_back(new ofstream((outputDir + getRootName(getSimpleName(fastaFile)) + group + ".fasta").c_str(), ios::ate));
387 outputNames.push_back((outputDir + getRootName(getSimpleName(fastaFile)) + group + ".fasta"));
395 numFPrimers = forPrimer.size();
396 numRPrimers = revPrimer.size();
399 catch(exception& e) {
400 m->errorOut(e, "TrimSeqsCommand", "getOligos");
406 //***************************************************************************************************************
408 bool TrimSeqsCommand::stripBarcode(Sequence& seq, int& group){
410 string rawSequence = seq.getUnaligned();
411 bool success = 0; //guilty until proven innocent
413 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
414 string oligo = it->first;
415 if(rawSequence.length() < oligo.length()){ //let's just assume that the barcodes are the same length
420 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
422 seq.setUnaligned(rawSequence.substr(oligo.length()));
430 catch(exception& e) {
431 m->errorOut(e, "TrimSeqsCommand", "stripBarcode");
437 //***************************************************************************************************************
439 bool TrimSeqsCommand::stripForward(Sequence& seq){
441 string rawSequence = seq.getUnaligned();
442 bool success = 0; //guilty until proven innocent
444 for(int i=0;i<numFPrimers;i++){
445 string oligo = forPrimer[i];
447 if(rawSequence.length() < oligo.length()){
452 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
453 seq.setUnaligned(rawSequence.substr(oligo.length()));
462 catch(exception& e) {
463 m->errorOut(e, "TrimSeqsCommand", "stripForward");
468 //***************************************************************************************************************
470 bool TrimSeqsCommand::stripReverse(Sequence& seq){
472 string rawSequence = seq.getUnaligned();
473 bool success = 0; //guilty until proven innocent
475 for(int i=0;i<numRPrimers;i++){
476 string oligo = revPrimer[i];
478 if(rawSequence.length() < oligo.length()){
483 if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
484 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
492 catch(exception& e) {
493 m->errorOut(e, "TrimSeqsCommand", "stripReverse");
498 //***************************************************************************************************************
500 bool TrimSeqsCommand::cullLength(Sequence& seq){
503 int length = seq.getNumBases();
504 bool success = 0; //guilty until proven innocent
506 if(length >= minLength && maxLength == 0) { success = 1; }
507 else if(length >= minLength && length <= maxLength) { success = 1; }
508 else { success = 0; }
513 catch(exception& e) {
514 m->errorOut(e, "TrimSeqsCommand", "cullLength");
520 //***************************************************************************************************************
522 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
524 int longHomoP = seq.getLongHomoPolymer();
525 bool success = 0; //guilty until proven innocent
527 if(longHomoP <= maxHomoP){ success = 1; }
528 else { success = 0; }
532 catch(exception& e) {
533 m->errorOut(e, "TrimSeqsCommand", "cullHomoP");
539 //***************************************************************************************************************
541 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
543 int numNs = seq.getAmbigBases();
544 bool success = 0; //guilty until proven innocent
546 if(numNs <= maxAmbig) { success = 1; }
547 else { success = 0; }
551 catch(exception& e) {
552 m->errorOut(e, "TrimSeqsCommand", "cullAmbigs");
558 //***************************************************************************************************************
560 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
563 int length = oligo.length();
565 for(int i=0;i<length;i++){
567 if(oligo[i] != seq[i]){
568 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C') { success = 0; }
569 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { success = 0; }
570 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { success = 0; }
571 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { success = 0; }
572 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { success = 0; }
573 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
574 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { success = 0; }
575 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
576 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
577 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
578 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { success = 0; }
579 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
581 if(success == 0) { break; }
590 catch(exception& e) {
591 m->errorOut(e, "TrimSeqsCommand", "compareDNASeq");
597 //***************************************************************************************************************
599 bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
601 string rawSequence = seq.getUnaligned();
602 int seqLength = rawSequence.length();
606 if (name.length() != 0) { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta and qual file"); m->mothurOutEndLine(); } }
607 while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
612 for(int i=0;i<seqLength;i++){
615 if(score <= qThreshold){
620 for(int i=end+1;i<seqLength;i++){
624 seq.setUnaligned(rawSequence.substr(0,end));
628 catch(exception& e) {
629 m->errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
634 //***************************************************************************************************************
636 bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
638 string rawSequence = seq.getUnaligned();
639 int seqLength = seq.getNumBases();
640 bool success = 0; //guilty until proven innocent
644 if (name[0] == '>') { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); } }
646 while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
651 for(int i=0;i<seqLength;i++){
655 average /= seqLength;
657 if(average >= qAverage) { success = 1; }
658 else { success = 0; }
662 catch(exception& e) {
663 m->errorOut(e, "TrimSeqsCommand", "cullQualAverage");
668 //***************************************************************************************************************