patterns Module
Genetic pattern matching and filtering.
Overview
The patterns subpackage implements the syntax and logic for matching genotypes and haploid genomes against symbolic patterns.
Complete Module Reference
natal.patterns
Pattern matching system for genotypes and haploid genomes.
Provides regex-like pattern matching for genetic sequences: - PatternElement: Base class for allele-level matching - HaplotypePath: Pattern for a single DNA strand of one chromosome - ChromosomePairPattern: Pattern for a pair of homologous chromosomes - GenotypePattern: Pattern for a complete diploid genotype - HaploidGenomePattern: Pattern for a complete haploid genome - GenotypePatternParser: Parser for pattern syntax strings - GenotypeSelector: Unified genotype selector for observation/filtering
PatternParseError
Bases: Exception
Error raised during genotype pattern parsing.
Indicates that a pattern string could not be parsed due to invalid syntax, unsupported constructs, or species context mismatches.
LabPattern
Pattern for matching gamete / somatic label names.
Supports the same syntax as allele patterns
@cas9_high— exact match@!cas9_high— any label except "cas9_high"@{cas9_high,cas9_low}— any label in the set@!{cas9_high,cas9_low}— any label NOT in the set
When lab and lab_set are both None the pattern matches any label
(equivalent to omitting the @ suffix entirely).
Attributes:
| Name | Type | Description |
|---|---|---|
lab |
Optional[str]
|
Exact label to match, or |
negate |
bool
|
If True, negate the matching condition. |
lab_set |
Optional[Set[str]]
|
Set of labels for set matching. |
Initialize a LabPattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lab
|
Optional[str]
|
Exact label name to match, or |
None
|
negate
|
bool
|
If True, match the complement of the constraint. |
False
|
lab_set
|
Optional[Set[str]]
|
Set of label names for set matching. |
None
|
Source code in src/natal/patterns/elements/atom.py
matches
Return True if value satisfies this pattern.
Source code in src/natal/patterns/elements/atom.py
is_wildcard
parse
staticmethod
Parse a @lab suffix string into a LabPattern.
Returns a wildcard (matches-everything) pattern for "*"
or the empty string.
Source code in src/natal/patterns/elements/atom.py
ZygoteTypePattern
Pattern for a zygote (diploid genotype) with a slab (somatic) label.
A zygote type pairs a :class:GenotypePattern with an optional
:class:LabPattern parsed from the @slab suffix (e.g.
A|a@infected). This is the slab-aware equivalent of
GenotypePattern — it resolves to a (genotype_index, slab_index)
pair used for ZType indexing in config arrays.
Supports both string and tuple construction::
ZygoteTypePattern.parse("A|a@infected", species)
ZygoteTypePattern.from_pair(genotype_obj, "infected", species)
Initialize a ZygoteTypePattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
genotype
|
GenotypePattern
|
The genotype pattern to match. |
required |
slab
|
Optional[LabPattern]
|
Optional somatic-label pattern parsed from the |
None
|
Source code in src/natal/patterns/elements/diploid.py
parse
staticmethod
Parse a ZType pattern string like "A|a@infected".
The @slab suffix is extracted; everything before it is parsed
as a :class:GenotypePattern.
Source code in src/natal/patterns/elements/diploid.py
from_pair
staticmethod
Build a ZygoteTypePattern from a (Genotype, slab_name) pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
genotype
|
Genotype
|
A Genotype instance. |
required |
slab
|
str
|
Somatic label name. |
required |
species
|
Species
|
Species for genotype-string resolution. |
required |
Returns:
| Type | Description |
|---|---|
ZygoteTypePattern
|
A ZygoteTypePattern matching the given genotype and slab. |
Source code in src/natal/patterns/elements/diploid.py
from_slab_key
staticmethod
Parse a genotype key that may include an @slab suffix.
Splits at @, canonicalizes the genotype part via
species.get_genotype_from_str, and creates a ZygoteTypePattern
with the resolved slab suffix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Genotype key like |
required |
species
|
Species
|
Species definition for genotype resolution. |
required |
Returns:
| Type | Description |
|---|---|
ZygoteTypePattern
|
A ZygoteTypePattern with the canonical genotype and slab. |
Source code in src/natal/patterns/elements/diploid.py
matches
Check if this pattern matches a (genotype, slab_label) pair.
Source code in src/natal/patterns/elements/diploid.py
GameteTypePattern
Pattern for a gamete (haploid genome) with optional label constraint.
A gamete type pairs a :class:HaplotypePath (the genetic content across
all chromosomes) with an optional :class:LabPattern parsed from the
@lab suffix (e.g. A1/B1; C1@cas9_deposited).
Label matching is the caller's responsibility — this class simply stores both components so the parser doesn't silently discard the label.
Initialize a GameteTypePattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
haplotype_path
|
HaplotypePath
|
HaplotypePath pattern for the genetic content. |
required |
lab
|
Optional[LabPattern]
|
Optional gamete-label constraint. |
None
|
Source code in src/natal/patterns/elements/haploid.py
GenotypePatternParser
Parses genotype pattern strings into GenotypePattern objects.
Parses flexible pattern syntax including wildcards (*), set
patterns ({A,B}), negation (!A), unordered pairs (::),
bracketed groupings (()), and label suffixes (@lab).
Results are cached per (species, pattern_string) pair for performance.
Initialize parser for a specific species.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species
|
Species
|
The Species object to use for validation and context. |
required |
Source code in src/natal/patterns/parser.py
parse
Parse a pattern string into a GenotypePattern.
Supported syntax includes
;separates chromosomes (outside parentheses)|separates maternal (left) and paternal (right)/separates loci within a chromosome*matches any allele{A,B,C}matches any allele in the set!Amatches any allele except A::matches unordered pair (A::B matches A|B or B|A)()groups loci within a chromosome@labsuffix selects a somatic label (ZType constraint), e.g.A|a@cas9_high- Omitted chromosomes default to wildcard matching (optional)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern_str
|
str
|
The pattern string to parse. |
required |
Returns:
| Type | Description |
|---|---|
GenotypePattern
|
A GenotypePattern object. |
Raises:
| Type | Description |
|---|---|
PatternParseError
|
If the pattern is invalid. |
Source code in src/natal/patterns/parser.py
parse_haplotype_pattern
Parse a complete haplotype pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern_str
|
str
|
Pattern string for a single haplotype
(e.g. |
required |
Returns:
| Type | Description |
|---|---|
GameteTypePattern
|
GameteTypePattern with haplotype path and optional lab constraint. |
Raises:
| Type | Description |
|---|---|
PatternParseError
|
If the pattern is invalid. |
Source code in src/natal/patterns/parser.py
parse_haploid_genome_pattern
Parse a haploid genome pattern (single DNA strand of individual).
For haploid genomes:
- ; at top level separates different chromosomes
- () brackets represent a single haplotype (one DNA strand)
- Inside brackets, ; separates different loci on that strand
- / is not used inside brackets for haploid (it's only for diploid)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern_str
|
str
|
Pattern string (e.g., "A1/B1; C1" or "(A1; B1); C1") |
required |
Returns:
| Type | Description |
|---|---|
HaploidGenomePattern
|
HaploidGenomePattern object. |
Raises:
| Type | Description |
|---|---|
PatternParseError
|
If the pattern is invalid. |
Source code in src/natal/patterns/parser.py
get_allowed_alleles
Get all allowed allele names for a pattern element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern_element
|
PatternElement
|
The PatternElement to analyze. |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List of allowed allele names. |
Source code in src/natal/patterns/parser.py
GenotypeSelector
Unified genotype selector for observation and filtering.
Provides a unified interface for selecting genotypes using various input formats (integers, strings, pattern strings, or Genotype objects), leveraging the existing pattern matching system.
Initialize a GenotypeSelector for a specific species.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species
|
Species
|
The Species object to use for pattern parsing and genotype resolution. |
required |
Source code in src/natal/patterns/selector.py
resolve_genotype_indices
resolve_genotype_indices(gen_spec: Optional[Iterable[Any]], diploid_genotypes: Optional[Sequence[Any]], unordered: bool = False) -> List[int]
Resolve genotype selectors into a list of indices.
This method provides the same functionality as observation.py's _resolve_genotype_list() but uses the pattern matching system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen_spec
|
Optional[Iterable[Any]]
|
Genotype selector specification. Can be: - None: select all genotypes - int: genotype index - str: genotype pattern string - Genotype: genotype object - Iterable of any of the above |
required |
diploid_genotypes
|
Optional[Sequence[Any]]
|
Sequence of diploid genotypes for resolution. |
required |
unordered
|
bool
|
Whether to treat genotypes as unordered (A|a == a|A). |
False
|
Returns:
| Type | Description |
|---|---|
List[int]
|
List of resolved genotype indices. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If diploid_genotypes is required but missing. |
Source code in src/natal/patterns/selector.py
create_filter_function
create_filter_function(gen_spec: Optional[Iterable[Any]], unordered: bool = False) -> Callable[[Any], bool]
Create a filter function for genotype selection.
NOTE: Dead code as of 2026-06 — zero callers in the codebase.
The active path uses ZygoteTypePattern and resolve_zygote_type
directly. Keep for reference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen_spec
|
Optional[Iterable[Any]]
|
Genotype selector specification. |
required |
unordered
|
bool
|
Whether to use unordered matching. |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[Any], bool]
|
A callable that takes a genotype and returns True if it matches. |
Source code in src/natal/patterns/selector.py
get_pattern_for_selector
Convert a selector to a GenotypePattern if possible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selector
|
Any
|
Genotype selector. |
required |
Returns:
| Type | Description |
|---|---|
Optional[GenotypePattern]
|
GenotypePattern if selector can be converted, None otherwise. |
Source code in src/natal/patterns/selector.py
resolve_zygote_type
Resolve a genotype string to ZType indices, with species-appropriate matching.
For unordered species, auto-promotes | to :: so that "A|a"
matches both ordered and unordered (canonicalized) registrations. This
mirrors the canonicalization logic in
:meth:genetic_structures.Species.resolve_genotype_selectors.
For ordered species (e.g. sex chromosomes), | is treated strictly —
"a|A" and "A|a" are distinct genotypes and will each only match
their exact ordering.
Does NOT perform the reversed-maternal/paternal fallback (that would be a bug for ordered species).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
str
|
Genotype selector string (e.g. |
required |
species
|
Species
|
Species for genotype-resolution context. |
required |
index_registry
|
IndexRegistry
|
Registry for ZType index resolution. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
List of matching ZType indices (may be empty if nothing matches). |