Source code for jitxlib.gerber.extract.padstacks

"""Vias, component pads and the drill files they produce.

Every pad is a flash: 4.10 requires that all pads are flashed and all flashes
are pads, so nothing here ever emits a pad as a region, whatever its shape.

Hole sizes pass straight through. `Via.hole_diameter` and a `Cutout`'s
dimension are the finished hole, which is exactly what a drill file states -
XNC 2.3, "the tool diameter is the end (or finished) diameter, after plating"
- so the exporter applies no plating allowance in either direction. The
fabricator picks the bit. A value compensated here would be compensated
twice, which is how holes come back undersize.

Drill `TA.AperFunction` is the bare function name. Plating is a file
attribute by design, which is also why plated and non-plated hits cannot
share a file.

A backdrilled via is two files, per 6.6.1: the via itself is drilled to the
surface and lands in a plated file spanning the whole drilled depth, and the
stub removal lands in a non-plated file spanning only the layers that lose
their plating. The via's own start_layer/stop_layer describe the functional
span, not the drilled one.
"""

from __future__ import annotations

from dataclasses import dataclass, field, replace
from logging import getLogger

from jitx.feature import Cutout, Soldermask
from jitx.inspect import extract
from jitx.landpattern import Pad, PadShape
from jitx.run.runtime import RuntimeDesign
from jitx.shapes import Shape
from jitx.shapes.primitive import Arc, ArcPolyline, Circle, Empty, Polyline
from jitx.transform import Transform
from jitx.via import Backdrill, BackdrillSet, Via, ViaDiameter

from ..format.apertures import circle_aperture
from ..format.compat import DEFAULT as DEFAULT_COMPAT
from ..format.compat import Compat
from ..format.model import (
    Attribute,
    AttrSet,
    Contour,
    DrillContent,
    DrillFile,
    DrillFormat,
    Flash,
    Hit,
    Slot,
    Tool,
    attr,
)
from . import geometry, regions
from .components import COMPONENT_ATTRIBUTE, ComponentIndex, PinRef
from .layers import LayerModel
from .nets import NetResolver

logger = getLogger(__name__)

VIA_DRILL = attr(".AperFunction", "ViaDrill")
BACKDRILL = attr(".AperFunction", "BackDrill")
COMPONENT_DRILL = attr(".AperFunction", "ComponentDrill")
MECHANICAL_DRILL = attr(".AperFunction", "MechanicalDrill")
VIA_PAD = attr(".AperFunction", "ViaPad")
COMPONENT_PAD = attr(".AperFunction", "ComponentPad")
SMD_PAD_CU = attr(".AperFunction", "SMDPad", "CuDef")
SMD_PAD_SM = attr(".AperFunction", "SMDPad", "SMDef")


