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; }
87 vector<string> myArray = setParameters();
89 OptionParser parser(option);
90 map<string,string> parameters = parser.getParameters();
92 ValidParameters validParameter;
93 map<string,string>::iterator it;
95 //check to make sure all parameters are valid for command
96 for (it = parameters.begin(); it != parameters.end(); it++) {
97 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
100 //initialize outputTypes
101 vector<string> tempOutNames;
102 outputTypes["flow"] = tempOutNames;
103 outputTypes["fasta"] = tempOutNames;
105 //if the user changes the input directory command factory will send this info to us in the output parameter
106 string inputDir = validParameter.validFile(parameters, "inputdir", false);
107 if (inputDir == "not found"){ inputDir = ""; }
110 it = parameters.find("flow");
111 //user has given a template file
112 if(it != parameters.end()){
113 path = m->hasPath(it->second);
114 //if the user has not given a path then, add inputdir. else leave path alone.
115 if (path == "") { parameters["flow"] = inputDir + it->second; }
118 it = parameters.find("oligos");
119 //user has given a template file
120 if(it != parameters.end()){
121 path = m->hasPath(it->second);
122 //if the user has not given a path then, add inputdir. else leave path alone.
123 if (path == "") { parameters["oligos"] = inputDir + it->second; }
127 // it = parameters.find("group");
128 // //user has given a template file
129 // if(it != parameters.end()){
130 // path = m->hasPath(it->second);
131 // //if the user has not given a path then, add inputdir. else leave path alone.
132 // if (path == "") { parameters["group"] = inputDir + it->second; }
137 //check for required parameters
138 flowFileName = validParameter.validFile(parameters, "flow", true);
139 if (flowFileName == "not found") {
140 flowFileName = m->getFlowFile();
141 if (flowFileName != "") { m->mothurOut("Using " + flowFileName + " as input file for the flow parameter."); m->mothurOutEndLine(); }
143 m->mothurOut("No valid current flow file. You must provide a flow file."); m->mothurOutEndLine();
146 }else if (flowFileName == "not open") { flowFileName = ""; abort = true; }
148 //if the user changes the output directory command factory will send this info to us in the output parameter
149 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
151 outputDir += m->hasPath(flowFileName); //if user entered a file with a path then preserve it
155 //check for optional parameter and set defaults
156 // ...at some point should added some additional type checking...
159 temp = validParameter.validFile(parameters, "minflows", false); if (temp == "not found") { temp = "360"; }
160 convert(temp, minFlows);
162 temp = validParameter.validFile(parameters, "maxflows", false); if (temp == "not found") { temp = "720"; }
163 convert(temp, maxFlows);
166 temp = validParameter.validFile(parameters, "oligos", true);
167 if (temp == "not found") { oligoFileName = ""; }
168 else if(temp == "not open") { abort = true; }
169 else { oligoFileName = temp; }
171 temp = validParameter.validFile(parameters, "fasta", false); if (temp == "not found"){ fasta = 0; }
172 else if(m->isTrue(temp)) { fasta = 1; }
174 temp = validParameter.validFile(parameters, "maxhomop", false); if (temp == "not found"){ temp = "9"; }
175 convert(temp, maxHomoP);
177 temp = validParameter.validFile(parameters, "signal", false); if (temp == "not found"){ temp = "0.50"; }
178 convert(temp, signal);
180 temp = validParameter.validFile(parameters, "noise", false); if (temp == "not found"){ temp = "0.70"; }
181 convert(temp, noise);
183 temp = validParameter.validFile(parameters, "minlength", false); if (temp == "not found"){ temp = "0"; }
184 convert(temp, minLength);
186 temp = validParameter.validFile(parameters, "maxlength", false); if (temp == "not found"){ temp = "0"; }
187 convert(temp, maxLength);
189 temp = validParameter.validFile(parameters, "bdiffs", false); if (temp == "not found"){ temp = "0"; }
190 convert(temp, bdiffs);
192 temp = validParameter.validFile(parameters, "pdiffs", false); if (temp == "not found"){ temp = "0"; }
193 convert(temp, pdiffs);
195 temp = validParameter.validFile(parameters, "tdiffs", false);
196 if (temp == "not found"){ int tempTotal = pdiffs + bdiffs; temp = toString(tempTotal); }
197 convert(temp, tdiffs);
198 if(tdiffs == 0){ tdiffs = bdiffs + pdiffs; }
200 temp = validParameter.validFile(parameters, "allfiles", false); if (temp == "not found"){ temp = "T"; }
201 allFiles = m->isTrue(temp);
203 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
204 m->setProcessors(temp);
205 convert(temp, processors);
207 flowOrder = validParameter.validFile(parameters, "order", false);
208 if (flowOrder == "not found"){ flowOrder = "TACG"; }
209 else if(flowOrder.length() != 4){
210 m->mothurOut("The value of the order option must be four bases long\n");
213 if(oligoFileName == ""){ allFiles = 0; }
220 catch(exception& e) {
221 m->errorOut(e, "TrimFlowsCommand", "TrimSeqsCommand");
226 //***************************************************************************************************************
228 int TrimFlowsCommand::execute(){
231 if (abort == true) { if (calledHelp) { return 0; } return 2; }
233 string trimFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "trim.flow";
234 outputNames.push_back(trimFlowFileName); outputTypes["flow"].push_back(trimFlowFileName);
236 string scrapFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "scrap.flow";
237 outputNames.push_back(scrapFlowFileName); outputTypes["flow"].push_back(scrapFlowFileName);
239 string fastaFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.fasta";
241 outputNames.push_back(fastaFileName); outputTypes["fasta"].push_back(fastaFileName);
244 vector<unsigned long int> flowFilePos = getFlowFileBreaks();
245 for (int i = 0; i < (flowFilePos.size()-1); i++) {
246 lines.push_back(new linePair(flowFilePos[i], flowFilePos[(i+1)]));
249 vector<vector<string> > barcodePrimerComboFileNames;
250 if(oligoFileName != ""){
251 getOligos(barcodePrimerComboFileNames);
254 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
256 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
258 createProcessesCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames);
261 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
264 if (m->control_pressed) { return 0; }
266 string flowFilesFileName;
271 flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
272 m->openOutputFile(flowFilesFileName, output);
274 for(int i=0;i<barcodePrimerComboFileNames.size();i++){
275 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
278 unsigned long int size;
280 //get num bytes in file
281 pFile = fopen (barcodePrimerComboFileNames[i][j].c_str(),"rb");
282 if (pFile==NULL) perror ("Error opening file");
284 fseek (pFile, 0, SEEK_END);
290 remove(barcodePrimerComboFileNames[i][j].c_str());
293 output << barcodePrimerComboFileNames[i][j] << endl;
300 flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
301 m->openOutputFile(flowFilesFileName, output);
303 output << trimFlowFileName << endl;
307 outputTypes["flow.files"].push_back(flowFilesFileName);
308 outputNames.push_back(flowFileName);
310 //set fasta file as new current fastafile
312 itTypes = outputTypes.find("fasta");
313 if (itTypes != outputTypes.end()) {
314 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
317 m->mothurOutEndLine();
318 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
319 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
320 m->mothurOutEndLine();
324 catch(exception& e) {
325 m->errorOut(e, "TrimSeqsCommand", "execute");
330 //***************************************************************************************************************
332 int TrimFlowsCommand::driverCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames, linePair* line){
336 ofstream trimFlowFile;
337 m->openOutputFile(trimFlowFileName, trimFlowFile);
338 trimFlowFile.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
340 ofstream scrapFlowFile;
341 m->openOutputFile(scrapFlowFileName, scrapFlowFile);
342 scrapFlowFile.setf(ios::fixed, ios::floatfield); scrapFlowFile.setf(ios::showpoint);
344 if(line->start == 4){
345 scrapFlowFile << maxFlows << endl;
346 trimFlowFile << maxFlows << endl;
348 for(int i=0;i<barcodePrimerComboFileNames.size();i++){
349 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
350 // barcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
352 m->openOutputFile(barcodePrimerComboFileNames[i][j], temp);
353 temp << maxFlows << endl;
360 FlowData flowData(numFlows, signal, noise, maxHomoP, flowOrder);
363 if(fasta){ m->openOutputFile(fastaFileName, fastaFile); }
366 m->openInputFile(flowFileName, flowFile);
368 flowFile.seekg(line->start);
376 int currentSeqDiffs = 0;
377 string trashCode = "";
379 flowData.getNext(flowFile);
380 flowData.capFlows(maxFlows);
382 Sequence currSeq = flowData.getSequence();
383 if(!flowData.hasMinFlows(minFlows)){ //screen to see if sequence is of a minimum number of flows
388 if(minLength > 0 || maxLength > 0){ //screen to see if sequence is above and below a specific number of bases
389 int seqLength = currSeq.getNumBases();
390 if(seqLength < minLength || seqLength > maxLength){
397 int barcodeIndex = 0;
399 if(barcodes.size() != 0){
400 success = stripBarcode(currSeq, barcodeIndex);
401 if(success > bdiffs) { trashCode += 'b'; }
402 else{ currentSeqDiffs += success; }
405 if(numFPrimers != 0){
406 success = stripForward(currSeq, primerIndex);
407 if(success > pdiffs) { trashCode += 'f'; }
408 else{ currentSeqDiffs += success; }
411 if (currentSeqDiffs > tdiffs) { trashCode += 't'; }
413 if(numRPrimers != 0){
414 success = stripReverse(currSeq);
415 if(!success) { trashCode += 'r'; }
418 if(trashCode.length() == 0){
420 flowData.printFlows(trimFlowFile);
422 if(fasta) { currSeq.printSequence(fastaFile); }
426 m->openOutputFileAppend(barcodePrimerComboFileNames[barcodeIndex][primerIndex], output);
427 output.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
429 flowData.printFlows(output);
434 flowData.printFlows(scrapFlowFile, trashCode);
440 if((count) % 10000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
442 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
443 unsigned long int pos = flowFile.tellg();
445 if ((pos == -1) || (pos >= line->end)) { break; }
447 if (flowFile.eof()) { break; }
452 if((count) % 10000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
454 trimFlowFile.close();
455 scrapFlowFile.close();
457 if(fasta){ fastaFile.close(); }
461 catch(exception& e) {
462 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
467 //***************************************************************************************************************
469 void TrimFlowsCommand::getOligos(vector<vector<string> >& outFlowFileNames){
472 m->openInputFile(oligoFileName, oligosFile);
474 string type, oligo, group;
477 int indexBarcode = 0;
479 while(!oligosFile.eof()){
481 oligosFile >> type; m->gobble(oligosFile); //get the first column value of the row - is it a comment or a feature we are interested in?
483 if(type[0] == '#'){ //igore the line because there's a comment
484 while (!oligosFile.eof()) { char c = oligosFile.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
486 else{ //there's a feature we're interested in
488 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); } //make type case insensitive
490 oligosFile >> oligo; //get the DNA sequence for the feature
492 for(int i=0;i<oligo.length();i++){ //make type case insensitive and change any U's to T's
493 oligo[i] = toupper(oligo[i]);
494 if(oligo[i] == 'U') { oligo[i] = 'T'; }
497 if(type == "FORWARD"){ //if the feature is a forward primer...
500 while (!oligosFile.eof()) { // get rest of line in case there is a primer name = will have the name of the primer
501 char c = oligosFile.get();
502 if (c == 10 || c == 13){ break; }
503 else if (c == 32 || c == 9){;} //space or tab
507 //have we seen this primer already?
508 map<string, int>::iterator itPrimer = primers.find(oligo);
509 if (itPrimer != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
511 primers[oligo]=indexPrimer; indexPrimer++;
512 primerNameVector.push_back(group);
515 else if(type == "REVERSE"){
516 Sequence oligoRC("reverse", oligo);
517 oligoRC.reverseComplement();
518 revPrimer.push_back(oligoRC.getUnaligned());
520 else if(type == "BARCODE"){
523 //check for repeat barcodes
524 map<string, int>::iterator itBar = barcodes.find(oligo);
525 if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
527 barcodes[oligo]=indexBarcode; indexBarcode++;
528 barcodeNameVector.push_back(group);
531 m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();
535 m->gobble(oligosFile);
539 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0; }
541 //add in potential combos
542 if(barcodeNameVector.size() == 0){
544 barcodeNameVector.push_back("");
547 if(primerNameVector.size() == 0){
549 primerNameVector.push_back("");
553 outFlowFileNames.resize(barcodeNameVector.size());
554 for(int i=0;i<outFlowFileNames.size();i++){
555 outFlowFileNames[i].assign(primerNameVector.size(), "");
560 for(map<string, int>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
561 for(map<string, int>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
563 string primerName = primerNameVector[itPrimer->second];
564 string barcodeName = barcodeNameVector[itBar->second];
566 string comboGroupName = "";
567 string fileName = "";
569 if(primerName == ""){
570 comboGroupName = barcodeNameVector[itBar->second];
571 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
574 if(barcodeName == ""){
575 comboGroupName = primerNameVector[itPrimer->second];
578 comboGroupName = barcodeNameVector[itBar->second] + "." + primerNameVector[itPrimer->second];
580 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
583 outputNames.push_back(fileName);
584 outputTypes["flow"].push_back(fileName);
585 outFlowFileNames[itBar->second][itPrimer->second] = fileName;
588 m->openOutputFile(fileName, temp);
594 numFPrimers = primers.size();
595 numRPrimers = revPrimer.size();
598 catch(exception& e) {
599 m->errorOut(e, "TrimSeqsCommand", "getOligos");
604 //***************************************************************************************************************
606 int TrimFlowsCommand::stripBarcode(Sequence& seq, int& group){
609 string rawSequence = seq.getUnaligned();
610 int success = bdiffs + 1; //guilty until proven innocent
612 //can you find the barcode
613 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
614 string oligo = it->first;
615 if(rawSequence.length() < oligo.length()){ //let's just assume that the barcodes are the same length
616 success = bdiffs + 10; //if the sequence is shorter than the barcode then bail out
620 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
622 seq.setUnaligned(rawSequence.substr(oligo.length()));
629 //if you found the barcode or if you don't want to allow for diffs
630 if ((bdiffs == 0) || (success == 0)) { return success; }
632 else { //try aligning and see if you can find it
636 Alignment* alignment;
637 if (barcodes.size() > 0) {
638 map<string,int>::iterator it=barcodes.begin();
640 for(it;it!=barcodes.end();it++){
641 if(it->first.length() > maxLength){
642 maxLength = it->first.length();
645 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));
647 }else{ alignment = NULL; }
649 //can you find the barcode
655 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
656 string oligo = it->first;
657 // int length = oligo.length();
659 if(rawSequence.length() < maxLength){ //let's just assume that the barcodes are the same length
660 success = bdiffs + 10;
664 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
665 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
666 oligo = alignment->getSeqAAln();
667 string temp = alignment->getSeqBAln();
669 int alnLength = oligo.length();
671 for(int i=oligo.length()-1;i>=0;i--){
672 if(oligo[i] != '-'){ alnLength = i+1; break; }
674 oligo = oligo.substr(0,alnLength);
675 temp = temp.substr(0,alnLength);
677 int numDiff = countDiffs(oligo, temp);
679 if(numDiff < minDiff){
682 minGroup = it->second;
684 for(int i=0;i<alnLength;i++){
690 else if(numDiff == minDiff){
696 if(minDiff > bdiffs) { success = minDiff; } //no good matches
697 else if(minCount > 1) { success = bdiffs + 100; } //can't tell the difference between multiple barcodes
698 else{ //use the best match
700 seq.setUnaligned(rawSequence.substr(minPos));
704 if (alignment != NULL) { delete alignment; }
711 catch(exception& e) {
712 m->errorOut(e, "TrimFlowsCommand", "stripBarcode");
718 //***************************************************************************************************************
720 int TrimFlowsCommand::stripForward(Sequence& seq, int& group){
723 string rawSequence = seq.getUnaligned();
724 int success = pdiffs + 1; //guilty until proven innocent
726 //can you find the primer
727 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
728 string oligo = it->first;
729 if(rawSequence.length() < oligo.length()){ //let's just assume that the primers are the same length
730 success = pdiffs + 10; //if the sequence is shorter than the barcode then bail out
734 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
736 seq.setUnaligned(rawSequence.substr(oligo.length()));
742 //if you found the barcode or if you don't want to allow for diffs
743 if ((pdiffs == 0) || (success == 0)) { return success; }
745 else { //try aligning and see if you can find it
749 Alignment* alignment;
750 if (primers.size() > 0) {
751 map<string,int>::iterator it=primers.begin();
753 for(it;it!=primers.end();it++){
754 if(it->first.length() > maxLength){
755 maxLength = it->first.length();
758 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));
760 }else{ alignment = NULL; }
762 //can you find the barcode
768 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
769 string oligo = it->first;
770 // int length = oligo.length();
772 if(rawSequence.length() < maxLength){
773 success = pdiffs + 100;
777 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
778 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
779 oligo = alignment->getSeqAAln();
780 string temp = alignment->getSeqBAln();
782 int alnLength = oligo.length();
784 for(int i=oligo.length()-1;i>=0;i--){
785 if(oligo[i] != '-'){ alnLength = i+1; break; }
787 oligo = oligo.substr(0,alnLength);
788 temp = temp.substr(0,alnLength);
790 int numDiff = countDiffs(oligo, temp);
792 if(numDiff < minDiff){
795 minGroup = it->second;
797 for(int i=0;i<alnLength;i++){
803 else if(numDiff == minDiff){
809 if(minDiff > pdiffs) { success = minDiff; } //no good matches
810 else if(minCount > 1) { success = pdiffs + 10; } //can't tell the difference between multiple primers
811 else{ //use the best match
813 seq.setUnaligned(rawSequence.substr(minPos));
817 if (alignment != NULL) { delete alignment; }
824 catch(exception& e) {
825 m->errorOut(e, "TrimFlowsCommand", "stripForward");
830 //***************************************************************************************************************
832 bool TrimFlowsCommand::stripReverse(Sequence& seq){
835 string rawSequence = seq.getUnaligned();
836 bool success = 0; //guilty until proven innocent
838 for(int i=0;i<numRPrimers;i++){
839 string oligo = revPrimer[i];
841 if(rawSequence.length() < oligo.length()){
846 if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
847 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
856 catch(exception& e) {
857 m->errorOut(e, "TrimFlowsCommand", "stripReverse");
863 //***************************************************************************************************************
865 bool TrimFlowsCommand::compareDNASeq(string oligo, string seq){
868 int length = oligo.length();
870 for(int i=0;i<length;i++){
872 if(oligo[i] != seq[i]){
873 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C') { success = 0; }
874 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { success = 0; }
875 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { success = 0; }
876 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { success = 0; }
877 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { success = 0; }
878 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
879 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { success = 0; }
880 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
881 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
882 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
883 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { success = 0; }
884 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
886 if(success == 0) { break; }
895 catch(exception& e) {
896 m->errorOut(e, "TrimFlowsCommand", "compareDNASeq");
902 //***************************************************************************************************************
904 int TrimFlowsCommand::countDiffs(string oligo, string seq){
907 int length = oligo.length();
910 for(int i=0;i<length;i++){
912 if(oligo[i] != seq[i]){
913 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.') { countDiffs++; }
914 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { countDiffs++; }
915 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { countDiffs++; }
916 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { countDiffs++; }
917 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { countDiffs++; }
918 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
919 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { countDiffs++; }
920 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
921 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
922 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
923 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { countDiffs++; }
924 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
931 catch(exception& e) {
932 m->errorOut(e, "TrimFlowsCommand", "countDiffs");
938 /**************************************************************************************************/
940 vector<unsigned long int> TrimFlowsCommand::getFlowFileBreaks() {
944 vector<unsigned long int> filePos;
945 filePos.push_back(0);
948 unsigned long int size;
950 //get num bytes in file
951 pFile = fopen (flowFileName.c_str(),"rb");
952 if (pFile==NULL) perror ("Error opening file");
954 fseek (pFile, 0, SEEK_END);
959 //estimate file breaks
960 unsigned long int chunkSize = 0;
961 chunkSize = size / processors;
963 //file too small to divide by processors
964 if (chunkSize == 0) { processors = 1; filePos.push_back(size); return filePos; }
966 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
967 for (int i = 0; i < processors; i++) {
968 unsigned long int spot = (i+1) * chunkSize;
971 m->openInputFile(flowFileName, in);
974 string dummy = m->getline(in);
976 //there was not another sequence before the end of the file
977 unsigned long int sanityPos = in.tellg();
979 // if (sanityPos == -1) { break; }
980 // else { filePos.push_back(newSpot); }
981 if (sanityPos == -1) { break; }
982 else { filePos.push_back(sanityPos); }
988 filePos.push_back(size);
990 //sanity check filePos
991 for (int i = 0; i < (filePos.size()-1); i++) {
992 if (filePos[(i+1)] <= filePos[i]) { filePos.erase(filePos.begin()+(i+1)); i--; }
996 m->openInputFile(flowFileName, in);
999 unsigned long int spot = in.tellg();
1003 processors = (filePos.size() - 1);
1007 catch(exception& e) {
1008 m->errorOut(e, "TrimSeqsCommand", "getFlowFileBreaks");
1013 /**************************************************************************************************/
1015 int TrimFlowsCommand::createProcessesCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames){
1018 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1020 int exitCommand = 1;
1023 //loop through and create all the processes you want
1024 while (process != processors) {
1028 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1030 }else if (pid == 0){
1032 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
1034 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
1035 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
1036 tempBarcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
1038 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
1044 driverCreateTrim(flowFileName,
1045 (trimFlowFileName + toString(getpid()) + ".temp"),
1046 (scrapFlowFileName + toString(getpid()) + ".temp"),
1047 (fastaFileName + toString(getpid()) + ".temp"),
1048 tempBarcodePrimerComboFileNames, lines[process]);
1052 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1053 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1060 m->openOutputFile(trimFlowFileName, temp);
1063 m->openOutputFile(scrapFlowFileName, temp);
1067 m->openOutputFile(fastaFileName, temp);
1071 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
1073 //force parent to wait until all the processes are done
1074 for (int i=0;i<processIDS.size();i++) {
1075 int temp = processIDS[i];
1080 m->mothurOutEndLine();
1081 for(int i=0;i<processIDS.size();i++){
1083 m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
1085 m->appendFiles((trimFlowFileName + toString(processIDS[i]) + ".temp"), trimFlowFileName);
1086 remove((trimFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1087 // m->mothurOut("\tDone with trim.flow file"); m->mothurOutEndLine();
1089 m->appendFiles((scrapFlowFileName + toString(processIDS[i]) + ".temp"), scrapFlowFileName);
1090 remove((scrapFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1091 // m->mothurOut("\tDone with scrap.flow file"); m->mothurOutEndLine();
1094 m->appendFiles((fastaFileName + toString(processIDS[i]) + ".temp"), fastaFileName);
1095 remove((fastaFileName + toString(processIDS[i]) + ".temp").c_str());
1096 // m->mothurOut("\tDone with flow.fasta file"); m->mothurOutEndLine();
1099 for (int j = 0; j < barcodePrimerComboFileNames.size(); j++) {
1100 for (int k = 0; k < barcodePrimerComboFileNames[0].size(); k++) {
1101 m->appendFiles((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"), barcodePrimerComboFileNames[j][k]);
1102 remove((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp").c_str());
1111 catch(exception& e) {
1112 m->errorOut(e, "TrimFlowsCommand", "createProcessesCreateTrim");
1117 //***************************************************************************************************************