Source code for jitxlib.gerber.extract.components

"""Components: the X3 component layers and the index every other layer needs.

Three jobs, split so that only the first of them needs a design.

The **walk** resolves every soldered component to a `Placed` record: where it
sits, which way round it is, what its pins are and where its outline comes
from. That is the only part that touches the design API.

The **emission** turns a `Placed` into §6.9's component-layer objects - a
`ComponentMain` flash carrying the `.Cxxx` characteristics, an outline drawn
from the courtyard or the pad bounding box, and a `ComponentPin` flash at
every pin with the key pin marked. Every aperture on these layers is mandated
by 5.6.10 rather than chosen, which is precisely the kind of property worth
testing without a design in the way.

The **index** is what the rest of the extract layer reads. `TO.C` belongs on
component pads, on the soldermask openings and paste deposits of a component,
and on legend objects that belong to one, and `TO.P` belongs on component
pads - none of which is reachable without knowing which component owns a
given design path. The index answers that two ways: an exact lookup for a
pad, which also carries the pin identity, and a path-prefix lookup for
anything else a component contains.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from logging import getLogger
from typing import TypeAlias

from jitx.component import Component as JitxComponent
from jitx.feature import Courtyard, Cutout
from jitx.inspect import Trace, extract, visit
from jitx.landpattern import Landpattern, Pad, PadMapping, PadShape
from jitx.layerindex import Side as JitxSide
from jitx.net import Port
from jitx.placement import Placement
from jitx.proxy import typeof
from jitx.run.runtime import RuntimeDesign
from jitx.shapes import Shape
from jitx.transform import IDENTITY, Transform
from jitx.units import PlainQuantity, rkm_code, valuestring

from ..format.apertures import circle_aperture, polygon_aperture
from ..format.model import (
    Aperture,
    Attribute,
    AttrSet,
    Component as ComponentFunction,
    Contour,
    FilePolarity,
    Flash,
    GerberFile,
    Side,
    attr,
)
from . import geometry
from .layers import LayerModel
from .nets import NetResolver

logger = getLogger(__name__)

Pads: TypeAlias = "list[tuple[Trace, Pad]]"
"""A component's pads in `visit` tree order, which is also pin order."""

REF_LABEL = ">REF"
VALUE_LABEL = ">VALUE"
"""The label placeholders silkscreen text carries through the runtime round
trip, for an exporter to resolve against the component that owns them."""

COMPONENT_ATTRIBUTE = ".C"
PIN_ATTRIBUTE = ".P"

MAIN = attr(".AperFunction", "ComponentMain")
PIN = attr(".AperFunction", "ComponentPin")

MAIN_DIAMETER = 0.300
"""5.6.10 mandates `%ADDnnC,0.300*%` for ComponentMain in millimeters."""

PIN_DIAMETER = 0.100
"""5.6.10 mandates `%ADDnnC,0.1*%` for every pin that is not the key pin."""

KEY_PIN_DIAMETER = 0.360
"""5.6.10 mandates `%ADDnnP,0.360X4X0.0*%`, a diamond, for the key pin."""

OUTLINE_WIDTH = 0.100
"""5.6.10 mandates `%ADDnnC,0.100*%` for every ComponentOutline draw."""

COURTYARD = "Courtyard"
FOOTPRINT = "Footprint"
"""The two `ComponentOutline` types this exporter can source.

`Courtyard` comes from `jitx.feature.Courtyard`, which is documented as land
pattern bounds and whose `__post_init__` rejects polylines, so it is always
closed. The bounding box of the pads is labeled `Footprint` and not
`Courtyard` because that is what it is: an approximation from the copper,
with no keep-out margin in it. Body and lead-to-lead outlines have no source
in the design API and are not emitted.
"""

TH = "TH"
SMD = "SMD"
"""The two `.CMnt` values a JITX design can distinguish.

`Pressfit` and `Other` are the rest of 5.6.16's enumeration and have no
source here: a pad with a cutout is through-hole and a pad without one is
surface mount, which is the whole of what the design says.
"""