[docs] @dataclass class NpthHole: """A non-plated round hole: placed center and finished diameter, in mm.""" x: float y: float diameter: float
[docs] @dataclass class Padstacks: """What the via and pad walk produced. Args: flashes: per absolute conductor index, in emission order. Flashes go out after every region, so nothing can erase them. pieces: pad and via copper in the connectivity graph. They are not in the union: a pad contributes no region geometry, and its own holes live in its aperture, where they are transparent. drills: one file per (span, plating), keyed so the two can never merge. profile: pad cutouts of a general shape, placed. 6.6 sends these to the profile layer rather than to a drill file, and the profile file is built before this walk runs, so they are collected here and stroked in afterwards. """ flashes: dict[int, list[Flash]] = field(default_factory=dict) pieces: dict[int, list[regions.Piece]] = field(default_factory=dict) drills: dict[tuple[int, int, bool], DrillFile] = field(default_factory=dict) profile: list[geometry.Island] = field(default_factory=list)
[docs] def flash(self, layer: int, item: Flash) -> None: self.flashes.setdefault(layer, []).append(item)
[docs] def piece(self, layer: int, item: regions.Piece) -> None: self.pieces.setdefault(layer, []).append(item)
class _Drills: """The drill files a run writes, created on first hit.""" def __init__(self, model: LayerModel, into: Padstacks, format: DrillFormat) -> None: self._model = model self._files = into.drills self._format = format def file(self, span: tuple[int, int], *, plated: bool) -> DrillFile: key = (span[0], span[1], plated) found = self._files.get(key) if found is None: function = self._model.drill(span, plated=plated) found = DrillFile(replace(function, format=self._format)) self._files[key] = found return found def finalize(self) -> None: """Set each file's content field once its hits and slots are known. A capsule cutout becomes a rout, and a file holding both routs and plain hits is `Mixed`; the label cannot be chosen before the walk is over. """ for key, file in self._files.items(): if file.slots and file.hits: content = DrillContent.MIXED elif file.slots: content = DrillContent.ROUT else: content = None self._files[key] = DrillFile( replace(file.function, content=content), file.hits, file.slots )
[docs] def build( design: RuntimeDesign, model: LayerModel, nets: NetResolver, npth: list[NpthHole], components: ComponentIndex, drill_format: DrillFormat = DrillFormat.GERBER, compat: Compat = DEFAULT_COMPAT, ) -> Padstacks: """Walk vias and pads into flashes, drill hits and connectivity pieces. Args: components: the component index, for the `TO.C` and `TO.P` a component pad carries. compat: output adjustments applied to the pad apertures. """ out = Padstacks() drills = _Drills(model, out, drill_format) degenerate = 0 extra_cutouts = 0 for trace, element in design.query((Via, Pad)): if not trace.transform or not element.transform: logger.warning("Skipping %s with no transform", type(element).__name__) continue placed = trace.transform * element.transform if isinstance(element, Via): degenerate += _via(out, drills, model, nets, element, placed) else: extra_cutouts += _pad( out, drills, model, nets, element, placed, components.pin(str(trace.path)), compat, ) for hole in npth: _mechanical(drills, model, hole) if degenerate: logger.warning( "%d backdrills strip no layer and were skipped: the via already " "starts at the surface they are drilled from", degenerate, ) if extra_cutouts: logger.warning( "%d pads carry more than one cutout; only the first is drilled", extra_cutouts, ) drills.finalize() return out
# -------------------------------------------------------------------------- # vias def _backdrills(via: Via) -> tuple[Backdrill | None, Backdrill | None]: """The (top, bottom) backdrill of a via, either side possibly absent. A bare `Backdrill` is drilled from the bottom, matching jitx's own reading of the field. """ if isinstance(via.backdrill, Backdrill): return (None, via.backdrill) if isinstance(via.backdrill, BackdrillSet): return (via.backdrill.top, via.backdrill.bottom) return (None, None) def _via( out: Padstacks, drills: _Drills, model: LayerModel, nets: NetResolver, via: Via, placed: Transform, ) -> int: """One via: a drill hit on its span's file, its backdrills, and its pads. Via layer indices are absolute in the board and via instances are never flipped, unlike landpattern pads. Returns: the number of backdrills that strip no layer and were skipped. """ x, y = placed.translation net = nets.attribute(via) first, last = model.span(via.start_layer, via.stop_layer) top, bottom = _backdrills(via) # A backdrilled via is drilled to the surface and the stub is removed # afterwards, so the drilled span is wider than the functional one that # start_layer/stop_layer state. jitx's own Via -> Cutout transformer # extends the span the same way; taking start/stop verbatim here would # describe a blind via, which is a different and costlier structure. drilled = (0 if top else first, model.conductors - 1 if bottom else last) file = drills.file(drilled, plated=True) file.hits.append(Hit(x, y, Tool(via.hole_diameter, (VIA_DRILL,)), (net,))) degenerate = 0 # The backdrill span is the layers that lose their plating, not the ones # that keep it: spec 6.6.1's 8 layer example strips 8 and 7 and writes # NonPlated,8,7,Blind. The file is non-plated because the hole is drilled # after plating, which is also what keeps it out of the via's own file. for backdrill, span in ( (top, (0, first - 1)), (bottom, (last + 1, model.conductors - 1)), ): if backdrill is None: continue if span[0] > span[1]: degenerate += 1 continue stub = drills.file(span, plated=False) stub.hits.append(Hit(x, y, Tool(backdrill.diameter, (BACKDRILL,)), (net,))) for layer, diameter in ViaDiameter.stack(via, model.conductors): # float(diameter) is ViaDiameter.pad; .nfp is deliberately ignored, so # non-functional pads are always kept. That is the conservative # choice, and it is a choice rather than an oversight. size = float(diameter) index = model.normalize(layer) out.flash(index, Flash(x, y, circle_aperture(size, attrs=(VIA_PAD,)), (net,))) out.piece( index, regions.Piece(_disc(x, y, size), _net_set(nets, via), filled=False), ) return degenerate def _disc(x: float, y: float, diameter: float): import shapely return shapely.set_precision( shapely.Point(x, y).buffer(diameter / 2, quad_segs=32), regions.GRID ) def _net_set(nets: NetResolver, element: object) -> frozenset[str]: name = nets.name(element) return frozenset() if name is None else frozenset([name]) # -------------------------------------------------------------------------- # pads def _pad( out: Padstacks, drills: _Drills, model: LayerModel, nets: NetResolver, pad: Pad, placed: Transform, pin: PinRef | None = None, compat: Compat = DEFAULT_COMPAT, ) -> int: """One pad: its per-layer copper, and its hole if it has one. Args: pin: the component pin this pad is, when it belongs to a component. It decides the `TO.C` the pad carries on every layer and the `TO.P` it carries on one. Returns the number of cutouts beyond the first, which are not drilled. """ cutouts = list(extract(pad, Cutout)) stack = [ (layer, _shape_of(shape)) for layer, shape in PadShape.stack(pad, model.conductors) ] coppered = [(layer, shape) for layer, shape in stack if not _is_empty(shape)] # a pad with no copper on any layer is non-plated whatever its cutout # suggests: a mounting hole modelled as a Pad with an Empty shape plus a # Cutout would otherwise reach the fab as a plated component hole while # this exporter emits no copper for it anywhere. plated = bool(coppered) through = bool(cutouts) if cutouts: _pad_hole(drills, model, nets, pad, cutouts[0], placed, out, plated=plated) function = _pad_function(pad, through) net = nets.attribute(pad) names = _net_set(nets, pad) for layer, shape in coppered: index = _pad_layer(model, placed, layer) built = geometry.pad_aperture(shape, placed, (function,), compat) if built is None: continue aperture, point = built out.flash( index, Flash(point[0], point[1], aperture, pad_attributes(net, pin, index)) ) out.piece( index, regions.Piece(geometry.to_shapely(shape, placed).g, names, filled=False), ) return max(0, len(cutouts) - 1)
[docs] def pad_attributes(net: Attribute, pin: PinRef | None, layer: int) -> AttrSet: """The object attributes one layer of a pad carries. `.C` goes on every layer of a component pad; `.P` goes only on the copper layer the component sits on. 5.6.15 restricts `.P` to component layers and the copper layers carrying the components, so the inner-layer rings of a through-hole pad name their net and their component but not a pin - the pin is on the surface, and the ring is not it. """ if pin is None: return (net,) identity = attr(COMPONENT_ATTRIBUTE, pin.refdes) if layer != pin.layer: return (net, identity) return (net, identity, pin.attribute())
def _pad_layer(model: LayerModel, placed: Transform, layer: int) -> int: from jitx import Placement return model.normalize(Placement(placed).side.apply(layer)) def _shape_of(shape: Shape | PadShape) -> Shape: return shape.shape if isinstance(shape, PadShape) else shape def _is_empty(shape: Shape) -> bool: return isinstance(shape.to_primitive().geometry, Empty) def _pad_function(pad: Pad, through: bool): """`ComponentPad` for a through-hole pad, `SMDPad` with its definition for a surface pad. An opening larger than or equal to the copper is copper-defined, an opening strictly smaller is soldermask-defined, and a pad with no mask feature at all is copper-defined. The comparison runs on the 1 nm grid so a sub-nanometre difference cannot flip the classification. """ if through: return COMPONENT_PAD try: openings = [feature.shape for feature in extract(pad, Soldermask)] if not openings: return SMD_PAD_CU import shapely copper = geometry.to_shapely(_shape_of(pad.shape)).g mask = shapely.union_all( [geometry.to_shapely(shape).g for shape in openings], grid_size=regions.GRID, ) return SMD_PAD_CU if mask.contains(copper) else SMD_PAD_SM except Exception as error: # pragma: no cover - shape-dependent logger.debug("Could not classify the soldermask definition of a pad: %s", error) return SMD_PAD_CU def _pad_hole( drills: _Drills, model: LayerModel, nets: NetResolver, pad: Pad, cutout: Cutout, placed: Transform, into: Padstacks, *, plated: bool, ) -> None: """The drill hit, rout slot or profile opening for a pad's cutout. Which of the three it is follows 6.6 and nothing else: a circle is a drilled hole, an open polyline is a routed slot of its own width, and any other shape is an opening in the profile. """ prim = cutout.shape.to_primitive() place = geometry.Placer(placed * prim.transform) geom = prim.geometry file = drills.file(model.through, plated=plated) function = COMPONENT_DRILL if plated else MECHANICAL_DRILL attrs: AttrSet = (nets.attribute(pad),) if plated else () if isinstance(geom, Circle): x, y = place.point(0.0, 0.0) tool = Tool(place.length(2 * geom.radius), (function,)) file.hits.append(Hit(x, y, tool, attrs)) return if isinstance(geom, (Polyline, ArcPolyline)): path = geometry.to_path(cutout.shape, placed) if path is None: return start, segments = path if not _closed(geom): tool = Tool(place.length(geom.width), (function,)) file.slots.append(Slot(start, segments, tool, attrs)) return # a closed centre line is a board edge rather than a path to follow: # 6.6, "cut-outs defined by draws where the center line defines the # edge of the board does not belong to a rout file, add them to the # profile layer" into.profile.append(geometry.Island(Contour(start, segments))) return # a cutout of a general shape is not a rout either. 6.6 is explicit: a # drill file holds flashes for holes and non-closed draw/arc chains for # slots, and "for milling or cutouts (openings with a general shape): # openings in the profile layer". So it leaves the drill file entirely and # is stroked into the profile, which is already where a non-circular board # cutout goes. try: into.profile += geometry.to_islands(cutout.shape, placed) except geometry.GeometryError: # neither filled nor stroked, so there is no hole to be had from it. # Warn rather than raise: a cutout nobody can express should not cost # the whole export, and a dropped hole has to be visible in the log. logger.warning( "Pad cutout shape %s is neither a hole, a rout nor an opening; " "no material will be removed for it", type(geom).__name__, ) def _closed(geom: Polyline | ArcPolyline) -> bool: """Whether a polyline returns to where it started. A closed chain is not a slot (6.6 says a non-closed chain), and a closed path with a width is an area to remove rather than a path to follow, so it takes the profile route instead. """ points = [e for e in geom.elements if not isinstance(e, Arc)] if len(points) < 2 or len(points) != len(list(geom.elements)): return False return tuple(points[0]) == tuple(points[-1]) def _mechanical(drills: _Drills, model: LayerModel, hole: NpthHole) -> None: """A circular board cutout as a non-plated mechanical hole. No `TO.N`: the attribute is the spec's recommendation for conducting objects, and nothing in a non-plated file conducts. """ file = drills.file(model.through, plated=False) file.hits.append(Hit(hole.x, hole.y, Tool(hole.diameter, (MECHANICAL_DRILL,)), ()))