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; }
128 // it = parameters.find("group");
129 // //user has given a template file
130 // if(it != parameters.end()){
131 // path = m->hasPath(it->second);
132 // //if the user has not given a path then, add inputdir. else leave path alone.
133 // if (path == "") { parameters["group"] = inputDir + it->second; }
138 //check for required parameters
139 flowFileName = validParameter.validFile(parameters, "flow", true);
140 if (flowFileName == "not found") {
141 flowFileName = m->getFlowFile();
142 if (flowFileName != "") { m->mothurOut("Using " + flowFileName + " as input file for the flow parameter."); m->mothurOutEndLine(); }
144 m->mothurOut("No valid current flow file. You must provide a flow file."); m->mothurOutEndLine();
147 }else if (flowFileName == "not open") { flowFileName = ""; abort = true; }
149 //if the user changes the output directory command factory will send this info to us in the output parameter
150 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
152 outputDir += m->hasPath(flowFileName); //if user entered a file with a path then preserve it
156 //check for optional parameter and set defaults
157 // ...at some point should added some additional type checking...
160 temp = validParameter.validFile(parameters, "minflows", false); if (temp == "not found") { temp = "360"; }
161 convert(temp, minFlows);
163 temp = validParameter.validFile(parameters, "maxflows", false); if (temp == "not found") { temp = "720"; }
164 convert(temp, maxFlows);
167 temp = validParameter.validFile(parameters, "oligos", true);
168 if (temp == "not found") { oligoFileName = ""; }
169 else if(temp == "not open") { abort = true; }
170 else { oligoFileName = temp; }
172 temp = validParameter.validFile(parameters, "fasta", false); if (temp == "not found"){ fasta = 0; }
173 else if(m->isTrue(temp)) { fasta = 1; }
175 temp = validParameter.validFile(parameters, "maxhomop", false); if (temp == "not found"){ temp = "9"; }
176 convert(temp, maxHomoP);
178 temp = validParameter.validFile(parameters, "signal", false); if (temp == "not found"){ temp = "0.50"; }
179 convert(temp, signal);
181 temp = validParameter.validFile(parameters, "noise", false); if (temp == "not found"){ temp = "0.70"; }
182 convert(temp, noise);
184 temp = validParameter.validFile(parameters, "minlength", false); if (temp == "not found"){ temp = "0"; }
185 convert(temp, minLength);
187 temp = validParameter.validFile(parameters, "maxlength", false); if (temp == "not found"){ temp = "0"; }
188 convert(temp, maxLength);
190 temp = validParameter.validFile(parameters, "bdiffs", false); if (temp == "not found"){ temp = "0"; }
191 convert(temp, bdiffs);
193 temp = validParameter.validFile(parameters, "pdiffs", false); if (temp == "not found"){ temp = "0"; }
194 convert(temp, pdiffs);
196 temp = validParameter.validFile(parameters, "tdiffs", false);
197 if (temp == "not found"){ int tempTotal = pdiffs + bdiffs; temp = toString(tempTotal); }
198 convert(temp, tdiffs);
199 if(tdiffs == 0){ tdiffs = bdiffs + pdiffs; }
201 temp = validParameter.validFile(parameters, "allfiles", false); if (temp == "not found"){ temp = "T"; }
202 allFiles = m->isTrue(temp);
204 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
205 m->setProcessors(temp);
206 convert(temp, processors);
208 flowOrder = validParameter.validFile(parameters, "order", false);
209 if (flowOrder == "not found"){ flowOrder = "TACG"; }
210 else if(flowOrder.length() != 4){
211 m->mothurOut("The value of the order option must be four bases long\n");
214 if(oligoFileName == ""){ allFiles = 0; }
221 catch(exception& e) {
222 m->errorOut(e, "TrimFlowsCommand", "TrimSeqsCommand");
227 //***************************************************************************************************************
229 int TrimFlowsCommand::execute(){
232 if (abort == true) { if (calledHelp) { return 0; } return 2; }
234 string trimFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "trim.flow";
235 outputNames.push_back(trimFlowFileName); outputTypes["flow"].push_back(trimFlowFileName);
237 string scrapFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "scrap.flow";
238 outputNames.push_back(scrapFlowFileName); outputTypes["flow"].push_back(scrapFlowFileName);
240 string fastaFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.fasta";
242 outputNames.push_back(fastaFileName); outputTypes["fasta"].push_back(fastaFileName);
245 vector<unsigned long int> flowFilePos = getFlowFileBreaks();
246 for (int i = 0; i < (flowFilePos.size()-1); i++) {
247 lines.push_back(new linePair(flowFilePos[i], flowFilePos[(i+1)]));
250 vector<vector<string> > barcodePrimerComboFileNames;
251 if(oligoFileName != ""){
252 getOligos(barcodePrimerComboFileNames);
255 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
257 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
259 createProcessesCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames);
262 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
265 if (m->control_pressed) { return 0; }
267 string flowFilesFileName;
272 flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
273 m->openOutputFile(flowFilesFileName, output);
275 for(int i=0;i<barcodePrimerComboFileNames.size();i++){
276 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
279 unsigned long int size;
281 //get num bytes in file
282 pFile = fopen (barcodePrimerComboFileNames[i][j].c_str(),"rb");
283 if (pFile==NULL) perror ("Error opening file");
285 fseek (pFile, 0, SEEK_END);
291 remove(barcodePrimerComboFileNames[i][j].c_str());
294 output << barcodePrimerComboFileNames[i][j] << endl;
301 flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
302 m->openOutputFile(flowFilesFileName, output);
304 output << trimFlowFileName << endl;
308 outputTypes["flow.files"].push_back(flowFilesFileName);
309 outputNames.push_back(flowFileName);
311 //set fasta file as new current fastafile
313 itTypes = outputTypes.find("fasta");
314 if (itTypes != outputTypes.end()) {
315 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
318 m->mothurOutEndLine();
319 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
320 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
321 m->mothurOutEndLine();
325 catch(exception& e) {
326 m->errorOut(e, "TrimSeqsCommand", "execute");
331 //***************************************************************************************************************
333 int TrimFlowsCommand::driverCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames, linePair* line){
337 ofstream trimFlowFile;
338 m->openOutputFile(trimFlowFileName, trimFlowFile);
339 trimFlowFile.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
341 ofstream scrapFlowFile;
342 m->openOutputFile(scrapFlowFileName, scrapFlowFile);
343 scrapFlowFile.setf(ios::fixed, ios::floatfield); scrapFlowFile.setf(ios::showpoint);
345 if(line->start == 4){
346 scrapFlowFile << maxFlows << endl;
347 trimFlowFile << maxFlows << endl;
349 for(int i=0;i<barcodePrimerComboFileNames.size();i++){
350 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
351 // barcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
353 m->openOutputFile(barcodePrimerComboFileNames[i][j], temp);
354 temp << maxFlows << endl;
361 FlowData flowData(numFlows, signal, noise, maxHomoP, flowOrder);
364 if(fasta){ m->openOutputFile(fastaFileName, fastaFile); }
367 m->openInputFile(flowFileName, flowFile);
369 flowFile.seekg(line->start);
377 int currentSeqDiffs = 0;
378 string trashCode = "";
380 flowData.getNext(flowFile);
381 flowData.capFlows(maxFlows);
383 Sequence currSeq = flowData.getSequence();
384 if(!flowData.hasMinFlows(minFlows)){ //screen to see if sequence is of a minimum number of flows
389 if(minLength > 0 || maxLength > 0){ //screen to see if sequence is above and below a specific number of bases
390 int seqLength = currSeq.getNumBases();
391 if(seqLength < minLength || seqLength > maxLength){
398 int barcodeIndex = 0;
400 if(barcodes.size() != 0){
401 success = stripBarcode(currSeq, barcodeIndex);
402 if(success > bdiffs) { trashCode += 'b'; }
403 else{ currentSeqDiffs += success; }
406 if(numFPrimers != 0){
407 success = stripForward(currSeq, primerIndex);
408 if(success > pdiffs) { trashCode += 'f'; }
409 else{ currentSeqDiffs += success; }
412 if (currentSeqDiffs > tdiffs) { trashCode += 't'; }
414 if(numRPrimers != 0){
415 success = stripReverse(currSeq);
416 if(!success) { trashCode += 'r'; }
419 if(trashCode.length() == 0){
421 flowData.printFlows(trimFlowFile);
423 if(fasta) { currSeq.printSequence(fastaFile); }
427 m->openOutputFileAppend(barcodePrimerComboFileNames[barcodeIndex][primerIndex], output);
428 output.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
430 flowData.printFlows(output);
435 flowData.printFlows(scrapFlowFile, trashCode);
441 if((count) % 10000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
443 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
444 unsigned long int pos = flowFile.tellg();
446 if ((pos == -1) || (pos >= line->end)) { break; }
448 if (flowFile.eof()) { break; }
453 if((count) % 10000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
455 trimFlowFile.close();
456 scrapFlowFile.close();
458 if(fasta){ fastaFile.close(); }
462 catch(exception& e) {
463 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
468 //***************************************************************************************************************
470 void TrimFlowsCommand::getOligos(vector<vector<string> >& outFlowFileNames){
473 m->openInputFile(oligoFileName, oligosFile);
475 string type, oligo, group;
478 int indexBarcode = 0;
480 while(!oligosFile.eof()){
482 oligosFile >> type; m->gobble(oligosFile); //get the first column value of the row - is it a comment or a feature we are interested in?
484 if(type[0] == '#'){ //igore the line because there's a comment
485 while (!oligosFile.eof()) { char c = oligosFile.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
487 else{ //there's a feature we're interested in
489 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); } //make type case insensitive
491 oligosFile >> oligo; //get the DNA sequence for the feature
493 for(int i=0;i<oligo.length();i++){ //make type case insensitive and change any U's to T's
494 oligo[i] = toupper(oligo[i]);
495 if(oligo[i] == 'U') { oligo[i] = 'T'; }
498 if(type == "FORWARD"){ //if the feature is a forward primer...
501 while (!oligosFile.eof()) { // get rest of line in case there is a primer name = will have the name of the primer
502 char c = oligosFile.get();
503 if (c == 10 || c == 13){ break; }
504 else if (c == 32 || c == 9){;} //space or tab
508 //have we seen this primer already?
509 map<string, int>::iterator itPrimer = primers.find(oligo);
510 if (itPrimer != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
512 primers[oligo]=indexPrimer; indexPrimer++;
513 primerNameVector.push_back(group);
516 else if(type == "REVERSE"){
517 Sequence oligoRC("reverse", oligo);
518 oligoRC.reverseComplement();
519 revPrimer.push_back(oligoRC.getUnaligned());
521 else if(type == "BARCODE"){
524 //check for repeat barcodes
525 map<string, int>::iterator itBar = barcodes.find(oligo);
526 if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
528 barcodes[oligo]=indexBarcode; indexBarcode++;
529 barcodeNameVector.push_back(group);
532 m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();
536 m->gobble(oligosFile);
540 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0; }
542 //add in potential combos
543 if(barcodeNameVector.size() == 0){
545 barcodeNameVector.push_back("");
548 if(primerNameVector.size() == 0){
550 primerNameVector.push_back("");
554 outFlowFileNames.resize(barcodeNameVector.size());
555 for(int i=0;i<outFlowFileNames.size();i++){
556 outFlowFileNames[i].assign(primerNameVector.size(), "");
561 for(map<string, int>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
562 for(map<string, int>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
564 string primerName = primerNameVector[itPrimer->second];
565 string barcodeName = barcodeNameVector[itBar->second];
567 string comboGroupName = "";
568 string fileName = "";
570 if(primerName == ""){
571 comboGroupName = barcodeNameVector[itBar->second];
572 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
575 if(barcodeName == ""){
576 comboGroupName = primerNameVector[itPrimer->second];
579 comboGroupName = barcodeNameVector[itBar->second] + "." + primerNameVector[itPrimer->second];
581 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
584 outputNames.push_back(fileName);
585 outputTypes["flow"].push_back(fileName);
586 outFlowFileNames[itBar->second][itPrimer->second] = fileName;
589 m->openOutputFile(fileName, temp);
595 numFPrimers = primers.size();
596 numRPrimers = revPrimer.size();
599 catch(exception& e) {
600 m->errorOut(e, "TrimSeqsCommand", "getOligos");
605 //***************************************************************************************************************
607 int TrimFlowsCommand::stripBarcode(Sequence& seq, int& group){
610 string rawSequence = seq.getUnaligned();
611 int success = bdiffs + 1; //guilty until proven innocent
613 //can you find the barcode
614 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
615 string oligo = it->first;
616 if(rawSequence.length() < oligo.length()){ //let's just assume that the barcodes are the same length
617 success = bdiffs + 10; //if the sequence is shorter than the barcode then bail out
621 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
623 seq.setUnaligned(rawSequence.substr(oligo.length()));
630 //if you found the barcode or if you don't want to allow for diffs
631 if ((bdiffs == 0) || (success == 0)) { return success; }
633 else { //try aligning and see if you can find it
637 Alignment* alignment;
638 if (barcodes.size() > 0) {
639 map<string,int>::iterator it=barcodes.begin();
641 for(it;it!=barcodes.end();it++){
642 if(it->first.length() > maxLength){
643 maxLength = it->first.length();
646 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));
648 }else{ alignment = NULL; }
650 //can you find the barcode
656 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
657 string oligo = it->first;
658 // int length = oligo.length();
660 if(rawSequence.length() < maxLength){ //let's just assume that the barcodes are the same length
661 success = bdiffs + 10;
665 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
666 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
667 oligo = alignment->getSeqAAln();
668 string temp = alignment->getSeqBAln();
670 int alnLength = oligo.length();
672 for(int i=oligo.length()-1;i>=0;i--){
673 if(oligo[i] != '-'){ alnLength = i+1; break; }
675 oligo = oligo.substr(0,alnLength);
676 temp = temp.substr(0,alnLength);
678 int numDiff = countDiffs(oligo, temp);
680 if(numDiff < minDiff){
683 minGroup = it->second;
685 for(int i=0;i<alnLength;i++){
691 else if(numDiff == minDiff){
697 if(minDiff > bdiffs) { success = minDiff; } //no good matches
698 else if(minCount > 1) { success = bdiffs + 100; } //can't tell the difference between multiple barcodes
699 else{ //use the best match
701 seq.setUnaligned(rawSequence.substr(minPos));
705 if (alignment != NULL) { delete alignment; }
712 catch(exception& e) {
713 m->errorOut(e, "TrimFlowsCommand", "stripBarcode");
719 //***************************************************************************************************************
721 int TrimFlowsCommand::stripForward(Sequence& seq, int& group){
724 string rawSequence = seq.getUnaligned();
725 int success = pdiffs + 1; //guilty until proven innocent
727 //can you find the primer
728 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
729 string oligo = it->first;
730 if(rawSequence.length() < oligo.length()){ //let's just assume that the primers are the same length
731 success = pdiffs + 10; //if the sequence is shorter than the barcode then bail out
735 if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
737 seq.setUnaligned(rawSequence.substr(oligo.length()));
743 //if you found the barcode or if you don't want to allow for diffs
744 if ((pdiffs == 0) || (success == 0)) { return success; }
746 else { //try aligning and see if you can find it
750 Alignment* alignment;
751 if (primers.size() > 0) {
752 map<string,int>::iterator it=primers.begin();
754 for(it;it!=primers.end();it++){
755 if(it->first.length() > maxLength){
756 maxLength = it->first.length();
759 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));
761 }else{ alignment = NULL; }
763 //can you find the barcode
769 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
770 string oligo = it->first;
771 // int length = oligo.length();
773 if(rawSequence.length() < maxLength){
774 success = pdiffs + 100;
778 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
779 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
780 oligo = alignment->getSeqAAln();
781 string temp = alignment->getSeqBAln();
783 int alnLength = oligo.length();
785 for(int i=oligo.length()-1;i>=0;i--){
786 if(oligo[i] != '-'){ alnLength = i+1; break; }
788 oligo = oligo.substr(0,alnLength);
789 temp = temp.substr(0,alnLength);
791 int numDiff = countDiffs(oligo, temp);
793 if(numDiff < minDiff){
796 minGroup = it->second;
798 for(int i=0;i<alnLength;i++){
804 else if(numDiff == minDiff){
810 if(minDiff > pdiffs) { success = minDiff; } //no good matches
811 else if(minCount > 1) { success = pdiffs + 10; } //can't tell the difference between multiple primers
812 else{ //use the best match
814 seq.setUnaligned(rawSequence.substr(minPos));
818 if (alignment != NULL) { delete alignment; }
825 catch(exception& e) {
826 m->errorOut(e, "TrimFlowsCommand", "stripForward");
831 //***************************************************************************************************************
833 bool TrimFlowsCommand::stripReverse(Sequence& seq){
836 string rawSequence = seq.getUnaligned();
837 bool success = 0; //guilty until proven innocent
839 for(int i=0;i<numRPrimers;i++){
840 string oligo = revPrimer[i];
842 if(rawSequence.length() < oligo.length()){
847 if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
848 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
857 catch(exception& e) {
858 m->errorOut(e, "TrimFlowsCommand", "stripReverse");
864 //***************************************************************************************************************
866 bool TrimFlowsCommand::compareDNASeq(string oligo, string seq){
869 int length = oligo.length();
871 for(int i=0;i<length;i++){
873 if(oligo[i] != seq[i]){
874 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C') { success = 0; }
875 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { success = 0; }
876 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { success = 0; }
877 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { success = 0; }
878 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { success = 0; }
879 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
880 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { success = 0; }
881 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
882 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
883 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { success = 0; }
884 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { success = 0; }
885 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { success = 0; }
887 if(success == 0) { break; }
896 catch(exception& e) {
897 m->errorOut(e, "TrimFlowsCommand", "compareDNASeq");
903 //***************************************************************************************************************
905 int TrimFlowsCommand::countDiffs(string oligo, string seq){
908 int length = oligo.length();
911 for(int i=0;i<length;i++){
913 if(oligo[i] != seq[i]){
914 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.') { countDiffs++; }
915 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N')) { countDiffs++; }
916 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G')) { countDiffs++; }
917 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T')) { countDiffs++; }
918 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A')) { countDiffs++; }
919 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
920 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A')) { countDiffs++; }
921 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
922 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
923 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G')) { countDiffs++; }
924 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C')) { countDiffs++; }
925 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G')) { countDiffs++; }
932 catch(exception& e) {
933 m->errorOut(e, "TrimFlowsCommand", "countDiffs");
939 /**************************************************************************************************/
941 vector<unsigned long int> TrimFlowsCommand::getFlowFileBreaks() {
945 vector<unsigned long int> filePos;
946 filePos.push_back(0);
949 unsigned long int size;
951 //get num bytes in file
952 pFile = fopen (flowFileName.c_str(),"rb");
953 if (pFile==NULL) perror ("Error opening file");
955 fseek (pFile, 0, SEEK_END);
960 //estimate file breaks
961 unsigned long int chunkSize = 0;
962 chunkSize = size / processors;
964 //file too small to divide by processors
965 if (chunkSize == 0) { processors = 1; filePos.push_back(size); return filePos; }
967 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
968 for (int i = 0; i < processors; i++) {
969 unsigned long int spot = (i+1) * chunkSize;
972 m->openInputFile(flowFileName, in);
975 string dummy = m->getline(in);
977 //there was not another sequence before the end of the file
978 unsigned long int sanityPos = in.tellg();
980 // if (sanityPos == -1) { break; }
981 // else { filePos.push_back(newSpot); }
982 if (sanityPos == -1) { break; }
983 else { filePos.push_back(sanityPos); }
989 filePos.push_back(size);
991 //sanity check filePos
992 for (int i = 0; i < (filePos.size()-1); i++) {
993 if (filePos[(i+1)] <= filePos[i]) { filePos.erase(filePos.begin()+(i+1)); i--; }
997 m->openInputFile(flowFileName, in);
1000 unsigned long int spot = in.tellg();
1004 processors = (filePos.size() - 1);
1008 catch(exception& e) {
1009 m->errorOut(e, "TrimSeqsCommand", "getFlowFileBreaks");
1014 /**************************************************************************************************/
1016 int TrimFlowsCommand::createProcessesCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames){
1019 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1021 int exitCommand = 1;
1024 //loop through and create all the processes you want
1025 while (process != processors) {
1029 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1031 }else if (pid == 0){
1033 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
1035 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
1036 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
1037 tempBarcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
1039 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
1045 driverCreateTrim(flowFileName,
1046 (trimFlowFileName + toString(getpid()) + ".temp"),
1047 (scrapFlowFileName + toString(getpid()) + ".temp"),
1048 (fastaFileName + toString(getpid()) + ".temp"),
1049 tempBarcodePrimerComboFileNames, lines[process]);
1053 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1054 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1061 m->openOutputFile(trimFlowFileName, temp);
1064 m->openOutputFile(scrapFlowFileName, temp);
1068 m->openOutputFile(fastaFileName, temp);
1072 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
1074 //force parent to wait until all the processes are done
1075 for (int i=0;i<processIDS.size();i++) {
1076 int temp = processIDS[i];
1081 m->mothurOutEndLine();
1082 for(int i=0;i<processIDS.size();i++){
1084 m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
1086 m->appendFiles((trimFlowFileName + toString(processIDS[i]) + ".temp"), trimFlowFileName);
1087 remove((trimFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1088 // m->mothurOut("\tDone with trim.flow file"); m->mothurOutEndLine();
1090 m->appendFiles((scrapFlowFileName + toString(processIDS[i]) + ".temp"), scrapFlowFileName);
1091 remove((scrapFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1092 // m->mothurOut("\tDone with scrap.flow file"); m->mothurOutEndLine();
1095 m->appendFiles((fastaFileName + toString(processIDS[i]) + ".temp"), fastaFileName);
1096 remove((fastaFileName + toString(processIDS[i]) + ".temp").c_str());
1097 // m->mothurOut("\tDone with flow.fasta file"); m->mothurOutEndLine();
1100 for (int j = 0; j < barcodePrimerComboFileNames.size(); j++) {
1101 for (int k = 0; k < barcodePrimerComboFileNames[0].size(); k++) {
1102 m->appendFiles((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"), barcodePrimerComboFileNames[j][k]);
1103 remove((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp").c_str());
1112 catch(exception& e) {
1113 m->errorOut(e, "TrimFlowsCommand", "createProcessesCreateTrim");
1118 //***************************************************************************************************************