Source code for jitxlib.gerber.extract.job

"""Assemble a complete Gerber data set from a captured design and write it.

The order here is fixed by §6.10 rather than by convenience: naming runs
first, then the job file, then the writer. The job file's `Path` values are
the final resolved filenames, so if it re-derived a name instead of being
handed the resolved map, "nothing outside `naming.py` builds a filename"
would be false on the first day.

Within a copper file the emission order is fixed too: every filled surface,
containment-ordered, then the traces and flashes. A clear region erases what
was drawn before it, and nothing else can erase anything, so objects that
come after every region are safe by construction.
"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from logging import getLogger
from pathlib import Path
from collections.abc import Callable
from typing import Sequence

import shapely
from jitx.run.runtime import RuntimeDesign

from ..format import naming
from ..format.compat import DEFAULT as DEFAULT_COMPAT
from ..format.compat import Compat
from ..format.emit import emit_gerber
from ..format.jobfile import FileEntry, JobFile, emit_jobfile, project_guid
from ..format.model import (
    DrillFormat,
    Contour,
    DrillFile,
    FileFunction,
    FileMeta,
    FilePolarity,
    GenerationSoftware,
    GerberFile,
    ProjectId,
    Surface,
)
from ..format.naming import FileNaming
from ..format.pack import OutputFile, is_archive, write_set
from ..format.drill import emit_drill_gerber
from ..format.xnc import emit_xnc
from . import copper as copper_module
from . import components, features, geometry, outline, padstacks, regions, stackup
from .layers import LayerModel
from .nets import NetResolver, net_attribute

logger = getLogger(__name__)

VENDOR = "JITX"
APPLICATION = "jitxlib-gerber"
GERBER_FORMAT = "Gerber"

JOB_FORMAT: dict[DrillFormat, str] = {
    DrillFormat.XNC: "XNC",
    DrillFormat.GERBER: GERBER_FORMAT,
}
"""The gbrjob `FileFormat` value each drill format declares.

The job spec enumerates `(Gerber|XNC|NC|SM|IPC356|Other)`; this maps the
formats this exporter can write onto it.
"""

DRILL_EMITTERS: dict[DrillFormat, Callable[[DrillFile, FileMeta], str]] = {
    DrillFormat.XNC: emit_xnc,
    DrillFormat.GERBER: emit_drill_gerber,
}
"""How each drill format is serialized.

