Compare commits
6 Commits
main
...
d735f9485c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d735f9485c | ||
|
|
c84dd781a3 | ||
|
|
1aa2d92083 | ||
|
|
297c6713de | ||
|
|
d931bead0a | ||
|
|
7bf464b467 |
51
CONTRACT.md
Normal file
51
CONTRACT.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# reactor — Contract
|
||||
|
||||
Hand-maintained for Phase 6; the `## Inputs` table is generated from
|
||||
`src/commands/index.js` (see Phase 9 generator). Keep ≤ 80 lines.
|
||||
|
||||
## 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",
|
||||
"main": "reactor.js",
|
||||
"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": {
|
||||
"nodes": {
|
||||
|
||||
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;
|
||||
227
src/nodeClass.js
227
src/nodeClass.js
@@ -1,207 +1,52 @@
|
||||
const { Reactor_CSTR, Reactor_PFR } = require('./specificClass.js');
|
||||
const { outputUtils, configManager } = require('generalFunctions');
|
||||
'use strict';
|
||||
|
||||
const REACTOR_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'
|
||||
];
|
||||
const { BaseNodeAdapter } = require('generalFunctions');
|
||||
const Reactor = require('./specificClass.js');
|
||||
const commands = require('./commands');
|
||||
|
||||
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 {
|
||||
/**
|
||||
* Node-RED node class for advanced-reactor.
|
||||
* @param {object} uiConfig - Node-RED node configuration
|
||||
* @param {object} RED - Node-RED runtime API
|
||||
* @param {object} nodeInstance - Node-RED node instance
|
||||
* @param {string} nameOfNode - Name of the node
|
||||
*/
|
||||
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;
|
||||
class nodeClass extends BaseNodeAdapter {
|
||||
static DomainClass = Reactor;
|
||||
static commands = commands;
|
||||
// Tick-driven: ASM kinetics integrate over wall-clock time. The engine's
|
||||
// updateState computes how many internal Euler/FD steps fit in the elapsed
|
||||
// ms; without a periodic tick the integrator never advances.
|
||||
static tickInterval = 1000;
|
||||
static statusInterval = 1000;
|
||||
|
||||
this._loadConfig(uiConfig)
|
||||
this._setupClass();
|
||||
this._output = new outputUtils();
|
||||
|
||||
this._attachInputHandler();
|
||||
this._registerChild();
|
||||
this._startTickLoop();
|
||||
this._attachCloseHandler();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle node-red input messages
|
||||
*/
|
||||
_attachInputHandler() {
|
||||
this.node.on('input', (msg, send, done) => {
|
||||
try {
|
||||
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, {
|
||||
buildDomainConfig(uiConfig) {
|
||||
const initialState = {};
|
||||
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),
|
||||
resolution_L: parseInt(uiConfig.resolution_L, 10),
|
||||
alpha: parseFloat(uiConfig.alpha),
|
||||
n_inlets: parseInt(uiConfig.n_inlets),
|
||||
n_inlets: parseInt(uiConfig.n_inlets, 10),
|
||||
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),
|
||||
speedUpFactor: Number(uiConfig.speedUpFactor) || 1,
|
||||
},
|
||||
initialState,
|
||||
};
|
||||
|
||||
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();
|
||||
});
|
||||
// The kinetics engine drives Port-0 effluent + grid-profile shapes that
|
||||
// don't fit BaseNodeAdapter's delta-compressed payload. Override the
|
||||
// periodic emission so the Fluent / GridProfile contract is preserved.
|
||||
_emitOutputs() {
|
||||
const src = this.source;
|
||||
if (!src?.engine) return;
|
||||
src.updateState(Date.now());
|
||||
const grid = src.getGridProfile;
|
||||
if (grid) this.node.send([{ topic: 'GridProfile', payload: grid }, null, null]);
|
||||
const raw = src.getOutput();
|
||||
const influx = this._output.formatMsg(raw, src.config || this.config, 'influxdb');
|
||||
this.node.send([src.getEffluent, influx, null]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,481 +1,134 @@
|
||||
const ASM3 = require('./reaction_modules/asm3_class.js');
|
||||
const { create, all, isArray } = require('mathjs');
|
||||
const { assertNoNaN } = require('./utils.js');
|
||||
const { childRegistrationUtils, logger, MeasurementContainer, POSITIONS } = require('generalFunctions');
|
||||
const EventEmitter = require('events');
|
||||
'use strict';
|
||||
|
||||
const mathConfig = {
|
||||
matrix: 'Array' // use Array as the matrix type
|
||||
};
|
||||
const { BaseDomain, statusBadge, POSITIONS } = require('generalFunctions');
|
||||
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;
|
||||
const NUM_SPECIES = 13;
|
||||
const DEBUG = false;
|
||||
// Reactor — biological reactor orchestrator (Unit-level). Wraps a CSTR or
|
||||
// PFR kinetics engine and exposes the BaseDomain surface to BaseNodeAdapter.
|
||||
// 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 {
|
||||
/**
|
||||
* Reactor base class.
|
||||
* @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
|
||||
configure() {
|
||||
const flat = this._flattenEngineConfig(this.config);
|
||||
this.engine = this._buildEngine(flat);
|
||||
|
||||
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]
|
||||
this.Cs_in = Array.from(Array(config.n_inlets), () => new Array(NUM_SPECIES).fill(0)); // composition influents
|
||||
this.OTR = 0.0; // oxygen transfer rate [g O2 d-1 m-3]
|
||||
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
|
||||
// Bridge engine.measurements into the BaseDomain measurements container
|
||||
// so getFlattenedOutput surfaces temperature / oxygen series.
|
||||
this.measurements = this.engine.measurements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for influent data.
|
||||
* @param {object} input - Input object (msg) containing payload with inlet index, flow rate, and concentrations.
|
||||
*/
|
||||
set setInfluent(input) {
|
||||
let index_in = input.payload.inlet;
|
||||
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() {
|
||||
// Translate the nested schema config (reactor.*, initialState.*) into the
|
||||
// flat shape the kinetics engines accept.
|
||||
_flattenEngineConfig(config) {
|
||||
const reactor = config.reactor || {};
|
||||
const init = config.initialState || {};
|
||||
const initialState = SPECIES_KEYS.map((k) => Number(init[k] ?? 0));
|
||||
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
|
||||
general: config.general,
|
||||
functionality: config.functionality,
|
||||
reactor_type: reactor.reactor_type ?? 'CSTR',
|
||||
volume: Number(reactor.volume),
|
||||
length: Number(reactor.length),
|
||||
resolution_L: Number(reactor.resolution_L),
|
||||
alpha: Number(reactor.alpha),
|
||||
n_inlets: Number(reactor.n_inlets),
|
||||
kla: Number(reactor.kla),
|
||||
timeStep: Number(reactor.timeStep),
|
||||
speedUpFactor: Number(reactor.speedUpFactor) || 1,
|
||||
initialState,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for axial dispersion.
|
||||
* @param {object} input - Input object (msg) containing payload with dispersion value [m2 d-1].
|
||||
*/
|
||||
set setDispersion(input) {
|
||||
this.D = input.payload;
|
||||
}
|
||||
|
||||
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;
|
||||
_buildEngine(flat) {
|
||||
// The schema enum validator lowercases the configured value, so accept
|
||||
// either case.
|
||||
switch (String(flat.reactor_type || '').toUpperCase()) {
|
||||
case 'CSTR': return new Reactor_CSTR(flat);
|
||||
case 'PFR': return new Reactor_PFR(flat);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply boundary conditions to the reactor state.
|
||||
* for inlet, apply generalised Danckwerts BC, if there is not flow, apply Neumann BC with no flux
|
||||
* for outlet, apply regular Danckwerts BC (Neumann BC with no flux)
|
||||
* @param {Array} state - Current reactor state without enforced BCs.
|
||||
*/
|
||||
_applyBoundaryConditions(state) {
|
||||
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];
|
||||
const BC_dispersion_term = (1-this.alpha)*this.D*this.A/(math.sum(this.Fs)*this.d_x);
|
||||
state[0] = math.multiply(1/(1+BC_dispersion_term), math.add(BC_C_in, math.multiply(BC_dispersion_term, state[1])));
|
||||
} else {
|
||||
state[0] = state[1];
|
||||
}
|
||||
// Neumann BC (no flux)
|
||||
state[this.n_x-1] = state[this.n_x-2];
|
||||
// Adapter input setters — forwarded straight to the engine.
|
||||
set setInfluent(msg) { this.engine.setInfluent = msg; }
|
||||
set setOTR(msg) { this.engine.setOTR = msg; }
|
||||
set setTemperature(msg) { this.engine.setTemperature = msg; }
|
||||
set setDispersion(msg) { if (this.engine instanceof Reactor_PFR) this.engine.setDispersion = msg; }
|
||||
|
||||
updateState(t) { this.engine.updateState(t); this.notifyOutputChanged(); }
|
||||
|
||||
// Engine pass-through — needed so the BaseNodeAdapter tick loop (and
|
||||
// tests calling reactor.tick(dt) directly) drive the ASM integration.
|
||||
// Without this the Node-RED tick fires `source.tick?.()`, gets undefined,
|
||||
// and the kinetics state never advances.
|
||||
tick(timeStep) {
|
||||
const result = this.engine.tick(timeStep);
|
||||
this.notifyOutputChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create finite difference first derivative operator.
|
||||
* @param {boolean} central - Use central difference scheme if true, otherwise use upwind scheme.
|
||||
* @param {boolean} higher_order - Use higher order scheme if true, otherwise use first order scheme.
|
||||
* @returns {Array} - First derivative operator matrix.
|
||||
*/
|
||||
_makeDoperator(central = false, higher_order = false) { // create gradient operator
|
||||
if (higher_order) {
|
||||
if (central) {
|
||||
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);
|
||||
const NearBoundary = Array(this.n_x).fill(0.0);
|
||||
NearBoundary[0] = -1/4;
|
||||
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.");
|
||||
get getEffluent() { return this.engine.getEffluent; }
|
||||
get getGridProfile() { return this.engine.getGridProfile; }
|
||||
get temperature() { return this.engine.temperature; }
|
||||
|
||||
// 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.
|
||||
getOutput() {
|
||||
const eff = this.engine.getEffluent;
|
||||
const C = Array.isArray(eff?.payload?.C) ? eff.payload.C : [];
|
||||
const out = {
|
||||
flow_total: Number(eff?.payload?.F),
|
||||
temperature: Number(this.engine.temperature),
|
||||
};
|
||||
for (let i = 0; i < Math.min(SPECIES_KEYS.length, C.length); i += 1) {
|
||||
const v = Number(C[i]);
|
||||
if (Number.isFinite(v)) out[SPECIES_KEYS[i]] = v;
|
||||
}
|
||||
} 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() {
|
||||
const eff = this.engine.getEffluent;
|
||||
const F = Number(eff?.payload?.F) || 0;
|
||||
const SO = Array.isArray(eff?.payload?.C) ? Number(eff.payload.C[0]) : NaN;
|
||||
const so = Number.isFinite(SO) ? SO.toFixed(2) : '—';
|
||||
return statusBadge.compose(
|
||||
[`${this.engine.constructor.name.replace('Reactor_', '')}`,
|
||||
`T=${Number(this.engine.temperature).toFixed(1)} C`,
|
||||
`F=${F.toFixed(2)} m³/d`,
|
||||
`S_O=${so} mg/L`],
|
||||
{ fill: 'green', shape: 'dot' },
|
||||
);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.engine?.emitter?.removeAllListeners?.();
|
||||
super.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create central finite difference second derivative operator.
|
||||
* @returns {Array} - Second derivative operator matrix.
|
||||
*/
|
||||
_makeD2operator() { // create the central second derivative operator
|
||||
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); // set by BCs elsewhere
|
||||
D2[this.n_x - 1] = Array(this.n_x).fill(0);
|
||||
return D2;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Reactor_CSTR, Reactor_PFR };
|
||||
|
||||
// DEBUG
|
||||
// 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
|
||||
// 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];
|
||||
// const Reactor = new Reactor_PFR(200, 10, 10, 1, 100, initial_state);
|
||||
// Reactor.Cs_in[0] = [0.0, 30., 100., 16., 0., 0., 5., 25., 75., 30., 0., 0., 125.];
|
||||
// Reactor.Fs[0] = 10;
|
||||
// Reactor.D = 0.01;
|
||||
// let N = 0;
|
||||
// while (N < 5000) {
|
||||
// console.log(Reactor.tick(0.001));
|
||||
// N += 1;
|
||||
// }
|
||||
module.exports = Reactor;
|
||||
module.exports.Reactor = Reactor;
|
||||
module.exports.Reactor_CSTR = Reactor_CSTR;
|
||||
module.exports.Reactor_PFR = Reactor_PFR;
|
||||
// POSITIONS is consumed by older test setups; surface it here so they don't
|
||||
// need to chase down generalFunctions internals.
|
||||
module.exports.POSITIONS = POSITIONS;
|
||||
|
||||
@@ -1,16 +1,43 @@
|
||||
'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 assert = require('node:assert/strict');
|
||||
|
||||
const NodeClass = require('../../src/nodeClass');
|
||||
const nodeClass = require('../../src/nodeClass');
|
||||
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', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
inst.node = { id: 'n-reactor-1' };
|
||||
inst.name = 'reactor';
|
||||
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||
|
||||
inst._loadConfig(
|
||||
function makeNode(id = 'reactor-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('buildDomainConfig coerces numeric fields and builds initial state vector', () => {
|
||||
const node = makeNode();
|
||||
const inst = new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||
try {
|
||||
const dc = inst.buildDomainConfig(
|
||||
makeUiConfig({
|
||||
volume: '12.5',
|
||||
length: '9',
|
||||
@@ -22,34 +49,35 @@ test('_loadConfig coerces numeric fields and builds initial state vector', () =>
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(inst.config.volume, 12.5);
|
||||
assert.equal(inst.config.length, 9);
|
||||
assert.equal(inst.config.resolution_L, 7);
|
||||
assert.equal(inst.config.alpha, 0.5);
|
||||
assert.equal(inst.config.n_inlets, 3);
|
||||
assert.equal(inst.config.timeStep, 2);
|
||||
assert.equal(inst.config.initialState.length, 13);
|
||||
assert.equal(inst.config.initialState[0], 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', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
inst.node = makeNodeStub();
|
||||
inst.config = makeReactorConfig({ reactor_type: 'CSTR' });
|
||||
|
||||
inst._setupClass();
|
||||
|
||||
assert.ok(inst.source instanceof Reactor_CSTR);
|
||||
assert.equal(inst.node.source, inst.source);
|
||||
test('Reactor wrapper instantiates CSTR engine when configured as CSTR', () => {
|
||||
const node = makeNode();
|
||||
const inst = new nodeClass(makeUiConfig({ reactor_type: 'CSTR' }), makeRED(), node, 'reactor');
|
||||
try {
|
||||
assert.ok(inst.source.engine instanceof Reactor_CSTR);
|
||||
} finally {
|
||||
closeNode(node);
|
||||
}
|
||||
});
|
||||
|
||||
test('_setupClass selects Reactor_PFR when configured as PFR', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
inst.node = makeNodeStub();
|
||||
inst.config = makeReactorConfig({ reactor_type: 'PFR', length: 10, resolution_L: 5 });
|
||||
|
||||
inst._setupClass();
|
||||
|
||||
assert.ok(inst.source instanceof Reactor_PFR);
|
||||
assert.equal(inst.node.source, inst.source);
|
||||
test('Reactor wrapper instantiates PFR engine when configured as PFR', () => {
|
||||
const node = makeNode();
|
||||
const inst = new nodeClass(makeUiConfig({ reactor_type: 'PFR' }), makeRED(), node, 'reactor');
|
||||
try {
|
||||
assert.ok(inst.source.engine instanceof Reactor_PFR);
|
||||
} finally {
|
||||
closeNode(node);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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 assert = require('node:assert/strict');
|
||||
|
||||
const NodeClass = require('../../src/nodeClass');
|
||||
const { makeNodeStub, makeREDStub } = require('../helpers/factories');
|
||||
const nodeClass = require('../../src/nodeClass');
|
||||
const { makeUiConfig } = require('../helpers/factories');
|
||||
|
||||
test('_attachInputHandler routes supported topics to source methods/setters', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
const node = makeNodeStub();
|
||||
const calls = [];
|
||||
|
||||
const source = {
|
||||
updateState(timestamp) {
|
||||
calls.push(['clock', timestamp]);
|
||||
},
|
||||
childRegistrationUtils: {
|
||||
registerChild(childSource, position) {
|
||||
calls.push(['registerChild', childSource, position]);
|
||||
},
|
||||
},
|
||||
function makeNode(id = 'reactor-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() {},
|
||||
};
|
||||
}
|
||||
|
||||
Object.defineProperty(source, 'setInfluent', {
|
||||
set(v) {
|
||||
calls.push(['Fluent', v]);
|
||||
},
|
||||
});
|
||||
function makeRED(nodeMap = {}) {
|
||||
return { nodes: { getNode: (id) => nodeMap[id] || null } };
|
||||
}
|
||||
|
||||
Object.defineProperty(source, 'setOTR', {
|
||||
set(v) {
|
||||
calls.push(['OTR', v]);
|
||||
},
|
||||
});
|
||||
function closeNode(node) {
|
||||
if (node.handlers.close) node.handlers.close(() => {});
|
||||
}
|
||||
|
||||
Object.defineProperty(source, 'setTemperature', {
|
||||
set(v) {
|
||||
calls.push(['Temperature', v]);
|
||||
},
|
||||
});
|
||||
test('legacy alias topics drive engine setters and updateState', async () => {
|
||||
const childSource = {
|
||||
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', {
|
||||
set(v) {
|
||||
calls.push(['Dispersion', v]);
|
||||
},
|
||||
});
|
||||
|
||||
inst.node = node;
|
||||
inst.RED = makeREDStub({
|
||||
childA: {
|
||||
source: { id: 'child-source-A' },
|
||||
},
|
||||
});
|
||||
inst.source = source;
|
||||
|
||||
inst._attachInputHandler();
|
||||
|
||||
const onInput = node._handlers.input;
|
||||
const sent = [];
|
||||
try {
|
||||
let doneCount = 0;
|
||||
const done = () => { doneCount += 1; };
|
||||
|
||||
onInput({ topic: 'clock', timestamp: 1000 }, (msg) => sent.push(msg), () => doneCount++);
|
||||
onInput({ topic: 'Fluent', payload: { inlet: 0, F: 10, C: [] } }, () => {}, () => doneCount++);
|
||||
onInput({ topic: 'OTR', payload: 3.5 }, () => {}, () => doneCount++);
|
||||
onInput({ topic: 'Temperature', payload: 18.2 }, () => {}, () => doneCount++);
|
||||
onInput({ topic: 'Dispersion', payload: 0.2 }, () => {}, () => doneCount++);
|
||||
onInput({ topic: 'registerChild', payload: 'childA', positionVsParent: 'upstream' }, () => {}, () => doneCount++);
|
||||
// data.clock alias → updateState(timestamp). Capture currentTime
|
||||
// before/after to verify the engine advanced.
|
||||
const t0 = inst.source.engine.currentTime;
|
||||
await node.handlers.input({ topic: 'clock', timestamp: t0 + 1 }, () => {}, done);
|
||||
|
||||
// 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]);
|
||||
|
||||
// OTR alias → engine setOTR setter.
|
||||
await node.handlers.input({ topic: 'OTR', payload: 3.5 }, () => {}, done);
|
||||
assert.equal(inst.source.engine.OTR, 3.5);
|
||||
|
||||
// Temperature alias → engine setTemperature setter.
|
||||
await node.handlers.input({ topic: 'Temperature', payload: 18.2 }, () => {}, done);
|
||||
assert.equal(inst.source.engine.temperature, 18.2);
|
||||
|
||||
// Dispersion alias — CSTR engine does not own a setDispersion setter
|
||||
// (only PFR does); the Reactor wrapper guards on engine type and the
|
||||
// dispatch should silently return without throwing.
|
||||
await node.handlers.input({ topic: 'Dispersion', payload: 0.2 }, () => {}, done);
|
||||
|
||||
// registerChild alias → registers via childRegistrationUtils.
|
||||
// The handler resolves the child via RED.nodes.getNode(payload).source.
|
||||
await node.handlers.input(
|
||||
{ topic: 'registerChild', payload: 'childA', positionVsParent: 'upstream' },
|
||||
() => {}, done,
|
||||
);
|
||||
|
||||
assert.equal(doneCount, 6);
|
||||
assert.equal(sent.length, 1);
|
||||
assert.equal(Array.isArray(sent[0]), true);
|
||||
assert.deepEqual(calls[0], ['clock', 1000]);
|
||||
assert.equal(calls.some((x) => x[0] === 'Fluent'), true);
|
||||
assert.equal(calls.some((x) => x[0] === 'OTR'), true);
|
||||
assert.equal(calls.some((x) => x[0] === 'Temperature'), true);
|
||||
assert.equal(calls.some((x) => x[0] === 'Dispersion'), true);
|
||||
assert.deepEqual(calls.at(-1), ['registerChild', { id: 'child-source-A' }, 'upstream']);
|
||||
} 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 assert = require('node:assert/strict');
|
||||
|
||||
const NodeClass = require('../../src/nodeClass');
|
||||
const { makeNodeStub } = require('../helpers/factories');
|
||||
const nodeClass = require('../../src/nodeClass');
|
||||
const { makeUiConfig } = require('../helpers/factories');
|
||||
|
||||
test('_registerChild emits delayed registration message on output 2', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
const node = makeNodeStub();
|
||||
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||
|
||||
inst.node = node;
|
||||
inst.config = {
|
||||
functionality: {
|
||||
positionVsParent: 'downstream',
|
||||
},
|
||||
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() {},
|
||||
};
|
||||
|
||||
const originalSetTimeout = global.setTimeout;
|
||||
const delays = [];
|
||||
|
||||
global.setTimeout = (fn, ms) => {
|
||||
delays.push(ms);
|
||||
fn();
|
||||
return 1;
|
||||
};
|
||||
|
||||
try {
|
||||
inst._registerChild();
|
||||
} finally {
|
||||
global.setTimeout = originalSetTimeout;
|
||||
}
|
||||
|
||||
assert.deepEqual(delays, [100]);
|
||||
assert.equal(node._sent.length, 1);
|
||||
assert.equal(Array.isArray(node._sent[0]), true);
|
||||
assert.equal(node._sent[0][2].topic, 'registerChild');
|
||||
assert.equal(node._sent[0][2].payload, node.id);
|
||||
assert.equal(node._sent[0][2].positionVsParent, 'downstream');
|
||||
function closeNode(node) {
|
||||
if (node.handlers.close) node.handlers.close(() => {});
|
||||
}
|
||||
|
||||
test('scheduled child.register message lands on Port 2 after construction', async () => {
|
||||
const node = makeNode();
|
||||
const inst = new nodeClass(
|
||||
makeUiConfig({ positionVsParent: 'downstream' }),
|
||||
makeRED(),
|
||||
node,
|
||||
'reactor',
|
||||
);
|
||||
|
||||
try {
|
||||
// BaseNodeAdapter._scheduleRegistration uses a 100ms setTimeout; wait
|
||||
// slightly longer to let it fire.
|
||||
await new Promise((r) => setTimeout(r, 130));
|
||||
|
||||
// The registration send is the [null, null, {child.register}] triple.
|
||||
const regSends = node.sends.filter(
|
||||
(s) => Array.isArray(s) && s[0] === null && s[1] === null && s[2] && s[2].topic === 'child.register',
|
||||
);
|
||||
assert.equal(regSends.length, 1, 'exactly one child.register message expected');
|
||||
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 assert = require('node:assert/strict');
|
||||
|
||||
const { Reactor_CSTR } = require('../../src/specificClass');
|
||||
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');
|
||||
|
||||
/**
|
||||
* Smoke tests for Fix 3: configurable speedUpFactor on Reactor.
|
||||
*/
|
||||
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||
|
||||
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 reactor = new Reactor_CSTR(config);
|
||||
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();
|
||||
config.speedUpFactor = 10;
|
||||
const reactor = new Reactor_CSTR(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();
|
||||
config.speedUpFactor = 60;
|
||||
const reactor = new Reactor_CSTR(config);
|
||||
assert.equal(reactor.speedUpFactor, 60, 'speedUpFactor=60 should be accepted');
|
||||
});
|
||||
|
||||
test('nodeClass passes speedUpFactor from uiConfig to reactor config', () => {
|
||||
const uiConfig = makeUiConfig({ speedUpFactor: 5 });
|
||||
const node = makeNodeStub();
|
||||
const RED = makeREDStub();
|
||||
|
||||
const nc = new nodeClass(uiConfig, RED, node, 'test-reactor');
|
||||
assert.equal(nc.source.speedUpFactor, 5, 'nodeClass should pass speedUpFactor=5 to specificClass');
|
||||
test('buildDomainConfig propagates speedUpFactor from uiConfig', () => {
|
||||
const node = makeNode();
|
||||
const inst = new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||
try {
|
||||
const dc = inst.buildDomainConfig(makeUiConfig({ speedUpFactor: 5 }));
|
||||
assert.equal(dc.reactor.speedUpFactor, 5);
|
||||
} finally {
|
||||
closeNode(node);
|
||||
}
|
||||
});
|
||||
|
||||
test('nodeClass defaults speedUpFactor to 1 when not in uiConfig', () => {
|
||||
const uiConfig = makeUiConfig();
|
||||
// Ensure speedUpFactor is not set
|
||||
delete uiConfig.speedUpFactor;
|
||||
|
||||
const node = makeNodeStub();
|
||||
const RED = makeREDStub();
|
||||
|
||||
const nc = new nodeClass(uiConfig, RED, node, 'test-reactor');
|
||||
assert.equal(nc.source.speedUpFactor, 1, 'nodeClass should default speedUpFactor to 1');
|
||||
test('buildDomainConfig defaults speedUpFactor to 1 when missing from uiConfig', () => {
|
||||
const node = makeNode();
|
||||
const inst = new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||
try {
|
||||
const ui = makeUiConfig();
|
||||
delete ui.speedUpFactor;
|
||||
const dc = inst.buildDomainConfig(ui);
|
||||
assert.equal(dc.reactor.speedUpFactor, 1);
|
||||
} finally {
|
||||
closeNode(node);
|
||||
}
|
||||
});
|
||||
|
||||
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;
|
||||
const reactor = new Reactor_CSTR(config);
|
||||
|
||||
// Set a known start time
|
||||
const t0 = reactor.currentTime;
|
||||
// Advance by 2 seconds real time
|
||||
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;
|
||||
assert.ok(elapsed < 5000, `Elapsed ${elapsed}ms should be close to 2000ms, not 120000ms (old 60x factor)`);
|
||||
});
|
||||
|
||||
@@ -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 assert = require('node:assert/strict');
|
||||
|
||||
const NodeClass = require('../../src/nodeClass');
|
||||
const { makeNodeStub, makeUiConfig } = require('../helpers/factories');
|
||||
const nodeClass = require('../../src/nodeClass');
|
||||
const { Reactor_CSTR } = require('../../src/specificClass');
|
||||
const { makeUiConfig } = require('../helpers/factories');
|
||||
|
||||
test('_setupClass with unknown reactor_type throws (known error-path behavior)', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
inst.node = makeNodeStub();
|
||||
inst.config = makeUiConfig({ reactor_type: 'UNKNOWN_TYPE' });
|
||||
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||
|
||||
assert.throws(() => {
|
||||
inst._setupClass();
|
||||
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 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 assert = require('node:assert/strict');
|
||||
|
||||
const NodeClass = require('../../src/nodeClass');
|
||||
const { makeNodeStub, makeREDStub } = require('../helpers/factories');
|
||||
const nodeClass = require('../../src/nodeClass');
|
||||
const { makeUiConfig } = require('../helpers/factories');
|
||||
|
||||
test('unknown input topic does not throw and still calls done', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
const node = makeNodeStub();
|
||||
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||
|
||||
inst.node = node;
|
||||
inst.RED = makeREDStub();
|
||||
inst.source = {
|
||||
childRegistrationUtils: {
|
||||
registerChild() {},
|
||||
},
|
||||
updateState() {},
|
||||
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() {},
|
||||
};
|
||||
}
|
||||
|
||||
inst._attachInputHandler();
|
||||
function closeNode(node) {
|
||||
if (node.handlers.close) node.handlers.close(() => {});
|
||||
}
|
||||
|
||||
test('unknown input topic does not throw and still calls done', async () => {
|
||||
const node = makeNode();
|
||||
new nodeClass(makeUiConfig(), makeRED(), node, 'reactor');
|
||||
|
||||
try {
|
||||
let doneCalled = 0;
|
||||
assert.doesNotThrow(() => {
|
||||
node._handlers.input({ topic: 'somethingUnknown', payload: 1 }, () => {}, () => {
|
||||
doneCalled += 1;
|
||||
await assert.doesNotReject(async () => {
|
||||
await node.handlers.input(
|
||||
{ topic: 'somethingUnknown', payload: 1 },
|
||||
() => {},
|
||||
() => { doneCalled += 1; },
|
||||
);
|
||||
});
|
||||
assert.equal(doneCalled, 1);
|
||||
} finally {
|
||||
closeNode(node);
|
||||
}
|
||||
});
|
||||
|
||||
assert.equal(doneCalled, 1);
|
||||
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 assert = require('node:assert/strict');
|
||||
|
||||
const NodeClass = require('../../src/nodeClass');
|
||||
const { makeNodeStub, makeREDStub } = require('../helpers/factories');
|
||||
const nodeClass = require('../../src/nodeClass');
|
||||
const { makeUiConfig } = require('../helpers/factories');
|
||||
|
||||
test('registerChild with unknown node id is ignored without throwing', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
const node = makeNodeStub();
|
||||
function makeRED(nodeMap = {}) {
|
||||
return { nodes: { getNode: (id) => nodeMap[id] || null } };
|
||||
}
|
||||
|
||||
inst.node = node;
|
||||
inst.RED = makeREDStub();
|
||||
inst.source = {
|
||||
childRegistrationUtils: {
|
||||
registerChild() {},
|
||||
},
|
||||
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() {},
|
||||
};
|
||||
}
|
||||
|
||||
inst._attachInputHandler();
|
||||
function closeNode(node) {
|
||||
if (node.handlers.close) node.handlers.close(() => {});
|
||||
}
|
||||
|
||||
assert.doesNotThrow(() => {
|
||||
node._handlers.input(
|
||||
test('registerChild alias 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: '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);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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 assert = require('node:assert/strict');
|
||||
|
||||
const NodeClass = require('../../src/nodeClass');
|
||||
const { makeNodeStub } = require('../helpers/factories');
|
||||
const nodeClass = require('../../src/nodeClass');
|
||||
const { makeUiConfig } = require('../helpers/factories');
|
||||
|
||||
test('_tick emits source effluent on process output', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
const node = makeNodeStub();
|
||||
function makeRED() { return { nodes: { getNode: () => null } }; }
|
||||
|
||||
inst.node = node;
|
||||
inst._output = { formatMsg() { return null; } };
|
||||
inst.source = {
|
||||
get getEffluent() {
|
||||
return { topic: 'Fluent', payload: { inlet: 0, F: 1, C: [] }, timestamp: 1 };
|
||||
},
|
||||
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() {},
|
||||
};
|
||||
}
|
||||
|
||||
inst._tick();
|
||||
function closeNode(node) {
|
||||
if (node.handlers.close) node.handlers.close(() => {});
|
||||
}
|
||||
|
||||
assert.equal(node._sent.length, 1);
|
||||
assert.equal(node._sent[0][0].topic, 'Fluent');
|
||||
assert.equal(node._sent[0][1], null);
|
||||
assert.equal(node._sent[0][2], null);
|
||||
function pickEffluentSends(node) {
|
||||
return node.sends.filter((s) => Array.isArray(s) && s[0] && s[0].topic === 'Fluent');
|
||||
}
|
||||
|
||||
function pickGridSends(node) {
|
||||
return node.sends.filter((s) => Array.isArray(s) && s[0] && s[0].topic === 'GridProfile');
|
||||
}
|
||||
|
||||
test('_emitOutputs sends the effluent message on process output (CSTR)', () => {
|
||||
const node = makeNode();
|
||||
const inst = new nodeClass(
|
||||
makeUiConfig({ reactor_type: 'CSTR' }),
|
||||
makeRED(),
|
||||
node,
|
||||
'reactor',
|
||||
);
|
||||
|
||||
try {
|
||||
// Reset sends so any construction-time emissions don't pollute the
|
||||
// assertion (the registration triple lands on the same buffer).
|
||||
node.sends.length = 0;
|
||||
inst._emitOutputs();
|
||||
|
||||
const fluentSends = pickEffluentSends(node);
|
||||
assert.equal(fluentSends.length, 1, 'exactly one Fluent message');
|
||||
const triple = fluentSends[0];
|
||||
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('_tick emits reactor telemetry on influx output', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
const node = makeNodeStub();
|
||||
let captured = null;
|
||||
test('_emitOutputs emits a GridProfile message when engine exposes one (PFR)', () => {
|
||||
const node = makeNode();
|
||||
const inst = new nodeClass(
|
||||
makeUiConfig({ reactor_type: 'PFR' }),
|
||||
makeRED(),
|
||||
node,
|
||||
'reactor',
|
||||
);
|
||||
|
||||
inst.node = node;
|
||||
inst.config = { functionality: { softwareType: 'reactor' }, general: { id: 'reactor-node-1' } };
|
||||
inst._output = {
|
||||
formatMsg(output, config, format) {
|
||||
captured = { output, config, format };
|
||||
return { topic: 'reactor_reactor-node-1', payload: { measurement: 'reactor_reactor-node-1', fields: output } };
|
||||
try {
|
||||
node.sends.length = 0;
|
||||
inst._emitOutputs();
|
||||
|
||||
assert.equal(pickGridSends(node).length, 1, 'exactly one GridProfile message');
|
||||
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 = {
|
||||
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.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);
|
||||
};
|
||||
|
||||
inst._tick();
|
||||
node.sends.length = 0;
|
||||
inst._emitOutputs();
|
||||
|
||||
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.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('_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;
|
||||
};
|
||||
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 {
|
||||
inst._startTickLoop();
|
||||
} finally {
|
||||
global.setTimeout = originalSetTimeout;
|
||||
global.setInterval = originalSetInterval;
|
||||
}
|
||||
|
||||
assert.deepEqual(delays, [1000]);
|
||||
assert.deepEqual(intervals, [1000]);
|
||||
assert.equal(inst._tickInterval, 22);
|
||||
assert.equal(tickCount, 1);
|
||||
});
|
||||
|
||||
test('_attachCloseHandler clears tick interval and calls done callback', () => {
|
||||
const inst = Object.create(NodeClass.prototype);
|
||||
const node = makeNodeStub();
|
||||
inst.node = node;
|
||||
inst._tickInterval = 55;
|
||||
|
||||
const cleared = [];
|
||||
const originalClearInterval = global.clearInterval;
|
||||
global.clearInterval = (id) => {
|
||||
cleared.push(id);
|
||||
// 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] },
|
||||
};
|
||||
|
||||
let doneCalled = 0;
|
||||
const stateBefore = JSON.stringify(inst.source.engine.state);
|
||||
inst.source.tick(0.001);
|
||||
const stateAfter = JSON.stringify(inst.source.engine.state);
|
||||
|
||||
try {
|
||||
inst._attachCloseHandler();
|
||||
node._handlers.close(() => {
|
||||
doneCalled += 1;
|
||||
});
|
||||
assert.notEqual(stateBefore, stateAfter, 'engine state should advance after tick(dt)');
|
||||
} finally {
|
||||
global.clearInterval = originalClearInterval;
|
||||
closeNode(node);
|
||||
}
|
||||
|
||||
assert.deepEqual(cleared, [55]);
|
||||
assert.equal(doneCalled, 1);
|
||||
});
|
||||
|
||||
300
wiki/Home.md
Normal file
300
wiki/Home.md
Normal file
@@ -0,0 +1,300 @@
|
||||
# reactor
|
||||
|
||||
> **Reflects code as of `c84dd78` · regenerated `2026-05-11` via `npm run wiki:all`**
|
||||
> If this banner is stale, the page may be out of date. Treat as informative, not authoritative.
|
||||
|
||||
## 1. What this node is
|
||||
|
||||
**reactor** is an S88 Unit that wraps an ASM3 biological-process engine — either a CSTR (fully mixed tank) or a PFR (plug-flow with axial dispersion). It integrates 13 species (S_O, S_NH, X_H, X_TS, …) and emits the effluent vector each tick. Drives a settler downstream and accepts a recirculation pump child.
|
||||
|
||||
## 2. Position in the platform
|
||||
|
||||
~~~mermaid
|
||||
flowchart LR
|
||||
upstream[reactor<br/>upstream<br/>Unit]:::unit
|
||||
reactor[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/>oxygen<br/>at distance]:::ctrl
|
||||
|
||||
upstream -.stateChange.-> reactor
|
||||
reactor -->|Fluent inlet=0| settler
|
||||
settler -.stateChange.-> reactor
|
||||
diffuser -->|data.otr| reactor
|
||||
tsens -->|child.register| reactor
|
||||
osens -->|child.register| reactor
|
||||
tsens -->|temperature.measured.atEquipment| reactor
|
||||
osens -->|quantity(oxygen).measured.distance| reactor
|
||||
classDef unit fill:#50a8d9,color:#000
|
||||
classDef equip fill:#86bbdd,color:#000
|
||||
classDef ctrl fill:#a9daee,color:#000
|
||||
~~~
|
||||
|
||||
S88 colours: Unit `#50a8d9`, Equipment `#86bbdd`, Control Module `#a9daee`. Source of truth: `.claude/rules/node-red-flow-layout.md`.
|
||||
|
||||
reactor sits at the Unit level. A diffuser (Equipment) sends aeration rates via `data.otr` — it is NOT registered as a child. Measurement children (Control Module) register and supply temperature or dissolved-oxygen reconciliation. Settler is a downstream Unit that listens to `stateChange` to pull effluent; an upstream reactor drives this reactor the same way.
|
||||
|
||||
## 3. Capability matrix
|
||||
|
||||
| Capability | Status | Notes |
|
||||
|---|---|---|
|
||||
| ASM3 13-species ODE integration | ✅ | CSTR + PFR engines under `kinetics/`. |
|
||||
| CSTR (fully mixed) | ✅ | Single concentration vector per tick. |
|
||||
| PFR (axial discretization) | ✅ | `resolution_L` grid cells; emits `GridProfile` alongside `Fluent`. |
|
||||
| Multi-inlet mixing | ✅ | `n_inlets`; each inlet receives its own `data.fluent` with `inlet` index. |
|
||||
| Temperature reconcile from measurement | ✅ | `temperature.measured.atEquipment` writes `engine.temperature`. Code constant: `POSITIONS.AT_EQUIPMENT`. |
|
||||
| Oxygen reconcile (PFR) | ✅ | `quantity (oxygen).measured.<distance>` maps to nearest grid cell. |
|
||||
| KLa-driven aeration | ✅ | `reactor.kla` > 0 enables internal mass transfer; falls back to `data.otr`. |
|
||||
| Speed-up factor (sim time) | ✅ | `reactor.speedUpFactor` accelerates wall-clock → process time. |
|
||||
| Dispersion override (PFR) | ✅ | `data.dispersion` updates axial `D`. |
|
||||
| Hot-swap engine type | ❌ | `reactor_type` is read once in `configure()`. |
|
||||
|
||||
## 4. Code map
|
||||
|
||||
~~~mermaid
|
||||
flowchart TB
|
||||
subgraph nodeRED["nodeClass.js — adapter (BaseNodeAdapter)"]
|
||||
nc["buildDomainConfig()<br/>static DomainClass = Reactor<br/>static commands"]
|
||||
end
|
||||
subgraph domain["specificClass.js — orchestrator (BaseDomain)"]
|
||||
sc["Reactor.configure()<br/>_flattenEngineConfig()<br/>_buildEngine() → CSTR or PFR<br/>ChildRouter.onRegister rules"]
|
||||
end
|
||||
subgraph kinetics["src/kinetics/"]
|
||||
be["baseEngine.js<br/>BaseReactorEngine<br/>influent state, OTR, T<br/>_connectMeasurement / _connectReactor<br/>updateState() → n_iter ticks"]
|
||||
cstr["cstr.js<br/>Reactor_CSTR extends BaseReactorEngine<br/>Forward-Euler 0-D integrator"]
|
||||
pfr["pfr.js<br/>Reactor_PFR extends BaseReactorEngine<br/>FD spatial grid + Danckwerts BC"]
|
||||
end
|
||||
subgraph commands["src/commands/"]
|
||||
cmds["index.js — 6 descriptors<br/>handlers.js — 6 pure fns"]
|
||||
end
|
||||
nc --> sc
|
||||
nc --> cmds
|
||||
sc --> be
|
||||
cstr --> be
|
||||
pfr --> be
|
||||
~~~
|
||||
|
||||
| Module | Owns | Read first if you're changing… |
|
||||
|---|---|---|
|
||||
| `kinetics/baseEngine.js` | ASM3 stoichiometry + rate vector + species list. | Stoichiometric matrix, kinetic constants. |
|
||||
| `kinetics/cstr.js` | 0-D CSTR integrator + `_connectMeasurement` + `_connectReactor`. | Mixed-tank behaviour, child wiring. |
|
||||
| `kinetics/pfr.js` | Axial discretization, dispersion, grid profile emission. | PFR-specific behaviour, grid math. |
|
||||
| `commands/` | 6 input descriptors + handlers (clock, fluent, OTR, temperature, dispersion, child). | Inbound topic API, alias deprecation. |
|
||||
| `reaction_modules/` | Optional plug-in reaction modules (legacy — not yet refactored). | Adding new bio-process modules. |
|
||||
| `additional_nodes/` | Sibling Node-RED nodes (`recirculation-pump`, `settling-basin`) shipped from this repo. | Cross-node deploy in same package. |
|
||||
|
||||
## 5. Topic contract
|
||||
|
||||
> **Auto-generated** from `src/commands/index.js`. Do NOT hand-edit between the markers. Re-run `npm run wiki:contract`.
|
||||
|
||||
<!-- 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 -->
|
||||
|
||||
## 6. Child registration
|
||||
|
||||
~~~mermaid
|
||||
flowchart LR
|
||||
subgraph kids["accepted children (softwareType)"]
|
||||
m_t["measurement<br/>temperature<br/>positionVsParent=atEquipment"]:::ctrl
|
||||
m_o["measurement<br/>quantity (oxygen)<br/>positionVsParent=distance (numeric)"]:::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
|
||||
~~~
|
||||
|
||||
| softwareType | filter | wired to | side-effect |
|
||||
|---|---|---|---|
|
||||
| `measurement` | `asset.type = temperature`, `positionVsParent = atEquipment` | `engine._connectMeasurement` | Writes `engine.temperature`. CSTR only honours temperature; PFR additionally reconciles `quantity (oxygen).measured.<distance>` (numeric position) → nearest grid cell DO. |
|
||||
| `measurement` | `asset.type = quantity (oxygen)`, `positionVsParent = <numeric distance>` | `engine._connectMeasurement` → `pfr._updateMeasurement` | PFR only: maps measurement to nearest grid cell by `round(pos / length × n_x)`. |
|
||||
| `reactor` | `positionVsParent = upstream` | `engine._connectReactor` | Subscribes to upstream reactor's `stateChange`; pulls `getEffluent` into `Fs[0]` / `Cs_in[0]` before next integration step. |
|
||||
|
||||
`diffuser` is NOT a registered child — it feeds aeration via `data.otr` on Port 0. No child-registration handshake is involved.
|
||||
|
||||
## 7. Lifecycle — what one `data.clock` advance does
|
||||
|
||||
~~~mermaid
|
||||
sequenceDiagram
|
||||
participant clock as clock injector
|
||||
participant reactor as reactor (specificClass)
|
||||
participant engine as kinetics engine (CSTR/PFR)
|
||||
participant downstream as settler / next reactor
|
||||
participant out as Port-0 output
|
||||
|
||||
clock->>reactor: data.clock { timestamp }
|
||||
reactor->>engine: updateState(timestamp)
|
||||
Note over engine: n_iter = floor(speedUpFactor × Δt / timeStep)<br/>each step calls tick(timeStep)
|
||||
engine->>engine: integrate ASM3 rates (CSTR: Forward Euler / PFR: FD)
|
||||
engine->>engine: cap S_O to saturation, clip negatives to 0
|
||||
engine->>engine: emit 'stateChange' (currentTime)
|
||||
reactor->>reactor: notifyOutputChanged → getOutput()
|
||||
reactor->>out: getOutput() → {flow_total, temperature, S_O … X_TS}
|
||||
alt PFR engine
|
||||
reactor->>out: GridProfile { grid[n_x][13], n_x, d_x, length, species }
|
||||
end
|
||||
out->>downstream: Fluent { inlet=0, F, C[13] } via stateChange listener
|
||||
~~~
|
||||
|
||||
`stateChange` re-emits on `reactor.emitter` (BaseDomain emitter) — wired in `specificClass.configure()`. Downstream settlers or chained reactors subscribed via `_connectReactor` call their own `updateState` on each `stateChange` event. The tick loop is opt-in (tick-driven via `static tickInterval`) because the reactor integrates process-time steps that have no fixed wall-clock mapping.
|
||||
|
||||
## 8. Data model — `getOutput()`
|
||||
|
||||
Port-0 process payload is the `Fluent` envelope (+ optional `GridProfile` for PFR). Port-1 telemetry is the scalar snapshot below.
|
||||
|
||||
<!-- BEGIN AUTOGEN: data-model -->
|
||||
|
||||
| Key | Type | Unit | Sample |
|
||||
|---|---|---|---|
|
||||
| `S_HCO` | number | — | `5` |
|
||||
| `S_I` | number | — | `30` |
|
||||
| `S_N2` | number | — | `0` |
|
||||
| `S_NH` | number | — | `25` |
|
||||
| `S_NO` | number | — | `0` |
|
||||
| `S_O` | number | — | `0` |
|
||||
| `S_S` | number | — | `70` |
|
||||
| `X_A` | number | — | `200` |
|
||||
| `X_H` | number | — | `2000` |
|
||||
| `X_I` | number | — | `1000` |
|
||||
| `X_S` | number | — | `100` |
|
||||
| `X_STO` | number | — | `0` |
|
||||
| `X_TS` | number | — | `3500` |
|
||||
| `flow_total` | number | — | `0` |
|
||||
| `temperature` | number | — | `20` |
|
||||
|
||||
<!-- END AUTOGEN: data-model -->
|
||||
|
||||
**Concrete sample** (CSTR mid-integration, nitrifying):
|
||||
|
||||
```json
|
||||
{
|
||||
"flow_total": 1000,
|
||||
"temperature": 15.2,
|
||||
"S_O": 2.1,
|
||||
"S_I": 30,
|
||||
"S_S": 12.4,
|
||||
"S_NH": 0.8,
|
||||
"S_N2": 4.3,
|
||||
"S_NO": 18.6,
|
||||
"S_HCO": 4.2,
|
||||
"X_I": 1050,
|
||||
"X_S": 65,
|
||||
"X_H": 2150,
|
||||
"X_STO": 4.5,
|
||||
"X_A": 215,
|
||||
"X_TS": 3680
|
||||
}
|
||||
```
|
||||
|
||||
Species ordering follows ASM3: indices 0–6 are soluble, 7–12 are particulate. `flow_total` is the effluent flow (m³/d); the reactor uses days as the time unit internally.
|
||||
|
||||
## 9. Configuration — editor form ↔ config keys
|
||||
|
||||
~~~mermaid
|
||||
flowchart TB
|
||||
subgraph editor["Node-RED editor form (reactor.html)"]
|
||||
f1["Reactor type: CSTR / PFR"]
|
||||
f2["Volume (m³)"]
|
||||
f3["Length (m) + Resolution — PFR only"]
|
||||
f4["Alpha α (boundary condition blend)"]
|
||||
f5["Number of inlets"]
|
||||
f6["kLa (d⁻¹) — internal aeration"]
|
||||
f7["13 × initial concentration fields"]
|
||||
f8["Time step (s label) + Speed-up factor"]
|
||||
end
|
||||
subgraph config["Domain config slice (reactor.json)"]
|
||||
c1[reactor.reactor_type]
|
||||
c2[reactor.volume]
|
||||
c3["reactor.length<br/>reactor.resolution_L"]
|
||||
c4[reactor.alpha]
|
||||
c5[reactor.n_inlets]
|
||||
c6[reactor.kla]
|
||||
c7["initialState.S_O … X_TS"]
|
||||
c8["reactor.timeStep (unit: h per schema)<br/>reactor.speedUpFactor"]
|
||||
end
|
||||
f1 --> c1
|
||||
f2 --> c2
|
||||
f3 --> c3
|
||||
f4 --> c4
|
||||
f5 --> c5
|
||||
f6 --> c6
|
||||
f7 --> c7
|
||||
f8 --> c8
|
||||
~~~
|
||||
|
||||
| Form field | Config key | Schema default | Range | Where used |
|
||||
|---|---|---|---|---|
|
||||
| Reactor type | `reactor.reactor_type` | `CSTR` | enum: `CSTR` / `PFR` (schema validator lowercases; `_buildEngine` toUpperCase guards) | engine selection in `Reactor._buildEngine()` |
|
||||
| Volume (m³) | `reactor.volume` | `1000` | > 0 | residence time, mass balance |
|
||||
| Length (m) | `reactor.length` | `10` | > 0 | PFR only — axial extent |
|
||||
| Resolution | `reactor.resolution_L` | `10` | ≥ 1 | PFR grid cell count `n_x` |
|
||||
| Alpha | `reactor.alpha` | `0.5` | 0–1 | Danckwerts (0) vs Dirichlet (1) inlet BC |
|
||||
| Inlets | `reactor.n_inlets` | `1` | ≥ 1 | `Fs[]` / `Cs_in[]` array sizes |
|
||||
| kLa (d⁻¹) | `reactor.kla` | `0` | ≥ 0; set to `NaN` to use `data.otr` instead | `_calcOTR()` in `baseEngine.js` |
|
||||
| Time step | `reactor.timeStep` | `0.001` | ≥ 0.0001 | integrator inner step (schema says `h`; HTML label says `s` — see limitation #6) |
|
||||
| Speed-up factor | `reactor.speedUpFactor` | `1` | ≥ 1 | `n_iter = floor(speedUpFactor × Δt_wall / timeStep_days)` |
|
||||
| Initial S_O | `initialState.S_O` | `0` | ≥ 0 (mg/L) | starting dissolved oxygen (caps to saturation in first tick) |
|
||||
| Initial S_NH | `initialState.S_NH` | `25` | ≥ 0 (mg/L) | starting ammonium |
|
||||
| Initial X_H | `initialState.X_H` | `2000` | ≥ 0 (mg/L) | starting heterotroph biomass |
|
||||
| Initial X_A | `initialState.X_A` | `200` | ≥ 0 (mg/L) | starting autotroph biomass — must be ≥ ~50 mg/L for nitrification; HTML default is `0.001` (footgun) |
|
||||
| Initial X_TS | `initialState.X_TS` | `3500` | ≥ 0 (mg/L) | starting TSS — drives settler split |
|
||||
|
||||
## 10. State chart
|
||||
|
||||
Skipped — reactor has no FSM. It runs continuous-state ODE integration; the engine's only stateful event is `stateChange`, fired after every successful integration advance. See section 7 for the integration sequence.
|
||||
|
||||
## 11. Examples
|
||||
|
||||
| Tier | File | What it shows | Status |
|
||||
|---|---|---|---|
|
||||
| Basic | `examples/basic.flow.json` | CSTR with one inlet, watch `Fluent` effluent | ✅ in repo |
|
||||
| Integration | `examples/integration.flow.json` | upstream reactor → reactor → settler chain | ✅ in repo |
|
||||
| Edge | `examples/edge.flow.json` | PFR with dispersion + multi-inlet | ✅ in repo |
|
||||
| Companions | `additional_nodes/*` | recirculation-pump + settling-basin Node-RED nodes shipped from this repo | ✅ in repo |
|
||||
|
||||
One screenshot per tier where helpful. PNG ≤ 200 KB under `wiki/_partial-screenshots/reactor/`.
|
||||
|
||||
## 12. Debug recipes
|
||||
|
||||
| Symptom | First thing to check | Where to look |
|
||||
|---|---|---|
|
||||
| Nitrification doesn't proceed (S_NH stays high) | `initialState.X_A` must be ≥ ~50 mg/L. Defaulting to `0.001` (a known footgun) means no autotrophs. | `generalFunctions/src/configs/reactor.json` |
|
||||
| `Fluent` effluent flow zero | No `data.clock` ticks arriving, or `data.fluent` never set `Fs[0] > 0`. | `commands/handlers.js`, engine `setInfluent` |
|
||||
| PFR `GridProfile` not emitted | `reactor_type` set to `CSTR` — only PFR emits grid. | `_buildEngine` switch |
|
||||
| Settler downstream not updating | `stateChange` event listener path: settler must subscribe to `reactor.emitter`, NOT `reactor.measurements.emitter`. | settler `_connectReactor` |
|
||||
| Temperature reconcile silently ignored | Child measurement's `asset.type` not `temperature` exactly, or `positionVsParent` not `atEquipment`. | `engine._connectMeasurement` |
|
||||
| Integrator slow / stalls | `reactor.timeStep` too small for `speedUpFactor`. Internal `n_iter` count blows up. | `engine.updateState` |
|
||||
| `wiki:datamodel` script slow / hangs | `mathjs` cold-start ~13 s; instantiation depends on it transitively. See known-limitations row 1. | `kinetics/baseEngine.js` |
|
||||
|
||||
## 13. When you would NOT use this node
|
||||
|
||||
- Use reactor for **ASM3 biological treatment** modelling (activated sludge, nitrification, denitrification). For aerobic-only or simpler kinetics, the ASM3 species vector is overkill.
|
||||
- Don't use reactor for a passive equalisation tank — the kinetics engines assume reactions are happening.
|
||||
- Skip reactor when you only need a residence-time delay; a simple buffer node is lighter and doesn't require `mathjs`.
|
||||
|
||||
## 14. Known limitations / current issues
|
||||
|
||||
| # | Issue | Tracked in |
|
||||
|---|---|---|
|
||||
| 1 | `mathjs` cold-start adds ~13 s to first `require()` — `wiki:datamodel` auto-gen may time out on the 60 s wrapper. Falls back to the hand-curated `concrete sample` block. Two remedies tracked: tree-shake mathjs to used ops only; cache the instance. | `.claude/refactor/OPEN_QUESTIONS.md` — "mathjs slow load" |
|
||||
| 2 | `initialState.X_A` HTML default is `0.001` mg/L (silently disabling nitrification) but the schema default is `200` mg/L. Always check the deployed node's form value before expecting nitrification. | `reactor.html` line 38 vs `generalFunctions/src/configs/reactor.json` |
|
||||
| 3 | `getEffluent` shape historically varied (array vs single envelope) — settler's `_connectReactor` tolerates both. Don't break the contract without updating settler. | `nodes/settler/src/specificClass.js → _connectReactor` |
|
||||
| 4 | `additional_nodes/recirculation-pump` and `settling-basin` are legacy companions — not yet refactored to BaseDomain. | P6.5 follow-up |
|
||||
| 5 | `reaction_modules/` is a legacy plug-in directory not consumed by the current engines. Removal pending. | P6.5 follow-up |
|
||||
| 6 | `reactor_type` enum casing: the JSON schema validator lowercases the user-supplied value (`'PFR'` → `'pfr'`). `Reactor._buildEngine` calls `.toUpperCase()` to work around this until Phase 7 decides the platform-wide canonical casing. If the guard is removed prematurely, PFR config silently falls back to CSTR. | `.claude/refactor/OPEN_QUESTIONS.md` — "reactor schema enum lowercases reactor_type" |
|
||||
| 7 | `timeStep` unit mismatch: the HTML form label says "Time step [s]" but `reactor.json` declares `unit: "h"`. `baseEngine.js` converts `config.timeStep` by `÷ 86 400` (seconds → days), suggesting the true input unit is seconds. Audited in OPEN_QUESTIONS.md Phase 5/6 cleanup list. | `baseEngine.js` line 40; `reactor.json` `timeStep.rules.unit`; `reactor.html` time-step label |
|
||||
Reference in New Issue
Block a user