Compare commits
12 Commits
main
...
developmen
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46fc8dddf7 | ||
|
|
75d0413994 | ||
|
|
346a3ce2ab | ||
|
|
6b8ae5cfc3 | ||
|
|
cb49bb8b4d | ||
|
|
0e34403c5d | ||
|
|
d735f9485c | ||
|
|
c84dd781a3 | ||
|
|
1aa2d92083 | ||
|
|
297c6713de | ||
|
|
d931bead0a | ||
|
|
7bf464b467 |
17
CLAUDE.md
17
CLAUDE.md
@@ -21,3 +21,20 @@ Key points for this node:
|
|||||||
- Stack same-level siblings vertically.
|
- Stack same-level siblings vertically.
|
||||||
- Parent/children sit on adjacent lanes (children one lane left, parent one lane right).
|
- Parent/children sit on adjacent lanes (children one lane left, parent one lane right).
|
||||||
- Wrap in a Node-RED group box coloured `#50a8d9` (Unit).
|
- Wrap in a Node-RED group box coloured `#50a8d9` (Unit).
|
||||||
|
|
||||||
|
## Folder & File Layout
|
||||||
|
|
||||||
|
Every per-node file MUST use the folder name (`reactor`) **exactly**, case-sensitive. Full rule: [`.claude/rules/node-architecture.md`](https://gitea.wbd-rd.nl/RnD/EVOLV/src/branch/development/.claude/rules/node-architecture.md) in the EVOLV superproject.
|
||||||
|
|
||||||
|
| Path | Required name |
|
||||||
|
|---|---|
|
||||||
|
| Entry file | `reactor.js` |
|
||||||
|
| Editor HTML | `reactor.html` |
|
||||||
|
| Node adapter | `src/nodeClass.js` |
|
||||||
|
| Domain logic | `src/specificClass.js` |
|
||||||
|
| Editor JS modules | `src/editor/*.js` (extract when inline editor JS exceeds ~50 lines) |
|
||||||
|
| Tests | `test/{basic,integration,edge}/*.test.js` |
|
||||||
|
| Example flows | `examples/*.flow.json` |
|
||||||
|
|
||||||
|
|
||||||
|
When adding new files, read the rule above first to avoid drift.
|
||||||
|
|||||||
73
CONTRACT.md
Normal file
73
CONTRACT.md
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
# reactor — Contract
|
||||||
|
|
||||||
|
Hand-maintained for Phase 6; the `## Inputs` table is generated from
|
||||||
|
`src/commands/index.js` (see Phase 9 generator). Keep ≤ 80 lines.
|
||||||
|
|
||||||
|
## Unit convention — approved exception to the canonical-unit rule
|
||||||
|
|
||||||
|
EVOLV's canonical units (`CLAUDE.md`, `generalFunctions/CONTRACT.md`)
|
||||||
|
are Pa / m³/s / W / K. **reactor diverges deliberately** — it follows
|
||||||
|
the ASM (Activated Sludge Model) kinetics literature convention:
|
||||||
|
|
||||||
|
- Concentrations: `mg/L` (= g/m³), `mmol/L` for alkalinity.
|
||||||
|
- Flow internally: `m³/d` (engine integrator runs in days; see
|
||||||
|
`baseEngine.js` line 40 — `timeStep` config field is seconds, but the
|
||||||
|
internal time base is days).
|
||||||
|
- Temperature: `°C`.
|
||||||
|
- KLa: `1/h` per the schema; multiplied by the seconds-input `timeStep`
|
||||||
|
inside `_calcOTR` — readers verifying the math should account for the
|
||||||
|
day-internal time base.
|
||||||
|
|
||||||
|
Unit conversion at the parent/child boundary happens via
|
||||||
|
`MeasurementContainer.UnitPolicy` and the `convert` utility. Other
|
||||||
|
nodes (rotatingMachine, pumpingStation, …) honour canonical units;
|
||||||
|
reactor is the only ASM-modelled node and pays the small cost of
|
||||||
|
domain-textbook units to stay aligned with every published reactor
|
||||||
|
reference.
|
||||||
|
|
||||||
|
## Inputs (msg.topic on Port 0)
|
||||||
|
|
||||||
|
| Canonical | Aliases (deprecated) | Payload | Effect |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `data.clock` | `clock` | `msg.timestamp` (ms since epoch) | Calls `source.updateState(timestamp)` — advances the ASM kinetics integrator by `n_iter` time steps that fit between `currentTime` and the supplied timestamp (scaled by `speedUpFactor`). |
|
||||||
|
| `data.fluent` | `Fluent` | `{ inlet: number, F: number, C: number[13] }` | Writes the per-inlet flow rate (`F`, m³/d) and concentration vector (`C`) into `engine.Fs[inlet]` / `engine.Cs_in[inlet]`. |
|
||||||
|
| `data.otr` | `OTR` | numeric | Sets the externally-supplied oxygen transfer rate (used when `kla` is NaN). |
|
||||||
|
| `data.temperature` | `Temperature` | numeric or `{ value: number }` | Sets `engine.temperature` (°C). Non-numeric payloads are warned and ignored. |
|
||||||
|
| `data.dispersion` | `Dispersion` | numeric | PFR only — sets the axial dispersion coefficient `D` (m²/d). |
|
||||||
|
| `child.register` | `registerChild` | child node id (string) | Looks up the sibling node via `RED.nodes.getNode(id)` and delegates to `source.childRegistrationUtils.registerChild` with `msg.positionVsParent`. |
|
||||||
|
|
||||||
|
Aliases log a one-time deprecation warning the first time they fire.
|
||||||
|
|
||||||
|
## Outputs (msg.topic on Port 0/1/2)
|
||||||
|
|
||||||
|
- **Port 0 (process):** every tick emits the engine's effluent:
|
||||||
|
`{ topic: 'Fluent', payload: { inlet: 0, F, C: number[13] }, timestamp }`.
|
||||||
|
For a PFR an additional `{ topic: 'GridProfile', payload: { grid, n_x, d_x, length, species, timestamp } }`
|
||||||
|
message goes out on the same port before the effluent.
|
||||||
|
- **Port 1 (InfluxDB telemetry):** formatted via `outputUtils.formatMsg(..., 'influxdb')`
|
||||||
|
from `getOutput()` — carries `flow_total`, `temperature`, and one field per ASM3
|
||||||
|
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`).
|
||||||
|
- **Port 2 (registration):** at startup the node sends one
|
||||||
|
`{ topic: 'child.register', payload: <node.id>, positionVsParent, distance }`
|
||||||
|
to its parent.
|
||||||
|
|
||||||
|
## Events emitted by `source.emitter`
|
||||||
|
|
||||||
|
- `stateChange` — fires after every `updateState()` that advances the integrator.
|
||||||
|
Payload is the new `currentTime` (ms since epoch). Downstream reactors register
|
||||||
|
via `child.register` and subscribe to this event to pull the upstream
|
||||||
|
effluent on each advance.
|
||||||
|
- `output-changed` — base notification fired by `updateState()` so the
|
||||||
|
BaseNodeAdapter pipeline pushes outputs (currently used only as a heartbeat;
|
||||||
|
effluent is emitted directly from the periodic tick).
|
||||||
|
|
||||||
|
## Children accepted
|
||||||
|
|
||||||
|
- `measurement` — subscribes to `<type>.measured.<position>` on the child's
|
||||||
|
`measurements.emitter`. Recognised reconciliations: `temperature.measured.atEquipment`
|
||||||
|
writes `engine.temperature`; PFR additionally honours
|
||||||
|
`quantity (oxygen).measured.<distance>` to reconcile dissolved-oxygen
|
||||||
|
concentration into the nearest grid cell.
|
||||||
|
- `reactor` — registers as the upstream reactor; the downstream `updateState`
|
||||||
|
pulls the upstream effluent into `Fs[0]` / `Cs_in[0]` before integrating.
|
||||||
@@ -17,7 +17,10 @@
|
|||||||
"author": "P.R. van der Wilt",
|
"author": "P.R. van der Wilt",
|
||||||
"main": "reactor.js",
|
"main": "reactor.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node --test test/basic/*.test.js test/integration/*.test.js test/edge/*.test.js"
|
"test": "node --test test/basic/*.test.js test/integration/*.test.js test/edge/*.test.js",
|
||||||
|
"wiki:contract": "node ../generalFunctions/scripts/wikiGen.js contract ./src/commands/index.js --write ./wiki/Home.md",
|
||||||
|
"wiki:datamodel": "node ../generalFunctions/scripts/wikiGen.js datamodel ./src/specificClass.js --write ./wiki/Home.md",
|
||||||
|
"wiki:all": "npm run wiki:contract && npm run wiki:datamodel"
|
||||||
},
|
},
|
||||||
"node-red": {
|
"node-red": {
|
||||||
"nodes": {
|
"nodes": {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
<script type="text/javascript">
|
<script type="text/javascript">
|
||||||
RED.nodes.registerType("reactor", {
|
RED.nodes.registerType("reactor", {
|
||||||
category: "EVOLV",
|
category: "EVOLV",
|
||||||
color: "#50a8d9",
|
color: "#6FAE5F",
|
||||||
defaults: {
|
defaults: {
|
||||||
name: { value: "" },
|
name: { value: "" },
|
||||||
reactor_type: { value: "CSTR", required: true },
|
reactor_type: { value: "CSTR", required: true },
|
||||||
@@ -35,7 +35,7 @@
|
|||||||
X_S_init: { value: 75., required: true },
|
X_S_init: { value: 75., required: true },
|
||||||
X_H_init: { value: 30., required: true },
|
X_H_init: { value: 30., required: true },
|
||||||
X_STO_init: { value: 0., required: true },
|
X_STO_init: { value: 0., required: true },
|
||||||
X_A_init: { value: 0.001, required: true },
|
X_A_init: { value: 200, required: true },
|
||||||
X_TS_init: { value: 125.0009, required: true },
|
X_TS_init: { value: 125.0009, required: true },
|
||||||
|
|
||||||
timeStep: { value: 1, required: true },
|
timeStep: { value: 1, required: true },
|
||||||
@@ -267,7 +267,8 @@
|
|||||||
<label for="node-input-dbaseOutputFormat"><i class="fa fa-database"></i> Database Output</label>
|
<label for="node-input-dbaseOutputFormat"><i class="fa fa-database"></i> Database Output</label>
|
||||||
<select id="node-input-dbaseOutputFormat" style="width:60%;">
|
<select id="node-input-dbaseOutputFormat" style="width:60%;">
|
||||||
<option value="influxdb">influxdb</option>
|
<option value="influxdb">influxdb</option>
|
||||||
<option value="json">json</option>
|
<option value="frost">frost</option>
|
||||||
|
<option value="json">json</option>
|
||||||
<option value="csv">csv</option>
|
<option value="csv">csv</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
25
src/commands/handlers.js
Normal file
25
src/commands/handlers.js
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Reactor input handlers. Each receives (source, msg, ctx) where source is
|
||||||
|
// the Reactor domain and ctx is { node, RED, send, logger }. The handlers
|
||||||
|
// either forward to engine setters or drive a synchronous state update.
|
||||||
|
|
||||||
|
exports.dataClock = (source, msg) => {
|
||||||
|
source.updateState(msg.timestamp ?? Date.now());
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.dataFluent = (source, msg) => { source.setInfluent = msg; };
|
||||||
|
exports.dataOTR = (source, msg) => { source.setOTR = msg; };
|
||||||
|
exports.dataTemperature = (source, msg) => { source.setTemperature = msg; };
|
||||||
|
exports.dataDispersion = (source, msg) => { source.setDispersion = msg; };
|
||||||
|
|
||||||
|
exports.childRegister = (source, msg, ctx) => {
|
||||||
|
const childId = msg.payload;
|
||||||
|
const RED = ctx?.RED;
|
||||||
|
const childObj = RED?.nodes?.getNode?.(childId);
|
||||||
|
if (!childObj || !childObj.source) {
|
||||||
|
source?.logger?.warn?.(`registerChild skipped: missing child/source for id=${childId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
source.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
|
||||||
|
};
|
||||||
55
src/commands/index.js
Normal file
55
src/commands/index.js
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// reactor command registry. Canonical names follow CONTRACTS.md §1.
|
||||||
|
// Legacy names (clock, Fluent, OTR, Temperature, Dispersion, registerChild)
|
||||||
|
// stay as aliases — they log a one-time deprecation warning on first use
|
||||||
|
// and are removed in Phase 7.
|
||||||
|
|
||||||
|
const handlers = require('./handlers');
|
||||||
|
|
||||||
|
module.exports = [
|
||||||
|
{
|
||||||
|
topic: 'data.clock',
|
||||||
|
aliases: ['clock'],
|
||||||
|
payloadSchema: { type: 'any' },
|
||||||
|
description: 'Push the simulation clock tick (timestamp / dt) to the ASM solver.',
|
||||||
|
handler: handlers.dataClock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
topic: 'data.fluent',
|
||||||
|
aliases: ['Fluent'],
|
||||||
|
payloadSchema: { type: 'object' },
|
||||||
|
// Compound payload `{F, C: [...]}` — registry-level units normalisation is
|
||||||
|
// skipped (the handler converts per-field internally).
|
||||||
|
description: 'Push the influent stream (payload: {F: flow m3/h, C: [concentrations mg/L]}).',
|
||||||
|
handler: handlers.dataFluent,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
topic: 'data.otr',
|
||||||
|
aliases: ['OTR'],
|
||||||
|
payloadSchema: { type: 'any' },
|
||||||
|
description: 'Push the current oxygen-transfer rate into the reactor.',
|
||||||
|
handler: handlers.dataOTR,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
topic: 'data.temperature',
|
||||||
|
aliases: ['Temperature'],
|
||||||
|
payloadSchema: { type: 'any' },
|
||||||
|
description: 'Push the current reactor temperature.',
|
||||||
|
handler: handlers.dataTemperature,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
topic: 'data.dispersion',
|
||||||
|
aliases: ['Dispersion'],
|
||||||
|
payloadSchema: { type: 'any' },
|
||||||
|
description: 'Push a dispersion/mixing parameter update.',
|
||||||
|
handler: handlers.dataDispersion,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
topic: 'child.register',
|
||||||
|
aliases: ['registerChild'],
|
||||||
|
payloadSchema: { type: 'any' },
|
||||||
|
description: 'Register a child node (settler / measurement) with this reactor.',
|
||||||
|
handler: handlers.childRegister,
|
||||||
|
},
|
||||||
|
];
|
||||||
139
src/kinetics/baseEngine.js
Normal file
139
src/kinetics/baseEngine.js
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const EventEmitter = require('events');
|
||||||
|
const ASM3 = require('../reaction_modules/asm3_class.js');
|
||||||
|
const { create, all } = require('mathjs');
|
||||||
|
const { childRegistrationUtils, logger, MeasurementContainer, POSITIONS } = require('generalFunctions');
|
||||||
|
|
||||||
|
const math = create(all, { matrix: 'Array' });
|
||||||
|
|
||||||
|
const S_O_INDEX = 0;
|
||||||
|
const NUM_SPECIES = 13;
|
||||||
|
|
||||||
|
// Abstract reactor engine. Holds the influent/OTR/temperature state plus
|
||||||
|
// the parent-side child registration that the original Reactor class
|
||||||
|
// exposed. Concrete CSTR / PFR subclasses provide tick().
|
||||||
|
class BaseReactorEngine {
|
||||||
|
constructor(config) {
|
||||||
|
this.config = config;
|
||||||
|
this.logger = new logger(
|
||||||
|
this.config.general.logging.enabled,
|
||||||
|
this.config.general.logging.logLevel,
|
||||||
|
config.general.name,
|
||||||
|
);
|
||||||
|
this.emitter = new EventEmitter();
|
||||||
|
this.measurements = new MeasurementContainer();
|
||||||
|
this.upstreamReactor = null;
|
||||||
|
this.childRegistrationUtils = new childRegistrationUtils(this);
|
||||||
|
|
||||||
|
this.asm = new ASM3();
|
||||||
|
this.volume = config.volume;
|
||||||
|
|
||||||
|
this.Fs = Array(config.n_inlets).fill(0);
|
||||||
|
this.Cs_in = Array.from(Array(config.n_inlets), () => new Array(NUM_SPECIES).fill(0));
|
||||||
|
this.OTR = 0.0;
|
||||||
|
this.temperature = 20;
|
||||||
|
|
||||||
|
this.kla = config.kla;
|
||||||
|
this.currentTime = Date.now();
|
||||||
|
// timeStep stored in days (the integrator uses [d] internally).
|
||||||
|
this.timeStep = (1 / (24 * 60 * 60)) * this.config.timeStep;
|
||||||
|
this.speedUpFactor = config.speedUpFactor ?? 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
set setInfluent(input) {
|
||||||
|
const index_in = input.payload.inlet;
|
||||||
|
this.Fs[index_in] = input.payload.F;
|
||||||
|
this.Cs_in[index_in] = input.payload.C;
|
||||||
|
}
|
||||||
|
|
||||||
|
set setOTR(input) { this.OTR = input.payload; }
|
||||||
|
|
||||||
|
set setTemperature(input) {
|
||||||
|
const p = input?.payload;
|
||||||
|
const raw = (p && typeof p === 'object' && p.value !== undefined) ? p.value : p;
|
||||||
|
const v = Number(raw);
|
||||||
|
if (!Number.isFinite(v)) { this.logger.warn(`Invalid temperature input: ${raw}`); return; }
|
||||||
|
this.temperature = v;
|
||||||
|
}
|
||||||
|
|
||||||
|
get getEffluent() {
|
||||||
|
const last = Array.isArray(this.state.at?.(-1)) ? this.state.at(-1) : this.state;
|
||||||
|
return { topic: 'Fluent', payload: { inlet: 0, F: math.sum(this.Fs), C: last }, timestamp: this.currentTime };
|
||||||
|
}
|
||||||
|
|
||||||
|
get getGridProfile() { return null; }
|
||||||
|
|
||||||
|
_calcOTR(S_O, T = 20.0) {
|
||||||
|
const sat = this._calcOxygenSaturation(T);
|
||||||
|
return this.kla * (sat - S_O);
|
||||||
|
}
|
||||||
|
|
||||||
|
_calcOxygenSaturation(T = 20.0) {
|
||||||
|
return 14.652 - 4.1022e-1 * T + 7.9910e-3 * T * T + 7.7774e-5 * T * T * T;
|
||||||
|
}
|
||||||
|
|
||||||
|
_capDissolvedOxygen(state) {
|
||||||
|
const sat = this._calcOxygenSaturation(this.temperature);
|
||||||
|
const capRow = (row) => {
|
||||||
|
if (!Array.isArray(row)) return row;
|
||||||
|
const next = row.slice();
|
||||||
|
if (Number.isFinite(next[S_O_INDEX])) next[S_O_INDEX] = Math.max(0, Math.min(next[S_O_INDEX], sat));
|
||||||
|
return next;
|
||||||
|
};
|
||||||
|
return (Array.isArray(state) && Array.isArray(state[0])) ? state.map(capRow) : capRow(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
_arrayClip2Zero(arr) {
|
||||||
|
if (Array.isArray(arr)) return arr.map((x) => this._arrayClip2Zero(x));
|
||||||
|
return arr < 0 ? 0 : arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
registerChild(child, softwareType) {
|
||||||
|
switch (softwareType) {
|
||||||
|
case 'measurement': this._connectMeasurement(child); break;
|
||||||
|
case 'reactor': this._connectReactor(child); break;
|
||||||
|
default: this.logger.error(`Unrecognized softwareType: ${softwareType}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_connectMeasurement(measurement) {
|
||||||
|
if (!measurement) { this.logger.warn('Invalid measurement provided.'); return; }
|
||||||
|
const fn = measurement.config.functionality;
|
||||||
|
const position = fn.distance !== 'undefined' ? fn.distance : fn.positionVsParent;
|
||||||
|
const measurementType = measurement.config.asset.type;
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
_connectReactor(reactor) {
|
||||||
|
if (!reactor) { this.logger.warn('Invalid reactor provided.'); return; }
|
||||||
|
this.upstreamReactor = reactor;
|
||||||
|
reactor.emitter.on('stateChange', (data) => this.updateState(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
_updateMeasurement(measurementType, value, position) {
|
||||||
|
if (measurementType === 'temperature' && position === POSITIONS.AT_EQUIPMENT) {
|
||||||
|
this.temperature = value;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.logger.error(`Type '${measurementType}' not recognized for measured update.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateState(newTime = Date.now()) {
|
||||||
|
const day2ms = 1000 * 60 * 60 * 24;
|
||||||
|
if (this.upstreamReactor) this.setInfluent = this.upstreamReactor.getEffluent;
|
||||||
|
const n_iter = Math.floor(this.speedUpFactor * (newTime - this.currentTime) / (this.timeStep * day2ms));
|
||||||
|
if (!n_iter) return;
|
||||||
|
for (let n = 0; n < n_iter; n += 1) this.tick(this.timeStep);
|
||||||
|
this.currentTime += (n_iter * this.timeStep * day2ms) / this.speedUpFactor;
|
||||||
|
this.emitter.emit('stateChange', this.currentTime);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { BaseReactorEngine, math, S_O_INDEX, NUM_SPECIES };
|
||||||
27
src/kinetics/cstr.js
Normal file
27
src/kinetics/cstr.js
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { BaseReactorEngine, math, S_O_INDEX, NUM_SPECIES } = require('./baseEngine.js');
|
||||||
|
|
||||||
|
class Reactor_CSTR extends BaseReactorEngine {
|
||||||
|
constructor(config) {
|
||||||
|
super(config);
|
||||||
|
this.state = config.initialState;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forward Euler step over `time_step` days.
|
||||||
|
tick(time_step) {
|
||||||
|
const inflow = math.multiply(math.divide([this.Fs], this.volume), this.Cs_in)[0];
|
||||||
|
const outflow = math.multiply(-1 * math.sum(this.Fs) / this.volume, this.state);
|
||||||
|
const reaction = this.asm.compute_dC(this.state, this.temperature);
|
||||||
|
const transfer = Array(NUM_SPECIES).fill(0.0);
|
||||||
|
transfer[S_O_INDEX] = isNaN(this.kla)
|
||||||
|
? this.OTR
|
||||||
|
: this._calcOTR(this.state[S_O_INDEX], this.temperature);
|
||||||
|
|
||||||
|
const dC_total = math.multiply(math.add(inflow, outflow, reaction, transfer), time_step);
|
||||||
|
this.state = this._capDissolvedOxygen(this._arrayClip2Zero(math.add(this.state, dC_total)));
|
||||||
|
return this.state;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = Reactor_CSTR;
|
||||||
132
src/kinetics/pfr.js
Normal file
132
src/kinetics/pfr.js
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { assertNoNaN } = require('../utils.js');
|
||||||
|
const { BaseReactorEngine, math, S_O_INDEX, NUM_SPECIES } = require('./baseEngine.js');
|
||||||
|
|
||||||
|
class Reactor_PFR extends BaseReactorEngine {
|
||||||
|
constructor(config) {
|
||||||
|
super(config);
|
||||||
|
|
||||||
|
this.length = config.length;
|
||||||
|
this.n_x = config.resolution_L;
|
||||||
|
this.d_x = this.length / this.n_x;
|
||||||
|
this.A = this.volume / this.length;
|
||||||
|
this.alpha = config.alpha;
|
||||||
|
|
||||||
|
this.state = Array.from(Array(this.n_x), () => config.initialState.slice());
|
||||||
|
this.D = 0.0;
|
||||||
|
|
||||||
|
this.D_op = this._makeDoperator(true, true);
|
||||||
|
this.D2_op = this._makeD2operator();
|
||||||
|
assertNoNaN(this.D_op, 'Derivative operator');
|
||||||
|
assertNoNaN(this.D2_op, 'Second derivative operator');
|
||||||
|
}
|
||||||
|
|
||||||
|
get getGridProfile() {
|
||||||
|
return {
|
||||||
|
grid: this.state.map((row) => row.slice()),
|
||||||
|
n_x: this.n_x,
|
||||||
|
d_x: this.d_x,
|
||||||
|
length: this.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: this.currentTime,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
set setDispersion(input) { this.D = input.payload; }
|
||||||
|
|
||||||
|
updateState(newTime) {
|
||||||
|
super.updateState(newTime);
|
||||||
|
const Pe_local = (this.d_x * math.sum(this.Fs)) / (this.D * this.A);
|
||||||
|
const Co_D = (this.D * this.timeStep) / (this.d_x * this.d_x);
|
||||||
|
if (Pe_local >= 2) this.logger.warn(`Local Peclet number (${Pe_local}) is too high! Increase reactor resolution.`);
|
||||||
|
if (Co_D >= 0.5) this.logger.warn(`Courant number (${Co_D}) is too high! Reduce time step size.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Explicit finite-difference step over `time_step` days.
|
||||||
|
tick(time_step) {
|
||||||
|
const dispersion = math.multiply(this.D / (this.d_x * this.d_x), this.D2_op, this.state);
|
||||||
|
const advection = math.multiply(-1 * math.sum(this.Fs) / (this.A * this.d_x), this.D_op, this.state);
|
||||||
|
const reaction = this.state.map((slice) => this.asm.compute_dC(slice, this.temperature));
|
||||||
|
const transfer = Array.from(Array(this.n_x), () => new Array(NUM_SPECIES).fill(0));
|
||||||
|
|
||||||
|
const klaIsNaN = isNaN(this.kla);
|
||||||
|
for (let i = 1; i < this.n_x - 1; i += 1) {
|
||||||
|
const otr = klaIsNaN ? this.OTR : this._calcOTR(this.state[i][S_O_INDEX], this.temperature);
|
||||||
|
transfer[i][S_O_INDEX] = otr * this.n_x / (this.n_x - 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dC_total = math.multiply(math.add(dispersion, advection, reaction, transfer), time_step);
|
||||||
|
const stateNew = math.add(this.state, dC_total);
|
||||||
|
this._applyBoundaryConditions(stateNew);
|
||||||
|
this.state = this._capDissolvedOxygen(this._arrayClip2Zero(stateNew));
|
||||||
|
return stateNew;
|
||||||
|
}
|
||||||
|
|
||||||
|
_updateMeasurement(measurementType, value, position, context) {
|
||||||
|
if (measurementType === 'quantity (oxygen)') {
|
||||||
|
if (!Number.isFinite(position) || !Number.isFinite(value) || this.config.length <= 0) {
|
||||||
|
this.logger.warn(`Ignoring oxygen measurement update with invalid data (position=${position}, value=${value}).`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rawIndex = Math.round((position / this.config.length) * this.n_x);
|
||||||
|
const grid_pos = Math.max(0, Math.min(this.n_x - 1, rawIndex));
|
||||||
|
this.state[grid_pos][S_O_INDEX] = value;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super._updateMeasurement(measurementType, value, position, context);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generalised Danckwerts at inlet when flow > 0; Neumann (no-flux) at outlet
|
||||||
|
// and at inlet when there is no flow.
|
||||||
|
_applyBoundaryConditions(state) {
|
||||||
|
if (math.sum(this.Fs) > 0) {
|
||||||
|
const BC_C_in = math.multiply(1 / math.sum(this.Fs), [this.Fs], this.Cs_in)[0];
|
||||||
|
const BC_disp = ((1 - this.alpha) * this.D * this.A) / (math.sum(this.Fs) * this.d_x);
|
||||||
|
state[0] = math.multiply(1 / (1 + BC_disp), math.add(BC_C_in, math.multiply(BC_disp, state[1])));
|
||||||
|
} else {
|
||||||
|
state[0] = state[1];
|
||||||
|
}
|
||||||
|
state[this.n_x - 1] = state[this.n_x - 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
_makeDoperator(central = false, higher_order = false) {
|
||||||
|
if (higher_order) {
|
||||||
|
if (!central) throw new Error('Upwind higher order method not implemented! Use central scheme instead.');
|
||||||
|
const I = math.resize(math.diag(Array(this.n_x).fill(1 / 12), -2), [this.n_x, this.n_x]);
|
||||||
|
const A = math.resize(math.diag(Array(this.n_x).fill(-2 / 3), -1), [this.n_x, this.n_x]);
|
||||||
|
const B = math.resize(math.diag(Array(this.n_x).fill(2 / 3), 1), [this.n_x, this.n_x]);
|
||||||
|
const C = math.resize(math.diag(Array(this.n_x).fill(-1 / 12), 2), [this.n_x, this.n_x]);
|
||||||
|
const D = math.add(I, A, B, C);
|
||||||
|
// Preserve the pre-refactor aliasing: D[1] = NearBoundary; NearBoundary.reverse()
|
||||||
|
// mutates D[1] in place; then D[n_x-2] = -1 * NearBoundary uses the reversed view.
|
||||||
|
const nb = Array(this.n_x).fill(0.0);
|
||||||
|
nb[0] = -1 / 4; nb[1] = -5 / 6; nb[2] = 3 / 2; nb[3] = -1 / 2; nb[4] = 1 / 12;
|
||||||
|
D[1] = nb;
|
||||||
|
nb.reverse();
|
||||||
|
D[this.n_x - 2] = math.multiply(-1, nb);
|
||||||
|
D[0] = Array(this.n_x).fill(0);
|
||||||
|
D[this.n_x - 1] = Array(this.n_x).fill(0);
|
||||||
|
return D;
|
||||||
|
}
|
||||||
|
const I = math.resize(math.diag(Array(this.n_x).fill(1 / (1 + central)), central), [this.n_x, this.n_x]);
|
||||||
|
const A = math.resize(math.diag(Array(this.n_x).fill(-1 / (1 + central)), -1), [this.n_x, this.n_x]);
|
||||||
|
const D = math.add(I, A);
|
||||||
|
D[0] = Array(this.n_x).fill(0);
|
||||||
|
D[this.n_x - 1] = Array(this.n_x).fill(0);
|
||||||
|
return D;
|
||||||
|
}
|
||||||
|
|
||||||
|
_makeD2operator() {
|
||||||
|
const I = math.diag(Array(this.n_x).fill(-2), 0);
|
||||||
|
const A = math.resize(math.diag(Array(this.n_x).fill(1), 1), [this.n_x, this.n_x]);
|
||||||
|
const B = math.resize(math.diag(Array(this.n_x).fill(1), -1), [this.n_x, this.n_x]);
|
||||||
|
const D2 = math.add(I, A, B);
|
||||||
|
D2[0] = Array(this.n_x).fill(0);
|
||||||
|
D2[this.n_x - 1] = Array(this.n_x).fill(0);
|
||||||
|
return D2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = Reactor_PFR;
|
||||||
245
src/nodeClass.js
245
src/nodeClass.js
@@ -1,208 +1,53 @@
|
|||||||
const { Reactor_CSTR, Reactor_PFR } = require('./specificClass.js');
|
'use strict';
|
||||||
const { outputUtils, configManager } = require('generalFunctions');
|
|
||||||
|
|
||||||
const REACTOR_SPECIES = [
|
const { BaseNodeAdapter } = require('generalFunctions');
|
||||||
'S_O',
|
const Reactor = require('./specificClass.js');
|
||||||
'S_I',
|
const commands = require('./commands');
|
||||||
'S_S',
|
|
||||||
'S_NH',
|
|
||||||
'S_N2',
|
|
||||||
'S_NO',
|
|
||||||
'S_HCO',
|
|
||||||
'X_I',
|
|
||||||
'X_S',
|
|
||||||
'X_H',
|
|
||||||
'X_STO',
|
|
||||||
'X_A',
|
|
||||||
'X_TS'
|
|
||||||
];
|
|
||||||
|
|
||||||
|
const 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'];
|
||||||
|
|
||||||
class nodeClass {
|
class nodeClass extends BaseNodeAdapter {
|
||||||
/**
|
static DomainClass = Reactor;
|
||||||
* Node-RED node class for advanced-reactor.
|
static commands = commands;
|
||||||
* @param {object} uiConfig - Node-RED node configuration
|
// Tick-driven: ASM kinetics integrate over wall-clock time. The engine's
|
||||||
* @param {object} RED - Node-RED runtime API
|
// updateState computes how many internal Euler/FD steps fit in the elapsed
|
||||||
* @param {object} nodeInstance - Node-RED node instance
|
// ms; without a periodic tick the integrator never advances.
|
||||||
* @param {string} nameOfNode - Name of the node
|
static tickInterval = 1000;
|
||||||
*/
|
static statusInterval = 1000;
|
||||||
constructor(uiConfig, RED, nodeInstance, nameOfNode) {
|
|
||||||
// Preserve RED reference for HTTP endpoints if needed
|
|
||||||
this.node = nodeInstance;
|
|
||||||
this.RED = RED;
|
|
||||||
this.name = nameOfNode;
|
|
||||||
this.source = null;
|
|
||||||
|
|
||||||
this._loadConfig(uiConfig)
|
buildDomainConfig(uiConfig) {
|
||||||
this._setupClass();
|
const initialState = {};
|
||||||
this._output = new outputUtils();
|
for (const k of SPECIES) initialState[k] = parseFloat(uiConfig[`${k}_init`]);
|
||||||
|
return {
|
||||||
|
reactor: {
|
||||||
|
reactor_type: uiConfig.reactor_type,
|
||||||
|
volume: parseFloat(uiConfig.volume),
|
||||||
|
length: parseFloat(uiConfig.length),
|
||||||
|
resolution_L: parseInt(uiConfig.resolution_L, 10),
|
||||||
|
alpha: parseFloat(uiConfig.alpha),
|
||||||
|
n_inlets: parseInt(uiConfig.n_inlets, 10),
|
||||||
|
kla: parseFloat(uiConfig.kla),
|
||||||
|
timeStep: parseFloat(uiConfig.timeStep),
|
||||||
|
speedUpFactor: Number(uiConfig.speedUpFactor) || 1,
|
||||||
|
},
|
||||||
|
initialState,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
this._attachInputHandler();
|
// The kinetics engine drives Port-0 effluent + grid-profile shapes that
|
||||||
this._registerChild();
|
// don't fit BaseNodeAdapter's delta-compressed payload. Override the
|
||||||
this._startTickLoop();
|
// periodic emission so the Fluent / GridProfile contract is preserved.
|
||||||
this._attachCloseHandler();
|
_emitOutputs() {
|
||||||
}
|
const src = this.source;
|
||||||
|
if (!src?.engine) return;
|
||||||
/**
|
src.updateState(Date.now());
|
||||||
* Handle node-red input messages
|
const grid = src.getGridProfile;
|
||||||
*/
|
if (grid) this.node.send([{ topic: 'GridProfile', payload: grid }, null, null]);
|
||||||
_attachInputHandler() {
|
const raw = src.getOutput();
|
||||||
this.node.on('input', (msg, send, done) => {
|
const influx = this._output.formatMsg(raw, src.config || this.config, 'influxdb');
|
||||||
try {
|
this.node.send([src.getEffluent, influx, null]);
|
||||||
switch (msg.topic) {
|
}
|
||||||
case "clock":
|
|
||||||
this.source.updateState(msg.timestamp);
|
|
||||||
send([msg, null, null]);
|
|
||||||
break;
|
|
||||||
case "Fluent":
|
|
||||||
this.source.setInfluent = msg;
|
|
||||||
break;
|
|
||||||
case "OTR":
|
|
||||||
this.source.setOTR = msg;
|
|
||||||
break;
|
|
||||||
case "Temperature":
|
|
||||||
this.source.setTemperature = msg;
|
|
||||||
break;
|
|
||||||
case "Dispersion":
|
|
||||||
this.source.setDispersion = msg;
|
|
||||||
break;
|
|
||||||
case 'registerChild': {
|
|
||||||
const childId = msg.payload;
|
|
||||||
const childObj = this.RED.nodes.getNode(childId);
|
|
||||||
if (!childObj || !childObj.source) {
|
|
||||||
this.source?.logger?.warn(`registerChild skipped: missing child/source for id=${childId}`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
this.source.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
this.source?.logger?.warn(`Unknown topic: ${msg.topic}`);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
this.source?.logger?.error(`Input handler failure: ${error.message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof done === 'function') {
|
|
||||||
done();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse node configuration using ConfigManager
|
|
||||||
* @param {object} uiConfig Config set in UI in node-red
|
|
||||||
*/
|
|
||||||
_loadConfig(uiConfig) {
|
|
||||||
const cfgMgr = new configManager();
|
|
||||||
|
|
||||||
// Build config: base sections + reactor-specific domain config
|
|
||||||
this.config = cfgMgr.buildConfig('reactor', uiConfig, this.node.id, {
|
|
||||||
reactor_type: uiConfig.reactor_type,
|
|
||||||
volume: parseFloat(uiConfig.volume),
|
|
||||||
length: parseFloat(uiConfig.length),
|
|
||||||
resolution_L: parseInt(uiConfig.resolution_L),
|
|
||||||
alpha: parseFloat(uiConfig.alpha),
|
|
||||||
n_inlets: parseInt(uiConfig.n_inlets),
|
|
||||||
kla: parseFloat(uiConfig.kla),
|
|
||||||
initialState: [
|
|
||||||
parseFloat(uiConfig.S_O_init),
|
|
||||||
parseFloat(uiConfig.S_I_init),
|
|
||||||
parseFloat(uiConfig.S_S_init),
|
|
||||||
parseFloat(uiConfig.S_NH_init),
|
|
||||||
parseFloat(uiConfig.S_N2_init),
|
|
||||||
parseFloat(uiConfig.S_NO_init),
|
|
||||||
parseFloat(uiConfig.S_HCO_init),
|
|
||||||
parseFloat(uiConfig.X_I_init),
|
|
||||||
parseFloat(uiConfig.X_S_init),
|
|
||||||
parseFloat(uiConfig.X_H_init),
|
|
||||||
parseFloat(uiConfig.X_STO_init),
|
|
||||||
parseFloat(uiConfig.X_A_init),
|
|
||||||
parseFloat(uiConfig.X_TS_init)
|
|
||||||
],
|
|
||||||
timeStep: parseFloat(uiConfig.timeStep),
|
|
||||||
speedUpFactor: Number(uiConfig.speedUpFactor) || 1
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register this node as a child upstream and downstream.
|
|
||||||
* Delayed to avoid Node-RED startup race conditions.
|
|
||||||
*/
|
|
||||||
_registerChild() {
|
|
||||||
setTimeout(() => {
|
|
||||||
this.node.send([
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
{ topic: 'registerChild', payload: this.node.id, positionVsParent: this.config?.functionality?.positionVsParent || 'atEquipment' }
|
|
||||||
]);
|
|
||||||
}, 100);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Setup reactor class based on config
|
|
||||||
*/
|
|
||||||
_setupClass() {
|
|
||||||
let new_reactor;
|
|
||||||
|
|
||||||
switch (this.config.reactor_type) {
|
|
||||||
case "CSTR":
|
|
||||||
new_reactor = new Reactor_CSTR(this.config);
|
|
||||||
break;
|
|
||||||
case "PFR":
|
|
||||||
new_reactor = new Reactor_PFR(this.config);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
this.node.warn("Unknown reactor type: " + this.config.reactor_type + ". Falling back to CSTR.");
|
|
||||||
new_reactor = new Reactor_CSTR(this.config);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.source = new_reactor; // protect from reassignment
|
|
||||||
this.node.source = this.source;
|
|
||||||
}
|
|
||||||
|
|
||||||
_startTickLoop() {
|
|
||||||
setTimeout(() => {
|
|
||||||
this._tickInterval = setInterval(() => this._tick(), 1000);
|
|
||||||
}, 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
_tick(){
|
|
||||||
const gridProfile = this.source.getGridProfile;
|
|
||||||
if (gridProfile) {
|
|
||||||
this.node.send([{ topic: "GridProfile", payload: gridProfile }, null, null]);
|
|
||||||
}
|
|
||||||
this.node.send([this.source.getEffluent, this._buildTelemetryMessage(), null]);
|
|
||||||
}
|
|
||||||
|
|
||||||
_buildTelemetryMessage() {
|
|
||||||
const effluent = this.source?.getEffluent;
|
|
||||||
const concentrations = effluent?.payload?.C;
|
|
||||||
if (!Array.isArray(concentrations)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const telemetry = {
|
|
||||||
flow_total: Number(effluent.payload.F),
|
|
||||||
temperature: Number(this.source?.temperature),
|
|
||||||
};
|
|
||||||
|
|
||||||
for (let i = 0; i < Math.min(REACTOR_SPECIES.length, concentrations.length); i += 1) {
|
|
||||||
const value = Number(concentrations[i]);
|
|
||||||
if (Number.isFinite(value)) {
|
|
||||||
telemetry[REACTOR_SPECIES[i]] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return this._output.formatMsg(telemetry, this.config, 'influxdb');
|
|
||||||
}
|
|
||||||
|
|
||||||
_attachCloseHandler() {
|
|
||||||
this.node.on('close', (done) => {
|
|
||||||
clearInterval(this._tickInterval);
|
|
||||||
if (typeof done === 'function') done();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = nodeClass;
|
module.exports = nodeClass;
|
||||||
|
|||||||
@@ -1,481 +1,134 @@
|
|||||||
const ASM3 = require('./reaction_modules/asm3_class.js');
|
'use strict';
|
||||||
const { create, all, isArray } = require('mathjs');
|
|
||||||
const { assertNoNaN } = require('./utils.js');
|
|
||||||
const { childRegistrationUtils, logger, MeasurementContainer, POSITIONS } = require('generalFunctions');
|
|
||||||
const EventEmitter = require('events');
|
|
||||||
|
|
||||||
const mathConfig = {
|
const { BaseDomain, statusBadge, POSITIONS } = require('generalFunctions');
|
||||||
matrix: 'Array' // use Array as the matrix type
|
const Reactor_CSTR = require('./kinetics/cstr.js');
|
||||||
};
|
const Reactor_PFR = require('./kinetics/pfr.js');
|
||||||
|
|
||||||
const math = create(all, mathConfig);
|
const SPECIES_KEYS = ['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'];
|
||||||
|
|
||||||
const S_O_INDEX = 0;
|
// Reactor — biological reactor orchestrator (Unit-level). Wraps a CSTR or
|
||||||
const NUM_SPECIES = 13;
|
// PFR kinetics engine and exposes the BaseDomain surface to BaseNodeAdapter.
|
||||||
const DEBUG = false;
|
// The engines own the ASM3 integration; this class wires child registration
|
||||||
|
// through ChildRouter, holds the validated config, and presents getOutput /
|
||||||
|
// getStatusBadge.
|
||||||
|
class Reactor extends BaseDomain {
|
||||||
|
static name = 'reactor';
|
||||||
|
|
||||||
class Reactor {
|
configure() {
|
||||||
/**
|
const flat = this._flattenEngineConfig(this.config);
|
||||||
* Reactor base class.
|
this.engine = this._buildEngine(flat);
|
||||||
* @param {object} config - Configuration object containing reactor parameters.
|
|
||||||
*/
|
|
||||||
constructor(config) {
|
|
||||||
this.config = config;
|
|
||||||
// EVOLV stuff
|
|
||||||
this.logger = new logger(this.config.general.logging.enabled, this.config.general.logging.logLevel, config.general.name);
|
|
||||||
this.emitter = new EventEmitter();
|
|
||||||
this.measurements = new MeasurementContainer();
|
|
||||||
this.upstreamReactor = null;
|
|
||||||
this.childRegistrationUtils = new childRegistrationUtils(this); // Child registration utility
|
|
||||||
|
|
||||||
this.asm = new ASM3();
|
// Re-emit upstream-reactor stateChange and engine stateChange events on
|
||||||
|
// the BaseDomain emitter so adapter listeners pick them up uniformly.
|
||||||
|
this.engine.emitter.on('stateChange', (t) => this.emitter.emit('stateChange', t));
|
||||||
|
|
||||||
this.volume = config.volume; // fluid volume reactor [m3]
|
// ChildRouter dispatches to engine handlers — keeps the existing
|
||||||
|
// _connectMeasurement / _connectReactor wiring intact, just centralised.
|
||||||
|
this.router.onRegister('measurement', (child) => this.engine._connectMeasurement(child));
|
||||||
|
this.router.onRegister('reactor', (child) => this.engine._connectReactor(child));
|
||||||
|
|
||||||
this.Fs = Array(config.n_inlets).fill(0); // fluid debits per inlet [m3 d-1]
|
// Bridge engine.measurements into the BaseDomain measurements container
|
||||||
this.Cs_in = Array.from(Array(config.n_inlets), () => new Array(NUM_SPECIES).fill(0)); // composition influents
|
// so getFlattenedOutput surfaces temperature / oxygen series.
|
||||||
this.OTR = 0.0; // oxygen transfer rate [g O2 d-1 m-3]
|
this.measurements = this.engine.measurements;
|
||||||
this.temperature = 20; // temperature [C]
|
|
||||||
|
|
||||||
this.kla = config.kla; // if NaN, use externaly provided OTR [d-1]
|
|
||||||
|
|
||||||
this.currentTime = Date.now(); // milliseconds since epoch [ms]
|
|
||||||
this.timeStep = 1 / (24*60*60) * this.config.timeStep; // time step in seconds, converted to days.
|
|
||||||
this.speedUpFactor = config.speedUpFactor ?? 1; // speed up factor for simulation
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Translate the nested schema config (reactor.*, initialState.*) into the
|
||||||
* Setter for influent data.
|
// flat shape the kinetics engines accept.
|
||||||
* @param {object} input - Input object (msg) containing payload with inlet index, flow rate, and concentrations.
|
_flattenEngineConfig(config) {
|
||||||
*/
|
const reactor = config.reactor || {};
|
||||||
set setInfluent(input) {
|
const init = config.initialState || {};
|
||||||
let index_in = input.payload.inlet;
|
const initialState = SPECIES_KEYS.map((k) => Number(init[k] ?? 0));
|
||||||
this.Fs[index_in] = input.payload.F;
|
|
||||||
this.Cs_in[index_in] = input.payload.C;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Setter for OTR (Oxygen Transfer Rate).
|
|
||||||
* @param {object} input - Input object (msg) containing payload with OTR value [g O2 d-1 m-3].
|
|
||||||
*/
|
|
||||||
set setOTR(input) {
|
|
||||||
this.OTR = input.payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Setter for reactor temperature [C].
|
|
||||||
* Accepts either a direct numeric payload or { value } object payload.
|
|
||||||
* @param {object} input - Input object (msg)
|
|
||||||
*/
|
|
||||||
set setTemperature(input) {
|
|
||||||
const payload = input?.payload;
|
|
||||||
const rawValue = (payload && typeof payload === 'object' && payload.value !== undefined)
|
|
||||||
? payload.value
|
|
||||||
: payload;
|
|
||||||
const parsedValue = Number(rawValue);
|
|
||||||
if (!Number.isFinite(parsedValue)) {
|
|
||||||
this.logger.warn(`Invalid temperature input: ${rawValue}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.temperature = parsedValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Getter for effluent data.
|
|
||||||
* @returns {object} Effluent data object (msg), defaults to inlet 0.
|
|
||||||
*/
|
|
||||||
get getEffluent() { // getter for Effluent, defaults to inlet 0
|
|
||||||
if (isArray(this.state.at(-1))) {
|
|
||||||
return { topic: "Fluent", payload: { inlet: 0, F: math.sum(this.Fs), C: this.state.at(-1) }, timestamp: this.currentTime };
|
|
||||||
}
|
|
||||||
return { topic: "Fluent", payload: { inlet: 0, F: math.sum(this.Fs), C: this.state }, timestamp: this.currentTime };
|
|
||||||
}
|
|
||||||
|
|
||||||
get getGridProfile() { return null; }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Calculate the oxygen transfer rate (OTR) based on the dissolved oxygen concentration and temperature.
|
|
||||||
* @param {number} S_O - Dissolved oxygen concentration [g O2 m-3].
|
|
||||||
* @param {number} T - Temperature in Celsius, default to 20 C.
|
|
||||||
* @returns {number} - Calculated OTR [g O2 d-1 m-3].
|
|
||||||
*/
|
|
||||||
_calcOTR(S_O, T = 20.0) { // caculate the OTR using basic correlation, default to temperature: 20 C
|
|
||||||
let S_O_sat = 14.652 - 4.1022e-1 * T + 7.9910e-3 * T*T + 7.7774e-5 * T*T*T;
|
|
||||||
return this.kla * (S_O_sat - S_O);
|
|
||||||
}
|
|
||||||
|
|
||||||
_calcOxygenSaturation(T = 20.0) {
|
|
||||||
return 14.652 - 4.1022e-1 * T + 7.9910e-3 * T*T + 7.7774e-5 * T*T*T;
|
|
||||||
}
|
|
||||||
|
|
||||||
_capDissolvedOxygen(state) {
|
|
||||||
const saturation = this._calcOxygenSaturation(this.temperature);
|
|
||||||
const capRow = (row) => {
|
|
||||||
if (!Array.isArray(row)) {
|
|
||||||
return row;
|
|
||||||
}
|
|
||||||
const next = row.slice();
|
|
||||||
if (Number.isFinite(next[S_O_INDEX])) {
|
|
||||||
next[S_O_INDEX] = Math.max(0, Math.min(next[S_O_INDEX], saturation));
|
|
||||||
}
|
|
||||||
return next;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (Array.isArray(state) && Array.isArray(state[0])) {
|
|
||||||
return state.map(capRow);
|
|
||||||
}
|
|
||||||
return capRow(state);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clip values in an array to zero.
|
|
||||||
* @param {Array} arr - Array of values to clip.
|
|
||||||
* @returns {Array} - New array with values clipped to zero.
|
|
||||||
*/
|
|
||||||
_arrayClip2Zero(arr) {
|
|
||||||
if (Array.isArray(arr)) {
|
|
||||||
return arr.map(x => this._arrayClip2Zero(x));
|
|
||||||
} else {
|
|
||||||
return arr < 0 ? 0 : arr;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
registerChild(child, softwareType) {
|
|
||||||
switch (softwareType) {
|
|
||||||
case "measurement":
|
|
||||||
this.logger.debug(`Registering measurement child.`);
|
|
||||||
this._connectMeasurement(child);
|
|
||||||
break;
|
|
||||||
case "reactor":
|
|
||||||
this.logger.debug(`Registering reactor child.`);
|
|
||||||
this._connectReactor(child);
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
this.logger.error(`Unrecognized softwareType: ${softwareType}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_connectMeasurement(measurement) {
|
|
||||||
if (!measurement) {
|
|
||||||
this.logger.warn("Invalid measurement provided.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let position;
|
|
||||||
if (measurement.config.functionality.distance !== 'undefined') {
|
|
||||||
position = measurement.config.functionality.distance;
|
|
||||||
} else {
|
|
||||||
position = measurement.config.functionality.positionVsParent;
|
|
||||||
}
|
|
||||||
const measurementType = measurement.config.asset.type;
|
|
||||||
const eventName = `${measurementType}.measured.${position}`;
|
|
||||||
|
|
||||||
// Register event listener for measurement updates
|
|
||||||
measurement.measurements.emitter.on(eventName, (eventData) => {
|
|
||||||
this.logger.debug(`${position} ${measurementType} from ${eventData.childName}: ${eventData.value} ${eventData.unit}`);
|
|
||||||
|
|
||||||
// Store directly in parent's measurement container
|
|
||||||
this.measurements
|
|
||||||
.type(measurementType)
|
|
||||||
.variant("measured")
|
|
||||||
.position(position)
|
|
||||||
.value(eventData.value, eventData.timestamp, eventData.unit);
|
|
||||||
|
|
||||||
this._updateMeasurement(measurementType, eventData.value, position, eventData);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
_connectReactor(reactor) {
|
|
||||||
if (!reactor) {
|
|
||||||
this.logger.warn("Invalid reactor provided.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.upstreamReactor = reactor;
|
|
||||||
|
|
||||||
reactor.emitter.on("stateChange", (data) => {
|
|
||||||
this.logger.debug(`State change of upstream reactor detected.`);
|
|
||||||
this.updateState(data);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
_updateMeasurement(measurementType, value, position, _context) {
|
|
||||||
this.logger.debug(`---------------------- updating ${measurementType} ------------------ `);
|
|
||||||
switch (measurementType) {
|
|
||||||
case "temperature":
|
|
||||||
if (position == POSITIONS.AT_EQUIPMENT) {
|
|
||||||
this.temperature = value;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
this.logger.error(`Type '${measurementType}' not recognized for measured update.`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update the reactor state based on the new time.
|
|
||||||
* @param {number} newTime - New time to update reactor state to, in milliseconds since epoch.
|
|
||||||
*/
|
|
||||||
updateState(newTime = Date.now()) { // expect update with timestamp
|
|
||||||
const day2ms = 1000 * 60 * 60 * 24;
|
|
||||||
|
|
||||||
if (this.upstreamReactor) {
|
|
||||||
this.setInfluent = this.upstreamReactor.getEffluent;
|
|
||||||
}
|
|
||||||
|
|
||||||
let n_iter = Math.floor(this.speedUpFactor * (newTime-this.currentTime) / (this.timeStep*day2ms));
|
|
||||||
if (n_iter) {
|
|
||||||
let n = 0;
|
|
||||||
while (n < n_iter) {
|
|
||||||
this.tick(this.timeStep);
|
|
||||||
n += 1;
|
|
||||||
}
|
|
||||||
this.currentTime += n_iter * this.timeStep * day2ms / this.speedUpFactor;
|
|
||||||
this.emitter.emit("stateChange", this.currentTime);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Reactor_CSTR extends Reactor {
|
|
||||||
/**
|
|
||||||
* Reactor_CSTR class for Continuous Stirred Tank Reactor.
|
|
||||||
* @param {object} config - Configuration object containing reactor parameters.
|
|
||||||
*/
|
|
||||||
constructor(config) {
|
|
||||||
super(config);
|
|
||||||
this.state = config.initialState;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tick the reactor state using the forward Euler method.
|
|
||||||
* @param {number} time_step - Time step for the simulation [d].
|
|
||||||
* @returns {Array} - New reactor state.
|
|
||||||
*/
|
|
||||||
tick(time_step) { // tick reactor state using forward Euler method
|
|
||||||
const inflow = math.multiply(math.divide([this.Fs], this.volume), this.Cs_in)[0];
|
|
||||||
const outflow = math.multiply(-1 * math.sum(this.Fs) / this.volume, this.state);
|
|
||||||
const reaction = this.asm.compute_dC(this.state, this.temperature);
|
|
||||||
const transfer = Array(NUM_SPECIES).fill(0.0);
|
|
||||||
transfer[S_O_INDEX] = isNaN(this.kla) ? this.OTR : this._calcOTR(this.state[S_O_INDEX], this.temperature); // calculate OTR if kla is not NaN, otherwise use externaly calculated OTR
|
|
||||||
|
|
||||||
const dC_total = math.multiply(math.add(inflow, outflow, reaction, transfer), time_step)
|
|
||||||
this.state = this._capDissolvedOxygen(this._arrayClip2Zero(math.add(this.state, dC_total))); // clip concentrations and enforce physical DO saturation
|
|
||||||
if(DEBUG){
|
|
||||||
assertNoNaN(dC_total, "change in state");
|
|
||||||
assertNoNaN(this.state, "new state");
|
|
||||||
}
|
|
||||||
return this.state;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Reactor_PFR extends Reactor {
|
|
||||||
/**
|
|
||||||
* Reactor_PFR class for Plug Flow Reactor.
|
|
||||||
* @param {object} config - Configuration object containing reactor parameters.
|
|
||||||
*/
|
|
||||||
constructor(config) {
|
|
||||||
super(config);
|
|
||||||
|
|
||||||
this.length = config.length; // reactor length [m]
|
|
||||||
this.n_x = config.resolution_L; // number of slices
|
|
||||||
|
|
||||||
this.d_x = this.length / this.n_x;
|
|
||||||
this.A = this.volume / this.length; // crosssectional area [m2]
|
|
||||||
|
|
||||||
this.alpha = config.alpha;
|
|
||||||
|
|
||||||
this.state = Array.from(Array(this.n_x), () => config.initialState.slice())
|
|
||||||
|
|
||||||
this.D = 0.0; // axial dispersion [m2 d-1]
|
|
||||||
|
|
||||||
this.D_op = this._makeDoperator(true, true);
|
|
||||||
assertNoNaN(this.D_op, "Derivative operator");
|
|
||||||
|
|
||||||
this.D2_op = this._makeD2operator();
|
|
||||||
assertNoNaN(this.D2_op, "Second derivative operator");
|
|
||||||
}
|
|
||||||
|
|
||||||
get getGridProfile() {
|
|
||||||
return {
|
return {
|
||||||
grid: this.state.map(row => row.slice()),
|
general: config.general,
|
||||||
n_x: this.n_x,
|
functionality: config.functionality,
|
||||||
d_x: this.d_x,
|
reactor_type: reactor.reactor_type ?? 'CSTR',
|
||||||
length: this.length,
|
volume: Number(reactor.volume),
|
||||||
species: ['S_O','S_I','S_S','S_NH','S_N2','S_NO','S_HCO',
|
length: Number(reactor.length),
|
||||||
'X_I','X_S','X_H','X_STO','X_A','X_TS'],
|
resolution_L: Number(reactor.resolution_L),
|
||||||
timestamp: this.currentTime
|
alpha: Number(reactor.alpha),
|
||||||
|
n_inlets: Number(reactor.n_inlets),
|
||||||
|
kla: Number(reactor.kla),
|
||||||
|
timeStep: Number(reactor.timeStep),
|
||||||
|
speedUpFactor: Number(reactor.speedUpFactor) || 1,
|
||||||
|
initialState,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
_buildEngine(flat) {
|
||||||
* Setter for axial dispersion.
|
// The schema enum validator lowercases the configured value, so accept
|
||||||
* @param {object} input - Input object (msg) containing payload with dispersion value [m2 d-1].
|
// either case.
|
||||||
*/
|
switch (String(flat.reactor_type || '').toUpperCase()) {
|
||||||
set setDispersion(input) {
|
case 'CSTR': return new Reactor_CSTR(flat);
|
||||||
this.D = input.payload;
|
case 'PFR': return new Reactor_PFR(flat);
|
||||||
}
|
|
||||||
|
|
||||||
updateState(newTime) {
|
|
||||||
super.updateState(newTime);
|
|
||||||
let Pe_local = this.d_x*math.sum(this.Fs)/(this.D*this.A)
|
|
||||||
let Co_D = this.D*this.timeStep/(this.d_x*this.d_x);
|
|
||||||
|
|
||||||
(Pe_local >= 2) && this.logger.warn(`Local Peclet number (${Pe_local}) is too high! Increase reactor resolution.`);
|
|
||||||
(Co_D >= 0.5) && this.logger.warn(`Courant number (${Co_D}) is too high! Reduce time step size.`);
|
|
||||||
|
|
||||||
if(DEBUG) {
|
|
||||||
console.log("Inlet state max " + math.max(this.state[0]))
|
|
||||||
console.log("Pe total " + this.length*math.sum(this.Fs)/(this.D*this.A));
|
|
||||||
console.log("Pe local " + Pe_local);
|
|
||||||
console.log("Co ad " + math.sum(this.Fs)*this.timeStep/(this.A*this.d_x));
|
|
||||||
console.log("Co D " + Co_D);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tick the reactor state using explicit finite difference method.
|
|
||||||
* @param {number} time_step - Time step for the simulation [d].
|
|
||||||
* @returns {Array} - New reactor state.
|
|
||||||
*/
|
|
||||||
tick(time_step) {
|
|
||||||
const dispersion = math.multiply(this.D / (this.d_x*this.d_x), this.D2_op, this.state);
|
|
||||||
const advection = math.multiply(-1 * math.sum(this.Fs) / (this.A*this.d_x), this.D_op, this.state);
|
|
||||||
const reaction = this.state.map((state_slice) => this.asm.compute_dC(state_slice, this.temperature));
|
|
||||||
const transfer = Array.from(Array(this.n_x), () => new Array(NUM_SPECIES).fill(0));
|
|
||||||
|
|
||||||
if (isNaN(this.kla)) { // calculate OTR if kla is not NaN, otherwise use externally calculated OTR
|
|
||||||
for (let i = 1; i < this.n_x - 1; i++) {
|
|
||||||
transfer[i][S_O_INDEX] = this.OTR * this.n_x/(this.n_x-2);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for (let i = 1; i < this.n_x - 1; i++) {
|
|
||||||
transfer[i][S_O_INDEX] = this._calcOTR(this.state[i][S_O_INDEX], this.temperature) * this.n_x/(this.n_x-2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const dC_total = math.multiply(math.add(dispersion, advection, reaction, transfer), time_step);
|
|
||||||
|
|
||||||
const stateNew = math.add(this.state, dC_total);
|
|
||||||
this._applyBoundaryConditions(stateNew);
|
|
||||||
|
|
||||||
if (DEBUG) {
|
|
||||||
assertNoNaN(dispersion, "dispersion");
|
|
||||||
assertNoNaN(advection, "advection");
|
|
||||||
assertNoNaN(reaction, "reaction");
|
|
||||||
assertNoNaN(dC_total, "change in state");
|
|
||||||
assertNoNaN(stateNew, "new state post BC");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.state = this._capDissolvedOxygen(this._arrayClip2Zero(stateNew));
|
|
||||||
return stateNew;
|
|
||||||
}
|
|
||||||
|
|
||||||
_updateMeasurement(measurementType, value, position, context) {
|
|
||||||
switch(measurementType) {
|
|
||||||
case "quantity (oxygen)":
|
|
||||||
if (!Number.isFinite(position) || !Number.isFinite(value) || this.config.length <= 0) {
|
|
||||||
this.logger.warn(`Ignoring oxygen measurement update with invalid data (position=${position}, value=${value}).`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
{
|
|
||||||
// Clamp sensor-derived position to valid PFR grid bounds.
|
|
||||||
const rawIndex = Math.round(position / this.config.length * this.n_x);
|
|
||||||
const grid_pos = Math.max(0, Math.min(this.n_x - 1, rawIndex));
|
|
||||||
this.state[grid_pos][S_O_INDEX] = value; // reconcile measured oxygen concentration into nearest grid cell
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
default:
|
||||||
super._updateMeasurement(measurementType, value, position, context);
|
this.logger.warn(`Unknown reactor type: ${flat.reactor_type}. Falling back to CSTR.`);
|
||||||
|
return new Reactor_CSTR(flat);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Adapter input setters — forwarded straight to the engine.
|
||||||
* Apply boundary conditions to the reactor state.
|
set setInfluent(msg) { this.engine.setInfluent = msg; }
|
||||||
* for inlet, apply generalised Danckwerts BC, if there is not flow, apply Neumann BC with no flux
|
set setOTR(msg) { this.engine.setOTR = msg; }
|
||||||
* for outlet, apply regular Danckwerts BC (Neumann BC with no flux)
|
set setTemperature(msg) { this.engine.setTemperature = msg; }
|
||||||
* @param {Array} state - Current reactor state without enforced BCs.
|
set setDispersion(msg) { if (this.engine instanceof Reactor_PFR) this.engine.setDispersion = msg; }
|
||||||
*/
|
|
||||||
_applyBoundaryConditions(state) {
|
updateState(t) { this.engine.updateState(t); this.notifyOutputChanged(); }
|
||||||
if (math.sum(this.Fs) > 0) { // Danckwerts BC
|
|
||||||
const BC_C_in = math.multiply(1 / math.sum(this.Fs), [this.Fs], this.Cs_in)[0];
|
// Engine pass-through — needed so the BaseNodeAdapter tick loop (and
|
||||||
const BC_dispersion_term = (1-this.alpha)*this.D*this.A/(math.sum(this.Fs)*this.d_x);
|
// tests calling reactor.tick(dt) directly) drive the ASM integration.
|
||||||
state[0] = math.multiply(1/(1+BC_dispersion_term), math.add(BC_C_in, math.multiply(BC_dispersion_term, state[1])));
|
// Without this the Node-RED tick fires `source.tick?.()`, gets undefined,
|
||||||
} else {
|
// and the kinetics state never advances.
|
||||||
state[0] = state[1];
|
tick(timeStep) {
|
||||||
}
|
const result = this.engine.tick(timeStep);
|
||||||
// Neumann BC (no flux)
|
this.notifyOutputChanged();
|
||||||
state[this.n_x-1] = state[this.n_x-2];
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
get getEffluent() { return this.engine.getEffluent; }
|
||||||
* Create finite difference first derivative operator.
|
get getGridProfile() { return this.engine.getGridProfile; }
|
||||||
* @param {boolean} central - Use central difference scheme if true, otherwise use upwind scheme.
|
get temperature() { return this.engine.temperature; }
|
||||||
* @param {boolean} higher_order - Use higher order scheme if true, otherwise use first order scheme.
|
|
||||||
* @returns {Array} - First derivative operator matrix.
|
// Per-tick output for Port 0 / Port 1. Carries the effluent vector plus
|
||||||
*/
|
// a flat per-species block keyed by SPECIES_KEYS for InfluxDB telemetry.
|
||||||
_makeDoperator(central = false, higher_order = false) { // create gradient operator
|
getOutput() {
|
||||||
if (higher_order) {
|
const eff = this.engine.getEffluent;
|
||||||
if (central) {
|
const C = Array.isArray(eff?.payload?.C) ? eff.payload.C : [];
|
||||||
const I = math.resize(math.diag(Array(this.n_x).fill(1/12), -2), [this.n_x, this.n_x]);
|
const out = {
|
||||||
const A = math.resize(math.diag(Array(this.n_x).fill(-2/3), -1), [this.n_x, this.n_x]);
|
flow_total: Number(eff?.payload?.F),
|
||||||
const B = math.resize(math.diag(Array(this.n_x).fill(2/3), 1), [this.n_x, this.n_x]);
|
temperature: Number(this.engine.temperature),
|
||||||
const C = math.resize(math.diag(Array(this.n_x).fill(-1/12), 2), [this.n_x, this.n_x]);
|
};
|
||||||
const D = math.add(I, A, B, C);
|
for (let i = 0; i < Math.min(SPECIES_KEYS.length, C.length); i += 1) {
|
||||||
const NearBoundary = Array(this.n_x).fill(0.0);
|
const v = Number(C[i]);
|
||||||
NearBoundary[0] = -1/4;
|
if (Number.isFinite(v)) out[SPECIES_KEYS[i]] = v;
|
||||||
NearBoundary[1] = -5/6;
|
|
||||||
NearBoundary[2] = 3/2;
|
|
||||||
NearBoundary[3] = -1/2;
|
|
||||||
NearBoundary[4] = 1/12;
|
|
||||||
D[1] = NearBoundary;
|
|
||||||
NearBoundary.reverse();
|
|
||||||
D[this.n_x-2] = math.multiply(-1, NearBoundary);
|
|
||||||
D[0] = Array(this.n_x).fill(0); // set by BCs elsewhere
|
|
||||||
D[this.n_x-1] = Array(this.n_x).fill(0);
|
|
||||||
return D;
|
|
||||||
} else {
|
|
||||||
throw new Error("Upwind higher order method not implemented! Use central scheme instead.");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const I = math.resize(math.diag(Array(this.n_x).fill(1 / (1+central)), central), [this.n_x, this.n_x]);
|
|
||||||
const A = math.resize(math.diag(Array(this.n_x).fill(-1 / (1+central)), -1), [this.n_x, this.n_x]);
|
|
||||||
const D = math.add(I, A);
|
|
||||||
D[0] = Array(this.n_x).fill(0); // set by BCs elsewhere
|
|
||||||
D[this.n_x-1] = Array(this.n_x).fill(0);
|
|
||||||
return D;
|
|
||||||
}
|
}
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
getStatusBadge() {
|
||||||
* Create central finite difference second derivative operator.
|
const eff = this.engine.getEffluent;
|
||||||
* @returns {Array} - Second derivative operator matrix.
|
const F = Number(eff?.payload?.F) || 0;
|
||||||
*/
|
const SO = Array.isArray(eff?.payload?.C) ? Number(eff.payload.C[0]) : NaN;
|
||||||
_makeD2operator() { // create the central second derivative operator
|
const so = Number.isFinite(SO) ? SO.toFixed(2) : '—';
|
||||||
const I = math.diag(Array(this.n_x).fill(-2), 0);
|
return statusBadge.compose(
|
||||||
const A = math.resize(math.diag(Array(this.n_x).fill(1), 1), [this.n_x, this.n_x]);
|
[`${this.engine.constructor.name.replace('Reactor_', '')}`,
|
||||||
const B = math.resize(math.diag(Array(this.n_x).fill(1), -1), [this.n_x, this.n_x]);
|
`T=${Number(this.engine.temperature).toFixed(1)} C`,
|
||||||
const D2 = math.add(I, A, B);
|
`F=${F.toFixed(2)} m³/d`,
|
||||||
D2[0] = Array(this.n_x).fill(0); // set by BCs elsewhere
|
`S_O=${so} mg/L`],
|
||||||
D2[this.n_x - 1] = Array(this.n_x).fill(0);
|
{ fill: 'green', shape: 'dot' },
|
||||||
return D2;
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
this.engine?.emitter?.removeAllListeners?.();
|
||||||
|
super.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { Reactor_CSTR, Reactor_PFR };
|
module.exports = Reactor;
|
||||||
|
module.exports.Reactor = Reactor;
|
||||||
// DEBUG
|
module.exports.Reactor_CSTR = Reactor_CSTR;
|
||||||
// state: 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
|
module.exports.Reactor_PFR = Reactor_PFR;
|
||||||
// let initial_state = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1];
|
// POSITIONS is consumed by older test setups; surface it here so they don't
|
||||||
// const Reactor = new Reactor_PFR(200, 10, 10, 1, 100, initial_state);
|
// need to chase down generalFunctions internals.
|
||||||
// Reactor.Cs_in[0] = [0.0, 30., 100., 16., 0., 0., 5., 25., 75., 30., 0., 0., 125.];
|
module.exports.POSITIONS = POSITIONS;
|
||||||
// Reactor.Fs[0] = 10;
|
|
||||||
// Reactor.D = 0.01;
|
|
||||||
// let N = 0;
|
|
||||||
// while (N < 5000) {
|
|
||||||
// console.log(Reactor.tick(0.001));
|
|
||||||
// N += 1;
|
|
||||||
// }
|
|
||||||
|
|||||||
@@ -1,55 +1,83 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Phase 10 rewrite: drives only the public BaseNodeAdapter surface.
|
||||||
|
// The pre-refactor _loadConfig / _setupClass private methods are gone —
|
||||||
|
// config build is exposed via buildDomainConfig (override hook in
|
||||||
|
// CONTRACTS.md §2), and engine selection is observable via
|
||||||
|
// `inst.source.engine instanceof Reactor_CSTR | Reactor_PFR` after a
|
||||||
|
// full `new nodeClass(...)` construction.
|
||||||
|
|
||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
const NodeClass = require('../../src/nodeClass');
|
const nodeClass = require('../../src/nodeClass');
|
||||||
const { Reactor_CSTR, Reactor_PFR } = require('../../src/specificClass');
|
const { Reactor_CSTR, Reactor_PFR } = require('../../src/specificClass');
|
||||||
const { makeUiConfig, makeReactorConfig, makeNodeStub } = require('../helpers/factories');
|
const { makeUiConfig } = require('../helpers/factories');
|
||||||
|
|
||||||
test('_loadConfig coerces numeric fields and builds initial state vector', () => {
|
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||||
const inst = Object.create(NodeClass.prototype);
|
|
||||||
inst.node = { id: 'n-reactor-1' };
|
|
||||||
inst.name = 'reactor';
|
|
||||||
|
|
||||||
inst._loadConfig(
|
function makeNode(id = 'reactor-1') {
|
||||||
makeUiConfig({
|
const sends = [];
|
||||||
volume: '12.5',
|
const statuses = [];
|
||||||
length: '9',
|
const handlers = {};
|
||||||
resolution_L: '7',
|
return {
|
||||||
alpha: '0.5',
|
id, sends, statuses, handlers,
|
||||||
n_inlets: '3',
|
send(arr) { sends.push(arr); },
|
||||||
timeStep: '2',
|
status(b) { statuses.push(b); },
|
||||||
S_O_init: '1.1',
|
on(ev, fn) { handlers[ev] = fn; },
|
||||||
}),
|
warn() {}, error() {},
|
||||||
);
|
};
|
||||||
|
}
|
||||||
|
|
||||||
assert.equal(inst.config.volume, 12.5);
|
function closeNode(node) {
|
||||||
assert.equal(inst.config.length, 9);
|
if (node.handlers.close) node.handlers.close(() => {});
|
||||||
assert.equal(inst.config.resolution_L, 7);
|
}
|
||||||
assert.equal(inst.config.alpha, 0.5);
|
|
||||||
assert.equal(inst.config.n_inlets, 3);
|
test('buildDomainConfig coerces numeric fields and builds initial state vector', () => {
|
||||||
assert.equal(inst.config.timeStep, 2);
|
const node = makeNode();
|
||||||
assert.equal(inst.config.initialState.length, 13);
|
const inst = new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||||
assert.equal(inst.config.initialState[0], 1.1);
|
try {
|
||||||
|
const dc = inst.buildDomainConfig(
|
||||||
|
makeUiConfig({
|
||||||
|
volume: '12.5',
|
||||||
|
length: '9',
|
||||||
|
resolution_L: '7',
|
||||||
|
alpha: '0.5',
|
||||||
|
n_inlets: '3',
|
||||||
|
timeStep: '2',
|
||||||
|
S_O_init: '1.1',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(dc.reactor.volume, 12.5);
|
||||||
|
assert.equal(dc.reactor.length, 9);
|
||||||
|
assert.equal(dc.reactor.resolution_L, 7);
|
||||||
|
assert.equal(dc.reactor.alpha, 0.5);
|
||||||
|
assert.equal(dc.reactor.n_inlets, 3);
|
||||||
|
assert.equal(dc.reactor.timeStep, 2);
|
||||||
|
assert.equal(Object.keys(dc.initialState).length, 13);
|
||||||
|
assert.equal(dc.initialState.S_O, 1.1);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('_setupClass selects Reactor_CSTR when configured as CSTR', () => {
|
test('Reactor wrapper instantiates CSTR engine when configured as CSTR', () => {
|
||||||
const inst = Object.create(NodeClass.prototype);
|
const node = makeNode();
|
||||||
inst.node = makeNodeStub();
|
const inst = new nodeClass(makeUiConfig({ reactor_type: 'CSTR' }), makeRED(), node, 'reactor');
|
||||||
inst.config = makeReactorConfig({ reactor_type: 'CSTR' });
|
try {
|
||||||
|
assert.ok(inst.source.engine instanceof Reactor_CSTR);
|
||||||
inst._setupClass();
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
assert.ok(inst.source instanceof Reactor_CSTR);
|
}
|
||||||
assert.equal(inst.node.source, inst.source);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('_setupClass selects Reactor_PFR when configured as PFR', () => {
|
test('Reactor wrapper instantiates PFR engine when configured as PFR', () => {
|
||||||
const inst = Object.create(NodeClass.prototype);
|
const node = makeNode();
|
||||||
inst.node = makeNodeStub();
|
const inst = new nodeClass(makeUiConfig({ reactor_type: 'PFR' }), makeRED(), node, 'reactor');
|
||||||
inst.config = makeReactorConfig({ reactor_type: 'PFR', length: 10, resolution_L: 5 });
|
try {
|
||||||
|
assert.ok(inst.source.engine instanceof Reactor_PFR);
|
||||||
inst._setupClass();
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
assert.ok(inst.source instanceof Reactor_PFR);
|
}
|
||||||
assert.equal(inst.node.source, inst.source);
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,77 +1,111 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Phase 10 rewrite: drives only the public BaseNodeAdapter surface.
|
||||||
|
// The pre-refactor _attachInputHandler private switch is gone — input
|
||||||
|
// dispatch goes through the commands registry that BaseNodeAdapter builds
|
||||||
|
// at construction. Tests fire msgs through `node.handlers.input` and
|
||||||
|
// observe via `node.sends`, `inst.source.engine.*`, and per-fire calls
|
||||||
|
// captured on a child stub registered through `RED.nodes.getNode(id)`.
|
||||||
|
|
||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
const NodeClass = require('../../src/nodeClass');
|
const nodeClass = require('../../src/nodeClass');
|
||||||
const { makeNodeStub, makeREDStub } = require('../helpers/factories');
|
const { makeUiConfig } = require('../helpers/factories');
|
||||||
|
|
||||||
test('_attachInputHandler routes supported topics to source methods/setters', () => {
|
function makeNode(id = 'reactor-1') {
|
||||||
const inst = Object.create(NodeClass.prototype);
|
const sends = [];
|
||||||
const node = makeNodeStub();
|
const statuses = [];
|
||||||
const calls = [];
|
const handlers = {};
|
||||||
|
return {
|
||||||
const source = {
|
id, sends, statuses, handlers,
|
||||||
updateState(timestamp) {
|
send(arr) { sends.push(arr); },
|
||||||
calls.push(['clock', timestamp]);
|
status(b) { statuses.push(b); },
|
||||||
},
|
on(ev, fn) { handlers[ev] = fn; },
|
||||||
childRegistrationUtils: {
|
warn() {}, error() {},
|
||||||
registerChild(childSource, position) {
|
|
||||||
calls.push(['registerChild', childSource, position]);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
Object.defineProperty(source, 'setInfluent', {
|
function makeRED(nodeMap = {}) {
|
||||||
set(v) {
|
return { nodes: { getNode: (id) => nodeMap[id] || null } };
|
||||||
calls.push(['Fluent', v]);
|
}
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
Object.defineProperty(source, 'setOTR', {
|
function closeNode(node) {
|
||||||
set(v) {
|
if (node.handlers.close) node.handlers.close(() => {});
|
||||||
calls.push(['OTR', v]);
|
}
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
Object.defineProperty(source, 'setTemperature', {
|
test('legacy alias topics drive engine setters and updateState', async () => {
|
||||||
set(v) {
|
const childSource = {
|
||||||
calls.push(['Temperature', v]);
|
id: 'child-source-A',
|
||||||
},
|
config: { general: { id: 'child-source-A' }, functionality: { softwareType: 'measurement', positionVsParent: 'upstream' }, asset: { type: 'temperature' } },
|
||||||
});
|
};
|
||||||
|
const node = makeNode();
|
||||||
|
const RED = makeRED({ childA: { source: childSource } });
|
||||||
|
const inst = new nodeClass(makeUiConfig(), RED, node, 'reactor');
|
||||||
|
|
||||||
Object.defineProperty(source, 'setDispersion', {
|
try {
|
||||||
set(v) {
|
let doneCount = 0;
|
||||||
calls.push(['Dispersion', v]);
|
const done = () => { doneCount += 1; };
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
inst.node = node;
|
// data.clock alias → updateState(timestamp). Capture currentTime
|
||||||
inst.RED = makeREDStub({
|
// before/after to verify the engine advanced.
|
||||||
childA: {
|
const t0 = inst.source.engine.currentTime;
|
||||||
source: { id: 'child-source-A' },
|
await node.handlers.input({ topic: 'clock', timestamp: t0 + 1 }, () => {}, done);
|
||||||
},
|
|
||||||
});
|
|
||||||
inst.source = source;
|
|
||||||
|
|
||||||
inst._attachInputHandler();
|
// Fluent alias → engine setInfluent setter.
|
||||||
|
await node.handlers.input(
|
||||||
|
{ topic: 'Fluent', payload: { inlet: 0, F: 7, C: [1,2,3,4,5,6,7,8,9,10,11,12,13] } },
|
||||||
|
() => {}, done,
|
||||||
|
);
|
||||||
|
assert.equal(inst.source.engine.Fs[0], 7);
|
||||||
|
assert.deepEqual(inst.source.engine.Cs_in[0], [1,2,3,4,5,6,7,8,9,10,11,12,13]);
|
||||||
|
|
||||||
const onInput = node._handlers.input;
|
// OTR alias → engine setOTR setter.
|
||||||
const sent = [];
|
await node.handlers.input({ topic: 'OTR', payload: 3.5 }, () => {}, done);
|
||||||
let doneCount = 0;
|
assert.equal(inst.source.engine.OTR, 3.5);
|
||||||
|
|
||||||
onInput({ topic: 'clock', timestamp: 1000 }, (msg) => sent.push(msg), () => doneCount++);
|
// Temperature alias → engine setTemperature setter.
|
||||||
onInput({ topic: 'Fluent', payload: { inlet: 0, F: 10, C: [] } }, () => {}, () => doneCount++);
|
await node.handlers.input({ topic: 'Temperature', payload: 18.2 }, () => {}, done);
|
||||||
onInput({ topic: 'OTR', payload: 3.5 }, () => {}, () => doneCount++);
|
assert.equal(inst.source.engine.temperature, 18.2);
|
||||||
onInput({ topic: 'Temperature', payload: 18.2 }, () => {}, () => doneCount++);
|
|
||||||
onInput({ topic: 'Dispersion', payload: 0.2 }, () => {}, () => doneCount++);
|
|
||||||
onInput({ topic: 'registerChild', payload: 'childA', positionVsParent: 'upstream' }, () => {}, () => doneCount++);
|
|
||||||
|
|
||||||
assert.equal(doneCount, 6);
|
// Dispersion alias — CSTR engine does not own a setDispersion setter
|
||||||
assert.equal(sent.length, 1);
|
// (only PFR does); the Reactor wrapper guards on engine type and the
|
||||||
assert.equal(Array.isArray(sent[0]), true);
|
// dispatch should silently return without throwing.
|
||||||
assert.deepEqual(calls[0], ['clock', 1000]);
|
await node.handlers.input({ topic: 'Dispersion', payload: 0.2 }, () => {}, done);
|
||||||
assert.equal(calls.some((x) => x[0] === 'Fluent'), true);
|
|
||||||
assert.equal(calls.some((x) => x[0] === 'OTR'), true);
|
// registerChild alias → registers via childRegistrationUtils.
|
||||||
assert.equal(calls.some((x) => x[0] === 'Temperature'), true);
|
// The handler resolves the child via RED.nodes.getNode(payload).source.
|
||||||
assert.equal(calls.some((x) => x[0] === 'Dispersion'), true);
|
await node.handlers.input(
|
||||||
assert.deepEqual(calls.at(-1), ['registerChild', { id: 'child-source-A' }, 'upstream']);
|
{ topic: 'registerChild', payload: 'childA', positionVsParent: 'upstream' },
|
||||||
|
() => {}, done,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(doneCount, 6);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('canonical topics are accepted (data.fluent, data.otr, data.temperature)', async () => {
|
||||||
|
const node = makeNode();
|
||||||
|
const inst = new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||||
|
|
||||||
|
try {
|
||||||
|
let done = 0;
|
||||||
|
await node.handlers.input(
|
||||||
|
{ topic: 'data.fluent', payload: { inlet: 0, F: 11, C: [0,0,0,0,0,0,0,0,0,0,0,0,0] } },
|
||||||
|
() => {}, () => { done += 1; },
|
||||||
|
);
|
||||||
|
assert.equal(inst.source.engine.Fs[0], 11);
|
||||||
|
|
||||||
|
await node.handlers.input({ topic: 'data.otr', payload: 4.2 }, () => {}, () => { done += 1; });
|
||||||
|
assert.equal(inst.source.engine.OTR, 4.2);
|
||||||
|
|
||||||
|
await node.handlers.input({ topic: 'data.temperature', payload: 19.7 }, () => {}, () => { done += 1; });
|
||||||
|
assert.equal(inst.source.engine.temperature, 19.7);
|
||||||
|
|
||||||
|
assert.equal(done, 3);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,39 +1,84 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Phase 10 rewrite: drives only the public BaseNodeAdapter surface.
|
||||||
|
// The pre-refactor _registerChild method was renamed to
|
||||||
|
// _scheduleRegistration inside BaseNodeAdapter and now fires automatically
|
||||||
|
// 100ms after construction. We verify the emission by capturing the Port-2
|
||||||
|
// message on `node.sends` after the registration delay elapses.
|
||||||
|
|
||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
const NodeClass = require('../../src/nodeClass');
|
const nodeClass = require('../../src/nodeClass');
|
||||||
const { makeNodeStub } = require('../helpers/factories');
|
const { makeUiConfig } = require('../helpers/factories');
|
||||||
|
|
||||||
test('_registerChild emits delayed registration message on output 2', () => {
|
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||||
const inst = Object.create(NodeClass.prototype);
|
|
||||||
const node = makeNodeStub();
|
|
||||||
|
|
||||||
inst.node = node;
|
function makeNode(id = 'reactor-node-1') {
|
||||||
inst.config = {
|
const sends = [];
|
||||||
functionality: {
|
const statuses = [];
|
||||||
positionVsParent: 'downstream',
|
const handlers = {};
|
||||||
},
|
return {
|
||||||
|
id, sends, statuses, handlers,
|
||||||
|
send(arr) { sends.push(arr); },
|
||||||
|
status(b) { statuses.push(b); },
|
||||||
|
on(ev, fn) { handlers[ev] = fn; },
|
||||||
|
warn() {}, error() {},
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const originalSetTimeout = global.setTimeout;
|
function closeNode(node) {
|
||||||
const delays = [];
|
if (node.handlers.close) node.handlers.close(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
global.setTimeout = (fn, ms) => {
|
test('scheduled child.register message lands on Port 2 after construction', async () => {
|
||||||
delays.push(ms);
|
const node = makeNode();
|
||||||
fn();
|
const inst = new nodeClass(
|
||||||
return 1;
|
makeUiConfig({ positionVsParent: 'downstream' }),
|
||||||
};
|
makeRED(),
|
||||||
|
node,
|
||||||
|
'reactor',
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
inst._registerChild();
|
// BaseNodeAdapter._scheduleRegistration uses a 100ms setTimeout; wait
|
||||||
} finally {
|
// slightly longer to let it fire.
|
||||||
global.setTimeout = originalSetTimeout;
|
await new Promise((r) => setTimeout(r, 130));
|
||||||
}
|
|
||||||
|
|
||||||
assert.deepEqual(delays, [100]);
|
// The registration send is the [null, null, {child.register}] triple.
|
||||||
assert.equal(node._sent.length, 1);
|
const regSends = node.sends.filter(
|
||||||
assert.equal(Array.isArray(node._sent[0]), true);
|
(s) => Array.isArray(s) && s[0] === null && s[1] === null && s[2] && s[2].topic === 'child.register',
|
||||||
assert.equal(node._sent[0][2].topic, 'registerChild');
|
);
|
||||||
assert.equal(node._sent[0][2].payload, node.id);
|
assert.equal(regSends.length, 1, 'exactly one child.register message expected');
|
||||||
assert.equal(node._sent[0][2].positionVsParent, 'downstream');
|
const msg = regSends[0][2];
|
||||||
|
assert.equal(msg.topic, 'child.register');
|
||||||
|
assert.equal(msg.payload, node.id);
|
||||||
|
assert.equal(msg.positionVsParent, 'downstream');
|
||||||
|
// After construction the source is exposed on the node for sibling lookup.
|
||||||
|
assert.strictEqual(node.source, inst.source);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('child.register handler ignores unknown child ids without throwing', async () => {
|
||||||
|
const node = makeNode();
|
||||||
|
const inst = new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||||
|
|
||||||
|
try {
|
||||||
|
let done = 0;
|
||||||
|
await assert.doesNotReject(async () => {
|
||||||
|
await node.handlers.input(
|
||||||
|
{ topic: 'child.register', payload: 'missing-child', positionVsParent: 'upstream' },
|
||||||
|
() => {},
|
||||||
|
() => { done += 1; },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert.equal(done, 1);
|
||||||
|
// No child should have been registered into the engine's registry.
|
||||||
|
const registered = inst.source.engine.childRegistrationUtils;
|
||||||
|
assert.ok(registered, 'childRegistrationUtils exists on engine');
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,53 +1,80 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Phase 10 rewrite: drives only the public BaseNodeAdapter surface for
|
||||||
|
// the nodeClass-level checks, and the public Reactor_CSTR engine surface
|
||||||
|
// for the domain-level checks. The pre-refactor private nodeClass methods
|
||||||
|
// are gone — `buildDomainConfig` is the documented override hook
|
||||||
|
// (CONTRACTS.md §2) and is fair game to call on a real constructed
|
||||||
|
// instance.
|
||||||
|
|
||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
const { Reactor_CSTR } = require('../../src/specificClass');
|
|
||||||
const nodeClass = require('../../src/nodeClass');
|
const nodeClass = require('../../src/nodeClass');
|
||||||
const { makeReactorConfig, makeUiConfig, makeNodeStub, makeREDStub } = require('../helpers/factories');
|
const { Reactor_CSTR } = require('../../src/specificClass');
|
||||||
|
const { makeReactorConfig, makeUiConfig } = require('../helpers/factories');
|
||||||
|
|
||||||
/**
|
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||||
* Smoke tests for Fix 3: configurable speedUpFactor on Reactor.
|
|
||||||
*/
|
|
||||||
|
|
||||||
test('specificClass defaults speedUpFactor to 1 when not in config', () => {
|
function makeNode(id = 'reactor-node-1') {
|
||||||
|
const sends = [];
|
||||||
|
const statuses = [];
|
||||||
|
const handlers = {};
|
||||||
|
return {
|
||||||
|
id, sends, statuses, handlers,
|
||||||
|
send(arr) { sends.push(arr); },
|
||||||
|
status(b) { statuses.push(b); },
|
||||||
|
on(ev, fn) { handlers[ev] = fn; },
|
||||||
|
warn() {}, error() {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeNode(node) {
|
||||||
|
if (node.handlers.close) node.handlers.close(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Reactor_CSTR engine defaults speedUpFactor to 1 when not in config', () => {
|
||||||
const config = makeReactorConfig();
|
const config = makeReactorConfig();
|
||||||
const reactor = new Reactor_CSTR(config);
|
const reactor = new Reactor_CSTR(config);
|
||||||
assert.equal(reactor.speedUpFactor, 1, 'speedUpFactor should default to 1');
|
assert.equal(reactor.speedUpFactor, 1, 'speedUpFactor should default to 1');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('specificClass accepts speedUpFactor from config', () => {
|
test('Reactor_CSTR engine accepts speedUpFactor from config', () => {
|
||||||
const config = makeReactorConfig();
|
const config = makeReactorConfig();
|
||||||
config.speedUpFactor = 10;
|
config.speedUpFactor = 10;
|
||||||
const reactor = new Reactor_CSTR(config);
|
const reactor = new Reactor_CSTR(config);
|
||||||
assert.equal(reactor.speedUpFactor, 10, 'speedUpFactor should be read from config');
|
assert.equal(reactor.speedUpFactor, 10, 'speedUpFactor should be read from config');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('specificClass accepts speedUpFactor = 60 for accelerated simulation', () => {
|
test('Reactor_CSTR engine accepts speedUpFactor = 60 for accelerated simulation', () => {
|
||||||
const config = makeReactorConfig();
|
const config = makeReactorConfig();
|
||||||
config.speedUpFactor = 60;
|
config.speedUpFactor = 60;
|
||||||
const reactor = new Reactor_CSTR(config);
|
const reactor = new Reactor_CSTR(config);
|
||||||
assert.equal(reactor.speedUpFactor, 60, 'speedUpFactor=60 should be accepted');
|
assert.equal(reactor.speedUpFactor, 60, 'speedUpFactor=60 should be accepted');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('nodeClass passes speedUpFactor from uiConfig to reactor config', () => {
|
test('buildDomainConfig propagates speedUpFactor from uiConfig', () => {
|
||||||
const uiConfig = makeUiConfig({ speedUpFactor: 5 });
|
const node = makeNode();
|
||||||
const node = makeNodeStub();
|
const inst = new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||||
const RED = makeREDStub();
|
try {
|
||||||
|
const dc = inst.buildDomainConfig(makeUiConfig({ speedUpFactor: 5 }));
|
||||||
const nc = new nodeClass(uiConfig, RED, node, 'test-reactor');
|
assert.equal(dc.reactor.speedUpFactor, 5);
|
||||||
assert.equal(nc.source.speedUpFactor, 5, 'nodeClass should pass speedUpFactor=5 to specificClass');
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('nodeClass defaults speedUpFactor to 1 when not in uiConfig', () => {
|
test('buildDomainConfig defaults speedUpFactor to 1 when missing from uiConfig', () => {
|
||||||
const uiConfig = makeUiConfig();
|
const node = makeNode();
|
||||||
// Ensure speedUpFactor is not set
|
const inst = new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||||
delete uiConfig.speedUpFactor;
|
try {
|
||||||
|
const ui = makeUiConfig();
|
||||||
const node = makeNodeStub();
|
delete ui.speedUpFactor;
|
||||||
const RED = makeREDStub();
|
const dc = inst.buildDomainConfig(ui);
|
||||||
|
assert.equal(dc.reactor.speedUpFactor, 1);
|
||||||
const nc = new nodeClass(uiConfig, RED, node, 'test-reactor');
|
} finally {
|
||||||
assert.equal(nc.source.speedUpFactor, 1, 'nodeClass should default speedUpFactor to 1');
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('updateState with speedUpFactor=1 advances roughly real-time', () => {
|
test('updateState with speedUpFactor=1 advances roughly real-time', () => {
|
||||||
@@ -56,13 +83,9 @@ test('updateState with speedUpFactor=1 advances roughly real-time', () => {
|
|||||||
config.n_inlets = 1;
|
config.n_inlets = 1;
|
||||||
const reactor = new Reactor_CSTR(config);
|
const reactor = new Reactor_CSTR(config);
|
||||||
|
|
||||||
// Set a known start time
|
|
||||||
const t0 = reactor.currentTime;
|
const t0 = reactor.currentTime;
|
||||||
// Advance by 2 seconds real time
|
|
||||||
reactor.updateState(t0 + 2000);
|
reactor.updateState(t0 + 2000);
|
||||||
|
|
||||||
// With speedUpFactor=1, simulation should have advanced ~2 seconds worth
|
|
||||||
// (not 120 seconds like with the old hardcoded 60x factor)
|
|
||||||
const elapsed = reactor.currentTime - t0;
|
const elapsed = reactor.currentTime - t0;
|
||||||
assert.ok(elapsed < 5000, `Elapsed ${elapsed}ms should be close to 2000ms, not 120000ms (old 60x factor)`);
|
assert.ok(elapsed < 5000, `Elapsed ${elapsed}ms should be close to 2000ms, not 120000ms (old 60x factor)`);
|
||||||
});
|
});
|
||||||
|
|||||||
44
test/basic/timestep-units.basic.test.js
Normal file
44
test/basic/timestep-units.basic.test.js
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Locks in the contract that `config.timeStep` is interpreted as SECONDS by
|
||||||
|
// the reactor kinetics engine. Before 2026-05-19 the schema labelled the field
|
||||||
|
// `unit: "h"` while reactor.html labelled it `[s]` and baseEngine divided by
|
||||||
|
// 86400 (seconds-per-day) to convert to internal days. A 0.001 schema default
|
||||||
|
// — read as hours — would have produced a 3.6 s step; read as seconds it is a
|
||||||
|
// 1 ms step. The fix aligned the schema to seconds. This test prevents the
|
||||||
|
// drift from reappearing.
|
||||||
|
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
|
const { Reactor_CSTR } = require('../../src/specificClass');
|
||||||
|
const { makeReactorConfig } = require('../helpers/factories');
|
||||||
|
|
||||||
|
const SECONDS_PER_DAY = 24 * 60 * 60;
|
||||||
|
|
||||||
|
function makeEngine(timeStepSeconds) {
|
||||||
|
return new Reactor_CSTR(makeReactorConfig({ reactor_type: 'CSTR', n_inlets: 1, timeStep: timeStepSeconds }));
|
||||||
|
}
|
||||||
|
|
||||||
|
test('engine stores timeStep in days, treating input as seconds', () => {
|
||||||
|
const eng = makeEngine(1);
|
||||||
|
assert.ok(Math.abs(eng.timeStep - 1 / SECONDS_PER_DAY) < 1e-15,
|
||||||
|
`engine.timeStep should be 1/86400 days for a 1-second config; got ${eng.timeStep}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('engine timeStep scales linearly with config.timeStep (seconds in)', () => {
|
||||||
|
const a = makeEngine(1);
|
||||||
|
const b = makeEngine(10);
|
||||||
|
assert.ok(Math.abs(b.timeStep - 10 * a.timeStep) < 1e-15,
|
||||||
|
'engine.timeStep must scale linearly with config.timeStep; broke the seconds→days conversion');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('schema default for timeStep matches the seconds convention', () => {
|
||||||
|
const path = require('node:path');
|
||||||
|
const gfRoot = path.dirname(require.resolve('generalFunctions'));
|
||||||
|
const schema = require(path.join(gfRoot, 'src/configs/reactor.json'));
|
||||||
|
assert.equal(schema.reactor.timeStep.rules.unit, 's',
|
||||||
|
'schema timeStep.unit must be "s" — engine treats input as seconds');
|
||||||
|
assert.equal(schema.reactor.timeStep.default, 1,
|
||||||
|
'schema timeStep.default must be 1 (1 second), matching reactor.html');
|
||||||
|
});
|
||||||
@@ -1,15 +1,65 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Phase 10 rewrite: drives only the public BaseNodeAdapter surface.
|
||||||
|
// The schema validator coerces `reactor_type` through the enum — values
|
||||||
|
// outside `CSTR` / `PFR` are remapped to the default `CSTR` at validation
|
||||||
|
// time. The Reactor wrapper additionally falls back to CSTR if anything
|
||||||
|
// unrecognised slips through (defensive guard). Either way, the observable
|
||||||
|
// effect after `new nodeClass(...)` is `inst.source.engine instanceof
|
||||||
|
// Reactor_CSTR`.
|
||||||
|
|
||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
const NodeClass = require('../../src/nodeClass');
|
const nodeClass = require('../../src/nodeClass');
|
||||||
const { makeNodeStub, makeUiConfig } = require('../helpers/factories');
|
const { Reactor_CSTR } = require('../../src/specificClass');
|
||||||
|
const { makeUiConfig } = require('../helpers/factories');
|
||||||
|
|
||||||
test('_setupClass with unknown reactor_type throws (known error-path behavior)', () => {
|
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||||
const inst = Object.create(NodeClass.prototype);
|
|
||||||
inst.node = makeNodeStub();
|
|
||||||
inst.config = makeUiConfig({ reactor_type: 'UNKNOWN_TYPE' });
|
|
||||||
|
|
||||||
assert.throws(() => {
|
function makeNode(id = 'reactor-node-1') {
|
||||||
inst._setupClass();
|
const sends = [];
|
||||||
});
|
const statuses = [];
|
||||||
|
const handlers = {};
|
||||||
|
return {
|
||||||
|
id, sends, statuses, handlers,
|
||||||
|
send(arr) { sends.push(arr); },
|
||||||
|
status(b) { statuses.push(b); },
|
||||||
|
on(ev, fn) { handlers[ev] = fn; },
|
||||||
|
warn() {}, error() {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeNode(node) {
|
||||||
|
if (node.handlers.close) node.handlers.close(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Reactor wrapper falls back to CSTR when reactor_type is unknown', () => {
|
||||||
|
const node = makeNode();
|
||||||
|
const inst = new nodeClass(
|
||||||
|
makeUiConfig({ reactor_type: 'UNKNOWN_TYPE' }),
|
||||||
|
makeRED(),
|
||||||
|
node,
|
||||||
|
'reactor',
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
assert.ok(inst.source.engine instanceof Reactor_CSTR);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Reactor wrapper falls back to CSTR when reactor_type is empty string', () => {
|
||||||
|
const node = makeNode();
|
||||||
|
const inst = new nodeClass(
|
||||||
|
makeUiConfig({ reactor_type: '' }),
|
||||||
|
makeRED(),
|
||||||
|
node,
|
||||||
|
'reactor',
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
assert.ok(inst.source.engine instanceof Reactor_CSTR);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,30 +1,68 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Phase 10 rewrite: drives only the public BaseNodeAdapter surface. The
|
||||||
|
// commands registry built by BaseNodeAdapter logs a warn on unknown topics
|
||||||
|
// and still calls done — no throw.
|
||||||
|
|
||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
const NodeClass = require('../../src/nodeClass');
|
const nodeClass = require('../../src/nodeClass');
|
||||||
const { makeNodeStub, makeREDStub } = require('../helpers/factories');
|
const { makeUiConfig } = require('../helpers/factories');
|
||||||
|
|
||||||
test('unknown input topic does not throw and still calls done', () => {
|
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||||
const inst = Object.create(NodeClass.prototype);
|
|
||||||
const node = makeNodeStub();
|
|
||||||
|
|
||||||
inst.node = node;
|
function makeNode(id = 'reactor-node-1') {
|
||||||
inst.RED = makeREDStub();
|
const sends = [];
|
||||||
inst.source = {
|
const statuses = [];
|
||||||
childRegistrationUtils: {
|
const handlers = {};
|
||||||
registerChild() {},
|
return {
|
||||||
},
|
id, sends, statuses, handlers,
|
||||||
updateState() {},
|
send(arr) { sends.push(arr); },
|
||||||
|
status(b) { statuses.push(b); },
|
||||||
|
on(ev, fn) { handlers[ev] = fn; },
|
||||||
|
warn() {}, error() {},
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
inst._attachInputHandler();
|
function closeNode(node) {
|
||||||
|
if (node.handlers.close) node.handlers.close(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
let doneCalled = 0;
|
test('unknown input topic does not throw and still calls done', async () => {
|
||||||
assert.doesNotThrow(() => {
|
const node = makeNode();
|
||||||
node._handlers.input({ topic: 'somethingUnknown', payload: 1 }, () => {}, () => {
|
new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||||
doneCalled += 1;
|
|
||||||
|
try {
|
||||||
|
let doneCalled = 0;
|
||||||
|
await assert.doesNotReject(async () => {
|
||||||
|
await node.handlers.input(
|
||||||
|
{ topic: 'somethingUnknown', payload: 1 },
|
||||||
|
() => {},
|
||||||
|
() => { doneCalled += 1; },
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
assert.equal(doneCalled, 1);
|
||||||
|
} finally {
|
||||||
assert.equal(doneCalled, 1);
|
closeNode(node);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('missing topic field is handled gracefully', async () => {
|
||||||
|
const node = makeNode();
|
||||||
|
new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||||
|
|
||||||
|
try {
|
||||||
|
let doneCalled = 0;
|
||||||
|
await assert.doesNotReject(async () => {
|
||||||
|
await node.handlers.input(
|
||||||
|
{ payload: 'no-topic-here' },
|
||||||
|
() => {},
|
||||||
|
() => { doneCalled += 1; },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert.equal(doneCalled, 1);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,28 +1,91 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Phase 10 rewrite: drives only the public BaseNodeAdapter surface.
|
||||||
|
// A child.register / registerChild msg with an unknown id should resolve
|
||||||
|
// to no-op (the handler logs warn, no throw) and still call done.
|
||||||
|
|
||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
const NodeClass = require('../../src/nodeClass');
|
const nodeClass = require('../../src/nodeClass');
|
||||||
const { makeNodeStub, makeREDStub } = require('../helpers/factories');
|
const { makeUiConfig } = require('../helpers/factories');
|
||||||
|
|
||||||
test('registerChild with unknown node id is ignored without throwing', () => {
|
function makeRED(nodeMap = {}) {
|
||||||
const inst = Object.create(NodeClass.prototype);
|
return { nodes: { getNode: (id) => nodeMap[id] || null } };
|
||||||
const node = makeNodeStub();
|
}
|
||||||
|
|
||||||
inst.node = node;
|
function makeNode(id = 'reactor-node-1') {
|
||||||
inst.RED = makeREDStub();
|
const sends = [];
|
||||||
inst.source = {
|
const statuses = [];
|
||||||
childRegistrationUtils: {
|
const handlers = {};
|
||||||
registerChild() {},
|
return {
|
||||||
},
|
id, sends, statuses, handlers,
|
||||||
|
send(arr) { sends.push(arr); },
|
||||||
|
status(b) { statuses.push(b); },
|
||||||
|
on(ev, fn) { handlers[ev] = fn; },
|
||||||
|
warn() {}, error() {},
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
inst._attachInputHandler();
|
function closeNode(node) {
|
||||||
|
if (node.handlers.close) node.handlers.close(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
assert.doesNotThrow(() => {
|
test('registerChild alias with unknown id is ignored without throwing', async () => {
|
||||||
node._handlers.input(
|
const node = makeNode();
|
||||||
{ topic: 'registerChild', payload: 'missing-child', positionVsParent: 'upstream' },
|
new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||||
() => {},
|
|
||||||
() => {},
|
try {
|
||||||
);
|
let done = 0;
|
||||||
});
|
await assert.doesNotReject(async () => {
|
||||||
|
await node.handlers.input(
|
||||||
|
{ topic: 'registerChild', payload: 'missing-child', positionVsParent: 'upstream' },
|
||||||
|
() => {},
|
||||||
|
() => { done += 1; },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert.equal(done, 1);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('child.register canonical topic with unknown id is ignored without throwing', async () => {
|
||||||
|
const node = makeNode();
|
||||||
|
new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||||
|
|
||||||
|
try {
|
||||||
|
let done = 0;
|
||||||
|
await assert.doesNotReject(async () => {
|
||||||
|
await node.handlers.input(
|
||||||
|
{ topic: 'child.register', payload: 'missing-child', positionVsParent: 'upstream' },
|
||||||
|
() => {},
|
||||||
|
() => { done += 1; },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert.equal(done, 1);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('child.register with a child that has no .source is ignored without throwing', async () => {
|
||||||
|
const node = makeNode();
|
||||||
|
// The looked-up RED node exists but lacks a `.source` — the handler
|
||||||
|
// guards against this and logs warn.
|
||||||
|
new nodeClass(makeUiConfig(), makeRED({ orphan: {} }), node, 'reactor');
|
||||||
|
|
||||||
|
try {
|
||||||
|
let done = 0;
|
||||||
|
await assert.doesNotReject(async () => {
|
||||||
|
await node.handlers.input(
|
||||||
|
{ topic: 'child.register', payload: 'orphan', positionVsParent: 'upstream' },
|
||||||
|
() => {},
|
||||||
|
() => { done += 1; },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert.equal(done, 1);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ function makeUiConfig(overrides = {}) {
|
|||||||
X_S_init: 75,
|
X_S_init: 75,
|
||||||
X_H_init: 30,
|
X_H_init: 30,
|
||||||
X_STO_init: 0,
|
X_STO_init: 0,
|
||||||
X_A_init: 0.001,
|
X_A_init: 200,
|
||||||
X_TS_init: 125,
|
X_TS_init: 125,
|
||||||
timeStep: 1,
|
timeStep: 1,
|
||||||
enableLog: false,
|
enableLog: false,
|
||||||
|
|||||||
@@ -1,134 +1,156 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Phase 10 rewrite: drives only the public BaseNodeAdapter surface.
|
||||||
|
// The pre-refactor _tick / _startTickLoop methods are gone — periodic
|
||||||
|
// emission lives in `_emitOutputs()` (overridden in the reactor nodeClass
|
||||||
|
// to preserve the Fluent / GridProfile Port-0 contract; delta-compressed
|
||||||
|
// payloads can't carry the C-vector). The override is part of the
|
||||||
|
// documented BaseNodeAdapter override surface, so we exercise it
|
||||||
|
// directly. The fully-constructed adapter wires `inst.source.engine`,
|
||||||
|
// `inst._output`, etc. so we don't have to assemble stub bags.
|
||||||
|
|
||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
const NodeClass = require('../../src/nodeClass');
|
const nodeClass = require('../../src/nodeClass');
|
||||||
const { makeNodeStub } = require('../helpers/factories');
|
const { makeUiConfig } = require('../helpers/factories');
|
||||||
|
|
||||||
test('_tick emits source effluent on process output', () => {
|
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||||
const inst = Object.create(NodeClass.prototype);
|
|
||||||
const node = makeNodeStub();
|
|
||||||
|
|
||||||
inst.node = node;
|
function makeNode(id = 'reactor-node-1') {
|
||||||
inst._output = { formatMsg() { return null; } };
|
const sends = [];
|
||||||
inst.source = {
|
const statuses = [];
|
||||||
get getEffluent() {
|
const handlers = {};
|
||||||
return { topic: 'Fluent', payload: { inlet: 0, F: 1, C: [] }, timestamp: 1 };
|
return {
|
||||||
},
|
id, sends, statuses, handlers,
|
||||||
|
send(arr) { sends.push(arr); },
|
||||||
|
status(b) { statuses.push(b); },
|
||||||
|
on(ev, fn) { handlers[ev] = fn; },
|
||||||
|
warn() {}, error() {},
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
inst._tick();
|
function closeNode(node) {
|
||||||
|
if (node.handlers.close) node.handlers.close(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
assert.equal(node._sent.length, 1);
|
function pickEffluentSends(node) {
|
||||||
assert.equal(node._sent[0][0].topic, 'Fluent');
|
return node.sends.filter((s) => Array.isArray(s) && s[0] && s[0].topic === 'Fluent');
|
||||||
assert.equal(node._sent[0][1], null);
|
}
|
||||||
assert.equal(node._sent[0][2], null);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('_tick emits reactor telemetry on influx output', () => {
|
function pickGridSends(node) {
|
||||||
const inst = Object.create(NodeClass.prototype);
|
return node.sends.filter((s) => Array.isArray(s) && s[0] && s[0].topic === 'GridProfile');
|
||||||
const node = makeNodeStub();
|
}
|
||||||
let captured = null;
|
|
||||||
|
|
||||||
inst.node = node;
|
test('_emitOutputs sends the effluent message on process output (CSTR)', () => {
|
||||||
inst.config = { functionality: { softwareType: 'reactor' }, general: { id: 'reactor-node-1' } };
|
const node = makeNode();
|
||||||
inst._output = {
|
const inst = new nodeClass(
|
||||||
formatMsg(output, config, format) {
|
makeUiConfig({ reactor_type: 'CSTR' }),
|
||||||
captured = { output, config, format };
|
makeRED(),
|
||||||
return { topic: 'reactor_reactor-node-1', payload: { measurement: 'reactor_reactor-node-1', fields: output } };
|
node,
|
||||||
}
|
'reactor',
|
||||||
};
|
);
|
||||||
inst.source = {
|
|
||||||
temperature: 19.5,
|
|
||||||
get getGridProfile() {
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
get getEffluent() {
|
|
||||||
return {
|
|
||||||
topic: 'Fluent',
|
|
||||||
payload: {
|
|
||||||
inlet: 0,
|
|
||||||
F: 42,
|
|
||||||
C: [2.1, 30, 100, 16, 0, 1, 8, 25, 75, 1500, 0, 15, 2500]
|
|
||||||
},
|
|
||||||
timestamp: 1
|
|
||||||
};
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
inst._tick();
|
|
||||||
|
|
||||||
assert.equal(node._sent.length, 1);
|
|
||||||
assert.equal(node._sent[0][0].topic, 'Fluent');
|
|
||||||
assert.equal(node._sent[0][1].topic, 'reactor_reactor-node-1');
|
|
||||||
assert.equal(captured.format, 'influxdb');
|
|
||||||
assert.equal(captured.output.flow_total, 42);
|
|
||||||
assert.equal(captured.output.temperature, 19.5);
|
|
||||||
assert.equal(captured.output.S_O, 2.1);
|
|
||||||
assert.equal(captured.output.S_NH, 16);
|
|
||||||
assert.equal(captured.output.X_TS, 2500);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('_startTickLoop schedules periodic tick after startup delay', () => {
|
|
||||||
const inst = Object.create(NodeClass.prototype);
|
|
||||||
const delays = [];
|
|
||||||
const intervals = [];
|
|
||||||
let tickCount = 0;
|
|
||||||
|
|
||||||
inst._tick = () => {
|
|
||||||
tickCount += 1;
|
|
||||||
};
|
|
||||||
|
|
||||||
const originalSetTimeout = global.setTimeout;
|
|
||||||
const originalSetInterval = global.setInterval;
|
|
||||||
|
|
||||||
global.setTimeout = (fn, ms) => {
|
|
||||||
delays.push(ms);
|
|
||||||
fn();
|
|
||||||
return 10;
|
|
||||||
};
|
|
||||||
|
|
||||||
global.setInterval = (fn, ms) => {
|
|
||||||
intervals.push(ms);
|
|
||||||
fn();
|
|
||||||
return 22;
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
inst._startTickLoop();
|
// Reset sends so any construction-time emissions don't pollute the
|
||||||
} finally {
|
// assertion (the registration triple lands on the same buffer).
|
||||||
global.setTimeout = originalSetTimeout;
|
node.sends.length = 0;
|
||||||
global.setInterval = originalSetInterval;
|
inst._emitOutputs();
|
||||||
}
|
|
||||||
|
|
||||||
assert.deepEqual(delays, [1000]);
|
const fluentSends = pickEffluentSends(node);
|
||||||
assert.deepEqual(intervals, [1000]);
|
assert.equal(fluentSends.length, 1, 'exactly one Fluent message');
|
||||||
assert.equal(inst._tickInterval, 22);
|
const triple = fluentSends[0];
|
||||||
assert.equal(tickCount, 1);
|
assert.equal(triple[0].topic, 'Fluent');
|
||||||
|
assert.ok(triple[0].payload && Array.isArray(triple[0].payload.C));
|
||||||
|
// CSTR has no grid profile.
|
||||||
|
assert.equal(pickGridSends(node).length, 0);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('_attachCloseHandler clears tick interval and calls done callback', () => {
|
test('_emitOutputs emits a GridProfile message when engine exposes one (PFR)', () => {
|
||||||
const inst = Object.create(NodeClass.prototype);
|
const node = makeNode();
|
||||||
const node = makeNodeStub();
|
const inst = new nodeClass(
|
||||||
inst.node = node;
|
makeUiConfig({ reactor_type: 'PFR' }),
|
||||||
inst._tickInterval = 55;
|
makeRED(),
|
||||||
|
node,
|
||||||
const cleared = [];
|
'reactor',
|
||||||
const originalClearInterval = global.clearInterval;
|
);
|
||||||
global.clearInterval = (id) => {
|
|
||||||
cleared.push(id);
|
|
||||||
};
|
|
||||||
|
|
||||||
let doneCalled = 0;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
inst._attachCloseHandler();
|
node.sends.length = 0;
|
||||||
node._handlers.close(() => {
|
inst._emitOutputs();
|
||||||
doneCalled += 1;
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
global.clearInterval = originalClearInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
assert.deepEqual(cleared, [55]);
|
assert.equal(pickGridSends(node).length, 1, 'exactly one GridProfile message');
|
||||||
assert.equal(doneCalled, 1);
|
assert.equal(pickEffluentSends(node).length, 1, 'exactly one Fluent message');
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('_emitOutputs formats per-species influx telemetry via outputUtils', () => {
|
||||||
|
const node = makeNode();
|
||||||
|
const inst = new nodeClass(
|
||||||
|
makeUiConfig({ reactor_type: 'CSTR' }),
|
||||||
|
makeRED(),
|
||||||
|
node,
|
||||||
|
'reactor',
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Stub updateState so the engine integration does not overwrite the
|
||||||
|
// engineered state we want the telemetry formatter to see.
|
||||||
|
inst.source.updateState = () => {};
|
||||||
|
inst.source.engine.setInfluent = {
|
||||||
|
payload: { inlet: 0, F: 42, C: [2.1, 30, 100, 16, 0, 1, 8, 25, 75, 1500, 0, 15, 2500] },
|
||||||
|
};
|
||||||
|
inst.source.engine.state = [2.1, 30, 100, 16, 0, 1, 8, 25, 75, 1500, 0, 15, 2500];
|
||||||
|
inst.source.engine.temperature = 19.5;
|
||||||
|
|
||||||
|
let captured = null;
|
||||||
|
const realFormat = inst._output.formatMsg.bind(inst._output);
|
||||||
|
inst._output.formatMsg = (output, cfg, format) => {
|
||||||
|
if (format === 'influxdb') captured = { output, format };
|
||||||
|
return realFormat(output, cfg, format);
|
||||||
|
};
|
||||||
|
|
||||||
|
node.sends.length = 0;
|
||||||
|
inst._emitOutputs();
|
||||||
|
|
||||||
|
assert.ok(captured, 'formatMsg was called with influxdb format');
|
||||||
|
assert.equal(captured.format, 'influxdb');
|
||||||
|
assert.equal(captured.output.flow_total, 42);
|
||||||
|
assert.equal(captured.output.temperature, 19.5);
|
||||||
|
assert.equal(captured.output.S_O, 2.1);
|
||||||
|
assert.equal(captured.output.S_NH, 16);
|
||||||
|
assert.equal(captured.output.X_TS, 2500);
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Reactor.tick(dt) drives the kinetics engine and advances state', () => {
|
||||||
|
const node = makeNode();
|
||||||
|
const inst = new nodeClass(
|
||||||
|
makeUiConfig({ reactor_type: 'CSTR' }),
|
||||||
|
makeRED(),
|
||||||
|
node,
|
||||||
|
'reactor',
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Feed an influent so the integrator has something to chew on.
|
||||||
|
inst.source.engine.setInfluent = {
|
||||||
|
payload: { inlet: 0, F: 5, C: [0,30,100,16,0,0,5,25,75,30,0,0.001,125] },
|
||||||
|
};
|
||||||
|
|
||||||
|
const stateBefore = JSON.stringify(inst.source.engine.state);
|
||||||
|
inst.source.tick(0.001);
|
||||||
|
const stateAfter = JSON.stringify(inst.source.engine.state);
|
||||||
|
|
||||||
|
assert.notEqual(stateBefore, stateAfter, 'engine state should advance after tick(dt)');
|
||||||
|
} finally {
|
||||||
|
closeNode(node);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
182
wiki/Home.md
Normal file
182
wiki/Home.md
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
# reactor
|
||||||
|
|
||||||
|
  
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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<br/>upstream<br/>Unit]:::unit
|
||||||
|
rx[reactor<br/>Unit]:::unit
|
||||||
|
settler[settler<br/>downstream<br/>Unit]:::unit
|
||||||
|
diffuser[diffuser<br/>Equipment]:::equip
|
||||||
|
tsens[measurement<br/>temperature<br/>atEquipment]:::ctrl
|
||||||
|
osens[measurement<br/>quantity (oxygen)<br/>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<br/>positionVsParent=upstream| rx
|
||||||
|
|
||||||
|
classDef unit fill:#50a8d9,color:#000
|
||||||
|
classDef equip fill:#86bbdd,color:#000
|
||||||
|
classDef ctrl fill:#a9daee,color:#000
|
||||||
|
```
|
||||||
|
|
||||||
|
S88 colours are anchored in `.claude/rules/node-red-flow-layout.md`.
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Try it — 3-minute demo
|
||||||
|
|
||||||
|
Import the basic example flow, deploy, and watch a CSTR consume influent over the simulation clock.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST -H 'Content-Type: application/json' \
|
||||||
|
--data @nodes/reactor/examples/basic.flow.json \
|
||||||
|
http://localhost:1880/flow
|
||||||
|
```
|
||||||
|
|
||||||
|
What to click after deploy (each inject maps one-to-one to a topic in [Reference — Contracts](Reference-Contracts#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`).
|
||||||
|
|
||||||
|
> [!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`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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. |
|
||||||
|
|
||||||
|
> [!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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What you'll see come out
|
||||||
|
|
||||||
|
Sample Port 0 message (CSTR mid-integration, nitrifying):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
```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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
| 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). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The interesting bits
|
||||||
|
|
||||||
|
### CSTR vs PFR
|
||||||
|
|
||||||
|
The engine is selected once at `configure()` from `reactor.reactor_type`. The same input topics drive both, but PFR additionally:
|
||||||
|
|
||||||
|
- 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).
|
||||||
|
|
||||||
|
Hot-swapping engine type at runtime is not supported — redeploy the flow.
|
||||||
|
|
||||||
|
### Aeration: internal `kla` vs external `data.otr`
|
||||||
|
|
||||||
|
`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).
|
||||||
|
|
||||||
|
### `X_A` footgun
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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)
|
||||||
293
wiki/Reference-Architecture.md
Normal file
293
wiki/Reference-Architecture.md
Normal file
@@ -0,0 +1,293 @@
|
|||||||
|
# Reference — Architecture
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> [!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<br/>or tick(dt)]:::input --> us[updateState(newTime)]
|
||||||
|
us --> ni{n_iter = floor(<br/>speedUpFactor × Δt / timeStep)}
|
||||||
|
ni -->|0| skip[no-op]
|
||||||
|
ni -->|>0| loop[for each step:<br/>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]<br/>OTR, temperature, kla<br/>upstreamReactor link<br/>updateState(newTime)<br/>_connectMeasurement / _connectReactor"]
|
||||||
|
end
|
||||||
|
subgraph cstr["Reactor_CSTR"]
|
||||||
|
cs["state = number[13]<br/>tick(dt):<br/> inflow + outflow + reaction + transfer<br/> Forward Euler<br/> _capDissolvedOxygen / _arrayClip2Zero"]
|
||||||
|
end
|
||||||
|
subgraph pfr["Reactor_PFR"]
|
||||||
|
ps["state = number[n_x][13]<br/>length, n_x, d_x, A, alpha, D<br/>D_op / D2_op finite-difference operators<br/>tick(dt):<br/> dispersion + advection + reaction + transfer<br/> Explicit FD<br/> Danckwerts inlet / Neumann outlet BC<br/> 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<br/>asset.type=temperature<br/>positionVsParent=atEquipment"]:::ctrl
|
||||||
|
m_o["measurement<br/>asset.type=quantity (oxygen)<br/>positionVsParent=numeric distance (PFR)"]:::ctrl
|
||||||
|
r_up["reactor<br/>positionVsParent=upstream"]:::unit
|
||||||
|
end
|
||||||
|
m_t -->|temperature.measured.atEquipment| h_meas["engine._connectMeasurement<br/>(baseEngine.js)"]
|
||||||
|
m_o -->|quantity(oxygen).measured.<distance>| h_meas
|
||||||
|
r_up -.stateChange.-> h_react["engine._connectReactor<br/>(baseEngine.js)"]
|
||||||
|
h_meas --> reconcile["reconcile T → engine.temperature<br/>reconcile O2 → state grid cell (PFR only)"]
|
||||||
|
h_react --> pull["pull upstream getEffluent<br/>→ 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 `<measurementType>.measured.<position>` 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 '<x>' 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: <node.id>, positionVsParent, distance}` |
|
||||||
|
|
||||||
|
<!-- BEGIN AUTOGEN: data-model — populate via wiki-gen tool (TODO) -->
|
||||||
|
|
||||||
|
> [!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 |
|
||||||
|
|
||||||
|
<!-- END AUTOGEN: data-model -->
|
||||||
|
|
||||||
|
### Status badge
|
||||||
|
|
||||||
|
Composed by `getStatusBadge()` in `src/specificClass.js`:
|
||||||
|
|
||||||
|
```
|
||||||
|
<EngineType> T=<temperature> C F=<flow> m³/d S_O=<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 `<type>.measured.<position>` | `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 |
|
||||||
227
wiki/Reference-Contracts.md
Normal file
227
wiki/Reference-Contracts.md
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
# Reference — Contracts
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> [!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.
|
||||||
|
|
||||||
|
<!-- BEGIN AUTOGEN: topic-contract -->
|
||||||
|
|
||||||
|
| 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. |
|
||||||
|
|
||||||
|
<!-- END AUTOGEN: topic-contract -->
|
||||||
|
|
||||||
|
### 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": <m³/d>, "C": [<13 species, mg/L>] },
|
||||||
|
"timestamp": <ms since epoch>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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": <int>,
|
||||||
|
"d_x": <m>,
|
||||||
|
"length": <m>,
|
||||||
|
"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": <ms since epoch>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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`:
|
||||||
|
|
||||||
|
```
|
||||||
|
<EngineType> T=<°C>.X C F=<m³/d>.XX m³/d S_O=<mg/L>.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 = <numeric distance>` | `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: <x>` 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 |
|
||||||
160
wiki/Reference-Examples.md
Normal file
160
wiki/Reference-Examples.md
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
# Reference — Examples
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> [!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": "<upstream-reactor-node-id>",
|
||||||
|
"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: <m²/d>` 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: <raw>` 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 '<x>' 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 |
|
||||||
132
wiki/Reference-Limitations.md
Normal file
132
wiki/Reference-Limitations.md
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
# Reference — Limitations
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> [!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 |
|
||||||
20
wiki/_Sidebar.md
Normal file
20
wiki/_Sidebar.md
Normal file
@@ -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)
|
||||||
Reference in New Issue
Block a user