'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} 项敏感度内核测试全部通过。`);