Scores across models, positions and regions
The question: I have a score. Which model gives the best one, where along the sequence does it come from, and how unusual is it?
Every call on this page returns the numbers the basic calls return (log_pseq,
log_pseq_by_position), arranged for a larger question and computed in one pass. All
logarithms are natural.
Many models at once
Section titled “Many models at once”BEAM.log_pseq_matrix(models, sequences) scores every sequence under every model. Row is
what models[i].log_pseq_batch(sequences) returns.
import numpy as npimport BEAMfrom BEAM import BeamModel# groups: three lists of related sequences; queries: five sequences to scoremodels = [BeamModel(g, order=2, max_length=20) for g in groups]
scores = BEAM.log_pseq_matrix(models, queries) # one row per model, one column per sequenceprint(scores.shape)print(np.round(scores, 1))print(scores.argmax(axis=0)) # the model each sequence scores highest under(3, 5)[[ -1.4 -38. -64.1 -8. -44.5] [-37.6 -1.4 -53.6 -31.1 -40.9] [-67.4 -44.6 -1.1 -67.4 -51.2]][0 1 2 0 1]The models may differ in alphabet, order and length; a sequence a model cannot read scores
-inf under it.
By position
Section titled “By position”log_pseq_by_position(seq) splits a score into one term per residue, and the terms add up to
the score. Two calls extend it:
log_pseq_by_position_batch(sequences)returns the terms of many sequences as one array, one row per sequence, filled withnanafter the end of a shorter sequence;log_pseq_ratio_by_position(other, seq)returns, position by position, this model’s term minus the other model’s: positive where this model explains the residue better.
import numpy as npimport BEAMfrom BEAM import BeamModelreference = BEAM.load_pretrained("human_tcrb_cdr3_aa_foundation")model = BeamModel(group, order=2, max_length=20) # group: 40 related sequencesqueries = ["CASSLGQGYEQYF", "CASSPGTGELFF", "CASSLGQGYEQ"]
rows = model.log_pseq_by_position_batch(queries) # (sequences, longest); nan past the endprint(rows.shape)print(np.round(rows[2], 2))print(np.allclose(np.nansum(rows, axis=1), model.log_pseq_batch(queries)))
# Where does `model` explain the first sequence better than the reference model does?ratio = model.log_pseq_ratio_by_position(reference, queries[0])print(np.round(ratio, 2))print(f"{ratio.sum():.3f} {model.log_pseq(queries[0]) - reference.log_pseq(queries[0]):.3f}")(3, 13)[-4.15 -3.93 -1.11 -1.12 -1.16 1.82 -1.87 -3.17 -1.85 -1.46 -6.03 nan nan]True[-0.75 -0.03 1.01 1.44 2.2 1.42 2.19 1.93 1.48 0.5 -0.17 0.38 -2.71]8.904 8.904The ratio’s terms add up to the difference of the two scores, .
BEAM.log_pseq_by_position_matrix(models, sequences) stacks the batch over several models, as
an array of shape (models, sequences, positions).
A stretch of a sequence
Section titled “A stretch of a sequence”log_pseq_region(seq, start, stop) is the probability that a sequence of the same length
carries the residues seq[start:stop] at those positions, whatever the rest of it is. With
given=(a, b) it is the same probability among the sequences that carry seq[a:b]:
Positions count from 0 and stop is excluded, as in a Python slice.
import BEAM
model = BEAM.load_pretrained("human_tcrb_cdr3_aa_foundation")s = "CASSLGQGYEQYF"
middle = model.log_pseq_region(s, 4, 9) # LGQGY at positions 4 to 8print(f"{middle:.3f}")
# The same stretch, among sequences that start with CASS:print(f"{model.log_pseq_region(s, 4, 9, given=(0, 4)):.3f}")
# The whole sequence is a stretch, and then the rest given that stretch.rest = model.log_pseq_region(s, 0, len(s), given=(4, 9))whole = model.log_pseq(s) - model.log_length_prior(len(s)) # ln P(s | length)print(f"{middle:.3f} + {rest:.3f} = {middle + rest:.3f} whole: {whole:.3f}")-7.819-7.463-7.819 + -0.736 = -8.555 whole: -8.555A whole sequence splits exactly into any stretch and the rest given that stretch:
,
where is log_pseq(s) - log_length_prior(len(s)).
Every single-residue change
Section titled “Every single-residue change”log_pseq_substitutions(seq) returns the score of every sequence that differs from seq at
one position: an array with one row per position and one column per residue, in the alphabet’s
order. The column of the residue already there holds the sequence’s own score.
import numpy as npimport BEAM
model = BEAM.load_pretrained("human_tcrb_cdr3_aa_foundation")residues = "ACDEFGHIKLMNPQRSTVWY" # the columns, in the alphabet's orders = "CASSLGQGYEQYF"
scores = model.log_pseq_substitutions(s) # (positions, residues)print(scores.shape)print(scores[4, residues.index("L")] == model.log_pseq(s)) # L is already at position 4
# The change that costs most, and the best residue at each position with the others fixed.i, a = np.unravel_index(scores.argmin(), scores.shape)print(f"{s[i]}{i}{residues[a]}: {scores[i, a] - model.log_pseq(s):.1f}")print("".join(residues[k] for k in scores.argmax(axis=1)))
print(model.consensus(13)) # the most probable residue at each position(13, 20)TrueY11M: -18.4CASSLGQAYEQYFCASSLGGGYEQYFconsensus(length) returns the most probable residue at each position of a length, as a
string: the highest entry of each row of positional_marginals(length).
Each member without itself
Section titled “Each member without itself”A sequence scores higher under a model that was built with it. log_pseq_leave_one_out
returns, for each sequence, its score under the model with that sequence’s own counts removed:
what model.without([s]).log_pseq(s) gives, for every member in one call.
import numpy as npfrom BEAM import BeamModelmodel = BeamModel(group, order=2, max_length=20) # group: 40 related sequences
inside = model.log_pseq_batch(group) # each member, scored by a model that saw itheld_out = model.log_pseq_leave_one_out(group) # ... and by the model without itprint(np.round(inside[:5], 2))print(np.round(held_out[:5], 2))print(held_out[0] == model.without([group[0]]).log_pseq(group[0]))[-4.92 -8.37 -4.92 -1.42 -4.98][ -7.98 -14.51 -7.98 -1.46 -8.04]TruePass abundances= to remove more than one copy of each. An entry is nan when removing the
sequence would leave the model empty.
One model’s scores under another model’s sequences
Section titled “One model’s scores under another model’s sequences”calibrate() gives the distribution of a model’s score among its own sequences.
calibrate_against(source) gives the distribution of the same score among sequences drawn from
another model, at every length both produce. The two models need the same alphabet and
max_length, and source may have the model’s order or a lower one. A lower-order source
is used as the distribution it is: an order-0 source is a per-position background, which
describes a class of sequences without remembering any one of them.
import BEAMfrom BEAM import BeamModelreference = BEAM.load_pretrained("human_tcrb_cdr3_aa_foundation")config = dict(order=2, max_length=20)model = BeamModel(group, **config) # 40 related sequencesbackground = BeamModel(reference.sample(20_000, seed=1), **config)
# The distribution of model's score for sequences drawn from background.null = model.calibrate_against(background)
for s in (group[0], "CASSLGQGYEQFF", "CASSPGTGELFFF"): u = -model.log_pseq(s) p = null.pvalue(len(s), u, tail="lower") # share of background sequences scoring this well print(f"{s:14} {p:9.2e} {model.scale_score(s, null, tail='lower'):5.2f}")
# The two ends of what the grid can say about that share, and how fine the grid is.fine = model.calibrate_against(background, bins=8192)u = -model.log_pseq(group[0])for name, cal in (("default", null), ("8192 bins", fine)): low, high = cal.pvalue(len(group[0]), u, tail="lower", bounds=True) print(f"{name:10} {cal.bins:5} bins of {cal.spacing:.3f} nats " f"fine: {cal.is_fine_grained} between {low:.2e} and {high:.2e}")CASSLAQGYEQYF 1.53e-04 3.81CASSLGQGYEQFF 6.55e-04 3.18CASSPGTGELFFF 3.96e-01 0.40default 512 bins of 0.213 nats fine: True between 9.64e-05 and 6.55e-048192 bins 8192 bins of 0.013 nats fine: True between 1.02e-04 and 1.89e-04With for drawn from source:
null.pvalue(length, u, tail="lower")is : the share ofsource’s sequences of that length that score at least as well under the model;null.pvalue(length, u)is , the share that score no better;scale_score(seq, null, tail="lower")is of the first, so 3 means one sequence in a thousand.
Both tails are computed over every sequence source can produce, without sampling, so a
probability of is as available as one of .
How sure a tail is
Section titled “How sure a tail is”The scores are placed on a grid of bins cells, each null.spacing nats wide, and a
sequence’s probability lands within length + 1 cells of its own score. bounds=True returns
what that allows: two numbers the true probability lies between.
null.pvalue(length, u, tail="lower", bounds=True)returns(low, high);scale_score(seq, null, tail="lower", bounds=True)returns the same bracket as scores,(low, high)withlowof the largest the probability could be.
To decide that a score is too good to be a draw from source, use the high probability
(the low score): if even the largest value the probability could take is below your
threshold, the decision holds whatever the grid.
More bins close the bracket. calibrate_against uses 16 bins for every residue of
max_length by default, and at least 512; calibrate() uses 512. Every calibration reports
its own grid:
| Member | Meaning |
|---|---|
null.bins, null.spacing | Number of cells, and the width of one in nats. |
null.bins_per_residue | bins / max_length. |
null.is_fine_grained | Whether the grid has at least 16 bins per residue. When False, a deep tail read from it is set by the grid: use more bins, or read it with bounds=True. |
null.resolution(length) | (length + 1) * spacing: how far, in nats, a sequence’s probability can sit from its own score. |
Reading only the lower tail
Section titled “Reading only the lower tail”When the one question is how often source scores at least as well as a given score, two
keywords of calibrate_against answer it with a fraction of the work, and
lower_tail_against asks it in one call.
import BEAMfrom BEAM import BeamModelreference = BEAM.load_pretrained("human_tcrb_cdr3_aa_foundation")config = dict(order=2, max_length=20)model = BeamModel(group, **config) # 40 related sequencesbackground = BeamModel(reference.sample(20_000, seed=1), **config)
candidates = [group[0], "CASSLGQGYEQFF", "CASSPGTGELFFF"] # 13 residues eachu = -model.log_pseq_batch(candidates)
# One call: at most this share of background sequences scores as well as each candidate.print(u) # the scores, in natsprint(model.lower_tail_against(background, 13, u, bins=4096))
# The same null kept for many reads: the grid up to a cap, every step rounded down.null = model.calibrate_against(background, bins=4096, max_surprisal=45.0, bound="upper")print(null)print(null.pvalue(13, u)) # an upper bound on P(U <= u)low, high = null.pvalue(13, u, bounds=True) # the true value lies between theseprint(low, high)print(null.pvalue(13, 60.0)) # above the cap[ 4.921 8.039 40.783][1.893e-04 1.094e-03 4.315e-01]LowerTailCalibration(lengths=20, bins=1777 of 4096, max_surprisal=45, bound='upper')[1.893e-04 1.094e-03 4.315e-01][1.018e-04 1.894e-04 3.265e-01] [1.893e-04 1.094e-03 4.315e-01]1.0max_surprisal=capkeeps the grid up tocapnats. A read at or below the cap is the read from the full calibration at the samebins, and the cost grows with the cap instead of with the whole grid.bound="upper"rounds every step of a sequence’s score down to the grid.pvaluethen returns an upper bound on : the true probability is at most that, and it lies withinlength + 1cells of it, half the width of the bracket above. It is the number to compare with a threshold directly.model.lower_tail_against(source, length, scores, bins=...)is both at once for one length, with the cap set to the largest score given, and returns the bound for each score.
With either keyword the result is a LowerTailCalibration. It is read with pvalue, scale
and scale_score(seq, null, tail="lower") like any calibration, the lower tail being its
default, and it reports null.max_surprisal, null.bound, and null.kept_bins of
null.bins. Above the cap it returns what is known there:
| Read above the cap | Returns |
|---|---|
pvalue(..., bounds=True) | (low at the cap, 1.0) |
pvalue(...) with bound="upper" | 1.0 |
pvalue(...) without bound | nan |
Cost is proportional to the number of cells kept, so choose the cap from the scores you read
and bins from how close the bound has to be: null.pvalue(length, u, bounds=True) shows
both ends at any setting.
Evidence of a model
Section titled “Evidence of a model”log_evidence() is the log probability of a model’s counts under its
prior: the quantity
BEAM maximises when it chooses the prior strengths alpha. It can be evaluated at any
strengths, so that different models are compared on equal terms.
import numpy as npfrom BEAM import BeamModelconfig = dict(order=2, max_length=20)a, b, c = (BeamModel(seqs, **config) for seqs in (first, second, other))
print(f"{a.log_evidence():.2f}") # at the strengths the model choseparts = a.log_evidence(alpha=1.0, alpha_length=1.0, parts=True)print(np.round(parts["levels"], 2), round(parts["length"], 2), round(parts["total"], 2))
# Pooling two models: what the pooled counts gain over the two apart, at the same strengths.def gain(x, y, **strengths): return (x.merged(y).log_evidence(**strengths) - x.log_evidence(**strengths) - y.log_evidence(**strengths))
print(f"{gain(a, b, alpha=1.0, alpha_length=1.0):9.1f}") # two samples of one groupprint(f"{gain(a, c, alpha=1.0, alpha_length=1.0):9.1f}") # two different groups-1129.17[-553.31 -417.3 -384. ] -6.2 -1360.81 -115.4 -1205.4parts=True returns the terms: one per level of the prior (levels[k] covers the counts
that keep neighbouring residues, for both experts and every position), the term of the
length histogram (length), and their sum (total). Pooling two models that describe the same
sequences gains far more than pooling two that do not, which makes the gain a way to rank
candidate pools.