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