One format per data set, never both. Adding a format is a row here, a row in
`JOB_FORMAT`, and a row in `naming.DRILL_EXT` - nothing about the CLI, the
naming hook or the writer changes, which is the point of carrying the format
on the file function rather than threading it through every call.
"""


def _version() -> str:
    from importlib.metadata import PackageNotFoundError, version

    try:
        return version("jitxlib-gerber")
    except PackageNotFoundError:  # pragma: no cover - running from a source tree
        return "0.0.0+undefined"


[docs] @dataclass(frozen=True) class GerberResult: """What an export wrote. Args: root: the output path, whichever form it took - the directory the files were written into, or the archive itself. archive: the zip, when the output was one, and `root` again. files: every file written, with what it is, so a caller assembling a manufacturing packet does not have to re-derive the set. For a directory these are paths on disk; for an archive they are the names the files carry inside it, and nothing is on disk but the archive. """ root: Path archive: Path | None files: Sequence[tuple[FileFunction, Path]]
[docs] @dataclass class DataSet: """The file set before it has names or a destination.""" gerbers: list[GerberFile] drills: list[DrillFile] job: JobFile meta: FileMeta @property def functions(self) -> list[FileFunction]: from ..format.model import Job return ( [file.function for file in self.gerbers] + [file.function for file in self.drills] + [Job()] )
[docs] def build( design: RuntimeDesign, *, creation_date: str | None = None, drill_format: DrillFormat = DrillFormat.GERBER, compat: Compat = DEFAULT_COMPAT, ) -> DataSet: """Build the complete file set for a captured design. No file is written and no name is resolved here, which is what makes the whole pipeline testable without a directory. Args: drill_format: which format the drill files are written in. Exactly one, never both: a job file offering a CAM system the same span in two formats is a job file that invites drilling it twice. compat: output adjustments for readers that deviate from the spec. """ model = stackup.build(design) nets = NetResolver(design) board = outline.build(design) # the component walk runs first: the copper, mask, paste and legend files # all attach TO.C (and pads TO.P) off the index it builds, so there is no # order in which it can run alongside them index = components.build(design, model.layers, nets) plan = copper_module.collect(design, model.layers, nets) stacks = padstacks.build( design, model.layers, nets, board.npth, index, drill_format, compat ) # a pad cutout of a general shape is an opening in the profile (6.6), and # the pad walk is what finds it, so the profile file is finished here outline.add_cutouts(board, stacks.profile) surface_files = features.build(design, index) nets.report() gerbers = [ _copper_file(model.layers, plan, stacks, conductor) for conductor in range(model.layers.conductors) ] gerbers += surface_files.ordered() gerbers.append(board.file) gerbers += index.ordered() drills = [stacks.drills[key] for key in sorted(stacks.drills)] meta = FileMeta( GenerationSoftware(VENDOR, APPLICATION, _version()), creation_date or datetime.now().astimezone().isoformat(timespec="seconds"), ProjectId(design.name, project_guid(design.name)), compat, ) minx, miny, maxx, maxy = board.bounds job = JobFile( (maxx - minx, maxy - miny), model.layers.conductors, model.thickness, model.rows, ) return DataSet(gerbers, drills, job, meta)
[docs] def export( design: RuntimeDesign, *, output: Path, naming_scheme: str | FileNaming = naming.DEFAULT, overwrite: bool = False, creation_date: str | None = None, drill_format: DrillFormat = DrillFormat.GERBER, compat: Compat = DEFAULT_COMPAT, ) -> GerberResult: """Build and write the complete data set for a captured design.""" return write( build( design, creation_date=creation_date, drill_format=drill_format, compat=compat, ), design.name, output=output, naming_scheme=naming_scheme, overwrite=overwrite, )
[docs] def write( data: DataSet, design_name: str, *, output: Path, naming_scheme: str | FileNaming = naming.DEFAULT, overwrite: bool = False, ) -> GerberResult: """Name, serialize and write a built data set. Split from `build` so the whole write path - naming, the job file and the overwrite guard - is exercisable without a runtime, and so a caller that has already built a set can write it twice under two schemes. Args: output: a directory to write the files into, or a path ending in `.zip`, which writes exactly that archive and nothing beside it. A directory is the user's directory, not one this package created, so nothing here ever removes a directory. naming_scheme: a registered scheme name or a strategy object. An object is accepted so a caller can pass a configured instance without a registry round trip. Raises: OutputError: a name collides, or a target exists that this export may not replace. """ stem = naming.legal_stem(design_name) functions = data.functions names = naming.resolve(functions, stem, naming_scheme) # the job file names every other file, so naming runs before it and it # takes the resolved names rather than re-deriving anything data.job.files = [ FileEntry(name, function, *_entry(index, data)) for index, (name, function) in enumerate( zip(names[:-1], functions[:-1], strict=True) ) ] contents = [emit_gerber(file, data.meta) for file in data.gerbers] contents += [ DRILL_EMITTERS[file.function.format](file, data.meta) for file in data.drills ] contents.append(emit_jobfile(data.job, data.meta)) files = [ OutputFile(name, function, content) for name, function, content in zip(names, functions, contents, strict=True) ] written = write_set(files, output, data.meta.software, overwrite=overwrite) if is_archive(output): # the files live inside the archive and have no path of their own, so # what is reported back is the name each one carries in it return GerberResult(output, output, [(f.function, Path(f.name)) for f in files]) return GerberResult(output, None, list(zip(functions, written, strict=True)))
def _entry(index: int, data: DataSet) -> tuple[FilePolarity | None, str | None]: """The polarity and format fields of one `FilesAttributes` entry. Every entry declares its format, including the Gerber ones. The field is optional in the schema and it would be tempting to leave it off where it is implied by the file function, but the spec's own worked example sets it on all of them, and a consumer deciding which parser to hand a file to has nothing else to go on. """ if index < len(data.gerbers): return data.gerbers[index].polarity, GERBER_FORMAT function = data.drills[index - len(data.gerbers)].function # a drill file written as Gerber is a Gerber image and carries # TF.FilePolarity in the file itself, so the entry mirrors it; XNC has no # such concept and the field stays off polarity = FilePolarity.POSITIVE if function.format is DrillFormat.GERBER else None return polarity, JOB_FORMAT[function.format] # -------------------------------------------------------------------------- # copper def _copper_file( model: LayerModel, plan: copper_module.CopperPlan, stacks: padstacks.Padstacks, index: int, ) -> GerberFile: """One copper layer: its regions, then its traces, then its flashes.""" file = GerberFile(model.copper(index), FilePolarity.POSITIVE) pieces = plan.pieces.get(index, []) + stacks.pieces.get(index, []) report = regions.Report() for island in regions.build(pieces, report): surface = surface_of(island) if surface is not None: file.add(surface) regions.complain(report, model.copper(index).render()) for stroke in plan.strokes.get(index, []): file.add(stroke) for flash in stacks.flashes.get(index, []): file.add(flash) return file
[docs] def surface_of(island: regions.Island) -> Surface | None: """One resolved island as a dark region with its holes as clear ones. The holes inherit the island's object attributes deliberately: the dictionary is still set when they are emitted, and the cleared area does belong to that net's surface. """ if island.outer.area <= 0: return None attrs = (net_attribute(sorted(island.nets)),) aper = (copper_module.ETCHED_COMPONENT if island.tie else copper_module.CONDUCTOR,) return Surface( _contour(island.outer, ccw=True), tuple(_contour(hole, ccw=False) for hole in island.holes), attrs, aper, )
def _contour(polygon: shapely.Polygon, *, ccw: bool) -> Contour: return geometry.ring_contour( [(float(x), float(y)) for x, y in polygon.exterior.coords], ccw=ccw )