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.

Allele score query methods

Query

One record

All matching records (_rows)

Aggregated values (_agg)

One allele (for_allele)

get_allele_scores_for_allele()

get_allele_scores_for_allele_rows()

get_allele_scores_for_allele_agg()

One position (at_position)

Not implemented

Not implemented

Not implemented

A region (in_region)

Not implemented

get_allele_scores_in_region_rows()

get_allele_scores_in_region_agg()

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.

Allele score query results

Situation

Single-record read

_rows read

for_allele_agg read

No record for the allele

None

Empty result

None

Records exist, but the filter rejects all of them

None

Empty result

Aggregate over an empty selection

Exactly one record

Its values

One record

Aggregate of one record

Multiple records on a one resource

Warning and first record before enforcement, or AlleleMultiplicityError afterward

All matching records

Aggregate of all matching records

Any allele on a many resource

AlleleMultiplicityError, raised immediately

All matching records

Aggregate of all matching records

Unknown contig

ValueError

ValueError

ValueError

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_allele_score_from_resource(resource)

Build an allele score from an allele_score resource.

build_allele_score_from_resource_id(resource_id)

Build an allele score from the id of an allele_score resource.

AlleleScore(resource)

Allele-specific genomic score resource.

AlleleScore.DEFAULT_AGGREGATORS

The aggregator that a query uses when it names none, by the value type of the score: max for numbers, list for strings and none for booleans.

AlleleScore.HISTOGRAM_COUNT_UNIT

"alleles".

AlleleScore.Mode(*values)

The allele score mode, as the resource declares it.

AlleleScore.Multiplicity(*values)

How many table rows one allele may have.

AlleleScore.alleles_mode()

Return whether the mode of the resource is alleles.

AlleleScore.fetch_region_allele_arrays(...)

Fetch a region as column arrays, with the nucleotides.

AlleleScore.get_allele_score_for_allele(...)

Return the value of one score at the only row of one allele.

AlleleScore.get_allele_score_for_allele_agg(...)

Reduce the rows of one allele for one score.

AlleleScore.get_allele_score_for_allele_rows(...)

Return the value of one score for every row of one allele.

AlleleScore.get_allele_score_in_region_rows(...)

Yield (pos, ref, alt, value) for each row that overlaps a region.

AlleleScore.get_allele_scores_for_allele(...)

Return the values of the only row of one allele.

AlleleScore.get_allele_scores_for_allele_agg(...)

Reduce the rows of one allele to one value per query.

AlleleScore.get_allele_scores_for_allele_rows(...)

Return the values of every row of one allele, in file order.

AlleleScore.get_allele_scores_in_region_agg(...)

Reduce the alleles in a region to one value per query.

AlleleScore.get_allele_scores_in_region_rows(...)

Yield an AlleleEntry for each row that overlaps a region.

AlleleScore.get_schema()

Return the schema of the resource configuration.

AlleleScore.multiplicity

The number of rows that one allele may have in the table.

AlleleScore.substitutions_mode()

Return whether the mode of the resource is substitutions.

AlleleScore.supports_region_allele_arrays(scores)

Return whether fetch_region_allele_arrays() serves the scores.

AlleleAggregate(values, allele_keys)

The answer of a folding read: one value per query, and the allele keys.

AlleleEntry(pos, ref, alt, values)

One allele row of a region, as the unreduced region read yields it.

AlleleMultiplicityError(resource_id, detail, *)

The rows of an allele score disagree with its allele_multiplicity.

allele_key(chrom, pos, ref, alt[, suffix])

Build the allele key, chrom:pos[:ref:alt][:v1,v2].

Inherited from GenomicScore, which has its own page, Genomic scores:

GenomicScore.chrom_length_source

Return the source of chromosome lengths in the score's own table.

GenomicScore.chrom_length_sources

The sources that the score can answer a length from, best first.

GenomicScore.close()

Close the underlying table and mark the score not open.

GenomicScore.compile_filter(expression)

Compile a boolean expression into a filter over this score.

GenomicScore.fetch_records(chrom, pos_begin, ...)

Yield the records of a region, optionally filtered.

GenomicScore.fetch_region_segments_scores(chrom)

Yield (begin, end, values) for each record that touches a region.

GenomicScore.fetch_region_value_arrays(...)

Fetch a region as column arrays, without a record for each row.

GenomicScore.get_all_chrom_lengths([source])

Return the length of every chromosome.

GenomicScore.get_all_chromosomes()

Return the chromosome names that the score's table holds.

GenomicScore.get_chrom_length(chrom[, source])

Return the length of a chromosome.

GenomicScore.get_chrom_length_source(chrom)

Return the source that answers get_chrom_length().

GenomicScore.get_config()

Return the configuration of the score.

GenomicScore.get_score_value_from_record(...)

Read one score off a record of this score's table.

GenomicScore.has_chromosome(chrom)

Report whether the score's table carries a chromosome.

GenomicScore.is_open()

Report whether the score is open.

GenomicScore.open()

Open the score for reading and return it.

