Changing a model after it is built
The question: my model exists and my data moved on. How do I change the model without building it again from every sequence?
A model is its counts plus the tables built from them. Every method on this page changes the counts and rebuilds the tables, and gives the model you would get by building from scratch with the same sequences.
Add or remove sequences
Section titled “Add or remove sequences”add_sequences and remove_sequences take raw sequences (and, optionally, their abundances)
and change the model in place. Nothing else is read again.
from BEAM import BeamModel# group: 40 related CDR3 sequencesmodel = BeamModel(group[:30], order=2, max_length=20)print(model.n_observed, f"{model.log_pseq(group[35]):.3f}")
model.add_sequences(group[30:]) # in place: counted, then rebuilt onceprint(model.n_observed, f"{model.log_pseq(group[35]):.3f}")
model.remove_sequences(group[30:]) # and taken out againprint(model.n_observed, f"{model.log_pseq(group[35]):.3f}")
fresh = BeamModel(group[:30], order=2, max_length=20)print(model.log_pseq(group[35]) == fresh.log_pseq(group[35]))30 -14.50140 -8.51330 -14.501TrueAdding ten sequences and removing the same ten returns the model it was, to the last digit.
| Call | Effect |
|---|---|
model.add_sequences(sequences, abundances=None) | Counts the sequences into the model and rebuilds it. |
model.remove_sequences(sequences, abundances=None) | Takes their counts out and rebuilds it. Removing everything is refused. |
Many changes, one rebuild
Section titled “Many changes, one rebuild”Rebuilding is the costly step. With finalize=False a change stops at the counts, and the
model is rebuilt once: by model.finalize(), or by the next call that needs it (a score, a
sample, a save).
from BEAM import BeamModelmodel = BeamModel(group[:10], order=2, max_length=20)for s in group[10:]: model.add_sequences([s], finalize=False) # counts only: nothing is rebuilt yetmodel.finalize() # one rebuild for all thirty
at_once = BeamModel(group, order=2, max_length=20)print(model.n_observed, model.log_pseq(group[0]) == at_once.log_pseq(group[0]))40 Truefinalize=False is accepted by add_sequences, remove_sequences, add and subtract. The
result is the model that rebuilding after every change gives.
Prepare only the lengths you use
Section titled “Prepare only the lengths you use”By default a model can produce every length up to max_length, and building it computes a
normaliser for each of them. lengths= limits the model to the lengths you need, which
makes building faster in proportion.
from BEAM import BeamModel# group: 40 sequences, all 13 residues longconfig = dict(order=2, max_length=20)models = { "every length": BeamModel(group, **config), "observed": BeamModel(group, lengths="observed", **config), "listed": BeamModel(group, lengths=[12, 13, 14], **config),}for name, m in models.items(): print(f"{name:13} {len(m.observed_lengths):2} lengths " f"13 residues: {m.log_pseq('CASSLGQGYEQYF'):8.3f} " f"11 residues: {m.log_pseq('CASSLGQGYEQ'):8.3f}")every length 20 lengths 13 residues: -1.417 11 residues: -24.038observed 1 lengths 13 residues: -1.415 11 residues: -inflisted 3 lengths 13 residues: -1.417 11 residues: -inflengths= | Lengths the model produces | Length probabilities |
|---|---|---|
None (default) | every length from 1 to max_length | observed frequencies, smoothed over all of them |
"observed" | the lengths present in the data | exactly the observed frequencies |
a list, such as [12, 13, 14] | exactly the lengths listed | observed frequencies, smoothed over the list |
A sequence of a length the model does not produce has probability 0 (log_pseq returns
-inf), and a listed model refuses training sequences of any other length.
A lower order from the same counts
Section titled “A lower order from the same counts”The order of a model is how many neighbouring residues each expert reads. coarsened(order)
returns a new model of a lower order from the counts the model already holds: the counts are
summed over the neighbours the lower order no longer reads.
import numpy as npfrom BEAM import BeamModel# reads: 60 related nucleotide sequences, 30 bases eachmodel = BeamModel(reads, alphabet="nt", order=3, max_length=30)
for order in (2, 1, 0): lower = model.coarsened(order) # from the counts: nothing is re-read direct = BeamModel(reads, alphabet="nt", order=order, max_length=30) print(order, f"{lower.log_pseq(reads[0]):8.3f}", lower.log_pseq(reads[0]) == direct.log_pseq(reads[0]))
# Order 0 reads no neighbours: one residue distribution per position.independent = model.coarsened(0)print(independent.consensus(30))print(np.round(independent.positional_marginals(30)[0], 3)) # position 0: A C G T N2 -12.397 True1 -12.397 True0 -12.396 TrueTGTGCCAGCAGCTTAGGACAGGGATACGAG[0.018 0.018 0.051 0.91 0.002]Each coarsened model equals the model built directly at that order from the same sequences.
Nucleotide models go down to order 1 and order 0. At order 0 no neighbour is read: each expert holds one residue distribution per position, and the model is their normalised product,
- is the smoothed frequency of residue at position counted from the start, and the same counted from the end;
- and are the two experts’ weights, each by default;
- is the normaliser of length .
Order 0 and order 1 can also be built directly: BeamModel(sequences, alphabet="nt", order=0).
Amino-acid models start at order 2.