Debian Codegraph @

SeqLib/ReadFilter.h

raw symbols SCIP
1 #ifndef SEQLIB_READ_FILTER_H
2 #define SEQLIB_READ_FILTER_H
3
4 #define AHO_CORASICK 1
5
6 #include <string>
7 #include <vector>
8 #include <climits>
9
10 #include "json/json.h"
11
12 #include "SeqLib/GenomicRegionCollection.h"
13 #include "SeqLib/BamRecord.h"
14
15 #ifdef HAVE_C11
16 #include "SeqLib/aho_corasick.hpp"
17 #endif
18
19
20 #define MINIRULES_MATE_LINKED 1
21 #define MINIRULES_MATE_LINKED_EXCLUDE 2
22 #define MINIRULES_REGION 3
23 #define MINIRULES_REGION_EXCLUDE 4
24
25 namespace SeqLib {
26
27 typedef SeqHashSet<std::string> StringSet;
28
29 namespace Filter {
30
31 #ifdef HAVE_C11
32 /** Tool for using the Aho-Corasick method for substring queries of
33 * using large dictionaries
34 * @note Trie construction / searching implemented by https://github.com/blockchaindev/aho_corasick
35 */
36 struct AhoCorasick {
37
38 /** Allocate a new empty trie */
39 AhoCorasick() {
40 aho_trie = SeqPointer<aho_corasick::trie>(new aho_corasick::trie());
41 inv = false;
42 count = 0;
43 }
44
45 /** Deallocate the trie */
46 ~AhoCorasick() { }
47
48 /** Add a motif to the trie
49 * @note Trie construction is lazy. Won't build trie until
50 * first query. Therefore first query is slow, the rest are
51 * O(n) where (n) is length of query string.
52 */
53 void AddMotif(const std::string& m) {
54 aho_trie->insert(m);
55 }
56
57 /** Add a set of motifs to the trie from a file
58 * @param f File storing the motifs (new line separated)
59 * @exception Throws a runtime_error if file cannot be opened
60 */
61 void TrieFromFile(const std::string& f);
62
63 /** Query if a string is in the trie
64 * @param t Text to query
65 * @return Returns number of substrings in tree that are in t
66 */
67 int QueryText(const std::string& t) const;
68
69 SeqPointer<aho_corasick::trie> aho_trie; ///< The trie for the Aho-Corasick search
70
71 std::string file; ///< Name of the file holding the motifs
72
73 bool inv; ///< Is this an inverted dictinary (ie exclude hits)
74
75 int count; ///< Number of motifs in dictionary
76
77 };
78 #endif
79
80 /** Stores a rule for a single alignment flag.
81 *
82 * Rules for alignment flags can be one of three states:
83 * - NA - All flag values are valid
84 * - Off - Flag is valid if OFF
85 * - On - Flag is valid if ON
86 */
87 class Flag {
88
89 public:
90
91 /** Construct a new Flag with NA rule
92 */
93 Flag() : on(false), off(false), na(true) {}
94
95 /** Set the flag to NA (pass alignment regardless of flag value) */
96 void setNA() { on = false; off = false; na = true; }
97
98 /** Set the flag to ON (require flag ON to pass) */
99 void setOn() { on = true; off = false; na = false; }
100
101 /** Set the flag to OFF (require flag OFF to pass) */
102 void setOff() { on = false; off = true; na = false; }
103
104 /** Return if the Flag filter is NA */
105 bool isNA() const { return na; }
106
107 /** Return if the Flag filter is ON */
108 bool isOn() const { return on; }
109
110 /** Return if the Flag filter is OFF */
111 bool isOff() const { return off; }
112
113 /** Parse the Flag rule from a JSON entry */
114 bool parseJson(const Json::Value& value, const std::string& name);
115
116 private:
117
118 bool on;
119 bool off;
120 bool na;
121
122 };
123
124 /** Filter numeric values on whether they fall in/out of a range of values (eg mapping quality).
125 *
126 * Can optionally invert the range to make rule the complement of the range
127 * (eg insert-size NOT in [300,600]
128 */
129 class Range {
130
131 public:
132 /** Construct a default range with everything accepted
133 */
134 Range() : m_min(0), m_max(0), m_inverted(false), m_every(true) {}
135
136 /** Construct a Range from min to max, inclusive
137 * @param min Minimum for range
138 * @param max Maximum for range
139 * @param inverted Declare if this should be an inverted range (do NOT accept vals in range)
140 */
141 Range(int min, int max, bool inverted) : m_min(min), m_max(max), m_inverted(inverted), m_every(false) {}
142
143 /** Given a query value, determine if the value passes this Range
144 * @param val Query value (e.g. mapping quality)
145 * @return true if the value passes this Range rule
146 */
147 bool isValid(int val) {
148 if (m_every)
149 return true;
150 if (!m_inverted)
151 return (val >= m_min && val <= m_max);
152 else
153 return (val < m_min || val > m_max);
154 }
155
156 /** Parse a JSON value
157 * @param value
158 * @param name
159 */
160 void parseJson(const Json::Value& value, const std::string& name);
161
162 /** Print the contents of this Range */
163 friend std::ostream& operator<<(std::ostream &out, const Range &r);
164
165 /** Return if this range accepts all values */
166 bool isEvery() const { return m_every; }
167
168 /** Return the lower bound of the range */
169 int lowerBound() const { return m_min; }
170
171 /** Return the upper bound of the range */
172 int upperBound() const { return m_max; }
173
174 /** Return true if the range is inverted (e.g. do NOT accept i in [min,max] */
175 bool isInverted() const { return m_inverted; }
176
177 private:
178
179 int m_min;
180 int m_max;
181 bool m_inverted;
182 bool m_every;
183
184 };
185
186 /** Stores a set of Flag objects for filtering alignment flags
187 *
188 * An alignment can be queried against a FlagRule to check if it
189 * satisfies the requirements for its alignment flag.
190 */
191 class FlagRule {
192
193 public:
194
195 FlagRule() {
196 dup = Flag();
197 supp = Flag();
198 qcfail = Flag();
199 hardclip = Flag();
200 fwd_strand = Flag();
201 rev_strand = Flag();
202 mate_fwd_strand = Flag();
203 mate_rev_strand = Flag();
204 mapped = Flag();
205 mate_mapped = Flag();
206 ff = Flag();
207 fr = Flag();
208 rf = Flag();
209 rr = Flag();
210 ic = Flag();
211 paired = Flag();
212 m_all_on_flag = 0;
213 m_all_off_flag = 0;
214 m_any_on_flag = 0;
215 m_any_off_flag = 0;
216 every = false;
217 }
218
219 Flag dup; ///< Filter for duplicated flag
220 Flag supp; ///< Flag for supplementary flag
221 Flag qcfail; ///< Flag for qcfail flag
222 Flag hardclip; ///< Flag for presence of hardclip in cigar string
223 Flag fwd_strand; ///< Flag for forward strand alignment
224 Flag rev_strand; ///< Flag for reverse strand alignment
225 Flag mate_fwd_strand; ///< Flag for forward strand alignment for mate
226 Flag mate_rev_strand; ///< Flag for reverse strand alignment for mate
227 Flag mapped; ///< Flag for mapped alignment
228 Flag mate_mapped; ///< Flag for mate-mapped alignment
229 Flag ff; ///< Flag for both reads on forward strand
230 Flag fr; ///< Flag for lower (by position) read on forward strand, higher on reverse
231 Flag rf; ///< Flag for lower (by position) read on reverse strand, higher on forward
232 Flag rr; ///< Flag for both reads on reverse strand
233 Flag ic; ///< Flag for read and mate aligned to different chromosomes
234 Flag paired; ///< Flag for read is part of pair
235
236 /** Parse a FlagRule from a JSON object
237 */
238 void parseJson(const Json::Value& value);
239
240 /** Set rule to pass all alignment flags that have any bit in f on
241 * @param f Alignment flags to be on for alignment record to pass
242 */
243 void setAnyOnFlag(uint32_t f) { m_any_on_flag = f; every = (every && f == 0); }
244 // NOTE: every = (every && f == 0) means to set every to true only if
245 // input flag is zero and every was already true
246
247 /** Set rule to pass all alignment flags that have any bit in f off
248 * @param f Alignment flags to be off for alignment record to pass
249 */
250 void setAnyOffFlag(uint32_t f) { m_any_off_flag = f; every = (every && f == 0); }
251
252 /** Set rule to reject all alignment flags that have any bit in f off
253 * @param f Alignment flags to be on for alignment record to pass
254 */
255 void setAllOnFlag(uint32_t f) { m_all_on_flag = f; every = (every && f == 0); }
256
257 /** Set rule to reject all alignment flags that have any bit in f on
258 * @param f Alignment flags to be off for alignment record to pass
259 */
260 void setAllOffFlag(uint32_t f) { m_all_off_flag = f; every = (every && f == 0); }
261
262 /** Return whether a read passes the alignment flag rules in this object
263 * @param r Alignment record to query
264 * @return true if record passes rules
265 */
266 bool isValid(const BamRecord &r);
267
268 /** Print the flag rule */
269 friend std::ostream& operator<<(std::ostream &out, const FlagRule &fr);
270
271 /** Return if every this object will pass all records provided to it */
272 bool isEvery() const { return every; }
273
274 private:
275
276 bool every; // does this pass all flags?
277
278 uint32_t m_all_on_flag; // if read has all of these, keep
279 uint32_t m_all_off_flag; // if read has all of these, fail
280
281 uint32_t m_any_on_flag; // if read has any of these, keep
282 uint32_t m_any_off_flag;// if read has any of these, fail
283
284 int parse_json_int(const Json::Value& v);
285
286 };
287
288 /** Stores a full rule (Flag + Range + motif etc)
289 *
290 * An alignment can be queried with an AbstractRule object
291 * to check if it passes that rule.
292 */
293 class AbstractRule {
294
295 friend class ReadFilter;
296 friend class ReadFilterCollection;
297
298 public:
299
300 /** Create empty rule with default to accept all */
301 AbstractRule() : m_count(0), subsam_frac(1), subsam_seed(999) { }
302
303 /** Destroy the filter */
304 ~AbstractRule() {}
305
306 /** Add a list of motifs that will be search as sub-strings
307 * of the read sequence
308 * @param f Path to new-line separted file of motifs
309 * @param inverted If true, the reads that have a matching motif will fail isValid
310 */
311 void addMotifRule(const std::string& f, bool inverted);
312
313 /** Query a read against this rule. If the
314 * read passes this rule, return true.
315 * @param r An aligned sequencing read to query against filter
316 */
317 bool isValid(const BamRecord &r);
318
319 /** Supply the rule parameters with a JSON
320 * @param value JSON object created by parsing a string
321 */
322 void parseJson(const Json::Value& value);
323
324 /** Print some basic information about this filter
325 */
326 friend std::ostream& operator<<(std::ostream &out, const AbstractRule &fr);
327
328 /** Return if this rule accepts all reads
329 */
330 bool isEvery() const;
331
332 /** Set the rate to subsample (default 1 = no subsampling)
333 * @param s A rate between 0 and 1
334 */
335 void SetSubsampleRate(double s) { subsam_frac = s; };
336
337 /** Supply a name for this rule
338 * @param s ID to be associated with this rule
339 */
340 void SetRuleID(const std::string& s) { id = s; };
341
342 /** Specify a read-group for this filter.
343 * Reads that do not belong to this read group
344 * will not pass isValid
345 * @param rg Read group to be matched against RG:Z:readgroup
346 */
347 void SetReadGroup(const std::string& rg) { read_group = rg; }
348
349 FlagRule fr; ///< FlagRule specifying the alignment flag filter
350
351 Range isize; ///< Range object for insert-size filter
352 Range mapq; ///< Range object for mapping quality filter
353 Range len; ///< Range object for length filter
354 Range phred; ///< Range object for base-quality filter
355 Range clip; ///< Range object for number of clipped bases filter
356 Range nm; ///< Range object for NM (num mismatch) filter
357 Range nbases; ///< Range object for number of "N" bases filer
358 Range ins; ///< Range object for max CIGAR insertion size filter
359 Range del; ///< Range object for max CIGAR deletion size filter
360 Range xp; ///< Range object for number of secondary alignments
361
362 private:
363
364 void parseSeqLine(const Json::Value& value);
365
366 // read group
367 std::string read_group;
368
369 // how many reads pass this rule?
370 size_t m_count;
371
372 // the aho-corasick trie
373 #ifdef HAVE_C11
374 AhoCorasick aho;
375 #endif
376
377 // id for this rule
378 std::string id;
379
380 // fraction reads to subsample
381 double subsam_frac;
382
383 // data
384 uint32_t subsam_seed; // random seed for subsampling
385
386 void parseSubLine(const Json::Value& value);
387
388 };
389
390 class ReadFilterCollection;
391
392 /**
393 * A set of AbstractRules on a region united by logi rules.
394 *
395 * ReadFilter stores an arbitrarily complex collection of AbstractRules
396 * (e.g. (Mapped && Clipped) || (Unmapped)).
397 */
398 class ReadFilter {
399
400 friend class ReadFilterCollection;
401
402 public:
403
404 /** Construct an empty filter that passes all reads */
405 ReadFilter() : excluder(false), m_applies_to_mate(false), m_count(0) {}
406
407 /** Destroy the filter */
408 ~ReadFilter();
409
410 // ReadFilter(const ReadFilter& rf);
411
412 // Make a ReadFilter with an all exclude or include rule
413 // @param Samtools style string, BED file or VCF
414 // @param reg_type The type of rule this will be
415 // @param h BAM header that defines available chromosomes
416 ///
417 //ReadFilter(const CommandLineRegion& c, const BamHeader& hdr);
418
419 /** Return whether a read passes this filter
420 * @param r A read to query
421 * @note If this is an excluder rule, then this
422 * returns false if the read passes the filter
423 */
424 bool isValid(const BamRecord &r);
425
426 /** Add a rule to this filter. A read must pass all
427 * of the rules contained in this filter to pass
428 * @param ar A rule (eg MAPQ > 30) that the read must satisfy to pass this filter.
429 */
430 void AddRule(const AbstractRule& ar);
431
432 /** Provide the region covered by this read filter
433 * @param g Region that this filter applies to
434 */
435 void setRegions(const GRC& g);
436
437 /** Add additional regions to the filtered region
438 * @param g Additional regions to be included in filter
439 */
440 void addRegions(const GRC& g);
441
442 /** Check if a read is overlapping the region defined by this filter
443 * @param r Read to query whether it overlaps (even partially) the region.
444 * @note If this is a mate-linked region, then the read will overlap
445 * if its mate overlaps as well.
446 */
447 bool isReadOverlappingRegion(const BamRecord &r) const;
448
449 /** Print basic information about this filter */
450 friend std::ostream& operator<<(std::ostream& out, const ReadFilter &mr);
451
452 /** Return the number of rules in this filter */
453 size_t size() const {
454 return m_abstract_rules.size();
455 }
456
457 /** Set as an excluder region
458 * An excluder region is such that if a read satisfies
459 * this rule, then it will fail isValid, rather than pass
460 */
461 void SetExcluder(bool e) { excluder = e; }
462
463 /** Set as a mate linked region */
464 void SetMateLinked(bool e) { m_applies_to_mate = e; }
465
466 private:
467
468 GRC m_grv; // the interval tree with the regions this rule applies to. Empty is whole-genome
469
470 std::string id; // set a unique id for this filter
471
472 bool excluder; // this filter is such that if read passes, it gets excluded
473
474 std::string m_region_file;
475
476 std::vector<AbstractRule> m_abstract_rules; // hold all of the rules
477
478 // rule applies to mate too
479 bool m_applies_to_mate;
480
481 // how many reads pass this MiniRule
482 size_t m_count;
483
484 };
485
486 /** A full set of rules across any number of regions
487 *
488 * Stores the entire set of ReadFilter, each defined on a unique interval.
489 * A single ReadFilterCollection object is sufficient to store any combination of rules,
490 * and is the highest in the rule hierarchy. (ReadFilterCollection stores ReadFilter
491 * stores AbstractRules stores FlagRule/Ranges).
492 */
493 class ReadFilterCollection {
494
495 public:
496
497 /** Construct an empty ReadFilterCollection
498 * that will pass all reads.
499 */
500 ReadFilterCollection() : m_count(0), m_count_seen(0) {}
501
502 /** Create a new filter collection directly from a JSON
503 * @param script A JSON file or directly as JSON formatted string
504 * @param h BamHeader to convert chr sequence to id
505 * @exception invalid_argument if cannot parse JSON
506 */
507 ReadFilterCollection(const std::string& script, const SeqLib::BamHeader& h);
508
509 /** Add a new rule to the collection.
510 * If a read passes this rule, it will be included,
511 * even if it fails the other filters. Or, if this filter
512 * has the excluder tag, then if a read passes this filter
513 * then it will be excluded, regardless of the other filters
514 */
515 void AddReadFilter(const ReadFilter& rf);
516
517 /** Provide a global rule set (applies to each filter)
518 * @param rule A filter specified in JSON format
519 */
520 void addGlobalRule(const std::string& rule);
521
522 /** Query a read to see if it passes any one of the
523 * filters contained in this collection */
524 bool isValid(const BamRecord &r);
525
526 /** Print some basic information about this object */
527 friend std::ostream& operator<<(std::ostream& out, const ReadFilterCollection &mr);
528
529 /** Return a GenomicRegionCollection of all
530 * of the regions specified by the filters.
531 * @note This returns the raw regions. It may be useful
532 * to run mergeOverlappingIntervals on the output to see
533 * the minimal covered regions.
534 */
535 GRC getAllRegions() const;
536
537 /** Return the number of filters in this collection */
538 size_t size() const { return m_regions.size(); }
539
540 /** Return the total number of rules in this collection.
541 * Filters are composed of collections of rules, and this
542 * returns the total number of rules (e.g. MAPQ > 30) across
543 * all of the filters
544 */
545 size_t numRules() const {
546 size_t num = 0;
547 for (std::vector<ReadFilter>::const_iterator it = m_regions.begin(); it != m_regions.end(); ++it)
548 num += it->size();
549 return num;
550 }
551
552 /** Check that the filter collection includes something.
553 * If not, then give it a universal includer
554 */
555 void CheckHasIncluder();
556
557 // Return the a tab-delimited tally of which filters were satisfied.
558 // Includes the header:
559 // total_seen_count total_passed_count region region_passed_count rule rule_passed_count
560 //
561 //std::string EmitCounts() const;
562
563 private:
564
565 // the global rule that all other rules are inherited from
566 AbstractRule rule_all;
567
568 size_t m_count; // passed
569 size_t m_count_seen; // tested
570
571 // store all of the individual filters
572 std::vector<ReadFilter> m_regions;
573
574 bool ParseFilterObject(const std::string& filterName, const Json::Value& filterObject);
575
576 };
577
578 }
579
580 }
581 #endif