BeamModel
from BEAM import BeamModelA probability distribution over amino-acid or nucleotide sequences, built from their counts. See Building a model for a walk-through.
Constructor
Section titled “Constructor”BeamModel(sequences, *, abundances=None, alphabet="aa", order=None, weights=(0.5, 0.5), max_length=None, alpha=None, alpha_length=None, sparse=None, lengths=None)| Parameter | Meaning |
|---|---|
sequences | The training sequences. Empty strings, strings longer than max_length and strings with characters outside the alphabet are skipped and counted in n_skipped. |
abundances | How many cells (templates, reads) carry each sequence. Default: 1 each. Non-positive or non-finite values skip the sequence. |
alphabet | "aa" (the 20 amino acids, upper case) or "nt" (A C G T N, either case). Always named; never detected. |
order | How many neighbouring residues each expert looks at: 2 to 4 for aa, 0 to 9 for nt. Default 4 and 6. At order 0 each expert is one residue distribution per position. |
weights | : how much the start-anchored and end-anchored experts count in each residue’s factor , where and are the two experts’ probabilities of the residue. The default is their geometric mean. Keep them summing to 1; (1, 0) or (0, 1) uses one expert alone. |
max_length | Longest sequence represented: 1 to 255 for aa, 1 to 512 for nt. At a high order the limit is lower, because the tables hold max_length × radix**order rows against a 32-bit row index: nt at order 9 reaches 426, and a refusal names the limit for your own order. Default 27 for aa, 81 for nt. "data" takes the longest training sequence the alphabet accepts, at least 2 and at most that limit (not with from_sequence_file, from_parquet or builder, which read the data once). |
alpha, alpha_length | Strengths of the hierarchical prior. Default: chosen from the data. |
lengths | Which lengths the model produces: None for every length up to max_length (default), "observed" for the lengths in the data with exactly their observed frequencies, or a list of lengths. See Prepare only the lengths you use. |
sparse | Store only observed contexts (default). False stores every context: the same model, bit for bit, at gigabytes of memory for order 4. |
Building from files
Section titled “Building from files”| Method | Reads |
|---|---|
BeamModel.from_dataframe(data, sequence_column=None, abundance_column=None, **config) | A pandas DataFrame, an Arrow table or a dict of lists. |
BeamModel.from_sequence_file(path, sep="\t", sequence_column=0, abundance_column=1, has_header=False, **config) | A delimited text file, without loading it into memory. |
BeamModel.from_parquet(path, sequence_column=None, abundance_column=None, **config) | A parquet file, one batch at a time (needs pyarrow). |
BeamModel.builder(**config) | A Builder that accumulates counts batch by batch, for corpora of any size. |
BeamModel.from_file(path) | A model saved with save. |
from_dataframe and from_parquet read the column cdr3_aa when no sequence_column is
given (cdr3 for nucleotides), and count every row once when no abundance_column is given. To
compare with the reference model, name junction_aa explicitly: AIRR’s cdr3_aa leaves out the
conserved start and end residues.
A Builder takes batches with b.observe(sequences, abundances=None); b.build() returns the
model and closes the builder, and b.snapshot() returns the model so far and keeps it open.
Scoring
Section titled “Scoring”| Method | Returns |
|---|---|
pseq(seq_or_list, log=False) | Probability (or natural log) of one sequence or of each in a list. |
log_pseq(seq) | Natural log of one probability; -inf if the sequence cannot be represented. |
log_pseq_batch(seqs) | Log probabilities of a list, as a NumPy array; parallel where available. |
log_pseq_arrow(array) | Log probabilities of a pyarrow string column, read straight from its buffers; a null scores NaN. |
log_pseq_chunks(iterable, chunk_size=1_000_000) | Log probabilities of an iterable, yielded one array per chunk. |
log_pseq_file(path, sep="\t", column=0, has_header=False, out=None), log_pseq_parquet(path, column=None, out=None) | Every sequence of a delimited file or a parquet column (default cdr3_aa, cdr3 for nucleotides), in file order. out= fills a preallocated array or memory map. |
explain(seq) | For each residue, the log probability from each expert (forward, backward) and their weighted combination (combined = ·forward + ·backward), with log_length_prior and log_partition; together they rebuild log_pseq, which is also returned. Raises ValueError naming why a sequence cannot be scored. See Which residues drive a score. |
log_pseq_by_position(seq) | The score split per position; the sum is the score. |
log_pseq_by_position_batch(seqs) | The same for many sequences: an array with one row per sequence, nan after the end of a shorter one. |
log_pseq_ratio_by_position(other, seq_or_list) | Per position, this model’s term minus other’s; the sum is the difference of the two scores. |
log_pseq_region(seq, start, stop, *, given=None) | that a sequence of this length carries seq[start:stop] at those positions; with given=(a, b), among sequences that carry seq[a:b]. |
log_pseq_substitutions(seq) | The score of every single-residue change of seq: an array of (positions × residues), residues in the alphabet’s order. |
log_pseq_leave_one_out(seqs, *, abundances=None) | Each sequence’s score under the model without that sequence’s own counts; nan where nothing would be left. |
calibrate(*, bins=512), scale_score(seq_or_list, calibration) | A score comparable across lengths: of the share of same-length sequences at least as surprising, computed from the model’s own distribution of surprisal at each length. A score of 2 means the rarest 1% at any length. |
calibrate_against(source, *, bins=None, max_surprisal=None, bound=None) | The distribution of this model’s score among sequences drawn from source (same alphabet and max_length, and this model’s order or a lower one), as a calibration. calibration.pvalue(length, u, tail="lower") and scale_score(seq, calibration, tail="lower") read the share of source’s sequences that score at least as well; with bounds=True each returns (low, high), the two values the true answer lies between. calibration.is_fine_grained, .bins_per_residue and .spacing report whether the grid is fine enough for the model’s max_length. max_surprisal=cap keeps the grid up to cap nats and bound="upper" makes pvalue an upper bound on the lower tail; either returns a LowerTailCalibration, which holds the lower tail only and costs in proportion to the cells kept. |
lower_tail_against(source, length, scores, *, bins=None, max_surprisal=None) | An upper bound on the share of source’s sequences of length that score at least as well as each of scores (surprisals under this model): calibrate_against with bound="upper", capped at the largest score, for that one length. A float for one score, an array for several. |
seq in model | Whether seq has a non-zero probability. |
Two functions score several models at once: BEAM.log_pseq_matrix(models, seqs) returns an
array of (models × sequences) log probabilities, and
BEAM.log_pseq_by_position_matrix(models, seqs) an array of (models × sequences × positions).
See Scores across models, positions and regions.
Generating
Section titled “Generating”| Method | Returns |
|---|---|
sample(n, *, length=None, seed=None) | n sequences drawn in proportion to their probability. Without a seed the draw uses seed 0, so repeated calls return the same sequences; pass different seeds for independent draws. |
simulate(n, *, length=None, seed=None) | The same draws with their log probabilities (.sequences, .log_probs). |
top_k_sequences(k=20, *, length=None) | The k most probable sequences with their log probabilities. |
tempered(t) | A new model with , for : sharper for , flatter for . It scores, samples and computes like any model, but cannot be saved, copied or combined. |
Lengths
Section titled “Lengths”| Member | Returns |
|---|---|
length_distribution | {length: probability} over the lengths the model produces. |
length_pmf() | The same as an array indexed by length. |
log_length_prior(L) | , the log probability of length . |
log_partition(L) | , the normaliser of length (see How BEAM works). |
observed_lengths | Lengths the model can produce: every length up to max_length, since the length prior gives each some probability. |
Summaries of the whole distribution
Section titled “Summaries of the whole distribution”All computed directly over every sequence the model can produce, without simulation.
| Method | Returns |
|---|---|
entropy(*, base=math.e) | Shannon entropy of the sequence distribution, in nats; base=2 for bits. |
hill_number(q), hill_numbers(orders), diversity_profile() | Effective numbers of sequences (Hill numbers) at order q. |
hill_profile(orders) | Hill numbers at many orders at once, faster than hill_numbers. |
path_count(length=None) | Number of distinct sequences the model can produce. Every sequence up to max_length has some probability, so this is at length ( = 20 amino acids or 5 nucleotides), summed over lengths by default. For diversity, use Hill numbers. |
positional_marginals(length, *, clamp=None) | An array with one row per position and one column per residue: , the probability that position holds residue at length ; the basis of a sequence logo. clamp={position: residue} conditions on residues pinned at some positions. |
consensus(length) | The most probable residue at each position of a length, as a string. |
log_clamp_probability(length, clamp) | : the log probability that a length- sequence has the residues pinned by clamp. |
surprisal_stats() | Mean, variance, standard deviation, skewness and excess kurtosis of the surprisal over the model’s sequences. |
surprisal_range(), dynamic_range(*, base=10) | The smallest and largest surprisal of any sequence, and their span in orders of magnitude. |
log_evidence(*, alpha=None, alpha_length=None, parts=False) | Log probability of the model’s counts under its prior, at the model’s own strengths or at the ones given; parts=True returns the term of each prior level and of the length histogram. |
pseq_analysis() | The model’s probability spectrum: .atoms(bins) gives (probability, number of sequences) pairs, the input to publicness spectra. |
insights | Sequence logos; see Insights and logos. |
Combining and updating
Section titled “Combining and updating”| Method | Effect |
|---|---|
a.merged(b) | A new model with both models’ counts: one pooled repertoire. |
add(other), subtract(other) | Add or remove another model’s counts, in place. |
add_sequences(seqs, *, abundances=None), remove_sequences(seqs, *, abundances=None) | Add or remove raw sequences, in place. |
finalize() | Rebuilds the model after changes made with finalize=False, which add, subtract, add_sequences and remove_sequences accept to postpone the rebuild; the next call that needs the model also does it. |
coarsened(order) | A new model of a lower order from the same counts: the model built at that order from the same sequences. |
without(other, *, abundances=None) | A new model with other’s counts removed; other is a model or a list of sequences. |
with_prior(prior, kappa=100) | A new model updated towards prior’s probabilities; posterior(prior, kappa=100) does the same in place. |
copy() | An independent copy. |
Combined models need the same alphabet, order and max_length (ModelMismatch otherwise);
the result keeps the first model’s weights and prior settings. To mix probabilities rather
than pool counts, use Mixture; see
Merging counts or mixing models.
Saving, memory and introspection
Section titled “Saving, memory and introspection”| Member | Meaning |
|---|---|
save(path) | Writes counts and configuration; .beam is added when the path has no suffix. |
compact() | Drops the raw counts to save memory. The model still scores, samples and computes, but can no longer be saved, copied, combined or given new prior strengths. |
memory_bytes | Approximate memory of the model’s tables. |
config | The configuration it was built with, including the prior strengths chosen. |
alphabet, n_residues | "aa" or "nt", and its number of residues (20 or 5). |
n_observed (also len(model)), n_skipped | Sequence records accepted and rejected while building. |
total_weight (alias n_sequences) | Total abundance counted. |
metadata() | Everything the model records about itself, including when it was built. |
set_alpha(alpha=None, alpha_length=None) | Rebuilds the prior with new strengths (numbers, or "auto"); an argument left out keeps its setting. |