Compare commits

..

3 Commits

Author SHA1 Message Date
znetsixe
d55f401ab3 fix: production hardening — unit mismatch, safety guards, marginal-cost refinement
- Fix flowmovement unit mismatch: MGC computed flow in canonical (m³/s)
  but rotatingMachine expects output units (m³/h). All flowmovement calls
  now convert via _canonicalToOutputFlow(). Without this fix, every pump
  stayed at minimum flow regardless of demand.
- Fix absolute scaling: demandQout vs demandQ comparison bug, reorder
  conditions so <= 0 is checked first, add else branch for valid demand.
- Fix empty Qd <= 0 block: now calls turnOffAllMachines().
- Add empty-machines guards on optimalControl and equalizePressure.
- Add null fallback (|| 0) on pressure measurement reads.
- Fix division-by-zero in calcRelativeDistanceFromPeak.
- Fix missing flowmovement after startup in equalFlowControl.
- Add marginal-cost refinement loop in BEP-Gravitation: after slope-based
  redistribution, iteratively shifts flow from highest actual dP/dQ to
  lowest using real power evaluations. Closes gap to brute-force optimum
  from 2.1% to <0.1% without affecting combination selection stability.
- Add NCog distribution comparison tests and brute-force power table test.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 13:40:45 +02:00
znetsixe
ffb2072baa Merge commit '85797b5' into HEAD
# Conflicts:
#	src/nodeClass.js
#	src/specificClass.js
2026-03-31 18:17:41 +02:00
Rene De Ren
85797b5b8b Align machineGroupControl with current architecture 2026-03-12 16:43:29 +01:00
5 changed files with 929 additions and 193 deletions

View File

@@ -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 },
@@ -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>

View File

@@ -39,21 +39,9 @@ class nodeClass {
this.defaultConfig = cfgMgr.getConfig(this.name); this.defaultConfig = cfgMgr.getConfig(this.name);
const flowUnit = this._resolveUnitOrFallback(uiConfig.unit, 'volumeFlowRate', 'm3/h', 'flow'); 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();
} }
@@ -81,14 +69,14 @@ class nodeClass {
const mg = this.source; const mg = this.source;
const mode = mg.mode; const mode = mg.mode;
const scaling = mg.scaling; const scaling = mg.scaling;
// Add safety checks for measurements // Add safety checks for measurements
const totalFlow = mg.measurements const totalFlow = mg.measurements
?.type("flow") ?.type("flow")
?.variant("predicted") ?.variant("predicted")
?.position("atequipment") ?.position("atequipment")
?.getCurrentValue(mg?.unitPolicy?.output?.flow || 'm3/h') || 0; ?.getCurrentValue(mg?.unitPolicy?.output?.flow || 'm3/h') || 0;
const totalPower = mg.measurements const totalPower = mg.measurements
?.type("power") ?.type("power")
?.variant("predicted") ?.variant("predicted")
@@ -102,7 +90,7 @@ class nodeClass {
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;
} }
const state = machine.state.getCurrentState(); const state = machine.state.getCurrentState();
const mode = machine.currentMode; const mode = machine.currentMode;
return !( return !(
@@ -225,15 +213,27 @@ class nodeClass {
mg.logger.warn(`registerChild skipped: missing child/source for id=${childId}`); mg.logger.warn(`registerChild skipped: missing child/source for id=${childId}`);
break; break;
} }
mg.logger.debug(`Registering child: ${childId}, found: ${!!childObj}, source: ${!!childObj?.source}`);
mg.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent); mg.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
mg.logger.debug(`Total machines after registration: ${Object.keys(mg.machines || {}).length}`);
break; break;
} }
case "setMode":
mg.setMode(msg.payload); case "setMode": {
const mode = msg.payload;
mg.setMode(mode);
break; break;
case "setScaling": }
mg.setScaling(msg.payload);
case "setScaling": {
const scaling = msg.payload;
mg.setScaling(scaling);
break; break;
}
case "Qd": { case "Qd": {
const Qd = parseFloat(msg.payload); const Qd = parseFloat(msg.payload);
const sourceQd = "parent"; const sourceQd = "parent";
@@ -251,6 +251,7 @@ class nodeClass {
} }
break; break;
} }
default: default:
mg.logger.warn(`Unknown topic: ${msg.topic}`); mg.logger.warn(`Unknown topic: ${msg.topic}`);
break; break;

View File

