Compare commits
14 Commits
85797b5b8b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7eafd89f4e | ||
|
|
d55f401ab3 | ||
|
|
ffb2072baa | ||
|
|
b337bf9eb7 | ||
|
|
f8012c8bad | ||
|
|
ee38c8b581 | ||
| 0430471dca | |||
|
|
f4cb329597 | ||
|
|
b49f0c3ed2 | ||
|
|
edcffade75 | ||
|
|
b6ffefc92b | ||
|
|
ed2cf4c23d | ||
| 681856104d | |||
|
|
e0526250c2 |
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":[]}
|
||||||
|
]
|
||||||
2
mgc.html
2
mgc.html
@@ -41,7 +41,7 @@
|
|||||||
icon: "font-awesome/fa-cogs",
|
icon: "font-awesome/fa-cogs",
|
||||||
|
|
||||||
label: function () {
|
label: function () {
|
||||||
return this.positionIcon + " " + "machineGroup";
|
return (this.positionIcon || "") + " machineGroup";
|
||||||
},
|
},
|
||||||
oneditprepare: function() {
|
oneditprepare: function() {
|
||||||
// Initialize the menu data for the node
|
// Initialize the menu data for the node
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
"description": "Control module machineGroupControl",
|
"description": "Control module machineGroupControl",
|
||||||
"main": "mgc.js",
|
"main": "mgc.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node mgc.js"
|
"test": "node --test test/basic/*.test.js test/integration/*.test.js test/edge/*.test.js"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
|
|||||||
@@ -1,288 +1,345 @@
|
|||||||
// ...existing code...
|
'use strict';
|
||||||
const MachineGroup = require('./specificClass.js');
|
|
||||||
|
const MachineGroup = require('./specificClass');
|
||||||
const Machine = require('../../rotatingMachine/src/specificClass');
|
const Machine = require('../../rotatingMachine/src/specificClass');
|
||||||
const Measurement = require('../../measurement/src/specificClass');
|
const Measurement = require('../../measurement/src/specificClass');
|
||||||
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
|
const baseCurve = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
|
||||||
|
|
||||||
const stateConfig = { time:{starting:0,warmingup:0,stopping:0,coolingdown:0}, movement:{speed:1000,mode:"staticspeed"} };
|
const CONTROL_MODES = ['optimalcontrol', 'prioritycontrol', 'prioritypercentagecontrol'];
|
||||||
const ptConfig = {
|
const MODE_LABELS = {
|
||||||
general:{ logging:{enabled:false,logLevel:"warn"}, name:"testpt", id:"pt-1", unit:"mbar" },
|
optimalcontrol: 'OPT',
|
||||||
functionality:{ softwareType:"measurement", role:"sensor" },
|
prioritycontrol: 'PRIO',
|
||||||
asset:{ category:"sensor", type:"pressure", model:"testmodel", supplier:"vega", unit:"mbar" },
|
prioritypercentagecontrol: 'PERC'
|
||||||
scaling:{ absMin:0, absMax:4000 }
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const testSuite = [];
|
const stateConfig = {
|
||||||
const efficiencyComparisons = [];
|
time: { starting: 0, warmingup: 0, stopping: 0, coolingdown: 0, emergencystop: 0 },
|
||||||
|
movement: { speed: 1200, mode: 'staticspeed', maxSpeed: 1800 }
|
||||||
|
};
|
||||||
|
|
||||||
function logPass(name, details="") {
|
const ptConfig = {
|
||||||
const entry = { name, status:"PASS", details };
|
general: { logging: { enabled: false, logLevel: 'error' }, name: 'synthetic-pt', id: 'pt-1', unit: 'mbar' },
|
||||||
testSuite.push(entry);
|
functionality: {
|
||||||
console.log(`✅ ${name}${details ? ` — ${details}` : ""}`);
|
softwareType: 'measurement',
|
||||||
}
|
role: 'sensor',
|
||||||
function logFail(name, error) {
|
positionVsParent: 'downstream'
|
||||||
const entry = { name, status:"FAIL", details:error?.message || error };
|
},
|
||||||
testSuite.push(entry);
|
asset: { category: 'sensor', type: 'pressure', model: 'synthetic-pt', supplier: 'lab', unit: 'mbar' },
|
||||||
console.error(`❌ ${name} — ${entry.details}`);
|
scaling: { absMin: 0, absMax: 4000 }
|
||||||
}
|
};
|
||||||
function approxEqual(actual, expected, tolerancePct=1) {
|
|
||||||
const tolerance = (expected * tolerancePct) / 100;
|
|
||||||
return actual >= expected - tolerance && actual <= expected + tolerance;
|
|
||||||
}
|
|
||||||
async function sleep(ms){ return new Promise(resolve => setTimeout(resolve, ms)); }
|
|
||||||
|
|
||||||
function createMachineConfig(id,label) {
|
const scenarios = [
|
||||||
|
{
|
||||||
|
name: 'balanced_pair',
|
||||||
|
description: 'Two identical pumps validate equal-machine behaviour.',
|
||||||
|
machines: [
|
||||||
|
{ id: 'eq-1', label: 'equal-A', curveMods: { flowScale: 1, powerScale: 1 } },
|
||||||
|
{ id: 'eq-2', label: 'equal-B', curveMods: { flowScale: 1, powerScale: 1 } }
|
||||||
|
],
|
||||||
|
pressures: [900, 1300, 1700],
|
||||||
|
flowTargetsPercent: [0.1, 0.4, 0.7, 1],
|
||||||
|
flowMatchTolerance: 5,
|
||||||
|
priorityList: ['eq-1', 'eq-2']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'mixed_trio',
|
||||||
|
description: 'High / mid / low efficiency pumps to stress unequal-machine behaviour.',
|
||||||
|
machines: [
|
||||||
|
{ id: 'hi', label: 'high-eff', curveMods: { flowScale: 1.25, powerScale: 0.82, flowTilt: 0.1, powerTilt: -0.05 } },
|
||||||
|
{ id: 'mid', label: 'mid-eff', curveMods: { flowScale: 1, powerScale: 1 } },
|
||||||
|
{ id: 'low', label: 'low-eff', curveMods: { flowScale: 0.7, powerScale: 1.35, flowTilt: -0.08, powerTilt: 0.15 } }
|
||||||
|
],
|
||||||
|
pressures: [800, 1200, 1600, 2000],
|
||||||
|
flowTargetsPercent: [0.1, 0.35, 0.7, 1],
|
||||||
|
flowMatchTolerance: 8,
|
||||||
|
priorityList: ['hi', 'mid', 'low']
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
function createGroupConfig(name) {
|
||||||
return {
|
return {
|
||||||
general:{ logging:{enabled:false,logLevel:"warn"}, name:label, id, unit:"m3/h" },
|
general: { logging: { enabled: false, logLevel: 'error' }, name: `machinegroup-${name}` },
|
||||||
functionality:{ softwareType:"machine", role:"rotationaldevicecontroller" },
|
functionality: { softwareType: 'machinegroup', role: 'groupcontroller' },
|
||||||
asset:{ category:"pump", type:"centrifugal", model:"hidrostal-h05k-s03r", supplier:"hydrostal", machineCurve:specs },
|
scaling: { current: 'normalized' },
|
||||||
mode:{
|
mode: { current: 'optimalcontrol' }
|
||||||
current:"auto",
|
};
|
||||||
allowedActions:{
|
}
|
||||||
auto:["execSequence","execMovement","flowMovement","statusCheck"],
|
|
||||||
virtualControl:["execMovement","statusCheck"],
|
function sleep(ms) {
|
||||||
fysicalControl:["statusCheck"]
|
return new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setPressure(pt, value) {
|
||||||
|
const retries = 6;
|
||||||
|
for (let attempt = 0; attempt < retries; attempt += 1) {
|
||||||
|
try {
|
||||||
|
pt.calculateInput(value);
|
||||||
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
const message = error?.message || String(error);
|
||||||
|
if (!message.toLowerCase().includes('coolprop is still warming up')) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
await sleep(50);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error(`Unable to update pressure to ${value} mbar; CoolProp did not initialise in time.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deepClone(obj) {
|
||||||
|
return JSON.parse(JSON.stringify(obj));
|
||||||
|
}
|
||||||
|
|
||||||
|
function distortSeries(series = [], scale = 1, tilt = 0) {
|
||||||
|
if (!Array.isArray(series) || series.length === 0) {
|
||||||
|
return series;
|
||||||
|
}
|
||||||
|
const lastIndex = series.length - 1;
|
||||||
|
return series.map((value, index) => {
|
||||||
|
const gradient = lastIndex === 0 ? 0 : index / lastIndex - 0.5;
|
||||||
|
const distorted = value * scale * (1 + tilt * gradient);
|
||||||
|
return Number(Math.max(distorted, 0).toFixed(6));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createSyntheticCurve(mods = {}) {
|
||||||
|
const { flowScale = 1, powerScale = 1, flowTilt = 0, powerTilt = 0 } = mods;
|
||||||
|
const curve = deepClone(baseCurve);
|
||||||
|
if (curve.nq) {
|
||||||
|
Object.values(curve.nq).forEach(set => {
|
||||||
|
set.y = distortSeries(set.y, flowScale, flowTilt);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (curve.np) {
|
||||||
|
Object.values(curve.np).forEach(set => {
|
||||||
|
set.y = distortSeries(set.y, powerScale, powerTilt);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return curve;
|
||||||
|
}
|
||||||
|
|
||||||
|
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', machineCurve: baseCurve },
|
||||||
|
mode: {
|
||||||
|
current: 'auto',
|
||||||
|
allowedActions: {
|
||||||
|
auto: ['execsequence', 'execmovement', 'flowmovement', 'statuscheck'],
|
||||||
|
virtualControl: ['execmovement', 'statuscheck'],
|
||||||
|
fysicalControl: ['statuscheck']
|
||||||
},
|
},
|
||||||
allowedSources:{
|
allowedSources: {
|
||||||
auto:["parent","GUI"],
|
auto: ['parent', 'GUI'],
|
||||||
virtualControl:["GUI"],
|
virtualControl: ['GUI'],
|
||||||
fysicalControl:["fysical"]
|
fysicalControl: ['fysical']
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
sequences:{
|
sequences: {
|
||||||
startup:["starting","warmingup","operational"],
|
startup: ['starting', 'warmingup', 'operational'],
|
||||||
shutdown:["stopping","coolingdown","idle"],
|
shutdown: ['stopping', 'coolingdown', 'idle'],
|
||||||
emergencystop:["emergencystop","off"],
|
emergencystop: ['emergencystop', 'off'],
|
||||||
boot:["idle","starting","warmingup","operational"]
|
boot: ['idle', 'starting', 'warmingup', 'operational']
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function bootstrapGroup() {
|
async function bootstrapScenarioMachines(scenario) {
|
||||||
const groupCfg = {
|
const mg = new MachineGroup(createGroupConfig(scenario.name));
|
||||||
general:{ logging:{enabled:false,logLevel:"warn"}, name:"testmachinegroup" },
|
|
||||||
functionality:{ softwareType:"machinegroup", role:"groupcontroller" },
|
|
||||||
scaling:{ current:"normalized" },
|
|
||||||
mode:{ current:"optimalcontrol" }
|
|
||||||
};
|
|
||||||
|
|
||||||
const mg = new MachineGroup(groupCfg);
|
|
||||||
const pt = new Measurement(ptConfig);
|
const pt = new Measurement(ptConfig);
|
||||||
|
|
||||||
for (let idx=1; idx<=2; idx++){
|
for (const machineDef of scenario.machines) {
|
||||||
const machine = new Machine(createMachineConfig(String(idx),`machine-${idx}`), stateConfig);
|
const machine = new Machine(createMachineConfig(machineDef.id, machineDef.label), stateConfig);
|
||||||
mg.childRegistrationUtils.registerChild(machine,"downstream");
|
if (machineDef.curveMods) {
|
||||||
machine.childRegistrationUtils.registerChild(pt,"downstream");
|
machine.updateCurve(createSyntheticCurve(machineDef.curveMods));
|
||||||
}
|
}
|
||||||
pt.calculateInput(1000);
|
mg.childRegistrationUtils.registerChild(machine, 'downstream');
|
||||||
await sleep(10);
|
machine.childRegistrationUtils.registerChild(pt, 'downstream');
|
||||||
|
}
|
||||||
|
|
||||||
|
await sleep(25);
|
||||||
return { mg, pt };
|
return { mg, pt };
|
||||||
}
|
}
|
||||||
|
|
||||||
function captureState(mg,label){
|
function captureTotals(mg) {
|
||||||
return {
|
const flow = mg.measurements.type('flow').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
||||||
label,
|
const power = mg.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
||||||
machines: Object.entries(mg.machines).map(([id,machine]) => ({
|
const efficiency = mg.measurements.type('efficiency').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
||||||
id,
|
return { flow, power, efficiency };
|
||||||
state: machine.state.getCurrentState(),
|
|
||||||
position: machine.state.getCurrentPosition(),
|
|
||||||
predictedFlow: machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0,
|
|
||||||
predictedPower: machine.measurements.type("power").variant("predicted").position("upstream").getCurrentValue() || 0
|
|
||||||
})),
|
|
||||||
totals: {
|
|
||||||
flow: mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0,
|
|
||||||
power: mg.measurements.type("power").variant("predicted").position("upstream").getCurrentValue() || 0,
|
|
||||||
efficiency: mg.measurements.type("efficiency").variant("predicted").position("downstream").getCurrentValue() || 0
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function testNormalizedScaling(mg,pt){
|
function computeAbsoluteTargets(dynamicTotals, percentages) {
|
||||||
const label = "Normalized scaling tracks expected flow";
|
const { flow } = dynamicTotals;
|
||||||
try{
|
const min = Number.isFinite(flow.min) ? flow.min : 0;
|
||||||
mg.setScaling("normalized");
|
const max = Number.isFinite(flow.max) ? flow.max : 0;
|
||||||
const dynamic = mg.calcDynamicTotals();
|
const span = Math.max(max - min, 1);
|
||||||
const checkpoints = [0,10,25,50,75,100];
|
return percentages.map(percent => {
|
||||||
for (const demand of checkpoints){
|
const pct = Math.max(0, Math.min(1, percent));
|
||||||
await mg.handleInput("parent", demand);
|
return min + pct * span;
|
||||||
pt.calculateInput(1400);
|
});
|
||||||
await sleep(20);
|
|
||||||
|
|
||||||
const totals = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
|
||||||
const expected = dynamic.flow.min + (demand/100)*(dynamic.flow.max - dynamic.flow.min);
|
|
||||||
if(!approxEqual(totals, expected, 2)){
|
|
||||||
throw new Error(`Flow ${totals.toFixed(2)} outside expectation ${expected.toFixed(2)} @ ${demand}%`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
logPass(label);
|
|
||||||
}catch(err){ logFail(label, err); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function testAbsoluteScaling(mg,pt){
|
async function driveModeToFlow({ mg, pt, mode, pressure, targetFlow, priorityOrder }) {
|
||||||
const label = "Absolute scaling accepts direct flow targets";
|
await setPressure(pt, pressure);
|
||||||
try{
|
await sleep(15);
|
||||||
mg.setScaling("absolute");
|
|
||||||
mg.setMode("optimalcontrol");
|
|
||||||
const absMin = mg.dynamicTotals.flow.min;
|
|
||||||
const absMax = mg.dynamicTotals.flow.max;
|
|
||||||
const demandPoints = [absMin, absMin+20, (absMin+absMax)/2, absMax-20];
|
|
||||||
|
|
||||||
for(const setpoint of demandPoints){
|
|
||||||
await mg.handleInput("parent", setpoint);
|
|
||||||
pt.calculateInput(1400);
|
|
||||||
await sleep(20);
|
|
||||||
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
|
||||||
if(!approxEqual(flow, setpoint, 2)){
|
|
||||||
throw new Error(`Flow ${flow.toFixed(2)} != demand ${setpoint.toFixed(2)}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
logPass(label);
|
|
||||||
}catch(err){ logFail(label, err); }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function testModeTransitions(mg,pt){
|
|
||||||
const label = "Mode transitions keep machines responsive";
|
|
||||||
try{
|
|
||||||
const modes = ["optimalcontrol","prioritycontrol","prioritypercentagecontrol"];
|
|
||||||
mg.setScaling("normalized");
|
|
||||||
for(const mode of modes){
|
|
||||||
mg.setMode(mode);
|
mg.setMode(mode);
|
||||||
await mg.handleInput("parent", 50);
|
mg.setScaling('normalized'); // required for prioritypercentagecontrol, works for others too
|
||||||
pt.calculateInput(1300);
|
|
||||||
await sleep(20);
|
const dynamic = mg.calcDynamicTotals();
|
||||||
const snapshot = captureState(mg, mode);
|
const span = Math.max(dynamic.flow.max - dynamic.flow.min, 1);
|
||||||
const active = snapshot.machines.filter(m => m.state !== "idle");
|
const normalizedTarget = ((targetFlow - dynamic.flow.min) / span) * 100;
|
||||||
if(active.length === 0){
|
|
||||||
throw new Error(`No active machines after switching to ${mode}`);
|
let low = 0;
|
||||||
|
let high = 100;
|
||||||
|
let demand = Math.max(0, Math.min(100, normalizedTarget || 0));
|
||||||
|
let best = { demand, flow: 0, power: 0, efficiency: 0, error: Infinity };
|
||||||
|
|
||||||
|
for (let attempt = 0; attempt < 4; attempt += 1) {
|
||||||
|
await mg.handleInput('parent', demand, Infinity, priorityOrder);
|
||||||
|
await sleep(30);
|
||||||
|
|
||||||
|
const totals = captureTotals(mg);
|
||||||
|
const error = Math.abs(totals.flow - targetFlow);
|
||||||
|
if (error < best.error) {
|
||||||
|
best = {
|
||||||
|
demand,
|
||||||
|
flow: totals.flow,
|
||||||
|
power: totals.power,
|
||||||
|
efficiency: totals.efficiency,
|
||||||
|
error
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (totals.flow > targetFlow) {
|
||||||
|
high = demand;
|
||||||
|
} else {
|
||||||
|
low = demand;
|
||||||
}
|
}
|
||||||
logPass(label);
|
demand = (low + high) / 2;
|
||||||
}catch(err){ logFail(label, err); }
|
}
|
||||||
|
|
||||||
|
return best;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function testRampBehaviour(mg,pt){
|
function formatEfficiencyRows(rows) {
|
||||||
const label = "Ramp up/down keeps monotonic flow";
|
return rows.map(row => {
|
||||||
try{
|
const optimal = row.modes.optimalcontrol;
|
||||||
mg.setMode("optimalcontrol");
|
const priority = row.modes.prioritycontrol;
|
||||||
mg.setScaling("normalized");
|
const percentage = row.modes.prioritypercentagecontrol;
|
||||||
const upDemands = [0,20,40,60,80,100];
|
return {
|
||||||
let lastFlow = 0;
|
pressure: row.pressure,
|
||||||
for(const demand of upDemands){
|
targetFlow: Number(row.targetFlow.toFixed(1)),
|
||||||
await mg.handleInput("parent", demand);
|
[`${MODE_LABELS.optimalcontrol}_Flow`]: Number(optimal.flow.toFixed(1)),
|
||||||
pt.calculateInput(1500);
|
[`${MODE_LABELS.optimalcontrol}_Eff`]: Number(optimal.efficiency.toFixed(3)),
|
||||||
await sleep(15);
|
[`${MODE_LABELS.prioritycontrol}_Flow`]: Number(priority.flow.toFixed(1)),
|
||||||
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
[`${MODE_LABELS.prioritycontrol}_Eff`]: Number(priority.efficiency.toFixed(3)),
|
||||||
if(flow < lastFlow - 1){
|
[`Δ${MODE_LABELS.prioritycontrol}-OPT_Eff`]: Number(
|
||||||
throw new Error(`Flow decreased during ramp up: ${flow.toFixed(2)} < ${lastFlow.toFixed(2)}`);
|
(priority.efficiency - optimal.efficiency).toFixed(3)
|
||||||
}
|
),
|
||||||
lastFlow = flow;
|
[`${MODE_LABELS.prioritypercentagecontrol}_Flow`]: Number(percentage.flow.toFixed(1)),
|
||||||
}
|
[`${MODE_LABELS.prioritypercentagecontrol}_Eff`]: Number(percentage.efficiency.toFixed(3)),
|
||||||
const downDemands = [100,80,60,40,20,0];
|
[`Δ${MODE_LABELS.prioritypercentagecontrol}-OPT_Eff`]: Number(
|
||||||
lastFlow = Infinity;
|
(percentage.efficiency - optimal.efficiency).toFixed(3)
|
||||||
for(const demand of downDemands){
|
)
|
||||||
await mg.handleInput("parent", demand);
|
};
|
||||||
pt.calculateInput(1200);
|
});
|
||||||
await sleep(15);
|
|
||||||
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
|
||||||
if(flow > lastFlow + 1){
|
|
||||||
throw new Error(`Flow increased during ramp down: ${flow.toFixed(2)} > ${lastFlow.toFixed(2)}`);
|
|
||||||
}
|
|
||||||
lastFlow = flow;
|
|
||||||
}
|
|
||||||
logPass(label);
|
|
||||||
}catch(err){ logFail(label, err); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function testPressureAdaptation(mg,pt){
|
function summarizeEfficiency(rows) {
|
||||||
const label = "Pressure changes update predictions";
|
const map = new Map();
|
||||||
try{
|
rows.forEach(row => {
|
||||||
mg.setMode("optimalcontrol");
|
CONTROL_MODES.forEach(mode => {
|
||||||
mg.setScaling("normalized");
|
const key = `${row.scenario}-${mode}`;
|
||||||
const pressures = [800,1200,1600,2000];
|
if (!map.has(key)) {
|
||||||
let previousFlow = null;
|
map.set(key, {
|
||||||
for(const p of pressures){
|
scenario: row.scenario,
|
||||||
pt.calculateInput(p);
|
mode,
|
||||||
await mg.handleInput("parent", 50);
|
samples: 0,
|
||||||
await sleep(20);
|
avgFlowDiff: 0,
|
||||||
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
avgEfficiency: 0
|
||||||
if(previousFlow !== null && Math.abs(flow - previousFlow) < 0.5){
|
|
||||||
throw new Error(`Flow did not react to pressure shift (${previousFlow.toFixed(2)} -> ${flow.toFixed(2)})`);
|
|
||||||
}
|
|
||||||
previousFlow = flow;
|
|
||||||
}
|
|
||||||
logPass(label);
|
|
||||||
}catch(err){ logFail(label, err); }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async function comparePriorityVsOptimal(mg, pt){
|
|
||||||
const label = "Priority vs Optimal efficiency comparison";
|
|
||||||
try{
|
|
||||||
mg.setScaling("normalized");
|
|
||||||
const pressures = [800, 1100, 1400, 1700];
|
|
||||||
const demands = [...Array(21)].map((_, idx) => idx * 5);
|
|
||||||
|
|
||||||
for (const pressure of pressures) {
|
|
||||||
pt.calculateInput(pressure);
|
|
||||||
await sleep(15);
|
|
||||||
|
|
||||||
for (const demand of demands) {
|
|
||||||
mg.setMode("optimalcontrol");
|
|
||||||
await mg.handleInput("parent", demand);
|
|
||||||
pt.calculateInput(pressure);
|
|
||||||
await sleep(20);
|
|
||||||
const optimalTotals = captureState(mg, `optimal-${pressure}-${demand}`).totals;
|
|
||||||
|
|
||||||
mg.setMode("prioritycontrol");
|
|
||||||
await mg.handleInput("parent", demand);
|
|
||||||
pt.calculateInput(pressure);
|
|
||||||
await sleep(20);
|
|
||||||
const priorityTotals = captureState(mg, `priority-${pressure}-${demand}`).totals;
|
|
||||||
|
|
||||||
efficiencyComparisons.push({
|
|
||||||
pressure,
|
|
||||||
demandPercent: demand,
|
|
||||||
optimalFlow: Number(optimalTotals.flow.toFixed(3)),
|
|
||||||
optimalPower: Number(optimalTotals.power.toFixed(3)),
|
|
||||||
optimalEfficiency: Number((optimalTotals.efficiency || 0).toFixed(4)),
|
|
||||||
priorityFlow: Number(priorityTotals.flow.toFixed(3)),
|
|
||||||
priorityPower: Number(priorityTotals.power.toFixed(3)),
|
|
||||||
priorityEfficiency: Number((priorityTotals.efficiency || 0).toFixed(4)),
|
|
||||||
efficiencyDelta: Number(((priorityTotals.efficiency || 0) - (optimalTotals.efficiency || 0)).toFixed(4)),
|
|
||||||
powerDelta: Number((priorityTotals.power - optimalTotals.power).toFixed(3))
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
const bucket = map.get(key);
|
||||||
|
const stats = row.modes[mode];
|
||||||
logPass(label, "efficiencyComparisons array populated");
|
bucket.samples += 1;
|
||||||
} catch (err) {
|
bucket.avgFlowDiff += Math.abs(stats.flow - row.targetFlow);
|
||||||
logFail(label, err);
|
bucket.avgEfficiency += stats.efficiency || 0;
|
||||||
}
|
});
|
||||||
|
});
|
||||||
|
return Array.from(map.values()).map(item => ({
|
||||||
|
scenario: item.scenario,
|
||||||
|
mode: item.mode,
|
||||||
|
samples: item.samples,
|
||||||
|
avgFlowDiff: Number((item.avgFlowDiff / item.samples).toFixed(2)),
|
||||||
|
avgEfficiency: Number((item.avgEfficiency / item.samples).toFixed(3))
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function evaluateScenario(scenario) {
|
||||||
|
console.log(`\nRunning scenario "${scenario.name}": ${scenario.description}`);
|
||||||
|
const { mg, pt } = await bootstrapScenarioMachines(scenario);
|
||||||
|
const priorityOrder =
|
||||||
|
scenario.priorityList && scenario.priorityList.length
|
||||||
|
? scenario.priorityList
|
||||||
|
: scenario.machines.map(machine => machine.id);
|
||||||
|
|
||||||
async function run(){
|
const rows = [];
|
||||||
console.log("🚀 Starting machine-group integration tests...");
|
|
||||||
const { mg, pt } = await bootstrapGroup();
|
|
||||||
|
|
||||||
await testNormalizedScaling(mg, pt);
|
for (const pressure of scenario.pressures) {
|
||||||
await testAbsoluteScaling(mg, pt);
|
await setPressure(pt, pressure);
|
||||||
await testModeTransitions(mg, pt);
|
await sleep(20);
|
||||||
await testRampBehaviour(mg, pt);
|
|
||||||
await testPressureAdaptation(mg, pt);
|
|
||||||
await comparePriorityVsOptimal(mg, pt);
|
|
||||||
|
|
||||||
console.log("\n📋 TEST SUMMARY");
|
const dynamicTotals = mg.calcDynamicTotals();
|
||||||
console.table(testSuite);
|
const targets = computeAbsoluteTargets(dynamicTotals, scenario.flowTargetsPercent || [0, 0.5, 1]);
|
||||||
console.log("\n📊 efficiencyComparisons:");
|
|
||||||
console.dir(efficiencyComparisons, { depth:null });
|
for (let idx = 0; idx < targets.length; idx += 1) {
|
||||||
console.log("✅ All tests completed.");
|
const targetFlow = targets[idx];
|
||||||
|
const row = {
|
||||||
|
scenario: scenario.name,
|
||||||
|
pressure,
|
||||||
|
targetFlow,
|
||||||
|
modes: {}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const mode of CONTROL_MODES) {
|
||||||
|
const stats = await driveModeToFlow({
|
||||||
|
mg,
|
||||||
|
pt,
|
||||||
|
mode,
|
||||||
|
pressure,
|
||||||
|
targetFlow,
|
||||||
|
priorityOrder
|
||||||
|
});
|
||||||
|
row.modes[mode] = stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
rows.push(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Efficiency comparison table for scenario "${scenario.name}":`);
|
||||||
|
console.table(formatEfficiencyRows(rows));
|
||||||
|
|
||||||
|
return { rows };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function run() {
|
||||||
|
const combinedRows = [];
|
||||||
|
|
||||||
|
for (const scenario of scenarios) {
|
||||||
|
const { rows } = await evaluateScenario(scenario);
|
||||||
|
combinedRows.push(...rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\nEfficiency summary by scenario and control mode:');
|
||||||
|
console.table(summarizeEfficiency(combinedRows));
|
||||||
|
|
||||||
|
console.log('\nAll machine group control tests completed successfully.');
|
||||||
}
|
}
|
||||||
|
|
||||||
run().catch(err => {
|
run().catch(err => {
|
||||||
console.error("💥 Test harness crashed:", err);
|
console.error('Machine group control test harness crashed:', err);
|
||||||
|
process.exitCode = 1;
|
||||||
});
|
});
|
||||||
// ...existing code...
|
|
||||||
|
|
||||||
// Run all tests
|
|
||||||
run();
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
const { outputUtils, configManager } = require("generalFunctions");
|
const { outputUtils, configManager, convert } = require("generalFunctions");
|
||||||
const Specific = require("./specificClass");
|
const Specific = require("./specificClass");
|
||||||
|
|
||||||
class nodeClass {
|
class nodeClass {
|
||||||
@@ -37,6 +37,7 @@ class nodeClass {
|
|||||||
_loadConfig(uiConfig, node) {
|
_loadConfig(uiConfig, node) {
|
||||||
const cfgMgr = new configManager();
|
const cfgMgr = new configManager();
|
||||||
this.defaultConfig = cfgMgr.getConfig(this.name);
|
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)
|
// Build config: base sections (no domain-specific config for group controller)
|
||||||
this.config = cfgMgr.buildConfig(this.name, uiConfig, node.id);
|
this.config = cfgMgr.buildConfig(this.name, uiConfig, node.id);
|
||||||
@@ -45,6 +46,24 @@ class nodeClass {
|
|||||||
this._output = new outputUtils();
|
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() {
|
_updateNodeStatus() {
|
||||||
//console.log('Updating node status...');
|
//console.log('Updating node status...');
|
||||||
const mg = this.source;
|
const mg = this.source;
|
||||||
@@ -55,20 +74,20 @@ class nodeClass {
|
|||||||
const totalFlow = mg.measurements
|
const totalFlow = mg.measurements
|
||||||
?.type("flow")
|
?.type("flow")
|
||||||
?.variant("predicted")
|
?.variant("predicted")
|
||||||
?.position("downstream")
|
?.position("atequipment")
|
||||||
?.getCurrentValue() || 0;
|
?.getCurrentValue(mg?.unitPolicy?.output?.flow || 'm3/h') || 0;
|
||||||
|
|
||||||
const totalPower = mg.measurements
|
const totalPower = mg.measurements
|
||||||
?.type("power")
|
?.type("power")
|
||||||
?.variant("predicted")
|
?.variant("predicted")
|
||||||
?.position("atEquipment")
|
?.position("atEquipment")
|
||||||
?.getCurrentValue() || 0;
|
?.getCurrentValue(mg?.unitPolicy?.output?.power || 'kW') || 0;
|
||||||
|
|
||||||
// Calculate total capacity based on available machines with safety checks
|
// Calculate total capacity based on available machines with safety checks
|
||||||
const availableMachines = Object.values(mg.machines || {}).filter((machine) => {
|
const availableMachines = Object.values(mg.machines || {}).filter((machine) => {
|
||||||
// Safety check: ensure machine and machine.state exist
|
// Safety check: ensure machine and machine.state exist
|
||||||
if (!machine || !machine.state || typeof machine.state.getCurrentState !== 'function') {
|
if (!machine || !machine.state || typeof machine.state.getCurrentState !== 'function') {
|
||||||
mg.logger.warn(`Machine missing or invalid: ${machine?.config?.general?.id || 'unknown'}`);
|
mg.logger?.warn(`Machine missing or invalid: ${machine?.config?.general?.id || 'unknown'}`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,8 +188,8 @@ class nodeClass {
|
|||||||
*/
|
*/
|
||||||
_tick() {
|
_tick() {
|
||||||
const raw = this.source.getOutput();
|
const raw = this.source.getOutput();
|
||||||
const processMsg = this._output.formatMsg(raw, this.config, "process");
|
const processMsg = this._output.formatMsg(raw, this.source.config, "process");
|
||||||
const influxMsg = this._output.formatMsg(raw, this.config, "influxdb");
|
const influxMsg = this._output.formatMsg(raw, this.source.config, "influxdb");
|
||||||
|
|
||||||
// Send only updated outputs on ports 0 & 1
|
// Send only updated outputs on ports 0 & 1
|
||||||
this.node.send([processMsg, influxMsg]);
|
this.node.send([processMsg, influxMsg]);
|
||||||
@@ -185,17 +204,19 @@ class nodeClass {
|
|||||||
async (msg, send, done) => {
|
async (msg, send, done) => {
|
||||||
const mg = this.source;
|
const mg = this.source;
|
||||||
const RED = this.RED;
|
const RED = this.RED;
|
||||||
|
try {
|
||||||
switch (msg.topic) {
|
switch (msg.topic) {
|
||||||
case "registerChild": {
|
case "registerChild": {
|
||||||
const childId = msg.payload;
|
const childId = msg.payload;
|
||||||
const childObj = RED.nodes.getNode(childId);
|
const childObj = RED.nodes.getNode(childId);
|
||||||
|
if (!childObj || !childObj.source) {
|
||||||
|
mg.logger.warn(`registerChild skipped: missing child/source for id=${childId}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
mg.logger.debug(`Registering child: ${childId}, found: ${!!childObj}, source: ${!!childObj?.source}`);
|
mg.logger.debug(`Registering child: ${childId}, found: ${!!childObj}, source: ${!!childObj?.source}`);
|
||||||
|
|
||||||
mg.childRegistrationUtils.registerChild(
|
mg.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
|
||||||
childObj.source,
|
|
||||||
msg.positionVsParent
|
|
||||||
);
|
|
||||||
|
|
||||||
mg.logger.debug(`Total machines after registration: ${Object.keys(mg.machines || {}).length}`);
|
mg.logger.debug(`Total machines after registration: ${Object.keys(mg.machines || {}).length}`);
|
||||||
break;
|
break;
|
||||||
@@ -210,35 +231,35 @@ class nodeClass {
|
|||||||
case "setScaling": {
|
case "setScaling": {
|
||||||
const scaling = msg.payload;
|
const scaling = msg.payload;
|
||||||
mg.setScaling(scaling);
|
mg.setScaling(scaling);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case "Qd": {
|
case "Qd": {
|
||||||
const Qd = parseFloat(msg.payload);
|
const Qd = parseFloat(msg.payload);
|
||||||
const sourceQd = "parent";
|
const sourceQd = "parent";
|
||||||
|
|
||||||
if (isNaN(Qd)) {
|
if (isNaN(Qd)) {
|
||||||
return mg.logger.error(`Invalid demand value: ${Qd}`);
|
mg.logger.error(`Invalid demand value: ${msg.payload}`);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await mg.handleInput(sourceQd, Qd);
|
await mg.handleInput(sourceQd, Qd);
|
||||||
msg.topic = mg.config.general.name;
|
msg.topic = mg.config.general.name;
|
||||||
msg.payload = "done";
|
msg.payload = "done";
|
||||||
send(msg);
|
send(msg);
|
||||||
} catch (e) {
|
} catch (error) {
|
||||||
mg.logger.error(`Demand handling failed: ${e.message}`);
|
mg.logger.error(`Failed to process Qd: ${error.message}`);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
// Handle unknown topics if needed
|
|
||||||
mg.logger.warn(`Unknown topic: ${msg.topic}`);
|
mg.logger.warn(`Unknown topic: ${msg.topic}`);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
done();
|
} catch (error) {
|
||||||
|
mg.logger.error(`Input handler failure: ${error.message}`);
|
||||||
|
}
|
||||||
|
if (typeof done === 'function') done();
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -250,7 +271,7 @@ class nodeClass {
|
|||||||
this.node.on("close", (done) => {
|
this.node.on("close", (done) => {
|
||||||
clearInterval(this._tickInterval);
|
clearInterval(this._tickInterval);
|
||||||
clearInterval(this._statusInterval);
|
clearInterval(this._statusInterval);
|
||||||
done();
|
if (typeof done === 'function') done();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,25 @@
|
|||||||
//load local dependencies
|
//load local dependencies
|
||||||
const EventEmitter = require("events");
|
const EventEmitter = require("events");
|
||||||
const {logger,configUtils,configManager, MeasurementContainer, interpolation , childRegistrationUtils, POSITIONS} = require('generalFunctions');
|
const {logger,configUtils,configManager, MeasurementContainer, interpolation , childRegistrationUtils, convert, POSITIONS} = require('generalFunctions');
|
||||||
|
|
||||||
|
const CANONICAL_UNITS = Object.freeze({
|
||||||
|
pressure: 'Pa',
|
||||||
|
flow: 'm3/s',
|
||||||
|
power: 'W',
|
||||||
|
temperature: 'K',
|
||||||
|
});
|
||||||
|
|
||||||
|
const DEFAULT_IO_UNITS = Object.freeze({
|
||||||
|
pressure: 'mbar',
|
||||||
|
flow: 'm3/h',
|
||||||
|
power: 'kW',
|
||||||
|
temperature: 'C',
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Machine group controller domain model.
|
||||||
|
* Aggregates multiple rotating machines and coordinates group-level optimization/control.
|
||||||
|
*/
|
||||||
class MachineGroup {
|
class MachineGroup {
|
||||||
constructor(machineGroupConfig = {}) {
|
constructor(machineGroupConfig = {}) {
|
||||||
|
|
||||||
@@ -10,12 +28,39 @@ class MachineGroup {
|
|||||||
this.defaultConfig = this.configManager.getConfig('machineGroupControl'); // Load default config for rotating machine ( use software type name ? )
|
this.defaultConfig = this.configManager.getConfig('machineGroupControl'); // Load default config for rotating machine ( use software type name ? )
|
||||||
this.configUtils = new configUtils(this.defaultConfig);// this will handle the config endpoints so we can load them dynamically
|
this.configUtils = new configUtils(this.defaultConfig);// this will handle the config endpoints so we can load them dynamically
|
||||||
this.config = this.configUtils.initConfig(machineGroupConfig); // verify and set the config for the machine group
|
this.config = this.configUtils.initConfig(machineGroupConfig); // verify and set the config for the machine group
|
||||||
|
this.unitPolicy = this._buildUnitPolicy(this.config);
|
||||||
|
this.config = this.configUtils.updateConfig(this.config, {
|
||||||
|
general: {
|
||||||
|
unit: this.unitPolicy.output.flow,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Init after config is set
|
// Init after config is set
|
||||||
this.logger = new logger(this.config.general.logging.enabled,this.config.general.logging.logLevel, this.config.general.name);
|
this.logger = new logger(this.config.general.logging.enabled,this.config.general.logging.logLevel, this.config.general.name);
|
||||||
|
|
||||||
// Initialize measurements
|
// Initialize measurements
|
||||||
this.measurements = new MeasurementContainer();
|
this.measurements = new MeasurementContainer({
|
||||||
|
autoConvert: true,
|
||||||
|
windowSize: 50,
|
||||||
|
defaultUnits: {
|
||||||
|
pressure: this.unitPolicy.output.pressure,
|
||||||
|
flow: this.unitPolicy.output.flow,
|
||||||
|
power: this.unitPolicy.output.power,
|
||||||
|
temperature: this.unitPolicy.output.temperature
|
||||||
|
},
|
||||||
|
preferredUnits: {
|
||||||
|
pressure: this.unitPolicy.output.pressure,
|
||||||
|
flow: this.unitPolicy.output.flow,
|
||||||
|
power: this.unitPolicy.output.power,
|
||||||
|
temperature: this.unitPolicy.output.temperature
|
||||||
|
},
|
||||||
|
canonicalUnits: this.unitPolicy.canonical,
|
||||||
|
storeCanonical: true,
|
||||||
|
strictUnitValidation: true,
|
||||||
|
throwOnInvalidUnit: true,
|
||||||
|
requireUnitForTypes: ['pressure', 'flow', 'power', 'temperature']
|
||||||
|
});
|
||||||
|
|
||||||
this.interpolation = new interpolation();
|
this.interpolation = new interpolation();
|
||||||
|
|
||||||
// Machines and child data
|
// Machines and child data
|
||||||
@@ -40,6 +85,9 @@ class MachineGroup {
|
|||||||
registerChild(child,softwareType) {
|
registerChild(child,softwareType) {
|
||||||
this.logger.debug('Setting up childs specific for this class');
|
this.logger.debug('Setting up childs specific for this class');
|
||||||
|
|
||||||
|
// Prefer functionality-scoped position metadata; keep general fallback for legacy nodes.
|
||||||
|
const position = child.config?.functionality?.positionVsParent || child.config?.general?.positionVsParent;
|
||||||
|
|
||||||
if(softwareType == "machine"){
|
if(softwareType == "machine"){
|
||||||
// Check if the machine is already registered
|
// Check if the machine is already registered
|
||||||
this.machines[child.config.general.id] === undefined ? this.machines[child.config.general.id] = child : this.logger.warn(`Machine ${child.config.general.id} is already registered.`);
|
this.machines[child.config.general.id] === undefined ? this.machines[child.config.general.id] = child : this.logger.warn(`Machine ${child.config.general.id} is already registered.`);
|
||||||
@@ -133,15 +181,23 @@ class MachineGroup {
|
|||||||
this.logger.debug(`\n --------- Calculating dynamic totals for ${Object.keys(this.machines).length} machines. @ current pressure settings : ----------`);
|
this.logger.debug(`\n --------- Calculating dynamic totals for ${Object.keys(this.machines).length} machines. @ current pressure settings : ----------`);
|
||||||
|
|
||||||
Object.values(this.machines).forEach(machine => {
|
Object.values(this.machines).forEach(machine => {
|
||||||
|
//skip machines without valid curve
|
||||||
|
if(!machine.hasCurve){
|
||||||
|
this.logger.error(`Machine ${machine.config.general.id} does not have a valid curve. Skipping in dynamic totals calculation.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.logger.debug(`Processing machine with id: ${machine.config.general.id}`);
|
this.logger.debug(`Processing machine with id: ${machine.config.general.id}`);
|
||||||
this.logger.debug(`Current pressure settings: ${JSON.stringify(machine.predictFlow.currentF)}`);
|
this.logger.debug(`Current pressure settings: ${JSON.stringify(machine.predictFlow.currentF)}`);
|
||||||
|
|
||||||
//fetch min flow ever seen over all machines
|
//fetch min flow ever seen over all machines
|
||||||
const minFlow = machine.predictFlow.currentFxyYMin;
|
const minFlow = machine.predictFlow.currentFxyYMin;
|
||||||
const maxFlow = machine.predictFlow.currentFxyYMax;
|
const maxFlow = machine.predictFlow.currentFxyYMax;
|
||||||
const minPower = machine.predictPower.currentFxyYMin;
|
const minPower = machine.predictPower.currentFxyYMin;
|
||||||
const maxPower = machine.predictPower.currentFxyYMax;
|
const maxPower = machine.predictPower.currentFxyYMax;
|
||||||
const actFlow = machine.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
|
||||||
const actPower = machine.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
const actFlow = this._readChildMeasurement(machine, "flow", "predicted", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow) || 0;
|
||||||
|
const actPower = this._readChildMeasurement(machine, "power", "predicted", POSITIONS.AT_EQUIPMENT, this.unitPolicy.canonical.power) || 0;
|
||||||
|
|
||||||
this.logger.debug(`Machine ${machine.config.general.id} - Min Flow: ${minFlow}, Max Flow: ${maxFlow}, Min Power: ${minPower}, Max Power: ${maxPower}, NCog: ${machine.NCog}`);
|
this.logger.debug(`Machine ${machine.config.general.id} - Min Flow: ${minFlow}, Max Flow: ${maxFlow}, Min Power: ${minPower}, Max Power: ${maxPower}, NCog: ${machine.NCog}`);
|
||||||
|
|
||||||
@@ -190,13 +246,13 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handlePressureChange() {
|
handlePressureChange() {
|
||||||
this.logger.info("---------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>Pressure change detected.");
|
this.logger.debug("Pressure change detected.");
|
||||||
// Recalculate totals
|
// Recalculate totals
|
||||||
const { flow, power } = this.calcDynamicTotals();
|
const { flow, power } = this.calcDynamicTotals();
|
||||||
|
|
||||||
this.logger.debug(`Dynamic Totals after pressure change - Flow: Min ${flow.min}, Max ${flow.max}, Act ${flow.act} | Power: Min ${power.min}, Max ${power.max}, Act ${power.act}`);
|
this.logger.debug(`Dynamic Totals after pressure change - Flow: Min ${flow.min}, Max ${flow.max}, Act ${flow.act} | Power: Min ${power.min}, Max ${power.max}, Act ${power.act}`);
|
||||||
this.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).value(flow.act);
|
this._writeMeasurement("flow", "predicted", POSITIONS.AT_EQUIPMENT, flow.act, this.unitPolicy.canonical.flow);
|
||||||
this.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(power.act);
|
this._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, power.act, this.unitPolicy.canonical.power);
|
||||||
|
|
||||||
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
|
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
|
||||||
const efficiency = this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
const efficiency = this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
||||||
@@ -209,7 +265,7 @@ class MachineGroup {
|
|||||||
|
|
||||||
calcRelativeDistanceFromPeak(currentEfficiency,maxEfficiency,minEfficiency){
|
calcRelativeDistanceFromPeak(currentEfficiency,maxEfficiency,minEfficiency){
|
||||||
let distance = 1;
|
let distance = 1;
|
||||||
if(currentEfficiency != null){
|
if(currentEfficiency != null && maxEfficiency !== minEfficiency){
|
||||||
distance = this.interpolation.interpolate_lin_single_point(currentEfficiency,maxEfficiency, minEfficiency, 0, 1);
|
distance = this.interpolation.interpolate_lin_single_point(currentEfficiency,maxEfficiency, minEfficiency, 0, 1);
|
||||||
}
|
}
|
||||||
return distance;
|
return distance;
|
||||||
@@ -235,11 +291,13 @@ class MachineGroup {
|
|||||||
//add special cases
|
//add special cases
|
||||||
if( state === "operational" && ( mode == "virtualControl" || mode === "fysicalControl") ){
|
if( state === "operational" && ( mode == "virtualControl" || mode === "fysicalControl") ){
|
||||||
let flow = 0;
|
let flow = 0;
|
||||||
if(machine.measurements.type("flow").variant("measured").position(POSITIONS.DOWNSTREAM).getCurrentValue()){
|
const measuredFlow = this._readChildMeasurement(machine, "flow", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow);
|
||||||
flow = machine.measurements.type("flow").variant("measured").position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
const predictedFlow = this._readChildMeasurement(machine, "flow", "predicted", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow);
|
||||||
|
if (Number.isFinite(measuredFlow) && measuredFlow !== 0) {
|
||||||
|
flow = measuredFlow;
|
||||||
}
|
}
|
||||||
else if(machine.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).getCurrentValue()){
|
else if (Number.isFinite(predictedFlow) && predictedFlow !== 0) {
|
||||||
flow = machine.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
flow = predictedFlow;
|
||||||
}
|
}
|
||||||
else{
|
else{
|
||||||
this.logger.error("Dont perform calculation at all seeing that there is a machine working but we dont know the flow its producing");
|
this.logger.error("Dont perform calculation at all seeing that there is a machine working but we dont know the flow its producing");
|
||||||
@@ -264,7 +322,7 @@ class MachineGroup {
|
|||||||
Object.keys(machines).forEach(machineId => {
|
Object.keys(machines).forEach(machineId => {
|
||||||
|
|
||||||
const state = machines[machineId].state.getCurrentState();
|
const state = machines[machineId].state.getCurrentState();
|
||||||
const validActionForMode = machines[machineId].isValidActionForMode("execSequence", "auto");
|
const validActionForMode = machines[machineId].isValidActionForMode("execsequence", "auto");
|
||||||
|
|
||||||
|
|
||||||
// Reasons why a machine is not valid for the combination
|
// Reasons why a machine is not valid for the combination
|
||||||
@@ -313,42 +371,71 @@ class MachineGroup {
|
|||||||
|
|
||||||
calcBestCombination(combinations, Qd) {
|
calcBestCombination(combinations, Qd) {
|
||||||
let bestCombination = null;
|
let bestCombination = null;
|
||||||
|
|
||||||
//keep track of totals
|
|
||||||
let bestPower = Infinity;
|
let bestPower = Infinity;
|
||||||
let bestFlow = 0;
|
let bestFlow = 0;
|
||||||
let bestCog = 0;
|
let bestCog = 0;
|
||||||
|
|
||||||
combinations.forEach(combination => {
|
combinations.forEach(combination => {
|
||||||
|
let flowDistribution = [];
|
||||||
let flowDistribution = []; // Stores the flow distribution for the best combination
|
|
||||||
let totalCoG = 0;
|
let totalCoG = 0;
|
||||||
let totalPower = 0;
|
let totalPower = 0;
|
||||||
let totalFlow = 0;
|
|
||||||
|
|
||||||
// Calculate the total CoG for the current combination
|
// Sum normalized CoG for the combination
|
||||||
combination.forEach(machineId => { totalCoG += ( Math.round(this.machines[machineId].NCog * 100 ) /100 ) ; });
|
combination.forEach(machineId => {
|
||||||
|
totalCoG += Math.round((this.machines[machineId].NCog || 0) * 100) / 100;
|
||||||
|
});
|
||||||
|
|
||||||
// Calculate the total power for the current combination
|
// Initial CoG-based distribution
|
||||||
combination.forEach(machineId => {
|
combination.forEach(machineId => {
|
||||||
let flow = 0;
|
let flow = 0;
|
||||||
|
|
||||||
// Prevent division by zero
|
|
||||||
if (totalCoG === 0) {
|
if (totalCoG === 0) {
|
||||||
// Distribute flow equally among all pumps
|
|
||||||
flow = Qd / combination.length;
|
flow = Qd / combination.length;
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
// Normal CoG-based distribution
|
flow = ((this.machines[machineId].NCog || 0) / totalCoG) * Qd;
|
||||||
flow = (this.machines[machineId].NCog / totalCoG) * Qd ;
|
|
||||||
this.logger.debug(`Machine Normalized CoG-based distribution ${machineId} flow: ${flow}`);
|
this.logger.debug(`Machine Normalized CoG-based distribution ${machineId} flow: ${flow}`);
|
||||||
}
|
}
|
||||||
totalFlow += flow;
|
|
||||||
totalPower += this.machines[machineId].inputFlowCalcPower(flow);
|
flowDistribution.push({ machineId, flow });
|
||||||
flowDistribution.push({ machineId: machineId,flow: flow });
|
});
|
||||||
|
|
||||||
|
// Clamp to min/max and spill leftover once
|
||||||
|
const clamped = flowDistribution.map(entry => {
|
||||||
|
const machine = this.machines[entry.machineId];
|
||||||
|
const min = machine.predictFlow.currentFxyYMin;
|
||||||
|
const max = machine.predictFlow.currentFxyYMax;
|
||||||
|
const clampedFlow = Math.min(max, Math.max(min, entry.flow));
|
||||||
|
return { ...entry, flow: clampedFlow, min, max, desired: entry.flow };
|
||||||
|
});
|
||||||
|
|
||||||
|
let remainder = Qd - clamped.reduce((sum, entry) => sum + entry.flow, 0);
|
||||||
|
|
||||||
|
if (Math.abs(remainder) > 1e-6) {
|
||||||
|
const adjustable = clamped.filter(entry =>
|
||||||
|
remainder > 0 ? entry.flow < entry.max : entry.flow > entry.min
|
||||||
|
);
|
||||||
|
const weightSum = adjustable.reduce((sum, entry) => sum + entry.desired, 0) || adjustable.length;
|
||||||
|
|
||||||
|
adjustable.forEach(entry => {
|
||||||
|
const weight = entry.desired / weightSum || 1 / adjustable.length;
|
||||||
|
const delta = remainder * weight;
|
||||||
|
const next = remainder > 0
|
||||||
|
? Math.min(entry.max, entry.flow + delta)
|
||||||
|
: Math.max(entry.min, entry.flow + delta);
|
||||||
|
|
||||||
|
remainder -= (next - entry.flow);
|
||||||
|
entry.flow = next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
flowDistribution = clamped;
|
||||||
|
|
||||||
|
let totalFlow = 0;
|
||||||
|
flowDistribution.forEach(({ machineId, flow }) => {
|
||||||
|
totalFlow += flow;
|
||||||
|
totalPower += this.machines[machineId].inputFlowCalcPower(flow);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Update the best combination if the current one is better
|
|
||||||
if (totalPower < bestPower) {
|
if (totalPower < bestPower) {
|
||||||
this.logger.debug(`New best combination found: ${totalPower} < ${bestPower}`);
|
this.logger.debug(`New best combination found: ${totalPower} < ${bestPower}`);
|
||||||
this.logger.debug(`combination ${JSON.stringify(flowDistribution)}`);
|
this.logger.debug(`combination ${JSON.stringify(flowDistribution)}`);
|
||||||
@@ -362,6 +449,203 @@ class MachineGroup {
|
|||||||
return { bestCombination, bestPower, bestFlow, bestCog };
|
return { bestCombination, bestPower, bestFlow, bestCog };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Estimate the local dP/dQ slopes around the BEP for the provided machine.
|
||||||
|
estimateSlopesAtBEP(machine, Q_BEP, delta = 1.0) {
|
||||||
|
const fallback = {
|
||||||
|
slopeLeft: 0,
|
||||||
|
slopeRight: 0,
|
||||||
|
alpha: 1,
|
||||||
|
Q_BEP: Q_BEP || 0,
|
||||||
|
P_BEP: 0
|
||||||
|
};
|
||||||
|
|
||||||
|
const minFlow = machine.predictFlow.currentFxyYMin;
|
||||||
|
const maxFlow = machine.predictFlow.currentFxyYMax;
|
||||||
|
const span = Math.max(0, maxFlow - minFlow);
|
||||||
|
const normalizedCog = Math.max(0, Math.min(1, machine.NCog || 0));
|
||||||
|
const targetBEP = Q_BEP ?? (minFlow + span * normalizedCog);
|
||||||
|
const clampFlow = (flow) => Math.min(maxFlow, Math.max(minFlow, flow)); // ensure within bounds using small helper function
|
||||||
|
const center = clampFlow(targetBEP);
|
||||||
|
const deltaSafe = Math.max(delta, 0.01);
|
||||||
|
const leftFlow = clampFlow(center - deltaSafe);
|
||||||
|
const rightFlow = clampFlow(center + deltaSafe);
|
||||||
|
const powerAt = (flow) => machine.inputFlowCalcPower(flow); // helper to get power at a given flow
|
||||||
|
const P_center = powerAt(center);
|
||||||
|
const P_left = powerAt(leftFlow);
|
||||||
|
const P_right = powerAt(rightFlow);
|
||||||
|
const slopeLeft = (P_center - P_left) / Math.max(1e-6, center - leftFlow);
|
||||||
|
const slopeRight = (P_right - P_center) / Math.max(1e-6, rightFlow - center);
|
||||||
|
const alpha = Math.max(1e-6, (Math.abs(slopeLeft) + Math.abs(slopeRight)) / 2);
|
||||||
|
|
||||||
|
return {
|
||||||
|
slopeLeft,
|
||||||
|
slopeRight,
|
||||||
|
alpha,
|
||||||
|
Q_BEP: center,
|
||||||
|
P_BEP: P_center
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//Redistribute remaining demand using slope-based weights so flatter curves attract more flow.
|
||||||
|
redistributeFlowBySlope(pumpInfos, flowDistribution, delta, directional = true) {
|
||||||
|
const tolerance = 1e-3; // Small tolerance to avoid infinite loops
|
||||||
|
let remaining = delta; // Remaining flow to distribute
|
||||||
|
const entryMap = new Map(flowDistribution.map(entry => [entry.machineId, entry])); // Map for quick access
|
||||||
|
|
||||||
|
// Loop until remaining flow is within tolerance
|
||||||
|
while (Math.abs(remaining) > tolerance) {
|
||||||
|
const increasing = remaining > 0; // Determine if we are increasing or decreasing flow
|
||||||
|
// Build candidates with capacity and weight
|
||||||
|
const candidates = pumpInfos.map(info => {
|
||||||
|
const entry = entryMap.get(info.id);
|
||||||
|
if (!entry) { return null; }
|
||||||
|
const capacity = increasing ? info.maxFlow - entry.flow : entry.flow - info.minFlow; // Calculate available capacity based on direction
|
||||||
|
if (capacity <= tolerance) { return null; }
|
||||||
|
|
||||||
|
const slope = increasing
|
||||||
|
? (directional ? info.slopes.slopeRight : info.slopes.alpha)
|
||||||
|
: (directional ? info.slopes.slopeLeft : info.slopes.alpha);
|
||||||
|
|
||||||
|
const weight = 1 / Math.max(1e-6, Math.abs(slope) || info.slopes.alpha || 1);
|
||||||
|
return { entry, capacity, weight };
|
||||||
|
}).filter(Boolean);
|
||||||
|
|
||||||
|
if (!candidates.length) { break; } // No candidates available, exit loop
|
||||||
|
|
||||||
|
const weightSum = candidates.reduce((sum, candidate) => sum + candidate.weight * candidate.capacity, 0); // weighted sum of capacities
|
||||||
|
if (weightSum <= 0) { break; } // Avoid division by zero
|
||||||
|
|
||||||
|
let progress = 0;
|
||||||
|
// Distribute remaining flow among candidates based on their weights and capacities
|
||||||
|
candidates.forEach(candidate => {
|
||||||
|
let share = (candidate.weight * candidate.capacity / weightSum) * Math.abs(remaining);
|
||||||
|
share = Math.min(share, candidate.capacity); // Ensure we don't exceed capacity
|
||||||
|
if (share <= 0) { return; } // Skip if no share to allocate
|
||||||
|
if (increasing) {
|
||||||
|
candidate.entry.flow += share;
|
||||||
|
} else {
|
||||||
|
candidate.entry.flow -= share;
|
||||||
|
}
|
||||||
|
progress += share; // Track total progress made in this iteration
|
||||||
|
});
|
||||||
|
|
||||||
|
if (progress <= tolerance) { break; }
|
||||||
|
remaining += increasing ? -progress : progress; // Update remaining flow to distribute
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BEP-gravitation based combination finder that biases allocation around each pump's BEP.
|
||||||
|
calcBestCombinationBEPGravitation(combinations, Qd, method = "BEP-Gravitation-Directional") {
|
||||||
|
let bestCombination = null;
|
||||||
|
let bestPower = Infinity;
|
||||||
|
let bestFlow = 0;
|
||||||
|
let bestCog = 0;
|
||||||
|
let bestDeviation = Infinity;
|
||||||
|
const directional = method === "BEP-Gravitation-Directional";
|
||||||
|
|
||||||
|
combinations.forEach(combination => {
|
||||||
|
const pumpInfos = combination.map(machineId => {
|
||||||
|
const machine = this.machines[machineId];
|
||||||
|
const minFlow = machine.predictFlow.currentFxyYMin;
|
||||||
|
const maxFlow = machine.predictFlow.currentFxyYMax;
|
||||||
|
const span = Math.max(0, maxFlow - minFlow);
|
||||||
|
const NCog = Math.max(0, Math.min(1, machine.NCog || 0));
|
||||||
|
const estimatedBEP = minFlow + span * NCog; // Estimated BEP flow based on current curve
|
||||||
|
const slopes = this.estimateSlopesAtBEP(machine, estimatedBEP);
|
||||||
|
return {
|
||||||
|
id: machineId,
|
||||||
|
machine,
|
||||||
|
minFlow,
|
||||||
|
maxFlow,
|
||||||
|
NCog,
|
||||||
|
Q_BEP: slopes.Q_BEP,
|
||||||
|
slopes
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Skip if no pumps in combination
|
||||||
|
if (pumpInfos.length === 0) { return; }
|
||||||
|
|
||||||
|
// Start at BEP flows
|
||||||
|
const flowDistribution = pumpInfos.map(info => ({
|
||||||
|
machineId: info.id,
|
||||||
|
flow: Math.min(info.maxFlow, Math.max(info.minFlow, info.Q_BEP))
|
||||||
|
}));
|
||||||
|
|
||||||
|
let totalFlow = flowDistribution.reduce((sum, entry) => sum + entry.flow, 0); // Initial total flow
|
||||||
|
const delta = Qd - totalFlow; // Difference to target demand
|
||||||
|
if (Math.abs(delta) > 1e-6) {
|
||||||
|
this.redistributeFlowBySlope(pumpInfos, flowDistribution, delta, directional);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clamp and compute initial power
|
||||||
|
flowDistribution.forEach(entry => {
|
||||||
|
const info = pumpInfos.find(info => info.id === entry.machineId);
|
||||||
|
entry.flow = Math.min(info.maxFlow, Math.max(info.minFlow, entry.flow));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Marginal-cost refinement: shift flow from most expensive to cheapest
|
||||||
|
// pump using actual power evaluations. Converges regardless of curve convexity.
|
||||||
|
const mcDelta = Math.max(1e-6, (Qd / pumpInfos.length) * 0.005);
|
||||||
|
for (let refineIter = 0; refineIter < 50; refineIter++) {
|
||||||
|
const mcEntries = flowDistribution.map(entry => {
|
||||||
|
const info = pumpInfos.find(i => i.id === entry.machineId);
|
||||||
|
const pNow = info.machine.inputFlowCalcPower(entry.flow);
|
||||||
|
const pUp = info.machine.inputFlowCalcPower(Math.min(info.maxFlow, entry.flow + mcDelta));
|
||||||
|
return { entry, info, mc: (pUp - pNow) / mcDelta };
|
||||||
|
});
|
||||||
|
let expensive = null, cheap = null;
|
||||||
|
for (const e of mcEntries) {
|
||||||
|
if (e.entry.flow > e.info.minFlow + mcDelta) { if (!expensive || e.mc > expensive.mc) expensive = e; }
|
||||||
|
if (e.entry.flow < e.info.maxFlow - mcDelta) { if (!cheap || e.mc < cheap.mc) cheap = e; }
|
||||||
|
}
|
||||||
|
if (!expensive || !cheap || expensive === cheap) break;
|
||||||
|
if (expensive.mc - cheap.mc < expensive.mc * 0.001) break;
|
||||||
|
const before = expensive.info.machine.inputFlowCalcPower(expensive.entry.flow) + cheap.info.machine.inputFlowCalcPower(cheap.entry.flow);
|
||||||
|
const after = expensive.info.machine.inputFlowCalcPower(expensive.entry.flow - mcDelta) + cheap.info.machine.inputFlowCalcPower(cheap.entry.flow + mcDelta);
|
||||||
|
if (after < before) { expensive.entry.flow -= mcDelta; cheap.entry.flow += mcDelta; } else { break; }
|
||||||
|
}
|
||||||
|
|
||||||
|
let totalPower = 0;
|
||||||
|
totalFlow = 0;
|
||||||
|
flowDistribution.forEach(entry => {
|
||||||
|
totalFlow += entry.flow;
|
||||||
|
const info = pumpInfos.find(i => i.id === entry.machineId);
|
||||||
|
totalPower += info.machine.inputFlowCalcPower(entry.flow);
|
||||||
|
});
|
||||||
|
|
||||||
|
const totalCog = pumpInfos.reduce((sum, info) => sum + info.NCog, 0);
|
||||||
|
const deviation = pumpInfos.reduce((sum, info) => {
|
||||||
|
const entry = flowDistribution.find(item => item.machineId === info.id);
|
||||||
|
const deltaFlow = entry ? (entry.flow - info.Q_BEP) : 0;
|
||||||
|
return sum + (deltaFlow * deltaFlow) * (info.slopes.alpha || 1);
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
const shouldUpdate = totalPower < bestPower ||
|
||||||
|
(totalPower === bestPower && deviation < bestDeviation);
|
||||||
|
|
||||||
|
if (shouldUpdate) {
|
||||||
|
bestCombination = flowDistribution.map(entry => ({ ...entry }));
|
||||||
|
bestPower = totalPower;
|
||||||
|
bestFlow = totalFlow;
|
||||||
|
bestCog = totalCog;
|
||||||
|
bestDeviation = deviation;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
bestCombination,
|
||||||
|
bestPower,
|
||||||
|
bestFlow,
|
||||||
|
bestCog,
|
||||||
|
bestDeviation,
|
||||||
|
method
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// -------- Mode and Input Management -------- //
|
// -------- Mode and Input Management -------- //
|
||||||
isValidActionForMode(action, mode) {
|
isValidActionForMode(action, mode) {
|
||||||
const allowedActionsSet = this.config.mode.allowedActions[mode] || [];
|
const allowedActionsSet = this.config.mode.allowedActions[mode] || [];
|
||||||
@@ -387,12 +671,17 @@ class MachineGroup {
|
|||||||
async optimalControl(Qd, powerCap = Infinity) {
|
async optimalControl(Qd, powerCap = Infinity) {
|
||||||
|
|
||||||
try{
|
try{
|
||||||
|
if (Object.keys(this.machines).length === 0) {
|
||||||
|
this.logger.warn("No machines registered. Cannot execute optimal control.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
//we need to force the pressures of all machines to be equal to the highest pressure measured in the group
|
//we need to force the pressures of all machines to be equal to the highest pressure measured in the group
|
||||||
// this is to ensure a correct evaluation of the flow and power consumption
|
// this is to ensure a correct evaluation of the flow and power consumption
|
||||||
const pressures = Object.entries(this.machines).map(([_machineId, machine]) => {
|
const pressures = Object.entries(this.machines).map(([_machineId, machine]) => {
|
||||||
return {
|
return {
|
||||||
downstream: machine.measurements.type("pressure").variant("measured").position(POSITIONS.DOWNSTREAM).getCurrentValue(),
|
downstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.pressure) || 0,
|
||||||
upstream: machine.measurements.type("pressure").variant("measured").position(POSITIONS.UPSTREAM).getCurrentValue()
|
upstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, this.unitPolicy.canonical.pressure) || 0
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -406,8 +695,8 @@ class MachineGroup {
|
|||||||
if(machine.state.getCurrentState() !== "operational" && machine.state.getCurrentState() !== "accelerating" && machine.state.getCurrentState() !== "decelerating"){
|
if(machine.state.getCurrentState() !== "operational" && machine.state.getCurrentState() !== "accelerating" && machine.state.getCurrentState() !== "decelerating"){
|
||||||
|
|
||||||
//Equilize pressures over all machines so we can make a proper calculation
|
//Equilize pressures over all machines so we can make a proper calculation
|
||||||
machine.measurements.type("pressure").variant("measured").position(POSITIONS.DOWNSTREAM).value(maxDownstream);
|
this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, maxDownstream, this.unitPolicy.canonical.pressure);
|
||||||
machine.measurements.type("pressure").variant("measured").position(POSITIONS.UPSTREAM).value(minUpstream);
|
this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, minUpstream, this.unitPolicy.canonical.pressure);
|
||||||
|
|
||||||
// after updating the measurement directly we need to force the update of the value OLIFANT this is not so clear now in the code
|
// after updating the measurement directly we need to force the update of the value OLIFANT this is not so clear now in the code
|
||||||
// we need to find a better way to do this but for now it works
|
// we need to find a better way to do this but for now it works
|
||||||
@@ -424,7 +713,9 @@ class MachineGroup {
|
|||||||
}, {});
|
}, {});
|
||||||
|
|
||||||
if( Qd <= 0 ) {
|
if( Qd <= 0 ) {
|
||||||
//if Qd is 0 turn all machines off and exit early
|
this.logger.debug("Flow demand <= 0, turning all machines off.");
|
||||||
|
await this.turnOffAllMachines();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if( Qd < dynamicTotals.flow.min && Qd > 0 ){
|
if( Qd < dynamicTotals.flow.min && Qd > 0 ){
|
||||||
@@ -440,7 +731,26 @@ class MachineGroup {
|
|||||||
|
|
||||||
// fetch all valid combinations that meet expectations
|
// fetch all valid combinations that meet expectations
|
||||||
const combinations = this.validPumpCombinations(this.machines, Qd, powerCap);
|
const combinations = this.validPumpCombinations(this.machines, Qd, powerCap);
|
||||||
const bestResult = this.calcBestCombination(combinations, Qd);
|
|
||||||
|
if (!combinations || combinations.length === 0) {
|
||||||
|
this.logger.warn(`Demand: ${Qd.toFixed(2)} -> No valid combination found (empty set).`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decide which optimization routine we run. Defaults to BEP-based gravitation with directionality.
|
||||||
|
const optimizationMethod = this.config.optimization?.method || "BEP-Gravitation-Directional";
|
||||||
|
let bestResult;
|
||||||
|
if (optimizationMethod === "NCog") {
|
||||||
|
bestResult = this.calcBestCombination(combinations, Qd);
|
||||||
|
} else if (
|
||||||
|
optimizationMethod === "BEP-Gravitation" ||
|
||||||
|
optimizationMethod === "BEP-Gravitation-Directional"
|
||||||
|
) {
|
||||||
|
bestResult = this.calcBestCombinationBEPGravitation(combinations, Qd, optimizationMethod);
|
||||||
|
} else {
|
||||||
|
this.logger.warn(`Unknown optimization method '${optimizationMethod}', falling back to BEP-Gravitation-Directional.`);
|
||||||
|
bestResult = this.calcBestCombinationBEPGravitation(combinations, Qd, "BEP-Gravitation-Directional");
|
||||||
|
}
|
||||||
|
|
||||||
if(bestResult.bestCombination === null){
|
if(bestResult.bestCombination === null){
|
||||||
this.logger.warn(`Demand: ${Qd.toFixed(2)} -> No valid combination found => not updating control `);
|
this.logger.warn(`Demand: ${Qd.toFixed(2)} -> No valid combination found => not updating control `);
|
||||||
@@ -451,8 +761,8 @@ class MachineGroup {
|
|||||||
this.logger.debug(`Moving to demand: ${Qd.toFixed(2)} -> Pumps: [${debugInfo}] => Total Power: ${bestResult.bestPower.toFixed(2)}`);
|
this.logger.debug(`Moving to demand: ${Qd.toFixed(2)} -> Pumps: [${debugInfo}] => Total Power: ${bestResult.bestPower.toFixed(2)}`);
|
||||||
|
|
||||||
//store the total delivered power
|
//store the total delivered power
|
||||||
this.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(bestResult.bestPower);
|
this._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, bestResult.bestPower, this.unitPolicy.canonical.power);
|
||||||
this.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).value(bestResult.bestFlow);
|
this._writeMeasurement("flow", "predicted", POSITIONS.DOWNSTREAM, bestResult.bestFlow, this.unitPolicy.canonical.flow);
|
||||||
this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(bestResult.bestFlow / bestResult.bestPower);
|
this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(bestResult.bestFlow / bestResult.bestPower);
|
||||||
this.measurements.type("Ncog").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(bestResult.bestCog);
|
this.measurements.type("Ncog").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(bestResult.bestCog);
|
||||||
|
|
||||||
@@ -469,16 +779,16 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if( (flow <= 0 ) && ( machineStates[machineId] === "operational" || machineStates[machineId] === "accelerating" || machineStates[machineId] === "decelerating" ) ){
|
if( (flow <= 0 ) && ( machineStates[machineId] === "operational" || machineStates[machineId] === "accelerating" || machineStates[machineId] === "decelerating" ) ){
|
||||||
await machine.handleInput("parent", "execSequence", "shutdown");
|
await machine.handleInput("parent", "execsequence", "shutdown");
|
||||||
}
|
}
|
||||||
|
|
||||||
if(machineStates[machineId] === "idle" && flow > 0){
|
if(machineStates[machineId] === "idle" && flow > 0){
|
||||||
await machine.handleInput("parent", "execSequence", "startup");
|
await machine.handleInput("parent", "execsequence", "startup");
|
||||||
await machine.handleInput("parent", "flowMovement", flow);
|
await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
|
||||||
}
|
}
|
||||||
|
|
||||||
if(machineStates[machineId] === "operational" && flow > 0 ){
|
if(machineStates[machineId] === "operational" && flow > 0 ){
|
||||||
await machine.handleInput("parent", "flowMovement", flow);
|
await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -489,11 +799,13 @@ class MachineGroup {
|
|||||||
|
|
||||||
// Equalize pressure across all machines for machines that are not running. This is needed to ensure accurate flow and power predictions.
|
// Equalize pressure across all machines for machines that are not running. This is needed to ensure accurate flow and power predictions.
|
||||||
equalizePressure(){
|
equalizePressure(){
|
||||||
|
if (Object.keys(this.machines).length === 0) return;
|
||||||
|
|
||||||
// Get current pressures from all machines
|
// Get current pressures from all machines
|
||||||
const pressures = Object.entries(this.machines).map(([_machineId, machine]) => {
|
const pressures = Object.entries(this.machines).map(([_machineId, machine]) => {
|
||||||
return {
|
return {
|
||||||
downstream: machine.measurements.type("pressure").variant("measured").position(POSITIONS.DOWNSTREAM).getCurrentValue(),
|
downstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.pressure) || 0,
|
||||||
upstream: machine.measurements.type("pressure").variant("measured").position(POSITIONS.UPSTREAM).getCurrentValue()
|
upstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, this.unitPolicy.canonical.pressure) || 0
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -504,8 +816,8 @@ class MachineGroup {
|
|||||||
// Set consistent pressures across machines
|
// Set consistent pressures across machines
|
||||||
Object.entries(this.machines).forEach(([machineId, machine]) => {
|
Object.entries(this.machines).forEach(([machineId, machine]) => {
|
||||||
if(!this.isMachineActive(machineId)){
|
if(!this.isMachineActive(machineId)){
|
||||||
machine.measurements.type("pressure").variant("measured").position(POSITIONS.DOWNSTREAM).value(maxDownstream);
|
this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, maxDownstream, this.unitPolicy.canonical.pressure);
|
||||||
machine.measurements.type("pressure").variant("measured").position(POSITIONS.UPSTREAM).value(minUpstream);
|
this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, minUpstream, this.unitPolicy.canonical.pressure);
|
||||||
// Update the measured pressure value
|
// Update the measured pressure value
|
||||||
const pressure = machine.getMeasuredPressure();
|
const pressure = machine.getMeasuredPressure();
|
||||||
this.logger.debug(`Setting pressure for machine ${machineId} to ${pressure}`);
|
this.logger.debug(`Setting pressure for machine ${machineId} to ${pressure}`);
|
||||||
@@ -551,7 +863,7 @@ class MachineGroup {
|
|||||||
filterOutUnavailableMachines(list) {
|
filterOutUnavailableMachines(list) {
|
||||||
const newList = list.filter(({ machine }) => {
|
const newList = list.filter(({ machine }) => {
|
||||||
const state = machine.state.getCurrentState();
|
const state = machine.state.getCurrentState();
|
||||||
const validActionForMode = machine.isValidActionForMode("execSequence", "auto");
|
const validActionForMode = machine.isValidActionForMode("execsequence", "auto");
|
||||||
|
|
||||||
return !(state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validActionForMode);
|
return !(state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validActionForMode);
|
||||||
});
|
});
|
||||||
@@ -683,8 +995,8 @@ class MachineGroup {
|
|||||||
this.logger.debug(`Priority control for demand: ${totalFlow.toFixed(2)} -> Active pumps: [${debugInfo}] => Total Power: ${totalPower.toFixed(2)}`);
|
this.logger.debug(`Priority control for demand: ${totalFlow.toFixed(2)} -> Active pumps: [${debugInfo}] => Total Power: ${totalPower.toFixed(2)}`);
|
||||||
|
|
||||||
// Store measurements
|
// Store measurements
|
||||||
this.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalPower);
|
this._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, totalPower, this.unitPolicy.canonical.power);
|
||||||
this.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).value(totalFlow);
|
this._writeMeasurement("flow", "predicted", POSITIONS.DOWNSTREAM, totalFlow, this.unitPolicy.canonical.flow);
|
||||||
this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalFlow / totalPower);
|
this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalFlow / totalPower);
|
||||||
this.measurements.type("Ncog").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalCog);
|
this.measurements.type("Ncog").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalCog);
|
||||||
|
|
||||||
@@ -696,13 +1008,14 @@ class MachineGroup {
|
|||||||
const currentState = this.machines[machineId].state.getCurrentState();
|
const currentState = this.machines[machineId].state.getCurrentState();
|
||||||
|
|
||||||
if (flow <= 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) {
|
if (flow <= 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) {
|
||||||
await machine.handleInput("parent", "execSequence", "shutdown");
|
await machine.handleInput("parent", "execsequence", "shutdown");
|
||||||
}
|
}
|
||||||
else if (currentState === "idle" && flow > 0) {
|
else if (currentState === "idle" && flow > 0) {
|
||||||
await machine.handleInput("parent", "execSequence", "startup");
|
await machine.handleInput("parent", "execsequence", "startup");
|
||||||
|
await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
|
||||||
}
|
}
|
||||||
else if (currentState === "operational" && flow > 0) {
|
else if (currentState === "operational" && flow > 0) {
|
||||||
await machine.handleInput("parent", "flowMovement", flow);
|
await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -718,7 +1031,7 @@ class MachineGroup {
|
|||||||
if(input < 0 ){
|
if(input < 0 ){
|
||||||
//turn all machines off
|
//turn all machines off
|
||||||
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
|
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
|
||||||
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execSequence", "shutdown"); }
|
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execsequence", "shutdown"); }
|
||||||
}));
|
}));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -782,13 +1095,13 @@ class MachineGroup {
|
|||||||
const currentState = this.machines[machineId].state.getCurrentState();
|
const currentState = this.machines[machineId].state.getCurrentState();
|
||||||
|
|
||||||
if (ctrl < 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) {
|
if (ctrl < 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) {
|
||||||
await machine.handleInput("parent", "execSequence", "shutdown");
|
await machine.handleInput("parent", "execsequence", "shutdown");
|
||||||
}
|
}
|
||||||
else if (currentState === "idle" && ctrl >= 0) {
|
else if (currentState === "idle" && ctrl >= 0) {
|
||||||
await machine.handleInput("parent", "execSequence", "startup");
|
await machine.handleInput("parent", "execsequence", "startup");
|
||||||
}
|
}
|
||||||
else if (currentState === "operational" && ctrl > 0) {
|
else if (currentState === "operational" && ctrl > 0) {
|
||||||
await machine.handleInput("parent", "execMovement", ctrl);
|
await machine.handleInput("parent", "execmovement", ctrl);
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -798,8 +1111,8 @@ class MachineGroup {
|
|||||||
// fetch and store measurements
|
// fetch and store measurements
|
||||||
Object.entries(this.machines).forEach(([_machineId, machine]) => {
|
Object.entries(this.machines).forEach(([_machineId, machine]) => {
|
||||||
|
|
||||||
const powerValue = machine.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
const powerValue = this._readChildMeasurement(machine, "power", "predicted", POSITIONS.AT_EQUIPMENT, this.unitPolicy.canonical.power);
|
||||||
const flowValue = machine.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
const flowValue = this._readChildMeasurement(machine, "flow", "predicted", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow);
|
||||||
|
|
||||||
if (powerValue !== null) {
|
if (powerValue !== null) {
|
||||||
totalPower.push(powerValue);
|
totalPower.push(powerValue);
|
||||||
@@ -809,8 +1122,8 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalPower.reduce((a, b) => a + b, 0));
|
this._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, totalPower.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.power);
|
||||||
this.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).value(totalFlow.reduce((a, b) => a + b, 0));
|
this._writeMeasurement("flow", "predicted", POSITIONS.DOWNSTREAM, totalFlow.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.flow);
|
||||||
|
|
||||||
if(totalPower.reduce((a, b) => a + b, 0) > 0){
|
if(totalPower.reduce((a, b) => a + b, 0) > 0){
|
||||||
this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalFlow.reduce((a, b) => a + b, 0) / totalPower.reduce((a, b) => a + b, 0));
|
this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalFlow.reduce((a, b) => a + b, 0) / totalPower.reduce((a, b) => a + b, 0));
|
||||||
@@ -824,13 +1137,19 @@ class MachineGroup {
|
|||||||
|
|
||||||
async handleInput(source, demand, powerCap = Infinity, priorityList = null) {
|
async handleInput(source, demand, powerCap = Infinity, priorityList = null) {
|
||||||
|
|
||||||
|
const demandQ = parseFloat(demand);
|
||||||
|
|
||||||
|
if(!Number.isFinite(demandQ)){
|
||||||
|
this.logger.error(`Invalid flow demand input: ${demand}. Must be a finite number.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
//abort current movements
|
//abort current movements
|
||||||
await this.abortActiveMovements("new demand received");
|
await this.abortActiveMovements("new demand received");
|
||||||
|
|
||||||
const scaling = this.scaling;
|
const scaling = this.scaling;
|
||||||
const mode = this.mode;
|
const mode = this.mode;
|
||||||
const dynamicTotals = this.calcDynamicTotals();
|
const dynamicTotals = this.calcDynamicTotals();
|
||||||
const demandQ = parseFloat(demand);
|
|
||||||
let demandQout = 0; // keep output Q by default 0 for safety
|
let demandQout = 0; // keep output Q by default 0 for safety
|
||||||
|
|
||||||
this.logger.debug(`Handling input from ${source}: Demand = ${demand}, Power Cap = ${powerCap}, Priority List = ${priorityList}`);
|
this.logger.debug(`Handling input from ${source}: Demand = ${demand}, Power Cap = ${powerCap}, Priority List = ${priorityList}`);
|
||||||
@@ -843,23 +1162,23 @@ class MachineGroup {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (demandQ < this.absoluteTotals.flow.min) {
|
if (demandQ <= 0) {
|
||||||
this.logger.warn(`Flow demand ${demandQ} is below minimum possible flow ${this.absoluteTotals.flow.min}. Capping to minimum flow.`);
|
|
||||||
demandQout = this.absoluteTotals.flow.min;
|
|
||||||
} else if (demandQout > this.absoluteTotals.flow.max) {
|
|
||||||
this.logger.warn(`Flow demand ${demandQ} is above maximum possible flow ${this.absoluteTotals.flow.max}. Capping to maximum flow.`);
|
|
||||||
demandQout = this.absoluteTotals.flow.max;
|
|
||||||
}else if(demandQout <= 0){
|
|
||||||
this.logger.debug(`Turning machines off`);
|
this.logger.debug(`Turning machines off`);
|
||||||
demandQout = 0;
|
demandQout = 0;
|
||||||
//return early and turn all machines off
|
|
||||||
this.turnOffAllMachines();
|
this.turnOffAllMachines();
|
||||||
return;
|
return;
|
||||||
|
} else if (demandQ < this.absoluteTotals.flow.min) {
|
||||||
|
this.logger.warn(`Flow demand ${demandQ} is below minimum possible flow ${this.absoluteTotals.flow.min}. Capping to minimum flow.`);
|
||||||
|
demandQout = this.absoluteTotals.flow.min;
|
||||||
|
} else if (demandQ > this.absoluteTotals.flow.max) {
|
||||||
|
this.logger.warn(`Flow demand ${demandQ} is above maximum possible flow ${this.absoluteTotals.flow.max}. Capping to maximum flow.`);
|
||||||
|
demandQout = this.absoluteTotals.flow.max;
|
||||||
|
} else {
|
||||||
|
demandQout = demandQ;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "normalized":
|
case "normalized":
|
||||||
|
|
||||||
this.logger.debug(`Normalizing flow demand: ${demandQ} with min: ${dynamicTotals.flow.min} and max: ${dynamicTotals.flow.max}`);
|
this.logger.debug(`Normalizing flow demand: ${demandQ} with min: ${dynamicTotals.flow.min} and max: ${dynamicTotals.flow.max}`);
|
||||||
if(demand < 0){
|
if(demand < 0){
|
||||||
this.logger.debug(`Turning machines off`);
|
this.logger.debug(`Turning machines off`);
|
||||||
@@ -877,7 +1196,6 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Execute control based on mode
|
// Execute control based on mode
|
||||||
switch(mode) {
|
switch(mode) {
|
||||||
case "prioritycontrol":
|
case "prioritycontrol":
|
||||||
@@ -906,17 +1224,124 @@ class MachineGroup {
|
|||||||
|
|
||||||
//recalc distance from BEP
|
//recalc distance from BEP
|
||||||
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
|
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
|
||||||
const efficiency = this.measurements.type("efficiency").variant("predicted").position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
const efficiency = this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
||||||
this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency);
|
this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async turnOffAllMachines(){
|
async turnOffAllMachines(){
|
||||||
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
|
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
|
||||||
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execSequence", "shutdown"); }
|
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execsequence", "shutdown"); }
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_buildUnitPolicy(config = {}) {
|
||||||
|
const flowUnit = this._resolveUnitOrFallback(
|
||||||
|
config?.general?.unit,
|
||||||
|
'volumeFlowRate',
|
||||||
|
DEFAULT_IO_UNITS.flow
|
||||||
|
);
|
||||||
|
const pressureUnit = this._resolveUnitOrFallback(
|
||||||
|
config?.general?.pressureUnit,
|
||||||
|
'pressure',
|
||||||
|
DEFAULT_IO_UNITS.pressure
|
||||||
|
);
|
||||||
|
const powerUnit = this._resolveUnitOrFallback(
|
||||||
|
config?.general?.powerUnit,
|
||||||
|
'power',
|
||||||
|
DEFAULT_IO_UNITS.power
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
canonical: { ...CANONICAL_UNITS },
|
||||||
|
output: {
|
||||||
|
flow: flowUnit,
|
||||||
|
pressure: pressureUnit,
|
||||||
|
power: powerUnit,
|
||||||
|
temperature: DEFAULT_IO_UNITS.temperature,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
_resolveUnitOrFallback(candidate, expectedMeasure, fallbackUnit) {
|
||||||
|
const fallback = String(fallbackUnit || '').trim();
|
||||||
|
const raw = typeof candidate === 'string' ? candidate.trim() : '';
|
||||||
|
if (!raw) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const desc = convert().describe(raw);
|
||||||
|
if (expectedMeasure && desc.measure !== expectedMeasure) {
|
||||||
|
throw new Error(`expected '${expectedMeasure}', got '${desc.measure}'`);
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger?.warn?.(`Invalid unit '${raw}' (${error.message}); falling back to '${fallback}'.`);
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_canonicalToOutputFlow(value) {
|
||||||
|
const from = this.unitPolicy.canonical.flow;
|
||||||
|
const to = this.unitPolicy.output.flow;
|
||||||
|
if (!from || !to || from === to) return value;
|
||||||
|
return convert(value).from(from).to(to);
|
||||||
|
}
|
||||||
|
|
||||||
|
_outputUnitForType(type) {
|
||||||
|
switch (String(type || '').toLowerCase()) {
|
||||||
|
case 'flow':
|
||||||
|
return this.unitPolicy.output.flow;
|
||||||
|
case 'power':
|
||||||
|
return this.unitPolicy.output.power;
|
||||||
|
case 'pressure':
|
||||||
|
return this.unitPolicy.output.pressure;
|
||||||
|
case 'temperature':
|
||||||
|
return this.unitPolicy.output.temperature;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_readMeasurement(type, variant, position, unit = null) {
|
||||||
|
const requestedUnit = unit || this._outputUnitForType(type);
|
||||||
|
return this.measurements
|
||||||
|
.type(type)
|
||||||
|
.variant(variant)
|
||||||
|
.position(position)
|
||||||
|
.getCurrentValue(requestedUnit || undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
_writeMeasurement(type, variant, position, value, unit = null, timestamp = Date.now()) {
|
||||||
|
if (!Number.isFinite(value)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.measurements
|
||||||
|
.type(type)
|
||||||
|
.variant(variant)
|
||||||
|
.position(position)
|
||||||
|
.value(value, timestamp, unit || undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
_readChildMeasurement(machine, type, variant, position, unit = null) {
|
||||||
|
return machine?.measurements
|
||||||
|
?.type(type)
|
||||||
|
?.variant(variant)
|
||||||
|
?.position(position)
|
||||||
|
?.getCurrentValue(unit || undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
_writeChildMeasurement(machine, type, variant, position, value, unit = null, timestamp = Date.now()) {
|
||||||
|
if (!machine?.measurements || !Number.isFinite(value)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
machine.measurements
|
||||||
|
.type(type)
|
||||||
|
.variant(variant)
|
||||||
|
.position(position)
|
||||||
|
.value(value, timestamp, unit || undefined);
|
||||||
|
}
|
||||||
|
|
||||||
setMode(mode) {
|
setMode(mode) {
|
||||||
this.mode = mode;
|
this.mode = mode;
|
||||||
}
|
}
|
||||||
@@ -929,10 +1354,10 @@ class MachineGroup {
|
|||||||
//build the output object
|
//build the output object
|
||||||
this.measurements.getTypes().forEach(type => {
|
this.measurements.getTypes().forEach(type => {
|
||||||
this.measurements.getVariants(type).forEach(variant => {
|
this.measurements.getVariants(type).forEach(variant => {
|
||||||
|
const unit = this._outputUnitForType(type);
|
||||||
const downstreamVal = this.measurements.type(type).variant(variant).position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
const downstreamVal = this._readMeasurement(type, variant, POSITIONS.DOWNSTREAM, unit);
|
||||||
const atEquipmentVal = this.measurements.type(type).variant(variant).position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
const atEquipmentVal = this._readMeasurement(type, variant, POSITIONS.AT_EQUIPMENT, unit);
|
||||||
const upstreamVal = this.measurements.type(type).variant(variant).position(POSITIONS.UPSTREAM).getCurrentValue();
|
const upstreamVal = this._readMeasurement(type, variant, POSITIONS.UPSTREAM, unit);
|
||||||
|
|
||||||
if (downstreamVal != null) {
|
if (downstreamVal != null) {
|
||||||
output[`downstream_${variant}_${type}`] = downstreamVal;
|
output[`downstream_${variant}_${type}`] = downstreamVal;
|
||||||
@@ -944,8 +1369,13 @@ class MachineGroup {
|
|||||||
output[`atEquipment_${variant}_${type}`] = atEquipmentVal;
|
output[`atEquipment_${variant}_${type}`] = atEquipmentVal;
|
||||||
}
|
}
|
||||||
if (downstreamVal != null && upstreamVal != null) {
|
if (downstreamVal != null && upstreamVal != null) {
|
||||||
const diffVal = this.measurements.type(type).variant(variant).difference().value;
|
const diff = this.measurements
|
||||||
output[`differential_${variant}_${type}`] = diffVal;
|
.type(type)
|
||||||
|
.variant(variant)
|
||||||
|
.difference({ from: POSITIONS.DOWNSTREAM, to: POSITIONS.UPSTREAM, unit });
|
||||||
|
if (diff?.value != null) {
|
||||||
|
output[`differential_${variant}_${type}`] = diff.value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -967,7 +1397,7 @@ class MachineGroup {
|
|||||||
|
|
||||||
module.exports = MachineGroup;
|
module.exports = MachineGroup;
|
||||||
/*
|
/*
|
||||||
|
const {coolprop} = require('generalFunctions');
|
||||||
const Machine = require('../../rotatingMachine/src/specificClass');
|
const Machine = require('../../rotatingMachine/src/specificClass');
|
||||||
const Measurement = require('../../measurement/src/specificClass');
|
const Measurement = require('../../measurement/src/specificClass');
|
||||||
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
|
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
|
||||||
@@ -995,9 +1425,9 @@ function createBaseMachineConfig(machineNum, name,specs) {
|
|||||||
mode: {
|
mode: {
|
||||||
current: "auto",
|
current: "auto",
|
||||||
allowedActions: {
|
allowedActions: {
|
||||||
auto: ["execSequence", "execMovement", "statusCheck"],
|
auto: ["execsequence", "execmovement", "statuscheck"],
|
||||||
virtualControl: ["execMovement", "statusCheck"],
|
virtualControl: ["execmovement", "statuscheck"],
|
||||||
fysicalControl: ["statusCheck"]
|
fysicalControl: ["statuscheck"]
|
||||||
},
|
},
|
||||||
allowedSources: {
|
allowedSources: {
|
||||||
auto: ["parent", "GUI"],
|
auto: ["parent", "GUI"],
|
||||||
@@ -1089,11 +1519,11 @@ async function makeMachines(){
|
|||||||
for(let i = 1; i <= numofMachines; i++){
|
for(let i = 1; i <= numofMachines; i++){
|
||||||
const machine = new Machine(machineConfigs[i],stateConfigs[i]);
|
const machine = new Machine(machineConfigs[i],stateConfigs[i]);
|
||||||
//mg.machines[i] = machine;
|
//mg.machines[i] = machine;
|
||||||
mg.childRegistrationUtils.registerChild(machine, POSITIONS.DOWNSTREAM);
|
mg.childRegistrationUtils.registerChild(machine, "downstream");
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.keys(mg.machines).forEach(machineId => {
|
Object.keys(mg.machines).forEach(machineId => {
|
||||||
mg.machines[machineId].childRegistrationUtils.registerChild(pt1, POSITIONS.DOWNSTREAM);
|
mg.machines[machineId].childRegistrationUtils.registerChild(pt1, "downstream");
|
||||||
});
|
});
|
||||||
|
|
||||||
mg.setMode("prioritycontrol");
|
mg.setMode("prioritycontrol");
|
||||||
@@ -1105,7 +1535,7 @@ async function makeMachines(){
|
|||||||
const percMax = 100;
|
const percMax = 100;
|
||||||
|
|
||||||
try{
|
try{
|
||||||
/*
|
|
||||||
for(let demand = mg.dynamicTotals.flow.min ; demand <= mg.dynamicTotals.flow.max ; demand += 2){
|
for(let demand = mg.dynamicTotals.flow.min ; demand <= mg.dynamicTotals.flow.max ; demand += 2){
|
||||||
//set pressure
|
//set pressure
|
||||||
|
|
||||||
@@ -1155,6 +1585,8 @@ async function makeMachines(){
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
makeMachines();
|
if (require.main === module) {
|
||||||
|
makeMachines();
|
||||||
|
}
|
||||||
|
|
||||||
//*/
|
//*/
|
||||||
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