Skip to content

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.

BEAM.log_pseq_matrix(models, sequences) scores every sequence under every model. Row ii is what models[i].log_pseq_batch(sequences) returns.

matrix.py
import numpy as np
import BEAM
from BEAM import BeamModel
# groups: three lists of related sequences; queries: five sequences to score
models = [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 sequence
print(scores.shape)
print(np.round(scores, 1))
print(scores.argmax(axis=0)) # the model each sequence scores highest under
Output
(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]
Full program, including the set-up hidden here

The models may differ in alphabet, order and length; a sequence a model cannot read scores -inf under it.

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 with nan after 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.
by_position.py
import numpy as np
import BEAM
from BEAM import BeamModel
reference = BEAM.load_pretrained("human_tcrb_cdr3_aa_foundation")
model = BeamModel(group, order=2, max_length=20) # group: 40 related sequences
queries = ["CASSLGQGYEQYF", "CASSPGTGELFF", "CASSLGQGYEQ"]
rows = model.log_pseq_by_position_batch(queries) # (sequences, longest); nan past the end
print(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}")
Output
(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.904
Full program, including the set-up hidden here

The ratio’s terms add up to the difference of the two scores, ln⁡PA(s)−ln⁡PB(s)\ln P_A(s) - \ln P_B(s). BEAM.log_pseq_by_position_matrix(models, sequences) stacks the batch over several models, as an array of shape (models, sequences, positions).

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]:

ln⁡P(sregion∣L)andln⁡P(sregion∣sgiven, L)\ln P(s_{\text{region}} \mid L) \qquad\text{and}\qquad \ln P(s_{\text{region}} \mid s_{\text{given}},\, L)

Positions count from 0 and stop is excluded, as in a Python slice.

region.py
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 8
print(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}")
Output
-7.819
-7.463
-7.819 + -0.736 = -8.555 whole: -8.555
Full program, including the set-up hidden here

A whole sequence splits exactly into any stretch and the rest given that stretch: ln⁡P(s∣L)=ln⁡P(region∣L)+ln⁡P(rest∣region,L)\ln P(s \mid L) = \ln P(\text{region} \mid L) + \ln P(\text{rest} \mid \text{region}, L), where ln⁡P(s∣L)\ln P(s \mid L) is log_pseq(s) - log_length_prior(len(s)).

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.

substitutions.py
import numpy as np
import BEAM
model = BEAM.load_pretrained("human_tcrb_cdr3_aa_foundation")
residues = "ACDEFGHIKLMNPQRSTVWY" # the columns, in the alphabet's order
s = "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
Output
(13, 20)
True
Y11M: -18.4
CASSLGQAYEQYF
CASSLGGGYEQYF
Full program, including the set-up hidden here

consensus(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).

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.

leave_one_out.py
import numpy as np
from BEAM import BeamModel
model = 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 it
held_out = model.log_pseq_leave_one_out(group) # ... and by the model without it
print(np.round(inside[:5], 2))
print(np.round(held_out[:5], 2))
print(held_out[0] == model.without([group[0]]).log_pseq(group[0]))
Output
[-4.92 -8.37 -4.92 -1.42 -4.98]
[ -7.98 -14.51 -7.98 -1.46 -8.04]
True
Full program, including the set-up hidden here

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

cross_null.py
import BEAM
from BEAM import BeamModel
reference = BEAM.load_pretrained("human_tcrb_cdr3_aa_foundation")
config = dict(order=2, max_length=20)
model = BeamModel(group, **config) # 40 related sequences
background = 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}")
Output
CASSLAQGYEQYF 1.53e-04 3.81
CASSLGQGYEQFF 6.55e-04 3.18
CASSPGTGELFFF 3.96e-01 0.40
default 512 bins of 0.213 nats fine: True between 9.64e-05 and 6.55e-04
8192 bins 8192 bins of 0.013 nats fine: True between 1.02e-04 and 1.89e-04
Full program, including the set-up hidden here

With U=−ln⁡Pmodel(s)U = -\ln P_{\text{model}}(s) for ss drawn from source:

  • null.pvalue(length, u, tail="lower") is P(U≤u)P(U \le u): the share of source’s sequences of that length that score at least as well under the model;
  • null.pvalue(length, u) is P(U≥u)P(U \ge u), the share that score no better;
  • scale_score(seq, null, tail="lower") is −log⁡10-\log_{10} 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 10−3010^{-30} is as available as one of 10−210^{-2}.

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) with low =−log⁡10= -\log_{10} of 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:

MemberMeaning
null.bins, null.spacingNumber of cells, and the width of one in nats.
null.bins_per_residuebins / max_length.
null.is_fine_grainedWhether 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.

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.

lower_tail.py
import BEAM
from BEAM import BeamModel
reference = BEAM.load_pretrained("human_tcrb_cdr3_aa_foundation")
config = dict(order=2, max_length=20)
model = BeamModel(group, **config) # 40 related sequences
background = BeamModel(reference.sample(20_000, seed=1), **config)
candidates = [group[0], "CASSLGQGYEQFF", "CASSPGTGELFFF"] # 13 residues each
u = -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 nats
print(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 these
print(low, high)
print(null.pvalue(13, 60.0)) # above the cap
Output
[ 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.0
Full program, including the set-up hidden here
  • max_surprisal=cap keeps the grid up to cap nats. A read at or below the cap is the read from the full calibration at the same bins, 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. pvalue then returns an upper bound on P(U≤u)P(U \le u): the true probability is at most that, and it lies within length + 1 cells 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 capReturns
pvalue(..., bounds=True)(low at the cap, 1.0)
pvalue(...) with bound="upper"1.0
pvalue(...) without boundnan

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.

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.

evidence.py
import numpy as np
from BEAM import BeamModel
config = 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 chose
parts = 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 group
print(f"{gain(a, c, alpha=1.0, alpha_length=1.0):9.1f}") # two different groups
Output
-1129.17
[-553.31 -417.3 -384. ] -6.2 -1360.81
-115.4
-1205.4
Full program, including the set-up hidden here

parts=True returns the terms: one per level of the prior (levels[k] covers the counts that keep kk 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.