Compare commits
1 Commits
dev-Rene
...
85797b5b8b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85797b5b8b |
@@ -1,8 +0,0 @@
|
|||||||
# machineGroupControl Example Flows
|
|
||||||
|
|
||||||
Import-ready Node-RED examples for machineGroupControl.
|
|
||||||
|
|
||||||
## Files
|
|
||||||
- basic.flow.json
|
|
||||||
- integration.flow.json
|
|
||||||
- edge.flow.json
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
[
|
|
||||||
{"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":[]}
|
|
||||||
]
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
[
|
|
||||||
{"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":[]}
|
|
||||||
]
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
[
|
|
||||||
{"id":"machineGroupControl_int_tab","type":"tab","label":"machineGroupControl integration","disabled":false,"info":"machineGroupControl integration example"},
|
|
||||||
{"id":"machineGroupControl_int_node","type":"machineGroupControl","z":"machineGroupControl_int_tab","name":"machineGroupControl integration","x":420,"y":180,"wires":[["machineGroupControl_int_dbg"]]},
|
|
||||||
{"id":"machineGroupControl_int_inj","type":"inject","z":"machineGroupControl_int_tab","name":"registerChild","props":[{"p":"topic","vt":"str"},{"p":"payload","vt":"str"}],"topic":"registerChild","payload":"example-child-id","payloadType":"str","x":170,"y":180,"wires":[["machineGroupControl_int_node"]]},
|
|
||||||
{"id":"machineGroupControl_int_dbg","type":"debug","z":"machineGroupControl_int_tab","name":"machineGroupControl integration debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":680,"y":180,"wires":[]}
|
|
||||||
]
|
|
||||||
22
mgc.html
22
mgc.html
@@ -18,6 +18,8 @@
|
|||||||
defaults: {
|
defaults: {
|
||||||
// Define default properties
|
// Define default properties
|
||||||
name: { value: "" },
|
name: { value: "" },
|
||||||
|
processOutputFormat: { value: "process" },
|
||||||
|
dbaseOutputFormat: { value: "influxdb" },
|
||||||
|
|
||||||
// Logger properties
|
// Logger properties
|
||||||
enableLog: { value: false },
|
enableLog: { value: false },
|
||||||
@@ -39,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
|
||||||
@@ -74,6 +76,24 @@
|
|||||||
|
|
||||||
<script type="text/html" data-template-name="machineGroupControl">
|
<script type="text/html" data-template-name="machineGroupControl">
|
||||||
|
|
||||||
|
<h3>Output Formats</h3>
|
||||||
|
<div class="form-row">
|
||||||
|
<label for="node-input-processOutputFormat"><i class="fa fa-random"></i> Process Output</label>
|
||||||
|
<select id="node-input-processOutputFormat" style="width:60%;">
|
||||||
|
<option value="process">process</option>
|
||||||
|
<option value="json">json</option>
|
||||||
|
<option value="csv">csv</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<label for="node-input-dbaseOutputFormat"><i class="fa fa-database"></i> Database Output</label>
|
||||||
|
<select id="node-input-dbaseOutputFormat" style="width:60%;">
|
||||||
|
<option value="influxdb">influxdb</option>
|
||||||
|
<option value="json">json</option>
|
||||||
|
<option value="csv">csv</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Logger fields injected here -->
|
<!-- Logger fields injected here -->
|
||||||
<div id="logger-fields-placeholder"></div>
|
<div id="logger-fields-placeholder"></div>
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
"description": "Control module machineGroupControl",
|
"description": "Control module machineGroupControl",
|
||||||
"main": "mgc.js",
|
"main": "mgc.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node --test test/basic/*.test.js test/integration/*.test.js test/edge/*.test.js"
|
"test": "node mgc.js"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
|
|||||||
@@ -1,345 +1,288 @@
|
|||||||
'use strict';
|
// ...existing code...
|
||||||
|
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 baseCurve = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
|
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
|
||||||
|
|
||||||
const CONTROL_MODES = ['optimalcontrol', 'prioritycontrol', 'prioritypercentagecontrol'];
|
|
||||||
const MODE_LABELS = {
|
|
||||||
optimalcontrol: 'OPT',
|
|
||||||
prioritycontrol: 'PRIO',
|
|
||||||
prioritypercentagecontrol: 'PERC'
|
|
||||||
};
|
|
||||||
|
|
||||||
const stateConfig = {
|
|
||||||
time: { starting: 0, warmingup: 0, stopping: 0, coolingdown: 0, emergencystop: 0 },
|
|
||||||
movement: { speed: 1200, mode: 'staticspeed', maxSpeed: 1800 }
|
|
||||||
};
|
|
||||||
|
|
||||||
|
const stateConfig = { time:{starting:0,warmingup:0,stopping:0,coolingdown:0}, movement:{speed:1000,mode:"staticspeed"} };
|
||||||
const ptConfig = {
|
const ptConfig = {
|
||||||
general: { logging: { enabled: false, logLevel: 'error' }, name: 'synthetic-pt', id: 'pt-1', unit: 'mbar' },
|
general:{ logging:{enabled:false,logLevel:"warn"}, name:"testpt", id:"pt-1", unit:"mbar" },
|
||||||
functionality: {
|
functionality:{ softwareType:"measurement", role:"sensor" },
|
||||||
softwareType: 'measurement',
|
asset:{ category:"sensor", type:"pressure", model:"testmodel", supplier:"vega", unit:"mbar" },
|
||||||
role: 'sensor',
|
|
||||||
positionVsParent: 'downstream'
|
|
||||||
},
|
|
||||||
asset: { category: 'sensor', type: 'pressure', model: 'synthetic-pt', supplier: 'lab', unit: 'mbar' },
|
|
||||||
scaling:{ absMin:0, absMax:4000 }
|
scaling:{ absMin:0, absMax:4000 }
|
||||||
};
|
};
|
||||||
|
|
||||||
const scenarios = [
|
const testSuite = [];
|
||||||
{
|
const efficiencyComparisons = [];
|
||||||
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) {
|
function logPass(name, details="") {
|
||||||
return {
|
const entry = { name, status:"PASS", details };
|
||||||
general: { logging: { enabled: false, logLevel: 'error' }, name: `machinegroup-${name}` },
|
testSuite.push(entry);
|
||||||
functionality: { softwareType: 'machinegroup', role: 'groupcontroller' },
|
console.log(`✅ ${name}${details ? ` — ${details}` : ""}`);
|
||||||
scaling: { current: 'normalized' },
|
|
||||||
mode: { current: 'optimalcontrol' }
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
function logFail(name, error) {
|
||||||
function sleep(ms) {
|
const entry = { name, status:"FAIL", details:error?.message || error };
|
||||||
return new Promise(resolve => setTimeout(resolve, ms));
|
testSuite.push(entry);
|
||||||
|
console.error(`❌ ${name} — ${entry.details}`);
|
||||||
}
|
}
|
||||||
|
function approxEqual(actual, expected, tolerancePct=1) {
|
||||||
async function setPressure(pt, value) {
|
const tolerance = (expected * tolerancePct) / 100;
|
||||||
const retries = 6;
|
return actual >= expected - tolerance && actual <= expected + tolerance;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
async function sleep(ms){ return new Promise(resolve => setTimeout(resolve, ms)); }
|
||||||
|
|
||||||
function createMachineConfig(id,label) {
|
function createMachineConfig(id,label) {
|
||||||
return {
|
return {
|
||||||
general: { logging: { enabled: false, logLevel: 'error' }, name: label, id, unit: 'm3/h' },
|
general:{ logging:{enabled:false,logLevel:"warn"}, name:label, id, unit:"m3/h" },
|
||||||
functionality: { softwareType: 'machine', role: 'rotationaldevicecontroller' },
|
functionality:{ softwareType:"machine", role:"rotationaldevicecontroller" },
|
||||||
asset: { category: 'pump', type: 'centrifugal', model: 'hidrostal-h05k-s03r', supplier: 'hidrostal', machineCurve: baseCurve },
|
asset:{ category:"pump", type:"centrifugal", model:"hidrostal-h05k-s03r", supplier:"hydrostal", machineCurve:specs },
|
||||||
mode:{
|
mode:{
|
||||||
current: 'auto',
|
current:"auto",
|
||||||
allowedActions:{
|
allowedActions:{
|
||||||
auto: ['execsequence', 'execmovement', 'flowmovement', 'statuscheck'],
|
auto:["execSequence","execMovement","flowMovement","statusCheck"],
|
||||||
virtualControl: ['execmovement', 'statuscheck'],
|
virtualControl:["execMovement","statusCheck"],
|
||||||
fysicalControl: ['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 bootstrapScenarioMachines(scenario) {
|
async function bootstrapGroup() {
|
||||||
const mg = new MachineGroup(createGroupConfig(scenario.name));
|
const groupCfg = {
|
||||||
|
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 (const machineDef of scenario.machines) {
|
for (let idx=1; idx<=2; idx++){
|
||||||
const machine = new Machine(createMachineConfig(machineDef.id, machineDef.label), stateConfig);
|
const machine = new Machine(createMachineConfig(String(idx),`machine-${idx}`), stateConfig);
|
||||||
if (machineDef.curveMods) {
|
mg.childRegistrationUtils.registerChild(machine,"downstream");
|
||||||
machine.updateCurve(createSyntheticCurve(machineDef.curveMods));
|
machine.childRegistrationUtils.registerChild(pt,"downstream");
|
||||||
}
|
}
|
||||||
mg.childRegistrationUtils.registerChild(machine, 'downstream');
|
pt.calculateInput(1000);
|
||||||
machine.childRegistrationUtils.registerChild(pt, 'downstream');
|
await sleep(10);
|
||||||
}
|
|
||||||
|
|
||||||
await sleep(25);
|
|
||||||
return { mg, pt };
|
return { mg, pt };
|
||||||
}
|
}
|
||||||
|
|
||||||
function captureTotals(mg) {
|
function captureState(mg,label){
|
||||||
const flow = mg.measurements.type('flow').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
|
||||||
const power = mg.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
|
||||||
const efficiency = mg.measurements.type('efficiency').variant('predicted').position('atequipment').getCurrentValue() || 0;
|
|
||||||
return { flow, power, efficiency };
|
|
||||||
}
|
|
||||||
|
|
||||||
function computeAbsoluteTargets(dynamicTotals, percentages) {
|
|
||||||
const { flow } = dynamicTotals;
|
|
||||||
const min = Number.isFinite(flow.min) ? flow.min : 0;
|
|
||||||
const max = Number.isFinite(flow.max) ? flow.max : 0;
|
|
||||||
const span = Math.max(max - min, 1);
|
|
||||||
return percentages.map(percent => {
|
|
||||||
const pct = Math.max(0, Math.min(1, percent));
|
|
||||||
return min + pct * span;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function driveModeToFlow({ mg, pt, mode, pressure, targetFlow, priorityOrder }) {
|
|
||||||
await setPressure(pt, pressure);
|
|
||||||
await sleep(15);
|
|
||||||
|
|
||||||
mg.setMode(mode);
|
|
||||||
mg.setScaling('normalized'); // required for prioritypercentagecontrol, works for others too
|
|
||||||
|
|
||||||
const dynamic = mg.calcDynamicTotals();
|
|
||||||
const span = Math.max(dynamic.flow.max - dynamic.flow.min, 1);
|
|
||||||
const normalizedTarget = ((targetFlow - dynamic.flow.min) / span) * 100;
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
demand = (low + high) / 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
return best;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatEfficiencyRows(rows) {
|
|
||||||
return rows.map(row => {
|
|
||||||
const optimal = row.modes.optimalcontrol;
|
|
||||||
const priority = row.modes.prioritycontrol;
|
|
||||||
const percentage = row.modes.prioritypercentagecontrol;
|
|
||||||
return {
|
return {
|
||||||
pressure: row.pressure,
|
label,
|
||||||
targetFlow: Number(row.targetFlow.toFixed(1)),
|
machines: Object.entries(mg.machines).map(([id,machine]) => ({
|
||||||
[`${MODE_LABELS.optimalcontrol}_Flow`]: Number(optimal.flow.toFixed(1)),
|
id,
|
||||||
[`${MODE_LABELS.optimalcontrol}_Eff`]: Number(optimal.efficiency.toFixed(3)),
|
state: machine.state.getCurrentState(),
|
||||||
[`${MODE_LABELS.prioritycontrol}_Flow`]: Number(priority.flow.toFixed(1)),
|
position: machine.state.getCurrentPosition(),
|
||||||
[`${MODE_LABELS.prioritycontrol}_Eff`]: Number(priority.efficiency.toFixed(3)),
|
predictedFlow: machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0,
|
||||||
[`Δ${MODE_LABELS.prioritycontrol}-OPT_Eff`]: Number(
|
predictedPower: machine.measurements.type("power").variant("predicted").position("upstream").getCurrentValue() || 0
|
||||||
(priority.efficiency - optimal.efficiency).toFixed(3)
|
})),
|
||||||
),
|
totals: {
|
||||||
[`${MODE_LABELS.prioritypercentagecontrol}_Flow`]: Number(percentage.flow.toFixed(1)),
|
flow: mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0,
|
||||||
[`${MODE_LABELS.prioritypercentagecontrol}_Eff`]: Number(percentage.efficiency.toFixed(3)),
|
power: mg.measurements.type("power").variant("predicted").position("upstream").getCurrentValue() || 0,
|
||||||
[`Δ${MODE_LABELS.prioritypercentagecontrol}-OPT_Eff`]: Number(
|
efficiency: mg.measurements.type("efficiency").variant("predicted").position("downstream").getCurrentValue() || 0
|
||||||
(percentage.efficiency - optimal.efficiency).toFixed(3)
|
}
|
||||||
)
|
|
||||||
};
|
};
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function summarizeEfficiency(rows) {
|
async function testNormalizedScaling(mg,pt){
|
||||||
const map = new Map();
|
const label = "Normalized scaling tracks expected flow";
|
||||||
rows.forEach(row => {
|
try{
|
||||||
CONTROL_MODES.forEach(mode => {
|
mg.setScaling("normalized");
|
||||||
const key = `${row.scenario}-${mode}`;
|
const dynamic = mg.calcDynamicTotals();
|
||||||
if (!map.has(key)) {
|
const checkpoints = [0,10,25,50,75,100];
|
||||||
map.set(key, {
|
for (const demand of checkpoints){
|
||||||
scenario: row.scenario,
|
await mg.handleInput("parent", demand);
|
||||||
mode,
|
pt.calculateInput(1400);
|
||||||
samples: 0,
|
|
||||||
avgFlowDiff: 0,
|
|
||||||
avgEfficiency: 0
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const bucket = map.get(key);
|
|
||||||
const stats = row.modes[mode];
|
|
||||||
bucket.samples += 1;
|
|
||||||
bucket.avgFlowDiff += Math.abs(stats.flow - row.targetFlow);
|
|
||||||
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);
|
|
||||||
|
|
||||||
const rows = [];
|
|
||||||
|
|
||||||
for (const pressure of scenario.pressures) {
|
|
||||||
await setPressure(pt, pressure);
|
|
||||||
await sleep(20);
|
await sleep(20);
|
||||||
|
|
||||||
const dynamicTotals = mg.calcDynamicTotals();
|
const totals = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
||||||
const targets = computeAbsoluteTargets(dynamicTotals, scenario.flowTargetsPercent || [0, 0.5, 1]);
|
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); }
|
||||||
|
}
|
||||||
|
|
||||||
for (let idx = 0; idx < targets.length; idx += 1) {
|
async function testAbsoluteScaling(mg,pt){
|
||||||
const targetFlow = targets[idx];
|
const label = "Absolute scaling accepts direct flow targets";
|
||||||
const row = {
|
try{
|
||||||
scenario: scenario.name,
|
mg.setScaling("absolute");
|
||||||
pressure,
|
mg.setMode("optimalcontrol");
|
||||||
targetFlow,
|
const absMin = mg.dynamicTotals.flow.min;
|
||||||
modes: {}
|
const absMax = mg.dynamicTotals.flow.max;
|
||||||
};
|
const demandPoints = [absMin, absMin+20, (absMin+absMax)/2, absMax-20];
|
||||||
|
|
||||||
for (const mode of CONTROL_MODES) {
|
for(const setpoint of demandPoints){
|
||||||
const stats = await driveModeToFlow({
|
await mg.handleInput("parent", setpoint);
|
||||||
mg,
|
pt.calculateInput(1400);
|
||||||
pt,
|
await sleep(20);
|
||||||
mode,
|
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);
|
||||||
|
await mg.handleInput("parent", 50);
|
||||||
|
pt.calculateInput(1300);
|
||||||
|
await sleep(20);
|
||||||
|
const snapshot = captureState(mg, mode);
|
||||||
|
const active = snapshot.machines.filter(m => m.state !== "idle");
|
||||||
|
if(active.length === 0){
|
||||||
|
throw new Error(`No active machines after switching to ${mode}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
logPass(label);
|
||||||
|
}catch(err){ logFail(label, err); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testRampBehaviour(mg,pt){
|
||||||
|
const label = "Ramp up/down keeps monotonic flow";
|
||||||
|
try{
|
||||||
|
mg.setMode("optimalcontrol");
|
||||||
|
mg.setScaling("normalized");
|
||||||
|
const upDemands = [0,20,40,60,80,100];
|
||||||
|
let lastFlow = 0;
|
||||||
|
for(const demand of upDemands){
|
||||||
|
await mg.handleInput("parent", demand);
|
||||||
|
pt.calculateInput(1500);
|
||||||
|
await sleep(15);
|
||||||
|
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
||||||
|
if(flow < lastFlow - 1){
|
||||||
|
throw new Error(`Flow decreased during ramp up: ${flow.toFixed(2)} < ${lastFlow.toFixed(2)}`);
|
||||||
|
}
|
||||||
|
lastFlow = flow;
|
||||||
|
}
|
||||||
|
const downDemands = [100,80,60,40,20,0];
|
||||||
|
lastFlow = Infinity;
|
||||||
|
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){
|
||||||
|
const label = "Pressure changes update predictions";
|
||||||
|
try{
|
||||||
|
mg.setMode("optimalcontrol");
|
||||||
|
mg.setScaling("normalized");
|
||||||
|
const pressures = [800,1200,1600,2000];
|
||||||
|
let previousFlow = null;
|
||||||
|
for(const p of pressures){
|
||||||
|
pt.calculateInput(p);
|
||||||
|
await mg.handleInput("parent", 50);
|
||||||
|
await sleep(20);
|
||||||
|
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 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,
|
pressure,
|
||||||
targetFlow,
|
demandPercent: demand,
|
||||||
priorityOrder
|
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))
|
||||||
});
|
});
|
||||||
row.modes[mode] = stats;
|
|
||||||
}
|
|
||||||
|
|
||||||
rows.push(row);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Efficiency comparison table for scenario "${scenario.name}":`);
|
logPass(label, "efficiencyComparisons array populated");
|
||||||
console.table(formatEfficiencyRows(rows));
|
} catch (err) {
|
||||||
|
logFail(label, err);
|
||||||
return { rows };
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async function run(){
|
async function run(){
|
||||||
const combinedRows = [];
|
console.log("🚀 Starting machine-group integration tests...");
|
||||||
|
const { mg, pt } = await bootstrapGroup();
|
||||||
|
|
||||||
for (const scenario of scenarios) {
|
await testNormalizedScaling(mg, pt);
|
||||||
const { rows } = await evaluateScenario(scenario);
|
await testAbsoluteScaling(mg, pt);
|
||||||
combinedRows.push(...rows);
|
await testModeTransitions(mg, pt);
|
||||||
}
|
await testRampBehaviour(mg, pt);
|
||||||
|
await testPressureAdaptation(mg, pt);
|
||||||
|
await comparePriorityVsOptimal(mg, pt);
|
||||||
|
|
||||||
console.log('\nEfficiency summary by scenario and control mode:');
|
console.log("\n📋 TEST SUMMARY");
|
||||||
console.table(summarizeEfficiency(combinedRows));
|
console.table(testSuite);
|
||||||
|
console.log("\n📊 efficiencyComparisons:");
|
||||||
console.log('\nAll machine group control tests completed successfully.');
|
console.dir(efficiencyComparisons, { depth:null });
|
||||||
|
console.log("✅ All tests completed.");
|
||||||
}
|
}
|
||||||
|
|
||||||
run().catch(err => {
|
run().catch(err => {
|
||||||
console.error('Machine group control test harness crashed:', err);
|
console.error("💥 Test harness crashed:", err);
|
||||||
process.exitCode = 1;
|
|
||||||
});
|
});
|
||||||
|
// ...existing code...
|
||||||
|
|
||||||
|
// Run all tests
|
||||||
|
run();
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
const { outputUtils, configManager, convert } = require("generalFunctions");
|
const { outputUtils, configManager } = require("generalFunctions");
|
||||||
const Specific = require("./specificClass");
|
const Specific = require("./specificClass");
|
||||||
|
|
||||||
class nodeClass {
|
class nodeClass {
|
||||||
@@ -37,45 +37,14 @@ 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');
|
|
||||||
|
|
||||||
// Merge UI config over defaults
|
// Build config: base sections (no domain-specific config for group controller)
|
||||||
this.config = {
|
this.config = cfgMgr.buildConfig(this.name, uiConfig, node.id);
|
||||||
general: {
|
|
||||||
name: uiConfig.name,
|
|
||||||
id: node.id, // node.id is for the child registration process
|
|
||||||
unit: flowUnit,
|
|
||||||
logging: {
|
|
||||||
enabled: uiConfig.enableLog,
|
|
||||||
logLevel: uiConfig.logLevel,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
functionality: {
|
|
||||||
positionVsParent: uiConfig.positionVsParent || "atEquipment", // Default to 'atEquipment' if not set
|
|
||||||
},
|
|
||||||
};
|
|
||||||
// Utility for formatting outputs
|
// Utility for formatting outputs
|
||||||
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;
|
||||||
@@ -86,20 +55,20 @@ class nodeClass {
|
|||||||
const totalFlow = mg.measurements
|
const totalFlow = mg.measurements
|
||||||
?.type("flow")
|
?.type("flow")
|
||||||
?.variant("predicted")
|
?.variant("predicted")
|
||||||
?.position("atequipment")
|
?.position("downstream")
|
||||||
?.getCurrentValue(mg?.unitPolicy?.output?.flow || 'm3/h') || 0;
|
?.getCurrentValue() || 0;
|
||||||
|
|
||||||
const totalPower = mg.measurements
|
const totalPower = mg.measurements
|
||||||
?.type("power")
|
?.type("power")
|
||||||
?.variant("predicted")
|
?.variant("predicted")
|
||||||
?.position("atEquipment")
|
?.position("atEquipment")
|
||||||
?.getCurrentValue(mg?.unitPolicy?.output?.power || 'kW') || 0;
|
?.getCurrentValue() || 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,8 +169,8 @@ class nodeClass {
|
|||||||
*/
|
*/
|
||||||
_tick() {
|
_tick() {
|
||||||
const raw = this.source.getOutput();
|
const raw = this.source.getOutput();
|
||||||
const processMsg = this._output.formatMsg(raw, this.source.config, "process");
|
const processMsg = this._output.formatMsg(raw, this.config, "process");
|
||||||
const influxMsg = this._output.formatMsg(raw, this.source.config, "influxdb");
|
const influxMsg = this._output.formatMsg(raw, this.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]);
|
||||||
@@ -216,49 +185,60 @@ 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}`);
|
mg.logger.debug(`Registering child: ${childId}, found: ${!!childObj}, source: ${!!childObj?.source}`);
|
||||||
|
|
||||||
|
mg.childRegistrationUtils.registerChild(
|
||||||
|
childObj.source,
|
||||||
|
msg.positionVsParent
|
||||||
|
);
|
||||||
|
|
||||||
|
mg.logger.debug(`Total machines after registration: ${Object.keys(mg.machines || {}).length}`);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
mg.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
|
|
||||||
|
case "setMode": {
|
||||||
|
const mode = msg.payload;
|
||||||
|
mg.setMode(mode);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "setMode":
|
|
||||||
mg.setMode(msg.payload);
|
case "setScaling": {
|
||||||
break;
|
const scaling = msg.payload;
|
||||||
case "setScaling":
|
mg.setScaling(scaling);
|
||||||
mg.setScaling(msg.payload);
|
|
||||||
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)) {
|
||||||
mg.logger.error(`Invalid demand value: ${msg.payload}`);
|
return mg.logger.error(`Invalid demand value: ${Qd}`);
|
||||||
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 (error) {
|
} catch (e) {
|
||||||
mg.logger.error(`Failed to process Qd: ${error.message}`);
|
mg.logger.error(`Demand handling failed: ${e.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;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
done();
|
||||||
mg.logger.error(`Input handler failure: ${error.message}`);
|
|
||||||
}
|
|
||||||
if (typeof done === 'function') done();
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -270,7 +250,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);
|
||||||
if (typeof done === 'function') done();
|
done();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,7 @@
|
|||||||
//load local dependencies
|
//load local dependencies
|
||||||
const EventEmitter = require("events");
|
const EventEmitter = require("events");
|
||||||
const {logger,configUtils,configManager, MeasurementContainer, interpolation , childRegistrationUtils, convert} = require('generalFunctions');
|
const {logger,configUtils,configManager, MeasurementContainer, interpolation , childRegistrationUtils, 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 = {}) {
|
||||||
|
|
||||||
@@ -28,39 +10,12 @@ 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
|
||||||
@@ -85,9 +40,6 @@ 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.`);
|
||||||
@@ -123,7 +75,7 @@ class MachineGroup {
|
|||||||
Object.values(this.machines).forEach(machine => {
|
Object.values(this.machines).forEach(machine => {
|
||||||
const totals = { flow: { min: Infinity, max: 0 }, power: { min: Infinity, max: 0 } };
|
const totals = { flow: { min: Infinity, max: 0 }, power: { min: Infinity, max: 0 } };
|
||||||
//fetch min flow ever seen over all machines
|
//fetch min flow ever seen over all machines
|
||||||
Object.entries(machine.predictFlow.inputCurve).forEach(([pressure, xyCurve], index) => {
|
Object.entries(machine.predictFlow.inputCurve).forEach(([pressure, xyCurve], _index) => {
|
||||||
const minFlow = Math.min(...xyCurve.y);
|
const minFlow = Math.min(...xyCurve.y);
|
||||||
const maxFlow = Math.max(...xyCurve.y);
|
const maxFlow = Math.max(...xyCurve.y);
|
||||||
|
|
||||||
@@ -181,23 +133,15 @@ 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 actFlow = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow) || 0;
|
const actPower = machine.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
||||||
const actPower = this._readChildMeasurement(machine, "power", "predicted", "atequipment", 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}`);
|
||||||
|
|
||||||
@@ -246,16 +190,16 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handlePressureChange() {
|
handlePressureChange() {
|
||||||
this.logger.debug("Pressure change detected.");
|
this.logger.info("---------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>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._writeMeasurement("flow", "predicted", "atequipment", flow.act, this.unitPolicy.canonical.flow);
|
this.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).value(flow.act);
|
||||||
this._writeMeasurement("power", "predicted", "atequipment", power.act, this.unitPolicy.canonical.power);
|
this.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(power.act);
|
||||||
|
|
||||||
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
|
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
|
||||||
const efficiency = this.measurements.type("efficiency").variant("predicted").position("atequipment").getCurrentValue();
|
const efficiency = this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
||||||
this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency);
|
this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -291,13 +235,11 @@ 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;
|
||||||
const measuredFlow = this._readChildMeasurement(machine, "flow", "measured", "downstream", this.unitPolicy.canonical.flow);
|
if(machine.measurements.type("flow").variant("measured").position(POSITIONS.DOWNSTREAM).getCurrentValue()){
|
||||||
const predictedFlow = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow);
|
flow = machine.measurements.type("flow").variant("measured").position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
||||||
if (Number.isFinite(measuredFlow) && measuredFlow !== 0) {
|
|
||||||
flow = measuredFlow;
|
|
||||||
}
|
}
|
||||||
else if (Number.isFinite(predictedFlow) && predictedFlow !== 0) {
|
else if(machine.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).getCurrentValue()){
|
||||||
flow = predictedFlow;
|
flow = machine.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
||||||
}
|
}
|
||||||
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");
|
||||||
@@ -322,7 +264,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
|
||||||
@@ -371,71 +313,42 @@ 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;
|
||||||
|
|
||||||
// Sum normalized CoG for the combination
|
// Calculate the total CoG for the current combination
|
||||||
combination.forEach(machineId => {
|
combination.forEach(machineId => { totalCoG += ( Math.round(this.machines[machineId].NCog * 100 ) /100 ) ; });
|
||||||
totalCoG += Math.round((this.machines[machineId].NCog || 0) * 100) / 100;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Initial CoG-based distribution
|
// Calculate the total power for the current combination
|
||||||
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 {
|
||||||
flow = ((this.machines[machineId].NCog || 0) / totalCoG) * Qd;
|
// Normal CoG-based distribution
|
||||||
|
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}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
flowDistribution.push({ machineId, 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;
|
totalFlow += flow;
|
||||||
totalPower += this.machines[machineId].inputFlowCalcPower(flow);
|
totalPower += this.machines[machineId].inputFlowCalcPower(flow);
|
||||||
|
flowDistribution.push({ machineId: machineId,flow: 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)}`);
|
||||||
@@ -449,177 +362,6 @@ 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
let totalPower = 0;
|
|
||||||
totalFlow = 0;
|
|
||||||
flowDistribution.forEach(entry => {
|
|
||||||
const info = pumpInfos.find(info => info.id === entry.machineId);
|
|
||||||
const flow = Math.min(info.maxFlow, Math.max(info.minFlow, entry.flow));
|
|
||||||
entry.flow = flow;
|
|
||||||
totalFlow += flow;
|
|
||||||
totalPower += info.machine.inputFlowCalcPower(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] || [];
|
||||||
@@ -647,10 +389,10 @@ class MachineGroup {
|
|||||||
try{
|
try{
|
||||||
//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: this._readChildMeasurement(machine, "pressure", "measured", "downstream", this.unitPolicy.canonical.pressure),
|
downstream: machine.measurements.type("pressure").variant("measured").position(POSITIONS.DOWNSTREAM).getCurrentValue(),
|
||||||
upstream: this._readChildMeasurement(machine, "pressure", "measured", "upstream", this.unitPolicy.canonical.pressure)
|
upstream: machine.measurements.type("pressure").variant("measured").position(POSITIONS.UPSTREAM).getCurrentValue()
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -660,12 +402,12 @@ class MachineGroup {
|
|||||||
this.logger.debug(`Max downstream pressure: ${maxDownstream}, Min upstream pressure: ${minUpstream}`);
|
this.logger.debug(`Max downstream pressure: ${maxDownstream}, Min upstream pressure: ${minUpstream}`);
|
||||||
|
|
||||||
//set the pressures
|
//set the pressures
|
||||||
Object.entries(this.machines).forEach(([machineId, machine]) => {
|
Object.entries(this.machines).forEach(([_machineId, machine]) => {
|
||||||
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
|
||||||
this._writeChildMeasurement(machine, "pressure", "measured", "downstream", maxDownstream, this.unitPolicy.canonical.pressure);
|
machine.measurements.type("pressure").variant("measured").position(POSITIONS.DOWNSTREAM).value(maxDownstream);
|
||||||
this._writeChildMeasurement(machine, "pressure", "measured", "upstream", minUpstream, this.unitPolicy.canonical.pressure);
|
machine.measurements.type("pressure").variant("measured").position(POSITIONS.UPSTREAM).value(minUpstream);
|
||||||
|
|
||||||
// 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
|
||||||
@@ -698,26 +440,7 @@ 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 `);
|
||||||
@@ -728,10 +451,10 @@ 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._writeMeasurement("power", "predicted", "atequipment", bestResult.bestPower, this.unitPolicy.canonical.power);
|
this.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(bestResult.bestPower);
|
||||||
this._writeMeasurement("flow", "predicted", "atequipment", bestResult.bestFlow, this.unitPolicy.canonical.flow);
|
this.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).value(bestResult.bestFlow);
|
||||||
this.measurements.type("efficiency").variant("predicted").position("atequipment").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("atequipment").value(bestResult.bestCog);
|
this.measurements.type("Ncog").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(bestResult.bestCog);
|
||||||
|
|
||||||
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
|
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
|
||||||
// Find the flow for this machine in the best combination
|
// Find the flow for this machine in the best combination
|
||||||
@@ -746,16 +469,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", flow);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(machineStates[machineId] === "operational" && flow > 0 ){
|
if(machineStates[machineId] === "operational" && flow > 0 ){
|
||||||
await machine.handleInput("parent", "flowmovement", flow);
|
await machine.handleInput("parent", "flowMovement", flow);
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -767,10 +490,10 @@ 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(){
|
||||||
// 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: this._readChildMeasurement(machine, "pressure", "measured", "downstream", this.unitPolicy.canonical.pressure),
|
downstream: machine.measurements.type("pressure").variant("measured").position(POSITIONS.DOWNSTREAM).getCurrentValue(),
|
||||||
upstream: this._readChildMeasurement(machine, "pressure", "measured", "upstream", this.unitPolicy.canonical.pressure)
|
upstream: machine.measurements.type("pressure").variant("measured").position(POSITIONS.UPSTREAM).getCurrentValue()
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -781,8 +504,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)){
|
||||||
this._writeChildMeasurement(machine, "pressure", "measured", "downstream", maxDownstream, this.unitPolicy.canonical.pressure);
|
machine.measurements.type("pressure").variant("measured").position(POSITIONS.DOWNSTREAM).value(maxDownstream);
|
||||||
this._writeChildMeasurement(machine, "pressure", "measured", "upstream", minUpstream, this.unitPolicy.canonical.pressure);
|
machine.measurements.type("pressure").variant("measured").position(POSITIONS.UPSTREAM).value(minUpstream);
|
||||||
// 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}`);
|
||||||
@@ -826,9 +549,9 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
filterOutUnavailableMachines(list) {
|
filterOutUnavailableMachines(list) {
|
||||||
const newList = list.filter(({ id, 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);
|
||||||
});
|
});
|
||||||
@@ -841,7 +564,7 @@ class MachineGroup {
|
|||||||
let lowestEfficiency = Infinity;
|
let lowestEfficiency = Infinity;
|
||||||
|
|
||||||
// Calculate the average efficiency of all machines -> peak is the average of them all
|
// Calculate the average efficiency of all machines -> peak is the average of them all
|
||||||
Object.entries(machines).forEach(([machineId, machine]) => {
|
Object.entries(machines).forEach(([_machineId, machine]) => {
|
||||||
cumEfficiency += machine.cog;
|
cumEfficiency += machine.cog;
|
||||||
if(machine.cog < lowestEfficiency){
|
if(machine.cog < lowestEfficiency){
|
||||||
lowestEfficiency = machine.cog;
|
lowestEfficiency = machine.cog;
|
||||||
@@ -856,7 +579,7 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//move machines assuming equal control in flow and a priority list
|
//move machines assuming equal control in flow and a priority list
|
||||||
async equalFlowControl(Qd, powerCap = Infinity, priorityList = null) {
|
async equalFlowControl(Qd, _powerCap = Infinity, priorityList = null) {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
// equalize pressure across all machines
|
// equalize pressure across all machines
|
||||||
@@ -911,7 +634,7 @@ class MachineGroup {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case (Qd > activeTotals.flow.max):
|
case (Qd > activeTotals.flow.max): {
|
||||||
// Case 2: Demand is above the maximum available flow.
|
// Case 2: Demand is above the maximum available flow.
|
||||||
// Start the non-active machine with the highest priority and distribute Qd over all available machines.
|
// Start the non-active machine with the highest priority and distribute Qd over all available machines.
|
||||||
let i = 1;
|
let i = 1;
|
||||||
@@ -931,9 +654,10 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
default:
|
default: {
|
||||||
// Default case: Demand is within the active range.
|
// Default case: Demand is within the active range.
|
||||||
const countActiveMachines = machinesInPriorityOrder.filter(({ id }) => this.isMachineActive(id)).length;
|
const countActiveMachines = machinesInPriorityOrder.filter(({ id }) => this.isMachineActive(id)).length;
|
||||||
|
|
||||||
@@ -948,6 +672,7 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Log information about flow distribution
|
// Log information about flow distribution
|
||||||
const debugInfo = flowDistribution
|
const debugInfo = flowDistribution
|
||||||
@@ -958,10 +683,10 @@ 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._writeMeasurement("power", "predicted", "atequipment", totalPower, this.unitPolicy.canonical.power);
|
this.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalPower);
|
||||||
this._writeMeasurement("flow", "predicted", "atequipment", totalFlow, this.unitPolicy.canonical.flow);
|
this.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).value(totalFlow);
|
||||||
this.measurements.type("efficiency").variant("predicted").position("atequipment").value(totalFlow / totalPower);
|
this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalFlow / totalPower);
|
||||||
this.measurements.type("Ncog").variant("predicted").position("atequipment").value(totalCog);
|
this.measurements.type("Ncog").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalCog);
|
||||||
|
|
||||||
this.logger.debug(`Flow distribution: ${JSON.stringify(flowDistribution)}`);
|
this.logger.debug(`Flow distribution: ${JSON.stringify(flowDistribution)}`);
|
||||||
// Apply the flow distribution to machines
|
// Apply the flow distribution to machines
|
||||||
@@ -971,13 +696,13 @@ 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");
|
||||||
}
|
}
|
||||||
else if (currentState === "operational" && flow > 0) {
|
else if (currentState === "operational" && flow > 0) {
|
||||||
await machine.handleInput("parent", "flowmovement", flow);
|
await machine.handleInput("parent", "flowMovement", flow);
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -993,13 +718,13 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
//capp input to 100
|
//capp input to 100
|
||||||
input > 100 ? input = 100 : input = input;
|
if (input > 100) { input = 100; }
|
||||||
|
|
||||||
const numOfMachines = Object.keys(this.machines).length;
|
const numOfMachines = Object.keys(this.machines).length;
|
||||||
const procentTotal = numOfMachines * input;
|
const procentTotal = numOfMachines * input;
|
||||||
@@ -1013,7 +738,7 @@ class MachineGroup {
|
|||||||
if(machinesNeeded > machinesActive){
|
if(machinesNeeded > machinesActive){
|
||||||
|
|
||||||
//start extra machine and put all active machines at min control
|
//start extra machine and put all active machines at min control
|
||||||
machinesInPriorityOrder.forEach(({ id, machine }, index) => {
|
machinesInPriorityOrder.forEach(({ id }, index) => {
|
||||||
if(index < machinesNeeded){
|
if(index < machinesNeeded){
|
||||||
ctrlDistribution.push({machineId : id, ctrl : 0});
|
ctrlDistribution.push({machineId : id, ctrl : 0});
|
||||||
}
|
}
|
||||||
@@ -1022,7 +747,7 @@ class MachineGroup {
|
|||||||
|
|
||||||
if(machinesNeeded < machinesActive){
|
if(machinesNeeded < machinesActive){
|
||||||
|
|
||||||
machinesInPriorityOrder.forEach(({ id, machine }, index) => {
|
machinesInPriorityOrder.forEach(({ id }, index) => {
|
||||||
if(this.isMachineActive(id)){
|
if(this.isMachineActive(id)){
|
||||||
if(index < machinesNeeded){
|
if(index < machinesNeeded){
|
||||||
ctrlDistribution.push({machineId : id, ctrl : 100});
|
ctrlDistribution.push({machineId : id, ctrl : 100});
|
||||||
@@ -1039,7 +764,7 @@ class MachineGroup {
|
|||||||
// distribute input equally among active machines (0 - 100%)
|
// distribute input equally among active machines (0 - 100%)
|
||||||
const ctrlPerMachine = procentTotal / machinesActive;
|
const ctrlPerMachine = procentTotal / machinesActive;
|
||||||
|
|
||||||
machinesInPriorityOrder.forEach(({ id, machine }) => {
|
machinesInPriorityOrder.forEach(({ id }) => {
|
||||||
if (this.isMachineActive(id)) {
|
if (this.isMachineActive(id)) {
|
||||||
// ensure ctrl is capped between 0 and 100%
|
// ensure ctrl is capped between 0 and 100%
|
||||||
const ctrlValue = Math.max(0, Math.min(ctrlPerMachine, 100));
|
const ctrlValue = Math.max(0, Math.min(ctrlPerMachine, 100));
|
||||||
@@ -1057,13 +782,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);
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -1071,10 +796,10 @@ class MachineGroup {
|
|||||||
const totalFlow = [];
|
const totalFlow = [];
|
||||||
|
|
||||||
// fetch and store measurements
|
// fetch and store measurements
|
||||||
Object.entries(this.machines).forEach(([machineId, machine]) => {
|
Object.entries(this.machines).forEach(([_machineId, machine]) => {
|
||||||
|
|
||||||
const powerValue = this._readChildMeasurement(machine, "power", "predicted", "atequipment", this.unitPolicy.canonical.power);
|
const powerValue = machine.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
||||||
const flowValue = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow);
|
const flowValue = machine.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
||||||
|
|
||||||
if (powerValue !== null) {
|
if (powerValue !== null) {
|
||||||
totalPower.push(powerValue);
|
totalPower.push(powerValue);
|
||||||
@@ -1084,11 +809,11 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this._writeMeasurement("power", "predicted", "atequipment", totalPower.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.power);
|
this.measurements.type("power").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalPower.reduce((a, b) => a + b, 0));
|
||||||
this._writeMeasurement("flow", "predicted", "atequipment", totalFlow.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.flow);
|
this.measurements.type("flow").variant("predicted").position(POSITIONS.DOWNSTREAM).value(totalFlow.reduce((a, b) => a + b, 0));
|
||||||
|
|
||||||
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("atequipment").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));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1099,19 +824,13 @@ 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}`);
|
||||||
@@ -1124,12 +843,12 @@ class MachineGroup {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (demandQ < absoluteTotals.flow.min) {
|
if (demandQ < this.absoluteTotals.flow.min) {
|
||||||
this.logger.warn(`Flow demand ${demandQ} is below minimum possible flow ${absoluteTotals.flow.min}. Capping to minimum flow.`);
|
this.logger.warn(`Flow demand ${demandQ} is below minimum possible flow ${this.absoluteTotals.flow.min}. Capping to minimum flow.`);
|
||||||
demandQout = this.absoluteTotals.flow.min;
|
demandQout = this.absoluteTotals.flow.min;
|
||||||
} else if (demandQout > absoluteTotals.flow.max) {
|
} else if (demandQout > this.absoluteTotals.flow.max) {
|
||||||
this.logger.warn(`Flow demand ${demandQ} is above maximum possible flow ${absoluteTotals.flow.max}. Capping to maximum flow.`);
|
this.logger.warn(`Flow demand ${demandQ} is above maximum possible flow ${this.absoluteTotals.flow.max}. Capping to maximum flow.`);
|
||||||
demandQout = absoluteTotals.flow.max;
|
demandQout = this.absoluteTotals.flow.max;
|
||||||
}else if(demandQout <= 0){
|
}else if(demandQout <= 0){
|
||||||
this.logger.debug(`Turning machines off`);
|
this.logger.debug(`Turning machines off`);
|
||||||
demandQout = 0;
|
demandQout = 0;
|
||||||
@@ -1140,6 +859,7 @@ class MachineGroup {
|
|||||||
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`);
|
||||||
@@ -1157,6 +877,7 @@ class MachineGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Execute control based on mode
|
// Execute control based on mode
|
||||||
switch(mode) {
|
switch(mode) {
|
||||||
case "prioritycontrol":
|
case "prioritycontrol":
|
||||||
@@ -1185,117 +906,17 @@ 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("downstream").getCurrentValue();
|
const efficiency = this.measurements.type("efficiency").variant("predicted").position(POSITIONS.DOWNSTREAM).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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_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;
|
||||||
}
|
}
|
||||||
@@ -1306,12 +927,12 @@ class MachineGroup {
|
|||||||
const output = {};
|
const output = {};
|
||||||
|
|
||||||
//build the output object
|
//build the output object
|
||||||
Object.entries(this.measurements.measurements || {}).forEach(([type, variants]) => {
|
this.measurements.getTypes().forEach(type => {
|
||||||
Object.keys(variants || {}).forEach((variant) => {
|
this.measurements.getVariants(type).forEach(variant => {
|
||||||
const unit = this._outputUnitForType(type);
|
|
||||||
const downstreamVal = this._readMeasurement(type, variant, "downstream", unit);
|
const downstreamVal = this.measurements.type(type).variant(variant).position(POSITIONS.DOWNSTREAM).getCurrentValue();
|
||||||
const atEquipmentVal = this._readMeasurement(type, variant, "atequipment", unit);
|
const atEquipmentVal = this.measurements.type(type).variant(variant).position(POSITIONS.AT_EQUIPMENT).getCurrentValue();
|
||||||
const upstreamVal = this._readMeasurement(type, variant, "upstream", unit);
|
const upstreamVal = this.measurements.type(type).variant(variant).position(POSITIONS.UPSTREAM).getCurrentValue();
|
||||||
|
|
||||||
if (downstreamVal != null) {
|
if (downstreamVal != null) {
|
||||||
output[`downstream_${variant}_${type}`] = downstreamVal;
|
output[`downstream_${variant}_${type}`] = downstreamVal;
|
||||||
@@ -1320,16 +941,11 @@ class MachineGroup {
|
|||||||
output[`upstream_${variant}_${type}`] = upstreamVal;
|
output[`upstream_${variant}_${type}`] = upstreamVal;
|
||||||
}
|
}
|
||||||
if (atEquipmentVal != null) {
|
if (atEquipmentVal != null) {
|
||||||
output[`atequipment${variant}_${type}`] = atEquipmentVal;
|
output[`atEquipment_${variant}_${type}`] = atEquipmentVal;
|
||||||
}
|
}
|
||||||
if (downstreamVal != null && upstreamVal != null) {
|
if (downstreamVal != null && upstreamVal != null) {
|
||||||
const diff = this.measurements
|
const diffVal = this.measurements.type(type).variant(variant).difference().value;
|
||||||
.type(type)
|
output[`differential_${variant}_${type}`] = diffVal;
|
||||||
.variant(variant)
|
|
||||||
.difference({ from: 'downstream', to: 'upstream', unit });
|
|
||||||
if (diff?.value != null) {
|
|
||||||
output[`differential_${variant}_${type}`] = diff.value;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1351,7 +967,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');
|
||||||
@@ -1379,9 +995,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"],
|
||||||
@@ -1473,11 +1089,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, "downstream");
|
mg.childRegistrationUtils.registerChild(machine, POSITIONS.DOWNSTREAM);
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.keys(mg.machines).forEach(machineId => {
|
Object.keys(mg.machines).forEach(machineId => {
|
||||||
mg.machines[machineId].childRegistrationUtils.registerChild(pt1, "downstream");
|
mg.machines[machineId].childRegistrationUtils.registerChild(pt1, POSITIONS.DOWNSTREAM);
|
||||||
});
|
});
|
||||||
|
|
||||||
mg.setMode("prioritycontrol");
|
mg.setMode("prioritycontrol");
|
||||||
@@ -1489,7 +1105,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
|
||||||
|
|
||||||
@@ -1539,8 +1155,6 @@ async function makeMachines(){
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (require.main === module) {
|
|
||||||
makeMachines();
|
makeMachines();
|
||||||
}
|
|
||||||
|
|
||||||
//*/
|
//*/
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
# 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
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
const test = require('node:test');
|
|
||||||
const assert = require('node:assert/strict');
|
|
||||||
|
|
||||||
test('machineGroupControl module load smoke', () => {
|
|
||||||
assert.doesNotThrow(() => {
|
|
||||||
require('../../mgc.js');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
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