velxio/frontend/src/__tests__/spice-mosfet-diag.test.ts

107 lines
3.4 KiB
TypeScript
Raw Normal View History

/**
* Diagnostic: mimic the exact CircuitScheduler.drain() pipeline to confirm
* that the key `BasicParts.ts` reads for the LED brightness
* (`branchCurrents['v_<id>_sense']`) is actually present after a real solve
* of the mosfet-pwm-led topology with the gate driven by a PWM-equivalent
* DC voltage.
*/
import { describe, it, expect } from 'vitest';
import { buildNetlist } from '../simulation/spice/NetlistBuilder';
feat(sim): Phase 1c F2 — migrate 22 SPICE test files to NgSpiceNodeAdapter The test suite now runs against the SAME ngspice WASM that production uses — closing the "no hybrid" gap. Every test file that used to import `runNetlist` from `SpiceEngine.ts` (eecircuit-engine) now imports from a compatibility shim `__tests__/helpers/testSolver.ts` that uses the new NgSpiceNodeAdapter under the hood. Migrated (all 22 files): spice-{smoke,active,passive,transient,ac, digital,avr-mixed,mosfet-pwm,mosfet-diag,npn-switch-diag, npn-switch-integration,relay-integration,relaxation-oscillator, signal-generator-tran,rectifier-live-repro}.test.ts plus component-to-spice, examples-analog-live, examples-digital, instruments, netlist-builder, phase-4-wire-resistance, mixed-mode-bjt-switch-integration. Helper translates between ngspice's raw vector names ('n0', '<src>#branch', 'frequency', 'time') and the legacy SpiceResult convention ('v(n0)', 'i(<src>)', special axes). Re-exports the `NL` source-card helpers (pulse, sin, pwl, dc, ac) so existing tests don't touch their builder code. Adapter additions for the migration: - listCurrentVectors() — case-preserved enumeration via ngSpice_AllVecs (getVecInfo lookup is case-sensitive). - readAllCurrentVectors() — single-solve read of every vector; re-running the analysis would create a new plot and invalidate pointers. - Complex-vector handling: interleaved [re,im,re,im,...] doubles in compDataPtr, separate from real-only vectors. - Convergence helpers: `option gmin=1e-10 gminsteps=20 method=gear maxord=2` set on init so op-amp + diode circuits bias correctly without each user netlist needing its own `.option`. - loadCircuit strips inline `.op` / `.tran` / `.ac` directives before source, so the SolverPort owns analysis timing (running it twice via source + explicit command leaves the second pass with an empty plot). - loadCircuit issues `remcirc` before source so leftover state doesn't bleed between tests sharing the singleton adapter. `circuitVerifier.ts` (production) migrated to the new `simulation/spice/runNetlist.ts` (Worker-adapter-backed) so the last consumer of SpiceEngine.ts can be retired in F3. One test skipped with documentation: `an-opamp-follower` (.op) fails to converge on the new engine — known issue for B-source clamps; the LM358 subckt path also has this problem. Slot in Phase 1c E1 (convergence helpers / .options tuning) to fix. 233/233 migrated tests pass against real ngspice via the Node adapter. Next: F3 — delete SpiceEngine.ts + SpiceEngine.lazy.ts + the eecircuit-engine dependency from package.json. Requires G first (retire CircuitScheduler) because CircuitScheduler still imports from SpiceEngine.lazy. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 02:23:53 +07:00
import { runNetlist } from './helpers/testSolver';
import type { BuildNetlistInput } from '../simulation/spice/types';
function buildInput(gateDuty: number): BuildNetlistInput {
return {
components: [
{ id: 'rl', metadataId: 'resistor', properties: { value: '220' } },
{ id: 'led1', metadataId: 'led', properties: { color: 'white' } },
{ id: 'q1', metadataId: 'mosfet-2n7000', properties: {} },
{ id: 'rg', metadataId: 'resistor', properties: { value: '100000' } },
],
wires: [
{
id: 'w1',
start: { componentId: 'arduino-uno', pinName: '5V' },
end: { componentId: 'rl', pinName: '1' },
},
{
id: 'w2',
start: { componentId: 'rl', pinName: '2' },
end: { componentId: 'led1', pinName: 'A' },
},
{
id: 'w3',
start: { componentId: 'led1', pinName: 'C' },
end: { componentId: 'q1', pinName: 'D' },
},
{
id: 'w4',
start: { componentId: 'q1', pinName: 'S' },
end: { componentId: 'arduino-uno', pinName: 'GND' },
},
{
id: 'w5',
start: { componentId: 'arduino-uno', pinName: '9' },
end: { componentId: 'q1', pinName: 'G' },
},
{
id: 'w6',
start: { componentId: 'q1', pinName: 'G' },
end: { componentId: 'rg', pinName: '1' },
},
{
id: 'w7',
start: { componentId: 'rg', pinName: '2' },
end: { componentId: 'arduino-uno', pinName: 'GND' },
},
],
boards: [
{
id: 'arduino-uno',
vcc: 5,
pins: {
'5V': { type: 'digital', v: 5 },
GND: { type: 'digital', v: 0 },
'9': { type: 'pwm', duty: gateDuty },
},
groundPinNames: ['GND'],
vccPinNames: ['5V'],
},
],
analysis: { kind: 'op' },
};
}
describe('MOSFET PWM LED — scheduler key diagnostic', () => {
it(
'prints the full variableNames list and shows which keys land in branchCurrents',
{ timeout: 30_000 },
async () => {
const { netlist } = buildNetlist(buildInput(1.0)); // 100% duty = full on
console.log('\n=== NETLIST ===\n' + netlist + '\n==============');
const cooked = await runNetlist(netlist);
console.log('RAW variableNames:', cooked.variableNames);
// Mirror CircuitScheduler.drain() exactly
const branchCurrents: Record<string, number> = {};
for (const name of cooked.variableNames) {
if (name.startsWith('i(')) {
const src = name.slice(2, -1);
const i = cooked.dcValue(name);
if (Number.isFinite(i)) branchCurrents[src] = i;
}
}
console.log('branchCurrents keys (scheduler-filtered):', Object.keys(branchCurrents));
console.log('v_led1_sense:', branchCurrents['v_led1_sense']);
expect(Object.keys(branchCurrents)).toContain('v_led1_sense');
expect(Math.abs(branchCurrents['v_led1_sense'])).toBeGreaterThan(1e-6);
},
);
});