'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} 项可视化内核测试全部通过。`);