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"
14 //**********************************************************************************************************************
15 vector<string> TrimFlowsCommand::setParameters(){
17 CommandParameter pflow("flow", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pflow);
18 CommandParameter poligos("oligos", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(poligos);
19 CommandParameter pmaxhomop("maxhomop", "Number", "", "9", "", "", "",false,false); parameters.push_back(pmaxhomop);
20 CommandParameter pmaxflows("maxflows", "Number", "", "450", "", "", "",false,false); parameters.push_back(pmaxflows);
21 CommandParameter pminflows("minflows", "Number", "", "450", "", "", "",false,false); parameters.push_back(pminflows);
22 CommandParameter ppdiffs("pdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(ppdiffs);
23 CommandParameter pbdiffs("bdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pbdiffs);
24 CommandParameter pldiffs("ldiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pldiffs);
25 CommandParameter psdiffs("sdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(psdiffs);
26 CommandParameter ptdiffs("tdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(ptdiffs);
27 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
28 CommandParameter psignal("signal", "Number", "", "0.50", "", "", "",false,false); parameters.push_back(psignal);
29 CommandParameter pnoise("noise", "Number", "", "0.70", "", "", "",false,false); parameters.push_back(pnoise);
30 CommandParameter pallfiles("allfiles", "Boolean", "", "t", "", "", "",false,false); parameters.push_back(pallfiles);
31 CommandParameter porder("order", "String", "", "TACG", "", "", "",false,false); parameters.push_back(porder);
32 CommandParameter pfasta("fasta", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pfasta);
33 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
34 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
36 vector<string> myArray;
37 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
41 m->errorOut(e, "TrimFlowsCommand", "setParameters");
45 //**********************************************************************************************************************
46 string TrimFlowsCommand::getHelpString(){
48 string helpString = "";
49 helpString += "The trim.flows command reads a flowgram file and creates .....\n";
50 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
51 helpString += "For more details please check out the wiki http://www.mothur.org/wiki/Trim.flows.\n";
55 m->errorOut(e, "TrimFlowsCommand", "getHelpString");
59 //**********************************************************************************************************************
60 string TrimFlowsCommand::getOutputFileNameTag(string type, string inputName=""){
62 string outputFileName = "";
63 map<string, vector<string> >::iterator it;
65 //is this a type this command creates
66 it = outputTypes.find(type);
67 if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
69 if (type == "flow") { outputFileName = "flow"; }
70 else if (type == "fasta") { outputFileName = "flow.fasta"; }
71 else if (type == "file") { outputFileName = "flow.files"; }
72 else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; }
74 return outputFileName;
77 m->errorOut(e, "TrimFlowsCommand", "getOutputFileNameTag");
81 //**********************************************************************************************************************
83 TrimFlowsCommand::TrimFlowsCommand(){
85 abort = true; calledHelp = true;
87 vector<string> tempOutNames;
88 outputTypes["flow"] = tempOutNames;
89 outputTypes["fasta"] = tempOutNames;
90 outputTypes["file"] = tempOutNames;
93 m->errorOut(e, "TrimFlowsCommand", "TrimFlowsCommand");
97 //**********************************************************************************************************************
99 TrimFlowsCommand::TrimFlowsCommand(string option) {
102 abort = false; calledHelp = false;
105 //allow user to run help
106 if(option == "help") { help(); abort = true; calledHelp = true; }
107 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
111 vector<string> myArray = setParameters();
113 OptionParser parser(option);
114 map<string,string> parameters = parser.getParameters();
116 ValidParameters validParameter;
117 map<string,string>::iterator it;
119 //check to make sure all parameters are valid for command
120 for (it = parameters.begin(); it != parameters.end(); it++) {
121 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
124 //initialize outputTypes
125 vector<string> tempOutNames;
126 outputTypes["flow"] = tempOutNames;
127 outputTypes["fasta"] = tempOutNames;
128 outputTypes["file"] = tempOutNames;
130 //if the user changes the input directory command factory will send this info to us in the output parameter
131 string inputDir = validParameter.validFile(parameters, "inputdir", false);
132 if (inputDir == "not found"){ inputDir = ""; }
135 it = parameters.find("flow");
136 //user has given a template file
137 if(it != parameters.end()){
138 path = m->hasPath(it->second);
139 //if the user has not given a path then, add inputdir. else leave path alone.
140 if (path == "") { parameters["flow"] = inputDir + it->second; }
143 it = parameters.find("oligos");
144 //user has given a template file
145 if(it != parameters.end()){
146 path = m->hasPath(it->second);
147 //if the user has not given a path then, add inputdir. else leave path alone.
148 if (path == "") { parameters["oligos"] = inputDir + it->second; }
154 //check for required parameters
155 flowFileName = validParameter.validFile(parameters, "flow", true);
156 if (flowFileName == "not found") {
157 flowFileName = m->getFlowFile();
158 if (flowFileName != "") { m->mothurOut("Using " + flowFileName + " as input file for the flow parameter."); m->mothurOutEndLine(); }
160 m->mothurOut("No valid current flow file. You must provide a flow file."); m->mothurOutEndLine();
163 }else if (flowFileName == "not open") { flowFileName = ""; abort = true; }
165 //if the user changes the output directory command factory will send this info to us in the output parameter
166 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
168 outputDir += m->hasPath(flowFileName); //if user entered a file with a path then preserve it
172 //check for optional parameter and set defaults
173 // ...at some point should added some additional type checking...
176 temp = validParameter.validFile(parameters, "minflows", false); if (temp == "not found") { temp = "450"; }
177 m->mothurConvert(temp, minFlows);
179 temp = validParameter.validFile(parameters, "maxflows", false); if (temp == "not found") { temp = "450"; }
180 m->mothurConvert(temp, maxFlows);
183 temp = validParameter.validFile(parameters, "oligos", true);
184 if (temp == "not found") { oligoFileName = ""; }
185 else if(temp == "not open") { abort = true; }
186 else { oligoFileName = temp; m->setOligosFile(oligoFileName); }
188 temp = validParameter.validFile(parameters, "fasta", false); if (temp == "not found"){ fasta = 0; }
189 else if(m->isTrue(temp)) { fasta = 1; }
191 temp = validParameter.validFile(parameters, "maxhomop", false); if (temp == "not found"){ temp = "9"; }
192 m->mothurConvert(temp, maxHomoP);
194 temp = validParameter.validFile(parameters, "signal", false); if (temp == "not found"){ temp = "0.50"; }
195 m->mothurConvert(temp, signal);
197 temp = validParameter.validFile(parameters, "noise", false); if (temp == "not found"){ temp = "0.70"; }
198 m->mothurConvert(temp, noise);
200 temp = validParameter.validFile(parameters, "bdiffs", false); if (temp == "not found"){ temp = "0"; }
201 m->mothurConvert(temp, bdiffs);
203 temp = validParameter.validFile(parameters, "pdiffs", false); if (temp == "not found"){ temp = "0"; }
204 m->mothurConvert(temp, pdiffs);
206 temp = validParameter.validFile(parameters, "ldiffs", false); if (temp == "not found") { temp = "0"; }
207 m->mothurConvert(temp, ldiffs);
209 temp = validParameter.validFile(parameters, "sdiffs", false); if (temp == "not found") { temp = "0"; }
210 m->mothurConvert(temp, sdiffs);
212 temp = validParameter.validFile(parameters, "tdiffs", false); if (temp == "not found") { int tempTotal = pdiffs + bdiffs + ldiffs + sdiffs; temp = toString(tempTotal); }
213 m->mothurConvert(temp, tdiffs);
215 if(tdiffs == 0){ tdiffs = bdiffs + pdiffs + ldiffs + sdiffs; }
218 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
219 m->setProcessors(temp);
220 m->mothurConvert(temp, processors);
222 flowOrder = validParameter.validFile(parameters, "order", false);
223 if (flowOrder == "not found"){ flowOrder = "TACG"; }
224 else if(flowOrder.length() != 4){
225 m->mothurOut("The value of the order option must be four bases long\n");
228 if(oligoFileName == "") { allFiles = 0; }
229 else { allFiles = 1; }
238 catch(exception& e) {
239 m->errorOut(e, "TrimFlowsCommand", "TrimFlowsCommand");
244 //***************************************************************************************************************
246 int TrimFlowsCommand::execute(){
249 if (abort == true) { if (calledHelp) { return 0; } return 2; }
251 string trimFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "trim." + getOutputFileNameTag("flow");
252 outputNames.push_back(trimFlowFileName); outputTypes["flow"].push_back(trimFlowFileName);
254 string scrapFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "scrap." + getOutputFileNameTag("flow");;
255 outputNames.push_back(scrapFlowFileName); outputTypes["flow"].push_back(scrapFlowFileName);
257 string fastaFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + getOutputFileNameTag("fasta");
259 outputNames.push_back(fastaFileName); outputTypes["fasta"].push_back(fastaFileName);
262 vector<unsigned long long> flowFilePos;
263 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
264 flowFilePos = getFlowFileBreaks();
265 for (int i = 0; i < (flowFilePos.size()-1); i++) {
266 lines.push_back(new linePair(flowFilePos[i], flowFilePos[(i+1)]));
269 ifstream in; m->openInputFile(flowFileName, in); in >> numFlows; in.close();
270 ///////////////////////////////////////// until I fix multiple processors for windows //////////////////
272 ///////////////////////////////////////// until I fix multiple processors for windows //////////////////
273 if (processors == 1) {
274 lines.push_back(new linePair(0, 1000));
277 flowFilePos = m->setFilePosEachLine(flowFileName, numFlowLines);
278 flowFilePos.erase(flowFilePos.begin() + 1); numFlowLines--;
280 //figure out how many sequences you have to process
281 int numSeqsPerProcessor = numFlowLines / processors;
282 cout << numSeqsPerProcessor << '\t' << numFlowLines << endl;
283 for (int i = 0; i < processors; i++) {
284 int startIndex = i * numSeqsPerProcessor;
285 if(i == (processors - 1)){ numSeqsPerProcessor = numFlowLines - i * numSeqsPerProcessor; }
286 lines.push_back(new linePair(flowFilePos[startIndex], numSeqsPerProcessor));
287 cout << flowFilePos[startIndex] << '\t' << numSeqsPerProcessor << endl;
292 vector<vector<string> > barcodePrimerComboFileNames;
293 if(oligoFileName != ""){
294 getOligos(barcodePrimerComboFileNames);
298 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
300 createProcessesCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames);
303 if (m->control_pressed) { return 0; }
305 string flowFilesFileName;
309 set<string> namesAlreadyProcessed;
310 flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + getOutputFileNameTag("file");
311 m->openOutputFile(flowFilesFileName, output);
313 for(int i=0;i<barcodePrimerComboFileNames.size();i++){
314 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
315 if (namesAlreadyProcessed.count(barcodePrimerComboFileNames[i][j]) == 0) {
317 unsigned long long size;
319 //get num bytes in file
320 pFile = fopen (barcodePrimerComboFileNames[i][j].c_str(),"rb");
321 if (pFile==NULL) perror ("Error opening file");
323 fseek (pFile, 0, SEEK_END);
329 m->mothurRemove(barcodePrimerComboFileNames[i][j]);
332 output << m->getFullPathName(barcodePrimerComboFileNames[i][j]) << endl;
333 outputNames.push_back(barcodePrimerComboFileNames[i][j]);
334 outputTypes["flow"].push_back(barcodePrimerComboFileNames[i][j]);
336 namesAlreadyProcessed.insert(barcodePrimerComboFileNames[i][j]);
343 flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + getOutputFileNameTag("file");
344 m->openOutputFile(flowFilesFileName, output);
346 output << m->getFullPathName(trimFlowFileName) << endl;
350 outputTypes["file"].push_back(flowFilesFileName);
351 outputNames.push_back(flowFilesFileName);
353 // set fasta file as new current fastafile
354 // string current = "";
355 // itTypes = outputTypes.find("fasta");
356 // if (itTypes != outputTypes.end()) {
357 // if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
360 m->mothurOutEndLine();
361 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
362 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
363 m->mothurOutEndLine();
367 catch(exception& e) {
368 m->errorOut(e, "TrimSeqsCommand", "execute");
373 //***************************************************************************************************************
375 int TrimFlowsCommand::driverCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > thisBarcodePrimerComboFileNames, linePair* line){
378 ofstream trimFlowFile;
379 m->openOutputFile(trimFlowFileName, trimFlowFile);
380 trimFlowFile.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
382 ofstream scrapFlowFile;
383 m->openOutputFile(scrapFlowFileName, scrapFlowFile);
384 scrapFlowFile.setf(ios::fixed, ios::floatfield); scrapFlowFile.setf(ios::showpoint);
387 if(fasta){ m->openOutputFile(fastaFileName, fastaFile); }
390 m->openInputFile(flowFileName, flowFile);
392 flowFile.seekg(line->start);
394 if(line->start == 0){
395 flowFile >> numFlows; m->gobble(flowFile);
396 scrapFlowFile << maxFlows << endl;
397 trimFlowFile << maxFlows << endl;
399 for(int i=0;i<thisBarcodePrimerComboFileNames.size();i++){
400 for(int j=0;j<thisBarcodePrimerComboFileNames[0].size();j++){
402 m->openOutputFile(thisBarcodePrimerComboFileNames[i][j], temp);
403 temp << maxFlows << endl;
410 FlowData flowData(numFlows, signal, noise, maxHomoP, flowOrder);
411 //cout << " driver flowdata address " << &flowData << &flowFile << endl;
415 TrimOligos trimOligos(pdiffs, bdiffs, ldiffs, sdiffs, primers, barcodes, revPrimer, linker, spacer);
419 if (m->control_pressed) { break; }
422 int currentSeqDiffs = 0;
423 string trashCode = "";
425 flowData.getNext(flowFile);
426 flowData.capFlows(maxFlows);
428 Sequence currSeq = flowData.getSequence();
429 if(!flowData.hasMinFlows(minFlows)){ //screen to see if sequence is of a minimum number of flows
435 int barcodeIndex = 0;
438 success = trimOligos.stripLinker(currSeq);
439 if(success > ldiffs) { trashCode += 'k'; }
440 else{ currentSeqDiffs += success; }
444 if (m->debug) { m->mothurOut("[DEBUG]: " + currSeq.getName() + " " + currSeq.getUnaligned() + "\n"); }
446 if(barcodes.size() != 0){
447 success = trimOligos.stripBarcode(currSeq, barcodeIndex);
448 if(success > bdiffs) { trashCode += 'b'; }
449 else{ currentSeqDiffs += success; }
453 success = trimOligos.stripSpacer(currSeq);
454 if(success > sdiffs) { trashCode += 's'; }
455 else{ currentSeqDiffs += success; }
459 if(numFPrimers != 0){
460 success = trimOligos.stripForward(currSeq, primerIndex);
461 if(success > pdiffs) { trashCode += 'f'; }
462 else{ currentSeqDiffs += success; }
465 if (currentSeqDiffs > tdiffs) { trashCode += 't'; }
467 if(numRPrimers != 0){
468 success = trimOligos.stripReverse(currSeq);
469 if(!success) { trashCode += 'r'; }
472 if(trashCode.length() == 0){
474 flowData.printFlows(trimFlowFile);
476 if(fasta) { currSeq.printSequence(fastaFile); }
480 m->openOutputFileAppend(thisBarcodePrimerComboFileNames[barcodeIndex][primerIndex], output);
481 output.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
483 flowData.printFlows(output);
488 flowData.printFlows(scrapFlowFile, trashCode);
492 //cout << "driver" << '\t' << currSeq.getName() << endl;
494 if((count) % 10000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
496 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
497 unsigned long long pos = flowFile.tellg();
499 if ((pos == -1) || (pos >= line->end)) { break; }
501 if (flowFile.eof()) { break; }
506 if((count) % 10000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
508 trimFlowFile.close();
509 scrapFlowFile.close();
511 if(fasta){ fastaFile.close(); }
515 catch(exception& e) {
516 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
521 //***************************************************************************************************************
523 void TrimFlowsCommand::getOligos(vector<vector<string> >& outFlowFileNames){
526 m->openInputFile(oligoFileName, oligosFile);
528 string type, oligo, group;
531 int indexBarcode = 0;
533 while(!oligosFile.eof()){
535 oligosFile >> type; m->gobble(oligosFile); //get the first column value of the row - is it a comment or a feature we are interested in?
537 if(type[0] == '#'){ //igore the line because there's a comment
538 while (!oligosFile.eof()) { char c = oligosFile.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
540 else{ //there's a feature we're interested in
542 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); } //make type case insensitive
544 oligosFile >> oligo; //get the DNA sequence for the feature
546 for(int i=0;i<oligo.length();i++){ //make type case insensitive and change any U's to T's
547 oligo[i] = toupper(oligo[i]);
548 if(oligo[i] == 'U') { oligo[i] = 'T'; }
551 if(type == "FORWARD"){ //if the feature is a forward primer...
554 while (!oligosFile.eof()) { // get rest of line in case there is a primer name = will have the name of the primer
555 char c = oligosFile.get();
556 if (c == 10 || c == 13){ break; }
557 else if (c == 32 || c == 9){;} //space or tab
561 //have we seen this primer already?
562 map<string, int>::iterator itPrimer = primers.find(oligo);
563 if (itPrimer != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
565 primers[oligo]=indexPrimer; indexPrimer++;
566 primerNameVector.push_back(group);
569 else if(type == "REVERSE"){
570 string oligoRC = reverseOligo(oligo);
571 revPrimer.push_back(oligoRC);
573 else if(type == "BARCODE"){
576 //check for repeat barcodes
577 map<string, int>::iterator itBar = barcodes.find(oligo);
578 if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
580 barcodes[oligo]=indexBarcode; indexBarcode++;
581 barcodeNameVector.push_back(group);
582 }else if(type == "LINKER"){
583 linker.push_back(oligo);
584 }else if(type == "SPACER"){
585 spacer.push_back(oligo);
588 m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();
592 m->gobble(oligosFile);
596 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0; }
598 //add in potential combos
599 if(barcodeNameVector.size() == 0){
601 barcodeNameVector.push_back("");
604 if(primerNameVector.size() == 0){
606 primerNameVector.push_back("");
610 outFlowFileNames.resize(barcodeNameVector.size());
611 for(int i=0;i<outFlowFileNames.size();i++){
612 outFlowFileNames[i].assign(primerNameVector.size(), "");
617 for(map<string, int>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
618 for(map<string, int>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
620 string primerName = primerNameVector[itPrimer->second];
621 string barcodeName = barcodeNameVector[itBar->second];
623 string comboGroupName = "";
624 string fileName = "";
626 if(primerName == ""){
627 comboGroupName = barcodeNameVector[itBar->second];
628 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
631 if(barcodeName == ""){
632 comboGroupName = primerNameVector[itPrimer->second];
635 comboGroupName = barcodeNameVector[itBar->second] + "." + primerNameVector[itPrimer->second];
637 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
640 outFlowFileNames[itBar->second][itPrimer->second] = fileName;
643 m->openOutputFile(fileName, temp);
649 numFPrimers = primers.size();
650 numRPrimers = revPrimer.size();
651 numLinkers = linker.size();
652 numSpacers = spacer.size();
655 catch(exception& e) {
656 m->errorOut(e, "TrimSeqsCommand", "getOligos");
660 //********************************************************************/
661 string TrimFlowsCommand::reverseOligo(string oligo){
665 for(int i=oligo.length()-1;i>=0;i--){
667 if(oligo[i] == 'A') { reverse += 'T'; }
668 else if(oligo[i] == 'T'){ reverse += 'A'; }
669 else if(oligo[i] == 'U'){ reverse += 'A'; }
671 else if(oligo[i] == 'G'){ reverse += 'C'; }
672 else if(oligo[i] == 'C'){ reverse += 'G'; }
674 else if(oligo[i] == 'R'){ reverse += 'Y'; }
675 else if(oligo[i] == 'Y'){ reverse += 'R'; }
677 else if(oligo[i] == 'M'){ reverse += 'K'; }
678 else if(oligo[i] == 'K'){ reverse += 'M'; }
680 else if(oligo[i] == 'W'){ reverse += 'W'; }
681 else if(oligo[i] == 'S'){ reverse += 'S'; }
683 else if(oligo[i] == 'B'){ reverse += 'V'; }
684 else if(oligo[i] == 'V'){ reverse += 'B'; }
686 else if(oligo[i] == 'D'){ reverse += 'H'; }
687 else if(oligo[i] == 'H'){ reverse += 'D'; }
689 else { reverse += 'N'; }
695 catch(exception& e) {
696 m->errorOut(e, "TrimFlowsCommand", "reverseOligo");
701 /**************************************************************************************************/
702 vector<unsigned long long> TrimFlowsCommand::getFlowFileBreaks() {
706 vector<unsigned long long> filePos;
707 filePos.push_back(0);
710 unsigned long long size;
712 //get num bytes in file
713 pFile = fopen (flowFileName.c_str(),"rb");
714 if (pFile==NULL) perror ("Error opening file");
716 fseek (pFile, 0, SEEK_END);
721 //estimate file breaks
722 unsigned long long chunkSize = 0;
723 chunkSize = size / processors;
725 //file too small to divide by processors
726 if (chunkSize == 0) { processors = 1; filePos.push_back(size); return filePos; }
728 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
729 for (int i = 0; i < processors; i++) {
730 unsigned long long spot = (i+1) * chunkSize;
733 m->openInputFile(flowFileName, in);
736 string dummy = m->getline(in);
738 //there was not another sequence before the end of the file
739 unsigned long long sanityPos = in.tellg();
741 // if (sanityPos == -1) { break; }
742 // else { filePos.push_back(newSpot); }
743 if (sanityPos == -1) { break; }
744 else { filePos.push_back(sanityPos); }
750 filePos.push_back(size);
752 //sanity check filePos
753 for (int i = 0; i < (filePos.size()-1); i++) {
754 if (filePos[(i+1)] <= filePos[i]) { filePos.erase(filePos.begin()+(i+1)); i--; }
758 m->openInputFile(flowFileName, in);
761 //unsigned long long spot = in.tellg();
765 processors = (filePos.size() - 1);
769 catch(exception& e) {
770 m->errorOut(e, "TrimSeqsCommand", "getFlowFileBreaks");
775 /**************************************************************************************************/
777 int TrimFlowsCommand::createProcessesCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames){
783 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
786 //loop through and create all the processes you want
787 while (process != processors) {
791 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
795 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
797 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
798 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
799 tempBarcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
801 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
807 driverCreateTrim(flowFileName,
808 (trimFlowFileName + toString(getpid()) + ".temp"),
809 (scrapFlowFileName + toString(getpid()) + ".temp"),
810 (fastaFileName + toString(getpid()) + ".temp"),
811 tempBarcodePrimerComboFileNames, lines[process]);
815 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
816 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
823 m->openOutputFile(trimFlowFileName, temp);
826 m->openOutputFile(scrapFlowFileName, temp);
830 m->openOutputFile(fastaFileName, temp);
834 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
836 //force parent to wait until all the processes are done
837 for (int i=0;i<processIDS.size();i++) {
838 int temp = processIDS[i];
842 //////////////////////////////////////////////////////////////////////////////////////////////////////
843 //Windows version shared memory, so be careful when passing variables through the trimFlowData struct.
844 //Above fork() will clone, so memory is separate, but that's not the case with windows,
845 //////////////////////////////////////////////////////////////////////////////////////////////////////
847 vector<trimFlowData*> pDataArray;
848 DWORD dwThreadIdArray[processors-1];
849 HANDLE hThreadArray[processors-1];
851 //Create processor worker threads.
852 for( int i=0; i<processors-1; i++ ){
853 // Allocate memory for thread data.
854 string extension = "";
855 if (i != 0) { extension = toString(i) + ".temp"; processIDS.push_back(i); }
857 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
859 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
860 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
861 tempBarcodePrimerComboFileNames[i][j] += extension;
863 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
870 trimFlowData* tempflow = new trimFlowData(flowFileName, (trimFlowFileName + extension), (scrapFlowFileName + extension), fastaFileName, flowOrder, tempBarcodePrimerComboFileNames, barcodes, primers, revPrimer, fasta, allFiles, lines[i]->start, lines[i]->end, m, signal, noise, numFlows, maxFlows, minFlows, maxHomoP, tdiffs, bdiffs, pdiffs, i);
871 pDataArray.push_back(tempflow);
873 //MyTrimFlowThreadFunction is in header. It must be global or static to work with the threads.
874 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
875 hThreadArray[i] = CreateThread(NULL, 0, MyTrimFlowThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
878 //using the main process as a worker saves time and memory
880 m->openOutputFile(trimFlowFileName, temp);
883 m->openOutputFile(scrapFlowFileName, temp);
887 m->openOutputFile(fastaFileName, temp);
891 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
893 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
894 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
895 tempBarcodePrimerComboFileNames[i][j] += toString(processors-1) + ".temp";
897 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
904 //do my part - do last piece because windows is looking for eof
905 int num = driverCreateTrim(flowFileName, (trimFlowFileName + toString(processors-1) + ".temp"), (scrapFlowFileName + toString(processors-1) + ".temp"), (fastaFileName + toString(processors-1) + ".temp"), tempBarcodePrimerComboFileNames, lines[processors-1]);
906 processIDS.push_back((processors-1));
908 //Wait until all threads have terminated.
909 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
911 //Close all thread handles and free memory allocations.
912 for(int i=0; i < pDataArray.size(); i++){
913 num += pDataArray[i]->count;
914 CloseHandle(hThreadArray[i]);
915 delete pDataArray[i];
921 m->mothurOutEndLine();
922 for(int i=0;i<processIDS.size();i++){
924 m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
926 m->appendFiles((trimFlowFileName + toString(processIDS[i]) + ".temp"), trimFlowFileName);
927 m->mothurRemove((trimFlowFileName + toString(processIDS[i]) + ".temp"));
928 // m->mothurOut("\tDone with trim.flow file"); m->mothurOutEndLine();
930 m->appendFiles((scrapFlowFileName + toString(processIDS[i]) + ".temp"), scrapFlowFileName);
931 m->mothurRemove((scrapFlowFileName + toString(processIDS[i]) + ".temp"));
932 // m->mothurOut("\tDone with scrap.flow file"); m->mothurOutEndLine();
935 m->appendFiles((fastaFileName + toString(processIDS[i]) + ".temp"), fastaFileName);
936 m->mothurRemove((fastaFileName + toString(processIDS[i]) + ".temp"));
937 // m->mothurOut("\tDone with flow.fasta file"); m->mothurOutEndLine();
940 for (int j = 0; j < barcodePrimerComboFileNames.size(); j++) {
941 for (int k = 0; k < barcodePrimerComboFileNames[0].size(); k++) {
942 m->appendFiles((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"), barcodePrimerComboFileNames[j][k]);
943 m->mothurRemove((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"));
952 catch(exception& e) {
953 m->errorOut(e, "TrimFlowsCommand", "createProcessesCreateTrim");
958 //***************************************************************************************************************