Skip to content

hashgraph-online/awesome-codex-plugins / plugins/aklofas/kicad-happy/skills/emc

EMC 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".

scripts/emc_spice.py

View on GitHub
"""SPICE-enhanced EMC analysis — PDN impedance and switching harmonics.

Optional module that uses the SPICE skill's simulator infrastructure to
provide more accurate PDN impedance sweeps and switching-waveform
harmonic amplitudes. Falls back gracefully when no simulator is available.

Requires: ngspice, LTspice, or Xyce (auto-detected).
Zero required external Python dependencies.
"""

import math
import os
import sys
import tempfile

import _core_path  # noqa: F401
from kicad_core.diagnostics import record

# Add spice skill scripts to path for simulator imports
_SPICE_SCRIPTS = os.path.join(os.path.dirname(__file__), '..', '..', 'spice', 'scripts')
if os.path.isdir(_SPICE_SCRIPTS):
    sys.path.insert(0, os.path.abspath(_SPICE_SCRIPTS))

from spice_models import spice_text  # noqa: E402


def detect_spice_simulator():
    """Try to detect a SPICE simulator.

    Returns a SimulatorBackend instance or None.
    """
    try:
        from spice_simulator import detect_simulator
        return detect_simulator()
    except ImportError:
        return None


def _format_eng(value):
    """Format a value in SPICE engineering notation."""
    if value == 0:
        return "0"
    abs_val = abs(value)
    prefixes = [
        (1e12, 'T'), (1e9, 'G'), (1e6, 'Meg'), (1e3, 'k'),
        (1, ''), (1e-3, 'm'), (1e-6, 'u'), (1e-9, 'n'), (1e-12, 'p'),
        (1e-15, 'f'),
    ]
    for threshold, prefix in prefixes:
        if abs_val >= threshold * 0.999:
            scaled = value / threshold
            if scaled == int(scaled):
                return f"{int(scaled)}{prefix}"
            return f"{scaled:.4g}{prefix}"
    return f"{value:.6e}"


# ---------------------------------------------------------------------------
# PDN Impedance SPICE Testbench
# ---------------------------------------------------------------------------

def generate_pdn_netlist(caps, plane_cap_f=0):
    """Generate a SPICE netlist for PDN impedance measurement.

    Each cap is modeled as series ESR-ESL-C from the rail node to ground.
    A 1A AC current source drives the rail — V(rail) = Z(f) directly.

    Args:
        caps: List of dicts with farads, esr_ohm, esl_h, and optionally ref.
        plane_cap_f: Interplane capacitance in Farads (added as parallel C).

    Returns:
        SPICE netlist string (without analysis/measurement commands).
    """
    lines = []
    lines.append('* PDN Impedance Sweep — auto-generated by kicad-happy EMC')
    lines.append(f'* {len(caps)} decoupling cap(s) in parallel, series R-L-C model')
    lines.append('')

    for i, cap in enumerate(caps):
        ref = cap.get('ref', f'C{i+1}')
        farads = cap.get('farads', 0)
        esr = cap.get('esr_ohm', 0.1)
        esl = cap.get('esl_h', 1e-9)
        if farads <= 0:
            continue

        n1 = f'n_esr_{i}'
        n2 = f'n_esl_{i}'
        lines.append(f'* {spice_text(ref)}: {_format_eng(farads)}F, ESR={_format_eng(esr)}, ESL={_format_eng(esl)}H')
        lines.append(f'R_esr_{i} rail {n1} {_format_eng(esr)}')
        lines.append(f'L_esl_{i} {n1} {n2} {_format_eng(esl)}')
        lines.append(f'C_cap_{i} {n2} 0 {_format_eng(farads)}')

    if plane_cap_f > 0:
        lines.append(f'')
        lines.append(f'* Interplane capacitance')
        lines.append(f'C_plane rail 0 {_format_eng(plane_cap_f)}')

    # Check if any caps were actually included
    cap_count = sum(1 for c in caps if c.get('farads', 0) > 0)
    if cap_count == 0:
        lines.insert(2, '* WARNING: 0 of {n} caps had valid farads — netlist is empty'.format(
            n=len(caps)))

    lines.append('')
    lines.append('* Bias resistor (prevents floating node)')
    lines.append('R_bias rail 0 1meg')
    lines.append('')
    lines.append('* 1A AC current source — V(rail) = Z(f)')
    lines.append('IAC 0 rail DC 0 AC 1')

    return '\n'.join(lines)


