feat: 开源母线电容计算器并接入独立自动部署
整理 Buck 与 PMSM 完整源码、离线构建、校核测试和使用说明,采用 MIT 许可。 增加页首开源链接,支持推送 main 后自动测试、构建并发布到原计算器网址。
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const accuracy=require('../src/buck-accuracy-engine.js');
|
||||
|
||||
// Frozen independent ngspice 46 fixtures, ideal synchronous Buck, Cout=2200 uF.
|
||||
// Finest transient maximum step T/8192; error = calculator / SPICE - 1.
|
||||
const fixtures=[
|
||||
{id:'BV0238',input:{vin:15.458206322975457,fsw:135434.65583067952,L:2.772909819523137e-6,iavg:.6706499610693777,D:.16843321004416784,R:.011389252466845913,Ls:3.7991307740620917e-7,C:2.4599129374100604e-5},spicePp:.18100548398990135,calcPp:.1804832103684394,tier:1},
|
||||
{id:'BV0360',input:{vin:23.77819098740816,fsw:10035.339421220124,L:2.204827760955319e-6,iavg:19.8589220456779,D:.1514770519249142,R:.0010550204811617732,Ls:1.0700912377331405e-5,C:.0005755906970465806},spicePp:3.053802599064099,calcPp:2.968762009731835,tier:3},
|
||||
{id:'BV0393',input:{vin:23.58033286370337,fsw:19871.921402215958,L:7.643392540351488e-5,iavg:4.9898645399138335,D:.49259504235815255,R:.00546036210656166,Ls:9.357682751957326e-7,C:8.576272778451178e-6},spicePp:13.181964585282248,calcPp:12.71537067643087,tier:5},
|
||||
{id:'BV0361',input:{vin:24.396451610997318,fsw:19865.651639178395,L:7.361992243747226e-5,iavg:5.05084116840735,D:.4983758472558111,R:.004618875935208053,Ls:1.0216104176826775e-6,C:2.269806856434103e-6},spicePp:16.564026064395136,calcPp:17.784641844026524,tier:'above5'}
|
||||
];
|
||||
function reference(input,options){return accuracy.reference({...input,drop:input.vin*(1-input.D),target:1},input,options);}
|
||||
|
||||
test('complete periodic reference agrees with independent SPICE across all four error bands',()=>{
|
||||
for(const f of fixtures){
|
||||
const ref=reference(f.input),estimate=accuracy.estimate(f.input,f.calcPp);
|
||||
assert.equal(ref.valid,true,f.id);assert.ok(ref.closure<1e-10,f.id);
|
||||
const observed=100*(f.calcPp/f.spicePp-1);
|
||||
assert.ok(Math.abs(estimate.errorPercent-observed)<.05,f.id);
|
||||
assert.equal(estimate.tier||(estimate.aboveFive?'above5':null),f.tier,f.id);
|
||||
assert.equal(Math.sign(estimate.errorPercent),Math.sign(observed),f.id);
|
||||
}
|
||||
});
|
||||
|
||||
test('reference extrema converge and scale linearly when voltages and currents scale together',()=>{
|
||||
for(const f of fixtures){
|
||||
const coarse=reference(f.input),fine=reference(f.input,{samples:8192});
|
||||
assert.ok(Math.abs(fine.pp/coarse.pp-1)<1e-6,f.id);
|
||||
const scaled=reference({...f.input,vin:f.input.vin*1.2,iavg:f.input.iavg*1.2});
|
||||
assert.ok(Math.abs(scaled.pp/(coarse.pp*1.2)-1)<1e-8,f.id);
|
||||
}
|
||||
});
|
||||
|
||||
test('coverage and invalid CCM references cannot produce an error band',()=>{
|
||||
const input=fixtures[0].input;
|
||||
for(const [key,[low,high]] of Object.entries(accuracy.limits)){
|
||||
for(const value of [low*.99,high*1.01,NaN]){
|
||||
const changed={...input,[key]:value};
|
||||
assert.ok(accuracy.coverage(changed).includes(key));
|
||||
assert.equal(accuracy.estimate(changed).tier,null);
|
||||
}
|
||||
}
|
||||
const invalid={vin:24,fsw:20000,L:75e-6,iavg:5,D:.5,R:.001,Ls:10e-6,C:6.332573977646111e-6};
|
||||
assert.equal(reference(invalid).valid,false);
|
||||
assert.equal(accuracy.estimate(invalid).tier,null);
|
||||
assert.throws(()=>reference({...input,R:0}));
|
||||
assert.throws(()=>reference(input,{samples:128}));
|
||||
});
|
||||
|
||||
test('guard margin assigns conservative bands and leaves the 5% boundary uncertain',()=>{
|
||||
const input=fixtures[0].input,pp=reference(input).pp;
|
||||
for(const sign of [-1,1])for(const [error,expected] of [[.94,1],[.98,3],[2.98,5],[4.9,5],[4.98,'boundary'],[5.02,'boundary'],[5.1,'above5']]){
|
||||
const estimate=accuracy.estimate(input,pp*(1+sign*error/100));
|
||||
assert.equal(estimate.tier||(estimate.aboveFive?'above5':estimate.boundary?'boundary':null),expected);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,334 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const engine = require('../src/buck-calculator-engine.js');
|
||||
const { operating, supplyHeadroom, harmonic, impedance, calculate, inverseFFT } = engine;
|
||||
|
||||
let passed = 0;
|
||||
function test(name, run) {
|
||||
run(); passed++;
|
||||
console.log('✓ ' + name);
|
||||
}
|
||||
function close(actual, expected, relative = 1e-9, absolute = 1e-11) {
|
||||
assert.ok(Number.isFinite(actual), 'actual must be finite: ' + actual);
|
||||
assert.ok(Math.abs(actual - expected) <= absolute + relative * Math.max(Math.abs(actual), Math.abs(expected)),
|
||||
`实际 ${actual},预期 ${expected}`);
|
||||
}
|
||||
const base = { vin: 24, drop: 12, iavg: 5, fsw: 20000, L: 75e-6, target: 0.12 };
|
||||
const op = operating(base);
|
||||
const normal = { R: 0.05, Ls: 1e-6, C: 470e-6 };
|
||||
function phasorQuadrature(work, n, points = 80000) {
|
||||
let re = 0, im = 0;
|
||||
for (let k = 0; k < points; k++) {
|
||||
const fraction = (k + 0.5) / points;
|
||||
const tOverT = work.D * fraction;
|
||||
const value = work.min + work.delta * fraction;
|
||||
const angle = 2 * Math.PI * n * tOverT;
|
||||
re += value * Math.cos(angle);
|
||||
im -= value * Math.sin(angle);
|
||||
}
|
||||
return { re: re * 2 * work.D / points, im: im * 2 * work.D / points };
|
||||
}
|
||||
function directVoltage(work, candidate, N, theta) {
|
||||
let value = 0;
|
||||
for (let n = 1; n <= N; n++) {
|
||||
const i = harmonic(work, n), z = impedance(candidate.R, candidate.Ls, candidate.C, i.omega);
|
||||
const vr = -(z.re * i.re - z.im * i.im);
|
||||
const vi = -(z.re * i.im + z.im * i.re);
|
||||
value += vr * Math.cos(n * theta) - vi * Math.sin(n * theta);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
test('CommonJS 和无依赖浏览器 globalThis 接口一致', () => {
|
||||
assert.equal(globalThis.BuckRLC, engine);
|
||||
const browser = {};
|
||||
vm.runInNewContext(fs.readFileSync(require.resolve('../src/buck-calculator-engine.js'), 'utf8'), browser);
|
||||
assert.equal(typeof browser.BuckRLC.calculate, 'function');
|
||||
assert.equal(typeof browser.BuckRLC.operating, 'function');
|
||||
assert.equal(typeof browser.BuckRLC.supplyHeadroom, 'function');
|
||||
assert.equal(browser.BuckRLC.operating(base).D, 0.5);
|
||||
});
|
||||
|
||||
test('工作点由 SI 输入正确计算,且 L 与 Ls 独立', () => {
|
||||
close(op.D, 0.5); close(op.IL, 10); close(op.delta, 4);
|
||||
close(op.min, 8); close(op.max, 12); close(op.ws, 40000 * Math.PI);
|
||||
for (const key of Object.keys(base)) assert.equal(op[key], base[key]);
|
||||
});
|
||||
|
||||
test('供电压差支持理想零电阻并准确区分耗尽压差的边界', () => {
|
||||
assert.deepEqual(supplyHeadroom(base, 0), {
|
||||
dcDrop: 0, averageBusVoltage: 24, targetOutputVoltage: 12, remainingVoltage: 12, feasible: true
|
||||
});
|
||||
const nominal = supplyHeadroom(base, 0.01);
|
||||
close(nominal.dcDrop, 0.05);
|
||||
close(nominal.averageBusVoltage, 23.95);
|
||||
close(nominal.remainingVoltage, 11.95);
|
||||
assert.equal(nominal.feasible, true);
|
||||
|
||||
const near = { ...base, vin: 100, drop: 1, iavg: 1 };
|
||||
const below = supplyHeadroom(near, 1 - 4 * Number.EPSILON);
|
||||
assert.equal(below.averageBusVoltage, below.targetOutputVoltage);
|
||||
assert.equal(below.remainingVoltage, 4 * Number.EPSILON);
|
||||
assert.equal(below.feasible, true);
|
||||
const exhausted = supplyHeadroom(near, 1);
|
||||
assert.equal(exhausted.remainingVoltage, 0);
|
||||
assert.equal(exhausted.feasible, false);
|
||||
assert.equal(supplyHeadroom(near, 1 + Number.EPSILON).feasible, false);
|
||||
const decimalTie = supplyHeadroom({ ...base, drop: 0.055, iavg: 5 }, 11 * 1e-3);
|
||||
assert.equal(decimalTie.remainingVoltage, 0);
|
||||
assert.equal(decimalTie.feasible, false);
|
||||
assert.throws(() => supplyHeadroom(base, -0.01), /电阻/);
|
||||
});
|
||||
|
||||
test('10%、50%、90% 占空比斜顶电流相量与直接积分吻合', () => {
|
||||
for (const D of [0.1, 0.5, 0.9]) {
|
||||
const work = operating({ ...base, drop: base.vin * (1 - D) });
|
||||
for (const n of [1, 2, 3, 9, 25]) {
|
||||
const exact = harmonic(work, n), numeric = phasorQuadrature(work, n);
|
||||
close(exact.re, numeric.re, 1e-6, 2e-8);
|
||||
close(exact.im, numeric.im, 1e-6, 2e-8);
|
||||
close(exact.amp, Math.hypot(exact.re, exact.im));
|
||||
assert.equal(exact.n, n); close(exact.omega, n * work.ws);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('50% 时保留斜率后偶次谐波不为零', () => {
|
||||
for (const n of [2, 4, 6, 10]) {
|
||||
const i = harmonic(op, n);
|
||||
close(i.re, 0, 0, 1e-12);
|
||||
close(i.im, op.delta / (Math.PI * n));
|
||||
assert.ok(i.amp > 0);
|
||||
}
|
||||
close(harmonic(op, 1).re, -2 * op.delta / Math.PI ** 2);
|
||||
close(harmonic(op, 1).im, -2 * op.IL / Math.PI);
|
||||
});
|
||||
|
||||
test('小角度斜坡计算不因 cos−sinc 相消而丢失精度', () => {
|
||||
const work = operating({ ...base, drop: base.vin * (1 - 1e-6), iavg: 1e-4, L: 1e-6 });
|
||||
const i = harmonic(work, 1), numeric = phasorQuadrature(work, 1, 120000);
|
||||
close(i.re, numeric.re, 1e-9, 1e-14);
|
||||
close(i.im, numeric.im, 1e-9, 1e-14);
|
||||
});
|
||||
|
||||
test('阻抗与展开分式吻合,零频精确为 R', () => {
|
||||
for (const R of [0.005, 0.1, 2]) for (const Ls of [0, 1e-6, 20e-6]) {
|
||||
const C = 100e-6;
|
||||
const zero = impedance(R, Ls, C, 0);
|
||||
assert.deepEqual(zero, { re: R, im: 0, amp: R });
|
||||
for (const w of [1, 1000, 100000, 1e8]) {
|
||||
const z = impedance(R, Ls, C, w);
|
||||
const a = 1 - w * w * Ls * C, b = w * R * C;
|
||||
const den = a * a + b * b;
|
||||
close(z.re, (R * a + w * Ls * b) / den, 1e-8, 1e-12);
|
||||
close(z.im, (w * Ls * a - R * b) / den, 1e-8, 1e-12);
|
||||
close(z.amp, Math.hypot(z.re, z.im));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('纯 R 并 C 的阻抗与高频极限正确', () => {
|
||||
const R = 0.2, C = 470e-6, w = 1e9;
|
||||
const z = impedance(R, 0, C, w);
|
||||
close(z.im * w * C, -1, 1e-8);
|
||||
assert.ok(z.re > 0);
|
||||
});
|
||||
|
||||
test('逆 FFT 与直接逆 DFT 一致(包含归一化约定)', () => {
|
||||
const a = [0.2, 1, -0.4, 0.8, 0, 0.3, -0.2, 0.1];
|
||||
const b = [0.1, -0.4, 0, 0.6, -0.2, -0.3, 0.5, 0];
|
||||
for (const normalize of [true, false]) {
|
||||
const re = Float64Array.from(a), im = Float64Array.from(b);
|
||||
const returned = inverseFFT(re, im, normalize);
|
||||
assert.equal(returned.re, re); assert.equal(returned.im, im);
|
||||
for (let k = 0; k < a.length; k++) {
|
||||
let er = 0, ei = 0;
|
||||
for (let n = 0; n < a.length; n++) {
|
||||
const theta = 2 * Math.PI * n * k / a.length;
|
||||
er += a[n] * Math.cos(theta) - b[n] * Math.sin(theta);
|
||||
ei += a[n] * Math.sin(theta) + b[n] * Math.cos(theta);
|
||||
}
|
||||
close(re[k], normalize ? er / a.length : er);
|
||||
close(im[k], normalize ? ei / a.length : ei);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('Hermitian FFT 电压采样与原始相量直接合成一致', () => {
|
||||
const result = calculate(op, normal, { N: 32 });
|
||||
assert.equal(result.N, 32);
|
||||
assert.ok(result.M >= 16 * (32 + 1));
|
||||
assert.equal(Math.log2(result.M) % 1, 0);
|
||||
assert.ok(result.wave.theta.length <= 1024);
|
||||
assert.equal(result.wave.theta.length, result.wave.voltage.length);
|
||||
close(result.wave.theta[0], 0);
|
||||
close(result.wave.theta.at(-1), 2 * Math.PI);
|
||||
for (let k = 0; k < result.wave.theta.length; k += 37) {
|
||||
close(result.wave.voltage[k], directVoltage(op, normal, 32, result.wave.theta[k]), 1e-9, 1e-10);
|
||||
}
|
||||
assert.ok(result.fftImagMax < 1e-10);
|
||||
close(result.dcDrop, normal.R * op.iavg);
|
||||
assert.equal(result.rmsTruncated, true);
|
||||
assert.equal(result.rmsHarmonics, 32);
|
||||
close(result.rms, Math.sqrt(result.spectrum.reduce((sum, row) => sum + row.voltage ** 2 / 2, 0)));
|
||||
});
|
||||
|
||||
test('spectrum 只返回前 64 次,电压含抽流负号', () => {
|
||||
const result = calculate(op, normal, { N: 128 });
|
||||
assert.equal(result.spectrum.length, 64);
|
||||
for (const row of result.spectrum) {
|
||||
assert.equal(row.freq, row.n * op.fsw);
|
||||
close(row.current, Math.hypot(row.ire, row.iim));
|
||||
close(row.voltage, Math.hypot(row.vre, row.vim));
|
||||
const z = impedance(normal.R, normal.Ls, normal.C, row.n * op.ws);
|
||||
close(row.vre, -(z.re * row.ire - z.im * row.iim));
|
||||
close(row.vim, -(z.re * row.iim + z.im * row.ire));
|
||||
}
|
||||
});
|
||||
|
||||
test('有限网格误差上界包含同阶数的更密集采样峰峰值', () => {
|
||||
for (const candidate of [normal, { R: 0.02, Ls: 1e-6, C: 63e-6 }, { R: 0.5, Ls: 0, C: 100e-6 }]) {
|
||||
const coarse = calculate(op, candidate, { N: 64 });
|
||||
const fine = calculate(op, candidate, { N: 64, gridFactor: 256 });
|
||||
assert.ok(fine.ppSample + 1e-9 >= coarse.ppSample);
|
||||
assert.ok(fine.ppSample <= coarse.ppSample + coarse.gridError + 1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
test('无限尾项电流及阻抗界逐频率成立,尾和不超过 sup 上界', () => {
|
||||
for (const candidate of [normal, { R: 0.5, Ls: 0, C: 10e-6 }]) {
|
||||
const result = calculate(op, candidate, { N: 32 });
|
||||
assert.equal(result.certified, true);
|
||||
const K = 2 * op.max / Math.PI;
|
||||
let finiteTail = 0;
|
||||
for (let n = 33; n <= 20000; n++) {
|
||||
const i = harmonic(op, n);
|
||||
const z = impedance(candidate.R, candidate.Ls, candidate.C, n * op.ws);
|
||||
assert.ok(i.amp <= K / n * (1 + 1e-12));
|
||||
assert.ok(z.amp <= result.tailKappa / (n * op.ws * candidate.C) * (1 + 1e-12));
|
||||
finiteTail += i.amp * z.amp;
|
||||
}
|
||||
assert.ok(finiteTail <= result.tailAmplitude);
|
||||
if (candidate.Ls === 0) assert.equal(result.tailKappa, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('低阶数的 pp 上下界包含高阶收敛波形,充分条件也是保守上界', () => {
|
||||
for (const candidate of [normal, { R: 0.1, Ls: 0, C: 220e-6 }, { R: 0.02, Ls: 1e-6, C: 63e-6 }]) {
|
||||
const low = calculate(op, candidate, { N: 64 });
|
||||
const high = calculate(op, candidate, { N: 4096 });
|
||||
assert.equal(low.certified, true); assert.equal(high.certified, true);
|
||||
assert.ok(low.ppLower <= high.ppSample + 1e-8);
|
||||
assert.ok(low.ppUpper >= high.ppSample - 1e-8);
|
||||
assert.ok(low.sufficientPP >= high.ppSample - 1e-8);
|
||||
assert.ok(high.tailAmplitude < low.tailAmplitude);
|
||||
}
|
||||
});
|
||||
|
||||
test('可用压差充足时,纹波与总判定取决于上下界而不是采样值', () => {
|
||||
const reference = calculate(op, normal, { N: 32 });
|
||||
const pass = calculate({ ...base, target: reference.ppUpper * 1.01 }, normal, { N: 32 });
|
||||
assert.equal(pass.status, 'pass');
|
||||
assert.equal(pass.rippleStatus, 'pass');
|
||||
const fail = calculate({ ...base, target: reference.ppLower / 2 }, normal, { N: 32 });
|
||||
assert.equal(fail.status, 'fail');
|
||||
assert.equal(fail.rippleStatus, 'fail');
|
||||
const uncertain = calculate({ ...base, target: (reference.ppLower + reference.ppUpper) / 2 }, normal, { N: 32 });
|
||||
assert.equal(uncertain.status, 'uncertain');
|
||||
assert.equal(uncertain.rippleStatus, 'uncertain');
|
||||
const noBound = calculate({ ...base, target: 1e10 }, { R: 0.1, Ls: 1e-12, C: 1e-12 }, { N: 32 });
|
||||
assert.equal(noBound.certified, false);
|
||||
assert.equal(noBound.status, 'uncertain');
|
||||
assert.equal(noBound.tailAmplitude, null);
|
||||
assert.equal(noBound.ppUpper, null);
|
||||
assert.equal(noBound.sufficientPP, null);
|
||||
assert.ok(noBound.tailReason.length > 0);
|
||||
});
|
||||
|
||||
test('线路压降耗尽或超过可用压差时,纹波合格仍无法维持工作点', () => {
|
||||
const line = { R: 0.05, Ls: 1e-6, C: 0.01 };
|
||||
const check = drop => calculate({ ...base, drop }, line, { N: engine.constants.FIXED_HARMONICS });
|
||||
const reproduced = check(0.1);
|
||||
assert.equal(reproduced.rippleStatus, 'pass');
|
||||
assert.ok(reproduced.ppUpper < 0.001);
|
||||
assert.equal(reproduced.status, 'fail');
|
||||
assert.equal(reproduced.headroom.feasible, false);
|
||||
close(reproduced.dcDrop, 0.25);
|
||||
close(reproduced.headroom.averageBusVoltage, 23.75);
|
||||
close(reproduced.headroom.targetOutputVoltage, 23.9);
|
||||
close(reproduced.headroom.remainingVoltage, -0.15);
|
||||
assert.equal(check(0.25).status, 'fail');
|
||||
assert.equal(check(0.250001).status, 'pass');
|
||||
});
|
||||
|
||||
test('峰值频率和峰值阻抗吻合导数变号;无峰时返回零频端点', () => {
|
||||
const Ls = 1e-6, C = 100e-6;
|
||||
for (const a of [0.001, 0.1, 1, 2, (1 + Math.SQRT2) * (1 - 1e-8)]) {
|
||||
const R = Math.sqrt(a * Ls / C);
|
||||
const result = calculate(op, { R, Ls, C }, { N: 32 });
|
||||
const p = result.peak;
|
||||
assert.equal(p.hasPeak, true);
|
||||
const z = impedance(R, Ls, C, p.omega);
|
||||
close(p.magnitude, z.amp, 1e-7, 1e-10);
|
||||
close(p.frequency, p.omega / (2 * Math.PI));
|
||||
const u = p.omega ** 2 * Ls * C;
|
||||
close(1 + 2 * a - (a + u) ** 2, 0, 0, 1e-12);
|
||||
assert.ok(1 + 2 * a - (a + (p.omega * 0.9) ** 2 * Ls * C) ** 2 > 0);
|
||||
assert.ok(1 + 2 * a - (a + (p.omega * 1.1) ** 2 * Ls * C) ** 2 < 0);
|
||||
assert.ok(p.omega < 1 / Math.sqrt(Ls * C));
|
||||
}
|
||||
for (const a of [3, 10]) {
|
||||
const R = Math.sqrt(a * Ls / C);
|
||||
const p = calculate(op, { R, Ls, C }, { N: 32 }).peak;
|
||||
assert.deepEqual(p, { hasPeak: false, frequency: 0, omega: 0, magnitude: R });
|
||||
}
|
||||
assert.equal(calculate(op, { R: 0.1, Ls: 0, C }, { N: 32 }).peak.hasPeak, false);
|
||||
});
|
||||
|
||||
test('输入与数值范围非法时抛中文错误,而不是返回伪通过', () => {
|
||||
const rejects = fn => assert.throws(fn, error => error instanceof Error && /[\u4e00-\u9fff]/.test(error.message));
|
||||
for (const key of Object.keys(base)) for (const bad of [0, -1, NaN, Infinity, '1', undefined]) {
|
||||
rejects(() => operating({ ...base, [key]: bad }));
|
||||
}
|
||||
rejects(() => operating({ ...base, drop: 24 }));
|
||||
rejects(() => operating({ ...base, drop: 25 }));
|
||||
rejects(() => operating({ ...base, L: 1e-12 }));
|
||||
rejects(() => operating({ ...base, fsw: Number.MAX_VALUE }));
|
||||
rejects(() => operating({ ...base, drop: Number.MIN_VALUE }));
|
||||
for (const n of [0, -1, 0.5, NaN, Infinity]) rejects(() => harmonic(op, n));
|
||||
rejects(() => harmonic({ ...op, D: 0 }, 1));
|
||||
rejects(() => impedance(0, 1e-6, 1e-4, 1));
|
||||
rejects(() => impedance(0.1, -1e-6, 1e-4, 1));
|
||||
rejects(() => impedance(0.1, 1e-6, 0, 1));
|
||||
rejects(() => impedance(0.1, 1e-6, 1e-4, -1));
|
||||
rejects(() => impedance(0.1, 1e200, 1e-4, 1e200));
|
||||
for (const N of [0, -1, 0.5, 16.5, 16384, NaN]) rejects(() => calculate(op, normal, { N }));
|
||||
for (const gridFactor of [0, 8, NaN, Infinity, 1e20]) rejects(() => calculate(op, normal, { gridFactor }));
|
||||
rejects(() => calculate(op, { ...normal, R: 0 }));
|
||||
rejects(() => calculate(op, { ...normal, C: Number.MIN_VALUE }, { N: 32 }));
|
||||
rejects(() => inverseFFT([1, 2, 3], [0, 0, 0]));
|
||||
rejects(() => inverseFFT([1, Infinity], [0, 0]));
|
||||
});
|
||||
|
||||
test('默认128次且支持非二次幂整数谐波次数', () => {
|
||||
assert.equal(calculate(op, normal).N, 128);
|
||||
for (const N of [1, 7, 16, 17, 33, 100, 127, 128]) {
|
||||
const r = calculate(op, normal, { N });
|
||||
assert.equal(r.N, N);
|
||||
assert.ok(r.M > 2 * N);
|
||||
close(r.wave.voltage[0], directVoltage(op, normal, N, 0), 1e-9, 1e-10);
|
||||
}
|
||||
});
|
||||
|
||||
test('有符号纹波可正可负,但峰峰值始终是max减min', () => {
|
||||
const work = operating({ vin: 24, drop: 20, iavg: 20, fsw: 200000, L: 6.8e-6, target: 0.1 });
|
||||
const r = calculate(work, { R: 0.05, Ls: 30e-6, C: 300e-6 }, { N: 64 });
|
||||
assert.ok(r.rippleMin < 0 && r.rippleMax > 0);
|
||||
close(r.rippleMax - r.rippleMin, r.ppSample);
|
||||
close(r.ppSample, 0.2764439552235223);
|
||||
assert.ok(24 - r.dcDrop + r.rippleMin > 0);
|
||||
});
|
||||
|
||||
console.log(`\n${passed} 项测试全部通过。`);
|
||||
@@ -0,0 +1,380 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const core = require('../src/buck-calculator-engine.js');
|
||||
const harness = require('../src/buck-harness-engine.js');
|
||||
const { geometry, transfer, currents, evaluate } = harness;
|
||||
|
||||
let passed = 0;
|
||||
function test(name, run) {
|
||||
run(); passed++;
|
||||
console.log('✓ ' + name);
|
||||
}
|
||||
function close(actual, expected, relative = 1e-9, absolute = 1e-12) {
|
||||
assert.ok(Number.isFinite(actual), 'actual must be finite: ' + actual);
|
||||
assert.ok(Math.abs(actual - expected) <= absolute + relative * Math.max(Math.abs(actual), Math.abs(expected)),
|
||||
`实际 ${actual},预期 ${expected}`);
|
||||
}
|
||||
function rejects(run) {
|
||||
assert.throws(run, error => error instanceof Error && /[\u4e00-\u9fff]/.test(error.message));
|
||||
}
|
||||
const base = { vin: 24, drop: 12, iavg: 5, fsw: 20000, L: 75e-6, target: 0.12 };
|
||||
const op = core.operating(base);
|
||||
const wire = { awg: 12, lengthM: 0.3, wallMm: 0.6, gapMm: 0, twisted: false };
|
||||
const normal = { R: 0.05, Ls: 1e-6, C: 470e-6 };
|
||||
function quadrature(work, n, points = 40000) {
|
||||
let re = 0, im = 0;
|
||||
for (let k = 0; k < points; k++) {
|
||||
const x = (k + 0.5) / points;
|
||||
const angle = 2 * Math.PI * n * work.D * x;
|
||||
const value = work.min + work.delta * x;
|
||||
re += value * Math.cos(angle); im -= value * Math.sin(angle);
|
||||
}
|
||||
return { re: re * 2 * work.D / points, im: im * 2 * work.D / points };
|
||||
}
|
||||
// Independent elementary complex formula (moderate values in all test cases).
|
||||
function directBranch(work, candidate, n, demand = core.harmonic(work, n)) {
|
||||
const omega = n * work.ws;
|
||||
const a = 1 - omega * omega * candidate.Ls * candidate.C;
|
||||
const b = omega * candidate.R * candidate.C;
|
||||
const den = a * a + b * b;
|
||||
const h = { re: a / den, im: -b / den };
|
||||
const source = {
|
||||
re: h.re * demand.re - h.im * demand.im,
|
||||
im: h.re * demand.im + h.im * demand.re
|
||||
};
|
||||
const capacitor = { re: source.re - demand.re, im: source.im - demand.im };
|
||||
return { source, capacitor, h };
|
||||
}
|
||||
function directRms(work, candidate, N) {
|
||||
let sourceEnergy = work.iavg ** 2, capEnergy = 0;
|
||||
for (let n = 1; n <= N; n++) {
|
||||
const ph = directBranch(work, candidate, n);
|
||||
sourceEnergy += (ph.source.re ** 2 + ph.source.im ** 2) / 2;
|
||||
capEnergy += (ph.capacitor.re ** 2 + ph.capacitor.im ** 2) / 2;
|
||||
}
|
||||
return { source: Math.sqrt(sourceEnergy), capacitor: Math.sqrt(capEnergy) };
|
||||
}
|
||||
|
||||
// Independent periodic RC differential-equation solution, integrated in time.
|
||||
function rcTimeRms(work, candidate, samples = 400000) {
|
||||
assert.equal(candidate.Ls, 0);
|
||||
const alpha = 1 / (work.fsw * candidate.R * candidate.C);
|
||||
const a = work.min, b = work.delta / work.D;
|
||||
const on = Math.exp(-alpha * work.D), off = Math.exp(-alpha * (1 - work.D));
|
||||
const s0 = off * ((a + work.delta - b / alpha) - (a - b / alpha) * on) / (-Math.expm1(-alpha));
|
||||
const sD = s0 / off;
|
||||
let sourceEnergy = 0, capEnergy = 0, sourceMean = 0, capMean = 0;
|
||||
for (let k = 0; k < samples; k++) {
|
||||
const x = (k + 0.5) / samples;
|
||||
const demand = x < work.D ? a + b * x : 0;
|
||||
const source = x < work.D
|
||||
? a + b * x - b / alpha + (s0 - a + b / alpha) * Math.exp(-alpha * x)
|
||||
: sD * Math.exp(-alpha * (x - work.D));
|
||||
const cap = source - demand;
|
||||
sourceEnergy += source * source; capEnergy += cap * cap;
|
||||
sourceMean += source; capMean += cap;
|
||||
}
|
||||
return {
|
||||
source: Math.sqrt(sourceEnergy / samples), capacitor: Math.sqrt(capEnergy / samples),
|
||||
sourceMean: sourceMean / samples, capMean: capMean / samples
|
||||
};
|
||||
}
|
||||
|
||||
test('CommonJS 与浏览器全局依赖、导出及加载顺序清楚', () => {
|
||||
assert.equal(globalThis.BuckHarness, harness);
|
||||
assert.ok(Object.isFrozen(harness));
|
||||
const browser = {};
|
||||
const engineSource = fs.readFileSync(require.resolve('../src/buck-calculator-engine.js'), 'utf8');
|
||||
const harnessSource = fs.readFileSync(require.resolve('../src/buck-harness-engine.js'), 'utf8');
|
||||
vm.runInNewContext(engineSource, browser);
|
||||
vm.runInNewContext(harnessSource, browser);
|
||||
for (const name of ['geometry', 'transfer', 'currents', 'evaluate']) assert.equal(typeof browser.BuckHarness[name], 'function');
|
||||
close(browser.BuckHarness.geometry(wire).Rwire, geometry(wire).Rwire);
|
||||
close(browser.BuckHarness.currents(base, normal, 16).source.rmsUpper, currents(base, normal, 16).source.rmsUpper);
|
||||
assert.throws(() => vm.runInNewContext(harnessSource, {}), /先加载 BuckRLC/);
|
||||
});
|
||||
|
||||
test('AWG12、0.3m 标准铜截面、两线回路 R 和 acosh 外部 L 正确', () => {
|
||||
const result = geometry(wire);
|
||||
const diameter = 0.127 * 92 ** ((36 - 12) / 39);
|
||||
const area = Math.PI * diameter ** 2 / 4;
|
||||
const bundle = diameter / Math.sqrt(0.85), spacing = bundle + 1.2;
|
||||
close(diameter, 2.052525388493948, 1e-12);
|
||||
close(area, 3.308772876111477, 1e-12);
|
||||
close(result.diameterMm, diameter); close(result.areaMm2, area);
|
||||
close(result.bundleDiameterMm, bundle); close(result.outerDiameterMm, spacing);
|
||||
close(result.spacingMm, spacing); close(result.lengthFactor, 1);
|
||||
close(result.wireLengthM, 0.3); close(result.loopLengthM, 0.6);
|
||||
close(result.Rwire, 0.01724 * 0.6 / area * (1 + 0.00393 * 40));
|
||||
close(result.LwireExt, 0.4e-6 * 0.3 * Math.acosh(spacing / bundle), 1e-12, 1e-20);
|
||||
close(result.LwireLowFreqMax - result.LwireExt, 0.1e-6 * 0.3, 1e-12, 1e-20);
|
||||
assert.deepEqual(result.candidate, { R: result.Rwire, Ls: result.LwireExt });
|
||||
close(result.totalR, result.Rwire); close(result.totalL, result.LwireExt);
|
||||
});
|
||||
|
||||
test('AWG全范围、轴向长/实际长、填充因子与温度影响方向正确', () => {
|
||||
let priorArea = Infinity;
|
||||
for (let awg = 6; awg <= 24; awg++) {
|
||||
const g = geometry({ ...wire, awg });
|
||||
assert.ok(g.areaMm2 < priorArea); priorArea = g.areaMm2;
|
||||
close(g.areaMm2, Math.PI * (0.127 * 92 ** ((36 - awg) / 39)) ** 2 / 4);
|
||||
}
|
||||
const first = geometry({ ...wire, tempC: 20, fillFactor: 1 });
|
||||
const longer = geometry({ ...wire, lengthM: 0.6, tempC: 20, fillFactor: 1 });
|
||||
close(longer.Rwire, first.Rwire * 2); close(longer.LwireExt, first.LwireExt * 2);
|
||||
const hot = geometry({ ...wire, tempC: 60, fillFactor: 1 });
|
||||
close(hot.Rwire / first.Rwire, 1 + 0.00393 * 40);
|
||||
const loose = geometry({ ...wire, tempC: 20, fillFactor: 0.5 });
|
||||
close(loose.Rwire, first.Rwire); close(loose.areaMm2, first.areaMm2);
|
||||
assert.ok(loose.bundleDiameterMm > first.bundleDiameterMm);
|
||||
assert.ok(loose.LwireExt < first.LwireExt);
|
||||
const spaced = geometry({ ...wire, gapMm: 3, fillFactor: 1, tempC: 20 });
|
||||
assert.ok(spaced.LwireExt > first.LwireExt); close(spaced.Rwire, first.Rwire);
|
||||
});
|
||||
|
||||
test('松绞实际长度因子同时增加 R、外部 L 和内部 L 范围,不任意减半', () => {
|
||||
const parallel = geometry(wire);
|
||||
const pitchMm = 5 * parallel.spacingMm;
|
||||
const twisted = geometry({ ...wire, twisted: true, pitchMm });
|
||||
const factor = Math.sqrt(1 + (Math.PI * parallel.spacingMm / pitchMm) ** 2);
|
||||
close(twisted.lengthFactor, factor);
|
||||
close(twisted.wireLengthM, wire.lengthM * factor);
|
||||
close(twisted.Rwire / parallel.Rwire, factor);
|
||||
close(twisted.LwireExt / parallel.LwireExt, factor);
|
||||
close(twisted.LwireLowFreqMax / parallel.LwireLowFreqMax, factor);
|
||||
assert.ok(twisted.Rwire > parallel.Rwire && twisted.LwireExt > parallel.LwireExt);
|
||||
const nearParallel = geometry({ ...wire, twisted: true, pitchMm: 1e12 });
|
||||
close(nearParallel.Rwire, parallel.Rwire, 1e-12);
|
||||
assert.throws(() => geometry({ ...wire, twisted: true, pitchMm: pitchMm * (1 - 1e-9) }), /至少为 5/);
|
||||
});
|
||||
|
||||
test('extraR/extraL只加整个额外支路一次,不混进 wire 结果', () => {
|
||||
const first = geometry(wire);
|
||||
const added = geometry({ ...wire, extraR: 0.02, extraL: 0.3e-6 });
|
||||
close(added.Rwire, first.Rwire); close(added.LwireExt, first.LwireExt);
|
||||
close(added.totalR, first.Rwire + 0.02);
|
||||
close(added.totalL, first.LwireExt + 0.3e-6);
|
||||
assert.deepEqual(added.candidate, { R: added.totalR, Ls: added.totalL });
|
||||
});
|
||||
|
||||
test('材料不决定载流量,温度/功耗/长线/几何近似有明确中文限制', () => {
|
||||
const result = geometry({ ...wire, material: 'PTFE', lengthM: 6 });
|
||||
const warnings = result.warnings.join(';');
|
||||
for (const text of ['直流电阻', '额外交流损耗', '厂家', '敷设', '温升', '不代表任何绝缘材料', '集总 RLC']) {
|
||||
assert.ok(warnings.includes(text), text);
|
||||
}
|
||||
close(geometry({ ...wire, material: 'silicone' }).Rwire, geometry({ ...wire, material: 'PVC' }).Rwire);
|
||||
assert.ok(!Object.hasOwn(result, 'ampacity'));
|
||||
assert.ok(!Object.hasOwn(result, 'safeCurrent'));
|
||||
});
|
||||
|
||||
test('10%、50%、90%占空比分支复相量吻合独立需求电流积分和复分流', () => {
|
||||
for (const D of [0.1, 0.5, 0.9]) {
|
||||
const work = core.operating({ ...base, drop: base.vin * (1 - D) });
|
||||
for (const candidate of [normal, { R: 0.2, Ls: 0, C: 100e-6 }]) {
|
||||
for (const n of [1, 2, 3, 9]) {
|
||||
const actual = transfer(work, candidate, n);
|
||||
const current = quadrature(work, n);
|
||||
const independent = directBranch(work, candidate, n, current);
|
||||
close(actual.source.re, independent.source.re, 1e-6, 1e-9);
|
||||
close(actual.source.im, independent.source.im, 1e-6, 1e-9);
|
||||
close(actual.capacitor.re, independent.capacitor.re, 1e-6, 1e-8);
|
||||
close(actual.capacitor.im, independent.capacitor.im, 1e-6, 1e-8);
|
||||
close(actual.source.re - actual.capacitor.re, actual.demand.re);
|
||||
close(actual.source.im - actual.capacitor.im, actual.demand.im);
|
||||
close(actual.H.re, independent.h.re); close(actual.H.im, independent.h.im);
|
||||
close(actual.source.amp, Math.hypot(actual.source.re, actual.source.im));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('谐振点的复数分流和低频 H−1 避免直接相减的消去误差', () => {
|
||||
const resonance = { R: 1e-4, Ls: 1e-6, C: 1 / (op.ws ** 2 * 1e-6) };
|
||||
const ph = transfer(op, resonance, 1);
|
||||
close(ph.H.re, 0, 0, 1e-9);
|
||||
close(ph.H.im, -1 / (op.ws * resonance.R * resonance.C));
|
||||
assert.ok(ph.source.amp > ph.demand.amp);
|
||||
const tiny = { R: 0.1, Ls: 0, C: 1e-24 };
|
||||
const stable = transfer(op, tiny, 1);
|
||||
assert.equal(stable.H.re, 1);
|
||||
assert.ok(stable.capacitorTransfer.amp > 0);
|
||||
close(stable.capacitorTransfer.im, -op.ws * tiny.R * tiny.C, 1e-12, 0);
|
||||
assert.ok(stable.capacitor.amp > 0);
|
||||
const scaled = transfer(op, { R: 1e145, Ls: 0, C: 1 }, 1);
|
||||
assert.ok(scaled.source.amp > 0 && Number.isFinite(scaled.source.amp));
|
||||
close(scaled.H.amp * op.ws * 1e145, 1, 1e-12);
|
||||
});
|
||||
|
||||
test('分支 partial RMS与独立时间合成Parseval一致,source含DC而cap不含DC', () => {
|
||||
const N = 16, M = 4096;
|
||||
const result = currents(op, normal, N);
|
||||
const phases = Array.from({ length: N }, (_, k) => directBranch(op, normal, k + 1));
|
||||
let s2 = 0, c2 = 0;
|
||||
for (let k = 0; k < M; k++) {
|
||||
const theta = 2 * Math.PI * k / M;
|
||||
let s = op.iavg, c = 0;
|
||||
for (let n = 1; n <= N; n++) {
|
||||
const a = Math.cos(n * theta), b = Math.sin(n * theta), ph = phases[n - 1];
|
||||
s += ph.source.re * a - ph.source.im * b;
|
||||
c += ph.capacitor.re * a - ph.capacitor.im * b;
|
||||
}
|
||||
s2 += s * s; c2 += c * c;
|
||||
}
|
||||
close(result.source.rmsPartial, Math.sqrt(s2 / M), 1e-12);
|
||||
close(result.capacitor.rmsPartial, Math.sqrt(c2 / M), 1e-12);
|
||||
assert.equal(result.source.dc, op.iavg); assert.equal(result.capacitor.dc, 0);
|
||||
assert.ok(result.source.rmsPartial >= op.iavg);
|
||||
close(result.demandRms, Math.sqrt(op.D * (op.IL ** 2 + op.delta ** 2 / 12)));
|
||||
});
|
||||
|
||||
test('RC微分方程周期解的完整时间RMS落在有限partial与upper之间', () => {
|
||||
const candidate = { R: 0.1, Ls: 0, C: 470e-6 };
|
||||
const time = rcTimeRms(op, candidate);
|
||||
close(time.sourceMean, op.iavg, 1e-9);
|
||||
close(time.capMean, 0, 0, 1e-9);
|
||||
const result = currents(op, candidate, 32);
|
||||
assert.equal(result.certified, true);
|
||||
for (const key of ['source', 'capacitor']) {
|
||||
assert.ok(time[key] >= result[key].rmsPartial - 2e-9, key + ' partial');
|
||||
assert.ok(time[key] <= result[key].rmsUpper + 2e-9, key + ' upper');
|
||||
}
|
||||
});
|
||||
|
||||
test('LC/RC无限尾均方界含独立高阶收敛RMS,尾能量与upper不是未知0', () => {
|
||||
const cases = [normal, { R: 0.2, Ls: 0, C: 220e-6 }, { R: 0.01, Ls: 1e-6, C: 63e-6 }];
|
||||
for (const candidate of cases) {
|
||||
const low = currents(op, candidate, 32);
|
||||
const high = directRms(op, candidate, 32768);
|
||||
assert.equal(low.certified, true);
|
||||
for (const key of ['source', 'capacitor']) {
|
||||
const branch = low[key];
|
||||
assert.ok(branch.rmsUpper !== null && branch.tailEnergy > 0);
|
||||
assert.ok(high[key] >= branch.rmsPartial - 1e-10);
|
||||
assert.ok(high[key] <= branch.rmsUpper);
|
||||
const impliedEnergy = high[key] ** 2 - branch.rmsPartial ** 2;
|
||||
assert.ok(impliedEnergy <= branch.tailEnergy + 1e-10);
|
||||
const upper = Math.hypot(branch.rmsPartial, Math.sqrt(branch.tailEnergy));
|
||||
assert.ok(branch.rmsUpper >= upper);
|
||||
close(branch.rmsUpper, upper, 1e-9);
|
||||
}
|
||||
if (candidate.Ls === 0) { assert.equal(low.tailQ, 0); assert.equal(low.tailKappa, 1); }
|
||||
}
|
||||
});
|
||||
|
||||
test('尾项逐谐波界、10/6/2积分系数和cap统一Hmax保守', () => {
|
||||
const N = 17, K = 2 * op.max / Math.PI;
|
||||
for (const candidate of [normal, { R: 0.2, Ls: 0, C: 220e-6 }]) {
|
||||
const result = currents(op, candidate, N);
|
||||
let sourceTail = 0, capTail = 0;
|
||||
let sourceFormula, capHmax;
|
||||
if (candidate.Ls > 0) {
|
||||
const q = 1 / ((N + 1) ** 2 * op.ws ** 2 * candidate.Ls * candidate.C);
|
||||
assert.ok(result.tailQ >= q);
|
||||
assert.ok(result.tailKappa >= 1 / (1 - q));
|
||||
sourceFormula = (K * result.tailKappa / (op.ws ** 2 * candidate.Ls * candidate.C)) ** 2 / (10 * N ** 5);
|
||||
capHmax = result.tailKappa / ((N + 1) ** 2 * op.ws ** 2 * candidate.Ls * candidate.C);
|
||||
} else {
|
||||
sourceFormula = (K / (op.ws * candidate.R * candidate.C)) ** 2 / (6 * N ** 3);
|
||||
capHmax = 1 / ((N + 1) * op.ws * candidate.R * candidate.C);
|
||||
}
|
||||
assert.ok(result.source.tailEnergy >= sourceFormula * (1 - 1e-14));
|
||||
const capFormula = K ** 2 * (1 + capHmax) ** 2 / (2 * N);
|
||||
assert.ok(result.capacitor.tailEnergy >= capFormula * (1 - 1e-14));
|
||||
close(result.source.tailEnergy, sourceFormula, 1e-9);
|
||||
close(result.capacitor.tailEnergy, capFormula, 1e-9);
|
||||
for (let n = N + 1; n <= 10000; n++) {
|
||||
const ph = directBranch(op, candidate, n);
|
||||
assert.ok(Math.hypot(ph.h.re, ph.h.im) <= capHmax * (1 + 1e-12));
|
||||
sourceTail += (ph.source.re ** 2 + ph.source.im ** 2) / 2;
|
||||
capTail += (ph.capacitor.re ** 2 + ph.capacitor.im ** 2) / 2;
|
||||
}
|
||||
assert.ok(sourceTail <= result.source.tailEnergy);
|
||||
assert.ok(capTail <= result.capacitor.tailEnergy);
|
||||
}
|
||||
});
|
||||
|
||||
test('扩大N时partial不下降、尾界收紧,缺失界时保持null且无安全pass', () => {
|
||||
let previous = null;
|
||||
for (const N of [1, 7, 17, 64, 128]) {
|
||||
const result = currents(op, normal, N);
|
||||
if (previous) for (const key of ['source', 'capacitor']) {
|
||||
assert.ok(result[key].rmsPartial >= previous[key].rmsPartial - 1e-12);
|
||||
assert.ok(result[key].tailEnergy < previous[key].tailEnergy);
|
||||
}
|
||||
previous = result;
|
||||
}
|
||||
const unknown = currents(op, { R: 0.1, Ls: 1e-12, C: 1e-12 }, 32);
|
||||
assert.equal(unknown.certified, false);
|
||||
assert.equal(unknown.source.rmsUpper, null); assert.equal(unknown.capacitor.rmsUpper, null);
|
||||
assert.equal(unknown.source.tailEnergy, null); assert.equal(unknown.capacitor.tailEnergy, null);
|
||||
assert.ok(unknown.tailReason.length > 0);
|
||||
assert.ok(unknown.source.rmsPartial > 0 && unknown.capacitor.rmsPartial > 0);
|
||||
assert.notEqual(unknown.status, 'pass');
|
||||
assert.ok(unknown.warnings.some(warning => warning.includes('不能代替')));
|
||||
});
|
||||
|
||||
test('q临界附近保守拒绝,上界下溢保留正的向外浮点余量', () => {
|
||||
const N = 16, Ls = 1e-6;
|
||||
const criticalC = 1 / ((N + 1) ** 2 * op.ws ** 2 * Ls);
|
||||
const at = currents(op, { R: 0.05, Ls, C: criticalC }, N);
|
||||
assert.equal(at.certified, false);
|
||||
assert.equal(at.source.rmsUpper, null);
|
||||
const far = currents(op, { R: 0.05, Ls, C: criticalC * 1.01 }, N);
|
||||
assert.equal(far.certified, true);
|
||||
const tiny = currents(op, { R: 1e180, Ls: 0, C: 1 }, 16);
|
||||
assert.equal(tiny.certified, true);
|
||||
assert.ok(tiny.source.tailEnergy > 0 && tiny.source.tailEnergy < 1e-300);
|
||||
assert.ok(tiny.source.rmsUpper >= op.iavg);
|
||||
});
|
||||
|
||||
test('evaluate只用外部L及一次extra、默认N128、core结果与直接调用相同', () => {
|
||||
const params = { ...wire, extraR: 0.01, extraL: 0.2e-6 };
|
||||
const result = evaluate(base, params, 470e-6, 17);
|
||||
const candidate = { R: result.geometry.totalR, Ls: result.geometry.totalL, C: 470e-6 };
|
||||
assert.deepEqual(result.candidate, candidate);
|
||||
const direct = core.calculate(base, candidate, { N: 17, gridFactor: 16 });
|
||||
for (const key of ['ppSample', 'ppUpper', 'dcDrop', 'rms', 'N', 'M']) assert.equal(result.core[key], direct[key]);
|
||||
assert.equal(result.core.status, direct.status);
|
||||
assert.deepEqual(result.currents, currents(base, candidate, 17));
|
||||
assert.equal(evaluate(base, wire, 470e-6).core.N, 128);
|
||||
assert.equal(currents(base, normal).N, 128);
|
||||
const stale = { ...op, IL: 1e20, D: 0.99, max: 1e30, ws: 2 };
|
||||
assert.deepEqual(currents(stale, normal, 17), currents(base, normal, 17));
|
||||
});
|
||||
|
||||
test('严格拒绝非法几何与不可信电气输入,报中文而非NaN/伪通过', () => {
|
||||
for (const params of [null, [], 1, 'wire']) rejects(() => geometry(params));
|
||||
for (const awg of [5, 25, 12.5, '12', NaN, Infinity, undefined]) rejects(() => geometry({ ...wire, awg }));
|
||||
for (const key of ['lengthM', 'wallMm', 'gapMm']) {
|
||||
for (const value of [-1, NaN, Infinity, '1', null, undefined]) rejects(() => geometry({ ...wire, [key]: value }));
|
||||
}
|
||||
for (const [key, values] of Object.entries({
|
||||
lengthM: [0, 1001, Number.MIN_VALUE], wallMm: [11], gapMm: [1001],
|
||||
fillFactor: [0, 0.09, 1.01, NaN, Infinity, '0.85'],
|
||||
tempC: [-101, 261, NaN, Infinity, '60'], extraR: [-1, 1e6 + 1, NaN, '0'],
|
||||
extraL: [-1, 2, NaN, '0'], twisted: [0, 1, 'false', null, undefined],
|
||||
pitchMm: [0, -1, NaN, Infinity, '20']
|
||||
})) for (const value of values) rejects(() => geometry({ ...wire, [key]: value }));
|
||||
rejects(() => geometry({ ...wire, wallMm: 0, gapMm: 0 }));
|
||||
rejects(() => geometry({ ...wire, wallMm: Number.MIN_VALUE, gapMm: 0 }));
|
||||
rejects(() => geometry({ ...wire, twisted: true }));
|
||||
rejects(() => geometry({ ...wire, twisted: true, pitchMm: 1 }));
|
||||
for (const N of [0, -1, 0.5, 8193, NaN, Infinity, '128', null]) {
|
||||
rejects(() => currents(base, normal, N)); rejects(() => evaluate(base, wire, 470e-6, N));
|
||||
}
|
||||
for (const candidate of [null, [], { ...normal, R: 0 }, { ...normal, Ls: -1 }, { ...normal, C: 0 },
|
||||
{ ...normal, R: NaN }, { ...normal, C: Infinity }, { ...normal, R: '1' }]) {
|
||||
rejects(() => currents(base, candidate)); rejects(() => transfer(base, candidate, 1));
|
||||
}
|
||||
rejects(() => currents({ ...base, L: 1e-12 }, normal));
|
||||
rejects(() => currents(base, { ...normal, C: Number.MIN_VALUE }));
|
||||
rejects(() => currents(base, { R: 1e308, Ls: 1e308, C: 1e308 }));
|
||||
for (const n of [0, -1, 0.5, NaN, Infinity, '1']) rejects(() => transfer(base, normal, n));
|
||||
assert.ok(Number.isFinite(geometry({ ...wire, wallMm: 0, gapMm: 0.1 }).Rwire));
|
||||
assert.ok(Number.isFinite(geometry({ ...wire, tempC: -100, fillFactor: 1 }).Rwire));
|
||||
});
|
||||
|
||||
console.log(`\n${passed} 项线束内核测试全部通过。`);
|
||||
@@ -0,0 +1,272 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const core = require('../src/buck-calculator-engine.js');
|
||||
const sensitivity = require('../src/buck-sensitivity-engine.js');
|
||||
const { analyzeOne, makeAnalyzer } = sensitivity;
|
||||
const source = fs.readFileSync(require.resolve('../src/buck-sensitivity-engine.js'), 'utf8');
|
||||
|
||||
let passed = 0;
|
||||
function test(name, run) { run(); passed++; console.log('✓ ' + name); }
|
||||
function close(actual, expected, relative = 1e-9, absolute = 1e-12) {
|
||||
assert.ok(Number.isFinite(actual), 'actual must be finite: ' + actual);
|
||||
assert.ok(Math.abs(actual - expected) <= absolute + relative * Math.max(Math.abs(actual), Math.abs(expected)),
|
||||
`实际 ${actual},预期 ${expected}`);
|
||||
}
|
||||
function rejects(run) {
|
||||
assert.throws(run, error => error instanceof Error && /[\u4e00-\u9fff]/.test(error.message));
|
||||
}
|
||||
const base = { vin: 24, drop: 12, iavg: 5, fsw: 20000, L: 75e-6, target: 0.12 };
|
||||
const normal = { R: 0.05, Ls: 1e-6, C: 470e-6 };
|
||||
const keys = ['drop', 'iavg', 'fsw', 'L', 'R', 'Ls', 'C'];
|
||||
const factor = 1.1;
|
||||
function stubAPI(calculate) {
|
||||
const browser = { BuckRLC: { operating: core.operating, calculate } };
|
||||
vm.runInNewContext(source, browser);
|
||||
return browser.BuckSensitivity;
|
||||
}
|
||||
function fakeResult(pp, { certified = true, halfWidth = 1e-8 } = {}) {
|
||||
return {
|
||||
ppSample: pp, ppLower: Math.max(0, pp - halfWidth),
|
||||
ppUpper: certified ? pp + halfWidth : null,
|
||||
sufficientPP: certified ? pp * 2 : null, certified
|
||||
};
|
||||
}
|
||||
|
||||
test('CommonJS/浏览器接口、加载顺序和只读常量一致', () => {
|
||||
assert.equal(globalThis.BuckSensitivity, sensitivity);
|
||||
assert.ok(Object.isFrozen(sensitivity));
|
||||
assert.deepEqual(sensitivity.constants.KEYS, keys);
|
||||
assert.deepEqual(sensitivity.constants.LEVEL_THRESHOLDS, [0.1, 0.3, 0.8, 1.5]);
|
||||
const browser = {};
|
||||
vm.runInNewContext(fs.readFileSync(require.resolve('../src/buck-calculator-engine.js'), 'utf8'), browser);
|
||||
vm.runInNewContext(source, browser);
|
||||
assert.equal(typeof browser.BuckSensitivity.analyzeOne, 'function');
|
||||
close(browser.BuckSensitivity.analyzeOne(base, normal, 'C', 16).elasticity, analyzeOne(base, normal, 'C', 16).elasticity);
|
||||
assert.throws(() => vm.runInNewContext(source, {}), /先加载 BuckRLC/);
|
||||
});
|
||||
|
||||
test('七参数独立乘1.1及倒数,每个摘要与保留复相位的core原计算一致', () => {
|
||||
const analyzer = makeAnalyzer(base, normal, 17);
|
||||
for (const key of keys) {
|
||||
const result = analyzer.analyzeOne(key);
|
||||
assert.equal(result.status, 'ok'); assert.equal(result.N, 17); assert.equal(result.factor, factor);
|
||||
assert.equal(result.value, Object.hasOwn(normal, key) ? normal[key] : base[key]);
|
||||
for (const [side, multiplier] of [['base', 1], ['minus', 1 / factor], ['plus', factor]]) {
|
||||
const changedOp = { ...base }, changedCandidate = { ...normal };
|
||||
if (Object.hasOwn(normal, key)) changedCandidate[key] = normal[key] * multiplier;
|
||||
else changedOp[key] = base[key] * multiplier;
|
||||
const direct = core.calculate(changedOp, changedCandidate, { N: 17, gridFactor: 16 });
|
||||
const summary = result[side];
|
||||
assert.equal(summary.valid, true); assert.equal(summary.error, null);
|
||||
close(summary.pp, direct.ppSample, 1e-12);
|
||||
close(summary.ratio, direct.ppSample / base.target, 1e-12);
|
||||
const margin = Math.max(1e-12, base.target * 1e-8, direct.sufficientPP * 1e-12);
|
||||
close(summary.margin, margin, 1e-12, 1e-20);
|
||||
close(summary.lower, Math.max(0, direct.ppLower - margin), 1e-12);
|
||||
close(summary.upper, direct.ppUpper + margin, 1e-12);
|
||||
assert.ok(summary.lower <= direct.ppLower && summary.upper >= direct.ppUpper);
|
||||
}
|
||||
close(result.minusRatio, result.minus.pp / result.base.pp);
|
||||
close(result.plusRatio, result.plus.pp / result.base.pp);
|
||||
close(result.goalRatio, result.base.pp / base.target);
|
||||
const expectedE = Math.max(Math.abs(Math.log(result.minusRatio)), Math.abs(Math.log(result.plusRatio))) / Math.log(factor);
|
||||
close(result.elasticity, expectedE, 1e-11);
|
||||
assert.ok(result.level >= 1 && result.level <= 5);
|
||||
}
|
||||
});
|
||||
|
||||
test('工作点变体重建D/IL/delta,不信任缓存的衍生工作点字段', () => {
|
||||
const op = core.operating(base);
|
||||
const stale = { ...op, D: 0.99, IL: 1e20, delta: 1e20, min: -5, max: 1e50, ws: 2 };
|
||||
for (const key of ['drop', 'iavg', 'fsw', 'L']) {
|
||||
const actual = analyzeOne(stale, normal, key, 16);
|
||||
const expected = analyzeOne(base, normal, key, 16);
|
||||
assert.deepEqual(actual, expected);
|
||||
}
|
||||
const changed = analyzeOne(base, normal, 'drop', 16);
|
||||
assert.notEqual(core.operating({ ...base, drop: changed.plus.value }).D, op.D);
|
||||
});
|
||||
|
||||
test('电流与delta同时放大10倍,七个无量纲E保持不变;target不改变E', () => {
|
||||
const first = makeAnalyzer(base, normal, 64);
|
||||
const scaled = makeAnalyzer({ ...base, iavg: base.iavg * 10, L: base.L / 10 }, normal, 64);
|
||||
const differentTarget = makeAnalyzer({ ...base, target: base.target * 7 }, normal, 64);
|
||||
for (const key of keys) {
|
||||
const a = first.analyzeOne(key), b = scaled.analyzeOne(key), t = differentTarget.analyzeOne(key);
|
||||
close(b.base.pp, a.base.pp * 10, 1e-11);
|
||||
close(a.elasticity, b.elasticity, 1e-8);
|
||||
close(a.elasticity, t.elasticity, 1e-10);
|
||||
assert.equal(a.level, b.level); assert.equal(a.level, t.level);
|
||||
close(t.goalRatio, a.goalRatio / 7);
|
||||
}
|
||||
});
|
||||
|
||||
test('五级显示阈值严格取最大绝对log变化,不受正负方向或单位左右', () => {
|
||||
for (const [exponent, level] of [[0, 1], [0.099, 1], [0.101, 2], [0.299, 2], [0.301, 3],
|
||||
[0.799, 3], [0.801, 4], [1.499, 4], [1.501, 5], [3, 5]]) {
|
||||
for (const sign of [-1, 1]) {
|
||||
const api = stubAPI((op, candidate) => fakeResult(candidate.R ** (sign * exponent)));
|
||||
const result = api.analyzeOne(base, { ...normal, R: 1 }, 'R');
|
||||
close(result.elasticity, exponent, 1e-10);
|
||||
assert.equal(result.level, level);
|
||||
}
|
||||
}
|
||||
const api = stubAPI((op, candidate) => fakeResult(candidate.R < 1 ? candidate.R ** 2 : candidate.R ** 0.2));
|
||||
close(api.analyzeOne(base, { ...normal, R: 1 }, 'R').elasticity, 2);
|
||||
});
|
||||
|
||||
test('方向可证明时用加宽区间;采样小于0.1%保持flat而非伪精度箭头', () => {
|
||||
for (const [exponent, expected] of [[1, 'decrease'], [-1, 'increase']]) {
|
||||
const api = stubAPI((op, candidate) => fakeResult(candidate.R ** exponent));
|
||||
const result = api.analyzeOne(base, { ...normal, R: 1 }, 'R');
|
||||
assert.equal(result.definiteDirection, expected); assert.equal(result.approxDirection, expected);
|
||||
assert.equal(result.confidence, 'interval');
|
||||
}
|
||||
const flat = stubAPI((op, candidate) => fakeResult(candidate.R ** 0.001));
|
||||
const result = flat.analyzeOne(base, { ...normal, R: 1 }, 'R');
|
||||
assert.equal(result.approxDirection, 'flat');
|
||||
// Even a very small model change can have interval evidence, but does not
|
||||
// become an unqualified direction when the noise-aware sample says flat.
|
||||
assert.equal(result.confidence, 'estimate');
|
||||
const identical = stubAPI(() => fakeResult(1)).analyzeOne(base, normal, 'R');
|
||||
assert.equal(identical.approxDirection, 'flat'); assert.equal(identical.definiteDirection, null);
|
||||
assert.equal(identical.elasticity, 0); assert.equal(identical.level, 1);
|
||||
});
|
||||
|
||||
test('局部峰给both、局部谷给hold,不泛化成参数全局过大或过小', () => {
|
||||
for (const [sign, expected] of [[-1, 'both'], [1, 'hold']]) {
|
||||
const api = stubAPI((op, candidate) => fakeResult(2 + sign * (Math.log(candidate.R) / Math.log(factor)) ** 2 * 0.1));
|
||||
const result = api.analyzeOne(base, { ...normal, R: 1 }, 'R');
|
||||
assert.equal(result.approxDirection, expected); assert.equal(result.definiteDirection, expected);
|
||||
assert.equal(result.confidence, 'interval');
|
||||
assert.ok(result.scope.includes('不表示参数全局过大/过小'));
|
||||
}
|
||||
});
|
||||
|
||||
test('真实RLC谐振附近两侧方向翻转,在局部峰两边都改善', () => {
|
||||
const resonantC = 1 / ((2 * Math.PI * base.fsw) ** 2 * normal.Ls);
|
||||
const below = analyzeOne(base, { ...normal, R: 0.003, C: resonantC * 0.85 }, 'C', 128);
|
||||
const peak = analyzeOne(base, { ...normal, R: 0.003, C: resonantC }, 'C', 128);
|
||||
const above = analyzeOne(base, { ...normal, R: 0.003, C: resonantC * 1.15 }, 'C', 128);
|
||||
assert.equal(below.definiteDirection, 'decrease');
|
||||
assert.equal(peak.definiteDirection, 'both');
|
||||
assert.equal(above.definiteDirection, 'increase');
|
||||
for (const result of [below, peak, above]) {
|
||||
assert.equal(result.approxDirection, result.definiteDirection);
|
||||
assert.equal(result.confidence, 'interval');
|
||||
}
|
||||
// R is also re-evaluated in the same resonant model, not assigned a rule.
|
||||
const r = analyzeOne(base, { ...normal, R: 0.003, C: resonantC }, 'R', 128);
|
||||
close(r.elasticity, Math.max(Math.abs(Math.log(r.minusRatio)), Math.abs(Math.log(r.plusRatio))) / Math.log(factor));
|
||||
});
|
||||
|
||||
test('有界但区间重叠只给estimate,双边缺一致区间证据不报definite', () => {
|
||||
const api = stubAPI((op, candidate) => fakeResult(candidate.R < 1 ? 0.9 : candidate.R > 1 ? 1.01 : 1,
|
||||
{ halfWidth: 0.02 }));
|
||||
const result = api.analyzeOne(base, { ...normal, R: 1 }, 'R');
|
||||
assert.equal(result.minus.upper < result.base.lower, true);
|
||||
assert.equal(result.plus.lower <= result.base.upper, true);
|
||||
assert.equal(result.approxDirection, 'decrease');
|
||||
assert.equal(result.definiteDirection, null); assert.equal(result.confidence, 'estimate');
|
||||
});
|
||||
|
||||
test('未越电容主导区缺tail界时保留null,无可证明方向,只标uncertain', () => {
|
||||
const result = analyzeOne(base, { R: 0.1, Ls: 1e-12, C: 1e-12 }, 'R', 16);
|
||||
assert.equal(result.status, 'ok'); assert.equal(result.confidence, 'uncertain');
|
||||
assert.equal(result.definiteDirection, null);
|
||||
for (const side of ['base', 'minus', 'plus']) {
|
||||
assert.equal(result[side].valid, true); assert.equal(result[side].certified, false);
|
||||
assert.equal(result[side].lower, null); assert.equal(result[side].upper, null);
|
||||
assert.ok(result[side].pp > 0);
|
||||
}
|
||||
assert.ok(result.warnings.some(warning => warning.includes('缺少无限尾项区间')));
|
||||
});
|
||||
|
||||
test('Ls=0灰态不造epsilon,不log零,不生成等级/方向或伪比值', () => {
|
||||
const result = analyzeOne(base, { ...normal, Ls: 0 }, 'Ls');
|
||||
assert.equal(result.status, 'zero'); assert.equal(result.oneSided, false);
|
||||
assert.equal(result.elasticity, null); assert.equal(result.level, null);
|
||||
assert.equal(result.approxDirection, null); assert.equal(result.definiteDirection, null);
|
||||
assert.equal(result.confidence, 'none');
|
||||
assert.equal(result.minusRatio, null); assert.equal(result.plusRatio, null);
|
||||
assert.equal(result.minus.value, 0); assert.equal(result.plus.value, 0);
|
||||
assert.equal(result.minus.valid, false); assert.equal(result.plus.valid, false);
|
||||
assert.equal(result.minus.pp, null); assert.equal(result.plus.pp, null);
|
||||
assert.ok(result.base.valid && result.goalRatio > 0);
|
||||
});
|
||||
|
||||
test('drop和CCM边界只用有效侧,边界本身不被当成改善或通过', () => {
|
||||
const dropEdge = analyzeOne({ ...base, drop: 23 }, normal, 'drop', 32);
|
||||
assert.equal(dropEdge.status, 'one-sided'); assert.equal(dropEdge.oneSided, true);
|
||||
assert.equal(dropEdge.minus.valid, true); assert.equal(dropEdge.plus.valid, false);
|
||||
assert.equal(dropEdge.plus.pp, null); assert.equal(dropEdge.plusRatio, null);
|
||||
assert.ok(dropEdge.plus.error.includes('小于输入电压'));
|
||||
close(dropEdge.elasticity, Math.abs(Math.log(dropEdge.minusRatio)) / Math.log(factor));
|
||||
const ccmEdge = analyzeOne({ ...base, iavg: 1.01 }, normal, 'iavg', 32);
|
||||
assert.equal(ccmEdge.status, 'one-sided'); assert.equal(ccmEdge.minus.valid, false);
|
||||
assert.equal(ccmEdge.plus.valid, true); assert.ok(ccmEdge.minus.error.includes('CCM'));
|
||||
assert.equal(ccmEdge.definiteDirection, null); assert.equal(ccmEdge.approxDirection, null);
|
||||
const allBad = stubAPI((op, candidate) => {
|
||||
if (candidate.R !== 1) throw new Error('测试变体边界无效');
|
||||
return fakeResult(1);
|
||||
}).analyzeOne(base, { ...normal, R: 1 }, 'R');
|
||||
assert.equal(allBad.status, 'invalid'); assert.equal(allBad.elasticity, null);
|
||||
assert.equal(allBad.level, null); assert.equal(allBad.confidence, 'none');
|
||||
assert.equal(allBad.definiteDirection, null); assert.equal(allBad.approxDirection, null);
|
||||
});
|
||||
|
||||
test('makeAnalyzer复制输入、缓存一次base及各参数,外部编辑不污染快照', () => {
|
||||
let calls = 0;
|
||||
const api = stubAPI((op, candidate, options) => {
|
||||
calls++;
|
||||
assert.equal(options.N, 17); assert.equal(options.gridFactor, 16);
|
||||
return fakeResult(op.iavg + candidate.R + candidate.C * 1000);
|
||||
});
|
||||
const editableOp = { ...base }, editableCandidate = { ...normal };
|
||||
const analyzer = api.makeAnalyzer(editableOp, editableCandidate, 17);
|
||||
assert.equal(calls, 1); assert.equal(analyzer.base.value, null);
|
||||
editableOp.iavg = 100; editableCandidate.R = 10;
|
||||
const first = analyzer.analyzeOne('R');
|
||||
assert.equal(calls, 3); assert.equal(first.value, normal.R);
|
||||
assert.equal(first.base.pp, base.iavg + normal.R + normal.C * 1000);
|
||||
assert.equal(analyzer.analyzeOne('R'), first); assert.equal(calls, 3);
|
||||
analyzer.analyzeOne('iavg'); assert.equal(calls, 5);
|
||||
assert.ok(Object.isFrozen(analyzer) && Object.isFrozen(analyzer.base));
|
||||
assert.ok(Object.isFrozen(first) && Object.isFrozen(first.plus) && Object.isFrozen(first.warnings));
|
||||
const zero = api.makeAnalyzer(base, { ...normal, Ls: 0 }, 17);
|
||||
const before = calls; zero.analyzeOne('Ls'); assert.equal(calls, before);
|
||||
});
|
||||
|
||||
test('默认N128及非二次幂支持;非法baseline/key/N中文抛错', () => {
|
||||
assert.equal(makeAnalyzer(base, normal).N, 128);
|
||||
assert.equal(analyzeOne(base, normal, 'C', 7).N, 7);
|
||||
for (const N of [0, -1, 0.5, 8193, NaN, Infinity, '128', null]) rejects(() => makeAnalyzer(base, normal, N));
|
||||
for (const key of ['vin', 'target', 'powerL', 'Rs', 'Cs', '', null, undefined, 1]) rejects(() => analyzeOne(base, normal, key));
|
||||
for (const value of [null, [], 'op', { ...base, iavg: 0 }, { ...base, L: 1e-12 }, { ...base, drop: 24 }]) {
|
||||
rejects(() => makeAnalyzer(value, normal));
|
||||
}
|
||||
for (const candidate of [null, [], { ...normal, R: 0 }, { ...normal, Ls: -1 },
|
||||
{ ...normal, C: 0 }, { ...normal, C: NaN }, { ...normal, R: '1' }]) rejects(() => makeAnalyzer(base, candidate));
|
||||
});
|
||||
|
||||
test('零/非有限pp及比值下溢明确无效,极端有效比值用log差保持E有限', () => {
|
||||
for (const pp of [0, -1, NaN, Infinity]) {
|
||||
const api = stubAPI(() => fakeResult(pp));
|
||||
assert.throws(() => api.makeAnalyzer(base, normal), /有限数值|大于零/);
|
||||
}
|
||||
const baselineZeroRatio = stubAPI(() => fakeResult(Number.MIN_VALUE));
|
||||
assert.throws(() => baselineZeroRatio.makeAnalyzer({ ...base, target: 1e100 }, normal), /比值超出/);
|
||||
const oneUnderflow = stubAPI((op, candidate) => fakeResult(candidate.R < 1 ? 0 : 1));
|
||||
const side = oneUnderflow.analyzeOne(base, { ...normal, R: 1 }, 'R');
|
||||
assert.equal(side.status, 'one-sided'); assert.equal(side.minus.valid, false);
|
||||
assert.equal(side.minusRatio, null); assert.equal(side.plusRatio, 1);
|
||||
const extreme = stubAPI((op, candidate) => fakeResult(candidate.R > 1 ? 1e200 : 1e-200));
|
||||
const large = extreme.analyzeOne(base, { ...normal, R: 1 }, 'R');
|
||||
assert.equal(large.plusRatio, null); assert.equal(large.plus.valid, true);
|
||||
assert.ok(Number.isFinite(large.elasticity) && large.elasticity > 1000);
|
||||
assert.equal(large.level, 5);
|
||||
});
|
||||
|
||||
console.log(`\n${passed} 项敏感度内核测试全部通过。`);
|
||||
@@ -0,0 +1,302 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const core = require('../src/buck-calculator-engine.js');
|
||||
const visual = require('../src/buck-visual-engine.js');
|
||||
const { impedance, scanImpedance, currentTrend, analyze } = visual;
|
||||
|
||||
let passed = 0;
|
||||
function test(name, run) { run(); passed++; console.log('✓ ' + name); }
|
||||
function close(actual, expected, relative = 1e-9, absolute = 1e-12) {
|
||||
assert.ok(Number.isFinite(actual), 'actual must be finite: ' + actual);
|
||||
assert.ok(Math.abs(actual - expected) <= absolute + relative * Math.max(Math.abs(actual), Math.abs(expected)),
|
||||
`实际 ${actual},预期 ${expected}`);
|
||||
}
|
||||
function rejects(run) {
|
||||
assert.throws(run, error => error instanceof Error && /[\u4e00-\u9fff]/.test(error.message));
|
||||
}
|
||||
const base = { vin: 24, drop: 12, iavg: 5, fsw: 20000, L: 75e-6, target: 0.12 };
|
||||
const op = core.operating(base);
|
||||
const normal = { R: 0.05, Ls: 1e-6, C: 470e-6 };
|
||||
const source = fs.readFileSync(require.resolve('../src/buck-visual-engine.js'), 'utf8');
|
||||
function directVoltage(spectrum, theta) {
|
||||
let value = 0;
|
||||
for (const row of spectrum) value += row.vre * Math.cos(row.n * theta) - row.vim * Math.sin(row.n * theta);
|
||||
return value;
|
||||
}
|
||||
|
||||
test('CommonJS与浏览器全局接口、依赖加载顺序明确', () => {
|
||||
assert.equal(globalThis.BuckVisual, visual); assert.ok(Object.isFrozen(visual));
|
||||
const browser = {};
|
||||
vm.runInNewContext(fs.readFileSync(require.resolve('../src/buck-calculator-engine.js'), 'utf8'), browser);
|
||||
vm.runInNewContext(source, browser);
|
||||
assert.equal(typeof browser.BuckVisual.impedance, 'function');
|
||||
assert.equal(typeof browser.BuckVisual.analyze, 'function');
|
||||
close(browser.BuckVisual.analyze(base, normal, 17).coreLike.ppSample, analyze(base, normal, 17).coreLike.ppSample);
|
||||
assert.throws(() => vm.runInNewContext(source, {}), /先加载 BuckRLC/);
|
||||
});
|
||||
|
||||
test('有损正常RLC含Ls0与core阻抗和解析界/波形完全一致', () => {
|
||||
for (const candidate of [normal, { R: 0.2, Ls: 0, C: 220e-6 }]) {
|
||||
for (const omega of [0, 1, op.ws, 1e9]) {
|
||||
const actual = impedance(candidate, omega), expected = core.impedance(candidate.R, candidate.Ls, candidate.C, omega);
|
||||
for (const key of ['re', 'im', 'amp']) assert.equal(actual[key], expected[key]);
|
||||
assert.equal(actual.singular, false); assert.equal(actual.short, false);
|
||||
}
|
||||
const actual = analyze(base, candidate, 17), expected = core.calculate(base, candidate, { N: 17, gridFactor: 16 });
|
||||
assert.equal(actual.mode, 'normal'); assert.equal(actual.boundedSteadyState, 'stable');
|
||||
for (const key of ['N', 'M', 'ppSample', 'ppLower', 'ppUpper', 'rms', 'certified', 'status', 'gridError', 'tailAmplitude']) {
|
||||
assert.equal(actual.coreLike[key], expected[key], key);
|
||||
}
|
||||
assert.deepEqual(actual.coreLike.wave, expected.wave); assert.deepEqual(actual.peak, expected.peak);
|
||||
assert.equal(actual.dcCurrent, op.iavg); assert.equal(actual.forcedOnly, false);
|
||||
}
|
||||
});
|
||||
|
||||
test('全部非负R/L/C的0Hz精确Z=R,理想源短路不偷加epsilon', () => {
|
||||
for (const R of [0, 0.1]) for (const Ls of [0, 1e-6]) for (const C of [0, 1e-3]) {
|
||||
assert.deepEqual(impedance({ R, Ls, C }, 0), { re: R, im: 0, amp: R, singular: false, short: R === 0 });
|
||||
}
|
||||
for (const C of [0, 1e-6, 1]) {
|
||||
const candidate = { R: 0, Ls: 0, C };
|
||||
for (const omega of [0, 1, 1e300]) {
|
||||
assert.deepEqual(impedance(candidate, omega), { re: 0, im: 0, amp: 0, singular: false, short: true });
|
||||
}
|
||||
const result = analyze(base, candidate, 32);
|
||||
assert.equal(result.mode, 'ideal-short'); assert.equal(result.boundedSteadyState, 'ideal');
|
||||
assert.equal(result.coreLike.ppSample, 0); assert.equal(result.coreLike.ppUpper, 0);
|
||||
assert.equal(result.coreLike.status, 'pass'); assert.equal(result.coreLike.certified, true);
|
||||
assert.ok(result.coreLike.wave.voltage.every(v => v === 0));
|
||||
assert.ok(result.spectrum.every(row => row.z === 0 && row.voltage === 0));
|
||||
assert.ok(result.notices.some(text => text.includes('理想通过不能代表实际')));
|
||||
}
|
||||
});
|
||||
|
||||
test('纯R无电容无电感用精确R·Imax及含跳变的时域,不受截断N影响', () => {
|
||||
const R = 0.2, pp = R * op.max;
|
||||
const result = analyze(base, { R, Ls: 0, C: 0 }, 1);
|
||||
assert.equal(result.mode, 'pure-r'); assert.equal(result.coreLike.ppSample, pp);
|
||||
assert.equal(result.coreLike.ppLower, pp); assert.equal(result.coreLike.ppUpper, pp);
|
||||
assert.equal(result.coreLike.status, 'fail'); assert.equal(result.coreLike.certified, true);
|
||||
close(result.coreLike.rippleMax - result.coreLike.rippleMin, pp);
|
||||
const wave = result.coreLike.wave;
|
||||
assert.equal(wave.theta[0], wave.theta[1]); assert.equal(wave.theta[2], wave.theta[3]);
|
||||
close(wave.voltage[1], -R * (op.min - op.iavg));
|
||||
close(wave.voltage[2], -R * (op.max - op.iavg));
|
||||
close(wave.voltage[3], R * op.iavg);
|
||||
assert.equal(analyze(base, { R, Ls: 0, C: 0 }, 128).coreLike.ppSample, pp);
|
||||
assert.equal(analyze({ ...base, target: pp }, { R, Ls: 0, C: 0 }, 7).coreLike.status, 'pass');
|
||||
});
|
||||
|
||||
test('C0且Ls>0返回R+jωLs,但开关阶跃电压脉冲无物理有限pp或波形', () => {
|
||||
for (const R of [0, 0.1]) {
|
||||
const candidate = { R, Ls: 2e-6, C: 0 };
|
||||
for (const omega of [1, 1e6]) {
|
||||
const z = impedance(candidate, omega);
|
||||
close(z.re, R); close(z.im, omega * candidate.Ls); close(z.amp, Math.hypot(R, omega * candidate.Ls));
|
||||
assert.equal(z.singular, false);
|
||||
}
|
||||
const result = analyze(base, candidate, 32);
|
||||
assert.equal(result.mode, 'inductive-no-cap'); assert.equal(result.boundedSteadyState, 'undefined');
|
||||
assert.equal(result.coreLike.wave, null); assert.equal(result.coreLike.ppSample, null);
|
||||
assert.equal(result.coreLike.ppUpper, null); assert.equal(result.coreLike.status, 'uncertain');
|
||||
assert.equal(result.coreLike.certified, false); assert.equal(result.peak.magnitude, Infinity);
|
||||
assert.equal(result.peak.frequency, null);
|
||||
assert.ok(result.spectrum.every(row => Number.isFinite(row.voltage)));
|
||||
assert.ok(result.notices.some(text => text.includes('有限峰峰值不定义')));
|
||||
}
|
||||
});
|
||||
|
||||
test('无损LC精确极点与1e-12邻域标Infinity/null,绝不变为有损有限值', () => {
|
||||
const candidate = { R: 0, Ls: 2e-6, C: 100e-6 };
|
||||
const omega0 = 1 / Math.sqrt(candidate.Ls * candidate.C);
|
||||
for (const multiplier of [1, 1 - 0.5e-12, 1 + 0.5e-12]) {
|
||||
const z = impedance(candidate, omega0 * multiplier);
|
||||
assert.equal(z.singular, true); assert.equal(z.amp, Infinity);
|
||||
assert.equal(z.re, null); assert.equal(z.im, null); assert.equal(z.short, false);
|
||||
}
|
||||
for (const multiplier of [0.5, 1 - 2e-12, 1 + 2e-12, 2]) {
|
||||
const omega = omega0 * multiplier, z = impedance(candidate, omega);
|
||||
assert.equal(z.singular, false); assert.ok(Number.isFinite(z.amp) && z.amp > 0);
|
||||
close(z.im, omega * candidate.Ls / (1 - omega ** 2 * candidate.Ls * candidate.C), 0.003);
|
||||
}
|
||||
});
|
||||
|
||||
test('无损LC被基波/偶次/显示N外谐波激励时无有界稳态和伪pass', () => {
|
||||
for (const [n, N] of [[1, 32], [2, 32], [200, 16]]) {
|
||||
const candidate = { R: 0, Ls: 1e-6, C: 1 / ((n * op.ws) ** 2 * 1e-6) };
|
||||
const result = analyze(base, candidate, N);
|
||||
assert.equal(result.mode, 'lossless-lc'); assert.equal(result.resonant, true);
|
||||
assert.equal(result.poleHarmonic, n); assert.equal(result.boundedSteadyState, 'unbounded');
|
||||
assert.equal(result.coreLike.wave, null); assert.equal(result.coreLike.ppSample, null);
|
||||
assert.equal(result.coreLike.ppUpper, null); assert.equal(result.coreLike.status, 'uncertain');
|
||||
assert.equal(result.peak.magnitude, Infinity); assert.equal(result.coreLike.certified, false);
|
||||
if (n <= N) {
|
||||
const row = result.spectrum[n - 1]; assert.equal(row.singular, true);
|
||||
assert.equal(row.z, Infinity); assert.equal(row.voltage, null); assert.equal(row.vre, null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('无损LC未命中谐波仅画finiteN受迫特解,保留初值自由振荡与未定状态', () => {
|
||||
const candidate = { R: 0, Ls: 1e-6, C: 1 / ((1.37 * op.ws) ** 2 * 1e-6) };
|
||||
const result = analyze(base, candidate, 17);
|
||||
assert.equal(result.mode, 'lossless-lc'); assert.equal(result.resonant, false);
|
||||
assert.equal(result.poleHarmonic, null); assert.equal(result.forcedOnly, true);
|
||||
assert.equal(result.boundedSteadyState, 'forced-only'); assert.ok(result.coreLike.wave);
|
||||
assert.equal(result.coreLike.certified, false); assert.equal(result.coreLike.status, 'uncertain');
|
||||
assert.equal(result.coreLike.ppLower, null); assert.equal(result.coreLike.ppUpper, null);
|
||||
assert.equal(result.peak.magnitude, Infinity);
|
||||
const wave = result.coreLike.wave;
|
||||
for (let k = 0; k < wave.theta.length; k += 41) close(wave.voltage[k], directVoltage(result.spectrum, wave.theta[k]), 1e-9);
|
||||
close(result.coreLike.rms, Math.sqrt(result.spectrum.reduce((s, row) => s + row.voltage ** 2 / 2, 0)));
|
||||
assert.ok(result.notices.some(text => text.includes('自由振荡')));
|
||||
});
|
||||
|
||||
test('完整N频谱保留需求相位与电压负号,不限于原内核64次', () => {
|
||||
const N = 129, result = analyze(base, normal, N);
|
||||
assert.equal(result.spectrum.length, N); assert.equal(result.coreLike.spectrum, result.spectrum);
|
||||
for (const n of [1, 2, 64, 65, N]) {
|
||||
const row = result.spectrum[n - 1], current = core.harmonic(op, n), z = core.impedance(normal.R, normal.Ls, normal.C, n * op.ws);
|
||||
assert.equal(row.n, n); assert.equal(row.freq, n * base.fsw);
|
||||
assert.equal(row.ire, current.re); assert.equal(row.iim, current.im); assert.equal(row.current, current.amp);
|
||||
close(row.vre, -(z.re * current.re - z.im * current.im));
|
||||
close(row.vim, -(z.re * current.im + z.im * current.re));
|
||||
close(row.voltage, z.amp * current.amp); assert.equal(row.singular, false);
|
||||
}
|
||||
});
|
||||
|
||||
test('水平Z参考严格target/(2Σ前N次峰值电流),独立于候选RLC且只覆盖截断预算', () => {
|
||||
let previous = null;
|
||||
for (const N of [1, 7, 32, 129]) {
|
||||
const result = analyze(base, normal, N);
|
||||
const sum = result.spectrum.reduce((s, row) => s + row.current, 0);
|
||||
close(result.sumCurrent, sum); close(result.referenceZ, base.target / (2 * sum));
|
||||
assert.equal(result.dcCurrent, op.iavg);
|
||||
close(analyze(base, { R: 0, Ls: 0, C: 0 }, N).referenceZ, result.referenceZ);
|
||||
if (previous) assert.ok(result.referenceZ < previous);
|
||||
previous = result.referenceZ;
|
||||
assert.ok(result.referenceScope.includes('不是全频阻抗限值'));
|
||||
}
|
||||
const trial = analyze(base, { R: 1e-4, Ls: 0, C: 470e-6 }, 32);
|
||||
assert.ok(trial.spectrum.every(row => row.z <= trial.referenceZ));
|
||||
assert.ok(2 * trial.spectrum.reduce((s, row) => s + row.voltage, 0) <= base.target);
|
||||
});
|
||||
|
||||
test('无损LC低频感性/高频容性斜率与有限正负频段一致', () => {
|
||||
const candidate = { R: 0, Ls: 1e-6, C: 100e-6 };
|
||||
const w0 = 1 / Math.sqrt(candidate.Ls * candidate.C);
|
||||
const low = impedance(candidate, w0 * 1e-5), low2 = impedance(candidate, w0 * 2e-5);
|
||||
const high = impedance(candidate, w0 * 1e5), high2 = impedance(candidate, w0 * 2e5);
|
||||
assert.ok(low.im > 0 && high.im < 0);
|
||||
close(low2.amp / low.amp, 2, 1e-8);
|
||||
close(high2.amp / high.amp, 0.5, 1e-8);
|
||||
close(low.im / (w0 * 1e-5 * candidate.Ls), 1, 1e-8);
|
||||
close(-high.im * w0 * 1e5 * candidate.C, 1, 1e-8);
|
||||
});
|
||||
|
||||
test('输入严格验证与数值溢出中文报错,不以NaN/epsilon伪装通过', () => {
|
||||
for (const candidate of [null, [], 'rlc', { ...normal, R: -1 }, { ...normal, Ls: -1 },
|
||||
{ ...normal, C: -1 }, { ...normal, R: '0' }, { ...normal, C: NaN }, { ...normal, Ls: Infinity }]) {
|
||||
rejects(() => impedance(candidate, 1)); rejects(() => analyze(base, candidate));
|
||||
}
|
||||
for (const omega of [-1, NaN, Infinity, '1', undefined]) rejects(() => impedance(normal, omega));
|
||||
for (const N of [0, -1, 0.5, 8193, NaN, Infinity, '128', null]) rejects(() => analyze(base, normal, N));
|
||||
rejects(() => analyze({ ...base, L: 1e-12 }, normal));
|
||||
rejects(() => impedance({ R: 0, Ls: 1e308, C: 0 }, 1e308));
|
||||
rejects(() => analyze(base, { ...normal, C: Number.MIN_VALUE }, 16));
|
||||
rejects(() => impedance({ R: 0, Ls: Number.MIN_VALUE, C: Number.MIN_VALUE }, 1));
|
||||
assert.equal(analyze(base, normal).N, 128);
|
||||
assert.equal(analyze(base, { R: 0, Ls: 0, C: 0 }, 8192).spectrum.length, 8192);
|
||||
});
|
||||
|
||||
test('单项参考为目标峰峰值除以电流峰峰值,不除N且不作总纹波保证', () => {
|
||||
for (const D of [0.1, 0.5, 0.9]) {
|
||||
const input = { ...base, drop: base.vin * (1-D) };
|
||||
const r = analyze(input, normal, 32);
|
||||
assert.equal(r.referenceMode, 'single-tone-voltage-current-ratio');
|
||||
assert.equal(r.impedanceLimits.length, 32);
|
||||
close(r.allowedVoltage, input.target/2);
|
||||
let budget = 0;
|
||||
for (const limit of r.impedanceLimits) {
|
||||
assert.equal(limit.freq, limit.n*input.fsw);
|
||||
assert.equal(limit.current, r.spectrum[limit.n-1].current);
|
||||
if (limit.current > 0) {
|
||||
close(limit.limit*limit.current, r.allowedVoltage);
|
||||
budget += limit.limit*limit.current;
|
||||
} else { assert.equal(limit.limit, Infinity); assert.equal(limit.finite, false); }
|
||||
}
|
||||
close(2*budget,32*input.target);
|
||||
const higherN=analyze(input,normal,128);
|
||||
for(let i=0;i<32;i++)close(higherN.impedanceLimits[i].limit,r.impedanceLimits[i].limit);
|
||||
assert.ok(r.referenceScope.includes('不是各次共同作用的总纹波充分条件'));
|
||||
assert.notEqual(r.impedanceLimits[0].limit, r.impedanceLimits[1].limit);
|
||||
close(analyze({...input,target:input.target*2},normal,32).impedanceLimits[0].limit,2*r.impedanceLimits[0].limit);
|
||||
const other = analyze(input,{R:0,Ls:0,C:0},32);
|
||||
for(let i=0;i<32;i++)close(other.impedanceLimits[i].limit,r.impedanceLimits[i].limit);
|
||||
}
|
||||
});
|
||||
|
||||
test('电流趋势经过精确整数次谐波,并符合单周期积分', () => {
|
||||
const points = currentTrend(base, 4);
|
||||
assert.equal(points.length, 49);
|
||||
for (const n of [1, 2, 3, 4]) {
|
||||
assert.deepEqual(points[(n - 1) * 16], { freq: n * op.fsw, current: core.harmonic(op, n).amp });
|
||||
}
|
||||
|
||||
const samples = 20000;
|
||||
const step = op.D / samples;
|
||||
const order = 1.5;
|
||||
let real = 0, imaginary = 0;
|
||||
for (let index = 0; index < samples; index++) {
|
||||
const time = (index + 0.5) * step;
|
||||
const current = op.IL + op.delta * (time / op.D - 0.5);
|
||||
const angle = -2 * Math.PI * order * time;
|
||||
real += current * Math.cos(angle);
|
||||
imaginary += current * Math.sin(angle);
|
||||
}
|
||||
assert.equal(points[8].freq, order * op.fsw);
|
||||
close(points[8].current, 2 * step * Math.hypot(real, imaginary), 1e-8);
|
||||
});
|
||||
|
||||
test('阻抗扫描基础点数与固定阶数的电流趋势一致,并可指定点数', () => {
|
||||
const N = core.constants.FIXED_HARMONICS;
|
||||
const min = 1e3, max = 1e6;
|
||||
const trend = currentTrend(base, N);
|
||||
const points = scanImpedance(normal, min, max);
|
||||
assert.equal(points.length, trend.length);
|
||||
assert.equal(points.length, 16369);
|
||||
const custom = scanImpedance(normal, min, max, undefined, 64);
|
||||
assert.equal(custom.length, 64);
|
||||
assert.equal(custom[0].f, min);
|
||||
assert.equal(custom.at(-1).f, max);
|
||||
for (const invalid of [1, 2.5, 65537, Infinity, '64']) {
|
||||
rejects(() => scanImpedance(normal, min, max, undefined, invalid));
|
||||
}
|
||||
});
|
||||
|
||||
test('阻抗扫描加密窄谐振峰的两侧,并在无损极点断开', () => {
|
||||
const candidate = { R: 1e-5, Ls: 1e-6, C: 1e-6 };
|
||||
const { peak } = analyze(base, candidate, 32);
|
||||
const min = 1e3, max = 1e6, halfWidth = candidate.R / candidate.Ls / (4 * Math.PI);
|
||||
const points = scanImpedance(candidate, min, max, peak);
|
||||
assert.ok(points.length > 16369);
|
||||
assert.equal(points[0].f, min);
|
||||
assert.equal(points.at(-1).f, max);
|
||||
assert.ok(points.every((point, index) => index === 0 || point.f > points[index - 1].f));
|
||||
close(points.find(point => point.f === peak.frequency).z.amp, peak.magnitude, 1e-6);
|
||||
for (const direction of [-1, 1]) {
|
||||
const shoulder = points.find(point => point.f === peak.frequency + direction * halfWidth);
|
||||
close(shoulder.z.amp / peak.magnitude, Math.SQRT1_2, 2e-5);
|
||||
}
|
||||
|
||||
const lossless = scanImpedance({ ...candidate, R: 0 }, min, max);
|
||||
const poleIndex = lossless.findIndex(point => point.z.singular);
|
||||
assert.ok(poleIndex > 0 && poleIndex < lossless.length - 1);
|
||||
assert.equal(lossless[poleIndex].z.amp, Infinity);
|
||||
assert.equal(lossless[poleIndex - 1].z.singular, false);
|
||||
assert.equal(lossless[poleIndex + 1].z.singular, false);
|
||||
});
|
||||
|
||||
console.log(`\n${passed} 项可视化内核测试全部通过。`);
|
||||
@@ -0,0 +1,115 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const ampacity = require('../src/buck-wire-ampacity.js');
|
||||
const { limit, table, info } = ampacity;
|
||||
let passed = 0;
|
||||
function test(name, run) { run(); passed++; console.log('✓ ' + name); }
|
||||
function close(actual, expected) {
|
||||
assert.ok(Number.isFinite(actual));
|
||||
assert.ok(Math.abs(actual - expected) <= Math.abs(expected) * 1e-12 + 1e-12, `实际 ${actual},预期 ${expected}`);
|
||||
}
|
||||
function rejects(run) {
|
||||
assert.throws(run, error => error instanceof Error && /[\u4e00-\u9fff]/.test(error.message));
|
||||
}
|
||||
const gauges = [6, 8, 10, 12, 14, 16, 18, 20, 22, 24];
|
||||
const single = [95, 75, 52, 34, 24, 15, 9.5, 6, 5, 3.5];
|
||||
const grouped = [55, 40, 30, 20, 15, 10, 7, 5, 3, 2];
|
||||
|
||||
test('CommonJS和无依赖浏览器全局导出一致,静态表及信息只读', () => {
|
||||
assert.equal(globalThis.BuckWireAmpacity, ampacity);
|
||||
const browser = {};
|
||||
vm.runInNewContext(fs.readFileSync(require.resolve('../src/buck-wire-ampacity.js'), 'utf8'), browser);
|
||||
assert.equal(typeof browser.BuckWireAmpacity.limit, 'function');
|
||||
assert.equal(browser.BuckWireAmpacity.limit(12).currentLimit, limit(12).currentLimit);
|
||||
for (const value of [ampacity, table, table.single, table.grouped, info, info.installations,
|
||||
info.supportedAwg, info.temperatureBands, ...info.temperatureBands]) assert.ok(Object.isFrozen(value));
|
||||
assert.throws(() => { table.single[12] = 999; }, TypeError);
|
||||
});
|
||||
|
||||
test('两列完整表逐行与已核实PVC铜线典型值一致,不进行插值', () => {
|
||||
assert.deepEqual(info.supportedAwg, gauges);
|
||||
assert.equal(Object.keys(table.single).length, 10); assert.equal(Object.keys(table.grouped).length, 10);
|
||||
for (const [index, awg] of gauges.entries()) {
|
||||
assert.equal(table.single[awg], single[index]); assert.equal(table.grouped[awg], grouped[index]);
|
||||
for (const [installation, expected] of [['single', single[index]], ['grouped', grouped[index]]]) {
|
||||
const result = limit(awg, { installation, ambientC: 30, designFactor: 1 });
|
||||
assert.equal(result.awg, awg); assert.equal(result.installation, installation);
|
||||
assert.equal(result.baseCurrent, expected); assert.equal(result.temperatureFactor, 1);
|
||||
assert.equal(result.currentLimit, expected); assert.equal(result.designFactor, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('默认grouped/30°C/0.8,0.8是工具自定余量而非源标准', () => {
|
||||
const result = limit(12);
|
||||
assert.equal(result.installation, 'grouped'); assert.equal(result.ambientC, 30);
|
||||
assert.equal(result.designFactor, 0.8); assert.equal(result.baseCurrent, 20);
|
||||
assert.equal(result.temperatureFactor, 1); assert.equal(result.currentLimit, 16);
|
||||
assert.equal(info.defaultInstallation, 'grouped'); assert.equal(info.defaultDesignFactor, 0.8);
|
||||
assert.ok(result.scope.includes('本工具自定')); assert.ok(result.scope.includes('不是原表'));
|
||||
assert.ok(info.designFactorScope.includes('不是原表'));
|
||||
});
|
||||
|
||||
test('环境分段边界严格≤30/≤40/≤45/≤50,低温不冷增额', () => {
|
||||
const cases = [[-40, 1], [-10, 1], [0, 1], [29.999999, 1], [30, 1],
|
||||
[30.000001, 0.82], [40, 0.82], [40.000001, 0.71], [45, 0.71], [45.000001, 0.58], [50, 0.58]];
|
||||
for (const [ambientC, expected] of cases) {
|
||||
const result = limit(10, { installation: 'single', ambientC, designFactor: 1 });
|
||||
assert.equal(result.temperatureFactor, expected); close(result.currentLimit, 52 * expected);
|
||||
assert.ok(result.currentLimit <= result.baseCurrent);
|
||||
}
|
||||
assert.equal(limit(10, { ambientC: -40 }).currentLimit, limit(10, { ambientC: 30 }).currentLimit);
|
||||
});
|
||||
|
||||
test('设计余量与环境因子相乘降额,单芯与≤3芯列不互相混用', () => {
|
||||
for (const awg of gauges) for (const installation of ['single', 'grouped']) {
|
||||
const result = limit(awg, { installation, ambientC: 42, designFactor: 0.6 });
|
||||
close(result.currentLimit, table[installation][awg] * 0.71 * 0.6);
|
||||
assert.ok(result.currentLimit <= result.baseCurrent);
|
||||
}
|
||||
close(limit(18, { installation: 'grouped', ambientC: 50 }).currentLimit, 7 * 0.58 * 0.8);
|
||||
close(limit(18, { installation: 'single', ambientC: 50 }).currentLimit, 9.5 * 0.58 * 0.8);
|
||||
});
|
||||
|
||||
test('使用比例允许超过100%,仍按所选表值及环境系数相乘', () => {
|
||||
for (const awg of gauges) for (const installation of ['single', 'grouped']) {
|
||||
for (const designFactor of [1.00001, 1.5, 2, 10]) {
|
||||
const result = limit(awg, { installation, ambientC: 42, designFactor });
|
||||
close(result.currentLimit, table[installation][awg] * 0.71 * designFactor);
|
||||
assert.equal(result.designFactor, designFactor);
|
||||
}
|
||||
}
|
||||
assert.equal(limit(18, { designFactor: 2 }).currentLimit, 14);
|
||||
});
|
||||
|
||||
test('不根据材质加额,single列使用/厂家敷设温升/非官方标准限制明示', () => {
|
||||
const ordinary = limit(12);
|
||||
for (const material of ['PVC', 'silicone', 'PTFE']) {
|
||||
assert.deepEqual(limit(12, { material }), ordinary);
|
||||
}
|
||||
assert.equal(info.sourceIsOfficialStandard, false);
|
||||
assert.equal(info.source, 'https://www.engineeringtoolbox.com/wire-gauges-d_419.html');
|
||||
assert.equal(ordinary.source, info.source);
|
||||
for (const text of ['PVC', 'single', '至多 3 芯', '不是官方标准', '不自动加额', '厂家', '敷设', '温升', '法规']) {
|
||||
assert.ok(ordinary.scope.includes(text), text);
|
||||
}
|
||||
});
|
||||
|
||||
test('严格拒绝奇数/非数AWG、不支持敷设、环境越界与非法余量,错误为中文', () => {
|
||||
for (const awg of [5, 7, 11, 23, 25, 12.5, '12', null, undefined, NaN, Infinity]) rejects(() => limit(awg));
|
||||
for (const options of [null, [], 'grouped', 1, false]) rejects(() => limit(12, options));
|
||||
for (const installation of ['', 'multicore', 'SINGLE', 'single ', 0, 1, null, {}, []]) {
|
||||
rejects(() => limit(12, { installation }));
|
||||
}
|
||||
for (const ambientC of [-40.00001, 50.00001, 51, NaN, Infinity, -Infinity, '30', null]) {
|
||||
rejects(() => limit(12, { ambientC }));
|
||||
}
|
||||
for (const designFactor of [0, -1, NaN, Infinity, '0.8', null, Number.MIN_VALUE, Number.MAX_VALUE]) {
|
||||
rejects(() => limit(12, { designFactor }));
|
||||
}
|
||||
assert.deepEqual(limit(12, {}), limit(12, { installation: undefined, ambientC: undefined, designFactor: undefined }));
|
||||
});
|
||||
|
||||
console.log(`\n${passed} 项经验载流表测试全部通过。`);
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
require('../src/calculator-validation-data.js');
|
||||
const validation=require('../src/calculator-validation.js');
|
||||
const data=globalThis.CalculatorValidationData;
|
||||
test('precision thresholds are inclusive and never classify missing results',()=>{
|
||||
for(const sign of [-1,1])for(const threshold of [1,3,5])assert.equal(validation.tier(sign*threshold),threshold);
|
||||
assert.equal(validation.tier(1.00001),3);assert.equal(validation.tier(5.00001),null);
|
||||
for(const value of [undefined,null,NaN,Infinity])assert.equal(validation.tier(value),null);
|
||||
});
|
||||
test('summary intervals contain only jointly tested points that pass the selected output',()=>{
|
||||
const pp=validation.summarize('buck','ripple',1),spectrum=validation.summarize('buck','spectrum',3);
|
||||
assert.equal(pp.total,64);assert.equal(pp.passed.length,63);assert.ok(!pp.passed.some(r=>r.id==='B02'));
|
||||
assert.equal(spectrum.passed.length,63);assert.equal(validation.summarize('buck','spectrum',5).passed.length,64);
|
||||
assert.equal(validation.summarize('pmsm','spectrum',1).passed.length,65);
|
||||
assert.equal(validation.summarize('pmsm','ripple',1).passed.length,70);
|
||||
assert.throws(()=>validation.summarize('buck','ripple',2));
|
||||
for(const kind of ['buck','pmsm'])for(const [key] of validation.definitions[kind]){
|
||||
let previous=0;
|
||||
for(const threshold of [1,3,5]){
|
||||
const result=validation.summarize(kind,key,threshold);assert.ok(result.passed.length>=previous);previous=result.passed.length;
|
||||
result.passed.forEach(r=>assert.ok(Math.abs(r.errors[key])<=threshold));
|
||||
}
|
||||
}
|
||||
});
|
||||
test('changing one supply parameter does not preserve an exact verified match',()=>{
|
||||
const input={...data.buck[1].input};assert.equal(validation.match('buck',input).id,'B02');
|
||||
assert.equal(validation.match('buck',{...input,C:input.C*1.01}),null);
|
||||
assert.equal(validation.coverage('buck',{...input,fsw:2.1e6}).outside.length,1);
|
||||
assert.equal(validation.match('pmsm',data.pmsm[0].input).id,'M01');
|
||||
assert.equal(validation.match('pmsm',{...data.pmsm[0].input,angle:.3}),null);
|
||||
});
|
||||
|
||||
test('Buck estimates use the periodic complete-circuit reference instead of nearest samples',()=>{
|
||||
const exact=validation.estimate('buck',{input:data.buck[1].input});
|
||||
assert.equal(exact.tier,3);assert.equal(exact.exact,false);assert.ok(exact.referencePp>0);assert.ok(Math.abs(exact.errorPercent+2.857)<.01);
|
||||
const nearby=validation.estimate('buck',{input:{vin:24,fsw:20000,L:75e-6,iavg:5,D:.5,R:.05,Ls:1e-6,C:.0015}});
|
||||
assert.ok([1,3,5].includes(nearby.tier));assert.equal(nearby.exact,false);assert.ok(nearby.upper>nearby.lower);
|
||||
assert.match(nearby.reason,/完整周期电路/);
|
||||
assert.equal(validation.estimate('pmsm',{input:data.pmsm[0].input}).disabled,true);
|
||||
});
|
||||
|
||||
test('unsupported algorithm settings and distant/ideal-boundary inputs never get an accuracy band',()=>{
|
||||
const input=data.buck[1].input;
|
||||
assert.equal(validation.estimate('buck',{input,eligible:false}).tier,null);
|
||||
assert.equal(validation.estimate('buck',{input:{...input,fsw:1e8}}).tier,null);
|
||||
assert.equal(validation.estimate('buck',{input:{...input,C:0}}).tier,null);
|
||||
assert.equal(validation.estimate('buck',{input:{...input,R:0}}).tier,null);
|
||||
assert.equal(validation.estimate('pmsm',{input:null}).tier,null);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const chart=require('../src/motor-bus-chart.js'),core=require('../src/buck-calculator-engine.js');
|
||||
const op=core.operating({vin:24,drop:12,iavg:5,fsw:20000,L:75e-6,target:.12});
|
||||
const points=Array.from({length:1024},(_,i)=>{const h=core.harmonic(op,i+1);return {f:(i+1)*op.fsw,ipk:h.amp,zRef:op.target/(2*h.amp),mode:'drive'};});
|
||||
|
||||
test('all four display densities evaluate three curves on the same exact grid and retain all 1024 real lines',()=>{
|
||||
for(const sampleCount of [32768,65536,131072,262144]){
|
||||
let evaluations=0;const peakHz=4321.123456;
|
||||
const curves=chart.sampleCurves({minHz:1000,maxHz:2.4e7,sampleCount,points,peakHz,targetVpp:.12,referenceFromCurrent:true,
|
||||
network:f=>{evaluations++;return 1/Math.hypot(1,f/2000);}});
|
||||
for(const values of [curves.frequency,curves.impedance,curves.reference,curves.currents[0].values])assert.equal(values.length,sampleCount);
|
||||
assert.equal(evaluations,sampleCount);
|
||||
for(let i=1;i<sampleCount;i++)assert.ok(curves.frequency[i]>curves.frequency[i-1]);
|
||||
const indices=new Map(Array.from(curves.frequency,(f,i)=>[f,i]));assert.ok(indices.has(peakHz));
|
||||
for(const p of points){const index=indices.get(p.f);assert.notEqual(index,undefined);assert.equal(curves.currents[0].values[index],p.ipk);assert.ok(Math.abs(curves.reference[index]/p.zRef-1)<1e-12);}
|
||||
assert.ok(Number.isNaN(curves.currents[0].values[0]));
|
||||
assert.equal(points.length,1024);
|
||||
}
|
||||
});
|
||||
|
||||
test('shape-preserving interpolation keeps real zeros, local extrema, modes and unsupported frequency gaps',()=>{
|
||||
const f=chart.frequencyGrid(1,100,1000,[2,4,8,16]);
|
||||
const values=chart.interpolate([{f:2,value:0},{f:4,value:10},{f:8,value:0},{f:16,value:5}],f);
|
||||
for(let i=0;i<f.length;i++)if(f[i]<2||f[i]>16)assert.ok(Number.isNaN(values[i]));else assert.ok(values[i]>=0&&values[i]<=10);
|
||||
for(const [frequency,value]of [[2,0],[4,10],[8,0],[16,5]])assert.equal(values[f.indexOf(frequency)],value);
|
||||
const curves=chart.sampleCurves({minHz:1,maxHz:100,sampleCount:1024,targetVpp:.2,referenceFromCurrent:true,network:()=>1,
|
||||
points:[{f:2,ipk:0,mode:'drive'},{f:4,ipk:10,mode:'drive'},{f:8,ipk:0,mode:'drive'},{f:4,ipk:3,mode:'regen'},{f:8,ipk:2,mode:'regen'}]});
|
||||
assert.equal(curves.currents.length,2);assert.equal(curves.reference[curves.frequency.indexOf(2)],Infinity);
|
||||
});
|
||||
|
||||
test('canvas path reduction preserves narrow extrema and non-finite breaks',()=>{
|
||||
const f=chart.frequencyGrid(1,100,10000),v=new Float64Array(f.length);v.fill(1);v[1234]=100;v[1235]=.001;v[5000]=Infinity;
|
||||
const indices=chart.pathIndices(f,v,100);
|
||||
assert.ok(indices.includes(1234));assert.ok(indices.includes(1235));assert.ok(indices.includes(-1));assert.ok(!indices.includes(5000));assert.ok(indices.length<1000);
|
||||
});
|
||||
|
||||
test('the actual renderer uses dense curves and reuses them for hover-only redraws',()=>{
|
||||
const noop=()=>{},ctx=new Proxy({measureText:s=>({width:s.length*6})},{get:(t,k)=>k in t?t[k]:noop});
|
||||
const canvas={clientWidth:900,clientHeight:360,style:{},dataset:{},getContext:()=>ctx,getBoundingClientRect:()=>({width:900,height:360})};
|
||||
let calls=0;const options={minHz:1000,maxHz:2.4e7,sampleCount:32768,points,dataKey:'same-case',branch:{R:.05,Ls:1e-6,C:.0015},referenceFromCurrent:true,targetVpp:.12,network:f=>{calls++;return 1/(1+f/1000);}};
|
||||
const first=chart.draw(canvas,options);assert.equal(calls,32768);assert.deepEqual(first.sampleCounts,{frequency:32768,impedance:32768,reference:32768,current:32768});
|
||||
assert.equal(canvas.dataset.referenceSamples,'32768');chart.draw(canvas,{...options,hoverHz:40000});assert.equal(calls,32768);
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
'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 { normalize, electricalLimit, snapFrequency, caseSpectrum, exactSpectrum, scan, scanAsync } = engine;
|
||||
let passed = 0;
|
||||
function test(name, run) { 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 rejects(run) { assert.throws(run, error => error instanceof Error && /[\u4e00-\u9fff]/.test(error.message)); }
|
||||
const { motor } = normalize();
|
||||
const Ib = Math.SQRT2 * 13.3;
|
||||
const cache = new Map();
|
||||
function point(fe, iqPeak, extra = {}) {
|
||||
const key = JSON.stringify([fe, iqPeak, extra]);
|
||||
if (!cache.has(key)) cache.set(key, caseSpectrum(motor, { fe, iqPeak, ...extra }));
|
||||
return cache.get(key);
|
||||
}
|
||||
|
||||
test('CommonJS/browser/worker global接口一致,依赖FFT加载明确', () => {
|
||||
assert.equal(globalThis.MotorBusEngine, engine);
|
||||
assert.ok(Object.isFrozen(engine));
|
||||
const browser = { setTimeout };
|
||||
vm.runInNewContext(fs.readFileSync(require.resolve('../src/buck-calculator-engine.js'), 'utf8'), browser);
|
||||
const source = fs.readFileSync(require.resolve('../src/motor-bus-engine.js'), 'utf8');
|
||||
vm.runInNewContext(source, browser);
|
||||
assert.equal(typeof browser.MotorBusEngine.scanAsync, 'function');
|
||||
close(browser.MotorBusEngine.caseSpectrum({}, { fe: 0, iqPeak: 49.04 }).peakLine.amplitude, 18.290380128839956);
|
||||
assert.throws(() => vm.runInNewContext(source, {}), /先加载 BuckRLC/);
|
||||
});
|
||||
|
||||
test('线间R/L折半,13.3ARMS基波与49.04Apk锁转假设分开', () => {
|
||||
close(motor.R, 0.065); close(motor.L, 44.985e-6);
|
||||
close(motor.alpha, motor.R / motor.L); close(motor.fePerRpm, 14 * 9.25 / 60);
|
||||
const normalized = normalize();
|
||||
assert.equal(normalized.options.phaseRms, 13.3); assert.equal(normalized.options.stallPeak, 49.04);
|
||||
assert.ok(engine.scope.includes('不是厂家已确认')); assert.ok(engine.scope.includes('不是连续域全局证明'));
|
||||
assert.equal(normalize({}, { maxBusW: '', maxRpm: '' }).options.maxBusW, 0);
|
||||
});
|
||||
|
||||
test('i_d0不弱磁可达边界随q正负/SPWM变化,边界相电压满足解析式', () => {
|
||||
const positive = electricalLimit(motor, Ib), negative = electricalLimit(motor, -Ib);
|
||||
assert.ok(negative.rpm > positive.rpm);
|
||||
close(positive.rpm, 295.10850140227); close(negative.rpm, 349.9719493142039);
|
||||
for (const pwm of ['svpwm', 'spwm']) for (const iqPeak of [-Ib, 0, Ib]) {
|
||||
const limit = electricalLimit(motor, iqPeak, pwm);
|
||||
assert.equal(limit.available, true);
|
||||
const rpm = limit.fe / motor.fePerRpm;
|
||||
const v = Math.hypot(motor.ke * rpm + motor.R * iqPeak, 2 * Math.PI * limit.fe * motor.L * iqPeak);
|
||||
close(v, limit.voltageLimit);
|
||||
}
|
||||
assert.ok(electricalLimit(motor, Ib, 'spwm').rpm < positive.rpm);
|
||||
const step = motor.fsw / 512;
|
||||
const last = Math.floor(positive.fe / step) * step;
|
||||
assert.ok(caseSpectrum(motor, { fe: last, iqPeak: Ib }).modulationRatio <= 1);
|
||||
rejects(() => caseSpectrum(motor, { fe: last + step, iqPeak: Ib }));
|
||||
});
|
||||
|
||||
test('有理电频公共周期保持真实freq=k*f0,不静默把任意rpm改网格', () => {
|
||||
const snapped = snapFrequency(motor, 310);
|
||||
assert.equal(snapped.fe, 312.5); close(snapped.rpm, 312.5 / motor.fePerRpm);
|
||||
const c = point(312.5, Ib);
|
||||
assert.equal(c.cycles, 64); assert.equal(c.M, 64 * 128);
|
||||
close(c.duration, 1 / c.f0); close(c.f0, motor.fsw / 64);
|
||||
assert.ok(c.k instanceof Uint32Array);
|
||||
for (const name of ['freq', 're', 'im']) assert.ok(c[name] instanceof Float64Array);
|
||||
assert.equal(c.freq.length, 640); assert.equal(c.freq.at(-1), 200000);
|
||||
for (let i = 0; i < c.freq.length; i++) { assert.equal(c.k[i], i + 1); assert.equal(c.freq[i], c.k[i] * c.f0); }
|
||||
rejects(() => caseSpectrum(motor, { fe: 310, iqPeak: Ib }));
|
||||
const fromRpm = caseSpectrum(motor, { rpm: c.rpm, iqPeak: Ib });
|
||||
close(fromRpm.dc, c.dc); close(fromRpm.peakLine.amplitude, c.peakLine.amplitude);
|
||||
});
|
||||
|
||||
test('已确认主谱线校核:额定143–148rpm约10.8A@40k,锁转18.29A@40k', () => {
|
||||
const running = point(312.5, Ib, { verifyLines: 12 });
|
||||
assert.ok(running.rpm > 143 && running.rpm < 148);
|
||||
assert.equal(running.peakLine.frequency, 40000); close(running.peakLine.amplitude, 10.8, 0.005);
|
||||
const locked = point(0, 49.04);
|
||||
assert.equal(locked.peakLine.frequency, 40000); close(locked.peakLine.amplitude, 18.29038012884, 1e-10);
|
||||
assert.equal(locked.M, 0); assert.equal(locked.freq.length, 10);
|
||||
assert.ok(running.verification.maxStrongRelativeError < 0.02);
|
||||
assert.ok(running.verification.maxAbsError < 0.01);
|
||||
});
|
||||
|
||||
test('实际DC可正取电/负回馈,q0有开关纹波且不篡改成理想功率公式', () => {
|
||||
const motoring = point(546.875, Ib), generating = point(546.875, -Ib), zero = point(546.875, 0);
|
||||
assert.ok(motoring.dc > 0); assert.ok(generating.dc < 0);
|
||||
assert.ok(zero.peakLine.amplitude > 0.05);
|
||||
assert.ok(Math.abs(zero.dc) > 1e-6); // held-duty tracking error is not overwritten.
|
||||
close(motoring.meanBusW, motor.Vdc * motoring.dc);
|
||||
close(generating.meanBusW, motor.Vdc * generating.dc);
|
||||
});
|
||||
|
||||
test('周期闭合/三相平衡与母线能量收支在理想模型内一致', () => {
|
||||
for (const c of [point(0, 49.04), point(312.5, Ib), point(546.875, -Ib), point(546.875, 0)]) {
|
||||
assert.ok(c.closure < 1e-9); assert.ok(c.balanceError < 1e-9);
|
||||
assert.ok(Math.abs(c.energyResidual) < 1e-8 + Math.abs(c.meanBusW) * 1e-9);
|
||||
close(c.meanBusW, c.copperW + c.electromagneticW, 1e-9);
|
||||
assert.ok(c.peakPhase > 0); assert.ok(c.phaseRms.every(x => x >= 0 && Number.isFinite(x)));
|
||||
}
|
||||
});
|
||||
|
||||
test('反向转速/转矩并将电角移π只交换相序,同工况母线复频谱一致', () => {
|
||||
const forward = point(312.5, Ib, { angle: 0.2 });
|
||||
const reverse = point(-312.5, -Ib, { angle: Math.PI - 0.2 });
|
||||
close(reverse.dc, forward.dc, 1e-9);
|
||||
assert.equal(reverse.freq.length, forward.freq.length);
|
||||
for (let i = 0; i < forward.freq.length; i++) {
|
||||
assert.equal(reverse.freq[i], forward.freq[i]);
|
||||
close(reverse.re[i], forward.re[i], 1e-7, 1e-8); close(reverse.im[i], forward.im[i], 1e-7, 1e-8);
|
||||
}
|
||||
});
|
||||
|
||||
test('精确开关边沿复积分校核采样峰值与相位,锁转用精确谱而非冻结相电流', () => {
|
||||
const c = point(312.5, Ib, { angle: 0.13 });
|
||||
const indices = Array.from({ length: c.freq.length }, (_, i) => i)
|
||||
.sort((a, b) => Math.hypot(c.re[b], c.im[b]) - Math.hypot(c.re[a], c.im[a])).slice(0, 12);
|
||||
const ex = exactSpectrum(motor, { fe: c.fe, iqPeak: Ib, angle: c.angle }, [0, ...indices.map(i => c.freq[i])]);
|
||||
close(ex.re[0], c.dc, 1e-9); close(ex.im[0], 0);
|
||||
for (let j = 0; j < indices.length; j++) {
|
||||
const i = indices[j], error = Math.hypot(c.re[i] - ex.re[j + 1], c.im[i] - ex.im[j + 1]);
|
||||
assert.ok(error < 0.01); assert.ok(error / Math.hypot(ex.re[j + 1], ex.im[j + 1]) < 0.03);
|
||||
}
|
||||
const locked = point(0, 49.04), lockedEx = exactSpectrum(motor, { fe: 0, iqPeak: 49.04 }, locked.freq);
|
||||
for (let i = 0; i < locked.freq.length; i++) { close(locked.re[i], lockedEx.re[i]); close(locked.im[i], lockedEx.im[i]); }
|
||||
});
|
||||
|
||||
test('提高spp的主谱线与精确积分收敛检查只声明数值误差', () => {
|
||||
const low = point(312.5, Ib, { samplesPerPwm: 64, verifyLines: 8 });
|
||||
const high = point(312.5, Ib, { samplesPerPwm: 256, verifyLines: 8 });
|
||||
assert.ok(high.verification.maxAbsError < low.verification.maxAbsError);
|
||||
close(high.peakLine.amplitude, point(312.5, Ib).peakLine.amplitude, 0.002);
|
||||
assert.ok(high.verification.scope.includes('不验证电机参数或硬件精度'));
|
||||
});
|
||||
|
||||
test('SVPWM/SPWM均支持中心PWM,SPWM改变波形但仍满足能量/平衡', () => {
|
||||
const c = point(312.5, Ib, { pwm: 'spwm', verifyLines: 4 });
|
||||
assert.equal(c.pwm, 'spwm'); assert.ok(c.modulationRatio < 1);
|
||||
assert.ok(Math.abs(c.energyResidual) < 1e-8); assert.ok(c.balanceError < 1e-9);
|
||||
assert.ok(c.verification.maxStrongRelativeError < 0.03);
|
||||
assert.notEqual(c.peakLine.amplitude, point(312.5, Ib).peakLine.amplitude);
|
||||
});
|
||||
|
||||
test('有限scan保留两组独立工况与signed q,锁转不伪扫转速;功率按实际DC过滤', () => {
|
||||
const options = { nSpeed: 2, nCurrent: 1, nAngle: 3, bands: 3, maxCycles: 128, samplesPerPwm: 64 };
|
||||
const result = scan(motor, options);
|
||||
assert.ok(result.rated.cases.length > 0 && result.locked.cases.length > 0);
|
||||
assert.ok(result.rated.cases.some(c => c.q === -1)); assert.ok(result.rated.cases.some(c => c.q === 0));
|
||||
assert.ok(result.rated.cases.some(c => c.q === 1));
|
||||
assert.ok(result.locked.cases.every(c => c.rpm === 0));
|
||||
assert.ok(result.locked.cases.some(c => c.iqPeak === 49.04));
|
||||
assert.ok(result.locked.cases.every(c => c.angle >= 0 && c.angle < Math.PI / 3));
|
||||
assert.equal(result.grid.lineAmplitudeThreshold, 0); assert.equal(result.grid.runningAngles, 1);
|
||||
assert.ok(result.scope.includes('不是连续域全局证明')); assert.ok(result.scope.includes('未扫描点'));
|
||||
const limited = scan(motor, { ...options, maxBusW: 50 });
|
||||
assert.ok(limited.skippedPower > 0);
|
||||
assert.ok([...limited.rated.cases, ...limited.locked.cases].every(c => Math.abs(motor.Vdc * c.dc) <= 50 * (1 + 1e-9)));
|
||||
const rpmLimited = scan(motor, { ...options, maxRpm: 100 });
|
||||
assert.ok(rpmLimited.rated.cases.every(c => c.rpm <= 100));
|
||||
});
|
||||
|
||||
test('非法输入、超调制和不支持公共周期拒绝而非偷偷夹限或epsilon替代', () => {
|
||||
for (const key of Object.keys(engine.defaults)) for (const value of [0, -1, NaN, Infinity, '1', null]) rejects(() => normalize({ [key]: value }));
|
||||
for (const options of [{ pwm: 'SVPWM' }, { bands: 11 }, { nSpeed: 0 }, { nCurrent: 0 },
|
||||
{ samplesPerPwm: 100 }, { maxCycles: 100 }, { maxBusW: -1 }, { maxRpm: -1 }, { phaseRms: 0 }, { stallPeak: 0 }]) rejects(() => normalize({}, options));
|
||||
rejects(() => caseSpectrum(motor, { fe: 100, iqPeak: Ib }));
|
||||
rejects(() => caseSpectrum(motor, { fe: 0, iqPeak: 1000 }));
|
||||
rejects(() => exactSpectrum(motor, { fe: 0, iqPeak: 1 }, [-1]));
|
||||
rejects(() => exactSpectrum(motor, { fe: 0, iqPeak: 1 }, new Array(257).fill(1)));
|
||||
});
|
||||
|
||||
async function asyncTests() {
|
||||
const options = { nSpeed: 1, nCurrent: 1, nAngle: 1, bands: 1, maxCycles: 64, samplesPerPwm: 64 };
|
||||
const sync = scan(motor, options); let progress = 0;
|
||||
const async = await scanAsync(motor, options, { onProgress(p) { progress++; assert.ok(p.evaluated > 0); } });
|
||||
assert.equal(async.evaluated, sync.evaluated); assert.equal(async.rated.cases.length, sync.rated.cases.length);
|
||||
close(async.rated.peak.amplitude, sync.rated.peak.amplitude); assert.equal(progress, async.evaluated);
|
||||
let count = 0;
|
||||
const cancelled = await scanAsync(motor, options, { shouldCancel: () => count >= 2, onProgress() { count++; } });
|
||||
assert.equal(cancelled.cancelled, true); assert.equal(count, 2);
|
||||
assert.equal(cancelled.rated.cases.length, 0);
|
||||
passed++; console.log('✓ async逐工况让出、进度与取消,结果不拼合半成品');
|
||||
console.log(`\n${passed} 项电机母线模型测试全部通过。`);
|
||||
}
|
||||
asyncTests().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,176 @@
|
||||
'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; });
|
||||
@@ -0,0 +1,221 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const core = require('../src/buck-calculator-engine.js');
|
||||
const supply = require('../src/motor-bus-supply.js');
|
||||
const TAU = 2 * Math.PI;
|
||||
function near(actual, expected, tolerance = 1e-10) {
|
||||
assert.ok(Math.abs(actual - expected) <= tolerance * Math.max(1, Math.abs(expected)), `${actual} != ${expected}`);
|
||||
}
|
||||
function current(re = [2], im = re.map(() => 0), extra = {}) {
|
||||
const f0 = extra.f0 === undefined ? 100 : extra.f0;
|
||||
const k = extra.k === undefined ? Uint32Array.from(re, (_, i) => i + 1) : Uint32Array.from(extra.k);
|
||||
return { dc: 0, f0, k, freq: Float64Array.from(k, n => n * f0),
|
||||
re: Float64Array.from(re), im: Float64Array.from(im), ...extra };
|
||||
}
|
||||
function densePp(input, branch, samples = 65536) {
|
||||
const lines = Array.from(input.re, (ir, i) => {
|
||||
const z = supply.impedance(branch, input.k[i] * input.f0);
|
||||
return { n: input.k[i], re: -(z.re * ir - z.im * input.im[i]), im: -(z.re * input.im[i] + z.im * ir) };
|
||||
});
|
||||
let min = Infinity, max = -Infinity;
|
||||
for (let j = 0; j < samples; j++) {
|
||||
let voltage = 0;
|
||||
for (const line of lines) {
|
||||
const angle = TAU * line.n * j / samples;
|
||||
voltage += line.re * Math.cos(angle) - line.im * Math.sin(angle);
|
||||
}
|
||||
min = Math.min(min, voltage); max = Math.max(max, voltage);
|
||||
}
|
||||
return max - min;
|
||||
}
|
||||
|
||||
test('端口阻抗与旧内核一致;C=0 和 DC 是有效边界', () => {
|
||||
for (const branch of [{ R: 0.05, Ls: 1e-6, C: 470e-6 }, { R: 0.2, Ls: 0, C: 1e-3 }]) {
|
||||
for (const f of [0, 10, 1000, 20000, 200000]) {
|
||||
const actual = supply.impedance(branch, f), expected = core.impedance(branch.R, branch.Ls, branch.C, TAU * f);
|
||||
near(actual.re, expected.re); near(actual.im, expected.im); near(actual.amp, expected.amp);
|
||||
}
|
||||
}
|
||||
const zeroC = supply.impedance({ R: 0.2, Ls: 3e-6, C: 0 }, 20000);
|
||||
near(zeroC.re, 0.2); near(zeroC.im, TAU * 20000 * 3e-6);
|
||||
const dc = supply.transfer({ R: 0.2, Ls: 3e-6, C: 1e-3 }, 0);
|
||||
assert.equal(dc.sourceRe, 1); assert.equal(dc.capRe, 0);
|
||||
});
|
||||
|
||||
test('支路传递等于解析 H;电容吸收方向 H−1;阻抗负号保持', () => {
|
||||
const branch = { R: 0.05, Ls: 1e-6, C: 470e-6 };
|
||||
for (const f of [1, 100, 5000, 200000]) {
|
||||
const w = TAU * f, a = 1 - w * w * branch.Ls * branch.C, b = w * branch.R * branch.C;
|
||||
const H = supply.transfer(branch, f), den = a * a + b * b;
|
||||
near(H.sourceRe, a / den); near(H.sourceIm, -b / den);
|
||||
near(H.capRe, H.sourceRe - 1); near(H.capIm, H.sourceIm);
|
||||
}
|
||||
const result = supply.pointMetrics(current([2]), { R: 0.5, Ls: 0, C: 0 }, { waveform: true });
|
||||
near(result.wave.voltage[0], -1); // I=+2cos,纯R电压−1cos。
|
||||
});
|
||||
|
||||
test('单正弦 pp=2|Z I|,峰值相量仅分半,不再双倍', () => {
|
||||
const input = current([3], [4]);
|
||||
const branch = { R: 0.2, Ls: 2e-6, C: 1000e-6 };
|
||||
const result = supply.pointMetrics(input, branch, { waveform: true });
|
||||
const exact = 10 * supply.impedance(branch, 100).amp;
|
||||
assert.ok(result.ppLower <= exact + 1e-12);
|
||||
assert.ok(result.ppUpper >= exact - 1e-12);
|
||||
near(result.ppSample, densePp(input, branch, result.M), 1e-12);
|
||||
assert.ok(result.fftImagMax < 1e-12);
|
||||
near(result.wave.time.at(-1), 0.01); near(result.wave.voltage[0], result.wave.voltage.at(-1));
|
||||
assert.equal(result.scope, 'finite-band'); assert.equal(result.tailKnown, false);
|
||||
assert.equal(result.totalPpUpper, null); assert.equal(result.rmsTruncated, true);
|
||||
});
|
||||
|
||||
test('有符号再生/静止 DC:source含dc²,cap不含,纹波不加DC', () => {
|
||||
const result = supply.pointMetrics(current([], [], { dc: -7, rpm: 0, angle: 0 }), { R: 0.1, Ls: 0, C: 0 });
|
||||
near(result.sourceRms, 7); near(result.demandRms, 7); assert.equal(result.capRms, 0);
|
||||
near(result.dcDrop, -0.7); near(result.ppSample, 0); near(result.ppUpper, 0);
|
||||
assert.equal(result.lineCount, 0);
|
||||
});
|
||||
|
||||
test('有限频带 RMS 与分支解析相量及 Parseval 一致', () => {
|
||||
const input = current([3, -0.4, 1.2], [4, 1, -0.7], { dc: -2.3 });
|
||||
const branch = { R: 0.1, Ls: 4e-6, C: 330e-6 };
|
||||
let srcSq = input.dc ** 2, capSq = 0, demandSq = input.dc ** 2;
|
||||
for (let i = 0; i < input.re.length; i++) {
|
||||
const H = supply.transfer(branch, input.freq[i]);
|
||||
const ampSq = input.re[i] ** 2 + input.im[i] ** 2;
|
||||
srcSq += (H.sourceRe ** 2 + H.sourceIm ** 2) * ampSq / 2;
|
||||
capSq += (H.capRe ** 2 + H.capIm ** 2) * ampSq / 2;
|
||||
demandSq += ampSq / 2;
|
||||
}
|
||||
const result = supply.pointMetrics(input, branch);
|
||||
near(result.sourceRms, Math.sqrt(srcSq)); near(result.capRms, Math.sqrt(capSq)); near(result.demandRms, Math.sqrt(demandSq));
|
||||
assert.equal('wave' in result, false);
|
||||
});
|
||||
|
||||
test('保峰谷的显示采样与细网格峰峰值一致', () => {
|
||||
const input = current([1.5, -0.3, 0.2], [0.7, 0.8, 0.4], { k: [1, 159, 211], f0: 10 });
|
||||
const result = supply.pointMetrics(input, { R: 0.1, Ls: 1e-6, C: 2e-6 }, { waveform: 'extrema', wavePoints: 26 });
|
||||
const {time, voltage, period, extremaPreserved} = result.wave;
|
||||
assert.ok(extremaPreserved && time.length <= 26);
|
||||
assert.equal(time[0], 0); assert.equal(time.at(-1), period);
|
||||
for (let i = 1; i < time.length; i++) assert.ok(time[i] >= time[i-1]);
|
||||
near(Math.max(...voltage) - Math.min(...voltage), result.ppSample);
|
||||
near(voltage[0], voltage.at(-1));
|
||||
});
|
||||
|
||||
test('同工况相位完整保留:不能把幅值三角和或跨工况包络当波形', () => {
|
||||
const branch = { R: 1, Ls: 0, C: 0 };
|
||||
const a = current([1, 0.5], [0, 0]);
|
||||
const b = current([1, 0], [0, 0.5]);
|
||||
const ra = supply.pointMetrics(a, branch), rb = supply.pointMetrics(b, branch);
|
||||
near(ra.ppSample, 2.25, 0.01);
|
||||
assert.ok(Math.abs(ra.ppSample - rb.ppSample) > 0.2);
|
||||
near(ra.demandRms, rb.demandRms);
|
||||
assert.ok(ra.ppSample < 2 * (1 + 0.5));
|
||||
const scan = supply.evaluate([a, b], branch);
|
||||
near(scan.maxPpSample, Math.max(ra.ppSample, rb.ppSample));
|
||||
});
|
||||
|
||||
test('稀疏高次 k 按原频率放入 IFFT,有限网格误差包含密网格极值', () => {
|
||||
const input = current([1, -0.8, 0.3], [0.7, 0.4, -0.1], { k: Uint32Array.from([1, 7, 19]), f0: 125 });
|
||||
const branch = { R: 0.13, Ls: 6e-6, C: 47e-6 };
|
||||
const coarse = supply.pointMetrics(input, branch), fine = supply.pointMetrics(input, branch, { gridFactor: 256 });
|
||||
assert.equal(coarse.maxK, 19); assert.equal(coarse.maxHz, 2375);
|
||||
assert.ok(coarse.ppLower <= fine.ppSample + 1e-12);
|
||||
assert.ok(coarse.ppUpper >= fine.ppSample - 1e-12);
|
||||
near(fine.ppSample, densePp(input, branch, fine.M), 1e-11);
|
||||
});
|
||||
|
||||
test('C0 感性源只给有限频带结果;供电RMS=需求RMS,电容RMS=0', () => {
|
||||
const input = current([3, 2], [1, -0.5], { dc: 4 });
|
||||
const result = supply.pointMetrics(input, { R: 0.05, Ls: 30e-6, C: 0 }, { target: 1e9 });
|
||||
near(result.sourceRms, result.demandRms); assert.equal(result.capRms, 0);
|
||||
assert.equal(result.c0Inductive, true); assert.match(result.notice, /尖峰/);
|
||||
assert.equal(result.finiteBandStatus, 'within-target');
|
||||
assert.equal(result.allBandwidthStatus, 'unknown'); assert.equal(result.totalPpUpper, null);
|
||||
assert.equal('pass' in result, false);
|
||||
});
|
||||
|
||||
test('evaluate 极值分别跨工况汇总、最坏工况轻量且不相位拼接', () => {
|
||||
const cases = [current([1], [0], { rpm: 10, iqPeak: 2, dc: 8, angle: 0 }),
|
||||
current([4], [0], { rpm: 20, iqPeak: -4, dc: -2, angle: 0.2 })];
|
||||
const branch = { R: 0.1, Ls: 0, C: 0 };
|
||||
const result = supply.evalCandidate(cases, branch, 1, { waveform: true });
|
||||
assert.equal(result.worstIndex, 1); assert.equal(result.worstCase.rpm, 20);
|
||||
assert.equal(result.worstSourceIndex, 0); near(result.maxAbsDcDropV, 0.8);
|
||||
near(result.maxPpSample, Math.max(...result.results.map(r => r.ppSample)));
|
||||
near(result.maxPpLower, Math.max(...result.results.map(r => r.ppLower)));
|
||||
near(result.maxPpUpper, Math.max(...result.results.map(r => r.ppUpper)));
|
||||
near(result.maxSourceRms, Math.max(...result.results.map(r => r.sourceRms)));
|
||||
near(result.maxCapRms, 0);
|
||||
assert.equal(result.finiteBandStatus, 'within-target');
|
||||
assert.equal('re' in result.worstCase, false); assert.equal('im' in result.worstCase, false);
|
||||
assert.equal('wave' in result.results[0], false); assert.ok(result.results[1].wave);
|
||||
assert.equal(result.worstPoint, result.results[1]);
|
||||
});
|
||||
|
||||
test('每次 evaluate 读取最新工况数组,不复用旧谱/旧 DC', () => {
|
||||
const input = current([1], [0]), branch = { R: 1, Ls: 0, C: 0 };
|
||||
const old = supply.evaluate([input], branch);
|
||||
input.re[0] = 4; input.dc = -3;
|
||||
const fresh = supply.evaluate([input], branch);
|
||||
near(old.maxPpSample, 2); near(fresh.maxPpSample, 8);
|
||||
near(fresh.maxSourceRms, Math.sqrt(17)); near(fresh.maxAbsDcDropV, 3);
|
||||
});
|
||||
|
||||
test('目标单位V,有限频带比较保留 uncertain;空扫描不是通过', () => {
|
||||
const input = current(), branch = { R: 1, Ls: 0, C: 0 };
|
||||
assert.equal(supply.evalCandidate(input, branch, 5).finiteBandStatus, 'within-target');
|
||||
assert.equal(supply.evalCandidate(input, branch, 1).finiteBandStatus, 'exceeds-target');
|
||||
assert.equal(supply.evalCandidate(input, branch, 4).finiteBandStatus, 'uncertain');
|
||||
const empty = supply.evaluate([], branch, { target: 1 });
|
||||
assert.equal(empty.finiteBandStatus, 'not-evaluated'); assert.equal(empty.maxPpSample, null);
|
||||
assert.equal(empty.maxPpUpper, null); assert.equal(empty.worstCase, null);
|
||||
});
|
||||
|
||||
test('严格拒绝非有限值、不共周期谱、重复k及超大网格', () => {
|
||||
const input = current(), branch = { R: 0.1, Ls: 0, C: 0 };
|
||||
for (const candidate of [{ ...branch, R: 0 }, { ...branch, Ls: -1 }, { ...branch, C: NaN }]) {
|
||||
assert.throws(() => supply.pointMetrics(input, candidate), /必须|不能/);
|
||||
}
|
||||
assert.throws(() => supply.impedance(branch, -1), /不能/);
|
||||
assert.throws(() => supply.pointMetrics({ ...input, re: [Infinity] }, branch), /有限/);
|
||||
assert.throws(() => supply.pointMetrics({ ...input, freq: [101] }, branch), /k\*f0/);
|
||||
assert.throws(() => supply.pointMetrics(current([1, 1], [0, 0], { k: [1, 1] }), branch), /严格递增/);
|
||||
assert.throws(() => supply.pointMetrics({ ...input, duration: 1 }, branch), /不一致/);
|
||||
assert.throws(() => supply.pointMetrics(input, branch, { gridFactor: 4 }), /小于 8/);
|
||||
assert.throws(() => supply.pointMetrics(input, branch, { gridFactor: 1e9 }), /网格过大/);
|
||||
});
|
||||
|
||||
test('真实电机 rotating/locked/q0 工况接口一致,C0 Parseval 与内核 bandRms 对齐', () => {
|
||||
const motor = require('../src/motor-bus-engine.js');
|
||||
const points = [motor.caseSpectrum({}, { fe: 312.5, iqPeak: Math.SQRT2 * 13.3 }),
|
||||
motor.caseSpectrum({}, { fe: 312.5, iqPeak: -Math.SQRT2 * 13.3 }),
|
||||
motor.caseSpectrum({}, { fe: 312.5, iqPeak: 0 }),
|
||||
motor.caseSpectrum({}, { fe: 0, iqPeak: 49.04, angle: 0 })];
|
||||
const result = supply.evaluate(points, { R: 0.05, Ls: 1e-6, C: 0 }, { waveform: true });
|
||||
assert.equal(result.caseCount, 4);
|
||||
assert.ok(points[1].dc < 0); assert.ok(points[2].bandRms > 0);
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
const expected = Math.hypot(points[i].dc, points[i].bandRms);
|
||||
near(result.results[i].sourceRms, expected, 1e-11);
|
||||
near(result.results[i].demandRms, expected, 1e-11);
|
||||
assert.equal(result.results[i].capRms, 0);
|
||||
near(result.results[i].period, points[i].duration);
|
||||
}
|
||||
const withCap = supply.evaluate(points, { R: 0.05, Ls: 1e-6, C: 1000e-6 }, { target: 0.12 });
|
||||
assert.ok(withCap.maxPpSample > 0); assert.ok(withCap.maxCapRms > 0);
|
||||
assert.equal(withCap.allBandwidthStatus, 'unknown');
|
||||
});
|
||||
|
||||
test('UMD 浏览器全局及别名可用', () => {
|
||||
const context = { BuckRLC: core };
|
||||
vm.runInNewContext(fs.readFileSync(require.resolve('../src/motor-bus-supply.js'), 'utf8'), context);
|
||||
assert.equal(typeof context.MotorBusSupply.evaluate, 'function');
|
||||
assert.equal(context.MotorBusSupply.z, context.MotorBusSupply.impedance);
|
||||
assert.equal(context.MotorBusSupply.H, context.MotorBusSupply.transfer);
|
||||
const result = context.MotorBusSupply.pointMetrics(current(), { R: 1, Ls: 0, C: 0 });
|
||||
near(result.ppSample, 4);
|
||||
});
|
||||
Reference in New Issue
Block a user