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", "", "", "", "", "",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["flow.files"].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(barcodes.size() != 0){
445 success = trimOligos.stripBarcode(currSeq, barcodeIndex);
446 if(success > bdiffs) { trashCode += 'b'; }
447 else{ currentSeqDiffs += success; }
451 success = trimOligos.stripSpacer(currSeq);
452 if(success > sdiffs) { trashCode += 's'; }
453 else{ currentSeqDiffs += success; }
457 if(numFPrimers != 0){
458 success = trimOligos.stripForward(currSeq, primerIndex);
459 if(success > pdiffs) { trashCode += 'f'; }
460 else{ currentSeqDiffs += success; }
463 if (currentSeqDiffs > tdiffs) { trashCode += 't'; }
465 if(numRPrimers != 0){
466 success = trimOligos.stripReverse(currSeq);
467 if(!success) { trashCode += 'r'; }
470 if(trashCode.length() == 0){
472 flowData.printFlows(trimFlowFile);
474 if(fasta) { currSeq.printSequence(fastaFile); }
478 m->openOutputFileAppend(thisBarcodePrimerComboFileNames[barcodeIndex][primerIndex], output);
479 output.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
481 flowData.printFlows(output);
486 flowData.printFlows(scrapFlowFile, trashCode);
490 //cout << "driver" << '\t' << currSeq.getName() << endl;
492 if((count) % 10000 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
494 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
495 unsigned long long pos = flowFile.tellg();
497 if ((pos == -1) || (pos >= line->end)) { break; }
499 if (flowFile.eof()) { break; }
504 if((count) % 10000 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
506 trimFlowFile.close();
507 scrapFlowFile.close();
509 if(fasta){ fastaFile.close(); }
513 catch(exception& e) {
514 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
519 //***************************************************************************************************************
521 void TrimFlowsCommand::getOligos(vector<vector<string> >& outFlowFileNames){
524 m->openInputFile(oligoFileName, oligosFile);
526 string type, oligo, group;
529 int indexBarcode = 0;
531 while(!oligosFile.eof()){
533 oligosFile >> type; m->gobble(oligosFile); //get the first column value of the row - is it a comment or a feature we are interested in?
535 if(type[0] == '#'){ //igore the line because there's a comment
536 while (!oligosFile.eof()) { char c = oligosFile.get(); if (c == 10 || c == 13){ break; } } // get rest of line if there's any crap there
538 else{ //there's a feature we're interested in
540 for(int i=0;i<type.length();i++){ type[i] = toupper(type[i]); } //make type case insensitive
542 oligosFile >> oligo; //get the DNA sequence for the feature
544 for(int i=0;i<oligo.length();i++){ //make type case insensitive and change any U's to T's
545 oligo[i] = toupper(oligo[i]);
546 if(oligo[i] == 'U') { oligo[i] = 'T'; }
549 if(type == "FORWARD"){ //if the feature is a forward primer...
552 while (!oligosFile.eof()) { // get rest of line in case there is a primer name = will have the name of the primer
553 char c = oligosFile.get();
554 if (c == 10 || c == 13){ break; }
555 else if (c == 32 || c == 9){;} //space or tab
559 //have we seen this primer already?
560 map<string, int>::iterator itPrimer = primers.find(oligo);
561 if (itPrimer != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
563 primers[oligo]=indexPrimer; indexPrimer++;
564 primerNameVector.push_back(group);
567 else if(type == "REVERSE"){
568 string oligoRC = reverseOligo(oligo);
569 revPrimer.push_back(oligoRC);
571 else if(type == "BARCODE"){
574 //check for repeat barcodes
575 map<string, int>::iterator itBar = barcodes.find(oligo);
576 if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine(); }
578 barcodes[oligo]=indexBarcode; indexBarcode++;
579 barcodeNameVector.push_back(group);
580 }else if(type == "LINKER"){
581 linker.push_back(oligo);
582 }else if(type == "SPACER"){
583 spacer.push_back(oligo);
586 m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();
590 m->gobble(oligosFile);
594 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0; }
596 //add in potential combos
597 if(barcodeNameVector.size() == 0){
599 barcodeNameVector.push_back("");
602 if(primerNameVector.size() == 0){
604 primerNameVector.push_back("");
608 outFlowFileNames.resize(barcodeNameVector.size());
609 for(int i=0;i<outFlowFileNames.size();i++){
610 outFlowFileNames[i].assign(primerNameVector.size(), "");
615 for(map<string, int>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
616 for(map<string, int>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
618 string primerName = primerNameVector[itPrimer->second];
619 string barcodeName = barcodeNameVector[itBar->second];
621 string comboGroupName = "";
622 string fileName = "";
624 if(primerName == ""){
625 comboGroupName = barcodeNameVector[itBar->second];
626 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
629 if(barcodeName == ""){
630 comboGroupName = primerNameVector[itPrimer->second];
633 comboGroupName = barcodeNameVector[itBar->second] + "." + primerNameVector[itPrimer->second];
635 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
638 outFlowFileNames[itBar->second][itPrimer->second] = fileName;
641 m->openOutputFile(fileName, temp);
647 numFPrimers = primers.size();
648 numRPrimers = revPrimer.size();
649 numLinkers = linker.size();
650 numSpacers = spacer.size();
653 catch(exception& e) {
654 m->errorOut(e, "TrimSeqsCommand", "getOligos");
658 //********************************************************************/
659 string TrimFlowsCommand::reverseOligo(string oligo){
663 for(int i=oligo.length()-1;i>=0;i--){
665 if(oligo[i] == 'A') { reverse += 'T'; }
666 else if(oligo[i] == 'T'){ reverse += 'A'; }
667 else if(oligo[i] == 'U'){ reverse += 'A'; }
669 else if(oligo[i] == 'G'){ reverse += 'C'; }
670 else if(oligo[i] == 'C'){ reverse += 'G'; }
672 else if(oligo[i] == 'R'){ reverse += 'Y'; }
673 else if(oligo[i] == 'Y'){ reverse += 'R'; }
675 else if(oligo[i] == 'M'){ reverse += 'K'; }
676 else if(oligo[i] == 'K'){ reverse += 'M'; }
678 else if(oligo[i] == 'W'){ reverse += 'W'; }
679 else if(oligo[i] == 'S'){ reverse += 'S'; }
681 else if(oligo[i] == 'B'){ reverse += 'V'; }
682 else if(oligo[i] == 'V'){ reverse += 'B'; }
684 else if(oligo[i] == 'D'){ reverse += 'H'; }
685 else if(oligo[i] == 'H'){ reverse += 'D'; }
687 else { reverse += 'N'; }
693 catch(exception& e) {
694 m->errorOut(e, "TrimFlowsCommand", "reverseOligo");
699 /**************************************************************************************************/
700 vector<unsigned long long> TrimFlowsCommand::getFlowFileBreaks() {
704 vector<unsigned long long> filePos;
705 filePos.push_back(0);
708 unsigned long long size;
710 //get num bytes in file
711 pFile = fopen (flowFileName.c_str(),"rb");
712 if (pFile==NULL) perror ("Error opening file");
714 fseek (pFile, 0, SEEK_END);
719 //estimate file breaks
720 unsigned long long chunkSize = 0;
721 chunkSize = size / processors;
723 //file too small to divide by processors
724 if (chunkSize == 0) { processors = 1; filePos.push_back(size); return filePos; }
726 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
727 for (int i = 0; i < processors; i++) {
728 unsigned long long spot = (i+1) * chunkSize;
731 m->openInputFile(flowFileName, in);
734 string dummy = m->getline(in);
736 //there was not another sequence before the end of the file
737 unsigned long long sanityPos = in.tellg();
739 // if (sanityPos == -1) { break; }
740 // else { filePos.push_back(newSpot); }
741 if (sanityPos == -1) { break; }
742 else { filePos.push_back(sanityPos); }
748 filePos.push_back(size);
750 //sanity check filePos
751 for (int i = 0; i < (filePos.size()-1); i++) {
752 if (filePos[(i+1)] <= filePos[i]) { filePos.erase(filePos.begin()+(i+1)); i--; }
756 m->openInputFile(flowFileName, in);
759 //unsigned long long spot = in.tellg();
763 processors = (filePos.size() - 1);
767 catch(exception& e) {
768 m->errorOut(e, "TrimSeqsCommand", "getFlowFileBreaks");
773 /**************************************************************************************************/
775 int TrimFlowsCommand::createProcessesCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames){
781 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
784 //loop through and create all the processes you want
785 while (process != processors) {
789 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
793 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
795 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
796 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
797 tempBarcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
799 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
805 driverCreateTrim(flowFileName,
806 (trimFlowFileName + toString(getpid()) + ".temp"),
807 (scrapFlowFileName + toString(getpid()) + ".temp"),
808 (fastaFileName + toString(getpid()) + ".temp"),
809 tempBarcodePrimerComboFileNames, lines[process]);
813 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
814 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
821 m->openOutputFile(trimFlowFileName, temp);
824 m->openOutputFile(scrapFlowFileName, temp);
828 m->openOutputFile(fastaFileName, temp);
832 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
834 //force parent to wait until all the processes are done
835 for (int i=0;i<processIDS.size();i++) {
836 int temp = processIDS[i];
840 //////////////////////////////////////////////////////////////////////////////////////////////////////
841 //Windows version shared memory, so be careful when passing variables through the trimFlowData struct.
842 //Above fork() will clone, so memory is separate, but that's not the case with windows,
843 //////////////////////////////////////////////////////////////////////////////////////////////////////
845 vector<trimFlowData*> pDataArray;
846 DWORD dwThreadIdArray[processors-1];
847 HANDLE hThreadArray[processors-1];
849 //Create processor worker threads.
850 for( int i=0; i<processors-1; i++ ){
851 // Allocate memory for thread data.
852 string extension = "";
853 if (i != 0) { extension = toString(i) + ".temp"; processIDS.push_back(i); }
855 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
857 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
858 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
859 tempBarcodePrimerComboFileNames[i][j] += extension;
861 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
868 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);
869 pDataArray.push_back(tempflow);
871 //MyTrimFlowThreadFunction is in header. It must be global or static to work with the threads.
872 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
873 hThreadArray[i] = CreateThread(NULL, 0, MyTrimFlowThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
876 //using the main process as a worker saves time and memory
878 m->openOutputFile(trimFlowFileName, temp);
881 m->openOutputFile(scrapFlowFileName, temp);
885 m->openOutputFile(fastaFileName, temp);
889 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
891 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
892 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
893 tempBarcodePrimerComboFileNames[i][j] += toString(processors-1) + ".temp";
895 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
902 //do my part - do last piece because windows is looking for eof
903 int num = driverCreateTrim(flowFileName, (trimFlowFileName + toString(processors-1) + ".temp"), (scrapFlowFileName + toString(processors-1) + ".temp"), (fastaFileName + toString(processors-1) + ".temp"), tempBarcodePrimerComboFileNames, lines[processors-1]);
904 processIDS.push_back((processors-1));
906 //Wait until all threads have terminated.
907 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
909 //Close all thread handles and free memory allocations.
910 for(int i=0; i < pDataArray.size(); i++){
911 num += pDataArray[i]->count;
912 CloseHandle(hThreadArray[i]);
913 delete pDataArray[i];
919 m->mothurOutEndLine();
920 for(int i=0;i<processIDS.size();i++){
922 m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
924 m->appendFiles((trimFlowFileName + toString(processIDS[i]) + ".temp"), trimFlowFileName);
925 m->mothurRemove((trimFlowFileName + toString(processIDS[i]) + ".temp"));
926 // m->mothurOut("\tDone with trim.flow file"); m->mothurOutEndLine();
928 m->appendFiles((scrapFlowFileName + toString(processIDS[i]) + ".temp"), scrapFlowFileName);
929 m->mothurRemove((scrapFlowFileName + toString(processIDS[i]) + ".temp"));
930 // m->mothurOut("\tDone with scrap.flow file"); m->mothurOutEndLine();
933 m->appendFiles((fastaFileName + toString(processIDS[i]) + ".temp"), fastaFileName);
934 m->mothurRemove((fastaFileName + toString(processIDS[i]) + ".temp"));
935 // m->mothurOut("\tDone with flow.fasta file"); m->mothurOutEndLine();
938 for (int j = 0; j < barcodePrimerComboFileNames.size(); j++) {
939 for (int k = 0; k < barcodePrimerComboFileNames[0].size(); k++) {
940 m->appendFiles((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"), barcodePrimerComboFileNames[j][k]);
941 m->mothurRemove((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"));
950 catch(exception& e) {
951 m->errorOut(e, "TrimFlowsCommand", "createProcessesCreateTrim");
956 //***************************************************************************************************************