Skip to content
DeGrootResearchGroupPublic

About

Differentiable reaction kinetics for water and wastewater treatment in Python. Define models in YAML (ASM1/2d/3, ADM1, ozonation, UV/H₂O₂ and more), simulate reactors and whole plants like BSM1/BSM2 with JAX and Diffrax stiff solvers, and get exact gradients for calibration, sensitivity analysis and experiment design.

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Latest commit

 

History

1,228 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

aquakin

CI codecov Docs PyPI DOI

Differentiable reaction kinetics for water and wastewater treatment.

aquakin simulates the chemistry and biology of aqueous systems — from a single ozonation batch test to a whole wastewater treatment plant. You write a reaction model in a short YAML file (or pick one of the shipped models), and aquakin compiles it to fast JAX code solved by the stiff integrators of Diffrax. Because every solve is differentiable, the same model can be fitted to data, screened for sensitivity, and used to design the next experiment.

Highlights

  • Models as data. Species, reactions, rate laws and parameters live in a readable YAML file with its literature references — no code to write and nothing to recompile. Rate expressions are parsed safely (no eval) and checked for unit consistency and mass / COD / nitrogen conservation.
  • A library of standard models. Ozonation / bromate and UV/H₂O₂ chemistry; ASM1, ASM2d and ASM3 with two-step nitrification, N₂O, anammox and comammox variants; ADM1 anaerobic digestion; WATS sewer processes; and pH speciation with mineral precipitation (struvite, calcite, chemical phosphorus removal).
  • Reactors and whole plants. Batch, plug-flow, dispersed-flow, tanks-in-series, biofilm and particle-track reactors, with dispersion and tanks-in-series fits to a tracer test, and plant-wide flowsheets: the IWA benchmarks BSM1 and BSM2 build in one line, with clarifiers, IFAS/MBBR, digestion, disinfection, events (pumps, dosing, SBR phases), steady-state solvers and EQI / OCI, carbon footprint and cost reporting.
  • Gradients through everything. jax.grad works through a stiff solve — including a full BSM2 plant — with exact forward sensitivities and a stable adjoint, so derivatives stay finite where naive autodiff breaks down.
  • Calibration and experiment design. Fit parameters with uncertainty, check identifiability before running an experiment, choose sampling times and sensors, and propagate uncertainty to design decisions.
  • Projects, studies and a browser editor. Save a flowsheet as a file, keep analyses as reproducible studies that know when they are out of date, and draw plants in the aquakin-ui flowsheet editor.

Installation

Requires Python 3.11 or later.

pip install aquakin

Optional extras: aquakin[plot] (solution.plot(...) via matplotlib), aquakin[dataframe] (export to pandas / CSV), aquakin[ui] (the flowsheet editor) and aquakin[mcp] (tools for an AI assistant).

Note. import aquakin turns on JAX 64-bit mode for the whole process, because stiff solves need double precision. Other JAX code in the same process will then use float64; run it in a separate process if it needs float32.

Quickstart

1. Write a model

A model is a YAML file. Here is first-order chlorine decay:

# decay.yaml
model:
  name: first_order_chlorine
  version: "1.0"
  description: "First-order chlorine decay"

species:
  - {name: HOCl, units: mg/L, default_concentration: 2.0}

reactions:
  - name: decay
    rate: "k * [HOCl]"
    parameters:
      k: {value: 0.05, units: h-1}
    stoichiometry: {HOCl: -1}

2. Solve it, differentiate it, fit it

import aquakin
import jax
import jax.numpy as jnp

model = aquakin.load_model_from_file("decay.yaml")   # or aquakin.load_model("asm1")
reactor = aquakin.BatchReactor(model, model.default_conditions())
C0 = model.default_concentrations()

# Solve over a day (the model's time unit, hours, comes from its rate constant).
sol = reactor.solve(C0, t_span=(0.0, 24.0), t_eval=jnp.linspace(0.0, 24.0, 25))
sol.final_named(["HOCl"])              # {'HOCl': 0.602}

# Differentiate the result with respect to the parameters.
def final_chlorine(params):
    return reactor.solve(C0, t_span=(0.0, 24.0), params=params).C_named("HOCl")[-1]

jax.grad(final_chlorine)(model.default_parameters())   # d[HOCl]/dk = -14.46

# Fit the rate constant to measurements, with its uncertainty.
t_obs = jnp.array([0.0, 4.0, 8.0, 12.0, 24.0])
measured = jnp.array([[2.00], [1.62], [1.36], [1.08], [0.61]])   # HOCl, mg/L
fit = aquakin.calibrate(reactor, C0, measured, t_obs, ["decay.k"],
                        loss="nll", sigma=0.02)
fit.params_named, fit.params_named_std  # k = 0.0501 ± 0.0009 h⁻¹

Solutions carry species names and units through to results: sol.C_named("HOCl"), sol.to_dataframe(), sol.plot("HOCl").

Plant-wide simulation

aquakin.plant connects reactors, clarifiers, digesters and other unit operations into a flowsheet and integrates the whole plant in one solve. The IWA benchmark plants are ready to build:

