Source code for jitxlib.gerber.format.units

"""Coordinate grid and number formatting for every file this package writes.

Everything is metric. Gerber files declare `%FSLAX46Y46*%` with `%MOMM*%`,
so a coordinate integer is a nanometer; XNC declares `METRIC` and writes
decimal millimeters off the same integers. All rounding goes through this
module so a point shared by a copper file and a drill file serializes
identically in both.
"""

from __future__ import annotations

import math

NM_PER_MM = 1_000_000
"""Coordinate units per millimeter under `FSLAX46Y46` with `MOMM`."""

DECIMALS = 6
"""Decimal places in the coordinate format, and in every emitted decimal."""

HALF_STEP = 0.5 / NM_PER_MM
"""Half the output grid step in mm: the largest error rounding can hide."""


[docs] def nm(value: float) -> int: """Quantize a millimeter value onto the 1 nm output grid. Raises: ValueError: the value is not finite. """ if not math.isfinite(value): raise ValueError(f"Non-finite value in output: {value}") return round(value * NM_PER_MM)
[docs] def grid(value: float) -> float: """Snap a millimeter value to the nearest representable grid point.""" return nm(value) / NM_PER_MM
[docs] def coord(value: float) -> str: """Format a millimeter value as a Gerber coordinate field (X, Y, I, J).""" return str(nm(value))
[docs] def decimal(value: float) -> str: """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. """ if not math.isfinite(value): raise ValueError(f"Non-finite value in output: {value}") text = f"{value:.{DECIMALS}f}" # a value that rounds to zero from below prints as "-0.000000" return text[1:] if text.startswith("-0.") and float(text) == 0.0 else text
[docs] def xnc_decimal(value: float) -> str: """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. """ text = f"{nm(value) / NM_PER_MM:.{DECIMALS}f}".rstrip("0") if text.endswith("."): text += "0" return "0.0" if float(text) == 0 else text
[docs] def quantize(value: float) -> float: """Round an interning key component onto the output grid. One rule covers lengths and angles alike: 6 decimals is the nanometer grid for a millimeter and far finer than the 1e-4 degrees §6.5 asks for, so a key can never disagree with the text that gets emitted. """ if not math.isfinite(value): raise ValueError(f"Non-finite value in output: {value}") return round(value, DECIMALS) + 0.0