Compare commits

...

2 Commits

Author SHA1 Message Date
root
2e3ba8a9bf Expand reactor demo telemetry and stability handling 2026-03-31 14:26:10 +02:00
znetsixe
2c69a5a0c1 updates 2026-03-11 11:13:51 +01:00
21 changed files with 4036 additions and 3781 deletions

View File

@@ -39,6 +39,7 @@
X_TS_init: { value: 125.0009, required: true }, X_TS_init: { value: 125.0009, required: true },
timeStep: { value: 1, required: true }, timeStep: { value: 1, required: true },
speedUpFactor: { value: 1 },
enableLog: { value: false }, enableLog: { value: false },
logLevel: { value: "error" }, logLevel: { value: "error" },
@@ -115,6 +116,10 @@
type:"num", type:"num",
types:["num"] types:["num"]
}) })
$("#node-input-speedUpFactor").typedInput({
type:"num",
types:["num"]
})
// Set initial visibility on dialog open // Set initial visibility on dialog open
const initialType = $("#node-input-reactor_type").typedInput("value"); const initialType = $("#node-input-reactor_type").typedInput("value");
if (initialType === "CSTR") { if (initialType === "CSTR") {
@@ -243,6 +248,10 @@
<label for="node-input-timeStep"><i class="fa fa-tag"></i> Time step [s]</label> <label for="node-input-timeStep"><i class="fa fa-tag"></i> Time step [s]</label>
<input type="text" id="node-input-timeStep" placeholder="s"> <input type="text" id="node-input-timeStep" placeholder="s">
</div> </div>
<div class="form-row">
<label for="node-input-speedUpFactor"><i class="fa fa-tag"></i> Speed-up factor</label>
<input type="text" id="node-input-speedUpFactor" placeholder="1 = real-time">
</div>
<!-- Logger fields injected here --> <!-- Logger fields injected here -->
<div id="logger-fields-placeholder"></div> <div id="logger-fields-placeholder"></div>

View File

@@ -1,4 +1,21 @@
const { Reactor_CSTR, Reactor_PFR } = require('./specificClass.js'); const { Reactor_CSTR, Reactor_PFR } = require('./specificClass.js');
const { outputUtils } = require('generalFunctions');
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'
];
class nodeClass { class nodeClass {
@@ -18,6 +35,7 @@ class nodeClass {
this._loadConfig(uiConfig) this._loadConfig(uiConfig)
this._setupClass(); this._setupClass();
this._output = new outputUtils();
this._attachInputHandler(); this._attachInputHandler();
this._registerChild(); this._registerChild();
@@ -112,7 +130,8 @@ class nodeClass {
parseFloat(uiConfig.X_A_init), parseFloat(uiConfig.X_A_init),
parseFloat(uiConfig.X_TS_init) parseFloat(uiConfig.X_TS_init)
], ],
timeStep: parseFloat(uiConfig.timeStep) timeStep: parseFloat(uiConfig.timeStep),
speedUpFactor: Number(uiConfig.speedUpFactor) || 1
} }
} }
@@ -159,7 +178,33 @@ class nodeClass {
} }
_tick(){ _tick(){
this.node.send([this.source.getEffluent, null, null]); 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() { _attachCloseHandler() {

View File

@@ -41,7 +41,7 @@ class Reactor {
this.currentTime = Date.now(); // milliseconds since epoch [ms] 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.timeStep = 1 / (24*60*60) * this.config.timeStep; // time step in seconds, converted to days.
this.speedUpFactor = 60; // speed up factor for simulation, 60 means 1 minute per simulated second this.speedUpFactor = config.speedUpFactor ?? 1; // speed up factor for simulation
} }
/** /**
@@ -91,6 +91,8 @@ class Reactor {
return { topic: "Fluent", payload: { inlet: 0, F: math.sum(this.Fs), C: this.state }, 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. * 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} S_O - Dissolved oxygen concentration [g O2 m-3].
@@ -102,6 +104,29 @@ class Reactor {
return this.kla * (S_O_sat - S_O); 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. * Clip values in an array to zero.
* @param {Array} arr - Array of values to clip. * @param {Array} arr - Array of values to clip.
@@ -239,7 +264,7 @@ class Reactor_CSTR extends Reactor {
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 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) const dC_total = math.multiply(math.add(inflow, outflow, reaction, transfer), time_step)
this.state = this._arrayClip2Zero(math.add(this.state, dC_total)); // clip value element-wise to avoid negative concentrations this.state = this._capDissolvedOxygen(this._arrayClip2Zero(math.add(this.state, dC_total))); // clip concentrations and enforce physical DO saturation
if(DEBUG){ if(DEBUG){
assertNoNaN(dC_total, "change in state"); assertNoNaN(dC_total, "change in state");
assertNoNaN(this.state, "new state"); assertNoNaN(this.state, "new state");
@@ -275,6 +300,18 @@ class Reactor_PFR extends Reactor {
assertNoNaN(this.D2_op, "Second 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
};
}
/** /**
* Setter for axial dispersion. * Setter for axial dispersion.
* @param {object} input - Input object (msg) containing payload with dispersion value [m2 d-1]. * @param {object} input - Input object (msg) containing payload with dispersion value [m2 d-1].
@@ -334,7 +371,7 @@ class Reactor_PFR extends Reactor {
assertNoNaN(stateNew, "new state post BC"); assertNoNaN(stateNew, "new state post BC");
} }
this.state = this._arrayClip2Zero(stateNew); this.state = this._capDissolvedOxygen(this._arrayClip2Zero(stateNew));
return stateNew; return stateNew;
} }

View File

@@ -0,0 +1,45 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { Reactor_CSTR, Reactor_PFR } = require('../../src/specificClass');
const { makeReactorConfig } = require('../helpers/factories');
test('CSTR getGridProfile returns null', () => {
const reactor = new Reactor_CSTR(makeReactorConfig({ reactor_type: 'CSTR' }));
assert.equal(reactor.getGridProfile, null);
});
test('PFR getGridProfile returns state matrix with correct dimensions', () => {
const n_x = 8;
const length = 40;
const reactor = new Reactor_PFR(
makeReactorConfig({ reactor_type: 'PFR', resolution_L: n_x, length }),
);
const profile = reactor.getGridProfile;
assert.notEqual(profile, null);
assert.equal(profile.n_x, n_x);
assert.equal(profile.d_x, length / n_x);
assert.equal(profile.length, length);
assert.equal(profile.grid.length, n_x, 'grid should have n_x rows');
assert.equal(profile.grid[0].length, 13, 'each row should have 13 species');
assert.ok(Array.isArray(profile.species), 'species list should be an array');
assert.equal(profile.species.length, 13);
assert.equal(profile.species[3], 'S_NH');
assert.equal(typeof profile.timestamp, 'number');
});
test('PFR getGridProfile is mutation-safe', () => {
const reactor = new Reactor_PFR(
makeReactorConfig({ reactor_type: 'PFR', resolution_L: 5, length: 10 }),
);
const profile = reactor.getGridProfile;
const originalValue = reactor.state[0][3]; // S_NH at cell 0
// Mutate the returned grid
profile.grid[0][3] = 999;
// Reactor internal state should be unchanged
assert.equal(reactor.state[0][3], originalValue, 'mutating grid copy must not affect reactor state');
});

View File

@@ -0,0 +1,68 @@
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)`);
});

View File

@@ -35,7 +35,10 @@ test('CSTR uses kla-based oxygen transfer when kla is finite', () => {
reactor.OTR = 1; reactor.OTR = 1;
reactor.state = Array(NUM_SPECIES).fill(0); reactor.state = Array(NUM_SPECIES).fill(0);
const expected = reactor._calcOTR(0, reactor.temperature); const expected = Math.min(
reactor._calcOTR(0, reactor.temperature),
reactor._calcOxygenSaturation(reactor.temperature),
);
reactor.tick(1); reactor.tick(1);
assert.ok(Math.abs(reactor.state[0] - expected) < 1e-9); assert.ok(Math.abs(reactor.state[0] - expected) < 1e-9);
@@ -75,7 +78,10 @@ test('PFR uses kla-based transfer branch when kla is finite', () => {
reactor.OTR = 0; reactor.OTR = 0;
reactor.state = Array.from({ length: reactor.n_x }, () => Array(NUM_SPECIES).fill(0)); reactor.state = Array.from({ length: reactor.n_x }, () => Array(NUM_SPECIES).fill(0));
const expected = reactor._calcOTR(0, reactor.temperature) * (reactor.n_x / (reactor.n_x - 2)); const expected = Math.min(
reactor._calcOTR(0, reactor.temperature) * (reactor.n_x / (reactor.n_x - 2)),
reactor._calcOxygenSaturation(reactor.temperature),
);
reactor.tick(1); reactor.tick(1);
assert.ok(Math.abs(reactor.state[1][0] - expected) < 1e-9); assert.ok(Math.abs(reactor.state[1][0] - expected) < 1e-9);

View File

@@ -9,6 +9,7 @@ test('_tick emits source effluent on process output', () => {
const node = makeNodeStub(); const node = makeNodeStub();
inst.node = node; inst.node = node;
inst._output = { formatMsg() { return null; } };
inst.source = { inst.source = {
get getEffluent() { get getEffluent() {
return { topic: 'Fluent', payload: { inlet: 0, F: 1, C: [] }, timestamp: 1 }; return { topic: 'Fluent', payload: { inlet: 0, F: 1, C: [] }, timestamp: 1 };
@@ -23,6 +24,50 @@ test('_tick emits source effluent on process output', () => {
assert.equal(node._sent[0][2], null); assert.equal(node._sent[0][2], null);
}); });
test('_tick emits reactor telemetry on influx output', () => {
const inst = Object.create(NodeClass.prototype);
const node = makeNodeStub();
let captured = null;
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;
},
get getEffluent() {
return {
topic: 'Fluent',
payload: {
inlet: 0,
F: 42,
C: [2.1, 30, 100, 16, 0, 1, 8, 25, 75, 1500, 0, 15, 2500]
},
timestamp: 1
};
},
};
inst._tick();
assert.equal(node._sent.length, 1);
assert.equal(node._sent[0][0].topic, 'Fluent');
assert.equal(node._sent[0][1].topic, 'reactor_reactor-node-1');
assert.equal(captured.format, 'influxdb');
assert.equal(captured.output.flow_total, 42);
assert.equal(captured.output.temperature, 19.5);
assert.equal(captured.output.S_O, 2.1);
assert.equal(captured.output.S_NH, 16);
assert.equal(captured.output.X_TS, 2500);
});
test('_startTickLoop schedules periodic tick after startup delay', () => { test('_startTickLoop schedules periodic tick after startup delay', () => {
const inst = Object.create(NodeClass.prototype); const inst = Object.create(NodeClass.prototype);
const delays = []; const delays = [];