Stable version of machinegroup control

This commit is contained in:
znetsixe
2025-10-02 17:08:41 +02:00
parent a55c6bdbea
commit b4364094c6
3 changed files with 452 additions and 587 deletions

View File

@@ -50,12 +50,6 @@ class MachineGroup {
}
// when a child gets updated do something
handleChildChange() {
this.absoluteTotals = this.calcAbsoluteTotals();
//for reference and not to recalc these values continiously
this.dynamicTotals = this.calcDynamicTotals();
}
registerChild(child,softwareType) {
this.logger.debug('Setting up childs specific for this class');
@@ -69,15 +63,26 @@ class MachineGroup {
child.measurements.emitter.on("pressure.measured.differential", (eventData) => {
this.logger.debug(`Pressure update from ${child.config.general.id}: ${eventData.value} ${eventData.unit}`);
this.handleChildChange();
this.logger.debug(`Pressure update from ${child.config.general.id}: ${eventData.value} ${eventData.unit}`);
this.handlePressureChange();
});
child.measurements.emitter.on("pressure.measured.downstream", (eventData) => {
this.logger.debug(`Pressure update from ${child.config.general.id}: ${eventData.value} ${eventData.unit}`);
this.handlePressureChange();
});
child.measurements.emitter.on("flow.predicted.downstream", (eventData) => {
this.logger.debug(`Flow prediction update from ${child.config.general.id}: ${eventData.value} ${eventData.unit}`);
//later change to this.handleFlowPredictionChange();
this.handlePressureChange();
});
}
}
calcAbsoluteTotals() {
const absoluteTotals = { flow: { min: Infinity, max: 0 }, power: { min: Infinity, max: 0 } };
@@ -99,6 +104,7 @@ class MachineGroup {
if( maxPower > totals.power.max ){ totals.power.max = maxPower; }
});
//surplus machines for max flow and power
if( totals.flow.min < absoluteTotals.flow.min ){ absoluteTotals.flow.min = totals.flow.min; }
if( totals.power.min < absoluteTotals.power.min ){ absoluteTotals.power.min = totals.power.min; }
@@ -107,6 +113,29 @@ class MachineGroup {
});
if(absoluteTotals.flow.min === Infinity) {
this.logger.warn(`Flow min ${absoluteTotals.flow.min} is Infinity. Setting to 0.`);
absoluteTotals.flow.min = 0;
}
if(absoluteTotals.power.min === Infinity) {
this.logger.warn(`Power min ${absoluteTotals.power.min} is Infinity. Setting to 0.`);
absoluteTotals.power.min = 0;
}
if(absoluteTotals.flow.max === -Infinity) {
this.logger.warn(`Flow max ${absoluteTotals.flow.max} is -Infinity. Setting to 0.`);
absoluteTotals.flow.max = 0;
}
if(absoluteTotals.power.max === -Infinity) {
this.logger.warn(`Power max ${absoluteTotals.power.max} is -Infinity. Setting to 0.`);
absoluteTotals.power.max = 0;
}
// Place data in object for external use
this.absoluteTotals = absoluteTotals;
return absoluteTotals;
}
@@ -114,9 +143,10 @@ class MachineGroup {
//max and min current flow and power based on their actual pressure curve
calcDynamicTotals() {
const dynamicTotals = { flow: { min: Infinity, max: 0 }, power: { min: Infinity, max: 0 }, NCog : 0 };
const dynamicTotals = { flow: { min: Infinity, max: 0, act: 0 }, power: { min: Infinity, max: 0, act: 0 }, NCog : 0 };
this.logger.debug(`\n --------- Calculating dynamic totals for ${Object.keys(this.machines).length} machines. @ current pressure settings : ----------`);
Object.values(this.machines).forEach(machine => {
this.logger.debug(`Processing machine with id: ${machine.config.general.id}`);
this.logger.debug(`Current pressure settings: ${JSON.stringify(machine.predictFlow.currentF)}`);
@@ -125,18 +155,27 @@ class MachineGroup {
const maxFlow = machine.predictFlow.currentFxyYMax;
const minPower = machine.predictPower.currentFxyYMin;
const maxPower = machine.predictPower.currentFxyYMax;
const actFlow = machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue();
const actPower = machine.measurements.type("power").variant("predicted").position("atEquipment").getCurrentValue();
this.logger.debug(`Machine ${machine.config.general.id} - Min Flow: ${minFlow}, Max Flow: ${maxFlow}, Min Power: ${minPower}, Max Power: ${maxPower}, NCog: ${machine.NCog}`);
if( minFlow < dynamicTotals.flow.min ){ dynamicTotals.flow.min = minFlow; }
if( minPower < dynamicTotals.power.min ){ dynamicTotals.power.min = minPower; }
dynamicTotals.flow.max += maxFlow;
dynamicTotals.power.max += maxPower;
dynamicTotals.flow.act += actFlow;
dynamicTotals.power.act += actPower;
//fetch total Normalized Cog over all machines
dynamicTotals.NCog += machine.NCog;
});
// Place data in object for external use
this.dynamicTotals = dynamicTotals;
return dynamicTotals;
}
@@ -166,10 +205,16 @@ class MachineGroup {
}
handlePressureChange() {
this.logger.info("Pressure change detected.");
this.calcDynamicTotals();
this.logger.info("---------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>Pressure change detected.");
// Recalculate totals
const { flow, power } = this.calcDynamicTotals();
this.logger.debug(`Dynamic Totals after pressure change - Flow: Min ${flow.min}, Max ${flow.max}, Act ${flow.act} | Power: Min ${power.min}, Max ${power.max}, Act ${power.act}`);
this.measurements.type("flow").variant("predicted").position("downstream").value(flow.act);
this.measurements.type("power").variant("predicted").position("atEquipment").value(power.act);
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
const efficiency = this.measurements.type("efficiency").variant("predicted").position("downstream").getCurrentValue();
const efficiency = this.measurements.type("efficiency").variant("predicted").position("atEquipment").getCurrentValue();
this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency);
}
@@ -232,7 +277,6 @@ class MachineGroup {
// Generate all possible subsets of machines (power set)
Object.keys(machines).forEach(machineId => {
//machineId = parseInt(machineId);
const state = machines[machineId].state.getCurrentState();
const validActionForMode = machines[machineId].isValidActionForMode("execSequence", "auto");
@@ -334,7 +378,6 @@ class MachineGroup {
}
// -------- Mode and Input Management -------- //
isValidActionForMode(action, mode) {
const allowedActionsSet = this.config.mode.allowedActions[mode] || [];
return allowedActionsSet.has(action);
@@ -346,8 +389,18 @@ class MachineGroup {
this.logger.debug(`Scaling set to: ${scaling}`);
}
async abortActiveMovements(reason = "new demand") {
await Promise.all(Object.values(this.machines).map(async machine => {
this.logger.warn(`Aborting active movements for machine ${machine.config.general.id} due to: ${reason}`);
if (typeof machine.abortMovement === "function") {
await machine.abortMovement(reason);
}
}));
}
//handle input from parent / user / UI
async optimalControl(Qd, powerCap = Infinity) {
try{
//we need to force the pressures of all machines to be equal to the highest pressure measured in the group
// this is to ensure a correct evaluation of the flow and power consumption
@@ -361,20 +414,25 @@ class MachineGroup {
const maxDownstream = Math.max(...pressures.map(p => p.downstream));
const minUpstream = Math.min(...pressures.map(p => p.upstream));
this.logger.debug(`Max downstream pressure: ${maxDownstream}, Min upstream pressure: ${minUpstream}`);
//set the pressures
Object.entries(this.machines).forEach(([machineId, machine]) => {
if(machine.state.getCurrentState() !== "operational" && machine.state.getCurrentState() !== "accelerating" && machine.state.getCurrentState() !== "decelerating"){
//Equilize pressures over all machines so we can make a proper calculation
machine.measurements.type("pressure").variant("measured").position("downstream").value(maxDownstream);
machine.measurements.type("pressure").variant("measured").position("upstream").value(minUpstream);
// after updating the measurement directly we need to force the update of the value OLIFANT this is not so clear now in the code
// we need to find a better way to do this but for now it works
machine.getMeasuredPressure();
}
});
//fetch dynamic totals
const dynamicTotals = this.dynamicTotals;
//update dynamic totals
const dynamicTotals = this.calcDynamicTotals();
const machineStates = Object.entries(this.machines).reduce((acc, [machineId, machine]) => {
acc[machineId] = machine.state.getCurrentState();
return acc;
@@ -396,48 +454,48 @@ class MachineGroup {
}
// fetch all valid combinations that meet expectations
const combinations = this.validPumpCombinations(this.machines, Qd, powerCap);
//
const combinations = this.validPumpCombinations(this.machines, Qd, powerCap);
const bestResult = this.calcBestCombination(combinations, Qd);
if(bestResult.bestCombination === null){
this.logger.warn(`Demand: ${Qd.toFixed(2)} -> No valid combination found => not updating control `);
return;
}
const debugInfo = bestResult.bestCombination.map(({ machineId, flow }) => `${machineId}: ${flow.toFixed(2)} units`).join(" | ");
this.logger.debug(`Moving to demand: ${Qd.toFixed(2)} -> Pumps: [${debugInfo}] => Total Power: ${bestResult.bestPower.toFixed(2)}`);
//store the total delivered power
this.measurements.type("power").variant("predicted").position("upstream").value(bestResult.bestPower);
this.measurements.type("power").variant("predicted").position("atEquipment").value(bestResult.bestPower);
this.measurements.type("flow").variant("predicted").position("downstream").value(bestResult.bestFlow);
this.measurements.type("efficiency").variant("predicted").position("downstream").value(bestResult.bestFlow / bestResult.bestPower);
this.measurements.type("Ncog").variant("predicted").position("downstream").value(bestResult.bestCog);
this.measurements.type("efficiency").variant("predicted").position("atEquipment").value(bestResult.bestFlow / bestResult.bestPower);
this.measurements.type("Ncog").variant("predicted").position("atEquipment").value(bestResult.bestCog);
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
const pumpInfo = bestResult.bestCombination.find(item => item.machineId == machineId);
// Find the flow for this machine in the best combination
this.logger.debug(`Searching for machine ${machineId} with state ${machineStates[machineId]} in best combination.`);
const pumpInfo = bestResult.bestCombination.find(item => item.machineId == machineId);
let flow;
if(pumpInfo !== undefined){
flow = pumpInfo.flow;
} else {
this.logger.debug(`Machine ${machineId} not in best combination, setting flow to 0`);
this.logger.debug(`Machine ${machineId} not in best combination, setting flow control to 0`);
flow = 0;
}
if( (flow <= 0 ) && ( machineStates[machineId] === "operational" || machineStates[machineId] === "accelerating" || machineStates[machineId] === "decelerating" ) ){
await machine.handleInput("parent", "execSequence", "shutdown");
}
else if(machineStates[machineId] === "idle" && flow > 0){
if(machineStates[machineId] === "idle" && flow > 0){
await machine.handleInput("parent", "execSequence", "startup");
}
else if(machineStates[machineId] === "operational" && flow > 0 ){
await machine.handleInput("parent", "flowMovement", flow);
}
if(machineStates[machineId] === "operational" && flow > 0 ){
await machine.handleInput("parent", "flowMovement", flow);
}
}));
}
catch(err){
this.logger.error(err);
@@ -499,7 +557,7 @@ class MachineGroup {
.map(id => ({ id, machine: this.machines[id] }));
} else {
machinesInPriorityOrder = Object.entries(this.machines)
.map(([id, machine]) => ({ id: parseInt(id), machine }))
.map(([id, machine]) => ({ id: id, machine }))
.sort((a, b) => a.id - b.id);
}
return machinesInPriorityOrder;
@@ -545,14 +603,6 @@ class MachineGroup {
// Update dynamic totals
const dynamicTotals = this.calcDynamicTotals();
// Handle zero demand by shutting down all machines early exit
if (Qd <= 0) {
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execSequence", "shutdown"); }
}));
return;
}
// Cap flow demand to min/max possible values
Qd = this.capFlowDemand(Qd,dynamicTotals);
@@ -646,14 +696,16 @@ class MachineGroup {
this.logger.debug(`Priority control for demand: ${totalFlow.toFixed(2)} -> Active pumps: [${debugInfo}] => Total Power: ${totalPower.toFixed(2)}`);
// Store measurements
this.measurements.type("power").variant("predicted").position("upstream").value(totalPower);
this.measurements.type("power").variant("predicted").position("atEquipment").value(totalPower);
this.measurements.type("flow").variant("predicted").position("downstream").value(totalFlow);
this.measurements.type("efficiency").variant("predicted").position("downstream").value(totalFlow / totalPower);
this.measurements.type("Ncog").variant("predicted").position("downstream").value(totalCog);
this.measurements.type("efficiency").variant("predicted").position("atEquipment").value(totalFlow / totalPower);
this.measurements.type("Ncog").variant("predicted").position("atEquipment").value(totalCog);
this.logger.debug(`Flow distribution: ${JSON.stringify(flowDistribution)}`);
// Apply the flow distribution to machines
await Promise.all(flowDistribution.map(async ({ machineId, flow }) => {
const machine = this.machines[machineId];
this.logger.debug(this.machines[machineId].state);
const currentState = this.machines[machineId].state.getCurrentState();
if (flow <= 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) {
@@ -758,8 +810,10 @@ class MachineGroup {
// fetch and store measurements
Object.entries(this.machines).forEach(([machineId, machine]) => {
const powerValue = machine.measurements.type("power").variant("predicted").position("upstream").getCurrentValue();
const powerValue = machine.measurements.type("power").variant("predicted").position("atEquipment").getCurrentValue();
const flowValue = machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue();
if (powerValue !== null) {
totalPower.push(powerValue);
}
@@ -768,10 +822,11 @@ class MachineGroup {
}
});
this.measurements.type("power").variant("predicted").position("upstream").value(totalPower.reduce((a, b) => a + b, 0));
this.measurements.type("power").variant("predicted").position("atEquipment").value(totalPower.reduce((a, b) => a + b, 0));
this.measurements.type("flow").variant("predicted").position("downstream").value(totalFlow.reduce((a, b) => a + b, 0));
if(totalPower.reduce((a, b) => a + b, 0) > 0){
this.measurements.type("efficiency").variant("predicted").position("downstream").value(totalFlow.reduce((a, b) => a + b, 0) / totalPower.reduce((a, b) => a + b, 0));
this.measurements.type("efficiency").variant("predicted").position("atEquipment").value(totalFlow.reduce((a, b) => a + b, 0) / totalPower.reduce((a, b) => a + b, 0));
}
}
@@ -780,43 +835,80 @@ class MachineGroup {
}
}
async handleInput(source, Qd, powerCap = Infinity, priorityList = null) {
async handleInput(source, demand, powerCap = Infinity, priorityList = null) {
//abort current movements
await this.abortActiveMovements("new demand received");
const scaling = this.scaling;
const mode = this.mode;
let rawInput = Qd;
const dynamicTotals = this.calcDynamicTotals();
const demandQ = parseFloat(demand);
let demandQout = 0; // keep output Q by default 0 for safety
this.logger.debug(`Handling input from ${source}: Demand = ${demand}, Power Cap = ${powerCap}, Priority List = ${priorityList}`);
switch (scaling) {
case "absolute":
// No scaling needed but cap range
if (Qd < this.absoluteTotals.flow.min) {
this.logger.warn(`Flow demand ${Qd} is below minimum possible flow ${this.absoluteTotals.flow.min}. Capping to minimum flow.`);
Qd = this.absoluteTotals.flow.min;
} else if (Qd > this.absoluteTotals.flow.max) {
this.logger.warn(`Flow demand ${Qd} is above maximum possible flow ${this.absoluteTotals.flow.max}. Capping to maximum flow.`);
Qd = this.absoluteTotals.flow.max;
if (isNaN(demandQ)) {
this.logger.warn(`Invalid absolute flow demand: ${demand}. Must be a number.`);
demandQout = 0;
return;
}
if (demandQ < absoluteTotals.flow.min) {
this.logger.warn(`Flow demand ${demandQ} is below minimum possible flow ${absoluteTotals.flow.min}. Capping to minimum flow.`);
demandQout = this.absoluteTotals.flow.min;
} else if (demandQout > absoluteTotals.flow.max) {
this.logger.warn(`Flow demand ${demandQ} is above maximum possible flow ${absoluteTotals.flow.max}. Capping to maximum flow.`);
demandQout = absoluteTotals.flow.max;
}else if(demandQout <= 0){
this.logger.debug(`Turning machines off`);
demandQout = 0;
//return early and turn all machines off
this.turnOffAllMachines();
return;
}
break;
case "normalized":
// Scale demand to 0-100% linear between min and max flow this is auto capped
Qd = this.interpolation.interpolate_lin_single_point(Qd, 0, 100, this.dynamicTotals.flow.min, this.dynamicTotals.flow.max);
this.logger.debug(`Normalizing flow demand: ${demandQ} with min: ${dynamicTotals.flow.min} and max: ${dynamicTotals.flow.max}`);
if(demand < 0){
this.logger.debug(`Turning machines off`);
demandQout = 0;
//return early and turn all machines off
this.turnOffAllMachines();
return;
}
else{
// Scale demand to 0-100% linear between min and max flow this is auto capped
demandQout = this.interpolation.interpolate_lin_single_point(demandQ, 0, 100, dynamicTotals.flow.min, dynamicTotals.flow.max );
this.logger.debug(`Normalized flow demand ${demandQ}% to: ${demandQout} Q units`);
}
break;
}
// Execute control based on mode
switch(mode) {
case "prioritycontrol":
await this.equalFlowControl(Qd,powerCap,priorityList);
this.logger.debug(`Calculating prio control. Input flow demand: ${demandQ} scaling : ${scaling} -> ${demandQout}`);
await this.equalFlowControl(demandQout,powerCap,priorityList);
break;
case "prioritypercentagecontrol":
this.logger.debug(`Calculating prio percentage control. Input flow demand: ${demandQ} scaling : ${scaling} -> ${demandQout}`);
if(scaling !== "normalized"){
this.logger.warn("Priority percentage control is only valid with normalized scaling.");
return;
}
await this.prioPercentageControl(rawInput,priorityList);
await this.prioPercentageControl(demandQout,priorityList);
break;
case "optimalcontrol":
await this.optimalControl(Qd,powerCap);
this.logger.debug(`Calculating optimal control. Input flow demand: ${demandQ} scaling : ${scaling} -> ${demandQout}`);
await this.optimalControl(demandQout,powerCap);
break;
default:
@@ -831,6 +923,12 @@ class MachineGroup {
}
async turnOffAllMachines(){
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execSequence", "shutdown"); }
}));
}
setMode(mode) {
this.mode = mode;
}
@@ -845,6 +943,7 @@ class MachineGroup {
this.measurements.getVariants(type).forEach(variant => {
const downstreamVal = this.measurements.type(type).variant(variant).position("downstream").getCurrentValue();
const atEquipmentVal = this.measurements.type(type).variant(variant).position("atEquipment").getCurrentValue();
const upstreamVal = this.measurements.type(type).variant(variant).position("upstream").getCurrentValue();
if (downstreamVal != null) {
@@ -853,6 +952,9 @@ class MachineGroup {
if (upstreamVal != null) {
output[`upstream_${variant}_${type}`] = upstreamVal;
}
if (atEquipmentVal != null) {
output[`atEquipment_${variant}_${type}`] = atEquipmentVal;
}
if (downstreamVal != null && upstreamVal != null) {
const diffVal = this.measurements.type(type).variant(variant).difference().value;
output[`differential_${variant}_${type}`] = diffVal;
@@ -876,17 +978,17 @@ class MachineGroup {
}
module.exports = MachineGroup;
/*
const Machine = require('../../rotatingMachine/src/specificClass');
const Measurement = require('../../measurement/src/specificClass');
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
const { number } = require("../../generalFunctions/src/convert/lodash/lodash._objecttypes");
const { max } = require("mathjs");
function createBaseMachineConfig(machineNum, name,specs) {
return {
general: {
logging: { enabled: true, logLevel: "warn" },
logging: { enabled: true, logLevel: "debug" },
name: name,
id: machineNum,
unit: "m3/h"
@@ -924,6 +1026,23 @@ function createBaseMachineConfig(machineNum, name,specs) {
};
}
function createStateConfig(){
return {
time:{
starting: 1,
stopping: 1,
warmingup: 1,
coolingdown: 1,
emergencystop: 1
},
movement:{
mode:"dynspeed",
speed:100,
maxSpeed: 1000
}
}
};
function createBaseMachineGroupConfig(name) {
return {
general: {
@@ -944,9 +1063,13 @@ function createBaseMachineGroupConfig(name) {
}
const machineGroupConfig = createBaseMachineGroupConfig("testmachinegroup");
const stateConfigs = {};
const machineConfigs = {};
machineConfigs[1]= createBaseMachineConfig(1,"testmachine",specs);
machineConfigs[2] = createBaseMachineConfig(2,"testmachine2",specs);
stateConfigs[1] = createStateConfig();
stateConfigs[2] = createStateConfig();
machineConfigs[1]= createBaseMachineConfig("asdfkj;asdf","testmachine",specs);
machineConfigs[2] = createBaseMachineConfig("asdfkj;asdf2","testmachine2",specs);
const ptConfig = {
general: {
@@ -976,14 +1099,16 @@ async function makeMachines(){
const pt1 = new Measurement(ptConfig);
const numofMachines = 2;
for(let i = 1; i <= numofMachines; i++){
const machine = new Machine(machineConfigs[i]);
const machine = new Machine(machineConfigs[i],stateConfigs[i]);
//mg.machines[i] = machine;
mg.childRegistrationUtils.registerChild(machine, "downstream");
}
mg.machines[1].childRegistrationUtils.registerChild(pt1, "downstream");
mg.machines[2].childRegistrationUtils.registerChild(pt1, "downstream");
//mg.setMode("prioritycontrol");
Object.keys(mg.machines).forEach(machineId => {
mg.machines[machineId].childRegistrationUtils.registerChild(pt1, "downstream");
});
mg.setMode("prioritycontrol");
mg.setScaling("normalized");
const absMax = mg.dynamicTotals.flow.max;
@@ -992,14 +1117,13 @@ async function makeMachines(){
const percMax = 100;
try{
/*
/*
for(let demand = mg.dynamicTotals.flow.min ; demand <= mg.dynamicTotals.flow.max ; demand += 2){
//set pressure
console.log("------------------------------------");
await mg.handleInput("parent",demand);
pt1.calculateInput(1400);
console.log("Waiting for 0.2 sec ");
//await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------");
@@ -1012,24 +1136,24 @@ async function makeMachines(){
await mg.handleInput("parent",demand);
pt1.calculateInput(1400);
console.log("Waiting for 0.2 sec ");
//await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------");
}
//*/
/*
for(let demand = 0 ; demand <= 100 ; demand += 1){
//*//*
for(let demand = 0 ; demand <= 50 ; demand += 1){
//set pressure
console.log(`processing demand of ${demand}`);
console.log(`TESTING: processing demand of ${demand}`);
await mg.handleInput("parent",demand);
console.log(mg.machines[1].state.getCurrentState());
console.log(mg.machines[2].state.getCurrentState());
Object.keys(mg.machines).forEach(machineId => {
console.log(mg.machines[machineId].state.getCurrentState());
});
console.log(`updating pressure to 1400 mbar`);
pt1.calculateInput(1400);
console.log("Waiting for 0.2 sec ");
//await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------");
}