5 * Created by Pat Schloss on 7/15/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "seqerrorcommand.h"
11 #include "reportfile.h"
12 #include "qualityscores.h"
13 #include "refchimeratest.h"
14 #include "filterseqscommand.h"
16 //**********************************************************************************************************************
17 vector<string> SeqErrorCommand::setParameters(){
19 CommandParameter pquery("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pquery);
20 CommandParameter preference("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(preference);
21 CommandParameter pqfile("qfile", "InputTypes", "", "", "none", "none", "QualReport",false,false); parameters.push_back(pqfile);
22 CommandParameter preport("report", "InputTypes", "", "", "none", "none", "QualReport",false,false); parameters.push_back(preport);
23 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
24 CommandParameter pignorechimeras("ignorechimeras", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(pignorechimeras);
25 CommandParameter pthreshold("threshold", "Number", "", "1.0", "", "", "",false,false); parameters.push_back(pthreshold);
26 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
27 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
28 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
30 vector<string> myArray;
31 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
35 m->errorOut(e, "SeqErrorCommand", "setParameters");
39 //**********************************************************************************************************************
40 string SeqErrorCommand::getHelpString(){
42 string helpString = "";
43 helpString += "The seq.error command reads a query alignment file and a reference alignment file and creates .....\n";
44 helpString += "Example seq.error(...).\n";
45 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
46 helpString += "For more details please check out the wiki http://www.mothur.org/wiki/seq.error .\n";
50 m->errorOut(e, "SeqErrorCommand", "getHelpString");
54 //**********************************************************************************************************************
55 SeqErrorCommand::SeqErrorCommand(){
57 abort = true; calledHelp = true;
58 vector<string> tempOutNames;
59 outputTypes["error.summary"] = tempOutNames;
60 outputTypes["error.seq"] = tempOutNames;
61 outputTypes["error.quality"] = tempOutNames;
62 outputTypes["error.qual.forward"] = tempOutNames;
63 outputTypes["error.qual.reverse"] = tempOutNames;
64 outputTypes["error.forward"] = tempOutNames;
65 outputTypes["error.reverse"] = tempOutNames;
66 outputTypes["error.count"] = tempOutNames;
67 outputTypes["error.matrix"] = tempOutNames;
70 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
74 //***************************************************************************************************************
76 SeqErrorCommand::SeqErrorCommand(string option) {
79 abort = false; calledHelp = false;
81 //allow user to run help
82 if(option == "help") { help(); abort = true; calledHelp = true; }
83 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
87 vector<string> myArray = setParameters();
89 OptionParser parser(option);
90 map<string,string> parameters = parser.getParameters();
92 ValidParameters validParameter;
93 map<string,string>::iterator it;
95 //check to make sure all parameters are valid for command
96 for (it = parameters.begin(); it != parameters.end(); it++) {
97 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
100 //initialize outputTypes
101 vector<string> tempOutNames;
102 outputTypes["error.summary"] = tempOutNames;
103 outputTypes["error.seq"] = tempOutNames;
104 outputTypes["error.quality"] = tempOutNames;
105 outputTypes["error.qual.forward"] = tempOutNames;
106 outputTypes["error.qual.reverse"] = tempOutNames;
107 outputTypes["error.forward"] = tempOutNames;
108 outputTypes["error.reverse"] = tempOutNames;
109 outputTypes["error.count"] = tempOutNames;
110 outputTypes["error.matrix"] = tempOutNames;
113 //if the user changes the input directory command factory will send this info to us in the output parameter
114 string inputDir = validParameter.validFile(parameters, "inputdir", false);
115 if (inputDir == "not found"){ inputDir = ""; }
118 it = parameters.find("fasta");
119 //user has given a template file
120 if(it != parameters.end()){
121 path = m->hasPath(it->second);
122 //if the user has not given a path then, add inputdir. else leave path alone.
123 if (path == "") { parameters["fasta"] = inputDir + it->second; }
126 it = parameters.find("reference");
127 //user has given a template file
128 if(it != parameters.end()){
129 path = m->hasPath(it->second);
130 //if the user has not given a path then, add inputdir. else leave path alone.
131 if (path == "") { parameters["reference"] = inputDir + it->second; }
134 it = parameters.find("name");
135 //user has given a names file
136 if(it != parameters.end()){
137 path = m->hasPath(it->second);
138 //if the user has not given a path then, add inputdir. else leave path alone.
139 if (path == "") { parameters["name"] = inputDir + it->second; }
142 it = parameters.find("qfile");
143 //user has given a quality score file
144 if(it != parameters.end()){
145 path = m->hasPath(it->second);
146 //if the user has not given a path then, add inputdir. else leave path alone.
147 if (path == "") { parameters["qfile"] = inputDir + it->second; }
150 it = parameters.find("report");
151 //user has given a alignment report file
152 if(it != parameters.end()){
153 path = m->hasPath(it->second);
154 //if the user has not given a path then, add inputdir. else leave path alone.
155 if (path == "") { parameters["report"] = inputDir + it->second; }
159 //check for required parameters
160 queryFileName = validParameter.validFile(parameters, "fasta", true);
161 if (queryFileName == "not found") {
162 queryFileName = m->getFastaFile();
163 if (queryFileName != "") { m->mothurOut("Using " + queryFileName + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
164 else { m->mothurOut("You have no current fasta file and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
166 else if (queryFileName == "not open") { abort = true; }
167 else { m->setFastaFile(queryFileName); }
169 referenceFileName = validParameter.validFile(parameters, "reference", true);
170 if (referenceFileName == "not found") { m->mothurOut("reference is a required parameter for the seq.error command."); m->mothurOutEndLine(); abort = true; }
171 else if (referenceFileName == "not open") { abort = true; }
174 //check for optional parameters
175 namesFileName = validParameter.validFile(parameters, "name", true);
176 if(namesFileName == "not found"){ namesFileName = ""; }
177 else if (namesFileName == "not open") { namesFileName = ""; abort = true; }
178 else { m->setNameFile(namesFileName); }
180 qualFileName = validParameter.validFile(parameters, "qfile", true);
181 if(qualFileName == "not found"){ qualFileName = ""; }
182 else if (qualFileName == "not open") { qualFileName = ""; abort = true; }
183 else { m->setQualFile(qualFileName); }
185 reportFileName = validParameter.validFile(parameters, "report", true);
186 if(reportFileName == "not found"){ reportFileName = ""; }
187 else if (reportFileName == "not open") { reportFileName = ""; abort = true; }
189 if((reportFileName != "" && qualFileName == "") || (reportFileName == "" && qualFileName != "")){
190 m->mothurOut("if you use either a qual file or a report file, you have to have both.");
191 m->mothurOutEndLine();
195 outputDir = validParameter.validFile(parameters, "outputdir", false);
196 if (outputDir == "not found"){
198 outputDir += m->hasPath(queryFileName); //if user entered a file with a path then preserve it
201 //check for optional parameter and set defaults
202 // ...at some point should added some additional type checking...
203 temp = validParameter.validFile(parameters, "threshold", false); if (temp == "not found") { temp = "1.00"; }
204 convert(temp, threshold);
206 temp = validParameter.validFile(parameters, "ignorechimeras", false); if (temp == "not found") { temp = "T"; }
207 ignoreChimeras = m->isTrue(temp);
209 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
210 m->setProcessors(temp);
211 convert(temp, processors);
213 substitutionMatrix.resize(6);
214 for(int i=0;i<6;i++){ substitutionMatrix[i].resize(6,0); }
217 catch(exception& e) {
218 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
222 //***************************************************************************************************************
224 int SeqErrorCommand::execute(){
226 if (abort == true) { if (calledHelp) { return 0; } return 2; }
228 int start = time(NULL);
233 string errorSummaryFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.summary";
234 outputNames.push_back(errorSummaryFileName); outputTypes["error.summary"].push_back(errorSummaryFileName);
236 string errorSeqFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq";
237 outputNames.push_back(errorSeqFileName); outputTypes["error.seq"].push_back(errorSeqFileName);
239 string errorChimeraFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.chimera";
240 outputNames.push_back(errorChimeraFileName); outputTypes["error.chimera"].push_back(errorChimeraFileName);
242 getReferences(); //read in reference sequences - make sure there's no ambiguous bases
244 if(namesFileName != ""){ weights = getWeights(); }
246 vector<unsigned long int> fastaFilePos;
247 vector<unsigned long int> qFilePos;
248 vector<unsigned long int> reportFilePos;
250 setLines(queryFileName, qualFileName, reportFileName, fastaFilePos, qFilePos, reportFilePos);
252 if (m->control_pressed) { return 0; }
254 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
255 lines.push_back(linePair(fastaFilePos[i], fastaFilePos[(i+1)]));
256 if (qualFileName != "") { qLines.push_back(linePair(qFilePos[i], qFilePos[(i+1)])); }
257 if (reportFileName != "") { rLines.push_back(linePair(reportFilePos[i], reportFilePos[(i+1)])); }
259 if(qualFileName == "") { qLines = lines; rLines = lines; } //fills with duds
262 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
264 numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
266 numSeqs = createProcesses(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName);
269 numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
272 if(qualFileName != "" && reportFileName != ""){
273 printErrorQuality(qScoreErrorMap);
274 printQualityFR(qualForwardMap, qualReverseMap);
277 printErrorFRFile(errorForward, errorReverse);
279 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
281 string errorCountFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.count";
282 ofstream errorCountFile;
283 m->openOutputFile(errorCountFileName, errorCountFile);
284 outputNames.push_back(errorCountFileName); outputTypes["error.count"].push_back(errorCountFileName);
285 m->mothurOut("Overall error rate:\t" + toString((double)(totalBases - totalMatches) / (double)totalBases) + "\n");
286 m->mothurOut("Errors\tSequences\n");
287 errorCountFile << "Errors\tSequences\n";
288 for(int i=0;i<misMatchCounts.size();i++){
289 m->mothurOut(toString(i) + '\t' + toString(misMatchCounts[i]) + '\n');
290 errorCountFile << i << '\t' << misMatchCounts[i] << endl;
292 errorCountFile.close();
294 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
298 string megAlignmentFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.ref-query";
299 ofstream megAlignmentFile;
300 m->openOutputFile(megAlignmentFileName, megAlignmentFile);
301 outputNames.push_back(megAlignmentFileName); outputTypes["error.ref-query"].push_back(megAlignmentFileName);
303 for(int i=0;i<numRefs;i++){
304 megAlignmentFile << referenceSeqs[i].getInlineSeq() << endl;
305 megAlignmentFile << megaAlignVector[i] << endl;
308 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences.");
309 m->mothurOutEndLine();
311 m->mothurOutEndLine();
312 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
313 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
314 m->mothurOutEndLine();
318 catch(exception& e) {
319 m->errorOut(e, "SeqErrorCommand", "execute");
323 //**********************************************************************************************************************
324 int SeqErrorCommand::createProcesses(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName) {
328 map<char, vector<int> >::iterator it;
330 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
332 //loop through and create all the processes you want
333 while (process != processors) {
337 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
341 num = driver(filename, qFileName, rFileName, summaryFileName + toString(getpid()) + ".temp", errorOutputFileName+ toString(getpid()) + ".temp", chimeraOutputFileName + toString(getpid()) + ".temp", lines[process], qLines[process], rLines[process]);
343 //pass groupCounts to parent
345 string tempFile = filename + toString(getpid()) + ".info.temp";
346 m->openOutputFile(tempFile, out);
348 //output totalBases and totalMatches
349 out << num << '\t' << totalBases << '\t' << totalMatches << endl << endl;
351 //output substitutionMatrix
352 for(int i = 0; i < substitutionMatrix.size(); i++) {
353 for (int j = 0; j < substitutionMatrix[i].size(); j++) {
354 out << substitutionMatrix[i][j] << '\t';
360 //output qScoreErrorMap
361 for (it = qScoreErrorMap.begin(); it != qScoreErrorMap.end(); it++) {
362 vector<int> thisScoreErrorMap = it->second;
363 out << it->first << '\t';
364 for (int i = 0; i < thisScoreErrorMap.size(); i++) {
365 out << thisScoreErrorMap[i] << '\t';
371 //output qualForwardMap
372 for(int i = 0; i < qualForwardMap.size(); i++) {
373 for (int j = 0; j < qualForwardMap[i].size(); j++) {
374 out << qualForwardMap[i][j] << '\t';
380 //output qualReverseMap
381 for(int i = 0; i < qualReverseMap.size(); i++) {
382 for (int j = 0; j < qualReverseMap[i].size(); j++) {
383 out << qualReverseMap[i][j] << '\t';
390 //output errorForward
391 for (it = errorForward.begin(); it != errorForward.end(); it++) {
392 vector<int> thisErrorForward = it->second;
393 out << it->first << '\t';
394 for (int i = 0; i < thisErrorForward.size(); i++) {
395 out << thisErrorForward[i] << '\t';
401 //output errorReverse
402 for (it = errorReverse.begin(); it != errorReverse.end(); it++) {
403 vector<int> thisErrorReverse = it->second;
404 out << it->first << '\t';
405 for (int i = 0; i < thisErrorReverse.size(); i++) {
406 out << thisErrorReverse[i] << '\t';
412 //output misMatchCounts
413 out << misMatchCounts.size() << endl;
414 for (int j = 0; j < misMatchCounts.size(); j++) {
415 out << misMatchCounts[j] << '\t';
420 //output megaAlignVector
421 for (int j = 0; j < megaAlignVector.size(); j++) {
422 out << megaAlignVector[j] << endl;
430 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
431 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
437 num = driver(filename, qFileName, rFileName, summaryFileName, errorOutputFileName, chimeraOutputFileName, lines[0], qLines[0], rLines[0]);
439 //force parent to wait until all the processes are done
440 for (int i=0;i<processIDS.size();i++) {
441 int temp = processIDS[i];
446 for(int i=0;i<processIDS.size();i++){
448 m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
450 m->appendFiles((summaryFileName + toString(processIDS[i]) + ".temp"), summaryFileName);
451 remove((summaryFileName + toString(processIDS[i]) + ".temp").c_str());
452 m->appendFiles((errorOutputFileName + toString(processIDS[i]) + ".temp"), errorOutputFileName);
453 remove((errorOutputFileName + toString(processIDS[i]) + ".temp").c_str());
454 m->appendFiles((chimeraOutputFileName + toString(processIDS[i]) + ".temp"), chimeraOutputFileName);
455 remove((chimeraOutputFileName + toString(processIDS[i]) + ".temp").c_str());
458 string tempFile = filename + toString(processIDS[i]) + ".info.temp";
459 m->openInputFile(tempFile, in);
461 //input totalBases and totalMatches
462 int tempBases, tempMatches, tempNumSeqs;
463 in >> tempNumSeqs >> tempBases >> tempMatches; m->gobble(in);
464 totalBases += tempBases; totalMatches += tempMatches; num += tempNumSeqs;
466 //input substitutionMatrix
468 for(int i = 0; i < substitutionMatrix.size(); i++) {
469 for (int j = 0; j < substitutionMatrix[i].size(); j++) {
470 in >> tempNum; substitutionMatrix[i][j] += tempNum;
476 //input qScoreErrorMap
478 for (int i = 0; i < qScoreErrorMap.size(); i++) {
480 vector<int> thisScoreErrorMap = qScoreErrorMap[first];
482 for (int i = 0; i < thisScoreErrorMap.size(); i++) {
483 in >> tempNum; thisScoreErrorMap[i] += tempNum;
485 qScoreErrorMap[first] = thisScoreErrorMap;
490 //input qualForwardMap
491 for(int i = 0; i < qualForwardMap.size(); i++) {
492 for (int j = 0; j < qualForwardMap[i].size(); j++) {
493 in >> tempNum; qualForwardMap[i][j] += tempNum;
499 //input qualReverseMap
500 for(int i = 0; i < qualReverseMap.size(); i++) {
501 for (int j = 0; j < qualReverseMap[i].size(); j++) {
502 in >> tempNum; qualReverseMap[i][j] += tempNum;
509 for (int i = 0; i < errorForward.size(); i++) {
511 vector<int> thisErrorForward = errorForward[first];
513 for (int i = 0; i < thisErrorForward.size(); i++) {
514 in >> tempNum; thisErrorForward[i] += tempNum;
516 errorForward[first] = thisErrorForward;
522 for (int i = 0; i < errorReverse.size(); i++) {
524 vector<int> thisErrorReverse = errorReverse[first];
526 for (int i = 0; i < thisErrorReverse.size(); i++) {
527 in >> tempNum; thisErrorReverse[i] += tempNum;
529 errorReverse[first] = thisErrorReverse;
534 //input misMatchCounts
536 in >> misMatchSize; m->gobble(in);
537 if (misMatchSize > misMatchCounts.size()) { misMatchCounts.resize(misMatchSize, 0); }
538 for (int j = 0; j < misMatchCounts.size(); j++) {
539 in >> tempNum; misMatchCounts[j] += tempNum;
543 //input megaAlignVector
545 for (int j = 0; j < megaAlignVector.size(); j++) {
546 thisLine = m->getline(in); m->gobble(in); megaAlignVector[j] += thisLine + '\n';
550 in.close(); remove(tempFile.c_str());
556 catch(exception& e) {
557 m->errorOut(e, "SeqErrorCommand", "createProcesses");
561 //**********************************************************************************************************************
562 int SeqErrorCommand::driver(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName, linePair line, linePair qline, linePair rline) {
566 QualityScores quality;
568 misMatchCounts.resize(11, 0);
572 map<string, int>::iterator it;
573 qScoreErrorMap['m'].assign(41, 0);
574 qScoreErrorMap['s'].assign(41, 0);
575 qScoreErrorMap['i'].assign(41, 0);
576 qScoreErrorMap['a'].assign(41, 0);
578 errorForward['m'].assign(maxLength,0);
579 errorForward['s'].assign(maxLength,0);
580 errorForward['i'].assign(maxLength,0);
581 errorForward['d'].assign(maxLength,0);
582 errorForward['a'].assign(maxLength,0);
584 errorReverse['m'].assign(maxLength,0);
585 errorReverse['s'].assign(maxLength,0);
586 errorReverse['i'].assign(maxLength,0);
587 errorReverse['d'].assign(maxLength,0);
588 errorReverse['a'].assign(maxLength,0);
590 //open inputfiles and go to beginning place for this processor
592 m->openInputFile(filename, queryFile);
593 queryFile.seekg(line.start);
597 if(qFileName != "" && rFileName != ""){
598 m->openInputFile(qFileName, qualFile);
599 qualFile.seekg(qline.start);
602 if (rline.start == 0) { report = ReportFile(reportFile, rFileName); }
604 m->openInputFile(rFileName, reportFile);
605 reportFile.seekg(rline.start);
608 qualForwardMap.resize(maxLength);
609 qualReverseMap.resize(maxLength);
610 for(int i=0;i<maxLength;i++){
611 qualForwardMap[i].assign(41,0);
612 qualReverseMap[i].assign(41,0);
616 ofstream outChimeraReport;
617 m->openOutputFile(chimeraOutputFileName, outChimeraReport);
618 RefChimeraTest chimeraTest(referenceSeqs);
619 if (line.start == 0) { chimeraTest.printHeader(outChimeraReport); }
621 ofstream errorSummaryFile;
622 m->openOutputFile(summaryFileName, errorSummaryFile);
623 if (line.start == 0) { printErrorHeader(errorSummaryFile); }
625 ofstream errorSeqFile;
626 m->openOutputFile(errorOutputFileName, errorSeqFile);
628 megaAlignVector.resize(numRefs, "");
636 if (m->control_pressed) { queryFile.close(); if(qFileName != "" && rFileName != ""){ reportFile.close(); qualFile.close(); } outChimeraReport.close(); errorSummaryFile.close();errorSeqFile.close(); return 0; }
638 Sequence query(queryFile);
640 int numParentSeqs = chimeraTest.analyzeQuery(query.getName(), query.getAligned(), outChimeraReport);
641 int closestRefIndex = chimeraTest.getClosestRefIndex();
643 if(numParentSeqs > 1 && ignoreChimeras == 1) { ignoreSeq = 1; }
644 else { ignoreSeq = 0; }
646 Compare minCompare = getErrors(query, referenceSeqs[closestRefIndex]);
648 if(namesFileName != ""){
649 it = weights.find(query.getName());
650 minCompare.weight = it->second;
652 else{ minCompare.weight = 1; }
654 printErrorData(minCompare, numParentSeqs, errorSummaryFile, errorSeqFile);
658 for(int i=0;i<minCompare.sequence.length();i++){
659 char letter = minCompare.sequence[i];
661 errorForward[letter][i] += minCompare.weight;
662 errorReverse[letter][minCompare.total-i-1] += minCompare.weight;
666 if(qualFileName != "" && reportFileName != ""){
667 report = ReportFile(reportFile);
669 // int origLength = report.getQueryLength();
670 int startBase = report.getQueryStart();
671 int endBase = report.getQueryEnd();
673 quality = QualityScores(qualFile);
676 quality.updateQScoreErrorMap(qScoreErrorMap, minCompare.sequence, startBase, endBase, minCompare.weight);
677 quality.updateForwardMap(qualForwardMap, startBase, endBase, minCompare.weight);
678 quality.updateReverseMap(qualReverseMap, startBase, endBase, minCompare.weight);
682 if(minCompare.errorRate < threshold && !ignoreSeq){
683 totalBases += (minCompare.total * minCompare.weight);
684 totalMatches += minCompare.matches * minCompare.weight;
685 if(minCompare.mismatches > maxMismatch){
686 maxMismatch = minCompare.mismatches;
687 misMatchCounts.resize(maxMismatch + 1, 0);
689 misMatchCounts[minCompare.mismatches] += minCompare.weight;
692 megaAlignVector[closestRefIndex] += query.getInlineSeq() + '\n';
697 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
698 unsigned long int pos = queryFile.tellg();
699 if ((pos == -1) || (pos >= line.end)) { break; }
701 if (queryFile.eof()) { break; }
704 if(index % 100 == 0){ m->mothurOut(toString(index) + '\n'); }
707 if(qFileName != "" && rFileName != ""){ reportFile.close(); qualFile.close(); }
708 errorSummaryFile.close();
709 errorSeqFile.close();
712 if(index % 100 != 0){ m->mothurOut(toString(index) + '\n'); }
716 catch(exception& e) {
717 m->errorOut(e, "SeqErrorCommand", "driver");
721 //***************************************************************************************************************
723 void SeqErrorCommand::getReferences(){
726 ifstream referenceFile;
727 m->openInputFile(referenceFileName, referenceFile);
729 int numAmbigSeqs = 0;
732 int minEndPos = 100000;
734 while(referenceFile){
735 Sequence currentSeq(referenceFile);
736 int numAmbigs = currentSeq.getAmbigBases();
737 if(numAmbigs > 0){ numAmbigSeqs++; }
739 // int startPos = currentSeq.getStartPos();
740 // if(startPos > maxStartPos) { maxStartPos = startPos; }
742 // int endPos = currentSeq.getEndPos();
743 // if(endPos < minEndPos) { minEndPos = endPos; }
744 referenceSeqs.push_back(currentSeq);
746 m->gobble(referenceFile);
748 referenceFile.close();
749 numRefs = referenceSeqs.size();
752 for(int i=0;i<numRefs;i++){
753 referenceSeqs[i].padToPos(maxStartPos);
754 referenceSeqs[i].padFromPos(minEndPos);
757 if(numAmbigSeqs != 0){
758 m->mothurOut("Warning: " + toString(numAmbigSeqs) + " reference sequences have ambiguous bases, these bases will be ignored\n");
762 catch(exception& e) {
763 m->errorOut(e, "SeqErrorCommand", "getReferences");
768 //***************************************************************************************************************
770 Compare SeqErrorCommand::getErrors(Sequence query, Sequence reference){
772 if(query.getAlignLength() != reference.getAlignLength()){
773 m->mothurOut("Warning: " + toString(query.getName()) + " and " + toString(reference.getName()) + " are different lengths\n");
775 int alignLength = query.getAlignLength();
777 string q = query.getAligned();
778 string r = reference.getAligned();
783 for(int i=0;i<alignLength;i++){
784 if(r[i] != 'N' && q[i] != '.' && r[i] != '.' && (q[i] != '-' || r[i] != '-')){ // no missing data and no double gaps
788 if(r[i] == 'A'){ errors.AA++; errors.matches++; errors.sequence += 'm'; }
789 if(r[i] == 'T'){ errors.AT++; errors.sequence += 's'; }
790 if(r[i] == 'G'){ errors.AG++; errors.sequence += 's'; }
791 if(r[i] == 'C'){ errors.AC++; errors.sequence += 's'; }
792 if(r[i] == '-'){ errors.Ai++; errors.sequence += 'i'; }
794 else if(q[i] == 'T'){
795 if(r[i] == 'A'){ errors.TA++; errors.sequence += 's'; }
796 if(r[i] == 'T'){ errors.TT++; errors.matches++; errors.sequence += 'm'; }
797 if(r[i] == 'G'){ errors.TG++; errors.sequence += 's'; }
798 if(r[i] == 'C'){ errors.TC++; errors.sequence += 's'; }
799 if(r[i] == '-'){ errors.Ti++; errors.sequence += 'i'; }
801 else if(q[i] == 'G'){
802 if(r[i] == 'A'){ errors.GA++; errors.sequence += 's'; }
803 if(r[i] == 'T'){ errors.GT++; errors.sequence += 's'; }
804 if(r[i] == 'G'){ errors.GG++; errors.matches++; errors.sequence += 'm'; }
805 if(r[i] == 'C'){ errors.GC++; errors.sequence += 's'; }
806 if(r[i] == '-'){ errors.Gi++; errors.sequence += 'i'; }
808 else if(q[i] == 'C'){
809 if(r[i] == 'A'){ errors.CA++; errors.sequence += 's'; }
810 if(r[i] == 'T'){ errors.CT++; errors.sequence += 's'; }
811 if(r[i] == 'G'){ errors.CG++; errors.sequence += 's'; }
812 if(r[i] == 'C'){ errors.CC++; errors.matches++; errors.sequence += 'm'; }
813 if(r[i] == '-'){ errors.Ci++; errors.sequence += 'i'; }
815 else if(q[i] == 'N'){
816 if(r[i] == 'A'){ errors.NA++; errors.sequence += 'a'; }
817 if(r[i] == 'T'){ errors.NT++; errors.sequence += 'a'; }
818 if(r[i] == 'G'){ errors.NG++; errors.sequence += 'a'; }
819 if(r[i] == 'C'){ errors.NC++; errors.sequence += 'a'; }
820 if(r[i] == '-'){ errors.Ni++; errors.sequence += 'a'; }
822 else if(q[i] == '-' && r[i] != '-'){
823 if(r[i] == 'A'){ errors.dA++; errors.sequence += 'd'; }
824 if(r[i] == 'T'){ errors.dT++; errors.sequence += 'd'; }
825 if(r[i] == 'G'){ errors.dG++; errors.sequence += 'd'; }
826 if(r[i] == 'C'){ errors.dC++; errors.sequence += 'd'; }
831 else if(q[i] == '.' && r[i] != '.'){ // reference extends beyond query
832 if(started == 1){ break; }
834 else if(q[i] != '.' && r[i] == '.'){ // query extends beyond reference
835 if(started == 1){ break; }
837 else if(q[i] == '.' && r[i] == '.'){ // both are missing data
838 if(started == 1){ break; }
842 errors.mismatches = errors.total-errors.matches;
843 errors.errorRate = (double)(errors.total-errors.matches) / (double)errors.total;
844 errors.queryName = query.getName();
845 errors.refName = reference.getName();
849 catch(exception& e) {
850 m->errorOut(e, "SeqErrorCommand", "getErrors");
855 //***************************************************************************************************************
857 map<string, int> SeqErrorCommand::getWeights(){
859 m->openInputFile(namesFileName, nameFile);
862 string redundantSeqs;
863 map<string, int> nameCountMap;
866 nameFile >> seqName >> redundantSeqs;
867 nameCountMap[seqName] = m->getNumNames(redundantSeqs);
874 //***************************************************************************************************************
876 void SeqErrorCommand::printErrorHeader(ofstream& errorSummaryFile){
878 errorSummaryFile << "query\treference\tweight\t";
879 errorSummaryFile << "AA\tAT\tAG\tAC\tTA\tTT\tTG\tTC\tGA\tGT\tGG\tGC\tCA\tCT\tCG\tCC\tNA\tNT\tNG\tNC\tAi\tTi\tGi\tCi\tNi\tdA\tdT\tdG\tdC\t";
880 errorSummaryFile << "insertions\tdeletions\tsubstitutions\tambig\tmatches\tmismatches\ttotal\terror\tnumparents\n";
882 errorSummaryFile << setprecision(6);
883 errorSummaryFile.setf(ios::fixed);
885 catch(exception& e) {
886 m->errorOut(e, "SeqErrorCommand", "printErrorHeader");
891 //***************************************************************************************************************
893 void SeqErrorCommand::printErrorData(Compare error, int numParentSeqs, ofstream& errorSummaryFile, ofstream& errorSeqFile){
896 errorSummaryFile << error.queryName << '\t' << error.refName << '\t' << error.weight << '\t';
897 errorSummaryFile << error.AA << '\t' << error.AT << '\t' << error.AG << '\t' << error.AC << '\t';
898 errorSummaryFile << error.TA << '\t' << error.TT << '\t' << error.TG << '\t' << error.TC << '\t';
899 errorSummaryFile << error.GA << '\t' << error.GT << '\t' << error.GG << '\t' << error.GC << '\t';
900 errorSummaryFile << error.CA << '\t' << error.CT << '\t' << error.CG << '\t' << error.CC << '\t';
901 errorSummaryFile << error.NA << '\t' << error.NT << '\t' << error.NG << '\t' << error.NC << '\t';
902 errorSummaryFile << error.Ai << '\t' << error.Ti << '\t' << error.Gi << '\t' << error.Ci << '\t' << error.Ni << '\t';
903 errorSummaryFile << error.dA << '\t' << error.dT << '\t' << error.dG << '\t' << error.dC << '\t';
905 errorSummaryFile << error.Ai + error.Ti + error.Gi + error.Ci << '\t'; //insertions
906 errorSummaryFile << error.dA + error.dT + error.dG + error.dC << '\t'; //deletions
907 errorSummaryFile << error.mismatches - (error.Ai + error.Ti + error.Gi + error.Ci) - (error.dA + error.dT + error.dG + error.dC) - (error.NA + error.NT + error.NG + error.NC + error.Ni) << '\t'; //substitutions
908 errorSummaryFile << error.NA + error.NT + error.NG + error.NC + error.Ni << '\t'; //ambiguities
909 errorSummaryFile << error.matches << '\t' << error.mismatches << '\t' << error.total << '\t' << error.errorRate << '\t' << numParentSeqs << endl;
911 errorSeqFile << '>' << error.queryName << "\tref:" << error.refName << '\n' << error.sequence << endl;
913 int a=0; int t=1; int g=2; int c=3;
916 if(numParentSeqs == 1 || ignoreChimeras == 0){
917 substitutionMatrix[a][a] += error.weight * error.AA;
918 substitutionMatrix[a][t] += error.weight * error.TA;
919 substitutionMatrix[a][g] += error.weight * error.GA;
920 substitutionMatrix[a][c] += error.weight * error.CA;
921 substitutionMatrix[a][gap] += error.weight * error.dA;
922 substitutionMatrix[a][n] += error.weight * error.NA;
924 substitutionMatrix[t][a] += error.weight * error.AT;
925 substitutionMatrix[t][t] += error.weight * error.TT;
926 substitutionMatrix[t][g] += error.weight * error.GT;
927 substitutionMatrix[t][c] += error.weight * error.CT;
928 substitutionMatrix[t][gap] += error.weight * error.dT;
929 substitutionMatrix[t][n] += error.weight * error.NT;
931 substitutionMatrix[g][a] += error.weight * error.AG;
932 substitutionMatrix[g][t] += error.weight * error.TG;
933 substitutionMatrix[g][g] += error.weight * error.GG;
934 substitutionMatrix[g][c] += error.weight * error.CG;
935 substitutionMatrix[g][gap] += error.weight * error.dG;
936 substitutionMatrix[g][n] += error.weight * error.NG;
938 substitutionMatrix[c][a] += error.weight * error.AC;
939 substitutionMatrix[c][t] += error.weight * error.TC;
940 substitutionMatrix[c][g] += error.weight * error.GC;
941 substitutionMatrix[c][c] += error.weight * error.CC;
942 substitutionMatrix[c][gap] += error.weight * error.dC;
943 substitutionMatrix[c][n] += error.weight * error.NC;
945 substitutionMatrix[gap][a] += error.weight * error.Ai;
946 substitutionMatrix[gap][t] += error.weight * error.Ti;
947 substitutionMatrix[gap][g] += error.weight * error.Gi;
948 substitutionMatrix[gap][c] += error.weight * error.Ci;
949 substitutionMatrix[gap][n] += error.weight * error.Ni;
952 catch(exception& e) {
953 m->errorOut(e, "SeqErrorCommand", "printErrorData");
958 //***************************************************************************************************************
960 void SeqErrorCommand::printSubMatrix(){
962 string subMatrixFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.matrix";
963 ofstream subMatrixFile;
964 m->openOutputFile(subMatrixFileName, subMatrixFile);
965 outputNames.push_back(subMatrixFileName); outputTypes["error.matrix"].push_back(subMatrixFileName);
966 vector<string> bases(6);
973 vector<int> refSums(5,1);
975 for(int i=0;i<5;i++){
976 subMatrixFile << "\tr" << bases[i];
978 for(int j=0;j<6;j++){
979 refSums[i] += substitutionMatrix[i][j];
982 subMatrixFile << endl;
984 for(int i=0;i<6;i++){
985 subMatrixFile << 'q' << bases[i];
986 for(int j=0;j<5;j++){
987 subMatrixFile << '\t' << substitutionMatrix[j][i];
989 subMatrixFile << endl;
992 subMatrixFile << "total";
993 for(int i=0;i<5;i++){
994 subMatrixFile << '\t' << refSums[i];
996 subMatrixFile << endl;
997 subMatrixFile.close();
999 catch(exception& e) {
1000 m->errorOut(e, "SeqErrorCommand", "printSubMatrix");
1004 //***************************************************************************************************************
1006 void SeqErrorCommand::printErrorFRFile(map<char, vector<int> > errorForward, map<char, vector<int> > errorReverse){
1008 string errorForwardFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq.forward";
1009 ofstream errorForwardFile;
1010 m->openOutputFile(errorForwardFileName, errorForwardFile);
1011 outputNames.push_back(errorForwardFileName); outputTypes["error.forward"].push_back(errorForwardFileName);
1013 errorForwardFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1014 for(int i=0;i<maxLength;i++){
1015 float match = (float)errorForward['m'][i];
1016 float subst = (float)errorForward['s'][i];
1017 float insert = (float)errorForward['i'][i];
1018 float del = (float)errorForward['d'][i];
1019 float amb = (float)errorForward['a'][i];
1020 float total = match + subst + insert + del + amb;
1021 if(total == 0){ break; }
1022 errorForwardFile << i+1 << '\t' << total << '\t' << match/total << '\t' << subst/total << '\t' << insert/total << '\t' << del/total << '\t' << amb/total << endl;
1024 errorForwardFile.close();
1026 string errorReverseFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq.reverse";
1027 ofstream errorReverseFile;
1028 m->openOutputFile(errorReverseFileName, errorReverseFile);
1029 outputNames.push_back(errorReverseFileName); outputTypes["error.reverse"].push_back(errorReverseFileName);
1031 errorReverseFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1032 for(int i=0;i<maxLength;i++){
1033 float match = (float)errorReverse['m'][i];
1034 float subst = (float)errorReverse['s'][i];
1035 float insert = (float)errorReverse['i'][i];
1036 float del = (float)errorReverse['d'][i];
1037 float amb = (float)errorReverse['a'][i];
1038 float total = match + subst + insert + del + amb;
1039 if(total == 0){ break; }
1040 errorReverseFile << i+1 << '\t' << total << '\t' << match/total << '\t' << subst/total << '\t' << insert/total << '\t' << del/total << '\t' << amb/total << endl;
1042 errorReverseFile.close();
1044 catch(exception& e) {
1045 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1050 //***************************************************************************************************************
1052 void SeqErrorCommand::printErrorQuality(map<char, vector<int> > qScoreErrorMap){
1055 string errorQualityFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.quality";
1056 ofstream errorQualityFile;
1057 m->openOutputFile(errorQualityFileName, errorQualityFile);
1058 outputNames.push_back(errorQualityFileName); outputTypes["error.quality"].push_back(errorQualityFileName);
1060 errorQualityFile << "qscore\tmatches\tsubstitutions\tinsertions\tambiguous" << endl;
1061 for(int i=0;i<41;i++){
1062 errorQualityFile << i << '\t' << qScoreErrorMap['m'][i] << '\t' << qScoreErrorMap['s'][i] << '\t' << qScoreErrorMap['i'][i] << '\t'<< qScoreErrorMap['a'][i] << endl;
1064 errorQualityFile.close();
1066 catch(exception& e) {
1067 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1073 //***************************************************************************************************************
1075 void SeqErrorCommand::printQualityFR(vector<vector<int> > qualForwardMap, vector<vector<int> > qualReverseMap){
1079 int numColumns = qualForwardMap[0].size();
1081 for(int i=0;i<qualForwardMap.size();i++){
1082 for(int j=0;j<numColumns;j++){
1083 if(qualForwardMap[i][j] != 0){
1084 if(numRows < i) { numRows = i+20; }
1089 string qualityForwardFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.qual.forward";
1090 ofstream qualityForwardFile;
1091 m->openOutputFile(qualityForwardFileName, qualityForwardFile);
1092 outputNames.push_back(qualityForwardFileName); outputTypes["error.qual.forward"].push_back(qualityForwardFileName);
1094 for(int i=0;i<numColumns;i++){ qualityForwardFile << '\t' << i; } qualityForwardFile << endl;
1096 for(int i=0;i<numRows;i++){
1097 qualityForwardFile << i+1;
1098 for(int j=0;j<numColumns;j++){
1099 qualityForwardFile << '\t' << qualForwardMap[i][j];
1102 qualityForwardFile << endl;
1104 qualityForwardFile.close();
1107 string qualityReverseFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.qual.reverse";
1108 ofstream qualityReverseFile;
1109 m->openOutputFile(qualityReverseFileName, qualityReverseFile);
1110 outputNames.push_back(qualityReverseFileName); outputTypes["error.qual.reverse"].push_back(qualityReverseFileName);
1112 for(int i=0;i<numColumns;i++){ qualityReverseFile << '\t' << i; } qualityReverseFile << endl;
1113 for(int i=0;i<numRows;i++){
1115 qualityReverseFile << i+1;
1116 for(int j=0;j<numColumns;j++){
1117 qualityReverseFile << '\t' << qualReverseMap[i][j];
1119 qualityReverseFile << endl;
1121 qualityReverseFile.close();
1123 catch(exception& e) {
1124 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1129 /**************************************************************************************************/
1131 int SeqErrorCommand::setLines(string filename, string qfilename, string rfilename, vector<unsigned long int>& fastaFilePos, vector<unsigned long int>& qfileFilePos, vector<unsigned long int>& rfileFilePos) {
1133 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1134 //set file positions for fasta file
1135 fastaFilePos = m->divideFile(filename, processors);
1137 if (qfilename == "") { return processors; }
1139 //get name of first sequence in each chunk
1140 map<string, int> firstSeqNames;
1141 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
1143 m->openInputFile(filename, in);
1144 in.seekg(fastaFilePos[i]);
1147 firstSeqNames[temp.getName()] = i;
1152 //make copy to use below
1153 map<string, int> firstSeqNamesReport = firstSeqNames;
1155 //seach for filePos of each first name in the qfile and save in qfileFilePos
1157 m->openInputFile(qfilename, inQual);
1160 while(!inQual.eof()){
1161 input = m->getline(inQual);
1163 if (input.length() != 0) {
1164 if(input[0] == '>'){ //this is a sequence name line
1165 istringstream nameStream(input);
1167 string sname = ""; nameStream >> sname;
1168 sname = sname.substr(1);
1170 map<string, int>::iterator it = firstSeqNames.find(sname);
1172 if(it != firstSeqNames.end()) { //this is the start of a new chunk
1173 unsigned long int pos = inQual.tellg();
1174 qfileFilePos.push_back(pos - input.length() - 1);
1175 firstSeqNames.erase(it);
1180 if (firstSeqNames.size() == 0) { break; }
1184 if (firstSeqNames.size() != 0) {
1185 for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
1186 m->mothurOut(it->first + " is in your fasta file and not in your quality file, aborting."); m->mothurOutEndLine();
1188 m->control_pressed = true;
1192 //get last file position of qfile
1194 unsigned long int size;
1196 //get num bytes in file
1197 pFile = fopen (qfilename.c_str(),"rb");
1198 if (pFile==NULL) perror ("Error opening file");
1200 fseek (pFile, 0, SEEK_END);
1205 qfileFilePos.push_back(size);
1207 //seach for filePos of each first name in the rfile and save in rfileFilePos
1210 m->openInputFile(rfilename, inR);
1212 //read column headers
1213 for (int i = 0; i < 16; i++) {
1214 if (!inR.eof()) { inR >> junk; }
1220 if (m->control_pressed) { inR.close(); return processors; }
1222 input = m->getline(inR);
1224 if (input.length() != 0) {
1226 istringstream nameStream(input);
1227 string sname = ""; nameStream >> sname;
1229 map<string, int>::iterator it = firstSeqNamesReport.find(sname);
1231 if(it != firstSeqNamesReport.end()) { //this is the start of a new chunk
1232 unsigned long int pos = inR.tellg();
1233 rfileFilePos.push_back(pos - input.length() - 1);
1234 firstSeqNamesReport.erase(it);
1238 if (firstSeqNamesReport.size() == 0) { break; }
1243 if (firstSeqNamesReport.size() != 0) {
1244 for (map<string, int>::iterator it = firstSeqNamesReport.begin(); it != firstSeqNamesReport.end(); it++) {
1245 m->mothurOut(it->first + " is in your fasta file and not in your report file, aborting."); m->mothurOutEndLine();
1247 m->control_pressed = true;
1251 //get last file position of qfile
1253 unsigned long int sizeR;
1255 //get num bytes in file
1256 rFile = fopen (rfilename.c_str(),"rb");
1257 if (rFile==NULL) perror ("Error opening file");
1259 fseek (rFile, 0, SEEK_END);
1260 sizeR=ftell (rFile);
1264 rfileFilePos.push_back(sizeR);
1270 fastaFilePos.push_back(0); qfileFilePos.push_back(0);
1271 //get last file position of fastafile
1273 unsigned long int size;
1275 //get num bytes in file
1276 pFile = fopen (filename.c_str(),"rb");
1277 if (pFile==NULL) perror ("Error opening file");
1279 fseek (pFile, 0, SEEK_END);
1283 fastaFilePos.push_back(size);
1285 //get last file position of fastafile
1288 //get num bytes in file
1289 qFile = fopen (qfilename.c_str(),"rb");
1290 if (qFile==NULL) perror ("Error opening file");
1292 fseek (qFile, 0, SEEK_END);
1296 qfileFilePos.push_back(size);
1302 catch(exception& e) {
1303 m->errorOut(e, "SeqErrorCommand", "setLines");
1307 //***************************************************************************************************************