Skip to content

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_sequences and remove_sequences take raw sequences (and, optionally, their abundances) and change the model in place. Nothing else is read again.

add_remove.py
from BEAM import BeamModel
# group: 40 related CDR3 sequences
model = 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 once
print(model.n_observed, f"{model.log_pseq(group[35]):.3f}")
model.remove_sequences(group[30:]) # and taken out again
print(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]))
Output
30 -14.501
40 -8.513
30 -14.501
True
Full program, including the set-up hidden here

Adding ten sequences and removing the same ten returns the model it was, to the last digit.

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

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

deferred.py
from BEAM import BeamModel
model = BeamModel(group[:10], order=2, max_length=20)
for s in group[10:]:
model.add_sequences([s], finalize=False) # counts only: nothing is rebuilt yet
model.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]))
Output
40 True
Full program, including the set-up hidden here

finalize=False is accepted by add_sequences, remove_sequences, add and subtract. The result is the model that rebuilding after every change gives.

By default a model can produce every length up to max_length, and building it computes a normaliser Z(L)Z(L) for each of them. lengths= limits the model to the lengths you need, which makes building faster in proportion.

lengths.py
from BEAM import BeamModel
# group: 40 sequences, all 13 residues long
config = 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}")
Output
every length 20 lengths 13 residues: -1.417 11 residues: -24.038
observed 1 lengths 13 residues: -1.415 11 residues: -inf
listed 3 lengths 13 residues: -1.417 11 residues: -inf
Full program, including the set-up hidden here
lengths=Lengths the model producesLength probabilities π(L)\pi(L)
None (default)every length from 1 to max_lengthobserved frequencies, smoothed over all of them
"observed"the lengths present in the dataexactly the observed frequencies
a list, such as [12, 13, 14]exactly the lengths listedobserved 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.

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.

coarsen.py
import numpy as np
from BEAM import BeamModel
# reads: 60 related nucleotide sequences, 30 bases each
model = 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 N
Output
2 -12.397 True
1 -12.397 True
0 -12.396 True
TGTGCCAGCAGCTTAGGACAGGGATACGAG
[0.018 0.018 0.051 0.91 0.002]
Full program, including the set-up hidden here

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,

P(s∣L)  =  1Z(L)∏i=1LqF(si∣i)wF  qB(si∣L−i+1)wBP(s \mid L) \;=\; \frac{1}{Z(L)} \prod_{i=1}^{L} q_F(s_i \mid i)^{w_F}\; q_B(s_i \mid L-i+1)^{w_B}
  • qF(si∣i)q_F(s_i \mid i) is the smoothed frequency of residue sis_i at position ii counted from the start, and qB(si∣L−i+1)q_B(s_i \mid L-i+1) the same counted from the end;
  • wFw_F and wBw_B are the two experts’ weights, 12\tfrac{1}{2} each by default;
  • Z(L)Z(L) is the normaliser of length LL.

Order 0 and order 1 can also be built directly: BeamModel(sequences, alphabet="nt", order=0). Amino-acid models start at order 2.