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