Your first model#
This page walks through writing a reaction model of your own, from an empty file to a model you can solve, check and differentiate. The YAML model format is the reference for every key used here.
The example is chlorine decay in a water sample. Free chlorine (HOCl) is used up in two ways: quickly by a small amount of reactive material R, and slowly by everything else in the water, which is in such excess that it is lumped into a first-order rate.
Reaction |
Rate |
|---|---|
HOCl + R → products |
k_fast [HOCl][R] |
HOCl → products |
k_bulk [HOCl] |
1. Write the model file#
Save this as chlorine_decay.yaml:
# chlorine_decay.yaml
model:
name: chlorine_decay
version: "1.0"
description: "Free chlorine decay with a fast-reacting fraction and a slow bulk demand."
references:
- "Your citation for the rate constants here."
species:
- name: HOCl
description: "Free chlorine"
units: mg/L
default_concentration: 2.0
- name: R_fast
description: "Fast-reacting chlorine demand"
units: mg/L
default_concentration: 0.5
conditions:
- name: T
description: "Water temperature"
units: K
default: 293.15
parameters:
k_fast:
value: 0.5
units: L/(mg*h)
bounds: [0.01, 10.0]
transform: positive_log
k_bulk:
value: 0.05
units: 1/h
bounds: [0.001, 1.0]
transform: positive_log
temperature: {theta: 1.05, ref_T: 293.15}
clip_negative_states: true
reactions:
- name: fast_demand
reference: "Your citation"
rate: "k_fast * [HOCl] * [R_fast]"
stoichiometry: {HOCl: -1, R_fast: -1}
- name: bulk_decay
reference: "Your citation"
rate: "k_bulk * [HOCl]"
stoichiometry: {HOCl: -1}
What each block does:
species:lists what the model tracks.default_concentrationis a convenient starting point, not a measurement; you can give other initial concentrations when you solve.conditions:lists the fields the rates may depend on that are not species, here the temperature.parameters:holds the rate constants. They are declared at the top level so that a reaction refers to them by name, and calibration has one value to adjust.boundsandtransformmatter only when you calibrate or analyze the model:positive_logkeeps a rate constant positive and lets it vary over orders of magnitude. Thetemperature:block makesk_bulkincrease by 5 % per degree above 20 °C (293.15 K).clip_negative_states: trueevaluates the rates as if a negative concentration were zero. A stiff solve can step a nearly used-up species slightly below zero, where a rate such ask_fast * [HOCl] * [R_fast]would turn negative and run the reaction backwards. Every shipped model sets it; set it in yours.reactions:gives each reaction a rate, written in the rate-expression language with species in[...], and a stoichiometry saying how much of each species one unit of rate consumes (negative) or produces (positive).
2. Load it and read it back#
import aquakin
model = aquakin.load_model_from_file("chlorine_decay.yaml")
print(model.summary())
The summary lists the species, conditions, reactions and parameters as aquakin read them, and a line you should always check:
Time unit: h (t_span / t_eval are in hours)
aquakin has no fixed time unit. It reads the unit from your rate constants
(1/h here), and every time you pass to a solve is in that unit. If the line
says the time unit cannot be determined, a rate constant is missing its
units: or two of them use different time units.
3. Check it#
print(model.check_units()) # [] when every rate is dimensionally consistent
check_units reads the units: strings and checks each rate: that it is a
concentration per time, that terms added together have the same units, and
that a rate matches the species it changes one for one. An empty list means
no problems were found. It can only check what has units, so give every
species and parameter one.
If your species carry conserved quantities, such as COD, nitrogen or
phosphorus, declare them with composition: and
model.check_conservation() will report any reaction that does not balance
(see Conservation).
4. Solve it#
reactor = aquakin.BatchReactor(model, model.default_conditions())
sol = reactor.solve(
model.default_concentrations(),
t_span=(0.0, 24.0), # hours, the model's time unit
params=model.default_parameters(),
)
print(sol.final_named(["HOCl"])) # about 0.44 mg/L after 24 h
To solve at another temperature, change only that condition:
cold = aquakin.BatchReactor(model, model.default_conditions().with_(T=283.15))
5. Differentiate it#
Every solve can be differentiated with JAX, which is what sensitivity analysis and calibration build on:
import jax
def chlorine_after_24_h(params):
sol = reactor.solve(model.default_concentrations(), t_span=(0.0, 24.0), params=params)
return sol.C_named("HOCl")[-1]
print(model.parameters) # the order of the parameter vector
print(jax.grad(chlorine_after_24_h)(model.default_parameters()))
The second entry, for k_bulk, is large and negative: a faster bulk decay
leaves less chlorine. The first, for k_fast, is small and positive, which
may surprise: the fast demand uses up all of R_fast either way, so a larger
k_fast only makes that 0.5 mg/L drop happen sooner, and the slow first-order
decay then works on less chlorine for the rest of the day. The
Sensitivity analysis and
Calibration pages go on from here.
Common mistakes#
Mixed time units. A rate constant in
1/dbeside one in1/hmakes the time unit undetermined and the rates wrong by a factor of 24.check_unitsreports it.^for a power. Write[X] ** 2;^is refused.Unquoted species names YAML misreads. A species named
NOorONmust be quoted ("NO"), or YAML reads it asfalse.The same parameter name at both levels. A name declared in the top-level
parameters:cannot also be declared in a reaction’s ownparameters:.logof something that can reach zero. Writelog(1 + [X]/K), or keep the argument positive some other way.
Declaring each species’ phase#
Each species can say which phase it is in: soluble, particulate, or gas
for a gas-phase state the model carries itself, such as a digester headspace.
A clarifier settles the particulates, a biofilm holds them in place while the
other species diffuse, and the editor suggests them as a clarifier’s solids:
species:
- {name: SS, phase: soluble, units: g_COD/m3}
- {name: XS, phase: particulate, units: g_COD/m3}
A species without phase: is particulate when its name starts with X, a gas
when it starts with S_gas_, and soluble otherwise, the naming convention of
the ASM and ADM families. Every shipped model declares the phase of every
species.
Declaring the microbial populations#
A model with biomass declares its populations: which species is each one’s biomass, which stores it keeps, what it grows on, and which oxidized nitrogen species it may produce. The rates do not read the block, but checks and tools do, so they need not guess from species names:
populations:
- {name: H, biomass: XH, stores: [XSTO], substrates: [SS, XS, XSTO]}
- {name: AOB, biomass: XAOB, substrates: [SNH4], may_produce: [SNO2]}
substrates needs at least one entry; stores and may_produce default to
empty, and description is free text. Each biomass belongs to one population,
and a population cannot list its own biomass as a store or substrate. Every
shipped model with biomass declares the block. Its tests check that only a
population with may_produce oxidizes nitrogen, and only to those species, and
that a biomass grows only while one of its substrates is consumed. The compiled
model lists the block:
asm3 = aquakin.load_model("asm3")
print([p.name for p in asm3.populations]) # ['H', 'A']
Under extends:, populations merge by name like reactions, and
remove: {populations: [...]} drops one.
Building on a shipped model#
To change a model aquakin ships, such as one rate constant or one rate law,
inherit it with extends: instead of copying it; see
Inheriting a model. The
Model catalogue lists what is available.
Contributing a model to aquakin#
A model that others would use can be added to the shipped set:
Put the YAML file in
aquakin/models/. It then loads by name withaquakin.load_model("<name>").Cite the literature in
references:and on each reaction’sreference:.Make sure
model.check_units()returns no findings, and declare itspopulations:if it has biomass.Add tests of its structure (species, key stoichiometry) and, where published data exist, a validation test against that data.
Describe it in the Model catalogue and the README.