Skip to main content

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, biofilm and particle-track reactors, 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) and aquakin[ui] (the flowsheet editor).

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 your browser:

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.

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, biofilm and particle-track reactors; 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
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.23784521).

License

MIT — see LICENSE.

Metadata

Release files for aquakin 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aquakin 0.3.0
File Size Uploaded Provenance Actions
aquakin-0.3.0.tar.gz 1.4 MB With provenance Details for aquakin-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aquakin 0.3.0
File Interpreter ABI Platform Actions
aquakin-0.3.0-py3-none-any.whl Python 3 none any Details for aquakin-0.3.0-py3-none-any.whl

Total release size: 2.8 MB

Release files / aquakin-0.3.0.tar.gz

Download URL aquakin-0.3.0.tar.gz
Size 1.4 MB
Tags Source
SHA-256 checksum
How to use checksums
880df2da9fbe72bf1ad5ce97c1b9168407135d39acd80f95151c3bd2d0c2205d
BLAKE2b-256 checksum
How to use checksums
6f7a62bd67547aa249ea6ff2d994f99ebe91657cb57aa5b2c24c721ea968939d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / aquakin-0.3.0-py3-none-any.whl

Download URL aquakin-0.3.0-py3-none-any.whl
Size 1.5 MB
Tags Python 3
SHA-256 checksum
How to use checksums
20498655eb251cb9baf4a05d79b7c1bc8aae9079da9bbffd524cf28e04793fdf
BLAKE2b-256 checksum
How to use checksums
71d2476530a5d59214af3fb2c14359df9f92202d9d92b9f2bda6518ede7f90ea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for aquakin 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for aquakin-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page