Merge commit '85797b5' into HEAD

# Conflicts:
#	src/nodeClass.js
#	src/specificClass.js
This commit is contained in:
znetsixe
2026-03-31 18:17:41 +02:00
3 changed files with 203 additions and 180 deletions

View File

@@ -18,6 +18,8 @@
defaults: {
// Define default properties
name: { value: "" },
processOutputFormat: { value: "process" },
dbaseOutputFormat: { value: "influxdb" },
// Logger properties
enableLog: { value: false },
@@ -74,6 +76,24 @@
<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 -->
<div id="logger-fields-placeholder"></div>

View File

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

View File

@@ -1,6 +1,6 @@
//load local dependencies
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({
pressure: 'Pa',
@@ -37,7 +37,7 @@ class MachineGroup {
// Init after config is set
this.logger = new logger(this.config.general.logging.enabled,this.config.general.logging.logLevel, this.config.general.name);
// Initialize measurements
this.measurements = new MeasurementContainer({
autoConvert: true,
@@ -87,11 +87,11 @@ class MachineGroup {
// Prefer functionality-scoped position metadata; keep general fallback for legacy nodes.
const position = child.config?.functionality?.positionVsParent || child.config?.general?.positionVsParent;
if(softwareType == "machine"){
// Check if the machine is already registered
this.machines[child.config.general.id] === undefined ? this.machines[child.config.general.id] = child : this.logger.warn(`Machine ${child.config.general.id} is already registered.`);
//listen for machine pressure changes
this.logger.debug(`Listening for pressure changes from machine ${child.config.general.id}`);
@@ -119,11 +119,11 @@ class MachineGroup {
calcAbsoluteTotals() {
const absoluteTotals = { flow: { min: Infinity, max: 0 }, power: { min: Infinity, max: 0 } };
Object.values(this.machines).forEach(machine => {
const totals = { flow: { min: Infinity, max: 0 }, power: { min: Infinity, max: 0 } };
//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 maxFlow = Math.max(...xyCurve.y);
@@ -143,27 +143,27 @@ class MachineGroup {
if( totals.power.min < absoluteTotals.power.min ){ absoluteTotals.power.min = totals.power.min; }
absoluteTotals.flow.max += totals.flow.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.`);
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.`);
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.`);
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.`);
absoluteTotals.power.max = 0;
absoluteTotals.power.max = 0;
}
// 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() {
const dynamicTotals = { flow: { min: Infinity, max: 0, act: 0 }, power: { min: Infinity, max: 0, act: 0 }, NCog : 0 };
this.logger.debug(`\n --------- Calculating dynamic totals for ${Object.keys(this.machines).length} machines. @ current pressure settings : ----------`);
Object.values(this.machines).forEach(machine => {
//skip machines without valid curve
if(!machine.hasCurve){
@@ -191,13 +191,13 @@ class MachineGroup {
this.logger.debug(`Current pressure settings: ${JSON.stringify(machine.predictFlow.currentF)}`);
//fetch min flow ever seen over all machines
const minFlow = machine.predictFlow.currentFxyYMin;
const minFlow = machine.predictFlow.currentFxyYMin;
const maxFlow = machine.predictFlow.currentFxyYMax;
const minPower = machine.predictPower.currentFxyYMin;
const maxPower = machine.predictPower.currentFxyYMax;
const actFlow = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow) || 0;
const actPower = this._readChildMeasurement(machine, "power", "predicted", "atequipment", this.unitPolicy.canonical.power) || 0;
const actFlow = this._readChildMeasurement(machine, "flow", "predicted", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow) || 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}`);
@@ -211,7 +211,7 @@ class MachineGroup {
//fetch total Normalized Cog over all machines
dynamicTotals.NCog += machine.NCog;
});
// Place data in object for external use
@@ -227,19 +227,19 @@ class MachineGroup {
this.logger.debug(`Processing machine with id: ${id}`);
if(this.isMachineActive(id)){
//fetch min flow ever seen over all machines
const minFlow = machine.predictFlow.currentFxyYMin;
const minFlow = machine.predictFlow.currentFxyYMin;
const maxFlow = machine.predictFlow.currentFxyYMax;
const minPower = machine.predictPower.currentFxyYMin;
const maxPower = machine.predictPower.currentFxyYMax;
totals.flow.min += minFlow;
totals.flow.max += maxFlow;
totals.power.min += minPower;
totals.power.max += maxPower;
totals.countActiveMachines++;
}
});
return totals;
@@ -251,11 +251,11 @@ class MachineGroup {
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._writeMeasurement("flow", "predicted", "atequipment", flow.act, this.unitPolicy.canonical.flow);
this._writeMeasurement("power", "predicted", "atequipment", power.act, this.unitPolicy.canonical.power);
this._writeMeasurement("flow", "predicted", POSITIONS.AT_EQUIPMENT, flow.act, this.unitPolicy.canonical.flow);
this._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, power.act, this.unitPolicy.canonical.power);
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);
}
@@ -274,11 +274,11 @@ class MachineGroup {
calcDistanceBEP(efficiency,maxEfficiency,minEfficiency){
const absDistFromPeak = this.calcDistanceFromPeak(efficiency,maxEfficiency);
const relDistFromPeak = this.calcRelativeDistanceFromPeak(efficiency,maxEfficiency,minEfficiency);
//store internally
this.absDistFromPeak = absDistFromPeak ;
this.relDistFromPeak = relDistFromPeak;
return { absDistFromPeak: absDistFromPeak, relDistFromPeak: relDistFromPeak };
}
@@ -287,15 +287,15 @@ class MachineGroup {
const state = machine.state.getCurrentState();
const mode = machine.currentMode;
//add special cases
//add special cases
if( state === "operational" && ( mode == "virtualControl" || mode === "fysicalControl") ){
let flow = 0;
const measuredFlow = this._readChildMeasurement(machine, "flow", "measured", "downstream", this.unitPolicy.canonical.flow);
const predictedFlow = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow);
const measuredFlow = this._readChildMeasurement(machine, "flow", "measured", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow);
const predictedFlow = this._readChildMeasurement(machine, "flow", "predicted", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow);
if (Number.isFinite(measuredFlow) && measuredFlow !== 0) {
flow = measuredFlow;
}
}
else if (Number.isFinite(predictedFlow) && predictedFlow !== 0) {
flow = predictedFlow;
}
@@ -304,7 +304,7 @@ class MachineGroup {
//abort the calculation
return false;
}
//Qd is less because we allready have machines delivering flow on manual control
Qd = Qd - flow;
}
@@ -317,28 +317,28 @@ class MachineGroup {
// adjust demand flow when there are machines being controlled by a manual source
Qd = this.checkSpecialCases(machines, Qd);
// Generate all possible subsets of machines (power set)
Object.keys(machines).forEach(machineId => {
const state = machines[machineId].state.getCurrentState();
const validActionForMode = machines[machineId].isValidActionForMode("execsequence", "auto");
// Reasons why a machine is not valid for the combination
if( state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validActionForMode){
return;
}
// go through each machine and add it to the subsets
let newSubsets = subsets.map(set => [...set, machineId]);
subsets = subsets.concat(newSubsets);
});
// Filter for non-empty subsets that can meet or exceed demand flow
const combinations = subsets.filter(subset => {
if (subset.length === 0) return false;
// Calculate total and minimum flow for the subset in one pass
const { maxFlow, minFlow, maxPower } = subset.reduce(
(acc, machineId) => {
@@ -353,7 +353,7 @@ class MachineGroup {
maxPower: acc.maxPower + maxPower
};
},
},
{ maxFlow: 0, minFlow: 0 , maxPower: 0 }
);
@@ -365,7 +365,7 @@ class MachineGroup {
return false;
}
});
return combinations;
}
@@ -449,7 +449,7 @@ class MachineGroup {
return { bestCombination, bestPower, bestFlow, bestCog };
}
// Estimate the local dP/dQ slopes around the BEP for the provided machine.
estimateSlopesAtBEP(machine, Q_BEP, delta = 1.0) {
const fallback = {
@@ -572,7 +572,7 @@ class MachineGroup {
const flowDistribution = pumpInfos.map(info => ({
machineId: info.id,
flow: Math.min(info.maxFlow, Math.max(info.minFlow, info.Q_BEP))
}));
}));
let totalFlow = flowDistribution.reduce((sum, entry) => sum + entry.flow, 0); // Initial total flow
const delta = Qd - totalFlow; // Difference to target demand
@@ -647,10 +647,10 @@ class MachineGroup {
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
const pressures = Object.entries(this.machines).map(([machineId, machine]) => {
return {
downstream: this._readChildMeasurement(machine, "pressure", "measured", "downstream", this.unitPolicy.canonical.pressure),
upstream: this._readChildMeasurement(machine, "pressure", "measured", "upstream", this.unitPolicy.canonical.pressure)
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)
};
});
@@ -660,19 +660,19 @@ class MachineGroup {
this.logger.debug(`Max downstream pressure: ${maxDownstream}, Min upstream pressure: ${minUpstream}`);
//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"){
//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", "upstream", minUpstream, this.unitPolicy.canonical.pressure);
this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, maxDownstream, 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
// we need to find a better way to do this but for now it works
machine.getMeasuredPressure();
}
});
//fetch dynamic totals
const dynamicTotals = this.dynamicTotals;
@@ -697,7 +697,7 @@ 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);
if (!combinations || combinations.length === 0) {
this.logger.warn(`Demand: ${Qd.toFixed(2)} -> No valid combination found (empty set).`);
@@ -726,12 +726,12 @@ class MachineGroup {
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._writeMeasurement("power", "predicted", "atequipment", bestResult.bestPower, this.unitPolicy.canonical.power);
this._writeMeasurement("flow", "predicted", "atequipment", bestResult.bestFlow, this.unitPolicy.canonical.flow);
this.measurements.type("efficiency").variant("predicted").position("atequipment").value(bestResult.bestFlow / bestResult.bestPower);
this.measurements.type("Ncog").variant("predicted").position("atequipment").value(bestResult.bestCog);
this._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, bestResult.bestPower, this.unitPolicy.canonical.power);
this._writeMeasurement("flow", "predicted", POSITIONS.DOWNSTREAM, bestResult.bestFlow, this.unitPolicy.canonical.flow);
this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(bestResult.bestFlow / bestResult.bestPower);
this.measurements.type("Ncog").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(bestResult.bestCog);
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
// Find the flow for this machine in the best combination
@@ -767,22 +767,22 @@ class MachineGroup {
// Equalize pressure across all machines for machines that are not running. This is needed to ensure accurate flow and power predictions.
equalizePressure(){
// Get current pressures from all machines
const pressures = Object.entries(this.machines).map(([machineId, machine]) => {
return {
downstream: this._readChildMeasurement(machine, "pressure", "measured", "downstream", this.unitPolicy.canonical.pressure),
upstream: this._readChildMeasurement(machine, "pressure", "measured", "upstream", this.unitPolicy.canonical.pressure)
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)
};
});
// Find the highest downstream and lowest upstream pressure
const maxDownstream = Math.max(...pressures.map(p => p.downstream));
const minUpstream = Math.min(...pressures.map(p => p.upstream));
// Set consistent pressures across machines
Object.entries(this.machines).forEach(([machineId, machine]) => {
if(!this.isMachineActive(machineId)){
this._writeChildMeasurement(machine, "pressure", "measured", "downstream", maxDownstream, this.unitPolicy.canonical.pressure);
this._writeChildMeasurement(machine, "pressure", "measured", "upstream", minUpstream, this.unitPolicy.canonical.pressure);
this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.DOWNSTREAM, maxDownstream, this.unitPolicy.canonical.pressure);
this._writeChildMeasurement(machine, "pressure", "measured", POSITIONS.UPSTREAM, minUpstream, this.unitPolicy.canonical.pressure);
// Update the measured pressure value
const pressure = machine.getMeasuredPressure();
this.logger.debug(`Setting pressure for machine ${machineId} to ${pressure}`);
@@ -826,11 +826,11 @@ class MachineGroup {
}
filterOutUnavailableMachines(list) {
const newList = list.filter(({ id, machine }) => {
const newList = list.filter(({ machine }) => {
const state = machine.state.getCurrentState();
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;
}
@@ -841,7 +841,7 @@ class MachineGroup {
let lowestEfficiency = Infinity;
// 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;
if(machine.cog < lowestEfficiency){
lowestEfficiency = machine.cog;
@@ -854,9 +854,9 @@ class MachineGroup {
return { maxEfficiency, lowestEfficiency };
}
//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 {
// equalize pressure across all machines
@@ -893,14 +893,14 @@ class MachineGroup {
availableFlow -= machine.machine.predictFlow.currentFxyYMin;
}
}
// Determine remaining active machines (not shut down).
const remainingMachines = machinesInPriorityOrder.filter(
({ id }) =>
this.isMachineActive(id) &&
!flowDistribution.some(item => item.machineId === id)
);
// Evenly distribute Qd among the remaining machines.
const distributedFlow = Qd / remainingMachines.length;
for (let machine of remainingMachines) {
@@ -910,14 +910,14 @@ class MachineGroup {
}
break;
}
case (Qd > activeTotals.flow.max):
case (Qd > activeTotals.flow.max): {
// 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.
let i = 1;
while (totalFlow < Qd && i <= machinesInPriorityOrder.length) {
Qd = Qd / i;
if(machinesInPriorityOrder[i-1].machine.predictFlow.currentFxyYMax >= Qd){
for ( let i2 = 0; i2 < i ; i2++){
if(! this.isMachineActive(machinesInPriorityOrder[i2].id)){
@@ -929,45 +929,47 @@ class MachineGroup {
}
i++;
}
break;
default:
break;
}
default: {
// Default case: Demand is within the active range.
const countActiveMachines = machinesInPriorityOrder.filter(({ id }) => this.isMachineActive(id)).length;
Qd /= countActiveMachines;
// Simply distribute the demand equally among all available machines.
for ( let i = 0 ; i < countActiveMachines ; i++){
flowDistribution.push({ machineId: machinesInPriorityOrder[i].id, flow: Qd});
totalFlow += Qd ;
totalPower += machinesInPriorityOrder[i].machine.inputFlowCalcPower(Qd);
}
break;
}
}
// Log information about flow distribution
const debugInfo = flowDistribution
.filter(({ flow }) => flow > 0)
.map(({ machineId, flow }) => `${machineId}: ${flow.toFixed(2)} units`)
.join(" | ");
this.logger.debug(`Priority control for demand: ${totalFlow.toFixed(2)} -> Active pumps: [${debugInfo}] => Total Power: ${totalPower.toFixed(2)}`);
// Store measurements
this._writeMeasurement("power", "predicted", "atequipment", totalPower, this.unitPolicy.canonical.power);
this._writeMeasurement("flow", "predicted", "atequipment", totalFlow, this.unitPolicy.canonical.flow);
this.measurements.type("efficiency").variant("predicted").position("atequipment").value(totalFlow / totalPower);
this.measurements.type("Ncog").variant("predicted").position("atequipment").value(totalCog);
this._writeMeasurement("power", "predicted", POSITIONS.AT_EQUIPMENT, totalPower, this.unitPolicy.canonical.power);
this._writeMeasurement("flow", "predicted", POSITIONS.DOWNSTREAM, totalFlow, this.unitPolicy.canonical.flow);
this.measurements.type("efficiency").variant("predicted").position(POSITIONS.AT_EQUIPMENT).value(totalFlow / totalPower);
this.measurements.type("Ncog").variant("predicted").position(POSITIONS.AT_EQUIPMENT).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);
this.logger.debug(this.machines[machineId].state);
const currentState = this.machines[machineId].state.getCurrentState();
if (flow <= 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) {
@@ -999,7 +1001,7 @@ class MachineGroup {
}
//capp input to 100
input > 100 ? input = 100 : input = input;
if (input > 100) { input = 100; }
const numOfMachines = Object.keys(this.machines).length;
const procentTotal = numOfMachines * input;
@@ -1011,9 +1013,9 @@ class MachineGroup {
const ctrlDistribution = []; //{machineId : 0, flow : 0} push for each machine
if(machinesNeeded > machinesActive){
//start extra machine and put all active machines at min control
machinesInPriorityOrder.forEach(({ id, machine }, index) => {
machinesInPriorityOrder.forEach(({ id }, index) => {
if(index < machinesNeeded){
ctrlDistribution.push({machineId : id, ctrl : 0});
}
@@ -1021,8 +1023,8 @@ class MachineGroup {
}
if(machinesNeeded < machinesActive){
machinesInPriorityOrder.forEach(({ id, machine }, index) => {
machinesInPriorityOrder.forEach(({ id }, index) => {
if(this.isMachineActive(id)){
if(index < machinesNeeded){
ctrlDistribution.push({machineId : id, ctrl : 100});
@@ -1038,11 +1040,11 @@ class MachineGroup {
if (machinesNeeded === machinesActive) {
// distribute input equally among active machines (0 - 100%)
const ctrlPerMachine = procentTotal / machinesActive;
machinesInPriorityOrder.forEach(({ id, machine }) => {
machinesInPriorityOrder.forEach(({ id }) => {
if (this.isMachineActive(id)) {
// 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 });
}
});
@@ -1071,10 +1073,10 @@ class MachineGroup {
const totalFlow = [];
// 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 flowValue = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow);
const powerValue = this._readChildMeasurement(machine, "power", "predicted", POSITIONS.AT_EQUIPMENT, this.unitPolicy.canonical.power);
const flowValue = this._readChildMeasurement(machine, "flow", "predicted", POSITIONS.DOWNSTREAM, this.unitPolicy.canonical.flow);
if (powerValue !== null) {
totalPower.push(powerValue);
@@ -1084,11 +1086,11 @@ class MachineGroup {
}
});
this._writeMeasurement("power", "predicted", "atequipment", 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("power", "predicted", POSITIONS.AT_EQUIPMENT, totalPower.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.power);
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){
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 +1098,9 @@ class MachineGroup {
this.logger.error(err);
}
}
async handleInput(source, demand, powerCap = Infinity, priorityList = null) {
const demandQ = parseFloat(demand);
if(!Number.isFinite(demandQ)){
@@ -1123,13 +1125,13 @@ class MachineGroup {
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.`);
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 > 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 > 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){
this.logger.debug(`Turning machines off`);
demandQout = 0;
@@ -1170,9 +1172,9 @@ class MachineGroup {
this.logger.warn("Priority percentage control is only valid with normalized scaling.");
return;
}
await this.prioPercentageControl(demandQout,priorityList);
await this.prioPercentageControl(demandQout,priorityList);
break;
case "optimalcontrol":
this.logger.debug(`Calculating optimal control. Input flow demand: ${demandQ} scaling : ${scaling} -> ${demandQout}`);
await this.optimalControl(demandQout,powerCap);
@@ -1185,7 +1187,7 @@ class MachineGroup {
//recalc distance from BEP
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);
}
@@ -1306,34 +1308,34 @@ class MachineGroup {
const output = {};
//build the output object
Object.entries(this.measurements.measurements || {}).forEach(([type, variants]) => {
Object.keys(variants || {}).forEach((variant) => {
const unit = this._outputUnitForType(type);
const downstreamVal = this._readMeasurement(type, variant, "downstream", unit);
const atEquipmentVal = this._readMeasurement(type, variant, "atequipment", unit);
const upstreamVal = this._readMeasurement(type, variant, "upstream", unit);
this.measurements.getTypes().forEach(type => {
this.measurements.getVariants(type).forEach(variant => {
const unit = this._outputUnitForType(type);
const downstreamVal = this._readMeasurement(type, variant, POSITIONS.DOWNSTREAM, unit);
const atEquipmentVal = this._readMeasurement(type, variant, POSITIONS.AT_EQUIPMENT, unit);
const upstreamVal = this._readMeasurement(type, variant, POSITIONS.UPSTREAM, unit);
if (downstreamVal != null) {
output[`downstream_${variant}_${type}`] = downstreamVal;
}
if (upstreamVal != null) {
output[`upstream_${variant}_${type}`] = upstreamVal;
}
if (atEquipmentVal != null) {
output[`atequipment${variant}_${type}`] = atEquipmentVal;
}
if (downstreamVal != null && upstreamVal != null) {
const diff = this.measurements
.type(type)
.variant(variant)
.difference({ from: 'downstream', to: 'upstream', unit });
if (diff?.value != null) {
output[`differential_${variant}_${type}`] = diff.value;
}
}
});
if (downstreamVal != null) {
output[`downstream_${variant}_${type}`] = downstreamVal;
}
if (upstreamVal != null) {
output[`upstream_${variant}_${type}`] = upstreamVal;
}
if (atEquipmentVal != null) {
output[`atEquipment_${variant}_${type}`] = atEquipmentVal;
}
if (downstreamVal != null && upstreamVal != null) {
const diff = this.measurements
.type(type)
.variant(variant)
.difference({ from: POSITIONS.DOWNSTREAM, to: POSITIONS.UPSTREAM, unit });
if (diff?.value != null) {
output[`differential_${variant}_${type}`] = diff.value;
}
}
});
});
//fill in the rest of the output object
output["mode"] = this.mode;
output["scaling"] = this.scaling;
@@ -1343,10 +1345,10 @@ class MachineGroup {
output["absDistFromPeak"] = this.absDistFromPeak;
output["relDistFromPeak"] = this.relDistFromPeak;
//this.logger.debug(`Output: ${JSON.stringify(output)}`);
return output;
}
}
module.exports = MachineGroup;
@@ -1359,8 +1361,8 @@ const { max } = require("mathjs");
function createBaseMachineConfig(machineNum, name,specs) {
return {
general: {
logging: { enabled: true, logLevel: "debug" },
general: {
logging: { enabled: true, logLevel: "debug" },
name: name,
id: machineNum,
unit: "m3/h"
@@ -1417,8 +1419,8 @@ function createStateConfig(){
function createBaseMachineGroupConfig(name) {
return {
general: {
logging: { enabled: true, logLevel: "debug" },
general: {
logging: { enabled: true, logLevel: "debug" },
name: name
},
functionality: {
@@ -1489,28 +1491,28 @@ 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);
//await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------");
}
for(let demand = 240 ; demand >= mg.dynamicTotals.flow.min ; demand -= 40){
//set pressure
console.log("------------------------------------");
await mg.handleInput("parent",demand);
pt1.calculateInput(1400);
//await new Promise(resolve => setTimeout(resolve, 200));
console.log("------------------------------------");
}
//*//*
@@ -1518,7 +1520,7 @@ async function makeMachines(){
//set pressure
console.log(`TESTING: processing demand of ${demand}`);
await mg.handleInput("parent",demand);
Object.keys(mg.machines).forEach(machineId => {
console.log(mg.machines[machineId].state.getCurrentState());
@@ -1527,7 +1529,7 @@ async function makeMachines(){
console.log(`updating pressure to 1400 mbar`);
pt1.calculateInput(1400);
console.log("------------------------------------");
}
}
catch(err){
@@ -1535,7 +1537,7 @@ async function makeMachines(){
}
}
@@ -1543,4 +1545,4 @@ if (require.main === module) {
makeMachines();
}
//*/
//*/