def run_pdn_spice(caps, plane_cap_f=0, backend=None,
                  freq_start=1e3, freq_stop=1e9,
                  points_per_decade=50, timeout=10, diagnostics=None):
    """Run SPICE AC sweep for PDN impedance and return results.

    Args:
        caps: List of cap dicts (farads, esr_ohm, esl_h).
        plane_cap_f: Interplane capacitance in Farads.
        backend: SimulatorBackend instance.
        freq_start/freq_stop: Sweep range in Hz.
        points_per_decade: Resolution.
        timeout: Simulation timeout in seconds.

    Returns:
        (success, sweep) where sweep is a list of {freq_hz, impedance_ohm}
        compatible with find_anti_resonances(). Returns (False, None) on failure.
    """
    if backend is None:
        return False, None

    netlist = generate_pdn_netlist(caps, plane_cap_f)

    # Build ngspice control block to output impedance at sampled frequencies
    # We use wrdata to dump the full AC sweep, then parse it
    try:
        from spice_simulator import NgspiceBackend, LtspiceBackend, XyceBackend
        from spice_templates import SpiceTestbench
    except ImportError:
        return False, None

    # Use SpiceTestbench for portable rendering
    decades = math.log10(freq_stop / freq_start)
    ppd = int(points_per_decade)
    ac_spec = f'dec {ppd} {_format_eng(freq_start)} {_format_eng(freq_stop)}'

    # Measurements: impedance at key frequencies + min/max
    measurements = [
        ('z_min', 'min', 'vm(rail)'),
        ('f_at_zmin', 'when', 'vm(rail)', 'z_min'),
    ]

    # Add measurement points at logarithmic intervals for the sweep
    # Use specific frequency probes
    probe_freqs = []
    n_probes = int(decades * 10)  # 10 probes per decade
    for i in range(n_probes + 1):
        f = freq_start * (10 ** (i * decades / n_probes))
        probe_freqs.append(f)
        meas_name = f'z_f{i}'
        measurements.append((meas_name, 'find', 'vm(rail)', f'at={_format_eng(f)}'))

    tb = SpiceTestbench(netlist, [('ac', ac_spec)], measurements)

    workdir = tempfile.mkdtemp(prefix='emc_pdn_')
    cir_file = os.path.join(workdir, 'pdn.cir')
    out_file = os.path.join(workdir, 'pdn_results.txt')

    try:
        cir_content = tb.render(backend, os.path.basename(out_file))
        with open(cir_file, 'w', encoding="utf-8", newline="\n") as f:
            f.write(cir_content)

        success, stdout, stderr = backend.run(os.path.basename(cir_file), timeout=timeout, cwd=workdir)
        if not success:
            return False, None

        results = backend.parse_results(out_file, stdout, stderr)
        if not results:
            return False, None

        # Build impedance sweep from probe measurements
        sweep = []
        for i, freq in enumerate(probe_freqs):
            z_key = f'z_f{i}'
            z_val = results.get(z_key)
            if z_val is not None and isinstance(z_val, (int, float)) and z_val > 0:
                sweep.append({'freq_hz': freq, 'impedance_ohm': z_val})

        if len(sweep) < 5:
            return False, None

        return True, sweep

    except Exception as exc:
        record(diagnostics, "emc_spice.run_pdn_spice", exc, "PDN SPICE sweep failed")
        return False, None
    finally:
        # Cleanup
        import shutil
        try:
            shutil.rmtree(workdir, ignore_errors=True)
        except Exception:
            pass


