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>
This commit is contained in:
znetsixe
2026-04-07 13:40:45 +02:00
parent ffb2072baa
commit d55f401ab3
3 changed files with 735 additions and 22 deletions

View File

@@ -265,7 +265,7 @@ class MachineGroup {
calcRelativeDistanceFromPeak(currentEfficiency,maxEfficiency,minEfficiency){
let distance = 1;
if(currentEfficiency != null){
if(currentEfficiency != null && maxEfficiency !== minEfficiency){
distance = this.interpolation.interpolate_lin_single_point(currentEfficiency,maxEfficiency, minEfficiency, 0, 1);
}
return distance;
@@ -580,14 +580,40 @@ class MachineGroup {
this.redistributeFlowBySlope(pumpInfos, flowDistribution, delta, directional);
}
// Clamp and compute initial power
flowDistribution.forEach(entry => {
const info = pumpInfos.find(info => info.id === entry.machineId);
entry.flow = Math.min(info.maxFlow, Math.max(info.minFlow, entry.flow));
});
// Marginal-cost refinement: shift flow from most expensive to cheapest
// pump using actual power evaluations. Converges regardless of curve convexity.
const mcDelta = Math.max(1e-6, (Qd / pumpInfos.length) * 0.005);
for (let refineIter = 0; refineIter < 50; refineIter++) {
const mcEntries = flowDistribution.map(entry => {
const info = pumpInfos.find(i => i.id === entry.machineId);
const pNow = info.machine.inputFlowCalcPower(entry.flow);
const pUp = info.machine.inputFlowCalcPower(Math.min(info.maxFlow, entry.flow + mcDelta));
return { entry, info, mc: (pUp - pNow) / mcDelta };
});
let expensive = null, cheap = null;
for (const e of mcEntries) {
if (e.entry.flow > e.info.minFlow + mcDelta) { if (!expensive || e.mc > expensive.mc) expensive = e; }
if (e.entry.flow < e.info.maxFlow - mcDelta) { if (!cheap || e.mc < cheap.mc) cheap = e; }
}
if (!expensive || !cheap || expensive === cheap) break;
if (expensive.mc - cheap.mc < expensive.mc * 0.001) break;
const before = expensive.info.machine.inputFlowCalcPower(expensive.entry.flow) + cheap.info.machine.inputFlowCalcPower(cheap.entry.flow);
const after = expensive.info.machine.inputFlowCalcPower(expensive.entry.flow - mcDelta) + cheap.info.machine.inputFlowCalcPower(cheap.entry.flow + mcDelta);
if (after < before) { expensive.entry.flow -= mcDelta; cheap.entry.flow += mcDelta; } else { break; }
}
let totalPower = 0;
totalFlow = 0;
flowDistribution.forEach(entry => {
const info = pumpInfos.find(info => info.id === entry.machineId);
const flow = Math.min(info.maxFlow, Math.max(info.minFlow, entry.flow));
entry.flow = flow;
totalFlow += flow;
totalPower += info.machine.inputFlowCalcPower(flow);
totalFlow += entry.flow;
const info = pumpInfos.find(i => i.id === entry.machineId);
totalPower += info.machine.inputFlowCalcPower(entry.flow);
});
const totalCog = pumpInfos.reduce((sum, info) => sum + info.NCog, 0);
@@ -645,12 +671,17 @@ class MachineGroup {
async optimalControl(Qd, powerCap = Infinity) {
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
// this is to ensure a correct evaluation of the flow and power consumption
const pressures = Object.entries(this.machines).map(([_machineId, machine]) => {
return {
downstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.pressure),
upstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, this.unitPolicy.canonical.pressure)
downstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.pressure) || 0,
upstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, this.unitPolicy.canonical.pressure) || 0
};
});
@@ -682,7 +713,9 @@ class MachineGroup {
}, {});
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 ){
@@ -751,11 +784,11 @@ class MachineGroup {
if(machineStates[machineId] === "idle" && flow > 0){
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 ){
await machine.handleInput("parent", "flowmovement", flow);
await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
}
}));
}
@@ -766,11 +799,13 @@ class MachineGroup {
// Equalize pressure across all machines for machines that are not running. This is needed to ensure accurate flow and power predictions.
equalizePressure(){
if (Object.keys(this.machines).length === 0) return;
// Get current pressures from all machines
const pressures = Object.entries(this.machines).map(([_machineId, machine]) => {
return {
downstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.pressure),
upstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, this.unitPolicy.canonical.pressure)
downstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.pressure) || 0,
upstream: this._readChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, this.unitPolicy.canonical.pressure) || 0
};
});
@@ -977,9 +1012,10 @@ class MachineGroup {
}
else if (currentState === "idle" && flow > 0) {
await machine.handleInput("parent", "execsequence", "startup");
await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
}
else if (currentState === "operational" && flow > 0) {
await machine.handleInput("parent", "flowmovement", flow);
await machine.handleInput("parent", "flowmovement", this._canonicalToOutputFlow(flow));
}
}));
}
@@ -1126,18 +1162,19 @@ class MachineGroup {
return;
}
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 (demandQout > this.absoluteTotals.flow.max) {
this.logger.warn(`Flow demand ${demandQ} is above maximum possible flow ${this.absoluteTotals.flow.max}. Capping to maximum flow.`);
demandQout = this.absoluteTotals.flow.max;
}else if(demandQout <= 0){
if (demandQ <= 0) {
this.logger.debug(`Turning machines off`);
demandQout = 0;
//return early and turn all machines off
this.turnOffAllMachines();
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;
@@ -1244,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) {
switch (String(type || '').toLowerCase()) {
case 'flow':