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