]> git.donarmstrong.com Git - mothur.git/blob - seqerrorcommand.cpp
mods to seq.errror
[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
15 //**********************************************************************************************************************
16 vector<string> SeqErrorCommand::getValidParameters(){   
17         try {
18                 string Array[] =  {"query", "reference", "name", "qfile", "report", "threshold", "inputdir", "outputdir"};
19                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
20                 return myArray;
21         }
22         catch(exception& e) {
23                 m->errorOut(e, "SeqErrorCommand", "getValidParameters");
24                 exit(1);
25         }
26 }
27 //**********************************************************************************************************************
28 SeqErrorCommand::SeqErrorCommand(){     
29         try {
30                 abort = true; calledHelp = true; 
31                 vector<string> tempOutNames;
32                 outputTypes["error.summary"] = tempOutNames;
33                 outputTypes["error.seq"] = tempOutNames;
34                 outputTypes["error.quality"] = tempOutNames;
35                 outputTypes["error.qual.forward"] = tempOutNames;
36                 outputTypes["error.qual.reverse"] = tempOutNames;
37                 outputTypes["error.forward"] = tempOutNames;
38                 outputTypes["error.reverse"] = tempOutNames;
39                 outputTypes["error.count"] = tempOutNames;
40                 outputTypes["error.matrix"] = tempOutNames;
41         }
42         catch(exception& e) {
43                 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
44                 exit(1);
45         }
46 }
47 //**********************************************************************************************************************
48 vector<string> SeqErrorCommand::getRequiredParameters(){        
49         try {
50                 string Array[] =  {"query","reference"};
51                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
52                 return myArray;
53         }
54         catch(exception& e) {
55                 m->errorOut(e, "SeqErrorCommand", "getRequiredParameters");
56                 exit(1);
57         }
58 }
59 //**********************************************************************************************************************
60 vector<string> SeqErrorCommand::getRequiredFiles(){     
61         try {
62                 vector<string> myArray;
63                 return myArray;
64         }
65         catch(exception& e) {
66                 m->errorOut(e, "SeqErrorCommand", "getRequiredFiles");
67                 exit(1);
68         }
69 }
70 //***************************************************************************************************************
71
72 SeqErrorCommand::SeqErrorCommand(string option)  {
73         try {
74                 
75                 abort = false; calledHelp = false;   
76                 
77                 //allow user to run help
78                 if(option == "help") { help(); abort = true; calledHelp = true; }
79                 
80                 else {
81                         string temp;
82                         
83                         //valid paramters for this command
84                         string AlignArray[] =  {"query", "reference", "name", "qfile", "report", "threshold", "inputdir", "ignorechimeras", "outputdir"};
85                         
86                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
87                         
88                         OptionParser parser(option);
89                         map<string,string> parameters = parser.getParameters();
90                         
91                         ValidParameters validParameter;
92                         map<string,string>::iterator it;
93                         
94                         //check to make sure all parameters are valid for command
95                         for (it = parameters.begin(); it != parameters.end(); it++) { 
96                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
97                         }
98                         
99                         //initialize outputTypes
100                         vector<string> tempOutNames;
101                         outputTypes["error.summary"] = tempOutNames;
102                         outputTypes["error.seq"] = tempOutNames;
103                         outputTypes["error.quality"] = tempOutNames;
104                         outputTypes["error.qual.forward"] = tempOutNames;
105                         outputTypes["error.qual.reverse"] = tempOutNames;
106                         outputTypes["error.forward"] = tempOutNames;
107                         outputTypes["error.reverse"] = tempOutNames;
108                         outputTypes["error.count"] = tempOutNames;
109                         outputTypes["error.matrix"] = tempOutNames;
110
111                         
112                         //if the user changes the input directory command factory will send this info to us in the output parameter 
113                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
114                         if (inputDir == "not found"){   inputDir = "";          }
115                         else {
116                                 string path;
117                                 it = parameters.find("query");
118                                 //user has given a template file
119                                 if(it != parameters.end()){ 
120                                         path = m->hasPath(it->second);
121                                         //if the user has not given a path then, add inputdir. else leave path alone.
122                                         if (path == "") {       parameters["query"] = inputDir + it->second;            }
123                                 }
124                                 
125                                 it = parameters.find("reference");
126                                 //user has given a template file
127                                 if(it != parameters.end()){ 
128                                         path = m->hasPath(it->second);
129                                         //if the user has not given a path then, add inputdir. else leave path alone.
130                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
131                                 }
132                                 
133                                 it = parameters.find("name");
134                                 //user has given a names file
135                                 if(it != parameters.end()){ 
136                                         path = m->hasPath(it->second);
137                                         //if the user has not given a path then, add inputdir. else leave path alone.
138                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
139                                 }
140
141                                 it = parameters.find("qfile");
142                                 //user has given a quality score file
143                                 if(it != parameters.end()){ 
144                                         path = m->hasPath(it->second);
145                                         //if the user has not given a path then, add inputdir. else leave path alone.
146                                         if (path == "") {       parameters["qfile"] = inputDir + it->second;            }
147                                 }
148                                 
149                                 it = parameters.find("report");
150                                 //user has given a alignment report file
151                                 if(it != parameters.end()){ 
152                                         path = m->hasPath(it->second);
153                                         //if the user has not given a path then, add inputdir. else leave path alone.
154                                         if (path == "") {       parameters["report"] = inputDir + it->second;           }
155                                 }
156                                 
157                         }
158                         //check for required parameters
159                         queryFileName = validParameter.validFile(parameters, "query", true);
160                         if (queryFileName == "not found") { m->mothurOut("query is a required parameter for the seq.error command."); m->mothurOutEndLine(); abort = true; }
161                         else if (queryFileName == "not open") { abort = true; } 
162                         
163                         referenceFileName = validParameter.validFile(parameters, "reference", true);
164                         if (referenceFileName == "not found") { m->mothurOut("reference is a required parameter for the seq.error command."); m->mothurOutEndLine(); abort = true; }
165                         else if (referenceFileName == "not open") { abort = true; }     
166                         
167
168                         //check for optional parameters
169                         namesFileName = validParameter.validFile(parameters, "name", true);
170                         if(namesFileName == "not found"){       namesFileName = "";     }
171                         
172                         qualFileName = validParameter.validFile(parameters, "qfile", true);
173                         if(qualFileName == "not found"){        qualFileName = "";      }
174
175                         reportFileName = validParameter.validFile(parameters, "report", true);
176                         if(reportFileName == "not found"){      reportFileName = "";    }
177                         
178                         if((reportFileName != "" && qualFileName == "") || (reportFileName == "" && qualFileName != "")){
179                                 m->mothurOut("if you use either a qual file or a report file, you have to have both.");
180                                 m->mothurOutEndLine();
181                                 abort = true; 
182                         }
183                         
184                         outputDir = validParameter.validFile(parameters, "outputdir", false);
185                         if (outputDir == "not found"){  
186                                 outputDir = ""; 
187                                 outputDir += m->hasPath(queryFileName); //if user entered a file with a path then preserve it   
188                         }
189                         
190                         //check for optional parameter and set defaults
191                         // ...at some point should added some additional type checking...
192                         temp = validParameter.validFile(parameters, "threshold", false);        if (temp == "not found") { temp = "1.00"; }
193                         convert(temp, threshold);  
194                         
195                         temp = validParameter.validFile(parameters, "ignorechimeras", false);   if (temp == "not found") { temp = "1"; }
196                         convert(temp, ignoreChimeras);  
197
198                         substitutionMatrix.resize(6);
199                         for(int i=0;i<6;i++){   substitutionMatrix[i].assign(6,0);      }
200                 }
201         }
202         catch(exception& e) {
203                 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
204                 exit(1);
205         }
206 }
207
208 //**********************************************************************************************************************
209
210 void SeqErrorCommand::help(){
211         try {
212                 m->mothurOut("The seq.error command reads a query alignment file and a reference alignment file and creates .....\n");
213                 m->mothurOut("Example seq.error(...).\n");
214                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n");
215                 m->mothurOut("For more details please check out the wiki http://www.mothur.org/wiki/seq.error .\n\n");
216         }
217         catch(exception& e) {
218                 m->errorOut(e, "SeqErrorCommand", "help");
219                 exit(1);
220         }
221 }
222
223 //***************************************************************************************************************
224
225 SeqErrorCommand::~SeqErrorCommand(){    /*      void    */      }
226
227 //***************************************************************************************************************
228
229 int SeqErrorCommand::execute(){
230         try{
231                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
232
233                 string errorSummaryFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.summary";
234                 m->openOutputFile(errorSummaryFileName, errorSummaryFile);
235                 outputNames.push_back(errorSummaryFileName); outputTypes["error.summary"].push_back(errorSummaryFileName);
236                 printErrorHeader();
237                 
238                 string errorSeqFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq";
239                 m->openOutputFile(errorSeqFileName, errorSeqFile);
240                 outputNames.push_back(errorSeqFileName); outputTypes["error.seq"].push_back(errorSeqFileName);
241
242                 getReferences();        //read in reference sequences - make sure there's no ambiguous bases
243
244                 map<string, int> weights;
245                 if(namesFileName != ""){        weights = getWeights(); }
246                 
247                 ifstream queryFile;
248                 m->openInputFile(queryFileName, queryFile);
249                 
250                 ifstream reportFile;
251                 ifstream qualFile;
252
253                 ReportFile report;
254                 QualityScores quality;
255                 vector<vector<int> > qualForwardMap;
256                 vector<vector<int> > qualReverseMap;
257                 
258                 if(qualFileName != "" && reportFileName != ""){
259                         m->openInputFile(qualFileName, qualFile);
260                         report = ReportFile(reportFile, reportFileName);
261                         
262                         qualForwardMap.resize(1000);
263                         qualReverseMap.resize(1000);
264                         for(int i=0;i<1000;i++){
265                                 qualForwardMap[i].assign(100,0);
266                                 qualReverseMap[i].assign(100,0);
267                         }                               
268                 }
269                 
270                 int totalBases = 0;
271                 int totalMatches = 0;
272                 
273                 vector<int> misMatchCounts(11, 0);
274                 int maxMismatch = 0;
275                 int numSeqs = 0;
276                 
277                 map<string, int>::iterator it;
278                 map<char, vector<int> > qScoreErrorMap;
279                 qScoreErrorMap['m'].assign(41, 0);
280                 qScoreErrorMap['s'].assign(41, 0);
281                 qScoreErrorMap['i'].assign(41, 0);
282                 qScoreErrorMap['a'].assign(41, 0);
283                 
284                 map<char, vector<int> > errorForward;
285                 errorForward['m'].assign(1000,0);
286                 errorForward['s'].assign(1000,0);
287                 errorForward['i'].assign(1000,0);
288                 errorForward['d'].assign(1000,0);
289                 errorForward['a'].assign(1000,0);
290                 
291                 map<char, vector<int> > errorReverse;
292                 errorReverse['m'].assign(1000,0);
293                 errorReverse['s'].assign(1000,0);
294                 errorReverse['i'].assign(1000,0);
295                 errorReverse['d'].assign(1000,0);
296                 errorReverse['a'].assign(1000,0);       
297                 
298
299                 string errorChimeraFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.chimera";
300                 RefChimeraTest chimeraTest(referenceSeqs, errorChimeraFileName);
301                 outputNames.push_back(errorChimeraFileName); outputTypes["error.chimera"].push_back(errorChimeraFileName);
302                 
303                 vector<string> megaAlignVector(numRefs, "");
304                                 
305                 int index = 0;
306                 bool ignoreSeq = 0;
307                 
308                 while(queryFile){
309                         
310                         if (m->control_pressed) { errorSummaryFile.close();     errorSeqFile.close(); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
311                 
312                         Sequence query(queryFile);
313                                                 
314                         int numParentSeqs = chimeraTest.analyzeQuery(query.getName(), query.getAligned());
315                         int closestRefIndex = chimeraTest.getClosestRefIndex();
316
317                         if(numParentSeqs > 1 && ignoreChimeras == 1)    {       ignoreSeq = 1;  }
318                         else                                                                                    {       ignoreSeq = 0;  }
319
320
321                         Compare minCompare = getErrors(query, referenceSeqs[closestRefIndex]);
322                         
323                         if(namesFileName != ""){
324                                 it = weights.find(query.getName());
325                                 minCompare.weight = it->second;
326                         }
327                         else    {       minCompare.weight = 1;  }
328
329                         printErrorData(minCompare, numParentSeqs);
330                         
331                         
332                         if(!ignoreSeq){
333                                 for(int i=0;i<minCompare.total;i++){
334                                         char letter = minCompare.sequence[i];
335                                         errorForward[letter][i] += minCompare.weight;
336                                         errorReverse[letter][minCompare.total-i-1] += minCompare.weight;                                
337                                 }
338                         }
339                         
340                         if(qualFileName != "" && reportFileName != ""){
341                                 report = ReportFile(reportFile);
342                                 
343 //                              int origLength = report.getQueryLength();
344                                 int startBase = report.getQueryStart();
345                                 int endBase = report.getQueryEnd();
346
347                                 quality = QualityScores(qualFile);
348
349                                 if(!ignoreSeq){
350                                         quality.updateQScoreErrorMap(qScoreErrorMap, minCompare.sequence, startBase, endBase, minCompare.weight);
351                                         quality.updateForwardMap(qualForwardMap, startBase, endBase, minCompare.weight);
352                                         quality.updateReverseMap(qualReverseMap, startBase, endBase, minCompare.weight);
353                                 }
354                         }                       
355                         
356                         if(minCompare.errorRate < threshold && !ignoreSeq){
357                                 totalBases += (minCompare.total * minCompare.weight);
358                                 totalMatches += minCompare.matches * minCompare.weight;
359                                 if(minCompare.mismatches > maxMismatch){
360                                         maxMismatch = minCompare.mismatches;
361                                         misMatchCounts.resize(maxMismatch + 1, 0);
362                                 }                               
363                                 misMatchCounts[minCompare.mismatches] += minCompare.weight;
364                                 numSeqs++;
365                                 
366                                 
367                                 megaAlignVector[closestRefIndex] += query.getInlineSeq() + '\n';
368                         }
369                         
370                         index++;
371                         if(index % 1000 == 0){  cout << index << endl;  }
372                 }
373                 queryFile.close();
374                 errorSummaryFile.close();       
375                 errorSeqFile.close();
376
377                 if(qualFileName != "" && reportFileName != ""){         
378                         printErrorQuality(qScoreErrorMap);
379                         printQualityFR(qualForwardMap, qualReverseMap);
380                 }
381                 
382                 printErrorFRFile(errorForward, errorReverse);
383                 
384                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
385
386                 string errorCountFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.count";
387                 ofstream errorCountFile;
388                 m->openOutputFile(errorCountFileName, errorCountFile);
389                 outputNames.push_back(errorCountFileName);  outputTypes["error.count"].push_back(errorCountFileName);
390                 m->mothurOut("Overall error rate:\t" + toString((double)(totalBases - totalMatches) / (double)totalBases) + "\n\n");
391                 m->mothurOut("Errors\tSequences\n");
392                 errorCountFile << "Errors\tSequences\n";                
393                 for(int i=0;i<misMatchCounts.size();i++){
394                         m->mothurOut(toString(i) + '\t' + toString(misMatchCounts[i]) + '\n');
395                         errorCountFile << i << '\t' << misMatchCounts[i] << endl;
396                 }
397                 errorCountFile.close();
398                 
399                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
400
401                 printSubMatrix();
402                                 
403                 string megAlignmentFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".ref-query";
404                 ofstream megAlignmentFile;
405                 m->openOutputFile(megAlignmentFileName, megAlignmentFile);
406                 
407                 for(int i=0;i<numRefs;i++){
408                         megAlignmentFile << referenceSeqs[i].getInlineSeq() << endl;
409                         megAlignmentFile << megaAlignVector[i] << endl;
410                 }
411                 
412                 
413                 m->mothurOutEndLine();
414                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
415                 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
416                 m->mothurOutEndLine();
417                 
418                 return 0;       
419         }
420         catch(exception& e) {
421                 m->errorOut(e, "SeqErrorCommand", "execute");
422                 exit(1);
423         }
424 }
425
426 //***************************************************************************************************************
427
428 void SeqErrorCommand::getReferences(){
429         try {
430                 
431                 ifstream referenceFile;
432                 m->openInputFile(referenceFileName, referenceFile);
433                 
434                 int numAmbigSeqs = 0;
435                 
436                 int maxStartPos = 0;
437                 int minEndPos = 100000;
438                 
439                 while(referenceFile){
440                         Sequence currentSeq(referenceFile);
441                         int numAmbigs = currentSeq.getAmbigBases();
442                         if(numAmbigs > 0){      numAmbigSeqs++; }
443                         
444                         int startPos = currentSeq.getStartPos();
445                         if(startPos > maxStartPos)      {       maxStartPos = startPos; }
446
447                         int endPos = currentSeq.getEndPos();
448                         if(endPos < minEndPos)          {       minEndPos = endPos;             }
449                         referenceSeqs.push_back(currentSeq);
450                         m->gobble(referenceFile);
451                 }
452                 referenceFile.close();
453                 numRefs = referenceSeqs.size();
454
455                 for(int i=0;i<numRefs;i++){
456                         referenceSeqs[i].padToPos(maxStartPos);
457                         referenceSeqs[i].padFromPos(minEndPos);
458                 }
459                 
460                 if(numAmbigSeqs != 0){
461                         m->mothurOut("Warning: " + toString(numAmbigSeqs) + " reference sequences have ambiguous bases, these bases will be ignored\n");
462                 }               
463                 
464         }
465         catch(exception& e) {
466                 m->errorOut(e, "SeqErrorCommand", "getReferences");
467                 exit(1);
468         }
469 }
470
471 //***************************************************************************************************************
472
473 Compare SeqErrorCommand::getErrors(Sequence query, Sequence reference){
474         try {
475                 if(query.getAlignLength() != reference.getAlignLength()){
476                         m->mothurOut("Warning: " + toString(query.getName()) + " and " + toString(reference.getName()) + " are different lengths\n");
477                 }
478                 int alignLength = query.getAlignLength();
479         
480                 string q = query.getAligned();
481                 string r = reference.getAligned();
482
483                 int started = 0;
484                 Compare errors;
485
486                 for(int i=0;i<alignLength;i++){
487                         if(q[i] != 'N' && q[i] != '.' && r[i] != '.' && (q[i] != '-' || r[i] != '-')){                  //      no missing data and no double gaps
488                                 started = 1;
489                                 
490                                 if(q[i] == 'A'){
491                                         if(r[i] == 'A'){        errors.AA++;    errors.matches++;       errors.sequence += 'm'; }
492                                         if(r[i] == 'T'){        errors.AT++;    errors.sequence += 's'; }
493                                         if(r[i] == 'G'){        errors.AG++;    errors.sequence += 's'; }
494                                         if(r[i] == 'C'){        errors.AC++;    errors.sequence += 's'; }
495                                         if(r[i] == '-'){        errors.Ai++;    errors.sequence += 'i'; }
496                                 }
497                                 else if(q[i] == 'T'){
498                                         if(r[i] == 'A'){        errors.TA++;    errors.sequence += 's'; }
499                                         if(r[i] == 'T'){        errors.TT++;    errors.matches++;       errors.sequence += 'm'; }
500                                         if(r[i] == 'G'){        errors.TG++;    errors.sequence += 's'; }
501                                         if(r[i] == 'C'){        errors.TC++;    errors.sequence += 's'; }
502                                         if(r[i] == '-'){        errors.Ti++;    errors.sequence += 'i'; }
503                                 }
504                                 else if(q[i] == 'G'){
505                                         if(r[i] == 'A'){        errors.GA++;    errors.sequence += 's'; }
506                                         if(r[i] == 'T'){        errors.GT++;    errors.sequence += 's'; }
507                                         if(r[i] == 'G'){        errors.GG++;    errors.matches++;       errors.sequence += 'm'; }
508                                         if(r[i] == 'C'){        errors.GC++;    errors.sequence += 's'; }
509                                         if(r[i] == '-'){        errors.Gi++;    errors.sequence += 'i'; }
510                                 }
511                                 else if(q[i] == 'C'){
512                                         if(r[i] == 'A'){        errors.CA++;    errors.sequence += 's'; }
513                                         if(r[i] == 'T'){        errors.CT++;    errors.sequence += 's'; }
514                                         if(r[i] == 'G'){        errors.CG++;    errors.sequence += 's'; }
515                                         if(r[i] == 'C'){        errors.CC++;    errors.matches++;       errors.sequence += 'm'; }
516                                         if(r[i] == '-'){        errors.Ci++;    errors.sequence += 'i'; }
517                                 }
518                                 else if(q[i] == 'N'){
519                                         if(r[i] == 'A'){        errors.NA++;    errors.sequence += 'a'; }
520                                         if(r[i] == 'T'){        errors.NT++;    errors.sequence += 'a'; }
521                                         if(r[i] == 'G'){        errors.NG++;    errors.sequence += 'a'; }
522                                         if(r[i] == 'C'){        errors.NC++;    errors.sequence += 'a'; }
523                                         if(r[i] == '-'){        errors.Ni++;    errors.sequence += 'a'; }
524                                 }
525                                 else if(q[i] == '-' && r[i] != '-'){
526                                         if(r[i] == 'A'){        errors.dA++;    errors.sequence += 'd'; }
527                                         if(r[i] == 'T'){        errors.dT++;    errors.sequence += 'd'; }
528                                         if(r[i] == 'G'){        errors.dG++;    errors.sequence += 'd'; }
529                                         if(r[i] == 'C'){        errors.dC++;    errors.sequence += 'd'; }
530                                 }
531                                 errors.total++; 
532                                 
533                         }
534                         else if(q[i] == '.' && r[i] != '.'){            //      reference extends beyond query
535                                 if(started == 1){       break;  }
536                         }
537                         else if(q[i] != '.' && r[i] == '.'){            //      query extends beyond reference
538                                 if(started == 1){       break;  }
539                         }
540                         else if(q[i] == '.' && r[i] == '.'){            //      both are missing data
541                                 if(started == 1){       break;  }                       
542                         }
543                         
544                 }
545                 errors.mismatches = errors.total-errors.matches;
546                 errors.errorRate = (double)(errors.total-errors.matches) / (double)errors.total;
547                 errors.queryName = query.getName();
548                 errors.refName = reference.getName();
549                 
550                 return errors;
551         }
552         catch(exception& e) {
553                 m->errorOut(e, "SeqErrorCommand", "getErrors");
554                 exit(1);
555         }
556 }
557
558 //***************************************************************************************************************
559
560 map<string, int> SeqErrorCommand::getWeights(){
561         ifstream nameFile;
562         m->openInputFile(namesFileName, nameFile);
563         
564         string seqName;
565         string redundantSeqs;
566         map<string, int> nameCountMap;
567         
568         while(nameFile){
569                 nameFile >> seqName >> redundantSeqs;
570                 nameCountMap[seqName] = m->getNumNames(redundantSeqs); 
571                 m->gobble(nameFile);
572         }
573         return nameCountMap;
574 }
575
576
577 //***************************************************************************************************************
578
579 void SeqErrorCommand::printErrorHeader(){
580         try {
581                 errorSummaryFile << "query\treference\tweight\t";
582                 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";
583                 errorSummaryFile << "insertions\tdeletions\tsubstitutions\tambig\tmatches\tmismatches\ttotal\terror\tnumparents\n";
584                 
585                 errorSummaryFile << setprecision(6);
586                 errorSummaryFile.setf(ios::fixed);
587         }
588         catch(exception& e) {
589                 m->errorOut(e, "SeqErrorCommand", "printErrorHeader");
590                 exit(1);
591         }
592 }
593
594 //***************************************************************************************************************
595
596 void SeqErrorCommand::printErrorData(Compare error, int numParentSeqs){
597         try {
598                 errorSummaryFile << error.queryName << '\t' << error.refName << '\t' << error.weight << '\t';
599                 errorSummaryFile << error.AA << '\t' << error.AT << '\t' << error.AG << '\t' << error.AC << '\t';
600                 errorSummaryFile << error.TA << '\t' << error.TT << '\t' << error.TG << '\t' << error.TC << '\t';
601                 errorSummaryFile << error.GA << '\t' << error.GT << '\t' << error.GG << '\t' << error.GC << '\t';
602                 errorSummaryFile << error.CA << '\t' << error.CT << '\t' << error.CG << '\t' << error.CC << '\t';
603                 errorSummaryFile << error.NA << '\t' << error.NT << '\t' << error.NG << '\t' << error.NC << '\t';
604                 errorSummaryFile << error.Ai << '\t' << error.Ti << '\t' << error.Gi << '\t' << error.Ci << '\t' << error.Ni << '\t' ;
605                 errorSummaryFile << error.dA << '\t' << error.dT << '\t' << error.dG << '\t' << error.dC << '\t';
606                 
607                 errorSummaryFile << error.Ai + error.Ti + error.Gi + error.Ci << '\t';                  //insertions
608                 errorSummaryFile << error.dA + error.dT + error.dG + error.dC << '\t';                  //deletions
609                 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
610                 errorSummaryFile << error.NA + error.NT + error.NG + error.NC + error.Ni << '\t';       //ambiguities
611                 errorSummaryFile << error.matches << '\t' << error.mismatches << '\t' << error.total << '\t' << error.errorRate << '\t' << numParentSeqs << endl;
612                 
613                 errorSeqFile << '>' << error.queryName << "\tref:" << error.refName << '\n' << error.sequence << endl;
614                 
615                 
616                 int a=0;                int t=1;                int g=2;                int c=3;
617                 int gap=4;              int n=5;
618                 if(numParentSeqs == 1 || ignoreChimeras == 0){
619                         substitutionMatrix[a][a] += error.weight * error.AA;
620                         substitutionMatrix[a][t] += error.weight * error.TA;
621                         substitutionMatrix[a][g] += error.weight * error.GA;
622                         substitutionMatrix[a][c] += error.weight * error.CA;
623                         substitutionMatrix[a][gap] += error.weight * error.dA;
624                         substitutionMatrix[a][n] += error.weight * error.NA;
625
626                         substitutionMatrix[t][a] += error.weight * error.AT;
627                         substitutionMatrix[t][t] += error.weight * error.TT;
628                         substitutionMatrix[t][g] += error.weight * error.GT;
629                         substitutionMatrix[t][c] += error.weight * error.CT;
630                         substitutionMatrix[t][gap] += error.weight * error.dT;
631                         substitutionMatrix[t][n] += error.weight * error.NT;
632
633                         substitutionMatrix[g][a] += error.weight * error.AG;
634                         substitutionMatrix[g][t] += error.weight * error.TG;
635                         substitutionMatrix[g][g] += error.weight * error.GG;
636                         substitutionMatrix[g][c] += error.weight * error.CG;
637                         substitutionMatrix[g][gap] += error.weight * error.dG;
638                         substitutionMatrix[g][n] += error.weight * error.NG;
639
640                         substitutionMatrix[c][a] += error.weight * error.AC;
641                         substitutionMatrix[c][t] += error.weight * error.TC;
642                         substitutionMatrix[c][g] += error.weight * error.GC;
643                         substitutionMatrix[c][c] += error.weight * error.CC;
644                         substitutionMatrix[c][gap] += error.weight * error.dC;
645                         substitutionMatrix[c][n] += error.weight * error.NC;
646
647                         substitutionMatrix[gap][a] += error.weight * error.Ai;
648                         substitutionMatrix[gap][t] += error.weight * error.Ti;
649                         substitutionMatrix[gap][g] += error.weight * error.Gi;
650                         substitutionMatrix[gap][c] += error.weight * error.Ci;
651                         substitutionMatrix[gap][n] += error.weight * error.Ni;
652                 }
653         }
654         catch(exception& e) {
655                 m->errorOut(e, "SeqErrorCommand", "printErrorData");
656                 exit(1);
657         }
658 }
659
660 //***************************************************************************************************************
661
662 void SeqErrorCommand::printSubMatrix(){
663         try {
664                 string subMatrixFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.matrix";
665                 ofstream subMatrixFile;
666                 m->openOutputFile(subMatrixFileName, subMatrixFile);
667                 outputNames.push_back(subMatrixFileName);  outputTypes["error.matrix"].push_back(subMatrixFileName);
668                 vector<string> bases(6);
669                 bases[0] = "A";
670                 bases[1] = "T";
671                 bases[2] = "G";
672                 bases[3] = "C";
673                 bases[4] = "Gap";
674                 bases[5] = "N";
675                 vector<int> refSums(5,1);
676
677                 for(int i=0;i<5;i++){
678                         subMatrixFile << "\tr" << bases[i];
679                         
680                         for(int j=0;j<6;j++){
681                                 refSums[i] += substitutionMatrix[i][j];                         
682                         }
683                 }
684                 subMatrixFile << endl;
685                 
686                 for(int i=0;i<6;i++){
687                         subMatrixFile << 'q' << bases[i];
688                         for(int j=0;j<5;j++){
689                                 subMatrixFile << '\t' << substitutionMatrix[j][i];                              
690                         }
691                         subMatrixFile << endl;
692                 }
693
694                 subMatrixFile << "total";
695                 for(int i=0;i<5;i++){
696                         subMatrixFile << '\t' << refSums[i];
697                 }
698                 subMatrixFile << endl;
699                 subMatrixFile.close();
700         }
701         catch(exception& e) {
702                 m->errorOut(e, "SeqErrorCommand", "printSubMatrix");
703                 exit(1);
704         }
705 }
706 //***************************************************************************************************************
707
708 void SeqErrorCommand::printErrorFRFile(map<char, vector<int> > errorForward, map<char, vector<int> > errorReverse){
709         try{
710                 string errorForwardFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq.forward";
711                 ofstream errorForwardFile;
712                 m->openOutputFile(errorForwardFileName, errorForwardFile);
713                 outputNames.push_back(errorForwardFileName);  outputTypes["error.forward"].push_back(errorForwardFileName);
714
715                 errorForwardFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
716                 for(int i=0;i<1000;i++){
717                         float match = (float)errorForward['m'][i];
718                         float subst = (float)errorForward['s'][i];
719                         float insert = (float)errorForward['i'][i];
720                         float del = (float)errorForward['d'][i];
721                         float amb = (float)errorForward['a'][i];
722                         float total = match + subst + insert + del + amb;
723                         if(total == 0){ break;  }
724                         errorForwardFile << i+1 << '\t' << total << '\t' << match/total  << '\t' << subst/total  << '\t' << insert/total  << '\t' << del/total  << '\t' << amb/total << endl;
725                 }
726                 errorForwardFile.close();
727
728                 string errorReverseFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.seq.reverse";
729                 ofstream errorReverseFile;
730                 m->openOutputFile(errorReverseFileName, errorReverseFile);
731                 outputNames.push_back(errorReverseFileName);  outputTypes["error.reverse"].push_back(errorReverseFileName);
732
733                 errorReverseFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
734                 for(int i=0;i<1000;i++){
735                         float match = (float)errorReverse['m'][i];
736                         float subst = (float)errorReverse['s'][i];
737                         float insert = (float)errorReverse['i'][i];
738                         float del = (float)errorReverse['d'][i];
739                         float amb = (float)errorReverse['a'][i];
740                         float total = match + subst + insert + del + amb;
741                         if(total == 0){ break;  }
742                         errorReverseFile << i+1 << '\t' << total << '\t' << match/total  << '\t' << subst/total  << '\t' << insert/total  << '\t' << del/total  << '\t' << amb/total << endl;
743                 }
744                 errorReverseFile.close();
745         }
746         catch(exception& e) {
747                 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
748                 exit(1);
749         }
750 }
751
752 //***************************************************************************************************************
753
754 void SeqErrorCommand::printErrorQuality(map<char, vector<int> > qScoreErrorMap){
755         try{
756
757                 string errorQualityFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.quality";
758                 ofstream errorQualityFile;
759                 m->openOutputFile(errorQualityFileName, errorQualityFile);
760                 outputNames.push_back(errorQualityFileName);  outputTypes["error.quality"].push_back(errorQualityFileName);
761
762                 errorQualityFile << "qscore\tmatches\tsubstitutions\tinsertions\tambiguous" << endl;
763                 for(int i=0;i<41;i++){
764                         errorQualityFile << i << '\t' << qScoreErrorMap['m'][i] << '\t' << qScoreErrorMap['s'][i] << '\t' << qScoreErrorMap['i'][i] << '\t'<< qScoreErrorMap['a'][i] << endl;
765                 }
766                 errorQualityFile.close();
767         }
768         catch(exception& e) {
769                 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
770                 exit(1);
771         }
772 }
773
774
775 //***************************************************************************************************************
776
777 void SeqErrorCommand::printQualityFR(vector<vector<int> > qualForwardMap, vector<vector<int> > qualReverseMap){
778         try{
779
780
781                 int lastRow = 0;
782                 int lastColumn = 0;
783
784                 for(int i=0;i<qualForwardMap.size();i++){
785                         for(int j=0;j<qualForwardMap[i].size();j++){
786                                 if(qualForwardMap[i][j] != 0){
787                                         if(lastRow < i)         {       lastRow = i+2;          }
788                                         if(lastColumn < j)      {       lastColumn = j+2;       }
789                                 }
790                         }
791                 }
792
793                 string qualityForwardFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.qual.forward";
794                 ofstream qualityForwardFile;
795                 m->openOutputFile(qualityForwardFileName, qualityForwardFile);
796                 outputNames.push_back(qualityForwardFileName);  outputTypes["error.qual.forward"].push_back(qualityForwardFileName);
797
798                 for(int i=0;i<lastColumn;i++){  qualityForwardFile << '\t' << i;        }       qualityForwardFile << endl;
799
800                 for(int i=0;i<lastRow;i++){
801                         qualityForwardFile << i+1;
802                         for(int j=0;j<lastColumn;j++){
803                                 qualityForwardFile << '\t' << qualForwardMap[i][j];
804                         }
805
806                         qualityForwardFile << endl;
807                 }
808                 qualityForwardFile.close();
809
810                 
811                 string qualityReverseFileName = queryFileName.substr(0,queryFileName.find_last_of('.')) + ".error.qual.reverse";
812                 ofstream qualityReverseFile;
813                 m->openOutputFile(qualityReverseFileName, qualityReverseFile);
814                 outputNames.push_back(qualityReverseFileName);  outputTypes["error.qual.reverse"].push_back(qualityReverseFileName);
815                 
816                 for(int i=0;i<lastColumn;i++){  qualityReverseFile << '\t' << i;        }       qualityReverseFile << endl;
817                 for(int i=0;i<lastRow;i++){
818                         
819                         qualityReverseFile << i+1;
820                         for(int j=0;j<lastColumn;j++){
821                                 qualityReverseFile << '\t' << qualReverseMap[i][j];
822                         }
823                         qualityReverseFile << endl;
824                 }
825                 qualityReverseFile.close();
826         }
827         catch(exception& e) {
828                 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
829                 exit(1);
830         }
831 }
832
833
834 //***************************************************************************************************************