diff --git a/CONTRACT.md b/CONTRACT.md new file mode 100644 index 0000000..78624c5 --- /dev/null +++ b/CONTRACT.md @@ -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: , 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 `.measured.` on the child's + `measurements.emitter`. Recognised reconciliations: `temperature.measured.atEquipment` + writes `engine.temperature`; PFR additionally honours + `quantity (oxygen).measured.` 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. diff --git a/src/commands/handlers.js b/src/commands/handlers.js new file mode 100644 index 0000000..bae6f28 --- /dev/null +++ b/src/commands/handlers.js @@ -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); +}; diff --git a/src/commands/index.js b/src/commands/index.js new file mode 100644 index 0000000..c80a590 --- /dev/null +++ b/src/commands/index.js @@ -0,0 +1,47 @@ +'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' }, + handler: handlers.dataClock, + }, + { + topic: 'data.fluent', + aliases: ['Fluent'], + payloadSchema: { type: 'object' }, + handler: handlers.dataFluent, + }, + { + topic: 'data.otr', + aliases: ['OTR'], + payloadSchema: { type: 'any' }, + handler: handlers.dataOTR, + }, + { + topic: 'data.temperature', + aliases: ['Temperature'], + payloadSchema: { type: 'any' }, + handler: handlers.dataTemperature, + }, + { + topic: 'data.dispersion', + aliases: ['Dispersion'], + payloadSchema: { type: 'any' }, + handler: handlers.dataDispersion, + }, + { + topic: 'child.register', + aliases: ['registerChild'], + payloadSchema: { type: 'any' }, + handler: handlers.childRegister, + }, +]; diff --git a/src/kinetics/baseEngine.js b/src/kinetics/baseEngine.js new file mode 100644 index 0000000..cc31c4b --- /dev/null +++ b/src/kinetics/baseEngine.js @@ -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 }; diff --git a/src/kinetics/cstr.js b/src/kinetics/cstr.js new file mode 100644 index 0000000..ce0caa6 --- /dev/null +++ b/src/kinetics/cstr.js @@ -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; diff --git a/src/kinetics/pfr.js b/src/kinetics/pfr.js new file mode 100644 index 0000000..2a21abc --- /dev/null +++ b/src/kinetics/pfr.js @@ -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; diff --git a/src/nodeClass.js b/src/nodeClass.js index 4573cf3..29580b9 100644 --- a/src/nodeClass.js +++ b/src/nodeClass.js @@ -1,208 +1,53 @@ -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(); + 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, 10), + alpha: parseFloat(uiConfig.alpha), + n_inlets: parseInt(uiConfig.n_inlets, 10), + kla: parseFloat(uiConfig.kla), + timeStep: parseFloat(uiConfig.timeStep), + speedUpFactor: Number(uiConfig.speedUpFactor) || 1, + }, + initialState, + }; + } - this._attachInputHandler(); - 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, { - reactor_type: uiConfig.reactor_type, - volume: parseFloat(uiConfig.volume), - length: parseFloat(uiConfig.length), - resolution_L: parseInt(uiConfig.resolution_L), - alpha: parseFloat(uiConfig.alpha), - n_inlets: parseInt(uiConfig.n_inlets), - kla: parseFloat(uiConfig.kla), - initialState: [ - parseFloat(uiConfig.S_O_init), - parseFloat(uiConfig.S_I_init), - parseFloat(uiConfig.S_S_init), - parseFloat(uiConfig.S_NH_init), - parseFloat(uiConfig.S_N2_init), - parseFloat(uiConfig.S_NO_init), - parseFloat(uiConfig.S_HCO_init), - parseFloat(uiConfig.X_I_init), - parseFloat(uiConfig.X_S_init), - parseFloat(uiConfig.X_H_init), - parseFloat(uiConfig.X_STO_init), - parseFloat(uiConfig.X_A_init), - parseFloat(uiConfig.X_TS_init) - ], - timeStep: parseFloat(uiConfig.timeStep), - speedUpFactor: Number(uiConfig.speedUpFactor) || 1 - }); - } - - /** - * Register this node as a child upstream and downstream. - * Delayed to avoid Node-RED startup race conditions. - */ - _registerChild() { - setTimeout(() => { - this.node.send([ - null, - null, - { topic: 'registerChild', payload: this.node.id, positionVsParent: this.config?.functionality?.positionVsParent || 'atEquipment' } - ]); - }, 100); - } - - /** - * Setup reactor class based on config - */ - _setupClass() { - let new_reactor; - - switch (this.config.reactor_type) { - case "CSTR": - new_reactor = new Reactor_CSTR(this.config); - break; - case "PFR": - new_reactor = new Reactor_PFR(this.config); - break; - default: - this.node.warn("Unknown reactor type: " + this.config.reactor_type + ". Falling back to CSTR."); - new_reactor = new Reactor_CSTR(this.config); - } - - this.source = new_reactor; // protect from reassignment - this.node.source = this.source; - } - - _startTickLoop() { - setTimeout(() => { - this._tickInterval = setInterval(() => this._tick(), 1000); - }, 1000); - } - - _tick(){ - const gridProfile = this.source.getGridProfile; - if (gridProfile) { - this.node.send([{ topic: "GridProfile", payload: gridProfile }, null, null]); - } - this.node.send([this.source.getEffluent, this._buildTelemetryMessage(), null]); - } - - _buildTelemetryMessage() { - const effluent = this.source?.getEffluent; - const concentrations = effluent?.payload?.C; - if (!Array.isArray(concentrations)) { - return null; - } - - const telemetry = { - flow_total: Number(effluent.payload.F), - temperature: Number(this.source?.temperature), - }; - - for (let i = 0; i < Math.min(REACTOR_SPECIES.length, concentrations.length); i += 1) { - const value = Number(concentrations[i]); - if (Number.isFinite(value)) { - telemetry[REACTOR_SPECIES[i]] = value; - } - } - - return this._output.formatMsg(telemetry, this.config, 'influxdb'); - } - - _attachCloseHandler() { - this.node.on('close', (done) => { - clearInterval(this._tickInterval); - if (typeof done === 'function') done(); - }); - } + // 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]); + } } module.exports = nodeClass; diff --git a/src/specificClass.js b/src/specificClass.js index 17725e7..e78572f 100644 --- a/src/specificClass.js +++ b/src/specificClass.js @@ -1,481 +1,124 @@ -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]; + // 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(); } + + 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; } - // Neumann BC (no flux) - state[this.n_x-1] = state[this.n_x-2]; + return out; } - /** - * 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."); - } - } 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; - } + 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' }, + ); } - /** - * 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; + close() { + this.engine?.emitter?.removeAllListeners?.(); + super.close(); } } -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; diff --git a/test/basic/constructor.basic.test.js b/test/basic/constructor.basic.test.js index e727719..618dc7b 100644 --- a/test/basic/constructor.basic.test.js +++ b/test/basic/constructor.basic.test.js @@ -3,14 +3,18 @@ const assert = require('node:assert/strict'); 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', () => { +// These tests pinned the old private _loadConfig / _setupClass methods on +// the pre-refactor nodeClass. After the BaseNodeAdapter migration the +// same logic lives in buildDomainConfig + the Reactor wrapper's engine +// selector. We exercise both surfaces directly. + +test('buildDomainConfig coerces numeric fields and builds initial state vector', () => { const inst = Object.create(NodeClass.prototype); inst.node = { id: 'n-reactor-1' }; inst.name = 'reactor'; - - inst._loadConfig( + const dc = inst.buildDomainConfig( makeUiConfig({ volume: '12.5', length: '9', @@ -22,34 +26,40 @@ 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); }); -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 Reactor = require('../../src/specificClass'); + const config = { + general: { name: 'reactor', id: 'n', logging: { enabled: false, logLevel: 'error' } }, + functionality: { softwareType: 'reactor', positionVsParent: 'atEquipment' }, + reactor: { reactor_type: 'CSTR', volume: 100, length: 10, resolution_L: 5, alpha: 0, + n_inlets: 1, kla: NaN, timeStep: 1 }, + initialState: { S_O: 0, S_I: 30, S_S: 100, S_NH: 16, S_N2: 0, S_NO: 0, S_HCO: 5, + X_I: 25, X_S: 75, X_H: 30, X_STO: 0, X_A: 0.001, X_TS: 125 }, + }; + const r = new Reactor(config); + assert.ok(r.engine instanceof Reactor_CSTR); }); -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 Reactor = require('../../src/specificClass'); + const config = { + general: { name: 'reactor', id: 'n', logging: { enabled: false, logLevel: 'error' } }, + functionality: { softwareType: 'reactor', positionVsParent: 'atEquipment' }, + reactor: { reactor_type: 'PFR', volume: 100, length: 10, resolution_L: 5, alpha: 0, + n_inlets: 1, kla: NaN, timeStep: 1 }, + initialState: { S_O: 0, S_I: 30, S_S: 100, S_NH: 16, S_N2: 0, S_NO: 0, S_HCO: 5, + X_I: 25, X_S: 75, X_H: 30, X_STO: 0, X_A: 0.001, X_TS: 125 }, + }; + const r = new Reactor(config); + assert.ok(r.engine instanceof Reactor_PFR); }); diff --git a/test/basic/input-routing.basic.test.js b/test/basic/input-routing.basic.test.js index abfa4f3..fb770f7 100644 --- a/test/basic/input-routing.basic.test.js +++ b/test/basic/input-routing.basic.test.js @@ -2,72 +2,51 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const NodeClass = require('../../src/nodeClass'); +const commands = require('../../src/commands'); +const { createRegistry } = require('generalFunctions'); const { makeNodeStub, makeREDStub } = require('../helpers/factories'); -test('_attachInputHandler routes supported topics to source methods/setters', () => { +// Post-refactor: dispatch goes through the commands registry built by +// BaseNodeAdapter (this._commands). We seed the registry on a prototype- +// derived instance, then drive _attachInputHandler the same way the live +// adapter would. + +test('input handler routes legacy topic aliases to engine setters', async () => { const inst = Object.create(NodeClass.prototype); const node = makeNodeStub(); const calls = []; const source = { - updateState(timestamp) { - calls.push(['clock', timestamp]); - }, + logger: { warn: () => {}, info: () => {}, debug: () => {}, error: () => {} }, + updateState(t) { calls.push(['clock', t]); }, childRegistrationUtils: { - registerChild(childSource, position) { - calls.push(['registerChild', childSource, position]); - }, + registerChild(childSource, position) { calls.push(['registerChild', childSource, position]); }, }, }; - Object.defineProperty(source, 'setInfluent', { - set(v) { - calls.push(['Fluent', v]); - }, - }); - - Object.defineProperty(source, 'setOTR', { - set(v) { - calls.push(['OTR', v]); - }, - }); - - Object.defineProperty(source, 'setTemperature', { - set(v) { - calls.push(['Temperature', v]); - }, - }); - - Object.defineProperty(source, 'setDispersion', { - set(v) { - calls.push(['Dispersion', v]); - }, - }); + Object.defineProperty(source, 'setInfluent', { set(v) { calls.push(['Fluent', v]); } }); + Object.defineProperty(source, 'setOTR', { set(v) { calls.push(['OTR', v]); } }); + Object.defineProperty(source, 'setTemperature', { set(v) { calls.push(['Temperature', v]); } }); + Object.defineProperty(source, 'setDispersion', { set(v) { calls.push(['Dispersion', v]); } }); inst.node = node; - inst.RED = makeREDStub({ - childA: { - source: { id: 'child-source-A' }, - }, - }); + inst.RED = makeREDStub({ childA: { source: { id: 'child-source-A' } } }); inst.source = source; - + inst._commands = createRegistry(commands, { logger: source.logger }); inst._attachInputHandler(); const onInput = node._handlers.input; - const sent = []; 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++); + await onInput({ topic: 'clock', timestamp: 1000 }, () => {}, done); + await onInput({ topic: 'Fluent', payload: { inlet: 0, F: 10, C: [] } }, () => {}, done); + await onInput({ topic: 'OTR', payload: 3.5 }, () => {}, done); + await onInput({ topic: 'Temperature', payload: 18.2 }, () => {}, done); + await onInput({ topic: 'Dispersion', payload: 0.2 }, () => {}, done); + await onInput({ 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); diff --git a/test/basic/register-child.basic.test.js b/test/basic/register-child.basic.test.js index 92b8705..ca86116 100644 --- a/test/basic/register-child.basic.test.js +++ b/test/basic/register-child.basic.test.js @@ -4,28 +4,21 @@ const assert = require('node:assert/strict'); const NodeClass = require('../../src/nodeClass'); const { makeNodeStub } = require('../helpers/factories'); -test('_registerChild emits delayed registration message on output 2', () => { +// Post-refactor: BaseNodeAdapter handles registration via _scheduleRegistration +// (was _registerChild). Topic moved from 'registerChild' to 'child.register'. +test('_scheduleRegistration emits delayed child.register message on output 2', () => { const inst = Object.create(NodeClass.prototype); const node = makeNodeStub(); inst.node = node; - inst.config = { - functionality: { - positionVsParent: 'downstream', - }, - }; + inst.config = { functionality: { positionVsParent: 'downstream', distance: null } }; const originalSetTimeout = global.setTimeout; const delays = []; - - global.setTimeout = (fn, ms) => { - delays.push(ms); - fn(); - return 1; - }; + global.setTimeout = (fn, ms) => { delays.push(ms); fn(); return 1; }; try { - inst._registerChild(); + inst._scheduleRegistration(); } finally { global.setTimeout = originalSetTimeout; } @@ -33,7 +26,7 @@ test('_registerChild emits delayed registration message on output 2', () => { 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].topic, 'child.register'); assert.equal(node._sent[0][2].payload, node.id); assert.equal(node._sent[0][2].positionVsParent, 'downstream'); }); diff --git a/test/basic/speedup-factor.basic.test.js b/test/basic/speedup-factor.basic.test.js index cc35b0e..50aa0c8 100644 --- a/test/basic/speedup-factor.basic.test.js +++ b/test/basic/speedup-factor.basic.test.js @@ -1,68 +1,61 @@ -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'); - -/** - * Smoke tests for Fix 3: configurable speedUpFactor on Reactor. - */ - -test('specificClass 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', () => { - 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', () => { - 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('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('updateState with speedUpFactor=1 advances roughly real-time', () => { - const config = makeReactorConfig(); - config.speedUpFactor = 1; - 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)`); -}); +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 } = require('../helpers/factories'); + +/** + * Smoke tests for Fix 3: configurable speedUpFactor on Reactor. + */ + +test('specificClass 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', () => { + 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', () => { + const config = makeReactorConfig(); + config.speedUpFactor = 60; + const reactor = new Reactor_CSTR(config); + assert.equal(reactor.speedUpFactor, 60, 'speedUpFactor=60 should be accepted'); +}); + +test('buildDomainConfig propagates speedUpFactor from uiConfig', () => { + const inst = Object.create(NodeClass.prototype); + inst.node = { id: 'n-reactor' }; + inst.name = 'reactor'; + const dc = inst.buildDomainConfig(makeUiConfig({ speedUpFactor: 5 })); + assert.equal(dc.reactor.speedUpFactor, 5); +}); + +test('buildDomainConfig defaults speedUpFactor to 1 when missing from uiConfig', () => { + const inst = Object.create(NodeClass.prototype); + inst.node = { id: 'n-reactor' }; + inst.name = 'reactor'; + const ui = makeUiConfig(); + delete ui.speedUpFactor; + const dc = inst.buildDomainConfig(ui); + assert.equal(dc.reactor.speedUpFactor, 1); +}); + +test('updateState with speedUpFactor=1 advances roughly real-time', () => { + const config = makeReactorConfig(); + config.speedUpFactor = 1; + config.n_inlets = 1; + const reactor = new Reactor_CSTR(config); + + const t0 = reactor.currentTime; + reactor.updateState(t0 + 2000); + + const elapsed = reactor.currentTime - t0; + assert.ok(elapsed < 5000, `Elapsed ${elapsed}ms should be close to 2000ms, not 120000ms (old 60x factor)`); +}); diff --git a/test/edge/invalid-reactor-type.edge.test.js b/test/edge/invalid-reactor-type.edge.test.js index 6892f9c..9000628 100644 --- a/test/edge/invalid-reactor-type.edge.test.js +++ b/test/edge/invalid-reactor-type.edge.test.js @@ -1,15 +1,21 @@ const test = require('node:test'); const assert = require('node:assert/strict'); -const NodeClass = require('../../src/nodeClass'); -const { makeNodeStub, makeUiConfig } = require('../helpers/factories'); +const Reactor = require('../../src/specificClass'); +const { Reactor_CSTR } = require('../../src/specificClass'); -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' }); +// Post-refactor: an unknown reactor_type falls back to CSTR and warns, +// rather than throwing. +test('Reactor wrapper falls back to CSTR when reactor_type is unknown', () => { + const config = { + general: { name: 'reactor', id: 'n', logging: { enabled: false, logLevel: 'error' } }, + functionality: { softwareType: 'reactor', positionVsParent: 'atEquipment' }, + reactor: { reactor_type: 'UNKNOWN_TYPE', volume: 100, length: 10, resolution_L: 5, + alpha: 0, n_inlets: 1, kla: NaN, timeStep: 1 }, + initialState: { S_O: 0, S_I: 30, S_S: 100, S_NH: 16, S_N2: 0, S_NO: 0, S_HCO: 5, + X_I: 25, X_S: 75, X_H: 30, X_STO: 0, X_A: 0.001, X_TS: 125 }, + }; - assert.throws(() => { - inst._setupClass(); - }); + const r = new Reactor(config); + assert.ok(r.engine instanceof Reactor_CSTR); }); diff --git a/test/edge/invalid-topic.edge.test.js b/test/edge/invalid-topic.edge.test.js index e6bde22..36e409f 100644 --- a/test/edge/invalid-topic.edge.test.js +++ b/test/edge/invalid-topic.edge.test.js @@ -2,26 +2,27 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const NodeClass = require('../../src/nodeClass'); +const commands = require('../../src/commands'); +const { createRegistry } = require('generalFunctions'); const { makeNodeStub, makeREDStub } = require('../helpers/factories'); -test('unknown input topic does not throw and still calls done', () => { +test('unknown input topic does not throw and still calls done', async () => { const inst = Object.create(NodeClass.prototype); const node = makeNodeStub(); inst.node = node; inst.RED = makeREDStub(); inst.source = { - childRegistrationUtils: { - registerChild() {}, - }, + logger: { warn: () => {}, info: () => {}, debug: () => {}, error: () => {} }, + childRegistrationUtils: { registerChild() {} }, updateState() {}, }; - + inst._commands = createRegistry(commands, { logger: inst.source.logger }); inst._attachInputHandler(); let doneCalled = 0; - assert.doesNotThrow(() => { - node._handlers.input({ topic: 'somethingUnknown', payload: 1 }, () => {}, () => { + await assert.doesNotReject(async () => { + await node._handlers.input({ topic: 'somethingUnknown', payload: 1 }, () => {}, () => { doneCalled += 1; }); }); diff --git a/test/edge/missing-child.edge.test.js b/test/edge/missing-child.edge.test.js index 3e2cb0f..f9abfa8 100644 --- a/test/edge/missing-child.edge.test.js +++ b/test/edge/missing-child.edge.test.js @@ -2,24 +2,25 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const NodeClass = require('../../src/nodeClass'); +const commands = require('../../src/commands'); +const { createRegistry } = require('generalFunctions'); const { makeNodeStub, makeREDStub } = require('../helpers/factories'); -test('registerChild with unknown node id is ignored without throwing', () => { +test('registerChild with unknown node id is ignored without throwing', async () => { const inst = Object.create(NodeClass.prototype); const node = makeNodeStub(); inst.node = node; inst.RED = makeREDStub(); inst.source = { - childRegistrationUtils: { - registerChild() {}, - }, + logger: { warn: () => {}, info: () => {}, debug: () => {}, error: () => {} }, + childRegistrationUtils: { registerChild() {} }, }; - + inst._commands = createRegistry(commands, { logger: inst.source.logger }); inst._attachInputHandler(); - assert.doesNotThrow(() => { - node._handlers.input( + await assert.doesNotReject(async () => { + await node._handlers.input( { topic: 'registerChild', payload: 'missing-child', positionVsParent: 'upstream' }, () => {}, () => {}, diff --git a/test/integration/tick-loop.integration.test.js b/test/integration/tick-loop.integration.test.js index c7bd80d..c76e521 100644 --- a/test/integration/tick-loop.integration.test.js +++ b/test/integration/tick-loop.integration.test.js @@ -4,19 +4,27 @@ const assert = require('node:assert/strict'); const NodeClass = require('../../src/nodeClass'); const { makeNodeStub } = require('../helpers/factories'); -test('_tick emits source effluent on process output', () => { +// Post-refactor: BaseNodeAdapter drives tick + status loops. The reactor +// nodeClass overrides _emitOutputs to preserve the Fluent / GridProfile +// Port-0 contract (delta-compressed payloads can't carry the C-vector). + +test('_emitOutputs emits effluent on process output', () => { const inst = Object.create(NodeClass.prototype); const node = makeNodeStub(); inst.node = node; + inst.config = { functionality: { softwareType: 'reactor' }, general: { id: 'r-1' } }; inst._output = { formatMsg() { return null; } }; inst.source = { - get getEffluent() { - return { topic: 'Fluent', payload: { inlet: 0, F: 1, C: [] }, timestamp: 1 }; - }, + engine: { temperature: 18, getEffluent: { topic: 'Fluent', payload: { inlet: 0, F: 1, C: [] }, timestamp: 1 }, get getGridProfile() { return null; } }, + config: inst.config, + updateState() {}, + get getEffluent() { return this.engine.getEffluent; }, + get getGridProfile() { return this.engine.getGridProfile; }, + getOutput() { return {}; }, }; - inst._tick(); + inst._emitOutputs(); assert.equal(node._sent.length, 1); assert.equal(node._sent[0][0].topic, 'Fluent'); @@ -24,7 +32,7 @@ test('_tick emits source effluent on process output', () => { assert.equal(node._sent[0][2], null); }); -test('_tick emits reactor telemetry on influx output', () => { +test('_emitOutputs emits reactor telemetry on influx output', () => { const inst = Object.create(NodeClass.prototype); const node = makeNodeStub(); let captured = null; @@ -32,30 +40,28 @@ test('_tick emits reactor telemetry on influx output', () => { 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 } }; - } - }; - inst.source = { - temperature: 19.5, - get getGridProfile() { - return null; + formatMsg(output, _config, format) { + captured = { output, format }; + return { topic: `reactor_${inst.config.general.id}`, payload: { measurement: 'reactor', fields: output } }; }, - 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 - }; + }; + const effluent = { 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: { temperature: 19.5, getEffluent: effluent, get getGridProfile() { return null; } }, + config: inst.config, + updateState() {}, + get getEffluent() { return this.engine.getEffluent; }, + get getGridProfile() { return this.engine.getGridProfile; }, + getOutput() { + const C = effluent.payload.C; + const out = { flow_total: effluent.payload.F, temperature: 19.5 }; + const 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']; + for (let i = 0; i < keys.length; i += 1) out[keys[i]] = C[i]; + return out; }, }; - inst._tick(); + inst._emitOutputs(); assert.equal(node._sent.length, 1); assert.equal(node._sent[0][0].topic, 'Fluent'); @@ -68,67 +74,30 @@ test('_tick emits reactor telemetry on influx output', () => { assert.equal(captured.output.X_TS, 2500); }); -test('_startTickLoop schedules periodic tick after startup delay', () => { - const inst = Object.create(NodeClass.prototype); - const delays = []; - const intervals = []; - let tickCount = 0; - - inst._tick = () => { - tickCount += 1; - }; - - const originalSetTimeout = global.setTimeout; - const originalSetInterval = global.setInterval; - - global.setTimeout = (fn, ms) => { - delays.push(ms); - fn(); - return 10; - }; - - global.setInterval = (fn, ms) => { - intervals.push(ms); - fn(); - return 22; - }; - - try { - 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', () => { +test('_emitOutputs also emits GridProfile when engine exposes one', () => { 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); + inst.node = node; + inst.config = { functionality: { softwareType: 'reactor' }, general: { id: 'r-1' } }; + inst._output = { formatMsg() { return null; } }; + const grid = { grid: [[0]], n_x: 1, d_x: 1, length: 1, species: [], timestamp: 1 }; + inst.source = { + engine: { + temperature: 18, + getEffluent: { topic: 'Fluent', payload: { inlet: 0, F: 1, C: [] }, timestamp: 1 }, + get getGridProfile() { return grid; }, + }, + config: inst.config, + updateState() {}, + get getEffluent() { return this.engine.getEffluent; }, + get getGridProfile() { return this.engine.getGridProfile; }, + getOutput() { return {}; }, }; - let doneCalled = 0; + inst._emitOutputs(); - try { - inst._attachCloseHandler(); - node._handlers.close(() => { - doneCalled += 1; - }); - } finally { - global.clearInterval = originalClearInterval; - } - - assert.deepEqual(cleared, [55]); - assert.equal(doneCalled, 1); + assert.equal(node._sent.length, 2); + assert.equal(node._sent[0][0].topic, 'GridProfile'); + assert.equal(node._sent[1][0].topic, 'Fluent'); });