# ---------------------------------------------------------------------------
# Goertzel algorithm for single-frequency magnitude (no numpy needed)
# ---------------------------------------------------------------------------

def _goertzel_magnitude(samples, sample_rate, target_freq):
    """Compute magnitude at a single frequency using the Goertzel algorithm.

    O(N) per frequency — more efficient than full FFT when only a few
    frequencies are needed. Works with Python stdlib only.

    Args:
        samples: List of float samples (time-domain signal).
        sample_rate: Sample rate in Hz.
        target_freq: Frequency to measure in Hz.

    Returns:
        Magnitude (linear, not dB).
    """
    n = len(samples)
    if n == 0:
        return 0.0
    k = int(0.5 + n * target_freq / sample_rate)
    omega = 2 * math.pi * k / n
    coeff = 2 * math.cos(omega)
    s0 = 0.0
    s1 = 0.0
    s2 = 0.0
    for sample in samples:
        s0 = sample + coeff * s1 - s2
        s2 = s1
        s1 = s0
    magnitude = math.sqrt(s1**2 + s2**2 - coeff * s1 * s2)
    return magnitude * 2 / n  # Single-sided spectrum: 2/N normalization


# ---------------------------------------------------------------------------
# Switching Waveform Transient + FFT
# ---------------------------------------------------------------------------

