5 * Created by Pat Schloss on 12/22/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "trimflowscommand.h"
11 #include "needlemanoverlap.hpp"
13 //**********************************************************************************************************************
14 vector<string> TrimFlowsCommand::setParameters(){
16 CommandParameter pflow("flow", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pflow);
17 CommandParameter poligos("oligos", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(poligos);
18 CommandParameter pmaxhomop("maxhomop", "Number", "", "9", "", "", "",false,false); parameters.push_back(pmaxhomop);
19 CommandParameter pmaxflows("maxflows", "Number", "", "720", "", "", "",false,false); parameters.push_back(pmaxflows);
20 CommandParameter pminflows("minflows", "Number", "", "360", "", "", "",false,false); parameters.push_back(pminflows);
21 CommandParameter pminlength("minlength", "Number", "", "0", "", "", "",false,false); parameters.push_back(pminlength);
22 CommandParameter pmaxlength("maxlength", "Number", "", "0", "", "", "",false,false); parameters.push_back(pmaxlength);
23 CommandParameter ppdiffs("pdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(ppdiffs);
24 CommandParameter pbdiffs("bdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pbdiffs);
25 CommandParameter ptdiffs("tdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(ptdiffs);
26 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
27 CommandParameter psignal("signal", "Number", "", "0.50", "", "", "",false,false); parameters.push_back(psignal);
28 CommandParameter pnoise("noise", "Number", "", "0.70", "", "", "",false,false); parameters.push_back(pnoise);
29 CommandParameter pallfiles("allfiles", "Boolean", "", "t", "", "", "",false,false); parameters.push_back(pallfiles);
30 CommandParameter porder("order", "String", "", "", "", "", "",false,false); parameters.push_back(porder);
31 CommandParameter pfasta("fasta", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pfasta);
32 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
33 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
35 vector<string> myArray;
36 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
40 m->errorOut(e, "TrimFlowsCommand", "setParameters");
44 //**********************************************************************************************************************
45 string TrimFlowsCommand::getHelpString(){
47 string helpString = "";
48 helpString += "The trim.flows command reads a flowgram file and creates .....\n";
49 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
50 helpString += "For more details please check out the wiki http://www.mothur.org/wiki/Trim.flows.\n";
54 m->errorOut(e, "TrimFlowsCommand", "getHelpString");
59 //**********************************************************************************************************************
61 TrimFlowsCommand::TrimFlowsCommand(){
63 abort = true; calledHelp = true;
65 vector<string> tempOutNames;
66 outputTypes["flow"] = tempOutNames;
67 outputTypes["fasta"] = tempOutNames;
70 m->errorOut(e, "TrimFlowsCommand", "TrimFlowsCommand");
74 //**********************************************************************************************************************
76 TrimFlowsCommand::TrimFlowsCommand(string option) {
79 abort = false; calledHelp = false;
82 //allow user to run help
83 if(option == "help") { help(); abort = true; calledHelp = true; }
84 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
88 vector<string> myArray = setParameters();
90 OptionParser parser(option);
91 map<string,string> parameters = parser.getParameters();
93 ValidParameters validParameter;
94 map<string,string>::iterator it;
96 //check to make sure all parameters are valid for command
97 for (it = parameters.begin(); it != parameters.end(); it++) {
98 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
101 //initialize outputTypes
102 vector<string> tempOutNames;
103 outputTypes["flow"] = tempOutNames;
104 outputTypes["fasta"] = tempOutNames;
106 //if the user changes the input directory command factory will send this info to us in the output parameter
107 string inputDir = validParameter.validFile(parameters, "inputdir", false);
108 if (inputDir == "not found"){ inputDir = ""; }
111 it = parameters.find("flow");
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["flow"] = inputDir + it->second; }
119 it = parameters.find("oligos");
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["oligos"] = inputDir + it->second; }
130 //check for required parameters
131 flowFileName = validParameter.validFile(parameters, "flow", true);
132 if (flowFileName == "not found") {
133 flowFileName = m->getFlowFile();
134 if (flowFileName != "") { m->mothurOut("Using " + flowFileName + " as input file for the flow parameter."); m->mothurOutEndLine(); }
136 m->mothurOut("No valid current flow file. You must provide a flow file."); m->mothurOutEndLine();
139 }else if (flowFileName == "not open") { flowFileName = ""; abort = true; }
141 //if the user changes the output directory command factory will send this info to us in the output parameter
142 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
144 outputDir += m->hasPath(flowFileName); //if user entered a file with a path then preserve it
148 //check for optional parameter and set defaults
149 // ...at some point should added some additional type checking...
152 temp = validParameter.validFile(parameters, "minflows", false); if (temp == "not found") { temp = "450"; }
153 convert(temp, minFlows);
155 temp = validParameter.validFile(parameters, "maxflows", false); if (temp == "not found") { temp = "450"; }
156 convert(temp, maxFlows);
159 temp = validParameter.validFile(parameters, "oligos", true);
160 if (temp == "not found") { oligoFileName = ""; }
161 else if(temp == "not open") { abort = true; }
162 else { oligoFileName = temp; }
164 temp = validParameter.validFile(parameters, "fasta", false); if (temp == "not found"){ fasta = 0; }
165 else if(m->isTrue(temp)) { fasta = 1; }
167 temp = validParameter.validFile(parameters, "maxhomop", false); if (temp == "not found"){ temp = "9"; }
168 convert(temp, maxHomoP);
170 temp = validParameter.validFile(parameters, "signal", false); if (temp == "not found"){ temp = "0.50"; }
171 convert(temp, signal);
173 temp = validParameter.validFile(parameters, "noise", false); if (temp == "not found"){ temp = "0.70"; }
174 convert(temp, noise);
176 temp = validParameter.validFile(parameters, "minlength", false); if (temp == "not found"){ temp = "0"; }
177 convert(temp, minLength);
179 temp = validParameter.validFile(parameters, "maxlength", false); if (temp == "not found"){ temp = "0"; }
180 convert(temp, maxLength);
182 temp = validParameter.validFile(parameters, "bdiffs", false); if (temp == "not found"){ temp = "0"; }
183 convert(temp, bdiffs);
185 temp = validParameter.validFile(parameters, "pdiffs", false); if (temp == "not found"){ temp = "0"; }
186 convert(temp, pdiffs);
188 temp = validParameter.validFile(parameters, "tdiffs", false);
189 if (temp == "not found"){ int tempTotal = pdiffs + bdiffs; temp = toString(tempTotal); }
190 convert(temp, tdiffs);
191 if(tdiffs == 0){ tdiffs = bdiffs + pdiffs; }
193 temp = validParameter.validFile(parameters, "allfiles", false); if (temp == "not found"){ temp = "T"; }
194 allFiles = m->isTrue(temp);
196 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
197 m->setProcessors(temp);
198 convert(temp, processors);
200 flowOrder = validParameter.validFile(parameters, "order", false);
201 if (flowOrder == "not found"){ flowOrder = "TACG"; }
202 else if(flowOrder.length() != 4){
203 m->mothurOut("The value of the order option must be four bases long\n");
206 if(oligoFileName == ""){ allFiles = 0; }
213 catch(exception& e) {
214 m->errorOut(e, "TrimFlowsCommand", "TrimSeqsCommand");
219 //***************************************************************************************************************
221 int TrimFlowsCommand::execute(){
224 if (abort == true) { if (calledHelp) { return 0; } return 2; }
226 string trimFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "trim.flow";
227 outputNames.push_back(trimFlowFileName); outputTypes["flow"].push_back(trimFlowFileName);
229 string scrapFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "scrap.flow";
230 outputNames.push_back(scrapFlowFileName); outputTypes["flow"].push_back(scrapFlowFileName);
232 string fastaFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.fasta";
234 outputNames.push_back(fastaFileName); outputTypes["fasta"].push_back(fastaFileName);
237 vector<unsigned long int> flowFilePos = getFlowFileBreaks();
238 for (int i = 0; i < (flowFilePos.size()-1); i++) {
239 lines.push_back(new linePair(flowFilePos[i], flowFilePos[(i+1)]));
242 vector<vector<string> > barcodePrimerComboFileNames;
243 if(oligoFileName != ""){
244 getOligos(barcodePrimerComboFileNames);
247 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
249 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
251 createProcessesCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames);
254 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
257 if (m->control_pressed) { return 0; }
259 string flowFilesFileName;
264 flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
265 m->openOutputFile(flowFilesFileName, output);
267 for(int i=0;i<barcodePrimerComboFileNames.size();i++){
268 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
271 unsigned long int size;
273 //get num bytes in file
274 pFile = fopen (barcodePrimerComboFileNames[i][j].c_str(),"rb");
275 if (pFile==NULL) perror ("Error opening file");
277 fseek (pFile, 0, SEEK_END);
283 remove(barcodePrimerComboFileNames[i][j].c_str());
286 output << barcodePrimerComboFileNames[i][j] << endl;
287 outputNames.push_back(barcodePrimerComboFileNames[i][j]);
288 outputTypes["flow"].push_back(barcodePrimerComboFileNames[i][j]);
295 flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
296 m->openOutputFile(flowFilesFileName, output);
298 output << trimFlowFileName << endl;
302 outputTypes["flow.files"].push_back(flowFilesFileName);
303 outputNames.push_back(flowFilesFileName);
305 // set fasta file as new current fastafile
306 // string current = "";
307 // itTypes = outputTypes.find("fasta");
308 // if (itTypes != outputTypes.end()) {
309 // if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
312 m->mothurOutEndLine();
313 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
314 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
315 m->mothurOutEndLine();
319 catch(exception& e) {
320 m->errorOut(e, "TrimSeqsCommand", "execute");
325 //***************************************************************************************************************
327 int TrimFlowsCommand::driverCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames, linePair* line){
331 ofstream trimFlowFile;
332 m->openOutputFile(trimFlowFileName, trimFlowFile);
333 trimFlowFile.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
335 ofstream scrapFlowFile;
336 m->openOutputFile(scrapFlowFileName, scrapFlowFile);
337 scrapFlowFile.setf(ios::fixed, ios::floatfield); scrapFlowFile.setf(ios::showpoint);
339 if(line->start == 4){
340 scrapFlowFile << maxFlows << endl;
341 trimFlowFile << maxFlows << endl;
343 for(int i=0;i<barcodePrimerComboFileNames.size();i++){
344 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
345 // barcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
347 m->openOutputFile(barcodePrimerComboFileNames[i][j], temp);
348 temp << maxFlows << endl;
355 FlowData flowData(numFlows, signal, noise, maxHomoP, flowOrder);
358 if(fasta){ m->openOutputFile(fastaFileName, fastaFile); }
361 m->openInputFile(flowFileName, flowFile);
363 flowFile.seekg(line->start);
371 int currentSeqDiffs = 0;
372 string trashCode = "";
374 flowData.getNext(flowFile);
375 flowData.capFlows(maxFlows);
377 Sequence currSeq = flowData.getSequence();
378 if(!flowData.hasMinFlows(minFlows)){ //screen to see if sequence is of a minimum number of flows
383 if(minLength > 0 || maxLength > 0){ //screen to see if sequence is above and below a specific number of bases
384 int seqLength = currSeq.getNumBases();
385 if(seqLength < minLength || seqLength > maxLength){
392 int barcodeIndex = 0;
394 if(barcodes.size() != 0){
395 success = stripBarcode(currSeq, barcodeIndex);
396 if(success > bdiffs) { trashCode += 'b'; }
397 else{ currentSeqDiffs += success; }
400 if(numFPrimers != 0){
401 success = stripForward(currSeq, primerIndex);
402 if(success > pdiffs) { trashCode += 'f'; }
403 else{ currentSeqDiffs += success; }
406 if (currentSeqDiffs > tdiffs) { trashCode += 't'; }
408 if(numRPrimers != 0){
409 success = stripReverse(currSeq);
410 if(!success) { trashCode += 'r'; }
413 if(trashCode.length() == 0){
415 flowData.printFlows(trimFlowFile);
417 if(fasta) { currSeq.printSequence(fastaFile); }
421 m->openOutputFileAppend(barcodePrimerComboFileNames[barcodeIndex][primerIndex], output);
422 output.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
424 flowData.printFlows(output);
429 flowData.printFlows(scrapFlowFile, trashCode);
435 if((count) % 10000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
437 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
438 unsigned long int pos = flowFile.tellg();
440 if ((pos == -1) || (pos >= line->end)) { break; }
442 if (flowFile.eof()) { break; }
447 if((count) % 10000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
449 trimFlowFile.close();
450 scrapFlowFile.close();
452 if(fasta){ fastaFile.close(); }
456 catch(exception& e) {
457 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
462 //***************************************************************************************************************
464 void TrimFlowsCommand::getOligos(vector<vector<string> >& outFlowFileNames){
467 m->openInputFile(oligoFileName, oligosFile);
469 string type, oligo, group;
472 int indexBarcode = 0;
474 while(!oligosFile.eof()){
476 oligosFile >> type; m->gobble(oligosFile); //get the first column value of the row - is it a comment or a feature we are interested in?
478 if(type[0] == '#'){ //igore the line because there's a comment
479 while (!oligosFile.eof()) { char c = oligosFile.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
481 else{ //there's a feature we're interested in
483 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); } //make type case insensitive
485 oligosFile >> oligo; //get the DNA sequence for the feature
487 for(int i=0;i<oligo.length();i++){ //make type case insensitive and change any U's to T's
488 oligo[i] = toupper(oligo[i]);
489 if(oligo[i] == 'U') { oligo[i] = 'T'; }
492 if(type == "FORWARD"){ //if the feature is a forward primer...
495 while (!oligosFile.eof()) { // get rest of line in case there is a primer name = will have the name of the primer
496 char c = oligosFile.get();
497 if (c == 10 || c == 13){ break; }
498 else if (c == 32 || c == 9){;} //space or tab
502 //have we seen this primer already?
503 map<string, int>::iterator itPrimer = primers.find(oligo);
504 if (itPrimer != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
506 primers[oligo]=indexPrimer; indexPrimer++;
507 primerNameVector.push_back(group);
510 else if(type == "REVERSE"){
511 Sequence oligoRC("reverse", oligo);
512 oligoRC.reverseComplement();
513 revPrimer.push_back(oligoRC.getUnaligned());
515 else if(type == "BARCODE"){
518 //check for repeat barcodes
519 map<string, int>::iterator itBar = barcodes.find(oligo);
520 if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
522 barcodes[oligo]=indexBarcode; indexBarcode++;
523 barcodeNameVector.push_back(group);
526 m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();
530 m->gobble(oligosFile);
534 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0; }
536 //add in potential combos
537 if(barcodeNameVector.size() == 0){
539 barcodeNameVector.push_back("");
542 if(primerNameVector.size() == 0){
544 primerNameVector.push_back("");
548 outFlowFileNames.resize(barcodeNameVector.size());
549 for(int i=0;i<outFlowFileNames.size();i++){
550 outFlowFileNames[i].assign(primerNameVector.size(), "");
555 for(map<string, int>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
556 for(map<string, int>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
558 string primerName = primerNameVector[itPrimer->second];
559 string barcodeName = barcodeNameVector[itBar->second];
561 string comboGroupName = "";
562 string fileName = "";
564 if(primerName == ""){
565 comboGroupName = barcodeNameVector[itBar->second];
566 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
569 if(barcodeName == ""){
570 comboGroupName = primerNameVector[itPrimer->second];
573 comboGroupName = barcodeNameVector[itBar->second] + "." + primerNameVector[itPrimer->second];
575 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
578 outFlowFileNames[itBar->second][itPrimer->second] = fileName;
581 m->openOutputFile(fileName, temp);
587 numFPrimers = primers.size();
588 numRPrimers = revPrimer.size();
591 catch(exception& e) {
592 m->errorOut(e, "TrimSeqsCommand", "getOligos");
597 //***************************************************************************************************************
599 int TrimFlowsCommand::stripBarcode(Sequence& seq, int& group){
602 string rawSequence = seq.getUnaligned();
603 int success = bdiffs + 1; //guilty until proven innocent
605 //can you find the barcode
606 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
607 string oligo = it->first;
608 if(rawSequence.length() < oligo.length()){ //let's just assume that the barcodes are the same length
609 success = bdiffs + 10; //if the sequence is shorter than the barcode then bail out
613 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
615 seq.setUnaligned(rawSequence.substr(oligo.length()));
622 //if you found the barcode or if you don't want to allow for diffs
623 if ((bdiffs == 0) || (success == 0)) { return success; }
625 else { //try aligning and see if you can find it
629 Alignment* alignment;
630 if (barcodes.size() > 0) {
631 map<string,int>::iterator it=barcodes.begin();
633 for(it;it!=barcodes.end();it++){
634 if(it->first.length() > maxLength){
635 maxLength = it->first.length();
638 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));
640 }else{ alignment = NULL; }
642 //can you find the barcode
648 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
649 string oligo = it->first;
650 // int length = oligo.length();
652 if(rawSequence.length() < maxLength){ //let's just assume that the barcodes are the same length
653 success = bdiffs + 10;
657 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
658 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
659 oligo = alignment->getSeqAAln();
660 string temp = alignment->getSeqBAln();
662 int alnLength = oligo.length();
664 for(int i=oligo.length()-1;i>=0;i--){
665 if(oligo[i] != '-'){ alnLength = i+1; break; }
667 oligo = oligo.substr(0,alnLength);
668 temp = temp.substr(0,alnLength);
670 int numDiff = countDiffs(oligo, temp);
672 if(numDiff < minDiff){
675 minGroup = it->second;
677 for(int i=0;i<alnLength;i++){
683 else if(numDiff == minDiff){
689 if(minDiff > bdiffs) { success = minDiff; } //no good matches
690 else if(minCount > 1) { success = bdiffs + 100; } //can't tell the difference between multiple barcodes
691 else{ //use the best match
693 seq.setUnaligned(rawSequence.substr(minPos));
697 if (alignment != NULL) { delete alignment; }
704 catch(exception& e) {
705 m->errorOut(e, "TrimFlowsCommand", "stripBarcode");
711 //***************************************************************************************************************
713 int TrimFlowsCommand::stripForward(Sequence& seq, int& group){
716 string rawSequence = seq.getUnaligned();
717 int success = pdiffs + 1; //guilty until proven innocent
719 //can you find the primer
720 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
721 string oligo = it->first;
722 if(rawSequence.length() < oligo.length()){ //let's just assume that the primers are the same length
723 success = pdiffs + 10; //if the sequence is shorter than the barcode then bail out
727 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
729 seq.setUnaligned(rawSequence.substr(oligo.length()));
735 //if you found the barcode or if you don't want to allow for diffs
736 if ((pdiffs == 0) || (success == 0)) { return success; }
738 else { //try aligning and see if you can find it
742 Alignment* alignment;
743 if (primers.size() > 0) {
744 map<string,int>::iterator it=primers.begin();
746 for(it;it!=primers.end();it++){
747 if(it->first.length() > maxLength){
748 maxLength = it->first.length();
751 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));
753 }else{ alignment = NULL; }
755 //can you find the barcode
761 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
762 string oligo = it->first;
763 // int length = oligo.length();
765 if(rawSequence.length() < maxLength){
766 success = pdiffs + 100;
770 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
771 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
772 oligo = alignment->getSeqAAln();
773 string temp = alignment->getSeqBAln();
775 int alnLength = oligo.length();
777 for(int i=oligo.length()-1;i>=0;i--){
778 if(oligo[i] != '-'){ alnLength = i+1; break; }
780 oligo = oligo.substr(0,alnLength);
781 temp = temp.substr(0,alnLength);
783 int numDiff = countDiffs(oligo, temp);
785 if(numDiff < minDiff){
788 minGroup = it->second;
790 for(int i=0;i<alnLength;i++){
796 else if(numDiff == minDiff){
802 if(minDiff > pdiffs) { success = minDiff; } //no good matches
803 else if(minCount > 1) { success = pdiffs + 10; } //can't tell the difference between multiple primers
804 else{ //use the best match
806 seq.setUnaligned(rawSequence.substr(minPos));
810 if (alignment != NULL) { delete alignment; }
817 catch(exception& e) {
818 m->errorOut(e, "TrimFlowsCommand", "stripForward");
823 //***************************************************************************************************************
825 bool TrimFlowsCommand::stripReverse(Sequence& seq){
828 string rawSequence = seq.getUnaligned();
829 bool success = 0; //guilty until proven innocent
831 for(int i=0;i<numRPrimers;i++){
832 string oligo = revPrimer[i];
834 if(rawSequence.length() < oligo.length()){
839 if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
840 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
849 catch(exception& e) {
850 m->errorOut(e, "TrimFlowsCommand", "stripReverse");
856 //***************************************************************************************************************
858 bool TrimFlowsCommand::compareDNASeq(string oligo, string seq){
861 int length = oligo.length();
863 for(int i=0;i<length;i++){
865 if(oligo[i] != seq[i]){
866 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C') { success = 0; }
867 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { success = 0; }
868 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { success = 0; }
869 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { success = 0; }
870 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { success = 0; }
871 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
872 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { success = 0; }
873 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
874 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
875 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
876 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { success = 0; }
877 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
879 if(success == 0) { break; }
888 catch(exception& e) {
889 m->errorOut(e, "TrimFlowsCommand", "compareDNASeq");
895 //***************************************************************************************************************
897 int TrimFlowsCommand::countDiffs(string oligo, string seq){
900 int length = oligo.length();
903 for(int i=0;i<length;i++){
905 if(oligo[i] != seq[i]){
906 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.') { countDiffs++; }
907 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { countDiffs++; }
908 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { countDiffs++; }
909 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { countDiffs++; }
910 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { countDiffs++; }
911 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
912 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { countDiffs++; }
913 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
914 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
915 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
916 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { countDiffs++; }
917 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
924 catch(exception& e) {
925 m->errorOut(e, "TrimFlowsCommand", "countDiffs");
931 /**************************************************************************************************/
933 vector<unsigned long int> TrimFlowsCommand::getFlowFileBreaks() {
937 vector<unsigned long int> filePos;
938 filePos.push_back(0);
941 unsigned long int size;
943 //get num bytes in file
944 pFile = fopen (flowFileName.c_str(),"rb");
945 if (pFile==NULL) perror ("Error opening file");
947 fseek (pFile, 0, SEEK_END);
952 //estimate file breaks
953 unsigned long int chunkSize = 0;
954 chunkSize = size / processors;
956 //file too small to divide by processors
957 if (chunkSize == 0) { processors = 1; filePos.push_back(size); return filePos; }
959 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
960 for (int i = 0; i < processors; i++) {
961 unsigned long int spot = (i+1) * chunkSize;
964 m->openInputFile(flowFileName, in);
967 string dummy = m->getline(in);
969 //there was not another sequence before the end of the file
970 unsigned long int sanityPos = in.tellg();
972 // if (sanityPos == -1) { break; }
973 // else { filePos.push_back(newSpot); }
974 if (sanityPos == -1) { break; }
975 else { filePos.push_back(sanityPos); }
981 filePos.push_back(size);
983 //sanity check filePos
984 for (int i = 0; i < (filePos.size()-1); i++) {
985 if (filePos[(i+1)] <= filePos[i]) { filePos.erase(filePos.begin()+(i+1)); i--; }
989 m->openInputFile(flowFileName, in);
992 unsigned long int spot = in.tellg();
996 processors = (filePos.size() - 1);
1000 catch(exception& e) {
1001 m->errorOut(e, "TrimSeqsCommand", "getFlowFileBreaks");
1006 /**************************************************************************************************/
1008 int TrimFlowsCommand::createProcessesCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames){
1011 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1013 int exitCommand = 1;
1016 //loop through and create all the processes you want
1017 while (process != processors) {
1021 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1023 }else if (pid == 0){
1025 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
1027 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
1028 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
1029 tempBarcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
1031 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
1037 driverCreateTrim(flowFileName,
1038 (trimFlowFileName + toString(getpid()) + ".temp"),
1039 (scrapFlowFileName + toString(getpid()) + ".temp"),
1040 (fastaFileName + toString(getpid()) + ".temp"),
1041 tempBarcodePrimerComboFileNames, lines[process]);
1045 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1046 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1053 m->openOutputFile(trimFlowFileName, temp);
1056 m->openOutputFile(scrapFlowFileName, temp);
1060 m->openOutputFile(fastaFileName, temp);
1064 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
1066 //force parent to wait until all the processes are done
1067 for (int i=0;i<processIDS.size();i++) {
1068 int temp = processIDS[i];
1073 m->mothurOutEndLine();
1074 for(int i=0;i<processIDS.size();i++){
1076 m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
1078 m->appendFiles((trimFlowFileName + toString(processIDS[i]) + ".temp"), trimFlowFileName);
1079 remove((trimFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1080 // m->mothurOut("\tDone with trim.flow file"); m->mothurOutEndLine();
1082 m->appendFiles((scrapFlowFileName + toString(processIDS[i]) + ".temp"), scrapFlowFileName);
1083 remove((scrapFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1084 // m->mothurOut("\tDone with scrap.flow file"); m->mothurOutEndLine();
1087 m->appendFiles((fastaFileName + toString(processIDS[i]) + ".temp"), fastaFileName);
1088 remove((fastaFileName + toString(processIDS[i]) + ".temp").c_str());
1089 // m->mothurOut("\tDone with flow.fasta file"); m->mothurOutEndLine();
1092 for (int j = 0; j < barcodePrimerComboFileNames.size(); j++) {
1093 for (int k = 0; k < barcodePrimerComboFileNames[0].size(); k++) {
1094 m->appendFiles((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"), barcodePrimerComboFileNames[j][k]);
1095 remove((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp").c_str());
1104 catch(exception& e) {
1105 m->errorOut(e, "TrimFlowsCommand", "createProcessesCreateTrim");
1110 //***************************************************************************************************************