Building a model¶
A model is built step by step with the methods of tq.Model, or read from text
(Reading and writing text); both give the same model. Each method's notation
equivalent is in the Notation reference.
tenqsp.Model
¶
A model under construction. Each method adds one piece; to_ir returns the
complete description and validate checks it.
axis(name, lower=None, upper=None, n=None, *, kind=None, units='', faces=None, spacing='uniform', ratio=None, labels=None, geometry='planar')
¶
Add an axis.
Continuous: m.axis("age", lower=0, upper=2, n=40, kind="one_way", units="h"), or
explicit cell boundaries with faces=[...], or spacing="geometric", ratio=....
kind is "one_way" (moves only upward, e.g. age), "bidirectional" (default)
or "spatial". geometry="spherical" (or "cylindrical") makes the axis a
radius: a field over it is a density per unit volume, d_r(...) is the divergence
through shells ((1/r^2)*d_r(r^2*...)) and totals are amounts in the sphere.
Categorical: m.axis("s", labels=["S", "R"]).
param(name, value=None, *, over=None, units='')
¶
Add one parameter. Without a value (m.param("k"), m.param("k", over=s)) it is
declared only: its value must be given when the model is solved or simulated
(params={"k": 2}); a missing value is an error, never a guess.
Scalar: m.param("k", 1e-9). One value per category: m.param("k", {"S": 1e-9,
"R": 1e-12}, over=s) (or a list in label order); use it as k[s]. Over several
axes, a nested dict (or a table with one row per category of the first axis):
m.param("V", {"liver": {"vascular": 0.1, "cellular": 1.5}, ...}, over=[organ, sub]),
used as V[organ, sub].
params(*names, **values)
¶
Add scalar parameters: k, beta = m.params(k=1e-9, beta=50.0). Names alone are
declared without a value, given when the model is solved or simulated:
ka, CL = m.params("ka", "CL"). Returns them in the order given (one object if only
one is given).
field(name, axes, *, init=None, units='', weights=None)
¶
Add a population density over one or more axes, e.g. m.field("I", axes=[age]).
init sets a starting density (a number or formula); see init for more.
weights gives each category a size, as cell widths do on a continuous axis, e.g.
organ volumes V (a parameter over [organ, sub]). The field then holds a
concentration; its amount is concentration x volume, and transition and
transfer take clearances or flows (volume per time), so what leaves one
category is exactly what arrives in another.
compartment(name, *, init=None, units='', volume=None)
¶
Add a well-mixed amount (free phage, drug, nutrient), e.g.
m.compartment("P", init=1e7). With volume (a parameter or formula of
parameters) it holds a concentration: doses and transfers are divided by the volume,
and its amount is value x volume.
define(name, expr)
¶
Name an intermediate formula, e.g. h = m.define("h", h_max*tq.sigmoid(...)).
Using the name keeps the stored equations short and readable.
integral(expr, *, over, name=None)
¶
Integral of expr over one or more axes (a sum on categorical axes). The result
varies over the axes not integrated. expr may be a slice, C.at(sub="vascular").
A field with weights is weighted by them (its integral is an amount). Without
name one is made up (int_age); the same integral asked for twice is stored
once.
transitions(name, *, axis, rates)
¶
Rates between the categories of an axis, e.g.
M = m.transitions("M", axis=s, rates={"S->R": mu, "R->S": mu}).
Only the moves are given; the "stay" (diagonal) rates are derived so that nothing is
created or lost. Use with transition.
A rate may vary over the field's other axes (e.g. with dormancy depth, or k[organ])
and depend on fields, compartments and totals; it may not vary along axis itself.
Joint transitions change several categorical axes at once (a shared receptor:
one mutation gives resistance to two phages). Give the axes as a list and each
category as its labels in that order, separated by commas:
m.transitions("X", axis=[r1, r2], rates={"S,S->R,R": mu_x}).
ode(compartment, rhs)
¶
The equation of a compartment: m.ode(P, beta*lysis - delta*P) means
dP/dt = beta*lysis - delta*P.
reaction(field, expr)
¶
Add expr to the field's rate of change, cell by cell (births, sources, losses).
field may be a slice, C.at(organ="liver"): only there.
hazard(field, rate)
¶
Remove the field at per-capita rate: adds -rate*field (on a slice, only
there).
advect(field, *, axis, velocity, scheme='erlang')
¶
Move the field along a continuous axis at velocity (ageing, maturation, drift).
scheme="erlang" (default) behaves exactly like a transit-compartment chain;
"sharp" keeps fronts and peaks sharper on the same grid.
diffuse(field, *, axis, D)
¶
Spread the field along a continuous axis with diffusivity D.
fokker_planck(field, *, axis, drift, D, scheme='sharp')
¶
Single cells moving along axis as dz = drift dt + sqrt(2 D) dW (Itô): their
density follows the Fokker–Planck equation d_t(F) = -d_z((drift - dD/dz)*F) +
d_z(D*d_z(F)). Adds that transport (velocity drift - dD/dz, the slope of D
worked out here) and that diffusion. D may vary along the axis through its
coordinate, but not through a field (write the two terms yourself then, with
grad).
The transport scheme is sharp by default: here D is the spread, and
erlang would add the grid's own spread (about |drift| x width / 2) to it.
transition(field, *, axis, matrix, of)
¶
Move of between the categories of axis with the rates of matrix (from
transitions). axis is the matrix's axis, or its list of axes for a joint
transition. field may be a slice: blood flow between organs only in
C.at(sub="vascular"). of has no default, so it always says which case is meant:
of=the field itself (m.transition(B, axis=s, matrix=Q, of=B)): cells switch category at the rates ofmatrixper cell (phenotypic switching, exchange between tissue spaces). On a field withweightsa rate is then a clearance or flow (volume per time): it moves rate x concentration of the origin, an amount per time.of=a rate of production (of=div, the division fluxg*B): a fraction of it ends up in another category, at the parent's rate (daughters carrying a mutation). The production itself is added withreactionas usual; this only moves the daughters.
Only the moves are given; what leaves the origin is derived, so nothing is created or lost.
inflow(field, *, axis, at, flux)
¶
Material entering at one end, e.g. newly infected cells entering age 0:
m.inflow(I, axis=age, at="lower", flux=k*B*P).
outflow(field, *, axis, at, to=None)
¶
Material carried out of one end by advection. It is absorbed (to=None) or added
to compartment to; either way it is recorded in the ledger.
at(field, *, flux=None, value=None, outflow=False, **end)
¶
A boundary condition, written as a paper writes it under the equation ("at z = 0:
..."). Name the end as z="lower", z="upper" or by its coordinate (z=0),
and give exactly one of:
flux=: the flux of the field along the axis at that end, positive toward larger coordinates, equals this formula. Inside it the field's own name means its value at that end.m.at(I, l=0, flux=k*P*B)(cells entering infection age 0,v*I(t, 0) = k*P*B);m.at(D, z=0, flux=alpha*(1 - frac)*B - beta*frac*D)(entry minus exit,-Dz*dD/dz = ...);flux=0: nothing crosses.value=: the field is held at this value there (C(t, 1) = 1).outflow=True: what the flow carries to this end leaves through it.
What crosses is recorded in the ledger. To use it in another equation, read the
field there: D(z=0), I(l="upper").
boundary(field, *, axis, at, kind, value=None, h=None, to=None)
¶
Any boundary condition: kind is "zero_flux" (nothing crosses),
"dirichlet" (held at value), or "robin" (exchange h*(value - field),
e.g. a biofilm surface with the bulk liquid). Inflow and outflow have their own
methods.
With to= a compartment (dirichlet or robin only), whatever crosses this end is
taken from that compartment (or given to it, if it leaves the field), so the two
exchange mass exactly: m.boundary(C, axis=z, at="upper", kind="robin",
value=Cb/V, h=h, to=Cb). The ledger records it on both sides.
init(target, value=None, *, total=None, shape=None, where=None, split=None)
¶
Starting state of a field or compartment.
m.init(P, 1e7): a value (for a field, a density; may be a formula of the axes).m.init(B, total=1e7, shape=tq.normal(z, mean=0.1, sd=0.08)): an amount and its shape; the shape is cut to the grid and scaled so the cells hold exactlytotal.where={s: "S"}: only these categories.split={s: {"S": 0.99, "R": 0.01}}: sharetotal(orvalue) between categories; the fractions must add up to 1.
dose(target, *, times, amounts=None, shape=None, density=None)
¶
Bolus doses at times, with one amount for every time or one per time.
- Into a compartment:
m.dose(P, times=[0, 24], amounts=1e8); with a volume, the value rises by amount / volume. - Into one element of a field (a slice fixing every axis):
m.dose(C.at(organ="gut", sub="vascular"), times=[0], amounts=100). - Into a field over continuous axes, as an initial value: an amount and its shape,
m.dose(G, times=[0, 12], amounts=100, shape=tq.point(g, at=0))(each dose is spread by the shape and the cells receive exactly the amount), or a density added to the field,m.dose(B, times=[0], density=1e6*tq.exp(-z)). A slice leaving some axes free doses only there.
lag(target, value)
¶
Every dose into target (a compartment, or every element of a field) arrives
value later, as NONMEM's ALAG: m.lag(depot, "tlag"). value is a formula of
parameters, >= 0 (checked when the model is run). It applies to the model's own doses
and to a regimen's alike; an infusion is shifted whole (start and stop).
bioavailability(target, value)
¶
Only the fraction value of every dose into target arrives, as NONMEM's F:
m.bioavailability(depot, "F"). value is a formula of parameters, >= 0 (checked
when the model is run; above 1 is allowed). Bolus amounts and infusion rates are scaled
by it; the ledger books the rest as "not absorbed".
observable(name, expr)
¶
A named output, e.g. m.observable("bacteria", m.integral(B, over=[z, s])), or a
slice of a field, m.observable("C_liver", C.at(organ="liver", sub="vascular")).
transfer(source, *, to, rate)
¶
Move material from source to to at rate x the source's value (an amount
per time). Each end is a compartment or a slice of a field; to=None removes it
(elimination, recorded in the ledger).
- compartment -> slice: every element of the slice receives
ratex the compartment (ratemay vary over the slice, e.g.Q[organ]); the compartment loses the sum. - slice -> compartment: the compartment receives the sum over the slice.
- slice -> slice: element by element over the axes both leave free; an end with
fewer free axes (one it leaves out or fixes,
A.at(organ="liver")) gives or takes the sum over the others.
With volumes or weights, the value is a concentration and rate a flow or
clearance (volume per time): m.transfer(C.at(sub="vascular"), to=Cven,
rate=Q[organ]) is venous return.
extinction(group, *, threshold, name=None, noise_floor=False)
¶
Declare a lineage group (fields, slices of fields such as B.at(s="R"), and
compartments) that is set to zero when its total falls below threshold after
having been above it. One group per strain:
for strain in ["S", "R"]:
m.extinction(B.at(s=strain), threshold=1.0)
The total is the sum of the members' amounts (field densities times cell widths, plus
compartment values), so the members must be counted in the same units. A group is
armed once its total reaches the threshold; an armed group crossing it downward is
set to zero at the exact crossing (sol.extinctions, and an extinction line in
the ledger) and disarmed. A group that has never reached the threshold (e.g. mutants
seeded from zero) is never touched. Once extinct, a group that nothing outside it
feeds (no reaction or rate that does not vanish with it, no switch or mutation into
it, no inflow or transfer) stays extinct: every equation sees it as zero until it is
back at the threshold, so round-off cannot bring it back; a run that doses into it
keeps its equations. explain() lists these groups.
noise_floor=True: while the group's total is below the threshold, every equation
sees the whole group as zero. Its sources still add to it, but round-off "ghost"
amounts cannot grow by feeding themselves. Nor does it see its own losses, so a feed
from outside the group fills it up; a feed too weak to hold it above the threshold
gives repeated fill-and-extinction cycles. Validation warns about such feeds: put
the source in the group (e.g. the blood compartment of a phage lineage).
to_ir()
¶
The complete model description (plain data; see tenqsp.ir).
to_text()
¶
The model as text in the TenQSP notation (docs/language/notation.md); it reads
back with from_text to the same model.
to_latex()
¶
The equations as a paper shows them (an amsmath align* block): every transition
written out category by category, then named formulas, boundaries and starting
values; see latex.
explain()
¶
The model in plain language: what each term means and which numerical scheme
carries it (a transit chain, its rate, mean transit time and CV, for erlang
transport), boundaries, starting values, doses, extinction groups and the complete
list of numerical safeguards; see explain. print(m.explain()).
diagnostics(sol=None)
¶
Accuracy guidance: per transported axis the cell Péclet number, the time
to cross a cell and the Erlang CV. With a solution (sol = m.solve(...)) also:
undershoot below atol followed by regrowth, negative values, solver
retries and how well the ledger closed. print(m.diagnostics(sol)).
from_text(text, *, name=None, cells=None, params=None)
classmethod
¶
Read a model written in the TenQSP notation (docs/language/notation.md); see
from_text. tq.load("model.tq") reads a file.
from_ir(ir)
classmethod
¶
Rebuild a model from its description (e.g. one loaded with ModelIR.from_json).
Objects are available by name: m["I"].
validate(*, raise_on_error=True)
¶
Check the whole model; list every problem, warning and note (see tenqsp.validate).
Raises ModelError if there are errors, unless raise_on_error=False.
compile()
¶
Compile the model to JAX functions (validates first). Builds are shared by models with the same structure, so calling it again, solving again, or changing only parameter values or dose times does not recompile.
solve(t_span, *, backend='scipy', **options)
¶
Solve the model over t_span = (start, end).
backend="scipy" (default) or "jax" (the JAX BDF, for gradients and batches;
same results; see jax_backend). Options: times, params (e.g.
{"k": 2e-9}), theta, method ("BDF" or "Radau"), rtol, atol,
max_step, regimen (a Regimen replacing the model's doses);
see solve.
simulator(outputs=None, **options)
¶
A simulator: the model built once, run with values, regimens and times given per
run. sim = m.simulator(outputs=["conc"]), then sim(scenario) or
sim(params={"CL": 5}, regimen=tq.bolus("depot", 100, every=12, n=7),
times=[...]). outputs: observables, fields or compartments (default: every
observable). Solver options (backend "scipy" or "jax", method, rtol,
atol, max_step, ledger) are fixed here. See simulate.
simulate(scenario=None, *, outputs=None, params=None, regimen=None, times=None, start=None, **options)
¶
One run: m.simulate(scenario) or m.simulate(params=..., regimen=...,
times=...); shorthand for m.simulator(outputs, **options)(...).
summary()
¶
Model size: state variables per field and compartment, and which axes drive it.
tenqsp.Slice
¶
Part of a field: field with the categories in where fixed (B.at(s="R")).
tenqsp.Condition
¶
A true/false formula, e.g. x > thr or (x > a) & (x <= b); used only to choose
between values in cases. Combine with & (and), | (or), ~ (not); stored
as text with and, or, not.
tenqsp.cases(*pairs, otherwise)
¶
Choose a value by conditions; the first true condition wins:
k = m.define("k", tq.cases((x > thr, k1),
(x > thr2, k2),
otherwise=k3))
The same as the formula text "k1 if x > thr else k2 if x > thr2 else k3".
otherwise is required: every cell always has a value.
tenqsp.eq(a, b)
¶
a == b as a condition.
tenqsp.ne(a, b)
¶
a != b as a condition.