Compare commits

..

11 Commits

Author SHA1 Message Date
znetsixe
f4cb329597 updates 2025-11-25 15:10:36 +01:00
znetsixe
b49f0c3ed2 attempt to fix flow distribution 2025-11-22 21:09:38 +01:00
znetsixe
edcffade75 Added edge case for when 1 pump cant handle the scope 2025-11-20 22:28:49 +01:00
znetsixe
b6ffefc92b Lots of minor bug fixes to update on architecture choices 2025-11-13 19:39:32 +01:00
znetsixe
ed2cf4c23d fixed outputformats 2025-11-06 11:18:38 +01:00
znetsixe
e0526250c2 changed colours, description based on s88 2025-10-14 13:52:18 +02:00
znetsixe
426d45890f ok 2025-10-05 07:56:35 +02:00
znetsixe
8c59a921d5 syncing 2025-10-05 07:55:23 +02:00
Rene De ren
15501e8b1d updates from laptop 2025-10-03 15:33:37 +02:00
znetsixe
b4364094c6 Stable version of machinegroup control 2025-10-02 17:08:41 +02:00
znetsixe
a55c6bdbea fixed pressure updates from machines. Everything seems to be working again. 2025-09-23 15:50:40 +02:00
4 changed files with 862 additions and 683 deletions

View File

