Compare commits

..

16 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
znetsixe
ac9d1b4fdd added test file 2025-09-23 15:12:01 +02:00
znetsixe
cbc0840f0c added testfile fixing bugs 2025-09-23 15:03:57 +02:00
znetsixe
c62071992d working on a stable version 2025-09-23 11:19:22 +02:00
znetsixe
ffab553f7e physicalPosition 1D update 2025-09-05 16:20:22 +02:00
znetsixe
078a0d80dc updated function for registration of machines 2025-09-04 17:07:18 +02:00
4 changed files with 965 additions and 254 deletions

View File

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

345
src/groupcontrol.test.js Normal file
View File

@@ -0,0 +1,345 @@
'use strict';
const MachineGroup = require('./specificClass');
const Machine = require('../../rotatingMachine/src/specificClass');
const Measurement = require('../../measurement/src/specificClass');
const baseCurve = 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 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' }
};
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function setPressure(pt, value) {
const retries = 6;
for (let attempt = 0; attempt < retries; attempt += 1) {
try {
pt.calculateInput(value);
return;
} catch (error) {
const message = error?.message || String(error);
if (!message.toLowerCase().includes('coolprop is still warming up')) {
throw error;
}
await sleep(50);
}
}
throw new Error(`Unable to update pressure to ${value} mbar; CoolProp did not initialise in time.`);
}
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function distortSeries(series = [], scale = 1, tilt = 0) {
if (!Array.isArray(series) || series.length === 0) {
return series;
}
const lastIndex = series.length - 1;
return series.map((value, index) => {
const gradient = lastIndex === 0 ? 0 : index / lastIndex - 0.5;
const distorted = value * scale * (1 + tilt * gradient);
return Number(Math.max(distorted, 0).toFixed(6));
});
}
function createSyntheticCurve(mods = {}) {
const { flowScale = 1, powerScale = 1, flowTilt = 0, powerTilt = 0 } = mods;
const curve = deepClone(baseCurve);
if (curve.nq) {
Object.values(curve.nq).forEach(set => {
set.y = distortSeries(set.y, flowScale, flowTilt);
});
}
if (curve.np) {
Object.values(curve.np).forEach(set => {
set.y = distortSeries(set.y, powerScale, powerTilt);
});
}
return curve;
}
function createMachineConfig(id, label) {
return {
general: { logging: { enabled: false, logLevel: 'error' }, name: label, id, unit: 'm3/h' },
functionality: { softwareType: 'machine', role: 'rotationaldevicecontroller' },
asset: { category: 'pump', type: 'centrifugal', model: 'hidrostal-h05k-s03r', supplier: 'hidrostal', machineCurve: baseCurve },
mode: {
current: 'auto',
allowedActions: {
auto: ['execsequence', 'execmovement', 'flowmovement', 'statuscheck'],
virtualControl: ['execmovement', 'statuscheck'],
fysicalControl: ['statuscheck']
},
allowedSources: {
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,28 +58,32 @@ class nodeClass {
} }
_updateNodeStatus() { _updateNodeStatus() {
//console.log('Updating node status...');
const mg = this.source; const mg = this.source;
const mode = mg.mode; const mode = mg.mode;
const scaling = mg.scaling; const scaling = mg.scaling;
const totalFlow =
Math.round( // Add safety checks for measurements
mg.measurements const totalFlow = mg.measurements
.type("flow") ?.type("flow")
.variant("predicted") ?.variant("predicted")
.position("downstream") ?.position("atequipment")
.getCurrentValue() * 1 ?.getCurrentValue('m3/h') || 0;
) / 1;
const totalPower = const totalPower = mg.measurements
Math.round( ?.type("power")
mg.measurements ?.variant("predicted")
.type("power") ?.position("atEquipment")
.variant("predicted") ?.getCurrentValue() || 0;
.position("upstream")
.getCurrentValue() * 1
) / 1;
// Calculate total capacity based on available machines // 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
if (!machine || !machine.state || typeof machine.state.getCurrentState !== 'function') {
console.warn(`Machine missing or invalid:`, machine?.config?.general?.id || 'unknown');
return false;
}
const state = machine.state.getCurrentState(); const state = machine.state.getCurrentState();
const mode = machine.currentMode; const mode = machine.currentMode;
return !( return !(
@@ -89,29 +93,27 @@ class nodeClass {
); );
}); });
const totalCapacity = Math.round(mg.dynamicTotals.flow.max * 1) / 1; const totalCapacity = Math.round((mg.dynamicTotals?.flow?.max || 0) * 1) / 1;
// Determine overall status based on available machines // Determine overall status based on available machines
const status = const status = availableMachines.length > 0
availableMachines.length > 0 ? `${availableMachines.length} machine(s) connected`
? `${availableMachines.length} machine(s) connected` : "No machines";
: "No machines";
let scalingSymbol = ""; let scalingSymbol = "";
switch (scaling.toLowerCase()) { switch ((scaling || "").toLowerCase()) {
case "absolute": case "absolute":
scalingSymbol = "Ⓐ"; // Clear symbol for Absolute mode scalingSymbol = "Ⓐ";
break; break;
case "normalized": case "normalized":
scalingSymbol = "Ⓝ"; // Clear symbol for Normalized mode scalingSymbol = "Ⓝ";
break; break;
default: default:
scalingSymbol = mode; scalingSymbol = mode || "";
break; break;
} }
// Generate status text in a single line const text = ` ${mode || 'Unknown'} | ${scalingSymbol}: 💨=${Math.round(totalFlow)}/${totalCapacity} | ⚡=${Math.round(totalPower)} | ${status}`;
const text = ` ${mode} | ${scalingSymbol}: 💨=${totalFlow}/${totalCapacity} | ⚡=${totalPower} | ${status}`;
return { return {
fill: availableMachines.length > 0 ? "green" : "red", fill: availableMachines.length > 0 ? "green" : "red",
@@ -179,8 +181,8 @@ class nodeClass {
*/ */
_tick() { _tick() {
const raw = this.source.getOutput(); const raw = this.source.getOutput();
const processMsg = this._output.formatMsg(raw, this.config, "process"); const processMsg = this._output.formatMsg(raw, this.source.config, "process");
const influxMsg = this._output.formatMsg(raw, this.config, "influxdb"); const influxMsg = this._output.formatMsg(raw, this.source.config, "influxdb");
// Send only updated outputs on ports 0 & 1 // Send only updated outputs on ports 0 & 1
this.node.send([processMsg, influxMsg]); this.node.send([processMsg, influxMsg]);
@@ -197,24 +199,36 @@ class nodeClass {
const RED = this.RED; const RED = this.RED;
switch (msg.topic) { switch (msg.topic) {
case "registerChild": case "registerChild":
//console.log(`Registering child in mgc: ${msg.payload}`); //console.log(`Registering child in mgc: ${msg.payload}`);
const childId = msg.payload; const childId = msg.payload;
const childObj = RED.nodes.getNode(childId); const childObj = RED.nodes.getNode(childId);
mg.childRegistrationUtils.registerChild(
childObj.source, // Debug: Check what we're getting
msg.positionVsParent //console.log(`Child object:`, childObj ? 'found' : 'NOT FOUND');
); //console.log(`Child source:`, childObj?.source ? 'exists' : 'MISSING');
break; if (childObj?.source) {
//console.log(`Child source type:`, childObj.source.constructor.name);
//console.log(`Child has state:`, !!childObj.source.state);
}
mg.childRegistrationUtils.registerChild(
childObj.source,
msg.positionVsParent
);
// Debug: Check machines after registration
//console.log(`Total machines after registration:`, Object.keys(mg.machines || {}).length);
break;
case "setMode": case "setMode":
const mode = msg.payload; const mode = msg.payload;
const source = "parent"; mg.setMode(mode);
mg.setMode(source, mode);
break; break;
case "setScaling": case "setScaling":
const scaling = msg.payload; const scaling = msg.payload;
mg.setScaling(scaling); mg.setScaling(scaling);
break; break;
case "Qd": case "Qd":

File diff suppressed because it is too large Load Diff