[docs] def main_aperture() -> Aperture: """The mandated `ComponentMain` aperture.""" return circle_aperture(MAIN_DIAMETER, attrs=(MAIN,))
[docs] def pin_aperture(*, key: bool) -> Aperture: """The mandated `ComponentPin` aperture: a diamond for the key pin.""" if key: return polygon_aperture(KEY_PIN_DIAMETER, 4, 0.0, attrs=(PIN,)) return circle_aperture(PIN_DIAMETER, attrs=(PIN,))
[docs] def pin_attribute(refdes: str, number: str, function: str | None) -> Attribute: """`TO.P,<refdes>,<number>[,<function>]`, one spelling for both layers. The optional third field is the pin function. It is emitted wherever the design knows it, on the component layer and on the copper layer alike, so the two cannot disagree about what a pin is. """ if function is None: return attr(PIN_ATTRIBUTE, refdes, number) return attr(PIN_ATTRIBUTE, refdes, number, function)
[docs] def outline_aperture(kind: str) -> Aperture: """The mandated outline aperture, carrying its outline type.""" return circle_aperture( OUTLINE_WIDTH, attrs=(attr(".AperFunction", "ComponentOutline", kind),) )
# -------------------------------------------------------------------------- # what the walk resolves a component to
[docs] @dataclass(frozen=True) class Pin: """One component pin, placed. Args: number: the pin number, which 5.6.15 allows to be any name. net: the `TO.N` attribute for the pin. `.N` is optional on a ComponentPin, but a component layer that names the net at every pin is the one a pick-and-place check can actually use. function: the pin function, when the design says what it is. 5.6.15 strongly recommends it alongside the number: it is less error-prone than a number and the redundancy is what catches a reversed diode or electrolytic. """ number: str x: float y: float net: Attribute function: str | None = None
[docs] def attribute(self, refdes: str) -> Attribute: """`TO.P,<refdes>,<number>[,<function>]`.""" return pin_attribute(refdes, self.number, self.function)
[docs] def ref(self, refdes: str, layer: int) -> PinRef: """The copper-layer view of this pin. The copper layer's `.P` is derived from the component layer's pin rather than resolved a second time, so the two files cannot describe one pin differently - which they could while the number and the function were looked up independently on each side. """ return PinRef(refdes, self.number, layer, self.function)
[docs] @dataclass(frozen=True) class Outline: """A component outline and which of 5.6.10's four types it is.""" kind: str contours: tuple[Contour, ...]
[docs] @dataclass(frozen=True) class Placed: """One component, resolved to everything its component layer needs. Args: rotation: the `.CRot` angle, already converted to the Gerber convention by `rotation`. mount: the `.CMnt` value, TH or SMD. footprint: the `.CFtp` land pattern name. pins: in pin order. The first is the key pin. """ refdes: str side: Side x: float y: float rotation: float mount: str footprint: str pins: tuple[Pin, ...] = () outline: Outline | None = None mpn: str | None = None manufacturer: str | None = None value: str | None = None
[docs] def identity(self) -> Attribute: """`TO.C,<refdes>`, which every object of this component carries.""" return attr(COMPONENT_ATTRIBUTE, self.refdes)
[docs] def characteristics(self) -> AttrSet: """The `.Cxxx` attributes of the ComponentMain flash. `.CHgt`, `.CPgN`, `.CPgD`, `.CLbN`, `.CLbD` and `.CSup` are the rest of 5.6.16 and have no source in the design API, so they are omitted rather than guessed at. The others are only valid on ComponentMain - 5.6.16 says they are ignored elsewhere - so nothing else carries them. """ out = [ attr(".CRot", angle(self.rotation)), attr(".CMnt", self.mount), attr(".CFtp", self.footprint), ] if self.mpn: out.append(attr(".CMPN", self.mpn)) if self.manufacturer: out.append(attr(".CMfr", self.manufacturer)) if self.value: out.append(attr(".CVal", self.value)) return tuple(out)
[docs] def emit(file: GerberFile, part: Placed) -> None: """Write one component onto a component layer. Order follows 6.9's worked example: the main flash, then the outline, then the pins with the key pin first. `.C` goes on the flash and on every outline draw, which 5.6.14 requires and is what links an outline back to the component it belongs to. """ identity = part.identity() file.add( Flash(part.x, part.y, main_aperture(), (identity, *part.characteristics())) ) if part.outline is not None: aperture = outline_aperture(part.outline.kind) for contour in part.outline.contours: for stroke in geometry.stroke_contour(contour, aperture, (identity,)): file.add(stroke) for number, pin in enumerate(part.pins): file.add( Flash( pin.x, pin.y, pin_aperture(key=number == 0), (pin.attribute(part.refdes), pin.net), ) )
[docs] def angle(value: float) -> str: """A `.CRot` decimal with no trailing zeros, since people read it.""" text = f"{value:.4f}".rstrip("0").rstrip(".") return "0" if text in ("", "-0") else text
[docs] def rotation(placed: Transform) -> float: """The `.CRot` angle of a placement, in degrees CCW viewed from the top. 5.6.16 defines rotation zero for a top-side component as IPC-7351B's, and for a bottom-side component by flipping that zero along the X axis, which is the scale `S(1,-1)`. A JITX bottom placement is `T * R(r) * S(-1,1)` and `S(-1,1) = R(180) * S(1,-1)`, so the same placement reads as `T * R(r + 180) * S(1,-1)` against the Gerber zero: a bottom component's angle is its own rotation plus a half turn. The mirror is read off the composed transform and nowhere else, which is the rule the whole extract layer follows: a bottom-side `Placement` already carries its mirror, so anything that applies a second side flip composes two mirrors into none. """ place = geometry.Placer(placed) return (place.rotation + 180.0 if place.mirrored else place.rotation) % 360.0
# -------------------------------------------------------------------------- # the index
[docs] @dataclass(frozen=True) class PinRef: """What a pad on a copper layer needs to name itself. Args: layer: the absolute conductor index the component sits on. `.P` is restricted to component layers and the copper layers carrying the components, so the inner-layer rings of a through-hole pad must not carry it even though they are the same pad. """ refdes: str number: str layer: int function: str | None = None
[docs] def attribute(self) -> Attribute: """`TO.P,<refdes>,<number>[,<function>]`.""" return pin_attribute(self.refdes, self.number, self.function)
[docs] @dataclass class ComponentIndex: """The component layers, plus who owns what in the design tree. Args: files: one file per populated side. pins: pad design path to the pin it is, for `TO.P`. owners: component design path to reference designator, for the `TO.C` that mask, paste and legend objects carry. """ files: dict[Side, GerberFile] = field(default_factory=dict) pins: dict[str, PinRef] = field(default_factory=dict) owners: dict[str, str] = field(default_factory=dict) labels: dict[str, dict[str, str]] = field(default_factory=dict)
[docs] def ordered(self) -> list[GerberFile]: """The component files, top before bottom.""" return [self.files[side] for side in Side if side in self.files]
[docs] def pin(self, path: str) -> PinRef | None: """The pin identity of a pad, by its full design path.""" return self.pins.get(path)
[docs] def owner(self, path: str) -> str | None: """The reference designator of the component containing a path. The longest matching component path wins, so a component nested in another attributes to the inner one. """ return self._innermost(self.owners, path)
[docs] def labels_for(self, path: str) -> dict[str, str]: """The label substitutions for a feature at a design path. Taken from the innermost component enclosing it, the same rule `owner` uses. Empty when no exported component owns the feature. """ return self._innermost(self.labels, path) or {}
@staticmethod def _innermost[T](owned: dict[str, T], path: str) -> T | None: best: str | None = None for candidate in owned: if _contains(candidate, path) and ( best is None or len(candidate) > len(best) ): best = candidate return None if best is None else owned[best]
[docs] def component_attribute(self, path: str) -> Attribute | None: """`TO.C` for an object at a design path, when a component owns it.""" refdes = self.owner(path) return None if refdes is None else attr(COMPONENT_ATTRIBUTE, refdes)
def _contains(owner: str, path: str) -> bool: """Whether `path` is `owner` or lies under it. A plain `startswith` would put `circuit.u1a` under `circuit.u1`, so the character after the prefix has to open a new step: `.` for an attribute and `[` for an index or a mapping key. """ if path == owner: return True return path.startswith(owner) and path[len(owner) : len(owner) + 1] in (".", "[") # -------------------------------------------------------------------------- # the walk
[docs] def build( design: RuntimeDesign, model: LayerModel, nets: NetResolver ) -> ComponentIndex: """Walk the soldered components into component layers and the index. Runs before the copper, feature and padstack walks: they attach `TO.C` and `TO.P` off the index it returns, so there is no order in which it can run beside them. """ out = ComponentIndex() packages: dict[type, str] = {} taken: set[str] = set() unknown = 0 unplaced = 0 for trace, comp in design.query(JitxComponent): if comp.soldered is False: continue if not trace.transform or not comp.transform: unplaced += 1 logger.warning("Skipping unplaced component %s", trace.path) continue placed = trace.transform * comp.transform side = _side_of(placed) # the refdes fallback numbers once across the design, not per file: a # per-file counter puts a UNK0 in both the top and the bottom layer refdes = comp.reference_designator if not refdes: refdes = f"UNK{unknown}" unknown += 1 pads = list(visit(comp, Pad)) functions = pin_functions(comp) x, y = placed.translation part = Placed( refdes=refdes, side=side, x=x, y=y, rotation=rotation(placed), mount=TH if _through(pads) else SMD, footprint=_package(packages, taken, comp), pins=tuple(_pins(placed, pads, nets, functions)), outline=_outline(comp, placed, side, pads), mpn=_text(comp.mpn), manufacturer=_text(comp.manufacturer), value=_value(comp.value), ) emit(_file(out, side, model), part) out.owners[str(trace.path)] = refdes out.labels[str(trace.path)] = _labels(refdes, comp.value) layer = 0 if side is Side.TOP else model.conductors - 1 for (ptrace, _), pin in zip(pads, part.pins, strict=True): out.pins[f"{trace.path}.{ptrace.path}"] = pin.ref(refdes, layer) if unplaced: logger.warning("%d components had no placement and were skipped", unplaced) if unknown: logger.warning( "%d components had no reference designator and were numbered UNK0 " "upwards across the whole design", unknown, ) return out
def _file(out: ComponentIndex, side: Side, model: LayerModel) -> GerberFile: found = out.files.get(side) if found is None: index = 1 if side is Side.TOP else model.conductors found = GerberFile(ComponentFunction(index, side), FilePolarity.POSITIVE) out.files[side] = found return found def _side_of(placed: Transform) -> Side: side = placed.side if isinstance(placed, Placement) else JitxSide.Top return Side.TOP if side == JitxSide.Top else Side.BOTTOM def _through(pads: Pads) -> bool: return any(list(extract(pad, Cutout)) for _, pad in pads) def _text(value: object) -> str | None: return None if value is None else str(value) def _labels(refdes: str, value: str | PlainQuantity | None) -> dict[str, str]: """The `>REF` and `>VALUE` substitutions for one component. Silkscreen text keeps these placeholders through the runtime round trip - the reverse-flow linker restores them deliberately, so an exporter can tell a label apart from raw text - and they are resolved against the component that owns the feature. """ out = {REF_LABEL: refdes} rendered = _value(value) if rendered is not None: out[VALUE_LABEL] = rendered return out def _value(value: str | PlainQuantity | None) -> str | None: """A component value, for `.CVal` and for a `>VALUE` label alike. `jitx.units.valuestring` is the common best-practice conversion and `rkm_code` the rendering it takes, so this is the toolchain's own spelling rather than a local one; both the attribute and the ink go through it, so a CAM tool's reading and the board cannot disagree. RKM is the right rendering for both. It is compact and pure ASCII (`4k7`, `100n`), which matters twice over: the legend font is a stroke font with a limited glyph table, so the micro and ohm signs the default rendering emits come out as gaps, and 5.6.11's own worked example spells `.CVal` the same compact way - `%TO.CVal,4K7*%`, where the default would give an escaped `4700 \u03a9`. (The spec example uses IEC 60062's uppercase resistance spelling and this writes the lowercase one; the standard defines both and the difference is cosmetic.) """ return None if value is None else valuestring(value, rkm_code)
[docs] def pin_functions(comp: JitxComponent) -> dict[Pad, str]: """Each pad's pin function: the path of the port it is mapped to. A pad maps to exactly one port while a port may map to several pads, so the pad side of the relation is a function and several pads can share one name - which is what a multi-pad ground looks like and is correct. `PadMapping` already keeps the inverse, including the default mapping the runtime synthesizes when a component declares none, so nothing is computed here that the design does not already hold. The port paths come from a walk rooted at the component, so a bundle member reads as its own dotted path (`VIN.Vp`) rather than as the bundle. """ ports = {port: str(trace.path) for trace, port in visit(comp, Port)} out: dict[Pad, str] = {} for mapping in extract(comp, PadMapping): for pad, port in mapping.inverse().items(): path = ports.get(port) if path is not None: out[pad] = path return out
def _pins( placed: Transform, pads: Pads, nets: NetResolver, functions: dict[Pad, str], ) -> list[Pin]: """Every pad placed, in tree order. Tree order is pin order and its first entry is the key pin. The design API exposes no pin-1 marker, and 5.6.10 wants one pin distinguished rather than the right one guessed, so tree order stands until there is a better source. """ out: list[Pin] = [] for number, (ptrace, pad) in enumerate(pads): x, y = (placed * _local(ptrace, pad)).translation out.append( Pin( _pin_name(ptrace.path, number), x, y, nets.attribute(pad), functions.get(pad), ) ) return out def _local(ptrace: Trace, pad: Pad) -> Transform: return (ptrace.transform or IDENTITY) * (pad.transform or IDENTITY) def _pin_name(path: object, fallback: int) -> str: leaf = str(path).rsplit(".", 1)[-1] return leaf or str(fallback) def _package(packages: dict[type, str], taken: set[str], comp: JitxComponent) -> str: """The `.CFtp` footprint name for a component. Keyed on the landpattern's true class rather than on a name: landpatterns arrive Proxy-wrapped, so `typeof` is what gets past the proxy, and the class object keeps same-named classes from different modules distinct. A component with no landpattern falls back to its own class. The name is the class name unchanged. Gerber field syntax escapes what it has to at emission, so there is nothing to scrub here, and scrubbing would only create collisions to disambiguate. """ landpattern = next(iter(extract(comp, Landpattern)), None) cls = typeof(landpattern if landpattern is not None else comp) found = packages.get(cls) if found is not None: return found name = cls.__name__ suffix = 1 while name in taken: suffix += 1 name = f"{cls.__name__}_{suffix}" packages[cls] = name taken.add(name) return name # -------------------------------------------------------------------------- # outlines def _outline( comp: JitxComponent, placed: Transform, side: Side, pads: Pads ) -> Outline | None: """The component outline: its courtyard, or the pad bounding box. A courtyard is the primary path and most components have one, since `jitxlib-landpatterns` generates them. The fallback is labeled `Footprint` rather than `Courtyard` because a box around the pads is not a courtyard: it carries no clearance and it stops at the copper. """ contours: list[Contour] = [] for ctrace, courtyard in visit(comp, Courtyard): total = placed * (ctrace.transform or IDENTITY) # a courtyard is a SurfaceFeature, so its side is relative to the # placement; one resolving to the other side belongs to neither this # component layer nor any other, and is dropped rather than drawn on # the side the component is not on if geometry.surface_side(total, courtyard.side) is not side: continue contours += [ island.outer for island in geometry.to_islands(courtyard.shape, total) ] if contours: return Outline(COURTYARD, tuple(contours)) box = _pad_bounds(placed, pads) if box is None: return None minx, miny, maxx, maxy = box ring = geometry.ring_contour( [(minx, miny), (maxx, miny), (maxx, maxy), (minx, maxy)], ccw=True ) return Outline(FOOTPRINT, (ring,)) def _pad_bounds( placed: Transform, pads: Pads ) -> tuple[float, float, float, float] | None: """The bounding box of every pad's copper, in board coordinates.""" boxes: list[tuple[float, float, float, float]] = [] for ptrace, pad in pads: total = placed * _local(ptrace, pad) try: bounds = geometry.to_shapely(_pad_shape(pad), total).g.bounds except Exception as error: # pragma: no cover - shape-dependent logger.debug("Pad shape has no bounds for the footprint box: %s", error) continue if bounds: boxes.append(bounds) if not boxes: return None return ( min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes), ) def _pad_shape(pad: Pad) -> Shape: shape = pad.shape return shape.shape if isinstance(shape, PadShape) else shape