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 outputNames.push_back(trimQualFile);
228 string scrapQualFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "scrap.qual";
229 outputNames.push_back(scrapQualFile);
230 string groupFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "groups";
232 vector<string> fastaFileNames;
233 vector<string> qualFileNames;
235 outputNames.push_back(groupFile);
236 getOligos(fastaFileNames, qualFileNames);
239 vector<unsigned long int> fastaFilePos;
240 vector<unsigned long int> qFilePos;
242 setLines(fastaFile, qFileName, fastaFilePos, qFilePos);
244 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
245 lines.push_back(new linePair(fastaFilePos[i], fastaFilePos[(i+1)]));
246 if (qFileName != "") { qLines.push_back(new linePair(qFilePos[i], qFilePos[(i+1)])); }
248 if(qFileName == "") { qLines = lines; } //files with duds
250 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
253 driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], qLines[0]);
255 for (int j = 0; j < fastaFileNames.size(); j++) {
256 rename((fastaFileNames[j] + toString(getpid()) + ".temp").c_str(), fastaFileNames[j].c_str());
259 for (int j = 0; j < qualFileNames.size(); j++) {
260 rename((qualFileNames[j] + toString(getpid()) + ".temp").c_str(), qualFileNames[j].c_str());
265 createProcessesCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames);
267 rename((trimSeqFile + toString(processIDS[0]) + ".temp").c_str(), trimSeqFile.c_str());
268 rename((scrapSeqFile + toString(processIDS[0]) + ".temp").c_str(), scrapSeqFile.c_str());
269 rename((groupFile + toString(processIDS[0]) + ".temp").c_str(), groupFile.c_str());
272 rename((trimQualFile + toString(processIDS[0]) + ".temp").c_str(), trimQualFile.c_str());
273 rename((scrapQualFile + toString(processIDS[0]) + ".temp").c_str(), scrapQualFile.c_str());
277 for (int j = 0; j < fastaFileNames.size(); j++) {
278 rename((fastaFileNames[j] + toString(processIDS[0]) + ".temp").c_str(), fastaFileNames[j].c_str());
281 for (int j = 0; j < qualFileNames.size(); j++) {
282 rename((qualFileNames[j] + toString(getpid()) + ".temp").c_str(), qualFileNames[j].c_str());
287 for(int i=1;i<processors;i++){
288 m->appendFiles((trimSeqFile + toString(processIDS[i]) + ".temp"), trimSeqFile);
289 remove((trimSeqFile + toString(processIDS[i]) + ".temp").c_str());
290 m->appendFiles((scrapSeqFile + toString(processIDS[i]) + ".temp"), scrapSeqFile);
291 remove((scrapSeqFile + toString(processIDS[i]) + ".temp").c_str());
293 m->appendFiles((trimQualFile + toString(processIDS[i]) + ".temp"), trimQualFile);
294 remove((trimQualFile + toString(processIDS[i]) + ".temp").c_str());
295 m->appendFiles((scrapQualFile + toString(processIDS[i]) + ".temp"), scrapQualFile);
296 remove((scrapQualFile + toString(processIDS[i]) + ".temp").c_str());
298 m->appendFiles((groupFile + toString(processIDS[i]) + ".temp"), groupFile);
299 remove((groupFile + toString(processIDS[i]) + ".temp").c_str());
300 for (int j = 0; j < fastaFileNames.size(); j++) {
301 m->appendFiles((fastaFileNames[j] + toString(processIDS[i]) + ".temp"), fastaFileNames[j]);
302 remove((fastaFileNames[j] + toString(processIDS[i]) + ".temp").c_str());
306 for (int j = 0; j < qualFileNames.size(); j++) {
307 m->appendFiles((qualFileNames[j] + toString(processIDS[i]) + ".temp"), qualFileNames[j]);
308 remove((qualFileNames[j] + toString(processIDS[i]) + ".temp").c_str());
316 if (m->control_pressed) { return 0; }
318 driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], qlines[0]);
320 for (int j = 0; j < fastaFileNames.size(); j++) {
321 rename((fastaFileNames[j] + toString(j) + ".temp").c_str(), fastaFileNames[j].c_str());
324 for (int j = 0; j < qualFileNames.size(); j++) {
325 rename((qualFileNames[j] + toString(j) + ".temp").c_str(), qualFileNames[j].c_str());
329 if (m->control_pressed) { return 0; }
333 for(int i=0;i<fastaFileNames.size();i++){
334 if (m->isBlank(fastaFileNames[i])) { remove(fastaFileNames[i].c_str()); }
335 else if (filesToRemove.count(fastaFileNames[i]) > 0) { remove(fastaFileNames[i].c_str()); }
339 m->openInputFile(fastaFileNames[i], inFASTA);
341 string outGroupFilename = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[i])) + "groups";
342 m->openOutputFile(outGroupFilename, outGroups);
343 outputNames.push_back(outGroupFilename);
345 string thisGroup = "";
346 if (i > comboStarts) {
347 map<string, int>::iterator itCombo;
348 for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
349 if(itCombo->second == i){ thisGroup = itCombo->first; combos.erase(itCombo); break; }
351 }else{ thisGroup = groupVector[i]; }
353 while(!inFASTA.eof()){
354 if(inFASTA.get() == '>'){
356 outGroups << seqName << '\t' << thisGroup << endl;
358 while (!inFASTA.eof()) { char c = inFASTA.get(); if (c == 10 || c == 13){ break; } }
366 for(int i=0;i<qualFileNames.size();i++){
367 if (m->isBlank(qualFileNames[i])) { remove(qualFileNames[i].c_str()); }
368 else if (filesToRemove.count(qualFileNames[i]) > 0) { remove(qualFileNames[i].c_str()); }
372 m->openInputFile(qualFileNames[i], inQual);
373 // ofstream outGroups;
375 // string thisGroup = "";
376 // if (i > comboStarts) {
377 // map<string, int>::iterator itCombo;
378 // for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
379 // if(itCombo->second == i){ thisGroup = itCombo->first; combos.erase(itCombo); break; }
382 // else{ thisGroup = groupVector[i]; }
390 if (m->control_pressed) {
391 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
395 m->mothurOutEndLine();
396 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
397 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
398 m->mothurOutEndLine();
403 catch(exception& e) {
404 m->errorOut(e, "TrimSeqsCommand", "execute");
409 /**************************************************************************************/
411 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) {
416 int able = m->openOutputFile(trimFile, outFASTA);
419 m->openOutputFile(scrapFile, scrapFASTA);
424 m->openOutputFile(trimQFile, outQual);
425 m->openOutputFile(scrapQFile, scrapQual);
429 vector<ofstream*> fastaFileNames;
430 vector<ofstream*> qualFileNames;
433 if (oligoFile != "") {
434 m->openOutputFile(groupFile, outGroups);
435 for (int i = 0; i < fastaNames.size(); i++) {
436 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
437 fastaFileNames.push_back(new ofstream((fastaNames[i] + toString(getpid()) + ".temp").c_str(), ios::ate));
439 qualFileNames.push_back(new ofstream((qualNames[i] + toString(getpid()) + ".temp").c_str(), ios::ate));
442 fastaFileNames.push_back(new ofstream((fastaNames[i] + toString(i) + ".temp").c_str(), ios::ate));
444 qualFileNames.push_back(new ofstream((qualNames[i] + toString(i) + ".temp").c_str(), ios::ate));
451 m->openInputFile(filename, inFASTA);
452 inFASTA.seekg(line->start);
455 if(qFileName != "") { m->openInputFile(qFileName, qFile); qFile.seekg(qline->start); }
462 if (m->control_pressed) {
463 inFASTA.close(); outFASTA.close(); scrapFASTA.close();
464 if (oligoFile != "") { outGroups.close(); }
466 for(int i=0;i<fastaFileNames.size();i++){ fastaFileNames[i]->close(); delete fastaFileNames[i]; }
470 for(int i=0;i<qualFileNames.size();i++){ qualFileNames[i]->close(); delete qualFileNames[i]; }
472 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
480 Sequence currSeq(inFASTA); m->gobble(inFASTA);
482 QualityScores currQual;
484 currQual = QualityScores(qFile, currSeq.getNumBases()); m->gobble(qFile);
487 string origSeq = currSeq.getUnaligned();
489 int groupBar, groupPrime;
490 string trashCode = "";
491 int currentSeqsDiffs = 0;
494 if(qThreshold != 0) { success = currQual.stripQualThreshold(currSeq, qThreshold); }
495 else if(qAverage != 0) { success = currQual.cullQualAverage(currSeq, qAverage); }
496 else if(qRollAverage != 0) { success = currQual.stripQualRollingAverage(currSeq, qRollAverage); }
497 else if(qWindowAverage != 0){ success = currQual.stripQualWindowAverage(currSeq, qWindowStep, qWindowSize, qWindowAverage); }
499 if (qtrim == 1 && (origSeq.length() != currSeq.getUnaligned().length())) {
500 success = 0; //if you don't want to trim and the sequence does not meet quality requirements, move to scrap
503 if(!success) { trashCode += 'q'; }
506 if(barcodes.size() != 0){
507 success = stripBarcode(currSeq, currQual, groupBar);
508 if(success > bdiffs) { trashCode += 'b'; }
509 else{ currentSeqsDiffs += success; }
512 if(numFPrimers != 0){
513 success = stripForward(currSeq, currQual, groupPrime);
514 if(success > pdiffs) { trashCode += 'f'; }
515 else{ currentSeqsDiffs += success; }
518 if (currentSeqsDiffs > tdiffs) { trashCode += 't'; }
520 if(numRPrimers != 0){
521 success = stripReverse(currSeq, currQual);
522 if(!success) { trashCode += 'r'; }
525 if(minLength > 0 || maxLength > 0){
526 success = cullLength(currSeq);
527 if(!success) { trashCode += 'l'; }
530 success = cullHomoP(currSeq);
531 if(!success) { trashCode += 'h'; }
534 success = cullAmbigs(currSeq);
535 if(!success) { trashCode += 'n'; }
538 if(flip){ currSeq.reverseComplement(); currQual.flipQScores(); } // should go last
540 if(trashCode.length() == 0){
541 currSeq.setAligned(currSeq.getUnaligned());
542 currSeq.printSequence(outFASTA);
543 currQual.printQScores(outQual);
545 if(barcodes.size() != 0){
546 string thisGroup = groupVector[groupBar];
547 int indexToFastaFile = groupBar;
548 if (primers.size() != 0){
549 //does this primer have a group
550 if (groupVector[groupPrime] != "") {
551 thisGroup += "." + groupVector[groupPrime];
552 indexToFastaFile = combos[thisGroup];
555 outGroups << currSeq.getName() << '\t' << thisGroup << endl;
557 currSeq.printSequence(*fastaFileNames[indexToFastaFile]);
560 currQual.printQScores(*qualFileNames[indexToFastaFile]);
566 currSeq.setName(currSeq.getName() + '|' + trashCode);
567 currSeq.setUnaligned(origSeq);
568 currSeq.setAligned(origSeq);
569 currSeq.printSequence(scrapFASTA);
570 currQual.printQScores(scrapQual);
575 unsigned long int pos = inFASTA.tellg();
576 if ((pos == -1) || (pos >= line->end)) { break; }
579 if((count) % 1000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
583 if((count) % 1000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
589 if (oligoFile != "") { outGroups.close(); }
590 if(qFileName != "") { qFile.close(); scrapQual.close(); outQual.close(); }
592 for(int i=0;i<fastaFileNames.size();i++){
593 fastaFileNames[i]->close();
594 delete fastaFileNames[i];
598 for(int i=0;i<qualFileNames.size();i++){
599 qualFileNames[i]->close();
600 delete qualFileNames[i];
606 catch(exception& e) {
607 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
612 /**************************************************************************************************/
614 int TrimSeqsCommand::createProcessesCreateTrim(string filename, string qFileName, string trimFile, string scrapFile, string trimQFile, string scrapQFile, string groupFile, vector<string> fastaNames, vector<string> qualNames) {
616 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
621 //loop through and create all the processes you want
622 while (process != processors) {
626 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
629 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]);
631 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
634 //force parent to wait until all the processes are done
635 for (int i=0;i<processors;i++) {
636 int temp = processIDS[i];
643 catch(exception& e) {
644 m->errorOut(e, "TrimSeqsCommand", "createProcessesCreateTrim");
649 /**************************************************************************************************/
651 int TrimSeqsCommand::setLines(string filename, string qfilename, vector<unsigned long int>& fastaFilePos, vector<unsigned long int>& qfileFilePos) {
654 //set file positions for fasta file
655 fastaFilePos = m->divideFile(filename, processors);
657 if (qfilename == "") { return processors; }
659 //get name of first sequence in each chunk
660 map<string, int> firstSeqNames;
661 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
663 m->openInputFile(filename, in);
664 in.seekg(fastaFilePos[i]);
667 firstSeqNames[temp.getName()] = i;
672 //seach for filePos of each first name in the qfile and save in qfileFilePos
674 m->openInputFile(qfilename, inQual);
677 while(!inQual.eof()){
678 input = m->getline(inQual);
680 if (input.length() != 0) {
681 if(input[0] == '>'){ //this is a sequence name line
682 istringstream nameStream(input);
684 string sname = ""; nameStream >> sname;
685 sname = sname.substr(1);
687 map<string, int>::iterator it = firstSeqNames.find(sname);
689 if(it != firstSeqNames.end()) { //this is the start of a new chunk
690 unsigned long int pos = inQual.tellg();
691 qfileFilePos.push_back(pos - input.length() - 1);
692 firstSeqNames.erase(it);
697 if (firstSeqNames.size() == 0) { break; }
701 if (firstSeqNames.size() != 0) {
702 for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
703 m->mothurOut(it->first + " is in your fasta file and not in your quality file, not using quality file."); m->mothurOutEndLine();
709 //get last file position of qfile
711 unsigned long int size;
713 //get num bytes in file
714 pFile = fopen (qfilename.c_str(),"rb");
715 if (pFile==NULL) perror ("Error opening file");
717 fseek (pFile, 0, SEEK_END);
722 qfileFilePos.push_back(size);
726 catch(exception& e) {
727 m->errorOut(e, "TrimSeqsCommand", "setLines");
731 //***************************************************************************************************************
733 void TrimSeqsCommand::getOligos(vector<string>& outFASTAVec, vector<string>& outQualVec){
736 m->openInputFile(oligoFile, inOligos);
740 string type, oligo, group;
742 //int indexPrimer = 0;
744 while(!inOligos.eof()){
748 while (!inOligos.eof()) { char c = inOligos.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
751 //make type case insensitive
752 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); }
756 for(int i=0;i<oligo.length();i++){
757 oligo[i] = toupper(oligo[i]);
758 if(oligo[i] == 'U') { oligo[i] = 'T'; }
761 if(type == "FORWARD"){
764 // get rest of line in case there is a primer name
765 while (!inOligos.eof()) {
766 char c = inOligos.get();
767 if (c == 10 || c == 13){ break; }
768 else if (c == 32 || c == 9){;} //space or tab
772 //check for repeat barcodes
773 map<string, int>::iterator itPrime = primers.find(oligo);
774 if (itPrime != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
776 primers[oligo]=index; index++;
777 groupVector.push_back(group);
780 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
782 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
784 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
785 filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
787 filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
790 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
792 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
798 else if(type == "REVERSE"){
799 Sequence oligoRC("reverse", oligo);
800 oligoRC.reverseComplement();
801 revPrimer.push_back(oligoRC.getUnaligned());
803 else if(type == "BARCODE"){
806 //check for repeat barcodes
807 map<string, int>::iterator itBar = barcodes.find(oligo);
808 if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
810 barcodes[oligo]=index; index++;
811 groupVector.push_back(group);
814 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
815 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
817 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
818 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
821 }else{ m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine(); }
828 //add in potential combos
830 comboStarts = outFASTAVec.size()-1;
831 for (map<string, int>::iterator itBar = barcodes.begin(); itBar != barcodes.end(); itBar++) {
832 for (map<string, int>::iterator itPrime = primers.begin(); itPrime != primers.end(); itPrime++) {
833 if (groupVector[itPrime->second] != "") { //there is a group for this primer
834 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
835 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
836 combos[(groupVector[itBar->second] + "." + groupVector[itPrime->second])] = outFASTAVec.size()-1;
839 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
840 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
847 numFPrimers = primers.size();
848 numRPrimers = revPrimer.size();
851 catch(exception& e) {
852 m->errorOut(e, "TrimSeqsCommand", "getOligos");
856 //***************************************************************************************************************
858 int TrimSeqsCommand::stripBarcode(Sequence& seq, QualityScores& qual, int& group){
861 string rawSequence = seq.getUnaligned();
862 int success = bdiffs + 1; //guilty until proven innocent
864 //can you find the barcode
865 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
866 string oligo = it->first;
867 if(rawSequence.length() < oligo.length()){ //let's just assume that the barcodes are the same length
868 success = bdiffs + 10; //if the sequence is shorter than the barcode then bail out
872 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
874 seq.setUnaligned(rawSequence.substr(oligo.length()));
876 if(qual.getName() != ""){
877 qual.trimQScores(oligo.length(), -1);
885 //if you found the barcode or if you don't want to allow for diffs
887 if ((bdiffs == 0) || (success == 0)) { return success; }
889 else { //try aligning and see if you can find it
894 Alignment* alignment;
895 if (barcodes.size() > 0) {
896 map<string,int>::iterator it=barcodes.begin();
898 for(it;it!=barcodes.end();it++){
899 if(it->first.length() > maxLength){
900 maxLength = it->first.length();
903 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));
905 }else{ alignment = NULL; }
907 //can you find the barcode
913 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
914 string oligo = it->first;
915 // int length = oligo.length();
917 if(rawSequence.length() < maxLength){ //let's just assume that the barcodes are the same length
918 success = bdiffs + 10;
922 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
923 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
924 oligo = alignment->getSeqAAln();
925 string temp = alignment->getSeqBAln();
927 int alnLength = oligo.length();
929 for(int i=oligo.length()-1;i>=0;i--){
930 if(oligo[i] != '-'){ alnLength = i+1; break; }
932 oligo = oligo.substr(0,alnLength);
933 temp = temp.substr(0,alnLength);
936 int numDiff = countDiffs(oligo, temp);
938 // cout << oligo << '\t' << temp << '\t' << numDiff << endl;
940 if(numDiff < minDiff){
943 minGroup = it->second;
945 for(int i=0;i<alnLength;i++){
951 else if(numDiff == minDiff){
957 if(minDiff > bdiffs) { success = minDiff; } //no good matches
958 else if(minCount > 1) { success = bdiffs + 100; } //can't tell the difference between multiple barcodes
959 else{ //use the best match
961 seq.setUnaligned(rawSequence.substr(minPos));
963 if(qual.getName() != ""){
964 qual.trimQScores(minPos, -1);
969 if (alignment != NULL) { delete alignment; }
972 // cout << success << endl;
977 catch(exception& e) {
978 m->errorOut(e, "TrimSeqsCommand", "stripBarcode");
984 //***************************************************************************************************************
986 int TrimSeqsCommand::stripForward(Sequence& seq, QualityScores& qual, int& group){
988 string rawSequence = seq.getUnaligned();
989 int success = pdiffs + 1; //guilty until proven innocent
991 //can you find the primer
992 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
993 string oligo = it->first;
994 if(rawSequence.length() < oligo.length()){ //let's just assume that the primers are the same length
995 success = pdiffs + 10; //if the sequence is shorter than the barcode then bail out
999 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
1001 seq.setUnaligned(rawSequence.substr(oligo.length()));
1002 if(qual.getName() != ""){
1003 qual.trimQScores(oligo.length(), -1);
1011 //if you found the barcode or if you don't want to allow for diffs
1013 if ((pdiffs == 0) || (success == 0)) { return success; }
1015 else { //try aligning and see if you can find it
1020 Alignment* alignment;
1021 if (primers.size() > 0) {
1022 map<string,int>::iterator it=primers.begin();
1024 for(it;it!=primers.end();it++){
1025 if(it->first.length() > maxLength){
1026 maxLength = it->first.length();
1029 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));
1031 }else{ alignment = NULL; }
1033 //can you find the barcode
1039 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1040 string oligo = it->first;
1041 // int length = oligo.length();
1043 if(rawSequence.length() < maxLength){
1044 success = pdiffs + 100;
1048 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1049 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
1050 oligo = alignment->getSeqAAln();
1051 string temp = alignment->getSeqBAln();
1053 int alnLength = oligo.length();
1055 for(int i=oligo.length()-1;i>=0;i--){
1056 if(oligo[i] != '-'){ alnLength = i+1; break; }
1058 oligo = oligo.substr(0,alnLength);
1059 temp = temp.substr(0,alnLength);
1062 int numDiff = countDiffs(oligo, temp);
1064 // cout << oligo << '\t' << temp << '\t' << numDiff << endl;
1066 if(numDiff < minDiff){
1069 minGroup = it->second;
1071 for(int i=0;i<alnLength;i++){
1077 else if(numDiff == minDiff){
1083 if(minDiff > pdiffs) { success = minDiff; } //no good matches
1084 else if(minCount > 1) { success = pdiffs + 10; } //can't tell the difference between multiple primers
1085 else{ //use the best match
1087 seq.setUnaligned(rawSequence.substr(minPos));
1088 if(qual.getName() != ""){
1089 qual.trimQScores(minPos, -1);
1094 if (alignment != NULL) { delete alignment; }
1101 catch(exception& e) {
1102 m->errorOut(e, "TrimSeqsCommand", "stripForward");
1107 //***************************************************************************************************************
1109 bool TrimSeqsCommand::stripReverse(Sequence& seq, QualityScores& qual){
1111 string rawSequence = seq.getUnaligned();
1112 bool success = 0; //guilty until proven innocent
1114 for(int i=0;i<numRPrimers;i++){
1115 string oligo = revPrimer[i];
1117 if(rawSequence.length() < oligo.length()){
1122 if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
1123 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
1124 if(qual.getName() != ""){
1125 qual.trimQScores(-1, rawSequence.length()-oligo.length());
1134 catch(exception& e) {
1135 m->errorOut(e, "TrimSeqsCommand", "stripReverse");
1140 //***************************************************************************************************************
1142 bool TrimSeqsCommand::cullLength(Sequence& seq){
1145 int length = seq.getNumBases();
1146 bool success = 0; //guilty until proven innocent
1148 if(length >= minLength && maxLength == 0) { success = 1; }
1149 else if(length >= minLength && length <= maxLength) { success = 1; }
1150 else { success = 0; }
1155 catch(exception& e) {
1156 m->errorOut(e, "TrimSeqsCommand", "cullLength");
1162 //***************************************************************************************************************
1164 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
1166 int longHomoP = seq.getLongHomoPolymer();
1167 bool success = 0; //guilty until proven innocent
1169 if(longHomoP <= maxHomoP){ success = 1; }
1170 else { success = 0; }
1174 catch(exception& e) {
1175 m->errorOut(e, "TrimSeqsCommand", "cullHomoP");
1181 //***************************************************************************************************************
1183 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
1185 int numNs = seq.getAmbigBases();
1186 bool success = 0; //guilty until proven innocent
1188 if(numNs <= maxAmbig) { success = 1; }
1189 else { success = 0; }
1193 catch(exception& e) {
1194 m->errorOut(e, "TrimSeqsCommand", "cullAmbigs");
1200 //***************************************************************************************************************
1202 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
1205 int length = oligo.length();
1207 for(int i=0;i<length;i++){
1209 if(oligo[i] != seq[i]){
1210 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C') { success = 0; }
1211 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { success = 0; }
1212 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { success = 0; }
1213 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { success = 0; }
1214 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { success = 0; }
1215 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
1216 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { success = 0; }
1217 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
1218 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
1219 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
1220 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { success = 0; }
1221 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
1223 if(success == 0) { break; }
1232 catch(exception& e) {
1233 m->errorOut(e, "TrimSeqsCommand", "compareDNASeq");
1238 //***************************************************************************************************************
1240 int TrimSeqsCommand::countDiffs(string oligo, string seq){
1243 int length = oligo.length();
1246 for(int i=0;i<length;i++){
1248 if(oligo[i] != seq[i]){
1249 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.') { countDiffs++; }
1250 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { countDiffs++; }
1251 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { countDiffs++; }
1252 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { countDiffs++; }
1253 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { countDiffs++; }
1254 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
1255 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { countDiffs++; }
1256 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
1257 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
1258 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
1259 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { countDiffs++; }
1260 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
1267 catch(exception& e) {
1268 m->errorOut(e, "TrimSeqsCommand", "countDiffs");
1273 //***************************************************************************************************************
1275 //bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
1278 // string rawSequence = seq.getUnaligned();
1279 // int seqLength = seq.getNumBases();
1280 // bool success = 0; //guilty until proven innocent
1284 // if (name[0] == '>') { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); } }
1286 // while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
1289 // int end = seqLength;
1291 // for(int i=0;i<seqLength;i++){
1294 // if(score < qThreshold){
1299 // for(int i=end+1;i<seqLength;i++){
1303 // seq.setUnaligned(rawSequence.substr(0,end));
1307 // catch(exception& e) {
1308 // m->errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
1313 //***************************************************************************************************************
1315 //bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
1317 // string rawSequence = seq.getUnaligned();
1318 // int seqLength = seq.getNumBases();
1319 // bool success = 0; //guilty until proven innocent
1323 // if (name[0] == '>') { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); } }
1325 // while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
1328 // float average = 0;
1330 // for(int i=0;i<seqLength;i++){
1332 // average += score;
1334 // average /= seqLength;
1336 // if(average >= qAverage) { success = 1; }
1337 // else { success = 0; }
1341 // catch(exception& e) {
1342 // m->errorOut(e, "TrimSeqsCommand", "cullQualAverage");
1347 //***************************************************************************************************************