From cb49bb8b4d33f05335841d53df1cce335aa6a9ba Mon Sep 17 00:00:00 2001 From: znetsixe Date: Tue, 19 May 2026 09:42:11 +0200 Subject: [PATCH] docs(wiki): full 5-page wiki matching the rotatingMachine reference format Replaces the prior stub/partial wiki with a Home + Reference-{Architecture, Contracts,Examples,Limitations} + _Sidebar structure. Topic-contract and data-model sections wrapped in AUTOGEN markers for the future wiki-gen tool. Source-vs-spec contradictions surfaced and flagged inline (not silently fixed). Pending-review notes mark sections that need a full node review. Co-Authored-By: Claude Opus 4.7 (1M context) --- wiki/Home.md | 382 ++++++++++++--------------------- wiki/Reference-Architecture.md | 293 +++++++++++++++++++++++++ wiki/Reference-Contracts.md | 227 ++++++++++++++++++++ wiki/Reference-Examples.md | 160 ++++++++++++++ wiki/Reference-Limitations.md | 132 ++++++++++++ wiki/_Sidebar.md | 20 ++ 6 files changed, 964 insertions(+), 250 deletions(-) create mode 100644 wiki/Reference-Architecture.md create mode 100644 wiki/Reference-Contracts.md create mode 100644 wiki/Reference-Examples.md create mode 100644 wiki/Reference-Limitations.md create mode 100644 wiki/_Sidebar.md diff --git a/wiki/Home.md b/wiki/Home.md index 6ee36fb..26dae5a 100644 --- a/wiki/Home.md +++ b/wiki/Home.md @@ -1,300 +1,182 @@ # reactor -> **Reflects code as of `c84dd78` · regenerated `2026-05-11` via `npm run wiki:all`** -> If this banner is stale, the page may be out of date. Treat as informative, not authoritative. +![code-ref](https://img.shields.io/badge/code--ref-0e34403-blue) ![s88](https://img.shields.io/badge/S88-Unit-50a8d9) ![status](https://img.shields.io/badge/status-pending--review-orange) -## 1. What this node is +A `reactor` models a single biological-treatment tank governed by the ASM3 (Activated Sludge Model No. 3) kinetics. It wraps either a CSTR (fully-mixed) or PFR (plug-flow with axial dispersion) integrator, accepts an influent stream + aeration rate, integrates the 13 ASM3 species each tick, and emits the effluent vector for the next Unit downstream (typically a `settler` or another `reactor`). A `diffuser` (Equipment Module) supplies aeration via `data.otr`; `measurement` children supply temperature and (PFR-only) dissolved-oxygen reconciliation. -**reactor** is an S88 Unit that wraps an ASM3 biological-process engine — either a CSTR (fully mixed tank) or a PFR (plug-flow with axial dispersion). It integrates 13 species (S_O, S_NH, X_H, X_TS, …) and emits the effluent vector each tick. Drives a settler downstream and accepts a recirculation pump child. +> [!NOTE] +> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only. -## 2. Position in the platform +--- -~~~mermaid +## At a glance + +| Thing | Value | +|:---|:---| +| What it represents | One biological-treatment tank running ASM3 kinetics — aerated, anoxic, or anaerobic | +| S88 level | Unit | +| Use it when | You need an activated-sludge tank with nitrification / denitrification / heterotrophic growth modelled species-by-species | +| Don't use it for | Passive equalisation tanks (no reactions), simple residence-time delays (lighter buffer is better), aerobic-only contactors where ASM3's full 13-species vector is overkill | +| Children it accepts | `measurement` (temperature at equipment; PFR also: dissolved oxygen at numeric distance); upstream `reactor` | +| Parents / sinks it talks to | downstream `reactor` or `settler` (via `Fluent` on Port 0); `diffuser` pushes `data.otr` in | + +--- + +## How it fits + +```mermaid flowchart LR upstream[reactor
upstream
Unit]:::unit - reactor[reactor
Unit]:::unit + rx[reactor
Unit]:::unit settler[settler
downstream
Unit]:::unit diffuser[diffuser
Equipment]:::equip - tsens[measurement
temperature
atequipment]:::ctrl - osens[measurement
oxygen
at distance]:::ctrl + tsens[measurement
temperature
atEquipment]:::ctrl + osens[measurement
quantity (oxygen)
at numeric distance, PFR only]:::ctrl + + upstream -.stateChange.-> rx + rx -->|Fluent inlet=0| settler + diffuser -->|data.otr| rx + tsens -.measured.-> rx + osens -.measured.-> rx + tsens -->|child.register| rx + osens -->|child.register| rx + upstream -->|child.register
positionVsParent=upstream| rx - upstream -.stateChange.-> reactor - reactor -->|Fluent inlet=0| settler - settler -.stateChange.-> reactor - diffuser -->|data.otr| reactor - tsens -->|child.register| reactor - osens -->|child.register| reactor - tsens -->|temperature.measured.atEquipment| reactor - osens -->|quantity(oxygen).measured.distance| reactor classDef unit fill:#50a8d9,color:#000 classDef equip fill:#86bbdd,color:#000 classDef ctrl fill:#a9daee,color:#000 -~~~ +``` -S88 colours: Unit `#50a8d9`, Equipment `#86bbdd`, Control Module `#a9daee`. Source of truth: `.claude/rules/node-red-flow-layout.md`. +S88 colours are anchored in `.claude/rules/node-red-flow-layout.md`. -reactor sits at the Unit level. A diffuser (Equipment) sends aeration rates via `data.otr` — it is NOT registered as a child. Measurement children (Control Module) register and supply temperature or dissolved-oxygen reconciliation. Settler is a downstream Unit that listens to `stateChange` to pull effluent; an upstream reactor drives this reactor the same way. +reactor sits on lane **L4** (Unit). The `diffuser` (lane L3) is **not** a registered child — it just pushes aeration via the `data.otr` topic. A reactor chain (multi-stage treatment, e.g. anoxic → aerobic → aerobic) is built by registering each upstream reactor with `positionVsParent: 'upstream'`; downstream reactors then `getEffluent` from the upstream on every `stateChange`. -## 3. Capability matrix +--- -| Capability | Status | Notes | -|---|---|---| -| ASM3 13-species ODE integration | ✅ | CSTR + PFR engines under `kinetics/`. | -| CSTR (fully mixed) | ✅ | Single concentration vector per tick. | -| PFR (axial discretization) | ✅ | `resolution_L` grid cells; emits `GridProfile` alongside `Fluent`. | -| Multi-inlet mixing | ✅ | `n_inlets`; each inlet receives its own `data.fluent` with `inlet` index. | -| Temperature reconcile from measurement | ✅ | `temperature.measured.atEquipment` writes `engine.temperature`. Code constant: `POSITIONS.AT_EQUIPMENT`. | -| Oxygen reconcile (PFR) | ✅ | `quantity (oxygen).measured.` maps to nearest grid cell. | -| KLa-driven aeration | ✅ | `reactor.kla` > 0 enables internal mass transfer; falls back to `data.otr`. | -| Speed-up factor (sim time) | ✅ | `reactor.speedUpFactor` accelerates wall-clock → process time. | -| Dispersion override (PFR) | ✅ | `data.dispersion` updates axial `D`. | -| Hot-swap engine type | ❌ | `reactor_type` is read once in `configure()`. | +## Try it — 3-minute demo -## 4. Code map +Import the basic example flow, deploy, and watch a CSTR consume influent over the simulation clock. -~~~mermaid -flowchart TB - subgraph nodeRED["nodeClass.js — adapter (BaseNodeAdapter)"] - nc["buildDomainConfig()
static DomainClass = Reactor
static commands"] - end - subgraph domain["specificClass.js — orchestrator (BaseDomain)"] - sc["Reactor.configure()
_flattenEngineConfig()
_buildEngine() → CSTR or PFR
ChildRouter.onRegister rules"] - end - subgraph kinetics["src/kinetics/"] - be["baseEngine.js
BaseReactorEngine
influent state, OTR, T
_connectMeasurement / _connectReactor
updateState() → n_iter ticks"] - cstr["cstr.js
Reactor_CSTR extends BaseReactorEngine
Forward-Euler 0-D integrator"] - pfr["pfr.js
Reactor_PFR extends BaseReactorEngine
FD spatial grid + Danckwerts BC"] - end - subgraph commands["src/commands/"] - cmds["index.js — 6 descriptors
handlers.js — 6 pure fns"] - end - nc --> sc - nc --> cmds - sc --> be - cstr --> be - pfr --> be -~~~ +```bash +curl -X POST -H 'Content-Type: application/json' \ + --data @nodes/reactor/examples/basic.flow.json \ + http://localhost:1880/flow +``` -| Module | Owns | Read first if you're changing… | -|---|---|---| -| `kinetics/baseEngine.js` | ASM3 stoichiometry + rate vector + species list. | Stoichiometric matrix, kinetic constants. | -| `kinetics/cstr.js` | 0-D CSTR integrator + `_connectMeasurement` + `_connectReactor`. | Mixed-tank behaviour, child wiring. | -| `kinetics/pfr.js` | Axial discretization, dispersion, grid profile emission. | PFR-specific behaviour, grid math. | -| `commands/` | 6 input descriptors + handlers (clock, fluent, OTR, temperature, dispersion, child). | Inbound topic API, alias deprecation. | -| `reaction_modules/` | Optional plug-in reaction modules (legacy — not yet refactored). | Adding new bio-process modules. | -| `additional_nodes/` | Sibling Node-RED nodes (`recirculation-pump`, `settling-basin`) shipped from this repo. | Cross-node deploy in same package. | +What to click after deploy (each inject maps one-to-one to a topic in [Reference — Contracts](Reference-Contracts#topic-contract)): -## 5. Topic contract +1. `data.fluent` — inject an influent stream `{inlet: 0, F: 1000, C: [...13 species...]}` (m³/d, mg/L). The 13 species follow ASM3 ordering. +2. `data.temperature` — set reactor temperature (default 20 °C; nitrification rates depend on this). +3. `data.otr` (if `kla` is `NaN`) **or** rely on the configured `kla` for internal aeration. +4. `data.clock` — push wall-clock `msg.timestamp` to advance the integrator. The engine computes `n_iter = floor(speedUpFactor × Δt_wall / timeStep_days)` internal Euler / FD steps and integrates them in one shot. +5. Watch Port 0 (`Fluent` envelope on every advance) and Port 1 (InfluxDB scalar fields: `flow_total`, `temperature`, `S_O`…`X_TS`). -> **Auto-generated** from `src/commands/index.js`. Do NOT hand-edit between the markers. Re-run `npm run wiki:contract`. +> [!IMPORTANT] +> **GIF needed.** Demo recording of steps 1–5 with `S_NH` falling and `S_NO` rising (nitrification proceeding). Save as `wiki/_partial-gifs/reactor/01-basic-cstr.gif`, target ≤ 1 MB after `gifsicle -O3 --lossy=80`. - +--- -| Canonical topic | Aliases | Payload | Unit | Effect | -|---|---|---|---|---| -| `data.clock` | `clock` | `any` | — | Push the simulation clock tick (timestamp / dt) to the ASM solver. | -| `data.fluent` | `Fluent` | `object` | — | Push the influent stream (payload: {F: flow m3/h, C: [concentrations mg/L]}). | -| `data.otr` | `OTR` | `any` | — | Push the current oxygen-transfer rate into the reactor. | -| `data.temperature` | `Temperature` | `any` | — | Push the current reactor temperature. | -| `data.dispersion` | `Dispersion` | `any` | — | Push a dispersion/mixing parameter update. | -| `child.register` | `registerChild` | `any` | — | Register a child node (settler / measurement) with this reactor. | +## The six things you'll send - +| Topic | Aliases | Payload | What it does | +|:---|:---|:---|:---| +| `data.clock` | `clock` | `{timestamp: ms}` (or use `msg.timestamp`) | Advance the integrator. `updateState` computes how many internal steps fit between `currentTime` and the supplied timestamp (scaled by `speedUpFactor`) and runs them. | +| `data.fluent` | `Fluent` | `{inlet: number, F: number, C: number[13]}` | Set the per-inlet flow rate (`F`) and concentration vector (`C`). Stored in `engine.Fs[inlet]` / `engine.Cs_in[inlet]`. | +| `data.otr` | `OTR` | numeric | Set the externally-supplied oxygen transfer rate. Used when `kla` is `NaN`; ignored otherwise (internal mass transfer takes over). | +| `data.temperature` | `Temperature` | numeric or `{value: number}` | Set `engine.temperature` (°C). Non-numeric payloads are warned and ignored. | +| `data.dispersion` | `Dispersion` | numeric | **PFR only** — set axial dispersion coefficient `D` (m²/d). Triggers Peclet / Courant guard warnings on the next `updateState`. | +| `child.register` | `registerChild` | child node id (string) | Register a sibling node (`measurement`, upstream `reactor`) with this reactor. Port 2 wiring does this automatically in normal flows. | -## 6. Child registration +> [!NOTE] +> Pending full node review (2026-05). reactor's command surface is data-push only — there is **no FSM, no setpoint, no mode**. The kinetics engine runs continuous-state ODE / PDE integration; the only stateful event is `stateChange` after every successful advance. -~~~mermaid -flowchart LR - subgraph kids["accepted children (softwareType)"] - m_t["measurement
temperature
positionVsParent=atEquipment"]:::ctrl - m_o["measurement
quantity (oxygen)
positionVsParent=distance (numeric)"]:::ctrl - r_up["reactor
positionVsParent=upstream"]:::unit - end - m_t -->|temperature.measured.atEquipment| h_meas["engine._connectMeasurement
(baseEngine.js)"] - m_o -->|quantity(oxygen).measured.distance| h_meas - r_up -.stateChange.-> h_react["engine._connectReactor
(baseEngine.js)"] - h_meas --> reconcile["reconcile T → engine.temperature
reconcile O2 → state grid cell (PFR only)"] - h_react --> pull["pull upstream getEffluent
→ Fs[0] / Cs_in[0] before next tick"] - classDef ctrl fill:#a9daee,color:#000 - classDef unit fill:#50a8d9,color:#000 -~~~ +--- -| softwareType | filter | wired to | side-effect | -|---|---|---|---| -| `measurement` | `asset.type = temperature`, `positionVsParent = atEquipment` | `engine._connectMeasurement` | Writes `engine.temperature`. CSTR only honours temperature; PFR additionally reconciles `quantity (oxygen).measured.` (numeric position) → nearest grid cell DO. | -| `measurement` | `asset.type = quantity (oxygen)`, `positionVsParent = ` | `engine._connectMeasurement` → `pfr._updateMeasurement` | PFR only: maps measurement to nearest grid cell by `round(pos / length × n_x)`. | -| `reactor` | `positionVsParent = upstream` | `engine._connectReactor` | Subscribes to upstream reactor's `stateChange`; pulls `getEffluent` into `Fs[0]` / `Cs_in[0]` before next integration step. | +## What you'll see come out -`diffuser` is NOT a registered child — it feeds aeration via `data.otr` on Port 0. No child-registration handshake is involved. - -## 7. Lifecycle — what one `data.clock` advance does - -~~~mermaid -sequenceDiagram - participant clock as clock injector - participant reactor as reactor (specificClass) - participant engine as kinetics engine (CSTR/PFR) - participant downstream as settler / next reactor - participant out as Port-0 output - - clock->>reactor: data.clock { timestamp } - reactor->>engine: updateState(timestamp) - Note over engine: n_iter = floor(speedUpFactor × Δt / timeStep)
each step calls tick(timeStep) - engine->>engine: integrate ASM3 rates (CSTR: Forward Euler / PFR: FD) - engine->>engine: cap S_O to saturation, clip negatives to 0 - engine->>engine: emit 'stateChange' (currentTime) - reactor->>reactor: notifyOutputChanged → getOutput() - reactor->>out: getOutput() → {flow_total, temperature, S_O … X_TS} - alt PFR engine - reactor->>out: GridProfile { grid[n_x][13], n_x, d_x, length, species } - end - out->>downstream: Fluent { inlet=0, F, C[13] } via stateChange listener -~~~ - -`stateChange` re-emits on `reactor.emitter` (BaseDomain emitter) — wired in `specificClass.configure()`. Downstream settlers or chained reactors subscribed via `_connectReactor` call their own `updateState` on each `stateChange` event. The tick loop is opt-in (tick-driven via `static tickInterval`) because the reactor integrates process-time steps that have no fixed wall-clock mapping. - -## 8. Data model — `getOutput()` - -Port-0 process payload is the `Fluent` envelope (+ optional `GridProfile` for PFR). Port-1 telemetry is the scalar snapshot below. - - - -| Key | Type | Unit | Sample | -|---|---|---|---| -| `S_HCO` | number | — | `5` | -| `S_I` | number | — | `30` | -| `S_N2` | number | — | `0` | -| `S_NH` | number | — | `25` | -| `S_NO` | number | — | `0` | -| `S_O` | number | — | `0` | -| `S_S` | number | — | `70` | -| `X_A` | number | — | `200` | -| `X_H` | number | — | `2000` | -| `X_I` | number | — | `1000` | -| `X_S` | number | — | `100` | -| `X_STO` | number | — | `0` | -| `X_TS` | number | — | `3500` | -| `flow_total` | number | — | `0` | -| `temperature` | number | — | `20` | - - - -**Concrete sample** (CSTR mid-integration, nitrifying): +Sample Port 0 message (CSTR mid-integration, nitrifying): ```json { - "flow_total": 1000, - "temperature": 15.2, - "S_O": 2.1, - "S_I": 30, - "S_S": 12.4, - "S_NH": 0.8, - "S_N2": 4.3, - "S_NO": 18.6, - "S_HCO": 4.2, - "X_I": 1050, - "X_S": 65, - "X_H": 2150, - "X_STO": 4.5, - "X_A": 215, - "X_TS": 3680 + "topic": "Fluent", + "payload": { + "inlet": 0, + "F": 1000, + "C": [2.1, 30, 12.4, 0.8, 4.3, 18.6, 4.2, 1050, 65, 2150, 4.5, 215, 3680] + }, + "timestamp": 1747500000000 } ``` -Species ordering follows ASM3: indices 0–6 are soluble, 7–12 are particulate. `flow_total` is the effluent flow (m³/d); the reactor uses days as the time unit internally. +The `C` array is the 13-species ASM3 vector in fixed order (indices 0–6 soluble, 7–12 particulate). For a PFR an additional message goes out on the same port **before** the effluent each advance: -## 9. Configuration — editor form ↔ config keys +```json +{ + "topic": "GridProfile", + "payload": { + "grid": [[...13...], [...13...], "...n_x rows..."], + "n_x": 10, + "d_x": 1.0, + "length": 10, + "species": ["S_O","S_I","S_S","S_NH","S_N2","S_NO","S_HCO","X_I","X_S","X_H","X_STO","X_A","X_TS"], + "timestamp": 1747500000000 + } +} +``` -~~~mermaid -flowchart TB - subgraph editor["Node-RED editor form (reactor.html)"] - f1["Reactor type: CSTR / PFR"] - f2["Volume (m³)"] - f3["Length (m) + Resolution — PFR only"] - f4["Alpha α (boundary condition blend)"] - f5["Number of inlets"] - f6["kLa (d⁻¹) — internal aeration"] - f7["13 × initial concentration fields"] - f8["Time step (s label) + Speed-up factor"] - end - subgraph config["Domain config slice (reactor.json)"] - c1[reactor.reactor_type] - c2[reactor.volume] - c3["reactor.length
reactor.resolution_L"] - c4[reactor.alpha] - c5[reactor.n_inlets] - c6[reactor.kla] - c7["initialState.S_O … X_TS"] - c8["reactor.timeStep (unit: h per schema)
reactor.speedUpFactor"] - end - f1 --> c1 - f2 --> c2 - f3 --> c3 - f4 --> c4 - f5 --> c5 - f6 --> c6 - f7 --> c7 - f8 --> c8 -~~~ +Port 1 (InfluxDB telemetry) carries the same data flattened as scalar fields — `flow_total` (m³/d), `temperature` (°C), and one field per species (`S_O`, `S_I`, `S_S`, `S_NH`, `S_N2`, `S_NO`, `S_HCO`, `X_I`, `X_S`, `X_H`, `X_STO`, `X_A`, `X_TS`, mg/L; `S_HCO` is mmol/L). -| Form field | Config key | Schema default | Range | Where used | -|---|---|---|---|---| -| Reactor type | `reactor.reactor_type` | `CSTR` | enum: `CSTR` / `PFR` (schema validator lowercases; `_buildEngine` toUpperCase guards) | engine selection in `Reactor._buildEngine()` | -| Volume (m³) | `reactor.volume` | `1000` | > 0 | residence time, mass balance | -| Length (m) | `reactor.length` | `10` | > 0 | PFR only — axial extent | -| Resolution | `reactor.resolution_L` | `10` | ≥ 1 | PFR grid cell count `n_x` | -| Alpha | `reactor.alpha` | `0.5` | 0–1 | Danckwerts (0) vs Dirichlet (1) inlet BC | -| Inlets | `reactor.n_inlets` | `1` | ≥ 1 | `Fs[]` / `Cs_in[]` array sizes | -| kLa (d⁻¹) | `reactor.kla` | `0` | ≥ 0; set to `NaN` to use `data.otr` instead | `_calcOTR()` in `baseEngine.js` | -| Time step | `reactor.timeStep` | `0.001` | ≥ 0.0001 | integrator inner step (schema says `h`; HTML label says `s` — see limitation #6) | -| Speed-up factor | `reactor.speedUpFactor` | `1` | ≥ 1 | `n_iter = floor(speedUpFactor × Δt_wall / timeStep_days)` | -| Initial S_O | `initialState.S_O` | `0` | ≥ 0 (mg/L) | starting dissolved oxygen (caps to saturation in first tick) | -| Initial S_NH | `initialState.S_NH` | `25` | ≥ 0 (mg/L) | starting ammonium | -| Initial X_H | `initialState.X_H` | `2000` | ≥ 0 (mg/L) | starting heterotroph biomass | -| Initial X_A | `initialState.X_A` | `200` | ≥ 0 (mg/L) | starting autotroph biomass — must be ≥ ~50 mg/L for nitrification; HTML default is `0.001` (footgun) | -| Initial X_TS | `initialState.X_TS` | `3500` | ≥ 0 (mg/L) | starting TSS — drives settler split | +| Field | Meaning | +|:---|:---| +| `S_O` | Dissolved oxygen. Capped to saturation at each tick via `_capDissolvedOxygen`. | +| `S_I` | Inert soluble COD. | +| `S_S` | Readily biodegradable substrate. | +| `S_NH` | Ammonium nitrogen. Drops during nitrification. | +| `S_N2` | Dinitrogen (denitrification end product). | +| `S_NO` | Nitrate / nitrite nitrogen. Rises during nitrification. | +| `S_HCO` | Alkalinity (bicarbonate, mmol/L). | +| `X_I` | Inert particulate COD. | +| `X_S` | Slowly biodegradable substrate. | +| `X_H` | Heterotrophic biomass. | +| `X_STO` | Stored COD in biomass. | +| `X_A` | Autotrophic biomass. **Must be ≥ ~50 mg/L for nitrification to proceed.** | +| `X_TS` | Total suspended solids. Drives the downstream settler split. | +| `flow_total` | Effluent volumetric flow (m³/d) — `sum(Fs)`. | +| `temperature` | Reactor temperature (°C). | -## 10. State chart +--- -Skipped — reactor has no FSM. It runs continuous-state ODE integration; the engine's only stateful event is `stateChange`, fired after every successful integration advance. See section 7 for the integration sequence. +## The interesting bits -## 11. Examples +### CSTR vs PFR -| Tier | File | What it shows | Status | -|---|---|---|---| -| Basic | `examples/basic.flow.json` | CSTR with one inlet, watch `Fluent` effluent | ✅ in repo | -| Integration | `examples/integration.flow.json` | upstream reactor → reactor → settler chain | ✅ in repo | -| Edge | `examples/edge.flow.json` | PFR with dispersion + multi-inlet | ✅ in repo | -| Companions | `additional_nodes/*` | recirculation-pump + settling-basin Node-RED nodes shipped from this repo | ✅ in repo | +The engine is selected once at `configure()` from `reactor.reactor_type`. The same input topics drive both, but PFR additionally: -One screenshot per tier where helpful. PNG ≤ 200 KB under `wiki/_partial-screenshots/reactor/`. +- Discretises the tank along the `length` axis into `resolution_L` grid cells (`n_x`). +- Emits a `GridProfile` message **before** the effluent each `updateState`. +- Honours `data.dispersion` to set the axial dispersion coefficient. +- Reconciles oxygen measurements at a **numeric** `positionVsParent` (interpreted as distance from inlet) into the nearest grid cell. +- Warns when local Peclet ≥ 2 or Courant ≥ 0.5 (stability of the explicit FD scheme). -## 12. Debug recipes +Hot-swapping engine type at runtime is not supported — redeploy the flow. -| Symptom | First thing to check | Where to look | -|---|---|---| -| Nitrification doesn't proceed (S_NH stays high) | `initialState.X_A` must be ≥ ~50 mg/L. Defaulting to `0.001` (a known footgun) means no autotrophs. | `generalFunctions/src/configs/reactor.json` | -| `Fluent` effluent flow zero | No `data.clock` ticks arriving, or `data.fluent` never set `Fs[0] > 0`. | `commands/handlers.js`, engine `setInfluent` | -| PFR `GridProfile` not emitted | `reactor_type` set to `CSTR` — only PFR emits grid. | `_buildEngine` switch | -| Settler downstream not updating | `stateChange` event listener path: settler must subscribe to `reactor.emitter`, NOT `reactor.measurements.emitter`. | settler `_connectReactor` | -| Temperature reconcile silently ignored | Child measurement's `asset.type` not `temperature` exactly, or `positionVsParent` not `atEquipment`. | `engine._connectMeasurement` | -| Integrator slow / stalls | `reactor.timeStep` too small for `speedUpFactor`. Internal `n_iter` count blows up. | `engine.updateState` | -| `wiki:datamodel` script slow / hangs | `mathjs` cold-start ~13 s; instantiation depends on it transitively. See known-limitations row 1. | `kinetics/baseEngine.js` | +### Aeration: internal `kla` vs external `data.otr` -## 13. When you would NOT use this node +`reactor.kla > 0` enables internal mass-transfer: `OTR = kla × (sat(T) − S_O)`. Set `kla = NaN` to fall through to the externally-pushed `data.otr` value (the path a `diffuser` Equipment node uses). -- Use reactor for **ASM3 biological treatment** modelling (activated sludge, nitrification, denitrification). For aerobic-only or simpler kinetics, the ASM3 species vector is overkill. -- Don't use reactor for a passive equalisation tank — the kinetics engines assume reactions are happening. -- Skip reactor when you only need a residence-time delay; a simple buffer node is lighter and doesn't require `mathjs`. +### `X_A` footgun -## 14. Known limitations / current issues +The HTML editor form's default initial autotroph biomass is `0.001` mg/L — effectively zero, so nitrification never starts. The JSON schema default is `200` mg/L. Always check the deployed node's form value before expecting `S_NH` to drop. See [Reference — Limitations](Reference-Limitations#x_a-initial-default-footgun). -| # | Issue | Tracked in | -|---|---|---| -| 1 | `mathjs` cold-start adds ~13 s to first `require()` — `wiki:datamodel` auto-gen may time out on the 60 s wrapper. Falls back to the hand-curated `concrete sample` block. Two remedies tracked: tree-shake mathjs to used ops only; cache the instance. | `.claude/refactor/OPEN_QUESTIONS.md` — "mathjs slow load" | -| 2 | `initialState.X_A` HTML default is `0.001` mg/L (silently disabling nitrification) but the schema default is `200` mg/L. Always check the deployed node's form value before expecting nitrification. | `reactor.html` line 38 vs `generalFunctions/src/configs/reactor.json` | -| 3 | `getEffluent` shape historically varied (array vs single envelope) — settler's `_connectReactor` tolerates both. Don't break the contract without updating settler. | `nodes/settler/src/specificClass.js → _connectReactor` | -| 4 | `additional_nodes/recirculation-pump` and `settling-basin` are legacy companions — not yet refactored to BaseDomain. | P6.5 follow-up | -| 5 | `reaction_modules/` is a legacy plug-in directory not consumed by the current engines. Removal pending. | P6.5 follow-up | -| 6 | `reactor_type` enum casing: the JSON schema validator lowercases the user-supplied value (`'PFR'` → `'pfr'`). `Reactor._buildEngine` calls `.toUpperCase()` to work around this until Phase 7 decides the platform-wide canonical casing. If the guard is removed prematurely, PFR config silently falls back to CSTR. | `.claude/refactor/OPEN_QUESTIONS.md` — "reactor schema enum lowercases reactor_type" | -| 7 | `timeStep` unit mismatch: the HTML form label says "Time step [s]" but `reactor.json` declares `unit: "h"`. `baseEngine.js` converts `config.timeStep` by `÷ 86 400` (seconds → days), suggesting the true input unit is seconds. Audited in OPEN_QUESTIONS.md Phase 5/6 cleanup list. | `baseEngine.js` line 40; `reactor.json` `timeStep.rules.unit`; `reactor.html` time-step label | +--- + +## Need more? + +| Page | What you'll find | +|:---|:---| +| [Reference — Contracts](Reference-Contracts) | Full topic contract, config schema, child registration filters | +| [Reference — Architecture](Reference-Architecture) | Code map, integration sequence, kinetics layout, output ports | +| [Reference — Examples](Reference-Examples) | Shipped example flows + debug recipes | +| [Reference — Limitations](Reference-Limitations) | When not to use, known limitations, open questions | + +[EVOLV master wiki](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Home) · [Topology Patterns](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topology-Patterns) · [Topic Conventions](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topic-Conventions) diff --git a/wiki/Reference-Architecture.md b/wiki/Reference-Architecture.md new file mode 100644 index 0000000..cb4c1b2 --- /dev/null +++ b/wiki/Reference-Architecture.md @@ -0,0 +1,293 @@ +# Reference — Architecture + +![code-ref](https://img.shields.io/badge/code--ref-0e34403-blue) + +> [!NOTE] +> Code structure for `reactor`: the three-tier sandwich, the `src/` layout, the ASM3 kinetics engines (CSTR + PFR), the integration sequence, child registration, and the output-port pipeline. For an intuitive overview, return to [Home](Home). +> +> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only. + +--- + +## Three-tier code layout + +``` +nodes/reactor/ +| ++-- reactor.js entry: RED.nodes.registerType('reactor', NodeClass) +| ++-- src/ +| nodeClass.js extends BaseNodeAdapter (Node-RED bridge) +| specificClass.js extends BaseDomain (orchestration only) +| utils.js assertNoNaN + small helpers +| | +| +-- commands/ +| | index.js 6 topic descriptors +| | handlers.js pure handler functions +| | +| +-- kinetics/ +| | baseEngine.js BaseReactorEngine (influent / OTR / T / child wiring / updateState) +| | cstr.js Reactor_CSTR extends BaseReactorEngine (0-D Forward Euler) +| | pfr.js Reactor_PFR extends BaseReactorEngine (axial FD + Danckwerts BC) +| | +| +-- reaction_modules/ +| | asm3_class.js ASM3 stoichiometry + rate vector + species list +| | asm3_class Koch.js legacy variant (not consumed by current engines) +| | +| +-- io/ reserved (currently empty) +| ++-- additional_nodes/ +| recirculation-pump.{js,html} legacy companion node shipped from this repo +| settling-basin.{js,html} legacy companion node shipped from this repo +``` + +### Tier responsibilities + +| Tier | File | What it owns | Touches `RED.*` | +|:---|:---|:---|:---:| +| entry | `reactor.js` | Type registration | Yes | +| nodeClass | `src/nodeClass.js` | Tick loop (`tickInterval = 1000` ms), status badge (`statusInterval = 1000` ms), `buildDomainConfig` mapping editor fields to nested config, `_emitOutputs` override that preserves the `Fluent` + `GridProfile` envelope (BaseNodeAdapter's default delta-compressed payload doesn't fit). | Yes | +| specificClass | `src/specificClass.js` | `_flattenEngineConfig` translates nested schema to engine shape; `_buildEngine` selects CSTR or PFR; wires ChildRouter (`measurement` → `engine._connectMeasurement`, `reactor` → `engine._connectReactor`); re-emits engine `stateChange` on the BaseDomain emitter; surfaces `getOutput()`, `getStatusBadge()`. | No | +| kinetics | `src/kinetics/*.js` | Pure ASM3 integration. `BaseReactorEngine` owns influent state, OTR, temperature, child-registration utils, and `updateState`. `Reactor_CSTR` adds the 0-D Forward-Euler tick. `Reactor_PFR` adds spatial discretization + boundary conditions + grid-profile emission. | No | + +`specificClass` is thin stitching. All the real work lives in the kinetics engines. + +--- + +## No FSM — continuous-state integration + +reactor has **no finite-state machine, no mode, no setpoint**. The engine runs continuous ODE / PDE integration in process time. The only stateful event is `stateChange`, emitted by `BaseReactorEngine.updateState` after every successful advance (`n_iter > 0` internal steps completed). + +```mermaid +flowchart LR + clk[data.clock
or tick(dt)]:::input --> us[updateState(newTime)] + us --> ni{n_iter = floor(
speedUpFactor × Δt / timeStep)} + ni -->|0| skip[no-op] + ni -->|>0| loop[for each step:
tick(timeStep)] + loop --> emit[emit stateChange(currentTime)] + classDef input fill:#a9daee,color:#000 +``` + +`stateChange` is the trigger downstream Units (settlers, chained reactors) use to pull effluent. + +--- + +## Kinetics engines — CSTR vs PFR + +```mermaid +flowchart TB + subgraph base["BaseReactorEngine"] + bs["Fs[], Cs_in[][13]
OTR, temperature, kla
upstreamReactor link
updateState(newTime)
_connectMeasurement / _connectReactor"] + end + subgraph cstr["Reactor_CSTR"] + cs["state = number[13]
tick(dt):
inflow + outflow + reaction + transfer
Forward Euler
_capDissolvedOxygen / _arrayClip2Zero"] + end + subgraph pfr["Reactor_PFR"] + ps["state = number[n_x][13]
length, n_x, d_x, A, alpha, D
D_op / D2_op finite-difference operators
tick(dt):
dispersion + advection + reaction + transfer
Explicit FD
Danckwerts inlet / Neumann outlet BC
Peclet / Courant guard warnings"] + end + bs --> cs + bs --> ps +``` + +### Forward Euler (CSTR) + +`Reactor_CSTR.tick(time_step)` adds four contributions per step: + +| Term | Formula | Notes | +|:---|:---|:---| +| Inflow | `Fs · Cs_in / volume` | Per inlet, summed into a single concentration delta. | +| Outflow | `−sum(Fs) / volume · state` | Mass leaves at the current tank concentration. | +| Reaction | `asm.compute_dC(state, T)` | ASM3 rate vector applied at current temperature. | +| Transfer | `OTR or kla · (sat(T) − S_O)` on the `S_O` index only | All other species: zero transfer. | + +After integration, `_capDissolvedOxygen` caps `S_O` to saturation and `_arrayClip2Zero` floors negative concentrations. + +### Explicit FD (PFR) + +`Reactor_PFR.tick(time_step)` operates per grid cell: + +| Term | Notes | +|:---|:---| +| Dispersion | `(D / d_x²) · D2_op · state` — central-difference second-derivative operator. | +| Advection | `(−sum(Fs) / (A · d_x)) · D_op · state` — first-derivative operator (central or upwind per config). | +| Reaction | Per-cell `asm.compute_dC(slice, T)`. | +| Transfer | OTR / `kla` on the `S_O` index, scaled by `n_x / (n_x − 2)` for interior cells only. | + +Boundary conditions: **Danckwerts** at the inlet when `sum(Fs) > 0` (mixes inlet concentration with diffusive back-mix governed by `alpha`); **Neumann** (no-flux) at the outlet and at the inlet when there is no flow. After integration, the same `_capDissolvedOxygen` / `_arrayClip2Zero` post-processing applies cell-by-cell. + +`updateState` extends `BaseReactorEngine.updateState` with two stability checks: + +| Check | Threshold | Warning | +|:---|:---|:---| +| Local Peclet `Pe = d_x · sum(Fs) / (D · A)` | `≥ 2` | `Local Peclet number (…) is too high! Increase reactor resolution.` | +| Courant `Co_D = D · timeStep / d_x²` | `≥ 0.5` | `Courant number (…) is too high! Reduce time step size.` | + +--- + +## Lifecycle — what one `data.clock` advance does + +```mermaid +sequenceDiagram + autonumber + participant clock as data.clock injector + participant rx as reactor (specificClass) + participant engine as kinetics engine (CSTR / PFR) + participant downstream as settler / next reactor + participant out as Port 0 / 1 + + clock->>rx: data.clock { timestamp } + rx->>engine: updateState(timestamp) + Note over engine: n_iter = floor(speedUpFactor × Δt / timeStep) + alt upstreamReactor present + engine->>engine: setInfluent = upstream.getEffluent + end + loop n_iter times + engine->>engine: tick(timeStep) — integrate ASM3 rates + engine->>engine: cap S_O to saturation, clip negatives + end + engine->>rx: emit 'stateChange' (currentTime) + rx->>rx: re-emit 'stateChange' on BaseDomain emitter + rx->>rx: notifyOutputChanged + alt PFR engine + rx->>out: Port 0 — GridProfile { grid, n_x, d_x, length, species } + end + rx->>out: Port 0 — Fluent { inlet=0, F, C[13] } + rx->>out: Port 1 — InfluxDB scalars { flow_total, temperature, S_O…X_TS } + downstream-->>rx: subscribes to stateChange via _connectReactor + downstream->>downstream: pulls getEffluent on each stateChange +``` + +The tick loop is opt-in (`static tickInterval = 1000`) because the integrator advances **process time** in steps that have no fixed wall-clock mapping. Without ticks the engine simply doesn't advance. `nodeClass._emitOutputs` is overridden so the `Fluent` / `GridProfile` envelope shape survives the BaseNodeAdapter pipeline. + +--- + +## Child registration + +Source: `src/specificClass.js` `configure()` wires the ChildRouter; `BaseReactorEngine._connectMeasurement` and `_connectReactor` do the actual subscription. + +```mermaid +flowchart LR + subgraph kids["accepted children (softwareType)"] + m_t["measurement
asset.type=temperature
positionVsParent=atEquipment"]:::ctrl + m_o["measurement
asset.type=quantity (oxygen)
positionVsParent=numeric distance (PFR)"]:::ctrl + r_up["reactor
positionVsParent=upstream"]:::unit + end + m_t -->|temperature.measured.atEquipment| h_meas["engine._connectMeasurement
(baseEngine.js)"] + m_o -->|quantity(oxygen).measured.<distance>| h_meas + r_up -.stateChange.-> h_react["engine._connectReactor
(baseEngine.js)"] + h_meas --> reconcile["reconcile T → engine.temperature
reconcile O2 → state grid cell (PFR only)"] + h_react --> pull["pull upstream getEffluent
→ Fs[0] / Cs_in[0] before next tick"] + classDef ctrl fill:#a9daee,color:#000 + classDef unit fill:#50a8d9,color:#000 +``` + +### `_connectMeasurement` event wiring + +`measurement.measurements.emitter` fires `.measured.` on every published value. The reactor subscribes: + +```js +const eventName = `${measurementType}.measured.${position}`; +measurement.measurements.emitter.on(eventName, (eventData) => { + this.measurements + .type(measurementType).variant('measured').position(position) + .value(eventData.value, eventData.timestamp, eventData.unit); + this._updateMeasurement(measurementType, eventData.value, position, eventData); +}); +``` + +`_updateMeasurement` (CSTR base): only `temperature` at `POSITIONS.AT_EQUIPMENT` is honoured — writes `engine.temperature`. Any other type logs `Type '' not recognized for measured update.` + +`_updateMeasurement` (PFR override): additionally handles `quantity (oxygen)` at a **numeric** position. Position is interpreted as metres along `length`; the value is written to grid cell `clamp(round(pos / length × n_x), 0, n_x − 1)`. Non-finite position / value, or `length ≤ 0`, logs a warn and the update is dropped. + +### `_connectReactor` — upstream chain + +Setting `positionVsParent: 'upstream'` on the upstream reactor's child-register makes this reactor subscribe to the upstream's `stateChange`. On every event the downstream's `updateState` runs, which first pulls the upstream's `getEffluent` into `Fs[0]` / `Cs_in[0]` then integrates. + +> [!NOTE] +> `diffuser` is **not** a registered child. It feeds aeration via the `data.otr` topic on Port 0 (handled in `commands/handlers.js` `dataOTR`). No child-registration handshake. + +--- + +## Output ports + +| Port | Carries | Sample shape | +|:---|:---|:---| +| 0 (process) | `Fluent` envelope every advance. For PFR: an additional `GridProfile` message sent **before** the `Fluent`. | `{topic: 'Fluent', payload: {inlet: 0, F, C: [...13...]}, timestamp}` | +| 1 (telemetry) | InfluxDB line-protocol payload built from `getOutput()` via `outputUtils.formatMsg`. Fields: `flow_total`, `temperature`, and one per species. | `reactor,id=rx_a flow_total=1000,temperature=20,S_O=2.1,S_NH=0.8,...` | +| 2 (registration) | `child.register` upward at init | `{topic: 'child.register', payload: , positionVsParent, distance}` | + + + +> [!NOTE] +> Pending full node review (2026-05). The flat Port-1 telemetry shape (one field per species, plus `flow_total` + `temperature`) reflects the current `getOutput()` in `src/specificClass.js`. + +| Key | Type | Unit | Source | +|:---|:---|:---|:---| +| `flow_total` | number | m³/d | `sum(Fs)` from the engine's effluent envelope | +| `temperature` | number | °C | `engine.temperature` | +| `S_O` | number | mg/L | effluent `C[0]` — dissolved oxygen, capped to saturation | +| `S_I` | number | mg/L | effluent `C[1]` — inert soluble COD | +| `S_S` | number | mg/L | effluent `C[2]` — readily biodegradable substrate | +| `S_NH` | number | mg/L | effluent `C[3]` — ammonium nitrogen | +| `S_N2` | number | mg/L | effluent `C[4]` — dinitrogen | +| `S_NO` | number | mg/L | effluent `C[5]` — nitrate / nitrite | +| `S_HCO` | number | mmol/L | effluent `C[6]` — alkalinity | +| `X_I` | number | mg/L | effluent `C[7]` — inert particulate COD | +| `X_S` | number | mg/L | effluent `C[8]` — slowly biodegradable substrate | +| `X_H` | number | mg/L | effluent `C[9]` — heterotrophic biomass | +| `X_STO` | number | mg/L | effluent `C[10]` — stored COD in biomass | +| `X_A` | number | mg/L | effluent `C[11]` — autotrophic biomass | +| `X_TS` | number | mg/L | effluent `C[12]` — total suspended solids | + + + +### Status badge + +Composed by `getStatusBadge()` in `src/specificClass.js`: + +``` + T= C F= m³/d S_O= mg/L +``` + +Engine type is `CSTR` or `PFR` (derived from the constructor name). Fill is green by default; the badge is purely informational — no shape / colour transitions tied to plant state, since reactor has no FSM. + +--- + +## Event sources + +| Source | Where it fires | What it triggers | +|:---|:---|:---| +| `engine.emitter` `'stateChange'` | `BaseReactorEngine.updateState` after `n_iter > 0` integration steps | `specificClass` re-emits on `this.emitter`; BaseNodeAdapter `_emitOutputs` runs (Port 0 + Port 1) | +| Child measurement emitter | `measurement.measurements.emitter` per `.measured.` | `engine._connectMeasurement` callback → writes into MeasurementContainer + `_updateMeasurement` reconcile | +| Upstream reactor `'stateChange'` | Upstream reactor's `BaseDomain` emitter | `engine._connectReactor` callback → downstream `updateState(t)` runs, pulling upstream effluent first | +| Inbound `msg.topic` | Node-RED input wire | `commandRegistry` dispatch | +| `setInterval(tickInterval = 1000)` | `BaseNodeAdapter` periodic tick | `nodeClass._emitOutputs` → `source.updateState(Date.now())` + send | +| `setInterval(statusInterval = 1000)` | `BaseNodeAdapter` | Status badge re-render | + +--- + +## Where to start reading + +| If you're changing… | Read first | +|:---|:---| +| ASM3 stoichiometry / kinetic constants | `src/reaction_modules/asm3_class.js` | +| Mixed-tank integration, child wiring, influent / OTR / T setters | `src/kinetics/baseEngine.js`, `src/kinetics/cstr.js` | +| Plug-flow discretization, dispersion, grid profile | `src/kinetics/pfr.js` | +| Topic registration, alias deprecation | `src/commands/index.js`, `src/commands/handlers.js` | +| Editor-field ↔ engine-config mapping | `src/nodeClass.js` `buildDomainConfig`, `src/specificClass.js` `_flattenEngineConfig` | +| Port-0 envelope shape (`Fluent` + `GridProfile`) | `src/nodeClass.js` `_emitOutputs` | +| Schema defaults, types, units | `generalFunctions/src/configs/reactor.json` | + +--- + +## Related pages + +| Page | Why | +|:---|:---| +| [Home](Home) | Intuitive overview | +| [Reference — Contracts](Reference-Contracts) | Topic + config + child filters | +| [Reference — Examples](Reference-Examples) | Shipped flows + debug recipes | +| [Reference — Limitations](Reference-Limitations) | Known issues and open questions | +| [settler wiki](https://gitea.wbd-rd.nl/RnD/settler/wiki/Home) | The typical downstream Unit that subscribes to reactor `stateChange` | +| [diffuser wiki](https://gitea.wbd-rd.nl/RnD/diffuser/wiki/Home) | The Equipment node that pushes `data.otr` | +| [EVOLV — Architecture](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Architecture) | Platform-wide three-tier pattern | diff --git a/wiki/Reference-Contracts.md b/wiki/Reference-Contracts.md new file mode 100644 index 0000000..62bca57 --- /dev/null +++ b/wiki/Reference-Contracts.md @@ -0,0 +1,227 @@ +# Reference — Contracts + +![code-ref](https://img.shields.io/badge/code--ref-0e34403-blue) + +> [!NOTE] +> Full topic contract, configuration schema, and child-registration filters for `reactor`. Source of truth: `src/commands/index.js`, `src/specificClass.js` `configure()`, and the schema at `generalFunctions/src/configs/reactor.json`. +> +> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only. +> +> For an intuitive overview, return to the [Home](Home). + +--- + +## Topic contract + +The registry lives in `src/commands/index.js`. Each descriptor maps a canonical `msg.topic` to its handler; aliases emit a one-time deprecation warning the first time they fire. + + + +| Canonical topic | Aliases | Payload | Unit | Effect | +|:---|:---|:---|:---|:---| +| `data.clock` | `clock` | `{timestamp: number}` (ms since epoch). If absent, handler falls back to `Date.now()`. | ms | Calls `source.updateState(timestamp)` — advances the ASM kinetics integrator by `n_iter = floor(speedUpFactor × Δt / timeStep_days)` steps that fit between `currentTime` and the supplied timestamp. Emits `stateChange` on completion. | +| `data.fluent` | `Fluent` | `{inlet: number, F: number, C: number[13]}` | F in m³/d (canonical); C in mg/L (S_HCO in mmol/L) | Writes the per-inlet flow rate into `engine.Fs[inlet]` and concentration vector into `engine.Cs_in[inlet]`. Registry-level unit normalisation is skipped; the handler stores values as supplied. | +| `data.otr` | `OTR` | numeric (`msg.payload` is the OTR scalar) | mg O₂ / L / d | Sets the externally-supplied oxygen transfer rate. Used by the kinetics engine **only when `kla` is `NaN`**; if `kla` is a finite number the internal mass-transfer formula `kla × (sat(T) − S_O)` is used and `data.otr` is ignored. | +| `data.temperature` | `Temperature` | numeric or `{value: number}` | °C | Sets `engine.temperature`. Non-numeric / non-finite payloads log a warn (`Invalid temperature input: `) and are dropped. | +| `data.dispersion` | `Dispersion` | numeric | m²/d | **PFR only.** Sets axial dispersion coefficient `D`. The next `updateState` warns if local Peclet ≥ 2 or Courant ≥ 0.5. On CSTR the setter is a no-op (`if (this.engine instanceof Reactor_PFR)` guard in `specificClass`). | +| `child.register` | `registerChild` | child node id (string) | — | Looks up the sibling via `RED.nodes.getNode(id)` and delegates to `source.childRegistrationUtils.registerChild` with `msg.positionVsParent`. Missing child / source logs a warn and short-circuits. | + + + +### Modes / sources / actions + +reactor has **no mode, no action allow-lists, no source gating**. All topics are accepted as long as the payload shape is valid. (Contrast with `rotatingMachine`, which gates every input through a mode × source matrix.) + +--- + +## Data model — `getOutput()` shape + +Composed each tick by `src/specificClass.js` `getOutput()`. Used to build the Port-1 InfluxDB payload; Port 0 carries the engine's `getEffluent` envelope directly. + +### Port-0 process payload + +The engine's effluent envelope, emitted on every successful `updateState` advance: + +```json +{ + "topic": "Fluent", + "payload": { "inlet": 0, "F": , "C": [<13 species, mg/L>] }, + "timestamp": +} +``` + +For a PFR an additional message is sent **before** the `Fluent` on the same port each advance: + +```json +{ + "topic": "GridProfile", + "payload": { + "grid": [[<13 cells of n_x>]], + "n_x": , + "d_x": , + "length": , + "species": ["S_O","S_I","S_S","S_NH","S_N2","S_NO","S_HCO","X_I","X_S","X_H","X_STO","X_A","X_TS"], + "timestamp": + } +} +``` + +### Port-1 telemetry — scalar keys + +| Key | Type | Unit | Source | +|:---|:---|:---|:---| +| `flow_total` | number | m³/d | `sum(Fs)` from effluent envelope | +| `temperature` | number | °C | `engine.temperature` | +| `S_O` | number | mg/L | effluent `C[0]` — capped to saturation by `_capDissolvedOxygen` | +| `S_I` | number | mg/L | effluent `C[1]` | +| `S_S` | number | mg/L | effluent `C[2]` | +| `S_NH` | number | mg/L | effluent `C[3]` | +| `S_N2` | number | mg/L | effluent `C[4]` | +| `S_NO` | number | mg/L | effluent `C[5]` | +| `S_HCO` | number | mmol/L | effluent `C[6]` — alkalinity | +| `X_I` | number | mg/L | effluent `C[7]` | +| `X_S` | number | mg/L | effluent `C[8]` | +| `X_H` | number | mg/L | effluent `C[9]` | +| `X_STO` | number | mg/L | effluent `C[10]` | +| `X_A` | number | mg/L | effluent `C[11]` | +| `X_TS` | number | mg/L | effluent `C[12]` | + +Non-finite species values are **omitted** from the output (the `Number.isFinite` guard in `getOutput`); they are not emitted as `null`. Pick one convention per consumer (absent vs null) and document it — see `.claude/rules/output-coverage.md`. + +### Species ordering + +The 13-species vector is **fixed**: + +| Index | Key | Group | +|:---:|:---|:---| +| 0 | `S_O` | soluble | +| 1 | `S_I` | soluble | +| 2 | `S_S` | soluble | +| 3 | `S_NH` | soluble | +| 4 | `S_N2` | soluble | +| 5 | `S_NO` | soluble | +| 6 | `S_HCO` | soluble | +| 7 | `X_I` | particulate | +| 8 | `X_S` | particulate | +| 9 | `X_H` | particulate | +| 10 | `X_STO` | particulate | +| 11 | `X_A` | particulate | +| 12 | `X_TS` | particulate | + +Don't reshuffle — `getOutput()` and `_flattenEngineConfig()` both depend on this exact order, as does `additional_nodes/settling-basin` and the downstream `settler` node. + +### Status badge + +`getStatusBadge()` in `src/specificClass.js`: + +``` + T=<°C>.X C F=.XX m³/d S_O=.XX mg/L +``` + +Engine type is the constructor name with `Reactor_` stripped (so `CSTR` or `PFR`). Badge is always green-dot (no FSM-driven state). + +--- + +## Configuration schema — editor form to config keys + +Source of truth: `generalFunctions/src/configs/reactor.json` plus `nodeClass.buildDomainConfig` (`src/nodeClass.js`). + +### General (`config.general`) + +| Form field | Config key | Default | Notes | +|:---|:---|:---|:---| +| Name | `general.name` | `Reactor` | Human-readable. | +| (auto-assigned) | `general.id` | `null` | Node-RED node id. | +| Default unit | `general.unit` | `null` | Unused by the reactor's own logic (the engines pick up units from the schema's `rules.unit` strings); kept for parent compatibility. | +| Log enabled | `general.logging.enabled` | `true` | Master switch. | +| Log level | `general.logging.logLevel` | `info` | `debug` / `info` / `warn` / `error`. | + +### Functionality (`config.functionality`) + +| Form field | Config key | Default | Notes | +|:---|:---|:---|:---| +| Position vs parent | `functionality.positionVsParent` | `atEquipment` | Used in the child-register payload that goes UP to whatever parent registers this reactor. Enum: `upstream` / `atEquipment` / `downstream`. | +| (hidden) | `functionality.softwareType` | `reactor` | Constant. | +| (hidden) | `functionality.role` | `Biological reactor for wastewater treatment` | Constant. | + +### Reactor (`config.reactor`) + +| Form field | Config key | Schema default | Range / unit | Notes | +|:---|:---|:---|:---|:---| +| Reactor type | `reactor.reactor_type` | `CSTR` | enum: `CSTR` / `PFR` | Selected once at `configure()`. `_buildEngine` calls `.toUpperCase()` so `pfr` and `PFR` both resolve. | +| Volume | `reactor.volume` | `1000` | m³, `> 0` | Used by mass balance and (PFR) surface-area derivation. | +| Length | `reactor.length` | `10` | m, `> 0` | **PFR only.** Sets axial extent and grid pitch (`d_x = length / n_x`). | +| Resolution | `reactor.resolution_L` | `10` | integer `≥ 1` | **PFR only.** Grid cell count `n_x`. | +| Alpha | `reactor.alpha` | `0.5` | `0..1` | **PFR only.** Inlet boundary blend: `0` = pure Danckwerts, `1` = fully mixed inlet. | +| Inlets | `reactor.n_inlets` | `1` | integer `≥ 1` | `Fs[]` / `Cs_in[]` array size. | +| kLa | `reactor.kla` | `0` | 1/h, `≥ 0`; set `NaN` to disable | Enables internal aeration `OTR = kla · (sat(T) − S_O)`. When `NaN`, `data.otr` is honoured instead. | +| Time step | `reactor.timeStep` | `0.001` | `≥ 0.0001` | Schema declares unit `h`; `baseEngine.js` converts by `÷ 86400` (treating it as seconds). See [Limitations — timeStep unit mismatch](Reference-Limitations#timestep-unit-mismatch). | +| Speed-up factor | `reactor.speedUpFactor` | `1` | `≥ 1` | Multiplies wall-clock Δt when computing `n_iter`. `2` means twice as many internal steps per second. | + +### Initial state (`config.initialState`) + +13 starting concentrations, all written into the engine's `state` (CSTR: single row; PFR: replicated across all `n_x` grid cells at construction). + +| Form field | Config key | Schema default | HTML default | Unit | Notes | +|:---|:---|:---|:---|:---|:---| +| Initial S_O | `initialState.S_O` | `0` | check editor | mg/L | Capped to saturation on the first tick. | +| Initial S_I | `initialState.S_I` | `30` | check editor | mg/L | Inert soluble COD. | +| Initial S_S | `initialState.S_S` | `70` | check editor | mg/L | Readily biodegradable substrate. | +| Initial S_NH | `initialState.S_NH` | `25` | check editor | mg/L | Ammonium — declines with nitrification. | +| Initial S_N2 | `initialState.S_N2` | `0` | check editor | mg/L | Dinitrogen. | +| Initial S_NO | `initialState.S_NO` | `0` | check editor | mg/L | Nitrate / nitrite. | +| Initial S_HCO | `initialState.S_HCO` | `5` | check editor | mmol/L | Alkalinity. | +| Initial X_I | `initialState.X_I` | `1000` | check editor | mg/L | Inert particulate COD. | +| Initial X_S | `initialState.X_S` | `100` | check editor | mg/L | Slowly biodegradable substrate. | +| Initial X_H | `initialState.X_H` | `2000` | check editor | mg/L | Heterotrophic biomass. | +| Initial X_STO | `initialState.X_STO` | `0` | check editor | mg/L | Stored COD in biomass. | +| Initial X_A | `initialState.X_A` | `200` | **`0.001`** | mg/L | **Footgun.** HTML default in `reactor.html` (per `CONTRACT.md`) is effectively zero, disabling nitrification. Always verify the deployed form value. | +| Initial X_TS | `initialState.X_TS` | `3500` | check editor | mg/L | Total suspended solids — drives downstream settler split. | + +> [!WARNING] +> The HTML form supplies its own defaults; for fields where they differ from the schema (notably `X_A`), the HTML wins at deploy time. Either match the schema in the HTML or audit every deployed flow. + +### Unit policy + +reactor does **not** declare a UnitPolicy in `specificClass`. Units are carried in the schema's `rules.unit` strings (m³, m, 1/h, mg/L, mmol/L) and consumed by the engines without normalisation through MeasurementContainer's canonical-unit rule. Notable internal conversions: + +| Quantity | What the engine uses internally | Where converted | +|:---|:---|:---| +| `timeStep` | days | `baseEngine.js` line ~40: `timeStep = config.timeStep / 86400` | +| `Fs` | m³/d (assumed by mass-balance formulas) | not converted — the caller is expected to push m³/d on `data.fluent` | +| `temperature` | °C | stored as supplied (Celsius); `_calcOxygenSaturation(T)` expects °C | + +This is a known divergence from the platform-wide canonical-unit rule (`Pa` / `m³/s` / `W` / `K`). Tracked. + +--- + +## Child registration + +Source: `src/specificClass.js` `configure()` (ChildRouter wiring) + `BaseReactorEngine._connectMeasurement` / `_connectReactor`. + +| Software type | Filter | Wired to | Side-effect | +|:---|:---|:---|:---| +| `measurement` | `asset.type = 'temperature'`, `positionVsParent = atEquipment` | `engine._connectMeasurement` → `_updateMeasurement` | Writes `engine.temperature`. CSTR only honours this. | +| `measurement` | `asset.type = 'quantity (oxygen)'`, `positionVsParent = ` | `engine._connectMeasurement` → `Reactor_PFR._updateMeasurement` | **PFR only.** Maps measurement to nearest grid cell by `clamp(round(pos / length × n_x), 0, n_x − 1)`. Writes into `state[cell][S_O_INDEX]`. | +| `reactor` | `positionVsParent = 'upstream'` | `engine._connectReactor` | Subscribes to upstream reactor's `stateChange`. Each event triggers downstream `updateState`, which pulls upstream `getEffluent` into `Fs[0]` / `Cs_in[0]` before integrating. | + +### Not a child: `diffuser` + +`diffuser` (Equipment Module) is **not** registered as a reactor child. It feeds aeration via the `data.otr` topic on Port 0. No child-registration handshake is involved. If you want the diffuser's OTR to drive the reactor, wire the diffuser's process output to the reactor's input directly. + +### Unrecognised softwareType + +`BaseReactorEngine.registerChild` logs `Unrecognized softwareType: ` and drops the registration. There is no `valve`, `rotatingMachine`, etc. acceptance path. + +--- + +## Related pages + +| Page | Why | +|:---|:---| +| [Home](Home) | Intuitive overview | +| [Reference — Architecture](Reference-Architecture) | Code map, integration sequence, kinetics | +| [Reference — Examples](Reference-Examples) | Shipped flows + debug recipes | +| [Reference — Limitations](Reference-Limitations) | Known issues and open questions | +| [EVOLV — Topic Conventions](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topic-Conventions) | Platform-wide topic rules | +| [EVOLV — Telemetry](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Telemetry) | Port 0 / 1 / 2 InfluxDB layout | diff --git a/wiki/Reference-Examples.md b/wiki/Reference-Examples.md new file mode 100644 index 0000000..51b4522 --- /dev/null +++ b/wiki/Reference-Examples.md @@ -0,0 +1,160 @@ +# Reference — Examples + +![code-ref](https://img.shields.io/badge/code--ref-0e34403-blue) + +> [!NOTE] +> Every example flow shipped under `nodes/reactor/examples/`, plus how to load them, what they show, and the debug recipes that go with them. Live source: `nodes/reactor/examples/`. +> +> Pending full node review (2026-05). The current flows predate the standard 3-tier example-flow rework that `rotatingMachine` has completed; planned upgrade is tracked in the EVOLV superproject memory ("Example Flows" TODO). + +--- + +## Shipped examples + +| File | Tier | Dependencies | What it shows | +|:---|:---:|:---|:---| +| `basic.flow.json` | 1 | EVOLV only | Single CSTR with one inlet. Inject `data.fluent` to set influent, `data.clock` to advance the integrator; watch `Fluent` effluent on Port 0 and InfluxDB scalars on Port 1. | +| `integration.flow.json` | 2 | EVOLV only | Upstream `reactor` → `reactor` → `settler` chain. The downstream reactor registers the upstream via `child.register positionVsParent=upstream`; on each upstream `stateChange` the downstream pulls effluent and advances. | +| `edge.flow.json` | 3 | EVOLV only | PFR with axial dispersion (`data.dispersion`) and multi-inlet (`n_inlets > 1`). Emits both `GridProfile` and `Fluent` per advance. | + +> [!IMPORTANT] +> **Screenshots needed.** Editor capture of each example flow. Save as `wiki/_partial-screenshots/reactor/{01-basic-cstr,02-chain,03-pfr-edge}.png`. Replace these callouts with image links once captured. + +The legacy `additional_nodes/recirculation-pump` and `additional_nodes/settling-basin` Node-RED nodes are shipped from this repo but are not yet refactored to BaseDomain — they aren't part of these examples. + +--- + +## Loading a flow + +### Via the editor + +1. Open the Node-RED editor at `http://localhost:1880`. +2. Menu → Import → drag the JSON file. +3. Click Deploy. + +### Via the Admin API + +```bash +curl -X POST -H 'Content-Type: application/json' \ + --data @nodes/reactor/examples/basic.flow.json \ + http://localhost:1880/flows +``` + +--- + +## Example — Basic CSTR + +Single-reactor flow with one inlet and the minimum set of inputs needed to drive nitrification. + +### What to do after deploy + +1. Inject `data.temperature` with `payload: 15` (or whatever process T you want). Optional — default is 20 °C. +2. Inject `data.fluent` with: + ```json + { + "topic": "data.fluent", + "payload": { + "inlet": 0, + "F": 1000, + "C": [0, 30, 70, 25, 0, 0, 5, 1000, 100, 2000, 0, 200, 3500] + } + } + ``` + Note `C[11] = 200` (X_A — autotroph biomass). If you copy the HTML default of `0.001`, nitrification never starts. +3. If `kla > 0` is configured, you can skip OTR injection; the engine aerates internally. Otherwise inject `data.otr` with a positive scalar. +4. Inject `data.clock` repeatedly (or rely on the periodic tick — `tickInterval = 1000` ms wall-clock). Each advance integrates `n_iter = floor(speedUpFactor · Δt / timeStep_days)` internal steps. +5. Watch the debug tap on Port 0: `Fluent` envelopes with the 13-species effluent. `S_NH` should fall, `S_NO` should rise — nitrification is proceeding. + +> [!IMPORTANT] +> **GIF needed.** Demo recording of `S_NH` ↓ / `S_NO` ↑ over 30 simulated days. Save as `wiki/_partial-gifs/reactor/01-basic-cstr.gif`. + +--- + +## Example — Reactor chain + +Upstream → downstream coupling demo. The downstream reactor registers the upstream via: + +```json +{ + "topic": "child.register", + "payload": "", + "positionVsParent": "upstream" +} +``` + +On every upstream `stateChange`, `engine._connectReactor` triggers downstream `updateState`. That call first reads `upstream.getEffluent` into the downstream's `Fs[0]` / `Cs_in[0]`, then integrates. So one `data.clock` to the upstream advances the whole chain. + +> [!NOTE] +> Pending full node review (2026-05). The flow currently in `integration.flow.json` may not yet conform to the multi-tab layout standard (Process Plant / Dashboard UI / Demo Drivers / Setup) described in `.claude/rules/node-red-flow-layout.md` — planned upgrade tracked in the EVOLV "Example Flows" TODO. + +--- + +## Example — PFR edge + +Plug-flow reactor with axial discretization. After deploy: + +1. Inject `data.dispersion` with `payload: ` to set the axial dispersion coefficient `D`. +2. Inject one or more `data.fluent` messages with distinct `inlet` indices (0..`n_inlets − 1`). +3. Drive with `data.clock` as usual. +4. Watch Port 0: each advance emits a `GridProfile` **before** the `Fluent`. The grid has `n_x` rows, 13 columns each. +5. Add a `measurement` child with `asset.type = 'quantity (oxygen)'` and a numeric `positionVsParent` (e.g. `5` for 5 m from the inlet). On each measurement event the PFR engine writes the value into the nearest grid cell's `S_O`. + +Stability tips: + +- `Pe_local = d_x · sum(Fs) / (D · A)` must be `< 2` — if you see `Local Peclet number ... is too high!`, either increase `resolution_L` (more cells, smaller `d_x`) or raise `D`. +- `Co_D = D · timeStep / d_x²` must be `< 0.5` for the explicit FD scheme — if you see `Courant number ... is too high!`, decrease `timeStep`. + +--- + +## Debug recipes + +| Symptom | First thing to check | Where to look | +|:---|:---|:---| +| `S_NH` stays at its initial value — nitrification not proceeding | `initialState.X_A` is effectively zero (HTML default is `0.001` mg/L). Set to `~50` or higher to seed autotrophs. | `reactor.html` ↔ `generalFunctions/src/configs/reactor.json` `initialState.X_A` | +| `Fluent` payload `F = 0` | No `data.fluent` arrived, or `Fs[0]` is still 0 (no inlet flow). Check the message payload shape: `{inlet, F, C}`. | `src/commands/handlers.js` `dataFluent`, engine `setInfluent` | +| `Fluent` payload appears, but `C` array is all zeros / unchanged | `data.clock` not arriving, or `n_iter = 0` (timestamp delta too small for the configured `timeStep`). Bump `speedUpFactor` or check that clock injects are firing. | `engine.updateState` in `baseEngine.js` | +| PFR `GridProfile` not emitted | `reactor.reactor_type` is `CSTR` — only PFR has a grid profile. | `nodeClass._emitOutputs`, `pfr.getGridProfile` | +| `temperature` ignored | Payload is non-numeric, or wrapped as `{value: ...}` with `value` non-finite. Look for `Invalid temperature input: ` in the log. | `baseEngine.js` `setTemperature` setter | +| Temperature child measurement not reconciling | The child's `asset.type` must be exactly `'temperature'` and `positionVsParent = atEquipment`. Anything else logs `Type '' not recognized for measured update.` | `baseEngine.js` `_updateMeasurement` | +| `Local Peclet number ... is too high!` warning on every PFR `updateState` | Either `D` is too small, or `d_x` is too large. Increase `resolution_L` or set a larger dispersion. | `pfr.updateState` Peclet guard | +| `Courant number ... is too high!` warning | `timeStep` is too large for the configured `D`. Reduce it. | `pfr.updateState` Courant guard | +| Settler downstream not updating | Settler must subscribe to the **reactor's `emitter`**, not `reactor.measurements.emitter`. Historical bug in `settler/src/specificClass.js` `_connectReactor` (fixed 2026-03-02). | upstream chain wiring, `settler._connectReactor` | +| `wiki:datamodel` autogen script slow / timing out | `mathjs` cold-start is ~13 s. The current 60 s wrapper sometimes times out. | known limitation; fall back to the hand-curated Concrete sample in `CONTRACT.md` `Home.md` | +| `reactor_type: 'pfr'` (lowercase) silently runs CSTR | Schema validator lowercases the enum; `_buildEngine` calls `.toUpperCase()` to compensate. If you stripped that guard, lowercase `pfr` falls through to the default branch (CSTR). | `src/specificClass.js` `_buildEngine` | +| `data.otr` value ignored | `reactor.kla > 0`. The engine prefers internal `kla · (sat − S_O)` over external OTR. Set `kla = NaN` to enable external OTR. | `cstr.tick` / `pfr.tick` `klaIsNaN` branch | + +> Never ship `enableLog: 'debug'` in a demo — the kinetics engines log per-step on debug, which fills the container log within seconds. + +--- + +## Docker compose snippet + +To bring up Node-RED + InfluxDB with EVOLV nodes pre-loaded: + +```yaml +# docker-compose.yml (extract) +services: + nodered: + build: ./docker/nodered + ports: ['1880:1880'] + volumes: + - ./docker/nodered/data:/data/evolv + influxdb: + image: influxdb:2.7 + ports: ['8086:8086'] +``` + +Full file: [EVOLV/docker-compose.yml](https://gitea.wbd-rd.nl/RnD/EVOLV/src/branch/development/docker-compose.yml). + +--- + +## Related pages + +| Page | Why | +|:---|:---| +| [Home](Home) | Intuitive overview | +| [Reference — Contracts](Reference-Contracts) | Topic + config + child filters | +| [Reference — Architecture](Reference-Architecture) | Code map, kinetics engines, integration sequence | +| [Reference — Limitations](Reference-Limitations) | Known issues and open questions | +| [settler — Examples](https://gitea.wbd-rd.nl/RnD/settler/wiki/Reference-Examples) | The typical downstream Unit | +| [EVOLV — Topology Patterns](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topology-Patterns) | Where reactor fits in a larger plant | diff --git a/wiki/Reference-Limitations.md b/wiki/Reference-Limitations.md new file mode 100644 index 0000000..3959952 --- /dev/null +++ b/wiki/Reference-Limitations.md @@ -0,0 +1,132 @@ +# Reference — Limitations + +![code-ref](https://img.shields.io/badge/code--ref-0e34403-blue) + +> [!NOTE] +> What `reactor` does not do, current rough edges, and open questions. Open items live in `.agents/improvements/IMPROVEMENTS_BACKLOG.md` and `.claude/refactor/OPEN_QUESTIONS.md` in the superproject. +> +> Pending full node review (2026-05). Content reflects `CONTRACT.md`, the current source, and a partial walkthrough of `src/kinetics/` — not a full audit. + +--- + +## When you would not use this node + +| Scenario | Use instead | +|:---|:---| +| A passive equalisation tank (no biological reactions, just buffering) | A simple Node-RED buffer / function node — the kinetics engines assume reactions are happening. | +| A residence-time delay (plug-flow without ASM) | A delay node or custom buffer; the ASM3 13-species machinery + `mathjs` cold-start are overkill. | +| Aerobic-only contactors where you only need oxygen mass-transfer | An OTR-only model is lighter; ASM3 brings 13 species you'll ignore. | +| A clarifier / settler | `settler` — reactor has no settling, no sludge thickening, no underflow / overflow split. | +| A pump / blower / valve | `rotatingMachine` / `valve` — reactor is a process-tank model, not an actuator. | +| Anaerobic digestion | ASM3 is calibrated for activated sludge under aerobic / anoxic conditions. ADM1 (a separate model family) is the right tool for digesters. | + +--- + +## Known limitations + +### `X_A` initial default footgun + +The HTML editor form's default for initial autotroph biomass is **`0.001` mg/L** (effectively zero). The JSON schema default is `200` mg/L. The HTML wins at deploy time. With `X_A ≈ 0` nitrification never starts — `S_NH` stays at the influent value forever, no `S_NO` is produced. + +> [!WARNING] +> Always open every deployed reactor node and confirm `Initial X_A` is `≥ ~50` mg/L before expecting nitrification. Tracked in `CONTRACT.md` `## 14` row 2 and in EVOLV memory `MEMORY.md` "Key Integration Gotchas". + +### `mathjs` cold-start ~13 s + +`baseEngine.js` requires `mathjs`. The first `require('mathjs')` in a Node.js process takes ~13 s wall-clock to initialise. This delays first `data.clock` advance after a fresh deploy, and can time out the `wiki:datamodel` autogen wrapper (60 s budget). Two remedies tracked: + +1. Tree-shake `mathjs` to only the operations actually used (`add`, `multiply`, `diag`, `resize`, `sum`, `divide`). +2. Lazy-initialise / cache the instance. + +Tracked in `.claude/refactor/OPEN_QUESTIONS.md` — "mathjs slow load". + +### `timeStep` unit mismatch + +- HTML form label: `Time step [s]`. +- Schema (`generalFunctions/src/configs/reactor.json` line ~144): `unit: "h"`. +- `baseEngine.js` line ~40 converts by `÷ 86400` (seconds → days) before using it. + +The conversion suggests the **true** unit is seconds. Schema is wrong. Until reconciled, treat the form field as seconds. Tracked in `CONTRACT.md` `## 14` row 7 and in `OPEN_QUESTIONS.md` (Phase 5/6 cleanup list). + +### `reactor_type` enum casing + +The JSON schema validator lowercases `reactor_type` (so `'PFR'` → `'pfr'`). `Reactor._buildEngine` calls `.toUpperCase()` to compensate. If that guard is ever removed prematurely (before the platform-wide canonical casing rule is decided in Phase 7), PFR configs silently fall back to the default branch — which constructs a CSTR. Tracked in `OPEN_QUESTIONS.md`. + +### `getEffluent` shape historically varied + +Earlier versions of `BaseReactorEngine.getEffluent` returned either an envelope object or an array of envelopes (multi-outlet PFR). The current code emits a single `{topic, payload, timestamp}` envelope, but the downstream `settler._connectReactor` tolerates **both** shapes. Don't break this contract without coordinating with the settler node. EVOLV memory records a 2026-03-02 fix in settler for the array-vs-envelope assumption. + +### No FSM — no mode / setpoint / startup-shutdown sequencing + +reactor has no startup, no shutdown, no e-stop, no mode, no setpoint. It runs continuous-state ODE / PDE integration unconditionally as long as `data.clock` advances (or the tick loop fires). A downstream consumer that expects a `state` field on Port 0 will get nothing of the sort. This is by design — biological reactors don't have meaningful FSM states — but it's a divergence from `rotatingMachine` / `pumpingStation` patterns that callers should know about. + +### No mode / source / action allow-list gating + +All incoming topics are accepted as long as the payload validates. There is no `parent` / `GUI` / `fysical` source-gating, no `auto` / `virtualControl` / `fysicalControl` mode-gating. If you want to lock down a deployed reactor (e.g. ignore manual `data.fluent` injections while a real flow sensor is wired), you must do it externally. + +### `additional_nodes/` legacy companions not refactored + +`additional_nodes/recirculation-pump.js` and `additional_nodes/settling-basin.js` are sibling Node-RED nodes shipped from the reactor repo (because they share the same package context). They are **not yet refactored to BaseDomain**. Tracked as P6.5 follow-up. + +### `reaction_modules/` legacy directory + +`src/reaction_modules/asm3_class.js` is consumed by the current engines. `src/reaction_modules/asm3_class Koch.js` is a legacy plug-in variant **not consumed by anything in the current codebase**. Removal pending. Tracked as P6.5 follow-up. + +### Units don't follow EVOLV canonical-unit rule + +The platform-wide MeasurementContainer canonical units are `Pa` / `m³/s` / `W` / `K`. reactor uses m³/d for flow, °C for temperature, mg/L (or mmol/L for alkalinity) for concentrations. No conversion at the system boundary. Calling code that expects canonical units must convert. + +### `data.dispersion` is silently a no-op on CSTR + +`specificClass.set setDispersion` checks `if (this.engine instanceof Reactor_PFR)` before forwarding. On a CSTR the setter just drops the payload — no warn, no error. If you deploy a flow that injects `data.dispersion` and switch the reactor type to CSTR, the injection is silently ignored. + +### Single output-shape convention not documented per-key + +The `getOutput()` implementation **omits** non-finite species values (`Number.isFinite` guard) rather than emitting them as `null`. Per `.claude/rules/output-coverage.md`, every node should pick one convention and document it. reactor's is "absent" — downstream consumers should treat a missing species key as "not produced this tick", never as zero. + +### `output-coverage` manifest not yet present + +`test/_output-manifest.md` (required by the platform-wide output-coverage rule, 2026-05-14) is not yet checked in for reactor. The Port-0 envelope shape, Port-1 InfluxDB fields, and `GridProfile` payload all need enumeration with populated + degraded test coverage. Tracked in `.agents/improvements/IMPROVEMENTS_BACKLOG.md`. + +--- + +## Open questions (tracked) + +| Question | Where it lives | +|:---|:---| +| `mathjs` slow load — tree-shake or lazy-init | `.claude/refactor/OPEN_QUESTIONS.md` — "mathjs slow load" | +| `reactor_type` enum casing — platform-wide canonical | `.claude/refactor/OPEN_QUESTIONS.md` — "reactor schema enum lowercases reactor_type" | +| `timeStep` unit reconciliation (HTML `s` vs schema `h` vs engine `d`) | `OPEN_QUESTIONS.md` Phase 5/6 cleanup list | +| Removal of `reaction_modules/asm3_class Koch.js` and `additional_nodes/*` | P6.5 follow-up | +| Output-coverage manifest + populated / degraded tests | `.agents/improvements/IMPROVEMENTS_BACKLOG.md` | +| Should reactor adopt a canonical-unit boundary like the rest of EVOLV? | Internal — not yet ticketed | +| Multi-outlet PFR (separate effluent streams per spatial point) | Internal — long-term | + +--- + +## Migration notes + +### From the pre-`BaseDomain` reactor + +The current `specificClass` extends `BaseDomain` and uses ChildRouter to dispatch `measurement` / `reactor` registrations. Older flows that pre-date this refactor may have hand-wired child handlers; redeploying after `npm install` should pick up the new path automatically — no schema migration is required. + +### From legacy topic names + +The five `data.*` topics replace the pre-canonical PascalCase aliases (`Fluent`, `OTR`, `Temperature`, `Dispersion`, `clock`). The aliases are still accepted and emit a one-time deprecation warning on first use, but will be removed in Phase 7. Migrate flows by renaming the topic string on each inject. + +### From hand-counted internal steps + +Before the `speedUpFactor` field, simulation acceleration required adjusting `timeStep`. The current path is to leave `timeStep` at its physically-meaningful value (~1 s) and crank `speedUpFactor` to advance more process-time per wall-clock second. Old flows with abnormally large `timeStep` should be re-saved with the new field. + +--- + +## Related pages + +| Page | Why | +|:---|:---| +| [Home](Home) | Intuitive overview | +| [Reference — Contracts](Reference-Contracts) | Topic + config + child filters | +| [Reference — Architecture](Reference-Architecture) | Code map, kinetics engines, integration sequence | +| [Reference — Examples](Reference-Examples) | Shipped flows + debug recipes | +| [settler — Limitations](https://gitea.wbd-rd.nl/RnD/settler/wiki/Reference-Limitations) | The downstream Unit's quirks (incl. the historical `getEffluent` shape tolerance) | +| [diffuser wiki](https://gitea.wbd-rd.nl/RnD/diffuser/wiki/Home) | The Equipment node that pushes `data.otr` — not a registered child | diff --git a/wiki/_Sidebar.md b/wiki/_Sidebar.md new file mode 100644 index 0000000..54a2fef --- /dev/null +++ b/wiki/_Sidebar.md @@ -0,0 +1,20 @@ +### reactor + +- [Home](Home) + +**Reference** + +- [Contracts](Reference-Contracts) +- [Architecture](Reference-Architecture) +- [Examples](Reference-Examples) +- [Limitations](Reference-Limitations) + +**Related** + +- [EVOLV master wiki](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Home) +- [settler wiki](https://gitea.wbd-rd.nl/RnD/settler/wiki/Home) +- [diffuser wiki](https://gitea.wbd-rd.nl/RnD/diffuser/wiki/Home) +- [measurement wiki](https://gitea.wbd-rd.nl/RnD/measurement/wiki/Home) +- [Topology Patterns](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topology-Patterns) +- [Topic Conventions](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topic-Conventions) +- [Telemetry](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Telemetry)