feat: electrical simulation via ngspice-WASM (eecircuit-engine)
Adds full SPICE-accurate electrical simulation to Velxio, behind a lazy-
loaded ⚡ toolbar toggle. Arduino / ESP32 / RP2040 sketches now co-simulate
with real analog behaviour: correct voltages on wires, real I–V curves on
LEDs, working potentiometers, NTC thermistors read by analogRead(), PWM
driving RC filters, transistors, op-amps, diodes, MOSFETs, etc.
Engine: eecircuit-engine (ngspice compiled to WebAssembly). Main bundle
stays at 2.4 MB; the 20 MB SPICE chunk only loads when the user activates
electrical mode. Disabled at build time via VITE_ELECTRICAL_SIM=false.
Frontend additions:
- simulation/spice/: SpiceEngine wrapper + lazy entry, NetlistBuilder with
UnionFind over wires, componentToSpice mapping (24 metadataIds incl.
real part numbers: 2N2222, 2N3055, BC547, IRF540, 2N7000, 1N4148,
1N4007, 1N4733, LEDs, NTC, op-amp ideal), CircuitScheduler with
debounced coalescing, AVRSpiceBridge for quasi-static co-simulation.
- store/useElectricalStore: Zustand slice, feature-flag aware.
- components/analog-ui/: ⚡ toolbar toggle + SVG voltage overlay.
- components/components-instruments/: Voltmeter, Ammeter probes.
- 62 tests (spice-*, netlist-builder, component-to-spice, instruments).
Sandbox (test/test_circuit/): 47-test validation sandbox that proved
the approach (hand-rolled MNA baseline + ngspice pipeline) before
porting to the app. Kept as reference.
Docs: docs/wiki/circuit-emulation-*.md (13 engineering pages covering
architecture, solvers, components, AVR bridge, gotchas, performance,
integration plan, API reference, appendix) + electrical-simulation-
user-guide.md (end-user facing).
Reference plan: test/test_circuit/plan/phase_8_velxio_implementation.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 19:11:54 +07:00
|
|
|
|
import { describe, it, expect } from 'vitest';
|
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, type ComplexNumber } from './helpers/testSolver';
|
feat: electrical simulation via ngspice-WASM (eecircuit-engine)
Adds full SPICE-accurate electrical simulation to Velxio, behind a lazy-
loaded ⚡ toolbar toggle. Arduino / ESP32 / RP2040 sketches now co-simulate
with real analog behaviour: correct voltages on wires, real I–V curves on
LEDs, working potentiometers, NTC thermistors read by analogRead(), PWM
driving RC filters, transistors, op-amps, diodes, MOSFETs, etc.
Engine: eecircuit-engine (ngspice compiled to WebAssembly). Main bundle
stays at 2.4 MB; the 20 MB SPICE chunk only loads when the user activates
electrical mode. Disabled at build time via VITE_ELECTRICAL_SIM=false.
Frontend additions:
- simulation/spice/: SpiceEngine wrapper + lazy entry, NetlistBuilder with
UnionFind over wires, componentToSpice mapping (24 metadataIds incl.
real part numbers: 2N2222, 2N3055, BC547, IRF540, 2N7000, 1N4148,
1N4007, 1N4733, LEDs, NTC, op-amp ideal), CircuitScheduler with
debounced coalescing, AVRSpiceBridge for quasi-static co-simulation.
- store/useElectricalStore: Zustand slice, feature-flag aware.
- components/analog-ui/: ⚡ toolbar toggle + SVG voltage overlay.
- components/components-instruments/: Voltmeter, Ammeter probes.
- 62 tests (spice-*, netlist-builder, component-to-spice, instruments).
Sandbox (test/test_circuit/): 47-test validation sandbox that proved
the approach (hand-rolled MNA baseline + ngspice pipeline) before
porting to the app. Kept as reference.
Docs: docs/wiki/circuit-emulation-*.md (13 engineering pages covering
architecture, solvers, components, AVR bridge, gotchas, performance,
integration plan, API reference, appendix) + electrical-simulation-
user-guide.md (end-user facing).
Reference plan: test/test_circuit/plan/phase_8_velxio_implementation.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 19:11:54 +07:00
|
|
|
|
|
|
|
|
|
|
function magDB(c: ComplexNumber): number {
|
|
|
|
|
|
return 20 * Math.log10(Math.sqrt(c.real * c.real + c.img * c.img));
|
|
|
|
|
|
}
|
|
|
|
|
|
function phaseDeg(c: ComplexNumber): number {
|
|
|
|
|
|
return (Math.atan2(c.img, c.real) * 180) / Math.PI;
|
|
|
|
|
|
}
|
|
|
|
|
|
function re(v: number | ComplexNumber): number {
|
|
|
|
|
|
return typeof v === 'number' ? v : v.real;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
describe('ngspice — AC (small-signal) analysis', () => {
|
|
|
|
|
|
it('RC low-pass: −3 dB at f_c = 1/(2πRC)', { timeout: 30_000 }, async () => {
|
|
|
|
|
|
const netlist = `AC sweep RC low-pass
|
|
|
|
|
|
V1 in 0 AC 1
|
|
|
|
|
|
R1 in out 1k
|
|
|
|
|
|
C1 out 0 159.155n
|
|
|
|
|
|
.ac dec 20 10 1Meg
|
|
|
|
|
|
.end`;
|
|
|
|
|
|
const { vec } = await runNetlist(netlist);
|
|
|
|
|
|
const freq = vec('frequency');
|
|
|
|
|
|
const vout = vec('v(out)') as ComplexNumber[];
|
|
|
|
|
|
const mag = vout.map(magDB);
|
|
|
|
|
|
|
|
|
|
|
|
let f3db: number | null = null;
|
|
|
|
|
|
for (let i = 0; i < freq.length - 1; i++) {
|
|
|
|
|
|
if (mag[i] > -3 && mag[i + 1] <= -3) {
|
|
|
|
|
|
const a = mag[i];
|
|
|
|
|
|
const b = mag[i + 1];
|
|
|
|
|
|
const fa = re(freq[i]);
|
|
|
|
|
|
const fb = re(freq[i + 1]);
|
|
|
|
|
|
f3db = fa + ((-3 - a) / (b - a)) * (fb - fa);
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
expect(f3db).not.toBeNull();
|
|
|
|
|
|
expect(f3db!).toBeGreaterThan(900);
|
|
|
|
|
|
expect(f3db!).toBeLessThan(1100);
|
|
|
|
|
|
|
|
|
|
|
|
expect(mag[0]).toBeGreaterThan(-0.5);
|
|
|
|
|
|
|
|
|
|
|
|
// Phase at cutoff ≈ −45°
|
|
|
|
|
|
let fcIdx = 0;
|
|
|
|
|
|
for (let i = 0; i < freq.length; i++) {
|
|
|
|
|
|
if (re(freq[i]) >= 1000) {
|
|
|
|
|
|
fcIdx = i;
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
const ph = phaseDeg(vout[fcIdx]);
|
|
|
|
|
|
expect(ph).toBeLessThan(-40);
|
|
|
|
|
|
expect(ph).toBeGreaterThan(-50);
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
it('Parallel-tank RLC bandpass: peak at f₀ = 1/(2π√LC)', { timeout: 30_000 }, async () => {
|
|
|
|
|
|
const netlist = `RLC bandpass
|
|
|
|
|
|
V1 in 0 AC 1
|
|
|
|
|
|
R1 in out 1k
|
|
|
|
|
|
L1 out 0 1m
|
|
|
|
|
|
C1 out 0 1u
|
|
|
|
|
|
.ac dec 30 10 1Meg
|
|
|
|
|
|
.end`;
|
|
|
|
|
|
const { vec } = await runNetlist(netlist);
|
|
|
|
|
|
const freq = vec('frequency');
|
|
|
|
|
|
const vout = vec('v(out)') as ComplexNumber[];
|
|
|
|
|
|
const mag = vout.map(magDB);
|
|
|
|
|
|
|
|
|
|
|
|
let peakIdx = 0;
|
|
|
|
|
|
for (let i = 1; i < mag.length; i++) if (mag[i] > mag[peakIdx]) peakIdx = i;
|
|
|
|
|
|
const fpeak = re(freq[peakIdx]);
|
|
|
|
|
|
const expectedF0 = 1 / (2 * Math.PI * Math.sqrt(1e-3 * 1e-6));
|
|
|
|
|
|
expect(fpeak).toBeGreaterThan(expectedF0 * 0.8);
|
|
|
|
|
|
expect(fpeak).toBeLessThan(expectedF0 * 1.2);
|
|
|
|
|
|
expect(mag[peakIdx]).toBeGreaterThan(-1);
|
|
|
|
|
|
expect(mag[peakIdx]).toBeLessThan(0.01);
|
|
|
|
|
|
});
|
|
|
|
|
|
});
|