Position scores
Position score resources associate values with genomic positions. A record can describe a single position or a genomic interval, and the values depend only on the genomic location rather than on a particular allele. Examples include conservation scores such as phastCons100way and phyloP100way, GC content, and recombination rates. These resources can be stored in tabix-indexed files, bigWig files, or in-memory tables. Their configuration is described in the Position scores section of the GRR documentation.
GAIn provides the PositionScore Python class for retrieving and processing these values. PositionScore inherits the functionality described in Genomic scores and adds methods for querying individual positions, intervals, and bins.
Accessing a position score
A PositionScore object can be built from a resource ID and a repository using build_position_score_from_resource_id():
import gain.grr as grr
repo = grr.build_genomic_resource_repository()
score = grr.build_position_score_from_resource_id(
"hg38/scores/phastCons100way", repo
)
If you already have a GenomicResource object, use build_position_score_from_resource() instead:
resource = repo.get_resource("hg38/scores/phastCons100way")
score = grr.build_position_score_from_resource(resource)
Both functions are available through gain.grr. The generic build_score_from_resource_id() function also returns a PositionScore object when the specified resource is a position score.
Opening and closing a position score
Position scores are initially closed and must be opened before reading their values. As with other genomic scores, call open() explicitly and use a with block to ensure that the object is closed afterward:
with grr.build_position_score_from_resource_id(
"hg38/scores/phastCons100way", repo
).open() as score:
print(score.get_scores_at_position("chr21", 5_030_000))
The opening and closing behavior is described in more detail in Genomic scores.
Retrieving position scores
Position scores provide several methods for retrieving values at individual genomic positions or across intervals. Each query specifies a chromosome and either a position (pos) or interval boundaries (start and end).
Most operations have both plural and singular forms. Plural methods, named get_scores_..., retrieve multiple scores. For position and region queries, they accept a list of score IDs and return tuples with values in the corresponding order. If the list is omitted, they retrieve all scores defined by the resource. Singular methods, named get_score_..., retrieve one specified score and return individual values rather than tuples.
Aggregation and binning methods follow a similar distinction, but their plural forms accept a list of aggregation queries, each specifying a score and an aggregator. Their singular forms take a single score and aggregator.
Query |
Methods |
Result |
|---|---|---|
Single position |
Score values at one position |
|
Positions across a region |
Values for each position in the region |
|
Aggregated region |
One aggregated value per query |
|
Binned region |
Aggregated values for each bin |
|
Raw records |
Records at their original genomic extents |
For example, get_scores_at_position() returns a tuple containing the requested score values at a single genomic position, while get_scores_in_region() yields one tuple for each position in an interval:
with score.open() as opened_score:
print(opened_score.get_scores_at_position("chr21", 5_030_000))
for values in opened_score.get_scores_in_region(
"chr21", 5_030_000, 5_030_010
):
print(values)
Use the corresponding singular methods, get_score_at_position() and get_score_in_region(), when you need only one score. If a score has no value at a position, the result contains None for that score. This distinguishes positions without data from positions whose score is genuinely zero.
The raw-record methods in the table are inherited from GenomicScore. The shared interfaces for filtering, histograms, chromosome information, and reading data arrays are documented in Genomic scores. Aggregation and binning are described in the following subsections.
Aggregating scores across regions
When you need one summary value for a genomic interval rather than a value at each position, use get_score_in_region_agg() for a single score or get_scores_in_region_agg() for multiple aggregation queries.
An aggregator determines how values are combined across a region. Each score can specify a default aggregator in its resource configuration. If none is specified, GAIn uses the fallback for that value type defined in DEFAULT_AGGREGATORS. For multiple queries, the returned values follow the order of the queries, including when the same score is requested with different aggregators.
Retrieving scores in bins
get_score_in_bins() and get_scores_in_bins() aggregate scores within a series of fixed-width bins across a genomic region. Instead of producing a single result for the entire region, they produce a summary for each bin.
This is useful for displaying position scores at different genomic resolutions, such as in a genome-browser-style plot. As with region aggregation, the singular method takes one score and aggregator, while the plural method accepts multiple aggregation queries.
API
The class below is defined in the module
gain.genomic_resources.genomic_scores.position and is imported from
gain.genomic_resources.genomic_scores. PositionScore is also exported
by gain.grr, as grr.PositionScore.
The builders build_position_score_from_resource_id and
build_position_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_position_score_from_resource_id
and grr.build_position_score_from_resource.
|
Build a position score from a resource. |
|
Build a position score from the id of a resource. |
|
Position-based genomic score resource. |
Return the configuration schema of a position score. |
|
|
Return the value of one score at one position. |
|
Yield the aggregated value of one score for each bin of a region. |
|
Yield the value of one score at each position of a region. |
|
Reduce a region to one value for one score. |
|
Return the values of the scores at one position. |
|
Yield the aggregated values of each bin of a region. |
|
Yield the values of the scores at each position of a region. |
Reduce a region to one value for each query. |
|
Resolve each query to a score id, an aggregator name and a value. |
Inherited from GenomicScore, which Genomic scores describes:
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_position_score_from_resource(resource: GenomicResource) PositionScore[source]
Build a position score from a resource.
The score is closed. Call
open()before the first read. Each call returns a new score, so the caller owns it and closing it affects no other score.- Parameters:
resource (GenomicResource) – A resource of type
position_score.- Returns:
A closed position score for the resource.
- Return type:
- Raises:
ValueError – If the resource is not of type
position_score.
- build_position_score_from_resource_id(resource_id: str, grr: GenomicResourceRepo | None = None) PositionScore[source]
Build a position score from the id of a resource.
The score is closed. Call
open()before the first read. Each call returns a new score, so the caller owns it and closing it affects no other score.- Parameters:
resource_id (str) – The id of a resource of type
position_scorein the repository.grr (GenomicResourceRepo | None) – The repository that resolves
resource_id. When it isNone, the function builds the default repository withbuild_genomic_resource_repository().
- Returns:
A closed position score for the resource.
- Return type:
- Raises:
FileNotFoundError – If the repository has no resource with this id.
ValueError – If the resource is not of type
position_score.
- class PositionScore(resource: GenomicResource)[source]
Position-based genomic score resource.
A position score gives one or more scores for a genomic position or a run of positions. Unlike an allele score, it ignores the reference and alternative alleles. The data lives in a tabix-indexed file, a bigWig file or an in-memory table.
Typical resources are:
conservation scores, such as
phastConsandphyloPmappability scores
GC content
recombination rates
any metric that depends only on the genomic position
A score is built closed. Call
open()before the first read.Examples
import gain.grr as grr repo = grr.build_genomic_resource_repository() score = grr.build_position_score_from_resource_id( "hg38/scores/phastCons100way", repo) with score.open() as score: values = score.get_scores_at_position("chr1", 12345) for begin, end, row in score.fetch_region_segments_scores( "chr1", 10000, 20000): print(f"{begin}-{end}: {row}")
- Variables:
resource (GenomicResource) – The underlying genomic resource.
resource_id (str) – The identifier of the resource.
config (dict) – The validated configuration of the score.
score_definitions (dict[str, GenomicScoreDef]) – The definition of each score, by score id.
HISTOGRAM_COUNT_UNIT (str) – The unit of the histogram counts. For a position score it is
"base pairs".DEFAULT_AGGREGATORS (dict[str, str | None]) – The aggregator name that a region read uses for each value type, when the configuration of the score names none. A value of
Nonemeans that the type takes no default.
- HISTOGRAM_COUNT_UNIT: ClassVar[str] = 'base pairs'
The noun for what a histogram’s
ncounts – the weighting the statistics scan gives each record of this family: base pairs for a position score (record_weight), alleles, fragments, genes. Every concrete family states its own; the info pages read it.
- static get_schema() dict[str, Any][source]
Return the configuration schema of a position score.
The schema is the one of
GenomicScore, with anaggregatorkey added to the definition of each score.- Returns:
A new Cerberus schema dictionary, which the caller may modify.
- Return type:
dict[str, Any]
- get_score_at_position(chrom: str, pos: int, score: str | None = None) str | int | float | bool | None[source]
Return the value of one score at one position.
This is the singular form of
get_scores_at_position().- Parameters:
chrom (str) – The chromosome name.
pos (int) – The 1-based position.
score (str | None) – The id of the score.
Noneis accepted only when the resource defines exactly one score.
- Returns:
The value of the score.
Nonemeans that no record covers the position, or that the record has no value for the score.- Return type:
ScoreValue | None
- Raises:
ValueError – If the score is closed, the chromosome is unknown, the score id is unknown, or
scoreisNoneand the resource defines more than one score.
- get_score_in_bins(chrom: str, start: int, end: int, bin_size: int, score: str | None = None, aggregator: str | None = None, none_value_replacement: str | int | float | bool | None = None) Generator[tuple[int, int, str | int | float | bool | None], None, None][source]
Yield the aggregated value of one score for each bin of a region.
This is the singular form of
get_scores_in_bins().- Parameters:
chrom (str) – The chromosome name.
start (int) – The first 1-based position of the region.
end (int) – The last 1-based position of the region.
bin_size (int) – The width of a bin in positions. It must be at least 1.
score (str | None) – The id of the score.
Noneis accepted only when the resource defines exactly one score.aggregator (str | None) – The name of the aggregator.
Noneselects the aggregator that the configuration of the score names, or the default one for its value type.none_value_replacement (ScoreValue | None) – The value that stands for an uncovered position.
Nonemeans that an uncovered position is skipped by the aggregator.
- Yields:
tuple[int, int, ScoreValue] – The first position, the last position and the aggregated value of a bin, in position order. The value is
Nonewhen the aggregator has no value to report for the bin.- Raises:
ValueError – If the score is closed, the region is not valid,
bin_sizeis less than 1, the score id is unknown, no aggregator can be chosen, ornone_value_replacementdoes not match the value type.
- get_score_in_region(chrom: str, start: int, end: int, score: str | None = None) Generator[str | int | float | bool | None, None, None][source]
Yield the value of one score at each position of a region.
This is the singular form of
get_scores_in_region().- Parameters:
chrom (str) – The chromosome name.
start (int) – The first 1-based position of the region.
end (int) – The last 1-based position of the region.
score (str | None) – The id of the score.
Noneis accepted only when the resource defines exactly one score.
- Yields:
ScoreValue | None – One value for each position, in position order. A
Nonevalue means that no record covers the position, or that the record has no value for the score.- Raises:
ValueError – If the score is closed, the region is not valid, the chromosome is unknown, or the score id is unknown. The function raises before the first value, not during the iteration.
- get_score_in_region_agg(chrom: str, start: int, end: int, score: str | None = None, aggregator: str | None = None, none_value_replacement: str | int | float | bool | None = None) str | int | float | bool | None[source]
Reduce a region to one value for one score.
This is the singular form of
get_scores_in_region_agg().- Parameters:
chrom (str) – The chromosome name.
start (int) – The first 1-based position of the region.
end (int) – The last 1-based position of the region.
score (str | None) – The id of the score.
Noneis accepted only when the resource defines exactly one score.aggregator (str | None) – The name of the aggregator.
Noneselects the aggregator that the configuration of the score names, or the default one for its value type.none_value_replacement (ScoreValue | None) – The value that stands for an uncovered position.
Nonemeans that an uncovered position is skipped by the aggregator.
- Returns:
The aggregated value. It is
Nonewhen the aggregator has no value to report, for example when no position of the region has a value.- Return type:
ScoreValue
- Raises:
ValueError – If the score is closed, the region is not valid, the score id is unknown, no aggregator can be chosen, or
none_value_replacementdoes not match the value type.
- get_scores_at_position(chrom: str, pos: int, scores: Sequence[str] | None = None) tuple[str | int | float | bool | None, ...][source]
Return the values of the scores at one position.
- Parameters:
chrom (str) – The chromosome name.
pos (int) – The 1-based position.
scores (Sequence[str] | None) – The ids of the scores.
Noneasks for every score that the resource defines, in definition order.
- Returns:
One value for each requested score, in the order of
scores. ANonevalue means that no record covers the position, or that the record has no value for that score. The tuple is empty whenscoresis an empty sequence.- Return type:
tuple[ScoreValue | None, …]
- Raises:
ValueError – If the score is closed, the chromosome is unknown, or a score id is unknown.
- get_scores_in_bins(chrom: str, start: int, end: int, bin_size: int, queries: Sequence[PositionScoreAggregationQuery]) Generator[tuple[int, int, tuple[str | int | float | bool | None, ...]], None, None][source]
Yield the aggregated values of each bin of a region.
The bins follow the global grid that starts at position 1, so the results of adjacent regions tile and are comparable across calls. The first and the last bin are clipped to the region. The function emits every bin of the region, also a bin that no record touches.
- Parameters:
chrom (str) – The chromosome name.
start (int) – The first 1-based position of the region.
end (int) – The last 1-based position of the region.
bin_size (int) – The width of a bin in positions. It must be at least 1.
queries (Sequence[PositionScoreAggregationQuery]) – The queries. Each names a score, an aggregator and a replacement value for the uncovered positions.
- Yields:
tuple[int, int, tuple[ScoreValue, …]] – The first position, the last position and one aggregated value for each query of a bin, in position order. A value is
Nonewhen the aggregator has no value to report.- Raises:
ValueError – If the score is closed, the region is not valid,
bin_sizeis less than 1, or a query is not valid (seeresolve_aggregation_queries()).
Notes
A chromosome that the resource never mentions is not an error. The function emits every bin of it, as for a region that no record covers.
- get_scores_in_region(chrom: str, start: int, end: int, scores: Sequence[str] | None = None) Generator[tuple[str | int | float | bool | None, ...], None, None][source]
Yield the values of the scores at each position of a region.
- Parameters:
chrom (str) – The chromosome name.
start (int) – The first 1-based position of the region.
end (int) – The last 1-based position of the region.
scores (Sequence[str] | None) – The ids of the scores.
Noneasks for every score that the resource defines, in definition order.
- Yields:
tuple[ScoreValue | None, …] – Exactly
end - start + 1tuples, in position order. A tuple has one value for each requested score. ANonevalue means that no record covers the position, or that the record has no value for that score.- Raises:
ValueError – If the score is closed, the region is not valid, the chromosome is unknown, or a score id is unknown. The function raises before the first tuple, not during the iteration.
- get_scores_in_region_agg(chrom: str, start: int, end: int, queries: Sequence[PositionScoreAggregationQuery]) tuple[str | int | float | bool | None, ...][source]
Reduce a region to one value for each query.
Each position of the region counts once. A record counts once for each position of the region that it covers.
- Parameters:
chrom (str) – The chromosome name.
start (int) – The first 1-based position of the region.
end (int) – The last 1-based position of the region.
queries (Sequence[PositionScoreAggregationQuery]) – The queries. Each names a score, an aggregator and a replacement value for the uncovered positions.
- Returns:
One value for each query, in the order of
queries. A value isNonewhen the aggregator has no value to report. The tuple is empty whenqueriesis empty.- Return type:
tuple[ScoreValue, …]
- Raises:
ValueError – If the score is closed, the region is not valid, or a query is not valid (see
resolve_aggregation_queries()).
Notes
A chromosome that the resource never mentions is not an error. It answers as a region that no record covers.
- resolve_aggregation_queries(queries: Sequence[PositionScoreAggregationQuery]) list[tuple[str, str, str | int | float | bool | None]][source]
Resolve each query to a score id, an aggregator name and a value.
Use it to find out whether a query is answerable without reading. The position score annotator calls it once when the pipeline loads.
- Parameters:
queries (Sequence[PositionScoreAggregationQuery]) – The queries. Each names a score, an aggregator, and a replacement value for the uncovered positions.
- Returns:
One tuple for each query, in the order of
queries: the id of the score, the name of the aggregator, and thenone_value_replacementof the query. The list is empty whenqueriesis empty.- Return type:
list[tuple[str, str, ScoreValue]]
- Raises:
ValueError – If a score id is unknown, a
none_value_replacementhas a type that the score cannot take, or a query names no aggregator and the value type of the score has no default one.