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