Files
bus-capacitor-calculator/tests/motor-bus-recommend.test.cjs
gaochengyu 73ab36f7ff feat: 开源母线电容计算器并接入独立自动部署
整理 Buck 与 PMSM 完整源码、离线构建、校核测试和使用说明,采用 MIT 许可。
增加页首开源链接,支持推送 main 后自动测试、构建并发布到原计算器网址。
2026-11-27 04:38:28 +08:00

177 lines
12 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const engine = require('../src/motor-bus-engine.js');
const supply = require('../src/motor-bus-supply.js');
const harness = require('../src/buck-harness-engine.js');
const ampacity = require('../src/buck-wire-ampacity.js');
const recommendEngine = require('../src/motor-bus-recommend.js');
const { recommend } = recommendEngine;
const source = fs.readFileSync(require.resolve('../src/motor-bus-recommend.js'), 'utf8');
let passed = 0;
async function test(name, run) { await run(); passed++; console.log('✓ ' + name); }
function close(actual, expected, rel = 1e-9, abs = 1e-11) {
assert.ok(Number.isFinite(actual));
assert.ok(Math.abs(actual - expected) <= abs + rel * Math.max(Math.abs(actual), Math.abs(expected)), `实际 ${actual},预期 ${expected}`);
}
function c(dc, amp = 1, f0 = 20000, im = 0) {
return { dc, f0, duration: 1 / f0, k: Uint32Array.of(1), freq: Float64Array.of(f0), re: Float64Array.of(amp), im: Float64Array.of(im) };
}
function scan(rated, locked = []) { return { motor: { Vdc: 24, fsw: 20000 }, rated: { cases: rated }, locked: { cases: locked } }; }
function browserAPI(pointMetrics = supply.pointMetrics) {
const sandbox = { BuckHarness: harness, BuckWireAmpacity: ampacity,
MotorBusSupply: { ...supply, pointMetrics }, setTimeout };
vm.runInNewContext(source, sandbox);
return sandbox.MotorBusRecommend;
}
const controls = { yieldEvery: 100 };
async function rejects(run) { await assert.rejects(run, error => error instanceof Error && /[\u4e00-\u9fff]/.test(error.message)); }
(async () => {
await test('CommonJS/浏览器/Worker全局接口与依赖顺序明确', async () => {
assert.equal(globalThis.MotorBusRecommend, recommendEngine); assert.ok(Object.isFrozen(recommendEngine));
const api = browserAPI(); assert.equal(typeof api.recommend, 'function');
const input = scan([c(2, 4)], [c(20, 8)]);
const config = { coarse: 18, fine: 18, target: 0.2, dropPct: 10 };
const a = await api.recommend(input, config, controls), b = await recommend(input, config, controls);
close(a.selected.C, b.selected.C); close(a.selected.rated.ppSample, b.selected.rated.ppSample);
assert.throws(() => vm.runInNewContext(source, {}), /需要先加载/);
});
await test('小解析单正弦case完整复核有限带pp和RMS,与Supply一致', async () => {
const input = scan([c(2, 4, 20000, 1)], [c(20, 8)]);
const result = await recommend(input, { coarse: 18, fine: 18, target: 0.2, dropPct: 10 }, controls);
const row = result.selected; assert.ok(row); assert.equal(row.status, 'pass');
const point = supply.pointMetrics(input.rated.cases[0], row.branch, { target: 0.2, gridFactor: 8 });
close(row.rated.ppSample, point.ppSample); close(row.rated.ppUpper, point.ppUpper);
close(row.rated.sourceRms, point.sourceRms); close(row.rated.capRms, point.capRms);
const Z = supply.impedance(row.branch, 20000).amp;
const amplitude = Math.hypot(4, 1);
assert.ok(row.rated.ppSample <= 2 * Z * amplitude + 1e-10);
assert.ok(row.rated.ppUpper >= 2 * Z * amplitude - 1e-10);
assert.equal(row.rated.caseCount, 1); assert.equal(row.locked.caseCount, 1);
assert.equal(row.rated.allBandwidthStatus, 'unknown'); assert.equal(row.rated.totalPpUpper, null);
assert.ok(result.scope.includes('不含带外谐波'));
});
await test('正负Idc按绝对值检查压差,回馈不能绕过筛选', async () => {
const config = { coarse: 12, fine: 12, includeLocked: false, wire: { lengthM: 5 }, dropPct: 1 };
const positive = await recommend(scan([c(10, 0)]), config, controls);
const negative = await recommend(scan([c(-10, 0)]), config, controls);
assert.equal(positive.selected, null); assert.equal(negative.selected, null);
assert.equal(negative.rows[0].status, 'fail'); assert.ok(negative.rows[0].reason.includes('|R·Idc|'));
close(negative.rows[0].rated.maxAbsDcDropV, positive.rows[0].rated.maxAbsDcDropV);
assert.equal(negative.caseEvaluations, 0); assert.equal(positive.caseEvaluations, 0);
});
await test('连续额度仅筛额定组,短时锁转RMS另列且可选电压约束', async () => {
const input = scan([c(1, 1)], [c(40, 1)]);
const config = { coarse: 18, fine: 18, dropPct: 20 };
const result = await recommend(input, config, controls), row = result.selected;
assert.ok(row); assert.ok(row.rated.sourceRms < row.rating.currentLimit);
assert.ok(row.locked.sourceRms > row.rating.currentLimit * 5);
assert.ok(row.lockedNotice.includes('短时')); assert.ok(row.lockedNotice.includes('未拿连续'));
const ignored = await recommend(input, { ...config, includeLocked: false, dropPct: 1 }, controls);
assert.ok(ignored.selected); assert.equal(ignored.selected.locked, null);
const lockedDropFail = await recommend(input, { ...config, dropPct: 1 }, controls);
assert.equal(lockedDropFail.selected, null); assert.ok(lockedDropFail.rows[0].reason.includes('锁转'));
});
await test('按最高AWG选最细pass,几何/经验表/手填RMS早拒均生效', async () => {
const input = scan([c(6, 2)]);
const result = await recommend(input, { coarse: 14, fine: 18, includeLocked: false }, controls);
assert.deepEqual(result.rows.map(r => r.awg), [18, 16, 14]);
assert.equal(result.selected.awg, 16); assert.equal(result.rows[0].status, 'fail');
assert.equal(result.rows[1].rating.currentLimit, ampacity.limit(16).currentLimit);
const manual = await recommend(input, { coarse: 18, fine: 18, manualRms: 10, includeLocked: false }, controls);
assert.equal(manual.selected, null); assert.equal(manual.evaluations, 0);
const bad = await recommend(input, { coarse: 18, fine: 18, includeLocked: false, wire: { lengthM: -1 } }, controls);
assert.equal(bad.rows[0].status, 'uncertain'); assert.ok(bad.rows[0].reason.includes('几何'));
});
await test('细化后容值经过所有工况复核,并给出实际合成纹波', async () => {
const calls = [];
const api = browserAPI((input, branch, options) => { calls.push({ input, branch: { ...branch }, options }); return supply.pointMetrics(input, branch, options); });
const input = scan([c(1, 2), c(-1, 3, 20000, 0.2)], [c(10, 5)]);
const result = await api.recommend(input, { coarse: 18, fine: 18, dropPct: 10 }, controls), row = result.selected;
assert.ok(row); assert.equal(row.C, row.branch.C);
const passingCalls = calls.filter(x => x.branch.C === row.C);
assert.equal(passingCalls.length, 3);
assert.equal(new Set(passingCalls.map(x => x.input)).size, 3);
assert.equal(row.rated.caseCount, 2); assert.equal(row.locked.caseCount, 1);
assert.ok(passingCalls.every(x => x.options.gridFactor === 8 && x.options.waveform === false));
const exact = supply.evaluate(input.rated.cases, row.branch, { target: 0.5 });
close(row.rated.ppSample, exact.maxPpSample); close(row.rated.ppUpper, exact.maxPpUpper);
});
await test('目标加10%是推荐复核上限,超过该上限仍拒绝', async () => {
const input=scan([c(1,0)]),config={coarse:18,fine:18,target:.5,includeLocked:false};
const api=browserAPI((input,branch,options)=>({...supply.pointMetrics(input,branch,options),ppSample:.525,ppUpper:.525}));
const accepted=await api.recommend(input,config,controls);
close(accepted.rippleLimit,.55);assert.ok(accepted.selected);
assert.ok(accepted.selected.rated.ppUpper>accepted.target);
assert.ok(accepted.selected.rated.ppUpper<=accepted.rippleLimit);
const over=browserAPI((input,branch,options)=>({...supply.pointMetrics(input,branch,options),ppSample:.56,ppUpper:.56}));
assert.equal((await over.recommend(input,config,controls)).selected,null);
});
await test('必要条件过关但完整波形峰峰值超标时拒绝候选', async () => {
let calls = 0;
const api = browserAPI((input, branch, options) => {
calls++; return { ...supply.pointMetrics(input, branch, options), ppSample: 0.01, ppUpper: options.target * 2 };
});
const result = await api.recommend(scan([c(1, 0)]), { coarse: 18, fine: 18, includeLocked: false }, controls);
assert.equal(result.selected, null); assert.equal(result.rows[0].C, null);
assert.ok(calls >= 1); assert.ok(result.rows[0].reason.includes('峰峰值上界'));
});
await test('多case取各指标最差值但不拼相位、不返回巨大单点数组', async () => {
const input = scan([c(2, 2), c(-3, 4, 10000, 3)], [c(20, 8)]);
const result = await recommend(input, { coarse: 16, fine: 16, dropPct: 10, target: 0.3 }, controls), row = result.selected;
assert.ok(row);
const expected = supply.evaluate(input.rated.cases, row.branch, { target: 0.3 });
close(row.rated.ppSample, expected.maxPpSample); close(row.rated.ppUpper, expected.maxPpUpper);
close(row.rated.sourceRms, expected.maxSourceRms); close(row.rated.capRms, expected.maxCapRms);
assert.equal(Object.hasOwn(row.rated, 'results'), false); assert.equal(Object.hasOwn(row, 'cases'), false);
assert.equal(Object.hasOwn(row.rated, 'wave'), false);
});
await test('缺组/非法输入/非共周期拒绝,未知条件不伪装通过', async () => {
await rejects(() => recommend(scan([])));
await rejects(() => recommend(scan([c(1)], [])));
await rejects(() => recommend({ ...scan([c(1)], [c(1)]), cancelled: true }));
for (const config of [{ coarse: 5 }, { fine: 25 }, { coarse: 17, fine: 17 }, { target: 0 },
{ manualRms: -1 }, { includeLocked: 1 }, { dropPct: 100 }, { ambientC: 51 }, { installation: 'bad' }]) {
await rejects(() => recommend(scan([c(1)], [c(1)]), config));
}
await rejects(() => recommend(scan([{ ...c(1), freq: Float64Array.of(123) }], [c(1)])));
await rejects(() => recommend(scan([c(1)], [c(1)]), {}, { shouldCancel: 1 }));
});
await test('异步进度/取消会丢弃部分结果,不遗留可选旧推荐', async () => {
const input = scan([c(2, 4)], [c(20, 8)]);
let progress = 0;
const result = await recommend(input, { coarse: 12, fine: 18, dropPct: 10 }, {
yieldEvery: 1, onProgress() { progress++; }, shouldCancel: () => progress >= 3
});
assert.equal(result.cancelled, true); assert.equal(result.selected, null); assert.deepEqual(result.rows, []);
assert.equal(progress, 3);
});
await test('真实默认270工况:所有pass行对完整额定/锁转频带均可独立复核', async () => {
const started = Date.now();
const realScan = engine.scan({}, { nSpeed: 16, nCurrent: 4, nAngle: 9 });
assert.equal(realScan.evaluated, 270);
const scanMs = Date.now() - started, startRecommend = Date.now();
const result = await recommend(realScan, {}, controls);
const recommendationMs = Date.now() - startRecommend;
assert.equal(result.cancelled, false); assert.equal(result.rows.length, 10);
assert.equal(result.selected.awg, 12);
for (const row of result.rows.filter(r => r.status === 'pass')) {
assert.equal(row.rated.caseCount, realScan.rated.cases.length);
assert.equal(row.locked.caseCount, realScan.locked.cases.length);
assert.ok(row.rated.ppUpper <= result.rippleLimit && row.locked.ppUpper <= result.rippleLimit);
assert.ok(row.designRms <= row.rating.currentLimit);
assert.equal(row.C, row.branch.C);
}
const selected = result.selected;
const rated = supply.evaluate(realScan.rated.cases, selected.branch, { target: 0.5 });
const locked = supply.evaluate(realScan.locked.cases, selected.branch, { target: 0.5 });
close(selected.rated.ppSample, rated.maxPpSample); close(selected.rated.ppUpper, rated.maxPpUpper);
close(selected.locked.ppSample, locked.maxPpSample); close(selected.locked.ppUpper, locked.maxPpUpper);
close(selected.designRms, rated.maxSourceRms);
console.log(` 270工况基准:scan ${scanMs}ms;recommend ${recommendationMs}ms;C候选${result.evaluations},精确IFFT ${result.caseEvaluations}`);
});
console.log(`\n${passed} 项电机线材与电容推荐测试全部通过。`);
})().catch(error => { console.error(error); process.exitCode = 1; });