Flowsheet files, studies and the editor#
A plant can be saved as a flowsheet file, analyzed in studies that keep their results beside it, and drawn and edited in a browser. The examples save the BSM1 plant from Plant-wide simulation:
import aquakin
from aquakin.plant.bsm import build_bsm1
model = aquakin.load_model("asm1")
bsm1 = build_bsm1(model)
bsm1_feed = {"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}
bsm1.add_influent("feed", model.influent(bsm1_feed, Q=18446.0))
Saving a plant as a file#
A plant can be written as a YAML (or JSON) file and rebuilt from it:
bsm1.to_spec("flowsheet.yaml")
rebuilt = aquakin.Plant.from_spec("flowsheet.yaml")
The file lists every unit by its name, with an optional display label and all
of its settings (defaults included, so the file means the same plant whatever
the defaults of a later aquakin), the connections as unit.port -> unit.port,
the influents, named streams and recycle options, and the version of aquakin
that wrote it:
format: 2
aquakin: 0.3.0
name: BSM1
models:
asm1: {source: shipped, sha256: ...}
units:
feed: {kind: influent, model: asm1, Q: 18446.0, composition: {SI: 30.0, SS: 69.5, ...}}
tank3: {kind: cstr, label: Aerobic zone 1, model: asm1, volume: 1333.0, ...}
connections:
- tank2.out -> tank3.inlet
Every model a unit uses is listed under models:, either a shipped model or a
model YAML file beside the flowsheet. A model file can extends: a shipped
model, so a variant is a few lines: BSM2’s ASM1, with its parameters referenced
to 15 °C, is a models/asm1_bsm2.yaml that names extends: asm1 and lists the
parameters it changes (Inheriting a model).
Each model carries a fingerprint of its content, and reading a flowsheet whose
model has changed since it was written warns.
A time-varying influent is kept as a table file beside the flowsheet (columns
t, Q, optionally T, and species; see aquakin.plant.read_influent_table).
to_spec(path) writes it to data/<influent>.csv unless it was already read
from a table inside the flowsheet’s folder.
An influent’s times and flows are on the plant’s clock (options: time_unit),
like every other setting: on a plant running on hours, Q: 100 is 100 m³/h and
the t of an expression or a table is in hours. An influent written on another
clock says so with its own time_unit, and one whose values are in other units
lists them under units ({Q: m3/h, T: degC, SNH: mg/L}; not for a table,
whose columns are in the model’s units). to_spec writes both whenever it needs
them, so a feed read from a table of daily data, or a pattern written per day,
keeps its meaning on an hourly plant:
feed: {kind: influent, model: asm1, series: data/feed.csv, time_unit: d}
An SBR’s phases are a list with one mapping per phase, in SBRPhase’s own
field names, and its settling model a mapping that names its kind
(interface for InterfaceSettling, layered for LayeredSettling) and that
model’s arguments. A field left out takes its default (mixed: null lets the
phase decide from feed and kla), and to_spec writes every field. The
feed mode is required (a flowsheet written before SBRs had one is refused,
naming the three modes), the holding volume’s settings go with
feed: storage, and waste_flow goes with a phase that has waste: true:
sbr:
kind: sbr
model: asm1
phases:
- {name: fill, duration: 0.1, feed: true}
- {name: react, duration: 0.3, kla: 240.0}
- {name: settle, duration: 0.1, settle: true}
- {name: decant, duration: 0.1, decant: true}
settling: {kind: interface, v_settle: 400.0, area: 200.0}
full_volume: 1000.0
feed: storage
feed_flow: 5000.0
storage_volume: 600.0
storage_initial_fraction: 0.5
decant_flow: 5000.0
Reading a file checks it strictly: a misspelled setting (a phase’s too, named by
its entry), a value of the wrong type or a model that is not listed is an error
that names where it is. Anything a file cannot express yet (array-valued
settings such as initial concentrations, a heat-balance temperature model)
raises a SpecError that names it rather than being left out.
aquakin.plant.spec_fingerprint(spec) gives a fingerprint of the plant a file
builds: its settings, wiring and the content of its models and influent tables,
but not its layout, labels or where its files sit. Record it beside a result to
tell later whether the result still matches the flowsheet.
The project folder#
A flowsheet and everything it reads sit in one folder, the project, with the studies of it beside them:
my_project/
├── flowsheet.yaml the plant
├── aquakin.yaml the project's settings (optional; below)
├── models/ model files the flowsheet uses (shipped models stay in aquakin)
│ └── asm1_bsm2.yaml
├── data/ influent tables
│ └── feed.csv
└── studies/
└── effluent/ one study (below)
├── study.yaml what to run
├── data.csv observations, for a fit
├── run.yaml the record of the last run
├── results/ its results
├── frozen.yaml present while the study is frozen
└── snapshot/ the frozen copy of the plant: flowsheet, models, data
to_spec(path) and the editor’s Save copy a model or an influent table from
outside the folder into models/ and data/, so the folder can be moved or
shared whole.
Studies#
A study is one analysis of a flowsheet saved in the project with its results.
Each study is a folder under studies/ with a study.yaml saying what to run:
# studies/effluent/study.yaml
study:
kind: simulate
parameters: {asm1.muH: 5.0} # changed from the flowsheet's
initial_state: steady # or default, or a named-state file
time: {t_span: [0, 14], t_eval: {start: 0, stop: 14, num: 337}}
streams: [effluent] # saved whole: flow, temperature, species
states: all # each unit's state over time (or none, or [tank1, ...])
boundaries: true # also the influents and the streams that leave the plant
observables:
- stream: effluent
channels: [COD, TKN, NOx, TN, TSS]
aquakin study run studies/effluent # writes results/ and run.yaml
aquakin study check studies/effluent # fresh, stale (and why), damaged or failed
or aquakin.study.run_study(path) / check_study(path) from Python (the
commands are listed in The command line). Every
result is keyed by name (parameters by model.param, states by unit and state
name, trajectories as CSV columns such as effluent.SNH), so results stay
readable after the flowsheet is reorganized. Each run also writes
results/index.yaml, which lists every result table with its columns (grouped
by stream), its number of rows, its time range and its units, so you can see
what a run saved without opening the tables.
A simulation in time keeps everything its solve computed unless told
otherwise: every unit’s state over time, one table per unit
(results/states/<unit>.csv, columns such as tank1.SNH), and the plant’s
boundaries, the influents that enter it and the streams that leave it, beside
the streams it names. states: none or a list of units, and
boundaries: false, save less. A long run at a fine step can write hundreds of
megabytes, so aquakin.study.estimate_results(path) says how many rows,
columns and bytes a study will write before it runs, and warns above 200 MB with
what to save less of; the editor shows that warning when a run starts. The run
itself goes ahead whatever its size.
The tables are CSV files. By default they use commas between fields and a
decimal point. A spreadsheet set up for a language whose decimal mark is a comma
(French, German, Spanish and many others) opens such a file as one column; for
it, set the project to write semicolons between fields and decimal commas, in
an aquakin.yaml beside the flowsheet:
# aquakin.yaml
results:
csv: excel-comma-decimal # or standard (the default)
or with aquakin.study.set_csv_style(project, "excel-comma-decimal"), or the
Studies tab’s Results tables choice in the editor. Every study of the project
writes its tables that way from its next run on; results already written keep
their style, and no study needs running again. aquakin reads either style back,
as it does a calibration’s data table or an influent table saved from such a
spreadsheet.
A channel is a species, a
laboratory measurement (COD, TKN, NOx, TN, TP, TSS, Q, T) or a
weighted sum of your own; see
A channel of your own.
Besides simulate, a study can be a fisher information of a sensor design, a
calibrate fit to observations, a profile likelihood of one parameter, a
rank of candidate sensor sets (the methods are described in
Designing experiments), or a posterior sample of a
calibration’s uncertainty (below).
A fit reads its observations from a CSV table in the study folder, a t column
and one <stream>.<channel> column per measured channel. Because it fits the
likelihood of the data, it needs each channel’s measurement error: sigma, one
value for all channels or one per channel, or estimate_sigma: true to
estimate it from the fit:
study:
kind: calibrate
free: [asm1.muH, asm1.KS]
observables:
- {stream: effluent, channels: [SNH, TSS]}
data: data.csv # columns t, effluent.SNH, effluent.TSS
sigma: [0.2, 2.0] # each channel's measurement error
laplace: true
A posterior study draws from the posterior of a calibrate study’s fit by
Markov chain Monte Carlo (Sampling the posterior),
on that study’s plant or reactor, data and settings. It names the calibrate
study of the same project, whose results must be fresh:
study:
kind: posterior
fit: calibration # the calibrate study, studies/calibration
n_chains: 4
n_draws: 1000
n_warmup: 500
It writes every draw (draws.csv) and, per parameter, the optimum, mean,
standard deviation, 5 / 50 / 95 % quantiles, R-hat and effective sample size
(posterior.yaml). Check that every R-hat is below about 1.01 and the
effective sample sizes are large enough before using the draws; the editor
flags those that are not. The study goes stale when its calibrate study is run
again or changed, and freezing it keeps a frozen copy of the calibrate study,
results included.
A study follows the flowsheet: once a setting, a connection, a model or an
influent table it was run on changes, check reports it stale and names
what changed. A newer aquakin is noted but does not make a result stale; read
the changelog to decide whether to run it again. Running a study that has
results replaces them only when asked (--replace); aquakin study copy keeps
a copy first. The new results take the old ones’ place only when the run
succeeds: a run that fails or is cancelled leaves the earlier results as they
were, and check notes the attempt.
A study runs once at a time. While it runs, its folder holds running.yaml
with when the run started and how far it has got, so every program sees it:
check and the editor show the run’s progress, a second run of the study
(from the editor, the command line, an AI assistant or a script) is refused,
and so are freezing, unfreezing and editing it. aquakin study cancel stops
the run at its next checkpoint, whatever started it. A run that crashes or is
killed leaves no lock behind; the next run starts as usual.
aquakin study freeze instead pins a study to a snapshot of its plant, taken
inside the study folder with every model flattened (shipped models too) and
every influent table copied, so neither an edit to the project nor an aquakin
upgrade can change what it runs. aquakin study unfreeze --discard-results
makes it follow the flowsheet again and deletes its results, which were
computed on the snapshot.
From Python, aquakin.study.create_study(project, name, settings) and
update_study(path, settings) write a study.yaml, checking the settings as a
run would read them; plant_choices(spec) lists what a study of that flowsheet
may name, and study_results(path) reads a study’s results back: the values
of a steady state, an analysis’s summaries and tables, and the results index.
Series in time, a calibration’s fitted channels and data, and a posterior’s
draws are read with read_results(path, table), which reads only the columns,
time window (t=(start, end)) and every n-th row asked for, or gives their
statistics (stats=True: minimum, maximum, mean, time-weighted mean,
percentiles and final value, and for a stream that carries its flow, each
concentration’s flow-weighted mean and mean load), so a long run is never read
whole to look at one channel. A run writes the statistics of every series it
saved to results/statistics.yaml, where read_results finds them for a
whole table; a time window or a stride computes them afresh. A stream a simulation in time did not save, the return sludge or
the flow between two tanks, is rebuilt from the unit states it did save:
read_results(path, "stream:ras") (by its name, or "unit.port") gives its
flow, temperature and every species at the saved times, exactly as if the run
had saved it. That needs every unit’s state saved, and the study fresh (or
frozen), so the plant is the one that ran.
A run from a script is saved the same way: sol.save(folder) writes the files
a simulation study writes (every unit’s state, the plant’s inlets and outlets,
the streams and measured channels named, the final state, the parameters, the
index and the statistics), and aquakin.load_results(folder) reads them back a
slice at a time, as read_results reads a study:
from aquakin.plant import PlantObservable
week = bsm1.solve((0.0, 7.0), t_eval=[i / 96 for i in range(673)])
week.save("runs/week", streams=["effluent"],
observables=[PlantObservable("effluent", ("TN", "COD"))])
saved = aquakin.load_results("runs/week")
print(saved.tables) # streams, measured, states/tank1, ...
saved.read("measured", columns="effluent.TN", t=(6, 7))
saved.read("streams", columns="effluent.S*", stats=True)
Pass params= the vector the plant was solved with, if it was not the
default: the streams and channels are computed with it. A folder that already
holds saved results is refused rather than overwritten. load_results also
opens a study’s results/ folder.
To chart channels of streams, stream_chart reads them from a solution or from
saved results alike and gives a ChartSpec, a plain description of the chart;
to_svg draws it as SVG and draw on matplotlib axes (the plot extra):
from aquakin.core.charts import draw, to_svg
from aquakin.plant import stream_chart
spec = stream_chart(week, ["influent", "effluent"], "SNH") # one line per stream
svg = to_svg(spec)
ax = draw(stream_chart(saved, "effluent", ["TN"]))
comparison_chart puts one channel of one stream from several runs on one
chart, a line per run named as you name it (comparison_chart({"base": week, "saved": saved}, "effluent", "TN")); for studies, aquakin.study.study_comparison
takes their folders.
A study of a batch reactor#
A calibrate, profile or fisher study can study a batch reactor instead of
the flowsheet: a reactor: block gives its model and conditions, and
experiments the batches it is run on. The other settings are those of a
flowsheet study of the same kind:
# studies/ozone_fit/study.yaml
study:
kind: calibrate
reactor:
model: ../../models/ozone_demand.yaml # a model file, or a shipped model's name
conditions: {T: 293.15, pH: 7.5}
integrator: {rtol: 1.0e-6} # optional
experiments:
- {data: run1.csv, initial: {O3: 1.0, D: 12.0, M: 800.0}}
- {data: run2.csv, initial: {O3: 2.0, D: 12.0, M: 800.0}}
observed: [O3]
free: [fast.k1, slow.k2]
estimate_sigma: true
A model file’s path is read from the study folder, like flowsheet:;
create_study also takes one from the project folder (models/ozone_demand.yaml)
and stores it that way. Each experiment starts from its initial
concentrations (the model’s defaults for the species it does not name). Its
data table holds a t column and one column per observed species; the
experiments are fitted together, sharing the parameters, and are named by their
tables (run1, run2). The integrator settings are rtol, atol, order,
dtmax and max_steps (see
Choosing the integrator), and
time_unit gives the unit of the data’s times when it is not the model’s.
The results are those of a flowsheet study: the fit is saved as
CalibrationResult.save saves one, so
aquakin.load_calibration("studies/ozone_fit/results") reads it back, and
fitted.csv holds the fitted reactor’s observed species at the data’s times,
in columns such as run1.O3. A profile study takes one experiment. A
fisher study’s experiments give only their initial concentrations and, when
they differ from the study’s t_obs, their own sampling times (t_obs);
sigma is the measurement error.
The study is stale once the model (with any model it extends), a data table
or its settings change, and check names which. Freezing copies the model,
flattened, and the data tables into the study’s snapshot. A shipped model is
copied too.
Designing a batch experiment#
A design study optimizes a batch reactor’s experiments for the information
they give about the free parameters
(Designing experiments): it moves their sampling times
within time_bounds, at least min_spacing apart, and, for each species in
initial_bounds, their initial concentrations within its range. Experiments
already run go in base_experiments: they count, but do not move.
# studies/next_run/study.yaml
study:
kind: design
reactor: {model: ../../models/ozone_demand.yaml, conditions: {T: 293.15, pH: 7.5}}
base_experiments:
- {initial: {O3: 1.0, D: 12.0, M: 800.0}, t_obs: [5, 10, 20, 40]}
experiments:
- {initial: {O3: 2.0, D: 12.0, M: 800.0}, t_obs: [5, 10, 20, 40]}
observed: [O3]
free: [fast.k1, slow.k2]
sigma: 0.02
time_unit: min
criterion: D # or A, E, modified_E; subset: [...] scores only some
time_bounds: [1, 60]
min_spacing: 2
initial_bounds: {O3: [0.5, 3.0]}
The experiments start the search and keep their number of samples. The study
writes design.yaml: the optimized experiments as an experiments: list, in
the study’s time unit, ready to paste into a fisher or calibrate study (add
each run’s data: once it is made); the criterion at the start and at the
optimum; and each parameter’s standard deviation at both.
The simulate and rank kinds do not take a reactor yet. The editor lists a
reactor study and runs it, but its dialog edits only flowsheet studies; change a
reactor study in its study.yaml.
The flowsheet editor#
pip install "aquakin[ui]"
aquakin-ui flowsheet.yaml
(Installing the editor without Python covers a computer without Python: one download or one pasted line.)
opens a flowsheet editor in a window of its own on the flowsheet saved above (or an empty one, without a file), served on this machine only; closing the window stops it. Drag units from the palette, wire their ports, and edit each unit in a form generated from its own documentation; aquakin builds each unit and then the whole plant as you edit and lists any errors.
Open and Save read and write the files described above. Save writes exactly what
plant.to_spec(path)would, copying a model (with every file itextends:) or influent table from outside the project folder into it. Save refuses to overwrite a flowsheet that changed on disk since the window opened it, so two windows cannot silently undo each other’s work.The editor follows the project folder as other programs change it (an AI assistant, a text editor, another window). When the open flowsheet’s file changes, the editor shows the new version, keeping your view. If you have unsaved edits it asks first: discard them for the new version, or keep them (Save then refuses to write over the file; save under another name). When a study is added, edited or finishes, the Studies tab is updated.
Opening another file while the flowsheet has unsaved edits asks first (save them, or discard them). Undo takes back the last edits: a removed unit or wire, a move, a new unit or wire, or an applied form. Delete removes the selected units and wires (Backspace does not).
Edits typed into a unit’s form are applied when you select another unit, and a value that cannot be read is named under its field.
An influent’s composition lists every species of its model, each with its unit; type a number or an expression of time for each species in the feed and leave the rest empty. Focusing a species shows its description, and a long list can be narrowed by typing part of a name.
A chemical dosing unit’s reagent is set in its form: choose the model it is written in first, then add each species it contains with its concentration.
A sequencing batch reactor’s phases are a table in its form: add a phase, move it up or down, or remove it. Its settling model is a choice of kind, after which that model’s arguments appear.
The Model tab shows a model the flowsheet uses: each reaction’s rate and stoichiometric coefficients, and each parameter’s value, units and description, all editable, and Add a parameter. As you leave a field aquakin reads the edit: an error appears under it with a caret at the character it is about, and an edited expression lists the species, parameters and conditions it uses. A rate naming a parameter the model lacks offers to add it. Reactions, species, conditions and the model’s other blocks are edited in its YAML file.
Apply first loads and compiles the whole edited model, and writes nothing
unless it is valid. A model of the project is edited in its own file (written
again without its comments), holding only the changed fields when it
extends: another. A model shipped with aquakin is never changed: Apply asks
for a name (asm1_bsm1 for asm1 in a flowsheet named BSM1, say) and saves
the edits as models/<name>.yaml, which extends: the shipped model, and
every unit that used it switches to the new model. The flowsheet file is saved
in the same step, so it always names the model as saved.
Simulate saves the flowsheet, creates a study called simulation the first
time (simulation_<file name> for a file not named flowsheet.yaml, so each
flowsheet in a folder has its own), runs the plant to steady state, and shows a
table of every stream that leaves the plant: its flow, COD, TKN, NOx, TN and TSS,
with every species under Flow and species (temperatures in °C). To run in time
instead, or to save other streams, Edit the simulation study; a study that
runs in time shows a chart per channel of the stream you pick. From Python,
aquakin.study.simulation_study(spec) gives those settings.
The Studies tab lists the project’s studies and their status (fresh, stale
and why, not run, failed, cancelled). From it you can run a study and watch its
progress or cancel it, including a run another program started; freeze, unfreeze or copy it; and open Results: a
simulation’s streams, a Fisher study’s standard deviations, design criteria and
information matrix, a ranking of sensor sets, a calibration’s fitted parameters
with the data against the fit, or a profile’s curve and interval. Running a
study first saves the flowsheet’s unsaved edits, so it runs what you see (a
frozen study runs its snapshot). Replacing results or unfreezing asks first and
offers to keep a copy. Tick Don’t ask again to replace results without the
question from then on; the Ask before replacing results switch at the top of
the tab brings it back (the choice is kept in aquakin/ui.json in your
configuration folder). Unfreezing always asks. Results tables chooses the
CSV style the project’s runs write (above); the style you choose last is also
given to the next project you set up a study in.
New study sets one up in a dialog: pick its kind, and the fields that kind
uses appear, with the plant’s own streams, parameters and measurable channels to
choose from; Edit opens a study’s settings in the same dialog. The dialog
writes the same study.yaml you would write by hand, and a data table or saved
state chosen from elsewhere is copied into the study folder. A study set up in
the editor follows the flowsheet file that is open.
The command line#
Installing aquakin installs two commands:
Command |
What it does |
|---|---|
|
runs a study and writes its results; a study that has results is run again only with |
|
the same, reporting progress as JSON lines for a program that drives it; a line |
|
prints whether the results are fresh, stale (and why), not run, failed or cancelled, and the run in progress; exits with 0 when fresh or not run, 1 otherwise |
|
stops the study’s run at its next checkpoint, whichever program started it |
|
pins the study to a snapshot of its plant |
|
makes it follow the flowsheet again and deletes its results |
|
copies the study, results included, beside it under |
|
prints every unit kind a flowsheet file may use, with its settings and ports, as JSON |
|
serves aquakin’s tools to an AI assistant; |
|
opens the editor in a window of its own (in the browser where no window can be drawn); |
|
adds aquakin to this computer’s applications (an app on macOS, Start menu and Desktop shortcuts on Windows, an applications-menu entry on Linux); the installers run it |
<study> is the study’s folder, such as studies/effluent. A command that
fails exits with 2 and prints the reason.