/kicad-happy:spicefrom kicad-happy
Automatically generates and runs SPICE testbenches for analog subcircuits detected from KiCad schematic analysis. Validates filter frequencies, divider ratios, opamp gains, LC resonance, and crystal load capacitance using ngspice, LTspice, or Xyce.
Ships in kicad-happy. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Automatically generates and runs SPICE testbenches for circuit subcircuits detected by the kicad skill's schematic analyzer. Supports ngspice, LTspice, and Xyce (auto-detected). Validates calculated values (filter frequencies, divider ratios, opamp gains) against actual simulation results and produces a structured report.
This skill inverts the typical simulation workflow: instead of requiring users to create simulation sources and configure analysis (which ~2.5% of KiCad users do), it generates targeted testbenches automatically from the analyzer's subcircuit detections.
| Skill | Purpose |
|---|---|
kicad | Schematic/PCB analysis — produces the analyzer JSON this skill consumes |
digikey | Parametric specs for behavioral models, datasheet downloads |
mouser | Parametric specs (secondary source), datasheet downloads |
lcsc | Parametric specs (no auth needed), datasheet downloads |
element14 | Parametric specs (international), datasheet downloads |
emc | EMC pre-compliance — uses this skill's simulator infrastructure for SPICE-enhanced PDN impedance and switching-harmonic analysis |
Handoff guidance: The kicad skill's analyze_schematic.py produces the analysis JSON with subcircuit detections in the flat findings[] array (filtered by detector field). This skill reads that JSON, generates SPICE testbenches for simulatable subcircuits, runs the detected simulator (ngspice/LTspice/Xyce), and produces a structured verification report. Always run the schematic analyzer first. During a design review, run simulation after the analyzer and before writing the final report — simulation results should appear as a verification section in the report. The emc skill reuses this skill's simulator backend for SPICE-enhanced PDN impedance and switching-harmonic checks — when ngspice is available, the EMC skill's --spice-enhanced flag activates these checks automatically.
sudo apt install ngspice (Linux) / brew install ngspice (macOS) / ngspice.sourceforge.io (Windows). Most common choice.--simulator ngspice|ltspice|xyce or SPICE_SIMULATOR env var.analyze_schematic.py --outputIf no simulator is installed, skip simulation gracefully and note it in the report. Do not treat a missing simulator as an error — it's an optional enhancement.
python3 <kicad-skill-path>/scripts/analyze_schematic.py design.kicad_sch --analysis-dir analysis/
Pass --analysis-dir analysis/ — the script auto-resolves schematic.json
from the manifest's current run, writes spice.json into the same run
folder, and parks intermediate .cir / .raw files in a new
spice_sim_* folder under <run>/spice_work/ by default.
# Recommended: auto-resolve schematic + write spice.json into the current run
python3 <skill-path>/scripts/simulate_subcircuits.py --analysis-dir analysis/
# Explicit form — positional or --schematic path
python3 <skill-path>/scripts/simulate_subcircuits.py analysis.json --output sim_report.json
# Simulate specific types only
python3 <skill-path>/scripts/simulate_subcircuits.py --analysis-dir analysis/ --types rc_filters,voltage_dividers
# Keep simulation files for debugging in a new spice_sim_* folder inside the directory (default: <run>/spice_work/ when --analysis-dir is set, else a temp dir removed when the run ends)
python3 <skill-path>/scripts/simulate_subcircuits.py --analysis-dir analysis/ --workdir ./spice_runs
# Increase timeout for complex circuits (default: 5s per subcircuit)
python3 <skill-path>/scripts/simulate_subcircuits.py --analysis-dir analysis/ --timeout 10
# Omit file paths from output (cleaner for reports)
python3 <skill-path>/scripts/simulate_subcircuits.py --analysis-dir analysis/ --compact
To run a complete user-supplied deck (PSpice is explicit-only; the deck is trusted input), see "External Decks and PSpice" in the repository's spice-integration.md.
When both schematic and PCB exist, low-pass RC filters can be simulated with the PCB trace resistance and via inductance of their output net:
# Analyze PCB with full trace segment detail
python3 <kicad-skill-path>/scripts/analyze_pcb.py design.kicad_pcb --full --output pcb.json
# Extract parasitic R/L/C from PCB geometry
python3 <skill-path>/scripts/extract_parasitics.py pcb.json --output parasitics.json
# Run simulation with PCB parasitics injected into testbenches
python3 <skill-path>/scripts/simulate_subcircuits.py analysis.json --parasitics parasitics.json --output sim_report.json
With --parasitics, low-pass RC-filter testbenches insert the PCB trace resistance and via inductance of the filter's output net (matched by its exact net name) between R and C. Other testbenches ignore the parasitics file, and extracted coupling capacitance and via resistance are not inserted. The report shows the simulated result with those elements in place; it does not compare against the ideal run.
When to use parasitic simulation: to see whether layout series R/L moves a low-pass RC filter. It does not model LC filters, op-amp feedback networks, RF matching or crosstalk; for typical designs the ideal simulation is sufficient.
Run N simulations per subcircuit with randomized component values within tolerance bands. Reports statistical distributions and sensitivity analysis — which component contributes most to output variation.
# Run 100 Monte Carlo trials per subcircuit
python3 <skill-path>/scripts/simulate_subcircuits.py analysis.json --monte-carlo 100 --output sim_report.json
# Use uniform distribution (conservative worst-case envelope) instead of Gaussian
python3 <skill-path>/scripts/simulate_subcircuits.py analysis.json --monte-carlo 100 --mc-distribution uniform
# Set random seed for reproducibility (default: 42)
python3 <skill-path>/scripts/simulate_subcircuits.py analysis.json --monte-carlo 100 --mc-seed 123
Tolerance sourcing: Tolerances are extracted from component value strings first (e.g., "680K 1%" → 1%, "22uF/6.3V/20%/X5R" → 20%). When not specified in the value string, defaults are used: resistors 5%, capacitors 10%, inductors 20%.
Output: Each simulation result gains a tolerance_analysis section with:
When to use Monte Carlo: Use it for feedback networks (regulator output accuracy), precision voltage dividers, RC/LC filters near spec limits, and any circuit where tolerance stacking could push behavior outside acceptable bounds. For N=100 at ~5-50ms per simulation, expect ~0.5-5s per subcircuit.
Read the JSON report and incorporate findings into the design review. See the "Interpreting Results" and "Presenting to Users" sections below.
The script selects subcircuits from the analyzer's findings[] array (grouped by detector type). Not every detection is simulatable — the script skips configurations that can't produce meaningful results (comparators, open-loop opamps, active oscillators).
| Detector | Analysis | What's Measured | Model Fidelity | Trustworthiness |
|---|---|---|---|---|
rc_filters | AC sweep | -3dB frequency, phase at fc | Exact (ideal passives) | High — mathematically exact |
lc_filters | AC sweep | Resonant frequency (status); Q factor, bandwidth of the assumed ESR | Near-exact (ideal L/C + assumed ESR) | High for resonance; Q is the bench's assumption |
voltage_dividers | DC operating point | Output voltage, error % | Exact (ideal passives) | High — unloaded |
feedback_networks | DC operating point | FB pin voltage, regulator Vout | Exact (ideal passives) | High — cross-refs power_regulators |
opamp_circuits | AC sweep | Gain, -3dB bandwidth | Per-part or ideal | High with behavioral model, medium with ideal |
crystal_circuits | AC sweep | Series and load resonance, pulling, Rm (info); calculated CL range | Approximate (generic BVD) | Medium |
transistor_circuits | DC sweep | Threshold voltage, on-state current (info: generic model's values; PNP VBE(on) and P-channel VGS(th) are negative; a diode-connected part, or a PNP/P-channel part whose collector/drain is on ground, is skipped) | Approximate (generic FET/BJT) | Low |
current_sense | DC operating point | Current at 50mV/100mV drop (info without an expected current) | Exact (ideal resistor) | High |
protection_devices | DC sweep | Diode presence, clamping onset | Approximate (generic diode) | Low |
decoupling_analysis | AC impedance | PDN impedance profile | Exact + ESR estimates | High for passives |
power_regulators | DC operating point | FB voltage vs the part's Vref at the rail's named voltage (info when Vref is not from the part, its table entry is a family prefix shorter than the part number or comes from a symbol whose value names another part, an arm is a pot/trimmer, the divider top is not on the output rail, or the rail name carries no voltage) | Exact (ideal passives) | High |
rf_matching | AC sweep | Impedance profile (info); L/pi/T networks with shunt elements are skipped | Exact (ideal L/C) | Low — series-chained bench |
bridge_circuits | DC sweep | Low-side turn-on threshold and on-state current (info: generic model's values) | Approximate (generic) | Low |
snubber_circuits | AC impedance | Snubber damping frequency and the R·C time constant (info; warn when the time constant is outside 1 ns–100 µs) | Exact (ideal R/C) | High |
rf_chains | Gain budget | Per-stage gain/loss estimate (info; warn outside -30..+40 dB) | Heuristic | Low — role-based |
bms_systems | DC operating point | Cell balance resistor validation | Exact | High |
inrush_analysis | Transient | Peak inrush current and the time it is first reached (info: on the assumed soft-start, not compared against a limit) | Approximate | Medium |
parse_value() couldn't extract R/C/L values, the detection is skipped{
"summary": {"total": 5, "pass": 3, "warn": 1, "fail": 0, "skip": 1, "info": 0},
"simulation_results": [
{
"subcircuit_type": "rc_filter",
"components": ["R5", "C3"],
"filter_type": "low-pass",
"status": "pass",
"expected": {"fc_hz": 15915, "type": "low-pass"},
"simulated": {"fc_hz": 15878, "phase_at_fc_deg": -45},
"delta": {"fc_error_pct": 0.23},
"cir_file": "/tmp/spice_sim_xxx/rc-filter_R5_C3.cir",
"log_file": "/tmp/spice_sim_xxx/rc-filter_R5_C3.log",
"elapsed_s": 0.004
}
],
"workdir": "/tmp/spice_sim_xxx",
"total_elapsed_s": 0.032,
"simulator": "ngspice"
}
Status values and what they mean:
| Status | Meaning | Action |
|---|---|---|
| pass / info | pass: measured and within tolerance of the check's criterion. info: measured, but the bench has no criterion (no expected value, or the part model is generic) | Report pass as confirmed; report info as a measurement, not a verification. |
| warn | Simulation shows something worth noting — small deviation, model limitation, or edge case | Report with context. Often the "warn" reflects a real but minor issue (e.g., slight gain error from ideal opamp model). |
| fail | Simulation contradicts the analyzer — wrong frequency, large gain error, unexpected behavior | Investigate. Could be a real design issue, a topology misdetection by the analyzer, or a testbench generation bug. Check the .cir file and log. |
| skip | Could not simulate — missing data, unsupported configuration, simulator error | Note in report. Check the note field for the reason. |
These simulations use ideal component models, so the simulation is mathematically exact. Any significant deviation (>1%) from the analyzer's calculated value indicates a bug in either:
In testing across real projects, passive simulations consistently show <0.3% error — essentially confirming the analyzer's math is correct. A "pass" here means the calculated cutoff frequency, resonant frequency, or divider ratio is accurate.
What these simulations do NOT tell you: Whether the real circuit behaves this way. The simulation uses ideal isolated subcircuits without loading from downstream stages, PCB parasitics, or temperature effects. A voltage divider that simulates perfectly at 1.65V may actually produce 1.62V when loaded by a high-impedance ADC input — but that loading effect is real circuit behavior, not an analyzer error.
For recognized parts (49 op-amps in the built-in table, more through distributor APIs), the skill uses a per-part behavioral model with the correct GBW, input offset, and output swing. For unrecognized parts, it falls back to the ideal model (Aol=1e6, GBW=10MHz).
The model_note field in the report indicates which model was used:
"LM358 behavioral (lookup:LM358, GBW=1.0MHz)" — per-part model, bandwidth results are accurate"ideal opamp (Aol=1e6, GBW~10MHz)" — fallback, bandwidth results are approximateWhen the behavioral model is used, the simulation correctly captures bandwidth limitations. An LM358 at gain=-100 shows bandwidth of ~10 kHz (correct for 1 MHz GBW), while the ideal model would misleadingly report ~100 kHz.
For opamps with behavioral models, gain-bandwidth limitation warnings are informational — they flag where the part's GBW constrains the circuit. These are valuable design insights, not simulation errors.
Crystal simulations measure series resonance on the crystal alone and load resonance with the load caps (summed per leg) in the C1 – crystal – C2 loop, and report the pulling as info: the generic Butterworth-Van Dyke model is built from the nominal frequency, not the specific crystal's data, so the bench has no pass criterion. They warn when the analyzer's calculated CL is outside 4-30 pF (catching missing or grossly wrong load capacitors) or a resonance was not measured (not found in the sweep, or an Rm read far from the model's showing the sweep did not resolve it).
Check the note field first. Common causes:
| Note | Cause | Fix |
|---|---|---|
| "could not measure -3dB frequency" | AC sweep range doesn't include the -3dB point | Check if the filter fc is very low (<0.1 Hz) or very high (>100 MHz) |
| "AC measurement failed" | Testbench topology error — the circuit doesn't converge | Check .cir file for floating nodes or missing connections |
| "Testbench generation failed: KeyError" | Analyzer detection is missing expected fields | Check analyzer JSON — the detection may be incomplete |
| "ngspice/ltspice/xyce failed: ..." | Simulator error | Check .log file for error messages |
When debugging, use --workdir to preserve simulation files (each run writes them into a new spice_sim_* folder inside it). The .cir file is a standard SPICE netlist that can be run manually (ngspice -n -b file.cir, or opened in LTspice/Xyce). The .log file contains simulator stdout/stderr.
When incorporating simulation results into a design review report, follow this pattern:
### RC Filter R5/C3 (fc=15.9kHz lowpass) -- Confirmed
Simulated fc=15.9kHz, <0.3% from calculated. Phase=-45 deg at fc as expected.
Keep passing results brief — they confirm what the analyzer already reported. Group them if there are many.
### Opamp U4A (inverting gain=-10)
Simulated gain=20.0dB at 1kHz, matching expected -10x. Bandwidth 98.8kHz
(ideal model). Note: LM358 GBW is ~1MHz, so actual bandwidth would be
~100kHz — verify signal frequency stays below 85kHz for <1dB gain error.
### RC Filter R12/C8 -- MISMATCH
Simulated fc=3.2kHz vs expected 15.9kHz (80% deviation). This likely indicates
the analyzer misidentified the filter topology — R12 may be serving a different
purpose (pull-up, not series filter element). Manually verify the circuit
around R12/C8 in the schematic.
### Crystal Y1 (32.768kHz) -- Not simulated
Active oscillator module — no external load caps to validate.
## Simulation Verification (4 pass, 1 warn, 0 fail, 1 skip)
Verified 5 subcircuits in 0.03s. All passive circuits confirmed.
One opamp result requires interpretation (see U4A above).
For detailed information about the behavioral models used, their accuracy envelopes, and known limitations, read references/simulation-models.md. Consult this reference when:
| Script | Purpose |
|---|---|
scripts/simulate_subcircuits.py | Main orchestrator — CLI entry point, reads JSON, generates testbenches, runs simulator, produces report |
scripts/spice_templates.py | Testbench generators per detector type — one function per detector name |
scripts/spice_models.py | Behavioral model definitions (ideal opamp, generic semiconductors), net sanitization, engineering notation formatting |
scripts/spice_results.py | Simulation output parsing and per-type evaluation with pass/warn/fail/info/skip logic |
scripts/spice_simulator.py | Simulator backends — ngspice, LTspice, Xyce auto-detection and batch execution |
scripts/spice_part_library.py | Lookup table of electrical specs for 103 op-amps, LDOs, comparators and references, plus 24 crystal-driver and 10 MOSFET entries |
scripts/spice_model_generator.py | Parameterized behavioral .subckt generation from specs dicts |
scripts/spice_model_cache.py | Project-local model cache in spice/models/ beside the schematic the analysis JSON names (file or inputs.source_files[0]); an analysis that names no source file, or a relative one not found from the current directory, caches under the run's workdir (--model-cache-dir to share one cache) |
scripts/spice_spec_fetcher.py | Queries distributor APIs (LCSC, DigiKey, element14, Mouser), structured datasheet extractions, and PDF regex for parametric specs |
scripts/extract_parasitics.py | Compute trace R, via L, coupling C from PCB analysis JSON |
When the analyzer detects an opamp with a recognized MPN (e.g., LM358, TL072, MCP6002), the skill uses a per-part behavioral model instead of the generic ideal opamp. The model captures the actual GBW, input offset, and output swing from the part's datasheet.
Model resolution cascade:
<project>/spice/models/, beside the schematic the analysis JSON names) — previously resolved modelsspice_specs record from <project>/datasheets/extracted/ (score ≥ 6 of 10). It reads the datasheets skill's cache and older hand-made caches; the typed lookup() facts are not used by this resolver.
This tier and the PDF tier run only when the analysis names its project.<project>/datasheets/, extracts via text pattern matching (needs pdftotext)--offline skips the distributor and datasheet sources: only the project cache, the built-in lookup table and the ideal fallback are used.
The model_note field in the report indicates which model was used: "LM358 behavioral (lookup:LM358, GBW=1.0MHz)" vs "ideal opamp (Aol=1e6, GBW~10MHz)".
Models are cached project-locally in a spice/ directory beside the schematic the analysis JSON names (file or inputs.source_files[0]), the same pattern as datasheets/. An analysis that names no source file, or a relative one not found from the current directory, caches under the run's workdir. This keeps models co-located with the design and handles board revisions and subprojects naturally.
Q_factor reflects that assumption (model_note) and never sets the status. Real inductor Q varies from 10 (power inductors) to 300+ (RF inductors). The resonant frequency is accurate regardless of Q.-12V, NEG15V, -3V3 or (-)5V, and a 4V5_N beside a 4V5_P is -4.5 V; a negative rail named without a voltage (VEE, V-, -VCC) is assumed at -VCC and the result's model_note says so. Single-supply designs are detected when only VCC is found (VEE defaults to 0V); their benches are biased at mid-supply, the stage's AC ground. A supply below the part model's minimum is never a pass: warn when the rails' voltages are in their net names, info when the supply was assumed. A bench whose output never moved (hundreds of dB down) is info with no gain error.spice_part_library.py.__unnamed_N. These are KiCad internal net names for unlabeled wires. They work correctly in simulation but make .cir files less readable.references/simulation-models.md (opens in a new tab)scripts/_core_path.py (opens in a new tab)scripts/extract_parasitics.py (opens in a new tab)scripts/run_external_deck.py (opens in a new tab)scripts/simulate_subcircuits.py (opens in a new tab)scripts/spice_model_cache.py (opens in a new tab)scripts/spice_model_generator.py (opens in a new tab)scripts/spice_models.py (opens in a new tab)scripts/spice_part_library.py (opens in a new tab)scripts/spice_results.py (opens in a new tab)scripts/spice_simulator.py (opens in a new tab)scripts/spice_spec_fetcher.py (opens in a new tab)scripts/spice_templates.py (opens in a new tab)scripts/spice_tolerance.py (opens in a new tab)scripts/test_spice_simulator.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub aklofas/kicad-happy --plugin kicad-happy11 skills in this plugin
/bomBOM (Bill of Materials) management for electronics projects — the workflow skill that coordinates DigiKey, Mouser, LCSC, element14, JLCPCB, PCBWay, and KiCad skills around a unified BOM lifecycle. Create, update, and maintain BOMs with part numbers, costs, quantities stored as KiCad symbol properties. ALWAYS trigger this skill for any task involving component sourcing, pricing, ordering, distributor searches, BOM export, or fabrication preparation — even if the user names a specific distributor or fab house (e.g. "search DigiKey for...", "generate JLCPCB BOM", "order from Mouser"). This skill analyzes the schematic for sourcing gaps, recommends which distributor/fab skills to call for each gap, and writes results back as symbol properties — the agent (or user) performs the actual searches via the called skills. Also trigger on phrases like "what parts do I need", "order components", "how much will this cost", "export for JLCPCB", "find parts for this board", "compare pricing", or "check stock"./datasheetsExtract structured specifications from electronic component datasheet PDFs — pinouts, electrical characteristics, peripherals, topology, and features. Cache extractions per project for consumption by schematic and PCB analyzers. Primary consumer infrastructure for `kicad`, `emc`, `spice`, and `thermal` analyzers. Use this skill whenever the user asks to extract, verify, or read specs from a component datasheet; when analyzers need verified IC knowledge (EN pin thresholds, PG presence, USB peripheral speed); or when a review mentions datasheet coverage, extraction quality, or per-MPN specifications. Also triggers on "extract this datasheet", "what are the specs for MPN X", "verify datasheet extraction", or "check pin functions for part Y"./digikeySearch DigiKey for electronic components and download datasheets — primary source for prototype orders and the preferred API method for fetching datasheets. Find parts by keyword or MPN, check pricing/stock, download datasheets via API, analyze specifications. Sync and maintain a local datasheets directory — extract components from schematics, download missing datasheets, keep them up to date. Also supports batch MPN-list seeding (`--mpn-list`) for bulk workflows without a KiCad project. Use when the user asks about electronic components, part specs, datasheets, pricing, stock, footprints, or needs to download a datasheet — even without mentioning "DigiKey". Also for "sync datasheets", "download datasheets for my board/project", or mentions a datasheets directory. DigiKey is the default distributor for prototyping. For BOM workflows, see the bom skill./element14Search Newark, Farnell, and element14 for electronic components — find parts by MPN or distributor part number, check pricing/stock, download datasheets, analyze specifications. One unified API covers all three storefronts (Newark for US, Farnell for UK/EU, element14 for APAC). Free API key, simple query-parameter auth, no OAuth. Datasheets download directly from farnell.com CDN with no bot protection. Sync and maintain a local datasheets directory for a KiCad project, or use batch MPN-list seeding (`--mpn-list`) for bulk workflows without a project. Use this skill when the user mentions Newark, Farnell, element14, needs parts from a non-US distributor, wants to compare pricing across regions, or needs datasheets from a source that doesn't require complex API auth. For package cross-reference tables and BOM workflow, see the `bom` skill./emcEMC pre-compliance risk analysis for KiCad PCB designs — 18 check categories, 44 rule IDs covering ground planes, decoupling, I/O filtering, switching harmonics, clock routing, differential pair skew, board edge radiation, PDN impedance, return paths, crosstalk, ESD protection, shielding, and magnetic leakage from switching inductors. Produces severity-ranked risk report with pre-compliance test plan. Supports FCC Part 15, CISPR 32, CISPR 25 (automotive), MIL-STD-461G. SPICE-enhanced when available. Use when the user asks about EMC, EMI, radiated/conducted emissions, FCC compliance, CE marking, CISPR, ground plane issues, decoupling strategy, clock routing EMC, switching noise, differential pair skew, or whether their board will pass EMC testing. Also for "will this pass FCC?", "check my EMC", "is my ground plane okay?", "check my decoupling", or "generate an EMC test plan"./jlcpcbJLCPCB PCB fabrication and assembly — BOM/CPL generation, basic vs extended parts, assembly constraints, design rules, ordering workflow. Use with KiCad for JLCPCB manufacturing. Use this skill when the user mentions JLCPCB, wants to order PCBs or assembled boards, needs prototype bare PCBs and stencils, wants to know JLCPCB design rules and capabilities, or is asking about PCB manufacturing costs or turnaround times. For gerber/CPL export, stencil ordering, and BOM management, see the `bom` skill.Other plugins' skills for the same job