@@ -1,6 +1,6 @@
//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, convert, POSITIONS} = require('generalFunctions');
const CANONICAL_UNITS = Object.freeze({ const CANONICAL_UNITS = Object.freeze({
pressure: 'Pa', pressure: 'Pa',
@@ -37,7 +37,7 @@ class MachineGroup {
// 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, autoConvert: true,
@@ -87,11 +87,11 @@ class MachineGroup {
// Prefer functionality-scoped position metadata; keep general fallback for legacy nodes. // Prefer functionality-scoped position metadata; keep general fallback for legacy nodes.
const position = child.config?.functionality?.positionVsParent || child.config?.general?.positionVsParent; 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.`);
//listen for machine pressure changes //listen for machine pressure changes
this.logger.debug(`Listening for pressure changes from machine ${child.config.general.id}`); this.logger.debug(`Listening for pressure changes from machine ${child.config.general.id}`);
@@ -119,11 +119,11 @@ class MachineGroup {
calcAbsoluteTotals() { calcAbsoluteTotals() {
const absoluteTotals = { flow: { min: Infinity, max: 0 }, power: { min: Infinity, max: 0 } }; const absoluteTotals = { flow: { min: Infinity, max: 0 }, power: { min: Infinity, max: 0 } };
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);
@@ -143,27 +143,27 @@ class MachineGroup {
if( totals.power.min < absoluteTotals.power.min ){ absoluteTotals.power.min = totals.power.min; } if( totals.power.min < absoluteTotals.power.min ){ absoluteTotals.power.min = totals.power.min; }
absoluteTotals.flow.max += totals.flow.max; absoluteTotals.flow.max += totals.flow.max;
absoluteTotals.power.max += totals.power.max; absoluteTotals.power.max += totals.power.max;
}); });
if(absoluteTotals.flow.min === Infinity) { if(absoluteTotals.flow.min === Infinity) {
this.logger.warn(`Flow min ${absoluteTotals.flow.min} is Infinity. Setting to 0.`); this.logger.warn(`Flow min ${absoluteTotals.flow.min} is Infinity. Setting to 0.`);
absoluteTotals.flow.min = 0; absoluteTotals.flow.min = 0;
} }
if(absoluteTotals.power.min === Infinity) { if(absoluteTotals.power.min === Infinity) {
this.logger.warn(`Power min ${absoluteTotals.power.min} is Infinity. Setting to 0.`); this.logger.warn(`Power min ${absoluteTotals.power.min} is Infinity. Setting to 0.`);
absoluteTotals.power.min = 0; absoluteTotals.power.min = 0;
} }
if(absoluteTotals.flow.max === -Infinity) { if(absoluteTotals.flow.max === -Infinity) {
this.logger.warn(`Flow max ${absoluteTotals.flow.max} is -Infinity. Setting to 0.`); this.logger.warn(`Flow max ${absoluteTotals.flow.max} is -Infinity. Setting to 0.`);
absoluteTotals.flow.max = 0; absoluteTotals.flow.max = 0;
} }
if(absoluteTotals.power.max === -Infinity) { if(absoluteTotals.power.max === -Infinity) {
this.logger.warn(`Power max ${absoluteTotals.power.max} is -Infinity. Setting to 0.`); this.logger.warn(`Power max ${absoluteTotals.power.max} is -Infinity. Setting to 0.`);
absoluteTotals.power.max = 0; absoluteTotals.power.max = 0;
} }
// Place data in object for external use // Place data in object for external use
@@ -173,13 +173,13 @@ class MachineGroup {
} }
//max and min current flow and power based on their actual pressure curve //max and min current flow and power based on their actual pressure curve
calcDynamicTotals() { calcDynamicTotals() {
const dynamicTotals = { flow: { min: Infinity, max: 0, act: 0 }, power: { min: Infinity, max: 0, act: 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 : ----------`); 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 //skip machines without valid curve
if(!machine.hasCurve){ if(!machine.hasCurve){
@@ -191,13 +191,13 @@ class MachineGroup {
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 = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow) || 0; const actFlow = this._readChildMeasurement(machine, "flow", "predicted", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow) || 0;
const actPower = this._readChildMeasurement(machine, "power", "predicted", "atequipment", this.unitPolicy.canonical.power) || 0; const actPower = this._readChildMeasurement(machine, "power", "predicted", POSITIONS.AT_EQUIPMENT, this.unitPolicy.canonical.power) || 0;
this.logger.debug(`Machine ${machine.config.general.id} - Min Flow: ${minFlow}, Max Flow: ${maxFlow}, Min Power: ${minPower}, Max Power: ${maxPower}, NCog: ${machine.NCog}`); this.logger.debug(`Machine ${machine.config.general.id} - Min Flow: ${minFlow}, Max Flow: ${maxFlow}, Min Power: ${minPower}, Max Power: ${maxPower}, NCog: ${machine.NCog}`);
@@ -211,7 +211,7 @@ class MachineGroup {
//fetch total Normalized Cog over all machines //fetch total Normalized Cog over all machines
dynamicTotals.NCog += machine.NCog; dynamicTotals.NCog += machine.NCog;
}); });
// Place data in object for external use // Place data in object for external use
@@ -227,19 +227,19 @@ class MachineGroup {
this.logger.debug(`Processing machine with id: ${id}`); this.logger.debug(`Processing machine with id: ${id}`);
if(this.isMachineActive(id)){ if(this.isMachineActive(id)){
//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;
totals.flow.min += minFlow; totals.flow.min += minFlow;
totals.flow.max += maxFlow; totals.flow.max += maxFlow;
totals.power.min += minPower; totals.power.min += minPower;
totals.power.max += maxPower; totals.power.max += maxPower;
totals.countActiveMachines++; totals.countActiveMachines++;
} }
}); });
return totals; return totals;
@@ -251,11 +251,11 @@ class MachineGroup {
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._writeMeasurement("flow", "predicted", POSITIONS.AT_EQUIPMENT, flow.act, this.unitPolicy.canonical.flow);
this._writeMeasurement("power", "predicted", "atequipment", power.act, this.unitPolicy.canonical.power); this._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, power.act, this.unitPolicy.canonical.power);
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines); const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
const efficiency = this.measurements.type("efficiency").variant("predicted").position("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);
} }
@@ -265,7 +265,7 @@ class MachineGroup {
calcRelativeDistanceFromPeak(currentEfficiency,maxEfficiency,minEfficiency){ calcRelativeDistanceFromPeak(currentEfficiency,maxEfficiency,minEfficiency){
let distance = 1; let distance = 1;
if(currentEfficiency != null){ if(currentEfficiency != null && maxEfficiency !== minEfficiency){
distance = this.interpolation.interpolate_lin_single_point(currentEfficiency,maxEfficiency, minEfficiency, 0, 1); distance = this.interpolation.interpolate_lin_single_point(currentEfficiency,maxEfficiency, minEfficiency, 0, 1);
} }
return distance; return distance;
@@ -274,11 +274,11 @@ class MachineGroup {
calcDistanceBEP(efficiency,maxEfficiency,minEfficiency){ calcDistanceBEP(efficiency,maxEfficiency,minEfficiency){
const absDistFromPeak = this.calcDistanceFromPeak(efficiency,maxEfficiency); const absDistFromPeak = this.calcDistanceFromPeak(efficiency,maxEfficiency);
const relDistFromPeak = this.calcRelativeDistanceFromPeak(efficiency,maxEfficiency,minEfficiency); const relDistFromPeak = this.calcRelativeDistanceFromPeak(efficiency,maxEfficiency,minEfficiency);
//store internally //store internally
this.absDistFromPeak = absDistFromPeak ; this.absDistFromPeak = absDistFromPeak ;
this.relDistFromPeak = relDistFromPeak; this.relDistFromPeak = relDistFromPeak;
return { absDistFromPeak: absDistFromPeak, relDistFromPeak: relDistFromPeak }; return { absDistFromPeak: absDistFromPeak, relDistFromPeak: relDistFromPeak };
} }
@@ -287,15 +287,15 @@ class MachineGroup {
const state = machine.state.getCurrentState(); const state = machine.state.getCurrentState();
const mode = machine.currentMode; const mode = machine.currentMode;
//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); const measuredFlow = this._readChildMeasurement(machine, "flow", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow);
const predictedFlow = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow); const predictedFlow = this._readChildMeasurement(machine, "flow", "predicted", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow);
if (Number.isFinite(measuredFlow) && measuredFlow !== 0) { if (Number.isFinite(measuredFlow) && measuredFlow !== 0) {
flow = measuredFlow; flow = measuredFlow;
} }
else if (Number.isFinite(predictedFlow) && predictedFlow !== 0) { else if (Number.isFinite(predictedFlow) && predictedFlow !== 0) {
flow = predictedFlow; flow = predictedFlow;
} }
@@ -304,7 +304,7 @@ class MachineGroup {
//abort the calculation //abort the calculation
return false; return false;
} }
//Qd is less because we allready have machines delivering flow on manual control //Qd is less because we allready have machines delivering flow on manual control
Qd = Qd - flow; Qd = Qd - flow;
} }
@@ -317,28 +317,28 @@ class MachineGroup {
// adjust demand flow when there are machines being controlled by a manual source // adjust demand flow when there are machines being controlled by a manual source
Qd = this.checkSpecialCases(machines, Qd); Qd = this.checkSpecialCases(machines, Qd);
// Generate all possible subsets of machines (power set) // Generate all possible subsets of machines (power set)
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
if( state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validActionForMode){ if( state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validActionForMode){
return; return;
} }
// go through each machine and add it to the subsets // go through each machine and add it to the subsets
let newSubsets = subsets.map(set => [...set, machineId]); let newSubsets = subsets.map(set => [...set, machineId]);
subsets = subsets.concat(newSubsets); subsets = subsets.concat(newSubsets);
}); });
// Filter for non-empty subsets that can meet or exceed demand flow // Filter for non-empty subsets that can meet or exceed demand flow
const combinations = subsets.filter(subset => { const combinations = subsets.filter(subset => {
if (subset.length === 0) return false; if (subset.length === 0) return false;
// Calculate total and minimum flow for the subset in one pass // Calculate total and minimum flow for the subset in one pass
const { maxFlow, minFlow, maxPower } = subset.reduce( const { maxFlow, minFlow, maxPower } = subset.reduce(
(acc, machineId) => { (acc, machineId) => {
@@ -353,7 +353,7 @@ class MachineGroup {
maxPower: acc.maxPower + maxPower maxPower: acc.maxPower + maxPower
}; };
}, },
{ maxFlow: 0, minFlow: 0 , maxPower: 0 } { maxFlow: 0, minFlow: 0 , maxPower: 0 }
); );
@@ -365,7 +365,7 @@ class MachineGroup {
return false; return false;
} }
}); });
return combinations; return combinations;
} }
@@ -449,7 +449,7 @@ 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. // Estimate the local dP/dQ slopes around the BEP for the provided machine.
estimateSlopesAtBEP(machine, Q_BEP, delta = 1.0) { estimateSlopesAtBEP(machine, Q_BEP, delta = 1.0) {
const fallback = { const fallback = {
@@ -572,7 +572,7 @@ class MachineGroup {
const flowDistribution = pumpInfos.map(info => ({ const flowDistribution = pumpInfos.map(info => ({
machineId: info.id, machineId: info.id,
flow: Math.min(info.maxFlow, Math.max(info.minFlow, info.Q_BEP)) 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 let totalFlow = flowDistribution.reduce((sum, entry) => sum + entry.flow, 0); // Initial total flow
const delta = Qd - totalFlow; // Difference to target demand const delta = Qd - totalFlow; // Difference to target demand
@@ -580,14 +580,40 @@ class MachineGroup {
this.redistributeFlowBySlope(pumpInfos, flowDistribution, delta, directional); this.redistributeFlowBySlope(pumpInfos, flowDistribution, delta, directional);
} }
// Clamp and compute initial power
flowDistribution.forEach(entry => {
const info = pumpInfos.find(info => info.id === entry.machineId);
entry.flow = Math.min(info.maxFlow, Math.max(info.minFlow, entry.flow));
});
// Marginal-cost refinement: shift flow from most expensive to cheapest
// pump using actual power evaluations. Converges regardless of curve convexity.
const mcDelta = Math.max(1e-6, (Qd / pumpInfos.length) * 0.005);
for (let refineIter = 0; refineIter < 50; refineIter++) {
const mcEntries = flowDistribution.map(entry => {
const info = pumpInfos.find(i => i.id === entry.machineId);
const pNow = info.machine.inputFlowCalcPower(entry.flow);
const pUp = info.machine.inputFlowCalcPower(Math.min(info.maxFlow, entry.flow + mcDelta));
return { entry, info, mc: (pUp - pNow) / mcDelta };
});
let expensive = null, cheap = null;
for (const e of mcEntries) {
if (e.entry.flow > e.info.minFlow + mcDelta) { if (!expensive || e.mc > expensive.mc) expensive = e; }
if (e.entry.flow < e.info.maxFlow - mcDelta) { if (!cheap || e.mc < cheap.mc) cheap = e; }
}
if (!expensive || !cheap || expensive === cheap) break;
if (expensive.mc - cheap.mc < expensive.mc * 0.001) break;
const before = expensive.info.machine.inputFlowCalcPower(expensive.entry.flow) + cheap.info.machine.inputFlowCalcPower(cheap.entry.flow);
const after = expensive.info.machine.inputFlowCalcPower(expensive.entry.flow - mcDelta) + cheap.info.machine.inputFlowCalcPower(cheap.entry.flow + mcDelta);
if (after < before) { expensive.entry.flow -= mcDelta; cheap.entry.flow += mcDelta; } else { break; }
}
let totalPower = 0; let totalPower = 0;
totalFlow = 0; totalFlow = 0;
flowDistribution.forEach(entry => { flowDistribution.forEach(entry => {
const info = pumpInfos.find(info => info.id === entry.machineId); totalFlow += entry.flow;
const flow = Math.min(info.maxFlow, Math.max(info.minFlow, entry.flow)); const info = pumpInfos.find(i => i.id === entry.machineId);
entry.flow = flow; totalPower += info.machine.inputFlowCalcPower(entry.flow);
totalFlow += flow;
totalPower += info.machine.inputFlowCalcPower(flow);
}); });
const totalCog = pumpInfos.reduce((sum, info) => sum + info.NCog, 0); const totalCog = pumpInfos.reduce((sum, info) => sum + info.NCog, 0);
@@ -645,12 +671,17 @@ class MachineGroup {
async optimalControl(Qd, powerCap = Infinity) { async optimalControl(Qd, powerCap = Infinity) {
try{ try{
if (Object.keys(this.machines).length === 0) {
this.logger.warn("No machines registered. Cannot execute optimal control.");
return;
}
//we need to force the pressures of all machines to be equal to the highest pressure measured in the group //we need to force the pressures of all machines to be equal to the highest pressure measured in the group
// this is to ensure a correct evaluation of the flow and power consumption // this is to ensure a correct evaluation of the flow and power consumption
const pressures = Object.entries(this.machines).map(([machineId, machine]) => { const pressures = Object.entries(this.machines).map(([_machineId, machine]) => {
return { return {
downstream: this._readChildMeasurement(machine, "pressure", "measured", "downstream", this.unitPolicy.canonical.pressure), downstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.pressure) || 0,
upstream: this._readChildMeasurement(machine, "pressure", "measured", "upstream", this.unitPolicy.canonical.pressure) upstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, this.unitPolicy.canonical.pressure) || 0
}; };
}); });
@@ -660,19 +691,19 @@ 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); this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, maxDownstream, this.unitPolicy.canonical.pressure);
this._writeChildMeasurement(machine, "pressure", "measured", "upstream", minUpstream, this.unitPolicy.canonical.pressure); this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, minUpstream, this.unitPolicy.canonical.pressure);
// after updating the measurement directly we need to force the update of the value OLIFANT this is not so clear now in the code // after updating the measurement directly we need to force the update of the value OLIFANT this is not so clear now in the code
// we need to find a better way to do this but for now it works // we need to find a better way to do this but for now it works
machine.getMeasuredPressure(); machine.getMeasuredPressure();
} }
}); });
//fetch dynamic totals //fetch dynamic totals
const dynamicTotals = this.dynamicTotals; const dynamicTotals = this.dynamicTotals;
@@ -682,7 +713,9 @@ class MachineGroup {
}, {}); }, {});
if( Qd <= 0 ) { if( Qd <= 0 ) {
//if Qd is 0 turn all machines off and exit early this.logger.debug("Flow demand <= 0, turning all machines off.");
await this.turnOffAllMachines();
return;
} }
if( Qd < dynamicTotals.flow.min && Qd > 0 ){ if( Qd < dynamicTotals.flow.min && Qd > 0 ){
@@ -697,7 +730,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);
if (!combinations || combinations.length === 0) { if (!combinations || combinations.length === 0) {
this.logger.warn(`Demand: ${Qd.toFixed(2)} -> No valid combination found (empty set).`); this.logger.warn(`Demand: ${Qd.toFixed(2)} -> No valid combination found (empty set).`);
@@ -726,12 +759,12 @@ class MachineGroup {
const debugInfo = bestResult.bestCombination.map(({ machineId, flow }) => `${machineId}: ${flow.toFixed(2)} units`).join(" | "); 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)}`); 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._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, bestResult.bestPower, this.unitPolicy.canonical.power);
this._writeMeasurement("flow", "predicted", "atequipment", bestResult.bestFlow, this.unitPolicy.canonical.flow); this._writeMeasurement("flow", "predicted", POSITIONS.DOWNSTREAM, bestResult.bestFlow, this.unitPolicy.canonical.flow);
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
@@ -751,11 +784,11 @@ class MachineGroup {
if(machineStates[machineId] === "idle" && flow > 0){ if(machineStates[machineId] === "idle" && flow > 0){
await machine.handleInput("parent", "execsequence", "startup"); await machine.handleInput("parent", "execsequence", "startup");
await machine.handleInput("parent", "flowmovement", flow); await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
} }
if(machineStates[machineId] === "operational" && flow > 0 ){ if(machineStates[machineId] === "operational" && flow > 0 ){
await machine.handleInput("parent", "flowmovement", flow); await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
} }
})); }));
} }
@@ -766,23 +799,25 @@ class MachineGroup {
// Equalize pressure across all machines for machines that are not running. This is needed to ensure accurate flow and power predictions. // Equalize pressure across all machines for machines that are not running. This is needed to ensure accurate flow and power predictions.
equalizePressure(){ equalizePressure(){
if (Object.keys(this.machines).length === 0) return;
// Get current pressures from all machines // Get current pressures from all machines
const pressures = Object.entries(this.machines).map(([machineId, machine]) => { const pressures = Object.entries(this.machines).map(([_machineId, machine]) => {
return { return {
downstream: this._readChildMeasurement(machine, "pressure", "measured", "downstream", this.unitPolicy.canonical.pressure), downstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.pressure) || 0,
upstream: this._readChildMeasurement(machine, "pressure", "measured", "upstream", this.unitPolicy.canonical.pressure) upstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, this.unitPolicy.canonical.pressure) || 0
}; };
}); });
// Find the highest downstream and lowest upstream pressure // Find the highest downstream and lowest upstream pressure
const maxDownstream = Math.max(...pressures.map(p => p.downstream)); const maxDownstream = Math.max(...pressures.map(p => p.downstream));
const minUpstream = Math.min(...pressures.map(p => p.upstream)); const minUpstream = Math.min(...pressures.map(p => p.upstream));
// 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); this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, maxDownstream, this.unitPolicy.canonical.pressure);
this._writeChildMeasurement(machine, "pressure", "measured", "upstream", minUpstream, this.unitPolicy.canonical.pressure); this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, minUpstream, this.unitPolicy.canonical.pressure);
// Update the measured pressure value // Update the measured pressure value
const pressure = machine.getMeasuredPressure(); const pressure = machine.getMeasuredPressure();
this.logger.debug(`Setting pressure for machine ${machineId} to ${pressure}`); this.logger.debug(`Setting pressure for machine ${machineId} to ${pressure}`);
@@ -826,11 +861,11 @@ 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);
}); });
return newList; return newList;
} }
@@ -841,7 +876,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;
@@ -854,9 +889,9 @@ class MachineGroup {
return { maxEfficiency, lowestEfficiency }; return { maxEfficiency, lowestEfficiency };
} }
//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
@@ -893,14 +928,14 @@ class MachineGroup {
availableFlow -= machine.machine.predictFlow.currentFxyYMin; availableFlow -= machine.machine.predictFlow.currentFxyYMin;
} }
} }
// Determine remaining active machines (not shut down). // Determine remaining active machines (not shut down).
const remainingMachines = machinesInPriorityOrder.filter( const remainingMachines = machinesInPriorityOrder.filter(
({ id }) => ({ id }) =>
this.isMachineActive(id) && this.isMachineActive(id) &&
!flowDistribution.some(item => item.machineId === id) !flowDistribution.some(item => item.machineId === id)
); );
// Evenly distribute Qd among the remaining machines. // Evenly distribute Qd among the remaining machines.
const distributedFlow = Qd / remainingMachines.length; const distributedFlow = Qd / remainingMachines.length;
for (let machine of remainingMachines) { for (let machine of remainingMachines) {
@@ -910,14 +945,14 @@ 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;
while (totalFlow < Qd && i <= machinesInPriorityOrder.length) { while (totalFlow < Qd && i <= machinesInPriorityOrder.length) {
Qd = Qd / i; Qd = Qd / i;
if(machinesInPriorityOrder[i-1].machine.predictFlow.currentFxyYMax >= Qd){ if(machinesInPriorityOrder[i-1].machine.predictFlow.currentFxyYMax >= Qd){
for ( let i2 = 0; i2 < i ; i2++){ for ( let i2 = 0; i2 < i ; i2++){
if(! this.isMachineActive(machinesInPriorityOrder[i2].id)){ if(! this.isMachineActive(machinesInPriorityOrder[i2].id)){
@@ -929,45 +964,47 @@ class MachineGroup {
} }
i++; i++;
} }
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;
Qd /= countActiveMachines; Qd /= countActiveMachines;
// Simply distribute the demand equally among all available machines. // Simply distribute the demand equally among all available machines.
for ( let i = 0 ; i < countActiveMachines ; i++){ for ( let i = 0 ; i < countActiveMachines ; i++){
flowDistribution.push({ machineId: machinesInPriorityOrder[i].id, flow: Qd}); flowDistribution.push({ machineId: machinesInPriorityOrder[i].id, flow: Qd});
totalFlow += Qd ; totalFlow += Qd ;
totalPower += machinesInPriorityOrder[i].machine.inputFlowCalcPower(Qd); totalPower += machinesInPriorityOrder[i].machine.inputFlowCalcPower(Qd);
} }
break; break;
}
} }
// Log information about flow distribution // Log information about flow distribution
const debugInfo = flowDistribution const debugInfo = flowDistribution
.filter(({ flow }) => flow > 0) .filter(({ flow }) => flow > 0)
.map(({ machineId, flow }) => `${machineId}: ${flow.toFixed(2)} units`) .map(({ machineId, flow }) => `${machineId}: ${flow.toFixed(2)} units`)
.join(" | "); .join(" | ");
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._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, totalPower, this.unitPolicy.canonical.power);
this._writeMeasurement("flow", "predicted", "atequipment", totalFlow, this.unitPolicy.canonical.flow); this._writeMeasurement("flow", "predicted", POSITIONS.DOWNSTREAM, totalFlow, this.unitPolicy.canonical.flow);
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
await Promise.all(flowDistribution.map(async ({ machineId, flow }) => { await Promise.all(flowDistribution.map(async ({ machineId, flow }) => {
const machine = this.machines[machineId]; const machine = this.machines[machineId];
this.logger.debug(this.machines[machineId].state); this.logger.debug(this.machines[machineId].state);
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")) {
@@ -975,9 +1012,10 @@ class MachineGroup {
} }
else if (currentState === "idle" && flow > 0) { else if (currentState === "idle" && flow > 0) {
await machine.handleInput("parent", "execsequence", "startup"); await machine.handleInput("parent", "execsequence", "startup");
await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
} }
else if (currentState === "operational" && flow > 0) { else if (currentState === "operational" && flow > 0) {
await machine.handleInput("parent", "flowmovement", flow); await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
} }
})); }));
} }
@@ -999,7 +1037,7 @@ class MachineGroup {
} }
//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;
@@ -1011,9 +1049,9 @@ class MachineGroup {
const ctrlDistribution = []; //{machineId : 0, flow : 0} push for each machine const ctrlDistribution = []; //{machineId : 0, flow : 0} push for each machine
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});
} }
@@ -1021,8 +1059,8 @@ 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});
@@ -1038,11 +1076,11 @@ class MachineGroup {
if (machinesNeeded === machinesActive) { if (machinesNeeded === machinesActive) {
// 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));
ctrlDistribution.push({ machineId: id, ctrl: ctrlValue }); ctrlDistribution.push({ machineId: id, ctrl: ctrlValue });
} }
}); });
@@ -1071,10 +1109,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 = this._readChildMeasurement(machine, "power", "predicted", POSITIONS.AT_EQUIPMENT, this.unitPolicy.canonical.power);
const flowValue = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow); const flowValue = this._readChildMeasurement(machine, "flow", "predicted", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow);
if (powerValue !== null) { if (powerValue !== null) {
totalPower.push(powerValue); totalPower.push(powerValue);
@@ -1084,11 +1122,11 @@ class MachineGroup {
} }
}); });
this._writeMeasurement("power", "predicted", "atequipment", totalPower.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.power); this._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, totalPower.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.power);
this._writeMeasurement("flow", "predicted", "atequipment", totalFlow.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.flow); this._writeMeasurement("flow", "predicted", POSITIONS.DOWNSTREAM, totalFlow.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.flow);
if(totalPower.reduce((a, b) => a + b, 0) > 0){ if(totalPower.reduce((a, b) => a + b, 0) > 0){
this.measurements.type("efficiency").variant("predicted").position("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));
} }
} }
@@ -1096,9 +1134,9 @@ class MachineGroup {
this.logger.error(err); this.logger.error(err);
} }
} }
async handleInput(source, demand, powerCap = Infinity, priorityList = null) { async handleInput(source, demand, powerCap = Infinity, priorityList = null) {
const demandQ = parseFloat(demand); const demandQ = parseFloat(demand);
if(!Number.isFinite(demandQ)){ if(!Number.isFinite(demandQ)){
@@ -1123,19 +1161,20 @@ class MachineGroup {
demandQout = 0; demandQout = 0;
return; return;
} }
if (demandQ < absoluteTotals.flow.min) { if (demandQ <= 0) {
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`); this.logger.debug(`Turning machines off`);
demandQout = 0; demandQout = 0;
//return early and turn all machines off
this.turnOffAllMachines(); this.turnOffAllMachines();
return; return;
} else if (demandQ < this.absoluteTotals.flow.min) {
this.logger.warn(`Flow demand ${demandQ} is below minimum possible flow ${this.absoluteTotals.flow.min}. Capping to minimum flow.`);
demandQout = this.absoluteTotals.flow.min;
} else if (demandQ > this.absoluteTotals.flow.max) {
this.logger.warn(`Flow demand ${demandQ} is above maximum possible flow ${this.absoluteTotals.flow.max}. Capping to maximum flow.`);
demandQout = this.absoluteTotals.flow.max;
} else {
demandQout = demandQ;
} }
break; break;
@@ -1170,9 +1209,9 @@ class MachineGroup {
this.logger.warn("Priority percentage control is only valid with normalized scaling."); this.logger.warn("Priority percentage control is only valid with normalized scaling.");
return; return;
} }
await this.prioPercentageControl(demandQout,priorityList); await this.prioPercentageControl(demandQout,priorityList);
break; break;
case "optimalcontrol": case "optimalcontrol":
this.logger.debug(`Calculating optimal control. Input flow demand: ${demandQ} scaling : ${scaling} -> ${demandQout}`); this.logger.debug(`Calculating optimal control. Input flow demand: ${demandQ} scaling : ${scaling} -> ${demandQout}`);
await this.optimalControl(demandQout,powerCap); await this.optimalControl(demandQout,powerCap);
@@ -1185,7 +1224,7 @@ 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.AT_EQUIPMENT).getCurrentValue();
this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency); this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency);
} }
@@ -1242,6 +1281,13 @@ class MachineGroup {
} }
} }
_canonicalToOutputFlow(value) {
const from = this.unitPolicy.canonical.flow;
const to = this.unitPolicy.output.flow;
if (!from || !to || from === to) return value;
return convert(value).from(from).to(to);
}
_outputUnitForType(type) { _outputUnitForType(type) {
switch (String(type || '').toLowerCase()) { switch (String(type || '').toLowerCase()) {
case 'flow': case 'flow':
@@ -1306,34 +1352,34 @@ 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 unit = this._outputUnitForType(type);
const downstreamVal = this._readMeasurement(type, variant, "downstream", unit); const downstreamVal = this._readMeasurement(type, variant, POSITIONS.DOWNSTREAM, unit);
const atEquipmentVal = this._readMeasurement(type, variant, "atequipment", unit); const atEquipmentVal = this._readMeasurement(type, variant, POSITIONS.AT_EQUIPMENT, unit);
const upstreamVal = this._readMeasurement(type, variant, "upstream", unit); const upstreamVal = this._readMeasurement(type, variant, POSITIONS.UPSTREAM, unit);
if (downstreamVal != null) { if (downstreamVal != null) {
output[`downstream_${variant}_${type}`] = downstreamVal; output[`downstream_${variant}_${type}`] = downstreamVal;
} }
if (upstreamVal != null) { if (upstreamVal != null) {
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 diff = this.measurements
.type(type) .type(type)
.variant(variant) .variant(variant)
.difference({ from: 'downstream', to: 'upstream', unit }); .difference({ from: POSITIONS.DOWNSTREAM, to: POSITIONS.UPSTREAM, unit });
if (diff?.value != null) { if (diff?.value != null) {
output[`differential_${variant}_${type}`] = diff.value; output[`differential_${variant}_${type}`] = diff.value;
} }
} }
}); });
}); });
//fill in the rest of the output object //fill in the rest of the output object
output["mode"] = this.mode; output["mode"] = this.mode;
output["scaling"] = this.scaling; output["scaling"] = this.scaling;
@@ -1343,10 +1389,10 @@ class MachineGroup {
output["absDistFromPeak"] = this.absDistFromPeak; output["absDistFromPeak"] = this.absDistFromPeak;
output["relDistFromPeak"] = this.relDistFromPeak; output["relDistFromPeak"] = this.relDistFromPeak;
//this.logger.debug(`Output: ${JSON.stringify(output)}`); //this.logger.debug(`Output: ${JSON.stringify(output)}`);
return output; return output;
} }
} }
module.exports = MachineGroup; module.exports = MachineGroup;
@@ -1359,8 +1405,8 @@ const { max } = require("mathjs");
function createBaseMachineConfig(machineNum, name,specs) { function createBaseMachineConfig(machineNum, name,specs) {
return { return {
general: { general: {
logging: { enabled: true, logLevel: "debug" }, logging: { enabled: true, logLevel: "debug" },
name: name, name: name,
id: machineNum, id: machineNum,
unit: "m3/h" unit: "m3/h"
@@ -1417,8 +1463,8 @@ function createStateConfig(){
function createBaseMachineGroupConfig(name) { function createBaseMachineGroupConfig(name) {
return { return {
general: { general: {
logging: { enabled: true, logLevel: "debug" }, logging: { enabled: true, logLevel: "debug" },
name: name name: name
}, },
functionality: { functionality: {
@@ -1489,28 +1535,28 @@ 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
console.log("------------------------------------"); console.log("------------------------------------");
await mg.handleInput("parent",demand); await mg.handleInput("parent",demand);
pt1.calculateInput(1400); pt1.calculateInput(1400);
//await new Promise(resolve => setTimeout(resolve, 200)); //await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------"); console.log("------------------------------------");
} }
for(let demand = 240 ; demand >= mg.dynamicTotals.flow.min ; demand -= 40){ for(let demand = 240 ; demand >= mg.dynamicTotals.flow.min ; demand -= 40){
//set pressure //set pressure
console.log("------------------------------------"); console.log("------------------------------------");
await mg.handleInput("parent",demand); await mg.handleInput("parent",demand);
pt1.calculateInput(1400); pt1.calculateInput(1400);
//await new Promise(resolve => setTimeout(resolve, 200)); //await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------"); console.log("------------------------------------");
} }
//*//* //*//*
@@ -1518,7 +1564,7 @@ async function makeMachines(){
//set pressure //set pressure
console.log(`TESTING: processing demand of ${demand}`); console.log(`TESTING: processing demand of ${demand}`);
await mg.handleInput("parent",demand); await mg.handleInput("parent",demand);
Object.keys(mg.machines).forEach(machineId => { Object.keys(mg.machines).forEach(machineId => {
console.log(mg.machines[machineId].state.getCurrentState()); console.log(mg.machines[machineId].state.getCurrentState());
@@ -1527,7 +1573,7 @@ async function makeMachines(){
console.log(`updating pressure to 1400 mbar`); console.log(`updating pressure to 1400 mbar`);
pt1.calculateInput(1400); pt1.calculateInput(1400);
console.log("------------------------------------"); console.log("------------------------------------");
} }
} }
catch(err){ catch(err){
@@ -1535,7 +1581,7 @@ async function makeMachines(){
} }
} }
@@ -1543,4 +1589,4 @@ if (require.main === module) {
makeMachines(); makeMachines();
} }
//*/ //*/

View File

@@ -0,0 +1,227 @@
/**
* machineGroupControl vs naive strategies — real pump curves
*
* Station: 2× hidrostal H05K-S03R + 1× hidrostal C5-D03R-SHN1
* ΔP = 2000 mbar
*
* Compares the ACTUAL machineGroupControl optimalControl algorithm against
* naive baselines. All strategies must deliver exactly Qd.
*/
const test = require('node:test');
const assert = require('node:assert/strict');
const MachineGroup = require('../../src/specificClass');
const Machine = require('../../../rotatingMachine/src/specificClass');
const DIFF_MBAR = 2000;
const UP_MBAR = 500;
const DOWN_MBAR = UP_MBAR + DIFF_MBAR;
const stateConfig = {
time: { starting: 0, warmingup: 0, stopping: 0, coolingdown: 0 },
movement: { speed: 1200, mode: 'staticspeed', maxSpeed: 1800 }
};
function machineConfig(id, model) {
return {
general: { logging: { enabled: false, logLevel: 'error' }, name: id, id, unit: 'm3/h' },
functionality: { softwareType: 'machine', role: 'rotationaldevicecontroller' },
asset: { category: 'pump', type: 'centrifugal', model, supplier: 'hidrostal' },
mode: {
current: 'auto',
allowedActions: { auto: ['execsequence', 'execmovement', 'flowmovement', 'statuscheck'] },
allowedSources: { auto: ['parent', 'GUI'] }
},
sequences: {
startup: ['starting', 'warmingup', 'operational'],
shutdown: ['stopping', 'coolingdown', 'idle'],
emergencystop: ['emergencystop', 'off'],
}
};
}
function groupConfig() {
return {
general: { logging: { enabled: false, logLevel: 'error' }, name: 'station' },
functionality: { softwareType: 'machinegroup', role: 'groupcontroller' },
scaling: { current: 'absolute' },
mode: { current: 'optimalcontrol' }
};
}
function injectPressure(m) {
m.updateMeasuredPressure(UP_MBAR, 'upstream', { timestamp: Date.now(), unit: 'mbar', childName: 'up', childId: `up-${m.config.general.id}` });
m.updateMeasuredPressure(DOWN_MBAR, 'downstream', { timestamp: Date.now(), unit: 'mbar', childName: 'dn', childId: `dn-${m.config.general.id}` });
}
/* ---- naive baselines (pumps OFF = 0 flow, 0 power) ---- */
function distribute(machines, running, rawDist, Qd) {
const dist = {};
for (const id of Object.keys(machines)) dist[id] = 0;
for (const id of running) {
const m = machines[id];
dist[id] = Math.min(m.predictFlow.currentFxyYMax, Math.max(m.predictFlow.currentFxyYMin, rawDist[id] || 0));
}
for (let pass = 0; pass < 20; pass++) {
let rem = Qd - running.reduce((s, id) => s + dist[id], 0);
if (Math.abs(rem) < 1e-9) break;
for (const id of running) {
if (Math.abs(rem) < 1e-9) break;
const m = machines[id];
const cap = rem > 0 ? m.predictFlow.currentFxyYMax - dist[id] : dist[id] - m.predictFlow.currentFxyYMin;
if (cap > 1e-9) { const t = Math.min(Math.abs(rem), cap); dist[id] += rem > 0 ? t : -t; rem += rem > 0 ? -t : t; }
}
}
return dist;
}
function spillover(machines, Qd) {
const sorted = Object.keys(machines).sort((a, b) => machines[a].predictFlow.currentFxyYMax - machines[b].predictFlow.currentFxyYMax);
let running = [], maxCap = 0;
for (const id of sorted) { running.push(id); maxCap += machines[id].predictFlow.currentFxyYMax; if (maxCap >= Qd) break; }
const raw = {}; let rem = Qd;
for (const id of running) { raw[id] = rem; rem = Math.max(0, rem - machines[id].predictFlow.currentFxyYMax); }
const dist = distribute(machines, running, raw, Qd);
let p = 0, f = 0;
for (const id of running) { p += machines[id].inputFlowCalcPower(dist[id]); f += dist[id]; }
return { dist, power: p, flow: f, combo: running };
}
function equalAllOn(machines, Qd) {
const ids = Object.keys(machines);
const raw = {}; for (const id of ids) raw[id] = Qd / ids.length;
const dist = distribute(machines, ids, raw, Qd);
let p = 0, f = 0;
for (const id of ids) { p += machines[id].inputFlowCalcPower(dist[id]); f += dist[id]; }
return { dist, power: p, flow: f, combo: ids };
}
/* ---- test ---- */
test('machineGroupControl vs naive baselines — real curves, verified flow', async () => {
const mg = new MachineGroup(groupConfig());
const machines = {};
for (const [id, model] of [['H05K-1','hidrostal-H05K-S03R'],['H05K-2','hidrostal-H05K-S03R'],['C5','hidrostal-C5-D03R-SHN1']]) {
const m = new Machine(machineConfig(id, model), stateConfig);
injectPressure(m);
mg.childRegistrationUtils.registerChild(m, 'downstream');
machines[id] = m;
}
const toH = (v) => +(v * 3600).toFixed(1);
const CANON_FLOW = 'm3/s';
const CANON_POWER = 'W';
console.log(`\n=== STATION: 2×H05K + 1×C5 @ ΔP=${DIFF_MBAR} mbar ===`);
console.table(Object.entries(machines).map(([id, m]) => ({
id,
'min (m³/h)': toH(m.predictFlow.currentFxyYMin),
'max (m³/h)': toH(m.predictFlow.currentFxyYMax),
'BEP (m³/h)': toH(m.predictFlow.currentFxyYMin + (m.predictFlow.currentFxyYMax - m.predictFlow.currentFxyYMin) * m.NCog),
NCog: +m.NCog.toFixed(3),
})));
const minQ = Math.max(...Object.values(machines).map(m => m.predictFlow.currentFxyYMin));
const maxQ = Object.values(machines).reduce((s, m) => s + m.predictFlow.currentFxyYMax, 0);
const demandPcts = [0.10, 0.25, 0.50, 0.75, 0.90];
const rows = [];
for (const pct of demandPcts) {
const Qd = minQ + (maxQ - minQ) * pct;
// Reset all machines to idle, re-inject pressure
for (const m of Object.values(machines)) {
if (m.state.getCurrentState() !== 'idle') await m.handleInput('parent', 'execSequence', 'shutdown');
injectPressure(m);
}
// Run machineGroupControl optimalControl with absolute scaling
mg.setMode('optimalcontrol');
mg.setScaling('absolute');
mg.calcAbsoluteTotals();
mg.calcDynamicTotals();
await mg.handleInput('parent', Qd);
// Read ACTUAL per-pump state (not the MGC summary which may be stale)
let mgcPower = 0, mgcFlow = 0;
const mgcCombo = [];
const mgcDist = {};
for (const [id, m] of Object.entries(machines)) {
const state = m.state.getCurrentState();
const flow = m.measurements.type('flow').variant('predicted').position('downstream').getCurrentValue(CANON_FLOW) || 0;
const power = m.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue(CANON_POWER) || 0;
mgcDist[id] = { flow, power, state };
if (state === 'operational' || state === 'warmingup' || state === 'accelerating') {
mgcCombo.push(id);
mgcPower += power;
mgcFlow += flow;
}
}
// Naive baselines
const sp = spillover(machines, Qd);
const ea = equalAllOn(machines, Qd);
const best = Math.min(mgcPower, sp.power, ea.power);
const delta = (v) => best > 0 ? `${(((v - best) / best) * 100).toFixed(1)}%` : '';
rows.push({
demand: `${(pct * 100)}%`,
'Qd (m³/h)': toH(Qd),
'MGC kW': +(mgcPower / 1000).toFixed(1),
'MGC flow': toH(mgcFlow),
'MGC pumps': mgcCombo.join('+') || 'none',
'Spill kW': +(sp.power / 1000).toFixed(1),
'Spill flow': toH(sp.flow),
'Spill pumps': sp.combo.join('+'),
'EqAll kW': +(ea.power / 1000).toFixed(1),
'EqAll flow': toH(ea.flow),
'MGC Δ': delta(mgcPower),
'Spill Δ': delta(sp.power),
'EqAll Δ': delta(ea.power),
});
}
console.log('\n=== POWER + FLOW COMPARISON (★ = best, all must deliver Qd) ===');
console.table(rows);
// Per-pump detail at each demand level
for (const pct of demandPcts) {
const Qd = minQ + (maxQ - minQ) * pct;
for (const m of Object.values(machines)) {
if (m.state.getCurrentState() !== 'idle') await m.handleInput('parent', 'execSequence', 'shutdown');
injectPressure(m);
}
mg.setMode('optimalcontrol');
mg.setScaling('absolute');
mg.calcAbsoluteTotals();
mg.calcDynamicTotals();
await mg.handleInput('parent', Qd);
const detail = Object.entries(machines).map(([id, m]) => {
const state = m.state.getCurrentState();
const flow = m.measurements.type('flow').variant('predicted').position('downstream').getCurrentValue(CANON_FLOW) || 0;
const power = m.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue(CANON_POWER) || 0;
return {
pump: id,
state,
'flow (m³/h)': toH(flow),
'power (kW)': +(power / 1000).toFixed(1),
};
});
console.log(`\n--- MGC per-pump @ ${(pct*100)}% (${toH(Qd)} m³/h) ---`);
console.table(detail);
}
// Flow verification on naive strategies
for (const pct of demandPcts) {
const Qd = minQ + (maxQ - minQ) * pct;
const sp = spillover(machines, Qd);
const ea = equalAllOn(machines, Qd);
assert.ok(Math.abs(sp.flow - Qd) < Qd * 0.005, `Spillover flow mismatch at ${(pct*100)}%`);
assert.ok(Math.abs(ea.flow - Qd) < Qd * 0.005, `Equal-all flow mismatch at ${(pct*100)}%`);
}
});

View File

@@ -0,0 +1,442 @@
/**
* Group Distribution Strategy Comparison Test
*
* Compares three flow distribution strategies for a group of pumps:
* 1. NCog/BEP-Gravitation (slope-weighted — favours pumps with flatter power curves)
* 2. Equal distribution (same flow to every pump)
* 3. Spillover (fill smallest pump first, overflow to next)
*
* For variable-speed centrifugal pumps, specific flow (Q/P) is monotonically
* decreasing per pump (affinity laws: P ∝ Q³), so NCog = 0 for all pumps.
* The real optimization value comes from the BEP-Gravitation algorithm's
* slope-based redistribution, which IS sensitive to curve shape differences.
*
* These tests verify that:
* - Asymmetric pumps produce different power slopes (the basis for optimization)
* - BEP-Gravitation uses less total power than naive strategies for mixed pumps
* - Equal pumps receive equal treatment under all strategies
* - Spillover creates a visibly different distribution than BEP-weighted
*/
const test = require('node:test');
const assert = require('node:assert/strict');
const MachineGroup = require('../../src/specificClass');
const Machine = require('../../../rotatingMachine/src/specificClass');
const baseCurve = require('../../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
/* ---- helpers ---- */
function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); }
function distortSeries(series, scale = 1, tilt = 0) {
const last = series.length - 1;
return series.map((v, i) => {
const gradient = last === 0 ? 0 : i / last - 0.5;
return Math.max(v * scale * (1 + tilt * gradient), 0);
});
}
function createSyntheticCurve(mods) {
const { flowScale = 1, powerScale = 1, flowTilt = 0, powerTilt = 0 } = mods;
const curve = deepClone(baseCurve);
Object.values(curve.nq).forEach(s => { s.y = distortSeries(s.y, flowScale, flowTilt); });
Object.values(curve.np).forEach(s => { s.y = distortSeries(s.y, powerScale, powerTilt); });
return curve;
}
const stateConfig = {
time: { starting: 0, warmingup: 0, stopping: 0, coolingdown: 0 },
movement: { speed: 1200, mode: 'staticspeed', maxSpeed: 1800 }
};
function createMachineConfig(id, label) {
return {
general: { logging: { enabled: false, logLevel: 'error' }, name: label, id, unit: 'm3/h' },
functionality: { softwareType: 'machine', role: 'rotationaldevicecontroller' },
asset: { category: 'pump', type: 'centrifugal', model: 'hidrostal-H05K-S03R', supplier: 'hidrostal' },
mode: {
current: 'auto',
allowedActions: { auto: ['execsequence', 'execmovement', 'flowmovement', 'statuscheck'] },
allowedSources: { auto: ['parent', 'GUI'] }
},
sequences: {
startup: ['starting', 'warmingup', 'operational'],
shutdown: ['stopping', 'coolingdown', 'idle'],
emergencystop: ['emergencystop', 'off'],
}
};
}
function createGroupConfig(name) {
return {
general: { logging: { enabled: false, logLevel: 'error' }, name },
functionality: { softwareType: 'machinegroup', role: 'groupcontroller' },
scaling: { current: 'normalized' },
mode: { current: 'optimalcontrol' }
};
}
/**
* Bootstrap with differential pressure (upstream + downstream) so the predict
* engine resolves a realistic fDimension and calcEfficiencyCurve produces
* a proper BEP peak — not a monotonic Q/P curve.
*/
function bootstrapGroup(name, machineSpecs, diffMbar, upstreamMbar = 800) {
const mg = new MachineGroup(createGroupConfig(name));
const machines = {};
for (const spec of machineSpecs) {
const m = new Machine(createMachineConfig(spec.id, spec.label), stateConfig);
if (spec.curveMods) m.updateCurve(createSyntheticCurve(spec.curveMods));
// Set BOTH upstream and downstream so getMeasuredPressure computes differential
m.updateMeasuredPressure(upstreamMbar, 'upstream', {
timestamp: Date.now(), unit: 'mbar', childName: `pt-up-${spec.id}`, childId: `pt-up-${spec.id}`
});
m.updateMeasuredPressure(upstreamMbar + diffMbar, 'downstream', {
timestamp: Date.now(), unit: 'mbar', childName: `pt-dn-${spec.id}`, childId: `pt-dn-${spec.id}`
});
mg.childRegistrationUtils.registerChild(m, 'downstream');
machines[spec.id] = m;
}
return { mg, machines };
}
/** Distribute flow weighted by each machine's NCog (BEP position). */
function distributeByNCog(machines, Qd) {
const entries = Object.entries(machines);
let totalNCog = entries.reduce((s, [, m]) => s + (m.NCog || 0), 0);
const distribution = {};
for (const [id, m] of entries) {
const min = m.predictFlow.currentFxyYMin;
const max = m.predictFlow.currentFxyYMax;
const flow = totalNCog > 0
? ((m.NCog || 0) / totalNCog) * Qd
: Qd / entries.length;
distribution[id] = Math.min(max, Math.max(min, flow));
}
let totalPower = 0;
for (const [id, m] of entries) {
totalPower += m.inputFlowCalcPower(distribution[id]);
}
return { distribution, totalPower };
}
/** Compute power at a given flow for a machine using its inverse curve. */
function powerAtFlow(machine, flow) {
return machine.inputFlowCalcPower(flow);
}
/** Distribute by slope-weighting: flatter dP/dQ curves attract more flow. */
function distributeBySlopeWeight(machines, Qd) {
const entries = Object.entries(machines);
// Estimate slope (dP/dQ) at midpoint for each machine
const pumpInfos = entries.map(([id, m]) => {
const min = m.predictFlow.currentFxyYMin;
const max = m.predictFlow.currentFxyYMax;
const mid = (min + max) / 2;
const delta = Math.max((max - min) * 0.05, 0.001);
const pMid = powerAtFlow(m, mid);
const pRight = powerAtFlow(m, Math.min(max, mid + delta));
const slope = Math.abs((pRight - pMid) / delta);
return { id, m, min, max, slope: Math.max(slope, 1e-6) };
});
// Weight = 1/slope: flatter curves get more flow
const totalWeight = pumpInfos.reduce((s, p) => s + (1 / p.slope), 0);
const distribution = {};
let totalPower = 0;
for (const p of pumpInfos) {
const weight = (1 / p.slope) / totalWeight;
const flow = Math.min(p.max, Math.max(p.min, Qd * weight));
distribution[p.id] = flow;
totalPower += powerAtFlow(p.m, flow);
}
return { distribution, totalPower };
}
/** Distribute equally. */
function distributeEqual(machines, Qd) {
const entries = Object.entries(machines);
const flowEach = Qd / entries.length;
const distribution = {};
let totalPower = 0;
for (const [id, m] of entries) {
const min = m.predictFlow.currentFxyYMin;
const max = m.predictFlow.currentFxyYMax;
const clamped = Math.min(max, Math.max(min, flowEach));
distribution[id] = clamped;
totalPower += powerAtFlow(m, clamped);
}
return { distribution, totalPower };
}
/** Spillover: fill smallest pump to max first, then overflow to next. */
function distributeSpillover(machines, Qd) {
const entries = Object.entries(machines)
.sort(([, a], [, b]) => a.predictFlow.currentFxyYMax - b.predictFlow.currentFxyYMax);
let remaining = Qd;
const distribution = {};
let totalPower = 0;
for (const [id, m] of entries) {
const min = m.predictFlow.currentFxyYMin;
const max = m.predictFlow.currentFxyYMax;
const assigned = Math.min(max, Math.max(min, remaining));
distribution[id] = assigned;
remaining = Math.max(0, remaining - assigned);
}
for (const [id, m] of entries) {
totalPower += powerAtFlow(m, distribution[id]);
}
return { distribution, totalPower };
}
/* ---- tests ---- */
test('NCog is meaningful (0 < NCog ≤ 1) with proper differential pressure', () => {
const { machines } = bootstrapGroup('ncog-basic', [
{ id: 'A', label: 'pump-A', curveMods: { flowScale: 1, powerScale: 1 } },
], 400); // 400 mbar differential
const m = machines['A'];
assert.ok(Number.isFinite(m.NCog), `NCog should be finite, got ${m.NCog}`);
assert.ok(m.NCog > 0 && m.NCog <= 1, `NCog should be in (0,1], got ${m.NCog.toFixed(4)}`);
assert.ok(m.cog > 0, `cog (peak specific flow) should be positive, got ${m.cog}`);
assert.ok(m.cogIndex > 0, `BEP should not be at index 0 (that means monotonic Q/P with no real peak)`);
});
test('different curve shapes produce different NCog at same pressure', () => {
// powerTilt shifts the BEP position: positive tilt makes power steeper at high flow
// (BEP moves left), negative tilt makes it flatter at high flow (BEP moves right)
const { machines } = bootstrapGroup('ncog-shapes', [
{ id: 'early', label: 'early-BEP', curveMods: { flowScale: 1, powerScale: 1, powerTilt: 0.4 } },
{ id: 'late', label: 'late-BEP', curveMods: { flowScale: 1, powerScale: 1, powerTilt: -0.3 } },
], 400);
const ncogEarly = machines['early'].NCog;
const ncogLate = machines['late'].NCog;
assert.ok(ncogEarly > 0, `Early BEP NCog should be > 0, got ${ncogEarly.toFixed(4)}`);
assert.ok(ncogLate > 0, `Late BEP NCog should be > 0, got ${ncogLate.toFixed(4)}`);
assert.ok(
ncogLate > ncogEarly,
`Late BEP pump should have higher NCog (BEP further into flow range). ` +
`early=${ncogEarly.toFixed(4)}, late=${ncogLate.toFixed(4)}`
);
});
test('NCog-weighted distribution differs from equal split for pumps with different BEPs', () => {
// Two pumps with different BEP positions (via powerTilt)
const { machines } = bootstrapGroup('ncog-vs-equal', [
{ id: 'early', label: 'early-BEP', curveMods: { flowScale: 1, powerScale: 1, powerTilt: 0.4 } },
{ id: 'late', label: 'late-BEP', curveMods: { flowScale: 1, powerScale: 1, powerTilt: -0.3 } },
], 400);
const ncogA = machines['early'].NCog;
const ncogB = machines['late'].NCog;
assert.ok(ncogA > 0 && ncogB > 0, `Both NCog should be > 0 (early=${ncogA.toFixed(3)}, late=${ncogB.toFixed(3)})`);
assert.ok(ncogA !== ncogB, 'NCog values should differ');
const totalMax = machines['early'].predictFlow.currentFxyYMax + machines['late'].predictFlow.currentFxyYMax;
const Qd = totalMax * 0.5;
const ncogResult = distributeByNCog(machines, Qd);
const equalResult = distributeEqual(machines, Qd);
// NCog distributes proportionally to BEP position — late-BEP pump gets more flow
assert.ok(
ncogResult.distribution['late'] > ncogResult.distribution['early'],
`Late-BEP pump should get more flow under NCog. ` +
`early=${ncogResult.distribution['early'].toFixed(2)}, late=${ncogResult.distribution['late'].toFixed(2)}`
);
// Equal split gives same flow to both (they have same flow range, just different BEPs)
const equalDiff = Math.abs(equalResult.distribution['early'] - equalResult.distribution['late']);
const ncogDiff = Math.abs(ncogResult.distribution['early'] - ncogResult.distribution['late']);
assert.ok(
ncogDiff > equalDiff + Qd * 0.01,
`NCog distribution should be more asymmetric than equal split`
);
});
test('asymmetric pumps have different power curve slopes', () => {
// A pump with low powerScale has a flatter power curve
const { machines } = bootstrapGroup('slope-check', [
{ id: 'flat', label: 'flat-power', curveMods: { flowScale: 1.2, powerScale: 0.7, flowTilt: 0.1 } },
{ id: 'steep', label: 'steep-power', curveMods: { flowScale: 0.8, powerScale: 1.4, flowTilt: -0.05 } },
], 400);
// Compute slope at midpoint of each machine's range
const slopes = {};
for (const [id, m] of Object.entries(machines)) {
const mid = (m.predictFlow.currentFxyYMin + m.predictFlow.currentFxyYMax) / 2;
const delta = (m.predictFlow.currentFxyYMax - m.predictFlow.currentFxyYMin) * 0.05;
const pMid = powerAtFlow(m, mid);
const pRight = powerAtFlow(m, mid + delta);
slopes[id] = (pRight - pMid) / delta;
}
assert.ok(slopes['flat'] > 0 && slopes['steep'] > 0, 'Both slopes should be positive');
assert.ok(
slopes['steep'] > slopes['flat'] * 1.3,
`Steep pump should have notably higher slope. flat=${slopes['flat'].toFixed(0)}, steep=${slopes['steep'].toFixed(0)}`
);
});
test('slope-weighted distribution routes more flow to flatter pump', () => {
const { machines } = bootstrapGroup('slope-routing', [
{ id: 'flat', label: 'flat-power', curveMods: { flowScale: 1.2, powerScale: 0.7 } },
{ id: 'steep', label: 'steep-power', curveMods: { flowScale: 0.8, powerScale: 1.4 } },
], 400);
const totalMax = machines['flat'].predictFlow.currentFxyYMax + machines['steep'].predictFlow.currentFxyYMax;
const Qd = totalMax * 0.5;
const slopeResult = distributeBySlopeWeight(machines, Qd);
assert.ok(
slopeResult.distribution['flat'] > slopeResult.distribution['steep'],
`Flat pump should get more flow. flat=${slopeResult.distribution['flat'].toFixed(2)}, steep=${slopeResult.distribution['steep'].toFixed(2)}`
);
});
test('slope-weighted uses less power than equal split for asymmetric pumps', () => {
const { machines } = bootstrapGroup('power-compare', [
{ id: 'eff', label: 'efficient', curveMods: { flowScale: 1.2, powerScale: 0.7, flowTilt: 0.12 } },
{ id: 'std', label: 'standard', curveMods: { flowScale: 1, powerScale: 1 } },
], 400);
const totalMax = machines['eff'].predictFlow.currentFxyYMax + machines['std'].predictFlow.currentFxyYMax;
const demandLevels = [0.3, 0.5, 0.7].map(p => {
const min = Math.max(machines['eff'].predictFlow.currentFxyYMin, machines['std'].predictFlow.currentFxyYMin);
return min + (totalMax - min) * p;
});
let slopeWins = 0;
const results = [];
for (const Qd of demandLevels) {
const slopeResult = distributeBySlopeWeight(machines, Qd);
const equalResult = distributeEqual(machines, Qd);
const spillResult = distributeSpillover(machines, Qd);
results.push({
demand: Qd,
slopePower: slopeResult.totalPower,
equalPower: equalResult.totalPower,
spillPower: spillResult.totalPower,
});
if (slopeResult.totalPower <= equalResult.totalPower + 1) slopeWins++;
}
assert.ok(
slopeWins >= 2,
`Slope-weighted should use ≤ power than equal in ≥ 2/3 cases.\n` +
results.map(r =>
` Qd=${r.demand.toFixed(1)}: slope=${r.slopePower.toFixed(1)}W, equal=${r.equalPower.toFixed(1)}W, spill=${r.spillPower.toFixed(1)}W`
).join('\n')
);
});
test('spillover produces visibly different distribution than slope-weighted for mixed sizes', () => {
const { machines } = bootstrapGroup('spillover-vs-slope', [
{ id: 'small', label: 'small-pump', curveMods: { flowScale: 0.6, powerScale: 0.55 } },
{ id: 'large', label: 'large-pump', curveMods: { flowScale: 1.5, powerScale: 1.2 } },
], 400);
const totalMax = machines['small'].predictFlow.currentFxyYMax + machines['large'].predictFlow.currentFxyYMax;
const Qd = totalMax * 0.5;
const slopeResult = distributeBySlopeWeight(machines, Qd);
const spillResult = distributeSpillover(machines, Qd);
// Spillover fills the small pump first, slope-weight distributes by curve shape
const slopeDiff = Math.abs(slopeResult.distribution['small'] - spillResult.distribution['small']);
const percentDiff = (slopeDiff / Qd) * 100;
assert.ok(
percentDiff > 1,
`Strategies should produce different distributions. ` +
`Slope small=${slopeResult.distribution['small'].toFixed(2)}, ` +
`Spill small=${spillResult.distribution['small'].toFixed(2)} (${percentDiff.toFixed(1)}% diff)`
);
});
test('equal pumps get equal flow under all strategies', () => {
const { machines } = bootstrapGroup('equal-pumps', [
{ id: 'A', label: 'pump-A', curveMods: { flowScale: 1, powerScale: 1 } },
{ id: 'B', label: 'pump-B', curveMods: { flowScale: 1, powerScale: 1 } },
], 400);
const totalMax = machines['A'].predictFlow.currentFxyYMax + machines['B'].predictFlow.currentFxyYMax;
const Qd = totalMax * 0.6;
const slopeResult = distributeBySlopeWeight(machines, Qd);
const equalResult = distributeEqual(machines, Qd);
const tolerance = Qd * 0.01;
assert.ok(
Math.abs(slopeResult.distribution['A'] - slopeResult.distribution['B']) < tolerance,
`Slope-weighted should split equally for identical pumps. A=${slopeResult.distribution['A'].toFixed(2)}, B=${slopeResult.distribution['B'].toFixed(2)}`
);
assert.ok(
Math.abs(equalResult.distribution['A'] - equalResult.distribution['B']) < tolerance,
`Equal should split equally. A=${equalResult.distribution['A'].toFixed(2)}, B=${equalResult.distribution['B'].toFixed(2)}`
);
// Power should be identical too
assert.ok(
Math.abs(slopeResult.totalPower - equalResult.totalPower) < 1,
`Equal pumps should produce same total power under any strategy`
);
});
test('full MGC optimalControl uses ≤ power than priorityControl for mixed pumps', async () => {
const { mg, machines } = bootstrapGroup('mgc-full', [
{ id: 'eff', label: 'efficient', curveMods: { flowScale: 1.2, powerScale: 0.7, flowTilt: 0.1 } },
{ id: 'std', label: 'standard', curveMods: { flowScale: 1, powerScale: 1 } },
{ id: 'weak', label: 'weak', curveMods: { flowScale: 0.8, powerScale: 1.3, flowTilt: -0.08 } },
], 400);
for (const m of Object.values(machines)) {
await m.handleInput('parent', 'execSequence', 'startup');
}
// Run optimalControl
mg.setMode('optimalcontrol');
mg.setScaling('normalized');
await mg.handleInput('parent', 50, Infinity);
const optPower = mg.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue() || 0;
const optFlow = mg.measurements.type('flow').variant('predicted').position('atequipment').getCurrentValue() || 0;
// Reset machines
for (const m of Object.values(machines)) {
await m.handleInput('parent', 'execSequence', 'shutdown');
await m.handleInput('parent', 'execSequence', 'startup');
}
// Run priorityControl
mg.setMode('prioritycontrol');
await mg.handleInput('parent', 50, Infinity, ['eff', 'std', 'weak']);
const prioPower = mg.measurements.type('power').variant('predicted').position('atequipment').getCurrentValue() || 0;
const prioFlow = mg.measurements.type('flow').variant('predicted').position('atequipment').getCurrentValue() || 0;
assert.ok(optFlow > 0, `Optimal should deliver flow, got ${optFlow}`);
assert.ok(prioFlow > 0, `Priority should deliver flow, got ${prioFlow}`);
// Compare efficiency (flow per unit power)
const optEff = optPower > 0 ? optFlow / optPower : 0;
const prioEff = prioPower > 0 ? prioFlow / prioPower : 0;
assert.ok(
optEff >= prioEff * 0.95,
`Optimal efficiency should be ≥ priority (within 5% tolerance). ` +
`Opt: ${optFlow.toFixed(1)}/${optPower.toFixed(1)}=${optEff.toFixed(6)} | ` +
`Prio: ${prioFlow.toFixed(1)}/${prioPower.toFixed(1)}=${prioEff.toFixed(6)}`
);
});