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