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; }
168 referenceFileName = validParameter.validFile(parameters, "reference", true);
169 if (referenceFileName == "not found") { m->mothurOut("reference is a required parameter for the seq.error command."); m->mothurOutEndLine(); abort = true; }
170 else if (referenceFileName == "not open") { abort = true; }
173 //check for optional parameters
174 namesFileName = validParameter.validFile(parameters, "name", true);
175 if(namesFileName == "not found"){ namesFileName = ""; }
176 else if (namesFileName == "not open") { namesFileName = ""; abort = true; }
178 qualFileName = validParameter.validFile(parameters, "qfile", true);
179 if(qualFileName == "not found"){ qualFileName = ""; }
180 else if (qualFileName == "not open") { qualFileName = ""; abort = true; }
182 reportFileName = validParameter.validFile(parameters, "report", true);
183 if(reportFileName == "not found"){ reportFileName = ""; }
184 else if (reportFileName == "not open") { reportFileName = ""; abort = true; }
186 if((reportFileName != "" && qualFileName == "") || (reportFileName == "" && qualFileName != "")){
187 m->mothurOut("if you use either a qual file or a report file, you have to have both.");
188 m->mothurOutEndLine();
192 outputDir = validParameter.validFile(parameters, "outputdir", false);
193 if (outputDir == "not found"){
195 outputDir += m->hasPath(queryFileName); //if user entered a file with a path then preserve it
198 //check for optional parameter and set defaults
199 // ...at some point should added some additional type checking...
200 temp = validParameter.validFile(parameters, "threshold", false); if (temp == "not found") { temp = "1.00"; }
201 convert(temp, threshold);
203 temp = validParameter.validFile(parameters, "ignorechimeras", false); if (temp == "not found") { temp = "T"; }
204 ignoreChimeras = m->isTrue(temp);
206 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
207 m->setProcessors(temp);
208 convert(temp, processors);
210 substitutionMatrix.resize(6);
211 for(int i=0;i<6;i++){ substitutionMatrix[i].resize(6,0); }
214 catch(exception& e) {
215 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
219 //***************************************************************************************************************
221 int SeqErrorCommand::execute(){
223 if (abort == true) { if (calledHelp) { return 0; } return 2; }
225 int start = time(NULL);
230 string errorSummaryFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.summary";
231 outputNames.push_back(errorSummaryFileName); outputTypes["error.summary"].push_back(errorSummaryFileName);
233 string errorSeqFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq";
234 outputNames.push_back(errorSeqFileName); outputTypes["error.seq"].push_back(errorSeqFileName);
236 string errorChimeraFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.chimera";
237 outputNames.push_back(errorChimeraFileName); outputTypes["error.chimera"].push_back(errorChimeraFileName);
239 getReferences(); //read in reference sequences - make sure there's no ambiguous bases
241 if(namesFileName != ""){ weights = getWeights(); }
243 vector<unsigned long int> fastaFilePos;
244 vector<unsigned long int> qFilePos;
245 vector<unsigned long int> reportFilePos;
247 setLines(queryFileName, qualFileName, reportFileName, fastaFilePos, qFilePos, reportFilePos);
249 if (m->control_pressed) { return 0; }
251 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
252 lines.push_back(linePair(fastaFilePos[i], fastaFilePos[(i+1)]));
253 if (qualFileName != "") { qLines.push_back(linePair(qFilePos[i], qFilePos[(i+1)])); }
254 if (reportFileName != "") { rLines.push_back(linePair(reportFilePos[i], reportFilePos[(i+1)])); }
256 if(qualFileName == "") { qLines = lines; rLines = lines; } //fills with duds
259 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
261 numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
263 numSeqs = createProcesses(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName);
266 numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
269 if(qualFileName != "" && reportFileName != ""){
270 printErrorQuality(qScoreErrorMap);
271 printQualityFR(qualForwardMap, qualReverseMap);
274 printErrorFRFile(errorForward, errorReverse);
276 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
278 string errorCountFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.count";
279 ofstream errorCountFile;
280 m->openOutputFile(errorCountFileName, errorCountFile);
281 outputNames.push_back(errorCountFileName); outputTypes["error.count"].push_back(errorCountFileName);
282 m->mothurOut("Overall error rate:\t" + toString((double)(totalBases - totalMatches) / (double)totalBases) + "\n");
283 m->mothurOut("Errors\tSequences\n");
284 errorCountFile << "Errors\tSequences\n";
285 for(int i=0;i<misMatchCounts.size();i++){
286 m->mothurOut(toString(i) + '\t' + toString(misMatchCounts[i]) + '\n');
287 errorCountFile << i << '\t' << misMatchCounts[i] << endl;
289 errorCountFile.close();
291 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
295 string megAlignmentFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.ref-query";
296 ofstream megAlignmentFile;
297 m->openOutputFile(megAlignmentFileName, megAlignmentFile);
298 outputNames.push_back(megAlignmentFileName); outputTypes["error.ref-query"].push_back(megAlignmentFileName);
300 for(int i=0;i<numRefs;i++){
301 megAlignmentFile << referenceSeqs[i].getInlineSeq() << endl;
302 megAlignmentFile << megaAlignVector[i] << endl;
305 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences.");
306 m->mothurOutEndLine();
308 m->mothurOutEndLine();
309 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
310 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
311 m->mothurOutEndLine();
315 catch(exception& e) {
316 m->errorOut(e, "SeqErrorCommand", "execute");
320 //**********************************************************************************************************************
321 int SeqErrorCommand::createProcesses(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName) {
325 map<char, vector<int> >::iterator it;
327 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
329 //loop through and create all the processes you want
330 while (process != processors) {
334 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
338 num = driver(filename, qFileName, rFileName, summaryFileName + toString(getpid()) + ".temp", errorOutputFileName+ toString(getpid()) + ".temp", chimeraOutputFileName + toString(getpid()) + ".temp", lines[process], qLines[process], rLines[process]);
340 //pass groupCounts to parent
342 string tempFile = filename + toString(getpid()) + ".info.temp";
343 m->openOutputFile(tempFile, out);
345 //output totalBases and totalMatches
346 out << num << '\t' << totalBases << '\t' << totalMatches << endl << endl;
348 //output substitutionMatrix
349 for(int i = 0; i < substitutionMatrix.size(); i++) {
350 for (int j = 0; j < substitutionMatrix[i].size(); j++) {
351 out << substitutionMatrix[i][j] << '\t';
357 //output qScoreErrorMap
358 for (it = qScoreErrorMap.begin(); it != qScoreErrorMap.end(); it++) {
359 vector<int> thisScoreErrorMap = it->second;
360 out << it->first << '\t';
361 for (int i = 0; i < thisScoreErrorMap.size(); i++) {
362 out << thisScoreErrorMap[i] << '\t';
368 //output qualForwardMap
369 for(int i = 0; i < qualForwardMap.size(); i++) {
370 for (int j = 0; j < qualForwardMap[i].size(); j++) {
371 out << qualForwardMap[i][j] << '\t';
377 //output qualReverseMap
378 for(int i = 0; i < qualReverseMap.size(); i++) {
379 for (int j = 0; j < qualReverseMap[i].size(); j++) {
380 out << qualReverseMap[i][j] << '\t';
387 //output errorForward
388 for (it = errorForward.begin(); it != errorForward.end(); it++) {
389 vector<int> thisErrorForward = it->second;
390 out << it->first << '\t';
391 for (int i = 0; i < thisErrorForward.size(); i++) {
392 out << thisErrorForward[i] << '\t';
398 //output errorReverse
399 for (it = errorReverse.begin(); it != errorReverse.end(); it++) {
400 vector<int> thisErrorReverse = it->second;
401 out << it->first << '\t';
402 for (int i = 0; i < thisErrorReverse.size(); i++) {
403 out << thisErrorReverse[i] << '\t';
409 //output misMatchCounts
410 out << misMatchCounts.size() << endl;
411 for (int j = 0; j < misMatchCounts.size(); j++) {
412 out << misMatchCounts[j] << '\t';
417 //output megaAlignVector
418 for (int j = 0; j < megaAlignVector.size(); j++) {
419 out << megaAlignVector[j] << endl;
427 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
428 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
434 num = driver(filename, qFileName, rFileName, summaryFileName, errorOutputFileName, chimeraOutputFileName, lines[0], qLines[0], rLines[0]);
436 //force parent to wait until all the processes are done
437 for (int i=0;i<processIDS.size();i++) {
438 int temp = processIDS[i];
443 for(int i=0;i<processIDS.size();i++){
445 m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
447 m->appendFiles((summaryFileName + toString(processIDS[i]) + ".temp"), summaryFileName);
448 remove((summaryFileName + toString(processIDS[i]) + ".temp").c_str());
449 m->appendFiles((errorOutputFileName + toString(processIDS[i]) + ".temp"), errorOutputFileName);
450 remove((errorOutputFileName + toString(processIDS[i]) + ".temp").c_str());
451 m->appendFiles((chimeraOutputFileName + toString(processIDS[i]) + ".temp"), chimeraOutputFileName);
452 remove((chimeraOutputFileName + toString(processIDS[i]) + ".temp").c_str());
455 string tempFile = filename + toString(processIDS[i]) + ".info.temp";
456 m->openInputFile(tempFile, in);
458 //input totalBases and totalMatches
459 int tempBases, tempMatches, tempNumSeqs;
460 in >> tempNumSeqs >> tempBases >> tempMatches; m->gobble(in);
461 totalBases += tempBases; totalMatches += tempMatches; num += tempNumSeqs;
463 //input substitutionMatrix
465 for(int i = 0; i < substitutionMatrix.size(); i++) {
466 for (int j = 0; j < substitutionMatrix[i].size(); j++) {
467 in >> tempNum; substitutionMatrix[i][j] += tempNum;
473 //input qScoreErrorMap
475 for (int i = 0; i < qScoreErrorMap.size(); i++) {
477 vector<int> thisScoreErrorMap = qScoreErrorMap[first];
479 for (int i = 0; i < thisScoreErrorMap.size(); i++) {
480 in >> tempNum; thisScoreErrorMap[i] += tempNum;
482 qScoreErrorMap[first] = thisScoreErrorMap;
487 //input qualForwardMap
488 for(int i = 0; i < qualForwardMap.size(); i++) {
489 for (int j = 0; j < qualForwardMap[i].size(); j++) {
490 in >> tempNum; qualForwardMap[i][j] += tempNum;
496 //input qualReverseMap
497 for(int i = 0; i < qualReverseMap.size(); i++) {
498 for (int j = 0; j < qualReverseMap[i].size(); j++) {
499 in >> tempNum; qualReverseMap[i][j] += tempNum;
506 for (int i = 0; i < errorForward.size(); i++) {
508 vector<int> thisErrorForward = errorForward[first];
510 for (int i = 0; i < thisErrorForward.size(); i++) {
511 in >> tempNum; thisErrorForward[i] += tempNum;
513 errorForward[first] = thisErrorForward;
519 for (int i = 0; i < errorReverse.size(); i++) {
521 vector<int> thisErrorReverse = errorReverse[first];
523 for (int i = 0; i < thisErrorReverse.size(); i++) {
524 in >> tempNum; thisErrorReverse[i] += tempNum;
526 errorReverse[first] = thisErrorReverse;
531 //input misMatchCounts
533 in >> misMatchSize; m->gobble(in);
534 if (misMatchSize > misMatchCounts.size()) { misMatchCounts.resize(misMatchSize, 0); }
535 for (int j = 0; j < misMatchCounts.size(); j++) {
536 in >> tempNum; misMatchCounts[j] += tempNum;
540 //input megaAlignVector
542 for (int j = 0; j < megaAlignVector.size(); j++) {
543 thisLine = m->getline(in); m->gobble(in); megaAlignVector[j] += thisLine + '\n';
547 in.close(); remove(tempFile.c_str());
553 catch(exception& e) {
554 m->errorOut(e, "SeqErrorCommand", "createProcesses");
558 //**********************************************************************************************************************
559 int SeqErrorCommand::driver(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName, linePair line, linePair qline, linePair rline) {
563 QualityScores quality;
565 misMatchCounts.resize(11, 0);
569 map<string, int>::iterator it;
570 qScoreErrorMap['m'].assign(41, 0);
571 qScoreErrorMap['s'].assign(41, 0);
572 qScoreErrorMap['i'].assign(41, 0);
573 qScoreErrorMap['a'].assign(41, 0);
575 errorForward['m'].assign(maxLength,0);
576 errorForward['s'].assign(maxLength,0);
577 errorForward['i'].assign(maxLength,0);
578 errorForward['d'].assign(maxLength,0);
579 errorForward['a'].assign(maxLength,0);
581 errorReverse['m'].assign(maxLength,0);
582 errorReverse['s'].assign(maxLength,0);
583 errorReverse['i'].assign(maxLength,0);
584 errorReverse['d'].assign(maxLength,0);
585 errorReverse['a'].assign(maxLength,0);
587 //open inputfiles and go to beginning place for this processor
589 m->openInputFile(filename, queryFile);
590 queryFile.seekg(line.start);
594 if(qFileName != "" && rFileName != ""){
595 m->openInputFile(qFileName, qualFile);
596 qualFile.seekg(qline.start);
599 if (rline.start == 0) { report = ReportFile(reportFile, rFileName); }
601 m->openInputFile(rFileName, reportFile);
602 reportFile.seekg(rline.start);
605 qualForwardMap.resize(maxLength);
606 qualReverseMap.resize(maxLength);
607 for(int i=0;i<maxLength;i++){
608 qualForwardMap[i].assign(41,0);
609 qualReverseMap[i].assign(41,0);
613 ofstream outChimeraReport;
614 m->openOutputFile(chimeraOutputFileName, outChimeraReport);
615 RefChimeraTest chimeraTest(referenceSeqs);
616 if (line.start == 0) { chimeraTest.printHeader(outChimeraReport); }
618 ofstream errorSummaryFile;
619 m->openOutputFile(summaryFileName, errorSummaryFile);
620 if (line.start == 0) { printErrorHeader(errorSummaryFile); }
622 ofstream errorSeqFile;
623 m->openOutputFile(errorOutputFileName, errorSeqFile);
625 megaAlignVector.resize(numRefs, "");
633 if (m->control_pressed) { queryFile.close(); if(qFileName != "" && rFileName != ""){ reportFile.close(); qualFile.close(); } outChimeraReport.close(); errorSummaryFile.close();errorSeqFile.close(); return 0; }
635 Sequence query(queryFile);
637 int numParentSeqs = chimeraTest.analyzeQuery(query.getName(), query.getAligned(), outChimeraReport);
638 int closestRefIndex = chimeraTest.getClosestRefIndex();
640 if(numParentSeqs > 1 && ignoreChimeras == 1) { ignoreSeq = 1; }
641 else { ignoreSeq = 0; }
643 Compare minCompare = getErrors(query, referenceSeqs[closestRefIndex]);
645 if(namesFileName != ""){
646 it = weights.find(query.getName());
647 minCompare.weight = it->second;
649 else{ minCompare.weight = 1; }
651 printErrorData(minCompare, numParentSeqs, errorSummaryFile, errorSeqFile);
655 for(int i=0;i<minCompare.sequence.length();i++){
656 char letter = minCompare.sequence[i];
658 errorForward[letter][i] += minCompare.weight;
659 errorReverse[letter][minCompare.total-i-1] += minCompare.weight;
663 if(qualFileName != "" && reportFileName != ""){
664 report = ReportFile(reportFile);
666 // int origLength = report.getQueryLength();
667 int startBase = report.getQueryStart();
668 int endBase = report.getQueryEnd();
670 quality = QualityScores(qualFile);
673 quality.updateQScoreErrorMap(qScoreErrorMap, minCompare.sequence, startBase, endBase, minCompare.weight);
674 quality.updateForwardMap(qualForwardMap, startBase, endBase, minCompare.weight);
675 quality.updateReverseMap(qualReverseMap, startBase, endBase, minCompare.weight);
679 if(minCompare.errorRate < threshold && !ignoreSeq){
680 totalBases += (minCompare.total * minCompare.weight);
681 totalMatches += minCompare.matches * minCompare.weight;
682 if(minCompare.mismatches > maxMismatch){
683 maxMismatch = minCompare.mismatches;
684 misMatchCounts.resize(maxMismatch + 1, 0);
686 misMatchCounts[minCompare.mismatches] += minCompare.weight;
689 megaAlignVector[closestRefIndex] += query.getInlineSeq() + '\n';
694 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
695 unsigned long int pos = queryFile.tellg();
696 if ((pos == -1) || (pos >= line.end)) { break; }
698 if (queryFile.eof()) { break; }
701 if(index % 100 == 0){ m->mothurOut(toString(index) + '\n'); }
704 if(qFileName != "" && rFileName != ""){ reportFile.close(); qualFile.close(); }
705 errorSummaryFile.close();
706 errorSeqFile.close();
709 if(index % 100 != 0){ m->mothurOut(toString(index) + '\n'); }
713 catch(exception& e) {
714 m->errorOut(e, "SeqErrorCommand", "driver");
718 //***************************************************************************************************************
720 void SeqErrorCommand::getReferences(){
723 ifstream referenceFile;
724 m->openInputFile(referenceFileName, referenceFile);
726 int numAmbigSeqs = 0;
729 int minEndPos = 100000;
731 while(referenceFile){
732 Sequence currentSeq(referenceFile);
733 int numAmbigs = currentSeq.getAmbigBases();
734 if(numAmbigs > 0){ numAmbigSeqs++; }
736 // int startPos = currentSeq.getStartPos();
737 // if(startPos > maxStartPos) { maxStartPos = startPos; }
739 // int endPos = currentSeq.getEndPos();
740 // if(endPos < minEndPos) { minEndPos = endPos; }
741 referenceSeqs.push_back(currentSeq);
743 m->gobble(referenceFile);
745 referenceFile.close();
746 numRefs = referenceSeqs.size();
749 for(int i=0;i<numRefs;i++){
750 referenceSeqs[i].padToPos(maxStartPos);
751 referenceSeqs[i].padFromPos(minEndPos);
754 if(numAmbigSeqs != 0){
755 m->mothurOut("Warning: " + toString(numAmbigSeqs) + " reference sequences have ambiguous bases, these bases will be ignored\n");
759 catch(exception& e) {
760 m->errorOut(e, "SeqErrorCommand", "getReferences");
765 //***************************************************************************************************************
767 Compare SeqErrorCommand::getErrors(Sequence query, Sequence reference){
769 if(query.getAlignLength() != reference.getAlignLength()){
770 m->mothurOut("Warning: " + toString(query.getName()) + " and " + toString(reference.getName()) + " are different lengths\n");
772 int alignLength = query.getAlignLength();
774 string q = query.getAligned();
775 string r = reference.getAligned();
780 for(int i=0;i<alignLength;i++){
781 if(r[i] != 'N' && q[i] != '.' && r[i] != '.' && (q[i] != '-' || r[i] != '-')){ // no missing data and no double gaps
785 if(r[i] == 'A'){ errors.AA++; errors.matches++; errors.sequence += 'm'; }
786 if(r[i] == 'T'){ errors.AT++; errors.sequence += 's'; }
787 if(r[i] == 'G'){ errors.AG++; errors.sequence += 's'; }
788 if(r[i] == 'C'){ errors.AC++; errors.sequence += 's'; }
789 if(r[i] == '-'){ errors.Ai++; errors.sequence += 'i'; }
791 else if(q[i] == 'T'){
792 if(r[i] == 'A'){ errors.TA++; errors.sequence += 's'; }
793 if(r[i] == 'T'){ errors.TT++; errors.matches++; errors.sequence += 'm'; }
794 if(r[i] == 'G'){ errors.TG++; errors.sequence += 's'; }
795 if(r[i] == 'C'){ errors.TC++; errors.sequence += 's'; }
796 if(r[i] == '-'){ errors.Ti++; errors.sequence += 'i'; }
798 else if(q[i] == 'G'){
799 if(r[i] == 'A'){ errors.GA++; errors.sequence += 's'; }
800 if(r[i] == 'T'){ errors.GT++; errors.sequence += 's'; }
801 if(r[i] == 'G'){ errors.GG++; errors.matches++; errors.sequence += 'm'; }
802 if(r[i] == 'C'){ errors.GC++; errors.sequence += 's'; }
803 if(r[i] == '-'){ errors.Gi++; errors.sequence += 'i'; }
805 else if(q[i] == 'C'){
806 if(r[i] == 'A'){ errors.CA++; errors.sequence += 's'; }
807 if(r[i] == 'T'){ errors.CT++; errors.sequence += 's'; }
808 if(r[i] == 'G'){ errors.CG++; errors.sequence += 's'; }
809 if(r[i] == 'C'){ errors.CC++; errors.matches++; errors.sequence += 'm'; }
810 if(r[i] == '-'){ errors.Ci++; errors.sequence += 'i'; }
812 else if(q[i] == 'N'){
813 if(r[i] == 'A'){ errors.NA++; errors.sequence += 'a'; }
814 if(r[i] == 'T'){ errors.NT++; errors.sequence += 'a'; }
815 if(r[i] == 'G'){ errors.NG++; errors.sequence += 'a'; }
816 if(r[i] == 'C'){ errors.NC++; errors.sequence += 'a'; }
817 if(r[i] == '-'){ errors.Ni++; errors.sequence += 'a'; }
819 else if(q[i] == '-' && r[i] != '-'){
820 if(r[i] == 'A'){ errors.dA++; errors.sequence += 'd'; }
821 if(r[i] == 'T'){ errors.dT++; errors.sequence += 'd'; }
822 if(r[i] == 'G'){ errors.dG++; errors.sequence += 'd'; }
823 if(r[i] == 'C'){ errors.dC++; errors.sequence += 'd'; }
828 else if(q[i] == '.' && r[i] != '.'){ // reference extends beyond query
829 if(started == 1){ break; }
831 else if(q[i] != '.' && r[i] == '.'){ // query extends beyond reference
832 if(started == 1){ break; }
834 else if(q[i] == '.' && r[i] == '.'){ // both are missing data
835 if(started == 1){ break; }
839 errors.mismatches = errors.total-errors.matches;
840 errors.errorRate = (double)(errors.total-errors.matches) / (double)errors.total;
841 errors.queryName = query.getName();
842 errors.refName = reference.getName();
846 catch(exception& e) {
847 m->errorOut(e, "SeqErrorCommand", "getErrors");
852 //***************************************************************************************************************
854 map<string, int> SeqErrorCommand::getWeights(){
856 m->openInputFile(namesFileName, nameFile);
859 string redundantSeqs;
860 map<string, int> nameCountMap;
863 nameFile >> seqName >> redundantSeqs;
864 nameCountMap[seqName] = m->getNumNames(redundantSeqs);
871 //***************************************************************************************************************
873 void SeqErrorCommand::printErrorHeader(ofstream& errorSummaryFile){
875 errorSummaryFile << "query\treference\tweight\t";
876 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";
877 errorSummaryFile << "insertions\tdeletions\tsubstitutions\tambig\tmatches\tmismatches\ttotal\terror\tnumparents\n";
879 errorSummaryFile << setprecision(6);
880 errorSummaryFile.setf(ios::fixed);
882 catch(exception& e) {
883 m->errorOut(e, "SeqErrorCommand", "printErrorHeader");
888 //***************************************************************************************************************
890 void SeqErrorCommand::printErrorData(Compare error, int numParentSeqs, ofstream& errorSummaryFile, ofstream& errorSeqFile){
893 errorSummaryFile << error.queryName << '\t' << error.refName << '\t' << error.weight << '\t';
894 errorSummaryFile << error.AA << '\t' << error.AT << '\t' << error.AG << '\t' << error.AC << '\t';
895 errorSummaryFile << error.TA << '\t' << error.TT << '\t' << error.TG << '\t' << error.TC << '\t';
896 errorSummaryFile << error.GA << '\t' << error.GT << '\t' << error.GG << '\t' << error.GC << '\t';
897 errorSummaryFile << error.CA << '\t' << error.CT << '\t' << error.CG << '\t' << error.CC << '\t';
898 errorSummaryFile << error.NA << '\t' << error.NT << '\t' << error.NG << '\t' << error.NC << '\t';
899 errorSummaryFile << error.Ai << '\t' << error.Ti << '\t' << error.Gi << '\t' << error.Ci << '\t' << error.Ni << '\t';
900 errorSummaryFile << error.dA << '\t' << error.dT << '\t' << error.dG << '\t' << error.dC << '\t';
902 errorSummaryFile << error.Ai + error.Ti + error.Gi + error.Ci << '\t'; //insertions
903 errorSummaryFile << error.dA + error.dT + error.dG + error.dC << '\t'; //deletions
904 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
905 errorSummaryFile << error.NA + error.NT + error.NG + error.NC + error.Ni << '\t'; //ambiguities
906 errorSummaryFile << error.matches << '\t' << error.mismatches << '\t' << error.total << '\t' << error.errorRate << '\t' << numParentSeqs << endl;
908 errorSeqFile << '>' << error.queryName << "\tref:" << error.refName << '\n' << error.sequence << endl;
910 int a=0; int t=1; int g=2; int c=3;
913 if(numParentSeqs == 1 || ignoreChimeras == 0){
914 substitutionMatrix[a][a] += error.weight * error.AA;
915 substitutionMatrix[a][t] += error.weight * error.TA;
916 substitutionMatrix[a][g] += error.weight * error.GA;
917 substitutionMatrix[a][c] += error.weight * error.CA;
918 substitutionMatrix[a][gap] += error.weight * error.dA;
919 substitutionMatrix[a][n] += error.weight * error.NA;
921 substitutionMatrix[t][a] += error.weight * error.AT;
922 substitutionMatrix[t][t] += error.weight * error.TT;
923 substitutionMatrix[t][g] += error.weight * error.GT;
924 substitutionMatrix[t][c] += error.weight * error.CT;
925 substitutionMatrix[t][gap] += error.weight * error.dT;
926 substitutionMatrix[t][n] += error.weight * error.NT;
928 substitutionMatrix[g][a] += error.weight * error.AG;
929 substitutionMatrix[g][t] += error.weight * error.TG;
930 substitutionMatrix[g][g] += error.weight * error.GG;
931 substitutionMatrix[g][c] += error.weight * error.CG;
932 substitutionMatrix[g][gap] += error.weight * error.dG;
933 substitutionMatrix[g][n] += error.weight * error.NG;
935 substitutionMatrix[c][a] += error.weight * error.AC;
936 substitutionMatrix[c][t] += error.weight * error.TC;
937 substitutionMatrix[c][g] += error.weight * error.GC;
938 substitutionMatrix[c][c] += error.weight * error.CC;
939 substitutionMatrix[c][gap] += error.weight * error.dC;
940 substitutionMatrix[c][n] += error.weight * error.NC;
942 substitutionMatrix[gap][a] += error.weight * error.Ai;
943 substitutionMatrix[gap][t] += error.weight * error.Ti;
944 substitutionMatrix[gap][g] += error.weight * error.Gi;
945 substitutionMatrix[gap][c] += error.weight * error.Ci;
946 substitutionMatrix[gap][n] += error.weight * error.Ni;
949 catch(exception& e) {
950 m->errorOut(e, "SeqErrorCommand", "printErrorData");
955 //***************************************************************************************************************
957 void SeqErrorCommand::printSubMatrix(){
959 string subMatrixFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.matrix";
960 ofstream subMatrixFile;
961 m->openOutputFile(subMatrixFileName, subMatrixFile);
962 outputNames.push_back(subMatrixFileName); outputTypes["error.matrix"].push_back(subMatrixFileName);
963 vector<string> bases(6);
970 vector<int> refSums(5,1);
972 for(int i=0;i<5;i++){
973 subMatrixFile << "\tr" << bases[i];
975 for(int j=0;j<6;j++){
976 refSums[i] += substitutionMatrix[i][j];
979 subMatrixFile << endl;
981 for(int i=0;i<6;i++){
982 subMatrixFile << 'q' << bases[i];
983 for(int j=0;j<5;j++){
984 subMatrixFile << '\t' << substitutionMatrix[j][i];
986 subMatrixFile << endl;
989 subMatrixFile << "total";
990 for(int i=0;i<5;i++){
991 subMatrixFile << '\t' << refSums[i];
993 subMatrixFile << endl;
994 subMatrixFile.close();
996 catch(exception& e) {
997 m->errorOut(e, "SeqErrorCommand", "printSubMatrix");
1001 //***************************************************************************************************************
1003 void SeqErrorCommand::printErrorFRFile(map<char, vector<int> > errorForward, map<char, vector<int> > errorReverse){
1005 string errorForwardFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq.forward";
1006 ofstream errorForwardFile;
1007 m->openOutputFile(errorForwardFileName, errorForwardFile);
1008 outputNames.push_back(errorForwardFileName); outputTypes["error.forward"].push_back(errorForwardFileName);
1010 errorForwardFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1011 for(int i=0;i<maxLength;i++){
1012 float match = (float)errorForward['m'][i];
1013 float subst = (float)errorForward['s'][i];
1014 float insert = (float)errorForward['i'][i];
1015 float del = (float)errorForward['d'][i];
1016 float amb = (float)errorForward['a'][i];
1017 float total = match + subst + insert + del + amb;
1018 if(total == 0){ break; }
1019 errorForwardFile << i+1 << '\t' << total << '\t' << match/total << '\t' << subst/total << '\t' << insert/total << '\t' << del/total << '\t' << amb/total << endl;
1021 errorForwardFile.close();
1023 string errorReverseFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq.reverse";
1024 ofstream errorReverseFile;
1025 m->openOutputFile(errorReverseFileName, errorReverseFile);
1026 outputNames.push_back(errorReverseFileName); outputTypes["error.reverse"].push_back(errorReverseFileName);
1028 errorReverseFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1029 for(int i=0;i<maxLength;i++){
1030 float match = (float)errorReverse['m'][i];
1031 float subst = (float)errorReverse['s'][i];
1032 float insert = (float)errorReverse['i'][i];
1033 float del = (float)errorReverse['d'][i];
1034 float amb = (float)errorReverse['a'][i];
1035 float total = match + subst + insert + del + amb;
1036 if(total == 0){ break; }
1037 errorReverseFile << i+1 << '\t' << total << '\t' << match/total << '\t' << subst/total << '\t' << insert/total << '\t' << del/total << '\t' << amb/total << endl;
1039 errorReverseFile.close();
1041 catch(exception& e) {
1042 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1047 //***************************************************************************************************************
1049 void SeqErrorCommand::printErrorQuality(map<char, vector<int> > qScoreErrorMap){
1052 string errorQualityFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.quality";
1053 ofstream errorQualityFile;
1054 m->openOutputFile(errorQualityFileName, errorQualityFile);
1055 outputNames.push_back(errorQualityFileName); outputTypes["error.quality"].push_back(errorQualityFileName);
1057 errorQualityFile << "qscore\tmatches\tsubstitutions\tinsertions\tambiguous" << endl;
1058 for(int i=0;i<41;i++){
1059 errorQualityFile << i << '\t' << qScoreErrorMap['m'][i] << '\t' << qScoreErrorMap['s'][i] << '\t' << qScoreErrorMap['i'][i] << '\t'<< qScoreErrorMap['a'][i] << endl;
1061 errorQualityFile.close();
1063 catch(exception& e) {
1064 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1070 //***************************************************************************************************************
1072 void SeqErrorCommand::printQualityFR(vector<vector<int> > qualForwardMap, vector<vector<int> > qualReverseMap){
1076 int numColumns = qualForwardMap[0].size();
1078 for(int i=0;i<qualForwardMap.size();i++){
1079 for(int j=0;j<numColumns;j++){
1080 if(qualForwardMap[i][j] != 0){
1081 if(numRows < i) { numRows = i+20; }
1086 string qualityForwardFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.qual.forward";
1087 ofstream qualityForwardFile;
1088 m->openOutputFile(qualityForwardFileName, qualityForwardFile);
1089 outputNames.push_back(qualityForwardFileName); outputTypes["error.qual.forward"].push_back(qualityForwardFileName);
1091 for(int i=0;i<numColumns;i++){ qualityForwardFile << '\t' << i; } qualityForwardFile << endl;
1093 for(int i=0;i<numRows;i++){
1094 qualityForwardFile << i+1;
1095 for(int j=0;j<numColumns;j++){
1096 qualityForwardFile << '\t' << qualForwardMap[i][j];
1099 qualityForwardFile << endl;
1101 qualityForwardFile.close();
1104 string qualityReverseFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.qual.reverse";
1105 ofstream qualityReverseFile;
1106 m->openOutputFile(qualityReverseFileName, qualityReverseFile);
1107 outputNames.push_back(qualityReverseFileName); outputTypes["error.qual.reverse"].push_back(qualityReverseFileName);
1109 for(int i=0;i<numColumns;i++){ qualityReverseFile << '\t' << i; } qualityReverseFile << endl;
1110 for(int i=0;i<numRows;i++){
1112 qualityReverseFile << i+1;
1113 for(int j=0;j<numColumns;j++){
1114 qualityReverseFile << '\t' << qualReverseMap[i][j];
1116 qualityReverseFile << endl;
1118 qualityReverseFile.close();
1120 catch(exception& e) {
1121 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1126 /**************************************************************************************************/
1128 int SeqErrorCommand::setLines(string filename, string qfilename, string rfilename, vector<unsigned long int>& fastaFilePos, vector<unsigned long int>& qfileFilePos, vector<unsigned long int>& rfileFilePos) {
1130 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1131 //set file positions for fasta file
1132 fastaFilePos = m->divideFile(filename, processors);
1134 if (qfilename == "") { return processors; }
1136 //get name of first sequence in each chunk
1137 map<string, int> firstSeqNames;
1138 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
1140 m->openInputFile(filename, in);
1141 in.seekg(fastaFilePos[i]);
1144 firstSeqNames[temp.getName()] = i;
1149 //make copy to use below
1150 map<string, int> firstSeqNamesReport = firstSeqNames;
1152 //seach for filePos of each first name in the qfile and save in qfileFilePos
1154 m->openInputFile(qfilename, inQual);
1157 while(!inQual.eof()){
1158 input = m->getline(inQual);
1160 if (input.length() != 0) {
1161 if(input[0] == '>'){ //this is a sequence name line
1162 istringstream nameStream(input);
1164 string sname = ""; nameStream >> sname;
1165 sname = sname.substr(1);
1167 map<string, int>::iterator it = firstSeqNames.find(sname);
1169 if(it != firstSeqNames.end()) { //this is the start of a new chunk
1170 unsigned long int pos = inQual.tellg();
1171 qfileFilePos.push_back(pos - input.length() - 1);
1172 firstSeqNames.erase(it);
1177 if (firstSeqNames.size() == 0) { break; }
1181 if (firstSeqNames.size() != 0) {
1182 for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
1183 m->mothurOut(it->first + " is in your fasta file and not in your quality file, aborting."); m->mothurOutEndLine();
1185 m->control_pressed = true;
1189 //get last file position of qfile
1191 unsigned long int size;
1193 //get num bytes in file
1194 pFile = fopen (qfilename.c_str(),"rb");
1195 if (pFile==NULL) perror ("Error opening file");
1197 fseek (pFile, 0, SEEK_END);
1202 qfileFilePos.push_back(size);
1204 //seach for filePos of each first name in the rfile and save in rfileFilePos
1207 m->openInputFile(rfilename, inR);
1209 //read column headers
1210 for (int i = 0; i < 16; i++) {
1211 if (!inR.eof()) { inR >> junk; }
1217 if (m->control_pressed) { inR.close(); return processors; }
1219 input = m->getline(inR);
1221 if (input.length() != 0) {
1223 istringstream nameStream(input);
1224 string sname = ""; nameStream >> sname;
1226 map<string, int>::iterator it = firstSeqNamesReport.find(sname);
1228 if(it != firstSeqNamesReport.end()) { //this is the start of a new chunk
1229 unsigned long int pos = inR.tellg();
1230 rfileFilePos.push_back(pos - input.length() - 1);
1231 firstSeqNamesReport.erase(it);
1235 if (firstSeqNamesReport.size() == 0) { break; }
1240 if (firstSeqNamesReport.size() != 0) {
1241 for (map<string, int>::iterator it = firstSeqNamesReport.begin(); it != firstSeqNamesReport.end(); it++) {
1242 m->mothurOut(it->first + " is in your fasta file and not in your report file, aborting."); m->mothurOutEndLine();
1244 m->control_pressed = true;
1248 //get last file position of qfile
1250 unsigned long int sizeR;
1252 //get num bytes in file
1253 rFile = fopen (rfilename.c_str(),"rb");
1254 if (rFile==NULL) perror ("Error opening file");
1256 fseek (rFile, 0, SEEK_END);
1257 sizeR=ftell (rFile);
1261 rfileFilePos.push_back(sizeR);
1267 fastaFilePos.push_back(0); qfileFilePos.push_back(0);
1268 //get last file position of fastafile
1270 unsigned long int size;
1272 //get num bytes in file
1273 pFile = fopen (filename.c_str(),"rb");
1274 if (pFile==NULL) perror ("Error opening file");
1276 fseek (pFile, 0, SEEK_END);
1280 fastaFilePos.push_back(size);
1282 //get last file position of fastafile
1285 //get num bytes in file
1286 qFile = fopen (qfilename.c_str(),"rb");
1287 if (qFile==NULL) perror ("Error opening file");
1289 fseek (qFile, 0, SEEK_END);
1293 qfileFilePos.push_back(size);
1299 catch(exception& e) {
1300 m->errorOut(e, "SeqErrorCommand", "setLines");
1304 //***************************************************************************************************************