hashgraph-online/awesome-codex-plugins / plugins/aklofas/kicad-happy/skills/kicad
kicad
VerifiedAnalyze KiCad projects and PDF schematics: schematics, PCB layouts, Gerbers, footprints, symbols, netlists, and design rules. Reviews designs for bugs, traces nets, cross-references schematic to PCB, extracts BOM data, checks DRC/ERC, DFM, power trees, and regulator circuits. Every finding carries a confidence label and evidence source with trust_summary rollup. Analyzes PDF schematics from dev boards, reference designs, eval kits, and datasheets. Supports KiCad 5–10. Use whenever the user mentions .kicad_sch, .kicad_pcb, .kicad_pro, PCB design review, schematic analysis, PDF schematics, reference designs, Gerber files, DRC/ERC, netlist issues, BOM extraction, signal tracing, power budget, DFM, or wants to understand, debug, compare, or review any hardware design. Also for "check my board", "review before fab", "what's wrong with my schematic", "is this ready to order", "check my power supply", "verify this circuit", OSHWA certification readiness, or any electronics/PCB design question.
scripts/methodology_pcb.md
View on GitHub# PCB Layout Analyzer — Methodology
This document describes the analysis methodology used by `analyze_pcb.py`. It covers parsing, extraction, connectivity analysis, DFM scoring, and all physical layout analyses.
## Design Philosophy
Same as the schematic analyzer — this is a **data extraction layer**. It outputs structured JSON containing neutral observations about the physical PCB layout. An LLM (or human reviewer) consumes this alongside the schematic analysis and datasheets for design review.
The PCB analyzer focuses on what can be determined from the `.kicad_pcb` file alone, without requiring the schematic. Cross-referencing with schematic data (component types, net functions) is performed by the consuming LLM.
Detection should be thorough — an undetected DFM issue or thermal problem is a blind spot that can cost hundreds of dollars at fab. At the same time, every reported measurement (trace width, clearance, via count, distance) must be accurate, because incorrect data leads to incorrect review conclusions. The analyzer favors comprehensive extraction with precise facts over selective reporting with opinions.
---
## 1. Parsing Pipeline
The PCB analyzer uses the same `kicad_core/sexp.py` as the schematic analyzer. A `.kicad_pcb` file is parsed into nested Python lists, then traversed using `find_all`, `find_first`, `get_value`, `get_property`, and `get_at`.
### Format Compatibility
The analyzer handles both:
- **KiCad 6+**: `(footprint ...)` blocks, `(property "Reference" "R1")` syntax
- **KiCad 5**: `(module ...)` blocks, `(fp_text reference "R1")` syntax
Detection is automatic: every top-level `(footprint ...)` and `(module ...)` block is read, in file order, so a file that mixes both forms (ergogen output) yields all of its parts.
---
## 2. Core Extraction
### 2.1 Layer Stack
Extracts from `(layers ...)` block: layer numbers, names, types (signal, user, etc.), and whether visible. Used to determine copper layer count and stackup.
### 2.2 Setup / Design Rules
Extracts from `(setup ...)` block:
- Copper weight
- Default trace width, via size/drill, clearance
- Solder mask/paste margins
- Zone fill settings (thermal relief, spoke width)
- DRC settings (min track width, min drill, min clearance)
Board thickness comes from `(general (thickness ...))`, which KiCad writes with or without a `(setup)` section, and is reported as `setup.board_thickness_mm`.
### 2.3 Net Definitions
KiCad ≤9: Extracts `(net N "name")` entries — maps net numbers to names. Net numbers are used throughout the file to identify which net a pad, track, via, or zone belongs to.
KiCad 10: No net declarations section. Nets are identified by name strings directly in pads, tracks, vias, and zones. The analyzer builds a synthetic integer mapping from all unique net names for internal use.
### 2.4 Footprint Extraction
Each `(footprint ...)` or `(module ...)` block produces:
```python
{
"library": "Resistor_SMD:R_0402_1005Metric",
"reference": "R1",
"value": "10k",
"mpn": "RC0402FR-0710KL",
"x": 100.0, "y": 50.0, "angle": 90.0,
"layer": "F.Cu",
"type": "smd", # or "through_hole"
"pad_count": 2,
"pads": [...], # detailed pad list
"dnp": False,
"exclude_from_bom": False,
"courtyard": {"min_x": ..., "max_x": ..., ...},
"connected_nets": ["GND", "+3V3"],
"models_3d": ["${KICAD8_3DMODEL_DIR}/Resistor_SMD.3dshapes/R_0402.wrl"],
}
```
**Pad extraction** per footprint includes:
- Pad number, type (`smd`, `thru_hole`, `np_thru_hole`), shape (`circle`, `rect`, `oval`, `roundrect`, `custom`)
- Absolute position (footprint-relative position rotated by footprint angle, then translated)
- Size (width, height), drill diameter and shape (round vs. oval)
- Net assignment (KiCad ≤9: net number + name; KiCad 10: net name only)
- Layer list (which copper/mask/paste layers the pad spans)
- Pin function and type (from schematic cross-reference: `pinfunction`, `pintype`)
- Custom pad copper area estimation (from primitives)
- Solder mask/paste margin overrides
- Zone connection override
**SMD vs. through-hole classification**: Determined from `(attr smd)` or `(attr through_hole)`. Falls back to pad type inspection for KiCad 5 files.
**Courtyard extraction**: Bounding box computed from `fp_line`, `fp_rect`, `fp_circle`, `fp_arc` and `fp_poly` on `CrtYd` layers, transformed to absolute coordinates. Circles become 32-sided polygons and arcs (including KiCad 5 centre/angle arcs) are tessellated, so the outline chains into `courtyard_poly` for the PM-001 overlap test. F.CrtYd and B.CrtYd are chained separately and kept apart: PM-001 tests F.CrtYd against F.CrtYd and B.CrtYd against B.CrtYd, as KiCad's DRC does, whichever side each part is mounted on (a front through-hole part's B.CrtYd collides with a back-mounted part's B.CrtYd). The public `courtyard` box and `courtyard_poly` merge both layers, and the same outline on both sides counts once there. A side that draws a segment twice, or whose outline does not close (ends more than 0.02 mm apart), is malformed, as in KiCad (`malformed_courtyard`): the footprint gets no courtyard and one `diagnostics` record.
### 2.5 Track Extraction
Extracts `(segment ...)` and `(arc ...)` blocks:
- Start/end coordinates, width, layer, net
- For arcs: start, mid, and end points (3-point arc definition)
- Width distribution histogram
- Layer distribution histogram
- Arc length computed via 3-point circle reconstruction
### 2.6 Via Extraction
Extracts `(via ...)` blocks:
- Position, pad size, drill diameter, net
- Layer span (e.g., `F.Cu` to `B.Cu` for through-hole, or specific layers for blind/micro vias)
- Via type: through, blind, or micro
- Tenting status (solder mask coverage)
- Free via flag (unanchored — typically stitching or thermal)
- Size distribution histogram
### 2.7 Zone Extraction
Extracts `(zone ...)` blocks — copper pours / fills:
- Net assignment, layer(s), fill type
- Zone outline polygon and bounding box
- Filled polygon regions (actual copper after zone fill)
- Outline area (user-drawn boundary) and filled area (actual copper)
- Thermal relief settings (spoke width, gap)
- Min thickness, clearance, pad connection type
**ZoneFills spatial index**: Filled polygon coordinates are stored in a `ZoneFills` class for efficient point-in-polygon queries. This allows checking whether copper actually exists at a specific (x, y) location on a given layer. Uses bounding box pre-filtering + ray-casting for the actual test.
**Important caveat**: Zone fill data is only accurate if zones were filled in KiCad (`Edit → Fill All Zones`) before saving. Stale fills produce incorrect copper presence results.
### 2.8 Board Outline
Extracts from `Edge.Cuts` layer: `gr_line`, `gr_arc`, `gr_circle`, `gr_rect` elements. Computes bounding box from all edge points to determine board dimensions (width × height).
---
## 3. Connectivity Analysis
Two levels of connectivity checking are performed.
### 3.1 Without `--full`
A net with at least 2 pads counts as routed when it has any track, arc, via, zone or net-bearing copper graphic. `routing_complete` then means only that: the plain-mode limit is stated in the `routing_complete` description of `--schema`, and only `--full` proves completeness, through the copper graph (3.2).
### 3.2 With `--full`
`routing_complete`, `unrouted_count` and RT-001 ("Incompletely routed net N (k copper islands hold its m pads)") come from the copper connectivity graph (`pcb/connectivity.py`), a union-find over copper objects:
1. **Pads, vias and track ends** join through the same-net tracks they touch (the real pad shape, not just the pad centre), and through arcs.
2. **Vias** join the copper of every layer they span.
3. **Zones** join the pads, vias and track ends that lie in their fills (from the `ZoneFills` index), not every pad on the net.
4. **Copper graphics** — a board graphic on a copper layer with a net (KiCad 8+) joins like a track of its stroke width; a filled one also joins the same-net pads, vias and track ends inside it; a graphic with a vertex inside a same-net zone fill joins that fill.
5. **Same-number pads** of one footprint join only through copper or the footprint's jumper settings.
A net whose pads sit on more than one copper island is unrouted. A zone that has no saved fill joins nothing.
---
## 4. Per-Net Trace Length
Measures total routing length per net:
- Segment length: `√((x2-x1)² + (y2-y1)²)`
- Arc length: 3-point circle reconstruction → radius × arc angle
- Per-layer breakdown (length and segment count)
- Via count per net
Enables differential pair matching, bus length matching, and routing completeness assessment.
---
## 5. Power Net Analysis
For nets classified as power/ground (by `is_power_net_name()` and `is_ground_name()`, with the explicit `--power-rails` set when given, or else the schematic's `statistics.power_rails` when `--schematic` is given; a VPP or VM net whose pads say signal is excluded unless the rail set names it, and only on boards that carry pad pin types (KiCad 7 and later); rails the schematic knows only by their pins are not included):
- Track widths used (min, max, all widths)
- Total track length
- Track count
- Via counts and drill sizes
- Zone coverage (layers, filled area)
Reports minimum track width per power net — the current bottleneck.
---
## 6. Decoupling Placement Analysis
For each IC (`U` or `IC` reference), finds capacitors (C-prefix) within 10mm:
- Distance from the nearest IC power or ground pad to the nearest cap pad (footprint centres when pad positions are missing)
- Whether cap shares a net with the IC other than the IC's signal-pin nets (likely decoupling)
- Whether cap is on the same PCB side as the IC
- Reports closest capacitor distance per IC
---
## 7. Ground Domain Analysis
Identifies ground domain splits:
- Separate ground nets (GND, AGND, DGND, PGND, etc.)
- Components connected to each ground domain
- Ground zones per domain (layers covered)
- Components connected to multiple ground domains (potential star-ground or errors)
---
## 8. Trace Proximity Analysis
Optional analysis (enabled with `--proximity` flag). Uses a spatial grid (default 0.5mm cells) to find signal net pairs with traces running close together on the same layer:
1. Rasterize all track segments into grid cells, recording which nets occupy each cell
2. For cells with multiple signal nets, count shared-cell pairs
3. Report pairs sorted by approximate coupling length (`shared_cells × grid_size`)
4. Exclude power/ground nets (expected to be everywhere)
Useful for crosstalk risk assessment.
---
## 9. Current Capacity Analysis
Provides facts for IPC-2221 current capacity assessment:
**Per power/ground net**:
- Minimum and maximum track widths
- All track widths used
- Copper layers used
- Via count and drill sizes
- Zone coverage (layers, filled area, min thickness)
**Per via drill size**:
- Plating barrel cross-section: `A = π × d × t` (where `t = 25µm` typical plating)
- Approximate current rating at 10°C rise
**Narrow signal net flagging**: Signal nets with traces ≤0.15mm and ≥5 segments are flagged as potential current bottlenecks.
---
## 10. Thermal Analysis
### 10.1 Zone Stitching Vias
For each copper zone: counts vias on the same net, computes via density (vias/cm²), and reports drill sizes. Indicates thermal conductivity between zone layers.
### 10.2 Thermal Pad Detection
Identifies exposed/thermal pads on QFN, BGA, DFN packages:
**Detection criteria** (all must be met):
- SMD pad type
- Pad area > 4mm² (if numbered EP or 0) or > 9mm² (other pads)
- At least 2× the average pad area for the same component
- Connected to a power or ground net
For each thermal pad:
- Pad size and area
- Net assignment
- Nearby standalone vias (within 1.5× pad dimension)
- Footprint-embedded thermal via pads (thru_hole pads on same net within footprint)
### 10.3 Thermal Pad Via Adequacy
Extended analysis per thermal pad:
- Via count within pad area (rotation-aware containment check)
- Via density (vias/mm²)
- Tenting status (tented vs. untented — affects solder wicking risk)
- Recommendations based on pad area (rule of thumb: ~1 via per 1–2mm²)
---
## 11. Via Analysis
Comprehensive via characterization:
### Type Breakdown
Through-hole vs. blind vs. micro via counts and size distributions.
### Annular Ring
`(pad_size - drill) / 2` for every via. Reports min/max, distribution, and counts below common manufacturer minimums (0.125mm, 0.100mm).
### Via-in-Pad Detection
Identifies vias located within SMD pad bounding boxes. For each match: component, pad, whether same net (intentional via-in-pad vs. error).
### Fanout Pattern Detection
For BGA/QFN/QFP packages (≥16 pads), counts vias within 2mm of the component courtyard. Reports fanout via count and unique net count — useful for assessing BGA breakout routing.
### Current Capacity
Per drill size: plating barrel area and approximate current rating (25µm plating, conservative 10°C rise).
---
## 12. Layer Transition Analysis
For each signal net that uses multiple copper layers:
- Which copper layers are used
- Via count and positions
- Via layer spans
Useful for ground return path analysis — a via forces return current to find a path between reference planes. If no nearby stitching via exists, the return current loop area increases, raising EMI.
Power/ground nets are excluded (layer transitions are expected for planes).
---
## 13. Placement Analysis
### Courtyard Overlap Detection
Checks all footprint pairs for courtyard overlap. As in KiCad, each courtyard is shrunk by 0.005 mm first, so courtyards that touch or overlap by less than 0.01 mm do not collide. Reports overlapping pairs with overlap area (measured on the unshrunk courtyards).
### Edge Clearance
Checks component courtyard proximity to board Edge.Cuts outline. Reports components closer than 0.5mm to board edge. The outline is the closed Edge.Cuts loops (slots and cutouts are board edge); a part is off-board only when neither its courtyard nor a pad is on the board. When the loops do not close or a shape is drawn twice, the outline's bounding box is used and one diagnostic is recorded.
### Density Metrics
Component density per unit area, front/back distribution.
---
## 14. Silkscreen Analysis
### Board-Level Text
Extracts `gr_text` on SilkS/Silkscreen layers — project names, version labels, logos.
### Per-Footprint Reference Visibility
For each footprint: whether its reference designator is visible on the silkscreen (checks both KiCad 9 `property` nodes and KiCad 5–8 `fp_text` nodes for hide flags).
### Documentation Audit
Checks for:
- Missing board name/project identifier
- Missing revision marking (Rev, V1, V2, etc.)
- Connectors without function labels
- Switches without on/off indicators
- Polarized components (LEDs, electrolytic caps) without polarity markers on silk
- Test points without labels
---
## 15. DFM (Design for Manufacturing) Scoring
Compares actual design parameters against JLCPCB standard and advanced process limits.
### Checked Parameters
| Parameter | Standard Limit | Advanced Limit |
|-----------|---------------|----------------|
| Min track width | 0.127mm (5 mil) | 0.100mm (4 mil) |
| Min track spacing | 0.127mm (5 mil) | 0.100mm (4 mil) |
| Min via drill | 0.200mm | 0.150mm |
| Min annular ring | 0.125mm | 0.100mm |
| Board size | 100×100mm pricing threshold | — |
| Min board dimension | 10mm | — |
### Track Spacing Estimation
Approximate minimum spacing computed from endpoint-to-endpoint distances between different-net segments on the same layer. Edge-to-edge spacing: `center_distance - (width_a + width_b) / 2`. Sampling limited to 2000 segments per layer for performance.
### DFM Tier Classification
- **Standard**: All parameters within standard limits
- **Advanced**: One or more parameters require advanced process
- **Challenging**: One or more parameters exceed even advanced limits
---
## 16. Tombstoning Risk Assessment
Evaluates thermal asymmetry for small passive components (0201, 0402):
**Thermal mass analysis per pad**:
- Total copper area (track width × length) connected to each pad
- Whether pad connects to a zone (high thermal mass)
- Via proximity (vias add thermal mass on the connected side)
**Risk classification**:
- **High**: One pad on ground/power zone, other on thin signal trace (large thermal imbalance)
- **Medium**: Asymmetric track widths or via proximity
- **Low**: Reasonable thermal symmetry
**Copper ratio**: Computed as `min(pad_copper) / max(pad_copper)`. Ratios below 0.3 indicate high risk, 0.3–0.6 medium risk.
---
## 17. Thermal Pad Via Adequacy
Extended per-component assessment for packages with exposed thermal pads:
- Rotation-aware via containment (via positions transformed into pad-local coordinates)
- Via count vs. recommended count based on pad area
- Tenting status audit (untented thermal pad vias risk solder wicking)
---
## 18. Copper Presence Analysis
Uses the `ZoneFills` spatial index to check actual filled copper at pad locations across layers. For power/ground pads on ICs, verifies that zone fills actually reach the pad location (not just that a zone exists on the net).
---
## 19. Additional Extractions
### Board Metadata
Title block (title, revision, date, company), comments, board-level custom properties, paper size.
### Dimension Annotations
Designer-placed measurements: connector spacing, board dimensions, mounting hole distances. Extracts value, type, text label, and feature line endpoints.
### Groups
Designer-defined component/routing groupings (KiCad 7+).
### Net Classes
Legacy KiCad 5 net class definitions (stored in PCB file): default and named classes with clearance, track width, via size/drill settings.
---
## 20. Geometry Helpers
- **Shoelace formula**: Polygon area from vertex coordinates. Used for zone outline and fill area computation.
- **Point-in-polygon**: Ray-casting algorithm with bounding box pre-filtering. Used by ZoneFills for spatial queries.
- **Arc length (3-point)**: Reconstructs circle from start/mid/end points, computes arc angle × radius. Handles degenerate (collinear) cases as straight lines.
---
## 21. Output Structure
```json
{
"analyzer_type": "pcb",
"summary": { "total_findings": 42, "by_severity": { "error": 2, "warning": 15, "info": 25 } },
"findings": [{ "detector", "rule_id", "category", "severity", "confidence",
"summary", "description", "components", "nets", "recommendation",
"report_context": { "section", "impact", "standard_ref" }, ... }],
"kicad_version": "9.0.0",
"statistics": { "footprint_count", "smd_count", "tht_count", "copper_layers_used",
"track_segments", "via_count", "zone_count", "total_track_length_mm",
"board_width_mm", "board_height_mm", "routing_complete" },
"layers": [...],
"setup": { "board_thickness_mm", "design_rules", "defaults", ... },
"nets": { "net_number": "net_name", ... },
"net_name_to_id": { "net_name": net_number, ... },
"board_outline": { "edges", "bounding_box" },
"component_groups": { "R": {"count": 45, "references": [...]}, ... },
"footprints": [{ "reference", "value", "x", "y", "layer", "type", "connected_nets", ... }],
"tracks": { "segment_count", "arc_count", "width_distribution", "layer_distribution" },
"vias": { "count", "size_distribution", "via_analysis": { "type_breakdown", "annular_ring",
"via_in_pad", "fanout_patterns", "current_capacity" } },
"zones": [...],
"connectivity": { "routing_complete", "unrouted_count", "routed_nets", "unrouted" },
"net_lengths": [{ "net", "total_length_mm", "layers", "via_count" }],
"power_net_routing": [...],
"decoupling_placement": [...],
"ground_domains": { "domains", "multi_domain_components" },
"layer_transitions": [...],
"silkscreen": { "board_texts", "refs_visible", "hidden_refs", "documentation_warnings" },
"board_metadata": { "title", "rev", "date", ... },
"dfm_summary": { "dfm_tier", "metrics", "violation_count", "ipc_class_compliance" },
"placement_density": { ... },
"copper_presence_summary": { ... },
"board_thickness_mm": 1.6
}
```
Sections previously at top level (`thermal_analysis`, `thermal_pad_vias`, `tombstoning_risk`, `placement_analysis`, `current_capacity`, `copper_presence`, `dfm`) are now flattened into `findings[]`. Summary data is preserved in `dfm_summary`, `placement_density`, `copper_presence_summary`, and `board_thickness_mm`.
---
## 22. Known Limitations
1. **No netlist cross-check**: The PCB analyzer doesn't read the schematic. Net names and pad assignments come from the PCB file itself. Cross-referencing with the schematic (e.g., detecting unplaced components) requires running both analyzers.
2. **Zone fill staleness**: Zone fill polygons in the PCB file may be stale (not refilled after layout changes). The analyzer trusts whatever fill data is present. If zones haven't been refilled, copper presence analysis may be inaccurate.
3. **Track spacing approximation**: Minimum trace spacing is estimated from endpoint-to-endpoint distances, not full segment-to-segment geometry. The actual minimum spacing could be smaller (e.g., traces running parallel but sampled at endpoints). The DFM report notes this approximation.
4. **Zone connectivity follows the saved fills**: in the `--full` connectivity graph a zone joins only the pads, vias and track ends that lie inside the same saved fill region; a zone with no saved fill joins nothing. Stale or missing fills therefore give stale or missing joins (see 2).
5. **First-order impedance only**: `--full` emits `impedance_ohm` from a microstrip estimate (Hammerstad effective permittivity on outer layers, bulk Er on inner layers). It is not a field solve; use a stackup calculator for controlled-impedance design.
6. **Single-file analysis**: Only processes one `.kicad_pcb` file. Doesn't handle multi-board projects or panelized designs.
7. **Courtyard overlap only**: overlap is tested on the courtyard shapes (bounding boxes first, then the courtyard polygons when both parts have them, with KiCad's 0.005 mm shrink); pad and silk geometry are not compared, and parts without a courtyard are not checked.
8. **Tombstoning risk is heuristic**: Thermal mass estimation uses track width × length as a proxy. Actual thermal behavior depends on copper weight, zone connections, and thermal relief geometry that aren't fully modeled.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 321k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 321k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 321k | Updated | Claude CodeCodex | Verified | Install |
| 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: 197k | Updated | Claude CodeCodex | Verified | Install |