jitxlib-odb 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ """Export ODB++ Design jobs from JITX designs.
2
+
3
+ The package splits in two: `format` is a standalone ODB++ writer with no JITX
4
+ dependencies, and `extract` populates the format model from a captured JITX
5
+ RuntimeDesign. The `plugin` module registers the jitx export entry point.
6
+ """
@@ -0,0 +1,5 @@
1
+ """Populate the ODB++ format model from a captured JITX RuntimeDesign.
2
+
3
+ All JITX geometry stays in mm inside this package; the mm-to-inch conversion
4
+ happens exactly once, in geometry.Placer, at the format-model boundary.
5
+ """
@@ -0,0 +1,311 @@
1
+ """Component enumeration and the eda/data recorder.
2
+
3
+ Components are discovered with query(Component); their pads are visited in
4
+ tree order, which defines the pin/toeprint indices. Padstack and copper
5
+ builders report the features they emit through EdaRecorder, which patches the
6
+ eda/data FID layer indices once the matrix (and thus the LYR list) is final.
7
+
8
+ Verified API surface (see the M3 spike): reference_designator is assigned by
9
+ the runtime during capture; landpatterns arrive Proxy-wrapped, so their true
10
+ type comes from jitx.proxy.typeof; nets resolve directly on pad objects.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass, field
16
+ from logging import getLogger
17
+
18
+ from jitx.component import Component
19
+ from jitx.feature import Cutout
20
+ from jitx.inspect import extract, visit
21
+ from jitx.landpattern import Landpattern, Pad, PadShape
22
+ from jitx.layerindex import Side
23
+ from jitx.placement import Placement
24
+ from jitx.proxy import typeof
25
+ from jitx.refpath import RefPath
26
+
27
+ from jitx.run.runtime import RuntimeDesign
28
+ from jitx.transform import IDENTITY
29
+ from jitx.units import PlainQuantity, rkm_code
30
+
31
+ from ..format.model import (
32
+ ComponentRecord,
33
+ ComponentsFile,
34
+ EdaData,
35
+ EdaNet,
36
+ Fid,
37
+ Package,
38
+ PackagePin,
39
+ Subnet,
40
+ Toeprint,
41
+ legal_name,
42
+ )
43
+ from .geometry import MM_PER_INCH, to_contours
44
+ from .nets import NetIndex
45
+
46
+ logger = getLogger(__name__)
47
+
48
+ COMP_TOP = "comp_+_top"
49
+ COMP_BOT = "comp_+_bot"
50
+
51
+ REF_LABEL = ">REF"
52
+ VALUE_LABEL = ">VALUE"
53
+
54
+
55
+ @dataclass
56
+ class Pin:
57
+ """One component pin: its eda TOP subnet plus the TOP record data."""
58
+
59
+ subnet: Subnet
60
+ net: int
61
+ toeprint: Toeprint
62
+
63
+
64
+ @dataclass
65
+ class ComponentIndex:
66
+ """Components split per side, with pads keyed by their full design path
67
+ so the padstack builder can attribute features to pins."""
68
+
69
+ files: dict[str, ComponentsFile] = field(default_factory=dict)
70
+ packages: list[Package] = field(default_factory=list)
71
+ pins: dict[str, Pin] = field(default_factory=dict)
72
+ # label substitutions per component, keyed by the component's path
73
+ labels: dict[RefPath, dict[str, str]] = field(default_factory=dict)
74
+
75
+ @property
76
+ def layer_names(self) -> list[str]:
77
+ return list(self.files)
78
+
79
+ def labels_for(self, path: RefPath) -> dict[str, str]:
80
+ """Label placeholder substitutions (>REF, >VALUE) for a feature at
81
+ `path`, taken from the innermost component enclosing it. Empty when no
82
+ exported component owns the feature."""
83
+ for end in range(len(path), 0, -1):
84
+ found = self.labels.get(path[:end])
85
+ if found is not None:
86
+ return found
87
+ return {}
88
+
89
+
90
+ class EdaRecorder:
91
+ """Collects SNT subnets and their FIDs during feature emission. FID layer
92
+ references are recorded by name and patched to LYR indices at assembly."""
93
+
94
+ def __init__(self, nets: NetIndex, components: ComponentIndex) -> None:
95
+ self._nets = nets
96
+ self._components = components
97
+ # net index -> ordered subnets
98
+ self._subnets: dict[int, list[Subnet]] = {}
99
+ self._trc: dict[int, Subnet] = {}
100
+ self._layer_names: list[tuple[Fid, str]] = []
101
+
102
+ def _register(self, net: int, subnet: Subnet) -> Subnet:
103
+ self._subnets.setdefault(net, []).append(subnet)
104
+ return subnet
105
+
106
+ def via(self, net: int) -> Subnet:
107
+ """A new VIA subnet on the net."""
108
+ return self._register(net, Subnet("VIA"))
109
+
110
+ def trace(self, net: int) -> Subnet:
111
+ """The net's shared TRC subnet, created on first use."""
112
+ subnet = self._trc.get(net)
113
+ if subnet is None:
114
+ subnet = self._trc[net] = self._register(net, Subnet("TRC"))
115
+ return subnet
116
+
117
+ def pin(self, path: str) -> Pin | None:
118
+ """The component pin for a pad's full design path, if any."""
119
+ return self._components.pins.get(path)
120
+
121
+ def register_pin(self, net: int, pin: Pin) -> None:
122
+ self._register(net, pin.subnet)
123
+
124
+ def fid(self, subnet: Subnet, kind: str, layer_name: str, feature: int) -> None:
125
+ """Record one feature reference; the layer index is patched later."""
126
+ fid = Fid(kind, -1, feature)
127
+ subnet.fids.append(fid)
128
+ self._layer_names.append((fid, layer_name))
129
+
130
+ def assemble(self, layers: list[str]) -> EdaData:
131
+ """Build the EdaData with LYR indices patched and TOP subnet indices
132
+ filled into the toeprint records."""
133
+ index = {name: i for i, name in enumerate(layers)}
134
+ for fid, name in self._layer_names:
135
+ fid.layer = index[name]
136
+ by_subnet = {id(pin.subnet): pin for pin in self._components.pins.values()}
137
+ nets = []
138
+ for net_num, name in enumerate(self._nets.names):
139
+ subnets = self._subnets.get(net_num, [])
140
+ nets.append(EdaNet(name, subnets))
141
+ for position, subnet in enumerate(subnets):
142
+ pin = by_subnet.get(id(subnet))
143
+ if pin is not None:
144
+ pin.toeprint.subnet = position
145
+ pin.toeprint.net = net_num
146
+ return EdaData(layers, nets, self._components.packages)
147
+
148
+
149
+ def build_components(design: RuntimeDesign, nets: NetIndex) -> ComponentIndex:
150
+ """Enumerate soldered components into per-side components files, package
151
+ definitions, and the pad-path index used by the padstack builder."""
152
+ out = ComponentIndex()
153
+ packages: dict[type, int] = {}
154
+
155
+ for trace, comp in design.query(Component):
156
+ if comp.soldered is False:
157
+ continue
158
+ if not trace.transform or not comp.transform:
159
+ logger.warning("Skipping unplaced component %s", trace.path)
160
+ continue
161
+ placement = trace.transform * comp.transform
162
+ side = placement.side if isinstance(placement, Placement) else Side.Top
163
+ layer_name = COMP_TOP if side == Side.Top else COMP_BOT
164
+ file = out.files.setdefault(layer_name, ComponentsFile())
165
+
166
+ pads = list(visit(comp, Pad))
167
+ pkg_ref = _package(out, packages, comp, pads)
168
+
169
+ refdes = comp.reference_designator or f"UNK{len(file.records)}"
170
+ part = legal_name(str(comp.mpn or typeof(comp).__name__))
171
+ properties: list[tuple[str, str]] = []
172
+ if comp.mpn:
173
+ properties.append(("PART_NO", str(comp.mpn)))
174
+ if comp.manufacturer:
175
+ properties.append(("MANUFACTURER", str(comp.manufacturer)))
176
+ if comp.value is not None:
177
+ properties.append(("VALUE", _value_text(comp.value)))
178
+
179
+ # .comp_mount_type options: Other;SMT;THMT;PressFit
180
+ through = any(list(extract(pad, Cutout)) for _, pad in pads)
181
+ record = ComponentRecord(
182
+ package=pkg_ref,
183
+ x=placement.translation[0] / MM_PER_INCH,
184
+ y=placement.translation[1] / MM_PER_INCH,
185
+ rotation=(-placement.rotation) % 360.0,
186
+ mirror=side == Side.Bottom,
187
+ name=refdes,
188
+ part=part,
189
+ properties=properties,
190
+ attributes=[(".comp_mount_type", 2 if through else 1)],
191
+ )
192
+ cmp_num = len(file.records)
193
+ file.records.append(record)
194
+
195
+ for pin_num, (ptrace, pad) in enumerate(pads):
196
+ local = (ptrace.transform or IDENTITY) * (pad.transform or IDENTITY)
197
+ placed = placement * local
198
+ net = nets.index_for(pad)
199
+ toeprint = Toeprint(
200
+ pin=pin_num,
201
+ x=placed.translation[0] / MM_PER_INCH,
202
+ y=placed.translation[1] / MM_PER_INCH,
203
+ rotation=(-placed.rotation) % 360.0,
204
+ mirror=side == Side.Bottom,
205
+ net=net,
206
+ subnet=0,
207
+ name=_pin_name(ptrace.path, pin_num),
208
+ )
209
+ record.toeprints.append(toeprint)
210
+ subnet = Subnet(
211
+ "TOP",
212
+ side="T" if side == Side.Top else "B",
213
+ component=cmp_num,
214
+ toeprint=pin_num,
215
+ )
216
+ out.pins[f"{trace.path}.{ptrace.path}"] = Pin(subnet, net, toeprint)
217
+
218
+ labels = {REF_LABEL: refdes}
219
+ if comp.value is not None:
220
+ labels[VALUE_LABEL] = _label_text(comp.value)
221
+ out.labels[trace.path] = labels
222
+ return out
223
+
224
+
225
+ def _value_text(value: str | PlainQuantity) -> str:
226
+ """Render a component value the way the jitx translate layer does, so the
227
+ exported text agrees with what the rest of the toolchain shows.
228
+
229
+ `str()` on a quantity gives `1e-07 farad`; `:g~P` gives `100 nF` for a
230
+ value written with the prefix its author meant."""
231
+ if isinstance(value, str):
232
+ return value
233
+ return f"{value:g~P}"
234
+
235
+
236
+ def _label_text(value: str | PlainQuantity) -> str:
237
+ """Render a component value for a silkscreen label.
238
+
239
+ RKM codes are compact and pure ASCII, which matters on silkscreen and in
240
+ ODB++ text records; the `:g~P` form used for the VALUE property emits the
241
+ micro and ohm signs."""
242
+ if isinstance(value, str):
243
+ return value
244
+ return rkm_code(value)
245
+
246
+
247
+ def _pin_name(path: object, fallback: int) -> str:
248
+ leaf = str(path).rsplit(".", 1)[-1]
249
+ return legal_name(leaf) if leaf else str(fallback)
250
+
251
+
252
+ def _package(
253
+ out: ComponentIndex,
254
+ packages: dict[type, int],
255
+ comp: Component,
256
+ pads: list,
257
+ ) -> int:
258
+ """The package index for a component, created from its landpattern (pad
259
+ layout in component-local coordinates) on first sight.
260
+
261
+ Packages are keyed by the landpattern's true class (typeof unwraps the
262
+ Proxy), falling back to the component class when there is no landpattern;
263
+ same-named classes from different modules stay distinct."""
264
+ landpattern = next(iter(extract(comp, Landpattern)), None)
265
+ cls = typeof(landpattern if landpattern is not None else comp)
266
+ existing = packages.get(cls)
267
+ if existing is not None:
268
+ return existing
269
+
270
+ pins: list[PackagePin] = []
271
+ centers: list[tuple[float, float]] = []
272
+ bounds: list[tuple[float, float]] = []
273
+ for pin_num, (ptrace, pad) in enumerate(pads):
274
+ local = (ptrace.transform or IDENTITY) * (pad.transform or IDENTITY)
275
+ x, y = local.translation
276
+ centers.append((x / MM_PER_INCH, y / MM_PER_INCH))
277
+ shape = pad.shape.shape if isinstance(pad.shape, PadShape) else pad.shape
278
+ outline = to_contours(shape, transform=local)
279
+ for contour in outline:
280
+ bounds.append(contour.start)
281
+ bounds.extend((seg.x, seg.y) for seg in contour.segments)
282
+ pins.append(
283
+ PackagePin(
284
+ name=_pin_name(ptrace.path, pin_num),
285
+ x=x / MM_PER_INCH,
286
+ y=y / MM_PER_INCH,
287
+ type="T" if list(extract(pad, Cutout)) else "S",
288
+ outline=outline,
289
+ )
290
+ )
291
+
292
+ points = bounds or centers or [(0.0, 0.0)]
293
+ xs = [p[0] for p in points]
294
+ ys = [p[1] for p in points]
295
+ pitch = 0.0
296
+ if len(centers) > 1:
297
+ pitch = min(
298
+ ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5
299
+ for i, (ax, ay) in enumerate(centers)
300
+ for bx, by in centers[i + 1 :]
301
+ )
302
+ name = legal_name(cls.__name__)
303
+ taken = {pkg.name for pkg in out.packages}
304
+ suffix = 1
305
+ while name in taken:
306
+ suffix += 1
307
+ name = f"{legal_name(cls.__name__)}_{suffix}"
308
+ package = Package(name, pitch, min(xs), min(ys), max(xs), max(ys), pins)
309
+ packages[cls] = len(out.packages)
310
+ out.packages.append(package)
311
+ return packages[cls]
@@ -0,0 +1,44 @@
1
+ """Convert JITX copper (traces and pours) to signal-layer features.
2
+
3
+ Pours arrive from the runtime already computed with isolation and clearance,
4
+ so they are plain positive surfaces. Vias and pads are opaque here; their
5
+ copper is built by padstacks.py.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from jitx import Copper, Placement, Via
11
+ from jitx.landpattern import Pad
12
+
13
+ from jitx.run.runtime import RuntimeDesign
14
+
15
+ from ..format.model import Step
16
+ from .components import EdaRecorder
17
+ from .geometry import add_surface, add_trace, is_trace
18
+ from .layers import LayerModel
19
+ from .nets import NetIndex
20
+
21
+
22
+ def build_copper(
23
+ design: RuntimeDesign,
24
+ layer_model: LayerModel,
25
+ step: Step,
26
+ nets: NetIndex,
27
+ recorder: EdaRecorder,
28
+ ) -> None:
29
+ """Add L/A records for traces and S records for other copper, reporting
30
+ each feature to the net's TRC subnet."""
31
+ for trace, copper in design.query(Copper, opaque=Via | Pad):
32
+ if not trace.transform:
33
+ continue
34
+ placement = Placement(trace.transform)
35
+ name = layer_model.signal_name(placement.side.apply(copper.layer))
36
+ file = step.layer(name)
37
+ if is_trace(copper.shape):
38
+ ids = add_trace(file, copper.shape, transform=trace.transform)
39
+ else:
40
+ ids = add_surface(file, copper.shape, transform=trace.transform)
41
+ if ids:
42
+ subnet = recorder.trace(nets.index_for(copper))
43
+ for feature in ids:
44
+ recorder.fid(subnet, "C", name, feature)
@@ -0,0 +1,118 @@
1
+ """Surface features: soldermask, silkscreen, paste.
2
+
3
+ ODB++ models these as first-class positive layers whose features are the
4
+ openings (mask) or the printed shapes (silk, paste), so the queried shapes
5
+ are emitted directly; no board-minus-openings subtraction as in the EDB
6
+ exporter. The query transformer layer also yields mask openings synthesized
7
+ from untented vias and pad soldermask definitions.
8
+
9
+ A feature's side is relative to its placement: Bottom means the opposite side
10
+ of where the owning landpattern is placed.
11
+
12
+ Silkscreen text keeps the >REF and >VALUE placeholders after the runtime
13
+ roundtrip (the reverse-flow linker restores them deliberately, so exporters can
14
+ tell a label apart from raw text); they are resolved here against the owning
15
+ component.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from logging import getLogger
21
+
22
+ from jitx.feature import Paste, Silkscreen, Soldermask, SurfaceFeature
23
+ from jitx.inspect import Trace
24
+ from jitx.layerindex import Side
25
+ from jitx.placement import Placement
26
+ from jitx.shapes import Shape
27
+
28
+ from jitx.run.runtime import RuntimeDesign
29
+
30
+ from ..format import model
31
+ from ..format.model import LayerType, MatrixLayer, Step
32
+ from .components import ComponentIndex
33
+ from .geometry import (
34
+ add_surface,
35
+ add_trace,
36
+ is_polygonal,
37
+ is_trace,
38
+ text_feature,
39
+ text_string,
40
+ )
41
+
42
+ logger = getLogger(__name__)
43
+
44
+ _MASK_PREFIX = "sm"
45
+
46
+ # soldermask layer names, shared with the stackup extractor: a stackup mask
47
+ # material puts its thickness and Dk/Df on these layers rather than emitting a
48
+ # dielectric row of its own
49
+ MASK_TOP = _MASK_PREFIX + "t"
50
+ MASK_BOTTOM = _MASK_PREFIX + "b"
51
+
52
+ # top-to-bottom physical order on the top side; mirrored on the bottom
53
+ _FEATURES: list[tuple[type[SurfaceFeature], LayerType, str]] = [
54
+ (Paste, LayerType.SOLDER_PASTE, "sp"),
55
+ (Silkscreen, LayerType.SILK_SCREEN, "ss"),
56
+ (Soldermask, LayerType.SOLDER_MASK, _MASK_PREFIX),
57
+ ]
58
+
59
+
60
+ def build_features(
61
+ design: RuntimeDesign, step: Step, components: ComponentIndex
62
+ ) -> tuple[list[MatrixLayer], list[MatrixLayer]]:
63
+ """Emit surface-feature layers with content and return their matrix rows
64
+ as (top rows, bottom rows) in physical top-to-bottom order."""
65
+ skipped: dict[str, int] = {}
66
+ for ftype, _, prefix in _FEATURES:
67
+ for trace, feature in design.query(ftype):
68
+ flip = (
69
+ trace.transform.side
70
+ if isinstance(trace.transform, Placement)
71
+ else Side.Top
72
+ )
73
+ side = feature.side if flip == Side.Top else feature.side.flip()
74
+ name = prefix + ("t" if side == Side.Top else "b")
75
+ if is_polygonal(feature.shape):
76
+ add_surface(step.layer(name), feature.shape, transform=trace.transform)
77
+ elif is_trace(feature.shape):
78
+ add_trace(step.layer(name), feature.shape, transform=trace.transform)
79
+ else:
80
+ text = _text(feature.shape, trace, components)
81
+ if text is not None:
82
+ step.layer(name).add(text)
83
+ else:
84
+ skipped[name] = skipped.get(name, 0) + 1
85
+
86
+ for name, count in sorted(skipped.items()):
87
+ logger.warning(
88
+ "Skipped %d non-polygonal features (e.g. text) on layer %s",
89
+ count,
90
+ name,
91
+ )
92
+
93
+ top: list[MatrixLayer] = []
94
+ bottom: list[MatrixLayer] = []
95
+ for _ftype, ltype, prefix in _FEATURES:
96
+ if prefix + "t" in step.layers:
97
+ top.append(MatrixLayer(prefix + "t", ltype))
98
+ if prefix + "b" in step.layers:
99
+ bottom.append(MatrixLayer(prefix + "b", ltype))
100
+ bottom.reverse()
101
+ return top, bottom
102
+
103
+
104
+ def _text(shape: Shape, trace: Trace, components: ComponentIndex) -> model.Text | None:
105
+ """A T record for a text shape, with >REF and >VALUE resolved against the
106
+ owning component. None for a non-text shape, or a placeholder no component
107
+ resolves: silkscreening the literal placeholder would be worse than
108
+ dropping it."""
109
+ string = text_string(shape)
110
+ if string is None:
111
+ return None
112
+ if string.startswith(">"):
113
+ resolved = components.labels_for(trace.path).get(string)
114
+ if resolved is None:
115
+ logger.warning("Dropping unresolved label %s at %s", string, trace.path)
116
+ return None
117
+ string = resolved
118
+ return text_feature(shape, transform=trace.transform, string=string)