From cbc0840f0ce5043319640fa4143a732a922d4b18 Mon Sep 17 00:00:00 2001 From: znetsixe <73483679+znetsixe@users.noreply.github.com> Date: Tue, 23 Sep 2025 15:03:57 +0200 Subject: [PATCH] added testfile fixing bugs --- src/groupcontrol.test.js | 526 +++++++++++++++++++++++++++++++++++++++ src/nodeClass.js | 3 +- src/specificClass.js | 57 +---- 3 files changed, 539 insertions(+), 47 deletions(-) create mode 100644 src/groupcontrol.test.js diff --git a/src/groupcontrol.test.js b/src/groupcontrol.test.js new file mode 100644 index 0000000..edb56b5 --- /dev/null +++ b/src/groupcontrol.test.js @@ -0,0 +1,526 @@ +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 ptConfig = { + general: { + logging: { enabled: true, logLevel: "debug" }, + name: "testpt", + id: "0", + unit: "mbar", + }, + functionality: { + softwareType: "measurement", + role: "sensor" + }, + asset: { + category: "sensor", + type: "pressure", + model: "testmodel", + supplier: "vega" + }, + scaling: { + absMin: 0, + absMax: 4000, + } +} + +const stateConfig = { + time:{starting:0, warmingup:0, stopping:0, coolingdown:0}, + movement:{speed:1000, mode:"staticspeed"}, +} + +async function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +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)..."); + 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); + } + } + + 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); +} + +// 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"); + + //first set pressure: + pt1.inputValue = 1400; + + //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]; + + for (const demand of testPoints) { + try { + console.log(`\n--- normalized demand: ${demand}% ---`); + await mg.handleInput("parent", demand); + + + logMachineStates(mg, `normalized ${demand}%`); + + } catch (err) { + console.error(`โŒ error at ${demand}%:`, err.message); + } + } +} + +async function testAbsoluteScaling(mg, pt1) { + console.log("\n๐Ÿงช testing absolute scaling..."); + mg.setScaling("absolute"); + + 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); + } + } +} + +async function testControlModes(mg, pt1) { + console.log("\n๐Ÿงช testing different control modes..."); + const modes = ["optimalcontrol", "prioritycontrol", "prioritypercentagecontrol"]; + const testDemand = 50; // 50% demand + + 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); + } + } +} + +async function testRampUpDown(mg, pt1) { + console.log("\n๐Ÿงช testing ramp up and down..."); + mg.setScaling("normalized"); + 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); + } + } + + // 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); + } + } +} + +async function testPressureResponse(mg, pt1) { + console.log("\n๐Ÿงช testing pressure response..."); + mg.setScaling("normalized"); + mg.setMode("optimalcontrol"); + + const pressures = [800, 1200, 1600, 2000]; + const demand = 50; + + for (const pressure of pressures) { + try { + console.log(`\n--- testing at ${pressure} mbar ---`); + pt1.calculateInput(pressure); + await mg.handleInput("parent", demand); + + + logMachineStates(mg, `${pressure} mbar, ${demand}%`); + + } catch (err) { + console.error(`โŒ error at pressure ${pressure}:`, err.message); + } + } +} + +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 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 all tests +runAllTests(); \ No newline at end of file diff --git a/src/nodeClass.js b/src/nodeClass.js index cce60c8..050982a 100644 --- a/src/nodeClass.js +++ b/src/nodeClass.js @@ -221,8 +221,7 @@ class nodeClass { case "setMode": const mode = msg.payload; - const source = "parent"; - mg.setMode(source, mode); + mg.setMode(mode); break; case "setScaling": diff --git a/src/specificClass.js b/src/specificClass.js index 399e1ba..30402b9 100644 --- a/src/specificClass.js +++ b/src/specificClass.js @@ -1,28 +1,4 @@ /** - * @file machine.js - * - * Permission is hereby granted to any person obtaining a copy of this software - * and associated documentation files (the "Software"), to use it for personal - * or non-commercial purposes, with the following restrictions: - * - * 1. **No Copying or Redistribution**: The Software or any of its parts may not - * be copied, merged, distributed, sublicensed, or sold without explicit - * prior written permission from the author. - * - * 2. **Commercial Use**: Any use of the Software for commercial purposes requires - * a valid license, obtainable only with the explicit consent of the author. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, - * OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - * - * Ownership of this code remains solely with the original author. Unauthorized - * use of this Software is strictly prohibited. - * * @summary A class to interact and manipulate machines with a non-euclidian curve * @description A class to interact and manipulate machines with a non-euclidian curve * @module machineGroup @@ -252,13 +228,11 @@ class MachineGroup { //machineId = parseInt(machineId); const state = machines[machineId].state.getCurrentState(); - - const validSourceForMode = machines[machineId].isValidSourceForMode("parent", "auto"); 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" || !validSourceForMode || !validActionForMode){ + if( state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validActionForMode){ return; } @@ -353,10 +327,6 @@ class MachineGroup { } // -------- Mode and Input Management -------- // - isValidSourceForMode(source, mode) { - const allowedSourcesSet = this.config.mode.allowedSources[mode] || []; - return allowedSourcesSet.has(source); - } isValidActionForMode(action, mode) { const allowedActionsSet = this.config.mode.allowedActions[mode] || []; @@ -531,10 +501,9 @@ class MachineGroup { filterOutUnavailableMachines(list) { const newList = list.filter(({ id, machine }) => { const state = machine.state.getCurrentState(); - const validSourceForMode = machine.isValidSourceForMode("parent", "auto"); const validActionForMode = machine.isValidActionForMode("execSequence", "auto"); - return !(state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validSourceForMode || !validActionForMode); + return !(state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validActionForMode); }); return newList; } @@ -806,12 +775,6 @@ class MachineGroup { async handleInput(source, Qd, powerCap = Infinity, priorityList = null) { - - if (!this.isValidSourceForMode(source, this.mode)) { - this.logger.warn(`Invalid source ${source} for mode ${this.mode}`); - return; - } - const scaling = this.scaling; const mode = this.mode; let rawInput = Qd; @@ -848,6 +811,10 @@ class MachineGroup { case "optimalcontrol": await this.optimalControl(Qd,powerCap); break; + + default: + this.logger.warn(`${mode} is not a valid mode.`); + break; } //recalc distance from BEP @@ -857,8 +824,8 @@ class MachineGroup { } - setMode(source,mode) { - this.isValidSourceForMode(source, mode) ? this.mode = mode : this.logger.warn(`Invalid source ${source} for mode ${mode}`); + setMode(mode) { + this.mode = mode; } getOutput() { @@ -1009,7 +976,7 @@ async function makeMachines(){ mg.machines[1].childRegistrationUtils.registerChild(pt1, "downstream"); mg.machines[2].childRegistrationUtils.registerChild(pt1, "downstream"); - mg.setMode("parent","prioritycontrol"); + //mg.setMode("prioritycontrol"); mg.setScaling("normalized"); const absMax = mg.dynamicTotals.flow.max; @@ -1047,9 +1014,9 @@ async function makeMachines(){ /* for(let demand = 0 ; demand <= 100 ; demand += 1){ //set pressure - - console.log("------------------------------------"); + console.log(`processing demand of ${demand}`); + await mg.handleInput("parent",demand); console.log(mg.machines[1].state.getCurrentState()); console.log(mg.machines[2].state.getCurrentState()); @@ -1071,4 +1038,4 @@ async function makeMachines(){ makeMachines(); -*/ \ No newline at end of file +//*/ \ No newline at end of file