]> git.donarmstrong.com Git - mothur.git/blob - seqerrorcommand.cpp
working on current change
[mothur.git] / seqerrorcommand.cpp
1 /*
2  *  seqerrorcommand.cpp
3  *  Mothur
4  *
5  *  Created by Pat Schloss on 7/15/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "seqerrorcommand.h"
11 #include "reportfile.h"
12 #include "qualityscores.h"
13 #include "refchimeratest.h"
14 #include "filterseqscommand.h"
15
16 //**********************************************************************************************************************
17 vector<string> SeqErrorCommand::setParameters(){        
18         try {
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);
29                 
30                 vector<string> myArray;
31                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
32                 return myArray;
33         }
34         catch(exception& e) {
35                 m->errorOut(e, "SeqErrorCommand", "setParameters");
36                 exit(1);
37         }
38 }
39 //**********************************************************************************************************************
40 string SeqErrorCommand::getHelpString(){        
41         try {
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";
47                 return helpString;
48         }
49         catch(exception& e) {
50                 m->errorOut(e, "SeqErrorCommand", "getHelpString");
51                 exit(1);
52         }
53 }
54 //**********************************************************************************************************************
55 SeqErrorCommand::SeqErrorCommand(){     
56         try {
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;
68         }
69         catch(exception& e) {
70                 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
71                 exit(1);
72         }
73 }
74 //***************************************************************************************************************
75
76 SeqErrorCommand::SeqErrorCommand(string option)  {
77         try {
78                 
79                 abort = false; calledHelp = false;   
80                 
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;}
84                 
85                 else {
86                         string temp;
87                         vector<string> myArray = setParameters();
88                         
89                         OptionParser parser(option);
90                         map<string,string> parameters = parser.getParameters();
91                         
92                         ValidParameters validParameter;
93                         map<string,string>::iterator it;
94                         
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;  }
98                         }
99                         
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;
111
112                         
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 = "";          }
116                         else {
117                                 string path;
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;            }
124                                 }
125                                 
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;                }
132                                 }
133                                 
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;             }
140                                 }
141
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;            }
148                                 }
149                                 
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;           }
156                                 }
157                                 
158                         }
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; }
165                         }
166                         else if (queryFileName == "not open") { abort = true; } 
167                         else { m->setFastaFile(queryFileName); }
168                         
169                         referenceFileName = validParameter.validFile(parameters, "reference", true);
170                         if (referenceFileName == "not found") { m->mothurOut("reference is a required parameter for the seq.error command."); m->mothurOutEndLine(); abort = true; }
171                         else if (referenceFileName == "not open") { abort = true; }     
172                         
173
174                         //check for optional parameters
175                         namesFileName = validParameter.validFile(parameters, "name", true);
176                         if(namesFileName == "not found"){       namesFileName = "";     }
177                         else if (namesFileName == "not open") { namesFileName = ""; abort = true; }     
178                         else { m->setNameFile(namesFileName); }
179                         
180                         qualFileName = validParameter.validFile(parameters, "qfile", true);
181                         if(qualFileName == "not found"){        qualFileName = "";      }
182                         else if (qualFileName == "not open") { qualFileName = ""; abort = true; }       
183                         else { m->setQualFile(qualFileName); }
184                         
185                         reportFileName = validParameter.validFile(parameters, "report", true);
186                         if(reportFileName == "not found"){      reportFileName = "";    }
187                         else if (reportFileName == "not open") { reportFileName = ""; abort = true; }   
188                         
189                         if((reportFileName != "" && qualFileName == "") || (reportFileName == "" && qualFileName != "")){
190                                 m->mothurOut("if you use either a qual file or a report file, you have to have both.");
191                                 m->mothurOutEndLine();
192                                 abort = true; 
193                         }
194                         
195                         outputDir = validParameter.validFile(parameters, "outputdir", false);
196                         if (outputDir == "not found"){  
197                                 outputDir = ""; 
198                                 outputDir += m->hasPath(queryFileName); //if user entered a file with a path then preserve it   
199                         }
200                         
201                         //check for optional parameter and set defaults
202                         // ...at some point should added some additional type checking...
203                         temp = validParameter.validFile(parameters, "threshold", false);        if (temp == "not found") { temp = "1.00"; }
204                         convert(temp, threshold);  
205                         
206                         temp = validParameter.validFile(parameters, "ignorechimeras", false);   if (temp == "not found") { temp = "T"; }
207                         ignoreChimeras = m->isTrue(temp);
208                         
209                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
210                         m->setProcessors(temp);
211                         convert(temp, processors); 
212
213                         substitutionMatrix.resize(6);
214                         for(int i=0;i<6;i++){   substitutionMatrix[i].resize(6,0);      }
215                 }
216         }
217         catch(exception& e) {
218                 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
219                 exit(1);
220         }
221 }
222 //***************************************************************************************************************
223
224 int SeqErrorCommand::execute(){
225         try{
226                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
227                 
228                 int start = time(NULL);
229                 maxLength = 2000;
230                 totalBases = 0;
231                 totalMatches = 0;
232                 
233                 string errorSummaryFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.summary";
234                 outputNames.push_back(errorSummaryFileName); outputTypes["error.summary"].push_back(errorSummaryFileName);
235                         
236                 string errorSeqFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq";
237                 outputNames.push_back(errorSeqFileName); outputTypes["error.seq"].push_back(errorSeqFileName);
238                 
239                 string errorChimeraFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.chimera";
240                 outputNames.push_back(errorChimeraFileName); outputTypes["error.chimera"].push_back(errorChimeraFileName);
241                 
242                 getReferences();        //read in reference sequences - make sure there's no ambiguous bases
243
244                 if(namesFileName != ""){        weights = getWeights(); }
245                 
246                 vector<unsigned long int> fastaFilePos;
247                 vector<unsigned long int> qFilePos;
248                 vector<unsigned long int> reportFilePos;
249                 
250                 setLines(queryFileName, qualFileName, reportFileName, fastaFilePos, qFilePos, reportFilePos);
251                 
252                 if (m->control_pressed) { return 0; }
253                 
254                 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
255                         lines.push_back(linePair(fastaFilePos[i], fastaFilePos[(i+1)]));
256                         if (qualFileName != "") {  qLines.push_back(linePair(qFilePos[i], qFilePos[(i+1)]));  }
257                         if (reportFileName != "") {  rLines.push_back(linePair(reportFilePos[i], reportFilePos[(i+1)]));  }
258                 }       
259                 if(qualFileName == "")  {       qLines = lines; rLines = lines; } //fills with duds
260                 
261                 int numSeqs = 0;
262 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
263                 if(processors == 1){
264                         numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
265                 }else{
266                         numSeqs = createProcesses(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName);
267                 }       
268 #else
269                 numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
270 #endif
271                 
272                 if(qualFileName != "" && reportFileName != ""){         
273                         printErrorQuality(qScoreErrorMap);
274                         printQualityFR(qualForwardMap, qualReverseMap);
275                 }
276                 
277                 printErrorFRFile(errorForward, errorReverse);
278                 
279                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
280
281                 string errorCountFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.count";
282                 ofstream errorCountFile;
283                 m->openOutputFile(errorCountFileName, errorCountFile);
284                 outputNames.push_back(errorCountFileName);  outputTypes["error.count"].push_back(errorCountFileName);
285                 m->mothurOut("Overall error rate:\t" + toString((double)(totalBases - totalMatches) / (double)totalBases) + "\n");
286                 m->mothurOut("Errors\tSequences\n");
287                 errorCountFile << "Errors\tSequences\n";                
288                 for(int i=0;i<misMatchCounts.size();i++){
289                         m->mothurOut(toString(i) + '\t' + toString(misMatchCounts[i]) + '\n');
290                         errorCountFile << i << '\t' << misMatchCounts[i] << endl;
291                 }
292                 errorCountFile.close();
293                 
294                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
295
296                 printSubMatrix();
297                                 
298                 string megAlignmentFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.ref-query";
299                 ofstream megAlignmentFile;
300                 m->openOutputFile(megAlignmentFileName, megAlignmentFile);
301                 outputNames.push_back(megAlignmentFileName);  outputTypes["error.ref-query"].push_back(megAlignmentFileName);
302                 
303                 for(int i=0;i<numRefs;i++){
304                         megAlignmentFile << referenceSeqs[i].getInlineSeq() << endl;
305                         megAlignmentFile << megaAlignVector[i] << endl;
306                 }
307                 
308                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences.");
309                 m->mothurOutEndLine();
310                 
311                 m->mothurOutEndLine();
312                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
313                 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
314                 m->mothurOutEndLine();
315                 
316                 return 0;       
317         }
318         catch(exception& e) {
319                 m->errorOut(e, "SeqErrorCommand", "execute");
320                 exit(1);
321         }
322 }
323 //**********************************************************************************************************************
324 int SeqErrorCommand::createProcesses(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName) {   
325         try {
326                 int process = 1;
327                 processIDS.clear();
328                 map<char, vector<int> >::iterator it;
329                 int num = 0;
330 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
331                 
332                 //loop through and create all the processes you want
333                 while (process != processors) {
334                         int pid = fork();
335                         
336                         if (pid > 0) {
337                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
338                                 process++;
339                         }else if (pid == 0){
340                                 
341                                 num = driver(filename, qFileName, rFileName, summaryFileName + toString(getpid()) + ".temp", errorOutputFileName+ toString(getpid()) + ".temp", chimeraOutputFileName + toString(getpid()) + ".temp", lines[process], qLines[process], rLines[process]);
342                                 
343                                 //pass groupCounts to parent
344                                 ofstream out;
345                                 string tempFile = filename + toString(getpid()) + ".info.temp";
346                                 m->openOutputFile(tempFile, out);
347                                 
348                                 //output totalBases and totalMatches
349                                 out << num << '\t' << totalBases << '\t' << totalMatches << endl << endl;
350                                 
351                                 //output substitutionMatrix
352                                 for(int i = 0; i < substitutionMatrix.size(); i++) {
353                                         for (int j = 0; j < substitutionMatrix[i].size(); j++) {
354                                                 out << substitutionMatrix[i][j] << '\t';
355                                         }
356                                         out << endl;
357                                 }
358                                 out << endl;
359                                 
360                                 //output qScoreErrorMap
361                                 for (it = qScoreErrorMap.begin(); it != qScoreErrorMap.end(); it++) {
362                                         vector<int> thisScoreErrorMap = it->second;
363                                         out << it->first << '\t';
364                                         for (int i = 0; i < thisScoreErrorMap.size(); i++) {
365                                                 out << thisScoreErrorMap[i] << '\t';
366                                         }
367                                         out << endl;
368                                 }
369                                 out << endl;
370                                 
371                                 //output qualForwardMap
372                                 for(int i = 0; i < qualForwardMap.size(); i++) {
373                                         for (int j = 0; j < qualForwardMap[i].size(); j++) {
374                                                 out << qualForwardMap[i][j] << '\t';
375                                         }
376                                         out << endl;
377                                 }
378                                 out << endl;
379                                 
380                                 //output qualReverseMap
381                                 for(int i = 0; i < qualReverseMap.size(); i++) {
382                                         for (int j = 0; j < qualReverseMap[i].size(); j++) {
383                                                 out << qualReverseMap[i][j] << '\t';
384                                         }
385                                         out << endl;
386                                 }
387                                 out << endl;
388                                 
389                                 
390                                 //output errorForward
391                                 for (it = errorForward.begin(); it != errorForward.end(); it++) {
392                                         vector<int> thisErrorForward = it->second;
393                                         out << it->first << '\t';
394                                         for (int i = 0; i < thisErrorForward.size(); i++) {
395                                                 out << thisErrorForward[i] << '\t';
396                                         }
397                                         out << endl;
398                                 }
399                                 out << endl;
400                                 
401                                 //output errorReverse
402                                 for (it = errorReverse.begin(); it != errorReverse.end(); it++) {
403                                         vector<int> thisErrorReverse = it->second;
404                                         out << it->first << '\t';
405                                         for (int i = 0; i < thisErrorReverse.size(); i++) {
406                                                 out << thisErrorReverse[i] << '\t';
407                                         }
408                                         out << endl;
409                                 }
410                                 out << endl;
411                                 
412                                 //output misMatchCounts
413                                 out << misMatchCounts.size() << endl;
414                                 for (int j = 0; j < misMatchCounts.size(); j++) {
415                                         out << misMatchCounts[j] << '\t';
416                                 }
417                                 out << endl;
418                                 
419                                 
420                                 //output megaAlignVector
421                                 for (int j = 0; j < megaAlignVector.size(); j++) {
422                                         out << megaAlignVector[j] << endl;
423                                 }
424                                 out << endl;
425                                 
426                                 out.close();
427                                 
428                                 exit(0);
429                         }else { 
430                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
431                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
432                                 exit(0);
433                         }
434                 }
435                 
436                 //do my part
437                 num = driver(filename, qFileName, rFileName, summaryFileName, errorOutputFileName, chimeraOutputFileName, lines[0], qLines[0], rLines[0]);
438                 
439                 //force parent to wait until all the processes are done
440                 for (int i=0;i<processIDS.size();i++) { 
441                         int temp = processIDS[i];
442                         wait(&temp);
443                 }
444                 
445                 //append files
446                 for(int i=0;i<processIDS.size();i++){
447                         
448                         m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
449                         
450                         m->appendFiles((summaryFileName + toString(processIDS[i]) + ".temp"), summaryFileName);
451                         remove((summaryFileName + toString(processIDS[i]) + ".temp").c_str());
452                         m->appendFiles((errorOutputFileName + toString(processIDS[i]) + ".temp"), errorOutputFileName);
453                         remove((errorOutputFileName + toString(processIDS[i]) + ".temp").c_str());
454                         m->appendFiles((chimeraOutputFileName + toString(processIDS[i]) + ".temp"), chimeraOutputFileName);
455                         remove((chimeraOutputFileName + toString(processIDS[i]) + ".temp").c_str());
456                         
457                         ifstream in;
458                         string tempFile =  filename + toString(processIDS[i]) + ".info.temp";
459                         m->openInputFile(tempFile, in);
460                         
461                         //input totalBases and totalMatches
462                         int tempBases, tempMatches, tempNumSeqs;
463                         in >> tempNumSeqs >> tempBases >> tempMatches; m->gobble(in);
464                         totalBases += tempBases; totalMatches += tempMatches; num += tempNumSeqs;
465                         
466                         //input substitutionMatrix
467                         int tempNum;
468                         for(int i = 0; i < substitutionMatrix.size(); i++) {
469                                 for (int j = 0; j < substitutionMatrix[i].size(); j++) {
470                                         in >> tempNum; substitutionMatrix[i][j] += tempNum;
471                                 }
472                                 m->gobble(in);
473                         }
474                         m->gobble(in);
475                         
476                         //input qScoreErrorMap
477                         char first;
478                         for (int i = 0; i < qScoreErrorMap.size(); i++) {
479                                 in >> first;
480                                 vector<int> thisScoreErrorMap = qScoreErrorMap[first];
481                                 
482                                 for (int i = 0; i < thisScoreErrorMap.size(); i++) {
483                                         in >> tempNum; thisScoreErrorMap[i] += tempNum;
484                                 }
485                                 qScoreErrorMap[first] = thisScoreErrorMap;
486                                 m->gobble(in);
487                         }
488                         m->gobble(in);
489                         
490                         //input qualForwardMap
491                         for(int i = 0; i < qualForwardMap.size(); i++) {
492                                 for (int j = 0; j < qualForwardMap[i].size(); j++) {
493                                         in >> tempNum; qualForwardMap[i][j] += tempNum;
494                                 }
495                                 m->gobble(in);
496                         }
497                         m->gobble(in);
498                         
499                         //input qualReverseMap
500                         for(int i = 0; i < qualReverseMap.size(); i++) {
501                                 for (int j = 0; j < qualReverseMap[i].size(); j++) {
502                                         in >> tempNum; qualReverseMap[i][j] += tempNum;
503                                 }
504                                 m->gobble(in);
505                         }
506                         m->gobble(in);
507                         
508                         //input errorForward
509                         for (int i = 0; i < errorForward.size(); i++) {
510                                 in >> first;
511                                 vector<int> thisErrorForward = errorForward[first];
512                                 
513                                 for (int i = 0; i < thisErrorForward.size(); i++) {
514                                         in >> tempNum; thisErrorForward[i] += tempNum;
515                                 }
516                                 errorForward[first] = thisErrorForward;
517                                 m->gobble(in);
518                         }
519                         m->gobble(in);
520                         
521                         //input errorReverse
522                         for (int i = 0; i < errorReverse.size(); i++) {
523                                 in >> first;
524                                 vector<int> thisErrorReverse = errorReverse[first];
525                                 
526                                 for (int i = 0; i < thisErrorReverse.size(); i++) {
527                                         in >> tempNum; thisErrorReverse[i] += tempNum;
528                                 }
529                                 errorReverse[first] = thisErrorReverse;
530                                 m->gobble(in);
531                         }
532                         m->gobble(in);
533                         
534                         //input misMatchCounts
535                         int misMatchSize;
536                         in >> misMatchSize; m->gobble(in);
537                         if (misMatchSize > misMatchCounts.size()) {     misMatchCounts.resize(misMatchSize, 0); }
538                         for (int j = 0; j < misMatchCounts.size(); j++) {
539                                 in >> tempNum; misMatchCounts[j] += tempNum;
540                         }
541                         m->gobble(in);
542                         
543                         //input megaAlignVector
544                         string thisLine;
545                         for (int j = 0; j < megaAlignVector.size(); j++) {
546                                 thisLine = m->getline(in); m->gobble(in); megaAlignVector[j] += thisLine + '\n';
547                         }
548                         m->gobble(in);
549                         
550                         in.close(); remove(tempFile.c_str());
551                         
552                 }
553 #endif          
554                 return num;
555         }
556         catch(exception& e) {
557                 m->errorOut(e, "SeqErrorCommand", "createProcesses");
558                 exit(1);
559         }
560 }
561 //**********************************************************************************************************************
562 int SeqErrorCommand::driver(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName, linePair line, linePair qline, linePair rline) {     
563         
564         try {
565                 ReportFile report;
566                 QualityScores quality;
567                 
568                 misMatchCounts.resize(11, 0);
569                 int maxMismatch = 0;
570                 int numSeqs = 0;
571                 
572                 map<string, int>::iterator it;
573                 qScoreErrorMap['m'].assign(41, 0);
574                 qScoreErrorMap['s'].assign(41, 0);
575                 qScoreErrorMap['i'].assign(41, 0);
576                 qScoreErrorMap['a'].assign(41, 0);
577                 
578                 errorForward['m'].assign(maxLength,0);
579                 errorForward['s'].assign(maxLength,0);
580                 errorForward['i'].assign(maxLength,0);
581                 errorForward['d'].assign(maxLength,0);
582                 errorForward['a'].assign(maxLength,0);
583                 
584                 errorReverse['m'].assign(maxLength,0);
585                 errorReverse['s'].assign(maxLength,0);
586                 errorReverse['i'].assign(maxLength,0);
587                 errorReverse['d'].assign(maxLength,0);
588                 errorReverse['a'].assign(maxLength,0);  
589                 
590                 //open inputfiles and go to beginning place for this processor
591                 ifstream queryFile;
592                 m->openInputFile(filename, queryFile);
593                 queryFile.seekg(line.start);
594                 
595                 ifstream reportFile;
596                 ifstream qualFile;
597                 if(qFileName != "" && rFileName != ""){
598                         m->openInputFile(qFileName, qualFile);
599                         qualFile.seekg(qline.start);  
600                         
601                         //gobble headers
602                         if (rline.start == 0) {  report = ReportFile(reportFile, rFileName); } 
603                         else{
604                                 m->openInputFile(rFileName, reportFile);
605                                 reportFile.seekg(rline.start); 
606                         }
607                         
608                         qualForwardMap.resize(maxLength);
609                         qualReverseMap.resize(maxLength);
610                         for(int i=0;i<maxLength;i++){
611                                 qualForwardMap[i].assign(41,0);
612                                 qualReverseMap[i].assign(41,0);
613                         }       
614                 }
615                 
616                 ofstream outChimeraReport;
617                 m->openOutputFile(chimeraOutputFileName, outChimeraReport);
618                 RefChimeraTest chimeraTest(referenceSeqs);
619                 if (line.start == 0) { chimeraTest.printHeader(outChimeraReport); }
620                 
621                 ofstream errorSummaryFile;
622                 m->openOutputFile(summaryFileName, errorSummaryFile);
623                 if (line.start == 0) { printErrorHeader(errorSummaryFile); }
624                 
625                 ofstream errorSeqFile;
626                 m->openOutputFile(errorOutputFileName, errorSeqFile);
627                 
628                 megaAlignVector.resize(numRefs, "");
629                 
630                 int index = 0;
631                 bool ignoreSeq = 0;
632                 
633                 bool moreSeqs = 1;
634                 while (moreSeqs) {
635                         
636                         if (m->control_pressed) { queryFile.close(); if(qFileName != "" && rFileName != ""){  reportFile.close(); qualFile.close(); } outChimeraReport.close(); errorSummaryFile.close();errorSeqFile.close(); return 0; }
637                         
638                         Sequence query(queryFile);
639                         
640                         int numParentSeqs = chimeraTest.analyzeQuery(query.getName(), query.getAligned(), outChimeraReport);
641                         int closestRefIndex = chimeraTest.getClosestRefIndex();
642                         
643                         if(numParentSeqs > 1 && ignoreChimeras == 1)    {       ignoreSeq = 1;  }
644                         else                                                                                    {       ignoreSeq = 0;  }
645                         
646                         Compare minCompare = getErrors(query, referenceSeqs[closestRefIndex]);
647                         
648                         if(namesFileName != ""){
649                                 it = weights.find(query.getName());
650                                 minCompare.weight = it->second;
651                         }
652                         else{   minCompare.weight = 1;  }
653                         
654                         printErrorData(minCompare, numParentSeqs, errorSummaryFile, errorSeqFile);
655                         
656                         if(!ignoreSeq){
657                                 
658                                 for(int i=0;i<minCompare.sequence.length();i++){
659                                         char letter = minCompare.sequence[i];
660                                         
661                                         errorForward[letter][i] += minCompare.weight;
662                                         errorReverse[letter][minCompare.total-i-1] += minCompare.weight;                                
663                                 }
664                         }
665                         
666                         if(qualFileName != "" && reportFileName != ""){
667                                 report = ReportFile(reportFile);
668                                 
669                                 //                              int origLength = report.getQueryLength();
670                                 int startBase = report.getQueryStart();
671                                 int endBase = report.getQueryEnd();
672                                 
673                                 quality = QualityScores(qualFile);
674                                 
675                                 if(!ignoreSeq){
676                                         quality.updateQScoreErrorMap(qScoreErrorMap, minCompare.sequence, startBase, endBase, minCompare.weight);
677                                         quality.updateForwardMap(qualForwardMap, startBase, endBase, minCompare.weight);
678                                         quality.updateReverseMap(qualReverseMap, startBase, endBase, minCompare.weight);
679                                 }
680                         }                       
681                         
682                         if(minCompare.errorRate < threshold && !ignoreSeq){
683                                 totalBases += (minCompare.total * minCompare.weight);
684                                 totalMatches += minCompare.matches * minCompare.weight;
685                                 if(minCompare.mismatches > maxMismatch){
686                                         maxMismatch = minCompare.mismatches;
687                                         misMatchCounts.resize(maxMismatch + 1, 0);
688                                 }                               
689                                 misMatchCounts[minCompare.mismatches] += minCompare.weight;
690                                 numSeqs++;
691                                 
692                                 megaAlignVector[closestRefIndex] += query.getInlineSeq() + '\n';
693                         }
694                         
695                         index++;
696                         
697                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
698                                 unsigned long int pos = queryFile.tellg();
699                                 if ((pos == -1) || (pos >= line.end)) { break; }
700                         #else
701                                 if (queryFile.eof()) { break; }
702                         #endif
703                         
704                         if(index % 100 == 0){   m->mothurOut(toString(index) + '\n');   }
705                 }
706                 queryFile.close();
707                 if(qFileName != "" && rFileName != ""){  reportFile.close(); qualFile.close(); }
708                 errorSummaryFile.close();       
709                 errorSeqFile.close();
710                 
711                 //report progress
712                 if(index % 100 != 0){   m->mothurOut(toString(index) + '\n');   }
713                 
714                 return index;
715         }
716         catch(exception& e) {
717                 m->errorOut(e, "SeqErrorCommand", "driver");
718                 exit(1);
719         }
720 }
721 //***************************************************************************************************************
722
723 void SeqErrorCommand::getReferences(){
724         try {
725                 
726                 ifstream referenceFile;
727                 m->openInputFile(referenceFileName, referenceFile);
728                 
729                 int numAmbigSeqs = 0;
730                 
731                 int maxStartPos = 0;
732                 int minEndPos = 100000;
733                 
734                 while(referenceFile){
735                         Sequence currentSeq(referenceFile);
736                         int numAmbigs = currentSeq.getAmbigBases();
737                         if(numAmbigs > 0){      numAmbigSeqs++; }
738                         
739 //                      int startPos = currentSeq.getStartPos();
740 //                      if(startPos > maxStartPos)      {       maxStartPos = startPos; }
741 //
742 //                      int endPos = currentSeq.getEndPos();
743 //                      if(endPos < minEndPos)          {       minEndPos = endPos;             }
744                         referenceSeqs.push_back(currentSeq);
745                                 
746                         m->gobble(referenceFile);
747                 }
748                 referenceFile.close();
749                 numRefs = referenceSeqs.size();
750
751                 
752                 for(int i=0;i<numRefs;i++){
753                         referenceSeqs[i].padToPos(maxStartPos);
754                         referenceSeqs[i].padFromPos(minEndPos);
755                 }
756                 
757                 if(numAmbigSeqs != 0){
758                         m->mothurOut("Warning: " + toString(numAmbigSeqs) + " reference sequences have ambiguous bases, these bases will be ignored\n");
759                 }               
760                 
761         }
762         catch(exception& e) {
763                 m->errorOut(e, "SeqErrorCommand", "getReferences");
764                 exit(1);
765         }
766 }
767
768 //***************************************************************************************************************
769
770 Compare SeqErrorCommand::getErrors(Sequence query, Sequence reference){
771         try {
772                 if(query.getAlignLength() != reference.getAlignLength()){
773                         m->mothurOut("Warning: " + toString(query.getName()) + " and " + toString(reference.getName()) + " are different lengths\n");
774                 }
775                 int alignLength = query.getAlignLength();
776         
777                 string q = query.getAligned();
778                 string r = reference.getAligned();
779
780                 int started = 0;
781                 Compare errors;
782
783                 for(int i=0;i<alignLength;i++){
784                         if(r[i] != 'N' && q[i] != '.' && r[i] != '.' && (q[i] != '-' || r[i] != '-')){                  //      no missing data and no double gaps
785                                 started = 1;
786                                 
787                                 if(q[i] == 'A'){
788                                         if(r[i] == 'A'){        errors.AA++;    errors.matches++;       errors.sequence += 'm'; }
789                                         if(r[i] == 'T'){        errors.AT++;    errors.sequence += 's'; }
790                                         if(r[i] == 'G'){        errors.AG++;    errors.sequence += 's'; }
791                                         if(r[i] == 'C'){        errors.AC++;    errors.sequence += 's'; }
792                                         if(r[i] == '-'){        errors.Ai++;    errors.sequence += 'i'; }
793                                 }
794                                 else if(q[i] == 'T'){
795                                         if(r[i] == 'A'){        errors.TA++;    errors.sequence += 's'; }
796                                         if(r[i] == 'T'){        errors.TT++;    errors.matches++;       errors.sequence += 'm'; }
797                                         if(r[i] == 'G'){        errors.TG++;    errors.sequence += 's'; }
798                                         if(r[i] == 'C'){        errors.TC++;    errors.sequence += 's'; }
799                                         if(r[i] == '-'){        errors.Ti++;    errors.sequence += 'i'; }
800                                 }
801                                 else if(q[i] == 'G'){
802                                         if(r[i] == 'A'){        errors.GA++;    errors.sequence += 's'; }
803                                         if(r[i] == 'T'){        errors.GT++;    errors.sequence += 's'; }
804                                         if(r[i] == 'G'){        errors.GG++;    errors.matches++;       errors.sequence += 'm'; }
805                                         if(r[i] == 'C'){        errors.GC++;    errors.sequence += 's'; }
806                                         if(r[i] == '-'){        errors.Gi++;    errors.sequence += 'i'; }
807                                 }
808                                 else if(q[i] == 'C'){
809                                         if(r[i] == 'A'){        errors.CA++;    errors.sequence += 's'; }
810                                         if(r[i] == 'T'){        errors.CT++;    errors.sequence += 's'; }
811                                         if(r[i] == 'G'){        errors.CG++;    errors.sequence += 's'; }
812                                         if(r[i] == 'C'){        errors.CC++;    errors.matches++;       errors.sequence += 'm'; }
813                                         if(r[i] == '-'){        errors.Ci++;    errors.sequence += 'i'; }
814                                 }
815                                 else if(q[i] == 'N'){
816                                         if(r[i] == 'A'){        errors.NA++;    errors.sequence += 'a'; }
817                                         if(r[i] == 'T'){        errors.NT++;    errors.sequence += 'a'; }
818                                         if(r[i] == 'G'){        errors.NG++;    errors.sequence += 'a'; }
819                                         if(r[i] == 'C'){        errors.NC++;    errors.sequence += 'a'; }
820                                         if(r[i] == '-'){        errors.Ni++;    errors.sequence += 'a'; }
821                                 }
822                                 else if(q[i] == '-' && r[i] != '-'){
823                                         if(r[i] == 'A'){        errors.dA++;    errors.sequence += 'd'; }
824                                         if(r[i] == 'T'){        errors.dT++;    errors.sequence += 'd'; }
825                                         if(r[i] == 'G'){        errors.dG++;    errors.sequence += 'd'; }
826                                         if(r[i] == 'C'){        errors.dC++;    errors.sequence += 'd'; }
827                                 }
828                                 errors.total++; 
829                                 
830                         }
831                         else if(q[i] == '.' && r[i] != '.'){            //      reference extends beyond query
832                                 if(started == 1){       break;  }
833                         }
834                         else if(q[i] != '.' && r[i] == '.'){            //      query extends beyond reference
835                                 if(started == 1){       break;  }
836                         }
837                         else if(q[i] == '.' && r[i] == '.'){            //      both are missing data
838                                 if(started == 1){       break;  }                       
839                         }
840                         
841                 }
842                 errors.mismatches = errors.total-errors.matches;
843                 errors.errorRate = (double)(errors.total-errors.matches) / (double)errors.total;
844                 errors.queryName = query.getName();
845                 errors.refName = reference.getName();
846                 
847                 return errors;
848         }
849         catch(exception& e) {
850                 m->errorOut(e, "SeqErrorCommand", "getErrors");
851                 exit(1);
852         }
853 }
854
855 //***************************************************************************************************************
856
857 map<string, int> SeqErrorCommand::getWeights(){
858         ifstream nameFile;
859         m->openInputFile(namesFileName, nameFile);
860         
861         string seqName;
862         string redundantSeqs;
863         map<string, int> nameCountMap;
864         
865         while(nameFile){
866                 nameFile >> seqName >> redundantSeqs;
867                 nameCountMap[seqName] = m->getNumNames(redundantSeqs); 
868                 m->gobble(nameFile);
869         }
870         return nameCountMap;
871 }
872
873
874 //***************************************************************************************************************
875
876 void SeqErrorCommand::printErrorHeader(ofstream& errorSummaryFile){
877         try {
878                 errorSummaryFile << "query\treference\tweight\t";
879                 errorSummaryFile << "AA\tAT\tAG\tAC\tTA\tTT\tTG\tTC\tGA\tGT\tGG\tGC\tCA\tCT\tCG\tCC\tNA\tNT\tNG\tNC\tAi\tTi\tGi\tCi\tNi\tdA\tdT\tdG\tdC\t";
880                 errorSummaryFile << "insertions\tdeletions\tsubstitutions\tambig\tmatches\tmismatches\ttotal\terror\tnumparents\n";
881                 
882                 errorSummaryFile << setprecision(6);
883                 errorSummaryFile.setf(ios::fixed);
884         }
885         catch(exception& e) {
886                 m->errorOut(e, "SeqErrorCommand", "printErrorHeader");
887                 exit(1);
888         }
889 }
890
891 //***************************************************************************************************************
892
893 void SeqErrorCommand::printErrorData(Compare error, int numParentSeqs, ofstream& errorSummaryFile, ofstream& errorSeqFile){
894         try {
895
896                 errorSummaryFile << error.queryName << '\t' << error.refName << '\t' << error.weight << '\t';
897                 errorSummaryFile << error.AA << '\t' << error.AT << '\t' << error.AG << '\t' << error.AC << '\t';
898                 errorSummaryFile << error.TA << '\t' << error.TT << '\t' << error.TG << '\t' << error.TC << '\t';
899                 errorSummaryFile << error.GA << '\t' << error.GT << '\t' << error.GG << '\t' << error.GC << '\t';
900                 errorSummaryFile << error.CA << '\t' << error.CT << '\t' << error.CG << '\t' << error.CC << '\t';
901                 errorSummaryFile << error.NA << '\t' << error.NT << '\t' << error.NG << '\t' << error.NC << '\t';
902                 errorSummaryFile << error.Ai << '\t' << error.Ti << '\t' << error.Gi << '\t' << error.Ci << '\t' << error.Ni << '\t';
903                 errorSummaryFile << error.dA << '\t' << error.dT << '\t' << error.dG << '\t' << error.dC << '\t';
904                 
905                 errorSummaryFile << error.Ai + error.Ti + error.Gi + error.Ci << '\t';                  //insertions
906                 errorSummaryFile << error.dA + error.dT + error.dG + error.dC << '\t';                  //deletions
907                 errorSummaryFile << error.mismatches - (error.Ai + error.Ti + error.Gi + error.Ci) - (error.dA + error.dT + error.dG + error.dC) - (error.NA + error.NT + error.NG + error.NC + error.Ni) << '\t';      //substitutions
908                 errorSummaryFile << error.NA + error.NT + error.NG + error.NC + error.Ni << '\t';       //ambiguities
909                 errorSummaryFile << error.matches << '\t' << error.mismatches << '\t' << error.total << '\t' << error.errorRate << '\t' << numParentSeqs << endl;
910
911                 errorSeqFile << '>' << error.queryName << "\tref:" << error.refName << '\n' << error.sequence << endl;
912                 
913                 int a=0;                int t=1;                int g=2;                int c=3;
914                 int gap=4;              int n=5;
915
916                 if(numParentSeqs == 1 || ignoreChimeras == 0){
917                         substitutionMatrix[a][a] += error.weight * error.AA;
918                         substitutionMatrix[a][t] += error.weight * error.TA;
919                         substitutionMatrix[a][g] += error.weight * error.GA;
920                         substitutionMatrix[a][c] += error.weight * error.CA;
921                         substitutionMatrix[a][gap] += error.weight * error.dA;
922                         substitutionMatrix[a][n] += error.weight * error.NA;
923                         
924                         substitutionMatrix[t][a] += error.weight * error.AT;
925                         substitutionMatrix[t][t] += error.weight * error.TT;
926                         substitutionMatrix[t][g] += error.weight * error.GT;
927                         substitutionMatrix[t][c] += error.weight * error.CT;
928                         substitutionMatrix[t][gap] += error.weight * error.dT;
929                         substitutionMatrix[t][n] += error.weight * error.NT;
930
931                         substitutionMatrix[g][a] += error.weight * error.AG;
932                         substitutionMatrix[g][t] += error.weight * error.TG;
933                         substitutionMatrix[g][g] += error.weight * error.GG;
934                         substitutionMatrix[g][c] += error.weight * error.CG;
935                         substitutionMatrix[g][gap] += error.weight * error.dG;
936                         substitutionMatrix[g][n] += error.weight * error.NG;
937
938                         substitutionMatrix[c][a] += error.weight * error.AC;
939                         substitutionMatrix[c][t] += error.weight * error.TC;
940                         substitutionMatrix[c][g] += error.weight * error.GC;
941                         substitutionMatrix[c][c] += error.weight * error.CC;
942                         substitutionMatrix[c][gap] += error.weight * error.dC;
943                         substitutionMatrix[c][n] += error.weight * error.NC;
944
945                         substitutionMatrix[gap][a] += error.weight * error.Ai;
946                         substitutionMatrix[gap][t] += error.weight * error.Ti;
947                         substitutionMatrix[gap][g] += error.weight * error.Gi;
948                         substitutionMatrix[gap][c] += error.weight * error.Ci;
949                         substitutionMatrix[gap][n] += error.weight * error.Ni;
950                 }
951         }
952         catch(exception& e) {
953                 m->errorOut(e, "SeqErrorCommand", "printErrorData");
954                 exit(1);
955         }
956 }
957
958 //***************************************************************************************************************
959
960 void SeqErrorCommand::printSubMatrix(){
961         try {
962                 string subMatrixFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.matrix";
963                 ofstream subMatrixFile;
964                 m->openOutputFile(subMatrixFileName, subMatrixFile);
965                 outputNames.push_back(subMatrixFileName);  outputTypes["error.matrix"].push_back(subMatrixFileName);
966                 vector<string> bases(6);
967                 bases[0] = "A";
968                 bases[1] = "T";
969                 bases[2] = "G";
970                 bases[3] = "C";
971                 bases[4] = "Gap";
972                 bases[5] = "N";
973                 vector<int> refSums(5,1);
974
975                 for(int i=0;i<5;i++){
976                         subMatrixFile << "\tr" << bases[i];
977                         
978                         for(int j=0;j<6;j++){
979                                 refSums[i] += substitutionMatrix[i][j];                         
980                         }
981                 }
982                 subMatrixFile << endl;
983                 
984                 for(int i=0;i<6;i++){
985                         subMatrixFile << 'q' << bases[i];
986                         for(int j=0;j<5;j++){
987                                 subMatrixFile << '\t' << substitutionMatrix[j][i];                              
988                         }
989                         subMatrixFile << endl;
990                 }
991
992                 subMatrixFile << "total";
993                 for(int i=0;i<5;i++){
994                         subMatrixFile << '\t' << refSums[i];
995                 }
996                 subMatrixFile << endl;
997                 subMatrixFile.close();
998         }
999         catch(exception& e) {
1000                 m->errorOut(e, "SeqErrorCommand", "printSubMatrix");
1001                 exit(1);
1002         }
1003 }
1004 //***************************************************************************************************************
1005
1006 void SeqErrorCommand::printErrorFRFile(map<char, vector<int> > errorForward, map<char, vector<int> > errorReverse){
1007         try{
1008                 string errorForwardFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq.forward";
1009                 ofstream errorForwardFile;
1010                 m->openOutputFile(errorForwardFileName, errorForwardFile);
1011                 outputNames.push_back(errorForwardFileName);  outputTypes["error.forward"].push_back(errorForwardFileName);
1012
1013                 errorForwardFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1014                 for(int i=0;i<maxLength;i++){
1015                         float match = (float)errorForward['m'][i];
1016                         float subst = (float)errorForward['s'][i];
1017                         float insert = (float)errorForward['i'][i];
1018                         float del = (float)errorForward['d'][i];
1019                         float amb = (float)errorForward['a'][i];
1020                         float total = match + subst + insert + del + amb;
1021                         if(total == 0){ break;  }
1022                         errorForwardFile << i+1 << '\t' << total << '\t' << match/total  << '\t' << subst/total  << '\t' << insert/total  << '\t' << del/total  << '\t' << amb/total << endl;
1023                 }
1024                 errorForwardFile.close();
1025
1026                 string errorReverseFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq.reverse";
1027                 ofstream errorReverseFile;
1028                 m->openOutputFile(errorReverseFileName, errorReverseFile);
1029                 outputNames.push_back(errorReverseFileName);  outputTypes["error.reverse"].push_back(errorReverseFileName);
1030
1031                 errorReverseFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1032                 for(int i=0;i<maxLength;i++){
1033                         float match = (float)errorReverse['m'][i];
1034                         float subst = (float)errorReverse['s'][i];
1035                         float insert = (float)errorReverse['i'][i];
1036                         float del = (float)errorReverse['d'][i];
1037                         float amb = (float)errorReverse['a'][i];
1038                         float total = match + subst + insert + del + amb;
1039                         if(total == 0){ break;  }
1040                         errorReverseFile << i+1 << '\t' << total << '\t' << match/total  << '\t' << subst/total  << '\t' << insert/total  << '\t' << del/total  << '\t' << amb/total << endl;
1041                 }
1042                 errorReverseFile.close();
1043         }
1044         catch(exception& e) {
1045                 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1046                 exit(1);
1047         }
1048 }
1049
1050 //***************************************************************************************************************
1051
1052 void SeqErrorCommand::printErrorQuality(map<char, vector<int> > qScoreErrorMap){
1053         try{
1054
1055                 string errorQualityFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.quality";
1056                 ofstream errorQualityFile;
1057                 m->openOutputFile(errorQualityFileName, errorQualityFile);
1058                 outputNames.push_back(errorQualityFileName);  outputTypes["error.quality"].push_back(errorQualityFileName);
1059
1060                 errorQualityFile << "qscore\tmatches\tsubstitutions\tinsertions\tambiguous" << endl;
1061                 for(int i=0;i<41;i++){
1062                         errorQualityFile << i << '\t' << qScoreErrorMap['m'][i] << '\t' << qScoreErrorMap['s'][i] << '\t' << qScoreErrorMap['i'][i] << '\t'<< qScoreErrorMap['a'][i] << endl;
1063                 }
1064                 errorQualityFile.close();
1065         }
1066         catch(exception& e) {
1067                 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1068                 exit(1);
1069         }
1070 }
1071
1072
1073 //***************************************************************************************************************
1074
1075 void SeqErrorCommand::printQualityFR(vector<vector<int> > qualForwardMap, vector<vector<int> > qualReverseMap){
1076
1077         try{
1078                 int numRows = 0;
1079                 int numColumns = qualForwardMap[0].size();
1080
1081                 for(int i=0;i<qualForwardMap.size();i++){
1082                         for(int j=0;j<numColumns;j++){
1083                                 if(qualForwardMap[i][j] != 0){
1084                                         if(numRows < i)         {       numRows = i+20;         }
1085                                 }
1086                         }
1087                 }
1088
1089                 string qualityForwardFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.qual.forward";
1090                 ofstream qualityForwardFile;
1091                 m->openOutputFile(qualityForwardFileName, qualityForwardFile);
1092                 outputNames.push_back(qualityForwardFileName);  outputTypes["error.qual.forward"].push_back(qualityForwardFileName);
1093
1094                 for(int i=0;i<numColumns;i++){  qualityForwardFile << '\t' << i;        }       qualityForwardFile << endl;
1095
1096                 for(int i=0;i<numRows;i++){
1097                         qualityForwardFile << i+1;
1098                         for(int j=0;j<numColumns;j++){
1099                                 qualityForwardFile << '\t' << qualForwardMap[i][j];
1100                         }
1101
1102                         qualityForwardFile << endl;
1103                 }
1104                 qualityForwardFile.close();
1105
1106                 
1107                 string qualityReverseFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.qual.reverse";
1108                 ofstream qualityReverseFile;
1109                 m->openOutputFile(qualityReverseFileName, qualityReverseFile);
1110                 outputNames.push_back(qualityReverseFileName);  outputTypes["error.qual.reverse"].push_back(qualityReverseFileName);
1111                 
1112                 for(int i=0;i<numColumns;i++){  qualityReverseFile << '\t' << i;        }       qualityReverseFile << endl;
1113                 for(int i=0;i<numRows;i++){
1114                         
1115                         qualityReverseFile << i+1;
1116                         for(int j=0;j<numColumns;j++){
1117                                 qualityReverseFile << '\t' << qualReverseMap[i][j];
1118                         }
1119                         qualityReverseFile << endl;
1120                 }
1121                 qualityReverseFile.close();
1122         }
1123         catch(exception& e) {
1124                 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1125                 exit(1);
1126         }
1127         
1128 }
1129 /**************************************************************************************************/
1130
1131 int SeqErrorCommand::setLines(string filename, string qfilename, string rfilename, vector<unsigned long int>& fastaFilePos, vector<unsigned long int>& qfileFilePos, vector<unsigned long int>& rfileFilePos) {
1132         try {
1133 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1134                 //set file positions for fasta file
1135                 fastaFilePos = m->divideFile(filename, processors);
1136                 
1137                 if (qfilename == "") { return processors; }
1138                 
1139                 //get name of first sequence in each chunk
1140                 map<string, int> firstSeqNames;
1141                 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
1142                         ifstream in;
1143                         m->openInputFile(filename, in);
1144                         in.seekg(fastaFilePos[i]);
1145                         
1146                         Sequence temp(in); 
1147                         firstSeqNames[temp.getName()] = i;
1148                         
1149                         in.close();
1150                 }
1151                 
1152                 //make copy to use below
1153                 map<string, int> firstSeqNamesReport = firstSeqNames;
1154                 
1155                 //seach for filePos of each first name in the qfile and save in qfileFilePos
1156                 ifstream inQual;
1157                 m->openInputFile(qfilename, inQual);
1158                 
1159                 string input;
1160                 while(!inQual.eof()){   
1161                         input = m->getline(inQual);
1162                         
1163                         if (input.length() != 0) {
1164                                 if(input[0] == '>'){ //this is a sequence name line
1165                                         istringstream nameStream(input);
1166                                         
1167                                         string sname = "";  nameStream >> sname;
1168                                         sname = sname.substr(1);
1169                                         
1170                                         map<string, int>::iterator it = firstSeqNames.find(sname);
1171                                         
1172                                         if(it != firstSeqNames.end()) { //this is the start of a new chunk
1173                                                 unsigned long int pos = inQual.tellg(); 
1174                                                 qfileFilePos.push_back(pos - input.length() - 1);       
1175                                                 firstSeqNames.erase(it);
1176                                         }
1177                                 }
1178                         }
1179                         
1180                         if (firstSeqNames.size() == 0) { break; }
1181                 }
1182                 inQual.close();
1183                 
1184                 if (firstSeqNames.size() != 0) { 
1185                         for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
1186                                 m->mothurOut(it->first + " is in your fasta file and not in your quality file, aborting."); m->mothurOutEndLine();
1187                         }
1188                         m->control_pressed = true;
1189                         return processors;
1190                 }
1191                 
1192                 //get last file position of qfile
1193                 FILE * pFile;
1194                 unsigned long int size;
1195                 
1196                 //get num bytes in file
1197                 pFile = fopen (qfilename.c_str(),"rb");
1198                 if (pFile==NULL) perror ("Error opening file");
1199                 else{
1200                         fseek (pFile, 0, SEEK_END);
1201                         size=ftell (pFile);
1202                         fclose (pFile);
1203                 }
1204                 
1205                 qfileFilePos.push_back(size);
1206                 
1207                 //seach for filePos of each first name in the rfile and save in rfileFilePos
1208                 string junk;
1209                 ifstream inR;
1210                 m->openInputFile(rfilename, inR);
1211                 
1212                 //read column headers
1213                 for (int i = 0; i < 16; i++) {  
1214                         if (!inR.eof()) {       inR >> junk;    }
1215                         else                    {       break;                  }
1216                 }
1217                 
1218                 while(!inR.eof()){
1219                         
1220                         if (m->control_pressed) { inR.close();  return processors; }
1221                         
1222                         input = m->getline(inR);        
1223                         
1224                         if (input.length() != 0) {
1225                                 
1226                                 istringstream nameStream(input);
1227                                 string sname = "";  nameStream >> sname;
1228                                 
1229                                 map<string, int>::iterator it = firstSeqNamesReport.find(sname);
1230                         
1231                                 if(it != firstSeqNamesReport.end()) { //this is the start of a new chunk
1232                                         unsigned long int pos = inR.tellg(); 
1233                                         rfileFilePos.push_back(pos - input.length() - 1);       
1234                                         firstSeqNamesReport.erase(it);
1235                                 }
1236                         }
1237                         
1238                         if (firstSeqNamesReport.size() == 0) { break; }
1239                         m->gobble(inR);
1240                 }
1241                 inR.close();
1242                 
1243                 if (firstSeqNamesReport.size() != 0) { 
1244                         for (map<string, int>::iterator it = firstSeqNamesReport.begin(); it != firstSeqNamesReport.end(); it++) {
1245                                 m->mothurOut(it->first + " is in your fasta file and not in your report file, aborting."); m->mothurOutEndLine();
1246                         }
1247                         m->control_pressed = true;
1248                         return processors;
1249                 }
1250                 
1251                 //get last file position of qfile
1252                 FILE * rFile;
1253                 unsigned long int sizeR;
1254                 
1255                 //get num bytes in file
1256                 rFile = fopen (rfilename.c_str(),"rb");
1257                 if (rFile==NULL) perror ("Error opening file");
1258                 else{
1259                         fseek (rFile, 0, SEEK_END);
1260                         sizeR=ftell (rFile);
1261                         fclose (rFile);
1262                 }
1263                 
1264                 rfileFilePos.push_back(sizeR);
1265                 
1266                 return processors;
1267                 
1268 #else
1269                 
1270                 fastaFilePos.push_back(0); qfileFilePos.push_back(0);
1271                 //get last file position of fastafile
1272                 FILE * pFile;
1273                 unsigned long int size;
1274                 
1275                 //get num bytes in file
1276                 pFile = fopen (filename.c_str(),"rb");
1277                 if (pFile==NULL) perror ("Error opening file");
1278                 else{
1279                         fseek (pFile, 0, SEEK_END);
1280                         size=ftell (pFile);
1281                         fclose (pFile);
1282                 }
1283                 fastaFilePos.push_back(size);
1284                 
1285                 //get last file position of fastafile
1286                 FILE * qFile;
1287                 
1288                 //get num bytes in file
1289                 qFile = fopen (qfilename.c_str(),"rb");
1290                 if (qFile==NULL) perror ("Error opening file");
1291                 else{
1292                         fseek (qFile, 0, SEEK_END);
1293                         size=ftell (qFile);
1294                         fclose (qFile);
1295                 }
1296                 qfileFilePos.push_back(size);
1297                 
1298                 return 1;
1299                 
1300 #endif
1301         }
1302         catch(exception& e) {
1303                 m->errorOut(e, "SeqErrorCommand", "setLines");
1304                 exit(1);
1305         }
1306 }
1307 //***************************************************************************************************************