Allele scores
Allele score resources associate values with individual alleles, identified by
chromosome, position, reference allele, and alternative allele. Variant-level
scores such as CADD are typical examples. A resource may contain one or
several records for the same allele, for example when scores are reported
separately for different transcripts. This is specified by the
allele_multiplicity setting in the resource definition, as described in the
Allele scores section of the GRR documentation.
GAIn provides the AlleleScore
Python class for retrieving and processing these values. AlleleScore
inherits the functionality described in Genomic scores and adds
methods for querying individual alleles and genomic regions. It also supports
retrieving multiple records for an allele and aggregating their values.
Accessing an allele score
An AlleleScore object can be built from a resource ID and a repository
using build_allele_score_from_resource_id():
import gain.grr as grr
repo = grr.build_genomic_resource_repository()
score = grr.build_allele_score_from_resource_id(
"hg38/scores/CADD_v1.7", repo
)
If you already have a GenomicResource object, use
build_allele_score_from_resource()
instead:
resource = repo.get_resource("hg38/scores/CADD_v1.7")
score = grr.build_allele_score_from_resource(resource)
Both builder functions are available through gain.grr. The generic
build_score_from_resource_id()
function also returns an AlleleScore object when the specified resource
is an allele score. The object’s multiplicity and score mode are determined
from the resource definition when it is built. These properties are explained
below.
Opening and closing an allele score
An AlleleScore object is initially closed and must be opened before
reading values. As with other genomic scores, call open() explicitly
and use a with block to close the object afterward:
with grr.build_allele_score_from_resource_id(
"hg38/scores/CADD_v1.7", repo
).open() as score:
print(score.get_allele_scores_for_allele("chr1", 69_094, "G", "A"))
The opening and closing behavior is described in more detail in Genomic scores.
Retrieving allele scores
Allele scores provide methods for retrieving values for a specified allele or for alleles found within a genomic interval. Queries for an individual allele use chrom, pos, ref, and alt. Region queries use chrom, start, and end. These location arguments are positional, while the remaining arguments are supplied by keyword. All the allele-query methods listed below accept an optional score_filter, as described in Genomic scores.
The methods differ in whether they return one record, all matching records,
or aggregated values. Methods ending in _rows return individual records
without combining them. Methods ending in _agg combine matching records
using aggregation queries. Methods without either suffix return the values
of a single record. The latter are appropriate only when the resource is
expected to have one record per allele.
Most read methods have plural and singular forms. Plural methods named
get_allele_scores_... accept a list of score IDs (scores). Singular
methods named get_allele_score_... take one score ID (score).
Aggregation methods use score-and-aggregator queries instead. The region
aggregation method has no singular counterpart.
Query |
One record |
All matching records ( |
Aggregated values ( |
|---|---|---|---|
One allele ( |
|||
One position ( |
Not implemented |
Not implemented |
Not implemented |
A region ( |
Not implemented |
The methods marked as not implemented are reserved in the interface, but no corresponding read methods are currently available.
For a specific allele, get_allele_scores_for_allele() returns a tuple of
values in the order of the requested scores, or None if no record is
found. Its singular counterpart,
get_allele_score_for_allele(),
returns one value. For alleles with potentially multiple records,
get_allele_scores_for_allele_rows()
returns a list of tuples, one per record. The singular
get_allele_score_for_allele_rows()
returns a list of values.
Region queries also report which alleles were found.
get_allele_scores_in_region_rows()
yields an AlleleEntry for each
record, containing pos, ref, alt, and values. Its singular
counterpart,
get_allele_score_in_region_rows(),
yields tuples of (pos, ref, alt, value). In contrast, methods querying
one specified allele do not include its coordinates and nucleotides in their
results, since these were already supplied by the caller.
For example:
with grr.build_score_from_resource_id(
"hg38/scores/CADD_v1.7", repo
).open() as score:
values = score.get_allele_scores_for_allele(
"chr1", 69_094, "G", "A"
)
print(values)
for entry in score.get_allele_scores_in_region_rows(
"chr1", 69_094, 69_096
):
print(entry.pos, entry.ref, entry.alt, entry.values)
Aggregating allele scores
Aggregation methods combine values from the records found for one allele or
within a genomic region. Use
get_allele_scores_for_allele_agg()
to aggregate the records for a specified allele, or
get_allele_scores_in_region_agg()
to aggregate records within a region. For a single score and aggregator at a
specified allele, use
get_allele_score_for_allele_agg().
There is no singular region aggregation method.
These methods return an
AlleleAggregate object,
which contains the aggregated values and the allele keys matched by the
query. The allele keys are present only when the call asks for them with the
allele_keys argument; otherwise allele_keys is None. The values are ordered according to the aggregation queries, not
indexed by score ID. Thus, asking for the same score with two different
aggregators produces two results. Region aggregation processes the matching
records in a single traversal, keeping the aggregate values and matched
alleles consistent. The shared aggregation interface is also discussed in
Genomic scores.
Multiple records per allele
An allele score resource may contain multiple records for the same allele, identified by (chrom, pos, ref, alt). For example, a variant may have separate annotations for different transcripts. The allele_multiplicity setting in the resource definition specifies whether a resource allows only one record per allele (one, the default) or multiple records (many). This setting is available in Python through multiplicity.
The multiplicity setting determines which methods can be used to retrieve allele scores. For resources with allele_multiplicity: many, methods that return a single record are not appropriate because several records may match the same allele. Instead, use methods ending in _rows to retrieve all matching records or _agg to combine their values. These methods also work with one resources. When the data is valid, _rows returns at most one record for each allele in a one resource, while _agg aggregates that record.
GAIn checks whether the records in a resource agree with its declared multiplicity. A single-record read on a many resource always raises AlleleMultiplicityError, even if the requested allele has only one record. For a one resource, finding multiple records for the same allele is a data error. Once multiplicity enforcement is enabled, this also raises AlleleMultiplicityError. Single-record reads count matching records before applying score_filter, so filtering cannot conceal a multiplicity violation.
Multiplicity is also checked when resource statistics are generated using grr_manage repo-stats or grr_manage repo-repair. For a resource declaring allele_multiplicity: one, duplicate allele records produce warnings before the enforcement release. During this period, single-record reads also warn and return the first matching record. The score_filter is applied only to that record, so the result may be None even if another matching record would pass the filter.
Starting with the enforcement release, duplicate allele records in a one resource raise AlleleMultiplicityError, and a statistics build encountering such a violation produces no output. The enforcement release is defined by ALLELE_MULTIPLICITY_ENFORCEMENT_RELEASE (2027.1.0) in gain.genomic_resources.resource_types. The allele_multiplicity_enforced() function in the same module indicates whether enforcement is active in the installed GAIn version.
Missing values and filtered results
The different read methods distinguish missing alleles and filtered records
in different ways. Single-record reads return None when no record is
found or the selected record is rejected by the filter. The _rows
methods return an empty result in either case. Aggregation methods make an
additional distinction between an allele with no matching records and an
allele whose records were all filtered out. For single-record reads, the first three cases assume a resource
with allele_multiplicity: one.
Situation |
Single-record read |
|
|
|---|---|---|---|
No record for the allele |
|
Empty result |
|
Records exist, but the filter rejects all of them |
|
Empty result |
Aggregate over an empty selection |
Exactly one record |
Its values |
One record |
Aggregate of one record |
Multiple records on a |
Warning and first record before enforcement, or |
All matching records |
Aggregate of all matching records |
Any allele on a |
|
All matching records |
Aggregate of all matching records |
Unknown contig |
|
|
|
For one allele, an empty _rows result is an empty list. For a region, an
empty _rows result is a generator that yields no records. These methods
never return None. The region aggregation method follows the same rules
as aggregation for one allele: it returns None if no record overlaps the
region, but returns an aggregate over an empty selection if records exist
and the filter rejects all of them. In an empty aggregate, max produces
None and list produces [].
Allele score modes
Allele score resources also declare an allele_score_mode of either
substitutions or alleles. These are reported by
substitutions_mode()
and alleles_mode().
Unlike allele_multiplicity, the mode does not change how the read methods
work. A direct lookup for an insertion or deletion retrieves its exact
record, or returns None, in either mode.
Instead, the mode determines how the allele score annotator processes a
VCFAllele. In substitutions mode, substitutions are matched exactly,
while insertions, deletions, and complex alleles are handled by aggregating
scores over the bases they cover. In alleles mode, every allele is
matched exactly. The annotator also considers allele_multiplicity.
For a one resource, it uses a single-record lookup. For a many
resource, it uses
get_allele_scores_for_allele_agg(),
aggregating each attribute with its configured aggregator.
API
The classes below are defined in the module
gain.genomic_resources.genomic_scores.allele, and the package
gain.genomic_resources.genomic_scores exports them. AlleleScore is also
exported by gain.grr, as grr.AlleleScore.
The builders build_allele_score_from_resource_id and
build_allele_score_from_resource build a closed score. They are
defined in the module gain.genomic_resources.genomic_scores.builders and
are imported from gain.genomic_resources.genomic_scores. They are also
exported by gain.grr, as grr.build_allele_score_from_resource_id
and grr.build_allele_score_from_resource.
|
Build an allele score from an |
|
Build an allele score from the id of an |
|
Allele-specific genomic score resource. |
The aggregator that a query uses when it names none, by the value type of the score: |
|
|
|
|
The allele score mode, as the resource declares it. |
|
How many table rows one allele may have. |
Return whether the mode of the resource is |
|
Fetch a region as column arrays, with the nucleotides. |
|
Return the value of one score at the only row of one allele. |
|
Reduce the rows of one allele for one score. |
|
Return the value of one score for every row of one allele. |
|
Yield |
|
Return the values of the only row of one allele. |
|
Reduce the rows of one allele to one value per query. |
|
Return the values of every row of one allele, in file order. |
|
Reduce the alleles in a region to one value per query. |
|
Yield an |
|
Return the schema of the resource configuration. |
|
The number of rows that one allele may have in the table. |
|
Return whether the mode of the resource is |
|
Return whether |
|
|
The answer of a folding read: one value per query, and the allele keys. |
|
One allele row of a region, as the unreduced region read yields it. |
|
The rows of an allele score disagree with its |
|
Build the allele key, |
Inherited from GenomicScore, which has its own page,
Genomic scores:
Return the source of chromosome lengths in the score's own table. |
|
The sources that the score can answer a length from, best first. |
|
Close the underlying table and mark the score not open. |
|
|
Compile a boolean expression into a filter over this score. |
|
Yield the records of a region, optionally filtered. |
Yield |
|
Fetch a region as column arrays, without a record for each row. |
|
|
Return the length of every chromosome. |
Return the chromosome names that the score's table holds. |
|
|
Return the length of a chromosome. |
Return the source that answers |
|
Return the configuration of the score. |
|
Read one score off a record of this score's table. |
|
|
Report whether the score's table carries a chromosome. |
Report whether the score is open. |
|
Open the score for reading and return it. |
|
Report whether |
- build_allele_score_from_resource(resource: GenomicResource) AlleleScore[source]
Build an allele score from an
allele_scoreresource.Every call builds a new score. The score is closed: call
open()before the first read.- Parameters:
resource (GenomicResource) – A resource of type
allele_score.- Returns:
A new, closed score. The mode is
allelesunless the resource setsallele_score_mode.- Return type:
- Raises:
ValueError – If the resource is not of type
allele_score. A resource that still declares the removed typenp_scoreis also refused. The message names the replacement type and the mode key that keeps the old reading.
- build_allele_score_from_resource_id(resource_id: str, grr: GenomicResourceRepo | None = None) AlleleScore[source]
Build an allele score from the id of an
allele_scoreresource.Every call builds a new score. The score is closed: call
open()before the first read.- Parameters:
resource_id (str) – The id of a resource of type
allele_scorein the repository.grr (GenomicResourceRepo or None, optional) – The repository that resolves
resource_id.None, the default, builds the default repository withbuild_genomic_resource_repository().
- Returns:
A new, closed score, as
build_allele_score_from_resourcebuilds it.- Return type:
- Raises:
FileNotFoundError – If the repository has no resource with this id.
ValueError – If the resource is not of type
allele_score.
- class AlleleScore(resource: GenomicResource)[source]
Allele-specific genomic score resource.
An AlleleScore provides scores that depend on specific alleles at genomic positions. Unlike PositionScore, AlleleScore considers both the reference and alternative alleles when computing scores. This makes it suitable for variant-specific predictions and annotations.
AlleleScore supports two operational modes:
SUBSTITUTIONS mode: Scores are specific to nucleotide substitutions (e.g., A>T, C>G). This mode is optimized for single nucleotide variants and considers the directionality of the change. Used by resources like CADD, which provide substitution-specific scores.
ALLELES mode: Scores are associated with specific alleles at positions, without considering the reference allele. This mode supports insertions, deletions, and more complex variants. The score depends on the alternative allele itself rather than the substitution pattern.
Typical use cases include: - Variant pathogenicity scores (e.g., CADD, DANN) - Functional impact predictions (e.g., PolyPhen, SIFT scores) - Splice site predictions - Regulatory variant scores - Any metric that depends on specific alleles
The score data is typically stored in VCF files or tabix-indexed tables with reference and alternative allele columns.
Example
>>> from gain.genomic_resources.repository_factory import ( ... build_genomic_resource_repository ... ) >>> repo = build_genomic_resource_repository() >>> resource = repo.get_resource("cadd_v1_6") >>> score = build_score_from_resource(resource) >>> with score.open() as score: ... # Fetch the scores of a specific variant's row ... values = score.get_allele_scores_for_allele( ... "chr1", 12345, "A", "T" ... ) ... # Iterate over the alleles in a region. The nucleotides ... # come off the record; the values come off the score. ... for record in score.fetch_records("chr1", 10000, 20000): ... values = score.get_score_values_from_record( ... record, score_defs ... ) ... print(f"{record[POS_BEGIN]} " ... f"{record[REF]}>{record[ALT]}: {values}")
Reducing those values over a region is the resource’s own job:
get_allele_scores_in_region_agg()folds a region in one streaming walk, one value perScoreAggregationQuery, with the allele keys beside them when asked, and the allele annotator’s region mode reads through it (gain.annotation.allele_score_annotator).No read consults the mode: an exact-match read answers an indel’s own line in either mode. The mode is for the caller to route on, and the allele score annotator does – on a
substitutionsresource it folds any allele other than a substitution over its span instead of matching it.- Variables:
resource (gain.genomic_resources.repository.GenomicResource) – The underlying GenomicResource object
resource_id – Unique identifier for the resource
config (dict[str, Any]) – Configuration dictionary for the score
table – GenomicPositionTable for data access (typically VCF)
score_definitions (dict[str, ScoreDefT]) – Dictionary mapping score IDs to their definitions
mode – Operating mode (SUBSTITUTIONS or ALLELES)
- Key Methods:
get_allele_scores_for_allele: Get the values of one allele’s only row, on a resource declaring one row per allele get_allele_score_for_allele: The same for one score get_allele_scores_in_region_agg: Reduce the alleles of a region to one value per query – and their keys – in one walk, telling the same two answers apart get_allele_scores_for_allele_agg: Reduce the rows of one allele to one value per query, telling an allele no row holds apart from one whose rows were all rejected get_allele_score_for_allele_agg: The same for one score get_allele_scores_for_allele_rows: Get the values of every row of one allele, unreduced get_allele_score_for_allele_rows: The same for one score get_allele_scores_in_region_rows: Stream an AlleleEntry per row of a region, unreduced, off the walk the folding read reduces get_allele_score_in_region_rows: The same for one score, as
(pos, ref, alt, value)fetch_region_segments_scores: Iterate over allele scores in a genomic region substitutions_mode: Check if operating in SUBSTITUTIONS mode alleles_mode: Check if operating in ALLELES mode- Configuration:
The resource configuration should specify:
table.filename: Path to the data file (usually VCF)
table.reference: Column/field containing reference alleles
table.alternative: Column/field containing alternative alleles
allele_score_mode: Either “substitutions” or “alleles” (optional)
allele_multiplicity: Either “one” (the default) or “many” – how many table rows one allele key may have (optional)
scores: List of score definitions with an optional aggregator specification
- DEFAULT_AGGREGATORS: ClassVar[dict[str, str | None]] = {'bool': None, 'float': 'max', 'int': 'max', 'str': 'list'}
The aggregator that a query uses when it names none, by the value type of the score:
maxfor numbers,listfor strings and none for booleans.
- HISTOGRAM_COUNT_UNIT: ClassVar[str] = 'alleles'
"alleles".- Type:
The unit that the histograms of this kind count
- class Mode(*values)[source]
The allele score mode, as the resource declares it.
SUBSTITUTIONSis the modesubstitutionsandALLELESis the modealleles. No read consults the mode. The allele score annotator uses it to route an allele.
- class Multiplicity(*values)[source]
How many table rows one allele may have.
The resource declares it with the top-level key
allele_multiplicity.ONEis the default.MANYmeans that several rows may hold one(chrom, pos, ref, alt), for example one row for each transcript.
- fetch_region_allele_arrays(chrom: str, pos_begin: int | None, pos_end: int | None, scores: list[str], *, batch_size: int = 100000) Generator[AlleleRecordArrays, None, None][source]
Fetch a region as column arrays, with the nucleotides.
The read widens
fetch_region_value_arrays()with thereferenceandalternativecolumns. It is meant for a caller that scans a whole region for allele content, such as the allele statistics.The nucleotides are raw and the scores are parsed. An NA sentinel of a score arrives as the non-value of the score. The two nucleotide columns go through no parsing: no upper-casing, no stripping and no sentinel handling. A caller that wants them normalised does it once, where the meaning is known.
- Parameters:
chrom (str) – The chromosome name.
pos_begin (int or None) – The first position of the region, 1-based.
Nonemeans the start of the chromosome.pos_end (int or None) – The last position of the region.
Nonemeans the end of the chromosome.scores (list[str]) – The score ids to read.
batch_size (int, optional) – The most rows in a batch. The reference and alternative columns count toward
VALUE_ARRAYS_CELL_BUDGETlike two scores, so a batch holds at mostbudget // (len(scores) + 2)rows. The default is 100000.
- Returns:
The batches, in position order. A batch has the position arrays and the value arrays of
fetch_region_value_arrays(), followed by thereferenceandalternativearrays. A key column that the table does not declare is an array ofNone.- Return type:
Generator[AlleleRecordArrays, None, None]
- Raises:
TypeError – If the score does not serve the read for
scores. Asksupports_region_allele_arrays()first.ValueError – If the score is not open, or if the contig is not in the resource.
Notes
The call checks the request. The errors above are raised when the method is called and not on the first
next().
- get_allele_score_for_allele(chrom: str, pos: int, ref: str, alt: str, *, score: str | None = None, score_filter: ScoreFilter | None = None) str | int | float | bool | None[source]
Return the value of one score at the only row of one allele.
The singular form of
get_allele_scores_for_allele().- Parameters:
chrom (str) – The chromosome name.
pos (int) – The position of the allele.
ref (str) – The reference nucleotides.
alt (str) – The alternative nucleotides.
score (str or None, optional) – The score id.
None, the default, is accepted only when the resource defines exactly one score.score_filter (ScoreFilter or None, optional) – Keep the row only if this filter accepts it.
- Returns:
The value of the score.
Nonewhen no row holds the allele, or whenscore_filterrejects the row. The value itself may also beNonewhen the row has no value for the score.- Return type:
ScoreValue or None
- Raises:
AlleleMultiplicityError – As
get_allele_scores_for_allele().ValueError – As
get_allele_scores_for_allele(). Also whenscoreisNoneand the resource defines several scores.ScoreFilterError – If
score_filterwas compiled for another resource.
- get_allele_score_for_allele_agg(chrom: str, pos: int, ref: str, alt: str, *, score: str | None = None, aggregator: str | None = None, score_filter: ScoreFilter | None = None) AlleleAggregate | None[source]
Reduce the rows of one allele for one score.
The singular form of
get_allele_scores_for_allele_agg(). It does not unwrap the answer: theAlleleAggregatehas avaluestuple of one element.- Parameters:
chrom (str) – The chromosome name.
pos (int) – The position of the allele.
ref (str) – The reference nucleotides.
alt (str) – The alternative nucleotides.
score (str or None, optional) – The score id.
None, the default, is accepted only when the resource defines exactly one score.aggregator (str or None, optional) – The aggregator name.
None, the default, is the default aggregator of the score.score_filter (ScoreFilter or None, optional) – Keep only the rows that this filter accepts.
- Returns:
- Return type:
AlleleAggregate or None
- Raises:
ValueError – As
get_allele_scores_for_allele_agg(). Also whenscoreisNoneand the resource defines several scores.ScoreFilterError – If
score_filterwas compiled for another resource.
- get_allele_score_for_allele_rows(chrom: str, pos: int, ref: str, alt: str, *, score: str | None = None, score_filter: ScoreFilter | None = None) list[str | int | float | bool | None][source]
Return the value of one score for every row of one allele.
The singular form of
get_allele_scores_for_allele_rows().- Parameters:
chrom (str) – The chromosome name.
pos (int) – The position of the allele.
ref (str) – The reference nucleotides.
alt (str) – The alternative nucleotides.
score (str or None, optional) – The score id.
None, the default, is accepted only when the resource defines exactly one score.score_filter (ScoreFilter or None, optional) – Keep only the rows that this filter accepts.
- Returns:
One value for each row that the filter keeps, in file order. The list is empty when no row carries the allele or when the filter rejects every row.
- Return type:
list[ScoreValue]
- Raises:
ValueError – As
get_allele_scores_for_allele_rows(). Also whenscoreisNoneand the resource defines several scores.ScoreFilterError – If
score_filterwas compiled for another resource.
- get_allele_score_in_region_rows(chrom: str, start: int, end: int, *, score: str | None = None, score_filter: ScoreFilter | None = None) Generator[tuple[int, str | None, str | None, str | int | float | bool | None], None, None][source]
Yield
(pos, ref, alt, value)for each row that overlaps a region.The singular form of
get_allele_scores_in_region_rows().- Parameters:
chrom (str) – The chromosome name.
start (int) – The first position of the region, 1-based.
end (int) – The last position of the region.
score (str or None, optional) – The score id.
None, the default, is accepted only when the resource defines exactly one score.score_filter (ScoreFilter or None, optional) – Keep only the rows that this filter accepts.
- Returns:
One tuple for each row that the filter keeps. The generator yields nothing when no row overlaps the region or when the filter rejects every row.
reforaltisNonewhen the table has no such column.- Return type:
Generator[tuple[int, str or None, str or None, ScoreValue], None, None]
- Raises:
ValueError – As
get_allele_scores_in_region_rows(). Also whenscoreisNoneand the resource defines several scores.ScoreFilterError – If
score_filterwas compiled for another resource.
Notes
The call checks the request. The table is read lazily, as in
get_allele_scores_in_region_rows().
- get_allele_scores_for_allele(chrom: str, pos: int, ref: str, alt: str, *, scores: Sequence[str] | None = None, score_filter: ScoreFilter | None = None) tuple[str | int | float | bool | None, ...] | None[source]
Return the values of the only row of one allele.
The match is exact on the position and on the nucleotides: a row that starts earlier and whose span reaches
posis not this allele. The read does not consultallele_score_mode.The read answers one row, as the
multiplicityof the resource promises. A resource that declaresallele_multiplicity: manyis refused, because one allele may hold several rows. On aoneresource, several rows that hold the allele are a data error. The rows are counted beforescore_filter, so a filter that hides one of them does not hide the error. Untilallele_multiplicity_enforced()answers true, the read warns once for each process and answers the first row. The filter applies to that row alone.- Parameters:
chrom (str) – The chromosome name.
pos (int) – The position of the allele.
ref (str) – The reference nucleotides.
alt (str) – The alternative nucleotides.
scores (Sequence[str] or None, optional) – The score ids to read.
None, the default, means every score of the resource, in definition order.score_filter (ScoreFilter or None, optional) – Keep the row only if this filter accepts it.
None, the default, accepts every row.
- Returns:
The values of the row, parallel to
scores.Nonewhen no row holds the allele, or whenscore_filterrejects the row.- Return type:
tuple[ScoreValue, …] or None
- Raises:
AlleleMultiplicityError – If the resource declares
allele_multiplicity: many. Also if several rows hold the allele on aoneresource, once the enforcement release is reached. Read every row withget_allele_scores_for_allele_rows(), or reduce the rows withget_allele_scores_for_allele_agg().ValueError – If a score id is unknown, or if the contig is not in the resource.
ScoreFilterError – If
score_filterwas compiled for another resource.
Notes
The call checks the request before it reads a row, and before the
manyrefusal: an unknown score id, an unknown contig and a foreign filter are refused on any resource.
- get_allele_scores_for_allele_agg(chrom: str, pos: int, ref: str, alt: str, *, queries: Sequence[ScoreAggregationQuery] | None = None, allele_keys: Sequence[str] | None = None, score_filter: ScoreFilter | None = None) AlleleAggregate | None[source]
Reduce the rows of one allele to one value per query.
Fold the rows at exactly
(chrom, pos, ref, alt). A row that starts earlier and whose span reachesposis not folded. The read folds the rows thatget_allele_scores_for_allele_rows()answers, with the queries, the aggregators and theAlleleAggregateofget_allele_scores_in_region_agg(). The read is allowed on both multiplicities and does not consultallele_score_mode. On aoneresource it folds the single row.- Parameters:
chrom (str) – The chromosome name.
pos (int) – The position of the allele.
ref (str) – The reference nucleotides.
alt (str) – The alternative nucleotides.
queries (Sequence[ScoreAggregationQuery] or None, optional) – What to compute.
None, the default, means every score of the resource with its default aggregator.allele_keys (Sequence[str] or None, optional) – As in
get_allele_scores_in_region_agg(). The answer has the one keychrom:pos:ref:alt, or several keys when a suffixed score differs across the rows.score_filter (ScoreFilter or None, optional) – Keep only the rows that this filter accepts.
None, the default, keeps every row.
- Returns:
Nonewhen no row holds the allele. The check happens before the filter. When the filter rejects every row, the answer is anAlleleAggregatein which each aggregator answers for no rows:maxgivesNone,listgives[]andcountgives0.- Return type:
AlleleAggregate or None
- Raises:
ValueError – If a score id is unknown, if a query has no aggregator to resolve to, if an aggregator is bad, or if the contig is not in the resource.
ScoreFilterError – If
score_filterwas compiled for another resource.
Notes
The call checks the request before it reads a row.
- get_allele_scores_for_allele_rows(chrom: str, pos: int, ref: str, alt: str, *, scores: Sequence[str] | None = None, score_filter: ScoreFilter | None = None) list[tuple[str | int | float | bool | None, ...]][source]
Return the values of every row of one allele, in file order.
Several rows may carry one allele, and all of them are answered. The read does not reduce the rows and does not consult
allele_score_mode. The match is exact on the position and on the nucleotides: a row that starts earlier and whose span reachesposis not this allele.- Parameters:
chrom (str) – The chromosome name.
pos (int) – The position of the allele.
ref (str) – The reference nucleotides.
alt (str) – The alternative nucleotides.
scores (Sequence[str] or None, optional) – The score ids to read.
None, the default, means every score of the resource.score_filter (ScoreFilter or None, optional) – Keep only the rows that this filter accepts. The filter is evaluated on every row that overlaps the position, not only on the rows of the allele.
None, the default, keeps every row.
- Returns:
One tuple for each row that the filter keeps, parallel to
scores. The list is empty both when no row carries the allele and when the filter rejects every row. The read does not tell the two cases apart.- Return type:
list[tuple[ScoreValue, …]]
- Raises:
ValueError – If a score id is unknown, or if the contig is not in the resource.
ScoreFilterError – If
score_filterwas compiled for another resource.
Notes
The call checks the request before it reads a row.
- get_allele_scores_in_region_agg(chrom: str, start: int, end: int, *, queries: Sequence[ScoreAggregationQuery] | None = None, allele_keys: Sequence[str] | None = None, score_filter: ScoreFilter | None = None) AlleleAggregate | None[source]
Reduce the alleles in a region to one value per query.
Fold the rows that overlap the region and that
score_filterkeeps, in one walk that holds no row. An allele row weighs 1.- Parameters:
chrom (str) – The chromosome name.
start (int) – The first position of the region, 1-based.
end (int) – The last position of the region.
queries (Sequence[ScoreAggregationQuery] or None, optional) – What to compute. Each query is a score with an optional aggregator, and the aggregator of the query wins over the default aggregator of the score.
None, the default, means every score of the resource with its default aggregator.allele_keys (Sequence[str] or None, optional) – The score ids that suffix each allele key.
None, the default, builds no keys. An empty sequence builds the barechrom:pos:ref:altkeys. Seeallele_key().score_filter (ScoreFilter or None, optional) – Keep only the rows that this filter accepts. Build the filter with
compile_filter()of this score.None, the default, keeps every row.
- Returns:
Nonewhen no row overlaps the region. The check happens before the filter. Otherwise anAlleleAggregate. When the filter rejects every row, each aggregator answers for an empty selection:maxgivesNoneandlistgives[]. The keys are distinct and in the order the rows were first seen.- Return type:
AlleleAggregate or None
- Raises:
ValueError – If a score id of
queriesorallele_keysis unknown, if a query has no aggregator to resolve to, or if the contig is not in the resource.ScoreFilterError – If
score_filterwas compiled for another resource.
Notes
The call checks the request before it reads a row.
- get_allele_scores_in_region_rows(chrom: str, start: int, end: int, *, scores: Sequence[str] | None = None, score_filter: ScoreFilter | None = None) Generator[AlleleEntry, None, None][source]
Yield an
AlleleEntryfor each row that overlaps a region.The entries come in the position order of the table. Rows that share an allele are each yielded. The read does not reduce the rows and does not consult
allele_score_mode.- Parameters:
chrom (str) – The chromosome name.
start (int) – The first position of the region, 1-based.
end (int) – The last position of the region.
scores (Sequence[str] or None, optional) – The score ids to read.
None, the default, means every score of the resource.score_filter (ScoreFilter or None, optional) – Keep only the rows that this filter accepts.
None, the default, keeps every row.
- Returns:
One entry for each row that the filter keeps, with
valuesparallel toscores. The generator yields nothing both when no row overlaps the region and when the filter rejects every row.get_allele_scores_in_region_agg()tells the two cases apart.- Return type:
Generator[AlleleEntry, None, None]
- Raises:
ValueError – If a score id is unknown, or if the contig is not in the resource.
ScoreFilterError – If
score_filterwas compiled for another resource.
Notes
The call checks the request, and the errors above are raised before the generator is returned. The table is read lazily, on the first
next(). Iterate one generator at a time, as with every region read of a table, and materialise what has to outlive the next read.
- static get_schema() dict[str, Any][source]
Return the schema of the resource configuration.
The schema is the
GenomicScoreschema plus the keysallele_score_mode,allele_multiplicityandmerge_vcf_scores, and thereference,alternativeandvariantcolumn definitions of the table.- Returns:
A new schema in the Cerberus format. The caller may change it.
- Return type:
dict[str, Any]
- property multiplicity: Multiplicity
The number of rows that one allele may have in the table.
Only the bare reads consult it, such as
get_allele_scores_for_allele().
- supports_region_allele_arrays(scores: list[str]) bool[source]
Return whether
fetch_region_allele_arrays()serves the scores.The answer needs the conditions of
supports_region_value_arrays()(the backend and the value types of the scores) and one more: the table must declare at least one of thereferenceandalternativecolumns. One column is enough. A bigWig-backed score has no such columns and is not served.The method works on a score that is not open. In one case the answer is conservative there: a table with
header_mode: filethat names its key columns only in its data file answersFalseuntil the score is opened, andTrueafter.- Parameters:
scores (list[str]) – The score ids that the caller wants to read.
- Returns:
Trueiffetch_region_allele_arrays()accepts the scores. If the answer isFalse, read per record withfetch_records(). The rows are the same.- Return type:
bool
- class AlleleAggregate(values: tuple[str | int | float | bool | None, ...], allele_keys: tuple[str, ...] | None)[source]
The answer of a folding read: one value per query, and the allele keys.
- Variables:
values (tuple[ScoreValue, ...]) – One value for each query of the read, in the order asked. A query is a score with an aggregator, so one score asked with two aggregators gives two values.
allele_keys (tuple[str, ...] | None) – The distinct allele keys of the rows that were folded, in the order the rows were first seen. The value is
Nonewhen the read was not asked for keys. Seeallele_key()for the format.
- class AlleleEntry(pos: int, ref: str | None, alt: str | None, values: tuple[ScoreValue, ...])[source]
One allele row of a region, as the unreduced region read yields it.
- Variables:
pos (int) – The position of the row.
ref (str | None) – The reference nucleotides of the row, as the table holds them. The value is
Nonewhen the table has no reference column.alt (str | None) – The alternative nucleotides of the row, as the table holds them. The value is
Nonewhen the table has no alternative column.values (tuple[ScoreValue, ...]) – The values of the scores that the read was asked for, in the order asked.
- alt: str | None
Alias for field number 2
- pos: int
Alias for field number 0
- ref: str | None
Alias for field number 1
- values: tuple[str | int | float | bool | None, ...]
Alias for field number 3
- class AlleleMultiplicityError(resource_id: str, detail: str, *, allele: tuple[str, int, str | None, str | None] | None = None)[source]
The rows of an allele score disagree with its
allele_multiplicity.The message is
detailwith a prefix: the resource id and, when the refusal concerns one allele, the allele spelled byallele_key():AlleleMultiplicityError( "scores/x", "holds 2 rows but declares allele_multiplicity: one", allele=("1", 10, "A", "G")) # allele score 'scores/x', allele 1:10:A:G: holds 2 rows ...
- Variables:
resource_id (str) – The id of the resource that the error is about.
allele (tuple[str, int, str | None, str | None] | None) – The allele as
(chrom, pos, ref, alt). The value isNonewhen the refusal does not concern one allele.detail (str) – The message without the prefix.
- allele_key(chrom: str, pos: int, ref: str | None, alt: str | None, suffix: Sequence[str | int | float | bool | None] = ()) str[source]
Build the allele key,
chrom:pos[:ref:alt][:v1,v2].The key is the identity of an allele as annotation output spells it.
- Parameters:
chrom (str) – The chromosome name.
pos (int) – The position of the allele.
ref (str or None) – The reference nucleotides. The key has no
:ref:altpart when this oraltisNone.alt (str or None) – The alternative nucleotides.
suffix (Sequence[ScoreValue], optional) – The values of the scores to append, in the order asked. Each value is rendered as
stringify()renders it for output, and the values are joined with,. The suffix is part of the identity: two rows of one allele that differ in a suffixed score give two keys. The default is an empty sequence, which appends nothing.
- Returns:
The key, for example
1:10:A:Gor1:10:A:G:0.5,2.- Return type:
str