@@ -1,15 +1,12 @@
<!--
brabantse delta kleuren:
#eaf4f1
#86bbdd
#bad33b
#0c99d9
#a9daee
#0f52a5
#50a8d9
#cade63
#4f8582
#c4cce0
| S88-niveau | Primair (blokkleur) | Tekstkleur |
| ---------------------- | ------------------- | ---------- |
| **Area** | `#0f52a5` | wit |
| **Process Cell** | `#0c99d9` | wit |
| **Unit** | `#50a8d9` | zwart |
| **Equipment (Module)** | `#86bbdd` | zwart |
| **Control Module** | `#a9daee` | zwart |
-->
<script src="/machineGroupControl/menu.js"></script> <!-- Load the menu script for dynamic dropdowns -->
<script src="/machineGroupControl/configData.js"></script> <!-- Load the config script for node information -->
@@ -17,7 +14,7 @@
<script>
RED.nodes.registerType('machineGroupControl',{
category: "EVOLV",
color: "#eaf4f1",
color: "#50a8d9",
defaults: {
// Define default properties
name: { value: "" },
@@ -39,7 +36,7 @@
outputs:3,
inputLabels: ["Input"],
outputLabels: ["process", "dbase", "parent"],
icon: "font-awesome/fa-tachometer",
icon: "font-awesome/fa-cogs",
label: function () {
return this.positionIcon + " " + "machineGroup";

View File

@@ -1,524 +1,345 @@
const MachineGroup = require('./specificClass.js');
'use strict';
const MachineGroup = require('./specificClass');
const Machine = require('../../rotatingMachine/src/specificClass');
const Measurement = require('../../measurement/src/specificClass');
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
const baseCurve = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
function createBaseMachineConfig(machineNum, name, specs) {
return {
general: {
logging: { enabled: true, logLevel: "warn" },
name: name,
id: machineNum,
unit: "m3/h"
},
functionality: {
softwareType: "machine",
role: "rotationaldevicecontroller"
},
asset: {
category: "pump",
type: "centrifugal",
model: "hidrostal-h05k-s03r",
supplier: "hydrostal",
machineCurve: specs
},
mode: {
current: "auto",
allowedActions: {
auto: ["execSequence", "execMovement", "statusCheck"],
virtualControl: ["execMovement", "statusCheck"],
fysicalControl: ["statusCheck"]
},
allowedSources: {
auto: ["parent", "GUI"],
virtualControl: ["GUI"],
fysicalControl: ["fysical"]
}
},
sequences: {
startup: ["starting", "warmingup", "operational"],
shutdown: ["stopping", "coolingdown", "idle"],
emergencystop: ["emergencystop", "off"],
boot: ["idle", "starting", "warmingup", "operational"]
}
};
}
function createBaseMachineGroupConfig(name) {
return {
general: {
logging: { enabled: true, logLevel: "debug" },
name: name
},
functionality: {
softwareType: "machinegroup",
role: "groupcontroller"
},
scaling: {
current: "normalized"
},
mode: {
current: "optimalcontrol"
}
};
}
const ptConfig = {
general: {
logging: { enabled: true, logLevel: "debug" },
name: "testpt",
id: "0",
unit: "mbar",
},
functionality: {
softwareType: "measurement",
role: "sensor"
},
asset: {
category: "sensor",
type: "pressure",
model: "testmodel",
supplier: "vega"
},
scaling: {
absMin: 0,
absMax: 4000,
}
}
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},
movement:{speed:1000, mode:"staticspeed"},
time: { starting: 0, warmingup: 0, stopping: 0, coolingdown: 0, emergencystop: 0 },
movement: { speed: 1200, mode: 'staticspeed', maxSpeed: 1800 }
};
const ptConfig = {
general: { logging: { enabled: false, logLevel: 'error' }, name: 'synthetic-pt', id: 'pt-1', unit: 'mbar' },
functionality: {
softwareType: 'measurement',
role: 'sensor',
positionVsParent: 'downstream'
},
asset: { category: 'sensor', type: 'pressure', model: 'synthetic-pt', supplier: 'lab', unit: 'mbar' },
scaling: { absMin: 0, absMax: 4000 }
};
const scenarios = [
{
name: 'balanced_pair',
description: 'Two identical pumps validate equal-machine behaviour.',
machines: [
{ id: 'eq-1', label: 'equal-A', curveMods: { flowScale: 1, powerScale: 1 } },
{ id: 'eq-2', label: 'equal-B', curveMods: { flowScale: 1, powerScale: 1 } }
],
pressures: [900, 1300, 1700],
flowTargetsPercent: [0.1, 0.4, 0.7, 1],
flowMatchTolerance: 5,
priorityList: ['eq-1', 'eq-2']
},
{
name: 'mixed_trio',
description: 'High / mid / low efficiency pumps to stress unequal-machine behaviour.',
machines: [
{ id: 'hi', label: 'high-eff', curveMods: { flowScale: 1.25, powerScale: 0.82, flowTilt: 0.1, powerTilt: -0.05 } },
{ id: 'mid', label: 'mid-eff', curveMods: { flowScale: 1, powerScale: 1 } },
{ id: 'low', label: 'low-eff', curveMods: { flowScale: 0.7, powerScale: 1.35, flowTilt: -0.08, powerTilt: 0.15 } }
],
pressures: [800, 1200, 1600, 2000],
flowTargetsPercent: [0.1, 0.35, 0.7, 1],
flowMatchTolerance: 8,
priorityList: ['hi', 'mid', 'low']
}
];
function createGroupConfig(name) {
return {
general: { logging: { enabled: false, logLevel: 'error' }, name: `machinegroup-${name}` },
functionality: { softwareType: 'machinegroup', role: 'groupcontroller' },
scaling: { current: 'normalized' },
mode: { current: 'optimalcontrol' }
};
}
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function logMachineStates(mg, testName) {
console.log(`\n=== ${testName} ===`);
console.log(`scaling: ${mg.scaling}, mode: ${mg.mode}`);
console.log(`flow range: ${mg.dynamicTotals.flow.min.toFixed(2)} - ${mg.dynamicTotals.flow.max.toFixed(2)} m3/h`);
Object.entries(mg.machines).forEach(([id, machine]) => {
const state = machine.state.getCurrentState();
const flow = machine.measurements?.type("flow")?.variant("predicted")?.position("downstream")?.getCurrentValue() || 0;
const power = machine.measurements?.type("power")?.variant("predicted")?.position("upstream")?.getCurrentValue() || 0;
const position = machine.state?.getCurrentPosition();
console.log(`machine ${id}: state=${state}, position=${position.toFixed(2)}, flow=${flow.toFixed(2)}, power=${power.toFixed(2)}`);
});
const totalFlow = mg.measurements?.type("flow")?.variant("predicted")?.position("downstream")?.getCurrentValue() || 0;
const totalPower = mg.measurements?.type("power")?.variant("predicted")?.position("upstream")?.getCurrentValue() || 0;
console.log(`total: flow=${totalFlow.toFixed(2)}, power=${totalPower.toFixed(2)}`);
// ADD THIS RETURN STATEMENT - this is what was missing!
return {
totalFlow,
totalPower,
efficiency: totalPower > 0 ? totalFlow / totalPower : 0
};
}
async function testPriorityVsOptimalEfficiency(mg, pt1) {
const demandIncrement = 1; // Test every 1% for detailed comparison
console.log("\n🔬 PRIORITY vs OPTIMAL CONTROL EFFICIENCY COMPARISON");
console.log("=".repeat(80));
const results = [];
console.log("\n📊 Testing OPTIMAL CONTROL (every 10% for speed)...");
mg.setScaling("normalized");
mg.setMode("optimalcontrol");
// Test every 10% for speed and give machines time to start
for (let demand = 0; demand <= 100; demand += demandIncrement) {
try {
console.log(`\n🔄 Setting optimal demand to ${demand}%`);
await mg.handleInput("parent", demand);
pt1.calculateInput(1400);
const data = logMachineStates(mg, `optimal ${demand}%`);
results.push({
demand,
optimal: {
flow: data.totalFlow,
power: data.totalPower,
efficiency: data.efficiency
}
});
console.log(`✅ optimal ${demand}%: flow=${data.totalFlow.toFixed(2)}, power=${data.totalPower.toFixed(2)}, eff=${data.efficiency.toFixed(4)}`);
} catch (err) {
console.error(`❌ error at optimal ${demand}%:`, err.message);
}
}
console.log("\n📊 Testing PRIORITY CONTROL (every 10% for speed)...");
mg.setMode("prioritycontrol");
let resultIndex = 0;
for (let demand = 0; demand <= 100; demand += demandIncrement) {
try {
console.log(`\n🔄 Setting priority demand to ${demand}%`);
await mg.handleInput("parent", demand);
pt1.calculateInput(1400);
const data = logMachineStates(mg, `priority ${demand}%`);
// Add priority data to existing result
if (results[resultIndex]) {
results[resultIndex].priority = {
flow: data.totalFlow,
power: data.totalPower,
efficiency: data.efficiency
};
}
console.log(`✅ priority ${demand}%: flow=${data.totalFlow.toFixed(2)}, power=${data.totalPower.toFixed(2)}, eff=${data.efficiency.toFixed(4)}`);
resultIndex++;
} catch (err) {
console.error(`❌ error at priority ${demand}%:`, err.message);
resultIndex++;
}
}
// Generate comparison report
generateEfficiencyReport(results);
}
// Add this report generation function
function generateEfficiencyReport(results) {
console.log("\n" + "=".repeat(100));
console.log("📈 EFFICIENCY COMPARISON REPORT");
console.log("=".repeat(100));
// Filter complete results with actual data
const completeResults = results.filter(r =>
r.optimal && r.priority &&
r.optimal.power > 0 && r.priority.power > 0 &&
r.optimal.flow > 0 && r.priority.flow > 0
);
if (completeResults.length === 0) {
console.log("❌ No complete results with active machines to compare");
console.log("💡 This might indicate machines are not starting properly");
// Show what data we do have
console.log("\n🔍 DEBUGGING DATA:");
results.forEach(r => {
if (r.optimal || r.priority) {
console.log(`${r.demand}%: optimal=${r.optimal?.power || 'missing'}, priority=${r.priority?.power || 'missing'}`);
}
});
return;
}
console.log(`\n📊 Successfully analyzed ${completeResults.length} test points with active machines`);
// Calculate summary statistics
let totalPowerDiff = 0;
let totalEffDiff = 0;
let validComparisons = 0;
console.log("\n📋 DETAILED BREAKDOWN:");
console.log("Demand | Optimal Power | Priority Power | Power Diff | Optimal Eff | Priority Eff | Eff Diff");
console.log("-------|---------------|----------------|------------|-------------|--------------|----------");
completeResults.forEach(r => {
const powerDiff = r.priority.power - r.optimal.power;
const effDiff = r.priority.efficiency - r.optimal.efficiency;
totalPowerDiff += powerDiff;
totalEffDiff += effDiff;
validComparisons++;
console.log(
`${r.demand}% | ${r.optimal.power.toFixed(3).padStart(11)} | ${r.priority.power.toFixed(3).padStart(12)} | ` +
`${powerDiff.toFixed(3).padStart(8)} | ${r.optimal.efficiency.toFixed(4).padStart(9)} | ` +
`${r.priority.efficiency.toFixed(4).padStart(10)} | ${effDiff.toFixed(4).padStart(7)}`
);
});
if (validComparisons > 0) {
const avgPowerDiff = totalPowerDiff / validComparisons;
const avgEffDiff = totalEffDiff / validComparisons;
console.log("\n📊 SUMMARY:");
console.log(`Valid comparisons: ${validComparisons}`);
console.log(`Average power difference: ${avgPowerDiff.toFixed(3)} kW`);
console.log(`Average efficiency difference: ${avgEffDiff.toFixed(4)} m3/h per kW`);
console.log("\n💡 RECOMMENDATION:");
if (avgEffDiff > 0.001) {
console.log(`✅ Priority Control shows ${avgEffDiff.toFixed(4)} better efficiency on average`);
} else if (avgEffDiff < -0.001) {
console.log(`✅ Optimal Control shows ${Math.abs(avgEffDiff).toFixed(4)} better efficiency on average`);
} else {
console.log(`⚖️ Both control methods show similar efficiency`);
}
}
}
async function testNormalizedScaling(mg, pt1) {
console.log("\n🧪 testing normalized scaling (0-100%)...");
mg.setScaling("normalized");
//first set pressure:
pt1.inputValue = 1400;
//fetch ranges
const maxflow = mg.dynamicTotals.flow.max;
console.log(`max group flow capacity: ${maxflow.toFixed(2)} m3/h`);
const minFlow = mg.dynamicTotals.flow.min;
console.log(`min group flow capacity: ${minFlow.toFixed(2)} m3/h`);
const testPoints = [0, 10, 25, 50, 75, 90, 100];
for (const demand of testPoints) {
try {
console.log(`\n--- normalized demand: ${demand}% ---`);
await mg.handleInput("parent", demand);
logMachineStates(mg, `normalized ${demand}%`);
} catch (err) {
console.error(`❌ error at ${demand}%:`, err.message);
}
}
}
async function testAbsoluteScaling(mg, pt1) {
console.log("\n🧪 testing absolute scaling...");
mg.setScaling("absolute");
const absMin = mg.dynamicTotals.flow.min;
const absMax = mg.dynamicTotals.flow.max;
const testPoints = [
absMin,
absMin + 20,
(absMin + absMax) / 2,
absMax - 20,
absMax
];
for (const demand of testPoints) {
try {
console.log(`\n--- absolute demand: ${demand.toFixed(2)} m3/h ---`);
await mg.handleInput("parent", demand);
pt1.calculateInput(1400);
logMachineStates(mg, `absolute ${demand.toFixed(2)} m3/h`);
} catch (err) {
console.error(`❌ error at ${demand.toFixed(2)}:`, err.message);
}
}
}
async function testControlModes(mg, pt1) {
console.log("\n🧪 testing different control modes...");
const modes = ["optimalcontrol", "prioritycontrol", "prioritypercentagecontrol"];
const testDemand = 50; // 50% demand
mg.setScaling("normalized");
for (const mode of modes) {
try {
console.log(`\n--- testing ${mode} ---`);
mg.setMode(mode);
await mg.handleInput("parent", testDemand);
pt1.calculateInput(1400);
logMachineStates(mg, `${mode} at ${testDemand}%`);
} catch (err) {
console.error(`❌ error testing mode ${mode}:`, err.message);
}
}
}
async function testRampUpDown(mg, pt1) {
console.log("\n🧪 testing ramp up and down...");
mg.setScaling("normalized");
mg.setMode("optimalcontrol");
// Ramp up
console.log("\n--- ramp up test ---");
for (let demand = 0; demand <= 100; demand += 20) {
try {
console.log(`ramping up to ${demand}%`);
await mg.handleInput("parent", demand);
pt1.calculateInput(1400);
if (demand % 40 === 0) { // Log every other step
logMachineStates(mg, `ramp up ${demand}%`);
}
} catch (err) {
console.error(`❌ error ramping up to ${demand}%:`, err.message);
}
}
// Ramp down
console.log("\n--- ramp down test ---");
for (let demand = 100; demand >= 0; demand -= 20) {
try {
console.log(`ramping down to ${demand}%`);
await mg.handleInput("parent", demand);
pt1.calculateInput(1400);
if (demand % 40 === 0) { // Log every other step
logMachineStates(mg, `ramp down ${demand}%`);
}
} catch (err) {
console.error(`❌ error ramping down to ${demand}%:`, err.message);
}
}
}
async function testPressureResponse(mg, pt1) {
console.log("\n🧪 testing pressure response...");
mg.setScaling("normalized");
mg.setMode("optimalcontrol");
const pressures = [800, 1200, 1600, 2000];
const demand = 50;
for (const pressure of pressures) {
try {
console.log(`\n--- testing at ${pressure} mbar ---`);
pt1.calculateInput(pressure);
await mg.handleInput("parent", demand);
logMachineStates(mg, `${pressure} mbar, ${demand}%`);
} catch (err) {
console.error(`❌ error at pressure ${pressure}:`, err.message);
}
}
}
async function testEdgeCases(mg, pt1) {
console.log("\n🧪 testing edge cases...");
mg.setScaling("normalized");
mg.setMode("optimalcontrol");
const edgeCases = [
{ demand: -10, name: "negative demand" },
{ demand: 0, name: "zero demand" },
{ demand: 0.5, name: "fractional demand" },
{ demand: 110, name: "over 100%" },
{ demand: 999, name: "extreme demand" }
];
for (const testCase of edgeCases) {
try {
console.log(`\n--- testing ${testCase.name}: ${testCase.demand} ---`);
await mg.handleInput("parent", testCase.demand);
pt1.calculateInput(1400);
logMachineStates(mg, testCase.name);
} catch (err) {
console.error(`❌ error testing ${testCase.name}:`, err.message);
}
}
}
async function testPerformanceMetrics(mg, pt1) {
console.log("\n🧪 testing performance metrics...");
mg.setScaling("normalized");
mg.setMode("optimalcontrol");
const demands = [25, 50, 75];
const results = [];
for (const demand of demands) {
try {
const startTime = Date.now();
await mg.handleInput("parent", demand);
pt1.calculateInput(1400);
const endTime = Date.now();
const totalFlow = mg.measurements?.type("flow")?.variant("predicted")?.position("downstream")?.getCurrentValue() || 0;
const totalPower = mg.measurements?.type("power")?.variant("predicted")?.position("upstream")?.getCurrentValue() || 0;
const efficiency = totalFlow > 0 ? (totalFlow / totalPower).toFixed(3) : 0;
results.push({
demand,
flow: totalFlow.toFixed(2),
power: totalPower.toFixed(2),
efficiency,
responseTime: endTime - startTime
});
} catch (err) {
console.error(`❌ error testing performance at ${demand}%:`, err.message);
}
}
console.log("\n=== performance summary ===");
console.log("demand | flow | power | efficiency | response(ms)");
console.log("-------|--------|--------|-----------|---------");
results.forEach(r => {
console.log(`${r.demand}% | ${r.flow} | ${r.power} | ${r.efficiency} | ${r.responseTime}`);
});
}
async function runAllTests() {
console.log("🚀 starting comprehensive machinegroup tests...\n");
async function setPressure(pt, value) {
const retries = 6;
for (let attempt = 0; attempt < retries; attempt += 1) {
try {
// Setup
const machineGroupConfig = createBaseMachineGroupConfig("testmachinegroup");
const machineConfigs = {};
machineConfigs[1] = createBaseMachineConfig(1, "testmachine1", specs);
machineConfigs[2] = createBaseMachineConfig(2, "testmachine2", specs);
const mg = new MachineGroup(machineGroupConfig);
const pt1 = new Measurement(ptConfig);
const numofMachines = 2;
// Register machines
for (let i = 1; i <= numofMachines; i++) {
const machine = new Machine(machineConfigs[i],stateConfig);
mg.childRegistrationUtils.registerChild(machine, "downstream");
}
mg.machines[1].childRegistrationUtils.registerChild(pt1, "downstream");
mg.machines[2].childRegistrationUtils.registerChild(pt1, "downstream");
console.log(`✅ setup complete: ${Object.keys(mg.machines).length} machines registered`);
console.log(`flow range: ${mg.dynamicTotals.flow.min.toFixed(2)} - ${mg.dynamicTotals.flow.max.toFixed(2)} m3/h\n`);
// Run test suites
//await testPriorityVsOptimalEfficiency(mg, pt1);
await testNormalizedScaling(mg, pt1);
await testAbsoluteScaling(mg, pt1);
await testControlModes(mg, pt1);
await testRampUpDown(mg, pt1);
await testPressureResponse(mg, pt1);
await testEdgeCases(mg, pt1);
await testPerformanceMetrics(mg, pt1);
console.log("\n🎉 all tests completed successfully!");
} catch (err) {
console.error("💥 test suite failed:", err.message);
console.error("stack trace:", err.stack);
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.`);
}
// Run all tests
runAllTests();
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function distortSeries(series = [], scale = 1, tilt = 0) {
if (!Array.isArray(series) || series.length === 0) {
return series;
}
const lastIndex = series.length - 1;
return series.map((value, index) => {
const gradient = lastIndex === 0 ? 0 : index / lastIndex - 0.5;
const distorted = value * scale * (1 + tilt * gradient);
return Number(Math.max(distorted, 0).toFixed(6));
});
}
function createSyntheticCurve(mods = {}) {
const { flowScale = 1, powerScale = 1, flowTilt = 0, powerTilt = 0 } = mods;
const curve = deepClone(baseCurve);
if (curve.nq) {
Object.values(curve.nq).forEach(set => {
set.y = distortSeries(set.y, flowScale, flowTilt);
});
}
if (curve.np) {
Object.values(curve.np).forEach(set => {
set.y = distortSeries(set.y, powerScale, powerTilt);
});
}
return curve;
}
function createMachineConfig(id, label) {
return {
general: { logging: { enabled: false, logLevel: 'error' }, name: label, id, unit: 'm3/h' },
functionality: { softwareType: 'machine', role: 'rotationaldevicecontroller' },
asset: { category: 'pump', type: 'centrifugal', model: 'hidrostal-h05k-s03r', supplier: 'hidrostal', machineCurve: baseCurve },
mode: {
current: 'auto',
allowedActions: {
auto: ['execsequence', 'execmovement', 'flowmovement', 'statuscheck'],
virtualControl: ['execmovement', 'statuscheck'],
fysicalControl: ['statuscheck']
},
allowedSources: {
auto: ['parent', 'GUI'],
virtualControl: ['GUI'],
fysicalControl: ['fysical']
}
},
sequences: {
startup: ['starting', 'warmingup', 'operational'],
shutdown: ['stopping', 'coolingdown', 'idle'],
emergencystop: ['emergencystop', 'off'],
boot: ['idle', 'starting', 'warmingup', 'operational']
}
};
}
async function bootstrapScenarioMachines(scenario) {
const mg = new MachineGroup(createGroupConfig(scenario.name));
const pt = new Measurement(ptConfig);
for (const machineDef of scenario.machines) {
const machine = new Machine(createMachineConfig(machineDef.id, machineDef.label), stateConfig);
if (machineDef.curveMods) {
machine.updateCurve(createSyntheticCurve(machineDef.curveMods));
}
mg.childRegistrationUtils.registerChild(machine, 'downstream');
machine.childRegistrationUtils.registerChild(pt, 'downstream');
}
await sleep(25);
return { mg, pt };
}
function captureTotals(mg) {
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 {
pressure: row.pressure,
targetFlow: Number(row.targetFlow.toFixed(1)),
[`${MODE_LABELS.optimalcontrol}_Flow`]: Number(optimal.flow.toFixed(1)),
[`${MODE_LABELS.optimalcontrol}_Eff`]: Number(optimal.efficiency.toFixed(3)),
[`${MODE_LABELS.prioritycontrol}_Flow`]: Number(priority.flow.toFixed(1)),
[`${MODE_LABELS.prioritycontrol}_Eff`]: Number(priority.efficiency.toFixed(3)),
[`Δ${MODE_LABELS.prioritycontrol}-OPT_Eff`]: Number(
(priority.efficiency - optimal.efficiency).toFixed(3)
),
[`${MODE_LABELS.prioritypercentagecontrol}_Flow`]: Number(percentage.flow.toFixed(1)),
[`${MODE_LABELS.prioritypercentagecontrol}_Eff`]: Number(percentage.efficiency.toFixed(3)),
[`Δ${MODE_LABELS.prioritypercentagecontrol}-OPT_Eff`]: Number(
(percentage.efficiency - optimal.efficiency).toFixed(3)
)
};
});
}
function summarizeEfficiency(rows) {
const map = new Map();
rows.forEach(row => {
CONTROL_MODES.forEach(mode => {
const key = `${row.scenario}-${mode}`;
if (!map.has(key)) {
map.set(key, {
scenario: row.scenario,
mode,
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);
const dynamicTotals = mg.calcDynamicTotals();
const targets = computeAbsoluteTargets(dynamicTotals, scenario.flowTargetsPercent || [0, 0.5, 1]);
for (let idx = 0; idx < targets.length; idx += 1) {
const targetFlow = targets[idx];
const row = {
scenario: scenario.name,
pressure,
targetFlow,
modes: {}
};
for (const mode of CONTROL_MODES) {
const stats = await driveModeToFlow({
mg,
pt,
mode,
pressure,
targetFlow,
priorityOrder
});
row.modes[mode] = stats;
}
rows.push(row);
}
}
console.log(`Efficiency comparison table for scenario "${scenario.name}":`);
console.table(formatEfficiencyRows(rows));
return { rows };
}
async function run() {
const combinedRows = [];
for (const scenario of scenarios) {
const { rows } = await evaluateScenario(scenario);
combinedRows.push(...rows);
}
console.log('\nEfficiency summary by scenario and control mode:');
console.table(summarizeEfficiency(combinedRows));
console.log('\nAll machine group control tests completed successfully.');
}
run().catch(err => {
console.error('Machine group control test harness crashed:', err);
process.exitCode = 1;
});

View File

@@ -58,6 +58,7 @@ class nodeClass {
}
_updateNodeStatus() {
//console.log('Updating node status...');
const mg = this.source;
const mode = mg.mode;
const scaling = mg.scaling;
@@ -66,13 +67,13 @@ class nodeClass {
const totalFlow = mg.measurements
?.type("flow")
?.variant("predicted")
?.position("downstream")
?.getCurrentValue() || 0;
?.position("atequipment")
?.getCurrentValue('m3/h') || 0;
const totalPower = mg.measurements
?.type("power")
?.variant("predicted")
?.position("upstream")
?.position("atEquipment")
?.getCurrentValue() || 0;
// Calculate total capacity based on available machines with safety checks
@@ -180,8 +181,8 @@ class nodeClass {
*/
_tick() {
const raw = this.source.getOutput();
const processMsg = this._output.formatMsg(raw, this.config, "process");
const influxMsg = this._output.formatMsg(raw, this.config, "influxdb");
const processMsg = this._output.formatMsg(raw, this.source.config, "process");
const influxMsg = this._output.formatMsg(raw, this.source.config, "influxdb");
// Send only updated outputs on ports 0 & 1
this.node.send([processMsg, influxMsg]);
@@ -198,16 +199,16 @@ class nodeClass {
const RED = this.RED;
switch (msg.topic) {
case "registerChild":
console.log(`Registering child in mgc: ${msg.payload}`);
//console.log(`Registering child in mgc: ${msg.payload}`);
const childId = msg.payload;
const childObj = RED.nodes.getNode(childId);
// Debug: Check what we're getting
console.log(`Child object:`, childObj ? 'found' : 'NOT FOUND');
console.log(`Child source:`, childObj?.source ? 'exists' : 'MISSING');
//console.log(`Child object:`, childObj ? 'found' : 'NOT FOUND');
//console.log(`Child source:`, childObj?.source ? 'exists' : 'MISSING');
if (childObj?.source) {
console.log(`Child source type:`, childObj.source.constructor.name);
console.log(`Child has state:`, !!childObj.source.state);
//console.log(`Child source type:`, childObj.source.constructor.name);
//console.log(`Child has state:`, !!childObj.source.state);
}
mg.childRegistrationUtils.registerChild(
@@ -216,7 +217,7 @@ class nodeClass {
);
// Debug: Check machines after registration
console.log(`Total machines after registration:`, Object.keys(mg.machines || {}).length);
//console.log(`Total machines after registration:`, Object.keys(mg.machines || {}).length);
break;
case "setMode":

View File

@@ -1,17 +1,3 @@
/**
* @summary A class to interact and manipulate machines with a non-euclidian curve
* @description A class to interact and manipulate machines with a non-euclidian curve
* @module machineGroup
* @exports machineGroup
* @version 0.1.0
* @since 0.1.0
*
* Author:
* - Rene De Ren
* Email:
* - r.de.ren@brabantsedelta.nl
*/
//load local dependencies
const EventEmitter = require("events");
const {logger,configUtils,configManager, MeasurementContainer, interpolation , childRegistrationUtils} = require('generalFunctions');
@@ -29,7 +15,17 @@ class MachineGroup {
this.logger = new logger(this.config.general.logging.enabled,this.config.general.logging.logLevel, this.config.general.name);
// Initialize measurements
this.measurements = new MeasurementContainer();
this.measurements = new MeasurementContainer({
autoConvert: true,
windowSize: 50,
defaultUnits: {
pressure: 'mbar',
flow: 'l/s',
power: 'kW',
temperature: 'C'
}
});
this.interpolation = new interpolation();
// Machines and child data
@@ -50,26 +46,36 @@ class MachineGroup {
}
// when a child gets updated do something
handleChildChange() {
this.absoluteTotals = this.calcAbsoluteTotals();
//for reference and not to recalc these values continiously
this.dynamicTotals = this.calcDynamicTotals();
}
registerChild(child,softwareType) {
this.logger.debug('Setting up childs specific for this class');
const position = child.config.general.positionVsParent;
if(softwareType == "machine"){
// 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.handleChildChange();
/*
// Listen for changes in the child machine
child.emitter.on('stateChange', () => this.handleChildChange());
child.emitter.on('pressureChange', () => this.handlePressureChange());
child.emitter.on('ncogChange', () => this.handleChildChange());
*/
//listen for machine pressure changes
this.logger.debug(`Listening for pressure changes from machine ${child.config.general.id}`);
child.measurements.emitter.on("pressure.measured.differential", (eventData) => {
this.logger.debug(`Pressure update from ${child.config.general.id}: ${eventData.value} ${eventData.unit}`);
this.handlePressureChange();
});
child.measurements.emitter.on("pressure.measured.downstream", (eventData) => {
this.logger.debug(`Pressure update from ${child.config.general.id}: ${eventData.value} ${eventData.unit}`);
this.handlePressureChange();
});
child.measurements.emitter.on("flow.predicted.downstream", (eventData) => {
this.logger.debug(`Flow prediction update from ${child.config.general.id}: ${eventData.value} ${eventData.unit}`);
//later change to this.handleFlowPredictionChange();
this.handlePressureChange();
});
}
}
@@ -95,6 +101,7 @@ class MachineGroup {
if( maxPower > totals.power.max ){ totals.power.max = maxPower; }
});
//surplus machines for max flow and power
if( totals.flow.min < absoluteTotals.flow.min ){ absoluteTotals.flow.min = totals.flow.min; }
if( totals.power.min < absoluteTotals.power.min ){ absoluteTotals.power.min = totals.power.min; }
@@ -103,6 +110,29 @@ class MachineGroup {
});
if(absoluteTotals.flow.min === Infinity) {
this.logger.warn(`Flow min ${absoluteTotals.flow.min} is Infinity. Setting to 0.`);
absoluteTotals.flow.min = 0;
}
if(absoluteTotals.power.min === Infinity) {
this.logger.warn(`Power min ${absoluteTotals.power.min} is Infinity. Setting to 0.`);
absoluteTotals.power.min = 0;
}
if(absoluteTotals.flow.max === -Infinity) {
this.logger.warn(`Flow max ${absoluteTotals.flow.max} is -Infinity. Setting to 0.`);
absoluteTotals.flow.max = 0;
}
if(absoluteTotals.power.max === -Infinity) {
this.logger.warn(`Power max ${absoluteTotals.power.max} is -Infinity. Setting to 0.`);
absoluteTotals.power.max = 0;
}
// Place data in object for external use
this.absoluteTotals = absoluteTotals;
return absoluteTotals;
}
@@ -110,26 +140,47 @@ class MachineGroup {
//max and min current flow and power based on their actual pressure curve
calcDynamicTotals() {
const dynamicTotals = { flow: { min: Infinity, max: 0 }, power: { min: Infinity, max: 0 }, NCog : 0 };
const dynamicTotals = { flow: { min: Infinity, max: 0, act: 0 }, power: { min: Infinity, max: 0, act: 0 }, NCog : 0 };
this.logger.debug(`\n --------- Calculating dynamic totals for ${Object.keys(this.machines).length} machines. @ current pressure settings : ----------`);
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(`Current pressure settings: ${JSON.stringify(machine.predictFlow.currentF)}`);
//fetch min flow ever seen over all machines
const minFlow = machine.predictFlow.currentFxyYMin;
const maxFlow = machine.predictFlow.currentFxyYMax;
const minPower = machine.predictPower.currentFxyYMin;
const maxPower = machine.predictPower.currentFxyYMax;
const actFlow = machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue();
const actPower = machine.measurements.type("power").variant("predicted").position("atequipment").getCurrentValue();
this.logger.debug(`Machine ${machine.config.general.id} - Min Flow: ${minFlow}, Max Flow: ${maxFlow}, Min Power: ${minPower}, Max Power: ${maxPower}, NCog: ${machine.NCog}`);
if( minFlow < dynamicTotals.flow.min ){ dynamicTotals.flow.min = minFlow; }
if( minPower < dynamicTotals.power.min ){ dynamicTotals.power.min = minPower; }
dynamicTotals.flow.max += maxFlow;
dynamicTotals.power.max += maxPower;
dynamicTotals.flow.act += actFlow;
dynamicTotals.power.act += actPower;
//fetch total Normalized Cog over all machines
dynamicTotals.NCog += machine.NCog;
});
// Place data in object for external use
this.dynamicTotals = dynamicTotals;
return dynamicTotals;
}
@@ -159,10 +210,16 @@ class MachineGroup {
}
handlePressureChange() {
this.logger.info("Pressure change detected.");
this.calcDynamicTotals();
this.logger.info("---------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>Pressure change detected.");
// Recalculate totals
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.measurements.type("flow").variant("predicted").position("atequipment").value(flow.act);
this.measurements.type("power").variant("predicted").position("atequipment").value(power.act);
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("atequipment").getCurrentValue();
this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency);
}
@@ -201,8 +258,8 @@ class MachineGroup {
if(machine.measurements.type("flow").variant("measured").position("downstream").getCurrentValue()){
flow = machine.measurements.type("flow").variant("measured").position("downstream").getCurrentValue();
}
else if(machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue()){
flow = machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue();
else if(machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue()){
flow = machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue();
}
else{
this.logger.error("Dont perform calculation at all seeing that there is a machine working but we dont know the flow its producing");
@@ -225,10 +282,9 @@ class MachineGroup {
// Generate all possible subsets of machines (power set)
Object.keys(machines).forEach(machineId => {
//machineId = parseInt(machineId);
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
@@ -277,42 +333,71 @@ class MachineGroup {
calcBestCombination(combinations, Qd) {
let bestCombination = null;
//keep track of totals
let bestPower = Infinity;
let bestFlow = 0;
let bestCog = 0;
combinations.forEach(combination => {
let flowDistribution = []; // Stores the flow distribution for the best combination
combinations.forEach(combination => {
let flowDistribution = [];
let totalCoG = 0;
let totalPower = 0;
let totalFlow = 0;
// Calculate the total CoG for the current combination
combination.forEach(machineId => { totalCoG += ( Math.round(this.machines[machineId].NCog * 100 ) /100 ) ; });
// Calculate the total power for the current combination
// Sum normalized CoG for the combination
combination.forEach(machineId => {
let flow = 0;
// Prevent division by zero
if (totalCoG === 0) {
// Distribute flow equally among all pumps
flow = Qd / combination.length;
} else {
// Normal CoG-based distribution
flow = (this.machines[machineId].NCog / totalCoG) * Qd ;
this.logger.debug(`Machine Normalized CoG-based distribution ${machineId} flow: ${flow}`);
}
totalFlow += flow;
totalPower += this.machines[machineId].inputFlowCalcPower(flow);
flowDistribution.push({ machineId: machineId,flow: flow });
totalCoG += Math.round((this.machines[machineId].NCog || 0) * 100) / 100;
});
// Initial CoG-based distribution
combination.forEach(machineId => {
let flow = 0;
if (totalCoG === 0) {
flow = Qd / combination.length;
} else {
flow = ((this.machines[machineId].NCog || 0) / totalCoG) * Qd;
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;
totalPower += this.machines[machineId].inputFlowCalcPower(flow);
});
// Update the best combination if the current one is better
if (totalPower < bestPower) {
this.logger.debug(`New best combination found: ${totalPower} < ${bestPower}`);
this.logger.debug(`combination ${JSON.stringify(flowDistribution)}`);
@@ -326,8 +411,178 @@ class MachineGroup {
return { bestCombination, bestPower, bestFlow, bestCog };
}
// -------- Mode and Input Management -------- //
// 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 -------- //
isValidActionForMode(action, mode) {
const allowedActionsSet = this.config.mode.allowedActions[mode] || [];
return allowedActionsSet.has(action);
@@ -339,8 +594,18 @@ class MachineGroup {
this.logger.debug(`Scaling set to: ${scaling}`);
}
async abortActiveMovements(reason = "new demand") {
await Promise.all(Object.values(this.machines).map(async machine => {
this.logger.warn(`Aborting active movements for machine ${machine.config.general.id} due to: ${reason}`);
if (typeof machine.abortMovement === "function") {
await machine.abortMovement(reason);
}
}));
}
//handle input from parent / user / UI
async optimalControl(Qd, powerCap = Infinity) {
try{
//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
@@ -354,20 +619,25 @@ class MachineGroup {
const maxDownstream = Math.max(...pressures.map(p => p.downstream));
const minUpstream = Math.min(...pressures.map(p => p.upstream));
this.logger.debug(`Max downstream pressure: ${maxDownstream}, Min upstream pressure: ${minUpstream}`);
//set the pressures
Object.entries(this.machines).forEach(([machineId, machine]) => {
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
machine.measurements.type("pressure").variant("measured").position("downstream").value(maxDownstream);
machine.measurements.type("pressure").variant("measured").position("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
// we need to find a better way to do this but for now it works
machine.getMeasuredPressure();
}
});
//fetch dynamic totals
const dynamicTotals = this.dynamicTotals;
//update dynamic totals
const dynamicTotals = this.calcDynamicTotals();
const machineStates = Object.entries(this.machines).reduce((acc, [machineId, machine]) => {
acc[machineId] = machine.state.getCurrentState();
return acc;
@@ -389,48 +659,67 @@ class MachineGroup {
}
// fetch all valid combinations that meet expectations
const combinations = this.validPumpCombinations(this.machines, Qd, powerCap);
//
const bestResult = this.calcBestCombination(combinations, Qd);
const combinations = this.validPumpCombinations(this.machines, Qd, powerCap);
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){
this.logger.warn(`Demand: ${Qd.toFixed(2)} -> No valid combination found => not updating control `);
return;
}
const debugInfo = bestResult.bestCombination.map(({ machineId, flow }) => `${machineId}: ${flow.toFixed(2)} units`).join(" | ");
this.logger.debug(`Moving to demand: ${Qd.toFixed(2)} -> Pumps: [${debugInfo}] => Total Power: ${bestResult.bestPower.toFixed(2)}`);
//store the total delivered power
this.measurements.type("power").variant("predicted").position("upstream").value(bestResult.bestPower);
this.measurements.type("flow").variant("predicted").position("downstream").value(bestResult.bestFlow);
this.measurements.type("efficiency").variant("predicted").position("downstream").value(bestResult.bestFlow / bestResult.bestPower);
this.measurements.type("Ncog").variant("predicted").position("downstream").value(bestResult.bestCog);
this.measurements.type("power").variant("predicted").position("atequipment").value(bestResult.bestPower);
this.measurements.type("flow").variant("predicted").position("atequipment").value(bestResult.bestFlow);
this.measurements.type("efficiency").variant("predicted").position("atequipment").value(bestResult.bestFlow / bestResult.bestPower);
this.measurements.type("Ncog").variant("predicted").position("atequipment").value(bestResult.bestCog);
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
const pumpInfo = bestResult.bestCombination.find(item => item.machineId == machineId);
// Find the flow for this machine in the best combination
this.logger.debug(`Searching for machine ${machineId} with state ${machineStates[machineId]} in best combination.`);
const pumpInfo = bestResult.bestCombination.find(item => item.machineId == machineId);
let flow;
if(pumpInfo !== undefined){
flow = pumpInfo.flow;
} else {
this.logger.debug(`Machine ${machineId} not in best combination, setting flow to 0`);
this.logger.debug(`Machine ${machineId} not in best combination, setting flow control to 0`);
flow = 0;
}
if( (flow <= 0 ) && ( machineStates[machineId] === "operational" || machineStates[machineId] === "accelerating" || machineStates[machineId] === "decelerating" ) ){
await machine.handleInput("parent", "execSequence", "shutdown");
await machine.handleInput("parent", "execsequence", "shutdown");
}
else if(machineStates[machineId] === "idle" && flow > 0){
await machine.handleInput("parent", "execSequence", "startup");
if(machineStates[machineId] === "idle" && flow > 0){
await machine.handleInput("parent", "execsequence", "startup");
await machine.handleInput("parent", "flowmovement", flow);
}
else if(machineStates[machineId] === "operational" && flow > 0 ){
await machine.handleInput("parent", "flowMovement", flow);
if(machineStates[machineId] === "operational" && flow > 0 ){
await machine.handleInput("parent", "flowmovement", flow);
}
}));
}
catch(err){
this.logger.error(err);
@@ -492,7 +781,7 @@ class MachineGroup {
.map(id => ({ id, machine: this.machines[id] }));
} else {
machinesInPriorityOrder = Object.entries(this.machines)
.map(([id, machine]) => ({ id: parseInt(id), machine }))
.map(([id, machine]) => ({ id: id, machine }))
.sort((a, b) => a.id - b.id);
}
return machinesInPriorityOrder;
@@ -501,7 +790,7 @@ class MachineGroup {
filterOutUnavailableMachines(list) {
const newList = list.filter(({ id, machine }) => {
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);
});
@@ -538,14 +827,6 @@ class MachineGroup {
// Update dynamic totals
const dynamicTotals = this.calcDynamicTotals();
// Handle zero demand by shutting down all machines early exit
if (Qd <= 0) {
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execSequence", "shutdown"); }
}));
return;
}
// Cap flow demand to min/max possible values
Qd = this.capFlowDemand(Qd,dynamicTotals);
@@ -639,24 +920,26 @@ class MachineGroup {
this.logger.debug(`Priority control for demand: ${totalFlow.toFixed(2)} -> Active pumps: [${debugInfo}] => Total Power: ${totalPower.toFixed(2)}`);
// Store measurements
this.measurements.type("power").variant("predicted").position("upstream").value(totalPower);
this.measurements.type("flow").variant("predicted").position("downstream").value(totalFlow);
this.measurements.type("efficiency").variant("predicted").position("downstream").value(totalFlow / totalPower);
this.measurements.type("Ncog").variant("predicted").position("downstream").value(totalCog);
this.measurements.type("power").variant("predicted").position("atequipment").value(totalPower);
this.measurements.type("flow").variant("predicted").position("atequipment").value(totalFlow);
this.measurements.type("efficiency").variant("predicted").position("atequipment").value(totalFlow / totalPower);
this.measurements.type("Ncog").variant("predicted").position("atequipment").value(totalCog);
this.logger.debug(`Flow distribution: ${JSON.stringify(flowDistribution)}`);
// Apply the flow distribution to machines
await Promise.all(flowDistribution.map(async ({ machineId, flow }) => {
const machine = this.machines[machineId];
this.logger.debug(this.machines[machineId].state);
const currentState = this.machines[machineId].state.getCurrentState();
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) {
await machine.handleInput("parent", "execSequence", "startup");
await machine.handleInput("parent", "execsequence", "startup");
}
else if (currentState === "operational" && flow > 0) {
await machine.handleInput("parent", "flowMovement", flow);
await machine.handleInput("parent", "flowmovement", flow);
}
}));
}
@@ -672,7 +955,7 @@ class MachineGroup {
if(input < 0 ){
//turn all machines off
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;
}
@@ -736,13 +1019,13 @@ class MachineGroup {
const currentState = this.machines[machineId].state.getCurrentState();
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) {
await machine.handleInput("parent", "execSequence", "startup");
await machine.handleInput("parent", "execsequence", "startup");
}
else if (currentState === "operational" && ctrl > 0) {
await machine.handleInput("parent", "execMovement", ctrl);
await machine.handleInput("parent", "execmovement", ctrl);
}
}));
@@ -751,8 +1034,10 @@ class MachineGroup {
// fetch and store measurements
Object.entries(this.machines).forEach(([machineId, machine]) => {
const powerValue = machine.measurements.type("power").variant("predicted").position("upstream").getCurrentValue();
const flowValue = machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue();
const powerValue = machine.measurements.type("power").variant("predicted").position("atequipment").getCurrentValue();
const flowValue = machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue();
if (powerValue !== null) {
totalPower.push(powerValue);
}
@@ -761,10 +1046,11 @@ class MachineGroup {
}
});
this.measurements.type("power").variant("predicted").position("upstream").value(totalPower.reduce((a, b) => a + b, 0));
this.measurements.type("flow").variant("predicted").position("downstream").value(totalFlow.reduce((a, b) => a + b, 0));
this.measurements.type("power").variant("predicted").position("atequipment").value(totalPower.reduce((a, b) => a + b, 0));
this.measurements.type("flow").variant("predicted").position("atequipment").value(totalFlow.reduce((a, b) => a + b, 0));
if(totalPower.reduce((a, b) => a + b, 0) > 0){
this.measurements.type("efficiency").variant("predicted").position("downstream").value(totalFlow.reduce((a, b) => a + b, 0) / totalPower.reduce((a, b) => a + b, 0));
this.measurements.type("efficiency").variant("predicted").position("atequipment").value(totalFlow.reduce((a, b) => a + b, 0) / totalPower.reduce((a, b) => a + b, 0));
}
}
@@ -773,43 +1059,85 @@ class MachineGroup {
}
}
async handleInput(source, Qd, 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
await this.abortActiveMovements("new demand received");
const scaling = this.scaling;
const mode = this.mode;
let rawInput = Qd;
const dynamicTotals = this.calcDynamicTotals();
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}`);
switch (scaling) {
case "absolute":
// No scaling needed but cap range
if (Qd < this.absoluteTotals.flow.min) {
this.logger.warn(`Flow demand ${Qd} is below minimum possible flow ${this.absoluteTotals.flow.min}. Capping to minimum flow.`);
Qd = this.absoluteTotals.flow.min;
} else if (Qd > this.absoluteTotals.flow.max) {
this.logger.warn(`Flow demand ${Qd} is above maximum possible flow ${this.absoluteTotals.flow.max}. Capping to maximum flow.`);
Qd = this.absoluteTotals.flow.max;
if (isNaN(demandQ)) {
this.logger.warn(`Invalid absolute flow demand: ${demand}. Must be a number.`);
demandQout = 0;
return;
}
if (demandQ < absoluteTotals.flow.min) {
this.logger.warn(`Flow demand ${demandQ} is below minimum possible flow ${absoluteTotals.flow.min}. Capping to minimum flow.`);
demandQout = this.absoluteTotals.flow.min;
} else if (demandQout > absoluteTotals.flow.max) {
this.logger.warn(`Flow demand ${demandQ} is above maximum possible flow ${absoluteTotals.flow.max}. Capping to maximum flow.`);
demandQout = absoluteTotals.flow.max;
}else if(demandQout <= 0){
this.logger.debug(`Turning machines off`);
demandQout = 0;
//return early and turn all machines off
this.turnOffAllMachines();
return;
}
break;
case "normalized":
// Scale demand to 0-100% linear between min and max flow this is auto capped
Qd = this.interpolation.interpolate_lin_single_point(Qd, 0, 100, this.dynamicTotals.flow.min, this.dynamicTotals.flow.max);
this.logger.debug(`Normalizing flow demand: ${demandQ} with min: ${dynamicTotals.flow.min} and max: ${dynamicTotals.flow.max}`);
if(demand < 0){
this.logger.debug(`Turning machines off`);
demandQout = 0;
//return early and turn all machines off
this.turnOffAllMachines();
return;
}
else{
// Scale demand to 0-100% linear between min and max flow this is auto capped
demandQout = this.interpolation.interpolate_lin_single_point(demandQ, 0, 100, dynamicTotals.flow.min, dynamicTotals.flow.max );
this.logger.debug(`Normalized flow demand ${demandQ}% to: ${demandQout} Q units`);
}
break;
}
// Execute control based on mode
switch(mode) {
case "prioritycontrol":
await this.equalFlowControl(Qd,powerCap,priorityList);
this.logger.debug(`Calculating prio control. Input flow demand: ${demandQ} scaling : ${scaling} -> ${demandQout}`);
await this.equalFlowControl(demandQout,powerCap,priorityList);
break;
case "prioritypercentagecontrol":
this.logger.debug(`Calculating prio percentage control. Input flow demand: ${demandQ} scaling : ${scaling} -> ${demandQout}`);
if(scaling !== "normalized"){
this.logger.warn("Priority percentage control is only valid with normalized scaling.");
return;
}
await this.prioPercentageControl(rawInput,priorityList);
await this.prioPercentageControl(demandQout,priorityList);
break;
case "optimalcontrol":
await this.optimalControl(Qd,powerCap);
this.logger.debug(`Calculating optimal control. Input flow demand: ${demandQ} scaling : ${scaling} -> ${demandQout}`);
await this.optimalControl(demandQout,powerCap);
break;
default:
@@ -824,6 +1152,12 @@ class MachineGroup {
}
async turnOffAllMachines(){
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execsequence", "shutdown"); }
}));
}
setMode(mode) {
this.mode = mode;
}
@@ -838,6 +1172,7 @@ class MachineGroup {
this.measurements.getVariants(type).forEach(variant => {
const downstreamVal = this.measurements.type(type).variant(variant).position("downstream").getCurrentValue();
const atEquipmentVal = this.measurements.type(type).variant(variant).position("atequipment").getCurrentValue();
const upstreamVal = this.measurements.type(type).variant(variant).position("upstream").getCurrentValue();
if (downstreamVal != null) {
@@ -846,6 +1181,9 @@ class MachineGroup {
if (upstreamVal != null) {
output[`upstream_${variant}_${type}`] = upstreamVal;
}
if (atEquipmentVal != null) {
output[`atequipment${variant}_${type}`] = atEquipmentVal;
}
if (downstreamVal != null && upstreamVal != null) {
const diffVal = this.measurements.type(type).variant(variant).difference().value;
output[`differential_${variant}_${type}`] = diffVal;
@@ -869,17 +1207,17 @@ class MachineGroup {
}
module.exports = MachineGroup;
/*
const {coolprop} = require('generalFunctions');
const Machine = require('../../rotatingMachine/src/specificClass');
const Measurement = require('../../measurement/src/specificClass');
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
const { number } = require("../../generalFunctions/src/convert/lodash/lodash._objecttypes");
const { max } = require("mathjs");
function createBaseMachineConfig(machineNum, name,specs) {
return {
general: {
logging: { enabled: true, logLevel: "warn" },
logging: { enabled: true, logLevel: "debug" },
name: name,
id: machineNum,
unit: "m3/h"
@@ -898,9 +1236,9 @@ function createBaseMachineConfig(machineNum, name,specs) {
mode: {
current: "auto",
allowedActions: {
auto: ["execSequence", "execMovement", "statusCheck"],
virtualControl: ["execMovement", "statusCheck"],
fysicalControl: ["statusCheck"]
auto: ["execsequence", "execmovement", "statuscheck"],
virtualControl: ["execmovement", "statuscheck"],
fysicalControl: ["statuscheck"]
},
allowedSources: {
auto: ["parent", "GUI"],
@@ -917,6 +1255,23 @@ function createBaseMachineConfig(machineNum, name,specs) {
};
}
function createStateConfig(){
return {
time:{
starting: 1,
stopping: 1,
warmingup: 1,
coolingdown: 1,
emergencystop: 1
},
movement:{
mode:"dynspeed",
speed:100,
maxSpeed: 1000
}
}
};
function createBaseMachineGroupConfig(name) {
return {
general: {
@@ -937,9 +1292,13 @@ function createBaseMachineGroupConfig(name) {
}
const machineGroupConfig = createBaseMachineGroupConfig("testmachinegroup");
const stateConfigs = {};
const machineConfigs = {};
machineConfigs[1]= createBaseMachineConfig(1,"testmachine",specs);
machineConfigs[2] = createBaseMachineConfig(2,"testmachine2",specs);
stateConfigs[1] = createStateConfig();
stateConfigs[2] = createStateConfig();
machineConfigs[1]= createBaseMachineConfig("asdfkj;asdf","testmachine",specs);
machineConfigs[2] = createBaseMachineConfig("asdfkj;asdf2","testmachine2",specs);
const ptConfig = {
general: {
@@ -969,14 +1328,16 @@ async function makeMachines(){
const pt1 = new Measurement(ptConfig);
const numofMachines = 2;
for(let i = 1; i <= numofMachines; i++){
const machine = new Machine(machineConfigs[i]);
const machine = new Machine(machineConfigs[i],stateConfigs[i]);
//mg.machines[i] = machine;
mg.childRegistrationUtils.registerChild(machine, "downstream");
}
mg.machines[1].childRegistrationUtils.registerChild(pt1, "downstream");
mg.machines[2].childRegistrationUtils.registerChild(pt1, "downstream");
//mg.setMode("prioritycontrol");
Object.keys(mg.machines).forEach(machineId => {
mg.machines[machineId].childRegistrationUtils.registerChild(pt1, "downstream");
});
mg.setMode("prioritycontrol");
mg.setScaling("normalized");
const absMax = mg.dynamicTotals.flow.max;
@@ -985,14 +1346,13 @@ async function makeMachines(){
const percMax = 100;
try{
/*
for(let demand = mg.dynamicTotals.flow.min ; demand <= mg.dynamicTotals.flow.max ; demand += 2){
//set pressure
console.log("------------------------------------");
await mg.handleInput("parent",demand);
pt1.calculateInput(1400);
console.log("Waiting for 0.2 sec ");
//await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------");
@@ -1005,24 +1365,24 @@ async function makeMachines(){
await mg.handleInput("parent",demand);
pt1.calculateInput(1400);
console.log("Waiting for 0.2 sec ");
//await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------");
}
//*/
/*
for(let demand = 0 ; demand <= 100 ; demand += 1){
//*//*
for(let demand = 0 ; demand <= 50 ; demand += 1){
//set pressure
console.log(`processing demand of ${demand}`);
console.log(`TESTING: processing demand of ${demand}`);
await mg.handleInput("parent",demand);
console.log(mg.machines[1].state.getCurrentState());
console.log(mg.machines[2].state.getCurrentState());
Object.keys(mg.machines).forEach(machineId => {
console.log(mg.machines[machineId].state.getCurrentState());
});
console.log(`updating pressure to 1400 mbar`);
pt1.calculateInput(1400);
console.log("Waiting for 0.2 sec ");
//await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------");
}
@@ -1038,4 +1398,4 @@ async function makeMachines(){
makeMachines();
//*/
//*/