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 //**********************************************************************************************************************
14 vector<string> TrimSeqsCommand::getValidParameters(){
16 string Array[] = {"fasta", "flip", "oligos", "maxambig", "maxhomop", "minlength", "maxlength", "qfile",
17 "qthreshold", "qwindowaverage", "qstepsize", "qwindowsize", "qaverage", "rollaverage", "allfiles", "qtrim","tdiffs", "pdiffs", "bdiffs", "processors", "outputdir","inputdir"};
18 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
22 m->errorOut(e, "TrimSeqsCommand", "getValidParameters");
26 //**********************************************************************************************************************
27 TrimSeqsCommand::TrimSeqsCommand(){
29 //initialize outputTypes
30 vector<string> tempOutNames;
31 outputTypes["fasta"] = tempOutNames;
32 outputTypes["qual"] = tempOutNames;
33 outputTypes["group"] = tempOutNames;
36 m->errorOut(e, "TrimSeqsCommand", "TrimSeqsCommand");
40 //**********************************************************************************************************************
41 vector<string> TrimSeqsCommand::getRequiredParameters(){
43 string Array[] = {"fasta"};
44 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
48 m->errorOut(e, "TrimSeqsCommand", "getRequiredParameters");
52 //**********************************************************************************************************************
53 vector<string> TrimSeqsCommand::getRequiredFiles(){
55 vector<string> myArray;
59 m->errorOut(e, "TrimSeqsCommand", "getRequiredFiles");
63 //***************************************************************************************************************
65 TrimSeqsCommand::TrimSeqsCommand(string option) {
71 //allow user to run help
72 if(option == "help") { help(); abort = true; }
75 //valid paramters for this command
76 string AlignArray[] = {"fasta", "flip", "oligos", "maxambig", "maxhomop", "minlength", "maxlength", "qfile",
77 "qthreshold", "qwindowaverage", "qstepsize", "qwindowsize", "qaverage", "rollaverage", "allfiles", "qtrim","tdiffs", "pdiffs", "bdiffs", "processors", "outputdir","inputdir"};
79 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
81 OptionParser parser(option);
82 map<string,string> parameters = parser.getParameters();
84 ValidParameters validParameter;
85 map<string,string>::iterator it;
87 //check to make sure all parameters are valid for command
88 for (it = parameters.begin(); it != parameters.end(); it++) {
89 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
92 //initialize outputTypes
93 vector<string> tempOutNames;
94 outputTypes["fasta"] = tempOutNames;
95 outputTypes["qual"] = tempOutNames;
96 outputTypes["group"] = tempOutNames;
98 //if the user changes the input directory command factory will send this info to us in the output parameter
99 string inputDir = validParameter.validFile(parameters, "inputdir", false);
100 if (inputDir == "not found"){ inputDir = ""; }
103 it = parameters.find("fasta");
104 //user has given a template file
105 if(it != parameters.end()){
106 path = m->hasPath(it->second);
107 //if the user has not given a path then, add inputdir. else leave path alone.
108 if (path == "") { parameters["fasta"] = inputDir + it->second; }
111 it = parameters.find("oligos");
112 //user has given a template file
113 if(it != parameters.end()){
114 path = m->hasPath(it->second);
115 //if the user has not given a path then, add inputdir. else leave path alone.
116 if (path == "") { parameters["oligos"] = inputDir + it->second; }
119 it = parameters.find("qfile");
120 //user has given a template file
121 if(it != parameters.end()){
122 path = m->hasPath(it->second);
123 //if the user has not given a path then, add inputdir. else leave path alone.
124 if (path == "") { parameters["qfile"] = inputDir + it->second; }
129 //check for required parameters
130 fastaFile = validParameter.validFile(parameters, "fasta", true);
131 if (fastaFile == "not found") { m->mothurOut("fasta is a required parameter for the trim.seqs command."); m->mothurOutEndLine(); abort = true; }
132 else if (fastaFile == "not open") { abort = true; }
134 //if the user changes the output directory command factory will send this info to us in the output parameter
135 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
137 outputDir += m->hasPath(fastaFile); //if user entered a file with a path then preserve it
141 //check for optional parameter and set defaults
142 // ...at some point should added some additional type checking...
144 temp = validParameter.validFile(parameters, "flip", false);
145 if (temp == "not found"){ flip = 0; }
146 else if(m->isTrue(temp)) { flip = 1; }
148 temp = validParameter.validFile(parameters, "oligos", true);
149 if (temp == "not found"){ oligoFile = ""; }
150 else if(temp == "not open"){ abort = true; }
151 else { oligoFile = temp; }
153 temp = validParameter.validFile(parameters, "maxambig", false); if (temp == "not found") { temp = "-1"; }
154 convert(temp, maxAmbig);
156 temp = validParameter.validFile(parameters, "maxhomop", false); if (temp == "not found") { temp = "0"; }
157 convert(temp, maxHomoP);
159 temp = validParameter.validFile(parameters, "minlength", false); if (temp == "not found") { temp = "0"; }
160 convert(temp, minLength);
162 temp = validParameter.validFile(parameters, "maxlength", false); if (temp == "not found") { temp = "0"; }
163 convert(temp, maxLength);
165 temp = validParameter.validFile(parameters, "bdiffs", false); if (temp == "not found") { temp = "0"; }
166 convert(temp, bdiffs);
168 temp = validParameter.validFile(parameters, "pdiffs", false); if (temp == "not found") { temp = "0"; }
169 convert(temp, pdiffs);
171 temp = validParameter.validFile(parameters, "tdiffs", false); if (temp == "not found") { int tempTotal = pdiffs + bdiffs; temp = toString(tempTotal); }
172 convert(temp, tdiffs);
174 if(tdiffs == 0){ tdiffs = bdiffs + pdiffs; }
176 temp = validParameter.validFile(parameters, "qfile", true);
177 if (temp == "not found") { qFileName = ""; }
178 else if(temp == "not open") { abort = true; }
179 else { qFileName = temp; }
181 temp = validParameter.validFile(parameters, "qthreshold", false); if (temp == "not found") { temp = "0"; }
182 convert(temp, qThreshold);
184 temp = validParameter.validFile(parameters, "qtrim", false); if (temp == "not found") { temp = "F"; }
185 qtrim = m->isTrue(temp);
187 temp = validParameter.validFile(parameters, "rollaverage", false); if (temp == "not found") { temp = "0"; }
188 convert(temp, qRollAverage);
190 temp = validParameter.validFile(parameters, "qwindowaverage", false);if (temp == "not found") { temp = "0"; }
191 convert(temp, qWindowAverage);
193 temp = validParameter.validFile(parameters, "qwindowsize", false); if (temp == "not found") { temp = "100"; }
194 convert(temp, qWindowSize);
196 temp = validParameter.validFile(parameters, "qstepsize", false); if (temp == "not found") { temp = "10"; }
197 convert(temp, qWindowStep);
199 temp = validParameter.validFile(parameters, "qaverage", false); if (temp == "not found") { temp = "0"; }
200 convert(temp, qAverage);
202 temp = validParameter.validFile(parameters, "allfiles", false); if (temp == "not found") { temp = "F"; }
203 allFiles = m->isTrue(temp);
205 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found") { temp = "1"; }
206 convert(temp, processors);
208 if(allFiles && oligoFile == ""){
209 m->mothurOut("You selected allfiles, but didn't enter an oligos file. Ignoring the allfiles request."); m->mothurOutEndLine();
211 if((qAverage != 0 && qThreshold != 0) && qFileName == ""){
212 m->mothurOut("You didn't provide a quality file name, quality criteria will be ignored."); m->mothurOutEndLine();
216 if(!flip && oligoFile=="" && !maxLength && !minLength && (maxAmbig==-1) && !maxHomoP && qFileName == ""){
217 m->mothurOut("You didn't set any options... quiting command."); m->mothurOutEndLine();
223 catch(exception& e) {
224 m->errorOut(e, "TrimSeqsCommand", "TrimSeqsCommand");
228 //**********************************************************************************************************************
230 void TrimSeqsCommand::help(){
232 m->mothurOut("The trim.seqs command reads a fastaFile and creates .....\n");
233 m->mothurOut("The trim.seqs command parameters are fasta, flip, oligos, maxambig, maxhomop, minlength, maxlength, qfile, qthreshold, qaverage, diffs, qtrim and allfiles.\n");
234 m->mothurOut("The fasta parameter is required.\n");
235 m->mothurOut("The flip parameter will output the reverse compliment of your trimmed sequence. The default is false.\n");
236 m->mothurOut("The oligos parameter .... The default is "".\n");
237 m->mothurOut("The maxambig parameter .... The default is -1.\n");
238 m->mothurOut("The maxhomop parameter .... The default is 0.\n");
239 m->mothurOut("The minlength parameter .... The default is 0.\n");
240 m->mothurOut("The maxlength parameter .... The default is 0.\n");
241 m->mothurOut("The tdiffs parameter is used to specify the total number of differences allowed in the sequence. The default is pdiffs + bdiffs.\n");
242 m->mothurOut("The bdiffs parameter is used to specify the number of differences allowed in the barcode. The default is 0.\n");
243 m->mothurOut("The pdiffs parameter is used to specify the number of differences allowed in the primer. The default is 0.\n");
244 m->mothurOut("The qfile parameter .....\n");
245 m->mothurOut("The qthreshold parameter .... The default is 0.\n");
246 m->mothurOut("The qaverage parameter .... The default is 0.\n");
247 m->mothurOut("The allfiles parameter .... The default is F.\n");
248 m->mothurOut("The qtrim parameter .... The default is F.\n");
249 m->mothurOut("The trim.seqs command should be in the following format: \n");
250 m->mothurOut("trim.seqs(fasta=yourFastaFile, flip=yourFlip, oligos=yourOligos, maxambig=yourMaxambig, \n");
251 m->mothurOut("maxhomop=yourMaxhomop, minlength=youMinlength, maxlength=yourMaxlength) \n");
252 m->mothurOut("Example trim.seqs(fasta=abrecovery.fasta, flip=..., oligos=..., maxambig=..., maxhomop=..., minlength=..., maxlength=...).\n");
253 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n");
254 m->mothurOut("For more details please check out the wiki http://www.mothur.org/wiki/Trim.seqs .\n\n");
257 catch(exception& e) {
258 m->errorOut(e, "TrimSeqsCommand", "help");
264 //***************************************************************************************************************
266 TrimSeqsCommand::~TrimSeqsCommand(){ /* do nothing */ }
268 //***************************************************************************************************************
270 int TrimSeqsCommand::execute(){
273 if (abort == true) { return 0; }
275 numFPrimers = 0; //this needs to be initialized
278 string trimSeqFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "trim.fasta";
279 outputNames.push_back(trimSeqFile); outputTypes["fasta"].push_back(trimSeqFile);
280 string scrapSeqFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "scrap.fasta";
281 outputNames.push_back(scrapSeqFile); outputTypes["fasta"].push_back(scrapSeqFile);
282 string trimQualFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "trim.qual";
283 string scrapQualFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "scrap.qual";
284 if (qFileName != "") { outputNames.push_back(trimQualFile); outputNames.push_back(scrapQualFile); outputTypes["qual"].push_back(trimQualFile); outputTypes["qual"].push_back(scrapQualFile); }
285 string groupFile = outputDir + m->getRootName(m->getSimpleName(fastaFile)) + "groups";
287 vector<string> fastaFileNames;
288 vector<string> qualFileNames;
290 outputNames.push_back(groupFile); outputTypes["group"].push_back(groupFile);
291 getOligos(fastaFileNames, qualFileNames);
294 vector<unsigned long int> fastaFilePos;
295 vector<unsigned long int> qFilePos;
297 setLines(fastaFile, qFileName, fastaFilePos, qFilePos);
299 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
300 lines.push_back(new linePair(fastaFilePos[i], fastaFilePos[(i+1)]));
301 if (qFileName != "") { qLines.push_back(new linePair(qFilePos[i], qFilePos[(i+1)])); }
303 if(qFileName == "") { qLines = lines; } //files with duds
305 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
308 driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], qLines[0]);
310 for (int j = 0; j < fastaFileNames.size(); j++) {
311 rename((fastaFileNames[j] + toString(getpid()) + ".temp").c_str(), fastaFileNames[j].c_str());
314 for (int j = 0; j < qualFileNames.size(); j++) {
315 rename((qualFileNames[j] + toString(getpid()) + ".temp").c_str(), qualFileNames[j].c_str());
320 createProcessesCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames);
322 rename((trimSeqFile + toString(processIDS[0]) + ".temp").c_str(), trimSeqFile.c_str());
323 rename((scrapSeqFile + toString(processIDS[0]) + ".temp").c_str(), scrapSeqFile.c_str());
324 rename((groupFile + toString(processIDS[0]) + ".temp").c_str(), groupFile.c_str());
327 rename((trimQualFile + toString(processIDS[0]) + ".temp").c_str(), trimQualFile.c_str());
328 rename((scrapQualFile + toString(processIDS[0]) + ".temp").c_str(), scrapQualFile.c_str());
332 for (int j = 0; j < fastaFileNames.size(); j++) {
333 rename((fastaFileNames[j] + toString(processIDS[0]) + ".temp").c_str(), fastaFileNames[j].c_str());
336 for (int j = 0; j < qualFileNames.size(); j++) {
337 rename((qualFileNames[j] + toString(getpid()) + ".temp").c_str(), qualFileNames[j].c_str());
342 for(int i=1;i<processors;i++){
343 m->appendFiles((trimSeqFile + toString(processIDS[i]) + ".temp"), trimSeqFile);
344 remove((trimSeqFile + toString(processIDS[i]) + ".temp").c_str());
345 m->appendFiles((scrapSeqFile + toString(processIDS[i]) + ".temp"), scrapSeqFile);
346 remove((scrapSeqFile + toString(processIDS[i]) + ".temp").c_str());
348 m->appendFiles((trimQualFile + toString(processIDS[i]) + ".temp"), trimQualFile);
349 remove((trimQualFile + toString(processIDS[i]) + ".temp").c_str());
350 m->appendFiles((scrapQualFile + toString(processIDS[i]) + ".temp"), scrapQualFile);
351 remove((scrapQualFile + toString(processIDS[i]) + ".temp").c_str());
353 m->appendFiles((groupFile + toString(processIDS[i]) + ".temp"), groupFile);
354 remove((groupFile + toString(processIDS[i]) + ".temp").c_str());
355 for (int j = 0; j < fastaFileNames.size(); j++) {
356 m->appendFiles((fastaFileNames[j] + toString(processIDS[i]) + ".temp"), fastaFileNames[j]);
357 remove((fastaFileNames[j] + toString(processIDS[i]) + ".temp").c_str());
361 for (int j = 0; j < qualFileNames.size(); j++) {
362 m->appendFiles((qualFileNames[j] + toString(processIDS[i]) + ".temp"), qualFileNames[j]);
363 remove((qualFileNames[j] + toString(processIDS[i]) + ".temp").c_str());
371 if (m->control_pressed) { return 0; }
373 driverCreateTrim(fastaFile, qFileName, trimSeqFile, scrapSeqFile, trimQualFile, scrapQualFile, groupFile, fastaFileNames, qualFileNames, lines[0], qLines[0]);
375 for (int j = 0; j < fastaFileNames.size(); j++) {
376 rename((fastaFileNames[j] + toString(j) + ".temp").c_str(), fastaFileNames[j].c_str());
379 for (int j = 0; j < qualFileNames.size(); j++) {
380 rename((qualFileNames[j] + toString(j) + ".temp").c_str(), qualFileNames[j].c_str());
384 if (m->control_pressed) { return 0; }
388 for(int i=0;i<fastaFileNames.size();i++){
389 if (m->isBlank(fastaFileNames[i])) { remove(fastaFileNames[i].c_str()); }
390 else if (filesToRemove.count(fastaFileNames[i]) > 0) { remove(fastaFileNames[i].c_str()); }
394 m->openInputFile(fastaFileNames[i], inFASTA);
396 string outGroupFilename = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[i])) + "groups";
397 m->openOutputFile(outGroupFilename, outGroups);
398 outputNames.push_back(outGroupFilename); outputTypes["group"].push_back(outGroupFilename);
400 string thisGroup = "";
401 if (i > comboStarts) {
402 map<string, int>::iterator itCombo;
403 for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
404 if(itCombo->second == i){ thisGroup = itCombo->first; combos.erase(itCombo); break; }
406 }else{ thisGroup = groupVector[i]; }
408 while(!inFASTA.eof()){
409 if(inFASTA.get() == '>'){
411 outGroups << seqName << '\t' << thisGroup << endl;
413 while (!inFASTA.eof()) { char c = inFASTA.get(); if (c == 10 || c == 13){ break; } }
421 for(int i=0;i<qualFileNames.size();i++){
422 if (m->isBlank(qualFileNames[i])) { remove(qualFileNames[i].c_str()); }
423 else if (filesToRemove.count(qualFileNames[i]) > 0) { remove(qualFileNames[i].c_str()); }
427 m->openInputFile(qualFileNames[i], inQual);
428 // ofstream outGroups;
430 // string thisGroup = "";
431 // if (i > comboStarts) {
432 // map<string, int>::iterator itCombo;
433 // for(itCombo=combos.begin();itCombo!=combos.end(); itCombo++){
434 // if(itCombo->second == i){ thisGroup = itCombo->first; combos.erase(itCombo); break; }
437 // else{ thisGroup = groupVector[i]; }
445 if (m->control_pressed) {
446 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
450 m->mothurOutEndLine();
451 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
452 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
453 m->mothurOutEndLine();
458 catch(exception& e) {
459 m->errorOut(e, "TrimSeqsCommand", "execute");
464 /**************************************************************************************/
466 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) {
471 int able = m->openOutputFile(trimFile, outFASTA);
474 m->openOutputFile(scrapFile, scrapFASTA);
479 m->openOutputFile(trimQFile, outQual);
480 m->openOutputFile(scrapQFile, scrapQual);
484 vector<ofstream*> fastaFileNames;
485 vector<ofstream*> qualFileNames;
487 if (oligoFile != "") {
488 m->openOutputFile(groupFile, outGroups);
489 for (int i = 0; i < fastaNames.size(); i++) {
491 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
492 fastaFileNames.push_back(new ofstream((fastaNames[i] + toString(getpid()) + ".temp").c_str(), ios::ate));
494 qualFileNames.push_back(new ofstream((qualNames[i] + toString(getpid()) + ".temp").c_str(), ios::ate));
497 fastaFileNames.push_back(new ofstream((fastaNames[i] + toString(i) + ".temp").c_str(), ios::ate));
499 qualFileNames.push_back(new ofstream((qualNames[i] + toString(i) + ".temp").c_str(), ios::ate));
506 m->openInputFile(filename, inFASTA);
507 inFASTA.seekg(line->start);
510 if(qFileName != "") { m->openInputFile(qFileName, qFile); qFile.seekg(qline->start); }
517 if (m->control_pressed) {
518 inFASTA.close(); outFASTA.close(); scrapFASTA.close();
519 if (oligoFile != "") { outGroups.close(); }
521 for(int i=0;i<fastaFileNames.size();i++){ fastaFileNames[i]->close(); delete fastaFileNames[i]; }
525 for(int i=0;i<qualFileNames.size();i++){ qualFileNames[i]->close(); delete qualFileNames[i]; }
527 for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }
535 Sequence currSeq(inFASTA); m->gobble(inFASTA);
537 QualityScores currQual;
539 currQual = QualityScores(qFile, currSeq.getNumBases()); m->gobble(qFile);
542 string origSeq = currSeq.getUnaligned();
544 int groupBar, groupPrime;
545 string trashCode = "";
546 int currentSeqsDiffs = 0;
549 if(qThreshold != 0) { success = currQual.stripQualThreshold(currSeq, qThreshold); }
550 else if(qAverage != 0) { success = currQual.cullQualAverage(currSeq, qAverage); }
551 else if(qRollAverage != 0) { success = currQual.stripQualRollingAverage(currSeq, qRollAverage); }
552 else if(qWindowAverage != 0){ success = currQual.stripQualWindowAverage(currSeq, qWindowStep, qWindowSize, qWindowAverage); }
554 if (qtrim == 1 && (origSeq.length() != currSeq.getUnaligned().length())) {
555 success = 0; //if you don't want to trim and the sequence does not meet quality requirements, move to scrap
558 if(!success) { trashCode += 'q'; }
561 if(barcodes.size() != 0){
562 success = stripBarcode(currSeq, currQual, groupBar);
563 if(success > bdiffs) { trashCode += 'b'; }
564 else{ currentSeqsDiffs += success; }
567 if(numFPrimers != 0){
568 success = stripForward(currSeq, currQual, groupPrime);
569 if(success > pdiffs) { trashCode += 'f'; }
570 else{ currentSeqsDiffs += success; }
573 if (currentSeqsDiffs > tdiffs) { trashCode += 't'; }
575 if(numRPrimers != 0){
576 success = stripReverse(currSeq, currQual);
577 if(!success) { trashCode += 'r'; }
580 if(minLength > 0 || maxLength > 0){
581 success = cullLength(currSeq);
582 if(!success) { trashCode += 'l'; }
585 success = cullHomoP(currSeq);
586 if(!success) { trashCode += 'h'; }
589 success = cullAmbigs(currSeq);
590 if(!success) { trashCode += 'n'; }
593 if(flip){ currSeq.reverseComplement(); currQual.flipQScores(); } // should go last
595 if(trashCode.length() == 0){
596 currSeq.setAligned(currSeq.getUnaligned());
597 currSeq.printSequence(outFASTA);
598 currQual.printQScores(outQual);
600 if(barcodes.size() != 0){
601 string thisGroup = groupVector[groupBar];
602 int indexToFastaFile = groupBar;
603 if (primers.size() != 0){
604 //does this primer have a group
605 if (groupVector[groupPrime] != "") {
606 thisGroup += "." + groupVector[groupPrime];
607 indexToFastaFile = combos[thisGroup];
610 outGroups << currSeq.getName() << '\t' << thisGroup << endl;
612 currSeq.printSequence(*fastaFileNames[indexToFastaFile]);
615 currQual.printQScores(*qualFileNames[indexToFastaFile]);
621 currSeq.setName(currSeq.getName() + '|' + trashCode);
622 currSeq.setUnaligned(origSeq);
623 currSeq.setAligned(origSeq);
624 currSeq.printSequence(scrapFASTA);
625 currQual.printQScores(scrapQual);
630 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
631 unsigned long int pos = inFASTA.tellg();
632 if ((pos == -1) || (pos >= line->end)) { break; }
634 if (inFASTA.eof()) { break; }
638 if((count) % 1000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
642 if((count) % 1000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
648 if (oligoFile != "") { outGroups.close(); }
649 if(qFileName != "") { qFile.close(); scrapQual.close(); outQual.close(); }
651 for(int i=0;i<fastaFileNames.size();i++){
652 fastaFileNames[i]->close();
653 delete fastaFileNames[i];
657 for(int i=0;i<qualFileNames.size();i++){
658 qualFileNames[i]->close();
659 delete qualFileNames[i];
665 catch(exception& e) {
666 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
671 /**************************************************************************************************/
673 int TrimSeqsCommand::createProcessesCreateTrim(string filename, string qFileName, string trimFile, string scrapFile, string trimQFile, string scrapQFile, string groupFile, vector<string> fastaNames, vector<string> qualNames) {
675 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
680 //loop through and create all the processes you want
681 while (process != processors) {
685 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
688 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]);
690 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
693 //force parent to wait until all the processes are done
694 for (int i=0;i<processors;i++) {
695 int temp = processIDS[i];
702 catch(exception& e) {
703 m->errorOut(e, "TrimSeqsCommand", "createProcessesCreateTrim");
708 /**************************************************************************************************/
710 int TrimSeqsCommand::setLines(string filename, string qfilename, vector<unsigned long int>& fastaFilePos, vector<unsigned long int>& qfileFilePos) {
713 //set file positions for fasta file
714 fastaFilePos = m->divideFile(filename, processors);
716 if (qfilename == "") { return processors; }
718 //get name of first sequence in each chunk
719 map<string, int> firstSeqNames;
720 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
722 m->openInputFile(filename, in);
723 in.seekg(fastaFilePos[i]);
726 firstSeqNames[temp.getName()] = i;
731 //seach for filePos of each first name in the qfile and save in qfileFilePos
733 m->openInputFile(qfilename, inQual);
736 while(!inQual.eof()){
737 input = m->getline(inQual);
739 if (input.length() != 0) {
740 if(input[0] == '>'){ //this is a sequence name line
741 istringstream nameStream(input);
743 string sname = ""; nameStream >> sname;
744 sname = sname.substr(1);
746 map<string, int>::iterator it = firstSeqNames.find(sname);
748 if(it != firstSeqNames.end()) { //this is the start of a new chunk
749 unsigned long int pos = inQual.tellg();
750 qfileFilePos.push_back(pos - input.length() - 1);
751 firstSeqNames.erase(it);
756 if (firstSeqNames.size() == 0) { break; }
760 if (firstSeqNames.size() != 0) {
761 for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
762 m->mothurOut(it->first + " is in your fasta file and not in your quality file, not using quality file."); m->mothurOutEndLine();
768 //get last file position of qfile
770 unsigned long int size;
772 //get num bytes in file
773 pFile = fopen (qfilename.c_str(),"rb");
774 if (pFile==NULL) perror ("Error opening file");
776 fseek (pFile, 0, SEEK_END);
781 qfileFilePos.push_back(size);
785 catch(exception& e) {
786 m->errorOut(e, "TrimSeqsCommand", "setLines");
790 //***************************************************************************************************************
792 void TrimSeqsCommand::getOligos(vector<string>& outFASTAVec, vector<string>& outQualVec){
795 m->openInputFile(oligoFile, inOligos);
799 string type, oligo, group;
801 //int indexPrimer = 0;
803 while(!inOligos.eof()){
807 while (!inOligos.eof()) { char c = inOligos.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
810 //make type case insensitive
811 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); }
815 for(int i=0;i<oligo.length();i++){
816 oligo[i] = toupper(oligo[i]);
817 if(oligo[i] == 'U') { oligo[i] = 'T'; }
820 if(type == "FORWARD"){
823 // get rest of line in case there is a primer name
824 while (!inOligos.eof()) {
825 char c = inOligos.get();
826 if (c == 10 || c == 13){ break; }
827 else if (c == 32 || c == 9){;} //space or tab
831 //check for repeat barcodes
832 map<string, int>::iterator itPrime = primers.find(oligo);
833 if (itPrime != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
835 primers[oligo]=index; index++;
836 groupVector.push_back(group);
839 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
841 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
843 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
844 filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
846 filesToRemove.insert((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
849 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
850 outputTypes["fasta"].push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
852 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
853 outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
859 else if(type == "REVERSE"){
860 Sequence oligoRC("reverse", oligo);
861 oligoRC.reverseComplement();
862 revPrimer.push_back(oligoRC.getUnaligned());
864 else if(type == "BARCODE"){
867 //check for repeat barcodes
868 map<string, int>::iterator itBar = barcodes.find(oligo);
869 if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
871 barcodes[oligo]=index; index++;
872 groupVector.push_back(group);
875 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
876 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
877 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + group + ".fasta"));
879 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
880 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
881 outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + group + ".qual"));
884 }else{ m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine(); }
891 //add in potential combos
893 comboStarts = outFASTAVec.size()-1;
894 for (map<string, int>::iterator itBar = barcodes.begin(); itBar != barcodes.end(); itBar++) {
895 for (map<string, int>::iterator itPrime = primers.begin(); itPrime != primers.end(); itPrime++) {
896 if (groupVector[itPrime->second] != "") { //there is a group for this primer
897 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
898 outputTypes["fasta"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
899 outFASTAVec.push_back((outputDir + m->getRootName(m->getSimpleName(fastaFile)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".fasta"));
900 combos[(groupVector[itBar->second] + "." + groupVector[itPrime->second])] = outFASTAVec.size()-1;
903 outQualVec.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
904 outputNames.push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
905 outputTypes["qual"].push_back((outputDir + m->getRootName(m->getSimpleName(qFileName)) + groupVector[itBar->second] + "." + groupVector[itPrime->second] + ".qual"));
912 numFPrimers = primers.size();
913 numRPrimers = revPrimer.size();
916 catch(exception& e) {
917 m->errorOut(e, "TrimSeqsCommand", "getOligos");
921 //***************************************************************************************************************
923 int TrimSeqsCommand::stripBarcode(Sequence& seq, QualityScores& qual, int& group){
926 string rawSequence = seq.getUnaligned();
927 int success = bdiffs + 1; //guilty until proven innocent
929 //can you find the barcode
930 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
931 string oligo = it->first;
932 if(rawSequence.length() < oligo.length()){ //let's just assume that the barcodes are the same length
933 success = bdiffs + 10; //if the sequence is shorter than the barcode then bail out
937 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
939 seq.setUnaligned(rawSequence.substr(oligo.length()));
941 if(qual.getName() != ""){
942 qual.trimQScores(oligo.length(), -1);
950 //if you found the barcode or if you don't want to allow for diffs
952 if ((bdiffs == 0) || (success == 0)) { return success; }
954 else { //try aligning and see if you can find it
959 Alignment* alignment;
960 if (barcodes.size() > 0) {
961 map<string,int>::iterator it=barcodes.begin();
963 for(it;it!=barcodes.end();it++){
964 if(it->first.length() > maxLength){
965 maxLength = it->first.length();
968 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));
970 }else{ alignment = NULL; }
972 //can you find the barcode
978 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
979 string oligo = it->first;
980 // int length = oligo.length();
982 if(rawSequence.length() < maxLength){ //let's just assume that the barcodes are the same length
983 success = bdiffs + 10;
987 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
988 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
989 oligo = alignment->getSeqAAln();
990 string temp = alignment->getSeqBAln();
992 int alnLength = oligo.length();
994 for(int i=oligo.length()-1;i>=0;i--){
995 if(oligo[i] != '-'){ alnLength = i+1; break; }
997 oligo = oligo.substr(0,alnLength);
998 temp = temp.substr(0,alnLength);
1001 int numDiff = countDiffs(oligo, temp);
1003 // cout << oligo << '\t' << temp << '\t' << numDiff << endl;
1005 if(numDiff < minDiff){
1008 minGroup = it->second;
1010 for(int i=0;i<alnLength;i++){
1016 else if(numDiff == minDiff){
1022 if(minDiff > bdiffs) { success = minDiff; } //no good matches
1023 else if(minCount > 1) { success = bdiffs + 100; } //can't tell the difference between multiple barcodes
1024 else{ //use the best match
1026 seq.setUnaligned(rawSequence.substr(minPos));
1028 if(qual.getName() != ""){
1029 qual.trimQScores(minPos, -1);
1034 if (alignment != NULL) { delete alignment; }
1037 // cout << success << endl;
1042 catch(exception& e) {
1043 m->errorOut(e, "TrimSeqsCommand", "stripBarcode");
1049 //***************************************************************************************************************
1051 int TrimSeqsCommand::stripForward(Sequence& seq, QualityScores& qual, int& group){
1053 string rawSequence = seq.getUnaligned();
1054 int success = pdiffs + 1; //guilty until proven innocent
1056 //can you find the primer
1057 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1058 string oligo = it->first;
1059 if(rawSequence.length() < oligo.length()){ //let's just assume that the primers are the same length
1060 success = pdiffs + 10; //if the sequence is shorter than the barcode then bail out
1064 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
1066 seq.setUnaligned(rawSequence.substr(oligo.length()));
1067 if(qual.getName() != ""){
1068 qual.trimQScores(oligo.length(), -1);
1076 //if you found the barcode or if you don't want to allow for diffs
1078 if ((pdiffs == 0) || (success == 0)) { return success; }
1080 else { //try aligning and see if you can find it
1085 Alignment* alignment;
1086 if (primers.size() > 0) {
1087 map<string,int>::iterator it=primers.begin();
1089 for(it;it!=primers.end();it++){
1090 if(it->first.length() > maxLength){
1091 maxLength = it->first.length();
1094 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));
1096 }else{ alignment = NULL; }
1098 //can you find the barcode
1104 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
1105 string oligo = it->first;
1106 // int length = oligo.length();
1108 if(rawSequence.length() < maxLength){
1109 success = pdiffs + 100;
1113 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
1114 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
1115 oligo = alignment->getSeqAAln();
1116 string temp = alignment->getSeqBAln();
1118 int alnLength = oligo.length();
1120 for(int i=oligo.length()-1;i>=0;i--){
1121 if(oligo[i] != '-'){ alnLength = i+1; break; }
1123 oligo = oligo.substr(0,alnLength);
1124 temp = temp.substr(0,alnLength);
1127 int numDiff = countDiffs(oligo, temp);
1129 // cout << oligo << '\t' << temp << '\t' << numDiff << endl;
1131 if(numDiff < minDiff){
1134 minGroup = it->second;
1136 for(int i=0;i<alnLength;i++){
1142 else if(numDiff == minDiff){
1148 if(minDiff > pdiffs) { success = minDiff; } //no good matches
1149 else if(minCount > 1) { success = pdiffs + 10; } //can't tell the difference between multiple primers
1150 else{ //use the best match
1152 seq.setUnaligned(rawSequence.substr(minPos));
1153 if(qual.getName() != ""){
1154 qual.trimQScores(minPos, -1);
1159 if (alignment != NULL) { delete alignment; }
1166 catch(exception& e) {
1167 m->errorOut(e, "TrimSeqsCommand", "stripForward");
1172 //***************************************************************************************************************
1174 bool TrimSeqsCommand::stripReverse(Sequence& seq, QualityScores& qual){
1176 string rawSequence = seq.getUnaligned();
1177 bool success = 0; //guilty until proven innocent
1179 for(int i=0;i<numRPrimers;i++){
1180 string oligo = revPrimer[i];
1182 if(rawSequence.length() < oligo.length()){
1187 if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
1188 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
1189 if(qual.getName() != ""){
1190 qual.trimQScores(-1, rawSequence.length()-oligo.length());
1199 catch(exception& e) {
1200 m->errorOut(e, "TrimSeqsCommand", "stripReverse");
1205 //***************************************************************************************************************
1207 bool TrimSeqsCommand::cullLength(Sequence& seq){
1210 int length = seq.getNumBases();
1211 bool success = 0; //guilty until proven innocent
1213 if(length >= minLength && maxLength == 0) { success = 1; }
1214 else if(length >= minLength && length <= maxLength) { success = 1; }
1215 else { success = 0; }
1220 catch(exception& e) {
1221 m->errorOut(e, "TrimSeqsCommand", "cullLength");
1227 //***************************************************************************************************************
1229 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
1231 int longHomoP = seq.getLongHomoPolymer();
1232 bool success = 0; //guilty until proven innocent
1234 if(longHomoP <= maxHomoP){ success = 1; }
1235 else { success = 0; }
1239 catch(exception& e) {
1240 m->errorOut(e, "TrimSeqsCommand", "cullHomoP");
1246 //***************************************************************************************************************
1248 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
1250 int numNs = seq.getAmbigBases();
1251 bool success = 0; //guilty until proven innocent
1253 if(numNs <= maxAmbig) { success = 1; }
1254 else { success = 0; }
1258 catch(exception& e) {
1259 m->errorOut(e, "TrimSeqsCommand", "cullAmbigs");
1265 //***************************************************************************************************************
1267 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
1270 int length = oligo.length();
1272 for(int i=0;i<length;i++){
1274 if(oligo[i] != seq[i]){
1275 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C') { success = 0; }
1276 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { success = 0; }
1277 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { success = 0; }
1278 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { success = 0; }
1279 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { success = 0; }
1280 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
1281 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { success = 0; }
1282 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
1283 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
1284 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
1285 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { success = 0; }
1286 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
1288 if(success == 0) { break; }
1297 catch(exception& e) {
1298 m->errorOut(e, "TrimSeqsCommand", "compareDNASeq");
1303 //***************************************************************************************************************
1305 int TrimSeqsCommand::countDiffs(string oligo, string seq){
1308 int length = oligo.length();
1311 for(int i=0;i<length;i++){
1313 if(oligo[i] != seq[i]){
1314 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.') { countDiffs++; }
1315 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { countDiffs++; }
1316 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { countDiffs++; }
1317 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { countDiffs++; }
1318 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { countDiffs++; }
1319 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
1320 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { countDiffs++; }
1321 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
1322 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
1323 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
1324 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { countDiffs++; }
1325 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
1332 catch(exception& e) {
1333 m->errorOut(e, "TrimSeqsCommand", "countDiffs");
1338 //***************************************************************************************************************
1340 //bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
1343 // string rawSequence = seq.getUnaligned();
1344 // int seqLength = seq.getNumBases();
1345 // bool success = 0; //guilty until proven innocent
1349 // if (name[0] == '>') { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); } }
1351 // while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
1354 // int end = seqLength;
1356 // for(int i=0;i<seqLength;i++){
1359 // if(score < qThreshold){
1364 // for(int i=end+1;i<seqLength;i++){
1368 // seq.setUnaligned(rawSequence.substr(0,end));
1372 // catch(exception& e) {
1373 // m->errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
1378 //***************************************************************************************************************
1380 //bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
1382 // string rawSequence = seq.getUnaligned();
1383 // int seqLength = seq.getNumBases();
1384 // bool success = 0; //guilty until proven innocent
1388 // if (name[0] == '>') { if(name.substr(1) != seq.getName()) { m->mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); m->mothurOutEndLine(); } }
1390 // while (!qFile.eof()) { char c = qFile.get(); if (c == 10 || c == 13){ break; } }
1393 // float average = 0;
1395 // for(int i=0;i<seqLength;i++){
1397 // average += score;
1399 // average /= seqLength;
1401 // if(average >= qAverage) { success = 1; }
1402 // else { success = 0; }
1406 // catch(exception& e) {
1407 // m->errorOut(e, "TrimSeqsCommand", "cullQualAverage");
1412 //***************************************************************************************************************