GenomicScore.supports_region_value_arrays(scores)

Report whether fetch_region_value_arrays() serves these scores.

build_allele_score_from_resource(resource: GenomicResource) → AlleleScore[source]

Build an allele score from an allele_score resource.

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 alleles unless the resource sets allele_score_mode.

Return type:

AlleleScore

Raises:

ValueError – If the resource is not of type allele_score. A resource that still declares the removed type np_score is 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_score resource.

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_score in the repository.

  • grr (GenomicResourceRepo or None, optional) – The repository that resolves resource_id. None, the default, builds the default repository with build_genomic_resource_repository().

Returns:

A new, closed score, as build_allele_score_from_resource builds it.

Return type:

AlleleScore

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:

  1. 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.

  2. 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 per ScoreAggregationQuery, 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 substitutions resource 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: max for numbers, list for 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.

SUBSTITUTIONS is the mode substitutions and ALLELES is the mode alleles. No read consults the mode. The allele score annotator uses it to route an allele.

static from_name(name: str) → Mode[source]

Return the mode that has the given configuration name.

Parameters:

name (str) – "substitutions" or "alleles".

Returns:

The mode of the name.

Return type:

AlleleScore.Mode

Raises:

ValueError – If the name is neither of the two.

class Multiplicity(*values)[source]

How many table rows one allele may have.

The resource declares it with the top-level key allele_multiplicity. ONE is the default. MANY means that several rows may hold one (chrom, pos, ref, alt), for example one row for each transcript.

alleles_mode() → bool[source]

Return whether the mode of the resource is alleles.

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 the reference and alternative columns. 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. None means the start of the chromosome.

  • pos_end (int or None) – The last position of the region. None means 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_BUDGET like two scores, so a batch holds at most budget // (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 the reference and alternative arrays. A key column that the table does not declare is an array of None.

Return type:

Generator[AlleleRecordArrays, None, None]

Raises:
  • TypeError – If the score does not serve the read for scores. Ask supports_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. None when no row holds the allele, or when score_filter rejects the row. The value itself may also be None when the row has no value for the score.

Return type:

ScoreValue or None

Raises:
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: the AlleleAggregate has a values tuple 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:

As get_allele_scores_for_allele_agg().

Return type:

AlleleAggregate or None

Raises:
  • ValueError – As get_allele_scores_for_allele_agg(). Also when score is None and the resource defines several scores.

  • ScoreFilterError – If score_filter was 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 when score is None and the resource defines several scores.

  • ScoreFilterError – If score_filter was 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. ref or alt is None when 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 when score is None and the resource defines several scores.

  • ScoreFilterError – If score_filter was 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 pos is not this allele. The read does not consult allele_score_mode.

The read answers one row, as the multiplicity of the resource promises. A resource that declares allele_multiplicity: many is refused, because one allele may hold several rows. On a one resource, several rows that hold the allele are a data error. The rows are counted before score_filter, so a filter that hides one of them does not hide the error. Until allele_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. None when no row holds the allele, or when score_filter rejects the row.

Return type:

tuple[ScoreValue, …] or None

Raises:

Notes

The call checks the request before it reads a row, and before the many refusal: 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 reaches pos is not folded. The read folds the rows that get_allele_scores_for_allele_rows() answers, with the queries, the aggregators and the AlleleAggregate of get_allele_scores_in_region_agg(). The read is allowed on both multiplicities and does not consult allele_score_mode. On a one resource 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 key chrom: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:

None when no row holds the allele. The check happens before the filter. When the filter rejects every row, the answer is an AlleleAggregate in which each aggregator answers for no rows: max gives None, list gives [] and count gives 0.

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_filter was 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 reaches pos is 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_filter was 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_filter keeps, 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 bare chrom:pos:ref:alt keys. See allele_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:

None when no row overlaps the region. The check happens before the filter. Otherwise an AlleleAggregate. When the filter rejects every row, each aggregator answers for an empty selection: max gives None and list gives []. 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 queries or allele_keys is unknown, if a query has no aggregator to resolve to, or if the contig is not in the resource.

  • ScoreFilterError – If score_filter was 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 AlleleEntry for 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 values parallel to scores. 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_filter was 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 GenomicScore schema plus the keys allele_score_mode, allele_multiplicity and merge_vcf_scores, and the reference, alternative and variant column 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().

substitutions_mode() → bool[source]

Return whether the mode of the resource is substitutions.

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 the reference and alternative columns. 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: file that names its key columns only in its data file answers False until the score is opened, and True after.

Parameters:

scores (list[str]) – The score ids that the caller wants to read.

Returns:

True if fetch_region_allele_arrays() accepts the scores. If the answer is False, read per record with fetch_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 None when the read was not asked for keys. See allele_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 None when the table has no reference column.

  • alt (str | None) – The alternative nucleotides of the row, as the table holds them. The value is None when 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 detail with a prefix: the resource id and, when the refusal concerns one allele, the allele spelled by allele_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 is None when 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:alt part when this or alt is None.

  • 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:G or 1:10:A:G:0.5,2.

Return type:

str