Source code for jitxlib.gerber.extract.nets

"""Resolve JITX nets to the `TO.N` attribute every conducting object carries.

The spec recommends `.N` on all copper objects because "the absence of the
.N attribute does not mean there is no net and is therefore ambiguous", so
copper that is genuinely on no net gets the reserved empty value `%TO.N,*%`
rather than no attribute at all.

Net names are not mangled here. The X2 field escaping in `format.model`
already turns every reserved character into a `\\uXXXX` escape, so a name
reaches the file intact and two names that differ cannot be collapsed into
one by a sanitizer.
"""

from __future__ import annotations

from collections.abc import Sequence
from hashlib import sha256
from logging import getLogger

from jitx.landpattern import Pad
from jitx.run.runtime import RuntimeDesign
from jitx.via import Via

from ..format.model import Attribute, attr

logger = getLogger(__name__)

NET_ATTRIBUTE = ".N"
EMPTY_NET = ""
"""The reserved `%TO.N,*%` value: an object genuinely on no net."""

SYNTHETIC_PREFIX = "N$"
"""Prefix for a name synthesized for a net object that arrived unnamed."""


[docs] def net_attribute(names: Sequence[str | None]) -> Attribute: """`TO.N` for an object spanning a known set of nets. An empty set, or one holding only unconnected copper, is the reserved empty value: the spec calls omitting the attribute ambiguous, so netless copper says so explicitly rather than staying silent. Several names is 5.6.13's list form, which describes an object whose parts lie on different nets. """ found = sorted({name for name in names if name is not None}) return attr(NET_ATTRIBUTE, *(found or [EMPTY_NET]))
[docs] class NetResolver: """Net names for design objects, and the `TO.N` attribute for them. Two situations look identical at the call site and are kept apart, which is the whole reason this class exists: - **No net object at all** is unconnected copper - tooling pads, isolated islands, logos - and takes the reserved empty value. - **A net object with no name** should not occur, because connected nets are named by the runtime one way or another. Collapsing it to the empty value would assert that connected copper is isolated, which is both wrong and invisible downstream, so a deterministic name is synthesized and the occurrences are counted into the run log. """ def __init__(self, design: RuntimeDesign) -> None: self._design = design self._index = design.nets self._synthetic: dict[int, str] | None = None self._unnamed = 0
[docs] def name(self, element: object) -> str | None: """The net name for an element, or None when it is on no net. None means the design has no net object for the element, which is what the empty `.N` value describes. It never means "unnamed". """ net = self._index.find(element) if net is None: return None if net.name is not None: return net.name self._unnamed += 1 return self._synthesize(net)
[docs] def attribute(self, element: object) -> Attribute: """The `TO.N` attribute for one conducting object.""" return self.names_attribute([self.name(element)])
[docs] def names_attribute(self, names: Sequence[str | None]) -> Attribute: """`TO.N` for an object spanning a known set of nets.""" return net_attribute(names)
[docs] def report(self) -> None: """Log the defensive branch if it fired. A synthesized name is not an error, but it means the runtime handed back a net with no name, so it should be visible in the run log rather than silently absorbed into the output. """ if self._unnamed: logger.warning( "%d references to net objects with no name; synthesized " "deterministic %s names for them", self._unnamed, SYNTHETIC_PREFIX, )
def _synthesize(self, net: object) -> str: """A name derived from the net's own membership. Deterministic has to mean stable across design edits and not merely across reruns of one export, or two exports of the same board disagree about which net is which. The name is a digest of the paths of the pads and vias on the net, so it moves only when that net's own membership does - unlike an index assigned in walk order, which every added pad elsewhere in the design would shift. """ if self._synthetic is None: self._synthetic = self._member_digests() found = self._synthetic.get(id(net)) if found is not None: return found # a net with no members at all has nothing to derive a name from; it # cannot reach a file either, since only members carry attributes return f"{SYNTHETIC_PREFIX}anon" def _member_digests(self) -> dict[int, str]: members: dict[int, list[str]] = {} for trace, element in self._design.query((Pad, Via)): net = self._index.find(element) if net is None or net.name is not None: continue members.setdefault(id(net), []).append(str(trace.path)) return { key: SYNTHETIC_PREFIX + sha256("\n".join(sorted(paths)).encode("utf-8")).hexdigest()[:8].upper() for key, paths in members.items() }