jitxlib.gerber.format package#
Standalone Gerber X2/X3, XNC and gbrjob writer.
No JITX imports anywhere in this package: it models and serializes the fabrication data set and is unit-testable without a runtime.
Everything is metric. Gerber files declare %FSLAX46Y46*% with %MOMM*%, so a coordinate integer is a nanometer, and XNC writes decimal millimeters off the same integers - a point shared by a copper file and a drill file serializes identically in both.
- class Aperture(template, params=(), attrs=())[source]#
Bases:
objectAn AD instantiation of a standard template or a macro.
- Parameters:
template (
str|Macro) – a standard template letter (C, R, O, P) or the macro to instantiate.params (
tuple[float,...]) – the AD modifiers in order, joined with X on emission. For a macro this includes the rotation argument.attrs (
tuple[tuple[str,tuple[str,...]],...]) – aperture attributes, applied to this aperture alone.
- exception ApertureError[source]#
Bases:
ValueErrorA shape cannot be expressed as an aperture.
- class ArcObj(x1, y1, x2, y2, cx, cy, ccw, aperture, attrs=())[source]#
Bases:
objectA D01 in circular mode, stroked from (x1, y1) to (x2, y2).
The center is absolute; the emitter derives the signed I/J offsets. ccw selects G03 over G02. A sweep over 180 degrees is split by the emitter, and a coincident start and end is a full circle, which the emitter also splits rather than emitting as the spec’s zero-length form.
- Parameters:
- class Compat(bake_macro_rotation=False)[source]#
Bases:
objectThe set of adjustments in effect for one export.
- Parameters:
bake_macro_rotation (
bool) – write rotated pads as macros with the rotation applied to the primitive coordinates and no rotation parameter, for readers that mishandle the macro rotation argument. Each distinct angle of a shape becomes its own macro.
- classmethod from_names(names)[source]#
The adjustments named, as on the command line (bake-macro-rotation).
- Raises:
ValueError – a name is not a known adjustment, listing the known ones.
- Return type:
- Parameters:
- class Component(index, side)[source]#
Bases:
objectComponent,L<index>,<side>, the X3 assembly layer for one side.
- kind = 'component'#
- exception ContourError[source]#
Bases:
ValueErrorA contour cannot be made to satisfy 4.10.3.
- class Copper(index, side, conductors, type=None)[source]#
Bases:
objectCopper,L<index>,<side>[,<type>].
- Parameters:
index (
int) – 1-based conductor index, counted from the top.side (
Side) – Top for index 1, Bot for the last conductor, Inr otherwise.conductors (
int) – total conductor count, for naming schemes that vary with board size. Not part of the rendered attribute.type (
CopperType|None) – emitted only when set; a plain signal layer leaves it off.
- type: CopperType | None = None#
- kind = 'copper'#
- class CopperType(*values)[source]#
Bases:
StrEnum- SIGNAL = 'Signal'#
- PLANE = 'Plane'#
- MIXED = 'Mixed'#
- class CurveSeg(x, y, cx, cy, ccw)[source]#
Bases:
objectAn arc contour segment ending at (x, y) around an absolute center.
- class Draw(x1, y1, x2, y2, aperture, attrs=())[source]#
Bases:
objectA D01 in linear mode: a straight stroke with round caps.
- Parameters:
- class Drill(first, last, hole, plated=True, content=None, format=DrillFormat.GERBER)[source]#
Bases:
object(Plated|NonPlated),<from>,<to>,<hole type>[,<content>].
- Parameters:
first (
int) – 1-based conductor index the span starts at.last (
int) – 1-based conductor index the span ends at.hole (
HoleType) – PTH/NPTH for a span crossing the whole board, Blind or Buried otherwise.plated (
bool) – selects the Plated or NonPlated keyword. Plating is a file attribute by design, which is why plated and non-plated hits cannot share a file.content (
DrillContent|None) – Drill, Rout or Mixed; omitted when the file is plain hits.format (
DrillFormat) – which format the file is written in. Not part of the rendered attribute - it decides the file’s extension and its gbrjob FileFormat, so naming and the job writer branch on it rather than on an extension they would otherwise have to guess.
- content: DrillContent | None = None#
- format: DrillFormat = 'gerber'#
- kind = 'drill'#
- class DrillContent(*values)[source]#
Bases:
StrEnum- DRILL = 'Drill'#
- ROUT = 'Rout'#
- MIXED = 'Mixed'#
- class DrillFormat(*values)[source]#
Bases:
StrEnumWhich format a drill file is written in.
One format per data set, never both: a job file listing an XNC and a Gerber drill file for the same span gives a CAM system every reason to drill the holes twice.
Gerber is the spec’s own recommendation - 6.6, “use Gerber rather than an NC format for drill and rout layers … mixing formats is asking for problems, especially in registration” - with XNC as the NC fallback it endorses, “the only one that is clearly specified and targeted to CAD to CAM data transfer”.
Gerber is the default. XNC remains available for a consumer whose intake wants an NC file, selected with –drill-format xnc.
- XNC = 'xnc'#
- GERBER = 'gerber'#
- class DrillFile(function, hits=list(), slots=list())[source]#
Bases:
objectOne XNC file: one plating, one span.
Hits and slots are emitted in the order added, grouped into the drill and rout sections the XNC grammar requires.
- class DescriptiveNaming[source]#
Bases:
objectThe neutral scheme: names say what the file is.
Every name is <stem>-<description><extension>, except the job file, whose extension is its whole identity.
- class FileEntry(path, function, polarity=None, file_format=None)[source]#
Bases:
objectOne FilesAttributes entry.
- Parameters:
path (
str) – the resolved filename, as written to disk.file_format (
str|None) – XNC for a drill file; omitted for Gerber, whose format is implied.function (FileFunction)
polarity (FilePolarity | None)
- polarity: FilePolarity | None = None#
- class FileKind(*values)[source]#
Bases:
StrEnumThe primary branch a naming scheme and the overwrite guard key on.
- COPPER = 'copper'#
- SOLDERMASK = 'soldermask'#
- LEGEND = 'legend'#
- PASTE = 'paste'#
- PROFILE = 'profile'#
- DRILL = 'drill'#
- COMPONENT = 'component'#
- JOB = 'job'#
- class FileNaming(*args, **kwargs)[source]#
Bases:
ProtocolA strategy that turns a file function into a filename.
Implement name and register the class under a scheme name. A scheme is free to return None for any file it has no convention for; the caller falls back to descriptive rather than inventing a name.
- name(function, stem, file_set)[source]#
The complete filename for one file, or None to defer.
- Parameters:
function (Copper | Soldermask | Legend | Paste | Profile | Drill | Component | Job) – what the file is, as the structured description it already carries for its TF.FileFunction attribute, so a scheme branches on data rather than on a rendered string.
stem (
str) – the scrubbed design name. Conventions that replace the extension entirely need it, which is why the strategy returns a whole filename rather than a suffix.file_set (
Sequence[Copper | Soldermask | Legend | Paste | Profile | Drill | Component | Job]) – every file function in the set being written, in emission order. Real conventions are not per-file functions of one file - whether a drill name needs decorating depends on whether the other drill file exists - so the set is passed even though many schemes will ignore it.
- Return type:
- class FileMeta(software, creation_date, project, compat=Compat(bake_macro_rotation=False))[source]#
Bases:
objectThe per-run identity every file in the set repeats.
Injected by the caller rather than read from a clock inside an emitter, so output is reproducible.
- Parameters:
creation_date (
str) – ISO 8601 with a time zone.compat (
Compat) – the output adjustments in effect, which every file names in a comment so it shows how it was written.software (GenerationSoftware)
project (ProjectId)
- software: GenerationSoftware#
- class Flash(x, y, aperture, attrs=())[source]#
Bases:
objectA D03: one aperture stamped at a point.
Every pad is a flash and every flash is a pad (spec 4.10), so nothing else may use this.
- class GenerationSoftware(vendor, application, version)[source]#
Bases:
objectTF.GenerationSoftware and the gbrjob Header object of the same name, which spells the same three fields as JSON.
- class GerberFile(function, polarity=FilePolarity.POSITIVE, objects=list())[source]#
Bases:
objectOne Gerber image: its file function, polarity and object list.
There is no aperture table here on purpose. Every object carries the aperture it uses, apertures are values rather than registry entries, and §7 assigns D-codes by sorted key once the set is complete - so the table is derived at emission and cannot drift out of step with the objects.
- Parameters:
- polarity: FilePolarity = 'Positive'#
- class HoleType(*values)[source]#
Bases:
StrEnum- PTH = 'PTH'#
- NPTH = 'NPTH'#
- BLIND = 'Blind'#
- BURIED = 'Buried'#
- class Job[source]#
Bases:
objectThe .gbrjob file.
It is not a Gerber file and carries no TF.FileFunction, but it is part of the written set, so naming and the overwrite guard need a handle for it.
- kind = 'job'#
- class JobFile(size, conductors, thickness=None, stackup=list(), files=list())[source]#
Bases:
objectThe job file model.
- Parameters:
- stackup: list[StackupRow]#
- class Macro(body)[source]#
Bases:
objectAn AM template, named from its content.
- exception NamingError[source]#
Bases:
LookupErrorNo such naming scheme.
- class OutputFile(name, function, content)[source]#
Bases:
objectOne resolved file: its final name, what it is, and its text.
- Parameters:
- class Polarity(*values)[source]#
Bases:
StrEnumObject polarity: dark adds to the image, clear erases from it.
- DARK = 'D'#
- CLEAR = 'C'#
- class Profile(plated=False)[source]#
Bases:
objectProfile,(P|NP). JITX has no edge plating, so NP in practice.
- Parameters:
plated (bool)
- kind = 'profile'#
- class ProjectId(name, guid, revision='rev?')[source]#
Bases:
objectTF.ProjectId: a name, an RFC 4122 GUID and a revision.
revision is rev? when the design carries none.
- class Region(contours, polarity=Polarity.DARK, attrs=(), aper_attrs=())[source]#
Bases:
objectA G36/G37 statement: the union of its contours’ filled areas.
All contours share one polarity, since polarity is a property of a graphic object. Holes are separate clear regions, not contours here.
- class Slot(start, segments, tool, attrs=())[source]#
Bases:
objectA rout path: tool down at start, one segment per step, tool up.
Arc segments span at most 180 degrees; XNC carries a radius rather than a center, so the emitter derives it and the direction comes from ccw.
- Parameters:
- class Soldermask(side)[source]#
Bases:
objectSoldermask,<side>. Images the openings, so the file is negative.
- Parameters:
side (Side)
- kind = 'soldermask'#
- class StackupRow(type, thickness=None, name=None, material=None, dielectric_constant=None, loss_tangent=None)[source]#
Bases:
objectOne MaterialStackup entry, top to bottom. Thickness in mm.
- Parameters:
- type: StackupType#
- class StackupType(*values)[source]#
Bases:
StrEnumMaterialStackup row types.
Soldermask and legend rows exist so a stackup layer that declares itself one is not mislabeled dielectric, which is what a “everything that is not a conductor is a dielectric” walk produces.
- COPPER = 'Copper'#
- DIELECTRIC = 'Dielectric'#
- SOLDERMASK = 'SolderMask'#
- LEGEND = 'Legend'#
- SURFACE_FINISH = 'SurfaceFinish'#
- class Surface(island, holes=(), attrs=(), aper_attrs=())[source]#
Bases:
objectAn island with the holes that belong to it, kept together.
The grouping is the unit any ordering moves, so an island can never be separated from a hole that would erase it. The emitter expands it into a dark region followed by one clear region per hole; island is also the outer ring a containment ordering sorts on.
- Parameters:
- class Tool(diameter, attrs=())[source]#
Bases:
objectOne XNC tool.
- Parameters:
diameter (
float) – the finished hole diameter after plating, in mm. The exporter never applies a plating allowance in either direction; the fabricator picks the bit.attrs (
tuple[tuple[str,tuple[str,...]],...]) – tool attributes, chiefly the bare TA.AperFunction value. Plating is not part of it - that is the file’s attribute.
- circle_aperture(diameter, *, hole=None, attrs=())[source]#
C,<diameter>[X<hole>]. Rotation is irrelevant to a circle.
- closed_ring(points)[source]#
A contour from a point ring, closing it if the caller has not.
The convention this package fixes, because the spec leaves it open and §8’s polarity simulator needs one to interpret: outer contours run counter-clockwise, holes clockwise. This helper does not reorder; it is the callers that owe the convention.
- decimal(value)[source]#
Format a millimeter or degree value as a Gerber decimal.
Used for AD parameters, AM primitive parameters and XNC tool diameters, all of which take decimals rather than coordinate integers.
- donut(outer, inner, attrs=())[source]#
An annular pad: a circle with a smaller centered round hole.
The hole is transparent, not clear - 4.4.6, “holes do not clear the objects under them” - so a donut pad over a same-net pour leaves the pour showing through the middle, which is the real copper.
- emit_gerber(file, meta)[source]#
The complete text of one Gerber file, M02* included.
- Return type:
- Parameters:
file (GerberFile)
meta (FileMeta)
- emit_drill_gerber(file, meta)[source]#
The complete text of one drill file in Gerber format, M02* included.
- escape_field(value)[source]#
Escape a string for use as an attribute field.
Reserved characters and everything outside printable ASCII become uXXXX (or UXXXXXXXX above the BMP), so the whole file stays 7-bit printable ASCII and a user net name cannot break the syntax.
- legal_stem(name)[source]#
Scrub a design name into a filename stem.
Restricted to ASCII on purpose, and as a portability rule rather than a fab-specific one: upload forms and older CAM tooling are known to reject filenames they cannot read as plain English, so a design name with non-ASCII characters must not be able to reach one.
The dot goes with them, for the same reason rather than a cosmetic one. A design name is a dotted module path in practice, so keeping dots would put several of them in every filename, and an upload form that reads the extension off the first dot rather than the last then sees a file it has no idea what to do with.
- macro_aperture(body, params, rotation, attrs=())[source]#
Instantiate a macro built from primitive lines.
rotation is appended as the last AD modifier, which is the $1 the primitives reference. None is a baked macro: its primitives reference no rotation and the AD carries none.
- macros(apertures)[source]#
Every macro the apertures instantiate, deduplicated by content and ordered by generated name.
- nm(value)[source]#
Quantize a millimeter value onto the 1 nm output grid.
- Raises:
ValueError – the value is not finite.
- Return type:
- Parameters:
value (float)
- obround_aperture(width, height, *, hole=None, attrs=())[source]#
O,<w>X<h>[X<hole>], axis-aligned; a capsule at 0 or 90 degrees.
- outline_aperture(points, rotation, attrs=(), *, mirrored=False, baked=False)[source]#
A straight-edged outline in the aperture’s own frame.
- Parameters:
points (
Sequence[tuple[float,float]]) – the ring, in the unrotated aperture frame.mirrored (
bool) – mirror the vertex list across the Y axis. Mirroring cannot be an AD parameter the way rotation can, so it becomes different macro content - which is the normal case, since every bottom-side placement is mirrored.baked (
bool) – apply the rotation to the coordinates rather than pass it to the macro.rotation (float)
attrs (AttrSet)
- Return type:
- outlines_aperture(islands, rotation, attrs=(), *, label='outline', baked=False)[source]#
Straight-edged outlines with holes, in the aperture’s own frame.
- Parameters:
islands (
Sequence[tuple[Sequence[tuple[float,float]],Sequence[Sequence[tuple[float,float]]]]]) – each outer ring with its holes, unrotated. A hole is an exposure-off outline, which only clears within this aperture.label (
str) – the macro’s comment line.baked (
bool) – apply the rotation to the coordinates rather than pass it to the macro.rotation (float)
attrs (AttrSet)
- Return type:
- polygon_aperture(diameter, vertices, rotation=0.0, *, hole=None, attrs=())[source]#
P,<outer>X<n>[X<rot>[X<hole>]], the only rotatable standard template.
- project_guid(name)[source]#
A stable GUID for a design name.
uuid5 gives determinism across reruns, but the spec requires an RFC 4122 version 1 or 4 GUID and a uuid5 carries a version 5 nibble, so the version and variant nibbles are forced to v4 afterwards.
- resolve(functions, stem, scheme='descriptive')[source]#
Resolve a whole file set to filenames, parallel to functions.
A scheme that returns None for a file defers to descriptive, which is why descriptive must be total. Collision checking is deliberately not here: it belongs to the writer, which sees the archive name as well and is where a collision has to stop the run.
- Return type:
- Parameters:
functions (Sequence[FileFunction])
stem (str)
scheme (str | FileNaming)
- rotated_capsule(width, height, rotation, attrs=(), *, baked=False)[source]#
A capsule (obround) at an arbitrary angle, exact rather than linearized: a rectangular body between two end circles.
- rotated_rect(width, height, rotation, attrs=(), *, baked=False)[source]#
A rectangle at an arbitrary angle.
Prefer rect_aperture at 0 or 90 degrees; the standard template is what every consumer handles best.
- rounded_rect(width, height, radius, rotation, attrs=(), *, baked=False)[source]#
A rectangle with round corners, exact: two overlapping center lines plus a circle at each corner. This is how the official sample_macro.gbr builds one, and it avoids linearizing a shape that has a closed form.
- scrub(contour)[source]#
Put a contour on the output grid and make it satisfy 4.10.3.
Snaps every coordinate, drops zero-length and collinear straight segments, turns sub-resolution arcs into straight segments, splits arcs over 180 degrees, and verifies the closure holds after rounding rather than before it.
- Raises:
ContourError – nothing survives the scrubbing, or the contour does not close on the grid.
- Return type:
- Parameters:
contour (Contour)
- signed_area(contour)[source]#
Twice the signed polygon area of a contour’s vertices, in mm².
Positive is counter-clockwise. Arc bulges are ignored, so this is for checking and fixing winding, not for measuring.
- validate(contour)[source]#
Check a scrubbed contour against 4.10.3.
Self-intersection is not checked here; it needs real geometry and the format layer carries no shapely dependency, so §8’s polarity layer owns it.
- Raises:
ContourError – a zero-length segment, a collinear vertex or an open contour survived.
- Return type:
- Parameters:
contour (Contour)
- is_archive(output)[source]#
Whether an output path asks for a zip rather than a directory.
The suffix is the whole switch. An output path is a destination the user named, so board.zip says what they want as plainly as a flag would and cannot disagree with one.
- write_set(files, output, software, *, overwrite=False)[source]#
Write the file set to output and return the paths written.
- Parameters:
output (
Path) – a directory to write the files into, or a path ending in .zip, which writes exactly that archive with the files at its root - the layout fab upload forms expect - and nothing beside it. The archive is built from the content in memory, so it never contains itself.software (
GenerationSoftware) – the identity the guard looks for when deciding whether an existing file is a previous export of ours.files (Sequence[OutputFile])
overwrite (bool)
- Return type:
- Returns:
One path per file for a directory, or the single archive path.
- Raises:
OutputError – a name is not a plain filename, two files resolve to one name, a target exists without overwrite, or a target exists that does not look like our own output.
- to_gerber(file)[source]#
The Gerber image of a drill file, hits first and then rout paths.
Object order follows emit_xnc so the two formats produce the same image in the same sequence and a golden test can compare them.
- Return type:
- Parameters:
file (DrillFile)
- xnc_decimal(value)[source]#
Format a millimeter value for an XNC coordinate or tool diameter.
The value comes off the 1 nm grid, so a drill hit and the copper around it agree exactly. Trailing zeros are trimmed, but never the decimal point: XNC permits a bare integer (“zero therefore must be encoded as 0”, 2.6), and readers descended from legacy Excellon reject one, because in that format a coordinate without a decimal point needs a number format the file does not carry. Writing 30.0 rather than 30 is a decimal either way and costs nothing.
- exception XncError[source]#
Bases:
ValueErrorA drill file cannot be expressed in XNC.