1 // ***************************************************************************
2 // bamtools_filter.cpp (c) 2010 Derek Barnett, Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // All rights reserved.
5 // ---------------------------------------------------------------------------
6 // Last modified: 31 August 2010
7 // ---------------------------------------------------------------------------
8 // Filters a single BAM file (or filters multiple BAM files and merges)
9 // according to some user-specified criteria.
10 // ***************************************************************************
20 #include "bamtools_filter.h"
21 #include "bamtools_filter_engine.h"
22 #include "bamtools_options.h"
23 #include "bamtools_utilities.h"
24 #include "BamReader.h"
25 #include "BamMultiReader.h"
26 #include "BamWriter.h"
29 #include "jsoncpp/json.h"
32 using namespace BamTools;
37 // -------------------------------
38 // string literal constants
41 const string ALIGNMENTFLAG_PROPERTY = "alignmentFlag";
42 const string INSERTSIZE_PROPERTY = "insertSize";
43 const string ISDUPLICATE_PROPERTY = "isDuplicate";
44 const string ISFAILEDQC_PROPERTY = "isFailedQC";
45 const string ISFIRSTMATE_PROPERTY = "isFirstMate";
46 const string ISMAPPED_PROPERTY = "isMapped";
47 const string ISMATEMAPPED_PROPERTY = "isMateMapped";
48 const string ISMATEREVERSESTRAND_PROPERTY = "isMateReverseStrand";
49 const string ISPAIRED_PROPERTY = "isPaired";
50 const string ISPRIMARYALIGNMENT_PROPERTY = "isPrimaryAlignment";
51 const string ISPROPERPAIR_PROPERTY = "isProperPair";
52 const string ISREVERSESTRAND_PROPERTY = "isReverseStrand";
53 const string ISSECONDMATE_PROPERTY = "isSecondMate";
54 const string MAPQUALITY_PROPERTY = "mapQuality";
55 const string MATEPOSITION_PROPERTY = "matePosition";
56 const string MATEREFERENCE_PROPERTY = "mateReference";
57 const string NAME_PROPERTY = "name";
58 const string POSITION_PROPERTY = "position";
59 const string QUERYBASES_PROPERTY = "queryBases";
60 const string REFERENCE_PROPERTY = "reference";
63 const string TRUE_STR = "true";
64 const string FALSE_STR = "false";
66 } // namespace BamTools
68 // ---------------------------------------------
69 // FilterToolPrivate declaration
71 class FilterTool::FilterToolPrivate {
75 FilterToolPrivate(FilterTool::FilterSettings* settings);
76 ~FilterToolPrivate(void);
84 bool AddPropertyTokensToFilter(const string& filterName, const map<string, string>& propertyTokens);
85 bool CheckAlignment(const BamAlignment& al);
86 const string GetScriptContents(void);
87 void InitProperties(void);
88 bool ParseCommandLine(void);
89 bool ParseFilterObject(const string& filterName, const Json::Value& filterObject);
90 bool ParseScript(void);
91 bool SetupFilters(void);
95 vector<string> m_propertyNames;
96 FilterTool::FilterSettings* m_settings;
97 RefVector m_references;
100 // ---------------------------------------------
101 // FilterSettings implementation
103 struct FilterTool::FilterSettings {
105 // ----------------------------------
109 bool HasInputBamFilename;
110 bool HasOutputBamFilename;
112 bool HasScriptFilename;
113 bool IsForceCompression;
116 vector<string> InputFiles;
117 string OutputFilename;
119 string ScriptFilename;
121 // -----------------------------------
122 // General filter opts
125 bool HasAlignmentFlagFilter;
126 bool HasInsertSizeFilter;
127 bool HasMapQualityFilter;
129 bool HasQueryBasesFilter;
131 // bool HasTagFilters;
134 string AlignmentFlagFilter;
135 string InsertSizeFilter;
137 string MapQualityFilter;
138 string QueryBasesFilter;
140 // vector<string> TagFilters;
142 // -----------------------------------
143 // AlignmentFlag filter opts
146 bool HasIsDuplicateFilter;
147 bool HasIsFailedQCFilter;
148 bool HasIsFirstMateFilter;
149 bool HasIsMappedFilter;
150 bool HasIsMateMappedFilter;
151 bool HasIsMateReverseStrandFilter;
152 bool HasIsPairedFilter;
153 bool HasIsPrimaryAlignmentFilter;
154 bool HasIsProperPairFilter;
155 bool HasIsReverseStrandFilter;
156 bool HasIsSecondMateFilter;
159 string IsDuplicateFilter;
160 string IsFailedQCFilter;
161 string IsFirstMateFilter;
162 string IsMappedFilter;
163 string IsMateMappedFilter;
164 string IsMateReverseStrandFilter;
165 string IsPairedFilter;
166 string IsPrimaryAlignmentFilter;
167 string IsProperPairFilter;
168 string IsReverseStrandFilter;
169 string IsSecondMateFilter;
171 // ---------------------------------
175 : HasInputBamFilename(false)
176 , HasOutputBamFilename(false)
178 , HasScriptFilename(false)
179 , IsForceCompression(false)
180 , OutputFilename(Options::StandardOut())
181 , HasAlignmentFlagFilter(false)
182 , HasInsertSizeFilter(false)
183 , HasMapQualityFilter(false)
184 , HasNameFilter(false)
185 , HasQueryBasesFilter(false)
186 // , HasTagFilters(false)
187 , HasIsDuplicateFilter(false)
188 , HasIsFailedQCFilter(false)
189 , HasIsFirstMateFilter(false)
190 , HasIsMappedFilter(false)
191 , HasIsMateMappedFilter(false)
192 , HasIsMateReverseStrandFilter(false)
193 , HasIsPairedFilter(false)
194 , HasIsPrimaryAlignmentFilter(false)
195 , HasIsProperPairFilter(false)
196 , HasIsReverseStrandFilter(false)
197 , HasIsSecondMateFilter(false)
198 , IsDuplicateFilter(TRUE_STR)
199 , IsFailedQCFilter(TRUE_STR)
200 , IsFirstMateFilter(TRUE_STR)
201 , IsMappedFilter(TRUE_STR)
202 , IsMateMappedFilter(TRUE_STR)
203 , IsMateReverseStrandFilter(TRUE_STR)
204 , IsPairedFilter(TRUE_STR)
205 , IsPrimaryAlignmentFilter(TRUE_STR)
206 , IsProperPairFilter(TRUE_STR)
207 , IsReverseStrandFilter(TRUE_STR)
208 , IsSecondMateFilter(TRUE_STR)
212 // ---------------------------------------------
213 // FilterTool implementation
215 FilterTool::FilterTool(void)
217 , m_settings(new FilterSettings)
220 // set program details
221 Options::SetProgramInfo("bamtools filter", "filters BAM file(s)", "-in <filename> [-in <filename> ... ] -out <filename> -region <REGION> [ [-script <filename] | [filterOptions] ]");
223 OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
224 Options::AddValueOption("-in", "BAM filename", "the input BAM file(s)", "", m_settings->HasInputBamFilename, m_settings->InputFiles, IO_Opts, Options::StandardIn());
225 Options::AddValueOption("-out", "BAM filename", "the output BAM file", "", m_settings->HasOutputBamFilename, m_settings->OutputFilename, IO_Opts, Options::StandardOut());
226 Options::AddValueOption("-region", "REGION", "only read data from this genomic region (see README for more details)", "", m_settings->HasRegion, m_settings->Region, IO_Opts);
227 Options::AddValueOption("-script", "filename", "the filter script file (see README for more details)", "", m_settings->HasScriptFilename, m_settings->ScriptFilename, IO_Opts);
228 Options::AddOption("-forceCompression", "if results are sent to stdout (like when piping to another tool), default behavior is to leave output uncompressed. Use this flag to override and force compression", m_settings->IsForceCompression, IO_Opts);
230 OptionGroup* FilterOpts = Options::CreateOptionGroup("General Filters");
231 Options::AddValueOption("-alignmentFlag", "int", "keep reads with this *exact* alignment flag (for more detailed queries, see below)", "", m_settings->HasAlignmentFlagFilter, m_settings->AlignmentFlagFilter, FilterOpts);
232 Options::AddValueOption("-insertSize", "int", "keep reads with insert size that mathces pattern", "", m_settings->HasInsertSizeFilter, m_settings->InsertSizeFilter, FilterOpts);
233 Options::AddValueOption("-mapQuality", "[0-255]", "keep reads with map quality that matches pattern", "", m_settings->HasMapQualityFilter, m_settings->MapQualityFilter, FilterOpts);
234 Options::AddValueOption("-name", "string", "keep reads with name that matches pattern", "", m_settings->HasNameFilter, m_settings->NameFilter, FilterOpts);
235 Options::AddValueOption("-queryBases", "string", "keep reads with motif that mathces pattern", "", m_settings->HasQueryBasesFilter, m_settings->QueryBasesFilter, FilterOpts);
237 // Options::AddValueOption("-tag", "TAG:VALUE", "keep reads with this key=>value pair. If multiple tags are given, reads must match all", "", m_settings->HasTagFilters, m_settings->TagFilters, FilterOpts);
239 OptionGroup* AlignmentFlagOpts = Options::CreateOptionGroup("Alignment Flag Filters");
240 Options::AddValueOption("-isDuplicate", "true/false", "keep only alignments that are marked as duplicate?", "", m_settings->HasIsDuplicateFilter, m_settings->IsDuplicateFilter, AlignmentFlagOpts, TRUE_STR);
241 Options::AddValueOption("-isFailedQC", "true/false", "keep only alignments that failed QC?", "", m_settings->HasIsFailedQCFilter, m_settings->IsFailedQCFilter, AlignmentFlagOpts, TRUE_STR);
242 Options::AddValueOption("-isFirstMate", "true/false", "keep only alignments marked as first mate?", "", m_settings->HasIsFirstMateFilter, m_settings->IsFirstMateFilter, AlignmentFlagOpts, TRUE_STR);
243 Options::AddValueOption("-isMapped", "true/false", "keep only alignments that were mapped?", "", m_settings->HasIsMappedFilter, m_settings->IsMappedFilter, AlignmentFlagOpts, TRUE_STR);
244 Options::AddValueOption("-isMateMapped", "true/false", "keep only alignments with mates that mapped", "", m_settings->HasIsMateMappedFilter, m_settings->IsMateMappedFilter, AlignmentFlagOpts, TRUE_STR);
245 Options::AddValueOption("-isMateReverseStrand", "true/false", "keep only alignments with mate on reverese strand?", "", m_settings->HasIsMateReverseStrandFilter, m_settings->IsMateReverseStrandFilter, AlignmentFlagOpts, TRUE_STR);
246 Options::AddValueOption("-isPaired", "true/false", "keep only alignments that were sequenced as paired?","", m_settings->HasIsPairedFilter, m_settings->IsPairedFilter, AlignmentFlagOpts, TRUE_STR);
247 Options::AddValueOption("-isPrimaryAlignment", "true/false", "keep only alignments marked as primary?", "", m_settings->HasIsPrimaryAlignmentFilter, m_settings->IsPrimaryAlignmentFilter, AlignmentFlagOpts, TRUE_STR);
248 Options::AddValueOption("-isProperPair", "true/false", "keep only alignments that passed PE resolution?", "", m_settings->HasIsProperPairFilter, m_settings->IsProperPairFilter, AlignmentFlagOpts, TRUE_STR);
249 Options::AddValueOption("-isReverseStrand", "true/false", "keep only alignments on reverse strand?", "", m_settings->HasIsReverseStrandFilter, m_settings->IsReverseStrandFilter, AlignmentFlagOpts, TRUE_STR);
250 Options::AddValueOption("-isSecondMate", "true/false", "keep only alignments marked as second mate?", "", m_settings->HasIsSecondMateFilter, m_settings->IsSecondMateFilter, AlignmentFlagOpts, TRUE_STR);
253 FilterTool::~FilterTool(void) {
261 int FilterTool::Help(void) {
262 Options::DisplayHelp();
266 int FilterTool::Run(int argc, char* argv[]) {
268 // parse command line arguments
269 Options::Parse(argc, argv, 1);
271 // run internal FilterTool implementation, return success/fail
272 m_impl = new FilterToolPrivate(m_settings);
274 if ( m_impl->Run() ) return 0;
278 // ---------------------------------------------
279 // FilterToolPrivate implementation
282 FilterTool::FilterToolPrivate::FilterToolPrivate(FilterTool::FilterSettings* settings)
283 : m_settings(settings)
287 FilterTool::FilterToolPrivate::~FilterToolPrivate(void) { }
289 bool FilterTool::FilterToolPrivate::AddPropertyTokensToFilter(const string& filterName, const map<string, string>& propertyTokens) {
292 // dummy temp values for token parsing
295 uint16_t uint16Value;
296 uint32_t uint32Value;
298 PropertyFilterValue::ValueCompareType type;
300 // iterate over property token map
301 map<string, string>::const_iterator mapIter = propertyTokens.begin();
302 map<string, string>::const_iterator mapEnd = propertyTokens.end();
303 for ( ; mapIter != mapEnd; ++mapIter ) {
305 const string& propertyName = (*mapIter).first;
306 const string& token = (*mapIter).second;
308 // ------------------------------
309 // convert token to value & compare type
310 // then add to filter engine
313 if ( propertyName == ISDUPLICATE_PROPERTY ||
314 propertyName == ISFAILEDQC_PROPERTY ||
315 propertyName == ISFIRSTMATE_PROPERTY ||
316 propertyName == ISMAPPED_PROPERTY ||
317 propertyName == ISMATEMAPPED_PROPERTY ||
318 propertyName == ISMATEREVERSESTRAND_PROPERTY ||
319 propertyName == ISPAIRED_PROPERTY ||
320 propertyName == ISPRIMARYALIGNMENT_PROPERTY ||
321 propertyName == ISPROPERPAIR_PROPERTY ||
322 propertyName == ISREVERSESTRAND_PROPERTY ||
323 propertyName == ISSECONDMATE_PROPERTY
326 FilterEngine::parseToken(token, boolValue, type);
327 FilterEngine::setProperty(filterName, propertyName, boolValue, type);
330 // int32_t conversion
331 else if ( propertyName == INSERTSIZE_PROPERTY ||
332 propertyName == MATEPOSITION_PROPERTY ||
333 propertyName == POSITION_PROPERTY
336 FilterEngine::parseToken(token, int32Value, type);
337 FilterEngine::setProperty(filterName, propertyName, int32Value, type);
340 // uint16_t conversion
341 else if ( propertyName == MAPQUALITY_PROPERTY )
343 FilterEngine::parseToken(token, uint16Value, type);
344 FilterEngine::setProperty(filterName, propertyName, uint16Value, type);
347 // uint32_t conversion
348 else if ( propertyName == ALIGNMENTFLAG_PROPERTY )
350 FilterEngine::parseToken(token, uint32Value, type);
351 FilterEngine::setProperty(filterName, propertyName, uint32Value, type);
355 else if ( propertyName == MATEREFERENCE_PROPERTY ||
356 propertyName == NAME_PROPERTY ||
357 propertyName == QUERYBASES_PROPERTY ||
358 propertyName == REFERENCE_PROPERTY
361 FilterEngine::parseToken(token, stringValue, type);
362 FilterEngine::setProperty(filterName, propertyName, stringValue, type);
365 // else unknown property
367 cerr << "Unknown property: " << propertyName << "!" << endl;
374 bool FilterTool::FilterToolPrivate::CheckAlignment(const BamAlignment& al) {
376 bool keepAlignment = true;
378 // only consider properties that are actually enabled
379 // iterate over these enabled properties
380 const vector<string> enabledProperties = FilterEngine::enabledPropertyNames();
381 vector<string>::const_iterator propIter = enabledProperties.begin();
382 vector<string>::const_iterator propEnd = enabledProperties.end();
383 for ( ; propIter != propEnd; ++propIter ) {
385 // check alignment data field depending on propertyName
386 const string& propertyName = (*propIter);
387 if ( propertyName == ALIGNMENTFLAG_PROPERTY ) keepAlignment &= FilterEngine::check(ALIGNMENTFLAG_PROPERTY, al.AlignmentFlag);
388 else if ( propertyName == INSERTSIZE_PROPERTY ) keepAlignment &= FilterEngine::check(INSERTSIZE_PROPERTY, al.InsertSize);
389 else if ( propertyName == ISDUPLICATE_PROPERTY ) keepAlignment &= FilterEngine::check(ISDUPLICATE_PROPERTY, al.IsDuplicate());
390 else if ( propertyName == ISFAILEDQC_PROPERTY ) keepAlignment &= FilterEngine::check(ISFAILEDQC_PROPERTY, al.IsFailedQC());
391 else if ( propertyName == ISFIRSTMATE_PROPERTY ) keepAlignment &= FilterEngine::check(ISFIRSTMATE_PROPERTY, al.IsFirstMate());
392 else if ( propertyName == ISMAPPED_PROPERTY ) keepAlignment &= FilterEngine::check(ISMAPPED_PROPERTY, al.IsMapped());
393 else if ( propertyName == ISMATEMAPPED_PROPERTY ) keepAlignment &= FilterEngine::check(ISMATEMAPPED_PROPERTY, al.IsMateMapped());
394 else if ( propertyName == ISMATEREVERSESTRAND_PROPERTY ) keepAlignment &= FilterEngine::check(ISMATEREVERSESTRAND_PROPERTY, al.IsMateReverseStrand());
395 else if ( propertyName == ISPAIRED_PROPERTY ) keepAlignment &= FilterEngine::check(ISPAIRED_PROPERTY, al.IsPaired());
396 else if ( propertyName == ISPRIMARYALIGNMENT_PROPERTY ) keepAlignment &= FilterEngine::check(ISPRIMARYALIGNMENT_PROPERTY, al.IsPrimaryAlignment());
397 else if ( propertyName == ISPROPERPAIR_PROPERTY ) keepAlignment &= FilterEngine::check(ISPROPERPAIR_PROPERTY, al.IsProperPair());
398 else if ( propertyName == ISREVERSESTRAND_PROPERTY ) keepAlignment &= FilterEngine::check(ISREVERSESTRAND_PROPERTY, al.IsReverseStrand());
399 else if ( propertyName == ISSECONDMATE_PROPERTY ) keepAlignment &= FilterEngine::check(ISSECONDMATE_PROPERTY, al.IsSecondMate());
400 else if ( propertyName == MAPQUALITY_PROPERTY ) keepAlignment &= FilterEngine::check(MAPQUALITY_PROPERTY, al.MapQuality);
401 else if ( propertyName == MATEPOSITION_PROPERTY ) keepAlignment &= ( al.IsPaired() && al.IsMateMapped() && FilterEngine::check(MATEPOSITION_PROPERTY, al.MateRefID) );
402 else if ( propertyName == MATEREFERENCE_PROPERTY ) {
403 if ( !al.IsPaired() || !al.IsMateMapped() ) return false;
404 BAMTOOLS_ASSERT_MESSAGE( (al.MateRefID>=0 && (al.MateRefID<(int)m_references.size())), "Invalid MateRefID");
405 const string& refName = m_references.at(al.MateRefID).RefName;
406 keepAlignment &= FilterEngine::check(MATEREFERENCE_PROPERTY, refName);
408 else if ( propertyName == NAME_PROPERTY ) keepAlignment &= FilterEngine::check(NAME_PROPERTY, al.Name);
409 else if ( propertyName == POSITION_PROPERTY ) keepAlignment &= FilterEngine::check(POSITION_PROPERTY, al.Position);
410 else if ( propertyName == QUERYBASES_PROPERTY ) keepAlignment &= FilterEngine::check(QUERYBASES_PROPERTY, al.QueryBases);
411 else if ( propertyName == REFERENCE_PROPERTY ) {
412 BAMTOOLS_ASSERT_MESSAGE( (al.RefID>=0 && (al.RefID<(int)m_references.size())), "Invalid RefID");
413 const string& refName = m_references.at(al.RefID).RefName;
414 keepAlignment &= FilterEngine::check(REFERENCE_PROPERTY, refName);
416 else BAMTOOLS_ASSERT_MESSAGE( false, "Unknown property");
418 // if alignment fails at ANY point, just quit and return false
419 if ( !keepAlignment ) return false;
422 // return success (should still be true at this point)
423 return keepAlignment;
426 const string FilterTool::FilterToolPrivate::GetScriptContents(void) {
428 // open script for reading
429 FILE* inFile = fopen(m_settings->ScriptFilename.c_str(), "rb");
431 cerr << "FilterTool error: Could not open script: " << m_settings->ScriptFilename << " for reading" << endl;
435 // read in entire script contents
437 ostringstream docStream("");
440 // peek ahead, make sure there is data available
441 char ch = fgetc(inFile);
443 if( feof(inFile) ) break;
445 // read next block of data
446 if ( fgets(buffer, 1024, inFile) == 0 ) {
447 cerr << "FilterTool error : could not read from script" << endl;
457 // import buffer contents to document, return
458 string document = docStream.str();
462 void FilterTool::FilterToolPrivate::InitProperties(void) {
464 // store property names in vector
465 m_propertyNames.push_back(ALIGNMENTFLAG_PROPERTY);
466 m_propertyNames.push_back(INSERTSIZE_PROPERTY);
467 m_propertyNames.push_back(ISDUPLICATE_PROPERTY);
468 m_propertyNames.push_back(ISFAILEDQC_PROPERTY);
469 m_propertyNames.push_back(ISFIRSTMATE_PROPERTY);
470 m_propertyNames.push_back(ISMAPPED_PROPERTY);
471 m_propertyNames.push_back(ISMATEMAPPED_PROPERTY);
472 m_propertyNames.push_back(ISMATEREVERSESTRAND_PROPERTY);
473 m_propertyNames.push_back(ISPAIRED_PROPERTY);
474 m_propertyNames.push_back(ISPRIMARYALIGNMENT_PROPERTY);
475 m_propertyNames.push_back(ISPROPERPAIR_PROPERTY);
476 m_propertyNames.push_back(ISREVERSESTRAND_PROPERTY);
477 m_propertyNames.push_back(ISSECONDMATE_PROPERTY);
478 m_propertyNames.push_back(MAPQUALITY_PROPERTY);
479 m_propertyNames.push_back(MATEPOSITION_PROPERTY);
480 m_propertyNames.push_back(MATEREFERENCE_PROPERTY);
481 m_propertyNames.push_back(NAME_PROPERTY);
482 m_propertyNames.push_back(POSITION_PROPERTY);
483 m_propertyNames.push_back(QUERYBASES_PROPERTY);
484 m_propertyNames.push_back(REFERENCE_PROPERTY);
486 // add vector contents to FilterEngine
487 vector<string>::const_iterator propertyNameIter = m_propertyNames.begin();
488 vector<string>::const_iterator propertyNameEnd = m_propertyNames.end();
489 for ( ; propertyNameIter != propertyNameEnd; ++propertyNameIter )
490 FilterEngine::addProperty((*propertyNameIter));
493 bool FilterTool::FilterToolPrivate::ParseCommandLine(void) {
495 // add a rule set to filter engine
496 const string CMD = "COMMAND_LINE";
497 FilterEngine::addFilter(CMD);
499 // map property names to command line args
500 map<string, string> propertyTokens;
501 if ( m_settings->HasAlignmentFlagFilter ) propertyTokens.insert( make_pair(ALIGNMENTFLAG_PROPERTY, m_settings->AlignmentFlagFilter) );
502 if ( m_settings->HasInsertSizeFilter ) propertyTokens.insert( make_pair(INSERTSIZE_PROPERTY, m_settings->InsertSizeFilter) );
503 if ( m_settings->HasIsDuplicateFilter ) propertyTokens.insert( make_pair(ISDUPLICATE_PROPERTY, m_settings->IsDuplicateFilter) );
504 if ( m_settings->HasIsFailedQCFilter ) propertyTokens.insert( make_pair(ISFAILEDQC_PROPERTY, m_settings->IsFailedQCFilter) );
505 if ( m_settings->HasIsFirstMateFilter ) propertyTokens.insert( make_pair(ISFIRSTMATE_PROPERTY, m_settings->IsFirstMateFilter) );
506 if ( m_settings->HasIsMappedFilter ) propertyTokens.insert( make_pair(ISMAPPED_PROPERTY, m_settings->IsMappedFilter) );
507 if ( m_settings->HasIsMateMappedFilter ) propertyTokens.insert( make_pair(ISMATEMAPPED_PROPERTY, m_settings->IsMateMappedFilter) );
508 if ( m_settings->HasIsMateReverseStrandFilter ) propertyTokens.insert( make_pair(ISMATEREVERSESTRAND_PROPERTY, m_settings->IsMateReverseStrandFilter) );
509 if ( m_settings->HasIsPairedFilter ) propertyTokens.insert( make_pair(ISPAIRED_PROPERTY, m_settings->IsPairedFilter) );
510 if ( m_settings->HasIsPrimaryAlignmentFilter ) propertyTokens.insert( make_pair(ISPRIMARYALIGNMENT_PROPERTY, m_settings->IsPrimaryAlignmentFilter) );
511 if ( m_settings->HasIsProperPairFilter ) propertyTokens.insert( make_pair(ISPROPERPAIR_PROPERTY, m_settings->IsProperPairFilter) );
512 if ( m_settings->HasIsReverseStrandFilter ) propertyTokens.insert( make_pair(ISREVERSESTRAND_PROPERTY, m_settings->IsReverseStrandFilter) );
513 if ( m_settings->HasIsSecondMateFilter ) propertyTokens.insert( make_pair(ISSECONDMATE_PROPERTY, m_settings->IsSecondMateFilter) );
514 if ( m_settings->HasMapQualityFilter ) propertyTokens.insert( make_pair(MAPQUALITY_PROPERTY, m_settings->MapQualityFilter) );
515 if ( m_settings->HasNameFilter ) propertyTokens.insert( make_pair(NAME_PROPERTY, m_settings->NameFilter) );
516 if ( m_settings->HasQueryBasesFilter ) propertyTokens.insert( make_pair(QUERYBASES_PROPERTY, m_settings->QueryBasesFilter) );
518 // send add these properties to filter set "COMMAND_LINE"
519 return AddPropertyTokensToFilter(CMD, propertyTokens);
522 bool FilterTool::FilterToolPrivate::ParseFilterObject(const string& filterName, const Json::Value& filterObject) {
524 // filter object parsing variables
525 Json::Value null(Json::nullValue);
526 Json::Value propertyValue;
529 map<string, string> propertyTokens;
531 // iterate over known properties
532 vector<string>::const_iterator propertyNameIter = m_propertyNames.begin();
533 vector<string>::const_iterator propertyNameEnd = m_propertyNames.end();
534 for ( ; propertyNameIter != propertyNameEnd; ++propertyNameIter ) {
535 const string& propertyName = (*propertyNameIter);
537 // if property defined in filter, add to token list
538 propertyValue = filterObject.get(propertyName, null);
539 if ( propertyValue != null )
540 propertyTokens.insert( make_pair(propertyName, propertyValue.asString()) );
543 // add this filter to engin
544 FilterEngine::addFilter(filterName);
546 // add token list to this filter
547 return AddPropertyTokensToFilter(filterName, propertyTokens);
550 bool FilterTool::FilterToolPrivate::ParseScript(void) {
552 // read in script contents from file
553 const string document = GetScriptContents();
555 // set up JsonCPP reader and attempt to parse script
558 if ( !reader.parse(document, root) ) {
559 // use built-in error reporting mechanism to alert user what was wrong with the script
560 cerr << "Failed to parse configuration\n" << reader.getFormatedErrorMessages();
564 // see if root object contains multiple filters
565 const Json::Value filters = root["filters"];
566 if ( !filters.isNull() ) {
570 // iterate over any filters found
572 Json::Value::const_iterator filtersIter = filters.begin();
573 Json::Value::const_iterator filtersEnd = filters.end();
574 for ( ; filtersIter != filtersEnd; ++filtersIter, ++filterIndex ) {
575 Json::Value filter = (*filtersIter);
577 // convert filter index to string
578 stringstream convert;
579 convert << filterIndex;
580 const string filterName = convert.str();
582 // create & parse filter
583 success &= ParseFilterObject(filterName, filter);
589 // otherwise, root is the only filter (just contains properties)
590 // create & parse filter named "ROOT"
591 else return ParseFilterObject("ROOT", root);
595 bool FilterTool::FilterToolPrivate::Run(void) {
597 // set to default input if none provided
598 if ( !m_settings->HasInputBamFilename )
599 m_settings->InputFiles.push_back(Options::StandardIn());
601 // initialize defined properties & user-specified filters
603 if ( !SetupFilters() ) return 1;
605 // open reader without index
606 BamMultiReader reader;
607 reader.Open(m_settings->InputFiles, false, true);
608 const string headerText = reader.GetHeaderText();
609 m_references = reader.GetReferenceData();
613 bool writeUncompressed = ( m_settings->OutputFilename == Options::StandardOut() && !m_settings->IsForceCompression );
614 writer.Open(m_settings->OutputFilename, headerText, m_references, writeUncompressed);
616 // set up error handling
617 ostringstream errorStream("");
618 bool foundError(false);
620 // if no REGION specified, run filter on entire file contents
621 if ( !m_settings->HasRegion ) {
623 while ( reader.GetNextAlignment(al) ) {
624 // perform main filter check
625 if ( CheckAlignment(al) )
626 writer.SaveAlignment(al);
633 // attempt to parse string into BamRegion struct
635 if ( Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
637 // check if there are index files *.bai/*.bti corresponding to the input files
638 bool hasDefaultIndex = false;
639 bool hasBamtoolsIndex = false;
640 bool hasNoIndex = false;
641 int defaultIndexCount = 0;
642 int bamtoolsIndexCount = 0;
643 for (vector<string>::const_iterator f = m_settings->InputFiles.begin(); f != m_settings->InputFiles.end(); ++f) {
645 if ( Utilities::FileExists(*f + ".bai") ) {
646 hasDefaultIndex = true;
650 if ( Utilities::FileExists(*f + ".bti") ) {
651 hasBamtoolsIndex = true;
652 ++bamtoolsIndexCount;
655 if ( !hasDefaultIndex && !hasBamtoolsIndex ) {
657 cerr << "*WARNING - could not find index file for " << *f
658 << ", parsing whole file(s) to get alignment counts for target region"
659 << " (could be slow)" << endl;
664 // determine if index file types are heterogeneous
665 bool hasDifferentIndexTypes = false;
666 if ( defaultIndexCount > 0 && bamtoolsIndexCount > 0 ) {
667 hasDifferentIndexTypes = true;
668 cerr << "*WARNING - different index file formats found"
669 << ", parsing whole file(s) to get alignment counts for target region"
670 << " (could be slow)" << endl;
673 // if any input file has no index, or if input files use different index formats
674 // can't use BamMultiReader to jump directly (**for now**)
675 if ( hasNoIndex || hasDifferentIndexTypes ) {
677 // read through sequentially, but onlt perform filter on reads overlapping REGION
679 while( reader.GetNextAlignment(al) ) {
680 if ( (al.RefID >= region.LeftRefID) && ( (al.Position + al.Length) >= region.LeftPosition ) &&
681 (al.RefID <= region.RightRefID) && ( al.Position <= region.RightPosition) )
683 // perform main filter check
684 if ( CheckAlignment(al) )
685 writer.SaveAlignment(al);
690 // has index file for each input file (and same format)
693 // this is kind of a hack...?
694 BamMultiReader reader;
695 reader.Open(m_settings->InputFiles, true, true, hasDefaultIndex );
697 if ( !reader.SetRegion(region.LeftRefID, region.LeftPosition, region.RightRefID, region.RightPosition) ) {
699 errorStream << "Could not set BamReader region to REGION: " << m_settings->Region << endl;
702 // filter only alignments from specified region
704 while ( reader.GetNextAlignment(al) ) {
705 // perform main filter check
706 if ( CheckAlignment(al) )
707 writer.SaveAlignment(al);
714 errorStream << "Could not parse REGION: " << m_settings->Region << endl;
715 errorStream << "Be sure REGION is in valid format (see README) and that coordinates are valid for selected references" << endl;
725 bool FilterTool::FilterToolPrivate::SetupFilters(void) {
727 // add known properties to FilterEngine
730 // parse script for filter rules, if given
731 if ( m_settings->HasScriptFilename ) return ParseScript();
733 // otherwise check command line for filters
734 else return ParseCommandLine();