[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ME00C2X05EHDMZ20XV3JP3":3,"skill-same:01M6ME00C2X05EHDMZ20XV3JP3":132},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":51,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M6ME00C2X05EHDMZ20XV3JP3","spice",null,"Run automatic SPICE simulations on subcircuits detected from KiCad schematic analysis — validates filter frequencies, divider ratios, opamp gains, LC resonance, and crystal load capacitance. Supports ngspice, LTspice, and Xyce (auto-detected). Generates testbenches, runs batch mode, produces structured pass\u002Fwarn\u002Ffail\u002Finfo report. Use when the user asks to simulate, verify, or validate any analog subcircuit — RC filters, LC filters, voltage dividers, opamp circuits, crystal oscillators. Also for \"simulate my circuit\", \"run spice\", \"verify with simulation\", \"check my filter cutoff\", \"does this divider give the right voltage\", \"what's the bandwidth of this opamp stage\". Consider suggesting simulation during design reviews when the schematic analyzer reports simulatable subcircuits and a SPICE simulator is available.","hashgraph-online\u002Fawesome-codex-plugins","hashgraph-online","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F160371962?v=4","01M6CNB6NRJVNNGN14TR01Q6D3","HOL (Hashgraph Online)","01M6JT1HSKKG9V68KQAQGBA7XP",1575,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002FSKILL.md",[],[5,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"simulation","Simulations","info","when","schematic","circuit","kicad","my","crystal","automatic","run","reports","filter","batch","analysis","filters","auto","design","mode","reviews","2026-11-10 10:12:30",false,"---\nname: spice\ndescription: >-\n  Run automatic SPICE simulations on subcircuits detected from KiCad schematic\n  analysis — validates filter frequencies, divider ratios, opamp gains, LC\n  resonance, and crystal load capacitance. Supports ngspice, LTspice, and Xyce\n  (auto-detected). Generates testbenches, runs batch mode, produces structured\n  pass\u002Fwarn\u002Ffail\u002Finfo report. Use when the user asks to simulate, verify, or\n  validate any analog subcircuit — RC filters, LC filters, voltage dividers,\n  opamp circuits, crystal oscillators. Also for \"simulate my circuit\", \"run\n  spice\", \"verify with simulation\", \"check my filter cutoff\", \"does this\n  divider give the right voltage\", \"what's the bandwidth of this opamp stage\".\n  Consider suggesting simulation during design reviews when the schematic\n  analyzer reports simulatable subcircuits and a SPICE simulator is available.\n---\n\n# SPICE Simulation Skill\n\nAutomatically 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.\n\nThis 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.\n\n## Related Skills\n\n| Skill | Purpose |\n|-------|---------|\n| `kicad` | Schematic\u002FPCB analysis — produces the analyzer JSON this skill consumes |\n| `digikey` | Parametric specs for behavioral models, datasheet downloads |\n| `mouser` | Parametric specs (secondary source), datasheet downloads |\n| `lcsc` | Parametric specs (no auth needed), datasheet downloads |\n| `element14` | Parametric specs (international), datasheet downloads |\n| `emc` | EMC pre-compliance — uses this skill's simulator infrastructure for SPICE-enhanced PDN impedance and EMI filter analysis |\n\n**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\u002FLTspice\u002FXyce), 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 EMI filter insertion loss checks — when ngspice is available, the EMC skill's `--spice-enhanced` flag activates these checks automatically.\n\n## Requirements\n\n- **A SPICE simulator** — one of the following (auto-detected, first available wins):\n  - **ngspice** — `sudo apt install ngspice` (Linux) \u002F `brew install ngspice` (macOS) \u002F ngspice.sourceforge.io (Windows). Most common choice.\n  - **LTspice** — free from analog.com\u002Fltspice. Popular on Windows, works via wine on Linux.\n  - **Xyce** — from xyce.sandia.gov. Parallel SPICE for large circuits.\n  - Override with `--simulator ngspice|ltspice|xyce` or `SPICE_SIMULATOR` env var.\n- **Python 3.10+** — stdlib only, no pip dependencies\n- **Schematic analyzer JSON** — from `analyze_schematic.py --output`\n\nIf 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.\n\n## Workflow\n\n### Step 1: Run the schematic analyzer\n\n```bash\npython3 \u003Ckicad-skill-path>\u002Fscripts\u002Fanalyze_schematic.py design.kicad_sch --analysis-dir analysis\u002F\n```\n\n### Step 2: Run SPICE simulations\n\nPass `--analysis-dir analysis\u002F` — the script auto-resolves `schematic.json`\nfrom the manifest's current run, writes `spice.json` into the same run\nfolder, and parks intermediate `.cir` \u002F `.raw` files in a new\n`spice_sim_*` folder under `\u003Crun>\u002Fspice_work\u002F` by default.\n\n```bash\n# Recommended: auto-resolve schematic + write spice.json into the current run\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F\n\n# Explicit form — positional or --schematic path\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --output sim_report.json\n\n# Simulate specific types only\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F --types rc_filters,voltage_dividers\n\n# Keep simulation files for debugging in a new spice_sim_* folder inside the directory (default: \u003Crun>\u002Fspice_work\u002F when --analysis-dir is set, else a temp dir)\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F --workdir .\u002Fspice_runs\n\n# Increase timeout for complex circuits (default: 5s per subcircuit)\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F --timeout 10\n\n# Omit file paths from output (cleaner for reports)\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F --compact\n```\n\nTo 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`.\n### Step 2b (optional): PCB parasitic-aware simulation\n\nWhen both schematic and PCB exist, low-pass RC filters can be simulated with the PCB trace resistance and via inductance of their output net:\n\n```bash\n# Analyze PCB with full trace segment detail\npython3 \u003Ckicad-skill-path>\u002Fscripts\u002Fanalyze_pcb.py design.kicad_pcb --full --output pcb.json\n\n# Extract parasitic R\u002FL\u002FC from PCB geometry\npython3 \u003Cskill-path>\u002Fscripts\u002Fextract_parasitics.py pcb.json --output parasitics.json\n\n# Run simulation with PCB parasitics injected into testbenches\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --parasitics parasitics.json --output sim_report.json\n```\n\nWith `--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.\n\n**When to use parasitic simulation:** to see whether layout series R\u002FL 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.\n\n### Step 2c (optional): Monte Carlo tolerance analysis\n\nRun N simulations per subcircuit with randomized component values within tolerance bands. Reports statistical distributions and sensitivity analysis — which component contributes most to output variation.\n\n```bash\n# Run 100 Monte Carlo trials per subcircuit\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --monte-carlo 100 --output sim_report.json\n\n# Use uniform distribution (conservative worst-case envelope) instead of Gaussian\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --monte-carlo 100 --mc-distribution uniform\n\n# Set random seed for reproducibility (default: 42)\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --monte-carlo 100 --mc-seed 123\n```\n\n**Tolerance sourcing:** Tolerances are extracted from component value strings first (e.g., \"680K 1%\" → 1%, \"22uF\u002F6.3V\u002F20%\u002FX5R\" → 20%). When not specified in the value string, defaults are used: resistors 5%, capacitors 10%, inductors 20%.\n\n**Output:** Each simulation result gains a `tolerance_analysis` section with:\n- **statistics**: mean, std, min, max, 3-sigma bounds, spread percentage for the primary output metric (fc, Vout, gain, etc.)\n- **sensitivity**: per-component contribution percentage showing which component dominates variation (e.g., \"C3 (10% tol) contributes 68% of fc variation, R5 (5% tol) contributes 32%\")\n- **components**: list of toleranceable components with their resolved tolerance values\n\n**When to use Monte Carlo:** Use it for feedback networks (regulator output accuracy), precision voltage dividers, RC\u002FLC 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.\n\n### Step 3: Interpret results and present to user\n\nRead the JSON report and incorporate findings into the design review. See the \"Interpreting Results\" and \"Presenting to Users\" sections below.\n\n## What Gets Simulated\n\nThe 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).\n\n| Detector | Analysis | What's Measured | Model Fidelity | Trustworthiness |\n|----------|----------|-----------------|----------------|-----------------|\n| `rc_filters` | AC sweep | -3dB frequency, phase at fc | Exact (ideal passives) | High — mathematically exact |\n| `lc_filters` | AC sweep | Resonant frequency (status); Q factor, bandwidth of the assumed ESR | Near-exact (ideal L\u002FC + assumed ESR) | High for resonance; Q is the bench's assumption |\n| `voltage_dividers` | DC operating point | Output voltage, error % | Exact (ideal passives) | High — unloaded |\n| `feedback_networks` | DC operating point | FB pin voltage, regulator Vout | Exact (ideal passives) | High — cross-refs power_regulators |\n| `opamp_circuits` | AC sweep | Gain, -3dB bandwidth | Per-part or ideal | High with behavioral model, medium with ideal |\n| `crystal_circuits` | AC sweep | Series and load resonance, pulling, Rm (`info`); calculated CL range | Approximate (generic BVD) | Medium |\n| `transistor_circuits` | DC sweep | Threshold voltage, on-state current (`info`: generic model's values; a PNP bench `warn`s, not measured) | Approximate (generic FET\u002FBJT) | Low |\n| `current_sense` | DC operating point | Current at 50mV\u002F100mV drop (`info` without an expected current) | Exact (ideal resistor) | High |\n| `protection_devices` | DC sweep | Diode presence, clamping onset | Approximate (generic diode) | Low |\n| `decoupling_analysis` | AC impedance | PDN impedance profile | Exact + ESR estimates | High for passives |\n| `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\u002Ftrimmer, the divider top is not on the output rail, or the rail name carries no voltage) | Exact (ideal passives) | High |\n| `rf_matching` | AC sweep | Impedance profile (`info`); L\u002Fpi\u002FT networks with shunt elements are skipped | Exact (ideal L\u002FC) | Low — series-chained bench |\n| `bridge_circuits` | DC sweep | Low-side turn-on threshold and on-state current (`info`: generic model's values) | Approximate (generic) | Low |\n| `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\u002FC) | High |\n| `rf_chains` | Gain budget | Per-stage gain\u002Floss estimate (`info`; `warn` outside -30..+40 dB) | Heuristic | Low — role-based |\n| `bms_systems` | DC operating point | Cell balance resistor validation | Exact | High |\n| `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 |\n\n### What is NOT simulated\n\n- **Comparators \u002F open-loop opamps** — no feedback network to validate, skipped\n- **Active oscillators** — self-contained modules, nothing to verify externally\n- **Regulator control loop stability** — requires full compensator model (behavioral models cover DC feedback only)\n- **Level-shifter FETs** — require modeling both FETs together, skipped\n- **High-side power switches** — source and drain both on power rails, need full load context\n- **Fuses and varistors** — require manufacturer-specific models\n- **Anything without parsed component values** — if `parse_value()` couldn't extract R\u002FC\u002FL values, the detection is skipped\n\n## Output Format\n\n```json\n{\n  \"summary\": {\"total\": 5, \"pass\": 3, \"warn\": 1, \"fail\": 0, \"skip\": 1, \"info\": 0},\n  \"simulation_results\": [\n    {\n      \"subcircuit_type\": \"rc_filter\",\n      \"components\": [\"R5\", \"C3\"],\n      \"filter_type\": \"low-pass\",\n      \"status\": \"pass\",\n      \"expected\": {\"fc_hz\": 15915, \"type\": \"low-pass\"},\n      \"simulated\": {\"fc_hz\": 15878, \"phase_at_fc_deg\": -45},\n      \"delta\": {\"fc_error_pct\": 0.23},\n      \"cir_file\": \"\u002Ftmp\u002Fspice_sim_xxx\u002Frc-filter_R5_C3.cir\",\n      \"log_file\": \"\u002Ftmp\u002Fspice_sim_xxx\u002Frc-filter_R5_C3.log\",\n      \"elapsed_s\": 0.004\n    }\n  ],\n  \"workdir\": \"\u002Ftmp\u002Fspice_sim_xxx\",\n  \"total_elapsed_s\": 0.032,\n  \"simulator\": \"ngspice\"\n}\n```\n\n**Status values and what they mean:**\n\n| Status | Meaning | Action |\n|--------|---------|--------|\n| **pass** \u002F **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. |\n| **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). |\n| **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. |\n| **skip** | Could not simulate — missing data, unsupported configuration, simulator error | Note in report. Check the `note` field for the reason. |\n\n## Interpreting Results\n\n### Passive circuits (RC filters, LC filters, voltage dividers)\n\nThese 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:\n- The analyzer's topology detection (e.g., it misidentified which net is input vs output)\n- The testbench generation (topology reconstruction error)\n- The analyzer's value parsing (component value parsed incorrectly)\n\nIn testing across real projects, passive simulations consistently show \u003C0.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.\n\n**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.\n\n### Opamp circuits\n\nFor 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).\n\nThe `model_note` field in the report indicates which model was used:\n- `\"LM358 behavioral (lookup:LM358, GBW=1.0MHz)\"` — per-part model, bandwidth results are accurate\n- `\"ideal opamp (Aol=1e6, GBW~10MHz)\"` — fallback, bandwidth results are approximate\n\nWhen 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.\n\nFor 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.\n\n### Crystal circuits\n\nCrystal 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).\n\n### When simulations fail or skip\n\nCheck the `note` field first. Common causes:\n\n| Note | Cause | Fix |\n|------|-------|-----|\n| \"could not measure -3dB frequency\" | AC sweep range doesn't include the -3dB point | Check if the filter fc is very low (\u003C0.1 Hz) or very high (>100 MHz) |\n| \"AC measurement failed\" | Testbench topology error — the circuit doesn't converge | Check `.cir` file for floating nodes or missing connections |\n| \"Testbench generation failed: KeyError\" | Analyzer detection is missing expected fields | Check analyzer JSON — the detection may be incomplete |\n| \"ngspice\u002Fltspice\u002Fxyce failed: ...\" | Simulator error | Check `.log` file for error messages |\n\nWhen 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\u002FXyce). The `.log` file contains simulator stdout\u002Fstderr.\n\n## Presenting Results to Users\n\nWhen incorporating simulation results into a design review report, follow this pattern:\n\n### For passing simulations (confidence builders)\n\n```\n### RC Filter R5\u002FC3 (fc=15.9kHz lowpass) -- Confirmed\nSimulated fc=15.9kHz, \u003C0.3% from calculated. Phase=-45 deg at fc as expected.\n```\n\nKeep passing results brief — they confirm what the analyzer already reported. Group them if there are many.\n\n### For warnings (context required)\n\n```\n### Opamp U4A (inverting gain=-10)\nSimulated gain=20.0dB at 1kHz, matching expected -10x. Bandwidth 98.8kHz\n(ideal model). Note: LM358 GBW is ~1MHz, so actual bandwidth would be\n~100kHz — verify signal frequency stays below 85kHz for \u003C1dB gain error.\n```\n\n### For failures (investigation needed)\n\n```\n### RC Filter R12\u002FC8 -- MISMATCH\nSimulated fc=3.2kHz vs expected 15.9kHz (80% deviation). This likely indicates\nthe analyzer misidentified the filter topology — R12 may be serving a different\npurpose (pull-up, not series filter element). Manually verify the circuit\naround R12\u002FC8 in the schematic.\n```\n\n### For skips (note the gap)\n\n```\n### Crystal Y1 (32.768kHz) -- Not simulated\nActive oscillator module — no external load caps to validate.\n```\n\n### Summary line for the simulation section\n\n```\n## Simulation Verification (4 pass, 1 warn, 0 fail, 1 skip)\nVerified 5 subcircuits in 0.03s. All passive circuits confirmed.\nOne opamp result requires interpretation (see U4A above).\n```\n\n## Model Accuracy Reference\n\nFor detailed information about the behavioral models used, their accuracy envelopes, and known limitations, read `references\u002Fsimulation-models.md`. Consult this reference when:\n- A user questions the accuracy of a simulation result\n- An opamp or crystal simulation shows unexpected behavior\n- You need to explain what \"ideal model\" means in concrete terms\n\n## Script Reference\n\n| Script | Purpose |\n|--------|---------|\n| `scripts\u002Fsimulate_subcircuits.py` | Main orchestrator — CLI entry point, reads JSON, generates testbenches, runs simulator, produces report |\n| `scripts\u002Fspice_templates.py` | Testbench generators per detector type — one function per detector name |\n| `scripts\u002Fspice_models.py` | Behavioral model definitions (ideal opamp, generic semiconductors), net sanitization, engineering notation formatting |\n| `scripts\u002Fspice_results.py` | Simulation output parsing and per-type evaluation with pass\u002Fwarn\u002Ffail\u002Finfo\u002Fskip logic |\n| `scripts\u002Fspice_simulator.py` | Simulator backends — ngspice, LTspice, Xyce auto-detection and batch execution |\n| `scripts\u002Fspice_part_library.py` | Lookup table of electrical specs for 103 op-amps, LDOs, comparators and references, plus 24 crystal-driver and 10 MOSFET entries |\n| `scripts\u002Fspice_model_generator.py` | Parameterized behavioral .subckt generation from specs dicts |\n| `scripts\u002Fspice_model_cache.py` | Project-local model cache in `spice\u002Fmodels\u002F` beside the schematic the analysis JSON names (`file` or `inputs.source_files[0]`); only an analysis that names no source file caches under the run's workdir (`--model-cache-dir` to share one cache) |\n| `scripts\u002Fspice_spec_fetcher.py` | Queries distributor APIs (LCSC, DigiKey, element14, Mouser), structured datasheet extractions, and PDF regex for parametric specs |\n| `scripts\u002Fextract_parasitics.py` | Compute trace R, via L, coupling C from PCB analysis JSON |\n\n## Per-Part Behavioral Models\n\nWhen 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.\n\nModel resolution cascade:\n1. **Project cache** (`\u003Cproject>\u002Fspice\u002Fmodels\u002F`, beside the schematic the analysis JSON names) — previously resolved models\n2. **Distributor API specs** — LCSC (no key, needs network), then DigiKey, element14 and Mouser when their keys are set; the first source with usable specs wins\n3. **Legacy structured extraction** — a `spice_specs` record from `\u003Cproject>\u002Fdatasheets\u002Fextracted\u002F` (score ≥ 6 of 10). It does not read v1.4 extractions, and in practice it finds nothing from the datasheets skill's cache; the typed `lookup()` facts are not used by this resolver.\n   This tier and the PDF tier run only when the analysis names its project.\n4. **Datasheet PDF regex extraction** — reads from `\u003Cproject>\u002Fdatasheets\u002F`, extracts via text pattern matching (needs `pdftotext`)\n5. **Built-in lookup table** — 103 op-amps, LDOs, comparators and references as offline fallback\n6. **Ideal model fallback** — if the MPN isn't recognized by any source\n\n`--offline` skips the distributor and datasheet sources: only the project cache, the built-in lookup table and the ideal fallback are used.\n\nThe `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)\"`.\n\nModels are cached project-locally in a `spice\u002F` directory beside the schematic the analysis JSON names (`file` or `inputs.source_files[0]`), the same pattern as `datasheets\u002F`. Only an analysis that names no source file caches under the run's workdir. This keeps models co-located with the design and handles board revisions and subprojects naturally.\n\n## Known Limitations\n\n- **Voltage dividers are simulated unloaded.** The analyzer's ratio is R_bot\u002F(R_top+R_bot) without loading. Adding a load resistor would make the simulation more \"real\" but would create false \"errors\" relative to the analyzer's calculated value. The purpose is to validate the calculation, not model the full circuit.\n- **LC filter Q factor uses estimated inductor ESR.** A default Q=100 is assumed for the inductor, so the reported `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.\n- **Opamp supply rails are inferred from net names.** May default to +\u002F-5V if the power nets aren't labeled with voltage. Negative rails are read from names like `-12V`, `NEG15V` or `-3V3`; 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.\n- **Per-part models cover 103 built-in parts.** Uncommon opamps\u002FLDOs fall back to ideal models. The lookup table can be extended by adding entries to `spice_part_library.py`.\n- **High-gain opamp circuits with realistic GBW** may show lower-than-expected gain at the measurement point (GBW \u002F (100 x gain), clamped to 1-1000 Hz) when bandwidth is limited. This is physically correct behavior (the model correctly captures the GBW limitation) but may need lower-frequency measurement for accurate gain comparison.\n- **Net names from the analyzer may be `__unnamed_N`.** These are KiCad internal net names for unlabeled wires. They work correctly in simulation but make `.cir` files less readable.\n","# SPICE Simulation Skill\n\nAutomatically 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.\n\nThis 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.\n\n## Related Skills\n\n| Skill | Purpose |\n|-------|---------|\n| `kicad` | Schematic\u002FPCB analysis — produces the analyzer JSON this skill consumes |\n| `digikey` | Parametric specs for behavioral models, datasheet downloads |\n| `mouser` | Parametric specs (secondary source), datasheet downloads |\n| `lcsc` | Parametric specs (no auth needed), datasheet downloads |\n| `element14` | Parametric specs (international), datasheet downloads |\n| `emc` | EMC pre-compliance — uses this skill's simulator infrastructure for SPICE-enhanced PDN impedance and EMI filter analysis |\n\n**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\u002FLTspice\u002FXyce), 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 EMI filter insertion loss checks — when ngspice is available, the EMC skill's `--spice-enhanced` flag activates these checks automatically.\n\n## Requirements\n\n- **A SPICE simulator** — one of the following (auto-detected, first available wins):\n  - **ngspice** — `sudo apt install ngspice` (Linux) \u002F `brew install ngspice` (macOS) \u002F ngspice.sourceforge.io (Windows). Most common choice.\n  - **LTspice** — free from analog.com\u002Fltspice. Popular on Windows, works via wine on Linux.\n  - **Xyce** — from xyce.sandia.gov. Parallel SPICE for large circuits.\n  - Override with `--simulator ngspice|ltspice|xyce` or `SPICE_SIMULATOR` env var.\n- **Python 3.10+** — stdlib only, no pip dependencies\n- **Schematic analyzer JSON** — from `analyze_schematic.py --output`\n\nIf 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.\n\n## Workflow\n\n### Step 1: Run the schematic analyzer\n\n```bash\npython3 \u003Ckicad-skill-path>\u002Fscripts\u002Fanalyze_schematic.py design.kicad_sch --analysis-dir analysis\u002F\n```\n\n### Step 2: Run SPICE simulations\n\nPass `--analysis-dir analysis\u002F` — the script auto-resolves `schematic.json`\nfrom the manifest's current run, writes `spice.json` into the same run\nfolder, and parks intermediate `.cir` \u002F `.raw` files in a new\n`spice_sim_*` folder under `\u003Crun>\u002Fspice_work\u002F` by default.\n\n```bash\n# Recommended: auto-resolve schematic + write spice.json into the current run\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F\n\n# Explicit form — positional or --schematic path\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --output sim_report.json\n\n# Simulate specific types only\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F --types rc_filters,voltage_dividers\n\n# Keep simulation files for debugging in a new spice_sim_* folder inside the directory (default: \u003Crun>\u002Fspice_work\u002F when --analysis-dir is set, else a temp dir)\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F --workdir .\u002Fspice_runs\n\n# Increase timeout for complex circuits (default: 5s per subcircuit)\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F --timeout 10\n\n# Omit file paths from output (cleaner for reports)\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py --analysis-dir analysis\u002F --compact\n```\n\nTo 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`.\n### Step 2b (optional): PCB parasitic-aware simulation\n\nWhen both schematic and PCB exist, low-pass RC filters can be simulated with the PCB trace resistance and via inductance of their output net:\n\n```bash\n# Analyze PCB with full trace segment detail\npython3 \u003Ckicad-skill-path>\u002Fscripts\u002Fanalyze_pcb.py design.kicad_pcb --full --output pcb.json\n\n# Extract parasitic R\u002FL\u002FC from PCB geometry\npython3 \u003Cskill-path>\u002Fscripts\u002Fextract_parasitics.py pcb.json --output parasitics.json\n\n# Run simulation with PCB parasitics injected into testbenches\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --parasitics parasitics.json --output sim_report.json\n```\n\nWith `--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.\n\n**When to use parasitic simulation:** to see whether layout series R\u002FL 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.\n\n### Step 2c (optional): Monte Carlo tolerance analysis\n\nRun N simulations per subcircuit with randomized component values within tolerance bands. Reports statistical distributions and sensitivity analysis — which component contributes most to output variation.\n\n```bash\n# Run 100 Monte Carlo trials per subcircuit\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --monte-carlo 100 --output sim_report.json\n\n# Use uniform distribution (conservative worst-case envelope) instead of Gaussian\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --monte-carlo 100 --mc-distribution uniform\n\n# Set random seed for reproducibility (default: 42)\npython3 \u003Cskill-path>\u002Fscripts\u002Fsimulate_subcircuits.py analysis.json --monte-carlo 100 --mc-seed 123\n```\n\n**Tolerance sourcing:** Tolerances are extracted from component value strings first (e.g., \"680K 1%\" → 1%, \"22uF\u002F6.3V\u002F20%\u002FX5R\" → 20%). When not specified in the value string, defaults are used: resistors 5%, capacitors 10%, inductors 20%.\n\n**Output:** Each simulation result gains a `tolerance_analysis` section with:\n- **statistics**: mean, std, min, max, 3-sigma bounds, spread percentage for the primary output metric (fc, Vout, gain, etc.)\n- **sensitivity**: per-component contribution percentage showing which component dominates variation (e.g., \"C3 (10% tol) contributes 68% of fc variation, R5 (5% tol) contributes 32%\")\n- **components**: list of toleranceable components with their resolved tolerance values\n\n**When to use Monte Carlo:** Use it for feedback networks (regulator output accuracy), precision voltage dividers, RC\u002FLC 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.\n\n### Step 3: Interpret results and present to user\n\nRead the JSON report and incorporate findings into the design review. See the \"Interpreting Results\" and \"Presenting to Users\" sections below.\n\n## What Gets Simulated\n\nThe 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).\n\n| Detector | Analysis | What's Measured | Model Fidelity | Trustworthiness |\n|----------|----------|-----------------|----------------|-----------------|\n| `rc_filters` | AC sweep | -3dB frequency, phase at fc | Exact (ideal passives) | High — mathematically exact |\n| `lc_filters` | AC sweep | Resonant frequency (status); Q factor, bandwidth of the assumed ESR | Near-exact (ideal L\u002FC + assumed ESR) | High for resonance; Q is the bench's assumption |\n| `voltage_dividers` | DC operating point | Output voltage, error % | Exact (ideal passives) | High — unloaded |\n| `feedback_networks` | DC operating point | FB pin voltage, regulator Vout | Exact (ideal passives) | High — cross-refs power_regulators |\n| `opamp_circuits` | AC sweep | Gain, -3dB bandwidth | Per-part or ideal | High with behavioral model, medium with ideal |\n| `crystal_circuits` | AC sweep | Series and load resonance, pulling, Rm (`info`); calculated CL range | Approximate (generic BVD) | Medium |\n| `transistor_circuits` | DC sweep | Threshold voltage, on-state current (`info`: generic model's values; a PNP bench `warn`s, not measured) | Approximate (generic FET\u002FBJT) | Low |\n| `current_sense` | DC operating point | Current at 50mV\u002F100mV drop (`info` without an expected current) | Exact (ideal resistor) | High |\n| `protection_devices` | DC sweep | Diode presence, clamping onset | Approximate (generic diode) | Low |\n| `decoupling_analysis` | AC impedance | PDN impedance profile | Exact + ESR estimates | High for passives |\n| `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\u002Ftrimmer, the divider top is not on the output rail, or the rail name carries no voltage) | Exact (ideal passives) | High |\n| `rf_matching` | AC sweep | Impedance profile (`info`); L\u002Fpi\u002FT networks with shunt elements are skipped | Exact (ideal L\u002FC) | Low — series-chained bench |\n| `bridge_circuits` | DC sweep | Low-side turn-on threshold and on-state current (`info`: generic model's values) | Approximate (generic) | Low |\n| `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\u002FC) | High |\n| `rf_chains` | Gain budget | Per-stage gain\u002Floss estimate (`info`; `warn` outside -30..+40 dB) | Heuristic | Low — role-based |\n| `bms_systems` | DC operating point | Cell balance resistor validation | Exact | High |\n| `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 |\n\n### What is NOT simulated\n\n- **Comparators \u002F open-loop opamps** — no feedback network to validate, skipped\n- **Active oscillators** — self-contained modules, nothing to verify externally\n- **Regulator control loop stability** — requires full compensator model (behavioral models cover DC feedback only)\n- **Level-shifter FETs** — require modeling both FETs together, skipped\n- **High-side power switches** — source and drain both on power rails, need full load context\n- **Fuses and varistors** — require manufacturer-specific models\n- **Anything without parsed component values** — if `parse_value()` couldn't extract R\u002FC\u002FL values, the detection is skipped\n\n## Output Format\n\n```json\n{\n  \"summary\": {\"total\": 5, \"pass\": 3, \"warn\": 1, \"fail\": 0, \"skip\": 1, \"info\": 0},\n  \"simulation_results\": [\n    {\n      \"subcircuit_type\": \"rc_filter\",\n      \"components\": [\"R5\", \"C3\"],\n      \"filter_type\": \"low-pass\",\n      \"status\": \"pass\",\n      \"expected\": {\"fc_hz\": 15915, \"type\": \"low-pass\"},\n      \"simulated\": {\"fc_hz\": 15878, \"phase_at_fc_deg\": -45},\n      \"delta\": {\"fc_error_pct\": 0.23},\n      \"cir_file\": \"\u002Ftmp\u002Fspice_sim_xxx\u002Frc-filter_R5_C3.cir\",\n      \"log_file\": \"\u002Ftmp\u002Fspice_sim_xxx\u002Frc-filter_R5_C3.log\",\n      \"elapsed_s\": 0.004\n    }\n  ],\n  \"workdir\": \"\u002Ftmp\u002Fspice_sim_xxx\",\n  \"total_elapsed_s\": 0.032,\n  \"simulator\": \"ngspice\"\n}\n```\n\n**Status values and what they mean:**\n\n| Status | Meaning | Action |\n|--------|---------|--------|\n| **pass** \u002F **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. |\n| **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). |\n| **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. |\n| **skip** | Could not simulate — missing data, unsupported configuration, simulator error | Note in report. Check the `note` field for the reason. |\n\n## Interpreting Results\n\n### Passive circuits (RC filters, LC filters, voltage dividers)\n\nThese 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:\n- The analyzer's topology detection (e.g., it misidentified which net is input vs output)\n- The testbench generation (topology reconstruction error)\n- The analyzer's value parsing (component value parsed incorrectly)\n\nIn testing across real projects, passive simulations consistently show \u003C0.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.\n\n**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.\n\n### Opamp circuits\n\nFor 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).\n\nThe `model_note` field in the report indicates which model was used:\n- `\"LM358 behavioral (lookup:LM358, GBW=1.0MHz)\"` — per-part model, bandwidth results are accurate\n- `\"ideal opamp (Aol=1e6, GBW~10MHz)\"` — fallback, bandwidth results are approximate\n\nWhen 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.\n\nFor 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.\n\n### Crystal circuits\n\nCrystal 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).\n\n### When simulations fail or skip\n\nCheck the `note` field first. Common causes:\n\n| Note | Cause | Fix |\n|------|-------|-----|\n| \"could not measure -3dB frequency\" | AC sweep range doesn't include the -3dB point | Check if the filter fc is very low (\u003C0.1 Hz) or very high (>100 MHz) |\n| \"AC measurement failed\" | Testbench topology error — the circuit doesn't converge | Check `.cir` file for floating nodes or missing connections |\n| \"Testbench generation failed: KeyError\" | Analyzer detection is missing expected fields | Check analyzer JSON — the detection may be incomplete |\n| \"ngspice\u002Fltspice\u002Fxyce failed: ...\" | Simulator error | Check `.log` file for error messages |\n\nWhen 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\u002FXyce). The `.log` file contains simulator stdout\u002Fstderr.\n\n## Presenting Results to Users\n\nWhen incorporating simulation results into a design review report, follow this pattern:\n\n### For passing simulations (confidence builders)\n\n```\n### RC Filter R5\u002FC3 (fc=15.9kHz lowpass) -- Confirmed\nSimulated fc=15.9kHz, \u003C0.3% from calculated. Phase=-45 deg at fc as expected.\n```\n\nKeep passing results brief — they confirm what the analyzer already reported. Group them if there are many.\n\n### For warnings (context required)\n\n```\n### Opamp U4A (inverting gain=-10)\nSimulated gain=20.0dB at 1kHz, matching expected -10x. Bandwidth 98.8kHz\n(ideal model). Note: LM358 GBW is ~1MHz, so actual bandwidth would be\n~100kHz — verify signal frequency stays below 85kHz for \u003C1dB gain error.\n```\n\n### For failures (investigation needed)\n\n```\n### RC Filter R12\u002FC8 -- MISMATCH\nSimulated fc=3.2kHz vs expected 15.9kHz (80% deviation). This likely indicates\nthe analyzer misidentified the filter topology — R12 may be serving a different\npurpose (pull-up, not series filter element). Manually verify the circuit\naround R12\u002FC8 in the schematic.\n```\n\n### For skips (note the gap)\n\n```\n### Crystal Y1 (32.768kHz) -- Not simulated\nActive oscillator module — no external load caps to validate.\n```\n\n### Summary line for the simulation section\n\n```\n## Simulation Verification (4 pass, 1 warn, 0 fail, 1 skip)\nVerified 5 subcircuits in 0.03s. All passive circuits confirmed.\nOne opamp result requires interpretation (see U4A above).\n```\n\n## Model Accuracy Reference\n\nFor detailed information about the behavioral models used, their accuracy envelopes, and known limitations, read `references\u002Fsimulation-models.md`. Consult this reference when:\n- A user questions the accuracy of a simulation result\n- An opamp or crystal simulation shows unexpected behavior\n- You need to explain what \"ideal model\" means in concrete terms\n\n## Script Reference\n\n| Script | Purpose |\n|--------|---------|\n| `scripts\u002Fsimulate_subcircuits.py` | Main orchestrator — CLI entry point, reads JSON, generates testbenches, runs simulator, produces report |\n| `scripts\u002Fspice_templates.py` | Testbench generators per detector type — one function per detector name |\n| `scripts\u002Fspice_models.py` | Behavioral model definitions (ideal opamp, generic semiconductors), net sanitization, engineering notation formatting |\n| `scripts\u002Fspice_results.py` | Simulation output parsing and per-type evaluation with pass\u002Fwarn\u002Ffail\u002Finfo\u002Fskip logic |\n| `scripts\u002Fspice_simulator.py` | Simulator backends — ngspice, LTspice, Xyce auto-detection and batch execution |\n| `scripts\u002Fspice_part_library.py` | Lookup table of electrical specs for 103 op-amps, LDOs, comparators and references, plus 24 crystal-driver and 10 MOSFET entries |\n| `scripts\u002Fspice_model_generator.py` | Parameterized behavioral .subckt generation from specs dicts |\n| `scripts\u002Fspice_model_cache.py` | Project-local model cache in `spice\u002Fmodels\u002F` beside the schematic the analysis JSON names (`file` or `inputs.source_files[0]`); only an analysis that names no source file caches under the run's workdir (`--model-cache-dir` to share one cache) |\n| `scripts\u002Fspice_spec_fetcher.py` | Queries distributor APIs (LCSC, DigiKey, element14, Mouser), structured datasheet extractions, and PDF regex for parametric specs |\n| `scripts\u002Fextract_parasitics.py` | Compute trace R, via L, coupling C from PCB analysis JSON |\n\n## Per-Part Behavioral Models\n\nWhen 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.\n\nModel resolution cascade:\n1. **Project cache** (`\u003Cproject>\u002Fspice\u002Fmodels\u002F`, beside the schematic the analysis JSON names) — previously resolved models\n2. **Distributor API specs** — LCSC (no key, needs network), then DigiKey, element14 and Mouser when their keys are set; the first source with usable specs wins\n3. **Legacy structured extraction** — a `spice_specs` record from `\u003Cproject>\u002Fdatasheets\u002Fextracted\u002F` (score ≥ 6 of 10). It does not read v1.4 extractions, and in practice it finds nothing from the datasheets skill's cache; the typed `lookup()` facts are not used by this resolver.\n   This tier and the PDF tier run only when the analysis names its project.\n4. **Datasheet PDF regex extraction** — reads from `\u003Cproject>\u002Fdatasheets\u002F`, extracts via text pattern matching (needs `pdftotext`)\n5. **Built-in lookup table** — 103 op-amps, LDOs, comparators and references as offline fallback\n6. **Ideal model fallback** — if the MPN isn't recognized by any source\n\n`--offline` skips the distributor and datasheet sources: only the project cache, the built-in lookup table and the ideal fallback are used.\n\nThe `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)\"`.\n\nModels are cached project-locally in a `spice\u002F` directory beside the schematic the analysis JSON names (`file` or `inputs.source_files[0]`), the same pattern as `datasheets\u002F`. Only an analysis that names no source file caches under the run's workdir. This keeps models co-located with the design and handles board revisions and subprojects naturally.\n\n## Known Limitations\n\n- **Voltage dividers are simulated unloaded.** The analyzer's ratio is R_bot\u002F(R_top+R_bot) without loading. Adding a load resistor would make the simulation more \"real\" but would create false \"errors\" relative to the analyzer's calculated value. The purpose is to validate the calculation, not model the full circuit.\n- **LC filter Q factor uses estimated inductor ESR.** A default Q=100 is assumed for the inductor, so the reported `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.\n- **Opamp supply rails are inferred from net names.** May default to +\u002F-5V if the power nets aren't labeled with voltage. Negative rails are read from names like `-12V`, `NEG15V` or `-3V3`; 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.\n- **Per-part models cover 103 built-in parts.** Uncommon opamps\u002FLDOs fall back to ideal models. The lookup table can be extended by adding entries to `spice_part_library.py`.\n- **High-gain opamp circuits with realistic GBW** may show lower-than-expected gain at the measurement point (GBW \u002F (100 x gain), clamped to 1-1000 Hz) when bandwidth is limited. This is physically correct behavior (the model correctly captures the GBW limitation) but may need lower-frequency measurement for accurate gain comparison.\n- **Net names from the analyzer may be `__unnamed_N`.** These are KiCad internal net names for unlabeled wires. They work correctly in simulation but make `.cir` files less readable.\n",{"name":5,"description":7},"main","47790c5af225ba335e83c027413077333397539e","plugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice",491,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins","https:\u002F\u002Fhol.org\u002Fplugins\u002Fbest-codex-plugins","https:\u002F\u002Fgithub.com\u002Fhashgraph-online","https:\u002F\u002Fhol.org","Open-source standards and developer tools for interoperable AI agents: discovery, identity, communication, payments, privacy and security.","2026-11-14 14:06:13",{"source":8,"skillName":5,"commands":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add hashgraph-online\u002Fawesome-codex-plugins --skill spice",{"tool":60,"command":61},"bunx","bunx skills add hashgraph-online\u002Fawesome-codex-plugins --skill spice",{"tool":63,"command":64},"pnpm","pnpm dlx skills add hashgraph-online\u002Fawesome-codex-plugins --skill spice","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002FSKILL.md",true,[68,74,80,84,88,92,96,100,104,108,112,116,120,124,128],{"path":69,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":72,"sourceHtmlUrl":73},"references\u002Fsimulation-models.md","REFERENCE","参考文档",21364,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Freferences\u002Fsimulation-models.md",{"path":75,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":78,"sourceHtmlUrl":79},"scripts\u002F_core_path.py","SCRIPT","脚本",697,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002F_core_path.py",{"path":81,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":82,"sourceHtmlUrl":83},"scripts\u002Fextract_parasitics.py",11168,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fextract_parasitics.py",{"path":85,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":86,"sourceHtmlUrl":87},"scripts\u002Frun_external_deck.py",7426,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Frun_external_deck.py",{"path":89,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":90,"sourceHtmlUrl":91},"scripts\u002Fsimulate_subcircuits.py",30059,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fsimulate_subcircuits.py",{"path":93,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":94,"sourceHtmlUrl":95},"scripts\u002Fspice_model_cache.py",16714,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fspice_model_cache.py",{"path":97,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":98,"sourceHtmlUrl":99},"scripts\u002Fspice_model_generator.py",7062,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fspice_model_generator.py",{"path":101,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":102,"sourceHtmlUrl":103},"scripts\u002Fspice_models.py",7369,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fspice_models.py",{"path":105,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":106,"sourceHtmlUrl":107},"scripts\u002Fspice_part_library.py",28122,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fspice_part_library.py",{"path":109,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":110,"sourceHtmlUrl":111},"scripts\u002Fspice_results.py",54623,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fspice_results.py",{"path":113,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":114,"sourceHtmlUrl":115},"scripts\u002Fspice_simulator.py",27149,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fspice_simulator.py",{"path":117,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":118,"sourceHtmlUrl":119},"scripts\u002Fspice_spec_fetcher.py",24617,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fspice_spec_fetcher.py",{"path":121,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":122,"sourceHtmlUrl":123},"scripts\u002Fspice_templates.py",72471,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fspice_templates.py",{"path":125,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":126,"sourceHtmlUrl":127},"scripts\u002Fspice_tolerance.py",10858,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Fspice_tolerance.py",{"path":129,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":130,"sourceHtmlUrl":131},"scripts\u002Ftest_spice_simulator.py",44147,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Faklofas\u002Fkicad-happy\u002Fskills\u002Fspice\u002Fscripts\u002Ftest_spice_simulator.py",[133,143,151,159,167,175],{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":137,"licenseFileUrl":138,"sourceHtmlUrl":139,"categories":140,"keywords":141,"publishedAt":142},"01M7DV332YQMGD8WTRJ9DZQXTB","worktable-review-with-annotations","Create, inspect, reply to, update, or resolve situated Worktable annotations. Use when feedback belongs to a Doc section, block, text range, or HTML Doc, or when the user asks to address existing review feedback and coordinate a requested artifact edit.","MIT","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":137,"licenseFileUrl":147,"sourceHtmlUrl":148,"categories":149,"keywords":150,"publishedAt":142},"01M7DV2YGHCZVBEB1AHYB6CGHE","worktable-find-and-synthesize-context","Find, assess, and synthesize context from Worktable Docs and Records. Use when the user asks what a workspace contains, wants workspace-backed research, needs current facts reconciled across artifacts, or requests a cited synthesis without changing workspace state.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FSKILL.md",[],[],{"skillNo":152,"name":153,"nameZh":6,"description":154,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":137,"licenseFileUrl":155,"sourceHtmlUrl":156,"categories":157,"keywords":158,"publishedAt":142},"01M7DV2TQN1H11ME2SAF9MXN7V","worktable-create-or-update-docs","Create, edit, rename, or maintain narrative Worktable Docs. Use for plans, decisions, briefs, notes, research syntheses, and other durable prose when the user requests a new artifact or a safe update to an existing one.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FSKILL.md",[],[],{"skillNo":160,"name":161,"nameZh":6,"description":162,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":137,"licenseFileUrl":163,"sourceHtmlUrl":164,"categories":165,"keywords":166,"publishedAt":142},"01M7DV2NE452NEA8TXATKSNAJH","worktable-create-or-manage-records","Organize repeated structured information as durable Worktable Records. Use for research datasets, inventories, directories, pipelines, trackers, and other collections whose items need identity, fields, filtering, links, validation, or individual updates.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FSKILL.md",[],[],{"skillNo":168,"name":169,"nameZh":6,"description":170,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":137,"licenseFileUrl":171,"sourceHtmlUrl":172,"categories":173,"keywords":174,"publishedAt":142},"01M7DV2HENRBR2KSCVM064WH0Y","worktable-create-or-manage-interactive-html","Create or improve durable visual and interactive artifacts in Worktable. Use for dashboards, trackers, calculators, mini apps, slide presentations, and other requests that benefit from a polished HTML Doc.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FSKILL.md",[],[],{"skillNo":176,"name":177,"nameZh":6,"description":178,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":137,"licenseFileUrl":179,"sourceHtmlUrl":180,"categories":181,"keywords":182,"publishedAt":142},"01M7DV2CADR5R7RQFFYPNAGR9Y","worktable-collaborate-threads","Read, answer, and hand off messages through durable Worktable threads with users or other authenticated participants. Use when the user asks to check addressed messages, reply to a participant, continue a thread, request another agent's help, wait briefly for a response, or watch for comments and messages sent to the agent.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FSKILL.md",[],[]]