forked from RnD/machineGroupControl
Stable version of machinegroup control
This commit is contained in:
@@ -1,548 +1,288 @@
|
||||
// ...existing code...
|
||||
const MachineGroup = require('./specificClass.js');
|
||||
const Machine = require('../../rotatingMachine/src/specificClass');
|
||||
const Measurement = require('../../measurement/src/specificClass');
|
||||
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
|
||||
|
||||
function createBaseMachineConfig(machineNum, name, specs) {
|
||||
return {
|
||||
general: {
|
||||
logging: { enabled: true, logLevel: "warn" },
|
||||
name: name,
|
||||
id: machineNum,
|
||||
unit: "m3/h"
|
||||
},
|
||||
functionality: {
|
||||
softwareType: "machine",
|
||||
role: "rotationaldevicecontroller"
|
||||
},
|
||||
asset: {
|
||||
category: "pump",
|
||||
type: "centrifugal",
|
||||
model: "hidrostal-h05k-s03r",
|
||||
supplier: "hydrostal",
|
||||
machineCurve: specs
|
||||
},
|
||||
mode: {
|
||||
current: "auto",
|
||||
allowedActions: {
|
||||
auto: ["execSequence", "execMovement", "statusCheck"],
|
||||
virtualControl: ["execMovement", "statusCheck"],
|
||||
fysicalControl: ["statusCheck"]
|
||||
},
|
||||
allowedSources: {
|
||||
auto: ["parent", "GUI"],
|
||||
virtualControl: ["GUI"],
|
||||
fysicalControl: ["fysical"]
|
||||
}
|
||||
},
|
||||
sequences: {
|
||||
startup: ["starting", "warmingup", "operational"],
|
||||
shutdown: ["stopping", "coolingdown", "idle"],
|
||||
emergencystop: ["emergencystop", "off"],
|
||||
boot: ["idle", "starting", "warmingup", "operational"]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createBaseMachineGroupConfig(name) {
|
||||
return {
|
||||
general: {
|
||||
logging: { enabled: true, logLevel: "debug" },
|
||||
name: name
|
||||
},
|
||||
functionality: {
|
||||
softwareType: "machinegroup",
|
||||
role: "groupcontroller"
|
||||
},
|
||||
scaling: {
|
||||
current: "normalized"
|
||||
},
|
||||
mode: {
|
||||
current: "optimalcontrol"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const stateConfig = { time:{starting:0,warmingup:0,stopping:0,coolingdown:0}, movement:{speed:1000,mode:"staticspeed"} };
|
||||
const ptConfig = {
|
||||
general: {
|
||||
logging: { enabled: true, logLevel: "debug" },
|
||||
name: "testpt",
|
||||
id: "0",
|
||||
unit: "mbar",
|
||||
general:{ logging:{enabled:false,logLevel:"warn"}, name:"testpt", id:"pt-1", unit:"mbar" },
|
||||
functionality:{ softwareType:"measurement", role:"sensor" },
|
||||
asset:{ category:"sensor", type:"pressure", model:"testmodel", supplier:"vega", unit:"mbar" },
|
||||
scaling:{ absMin:0, absMax:4000 }
|
||||
};
|
||||
|
||||
const testSuite = [];
|
||||
const efficiencyComparisons = [];
|
||||
|
||||
function logPass(name, details="") {
|
||||
const entry = { name, status:"PASS", details };
|
||||
testSuite.push(entry);
|
||||
console.log(`✅ ${name}${details ? ` — ${details}` : ""}`);
|
||||
}
|
||||
function logFail(name, error) {
|
||||
const entry = { name, status:"FAIL", details:error?.message || error };
|
||||
testSuite.push(entry);
|
||||
console.error(`❌ ${name} — ${entry.details}`);
|
||||
}
|
||||
function approxEqual(actual, expected, tolerancePct=1) {
|
||||
const tolerance = (expected * tolerancePct) / 100;
|
||||
return actual >= expected - tolerance && actual <= expected + tolerance;
|
||||
}
|
||||
async function sleep(ms){ return new Promise(resolve => setTimeout(resolve, ms)); }
|
||||
|
||||
function createMachineConfig(id,label) {
|
||||
return {
|
||||
general:{ logging:{enabled:false,logLevel:"warn"}, name:label, id, unit:"m3/h" },
|
||||
functionality:{ softwareType:"machine", role:"rotationaldevicecontroller" },
|
||||
asset:{ category:"pump", type:"centrifugal", model:"hidrostal-h05k-s03r", supplier:"hydrostal", machineCurve:specs },
|
||||
mode:{
|
||||
current:"auto",
|
||||
allowedActions:{
|
||||
auto:["execSequence","execMovement","flowMovement","statusCheck"],
|
||||
virtualControl:["execMovement","statusCheck"],
|
||||
fysicalControl:["statusCheck"]
|
||||
},
|
||||
allowedSources:{
|
||||
auto:["parent","GUI"],
|
||||
virtualControl:["GUI"],
|
||||
fysicalControl:["fysical"]
|
||||
}
|
||||
},
|
||||
functionality: {
|
||||
softwareType: "measurement",
|
||||
role: "sensor"
|
||||
},
|
||||
asset: {
|
||||
category: "sensor",
|
||||
type: "pressure",
|
||||
model: "testmodel",
|
||||
supplier: "vega"
|
||||
},
|
||||
scaling: {
|
||||
absMin: 0,
|
||||
absMax: 4000,
|
||||
sequences:{
|
||||
startup:["starting","warmingup","operational"],
|
||||
shutdown:["stopping","coolingdown","idle"],
|
||||
emergencystop:["emergencystop","off"],
|
||||
boot:["idle","starting","warmingup","operational"]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const stateConfig = {
|
||||
time:{starting:0, warmingup:0, stopping:0, coolingdown:0},
|
||||
movement:{speed:1000, mode:"staticspeed"},
|
||||
async function bootstrapGroup() {
|
||||
const groupCfg = {
|
||||
general:{ logging:{enabled:false,logLevel:"warn"}, name:"testmachinegroup" },
|
||||
functionality:{ softwareType:"machinegroup", role:"groupcontroller" },
|
||||
scaling:{ current:"normalized" },
|
||||
mode:{ current:"optimalcontrol" }
|
||||
};
|
||||
|
||||
const mg = new MachineGroup(groupCfg);
|
||||
const pt = new Measurement(ptConfig);
|
||||
|
||||
for (let idx=1; idx<=2; idx++){
|
||||
const machine = new Machine(createMachineConfig(String(idx),`machine-${idx}`), stateConfig);
|
||||
mg.childRegistrationUtils.registerChild(machine,"downstream");
|
||||
machine.childRegistrationUtils.registerChild(pt,"downstream");
|
||||
}
|
||||
pt.calculateInput(1000);
|
||||
await sleep(10);
|
||||
return { mg, pt };
|
||||
}
|
||||
|
||||
async function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
function captureState(mg,label){
|
||||
return {
|
||||
label,
|
||||
machines: Object.entries(mg.machines).map(([id,machine]) => ({
|
||||
id,
|
||||
state: machine.state.getCurrentState(),
|
||||
position: machine.state.getCurrentPosition(),
|
||||
predictedFlow: machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0,
|
||||
predictedPower: machine.measurements.type("power").variant("predicted").position("upstream").getCurrentValue() || 0
|
||||
})),
|
||||
totals: {
|
||||
flow: mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0,
|
||||
power: mg.measurements.type("power").variant("predicted").position("upstream").getCurrentValue() || 0,
|
||||
efficiency: mg.measurements.type("efficiency").variant("predicted").position("downstream").getCurrentValue() || 0
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function logMachineStates(mg, testName) {
|
||||
console.log(`\n=== ${testName} ===`);
|
||||
console.log(`scaling: ${mg.scaling}, mode: ${mg.mode}`);
|
||||
console.log(`flow range: ${mg.dynamicTotals.flow.min.toFixed(2)} - ${mg.dynamicTotals.flow.max.toFixed(2)} m3/h`);
|
||||
|
||||
Object.entries(mg.machines).forEach(([id, machine]) => {
|
||||
const state = machine.state.getCurrentState();
|
||||
const flow = machine.measurements?.type("flow")?.variant("predicted")?.position("downstream")?.getCurrentValue() || 0;
|
||||
const power = machine.measurements?.type("power")?.variant("predicted")?.position("upstream")?.getCurrentValue() || 0;
|
||||
const position = machine.state?.getCurrentPosition();
|
||||
|
||||
console.log(`machine ${id}: state=${state}, position=${position.toFixed(2)}, flow=${flow.toFixed(2)}, power=${power.toFixed(2)}`);
|
||||
});
|
||||
|
||||
const totalFlow = mg.measurements?.type("flow")?.variant("predicted")?.position("downstream")?.getCurrentValue() || 0;
|
||||
const totalPower = mg.measurements?.type("power")?.variant("predicted")?.position("upstream")?.getCurrentValue() || 0;
|
||||
console.log(`total: flow=${totalFlow.toFixed(2)}, power=${totalPower.toFixed(2)}`);
|
||||
|
||||
// ADD THIS RETURN STATEMENT - this is what was missing!
|
||||
return {
|
||||
totalFlow,
|
||||
totalPower,
|
||||
efficiency: totalPower > 0 ? totalFlow / totalPower : 0
|
||||
};
|
||||
}
|
||||
|
||||
async function testPriorityVsOptimalEfficiency(mg, pt1) {
|
||||
|
||||
const demandIncrement = 1; // Test every 1% for detailed comparison
|
||||
console.log("\n🔬 PRIORITY vs OPTIMAL CONTROL EFFICIENCY COMPARISON");
|
||||
console.log("=".repeat(80));
|
||||
|
||||
const results = [];
|
||||
|
||||
console.log("\n📊 Testing OPTIMAL CONTROL (every 10% for speed)...");
|
||||
async function testNormalizedScaling(mg,pt){
|
||||
const label = "Normalized scaling tracks expected flow";
|
||||
try{
|
||||
mg.setScaling("normalized");
|
||||
mg.setMode("optimalcontrol");
|
||||
|
||||
// Test every 10% for speed and give machines time to start
|
||||
for (let demand = 0; demand <= 100; demand += demandIncrement) {
|
||||
try {
|
||||
console.log(`\n🔄 Setting optimal demand to ${demand}%`);
|
||||
await mg.handleInput("parent", demand);
|
||||
pt1.calculateInput(1400);
|
||||
|
||||
const data = logMachineStates(mg, `optimal ${demand}%`);
|
||||
|
||||
results.push({
|
||||
demand,
|
||||
optimal: {
|
||||
flow: data.totalFlow,
|
||||
power: data.totalPower,
|
||||
efficiency: data.efficiency
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`✅ optimal ${demand}%: flow=${data.totalFlow.toFixed(2)}, power=${data.totalPower.toFixed(2)}, eff=${data.efficiency.toFixed(4)}`);
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error at optimal ${demand}%:`, err.message);
|
||||
}
|
||||
const dynamic = mg.calcDynamicTotals();
|
||||
const checkpoints = [0,10,25,50,75,100];
|
||||
for (const demand of checkpoints){
|
||||
await mg.handleInput("parent", demand);
|
||||
pt.calculateInput(1400);
|
||||
await sleep(20);
|
||||
|
||||
const totals = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
||||
const expected = dynamic.flow.min + (demand/100)*(dynamic.flow.max - dynamic.flow.min);
|
||||
if(!approxEqual(totals, expected, 2)){
|
||||
throw new Error(`Flow ${totals.toFixed(2)} outside expectation ${expected.toFixed(2)} @ ${demand}%`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log("\n📊 Testing PRIORITY CONTROL (every 10% for speed)...");
|
||||
mg.setMode("prioritycontrol");
|
||||
|
||||
let resultIndex = 0;
|
||||
for (let demand = 0; demand <= 100; demand += demandIncrement) {
|
||||
try {
|
||||
console.log(`\n🔄 Setting priority demand to ${demand}%`);
|
||||
await mg.handleInput("parent", demand);
|
||||
pt1.calculateInput(1400);
|
||||
|
||||
const data = logMachineStates(mg, `priority ${demand}%`);
|
||||
|
||||
// Add priority data to existing result
|
||||
if (results[resultIndex]) {
|
||||
results[resultIndex].priority = {
|
||||
flow: data.totalFlow,
|
||||
power: data.totalPower,
|
||||
efficiency: data.efficiency
|
||||
};
|
||||
}
|
||||
|
||||
console.log(`✅ priority ${demand}%: flow=${data.totalFlow.toFixed(2)}, power=${data.totalPower.toFixed(2)}, eff=${data.efficiency.toFixed(4)}`);
|
||||
|
||||
resultIndex++;
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error at priority ${demand}%:`, err.message);
|
||||
resultIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
// Generate comparison report
|
||||
generateEfficiencyReport(results);
|
||||
logPass(label);
|
||||
}catch(err){ logFail(label, err); }
|
||||
}
|
||||
|
||||
// Add this report generation function
|
||||
function generateEfficiencyReport(results) {
|
||||
console.log("\n" + "=".repeat(100));
|
||||
console.log("📈 EFFICIENCY COMPARISON REPORT");
|
||||
console.log("=".repeat(100));
|
||||
|
||||
// Filter complete results with actual data
|
||||
const completeResults = results.filter(r =>
|
||||
r.optimal && r.priority &&
|
||||
r.optimal.power > 0 && r.priority.power > 0 &&
|
||||
r.optimal.flow > 0 && r.priority.flow > 0
|
||||
);
|
||||
|
||||
if (completeResults.length === 0) {
|
||||
console.log("❌ No complete results with active machines to compare");
|
||||
console.log("💡 This might indicate machines are not starting properly");
|
||||
|
||||
// Show what data we do have
|
||||
console.log("\n🔍 DEBUGGING DATA:");
|
||||
results.forEach(r => {
|
||||
if (r.optimal || r.priority) {
|
||||
console.log(`${r.demand}%: optimal=${r.optimal?.power || 'missing'}, priority=${r.priority?.power || 'missing'}`);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`\n📊 Successfully analyzed ${completeResults.length} test points with active machines`);
|
||||
|
||||
// Calculate summary statistics
|
||||
let totalPowerDiff = 0;
|
||||
let totalEffDiff = 0;
|
||||
let validComparisons = 0;
|
||||
|
||||
console.log("\n📋 DETAILED BREAKDOWN:");
|
||||
console.log("Demand | Optimal Power | Priority Power | Power Diff | Optimal Eff | Priority Eff | Eff Diff");
|
||||
console.log("-------|---------------|----------------|------------|-------------|--------------|----------");
|
||||
|
||||
completeResults.forEach(r => {
|
||||
const powerDiff = r.priority.power - r.optimal.power;
|
||||
const effDiff = r.priority.efficiency - r.optimal.efficiency;
|
||||
|
||||
totalPowerDiff += powerDiff;
|
||||
totalEffDiff += effDiff;
|
||||
validComparisons++;
|
||||
|
||||
console.log(
|
||||
`${r.demand}% | ${r.optimal.power.toFixed(3).padStart(11)} | ${r.priority.power.toFixed(3).padStart(12)} | ` +
|
||||
`${powerDiff.toFixed(3).padStart(8)} | ${r.optimal.efficiency.toFixed(4).padStart(9)} | ` +
|
||||
`${r.priority.efficiency.toFixed(4).padStart(10)} | ${effDiff.toFixed(4).padStart(7)}`
|
||||
);
|
||||
});
|
||||
|
||||
if (validComparisons > 0) {
|
||||
const avgPowerDiff = totalPowerDiff / validComparisons;
|
||||
const avgEffDiff = totalEffDiff / validComparisons;
|
||||
|
||||
console.log("\n📊 SUMMARY:");
|
||||
console.log(`Valid comparisons: ${validComparisons}`);
|
||||
console.log(`Average power difference: ${avgPowerDiff.toFixed(3)} kW`);
|
||||
console.log(`Average efficiency difference: ${avgEffDiff.toFixed(4)} m3/h per kW`);
|
||||
|
||||
console.log("\n💡 RECOMMENDATION:");
|
||||
if (avgEffDiff > 0.001) {
|
||||
console.log(`✅ Priority Control shows ${avgEffDiff.toFixed(4)} better efficiency on average`);
|
||||
} else if (avgEffDiff < -0.001) {
|
||||
console.log(`✅ Optimal Control shows ${Math.abs(avgEffDiff).toFixed(4)} better efficiency on average`);
|
||||
} else {
|
||||
console.log(`⚖️ Both control methods show similar efficiency`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function testNormalizedScaling(mg, pt1) {
|
||||
console.log("\n🧪 testing normalized scaling (0-100%)...");
|
||||
mg.setScaling("normalized");
|
||||
|
||||
//fetch ranges
|
||||
const maxflow = mg.dynamicTotals.flow.max;
|
||||
console.log(`max group flow capacity: ${maxflow.toFixed(2)} m3/h`);
|
||||
const minFlow = mg.dynamicTotals.flow.min;
|
||||
console.log(`min group flow capacity: ${minFlow.toFixed(2)} m3/h`);
|
||||
|
||||
const testPoints = [0, 10, 25, 50, 75, 90, 100];
|
||||
const testPressurePoints = [800, 1200, 1600, 2000];
|
||||
|
||||
for (const pressure of testPressurePoints) {
|
||||
try {
|
||||
console.log(`\n--- testing at ${pressure} mbar ---`);
|
||||
pt1.calculateInput(pressure);
|
||||
logMachineStates(mg, `${pressure} mbar, before demand tests`);
|
||||
|
||||
|
||||
for (const demand of testPoints) {
|
||||
try {
|
||||
console.log(`\n--- normalized demand: ${demand}% ---`);
|
||||
await mg.handleInput("parent", demand);
|
||||
|
||||
|
||||
logMachineStates(mg, `normalized ${demand}%`);
|
||||
|
||||
//check if total flow is within expected range
|
||||
const totalFlow = mg.measurements?.type("flow")?.variant("predicted")?.position("downstream")?.getCurrentValue() || 0;
|
||||
const expectedFlow = minFlow + (demand / 100) * (maxflow - minFlow);
|
||||
const percentTolerance = 0.1 ; // % tolerance of expected flow
|
||||
const tolerance = (expectedFlow * percentTolerance) / 100;
|
||||
|
||||
if (totalFlow < expectedFlow - tolerance || totalFlow > expectedFlow + tolerance) {
|
||||
console.warn(`⚠️ Total flow (${totalFlow.toFixed(2)} m3/h) is outside expected range (${(expectedFlow - tolerance).toFixed(2)} - ${(expectedFlow + tolerance).toFixed(2)} m3/h)`);
|
||||
}
|
||||
else {
|
||||
console.log( `Difference between expected and actual flow: ${(totalFlow - expectedFlow).toFixed(2)} m3/h`);
|
||||
console.log(`✅ Total flow (${totalFlow.toFixed(2)} m3/h) is within expected range (${(expectedFlow - tolerance).toFixed(2)} - ${(expectedFlow + tolerance).toFixed(2)} m3/h)`);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error at ${demand}%:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error setting pressure to ${pressure}:`, err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function testAbsoluteScaling(mg, pt1) {
|
||||
console.log("\n🧪 testing absolute scaling...");
|
||||
async function testAbsoluteScaling(mg,pt){
|
||||
const label = "Absolute scaling accepts direct flow targets";
|
||||
try{
|
||||
mg.setScaling("absolute");
|
||||
|
||||
mg.setMode("optimalcontrol");
|
||||
const absMin = mg.dynamicTotals.flow.min;
|
||||
const absMax = mg.dynamicTotals.flow.max;
|
||||
const testPoints = [
|
||||
absMin,
|
||||
absMin + 20,
|
||||
(absMin + absMax) / 2,
|
||||
absMax - 20,
|
||||
absMax
|
||||
];
|
||||
|
||||
for (const demand of testPoints) {
|
||||
try {
|
||||
console.log(`\n--- absolute demand: ${demand.toFixed(2)} m3/h ---`);
|
||||
await mg.handleInput("parent", demand);
|
||||
pt1.calculateInput(1400);
|
||||
|
||||
logMachineStates(mg, `absolute ${demand.toFixed(2)} m3/h`);
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error at ${demand.toFixed(2)}:`, err.message);
|
||||
}
|
||||
const demandPoints = [absMin, absMin+20, (absMin+absMax)/2, absMax-20];
|
||||
|
||||
for(const setpoint of demandPoints){
|
||||
await mg.handleInput("parent", setpoint);
|
||||
pt.calculateInput(1400);
|
||||
await sleep(20);
|
||||
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
||||
if(!approxEqual(flow, setpoint, 2)){
|
||||
throw new Error(`Flow ${flow.toFixed(2)} != demand ${setpoint.toFixed(2)}`);
|
||||
}
|
||||
}
|
||||
logPass(label);
|
||||
}catch(err){ logFail(label, err); }
|
||||
}
|
||||
|
||||
async function testControlModes(mg, pt1) {
|
||||
console.log("\n🧪 testing different control modes...");
|
||||
const modes = ["optimalcontrol", "prioritycontrol", "prioritypercentagecontrol"];
|
||||
const testDemand = 50; // 50% demand
|
||||
|
||||
async function testModeTransitions(mg,pt){
|
||||
const label = "Mode transitions keep machines responsive";
|
||||
try{
|
||||
const modes = ["optimalcontrol","prioritycontrol","prioritypercentagecontrol"];
|
||||
mg.setScaling("normalized");
|
||||
|
||||
for (const mode of modes) {
|
||||
try {
|
||||
console.log(`\n--- testing ${mode} ---`);
|
||||
mg.setMode(mode);
|
||||
await mg.handleInput("parent", testDemand);
|
||||
pt1.calculateInput(1400);
|
||||
|
||||
logMachineStates(mg, `${mode} at ${testDemand}%`);
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error testing mode ${mode}:`, err.message);
|
||||
}
|
||||
for(const mode of modes){
|
||||
mg.setMode(mode);
|
||||
await mg.handleInput("parent", 50);
|
||||
pt.calculateInput(1300);
|
||||
await sleep(20);
|
||||
const snapshot = captureState(mg, mode);
|
||||
const active = snapshot.machines.filter(m => m.state !== "idle");
|
||||
if(active.length === 0){
|
||||
throw new Error(`No active machines after switching to ${mode}`);
|
||||
}
|
||||
}
|
||||
logPass(label);
|
||||
}catch(err){ logFail(label, err); }
|
||||
}
|
||||
|
||||
async function testRampUpDown(mg, pt1) {
|
||||
console.log("\n🧪 testing ramp up and down...");
|
||||
mg.setScaling("normalized");
|
||||
async function testRampBehaviour(mg,pt){
|
||||
const label = "Ramp up/down keeps monotonic flow";
|
||||
try{
|
||||
mg.setMode("optimalcontrol");
|
||||
|
||||
// Ramp up
|
||||
console.log("\n--- ramp up test ---");
|
||||
for (let demand = 0; demand <= 100; demand += 20) {
|
||||
try {
|
||||
console.log(`ramping up to ${demand}%`);
|
||||
await mg.handleInput("parent", demand);
|
||||
pt1.calculateInput(1400);
|
||||
|
||||
if (demand % 40 === 0) { // Log every other step
|
||||
logMachineStates(mg, `ramp up ${demand}%`);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error ramping up to ${demand}%:`, err.message);
|
||||
}
|
||||
mg.setScaling("normalized");
|
||||
const upDemands = [0,20,40,60,80,100];
|
||||
let lastFlow = 0;
|
||||
for(const demand of upDemands){
|
||||
await mg.handleInput("parent", demand);
|
||||
pt.calculateInput(1500);
|
||||
await sleep(15);
|
||||
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
||||
if(flow < lastFlow - 1){
|
||||
throw new Error(`Flow decreased during ramp up: ${flow.toFixed(2)} < ${lastFlow.toFixed(2)}`);
|
||||
}
|
||||
lastFlow = flow;
|
||||
}
|
||||
|
||||
// Ramp down
|
||||
console.log("\n--- ramp down test ---");
|
||||
for (let demand = 100; demand >= 0; demand -= 20) {
|
||||
try {
|
||||
console.log(`ramping down to ${demand}%`);
|
||||
await mg.handleInput("parent", demand);
|
||||
pt1.calculateInput(1400);
|
||||
|
||||
if (demand % 40 === 0) { // Log every other step
|
||||
logMachineStates(mg, `ramp down ${demand}%`);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error ramping down to ${demand}%:`, err.message);
|
||||
}
|
||||
const downDemands = [100,80,60,40,20,0];
|
||||
lastFlow = Infinity;
|
||||
for(const demand of downDemands){
|
||||
await mg.handleInput("parent", demand);
|
||||
pt.calculateInput(1200);
|
||||
await sleep(15);
|
||||
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
||||
if(flow > lastFlow + 1){
|
||||
throw new Error(`Flow increased during ramp down: ${flow.toFixed(2)} > ${lastFlow.toFixed(2)}`);
|
||||
}
|
||||
lastFlow = flow;
|
||||
}
|
||||
logPass(label);
|
||||
}catch(err){ logFail(label, err); }
|
||||
}
|
||||
|
||||
async function testPressureResponse(mg, pt1) {
|
||||
console.log("\n🧪 testing pressure response...");
|
||||
mg.setScaling("normalized");
|
||||
async function testPressureAdaptation(mg,pt){
|
||||
const label = "Pressure changes update predictions";
|
||||
try{
|
||||
mg.setMode("optimalcontrol");
|
||||
|
||||
const pressures = [800, 1200, 1600, 2000];
|
||||
const demand = 50;
|
||||
|
||||
mg.setScaling("normalized");
|
||||
const pressures = [800,1200,1600,2000];
|
||||
let previousFlow = null;
|
||||
for(const p of pressures){
|
||||
pt.calculateInput(p);
|
||||
await mg.handleInput("parent", 50);
|
||||
await sleep(20);
|
||||
const flow = mg.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue() || 0;
|
||||
if(previousFlow !== null && Math.abs(flow - previousFlow) < 0.5){
|
||||
throw new Error(`Flow did not react to pressure shift (${previousFlow.toFixed(2)} -> ${flow.toFixed(2)})`);
|
||||
}
|
||||
previousFlow = flow;
|
||||
}
|
||||
logPass(label);
|
||||
}catch(err){ logFail(label, err); }
|
||||
}
|
||||
|
||||
|
||||
async function comparePriorityVsOptimal(mg, pt){
|
||||
const label = "Priority vs Optimal efficiency comparison";
|
||||
try{
|
||||
mg.setScaling("normalized");
|
||||
const pressures = [800, 1100, 1400, 1700];
|
||||
const demands = [...Array(21)].map((_, idx) => idx * 5);
|
||||
|
||||
for (const pressure of pressures) {
|
||||
try {
|
||||
console.log(`\n--- testing at ${pressure} mbar ---`);
|
||||
pt1.calculateInput(pressure);
|
||||
await mg.handleInput("parent", demand);
|
||||
pt.calculateInput(pressure);
|
||||
await sleep(15);
|
||||
|
||||
|
||||
logMachineStates(mg, `${pressure} mbar, ${demand}%`);
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error at pressure ${pressure}:`, err.message);
|
||||
}
|
||||
for (const demand of demands) {
|
||||
mg.setMode("optimalcontrol");
|
||||
await mg.handleInput("parent", demand);
|
||||
pt.calculateInput(pressure);
|
||||
await sleep(20);
|
||||
const optimalTotals = captureState(mg, `optimal-${pressure}-${demand}`).totals;
|
||||
|
||||
mg.setMode("prioritycontrol");
|
||||
await mg.handleInput("parent", demand);
|
||||
pt.calculateInput(pressure);
|
||||
await sleep(20);
|
||||
const priorityTotals = captureState(mg, `priority-${pressure}-${demand}`).totals;
|
||||
|
||||
efficiencyComparisons.push({
|
||||
pressure,
|
||||
demandPercent: demand,
|
||||
optimalFlow: Number(optimalTotals.flow.toFixed(3)),
|
||||
optimalPower: Number(optimalTotals.power.toFixed(3)),
|
||||
optimalEfficiency: Number((optimalTotals.efficiency || 0).toFixed(4)),
|
||||
priorityFlow: Number(priorityTotals.flow.toFixed(3)),
|
||||
priorityPower: Number(priorityTotals.power.toFixed(3)),
|
||||
priorityEfficiency: Number((priorityTotals.efficiency || 0).toFixed(4)),
|
||||
efficiencyDelta: Number(((priorityTotals.efficiency || 0) - (optimalTotals.efficiency || 0)).toFixed(4)),
|
||||
powerDelta: Number((priorityTotals.power - optimalTotals.power).toFixed(3))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
logPass(label, "efficiencyComparisons array populated");
|
||||
} catch (err) {
|
||||
logFail(label, err);
|
||||
}
|
||||
}
|
||||
|
||||
async function testEdgeCases(mg, pt1) {
|
||||
console.log("\n🧪 testing edge cases...");
|
||||
mg.setScaling("normalized");
|
||||
mg.setMode("optimalcontrol");
|
||||
|
||||
const edgeCases = [
|
||||
{ demand: -10, name: "negative demand" },
|
||||
{ demand: 0, name: "zero demand" },
|
||||
{ demand: 0.5, name: "fractional demand" },
|
||||
{ demand: 110, name: "over 100%" },
|
||||
{ demand: 999, name: "extreme demand" }
|
||||
];
|
||||
|
||||
for (const testCase of edgeCases) {
|
||||
try {
|
||||
console.log(`\n--- testing ${testCase.name}: ${testCase.demand} ---`);
|
||||
await mg.handleInput("parent", testCase.demand);
|
||||
pt1.calculateInput(1400);
|
||||
|
||||
logMachineStates(mg, testCase.name);
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error testing ${testCase.name}:`, err.message);
|
||||
}
|
||||
}
|
||||
async function run(){
|
||||
console.log("🚀 Starting machine-group integration tests...");
|
||||
const { mg, pt } = await bootstrapGroup();
|
||||
|
||||
await testNormalizedScaling(mg, pt);
|
||||
await testAbsoluteScaling(mg, pt);
|
||||
await testModeTransitions(mg, pt);
|
||||
await testRampBehaviour(mg, pt);
|
||||
await testPressureAdaptation(mg, pt);
|
||||
await comparePriorityVsOptimal(mg, pt);
|
||||
|
||||
console.log("\n📋 TEST SUMMARY");
|
||||
console.table(testSuite);
|
||||
console.log("\n📊 efficiencyComparisons:");
|
||||
console.dir(efficiencyComparisons, { depth:null });
|
||||
console.log("✅ All tests completed.");
|
||||
}
|
||||
|
||||
async function testPerformanceMetrics(mg, pt1) {
|
||||
console.log("\n🧪 testing performance metrics...");
|
||||
mg.setScaling("normalized");
|
||||
mg.setMode("optimalcontrol");
|
||||
|
||||
const demands = [25, 50, 75];
|
||||
const results = [];
|
||||
|
||||
for (const demand of demands) {
|
||||
try {
|
||||
const startTime = Date.now();
|
||||
await mg.handleInput("parent", demand);
|
||||
pt1.calculateInput(1400);
|
||||
const endTime = Date.now();
|
||||
|
||||
const totalFlow = mg.measurements?.type("flow")?.variant("predicted")?.position("downstream")?.getCurrentValue() || 0;
|
||||
const totalPower = mg.measurements?.type("power")?.variant("predicted")?.position("upstream")?.getCurrentValue() || 0;
|
||||
const efficiency = totalFlow > 0 ? (totalFlow / totalPower).toFixed(3) : 0;
|
||||
|
||||
results.push({
|
||||
demand,
|
||||
flow: totalFlow.toFixed(2),
|
||||
power: totalPower.toFixed(2),
|
||||
efficiency,
|
||||
responseTime: endTime - startTime
|
||||
});
|
||||
|
||||
|
||||
} catch (err) {
|
||||
console.error(`❌ error testing performance at ${demand}%:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
console.log("\n=== performance summary ===");
|
||||
console.log("demand | flow | power | efficiency | response(ms)");
|
||||
console.log("-------|--------|--------|-----------|---------");
|
||||
results.forEach(r => {
|
||||
console.log(`${r.demand}% | ${r.flow} | ${r.power} | ${r.efficiency} | ${r.responseTime}`);
|
||||
});
|
||||
}
|
||||
|
||||
async function runAllTests() {
|
||||
console.log("🚀 starting comprehensive machinegroup tests...\n");
|
||||
|
||||
try {
|
||||
// Setup
|
||||
const machineGroupConfig = createBaseMachineGroupConfig("testmachinegroup");
|
||||
const machineConfigs = {};
|
||||
machineConfigs[1] = createBaseMachineConfig(1, "testmachine1", specs);
|
||||
machineConfigs[2] = createBaseMachineConfig(2, "testmachine2", specs);
|
||||
|
||||
const mg = new MachineGroup(machineGroupConfig);
|
||||
const pt1 = new Measurement(ptConfig);
|
||||
const numofMachines = 2;
|
||||
|
||||
// Register machines
|
||||
for (let i = 1; i <= numofMachines; i++) {
|
||||
const machine = new Machine(machineConfigs[i],stateConfig);
|
||||
mg.childRegistrationUtils.registerChild(machine, "downstream");
|
||||
}
|
||||
|
||||
mg.machines[1].childRegistrationUtils.registerChild(pt1, "downstream");
|
||||
mg.machines[2].childRegistrationUtils.registerChild(pt1, "downstream");
|
||||
|
||||
console.log(`✅ setup complete: ${Object.keys(mg.machines).length} machines registered`);
|
||||
console.log(`flow range: ${mg.dynamicTotals.flow.min.toFixed(2)} - ${mg.dynamicTotals.flow.max.toFixed(2)} m3/h\n`);
|
||||
|
||||
// Run test suites
|
||||
//await testPriorityVsOptimalEfficiency(mg, pt1);
|
||||
await testNormalizedScaling(mg, pt1);
|
||||
await testAbsoluteScaling(mg, pt1);
|
||||
await testControlModes(mg, pt1);
|
||||
await testRampUpDown(mg, pt1);
|
||||
await testPressureResponse(mg, pt1);
|
||||
await testEdgeCases(mg, pt1);
|
||||
await testPerformanceMetrics(mg, pt1);
|
||||
|
||||
console.log("\n🎉 all tests completed successfully!");
|
||||
|
||||
} catch (err) {
|
||||
console.error("💥 test suite failed:", err.message);
|
||||
console.error("stack trace:", err.stack);
|
||||
}
|
||||
}
|
||||
run().catch(err => {
|
||||
console.error("💥 Test harness crashed:", err);
|
||||
});
|
||||
// ...existing code...
|
||||
|
||||
// Run all tests
|
||||
runAllTests();
|
||||
run();
|
||||
Reference in New Issue
Block a user