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