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 "myPerseus.h"
15 #include "filterseqscommand.h"
18 //**********************************************************************************************************************
20 vector<string> SeqErrorCommand::setParameters(){
22 CommandParameter pquery("fasta", "InputTypes", "", "", "none", "none", "none","errorType",false,true,true); parameters.push_back(pquery);
23 CommandParameter preference("reference", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(preference);
24 CommandParameter pqfile("qfile", "InputTypes", "", "", "none", "none", "QualReport","",false,false); parameters.push_back(pqfile);
25 CommandParameter preport("report", "InputTypes", "", "", "none", "none", "QualReport","",false,false); parameters.push_back(preport);
26 CommandParameter pname("name", "InputTypes", "", "", "namecount", "none", "none","",false,false,true); parameters.push_back(pname);
27 CommandParameter pcount("count", "InputTypes", "", "", "namecount", "none", "none","",false,false,true); parameters.push_back(pcount);
28 CommandParameter pignorechimeras("ignorechimeras", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(pignorechimeras);
29 CommandParameter pthreshold("threshold", "Number", "", "1.0", "", "", "","",false,false); parameters.push_back(pthreshold);
30 CommandParameter paligned("aligned", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(paligned);
31 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
32 CommandParameter psave("save", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psave);
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, "SeqErrorCommand", "setParameters");
46 //**********************************************************************************************************************
48 string SeqErrorCommand::getHelpString(){
50 string helpString = "";
51 helpString += "The seq.error command reads a query alignment file and a reference alignment file and creates .....\n";
52 helpString += "The fasta parameter...\n";
53 helpString += "The reference parameter...\n";
54 helpString += "The qfile parameter...\n";
55 helpString += "The report parameter...\n";
56 helpString += "The name parameter allows you to provide a name file associated with the fasta file.\n";
57 helpString += "The count parameter allows you to provide a count file associated with the fasta file.\n";
58 helpString += "The ignorechimeras parameter...\n";
59 helpString += "The threshold parameter...\n";
60 helpString += "The processors parameter...\n";
61 helpString += "If the save parameter is set to true the reference sequences will be saved in memory, to clear them later you can use the clear.memory command. Default=f.";
62 helpString += "Example seq.error(...).\n";
63 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
64 helpString += "For more details please check out the wiki http://www.mothur.org/wiki/seq.error .\n";
68 m->errorOut(e, "SeqErrorCommand", "getHelpString");
73 //**********************************************************************************************************************
75 string SeqErrorCommand::getOutputPattern(string type) {
79 if (type == "errorsummary") { pattern = "[filename],error.summary"; }
80 else if (type == "errorseq") { pattern = "[filename],error.seq"; }
81 else if (type == "errorquality") { pattern = "[filename],error.quality"; }
82 else if (type == "errorqualforward") { pattern = "[filename],error.qual.forward"; }
83 else if (type == "errorqualreverse") { pattern = "[filename],error.qual.reverse"; }
84 else if (type == "errorforward") { pattern = "[filename],error.seq.forward"; }
85 else if (type == "errorreverse") { pattern = "[filename],error.seq.reverse"; }
86 else if (type == "errorcount") { pattern = "[filename],error.count"; }
87 else if (type == "errormatrix") { pattern = "[filename],error.matrix"; }
88 else if (type == "errorchimera") { pattern = "[filename],error.chimera"; }
89 else if (type == "errorref-query") { pattern = "[filename],error.ref-query"; }
90 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
95 m->errorOut(e, "SeqErrorCommand", "getOutputPattern");
100 //**********************************************************************************************************************
102 SeqErrorCommand::SeqErrorCommand(){
104 abort = true; calledHelp = true;
106 vector<string> tempOutNames;
107 outputTypes["errorsummary"] = tempOutNames;
108 outputTypes["errorseq"] = tempOutNames;
109 outputTypes["errorquality"] = tempOutNames;
110 outputTypes["errorqualforward"] = tempOutNames;
111 outputTypes["errorqualreverse"] = tempOutNames;
112 outputTypes["errorforward"] = tempOutNames;
113 outputTypes["errorreverse"] = tempOutNames;
114 outputTypes["errorcount"] = tempOutNames;
115 outputTypes["errormatrix"] = tempOutNames;
116 outputTypes["errorchimera"] = tempOutNames;
117 outputTypes["errorref-query"] = tempOutNames;
119 catch(exception& e) {
120 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
125 //***************************************************************************************************************
127 SeqErrorCommand::SeqErrorCommand(string option) {
130 abort = false; calledHelp = false;
131 rdb = ReferenceDB::getInstance();
133 //allow user to run help
134 if(option == "help") { help(); abort = true; calledHelp = true; }
135 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
139 vector<string> myArray = setParameters();
141 OptionParser parser(option);
142 map<string,string> parameters = parser.getParameters();
144 ValidParameters validParameter;
145 map<string,string>::iterator it;
147 //check to make sure all parameters are valid for command
148 for (it = parameters.begin(); it != parameters.end(); it++) {
149 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
152 //initialize outputTypes
153 vector<string> tempOutNames;
154 outputTypes["errorsummary"] = tempOutNames;
155 outputTypes["errorseq"] = tempOutNames;
156 outputTypes["errorquality"] = tempOutNames;
157 outputTypes["errorqualforward"] = tempOutNames;
158 outputTypes["errorqualreverse"] = tempOutNames;
159 outputTypes["errorforward"] = tempOutNames;
160 outputTypes["errorreverse"] = tempOutNames;
161 outputTypes["errorcount"] = tempOutNames;
162 outputTypes["errormatrix"] = tempOutNames;
163 outputTypes["errorchimera"] = tempOutNames;
164 outputTypes["errorref-query"] = tempOutNames;
167 //if the user changes the input directory command factory will send this info to us in the output parameter
168 string inputDir = validParameter.validFile(parameters, "inputdir", false);
169 if (inputDir == "not found"){ inputDir = ""; }
172 it = parameters.find("fasta");
173 //user has given a template file
174 if(it != parameters.end()){
175 path = m->hasPath(it->second);
176 //if the user has not given a path then, add inputdir. else leave path alone.
177 if (path == "") { parameters["fasta"] = inputDir + it->second; }
180 it = parameters.find("reference");
181 //user has given a template file
182 if(it != parameters.end()){
183 path = m->hasPath(it->second);
184 //if the user has not given a path then, add inputdir. else leave path alone.
185 if (path == "") { parameters["reference"] = inputDir + it->second; }
188 it = parameters.find("name");
189 //user has given a names file
190 if(it != parameters.end()){
191 path = m->hasPath(it->second);
192 //if the user has not given a path then, add inputdir. else leave path alone.
193 if (path == "") { parameters["name"] = inputDir + it->second; }
196 it = parameters.find("count");
197 //user has given a names file
198 if(it != parameters.end()){
199 path = m->hasPath(it->second);
200 //if the user has not given a path then, add inputdir. else leave path alone.
201 if (path == "") { parameters["count"] = inputDir + it->second; }
204 it = parameters.find("qfile");
205 //user has given a quality score file
206 if(it != parameters.end()){
207 path = m->hasPath(it->second);
208 //if the user has not given a path then, add inputdir. else leave path alone.
209 if (path == "") { parameters["qfile"] = inputDir + it->second; }
212 it = parameters.find("report");
213 //user has given a alignment report file
214 if(it != parameters.end()){
215 path = m->hasPath(it->second);
216 //if the user has not given a path then, add inputdir. else leave path alone.
217 if (path == "") { parameters["report"] = inputDir + it->second; }
221 //check for required parameters
222 queryFileName = validParameter.validFile(parameters, "fasta", true);
223 if (queryFileName == "not found") {
224 queryFileName = m->getFastaFile();
225 if (queryFileName != "") { m->mothurOut("Using " + queryFileName + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
226 else { m->mothurOut("You have no current fasta file and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
228 else if (queryFileName == "not open") { queryFileName = ""; abort = true; }
229 else { m->setFastaFile(queryFileName); }
231 referenceFileName = validParameter.validFile(parameters, "reference", true);
232 if (referenceFileName == "not found") { m->mothurOut("reference is a required parameter for the seq.error command."); m->mothurOutEndLine(); abort = true; }
233 else if (referenceFileName == "not open") { abort = true; }
235 //check for optional parameters
236 namesFileName = validParameter.validFile(parameters, "name", true);
237 if(namesFileName == "not found"){ namesFileName = ""; }
238 else if (namesFileName == "not open") { namesFileName = ""; abort = true; }
239 else { m->setNameFile(namesFileName); }
241 //check for optional parameters
242 countfile = validParameter.validFile(parameters, "count", true);
243 if(countfile == "not found"){ countfile = ""; }
244 else if (countfile == "not open") { countfile = ""; abort = true; }
245 else { m->setCountTableFile(countfile); }
247 qualFileName = validParameter.validFile(parameters, "qfile", true);
248 if(qualFileName == "not found"){ qualFileName = ""; }
249 else if (qualFileName == "not open") { qualFileName = ""; abort = true; }
250 else { m->setQualFile(qualFileName); }
252 reportFileName = validParameter.validFile(parameters, "report", true);
253 if(reportFileName == "not found"){ reportFileName = ""; }
254 else if (reportFileName == "not open") { reportFileName = ""; abort = true; }
256 outputDir = validParameter.validFile(parameters, "outputdir", false);
257 if (outputDir == "not found"){
259 outputDir += m->hasPath(queryFileName); //if user entered a file with a path then preserve it
262 if ((countfile != "") && (namesFileName != "")) { m->mothurOut("You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
264 //check for optional parameter and set defaults
265 // ...at some point should added some additional type checking...
266 temp = validParameter.validFile(parameters, "threshold", false); if (temp == "not found") { temp = "1.00"; }
267 m->mothurConvert(temp, threshold);
270 temp = validParameter.validFile(parameters, "save", false); if (temp == "not found"){ temp = "f"; }
271 save = m->isTrue(temp);
273 if (save) { //clear out old references
277 //this has to go after save so that if the user sets save=t and provides no reference we abort
278 referenceFileName = validParameter.validFile(parameters, "reference", true);
279 if (referenceFileName == "not found") {
280 //check for saved reference sequences
281 if (rdb->referenceSeqs.size() != 0) {
282 referenceFileName = "saved";
284 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
285 m->mothurOutEndLine();
288 }else if (referenceFileName == "not open") { abort = true; }
289 else { if (save) { rdb->setSavedReference(referenceFileName); } }
292 temp = validParameter.validFile(parameters, "ignorechimeras", false); if (temp == "not found") { temp = "T"; }
293 ignoreChimeras = m->isTrue(temp);
295 temp = validParameter.validFile(parameters, "aligned", false); if (temp == "not found"){ temp = "t"; }
296 aligned = m->isTrue(temp);
298 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
299 m->setProcessors(temp);
300 m->mothurConvert(temp, processors);
302 substitutionMatrix.resize(6);
303 for(int i=0;i<6;i++){ substitutionMatrix[i].resize(6,0); }
305 if ((namesFileName == "") && (queryFileName != "")){
306 vector<string> files; files.push_back(queryFileName);
307 parser.getNameFile(files);
311 if((reportFileName != "" && qualFileName == "") || (reportFileName == "" && qualFileName != "")){
312 m->mothurOut("if you use either a qual file or a report file, you have to have both.");
313 m->mothurOutEndLine();
318 if(reportFileName != ""){
319 m->mothurOut("we are ignoring the report file if your sequences are not aligned. we will check that the sequences in your fasta and and qual file are the same length.");
320 m->mothurOutEndLine();
327 catch(exception& e) {
328 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
333 //***************************************************************************************************************
335 int SeqErrorCommand::execute(){
337 if (abort == true) { if (calledHelp) { return 0; } return 2; }
339 int start = time(NULL);
344 string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
345 map<string, string> variables;
346 variables["[filename]"] = fileNameRoot;
347 string errorSummaryFileName = getOutputFileName("errorsummary",variables);
348 outputNames.push_back(errorSummaryFileName); outputTypes["errorsummary"].push_back(errorSummaryFileName);
350 string errorSeqFileName = getOutputFileName("errorseq",variables);
351 outputNames.push_back(errorSeqFileName); outputTypes["errorseq"].push_back(errorSeqFileName);
353 string errorChimeraFileName = getOutputFileName("errorchimera",variables);
354 outputNames.push_back(errorChimeraFileName); outputTypes["errorchimera"].push_back(errorChimeraFileName);
356 getReferences(); //read in reference sequences - make sure there's no ambiguous bases
358 if(namesFileName != "") { weights = getWeights(); }
359 else if (countfile != "") {
361 ct.readTable(countfile, false, false);
362 weights = ct.getNameMap();
365 vector<unsigned long long> fastaFilePos;
366 vector<unsigned long long> qFilePos;
367 vector<unsigned long long> reportFilePos;
369 setLines(queryFileName, qualFileName, reportFileName, fastaFilePos, qFilePos, reportFilePos);
371 if (m->control_pressed) { return 0; }
373 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
374 lines.push_back(linePair(fastaFilePos[i], fastaFilePos[(i+1)]));
375 if (qualFileName != "") { qLines.push_back(linePair(qFilePos[i], qFilePos[(i+1)])); }
376 if (reportFileName != "" && aligned == true) { rLines.push_back(linePair(reportFilePos[i], reportFilePos[(i+1)])); }
378 if(qualFileName == "") { qLines = lines; rLines = lines; } //fills with duds
379 if(aligned == false){ rLines = lines; }
381 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
383 numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
386 numSeqs = createProcesses(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName);
389 numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
392 if(qualFileName != ""){
393 printErrorQuality(qScoreErrorMap);
394 printQualityFR(qualForwardMap, qualReverseMap);
397 printErrorFRFile(errorForward, errorReverse);
399 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
401 string errorCountFileName = getOutputFileName("errorcount",variables);
402 ofstream errorCountFile;
403 m->openOutputFile(errorCountFileName, errorCountFile);
404 outputNames.push_back(errorCountFileName); outputTypes["errorcount"].push_back(errorCountFileName);
405 m->mothurOut("Overall error rate:\t" + toString((double)(totalBases - totalMatches) / (double)totalBases) + "\n");
406 m->mothurOut("Errors\tSequences\n");
407 errorCountFile << "Errors\tSequences\n";
408 for(int i=0;i<misMatchCounts.size();i++){
409 m->mothurOut(toString(i) + '\t' + toString(misMatchCounts[i]) + '\n');
410 errorCountFile << i << '\t' << misMatchCounts[i] << endl;
412 errorCountFile.close();
414 // if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
418 string megAlignmentFileName = getOutputFileName("errorref-query",variables);
419 ofstream megAlignmentFile;
420 m->openOutputFile(megAlignmentFileName, megAlignmentFile);
421 outputNames.push_back(megAlignmentFileName); outputTypes["errorref-query"].push_back(megAlignmentFileName);
423 for(int i=0;i<numRefs;i++){
424 megAlignmentFile << referenceSeqs[i].getInlineSeq() << endl;
425 megAlignmentFile << megaAlignVector[i] << endl;
427 megAlignmentFile.close();
430 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences.");
431 m->mothurOutEndLine();
433 m->mothurOutEndLine();
434 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
435 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
436 m->mothurOutEndLine();
440 catch(exception& e) {
441 m->errorOut(e, "SeqErrorCommand", "execute");
446 //**********************************************************************************************************************
448 int SeqErrorCommand::createProcesses(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName) {
452 map<char, vector<int> >::iterator it;
454 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
456 //loop through and create all the processes you want
457 while (process != processors) {
461 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
465 num = driver(filename, qFileName, rFileName, summaryFileName + m->mothurGetpid(process) + ".temp", errorOutputFileName+ m->mothurGetpid(process) + ".temp", chimeraOutputFileName + m->mothurGetpid(process) + ".temp", lines[process], qLines[process], rLines[process]);
467 //pass groupCounts to parent
469 string tempFile = filename + m->mothurGetpid(process) + ".info.temp";
470 m->openOutputFile(tempFile, out);
472 //output totalBases and totalMatches
473 out << num << '\t' << totalBases << '\t' << totalMatches << endl << endl;
475 //output substitutionMatrix
476 for(int i = 0; i < substitutionMatrix.size(); i++) {
477 for (int j = 0; j < substitutionMatrix[i].size(); j++) {
478 out << substitutionMatrix[i][j] << '\t';
484 //output qScoreErrorMap
485 for (it = qScoreErrorMap.begin(); it != qScoreErrorMap.end(); it++) {
486 vector<int> thisScoreErrorMap = it->second;
487 out << it->first << '\t';
488 for (int i = 0; i < thisScoreErrorMap.size(); i++) {
489 out << thisScoreErrorMap[i] << '\t';
495 //output qualForwardMap
496 for(int i = 0; i < qualForwardMap.size(); i++) {
497 for (int j = 0; j < qualForwardMap[i].size(); j++) {
498 out << qualForwardMap[i][j] << '\t';
504 //output qualReverseMap
505 for(int i = 0; i < qualReverseMap.size(); i++) {
506 for (int j = 0; j < qualReverseMap[i].size(); j++) {
507 out << qualReverseMap[i][j] << '\t';
514 //output errorForward
515 for (it = errorForward.begin(); it != errorForward.end(); it++) {
516 vector<int> thisErrorForward = it->second;
517 out << it->first << '\t';
518 for (int i = 0; i < thisErrorForward.size(); i++) {
519 out << thisErrorForward[i] << '\t';
525 //output errorReverse
526 for (it = errorReverse.begin(); it != errorReverse.end(); it++) {
527 vector<int> thisErrorReverse = it->second;
528 out << it->first << '\t';
529 for (int i = 0; i < thisErrorReverse.size(); i++) {
530 out << thisErrorReverse[i] << '\t';
536 //output misMatchCounts
537 out << misMatchCounts.size() << endl;
538 for (int j = 0; j < misMatchCounts.size(); j++) {
539 out << misMatchCounts[j] << '\t';
544 //output megaAlignVector
545 for (int j = 0; j < megaAlignVector.size(); j++) {
546 out << megaAlignVector[j] << endl;
554 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
555 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
561 num = driver(filename, qFileName, rFileName, summaryFileName, errorOutputFileName, chimeraOutputFileName, lines[0], qLines[0], rLines[0]);
563 //force parent to wait until all the processes are done
564 for (int i=0;i<processIDS.size();i++) {
565 int temp = processIDS[i];
570 for(int i=0;i<processIDS.size();i++){
572 m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
574 m->appendFiles((summaryFileName + toString(processIDS[i]) + ".temp"), summaryFileName);
575 m->mothurRemove((summaryFileName + toString(processIDS[i]) + ".temp"));
576 m->appendFiles((errorOutputFileName + toString(processIDS[i]) + ".temp"), errorOutputFileName);
577 m->mothurRemove((errorOutputFileName + toString(processIDS[i]) + ".temp"));
578 m->appendFiles((chimeraOutputFileName + toString(processIDS[i]) + ".temp"), chimeraOutputFileName);
579 m->mothurRemove((chimeraOutputFileName + toString(processIDS[i]) + ".temp"));
582 string tempFile = filename + toString(processIDS[i]) + ".info.temp";
583 m->openInputFile(tempFile, in);
585 //input totalBases and totalMatches
586 int tempBases, tempMatches, tempNumSeqs;
587 in >> tempNumSeqs >> tempBases >> tempMatches; m->gobble(in);
588 totalBases += tempBases; totalMatches += tempMatches; num += tempNumSeqs;
590 //input substitutionMatrix
592 for(int i = 0; i < substitutionMatrix.size(); i++) {
593 for (int j = 0; j < substitutionMatrix[i].size(); j++) {
594 in >> tempNum; substitutionMatrix[i][j] += tempNum;
600 //input qScoreErrorMap
602 for (int i = 0; i < qScoreErrorMap.size(); i++) {
604 vector<int> thisScoreErrorMap = qScoreErrorMap[first];
606 for (int i = 0; i < thisScoreErrorMap.size(); i++) {
607 in >> tempNum; thisScoreErrorMap[i] += tempNum;
609 qScoreErrorMap[first] = thisScoreErrorMap;
614 //input qualForwardMap
615 for(int i = 0; i < qualForwardMap.size(); i++) {
616 for (int j = 0; j < qualForwardMap[i].size(); j++) {
617 in >> tempNum; qualForwardMap[i][j] += tempNum;
623 //input qualReverseMap
624 for(int i = 0; i < qualReverseMap.size(); i++) {
625 for (int j = 0; j < qualReverseMap[i].size(); j++) {
626 in >> tempNum; qualReverseMap[i][j] += tempNum;
633 for (int i = 0; i < errorForward.size(); i++) {
635 vector<int> thisErrorForward = errorForward[first];
637 for (int i = 0; i < thisErrorForward.size(); i++) {
638 in >> tempNum; thisErrorForward[i] += tempNum;
640 errorForward[first] = thisErrorForward;
646 for (int i = 0; i < errorReverse.size(); i++) {
648 vector<int> thisErrorReverse = errorReverse[first];
650 for (int i = 0; i < thisErrorReverse.size(); i++) {
651 in >> tempNum; thisErrorReverse[i] += tempNum;
653 errorReverse[first] = thisErrorReverse;
658 //input misMatchCounts
660 in >> misMatchSize; m->gobble(in);
661 if (misMatchSize > misMatchCounts.size()) { misMatchCounts.resize(misMatchSize, 0); }
662 for (int j = 0; j < misMatchSize; j++) {
663 in >> tempNum; misMatchCounts[j] += tempNum;
667 //input megaAlignVector
669 for (int j = 0; j < megaAlignVector.size(); j++) {
670 thisLine = m->getline(in); m->gobble(in); megaAlignVector[j] += thisLine + '\n';
674 in.close(); m->mothurRemove(tempFile);
680 catch(exception& e) {
681 m->errorOut(e, "SeqErrorCommand", "createProcesses");
686 //**********************************************************************************************************************
688 int SeqErrorCommand::driver(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName, linePair line, linePair qline, linePair rline) {
692 QualityScores quality;
694 misMatchCounts.resize(11, 0);
698 map<string, int>::iterator it;
699 qScoreErrorMap['m'].assign(101, 0);
700 qScoreErrorMap['s'].assign(101, 0);
701 qScoreErrorMap['i'].assign(101, 0);
702 qScoreErrorMap['a'].assign(101, 0);
704 errorForward['m'].assign(maxLength,0);
705 errorForward['s'].assign(maxLength,0);
706 errorForward['i'].assign(maxLength,0);
707 errorForward['d'].assign(maxLength,0);
708 errorForward['a'].assign(maxLength,0);
710 errorReverse['m'].assign(maxLength,0);
711 errorReverse['s'].assign(maxLength,0);
712 errorReverse['i'].assign(maxLength,0);
713 errorReverse['d'].assign(maxLength,0);
714 errorReverse['a'].assign(maxLength,0);
716 //open inputfiles and go to beginning place for this processor
718 m->openInputFile(filename, queryFile);
720 queryFile.seekg(line.start);
724 if((qFileName != "" && rFileName != "" && aligned)){
725 m->openInputFile(qFileName, qualFile);
726 qualFile.seekg(qline.start);
729 if (rline.start == 0) { report = ReportFile(reportFile, rFileName); }
731 m->openInputFile(rFileName, reportFile);
732 reportFile.seekg(rline.start);
735 qualForwardMap.resize(maxLength);
736 qualReverseMap.resize(maxLength);
737 for(int i=0;i<maxLength;i++){
738 qualForwardMap[i].assign(101,0);
739 qualReverseMap[i].assign(101,0);
742 else if(qFileName != "" && !aligned){
744 m->openInputFile(qFileName, qualFile);
745 qualFile.seekg(qline.start);
747 qualForwardMap.resize(maxLength);
748 qualReverseMap.resize(maxLength);
749 for(int i=0;i<maxLength;i++){
750 qualForwardMap[i].assign(101,0);
751 qualReverseMap[i].assign(101,0);
755 ofstream outChimeraReport;
756 m->openOutputFile(chimeraOutputFileName, outChimeraReport);
759 RefChimeraTest chimeraTest;
761 chimeraTest = RefChimeraTest(referenceSeqs, aligned);
762 if (line.start == 0) { chimeraTest.printHeader(outChimeraReport); }
765 ofstream errorSummaryFile;
766 m->openOutputFile(summaryFileName, errorSummaryFile);
767 if (line.start == 0) { printErrorHeader(errorSummaryFile); }
769 ofstream errorSeqFile;
770 m->openOutputFile(errorOutputFileName, errorSeqFile);
772 megaAlignVector.assign(numRefs, "");
780 Sequence query(queryFile);
782 int numParentSeqs = -1;
783 int closestRefIndex = -1;
785 string querySeq = query.getAligned();
786 if (!aligned) { querySeq = query.getUnaligned(); }
788 numParentSeqs = chimeraTest.analyzeQuery(query.getName(), querySeq, outChimeraReport);
790 closestRefIndex = chimeraTest.getClosestRefIndex();
792 reference = referenceSeqs[closestRefIndex];
794 reference.setAligned(chimeraTest.getClosestRefAlignment());
795 query.setAligned(chimeraTest.getQueryAlignment());
797 if(numParentSeqs > 1 && ignoreChimeras == 1) { ignoreSeq = 1; }
798 else { ignoreSeq = 0; }
802 getErrors(query, reference, minCompare);
804 if((namesFileName != "") || (countfile != "")){
805 it = weights.find(query.getName());
806 minCompare.weight = it->second;
808 else{ minCompare.weight = 1; }
811 printErrorData(minCompare, numParentSeqs, errorSummaryFile, errorSeqFile);
814 for(int i=0;i<minCompare.sequence.length();i++){
815 char letter = minCompare.sequence[i];
817 errorForward[letter][i] += minCompare.weight;
818 errorReverse[letter][minCompare.total-i-1] += minCompare.weight;
823 if(aligned && qualFileName != "" && reportFileName != ""){
824 report = ReportFile(reportFile);
826 // int origLength = report.getQueryLength();
827 int startBase = report.getQueryStart();
828 int endBase = report.getQueryEnd();
830 quality = QualityScores(qualFile);
833 quality.updateQScoreErrorMap(qScoreErrorMap, minCompare.sequence, startBase, endBase, minCompare.weight);
834 quality.updateForwardMap(qualForwardMap, startBase, endBase, minCompare.weight);
835 quality.updateReverseMap(qualReverseMap, startBase, endBase, minCompare.weight);
838 else if(aligned == false && qualFileName != ""){
840 quality = QualityScores(qualFile);
841 int qualityLength = quality.getLength();
843 if(qualityLength != query.getNumBases()){ cout << "warning - quality and fasta sequence files do not match at " << query.getName() << '\t' << qualityLength <<'\t' << query.getNumBases() << endl; }
846 int endBase = qualityLength;
849 quality.updateQScoreErrorMap(qScoreErrorMap, minCompare.sequence, startBase, endBase, minCompare.weight);
850 quality.updateForwardMap(qualForwardMap, startBase, endBase, minCompare.weight);
851 quality.updateReverseMap(qualReverseMap, startBase, endBase, minCompare.weight);
855 if(minCompare.errorRate <= threshold && !ignoreSeq){
856 totalBases += (minCompare.total * minCompare.weight);
857 totalMatches += minCompare.matches * minCompare.weight;
858 if(minCompare.mismatches > maxMismatch){
859 maxMismatch = minCompare.mismatches;
860 misMatchCounts.resize(maxMismatch + 1, 0);
862 misMatchCounts[minCompare.mismatches] += minCompare.weight;
865 megaAlignVector[closestRefIndex] += query.getInlineSeq() + '\n';
870 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
871 unsigned long long pos = queryFile.tellg();
872 if ((pos == -1) || (pos >= line.end)) { break; }
874 if (queryFile.eof()) { break; }
877 if(index % 100 == 0){ m->mothurOutJustToScreen(toString(index)+"\n"); }
880 outChimeraReport.close();
881 errorSummaryFile.close();
882 errorSeqFile.close();
884 if(qFileName != "" && rFileName != "") { reportFile.close(); qualFile.close(); }
885 else if(qFileName != "" && aligned == false){ qualFile.close(); }
888 m->mothurOutJustToScreen(toString(index)+"\n");
892 catch(exception& e) {
893 m->errorOut(e, "SeqErrorCommand", "driver");
898 //***************************************************************************************************************
900 void SeqErrorCommand::getReferences(){
902 int numAmbigSeqs = 0;
905 int minEndPos = 100000;
907 if (referenceFileName == "saved") {
908 int start = time(NULL);
909 m->mothurOutEndLine(); m->mothurOut("Using sequences from " + rdb->getSavedReference() + " that are saved in memory."); m->mothurOutEndLine();
911 for (int i = 0; i < rdb->referenceSeqs.size(); i++) {
912 int numAmbigs = rdb->referenceSeqs[i].getAmbigBases();
913 if(numAmbigs > 0){ numAmbigSeqs++; }
915 // int startPos = rdb->referenceSeqs[i].getStartPos();
916 // if(startPos > maxStartPos) { maxStartPos = startPos; }
918 // int endPos = rdb->referenceSeqs[i].getEndPos();
919 // if(endPos < minEndPos) { minEndPos = endPos; }
920 if (rdb->referenceSeqs[i].getNumBases() == 0) {
921 m->mothurOut("[WARNING]: " + rdb->referenceSeqs[i].getName() + " is blank, ignoring.");m->mothurOutEndLine();
923 referenceSeqs.push_back(rdb->referenceSeqs[i]);
927 referenceFileName = rdb->getSavedReference();
929 m->mothurOut("It took " + toString(time(NULL) - start) + " to load " + toString(referenceSeqs.size()) + " sequences.");m->mothurOutEndLine();
932 int start = time(NULL);
934 ifstream referenceFile;
935 m->openInputFile(referenceFileName, referenceFile);
937 while(referenceFile){
938 Sequence currentSeq(referenceFile);
939 int numAmbigs = currentSeq.getAmbigBases();
940 if(numAmbigs > 0){ numAmbigSeqs++; }
942 // int startPos = currentSeq.getStartPos();
943 // if(startPos > maxStartPos) { maxStartPos = startPos; }
945 // int endPos = currentSeq.getEndPos();
946 // if(endPos < minEndPos) { minEndPos = endPos; }
947 if (currentSeq.getNumBases() == 0) {
948 m->mothurOut("[WARNING]: " + currentSeq.getName() + " is blank, ignoring.");m->mothurOutEndLine();
950 referenceSeqs.push_back(currentSeq);
951 if (rdb->save) { rdb->referenceSeqs.push_back(currentSeq); }
954 m->gobble(referenceFile);
956 referenceFile.close();
958 m->mothurOut("It took " + toString(time(NULL) - start) + " to read " + toString(referenceSeqs.size()) + " sequences.");m->mothurOutEndLine();
961 numRefs = referenceSeqs.size();
963 for(int i=0;i<numRefs;i++){
964 referenceSeqs[i].padToPos(maxStartPos);
965 referenceSeqs[i].padFromPos(minEndPos);
968 if(numAmbigSeqs != 0){
969 m->mothurOut("Warning: " + toString(numAmbigSeqs) + " reference sequences have ambiguous bases, these bases will be ignored\n");
973 catch(exception& e) {
974 m->errorOut(e, "SeqErrorCommand", "getReferences");
979 //***************************************************************************************************************
981 int SeqErrorCommand::getErrors(Sequence query, Sequence reference, Compare& errors){
983 if(query.getAlignLength() != reference.getAlignLength()){
984 m->mothurOut("Warning: " + toString(query.getName()) + " and " + toString(reference.getName()) + " are different lengths\n");
986 int alignLength = query.getAlignLength();
988 string q = query.getAligned();
989 string r = reference.getAligned();
994 errors.sequence = "";
995 for(int i=0;i<alignLength;i++){
997 if(q[i] != '.' && r[i] != '.' && (q[i] != '-' || r[i] != '-')){ // no missing data and no double gaps
1002 if(r[i] == 'A'){ errors.AA++; errors.matches++; errors.sequence += 'm'; }
1003 if(r[i] == 'T'){ errors.AT++; errors.sequence += 's'; }
1004 if(r[i] == 'G'){ errors.AG++; errors.sequence += 's'; }
1005 if(r[i] == 'C'){ errors.AC++; errors.sequence += 's'; }
1006 if(r[i] == '-'){ errors.Ai++; errors.sequence += 'i'; }
1008 else if(q[i] == 'T'){
1009 if(r[i] == 'A'){ errors.TA++; errors.sequence += 's'; }
1010 if(r[i] == 'T'){ errors.TT++; errors.matches++; errors.sequence += 'm'; }
1011 if(r[i] == 'G'){ errors.TG++; errors.sequence += 's'; }
1012 if(r[i] == 'C'){ errors.TC++; errors.sequence += 's'; }
1013 if(r[i] == '-'){ errors.Ti++; errors.sequence += 'i'; }
1015 else if(q[i] == 'G'){
1016 if(r[i] == 'A'){ errors.GA++; errors.sequence += 's'; }
1017 if(r[i] == 'T'){ errors.GT++; errors.sequence += 's'; }
1018 if(r[i] == 'G'){ errors.GG++; errors.matches++; errors.sequence += 'm'; }
1019 if(r[i] == 'C'){ errors.GC++; errors.sequence += 's'; }
1020 if(r[i] == '-'){ errors.Gi++; errors.sequence += 'i'; }
1022 else if(q[i] == 'C'){
1023 if(r[i] == 'A'){ errors.CA++; errors.sequence += 's'; }
1024 if(r[i] == 'T'){ errors.CT++; errors.sequence += 's'; }
1025 if(r[i] == 'G'){ errors.CG++; errors.sequence += 's'; }
1026 if(r[i] == 'C'){ errors.CC++; errors.matches++; errors.sequence += 'm'; }
1027 if(r[i] == '-'){ errors.Ci++; errors.sequence += 'i'; }
1029 else if(q[i] == 'N'){
1030 if(r[i] == 'A'){ errors.NA++; errors.sequence += 'a'; }
1031 if(r[i] == 'T'){ errors.NT++; errors.sequence += 'a'; }
1032 if(r[i] == 'G'){ errors.NG++; errors.sequence += 'a'; }
1033 if(r[i] == 'C'){ errors.NC++; errors.sequence += 'a'; }
1034 if(r[i] == '-'){ errors.Ni++; errors.sequence += 'a'; }
1036 else if(q[i] == '-' && r[i] != '-'){
1037 if(r[i] == 'A'){ errors.dA++; errors.sequence += 'd'; }
1038 if(r[i] == 'T'){ errors.dT++; errors.sequence += 'd'; }
1039 if(r[i] == 'G'){ errors.dG++; errors.sequence += 'd'; }
1040 if(r[i] == 'C'){ errors.dC++; errors.sequence += 'd'; }
1047 errors.sequence += 'd'; errors.total++;
1050 errors.sequence += 'r';
1054 else if(q[i] == '.' && r[i] != '.'){ // reference extends beyond query
1055 if(started == 1){ break; }
1057 else if(q[i] != '.' && r[i] == '.'){ // query extends beyond reference
1058 if(started == 1){ break; }
1060 else if(q[i] == '.' && r[i] == '.'){ // both are missing data
1061 if(started == 1){ break; }
1065 errors.mismatches = errors.total-errors.matches;
1066 if(errors.total != 0){ errors.errorRate = (double)(errors.total-errors.matches) / (double)errors.total; }
1067 else{ errors.errorRate = 0; }
1069 errors.queryName = query.getName();
1070 errors.refName = reference.getName();
1074 catch(exception& e) {
1075 m->errorOut(e, "SeqErrorCommand", "getErrors");
1080 //***************************************************************************************************************
1082 map<string, int> SeqErrorCommand::getWeights(){
1084 m->openInputFile(namesFileName, nameFile);
1087 string redundantSeqs;
1088 map<string, int> nameCountMap;
1091 nameFile >> seqName >> redundantSeqs;
1092 nameCountMap[seqName] = m->getNumNames(redundantSeqs);
1093 m->gobble(nameFile);
1098 return nameCountMap;
1101 //***************************************************************************************************************
1103 void SeqErrorCommand::printErrorHeader(ofstream& errorSummaryFile){
1105 errorSummaryFile << "query\treference\tweight\t";
1106 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";
1107 errorSummaryFile << "insertions\tdeletions\tsubstitutions\tambig\tmatches\tmismatches\ttotal\terror\tnumparents\n";
1109 errorSummaryFile << setprecision(6);
1110 errorSummaryFile.setf(ios::fixed);
1112 catch(exception& e) {
1113 m->errorOut(e, "SeqErrorCommand", "printErrorHeader");
1118 //***************************************************************************************************************
1120 void SeqErrorCommand::printErrorData(Compare error, int numParentSeqs, ofstream& errorSummaryFile, ofstream& errorSeqFile){
1123 errorSummaryFile << error.queryName << '\t' << error.refName << '\t' << error.weight << '\t';
1124 errorSummaryFile << error.AA << '\t' << error.AT << '\t' << error.AG << '\t' << error.AC << '\t';
1125 errorSummaryFile << error.TA << '\t' << error.TT << '\t' << error.TG << '\t' << error.TC << '\t';
1126 errorSummaryFile << error.GA << '\t' << error.GT << '\t' << error.GG << '\t' << error.GC << '\t';
1127 errorSummaryFile << error.CA << '\t' << error.CT << '\t' << error.CG << '\t' << error.CC << '\t';
1128 errorSummaryFile << error.NA << '\t' << error.NT << '\t' << error.NG << '\t' << error.NC << '\t';
1129 errorSummaryFile << error.Ai << '\t' << error.Ti << '\t' << error.Gi << '\t' << error.Ci << '\t' << error.Ni << '\t';
1130 errorSummaryFile << error.dA << '\t' << error.dT << '\t' << error.dG << '\t' << error.dC << '\t';
1132 errorSummaryFile << error.Ai + error.Ti + error.Gi + error.Ci << '\t'; //insertions
1133 errorSummaryFile << error.dA + error.dT + error.dG + error.dC << '\t'; //deletions
1134 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
1135 errorSummaryFile << error.NA + error.NT + error.NG + error.NC + error.Ni << '\t'; //ambiguities
1136 errorSummaryFile << error.matches << '\t' << error.mismatches << '\t' << error.total << '\t' << error.errorRate << '\t' << numParentSeqs << endl;
1138 errorSeqFile << '>' << error.queryName << "\tref:" << error.refName << '\n' << error.sequence << endl;
1140 int a=0; int t=1; int g=2; int c=3;
1143 if(numParentSeqs == 1 || ignoreChimeras == 0){
1144 substitutionMatrix[a][a] += error.weight * error.AA;
1145 substitutionMatrix[a][t] += error.weight * error.TA;
1146 substitutionMatrix[a][g] += error.weight * error.GA;
1147 substitutionMatrix[a][c] += error.weight * error.CA;
1148 substitutionMatrix[a][gap] += error.weight * error.dA;
1149 substitutionMatrix[a][n] += error.weight * error.NA;
1151 substitutionMatrix[t][a] += error.weight * error.AT;
1152 substitutionMatrix[t][t] += error.weight * error.TT;
1153 substitutionMatrix[t][g] += error.weight * error.GT;
1154 substitutionMatrix[t][c] += error.weight * error.CT;
1155 substitutionMatrix[t][gap] += error.weight * error.dT;
1156 substitutionMatrix[t][n] += error.weight * error.NT;
1158 substitutionMatrix[g][a] += error.weight * error.AG;
1159 substitutionMatrix[g][t] += error.weight * error.TG;
1160 substitutionMatrix[g][g] += error.weight * error.GG;
1161 substitutionMatrix[g][c] += error.weight * error.CG;
1162 substitutionMatrix[g][gap] += error.weight * error.dG;
1163 substitutionMatrix[g][n] += error.weight * error.NG;
1165 substitutionMatrix[c][a] += error.weight * error.AC;
1166 substitutionMatrix[c][t] += error.weight * error.TC;
1167 substitutionMatrix[c][g] += error.weight * error.GC;
1168 substitutionMatrix[c][c] += error.weight * error.CC;
1169 substitutionMatrix[c][gap] += error.weight * error.dC;
1170 substitutionMatrix[c][n] += error.weight * error.NC;
1172 substitutionMatrix[gap][a] += error.weight * error.Ai;
1173 substitutionMatrix[gap][t] += error.weight * error.Ti;
1174 substitutionMatrix[gap][g] += error.weight * error.Gi;
1175 substitutionMatrix[gap][c] += error.weight * error.Ci;
1176 substitutionMatrix[gap][n] += error.weight * error.Ni;
1179 catch(exception& e) {
1180 m->errorOut(e, "SeqErrorCommand", "printErrorData");
1185 //***************************************************************************************************************
1187 void SeqErrorCommand::printSubMatrix(){
1189 string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
1190 map<string, string> variables;
1191 variables["[filename]"] = fileNameRoot;
1192 string subMatrixFileName = getOutputFileName("errormatrix",variables);
1193 ofstream subMatrixFile;
1194 m->openOutputFile(subMatrixFileName, subMatrixFile);
1195 outputNames.push_back(subMatrixFileName); outputTypes["errormatrix"].push_back(subMatrixFileName);
1196 vector<string> bases(6);
1203 vector<int> refSums(5,1);
1205 for(int i=0;i<5;i++){
1206 subMatrixFile << "\tr" << bases[i];
1208 for(int j=0;j<6;j++){
1209 refSums[i] += substitutionMatrix[i][j];
1212 subMatrixFile << endl;
1214 for(int i=0;i<6;i++){
1215 subMatrixFile << 'q' << bases[i];
1216 for(int j=0;j<5;j++){
1217 subMatrixFile << '\t' << substitutionMatrix[j][i];
1219 subMatrixFile << endl;
1222 subMatrixFile << "total";
1223 for(int i=0;i<5;i++){
1224 subMatrixFile << '\t' << refSums[i];
1226 subMatrixFile << endl;
1227 subMatrixFile.close();
1229 catch(exception& e) {
1230 m->errorOut(e, "SeqErrorCommand", "printSubMatrix");
1235 //***************************************************************************************************************
1237 void SeqErrorCommand::printErrorFRFile(map<char, vector<int> > errorForward, map<char, vector<int> > errorReverse){
1239 string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
1240 map<string, string> variables;
1241 variables["[filename]"] = fileNameRoot;
1242 string errorForwardFileName = getOutputFileName("errorforward",variables);
1243 ofstream errorForwardFile;
1244 m->openOutputFile(errorForwardFileName, errorForwardFile);
1245 outputNames.push_back(errorForwardFileName); outputTypes["errorforward"].push_back(errorForwardFileName);
1247 errorForwardFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1248 for(int i=0;i<maxLength;i++){
1249 float match = (float)errorForward['m'][i];
1250 float subst = (float)errorForward['s'][i];
1251 float insert = (float)errorForward['i'][i];
1252 float del = (float)errorForward['d'][i];
1253 float amb = (float)errorForward['a'][i];
1254 float total = match + subst + insert + del + amb;
1255 if(total == 0){ break; }
1256 errorForwardFile << i+1 << '\t' << total << '\t' << match/total << '\t' << subst/total << '\t' << insert/total << '\t' << del/total << '\t' << amb/total << endl;
1258 errorForwardFile.close();
1260 string errorReverseFileName = getOutputFileName("errorreverse",variables);
1261 ofstream errorReverseFile;
1262 m->openOutputFile(errorReverseFileName, errorReverseFile);
1263 outputNames.push_back(errorReverseFileName); outputTypes["errorreverse"].push_back(errorReverseFileName);
1265 errorReverseFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1266 for(int i=0;i<maxLength;i++){
1267 float match = (float)errorReverse['m'][i];
1268 float subst = (float)errorReverse['s'][i];
1269 float insert = (float)errorReverse['i'][i];
1270 float del = (float)errorReverse['d'][i];
1271 float amb = (float)errorReverse['a'][i];
1272 float total = match + subst + insert + del + amb;
1273 if(total == 0){ break; }
1274 errorReverseFile << i+1 << '\t' << total << '\t' << match/total << '\t' << subst/total << '\t' << insert/total << '\t' << del/total << '\t' << amb/total << endl;
1276 errorReverseFile.close();
1278 catch(exception& e) {
1279 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1284 //***************************************************************************************************************
1286 void SeqErrorCommand::printErrorQuality(map<char, vector<int> > qScoreErrorMap){
1288 string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
1289 map<string, string> variables;
1290 variables["[filename]"] = fileNameRoot;
1291 string errorQualityFileName = getOutputFileName("errorquality",variables);
1292 ofstream errorQualityFile;
1293 m->openOutputFile(errorQualityFileName, errorQualityFile);
1294 outputNames.push_back(errorQualityFileName); outputTypes["errorquality"].push_back(errorQualityFileName);
1296 errorQualityFile << "qscore\tmatches\tsubstitutions\tinsertions\tambiguous" << endl;
1297 for(int i=0;i<101;i++){
1298 errorQualityFile << i << '\t' << qScoreErrorMap['m'][i] << '\t' << qScoreErrorMap['s'][i] << '\t' << qScoreErrorMap['i'][i] << '\t'<< qScoreErrorMap['a'][i] << endl;
1300 errorQualityFile.close();
1302 catch(exception& e) {
1303 m->errorOut(e, "SeqErrorCommand", "printErrorQuality");
1308 //***************************************************************************************************************
1310 void SeqErrorCommand::printQualityFR(vector<vector<int> > qualForwardMap, vector<vector<int> > qualReverseMap){
1314 int numColumns = qualForwardMap[0].size();
1316 for(int i=0;i<qualForwardMap.size();i++){
1317 for(int j=0;j<numColumns;j++){
1318 if(qualForwardMap[i][j] != 0){
1319 if(numRows < i) { numRows = i+20; }
1323 string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
1324 map<string, string> variables;
1325 variables["[filename]"] = fileNameRoot;
1326 string qualityForwardFileName = getOutputFileName("errorqualforward",variables);
1327 ofstream qualityForwardFile;
1328 m->openOutputFile(qualityForwardFileName, qualityForwardFile);
1329 outputNames.push_back(qualityForwardFileName); outputTypes["errorqualforward"].push_back(qualityForwardFileName);
1331 for(int i=0;i<numColumns;i++){ qualityForwardFile << '\t' << i; } qualityForwardFile << endl;
1333 for(int i=0;i<numRows;i++){
1334 qualityForwardFile << i+1;
1335 for(int j=0;j<numColumns;j++){
1336 qualityForwardFile << '\t' << qualForwardMap[i][j];
1339 qualityForwardFile << endl;
1341 qualityForwardFile.close();
1344 string qualityReverseFileName = getOutputFileName("errorqualreverse",variables);
1345 ofstream qualityReverseFile;
1346 m->openOutputFile(qualityReverseFileName, qualityReverseFile);
1347 outputNames.push_back(qualityReverseFileName); outputTypes["errorqualreverse"].push_back(qualityReverseFileName);
1349 for(int i=0;i<numColumns;i++){ qualityReverseFile << '\t' << i; } qualityReverseFile << endl;
1350 for(int i=0;i<numRows;i++){
1352 qualityReverseFile << i+1;
1353 for(int j=0;j<numColumns;j++){
1354 qualityReverseFile << '\t' << qualReverseMap[i][j];
1356 qualityReverseFile << endl;
1358 qualityReverseFile.close();
1360 catch(exception& e) {
1361 m->errorOut(e, "SeqErrorCommand", "printQualityFR");
1367 /**************************************************************************************************/
1369 int SeqErrorCommand::setLines(string filename, string qfilename, string rfilename, vector<unsigned long long>& fastaFilePos, vector<unsigned long long>& qfileFilePos, vector<unsigned long long>& rfileFilePos) {
1371 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1372 //set file positions for fasta file
1373 fastaFilePos = m->divideFile(filename, processors);
1375 if (qfilename == "") { return processors; }
1377 //get name of first sequence in each chunk
1378 map<string, int> firstSeqNames;
1379 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
1381 m->openInputFile(filename, in);
1382 in.seekg(fastaFilePos[i]);
1385 firstSeqNames[temp.getName()] = i;
1390 //make copy to use below
1391 map<string, int> firstSeqNamesReport = firstSeqNames;
1393 //seach for filePos of each first name in the qfile and save in qfileFilePos
1395 m->openInputFile(qfilename, inQual);
1398 while(!inQual.eof()){
1399 input = m->getline(inQual);
1401 if (input.length() != 0) {
1402 if(input[0] == '>'){ //this is a sequence name line
1403 istringstream nameStream(input);
1405 string sname = ""; nameStream >> sname;
1406 sname = sname.substr(1);
1408 m->checkName(sname);
1410 map<string, int>::iterator it = firstSeqNames.find(sname);
1412 if(it != firstSeqNames.end()) { //this is the start of a new chunk
1413 unsigned long long pos = inQual.tellg();
1414 qfileFilePos.push_back(pos - input.length() - 1);
1415 firstSeqNames.erase(it);
1420 if (firstSeqNames.size() == 0) { break; }
1424 if (firstSeqNames.size() != 0) {
1425 for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
1426 m->mothurOut(it->first + " is in your fasta file and not in your quality file, aborting."); m->mothurOutEndLine();
1428 m->control_pressed = true;
1432 //get last file position of qfile
1434 unsigned long long size;
1436 //get num bytes in file
1437 pFile = fopen (qfilename.c_str(),"rb");
1438 if (pFile==NULL) perror ("Error opening file");
1440 fseek (pFile, 0, SEEK_END);
1445 qfileFilePos.push_back(size);
1448 //seach for filePos of each first name in the rfile and save in rfileFilePos
1452 m->openInputFile(rfilename, inR);
1454 //read column headers
1455 for (int i = 0; i < 16; i++) {
1456 if (!inR.eof()) { inR >> junk; }
1462 input = m->getline(inR);
1464 if (input.length() != 0) {
1466 istringstream nameStream(input);
1467 string sname = ""; nameStream >> sname;
1469 m->checkName(sname);
1471 map<string, int>::iterator it = firstSeqNamesReport.find(sname);
1473 if(it != firstSeqNamesReport.end()) { //this is the start of a new chunk
1474 unsigned long long pos = inR.tellg();
1475 rfileFilePos.push_back(pos - input.length() - 1);
1476 firstSeqNamesReport.erase(it);
1480 if (firstSeqNamesReport.size() == 0) { break; }
1485 if (firstSeqNamesReport.size() != 0) {
1486 for (map<string, int>::iterator it = firstSeqNamesReport.begin(); it != firstSeqNamesReport.end(); it++) {
1487 m->mothurOut(it->first + " is in your fasta file and not in your report file, aborting."); m->mothurOutEndLine();
1489 m->control_pressed = true;
1493 //get last file position of qfile
1495 unsigned long long sizeR;
1497 //get num bytes in file
1498 rFile = fopen (rfilename.c_str(),"rb");
1499 if (rFile==NULL) perror ("Error opening file");
1501 fseek (rFile, 0, SEEK_END);
1502 sizeR=ftell (rFile);
1506 rfileFilePos.push_back(sizeR);
1512 fastaFilePos.push_back(0); qfileFilePos.push_back(0);
1513 //get last file position of fastafile
1515 unsigned long long size;
1517 //get num bytes in file
1518 pFile = fopen (filename.c_str(),"rb");
1519 if (pFile==NULL) perror ("Error opening file");
1521 fseek (pFile, 0, SEEK_END);
1525 fastaFilePos.push_back(size);
1527 //get last file position of fastafile
1530 //get num bytes in file
1531 qFile = fopen (qfilename.c_str(),"rb");
1532 if (qFile==NULL) perror ("Error opening file");
1534 fseek (qFile, 0, SEEK_END);
1538 qfileFilePos.push_back(size);
1544 catch(exception& e) {
1545 m->errorOut(e, "SeqErrorCommand", "setLines");
1550 //***************************************************************************************************************