def run_switching_fft(v_peak, duty_cycle, rise_time_s, switching_freq_hz,
                      backend=None, n_harmonics=15, timeout=15, diagnostics=None):
    """Run transient simulation of a switching waveform and extract harmonics.

    Generates a PULSE source at the switching frequency, runs transient
    analysis for 20 cycles, dumps the raw waveform, and computes harmonic
    magnitudes using the Goertzel algorithm.

    Args:
        v_peak: Peak voltage of the switching node.
        duty_cycle: Duty cycle (0 to 1).
        rise_time_s: 10-90% rise time in seconds.
        switching_freq_hz: Switching frequency in Hz.
        backend: SimulatorBackend instance.
        n_harmonics: Number of harmonics to extract.
        timeout: Simulation timeout in seconds.

    Returns:
        (success, harmonics) where harmonics is a list of
        {harmonic, freq_hz, amplitude_v, amplitude_dbuv} dicts.
        Returns (False, None) on failure.
    """
    if backend is None:
        return False, None

    # Uses ngspice .control block with wrdata — not portable to LTspice/Xyce
    backend_name = getattr(backend, 'name', '')
    if backend_name and backend_name not in ('ngspice', ''):
        return False, None

    t_period = 1.0 / switching_freq_hz
    t_on = duty_cycle * t_period
    t_sim = 20 * t_period  # 20 cycles for steady state
    # Time step: at least 100 points per rise time for accuracy
    t_step = min(rise_time_s / 10, t_period / 200)

    netlist = (
        f'* Switching waveform for harmonic FFT\n'
        f'V1 sw 0 PULSE(0 {_format_eng(v_peak)} 0 '
        f'{_format_eng(rise_time_s)} {_format_eng(rise_time_s)} '
        f'{_format_eng(t_on - rise_time_s)} {_format_eng(t_period)})\n'
        f'R1 sw 0 1Meg\n'
    )

    workdir = tempfile.mkdtemp(prefix='emc_fft_')
    cir_file = os.path.join(workdir, 'fft.cir')
    raw_file = os.path.join(workdir, 'fft_raw.txt')
    out_file = os.path.join(workdir, 'fft_results.txt')

    try:
        # Build ngspice-specific netlist with .control block to dump raw data
        cir_content = (
            f'{netlist}\n'
            f'.tran {_format_eng(t_step)} {_format_eng(t_sim)}\n'
            f'.control\n'
            f'run\n'
            f'linearize v(sw)\n'
            f'wrdata {os.path.basename(raw_file)} v(sw)\n'
            f'echo "done=1" > {os.path.basename(out_file)}\n'
            f'.endc\n'
            f'.end\n'
        )

        with open(cir_file, 'w', encoding="utf-8", newline="\n") as f:
            f.write(cir_content)

        success, stdout, stderr = backend.run(os.path.basename(cir_file), timeout=timeout, cwd=workdir)
        # ngspice returns exit code 1 with .control blocks that lack
        # .print/.plot — check for output file instead of exit code
        if not success:
            if not (os.path.exists(raw_file) and os.path.getsize(raw_file) > 0):
                return False, None

        # Parse raw ASCII data: columns are time, v(sw)
        if not os.path.exists(raw_file):
            return False, None

        times = []
        values = []
        with open(raw_file, 'r', encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('#') or line.startswith('*'):
                    continue
                parts = line.split()
                if len(parts) >= 2:
                    try:
                        t = float(parts[0])
                        v = float(parts[1])
                        times.append(t)
                        values.append(v)
                    except ValueError:
                        continue

        if len(values) < 100:
            return False, None

        # Use only the last 10 cycles (skip initial transient)
        t_start = 10 * t_period
        start_idx = 0
        for i, t in enumerate(times):
            if t >= t_start:
                start_idx = i
                break

        steady_values = values[start_idx:]
        steady_times = times[start_idx:]
        if len(steady_values) < 50:
            steady_values = values  # Fall back to full waveform
            steady_times = times

        # Compute sample rate from time data
        if len(times) > 1:
            dt = (steady_times[-1] - steady_times[0]) / (len(steady_values) - 1)
            sample_rate = 1.0 / dt if dt > 0 else 1.0 / t_step
        else:
            return False, None

        # Extract harmonics using Goertzel
        harmonics = []
        for n in range(1, n_harmonics + 1):
            h_freq = n * switching_freq_hz
            if h_freq > sample_rate / 2:
                break  # Nyquist limit
            mag = _goertzel_magnitude(steady_values, sample_rate, h_freq)
            mag_dbuv = 20 * math.log10(mag * 1e6) if mag > 0 else -999
            harmonics.append({
                'harmonic': n,
                'freq_hz': h_freq,
                'amplitude_v': mag,
                'amplitude_dbuv': mag_dbuv,
            })

        if not harmonics:
            return False, None

        return True, harmonics

    except Exception as exc:
        record(diagnostics, "emc_spice.run_switching_fft", exc, "switching FFT SPICE run failed")
        return False, None
    finally:
        import shutil
        try:
            shutil.rmtree(workdir, ignore_errors=True)
        except Exception:
            pass


def verify_pdn_with_suggested_cap(caps, suggested_cap, plane_cap_f,
                                  z_target, backend, timeout=10,
                                  sweep_before=None, diagnostics=None):
    """Re-run PDN SPICE sweep with a suggested cap added and check if the
    anti-resonance peak is resolved.

    Args:
        caps: Original cap model list.
        suggested_cap: Dict with farads, esr_ohm, esl_h to add.
        plane_cap_f: Interplane capacitance.
        z_target: Target impedance.
        backend: SimulatorBackend.
        sweep_before: Optional pre-existing sweep data (avoids re-simulating).

    Returns:
        (success, peak_before_ohm, peak_after_ohm) or (False, None, None).
    """
    if backend is None:
        return False, None, None

    from emc_formulas import find_anti_resonances

    # Reuse existing sweep if provided, otherwise simulate
    if sweep_before:
        sweep1 = sweep_before
    else:
        ok1, sweep1 = run_pdn_spice(caps, plane_cap_f, backend, timeout=timeout,
                                   diagnostics=diagnostics)
        if not ok1 or not sweep1:
            return False, None, None

    peaks_before = find_anti_resonances(sweep1, z_target=z_target)
    exceeding_before = [p for p in peaks_before if p.get('exceeds_target')]
    if not exceeding_before:
        return True, 0, 0  # No peak to fix

    peak_before = max(p['impedance_ohm'] for p in exceeding_before)

    # Run with suggested cap added
    augmented = list(caps) + [suggested_cap]
    ok2, sweep2 = run_pdn_spice(augmented, plane_cap_f, backend, timeout=timeout,
                               diagnostics=diagnostics)
    if not ok2 or not sweep2:
        return False, peak_before, None

    peaks_after = find_anti_resonances(sweep2, z_target=z_target)
    exceeding_after = [p for p in peaks_after if p.get('exceeds_target')]
    peak_after = max((p['impedance_ohm'] for p in exceeding_after), default=0)

    return True, peak_before, peak_after


# ---------------------------------------------------------------------------
# Distributed PDN Impedance (Full-Board)
# ---------------------------------------------------------------------------

def generate_distributed_pdn_netlist(node, plane_cap_f=0):
    """Generate SPICE netlist for distributed PDN impedance at IC load point.

    Extends generate_pdn_netlist() by adding trace R+L between the regulator
    output node and the IC load point, plus local decoupling caps at the IC.
    The 1A AC current source is placed at the IC node, so V(ic_load) = Z(f)
    at the IC's power pins.

    Args:
        node: PowerTreeNode dict from build_power_tree().
        plane_cap_f: Interplane capacitance in Farads.

    Returns:
        SPICE netlist string.
    """
    lines = []
    lines.append('* Distributed PDN Impedance — auto-generated by kicad-happy EMC')
    lines.append('* Regulator output caps + trace parasitics + IC local decoupling')
    lines.append('')

    # Regulator output caps at 'rail' node
    reg_caps = [c for c in node.get('output_caps', [])
                if c.get('location') != 'ic_decoupling']
    ic_caps = [c for c in node.get('output_caps', [])
               if c.get('location') == 'ic_decoupling']

    for i, cap in enumerate(reg_caps):
        farads = cap.get('farads', 0)
        esr = cap.get('esr_ohm', 0.1)
        esl = cap.get('esl_h', 1e-9)
        if farads <= 0:
            continue
        ref = cap.get('ref', f'C_reg_{i}')
        n1 = f'n_reg_esr_{i}'
        n2 = f'n_reg_esl_{i}'
        lines.append(f'* Regulator cap {spice_text(ref)}: {_format_eng(farads)}F')
        lines.append(f'R_reg_esr_{i} rail {n1} {_format_eng(esr)}')
        lines.append(f'L_reg_esl_{i} {n1} {n2} {_format_eng(esl)}')
        lines.append(f'C_reg_cap_{i} {n2} 0 {_format_eng(farads)}')

    if plane_cap_f > 0:
        lines.append('')
        lines.append('* Interplane capacitance')
        lines.append(f'C_plane rail 0 {_format_eng(plane_cap_f)}')

    # Trace parasitics: rail -> ic_load
    r_trace = node.get('trace_r_total_ohm', 0)
    l_trace = node.get('trace_l_total_h', 0)

    lines.append('')
    lines.append('* Trace parasitics (regulator to IC)')
    if r_trace > 0:
        lines.append(f'R_trace rail n_trace {_format_eng(r_trace)}')
        trace_out = 'n_trace'
    else:
        trace_out = 'rail'

    if l_trace > 0:
        lines.append(f'L_trace {trace_out} ic_load {_format_eng(l_trace)}')
    elif trace_out != 'ic_load':
        # Direct connection if no inductance
        lines.append(f'R_trace_short {trace_out} ic_load 0.001')
    else:
        lines.append('R_trace_short rail ic_load 0.001')

    # Local IC decoupling caps at 'ic_load' node
    for i, cap in enumerate(ic_caps):
        farads = cap.get('farads', 0)
        esr = cap.get('esr_ohm', 0.1)
        esl = cap.get('esl_h', 1e-9)
        if farads <= 0:
            continue
        ref = cap.get('ref', f'C_ic_{i}')
        n1 = f'n_ic_esr_{i}'
        n2 = f'n_ic_esl_{i}'
        lines.append(f'* IC decoupling {spice_text(ref)}: {_format_eng(farads)}F')
        lines.append(f'R_ic_esr_{i} ic_load {n1} {_format_eng(esr)}')
        lines.append(f'L_ic_esl_{i} {n1} {n2} {_format_eng(esl)}')
        lines.append(f'C_ic_cap_{i} {n2} 0 {_format_eng(farads)}')

    lines.append('')
    lines.append('* Bias resistors')
    lines.append('R_bias_rail rail 0 1Meg')
    lines.append('R_bias_ic ic_load 0 1Meg')
    lines.append('')
    lines.append('* 1A AC current source at IC load point — V(ic_load) = Z(f)')
    lines.append('IAC 0 ic_load DC 0 AC 1')

    return '\n'.join(lines)


def run_distributed_pdn_spice(node, plane_cap_f=0, backend=None,
                              freq_start=1e3, freq_stop=1e9,
                              points_per_decade=50, timeout=10, diagnostics=None):
    """Run SPICE AC sweep for distributed PDN impedance at IC load point.

    Same pattern as run_pdn_spice() but uses the distributed netlist.

    Returns:
        (success: bool, sweep: list[dict] | None)
    """
    if not backend:
        return False, None

    netlist = generate_distributed_pdn_netlist(node, plane_cap_f)

    try:
        from spice_templates import SpiceTestbench
    except ImportError:
        return False, None

    # Create AC analysis
    decades = math.log10(freq_stop / freq_start)
    ppd = points_per_decade
    analyses = [('ac', f'dec {ppd} {_format_eng(freq_start)} {_format_eng(freq_stop)}')]

    # Measurement: probe impedance at ic_load at logarithmic points
    measurements = []
    probes_per_decade = 10
    n_probes = int(decades * probes_per_decade)
    for i in range(n_probes + 1):
        f = freq_start * (10 ** (i * decades / n_probes))
        measurements.append((f'z_at_{i}', 'find', 'vm(ic_load)', f'at={_format_eng(f)}'))

    tb = SpiceTestbench(netlist, analyses, measurements)

    # Write and run
    workdir = tempfile.mkdtemp(prefix='emc_dpdn_')
    cir_file = os.path.join(workdir, 'distributed_pdn.cir')
    out_file = os.path.join(workdir, 'distributed_pdn.out')

    try:
        cir_content = tb.render(backend, os.path.basename(out_file))
        with open(cir_file, 'w', encoding="utf-8", newline="\n") as f:
            f.write(cir_content)

        success, stdout, stderr = backend.run(os.path.basename(cir_file), timeout=timeout, cwd=workdir)
        if not success:
            return False, None

        if hasattr(backend, 'parse_results'):
            sim_data = backend.parse_results(out_file, stdout, stderr)
        else:
            return False, None

        # Build sweep from probe results
        sweep = []
        for i in range(n_probes + 1):
            f = freq_start * (10 ** (i * decades / n_probes))
            key = f'z_at_{i}'
            z = sim_data.get(key)
            if z is not None and isinstance(z, (int, float)) and z > 0:
                sweep.append({'freq_hz': f, 'impedance_ohm': abs(z)})

        return bool(sweep), sweep if sweep else None

    except Exception as exc:
        record(diagnostics, "emc_spice.run_distributed_pdn_spice", exc, "distributed PDN SPICE sweep failed")
        return False, None
    finally:
        # Cleanup
        import shutil
        try:
            shutil.rmtree(workdir, ignore_errors=True)
        except Exception:
            pass
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 321kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 321kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 321kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 197kUpdated Claude CodeCodexVerifiedInstall