5 * Created by Pat Schloss on 6/6/09.
6 * Copyright 2009 Patrick D. Schloss. All rights reserved.
10 #include "trimseqscommand.h"
11 #include "needlemanoverlap.hpp"
13 //***************************************************************************************************************
15 TrimSeqsCommand::TrimSeqsCommand(string option) {
21 //allow user to run help
22 if(option == "help") { help(); abort = true; }
25 //valid paramters for this command
26 string AlignArray[] = {"fasta", "flip", "oligos", "maxambig", "maxhomop", "minlength", "maxlength", "qfile",
27 "qthreshold", "qwindowaverage", "qstepsize", "qwindowsize", "qaverage", "rollaverage", "allfiles", "qtrim","tdiffs", "pdiffs", "bdiffs", "processors", "outputdir","inputdir"};
29 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
31 OptionParser parser(option);
32 map<string,string> parameters = parser.getParameters();
34 ValidParameters validParameter;
35 map<string,string>::iterator it;
37 //check to make sure all parameters are valid for command
38 for (it = parameters.begin(); it != parameters.end(); it++) {
39 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
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 = ""; }
47 it = parameters.find("fasta");
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["fasta"] = inputDir + it->second; }
55 it = parameters.find("oligos");
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["oligos"] = inputDir + it->second; }
63 it = parameters.find("qfile");
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["qfile"] = inputDir + it->second; }
73 //check for required parameters
74 fastaFile = validParameter.validFile(parameters, "fasta", true);
75 if (fastaFile == "not found") { m->mothurOut("fasta is a required parameter for the screen.seqs command."); m->mothurOutEndLine(); abort = true; }
76 else if (fastaFile == "not open") { abort = true; }
78 //if the user changes the output directory command factory will send this info to us in the output parameter
79 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
81 outputDir += m->hasPath(fastaFile); //if user entered a file with a path then preserve it
85 //check for optional parameter and set defaults
86 // ...at some point should added some additional type checking...
88 temp = validParameter.validFile(parameters, "flip", false);
89 if (temp == "not found"){ flip = 0; }
90 else if(m->isTrue(temp)) { flip = 1; }
92 temp = validParameter.validFile(parameters, "oligos", true);
93 if (temp == "not found"){ oligoFile = ""; }
94 else if(temp == "not open"){ abort = true; }
95 else { oligoFile = temp; }
97 temp = validParameter.validFile(parameters, "maxambig", false); if (temp == "not found") { temp = "-1"; }
98 convert(temp, maxAmbig);
100 temp = validParameter.validFile(parameters, "maxhomop", false); if (temp == "not found") { temp = "0"; }
101 convert(temp, maxHomoP);
103 temp = validParameter.validFile(parameters, "minlength", false); if (temp == "not found") { temp = "0"; }
104 convert(temp, minLength);
106 temp = validParameter.validFile(parameters, "maxlength", false); if (temp == "not found") { temp = "0"; }
107 convert(temp, maxLength);
109 temp = validParameter.validFile(parameters, "bdiffs", false); if (temp == "not found") { temp = "0"; }
110 convert(temp, bdiffs);
112 temp = validParameter.validFile(parameters, "pdiffs", false); if (temp == "not found") { temp = "0"; }
113 convert(temp, pdiffs);
115 temp = validParameter.validFile(parameters, "tdiffs", false); if (temp == "not found") { int tempTotal = pdiffs + bdiffs; temp = toString(tempTotal); }
116 convert(temp, tdiffs);
118 if(tdiffs == 0){ tdiffs = bdiffs + pdiffs; }
120 temp = validParameter.validFile(parameters, "qfile", true);
121 if (temp == "not found") { qFileName = ""; }
122 else if(temp == "not open") { abort = true; }
123 else { qFileName = temp; }
125 temp = validParameter.validFile(parameters, "qthreshold", false); if (temp == "not found") { temp = "0"; }
126 convert(temp, qThreshold);
128 temp = validParameter.validFile(parameters, "qtrim", false); if (temp == "not found") { temp = "F"; }
129 qtrim = m->isTrue(temp);
131 temp = validParameter.validFile(parameters, "rollaverage", false); if (temp == "not found") { temp = "0"; }
132 convert(temp, qRollAverage);
134 temp = validParameter.validFile(parameters, "qwindowaverage", false);if (temp == "not found") { temp = "0"; }
135 convert(temp, qWindowAverage);
137 temp = validParameter.validFile(parameters, "qwindowsize", false); if (temp == "not found") { temp = "100"; }
138 convert(temp, qWindowSize);
140 temp = validParameter.validFile(parameters, "qstepsize", false); if (temp == "not found") { temp = "10"; }
141 convert(temp, qWindowStep);
143 temp = validParameter.validFile(parameters, "qaverage", false); if (temp == "not found") { temp = "0"; }
144 convert(temp, qAverage);
146 temp = validParameter.validFile(parameters, "allfiles", false); if (temp == "not found") { temp = "F"; }
147 allFiles = m->isTrue(temp);
149 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found") { temp = "1"; }
150 convert(temp, processors);
152 if(allFiles && oligoFile == ""){
153 m->mothurOut("You selected allfiles, but didn't enter an oligos file. Ignoring the allfiles request."); m->mothurOutEndLine();
155 if((qAverage != 0 && qThreshold != 0) && qFileName == ""){
156 m->mothurOut("You didn't provide a quality file name, quality criteria will be ignored."); m->mothurOutEndLine();
160 if(!flip && oligoFile=="" && !maxLength && !minLength && (maxAmbig==-1) && !maxHomoP && qFileName == ""){
161 m->mothurOut("You didn't set any options... quiting command."); m->mothurOutEndLine();
167 catch(exception& e) {
168 m->errorOut(e, "TrimSeqsCommand", "TrimSeqsCommand");
172 //**********************************************************************************************************************
174 void TrimSeqsCommand::help(){
176 m->mothurOut("The trim.seqs command reads a fastaFile and creates .....\n");
177 m->mothurOut("The trim.seqs command parameters are fasta, flip, oligos, maxambig, maxhomop, minlength, maxlength, qfile, qthreshold, qaverage, diffs, qtrim and allfiles.\n");
178 m->mothurOut("The fasta parameter is required.\n");
179 m->mothurOut("The flip parameter will output the reverse compliment of your trimmed sequence. The default is false.\n");
180 m->mothurOut("The oligos parameter .... The default is "".\n");
181 m->mothurOut("The maxambig parameter .... The default is -1.\n");
182 m->mothurOut("The maxhomop parameter .... The default is 0.\n");
183 m->mothurOut("The minlength parameter .... The default is 0.\n");
184 m->mothurOut("The maxlength parameter .... The default is 0.\n");
185 m->mothurOut("The tdiffs parameter is used to specify the total number of differences allowed in the sequence. The default is pdiffs + bdiffs.\n");
186 m->mothurOut("The bdiffs parameter is used to specify the number of differences allowed in the barcode. The default is 0.\n");
187 m->mothurOut("The pdiffs parameter is used to specify the number of differences allowed in the primer. The default is 0.\n");
188 m->mothurOut("The qfile parameter .....\n");
189 m->mothurOut("The qthreshold parameter .... The default is 0.\n");
190 m->mothurOut("The qaverage parameter .... The default is 0.\n");
191 m->mothurOut("The allfiles parameter .... The default is F.\n");
192 m->mothurOut("The qtrim parameter .... The default is F.\n");
193 m->mothurOut("The trim.seqs command should be in the following format: \n");
194 m->mothurOut("trim.seqs(fasta=yourFastaFile, flip=yourFlip, oligos=yourOligos, maxambig=yourMaxambig, \n");
195 m->mothurOut("maxhomop=yourMaxhomop, minlength=youMinlength, maxlength=yourMaxlength) \n");
196 m->mothurOut("Example trim.seqs(fasta=abrecovery.fasta, flip=..., oligos=..., maxambig=..., maxhomop=..., minlength=..., maxlength=...).\n");
197 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n");
198 m->mothurOut("For more details please check out the wiki http://www.mothur.org/wiki/Trim.seqs .\n\n");
201 catch(exception& e) {
202 m->errorOut(e, "TrimSeqsCommand", "help");
208 //***************************************************************************************************************
210 TrimSeqsCommand::~TrimSeqsCommand(){ /* do nothing */ }
212 //***************************************************************************************************************
214 int TrimSeqsCommand::execute(){
217 if (abort == true) { return 0; }
219 numFPrimers = 0; //this needs to be initialized
222 string trimSeqFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "trim.fasta";
223 outputNames.push_back(trimSeqFile);
224 string scrapSeqFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "scrap.fasta";
225 outputNames.push_back(scrapSeqFile);
226 string trimQualFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "trim.qual";
227 string scrapQualFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "scrap.qual";
228 if (qFileName != "") { outputNames.push_back(trimQualFile); outputNames.push_back(scrapQualFile); }
229 string groupFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "groups";
231 vector<string> fastaFileNames;
232 vector<string> qualFileNames;
234 outputNames.push_back(groupFile);
235 getOligos(fastaFileNames, qualFileNames);
238 vector<unsigned long int> fastaFilePos;
239 vector<unsigned long int> qFilePos;
241 setLines(fastaFile, qFileName, fastaFilePos, qFilePos);
243 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
244 lines.push_back(new linePair(fastaFilePos[i], fastaFilePos[(i+1)]));
245 if (qFileName != "") { qLines.push_back(new linePair(qFilePos[i], qFilePos[(i+1)])); }
247 if(qFileName == "") { qLines = lines; } //files with duds
249 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
252 driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], qLines[0]);
254 for (int j = 0; j < fastaFileNames.size(); j++) {
255 rename((fastaFileNames[j] + toString(getpid()) + ".temp").c_str(), fastaFileNames[j].c_str());
258 for (int j = 0; j < qualFileNames.size(); j++) {
259 rename((qualFileNames[j] + toString(getpid()) + ".temp").c_str(), qualFileNames[j].c_str());
264 createProcessesCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames);
266 rename((trimSeqFile + toString(processIDS[0]) + ".temp").c_str(), trimSeqFile.c_str());
267 rename((scrapSeqFile + toString(processIDS[0]) + ".temp").c_str(), scrapSeqFile.c_str());
268 rename((groupFile + toString(processIDS[0]) + ".temp").c_str(), groupFile.c_str());
271 rename((trimQualFile + toString(processIDS[0]) + ".temp").c_str(), trimQualFile.c_str());
272 rename((scrapQualFile + toString(processIDS[0]) + ".temp").c_str(), scrapQualFile.c_str());
276 for (int j = 0; j < fastaFileNames.size(); j++) {
277 rename((fastaFileNames[j] + toString(processIDS[0]) + ".temp").c_str(), fastaFileNames[j].c_str());
280 for (int j = 0; j < qualFileNames.size(); j++) {
281 rename((qualFileNames[j] + toString(getpid()) + ".temp").c_str(), qualFileNames[j].c_str());
286 for(int i=1;i<processors;i++){
287 m->appendFiles((trimSeqFile + toString(processIDS[i]) + ".temp"), trimSeqFile);
288 remove((trimSeqFile + toString(processIDS[i]) + ".temp").c_str());
289 m->appendFiles((scrapSeqFile + toString(processIDS[i]) + ".temp"), scrapSeqFile);
290 remove((scrapSeqFile + toString(processIDS[i]) + ".temp").c_str());
292 m->appendFiles((trimQualFile + toString(processIDS[i]) + ".temp"), trimQualFile);
293 remove((trimQualFile + toString(processIDS[i]) + ".temp").c_str());
294 m->appendFiles((scrapQualFile + toString(processIDS[i]) + ".temp"), scrapQualFile);
295 remove((scrapQualFile + toString(processIDS[i]) + ".temp").c_str());
297 m->appendFiles((groupFile + toString(processIDS[i]) + ".temp"), groupFile);
298 remove((groupFile + toString(processIDS[i]) + ".temp").c_str());
299 for (int j = 0; j < fastaFileNames.size(); j++) {
300 m->appendFiles((fastaFileNames[j] + toString(processIDS[i]) + ".temp"), fastaFileNames[j]);
301 remove((fastaFileNames[j] + toString(processIDS[i]) + ".temp").c_str());
305 for (int j = 0; j < qualFileNames.size(); j++) {
306 m->appendFiles((qualFileNames[j] + toString(processIDS[i]) + ".temp"), qualFileNames[j]);
307 remove((qualFileNames[j] + toString(processIDS[i]) + ".temp").c_str());
315 if (m->control_pressed) { return 0; }
317 driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], qLines[0]);
319 for (int j = 0; j < fastaFileNames.size(); j++) {
320 rename((fastaFileNames[j] + toString(j) + ".temp").c_str(), fastaFileNames[j].c_str());
323 for (int j = 0; j < qualFileNames.size(); j++) {
324 rename((qualFileNames[j] + toString(j) + ".temp").c_str(), qualFileNames[j].c_str());
328 if (m->control_pressed) { return 0; }
332 for(int i=0;i<fastaFileNames.size();i++){
333 if (m->isBlank(fastaFileNames[i])) { remove(fastaFileNames[i].c_str()); }
334 else if (filesToRemove.count(fastaFileNames[i]) > 0) { remove(fastaFileNames[i].c_str()); }
338 m->openInputFile(fastaFileNames[i], inFASTA);
340 string outGroupFilename = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[i])) + "groups";
341 m->openOutputFile(outGroupFilename, outGroups);
342 outputNames.push_back(outGroupFilename);
344 string thisGroup = "";
345 if (i > comboStarts) {
346 map<string, int>::iterator itCombo;
347 for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
348 if(itCombo->second == i){ thisGroup = itCombo->first; combos.erase(itCombo); break; }
350 }else{ thisGroup = groupVector[i]; }
352 while(!inFASTA.eof()){
353 if(inFASTA.get() == '>'){
355 outGroups << seqName << '\t' << thisGroup << endl;
357 while (!inFASTA.eof()) { char c = inFASTA.get(); if (c == 10 || c == 13){ break; } }
365 for(int i=0;i<qualFileNames.size();i++){
366 if (m->isBlank(qualFileNames[i])) { remove(qualFileNames[i].c_str()); }
367 else if (filesToRemove.count(qualFileNames[i]) > 0) { remove(qualFileNames[i].c_str()); }
371 m->openInputFile(qualFileNames[i], inQual);
372 // ofstream outGroups;
374 // string thisGroup = "";
375 // if (i > comboStarts) {
376 // map<string, int>::iterator itCombo;
377 // for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
378 // if(itCombo->second == i){ thisGroup = itCombo->first; combos.erase(itCombo); break; }
381 // else{ thisGroup = groupVector[i]; }
389 if (m->control_pressed) {
390 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
394 m->mothurOutEndLine();
395 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
396 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
397 m->mothurOutEndLine();
402 catch(exception& e) {
403 m->errorOut(e, "TrimSeqsCommand", "execute");
408 /**************************************************************************************/
410 int TrimSeqsCommand::driverCreateTrim(string filename, string qFileName, string trimFile, string scrapFile, string trimQFile, string scrapQFile, string groupFile, vector<string> fastaNames, vector<string> qualNames, linePair* line, linePair* qline) {
415 int able = m->openOutputFile(trimFile, outFASTA);
418 m->openOutputFile(scrapFile, scrapFASTA);
423 m->openOutputFile(trimQFile, outQual);
424 m->openOutputFile(scrapQFile, scrapQual);
428 vector<ofstream*> fastaFileNames;
429 vector<ofstream*> qualFileNames;
431 if (oligoFile != "") {
432 m->openOutputFile(groupFile, outGroups);
433 for (int i = 0; i < fastaNames.size(); i++) {
435 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
436 fastaFileNames.push_back(new ofstream((fastaNames[i] + toString(getpid()) + ".temp").c_str(), ios::ate));
438 qualFileNames.push_back(new ofstream((qualNames[i] + toString(getpid()) + ".temp").c_str(), ios::ate));
441 fastaFileNames.push_back(new ofstream((fastaNames[i] + toString(i) + ".temp").c_str(), ios::ate));
443 qualFileNames.push_back(new ofstream((qualNames[i] + toString(i) + ".temp").c_str(), ios::ate));
450 m->openInputFile(filename, inFASTA);
451 inFASTA.seekg(line->start);
454 if(qFileName != "") { m->openInputFile(qFileName, qFile); qFile.seekg(qline->start); }
461 if (m->control_pressed) {
462 inFASTA.close(); outFASTA.close(); scrapFASTA.close();
463 if (oligoFile != "") { outGroups.close(); }
465 for(int i=0;i<fastaFileNames.size();i++){ fastaFileNames[i]->close(); delete fastaFileNames[i]; }
469 for(int i=0;i<qualFileNames.size();i++){ qualFileNames[i]->close(); delete qualFileNames[i]; }
471 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
479 Sequence currSeq(inFASTA); m->gobble(inFASTA);
481 QualityScores currQual;
483 currQual = QualityScores(qFile, currSeq.getNumBases()); m->gobble(qFile);
486 string origSeq = currSeq.getUnaligned();
488 int groupBar, groupPrime;
489 string trashCode = "";
490 int currentSeqsDiffs = 0;
493 if(qThreshold != 0) { success = currQual.stripQualThreshold(currSeq, qThreshold); }
494 else if(qAverage != 0) { success = currQual.cullQualAverage(currSeq, qAverage); }
495 else if(qRollAverage != 0) { success = currQual.stripQualRollingAverage(currSeq, qRollAverage); }
496 else if(qWindowAverage != 0){ success = currQual.stripQualWindowAverage(currSeq, qWindowStep, qWindowSize, qWindowAverage); }
498 if (qtrim == 1 && (origSeq.length() != currSeq.getUnaligned().length())) {
499 success = 0; //if you don't want to trim and the sequence does not meet quality requirements, move to scrap
502 if(!success) { trashCode += 'q'; }
505 if(barcodes.size() != 0){
506 success = stripBarcode(currSeq, currQual, groupBar);
507 if(success > bdiffs) { trashCode += 'b'; }
508 else{ currentSeqsDiffs += success; }
511 if(numFPrimers != 0){
512 success = stripForward(currSeq, currQual, groupPrime);
513 if(success > pdiffs) { trashCode += 'f'; }
514 else{ currentSeqsDiffs += success; }
517 if (currentSeqsDiffs > tdiffs) { trashCode += 't'; }
519 if(numRPrimers != 0){
520 success = stripReverse(currSeq, currQual);
521 if(!success) { trashCode += 'r'; }
524 if(minLength > 0 || maxLength > 0){
525 success = cullLength(currSeq);
526 if(!success) { trashCode += 'l'; }
529 success = cullHomoP(currSeq);
530 if(!success) { trashCode += 'h'; }
533 success = cullAmbigs(currSeq);
534 if(!success) { trashCode += 'n'; }
537 if(flip){ currSeq.reverseComplement(); currQual.flipQScores(); } // should go last
539 if(trashCode.length() == 0){
540 currSeq.setAligned(currSeq.getUnaligned());
541 currSeq.printSequence(outFASTA);
542 currQual.printQScores(outQual);
544 if(barcodes.size() != 0){
545 string thisGroup = groupVector[groupBar];
546 int indexToFastaFile = groupBar;
547 if (primers.size() != 0){
548 //does this primer have a group
549 if (groupVector[groupPrime] != "") {
550 thisGroup += "." + groupVector[groupPrime];
551 indexToFastaFile = combos[thisGroup];
554 outGroups << currSeq.getName() << '\t' << thisGroup << endl;
556 currSeq.printSequence(*fastaFileNames[indexToFastaFile]);
559 currQual.printQScores(*qualFileNames[indexToFastaFile]);
565 currSeq.setName(currSeq.getName() + '|' + trashCode);
566 currSeq.setUnaligned(origSeq);
567 currSeq.setAligned(origSeq);
568 currSeq.printSequence(scrapFASTA);
569 currQual.printQScores(scrapQual);
574 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
575 unsigned long int pos = inFASTA.tellg();
576 if ((pos == -1) || (pos >= line->end)) { break; }
578 if (inFASTA.eof()) { break; }
582 if((count) % 1000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
586 if((count) % 1000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
592 if (oligoFile != "") { outGroups.close(); }
593 if(qFileName != "") { qFile.close(); scrapQual.close(); outQual.close(); }
595 for(int i=0;i<fastaFileNames.size();i++){
596 fastaFileNames[i]->close();
597 delete fastaFileNames[i];
601 for(int i=0;i<qualFileNames.size();i++){
602 qualFileNames[i]->close();
603 delete qualFileNames[i];
609 catch(exception& e) {
610 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
615 /**************************************************************************************************/
617 int TrimSeqsCommand::createProcessesCreateTrim(string filename, string qFileName, string trimFile, string scrapFile, string trimQFile, string scrapQFile, string groupFile, vector<string> fastaNames, vector<string> qualNames) {
619 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
624 //loop through and create all the processes you want
625 while (process != processors) {
629 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
632 driverCreateTrim(filename, qFileName, (trimFile + toString(getpid()) + ".temp"), (scrapFile + toString(getpid()) + ".temp"), (trimQFile + toString(getpid()) + ".temp"), (scrapQFile + toString(getpid()) + ".temp"), (groupFile + toString(getpid()) + ".temp"), fastaNames, qualNames, lines[process], qLines[process]);
634 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
637 //force parent to wait until all the processes are done
638 for (int i=0;i<processors;i++) {
639 int temp = processIDS[i];
646 catch(exception& e) {
647 m->errorOut(e, "TrimSeqsCommand", "createProcessesCreateTrim");
652 /**************************************************************************************************/
654 int TrimSeqsCommand::setLines(string filename, string qfilename, vector<unsigned long int>& fastaFilePos, vector<unsigned long int>& qfileFilePos) {
657 //set file positions for fasta file
658 fastaFilePos = m->divideFile(filename, processors);
660 if (qfilename == "") { return processors; }
662 //get name of first sequence in each chunk
663 map<string, int> firstSeqNames;
664 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
666 m->openInputFile(filename, in);
667 in.seekg(fastaFilePos[i]);
670 firstSeqNames[temp.getName()] = i;
675 //seach for filePos of each first name in the qfile and save in qfileFilePos
677 m->openInputFile(qfilename, inQual);
680 while(!inQual.eof()){
681 input = m->getline(inQual);
683 if (input.length() != 0) {
684 if(input[0] == '>'){ //this is a sequence name line
685 istringstream nameStream(input);
687 string sname = ""; nameStream >> sname;
688 sname = sname.substr(1);
690 map<string, int>::iterator it = firstSeqNames.find(sname);
692 if(it != firstSeqNames.end()) { //this is the start of a new chunk
693 unsigned long int pos = inQual.tellg();
694 qfileFilePos.push_back(pos - input.length() - 1);
695 firstSeqNames.erase(it);
700 if (firstSeqNames.size() == 0) { break; }
704 if (firstSeqNames.size() != 0) {
705 for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
706 m->mothurOut(it->first + " is in your fasta file and not in your quality file, not using quality file."); m->mothurOutEndLine();
712 //get last file position of qfile
714 unsigned long int size;
716 //get num bytes in file
717 pFile = fopen (qfilename.c_str(),"rb");
718 if (pFile==NULL) perror ("Error opening file");
720 fseek (pFile, 0, SEEK_END);
725 qfileFilePos.push_back(size);
729 catch(exception& e) {
730 m->errorOut(e, "TrimSeqsCommand", "setLines");
734 //***************************************************************************************************************
736 void TrimSeqsCommand::getOligos(vector<string>& outFASTAVec, vector<string>& outQualVec){
739 m->openInputFile(oligoFile, inOligos);
743 string type, oligo, group;
745 //int indexPrimer = 0;
747 while(!inOligos.eof()){
751 while (!inOligos.eof()) { char c = inOligos.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
754 //make type case insensitive
755 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); }
759 for(int i=0;i<oligo.length();i++){
760 oligo[i] = toupper(oligo[i]);
761 if(oligo[i] == 'U') { oligo[i] = 'T'; }
764 if(type == "FORWARD"){
767 // get rest of line in case there is a primer name
768 while (!inOligos.eof()) {
769 char c = inOligos.get();
770 if (c == 10 || c == 13){ break; }
771 else if (c == 32 || c == 9){;} //space or tab
775 //check for repeat barcodes
776 map<string, int>::iterator itPrime = primers.find(oligo);
777 if (itPrime != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
779 primers[oligo]=index; index++;
780 groupVector.push_back(group);
783 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
785 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
787 if (group == "") { //if there is not a group for this primer, then this file will not get written to, but we add it to keep the indexes correct
788 filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
790 filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
793 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
795 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
801 else if(type == "REVERSE"){
802 Sequence oligoRC("reverse", oligo);
803 oligoRC.reverseComplement();
804 revPrimer.push_back(oligoRC.getUnaligned());
806 else if(type == "BARCODE"){
809 //check for repeat barcodes
810 map<string, int>::iterator itBar = barcodes.find(oligo);
811 if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
813 barcodes[oligo]=index; index++;
814 groupVector.push_back(group);
817 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
818 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
820 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
821 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
824 }else{ m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine(); }
831 //add in potential combos
833 comboStarts = outFASTAVec.size()-1;
834 for (map<string, int>::iterator itBar = barcodes.begin(); itBar != barcodes.end(); itBar++) {
835 for (map<string, int>::iterator itPrime = primers.begin(); itPrime != primers.end(); itPrime++) {
836 if (groupVector[itPrime->second] != "") { //there is a group for this primer
837 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
838 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
839 combos[(groupVector[itBar->second] + "." + groupVector[itPrime->second])] = outFASTAVec.size()-1;
842 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
843 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
850 numFPrimers = primers.size();
851 numRPrimers = revPrimer.size();
854 catch(exception& e) {
855 m->errorOut(e, "TrimSeqsCommand", "getOligos");
859 //***************************************************************************************************************
861 int TrimSeqsCommand::stripBarcode(Sequence& seq, QualityScores& qual, int& group){
864 string rawSequence = seq.getUnaligned();
865 int success = bdiffs + 1; //guilty until proven innocent
867 //can you find the barcode
868 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
869 string oligo = it->first;
870 if(rawSequence.length() < oligo.length()){ //let's just assume that the barcodes are the same length
871 success = bdiffs + 10; //if the sequence is shorter than the barcode then bail out
875 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
877 seq.setUnaligned(rawSequence.substr(oligo.length()));
879 if(qual.getName() != ""){
880 qual.trimQScores(oligo.length(), -1);
888 //if you found the barcode or if you don't want to allow for diffs
890 if ((bdiffs == 0) || (success == 0)) { return success; }
892 else { //try aligning and see if you can find it
897 Alignment* alignment;
898 if (barcodes.size() > 0) {
899 map<string,int>::iterator it=barcodes.begin();
901 for(it;it!=barcodes.end();it++){
902 if(it->first.length() > maxLength){
903 maxLength = it->first.length();
906 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));
908 }else{ alignment = NULL; }
910 //can you find the barcode
916 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
917 string oligo = it->first;
918 // int length = oligo.length();
920 if(rawSequence.length() < maxLength){ //let's just assume that the barcodes are the same length
921 success = bdiffs + 10;
925 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
926 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
927 oligo = alignment->getSeqAAln();
928 string temp = alignment->getSeqBAln();
930 int alnLength = oligo.length();
932 for(int i=oligo.length()-1;i>=0;i--){
933 if(oligo[i] != '-'){ alnLength = i+1; break; }
935 oligo = oligo.substr(0,alnLength);
936 temp = temp.substr(0,alnLength);
939 int numDiff = countDiffs(oligo, temp);
941 // cout << oligo << '\t' << temp << '\t' << numDiff << endl;
943 if(numDiff < minDiff){
946 minGroup = it->second;
948 for(int i=0;i<alnLength;i++){
954 else if(numDiff == minDiff){
960 if(minDiff > bdiffs) { success = minDiff; } //no good matches
961 else if(minCount > 1) { success = bdiffs + 100; } //can't tell the difference between multiple barcodes
962 else{ //use the best match
964 seq.setUnaligned(rawSequence.substr(minPos));
966 if(qual.getName() != ""){
967 qual.trimQScores(minPos, -1);
972 if (alignment != NULL) { delete alignment; }
975 // cout << success << endl;
980 catch(exception& e) {
981 m->errorOut(e, "TrimSeqsCommand", "stripBarcode");
987 //***************************************************************************************************************
989 int TrimSeqsCommand::stripForward(Sequence& seq, QualityScores& qual, int& group){
991 string rawSequence = seq.getUnaligned();
992 int success = pdiffs + 1; //guilty until proven innocent
994 //can you find the primer
995 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
996 string oligo = it->first;
997 if(rawSequence.length() < oligo.length()){ //let's just assume that the primers are the same length
998 success = pdiffs + 10; //if the sequence is shorter than the barcode then bail out
1002 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
1004 seq.setUnaligned(rawSequence.substr(oligo.length()));
1005 if(qual.getName() != ""){
1006 qual.trimQScores(oligo.length(), -1);
1014 //if you found the barcode or if you don't want to allow for diffs
1016 if ((pdiffs == 0) || (success == 0)) { return success; }
1018 else { //try aligning and see if you can find it
1023 Alignment* alignment;
1024 if (primers.size() > 0) {
1025 map<string,int>::iterator it=primers.begin();
1027 for(it;it!=primers.end();it++){
1028 if(it->first.length() > maxLength){
1029 maxLength = it->first.length();
1032 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));
1034 }else{ alignment = NULL; }
1036 //can you find the barcode
1042 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1043 string oligo = it->first;
1044 // int length = oligo.length();
1046 if(rawSequence.length() < maxLength){
1047 success = pdiffs + 100;
1051 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1052 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
1053 oligo = alignment->getSeqAAln();
1054 string temp = alignment->getSeqBAln();
1056 int alnLength = oligo.length();
1058 for(int i=oligo.length()-1;i>=0;i--){
1059 if(oligo[i] != '-'){ alnLength = i+1; break; }
1061 oligo = oligo.substr(0,alnLength);
1062 temp = temp.substr(0,alnLength);
1065 int numDiff = countDiffs(oligo, temp);
1067 // cout << oligo << '\t' << temp << '\t' << numDiff << endl;
1069 if(numDiff < minDiff){
1072 minGroup = it->second;
1074 for(int i=0;i<alnLength;i++){
1080 else if(numDiff == minDiff){
1086 if(minDiff > pdiffs) { success = minDiff; } //no good matches
1087 else if(minCount > 1) { success = pdiffs + 10; } //can't tell the difference between multiple primers
1088 else{ //use the best match
1090 seq.setUnaligned(rawSequence.substr(minPos));
1091 if(qual.getName() != ""){
1092 qual.trimQScores(minPos, -1);
1097 if (alignment != NULL) { delete alignment; }
1104 catch(exception& e) {
1105 m->errorOut(e, "TrimSeqsCommand", "stripForward");
1110 //***************************************************************************************************************
1112 bool TrimSeqsCommand::stripReverse(Sequence& seq, QualityScores& qual){
1114 string rawSequence = seq.getUnaligned();
1115 bool success = 0; //guilty until proven innocent
1117 for(int i=0;i<numRPrimers;i++){
1118 string oligo = revPrimer[i];
1120 if(rawSequence.length() < oligo.length()){
1125 if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
1126 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
1127 if(qual.getName() != ""){
1128 qual.trimQScores(-1, rawSequence.length()-oligo.length());
1137 catch(exception& e) {
1138 m->errorOut(e, "TrimSeqsCommand", "stripReverse");
1143 //***************************************************************************************************************
1145 bool TrimSeqsCommand::cullLength(Sequence& seq){
1148 int length = seq.getNumBases();
1149 bool success = 0; //guilty until proven innocent
1151 if(length >= minLength && maxLength == 0) { success = 1; }
1152 else if(length >= minLength && length <= maxLength) { success = 1; }
1153 else { success = 0; }
1158 catch(exception& e) {
1159 m->errorOut(e, "TrimSeqsCommand", "cullLength");
1165 //***************************************************************************************************************
1167 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
1169 int longHomoP = seq.getLongHomoPolymer();
1170 bool success = 0; //guilty until proven innocent
1172 if(longHomoP <= maxHomoP){ success = 1; }
1173 else { success = 0; }
1177 catch(exception& e) {
1178 m->errorOut(e, "TrimSeqsCommand", "cullHomoP");
1184 //***************************************************************************************************************
1186 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
1188 int numNs = seq.getAmbigBases();
1189 bool success = 0; //guilty until proven innocent
1191 if(numNs <= maxAmbig) { success = 1; }
1192 else { success = 0; }
1196 catch(exception& e) {
1197 m->errorOut(e, "TrimSeqsCommand", "cullAmbigs");
1203 //***************************************************************************************************************
1205 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
1208 int length = oligo.length();
1210 for(int i=0;i<length;i++){
1212 if(oligo[i] != seq[i]){
1213 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C') { success = 0; }
1214 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { success = 0; }
1215 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { success = 0; }
1216 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { success = 0; }
1217 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { success = 0; }
1218 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
1219 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { success = 0; }
1220 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
1221 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
1222 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
1223 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { success = 0; }
1224 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
1226 if(success == 0) { break; }
1235 catch(exception& e) {
1236 m->errorOut(e, "TrimSeqsCommand", "compareDNASeq");
1241 //***************************************************************************************************************
1243 int TrimSeqsCommand::countDiffs(string oligo, string seq){
1246 int length = oligo.length();
1249 for(int i=0;i<length;i++){
1251 if(oligo[i] != seq[i]){
1252 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.') { countDiffs++; }
1253 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { countDiffs++; }
1254 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { countDiffs++; }
1255 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { countDiffs++; }
1256 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { countDiffs++; }
1257 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
1258 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { countDiffs++; }
1259 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
1260 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
1261 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
1262 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { countDiffs++; }
1263 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
1270 catch(exception& e) {
1271 m->errorOut(e, "TrimSeqsCommand", "countDiffs");
1276 //***************************************************************************************************************
1278 //bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
1281 // string rawSequence = seq.getUnaligned();
1282 // int seqLength = seq.getNumBases();
1283 // bool success = 0; //guilty until proven innocent
1287 // if (name[0] == '>') { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); } }
1289 // while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
1292 // int end = seqLength;
1294 // for(int i=0;i<seqLength;i++){
1297 // if(score < qThreshold){
1302 // for(int i=end+1;i<seqLength;i++){
1306 // seq.setUnaligned(rawSequence.substr(0,end));
1310 // catch(exception& e) {
1311 // m->errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
1316 //***************************************************************************************************************
1318 //bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
1320 // string rawSequence = seq.getUnaligned();
1321 // int seqLength = seq.getNumBases();
1322 // bool success = 0; //guilty until proven innocent
1326 // if (name[0] == '>') { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); } }
1328 // while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
1331 // float average = 0;
1333 // for(int i=0;i<seqLength;i++){
1335 // average += score;
1337 // average /= seqLength;
1339 // if(average >= qAverage) { success = 1; }
1340 // else { success = 0; }
1344 // catch(exception& e) {
1345 // m->errorOut(e, "TrimSeqsCommand", "cullQualAverage");
1350 //***************************************************************************************************************