import aquakin
from aquakin.plant.bsm import build_bsm1

model = aquakin.load_model("asm1")
plant = build_bsm1(model)            # 5 reactors + secondary clarifier + recycles
plant.add_influent("feed", model.influent(
    {"SI": 30.0, "SS": 69.5, "XI": 51.2, "XS": 202.32, "XB_H": 28.17,
     "SNH": 31.56, "SND": 6.95, "XND": 10.59, "SALK": 7.0}, Q=18446.0))

ss = plant.run_to_steady_state()     # integrate until the plant settles
eff = plant.stream(ss.solution, "effluent")
eff.final_named(["SNH", "SNO"])      # {'SNH': 0.47, 'SNO': 11.6} g N/m³

From there you can:

  • run dynamic simulations with the benchmark dry / rain / storm influents, a measured CSV, or an influent written as a formula of time;
  • jump straight to a differentiable steady state (plant.steady_state()), several times faster than integrating to it;
  • score EQI / OCI, a carbon footprint (N₂O, energy, fugitive methane) and an operating cost, and compare scenarios in one KPI table;
  • build BSM2 (build_bsm2) with primary clarification, thickening, ADM1 digestion and dewatering, or your own flowsheet from the unit catalogue — including IFAS/MBBR biofilm, UV and chlorine disinfection, and aeration systems sized from blower and diffuser physics;
  • calibrate plant parameters against measured streams and rank sensor sets by what they can identify, with gradients through the whole plant.

Projects, studies and the flowsheet editor

A plant can be saved as a YAML flowsheet and rebuilt from it (plant.to_spec("plant.yaml"), aquakin.Plant.from_spec("plant.yaml")). A study stores one analysis of that flowsheet — a simulation, a calibration, a profile likelihood, a sensor ranking — beside its results, and knows when they are out of date:

aquakin study run studies/effluent      # writes the results
aquakin study check studies/effluent    # fresh, or stale and why

To draw and edit flowsheets in an editor window of their own:

pip install "aquakin[ui]"
aquakin-ui            # or: aquakin-ui flowsheet.yaml to open a saved plant

The editor lets you drag units from a palette, wire their ports, edit each unit in a form built from its documentation, see errors as you edit, and set up and run studies with their results plotted. Colleagues who do not use Python can install it with one download (Windows) or one pasted line (macOS, Linux): see Installing the editor without Python.

From an AI assistant

aquakin mcp gives an AI assistant (Claude Desktop, Claude Code, or any app that speaks the Model Context Protocol) tools to look up the shipped models and unit kinds, check flowsheets, and read the user guide and API reference. It runs on your computer under the assistant's own account; aquakin needs no key.

pip install "aquakin[mcp]"
claude mcp add aquakin -- aquakin mcp     # Claude Code; or the plugin and other apps: see the guide

See Using aquakin from an AI assistant.

Documentation

The full documentation is at aquakin.readthedocs.io:

Page
Getting started installation, a first solve, building inputs, reading results
Model catalogue every shipped model, its provenance and how to load it
Your first model writing a model of your own, step by step
YAML model format every key, function and rule of a model file
Reactors batch, plug-flow, dispersed-flow, tanks-in-series, biofilm and particle-track reactors; fitting a tracer test; events; integrator settings
Plant-wide simulation the BSM1 / BSM2 benchmarks, performance indices, reporting, unit and mass-balance checks
Building a flowsheet a plant of your own and every unit operation
Influents patterned feeds, pump schedules, laboratory and SCADA records
Flowsheet files, studies and the editor saving a plant, reproducible studies, the browser editor
Using aquakin from an AI assistant aquakin mcp: models, flowsheet checks and the guide as tools for Claude or another MCP app
Sensitivity analysis which tool answers which question, gradients, local and global sensitivity, uncertainty propagation
Calibration fitting parameters to data, posteriors, profile likelihood, identifiability, model comparison
Experiment design Fisher information, scoring and optimizing a design, choosing measurements
Calibrating a plant plant fits, measured channels, plant identifiability and sensor ranking
Worked example: designing an experiment an ozone-demand study from first design to calibrated model
Public API the API grouped by task

Runnable scripts are in examples/, and the changelog lists what is new in each release.

Development

git clone https://github.com/DeGrootResearchGroup/aquakin.git
cd aquakin
pip install -e ".[test]"
pytest -m "not validation and not slow"   # fast unit + integration tests
pytest -m validation                      # validation against published data

Citing

If you use aquakin in your work, please cite it using the metadata in CITATION.cff (DOI 10.5281/zenodo.21268513, which always resolves to the latest release; each release also has its own DOI on Zenodo).

License

MIT — see LICENSE.

About

Differentiable reaction kinetics for water and wastewater treatment in Python. Define models in YAML (ASM1/2d/3, ADM1, ozonation, UV/H₂O₂ and more), simulate reactors and whole plants like BSM1/BSM2 with JAX and Diffrax stiff solvers, and get exact gradients for calibration, sensitivity analysis and experiment design.

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages