Compare commits
7 Commits
0430471dca
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7eafd89f4e | ||
|
|
d55f401ab3 | ||
|
|
ffb2072baa | ||
|
|
85797b5b8b | ||
|
|
b337bf9eb7 | ||
|
|
f8012c8bad | ||
|
|
ee38c8b581 |
23
CLAUDE.md
Normal file
23
CLAUDE.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# machineGroupControl — Claude Code context
|
||||
|
||||
Coordinates multiple rotatingMachine or valve children.
|
||||
Part of the [EVOLV](https://gitea.wbd-rd.nl/RnD/EVOLV) wastewater-automation platform.
|
||||
|
||||
## S88 classification
|
||||
|
||||
| Level | Colour | Placement lane |
|
||||
|---|---|---|
|
||||
| **Unit** | `#50a8d9` | L4 |
|
||||
|
||||
## Flow layout rules
|
||||
|
||||
When wiring this node into a multi-node demo or production flow, follow the
|
||||
placement rule set in the **EVOLV superproject**:
|
||||
|
||||
> `.claude/rules/node-red-flow-layout.md` (in the EVOLV repo root)
|
||||
|
||||
Key points for this node:
|
||||
- Place on lane **L4** (x-position per the lane table in the rule).
|
||||
- Stack same-level siblings vertically.
|
||||
- Parent/children sit on adjacent lanes (children one lane left, parent one lane right).
|
||||
- Wrap in a Node-RED group box coloured `#50a8d9` (Unit).
|
||||
8
examples/README.md
Normal file
8
examples/README.md
Normal file
@@ -0,0 +1,8 @@
|
||||
# machineGroupControl Example Flows
|
||||
|
||||
Import-ready Node-RED examples for machineGroupControl.
|
||||
|
||||
## Files
|
||||
- basic.flow.json
|
||||
- integration.flow.json
|
||||
- edge.flow.json
|
||||
6
examples/basic.flow.json
Normal file
6
examples/basic.flow.json
Normal file
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{"id":"machineGroupControl_basic_tab","type":"tab","label":"machineGroupControl basic","disabled":false,"info":"machineGroupControl basic example"},
|
||||
{"id":"machineGroupControl_basic_node","type":"machineGroupControl","z":"machineGroupControl_basic_tab","name":"machineGroupControl basic","x":420,"y":180,"wires":[["machineGroupControl_basic_dbg"]]},
|
||||
{"id":"machineGroupControl_basic_inj","type":"inject","z":"machineGroupControl_basic_tab","name":"basic trigger","props":[{"p":"topic","vt":"str"},{"p":"payload","vt":"str"}],"topic":"ping","payload":"1","payloadType":"str","x":160,"y":180,"wires":[["machineGroupControl_basic_node"]]},
|
||||
{"id":"machineGroupControl_basic_dbg","type":"debug","z":"machineGroupControl_basic_tab","name":"machineGroupControl basic debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":660,"y":180,"wires":[]}
|
||||
]
|
||||
6
examples/edge.flow.json
Normal file
6
examples/edge.flow.json
Normal file
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{"id":"machineGroupControl_edge_tab","type":"tab","label":"machineGroupControl edge","disabled":false,"info":"machineGroupControl edge example"},
|
||||
{"id":"machineGroupControl_edge_node","type":"machineGroupControl","z":"machineGroupControl_edge_tab","name":"machineGroupControl edge","x":420,"y":180,"wires":[["machineGroupControl_edge_dbg"]]},
|
||||
{"id":"machineGroupControl_edge_inj","type":"inject","z":"machineGroupControl_edge_tab","name":"unknown topic","props":[{"p":"topic","vt":"str"},{"p":"payload","vt":"str"}],"topic":"doesNotExist","payload":"x","payloadType":"str","x":170,"y":180,"wires":[["machineGroupControl_edge_node"]]},
|
||||
{"id":"machineGroupControl_edge_dbg","type":"debug","z":"machineGroupControl_edge_tab","name":"machineGroupControl edge debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":660,"y":180,"wires":[]}
|
||||
]
|
||||
6
examples/integration.flow.json
Normal file
6
examples/integration.flow.json
Normal file
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{"id":"machineGroupControl_int_tab","type":"tab","label":"machineGroupControl integration","disabled":false,"info":"machineGroupControl integration example"},
|
||||
{"id":"machineGroupControl_int_node","type":"machineGroupControl","z":"machineGroupControl_int_tab","name":"machineGroupControl integration","x":420,"y":180,"wires":[["machineGroupControl_int_dbg"]]},
|
||||
{"id":"machineGroupControl_int_inj","type":"inject","z":"machineGroupControl_int_tab","name":"registerChild","props":[{"p":"topic","vt":"str"},{"p":"payload","vt":"str"}],"topic":"registerChild","payload":"example-child-id","payloadType":"str","x":170,"y":180,"wires":[["machineGroupControl_int_node"]]},
|
||||
{"id":"machineGroupControl_int_dbg","type":"debug","z":"machineGroupControl_int_tab","name":"machineGroupControl integration debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":680,"y":180,"wires":[]}
|
||||
]
|
||||
22
mgc.html
22
mgc.html
@@ -18,6 +18,8 @@
|
||||
defaults: {
|
||||
// Define default properties
|
||||
name: { value: "" },
|
||||
processOutputFormat: { value: "process" },
|
||||
dbaseOutputFormat: { value: "influxdb" },
|
||||
|
||||
// Logger properties
|
||||
enableLog: { value: false },
|
||||
@@ -39,7 +41,7 @@
|
||||
icon: "font-awesome/fa-cogs",
|
||||
|
||||
label: function () {
|
||||
return this.positionIcon + " " + "machineGroup";
|
||||
return (this.positionIcon || "") + " machineGroup";
|
||||
},
|
||||
oneditprepare: function() {
|
||||
// Initialize the menu data for the node
|
||||
@@ -74,6 +76,24 @@
|
||||
|
||||
<script type="text/html" data-template-name="machineGroupControl">
|
||||
|
||||
<h3>Output Formats</h3>
|
||||
<div class="form-row">
|
||||
<label for="node-input-processOutputFormat"><i class="fa fa-random"></i> Process Output</label>
|
||||
<select id="node-input-processOutputFormat" style="width:60%;">
|
||||
<option value="process">process</option>
|
||||
<option value="json">json</option>
|
||||
<option value="csv">csv</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="node-input-dbaseOutputFormat"><i class="fa fa-database"></i> Database Output</label>
|
||||
<select id="node-input-dbaseOutputFormat" style="width:60%;">
|
||||
<option value="influxdb">influxdb</option>
|
||||
<option value="json">json</option>
|
||||
<option value="csv">csv</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Logger fields injected here -->
|
||||
<div id="logger-fields-placeholder"></div>
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"description": "Control module machineGroupControl",
|
||||
"main": "mgc.js",
|
||||
"scripts": {
|
||||
"test": "node mgc.js"
|
||||
"test": "node --test test/basic/*.test.js test/integration/*.test.js test/edge/*.test.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -24,4 +24,4 @@
|
||||
"machineGroupControl": "mgc.js"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
119
src/nodeClass.js
119
src/nodeClass.js
@@ -1,4 +1,4 @@
|
||||
const { outputUtils, configManager } = require("generalFunctions");
|
||||
const { outputUtils, configManager, convert } = require("generalFunctions");
|
||||
const Specific = require("./specificClass");
|
||||
|
||||
class nodeClass {
|
||||
@@ -37,53 +37,60 @@ class nodeClass {
|
||||
_loadConfig(uiConfig, node) {
|
||||
const cfgMgr = new configManager();
|
||||
this.defaultConfig = cfgMgr.getConfig(this.name);
|
||||
const flowUnit = this._resolveUnitOrFallback(uiConfig.unit, 'volumeFlowRate', 'm3/h', 'flow');
|
||||
|
||||
// Build config: base sections (no domain-specific config for group controller)
|
||||
this.config = cfgMgr.buildConfig(this.name, uiConfig, node.id);
|
||||
|
||||
// Merge UI config over defaults
|
||||
this.config = {
|
||||
general: {
|
||||
name: uiConfig.name,
|
||||
id: node.id, // node.id is for the child registration process
|
||||
unit: uiConfig.unit, // add converter options later to convert to default units (need like a model that defines this which units we are going to use and then conver to those standards)
|
||||
logging: {
|
||||
enabled: uiConfig.enableLog,
|
||||
logLevel: uiConfig.logLevel,
|
||||
},
|
||||
},
|
||||
functionality: {
|
||||
positionVsParent: uiConfig.positionVsParent || "atEquipment", // Default to 'atEquipment' if not set
|
||||
},
|
||||
};
|
||||
// Utility for formatting outputs
|
||||
this._output = new outputUtils();
|
||||
}
|
||||
|
||||
_resolveUnitOrFallback(candidate, expectedMeasure, fallbackUnit, label) {
|
||||
const raw = typeof candidate === "string" ? candidate.trim() : "";
|
||||
const fallback = String(fallbackUnit || "").trim();
|
||||
if (!raw) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
const desc = convert().describe(raw);
|
||||
if (expectedMeasure && desc.measure !== expectedMeasure) {
|
||||
throw new Error(`expected '${expectedMeasure}' but got '${desc.measure}'`);
|
||||
}
|
||||
return raw;
|
||||
} catch (error) {
|
||||
this.node?.warn?.(`Invalid ${label} unit '${raw}' (${error.message}). Falling back to '${fallback}'.`);
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
_updateNodeStatus() {
|
||||
//console.log('Updating node status...');
|
||||
const mg = this.source;
|
||||
const mode = mg.mode;
|
||||
const scaling = mg.scaling;
|
||||
|
||||
|
||||
// Add safety checks for measurements
|
||||
const totalFlow = mg.measurements
|
||||
?.type("flow")
|
||||
?.variant("predicted")
|
||||
?.position("atequipment")
|
||||
?.getCurrentValue('m3/h') || 0;
|
||||
|
||||
?.getCurrentValue(mg?.unitPolicy?.output?.flow || 'm3/h') || 0;
|
||||
|
||||
const totalPower = mg.measurements
|
||||
?.type("power")
|
||||
?.variant("predicted")
|
||||
?.position("atEquipment")
|
||||
?.getCurrentValue() || 0;
|
||||
?.getCurrentValue(mg?.unitPolicy?.output?.power || 'kW') || 0;
|
||||
|
||||
// Calculate total capacity based on available machines with safety checks
|
||||
const availableMachines = Object.values(mg.machines || {}).filter((machine) => {
|
||||
// Safety check: ensure machine and machine.state exist
|
||||
if (!machine || !machine.state || typeof machine.state.getCurrentState !== 'function') {
|
||||
console.warn(`Machine missing or invalid:`, machine?.config?.general?.id || 'unknown');
|
||||
mg.logger?.warn(`Machine missing or invalid: ${machine?.config?.general?.id || 'unknown'}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
const state = machine.state.getCurrentState();
|
||||
const mode = machine.currentMode;
|
||||
return !(
|
||||
@@ -195,67 +202,65 @@ class nodeClass {
|
||||
this.node.on(
|
||||
"input",
|
||||
async (msg, send, done) => {
|
||||
const mg = this.source;
|
||||
const RED = this.RED;
|
||||
const mg = this.source;
|
||||
const RED = this.RED;
|
||||
try {
|
||||
switch (msg.topic) {
|
||||
case "registerChild":
|
||||
//console.log(`Registering child in mgc: ${msg.payload}`);
|
||||
const childId = msg.payload;
|
||||
const childObj = RED.nodes.getNode(childId);
|
||||
|
||||
// Debug: Check what we're getting
|
||||
//console.log(`Child object:`, childObj ? 'found' : 'NOT FOUND');
|
||||
//console.log(`Child source:`, childObj?.source ? 'exists' : 'MISSING');
|
||||
if (childObj?.source) {
|
||||
//console.log(`Child source type:`, childObj.source.constructor.name);
|
||||
//console.log(`Child has state:`, !!childObj.source.state);
|
||||
}
|
||||
|
||||
mg.childRegistrationUtils.registerChild(
|
||||
childObj.source,
|
||||
msg.positionVsParent
|
||||
);
|
||||
|
||||
// Debug: Check machines after registration
|
||||
//console.log(`Total machines after registration:`, Object.keys(mg.machines || {}).length);
|
||||
break;
|
||||
case "registerChild": {
|
||||
const childId = msg.payload;
|
||||
const childObj = RED.nodes.getNode(childId);
|
||||
if (!childObj || !childObj.source) {
|
||||
mg.logger.warn(`registerChild skipped: missing child/source for id=${childId}`);
|
||||
break;
|
||||
}
|
||||
|
||||
case "setMode":
|
||||
mg.logger.debug(`Registering child: ${childId}, found: ${!!childObj}, source: ${!!childObj?.source}`);
|
||||
|
||||
mg.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
|
||||
|
||||
mg.logger.debug(`Total machines after registration: ${Object.keys(mg.machines || {}).length}`);
|
||||
break;
|
||||
}
|
||||
|
||||
case "setMode": {
|
||||
const mode = msg.payload;
|
||||
mg.setMode(mode);
|
||||
break;
|
||||
}
|
||||
|
||||
case "setScaling":
|
||||
case "setScaling": {
|
||||
const scaling = msg.payload;
|
||||
mg.setScaling(scaling);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "Qd":
|
||||
case "Qd": {
|
||||
const Qd = parseFloat(msg.payload);
|
||||
const sourceQd = "parent";
|
||||
|
||||
if (isNaN(Qd)) {
|
||||
return mg.logger.error(`Invalid demand value: ${Qd}`);
|
||||
mg.logger.error(`Invalid demand value: ${msg.payload}`);
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
await mg.handleInput(sourceQd, Qd);
|
||||
msg.topic = mg.config.general.name;
|
||||
msg.payload = "done";
|
||||
send(msg);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
} catch (error) {
|
||||
mg.logger.error(`Failed to process Qd: ${error.message}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
// Handle unknown topics if needed
|
||||
mg.logger.warn(`Unknown topic: ${msg.topic}`);
|
||||
break;
|
||||
}
|
||||
done();
|
||||
} catch (error) {
|
||||
mg.logger.error(`Input handler failure: ${error.message}`);
|
||||
}
|
||||
if (typeof done === 'function') done();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -266,7 +271,7 @@ class nodeClass {
|
||||
this.node.on("close", (done) => {
|
||||
clearInterval(this._tickInterval);
|
||||
clearInterval(this._statusInterval);
|
||||
done();
|
||||
if (typeof done === 'function') done();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
12
test/README.md
Normal file
12
test/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# machineGroupControl Test Suite Layout
|
||||
|
||||
Required EVOLV layout:
|
||||
- basic/
|
||||
- integration/
|
||||
- edge/
|
||||
- helpers/
|
||||
|
||||
Baseline structure tests:
|
||||
- basic/structure-module-load.basic.test.js
|
||||
- integration/structure-examples.integration.test.js
|
||||
- edge/structure-examples-node-type.edge.test.js
|
||||
0
test/basic/.gitkeep
Normal file
0
test/basic/.gitkeep
Normal file
8
test/basic/structure-module-load.basic.test.js
Normal file
8
test/basic/structure-module-load.basic.test.js
Normal file
@@ -0,0 +1,8 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
test('machineGroupControl module load smoke', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
require('../../mgc.js');
|
||||
});
|
||||
});
|
||||
0
test/edge/.gitkeep
Normal file
0
test/edge/.gitkeep
Normal file
11
test/edge/structure-examples-node-type.edge.test.js
Normal file
11
test/edge/structure-examples-node-type.edge.test.js
Normal file
@@ -0,0 +1,11 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const flow = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../examples/basic.flow.json'), 'utf8'));
|
||||
|
||||
test('basic example includes node type machineGroupControl', () => {
|
||||
const count = flow.filter((n) => n && n.type === 'machineGroupControl').length;
|
||||
assert.equal(count >= 1, true);
|
||||
});
|
||||
0
test/helpers/.gitkeep
Normal file
0
test/helpers/.gitkeep
Normal file
0
test/integration/.gitkeep
Normal file
0
test/integration/.gitkeep
Normal file
227
test/integration/distribution-power-table.integration.test.js
Normal file
227
test/integration/distribution-power-table.integration.test.js
Normal file
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* machineGroupControl vs naive strategies — real pump curves
|
||||
*
|
||||
* Station: 2× hidrostal H05K-S03R + 1× hidrostal C5-D03R-SHN1
|
||||
* ΔP = 2000 mbar
|
||||
*
|
||||
* Compares the ACTUAL machineGroupControl optimalControl algorithm against
|
||||
* naive baselines. All strategies must deliver exactly Qd.
|
||||
*/
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const MachineGroup = require('../../src/specificClass');
|
||||
const Machine = require('../../../rotatingMachine/src/specificClass');
|
||||
|
||||
const DIFF_MBAR = 2000;
|
||||
const UP_MBAR = 500;
|
||||
const DOWN_MBAR = UP_MBAR + DIFF_MBAR;
|
||||
|
||||
const stateConfig = {
|
||||
time: { starting: 0, warmingup: 0, stopping: 0, coolingdown: 0 },
|
||||
movement: { speed: 1200, mode: 'staticspeed', maxSpeed: 1800 }
|
||||
};
|
||||
|
||||
function machineConfig(id, model) {
|
||||
return {
|
||||
general: { logging: { enabled: false, logLevel: 'error' }, name: id, id, unit: 'm3/h' },
|
||||
functionality: { softwareType: 'machine', role: 'rotationaldevicecontroller' },
|
||||
asset: { category: 'pump', type: 'centrifugal', model, supplier: 'hidrostal' },
|
||||
mode: {
|
||||
current: 'auto',
|
||||
allowedActions: { auto: ['execsequence', 'execmovement', 'flowmovement', 'statuscheck'] },
|
||||
allowedSources: { auto: ['parent', 'GUI'] }
|
||||
},
|
||||
sequences: {
|
||||
startup: ['starting', 'warmingup', 'operational'],
|
||||
shutdown: ['stopping', 'coolingdown', 'idle'],
|
||||
emergencystop: ['emergencystop', 'off'],
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function groupConfig() {
|
||||
return {
|
||||
general: { logging: { enabled: false, logLevel: 'error' }, name: 'station' },
|
||||
functionality: { softwareType: 'machinegroup', role: 'groupcontroller' },
|
||||
scaling: { current: 'absolute' },
|
||||
mode: { current: 'optimalcontrol' }
|
||||
};
|
||||
}
|
||||
|
||||
function injectPressure(m) {
|
||||
m.updateMeasuredPressure(UP_MBAR, 'upstream', { timestamp: Date.now(), unit: 'mbar', childName: 'up', childId: `up-${m.config.general.id}` });
|
||||
m.updateMeasuredPressure(DOWN_MBAR, 'downstream', { timestamp: Date.now(), unit: 'mbar', childName: 'dn', childId: `dn-${m.config.general.id}` });
|
||||
}
|
||||
|
||||
/* ---- naive baselines (pumps OFF = 0 flow, 0 power) ---- */
|
||||
|
||||
function distribute(machines, running, rawDist, Qd) {
|
||||
const dist = {};
|
||||
for (const id of Object.keys(machines)) dist[id] = 0;
|
||||
for (const id of running) {
|
||||
const m = machines[id];
|
||||
dist[id] = Math.min(m.predictFlow.currentFxyYMax, Math.max(m.predictFlow.currentFxyYMin, rawDist[id] || 0));
|
||||
}
|
||||
for (let pass = 0; pass < 20; pass++) {
|
||||
let rem = Qd - running.reduce((s, id) => s + dist[id], 0);
|
||||
if (Math.abs(rem) < 1e-9) break;
|
||||
for (const id of running) {
|
||||
if (Math.abs(rem) < 1e-9) break;
|
||||
const m = machines[id];
|
||||
const cap = rem > 0 ? m.predictFlow.currentFxyYMax - dist[id] : dist[id] - m.predictFlow.currentFxyYMin;
|
||||
if (cap > 1e-9) { const t = Math.min(Math.abs(rem), cap); dist[id] += rem > 0 ? t : -t; rem += rem > 0 ? -t : t; }
|
||||
}
|
||||
}
|
||||
return dist;
|
||||
}
|
||||
|
||||
function spillover(machines, Qd) {
|
||||
const sorted = Object.keys(machines).sort((a, b) => machines[a].predictFlow.currentFxyYMax - machines[b].predictFlow.currentFxyYMax);
|
||||
let running = [], maxCap = 0;
|
||||
for (const id of sorted) { running.push(id); maxCap += machines[id].predictFlow.currentFxyYMax; if (maxCap >= Qd) break; }
|
||||
const raw = {}; let rem = Qd;
|
||||
for (const id of running) { raw[id] = rem; rem = Math.max(0, rem - machines[id].predictFlow.currentFxyYMax); }
|
||||
const dist = distribute(machines, running, raw, Qd);
|
||||
let p = 0, f = 0;
|
||||
for (const id of running) { p += machines[id].inputFlowCalcPower(dist[id]); f += dist[id]; }
|
||||
return { dist, power: p, flow: f, combo: running };
|
||||
}
|
||||
|
||||
function equalAllOn(machines, Qd) {
|
||||
const ids = Object.keys(machines);
|
||||
const raw = {}; for (const id of ids) raw[id] = Qd / ids.length;
|
||||
const dist = distribute(machines, ids, raw, Qd);
|
||||
let p = 0, f = 0;
|
||||
for (const id of ids) { p += machines[id].inputFlowCalcPower(dist[id]); f += dist[id]; }
|
||||
return { dist, power: p, flow: f, combo: ids };
|
||||
}
|
||||
|
||||
/* ---- test ---- */
|
||||
|
||||
test('machineGroupControl vs naive baselines — real curves, verified flow', async () => {
|
||||
const mg = new MachineGroup(groupConfig());
|
||||
const machines = {};
|
||||
|
||||
for (const [id, model] of [['H05K-1','hidrostal-H05K-S03R'],['H05K-2','hidrostal-H05K-S03R'],['C5','hidrostal-C5-D03R-SHN1']]) {
|
||||
const m = new Machine(machineConfig(id, model), stateConfig);
|
||||
injectPressure(m);
|
||||
mg.childRegistrationUtils.registerChild(m, 'downstream');
|
||||
machines[id] = m;
|
||||
}
|
||||
|
||||
const toH = (v) => +(v * 3600).toFixed(1);
|
||||
const CANON_FLOW = 'm3/s';
|
||||
const CANON_POWER = 'W';
|
||||
|
||||
console.log(`\n=== STATION: 2×H05K + 1×C5 @ ΔP=${DIFF_MBAR} mbar ===`);
|
||||
console.table(Object.entries(machines).map(([id, m]) => ({
|
||||
id,
|
||||
'min (m³/h)': toH(m.predictFlow.currentFxyYMin),
|
||||
'max (m³/h)': toH(m.predictFlow.currentFxyYMax),
|
||||
'BEP (m³/h)': toH(m.predictFlow.currentFxyYMin + (m.predictFlow.currentFxyYMax - m.predictFlow.currentFxyYMin) * m.NCog),
|
||||
NCog: +m.NCog.toFixed(3),
|
||||
})));
|
||||
|
||||
const minQ = Math.max(...Object.values(machines).map(m => m.predictFlow.currentFxyYMin));
|
||||
const maxQ = Object.values(machines).reduce((s, m) => s + m.predictFlow.currentFxyYMax, 0);
|
||||
const demandPcts = [0.10, 0.25, 0.50, 0.75, 0.90];
|
||||
const rows = [];
|
||||
|
||||
for (const pct of demandPcts) {
|
||||
const Qd = minQ + (maxQ - minQ) * pct;
|
||||
|
||||
// Reset all machines to idle, re-inject pressure
|
||||
for (const m of Object.values(machines)) {
|
||||
if (m.state.getCurrentState() !== 'idle') await m.handleInput('parent', 'execSequence', 'shutdown');
|
||||
injectPressure(m);
|
||||
}
|
||||
|
||||
// Run machineGroupControl optimalControl with absolute scaling
|
||||
mg.setMode('optimalcontrol');
|
||||
mg.setScaling('absolute');
|
||||
mg.calcAbsoluteTotals();
|
||||
mg.calcDynamicTotals();
|
||||
await mg.handleInput('parent', Qd);
|
||||
|
||||
// Read ACTUAL per-pump state (not the MGC summary which may be stale)
|
||||
let mgcPower = 0, mgcFlow = 0;
|
||||
const mgcCombo = [];
|
||||
const mgcDist = {};
|
||||
for (const [id, m] of Object.entries(machines)) {
|
||||
const state = m.state.getCurrentState();
|
||||
const flow = m.measurements.type('flow').variant('predicted').position('downstream').getCurrentValue(CANON_FLOW) || 0;
|
||||
const power = m.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue(CANON_POWER) || 0;
|
||||
mgcDist[id] = { flow, power, state };
|
||||
if (state === 'operational' || state === 'warmingup' || state === 'accelerating') {
|
||||
mgcCombo.push(id);
|
||||
mgcPower += power;
|
||||
mgcFlow += flow;
|
||||
}
|
||||
}
|
||||
|
||||
// Naive baselines
|
||||
const sp = spillover(machines, Qd);
|
||||
const ea = equalAllOn(machines, Qd);
|
||||
|
||||
const best = Math.min(mgcPower, sp.power, ea.power);
|
||||
const delta = (v) => best > 0 ? `${(((v - best) / best) * 100).toFixed(1)}%` : '';
|
||||
|
||||
rows.push({
|
||||
demand: `${(pct * 100)}%`,
|
||||
'Qd (m³/h)': toH(Qd),
|
||||
'MGC kW': +(mgcPower / 1000).toFixed(1),
|
||||
'MGC flow': toH(mgcFlow),
|
||||
'MGC pumps': mgcCombo.join('+') || 'none',
|
||||
'Spill kW': +(sp.power / 1000).toFixed(1),
|
||||
'Spill flow': toH(sp.flow),
|
||||
'Spill pumps': sp.combo.join('+'),
|
||||
'EqAll kW': +(ea.power / 1000).toFixed(1),
|
||||
'EqAll flow': toH(ea.flow),
|
||||
'MGC Δ': delta(mgcPower),
|
||||
'Spill Δ': delta(sp.power),
|
||||
'EqAll Δ': delta(ea.power),
|
||||
});
|
||||
}
|
||||
|
||||
console.log('\n=== POWER + FLOW COMPARISON (★ = best, all must deliver Qd) ===');
|
||||
console.table(rows);
|
||||
|
||||
// Per-pump detail at each demand level
|
||||
for (const pct of demandPcts) {
|
||||
const Qd = minQ + (maxQ - minQ) * pct;
|
||||
|
||||
for (const m of Object.values(machines)) {
|
||||
if (m.state.getCurrentState() !== 'idle') await m.handleInput('parent', 'execSequence', 'shutdown');
|
||||
injectPressure(m);
|
||||
}
|
||||
mg.setMode('optimalcontrol');
|
||||
mg.setScaling('absolute');
|
||||
mg.calcAbsoluteTotals();
|
||||
mg.calcDynamicTotals();
|
||||
await mg.handleInput('parent', Qd);
|
||||
|
||||
const detail = Object.entries(machines).map(([id, m]) => {
|
||||
const state = m.state.getCurrentState();
|
||||
const flow = m.measurements.type('flow').variant('predicted').position('downstream').getCurrentValue(CANON_FLOW) || 0;
|
||||
const power = m.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue(CANON_POWER) || 0;
|
||||
return {
|
||||
pump: id,
|
||||
state,
|
||||
'flow (m³/h)': toH(flow),
|
||||
'power (kW)': +(power / 1000).toFixed(1),
|
||||
};
|
||||
});
|
||||
console.log(`\n--- MGC per-pump @ ${(pct*100)}% (${toH(Qd)} m³/h) ---`);
|
||||
console.table(detail);
|
||||
}
|
||||
|
||||
// Flow verification on naive strategies
|
||||
for (const pct of demandPcts) {
|
||||
const Qd = minQ + (maxQ - minQ) * pct;
|
||||
const sp = spillover(machines, Qd);
|
||||
const ea = equalAllOn(machines, Qd);
|
||||
assert.ok(Math.abs(sp.flow - Qd) < Qd * 0.005, `Spillover flow mismatch at ${(pct*100)}%`);
|
||||
assert.ok(Math.abs(ea.flow - Qd) < Qd * 0.005, `Equal-all flow mismatch at ${(pct*100)}%`);
|
||||
}
|
||||
});
|
||||
442
test/integration/ncog-distribution.integration.test.js
Normal file
442
test/integration/ncog-distribution.integration.test.js
Normal file
@@ -0,0 +1,442 @@
|
||||
/**
|
||||
* Group Distribution Strategy Comparison Test
|
||||
*
|
||||
* Compares three flow distribution strategies for a group of pumps:
|
||||
* 1. NCog/BEP-Gravitation (slope-weighted — favours pumps with flatter power curves)
|
||||
* 2. Equal distribution (same flow to every pump)
|
||||
* 3. Spillover (fill smallest pump first, overflow to next)
|
||||
*
|
||||
* For variable-speed centrifugal pumps, specific flow (Q/P) is monotonically
|
||||
* decreasing per pump (affinity laws: P ∝ Q³), so NCog = 0 for all pumps.
|
||||
* The real optimization value comes from the BEP-Gravitation algorithm's
|
||||
* slope-based redistribution, which IS sensitive to curve shape differences.
|
||||
*
|
||||
* These tests verify that:
|
||||
* - Asymmetric pumps produce different power slopes (the basis for optimization)
|
||||
* - BEP-Gravitation uses less total power than naive strategies for mixed pumps
|
||||
* - Equal pumps receive equal treatment under all strategies
|
||||
* - Spillover creates a visibly different distribution than BEP-weighted
|
||||
*/
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const MachineGroup = require('../../src/specificClass');
|
||||
const Machine = require('../../../rotatingMachine/src/specificClass');
|
||||
|
||||
const baseCurve = require('../../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
|
||||
|
||||
/* ---- helpers ---- */
|
||||
|
||||
function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); }
|
||||
|
||||
function distortSeries(series, scale = 1, tilt = 0) {
|
||||
const last = series.length - 1;
|
||||
return series.map((v, i) => {
|
||||
const gradient = last === 0 ? 0 : i / last - 0.5;
|
||||
return Math.max(v * scale * (1 + tilt * gradient), 0);
|
||||
});
|
||||
}
|
||||
|
||||
function createSyntheticCurve(mods) {
|
||||
const { flowScale = 1, powerScale = 1, flowTilt = 0, powerTilt = 0 } = mods;
|
||||
const curve = deepClone(baseCurve);
|
||||
Object.values(curve.nq).forEach(s => { s.y = distortSeries(s.y, flowScale, flowTilt); });
|
||||
Object.values(curve.np).forEach(s => { s.y = distortSeries(s.y, powerScale, powerTilt); });
|
||||
return curve;
|
||||
}
|
||||
|
||||
const stateConfig = {
|
||||
time: { starting: 0, warmingup: 0, stopping: 0, coolingdown: 0 },
|
||||
movement: { speed: 1200, mode: 'staticspeed', maxSpeed: 1800 }
|
||||
};
|
||||
|
||||
function createMachineConfig(id, label) {
|
||||
return {
|
||||
general: { logging: { enabled: false, logLevel: 'error' }, name: label, id, unit: 'm3/h' },
|
||||
functionality: { softwareType: 'machine', role: 'rotationaldevicecontroller' },
|
||||
asset: { category: 'pump', type: 'centrifugal', model: 'hidrostal-H05K-S03R', supplier: 'hidrostal' },
|
||||
mode: {
|
||||
current: 'auto',
|
||||
allowedActions: { auto: ['execsequence', 'execmovement', 'flowmovement', 'statuscheck'] },
|
||||
allowedSources: { auto: ['parent', 'GUI'] }
|
||||
},
|
||||
sequences: {
|
||||
startup: ['starting', 'warmingup', 'operational'],
|
||||
shutdown: ['stopping', 'coolingdown', 'idle'],
|
||||
emergencystop: ['emergencystop', 'off'],
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createGroupConfig(name) {
|
||||
return {
|
||||
general: { logging: { enabled: false, logLevel: 'error' }, name },
|
||||
functionality: { softwareType: 'machinegroup', role: 'groupcontroller' },
|
||||
scaling: { current: 'normalized' },
|
||||
mode: { current: 'optimalcontrol' }
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap with differential pressure (upstream + downstream) so the predict
|
||||
* engine resolves a realistic fDimension and calcEfficiencyCurve produces
|
||||
* a proper BEP peak — not a monotonic Q/P curve.
|
||||
*/
|
||||
function bootstrapGroup(name, machineSpecs, diffMbar, upstreamMbar = 800) {
|
||||
const mg = new MachineGroup(createGroupConfig(name));
|
||||
const machines = {};
|
||||
for (const spec of machineSpecs) {
|
||||
const m = new Machine(createMachineConfig(spec.id, spec.label), stateConfig);
|
||||
if (spec.curveMods) m.updateCurve(createSyntheticCurve(spec.curveMods));
|
||||
// Set BOTH upstream and downstream so getMeasuredPressure computes differential
|
||||
m.updateMeasuredPressure(upstreamMbar, 'upstream', {
|
||||
timestamp: Date.now(), unit: 'mbar', childName: `pt-up-${spec.id}`, childId: `pt-up-${spec.id}`
|
||||
});
|
||||
m.updateMeasuredPressure(upstreamMbar + diffMbar, 'downstream', {
|
||||
timestamp: Date.now(), unit: 'mbar', childName: `pt-dn-${spec.id}`, childId: `pt-dn-${spec.id}`
|
||||
});
|
||||
mg.childRegistrationUtils.registerChild(m, 'downstream');
|
||||
machines[spec.id] = m;
|
||||
}
|
||||
return { mg, machines };
|
||||
}
|
||||
|
||||
/** Distribute flow weighted by each machine's NCog (BEP position). */
|
||||
function distributeByNCog(machines, Qd) {
|
||||
const entries = Object.entries(machines);
|
||||
let totalNCog = entries.reduce((s, [, m]) => s + (m.NCog || 0), 0);
|
||||
|
||||
const distribution = {};
|
||||
for (const [id, m] of entries) {
|
||||
const min = m.predictFlow.currentFxyYMin;
|
||||
const max = m.predictFlow.currentFxyYMax;
|
||||
const flow = totalNCog > 0
|
||||
? ((m.NCog || 0) / totalNCog) * Qd
|
||||
: Qd / entries.length;
|
||||
distribution[id] = Math.min(max, Math.max(min, flow));
|
||||
}
|
||||
|
||||
let totalPower = 0;
|
||||
for (const [id, m] of entries) {
|
||||
totalPower += m.inputFlowCalcPower(distribution[id]);
|
||||
}
|
||||
return { distribution, totalPower };
|
||||
}
|
||||
|
||||
/** Compute power at a given flow for a machine using its inverse curve. */
|
||||
function powerAtFlow(machine, flow) {
|
||||
return machine.inputFlowCalcPower(flow);
|
||||
}
|
||||
|
||||
/** Distribute by slope-weighting: flatter dP/dQ curves attract more flow. */
|
||||
function distributeBySlopeWeight(machines, Qd) {
|
||||
const entries = Object.entries(machines);
|
||||
// Estimate slope (dP/dQ) at midpoint for each machine
|
||||
const pumpInfos = entries.map(([id, m]) => {
|
||||
const min = m.predictFlow.currentFxyYMin;
|
||||
const max = m.predictFlow.currentFxyYMax;
|
||||
const mid = (min + max) / 2;
|
||||
const delta = Math.max((max - min) * 0.05, 0.001);
|
||||
const pMid = powerAtFlow(m, mid);
|
||||
const pRight = powerAtFlow(m, Math.min(max, mid + delta));
|
||||
const slope = Math.abs((pRight - pMid) / delta);
|
||||
return { id, m, min, max, slope: Math.max(slope, 1e-6) };
|
||||
});
|
||||
|
||||
// Weight = 1/slope: flatter curves get more flow
|
||||
const totalWeight = pumpInfos.reduce((s, p) => s + (1 / p.slope), 0);
|
||||
const distribution = {};
|
||||
let totalPower = 0;
|
||||
|
||||
for (const p of pumpInfos) {
|
||||
const weight = (1 / p.slope) / totalWeight;
|
||||
const flow = Math.min(p.max, Math.max(p.min, Qd * weight));
|
||||
distribution[p.id] = flow;
|
||||
totalPower += powerAtFlow(p.m, flow);
|
||||
}
|
||||
|
||||
return { distribution, totalPower };
|
||||
}
|
||||
|
||||
/** Distribute equally. */
|
||||
function distributeEqual(machines, Qd) {
|
||||
const entries = Object.entries(machines);
|
||||
const flowEach = Qd / entries.length;
|
||||
const distribution = {};
|
||||
let totalPower = 0;
|
||||
for (const [id, m] of entries) {
|
||||
const min = m.predictFlow.currentFxyYMin;
|
||||
const max = m.predictFlow.currentFxyYMax;
|
||||
const clamped = Math.min(max, Math.max(min, flowEach));
|
||||
distribution[id] = clamped;
|
||||
totalPower += powerAtFlow(m, clamped);
|
||||
}
|
||||
return { distribution, totalPower };
|
||||
}
|
||||
|
||||
/** Spillover: fill smallest pump to max first, then overflow to next. */
|
||||
function distributeSpillover(machines, Qd) {
|
||||
const entries = Object.entries(machines)
|
||||
.sort(([, a], [, b]) => a.predictFlow.currentFxyYMax - b.predictFlow.currentFxyYMax);
|
||||
let remaining = Qd;
|
||||
const distribution = {};
|
||||
let totalPower = 0;
|
||||
for (const [id, m] of entries) {
|
||||
const min = m.predictFlow.currentFxyYMin;
|
||||
const max = m.predictFlow.currentFxyYMax;
|
||||
const assigned = Math.min(max, Math.max(min, remaining));
|
||||
distribution[id] = assigned;
|
||||
remaining = Math.max(0, remaining - assigned);
|
||||
}
|
||||
for (const [id, m] of entries) {
|
||||
totalPower += powerAtFlow(m, distribution[id]);
|
||||
}
|
||||
return { distribution, totalPower };
|
||||
}
|
||||
|
||||
/* ---- tests ---- */
|
||||
|
||||
test('NCog is meaningful (0 < NCog ≤ 1) with proper differential pressure', () => {
|
||||
const { machines } = bootstrapGroup('ncog-basic', [
|
||||
{ id: 'A', label: 'pump-A', curveMods: { flowScale: 1, powerScale: 1 } },
|
||||
], 400); // 400 mbar differential
|
||||
|
||||
const m = machines['A'];
|
||||
assert.ok(Number.isFinite(m.NCog), `NCog should be finite, got ${m.NCog}`);
|
||||
assert.ok(m.NCog > 0 && m.NCog <= 1, `NCog should be in (0,1], got ${m.NCog.toFixed(4)}`);
|
||||
assert.ok(m.cog > 0, `cog (peak specific flow) should be positive, got ${m.cog}`);
|
||||
assert.ok(m.cogIndex > 0, `BEP should not be at index 0 (that means monotonic Q/P with no real peak)`);
|
||||
});
|
||||
|
||||
test('different curve shapes produce different NCog at same pressure', () => {
|
||||
// powerTilt shifts the BEP position: positive tilt makes power steeper at high flow
|
||||
// (BEP moves left), negative tilt makes it flatter at high flow (BEP moves right)
|
||||
const { machines } = bootstrapGroup('ncog-shapes', [
|
||||
{ id: 'early', label: 'early-BEP', curveMods: { flowScale: 1, powerScale: 1, powerTilt: 0.4 } },
|
||||
{ id: 'late', label: 'late-BEP', curveMods: { flowScale: 1, powerScale: 1, powerTilt: -0.3 } },
|
||||
], 400);
|
||||
|
||||
const ncogEarly = machines['early'].NCog;
|
||||
const ncogLate = machines['late'].NCog;
|
||||
|
||||
assert.ok(ncogEarly > 0, `Early BEP NCog should be > 0, got ${ncogEarly.toFixed(4)}`);
|
||||
assert.ok(ncogLate > 0, `Late BEP NCog should be > 0, got ${ncogLate.toFixed(4)}`);
|
||||
assert.ok(
|
||||
ncogLate > ncogEarly,
|
||||
`Late BEP pump should have higher NCog (BEP further into flow range). ` +
|
||||
`early=${ncogEarly.toFixed(4)}, late=${ncogLate.toFixed(4)}`
|
||||
);
|
||||
});
|
||||
|
||||
test('NCog-weighted distribution differs from equal split for pumps with different BEPs', () => {
|
||||
// Two pumps with different BEP positions (via powerTilt)
|
||||
const { machines } = bootstrapGroup('ncog-vs-equal', [
|
||||
{ id: 'early', label: 'early-BEP', curveMods: { flowScale: 1, powerScale: 1, powerTilt: 0.4 } },
|
||||
{ id: 'late', label: 'late-BEP', curveMods: { flowScale: 1, powerScale: 1, powerTilt: -0.3 } },
|
||||
], 400);
|
||||
|
||||
const ncogA = machines['early'].NCog;
|
||||
const ncogB = machines['late'].NCog;
|
||||
assert.ok(ncogA > 0 && ncogB > 0, `Both NCog should be > 0 (early=${ncogA.toFixed(3)}, late=${ncogB.toFixed(3)})`);
|
||||
assert.ok(ncogA !== ncogB, 'NCog values should differ');
|
||||
|
||||
const totalMax = machines['early'].predictFlow.currentFxyYMax + machines['late'].predictFlow.currentFxyYMax;
|
||||
const Qd = totalMax * 0.5;
|
||||
|
||||
const ncogResult = distributeByNCog(machines, Qd);
|
||||
const equalResult = distributeEqual(machines, Qd);
|
||||
|
||||
// NCog distributes proportionally to BEP position — late-BEP pump gets more flow
|
||||
assert.ok(
|
||||
ncogResult.distribution['late'] > ncogResult.distribution['early'],
|
||||
`Late-BEP pump should get more flow under NCog. ` +
|
||||
`early=${ncogResult.distribution['early'].toFixed(2)}, late=${ncogResult.distribution['late'].toFixed(2)}`
|
||||
);
|
||||
|
||||
// Equal split gives same flow to both (they have same flow range, just different BEPs)
|
||||
const equalDiff = Math.abs(equalResult.distribution['early'] - equalResult.distribution['late']);
|
||||
const ncogDiff = Math.abs(ncogResult.distribution['early'] - ncogResult.distribution['late']);
|
||||
assert.ok(
|
||||
ncogDiff > equalDiff + Qd * 0.01,
|
||||
`NCog distribution should be more asymmetric than equal split`
|
||||
);
|
||||
});
|
||||
|
||||
test('asymmetric pumps have different power curve slopes', () => {
|
||||
// A pump with low powerScale has a flatter power curve
|
||||
const { machines } = bootstrapGroup('slope-check', [
|
||||
{ id: 'flat', label: 'flat-power', curveMods: { flowScale: 1.2, powerScale: 0.7, flowTilt: 0.1 } },
|
||||
{ id: 'steep', label: 'steep-power', curveMods: { flowScale: 0.8, powerScale: 1.4, flowTilt: -0.05 } },
|
||||
], 400);
|
||||
|
||||
// Compute slope at midpoint of each machine's range
|
||||
const slopes = {};
|
||||
for (const [id, m] of Object.entries(machines)) {
|
||||
const mid = (m.predictFlow.currentFxyYMin + m.predictFlow.currentFxyYMax) / 2;
|
||||
const delta = (m.predictFlow.currentFxyYMax - m.predictFlow.currentFxyYMin) * 0.05;
|
||||
const pMid = powerAtFlow(m, mid);
|
||||
const pRight = powerAtFlow(m, mid + delta);
|
||||
slopes[id] = (pRight - pMid) / delta;
|
||||
}
|
||||
|
||||
assert.ok(slopes['flat'] > 0 && slopes['steep'] > 0, 'Both slopes should be positive');
|
||||
assert.ok(
|
||||
slopes['steep'] > slopes['flat'] * 1.3,
|
||||
`Steep pump should have notably higher slope. flat=${slopes['flat'].toFixed(0)}, steep=${slopes['steep'].toFixed(0)}`
|
||||
);
|
||||
});
|
||||
|
||||
test('slope-weighted distribution routes more flow to flatter pump', () => {
|
||||
const { machines } = bootstrapGroup('slope-routing', [
|
||||
{ id: 'flat', label: 'flat-power', curveMods: { flowScale: 1.2, powerScale: 0.7 } },
|
||||
{ id: 'steep', label: 'steep-power', curveMods: { flowScale: 0.8, powerScale: 1.4 } },
|
||||
], 400);
|
||||
|
||||
const totalMax = machines['flat'].predictFlow.currentFxyYMax + machines['steep'].predictFlow.currentFxyYMax;
|
||||
const Qd = totalMax * 0.5;
|
||||
|
||||
const slopeResult = distributeBySlopeWeight(machines, Qd);
|
||||
|
||||
assert.ok(
|
||||
slopeResult.distribution['flat'] > slopeResult.distribution['steep'],
|
||||
`Flat pump should get more flow. flat=${slopeResult.distribution['flat'].toFixed(2)}, steep=${slopeResult.distribution['steep'].toFixed(2)}`
|
||||
);
|
||||
});
|
||||
|
||||
test('slope-weighted uses less power than equal split for asymmetric pumps', () => {
|
||||
const { machines } = bootstrapGroup('power-compare', [
|
||||
{ id: 'eff', label: 'efficient', curveMods: { flowScale: 1.2, powerScale: 0.7, flowTilt: 0.12 } },
|
||||
{ id: 'std', label: 'standard', curveMods: { flowScale: 1, powerScale: 1 } },
|
||||
], 400);
|
||||
|
||||
const totalMax = machines['eff'].predictFlow.currentFxyYMax + machines['std'].predictFlow.currentFxyYMax;
|
||||
const demandLevels = [0.3, 0.5, 0.7].map(p => {
|
||||
const min = Math.max(machines['eff'].predictFlow.currentFxyYMin, machines['std'].predictFlow.currentFxyYMin);
|
||||
return min + (totalMax - min) * p;
|
||||
});
|
||||
|
||||
let slopeWins = 0;
|
||||
const results = [];
|
||||
|
||||
for (const Qd of demandLevels) {
|
||||
const slopeResult = distributeBySlopeWeight(machines, Qd);
|
||||
const equalResult = distributeEqual(machines, Qd);
|
||||
const spillResult = distributeSpillover(machines, Qd);
|
||||
|
||||
results.push({
|
||||
demand: Qd,
|
||||
slopePower: slopeResult.totalPower,
|
||||
equalPower: equalResult.totalPower,
|
||||
spillPower: spillResult.totalPower,
|
||||
});
|
||||
|
||||
if (slopeResult.totalPower <= equalResult.totalPower + 1) slopeWins++;
|
||||
}
|
||||
|
||||
assert.ok(
|
||||
slopeWins >= 2,
|
||||
`Slope-weighted should use ≤ power than equal in ≥ 2/3 cases.\n` +
|
||||
results.map(r =>
|
||||
` Qd=${r.demand.toFixed(1)}: slope=${r.slopePower.toFixed(1)}W, equal=${r.equalPower.toFixed(1)}W, spill=${r.spillPower.toFixed(1)}W`
|
||||
).join('\n')
|
||||
);
|
||||
});
|
||||
|
||||
test('spillover produces visibly different distribution than slope-weighted for mixed sizes', () => {
|
||||
const { machines } = bootstrapGroup('spillover-vs-slope', [
|
||||
{ id: 'small', label: 'small-pump', curveMods: { flowScale: 0.6, powerScale: 0.55 } },
|
||||
{ id: 'large', label: 'large-pump', curveMods: { flowScale: 1.5, powerScale: 1.2 } },
|
||||
], 400);
|
||||
|
||||
const totalMax = machines['small'].predictFlow.currentFxyYMax + machines['large'].predictFlow.currentFxyYMax;
|
||||
const Qd = totalMax * 0.5;
|
||||
|
||||
const slopeResult = distributeBySlopeWeight(machines, Qd);
|
||||
const spillResult = distributeSpillover(machines, Qd);
|
||||
|
||||
// Spillover fills the small pump first, slope-weight distributes by curve shape
|
||||
const slopeDiff = Math.abs(slopeResult.distribution['small'] - spillResult.distribution['small']);
|
||||
const percentDiff = (slopeDiff / Qd) * 100;
|
||||
|
||||
assert.ok(
|
||||
percentDiff > 1,
|
||||
`Strategies should produce different distributions. ` +
|
||||
`Slope small=${slopeResult.distribution['small'].toFixed(2)}, ` +
|
||||
`Spill small=${spillResult.distribution['small'].toFixed(2)} (${percentDiff.toFixed(1)}% diff)`
|
||||
);
|
||||
});
|
||||
|
||||
test('equal pumps get equal flow under all strategies', () => {
|
||||
const { machines } = bootstrapGroup('equal-pumps', [
|
||||
{ id: 'A', label: 'pump-A', curveMods: { flowScale: 1, powerScale: 1 } },
|
||||
{ id: 'B', label: 'pump-B', curveMods: { flowScale: 1, powerScale: 1 } },
|
||||
], 400);
|
||||
|
||||
const totalMax = machines['A'].predictFlow.currentFxyYMax + machines['B'].predictFlow.currentFxyYMax;
|
||||
const Qd = totalMax * 0.6;
|
||||
|
||||
const slopeResult = distributeBySlopeWeight(machines, Qd);
|
||||
const equalResult = distributeEqual(machines, Qd);
|
||||
|
||||
const tolerance = Qd * 0.01;
|
||||
|
||||
assert.ok(
|
||||
Math.abs(slopeResult.distribution['A'] - slopeResult.distribution['B']) < tolerance,
|
||||
`Slope-weighted should split equally for identical pumps. A=${slopeResult.distribution['A'].toFixed(2)}, B=${slopeResult.distribution['B'].toFixed(2)}`
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(equalResult.distribution['A'] - equalResult.distribution['B']) < tolerance,
|
||||
`Equal should split equally. A=${equalResult.distribution['A'].toFixed(2)}, B=${equalResult.distribution['B'].toFixed(2)}`
|
||||
);
|
||||
|
||||
// Power should be identical too
|
||||
assert.ok(
|
||||
Math.abs(slopeResult.totalPower - equalResult.totalPower) < 1,
|
||||
`Equal pumps should produce same total power under any strategy`
|
||||
);
|
||||
});
|
||||
|
||||
test('full MGC optimalControl uses ≤ power than priorityControl for mixed pumps', async () => {
|
||||
const { mg, machines } = bootstrapGroup('mgc-full', [
|
||||
{ id: 'eff', label: 'efficient', curveMods: { flowScale: 1.2, powerScale: 0.7, flowTilt: 0.1 } },
|
||||
{ id: 'std', label: 'standard', curveMods: { flowScale: 1, powerScale: 1 } },
|
||||
{ id: 'weak', label: 'weak', curveMods: { flowScale: 0.8, powerScale: 1.3, flowTilt: -0.08 } },
|
||||
], 400);
|
||||
|
||||
for (const m of Object.values(machines)) {
|
||||
await m.handleInput('parent', 'execSequence', 'startup');
|
||||
}
|
||||
|
||||
// Run optimalControl
|
||||
mg.setMode('optimalcontrol');
|
||||
mg.setScaling('normalized');
|
||||
await mg.handleInput('parent', 50, Infinity);
|
||||
const optPower = mg.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
||||
const optFlow = mg.measurements.type('flow').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
||||
|
||||
// Reset machines
|
||||
for (const m of Object.values(machines)) {
|
||||
await m.handleInput('parent', 'execSequence', 'shutdown');
|
||||
await m.handleInput('parent', 'execSequence', 'startup');
|
||||
}
|
||||
|
||||
// Run priorityControl
|
||||
mg.setMode('prioritycontrol');
|
||||
await mg.handleInput('parent', 50, Infinity, ['eff', 'std', 'weak']);
|
||||
const prioPower = mg.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
||||
const prioFlow = mg.measurements.type('flow').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
||||
|
||||
assert.ok(optFlow > 0, `Optimal should deliver flow, got ${optFlow}`);
|
||||
assert.ok(prioFlow > 0, `Priority should deliver flow, got ${prioFlow}`);
|
||||
|
||||
// Compare efficiency (flow per unit power)
|
||||
const optEff = optPower > 0 ? optFlow / optPower : 0;
|
||||
const prioEff = prioPower > 0 ? prioFlow / prioPower : 0;
|
||||
|
||||
assert.ok(
|
||||
optEff >= prioEff * 0.95,
|
||||
`Optimal efficiency should be ≥ priority (within 5% tolerance). ` +
|
||||
`Opt: ${optFlow.toFixed(1)}/${optPower.toFixed(1)}=${optEff.toFixed(6)} | ` +
|
||||
`Prio: ${prioFlow.toFixed(1)}/${prioPower.toFixed(1)}=${prioEff.toFixed(6)}`
|
||||
);
|
||||
});
|
||||
23
test/integration/structure-examples.integration.test.js
Normal file
23
test/integration/structure-examples.integration.test.js
Normal file
@@ -0,0 +1,23 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const dir = path.resolve(__dirname, '../../examples');
|
||||
|
||||
function loadJson(file) {
|
||||
return JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));
|
||||
}
|
||||
|
||||
test('examples package exists for machineGroupControl', () => {
|
||||
for (const file of ['README.md', 'basic.flow.json', 'integration.flow.json', 'edge.flow.json']) {
|
||||
assert.equal(fs.existsSync(path.join(dir, file)), true, file + ' missing');
|
||||
}
|
||||
});
|
||||
|
||||
test('example flows are parseable arrays for machineGroupControl', () => {
|
||||
for (const file of ['basic.flow.json', 'integration.flow.json', 'edge.flow.json']) {
|
||||
const parsed = loadJson(file);
|
||||
assert.equal(Array.isArray(parsed), true);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user