API reference
Every name symdef exports, in the order of symdef.__all__.
DEFAULT_MODULE_MM
constant
Value: 2.5
GRID_DIVISION
constant
Value: 0.125
LIBRARY_VERSION
constant
Value: '0.40.0'
Allow
class
Allow(rule: str, reason: str) -> None
A lint exemption with its reason.
Anchor
class
Anchor(id: str, position: symdef.geometry.Point, direction: symdef.geometry.Direction) -> None
An attachment point for composition.
Attributes:
position: In module units.
direction: The way the anchor faces; two anchors join when they face each other.
Arc
class
Arc(center: symdef.geometry.Point, radius: float, start_deg: float, end_deg: float, weight: symdef.geometry.Weight = <Weight.NORMAL: 0.1>, style: symdef.geometry.Style = <Style.SOLID: 'solid'>, port: str | None = None) -> None
A circular arc swept clockwise on screen from start_deg to end_deg.
Angles are in degrees, measured clockwise on screen from +x (so 90 points down). Equal
angles make a full circle.
Attributes:
port: The id of the port this arc is the lead of, or None for an ordinary arc.
Box
class
Box(min: symdef.geometry.Point, max: symdef.geometry.Point) -> None
An axis-aligned rectangle in module units, from its min corner to its max corner.
Centre
class
Centre(*values)
The slot side `C`: the text centres on the slot point, along and across its reading line.
It is not a `Direction`: a slot side says where text sits, a port side says where a wire
leaves, and keeping `C` out of `Direction` means a port can never be `C`.
Circle
class
Circle(center: symdef.geometry.Point, radius: float, fill: symdef.geometry.Fill = <Fill.NONE: 'none'>, weight: symdef.geometry.Weight = <Weight.NORMAL: 0.1>) -> None
A circle, optionally filled; the radius is in module units.
Corner
class
Corner(*values)
A slot side that grows to a corner, both ways from `position`, the opposite corner.
The value is the unit vector of the growth, in SVG axes: `SE` grows east and south, so its
`position` is the box's north-west corner. It is not a `Direction`, so a port can never be one.
Direction
class
Direction(*values)
Compass direction, with the unit vector as its value.
The axes are SVG's, so N is (0, -1) (up on screen) and S is (0, 1).
Element
constant
Value: symdef.geometry.Line | symdef.geometry.Polyline | symdef.geometry.Circle | symdef.geometry.Arc | symdef.geometry.Text
Fill
class
Fill(*values)
Whether a closed shape is filled: not at all, solid black, or with a tint the renderer takes.
A tint is filled with the colour the caller passes to the renderer.
Finding
class
Finding(rule: str, severity: symdef.model.Severity, message: str, location: str | None = None, orientation: symdef.geometry.Orientation | None = None) -> None
One lint or load problem.
Attributes:
rule: The id of the rule that reported it.
message: Human-readable text.
location: Where it is, such as `elements[2]` or `slots.tag`, or None if it is about the
whole symbol.
orientation: The orientation it was found in, or None if the rule does not depend on
orientation.
FontMetrics
class
FontMetrics(name: str, units_per_em: float, cap_height: float, ascent: float, descent: float, advances: collections.abc.Mapping[symdef.geometry.Weight, collections.abc.Mapping[str, float]], default_advance: collections.abc.Mapping[symdef.geometry.Weight, float], heights: collections.abc.Mapping[str, float] = <factory>, family: str = '', text_block: str = 'cap') -> None
The measures of one font, in the font's own units; `units_per_em` is one em.
Attributes:
name: The font's name, for the record; it changes no measure.
units_per_em: How many font units make one em, the text height.
cap_height: Height of a capital letter above the baseline, in font units.
ascent: Height of the tallest glyph above the baseline, in font units.
descent: Depth of the lowest glyph below the baseline, in font units.
advances: One table per text weight (`TEXT_WEIGHTS`): the advance of each character, in
font units.
default_advance: One advance per text weight: what a character its table does not list
takes, so a bold text charges the bold face's own default (D119).
heights: Capital heights in millimetres by name, such as `smallest` or `body`. The
names are the library's own; symdef does not interpret them. Empty when none.
family: The family name a renderer resolves the font by. Empty at construction means the
same as `name`, so it is never empty. `measure_font` reads it from the face.
text_block: How `slot_lines` sets a text block: "cap" or "grid" (D95).
Grid
class
Grid(module_mm: float = 2.5, divisions_per_module: int = 8, wire_pitch: int = 8, wire_pitch_fine: int = 4, stretch_split: str = 'weight', declared_outline_margin: int | None = None) -> None
The drawing grid of a library: the size of the module and how many divisions it has.
Attributes:
module_mm: One module in millimetres.
divisions_per_module: How many grid divisions make one module; a power of two, so a
division is exact in floating point.
wire_pitch: The standard wire pitch in divisions; every port sits on it.
wire_pitch_fine: The fine wire pitch in divisions, for a dense page; it divides
`wire_pitch`. A library has these two pitches and no third.
stretch_split: How `stretch` shares a growth among several cuts: "weight" (by weight, the
default) or "whole" (in whole divisions, near cuts floored; D97).
declared_outline_margin: How far, in divisions, a unit outline stands off the boxes it
encloses, on all four sides, or None when the library declares none (D120). Read the
margin through `outline_margin`, which raises when none is declared.
GridBox
class
GridBox(min: symdef.gridtypes.GridPoint, max: symdef.gridtypes.GridPoint) -> None
An axis-aligned rectangle in whole grid divisions, from its min corner to its max corner.
GridPoint
class
GridPoint(x: int, y: int) -> None
A position in whole grid divisions.
GridPort
class
GridPort(id: str, x: int, y: int, direction: symdef.geometry.Direction) -> None
A connection point in whole grid divisions, with the direction it leaves the symbol.
InkBoxes
class
InkBoxes(body: B | None, leads: tuple[B, ...], texts: collections.abc.Mapping[str, B]) -> None
The drawn ink of a symbol, one box per group, no margin; `GridBox` on the grid.
Attributes:
body: The union of the elements that bind no port, or None when there are none.
leads: One box per bound lead, in element order.
texts: The box of each given slot string, by slot id.
InvalidValueError
class
InvalidValueError(...)
An argument or data is unusable; the message names the value, what is valid and the fix.
Library
class
Library(standard: str, title: str, number_pattern: str, symbols: collections.abc.Mapping[str, symdef.model.Symbol], vocabulary: symdef.model.Vocabulary = Vocabulary(path_kinds=(), potentials=(), links=()), required_slots: tuple[str, ...] = (), wires: tuple[symdef.model.WireStyle, ...] = (), grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None), lines: collections.abc.Mapping[symdef.geometry.Weight, float] = mappingproxy({}), dash: collections.abc.Mapping[str, tuple[float, ...]] = mappingproxy({}), *, font: symdef.font.FontMetrics, port_format: str) -> None
The symbols of one standard, keyed by reference number.
Iterating yields the symbols sorted by reference number; `len` is their count. `font` is the
metrics text is measured with (keyword-only, required: D124); `grid` is the
drawing grid; `lines` is the stroke width in millimetres of each `Weight`, empty when the
library declares none; `dash` is the named dash patterns in millimetres, empty when none;
`port_format` is the template of a repeated pole's port id (keyword-only, required: D123, D127).
LibraryError
class
LibraryError(findings: tuple[ForwardRef('Finding', owner=<function LibraryError.__init__ at 0x7fcdaf8ffa00>), ...]) -> None
A library failed to load; `findings` says why.
Line
class
Line(start: symdef.geometry.Point, end: symdef.geometry.Point, weight: symdef.geometry.Weight = <Weight.NORMAL: 0.1>, style: symdef.geometry.Style = <Style.SOLID: 'solid'>, port: str | None = None, between: bool = False) -> None
A straight segment, optionally the lead of a port.
Attributes:
port: The id of the port this line is the lead of, or None for an ordinary line.
between: True for a tick that `table` draws in every row but the last; outside a table
it is drawn as authored.
Measure
class
Measure(body: symdef.gridtypes.GridBox, keepout: symdef.gridtypes.GridBox, slots: collections.abc.Mapping[str, symdef.gridtypes.GridBox], ports: collections.abc.Mapping[str, symdef.gridtypes.GridPort], ink: symdef.gridtypes.GridBox) -> None
What a symbol takes up and where its ports are, in whole grid divisions.
Attributes:
body: The body box. A box's `max` is the extent rounded up, its `min` rounded down.
keepout: The body united with every slot box.
ink: The drawn ink alone: the body, the leads and the given texts, with no slot reservation.
slots: Slot id to its box, with the text measured when `measure` was given one.
ports: Port id to its position and its direction after the turn.
Node
class
Node(ports: tuple[str, ...], potential: str | None = None) -> None
Ports that are the same electrical point inside the symbol.
Attributes:
ports: Port ids.
potential: A word from the symbol set's `potentials` for the fixed potential the node
stands for, or None for an ordinary node.
Orientation
class
Orientation(*values)
One of the 8 orientations: an optional mirror (flip x), then a clockwise turn by n.
`R<n>` turns by n degrees; `MR<n>` mirrors first, then turns. R0 is the symbol as defined.
Path
class
Path(from_port: str, to_port: str, kind: str, through: bool = False) -> None
A two-terminal relation between the ports of two different nodes.
Attributes:
from_port: Id of the port at one end.
to_port: Id of the port at the other end.
kind: A word from the symbol set's `path_kinds`: the meaning of the relation.
through: Whether this is the symbol's through path, the one `repeat` requires and
keeps on pole 1 only.
Point
class
Point(x: float, y: float) -> None
A position in module units, x to the right and y downwards.
Polyline
class
Polyline(points: tuple[symdef.geometry.Point, ...], closed: bool = False, fill: symdef.geometry.Fill = <Fill.NONE: 'none'>, weight: symdef.geometry.Weight = <Weight.NORMAL: 0.1>, style: symdef.geometry.Style = <Style.SOLID: 'solid'>, between: bool = False, port: str | None = None) -> None
A chain of segments through `points`, optionally closed and filled.
Attributes:
closed: Whether the last point joins back to the first.
fill: Whether a closed polyline is filled.
between: True for a tick that `table` draws in every row but the last; outside a table
it is drawn as authored.
port: The id of the port this polyline is the lead of, or None for an ordinary one.
Port
class
Port(id: str, position: symdef.geometry.Point, direction: symdef.geometry.Direction, description: str = '', pattern: bool = False) -> None
A connection point on a symbol; the id is the only pin identity.
Attributes:
position: Where a wire meets the symbol, in module units.
direction: The outward normal: the side of the body box the port sits on.
description: Free text, empty if none.
pattern: True when the port stands for n ports repeated along its edge at the wire pitch;
`pattern_ports` expands it.
Reference
class
Reference(standard: str, number: str, edition: str | None = None, form: str | None = None) -> None
Where a symbol is defined in its standard.
ReferenceCellError
class
ReferenceCellError(...)
A point lies outside the reference grid of a page frame; the message names both.
Severity
class
Severity(*values)
How serious a finding is; a data repo gate rejects both.
Slot
class
Slot(id: str, position: symdef.geometry.Point, side: SlotSide, box: tuple[float, float], turn: bool = False) -> None
Room reserved for text the consumer draws; `box` is (width, height).
Attributes:
position: The point the box grows from, in module units.
side: The direction the box grows towards from `position`, `Centre.C` for a box centred
on it, or a `Corner` for a box that grows both ways from its opposite corner; see
`slot_box`.
box: Width and height in module units, never rotated: the footprint as drawn.
turn: True when a string in the slot is drawn turned, reading bottom-up, along the height
of `box`. It is fixed to the page: `orient` never changes it.
Status
class
Status(*values)
Whether a symbol's geometry was checked against the standard's own drawing.
Stretch
class
Stretch(axis: Literal['x', 'y'], at: float, weight: float = 1) -> None
A cut line across the body: `stretch` moves every point beyond it.
Attributes:
axis: The axis the symbol grows along.
at: The cut's coordinate on that axis, in module units.
weight: The cut's share of the growth against the other cuts on its axis; positive.
Style
class
Style(*values)
Line style; dashed is drawn with a dash of 0.5 M and a gap of 0.25 M.
Dash-dot is a dash of 1 M, a gap of 0.25 M, a dot of 0.0625 M and a gap of 0.25 M.
Symbol
class
Symbol(name: str, kind: symdef.model.SymbolKind, status: symdef.model.Status, reference: symdef.model.Reference, elements: tuple[symdef.geometry.Line | symdef.geometry.Polyline | symdef.geometry.Circle | symdef.geometry.Arc | symdef.geometry.Text, ...], ports: tuple[symdef.model.Port, ...] = (), nodes: tuple[symdef.model.Node, ...] = (), paths: tuple[symdef.model.Path, ...] = (), anchors: tuple[symdef.model.Anchor, ...] = (), slots: tuple[symdef.model.Slot, ...] = (), pole_pitch: int | None = None, lint_allow: tuple[symdef.model.Allow, ...] = (), stretch: tuple[symdef.model.Stretch, ...] = (), body: symdef.geometry.Box | None = None, keepout: symdef.geometry.Box | None = None) -> None
A symbol definition, not a placement: it has no label, tag or position.
Attributes:
name: The symbol's name.
reference: Where the standard defines it.
elements: The drawing, in module units.
pole_pitch: Spacing between poles for `repeat`, in module units; None means 4.
stretch: Cut lines for `stretch`, one or more per axis.
lint_allow: Lint exemptions the symbol claims.
body: A declared body box in module units, or None for the element extent (D98).
keepout: A declared keep-out box in module units, or None for the body and slot boxes.
SymbolKind
class
SymbolKind(*values)
Whether a symbol is placeable on its own or exists to be used as a part.
SymdefError
class
SymdefError(...)
Base class for every error this package raises.
Text
class
Text(content: str, position: symdef.geometry.Point, height: float = 1.0, weight: symdef.geometry.Weight = <Weight.NORMAL: 0.1>) -> None
A text label, always middle-anchored and upright; height is in module units.
Attributes:
position: The middle of the label.
TextPlacement
class
TextPlacement(point: symdef.geometry.Point, anchor: Anchor, turned: bool) -> None
Where a slot's string is drawn.
Attributes:
point: The baseline point the text is anchored at, in module units.
anchor: Which end of the text sits on `point`: `start`, `middle` or `end`.
turned: True when the text reads bottom-up, rotated a quarter turn counter-clockwise about
`point`.
TextRoot
class
TextRoot(x: int, y: int, h: Literal['left', 'right'], v: Literal['baseline', 'top']) -> None
A point where a text starts, in whole grid divisions, y down.
Attributes:
x: The point's horizontal position.
y: The point's vertical position.
h: The text's horizontal alignment at the point; `"right"` means it extends to the left.
v: The text's vertical alignment at the point: `"baseline"`, or `"top"` for a text that
hangs below it.
UnknownNameError
class
UnknownNameError(...)
A name is not in the set it was looked up in; the message lists the valid names.
UnknownSymbolError
class
UnknownSymbolError(...)
A library lookup found no symbol with the requested reference number.
Vocabulary
class
Vocabulary(path_kinds: tuple[str, ...] = (), potentials: tuple[str, ...] = (), links: tuple[str, ...] = ()) -> None
The words a symbol set declares in `library.toml [vocabulary]`; empty lists by default.
Weight
class
Weight(*values)
Line weight; the value is the stroke width in module units.
RULE is the thin rule weight of wire styles and the `[lines]` table (0.18 mm at the default
module); text and symbol elements do not use it.
WireStyle
class
WireStyle(id: str, weight: symdef.geometry.Weight, style: symdef.geometry.Style) -> None
A named line style for `wire`: one `[[wire]]` table of `library.toml`, or a bundle entry.
Attributes:
id: The name a caller passes to `wire`.
weight: The line weight of the wire.
style: Whether the wire is solid or dashed.
body_box
function
body_box(symbol: symdef.model.Symbol, font: symdef.font.FontMetrics | None = None) -> symdef.geometry.Box
Return the union of the element extents, in module units, ignoring stroke width.
Extents are as for text (`text_width` with `font`; with no font `0.6 * height` per character),
arcs (the true swept extent) and the other elements. A symbol without elements has the box
(0, 0) to (0, 0). Ports, anchors and slots do not count.
A symbol that declares its `body` (D98) has exactly that box, whatever its elements and
`font`.
bold_layer
function
bold_layer(fragment: str) -> str
Return `fragment` inside one group whose text is drawn bold.
ceil_divisions
function
ceil_divisions(grid: symdef.units.Grid, v: float) -> int
Round a value in module units up to whole grid divisions.
A value within the tolerance above a multiple counts as that multiple, so float noise
does not add a division.
corner_text
function
corner_text(box: symdef.geometry.Box, corner: Corner, height: float, font: symdef.font.FontMetrics | None, *, turn: bool = False) -> symdef.slottext.TextPlacement
Return where a one-line text of `height` sits at a corner of `box`, as `slot_text` does.
The text hangs inside the box on that corner: `W` corners start at the box's west edge and `E`
corners end at its east edge; `N` corners put the capitals' top on the north edge, `S` corners
put the baseline on the south edge. The result is upright, in the box's own unit.
With `turn` the text reads bottom-up, the same rule turned a quarter counter-clockwise: `S`
corners start the text at the south edge and `N` corners end it at the north edge; `W` corners
put the capitals' top on the west edge and `E` corners the baseline on the east edge.
Raises `InvalidValueError` for a corner that is not one of the four.
em_height
function
em_height(font: symdef.font.FontMetrics | None, cap: float) -> float
Return the text height whose capital is `cap` tall: the exact inverse of `cap_height`.
fitted_symbol
function
fitted_symbol(symbol: symdef.model.Symbol, texts: collections.abc.Mapping[str, str], library: symdef.model.Library, text_height: float) -> symdef.model.Symbol
Return `symbol` stretched on each axis so every slot in `texts` holds its text (D95).
A text is measured as `text_box` does in `library.font` at `text_height` (module units), a
multi-line text by its whole block, and a turned slot's text along y. The extent is rounded up
to whole grid divisions; a cut across the slot's box grows by that less the slot's reserved
extent. A slot whose text fits asks for nothing and needs no cut. The growth goes through
`stretch`; the result is an ordinary symbol.
Raises:
UnknownNameError: If a text names a slot the symbol does not have.
InvalidValueError: If `text_height` is not above zero, or a slot
that must grow has no cut across its box on that axis.
fitted_table
function
fitted_table(row: symdef.model.Symbol, axis: Axis, texts: collections.abc.Sequence[collections.abc.Mapping[str, str]], library: symdef.model.Library, text_height: float, *, port_format: str, head: symdef.model.Symbol | None = None, head_texts: collections.abc.Mapping[str, str] | None = None, fit: Literal['cross', 'step'] = 'cross') -> symdef.model.Symbol
Return `table(row, len(texts), axis, head)` with each column as wide as its widest text.
Rows stack along `axis`; a column runs across it, so it grows along the other axis. A column
is a slot of the row with a `[[stretch]]` cut across its box on that axis. Its text is set in
`library.font` at `text_height` (module units); the widest text over all rows, and over the
head's texts, is rounded up to whole grid divisions. The cut grows by that less the slot's
reserved extent, never below zero, so the row's own pads stay. The growth goes through
`stretch`; the head grows at the same cuts when it has them. The result is an ordinary symbol.
With `fit="step"` the rows grow along `axis` instead, by the largest text extent along it, so
every row has the same step and no two rows' marking boxes overlap; a slot of the row needs a
`[[stretch]]` cut on `axis` across its box. The head's texts, which may span several lines,
then fit along both axes: across as above, and along `axis` at the head's own cut across the
slot, which leaves the head with no cut on `axis` for `table` to stretch. To fit a table
that is to be turned, fit it unturned with `fit="step"` and orient the result.
Args:
row: A symbol in base orientation, a slot and a cut across it for each column.
axis: "x" or "y", the way the rows stack.
texts: One mapping of slot id to text for each row; its length is the row count.
library: The library whose font and grid measure the texts.
text_height: The text height in module units, above zero.
port_format: The library's template of a row's port id, such as `"{k}.{port}"`.
head: A symbol placed once before the rows, or None.
head_texts: Slot id of the head to its text, or None; each counts in its column.
fit: "cross" to grow columns across `axis`, "step" to grow the rows along it.
Returns:
The table, as `table` returns it.
Raises:
UnknownNameError: If a text names a slot its symbol does not have.
InvalidValueError: If `text_height` is not above zero, a text's
slot has no cut across its box, the head lacks a cut where the rows grow, or the
row count is out of range, or `fit` is neither "cross" nor "step".
floor_divisions
function
floor_divisions(grid: symdef.units.Grid, mm: float) -> int
Round a length in millimetres down to whole grid divisions, the mirror of `ceil_divisions`.
A value within the tolerance below a multiple counts as that multiple, so float noise
does not drop a division.
Raises:
InvalidValueError: `mm` is negative or not finite.
from_divisions
function
from_divisions(grid: symdef.units.Grid, n: int) -> float
Return the value in module units of `n` grid divisions.
group_mm
function
group_mm(body: str, at: Pt, *, classes: str = '') -> str
Return `body` inside one `<g>` moved to `at` (x, y) in mm by `translate`.
`classes` is the group's `class`, written first and left out when empty. `body` is written
as given, so a fragment already in mm keeps its numbers; `at` has at most four decimals.
ink_boxes
function
ink_boxes(symbol: symdef.model.Symbol, texts: collections.abc.Mapping[str, str] | None = None, height: float | None = None, font: symdef.font.FontMetrics | None = None, grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None), *, on_grid: bool = False) -> symdef.boxes.InkBoxes[symdef.geometry.Box] | symdef.boxes.InkBoxes[symdef.gridtypes.GridBox]
Return the ink of the symbol as separate boxes: its body, each bound lead and each slot text.
Unlike `keepout_box` and `body_box` no declared `body` or `keepout` and no slot reservation
enlarges a box: each is the extent of what is drawn, as `element_box` measures it (`font`
measures text elements). `texts` maps slot ids to the strings drawn there at text height
`height`; each gets the extent of the string where `slot_text` places it, as `slot_box`
measures it, without the slot's reserved box. A slot with no entry has no box. With `on_grid`
every box is a `GridBox` rounded outward as `measure` rounds it (min down, max up).
Raises:
InvalidValueError: If `texts` is given without a height.
UnknownNameError: If `texts` names a slot the symbol does not have.
keepout_box
function
keepout_box(symbol: symdef.model.Symbol, font: symdef.font.FontMetrics | None = None) -> symdef.geometry.Box
Return the room the symbol needs kept clear: the body box united with its bound leads.
A bound lead is a `Line`, `Polyline` or `Arc` whose `port` is set. Slots stay text slots and
never enlarge it (D101). `font` measures the body's text as `body_box` does. A symbol that
declares its `keepout` has exactly that box.
leads
function
leads(symbol: symdef.model.Symbol, ports: collections.abc.Iterable[str]) -> symdef.model.Symbol
Return the symbol without the bound leads of every port not in `ports`.
A stroke (`Line`, `Polyline`, `Arc`) whose `port` is None, one bound to a listed port and
every other element stay, in order. The caller names the wired ports; ids are those the
symbol holds, so `1.a` after `table` or `repeat`.
Raises:
UnknownNameError: A listed id is not a port of the symbol; the key names it.
line_mm
function
line_mm(a: Pt, b: Pt, *, library: symdef.model.Library, weight: symdef.geometry.Weight, stroke: str, dash: str | None = None, classes: str = '') -> str
Return one SVG `<line>` from `a` to `b` in mm, written as `rect_mm` writes its stroke.
Raises `InvalidValueError` for a bad colour, and `UnknownNameError` for a `weight` or a
`dash` the library lacks.
load_bundle
function
load_bundle(json_path: pathlib.Path) -> symdef.model.Library
Read a resolved bundle (`bundle.json`) into a library.
The library has the bundle's standard for both `standard` and `title`, and no number pattern
(D7). Symbols are checked like a source file, plus the resolved form (`validate_bundle`).
Args:
json_path: The bundle file.
Returns:
The library, its symbols keyed by the bundle's keys.
Raises:
LibraryError: If the file cannot be read, is not JSON or is not a valid bundle. Every
finding is a `schema` finding, its message prefixed with the file name.
load_library
function
load_library(root: pathlib.Path) -> symdef.model.Library
Read `library.toml` and `symbols/*.toml` under `root`, validate, resolve and flatten them.
Args:
root: The data repo's directory.
Returns:
The library, its symbols keyed by reference number.
Raises:
LibraryError: If a file cannot be read or fails any check. `findings` holds every
finding, `library.toml` first and then the symbol files in name order, each message
prefixed with its file name.
measure
function
measure(symbol: symdef.model.Symbol, orientation: symdef.geometry.Orientation, library: symdef.model.Library, texts: collections.abc.Mapping[str, str] | None = None, text_height: float | None = None, *, attach: collections.abc.Mapping[str, symdef.model.Symbol] | None = None, stretch: collections.abc.Mapping[symdef.stretch.Axis, float] | None = None) -> symdef.gridmeasure.Measure
Return the symbol turned to `orientation`, measured in divisions of `library.grid`.
The symbol is oriented first. Extents (the body and every slot box) round outward, so a
caller never rounds; ports are positions and must sit on the grid. Text is measured with
`library.font`: the body's own text, and a slot's string when `texts` has one for its id
(at `text_height`). A slot with no string is its reserved box. A symbol in `attach` under a
slot id has its keep-out box placed at the turned slot's point and side, as a slot's reserved
box is, and united with that slot's box, so `slots[id]` and `keepout` hold it; `ink` holds it
too. `ink` is the body, the leads and the given strings alone, so an empty slot adds nothing
to it and a symbol with no ink has the origin box (D140). The attached
box is never rotated, as a slot's box is not. `stretch` maps an axis to a body length: the
symbol is stretched so (`grid=library.grid`) before it is turned (D111).
Raises:
InvalidValueError: If `texts` is given without `text_height`, or a port is off the grid,
or `stretch()` refuses a length.
UnknownNameError: If a key of `texts` or `attach` is not a slot id of the symbol.
measure_font
function
measure_font(regular: bytes, bold: bytes) -> symdef.font.FontMetrics
Measure a regular and a bold TrueType face into font metrics.
The normal advances come from the regular face, the thick ones from the bold face, each for
ASCII, Latin-1 and a few symbols. The cap height is the top of the glyph `H`, the descent the
depth of the glyph `p` and the ascent the OS/2 typographic ascender, all from the regular face.
Args:
regular: The bytes of the regular `.ttf` file.
bold: The bytes of the bold `.ttf` file.
Returns:
The metrics: named by the regular face (name ID 1) and with its typographic family (name ID
16, else ID 1) as `family`, with each face's largest advance as its default advance and no
heights.
Raises:
InvalidValueError: If either argument is not a TrueType font, the faces differ in units
per em, or a face has no glyph `H` or `p`.
nodes_of
function
nodes_of(symbol: symdef.model.Symbol) -> tuple[symdef.model.Node, ...]
Return every node of a symbol: the declared ones, then one per port in no declared node.
Ports named twice, or named by a node but absent from `ports`, are kept as declared; the
linter reports them.
on_grid
function
on_grid(v: float, tol: float = 1e-09, grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None)) -> bool
Return whether a value in module units is within `tol` of a division of `grid`.
With no grid it is the default grid, as for `snap`.
only_ports
function
only_ports(symbol: symdef.model.Symbol, ports: collections.abc.Iterable[str]) -> symdef.model.Symbol
Return the symbol with only the listed ports, their leads and their marking slots.
Every other port goes, with its bound lead and its `marking.<port>` slot, so the spare
ports of a symbol leave no keep-out and no off-grid port behind. Other elements, slots and
anchors stay, in order. Call it before `stretch`. A declared `keepout` stays as declared.
Ids are those the symbol holds, so `1.a` after `table` or `repeat`.
Raises:
UnknownNameError: A listed id is not a port of the symbol; the message names it and the
symbol.
orient
function
orient(symbol: symdef.model.Symbol, orientation: symdef.geometry.Orientation) -> symdef.model.Symbol
Return the symbol mirrored first if the orientation is an MR, then turned clockwise.
Ports, anchors and slots move as points and turn as directions; circle and arc centres move
as points and radii stay. Arc angles are normalised into [0, 360): a turn adds its degrees,
and a mirror maps t to 180 - t and swaps start with end, so the arc is still swept clockwise.
Text elements and slot boxes stay upright and unchanged; only their position moves.
Args:
symbol: The symbol in its own orientation.
orientation: One of the 8 orientations.
Returns:
A new symbol; nodes, paths and all non-geometric fields are unchanged.
orient_box
function
orient_box(box: symdef.geometry.Box, orientation: symdef.geometry.Orientation) -> symdef.geometry.Box
Return a box mirrored (if the orientation is an MR) and then turned about the origin.
It is the box of its two corners turned as points, so it matches `body_box` of the oriented
symbol, whose extents turn the same way.
orient_direction
function
orient_direction(direction: symdef.geometry.Direction, orientation: symdef.geometry.Orientation) -> symdef.geometry.Direction
Return a direction (or slot side) transformed as a vector by an orientation.
orient_point
function
orient_point(point: symdef.geometry.Point, orientation: symdef.geometry.Orientation) -> symdef.geometry.Point
Return a point mirrored (if the orientation is an MR) and then turned clockwise.
Adding 0.0 turns -0.0 into 0.0, so the result never contains a negative zero.
outline_mm
function
outline_mm(box: Box4, *, library: symdef.model.Library, weight: symdef.geometry.Weight, stroke: str, dash: str | None = None, classes: str = '') -> str
Return the unfilled outline of `box` (x, y, width, height) in mm.
Solid, it is one `<rect>` with `fill="none"`. Dashed, it is four `<line>`s drawn left to right
and top down: top, bottom, left, right. Dashes then start at the same corner on facing edges,
so they stay in phase. Raises as `rect_mm` does.
pattern_ports
function
pattern_ports(symbol: symdef.model.Symbol, edge: symdef.geometry.Direction, n: int, *, port_format: str, grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None), pitch: float | None = None, positions: collections.abc.Sequence[float] | None = None) -> symdef.model.Symbol
Return the symbol with the pattern port of `edge` expanded into n ports along the edge.
The port marked `pattern` becomes n copies along the edge (x for N and S, y for E and W): copy
k, counted from 1, takes the id `port_format` makes of `k` and the id (the library's key). By
default it stands k-1 wire pitches (`wire_pitch`, in module units) past the original.
`pitch` sets the step instead, a whole multiple of the wire pitch; `positions` sets the n
coordinates, strictly increasing, each gap a whole multiple of the wire pitch, each inside the
body. Give at most one of them. Each bound lead and `marking.<id>` slot
is copied and renamed per copy, and the originals go. Named ports on the edge stay put. Call
it after `stretch`: expanding first would widen the body, as bound leads count in it.
Raises:
InvalidValueError: If n is below 1 or above MAX_REPEAT, `edge` has no pattern port, a
copy lies outside the body or within one wire pitch of a named port, or `pitch` or
`positions` is malformed; the message names the symbol and the fix.
pole_pitch
function
pole_pitch(symbol: symdef.model.Symbol) -> float
Return the spacing between poles in module units: the symbol's `pole_pitch`, else 4.
pole_port
function
pole_port(k: int, port_id: str, port_format: str) -> str
Return the id port `port_id` takes in pole `k` (counted from 1): `port_format` filled in.
rect_mm
function
rect_mm(box: Box4, *, library: symdef.model.Library, weight: symdef.geometry.Weight, stroke: str, fill: str, dash: str | None = None, classes: str = '') -> str
Return one SVG `<rect>` over `box` (x, y, width, height) in mm.
`stroke` and `fill` are written as given, each `#rgb`, `#rrggbb` or a colour name. The stroke
width is `library.lines[weight]`; `dash` is a key of `library.dash` or `None` for a solid
line; `classes` is the element's `class`, left out when empty. Raises `InvalidValueError`
for a negative width or height or a bad colour, and `UnknownNameError` for a `weight` or a
`dash` the library lacks.
reference_cell
function
reference_cell(columns: collections.abc.Sequence[str], rows: collections.abc.Sequence[str], width: int, height: int, point: symdef.gridtypes.GridPoint) -> tuple[str, str]
Return the (column label, row label) of the cell holding `point` in a frame's reference grid.
The grid divides the content box, `width` by `height` grid divisions with its origin at the
min corner, evenly into one cell per label: `columns` left to right, `rows` top to bottom
(the smallest y first). A point on a shared edge belongs to the cell on its max side, and
a point on the far edge of the box to the last cell. The labels are the frame's own and
are returned as given.
Raises:
InvalidValueError: `columns` or `rows` is empty, or `width` or `height` is not above zero.
ReferenceCellError: `point` lies outside the box; no clamping.
reference_labels
function
reference_labels(columns: int, rows: int, *, column_kind: Literal['letters', 'numbers'] = 'letters', row_kind: Literal['letters', 'numbers'] = 'numbers', row_order: Literal['top_down', 'bottom_up'] = 'top_down') -> tuple[tuple[str, ...], tuple[str, ...]]
Return the (column labels, row labels) of a frame of `columns` by `rows` cells.
Columns run left to right and rows top to bottom, each labelled `letters` (A, B, ...; at
most 26) or `numbers` (1, 2, ...). With `row_order="bottom_up"` the row labels count from
the bottom, so the top row carries the highest. They fit `reference_cell`.
Raises:
InvalidValueError: A count is below 1, more than 26 labels are letters, or a kind or
order is not one of the values named in the message.
reference_origin
function
reference_origin(columns: collections.abc.Sequence[str], rows: collections.abc.Sequence[str], width: int, height: int, cell: tuple[str, str]) -> symdef.gridtypes.GridPoint
Return the min corner of `cell`, a (column label, row label); `reference_cell` inverted.
The grid is the one `reference_cell` takes. The origin is the first whole division that
`reference_cell` places in the cell, so `reference_cell(..., reference_origin(..., c, r))`
gives `(c, r)` for every cell. A cell narrower than one division has no such point.
Raises:
InvalidValueError: A label is not in `columns` or `rows` (the message lists the known
ones), the grid is unusable as in `reference_cell`, or a label count exceeds its
divisions.
repeat
function
repeat(symbol: symdef.model.Symbol, n: int, *, port_format: str) -> symdef.model.Symbol
Return `n` copies of a symbol placed along +x, as an ordinary symbol.
Pole k (from 1) is the symbol translated by `((k - 1) * pitch, 0)`, where the pitch is the
symbol's `pole_pitch`, default 4. Ports, and the paths, nodes and bound leads that name them,
are renamed by `port_format`, a template with the fields `{k}` and `{port}` that the caller
supplies (a pole prefix is an electrical convention; symdef keeps none, D121); every node is
listed explicitly, `potential` kept. Marking slots (`marking.in` becomes `marking.` plus the
formatted id) repeat per pole; `tag`, `value` and any other slot come from pole 1 only.
Only pole 1's path keeps `through`; a symbol with no through path repeats just the same, its
poles all without one (D106). Pole 1's anchors become the result's anchors, and if one
is `link` and `n > 1` a dashed line joins pole 1's `link` to pole n's. `pole_pitch` becomes
`n * pitch`; everything else is carried over.
Args:
symbol: A symbol in base orientation.
n: The pole count, at least 1.
port_format: The template of a pole's port id, such as `"{k}.{port}"`; required.
Returns:
The repeated symbol; with `n = 1` it is the symbol with renamed ports and slots.
Raises:
InvalidValueError: If `n` is below 1, or `port_format` is not a template with
exactly the fields `{k}` and `{port}`.
sheet_svg
function
sheet_svg(width_mm: float, height_mm: float, body: str, *, margin_mm: float) -> str
Return one sheet's SVG: `body`, drawn in mm, on a page `width_mm` by `height_mm`.
A margin `m` widens the page by `m` on every side: the viewBox starts at `-m -m` and the
width and height grow by `2m`. A margin of 0 gives the plain page. The numbers are written
as the shapes write theirs (at most four decimals, a whole number without `.0`, D141);
`margin_mm` is required, symdef holds no margin default.
slot_box
function
slot_box(slot: symdef.model.Slot, text: str | None = None, height: float | None = None, font: symdef.font.FontMetrics | None = None, grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None)) -> symdef.geometry.Box
Return the box a slot reserves: it grows from the slot point towards its side.
E and W grow horizontally and are vertically centred; N grows up and S grows down and both
are horizontally centred; C is centred on the point both ways. The box is never rotated; only
the point and side are.
With a `text` the box also holds that string drawn at text height `height` (`slot_text`
places it, `font` measures it, 0.6 em per character with no font): the union of the reserved
box and the string's extent. Without a text it is the reserved box.
Raises:
InvalidValueError: If a text is given without a height.
slot_lines
function
slot_lines(slot: symdef.model.Slot, text: str, height: float, font: symdef.font.FontMetrics | None, grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None)) -> tuple[symdef.slottext.TextPlacement, ...]
Return one placement for each newline-separated line of a text (D95).
The font's `text_block` rule sets the rows: "cap" puts them `LINE_PITCH` cap heights apart,
"grid" a whole number of `grid` divisions apart.
slot_text
function
slot_text(slot: symdef.model.Slot, text: str, height: float, font: symdef.font.FontMetrics | None, grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None)) -> symdef.slottext.TextPlacement
Return where a string of text height `height` is drawn in a slot, as one line (D95).
The font's `text_block` rule sets the baseline: "cap" from `SIDE_ALIGN` and `TURNED_ALIGN`,
"grid" as a one-row block (`slot_lines`, `grid` gives the divisions).
slots_box
function
slots_box(symbol: symdef.model.Symbol) -> symdef.geometry.Box
Return the union of the boxes the slots reserve, without the body.
A symbol without slots has the box (0, 0) to (0, 0).
snap
function
snap(v: float, grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None)) -> float
Round a value in module units to the nearest division of `grid`.
With no grid it is the default grid, `GRID_DIVISION` (0.125 M), so a call without one gives
the output it always gave.
stretch
function
stretch(symbol: symdef.model.Symbol, axis: Axis, length: float, offsets: collections.abc.Mapping[str, float] | None = None, *, grid: symdef.units.Grid | None = None) -> symdef.model.Symbol
Return the symbol grown along an axis to a body extent of `length`.
The growth, `length` minus the natural extent, is shared among the axis's cuts in proportion
to their weights. A point moves by the shares of the cuts it lies beyond: element points,
ports, anchors and slot corners. A line or polyline segment across a cut gets longer by that
cut's share; a slot box across one grows the same way. `offsets` then places each named port
at its coordinate along the axis, with its bound lead and its `marking.<port>` slot; the port
must stand on an edge parallel to the axis, on the 1 M wiring grid, inside the stretched body.
The result has no stretch on that axis. With a `grid` whose `stretch_split` is "whole" (D97),
the growth must be a whole number of divisions and splits in whole divisions: each cut but the
last, by position along the axis, takes the floor of its weighted share, the last the rest.
Args:
symbol: A symbol in base orientation with a stretch on `axis`.
axis: "x" or "y".
length: The new body extent along the axis, in module units; the natural extent at least.
offsets: Port id to coordinate along the axis, or None.
grid: The library's grid, or None for the weighted split.
Returns:
An ordinary symbol; orient it afterwards.
Raises:
InvalidValueError: If the symbol has no stretch on the axis, `length` is below the natural
extent, a circle, arc or text crosses a cut, an offset names no port or a port on
another edge, or an offset lies outside the stretched body or off the grid, or the grid
splits in whole divisions and the growth is not a whole number of them.
stretch_to_ports
function
stretch_to_ports(symbol: symdef.model.Symbol, axis: Axis, edge: symdef.geometry.Direction, n: int, *, grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None), pitch: float | None = None, positions: collections.abc.Sequence[float] | None = None) -> tuple[float, dict[str, float]]
Return the `length` and `offsets` for `stretch` so that `edge` carries n ports on the pitch.
The n ports are the first n declared on the edge, in order along the axis. The first keeps
its coordinate and the rest follow at the grid's standard wire pitch (`wire_pitch`, in
module units). The ends keep the margins the symbol declares: from the body's low side to
the first port, and from the last declared port to its high side. The length is the span
those give, never below the natural extent, so `stretch(symbol, axis, length, offsets,
grid=grid)` is valid. Call `only_ports` first so the edge holds only the ports you wire.
An edge with a pattern port (`pattern_ports`) takes any n up to MAX_REPEAT, counting copies
of that port only. The offsets hold every port on the edge: those before the pattern port keep
their coordinate, the pattern port goes to the first copy, those after it move by the growth
of the copies' span. The length grows by that span. `pitch` (a whole multiple of the wire
pitch) or `positions` (n increasing coordinates) place the copies as in `pattern_ports`, and
apply to a pattern edge only. Run `stretch`, then `pattern_ports` with the same arguments.
Raises:
InvalidValueError: If the symbol has no stretch on the axis, `edge` is not parallel to
the axis, n is below 1 or above the ports declared on the edge (MAX_REPEAT on a
pattern edge), `pitch` or `positions` is malformed or given for an edge with no
pattern port; the message names the symbol, the edge and the fix.
table
function
table(row: symdef.model.Symbol | collections.abc.Sequence[symdef.model.Symbol], n: int, axis: Axis, head: symdef.model.Symbol | None = None, *, port_format: str, grid: symdef.units.Grid | None = None, gaps: collections.abc.Sequence[float] | None = None, positions: collections.abc.Sequence[float] | None = None, head_align: Literal['start', 'center', 'end'] | None = None) -> symdef.model.Symbol
Return `n` rows placed one after another along an axis, as an ordinary symbol.
Row k (from 1) is the row translated by `k - 1` times its body extent along the axis. `row` may
be a sequence of `n` unlike symbols: each is placed so its body low edge on the axis meets a
cursor that starts at row 1's low edge and advances by that row's own extent. Ports, paths,
nodes and bound leads are renamed by `port_format`, as `repeat` does. Every slot of every row is
kept: `marking.<port>` becomes `marking.<k>.<port>`, any other `<id>` becomes `<k>.<id>`. Row
1's anchors become the result's anchors. The head keeps its own ids and comes first; if it has
a stretch on the axis, it is stretched to span all `n` rows. The head is placed as authored,
in the row's frame: author it before the first row on the axis or, with a stretch on the axis,
spanning the rows. A `between` element is drawn in rows 1 to n-1 and left out of row n; a
single row draws none, and the head is unaffected. The result has no stretch and the first
row's `pole_pitch`.
`gaps` adds space after rows 1 to n-1; `positions` instead names the coordinate of each row's
low edge, rows never overlapping. `head_align` ("start", "center" or "end") lines the narrower
of the head and the rows up in the wider along the axis; a head already wider than the rows is
then not stretched.
Args:
row: A symbol in base orientation, or a sequence of `n` of them.
n: The row count, from 1 to `MAX_REPEAT`.
axis: "x" or "y".
head: A symbol placed once before the rows, or None.
port_format: The library's template of a row's port id, such as `"{k}.{port}"`; required.
grid: The library's grid, passed to the head's `stretch`, or None.
gaps: `n - 1` numbers of at least 0, the extra space after each row but the last.
positions: `n` coordinates for the rows' low edges, or None; not with `gaps`.
head_align: How the head lines up with the rows along the axis, or None for as authored.
Returns:
The table, carrying the first row's name, kind, status, reference and lint allowances.
Raises:
InvalidValueError: If `n` is outside 1 to `MAX_REPEAT` or differs from the number of rows
given, `gaps` or `positions` has the wrong length, a gap is below zero, rows overlap,
both are given, `head_align` is not one of the three, or the head's stretch cannot
span the rows.
tag_roots
function
tag_roots(symbol: symdef.model.Symbol, orientation: symdef.geometry.Orientation, library: symdef.model.Library, *, gap: float, marking_height: float) -> tuple[symdef.tagroots.TextRoot, symdef.tagroots.TextRoot, symdef.tagroots.TextRoot, symdef.tagroots.TextRoot]
Return the text root of the symbol's tag slot and its three reflections.
The roots are `TextRoot`s in whole divisions of `library.grid`, in the frame `measure` uses,
in the order top-left, bottom-left, top-right, bottom-right. The top-left root is the text
root of the `tag` slot. When a port leaves the top edge of the body, the point is `gap` to
the left of the leftmost such port and level with the baseline on which symdef sets a text
in that port's `marking.<port>` slot; if that point lies inside the body, it is lifted to
the body's top edge. With no such port, the point is the body's left edge, `gap` above its
top edge. A `tag` slot lying wholly inside the body gives that slot's start edge and baseline
in all four. The other three roots reflect the first through the body's centre, left-right,
top-bottom or both, and each reflection swaps `"right"` with `"left"` or `"baseline"` with
`"top"`, so a reflected text hangs away from the body as the original does.
`gap` is in pole units: it is multiplied by `pole_pitch(symbol)` and by
`library.grid.divisions_per_module`, and rounded to the nearest whole division, halves up.
`marking_height` is the height `slot_text` takes, for the text in a `marking.<port>` slot
and for the text in a `tag` slot lying inside the body.
Raises:
UnknownNameError: If the symbol has no `tag` slot.
InvalidValueError: If `gap` is negative or `marking_height` is not above zero.
text_boxes_prefix
function
text_boxes_prefix(slot: symdef.model.Slot, lines: collections.abc.Sequence[str], height: float, font: symdef.font.FontMetrics | None, grid: symdef.units.Grid = Grid(module_mm=2.5, divisions_per_module=8, wire_pitch=8, wire_pitch_fine=4, stretch_split='weight', declared_outline_margin=None)) -> tuple[symdef.geometry.Box, ...]
Return the box of each prefix of `lines`: the k-th is `text_box` of the first k lines.
Each distinct line is measured once for all prefixes. No lines give no boxes. A line holding
a newline raises `InvalidValueError`: give each row as its own entry.
text_divisions
function
text_divisions(grid: symdef.units.Grid, font: symdef.font.FontMetrics | None, cap_height_mm: float) -> int
Return the em box of a text whose capital is `cap_height_mm` tall, in whole grid divisions.
It measures the em box, the line a text occupies, not the ink of its capitals.
text_footprint
function
text_footprint(font: symdef.font.FontMetrics | None, text: str, cap_height_mm: float, grid: symdef.units.Grid, *, turn: bool = False) -> tuple[int, int]
Return the footprint of a text of one or more lines in whole divisions, as (width, height).
The text is set so its capital is `cap_height_mm` tall. Upright it is its widest line by the
block height, each rounded up. The block height follows the font's `text_block` rule: by "cap"
one em box plus `LINE_PITCH` cap heights for each further line, by "grid" a whole row of
divisions for each line. The height is the em box plus the extra lines' pitch, so it holds the
drawn block (cap plus extra), which is about 0.28 em smaller. With `turn`, a turned slot's text
that reads bottom-up, the two are exchanged: thickness by reading length, the `box` a
`turn = true` slot declares.
text_tag
function
text_tag(content: str, point: symdef.geometry.Point, height_mm: float, *, anchor: Anchor, font_family: str, turn: bool = False, weight: symdef.geometry.Weight = <Weight.NORMAL: 0.1>, tint: str | None = None, muted: str | None = None, classes: str = '', at: At = 'baseline', font: symdef.font.FontMetrics | None = None) -> str
Return the SVG `<text>` fragment in millimetres, anchored at `point`: one tag per line.
A `content` with line breaks stacks its lines as slot text does (D95): `LINE_PITCH` cap
heights apart, each row upright (or turned as one) and in reading order, the first line at
`point` and the next ones after it, or the block centred on `point` with `at="centre"`. A
one-line `content` gives the one tag it always did (D145).
`height_mm` is the font size. `anchor` says which end of the text sits on `point`. `turn`
rotates the text -90 degrees about the baseline point. `Weight.THICK` is `font-weight="bold"`.
The fill is `muted` when given, else `tint`, else black; each is `#rgb`, `#rrggbb` or a colour
name. `font_family` is escaped here for the attribute. `classes` is the element's `class`,
left out when empty.
`at` says what `point` is across the line. `baseline` (the default) is the baseline. `top` is
the top of the em box, so the baseline lies `ascent` below it (right of it when turned).
`centre` is the middle of the em box, so the baseline lies `ascent - height_mm / 2` below
it; with `turn` the text then reads upward centred on `point`. `top` and `centre` take
`ascent` from `font`. Raises `InvalidValueError` for a bad colour, an `at` that is not one of
the three, and `top` or `centre` with no `font`.
text_width
function
text_width(font: symdef.font.FontMetrics | None, text: str, height: float, weight: symdef.geometry.Weight = <Weight.NORMAL: 0.1>) -> float
Return the width of a text in module units when set at `height` (one em).
With a font it is the sum of the advances of the weight's table, in ems, times `height`. With
no font it is 0.6 em per character.
to_divisions
function
to_divisions(grid: symdef.units.Grid, v: float) -> int
Return how many grid divisions a value in module units spans; the value must sit on the grid.
Off-grid values raise, so a drawing never gets a half division by accident.
to_fragment
function
to_fragment(symbol: symdef.model.Symbol, *, tint: str | None = None, muted: str | None = None, texts: collections.abc.Mapping[str, str] | None = None, required_slots: collections.abc.Sequence[str] = ()) -> str
Render a symbol as a placeable SVG fragment: a `<g>` of its plain elements only.
For embedding one placed symbol inside a larger document the caller assembles. The caller
wraps the result in its own `<g transform="...">` to position, orient and scale it; this
function applies none of its own. No title and no annotations. Elements are drawn exactly as
in `to_svg`'s plain mode, in module units. The strings in `texts` follow them (D63).
Args:
symbol: The symbol to render, already oriented and repeated by the caller (via
`orient`/`repeat`), exactly as `to_svg` expects its own `symbol` argument.
tint: Fill colour of the tinted closed polylines, as in `to_svg`.
muted: The colour a muted symbol is drawn in, or None. Muted draws every stroke, every
text and every solid or tint fill in that colour, and every line style as a dash and
a gap each as long as the normal stroke width. An unfilled shape stays unfilled.
texts: The string to draw in each slot, by slot id, or None to draw none. A slot without
a string, or with an empty one, draws nothing. A string is aligned by the slot side
(E start, W end, N and S middle, as the sample texts of `to_svg`), sized to fit the
slot box (at most 1 M), black or in the muted colour, with no class. It is never
wrapped.
required_slots: The slots the symbol must have a string for, shaped as `lint`'s argument
(`marking.<port>` means one per port). Checked only when `texts` is given; an empty
string satisfies it. The default checks nothing.
Returns:
The `<g>...</g>` fragment text, ending with a single newline.
Raises:
UnknownNameError: A key of `texts` is not a slot id of the symbol; the key names it. Checked
before anything is drawn, also for an empty string.
InvalidValueError: The tint or the muted colour is not a hex colour or a colour name, or
`texts` is given and misses a required slot; the message names it and the symbol.
to_fragment_mm
function
to_fragment_mm(symbol: symdef.model.Symbol, *, module_mm: float, weights_mm: collections.abc.Mapping[symdef.geometry.Weight, float] | None = None, dash_mm: tuple[float, float] | None = None, dash_dot_mm: tuple[float, float, float, float] | None = None, font_family: str, font_mm: float, cap_ratio: float | None = None, tint: str | None = None, muted: str | None = None, texts: collections.abc.Mapping[str, str] | None = None, required_slots: collections.abc.Sequence[str] = (), library: symdef.model.Library | None = None) -> str
Render a symbol as a `<g>` fragment in millimetres, with no `scale(`.
The one transform is the `rotate(-90)` on the text element of a turned slot's string.
A different output from `to_fragment`, whose contract is module units with the caller
scaling. Here every coordinate and radius is multiplied by `module_mm`, and the stroke widths,
the dash pattern and the font size are the caller's absolute millimetres, so they do not
change with the module. Elements and their order are those of `to_fragment`. A text element
ignores its `height`: it is drawn at `font_mm`, middle-anchored, with its capitals centred on
its position.
Args:
symbol: The symbol to render, already oriented and repeated by the caller.
module_mm: Millimetres per module unit.
weights_mm: Stroke width in mm for each `Weight` the symbol uses. None takes
`library.lines`; given, it wins over the library as a whole.
dash_mm: Dash and gap lengths in mm of a dashed element. None takes
`library.dash["dashed"]`.
dash_dot_mm: Dash, gap, dot and gap lengths in mm of a dash-dot element. None takes
`library.dash["dash_dot"]`, and is then an error if a dash-dot element is drawn.
font_family: CSS font family of the text, escaped here for the attribute.
font_mm: Font size in mm of every text element.
cap_ratio: Capital height as a fraction of the font size; the baseline sits half of it
below the text position. None takes the library font's `cap_height / units_per_em`.
tint: Fill colour of the tinted closed polylines: `#rgb`, `#rrggbb` or a colour name.
None draws them unfilled. Checked even when no element is tinted.
muted: The colour a muted symbol is drawn in, or None. As in `to_fragment`, with the dash
and gap of the normal stroke width taken from `weights_mm`; `dash_mm` and
`dash_dot_mm` are then not used.
texts: The string to draw in each slot, by slot id, or None to draw none. A slot without
a string, or with an empty one, draws nothing. Each string follows the elements, in
slot id order, at `font_mm` in `font_family`, aligned by the slot side (E start, W
end, N and S middle; the baseline is half a capital below the slot point for E and W,
on it for N and one capital below it for S). A turned slot (`turn`) reads bottom-up:
N starts at the slot point, S ends there, E and W centre the text on it, and the text
element carries `rotate(-90)` about its baseline point. It is never measured, shrunk
or wrapped.
required_slots: The slots the symbol must have a string for, as in `to_fragment`.
library: The library whose `lines` and `dash` give each size the caller leaves None, so
one call to `Library.with_settings` changes every width and dash drawn here.
Returns:
The `<g>...</g>` fragment text, ending with a single newline.
Raises:
UnknownNameError: A weight an element uses, or `Weight.NORMAL` when muted, is missing from
`weights_mm` (or from `library.lines` when that is used); the key names it. Also a
dashed element is drawn and neither `dash_mm` nor `library.dash["dashed"]` is there.
Also a key of `texts` that is not a slot id
of the symbol, checked before anything is drawn, also for an empty string.
InvalidValueError: `cap_ratio` and `library` are both None, naming both. The tint or
the muted colour is not a hex colour or a colour name, a
dash-dot element is drawn and `dash_dot_mm` is None, or `texts` is given and misses a
required slot; the message names it and the symbol.
to_placed_fragment
function
to_placed_fragment(symbol: symdef.model.Symbol, orientation: symdef.geometry.Orientation, at: symdef.gridtypes.GridPoint, library: symdef.model.Library, *, tint: str | None = None, muted: str | None = None, texts: collections.abc.Mapping[str, str] | None = None, required_slots: collections.abc.Sequence[str] = ()) -> str
Return the symbol turned to `orientation` and drawn with its origin at `at`.
It is `to_fragment` of the oriented symbol inside one `<g transform="translate(X Y)">`, where
X and Y are `at` turned into module units by `library.grid`. The options are those of
`to_fragment`. The float forms (`to_fragment`, `to_fragment_mm`, `to_svg`) are unchanged.
Raises:
UnknownNameError: A key of `texts` is not a slot id of the symbol.
InvalidValueError: As `to_fragment`.
to_svg
function
to_svg(symbol: symdef.model.Symbol, *, module_mm: float = 2.5, annotate: bool = False, texts: collections.abc.Mapping[str, str] | None = None, tint: str | None = None) -> str
Render a symbol as an SVG document.
The viewBox is in module units, the extent grown by a margin of 1 on every side; width and
height are the viewBox size times module_mm, in mm. Plain, the extent is the body box; with
annotate it is the keep-out box, every port label box, every anchor and its label, every slot
label and the start of every lane, so no annotation is clipped. The elements are drawn first,
then the annotations, then the sample texts. The output is deterministic.
Args:
symbol: The symbol to render.
module_mm: Millimetres per module unit.
annotate: Draw the grid, the body and keep-out boxes, the slot boxes, the anchors and the
ports with their ids and wire lanes.
texts: Sample text per slot id. Each is drawn upright in its slot box (class
`sample-text`) in the largest font of at most 1 M that fits the box; an id that is
not a slot of the symbol is ignored. Drawn in both modes.
tint: Fill colour of the tinted closed polylines: `#rgb`, `#rrggbb` or a colour name.
None draws them unfilled. Checked even when no element is tinted.
Returns:
The SVG text, ending with a single newline.
Raises:
InvalidValueError: The tint is not a hex colour or a colour name.
translate
function
translate(symbol: symdef.model.Symbol, dx: float, dy: float) -> symdef.model.Symbol
Return the symbol shifted by (dx, dy).
Args:
symbol: The symbol to shift.
dx: Horizontal shift, positive to the right.
dy: Vertical shift, positive downwards.
Returns:
A new symbol; arc angles, directions and slot boxes are unchanged.
wire
function
wire(library: symdef.model.Library, style_id: str, points: collections.abc.Sequence[symdef.geometry.Point] | collections.abc.Sequence[tuple[float, float]], *, closed: bool = False, lanes: int = 1, pitch: float | None = None) -> symdef.model.Symbol
Return an element symbol that draws `lanes` parallel polylines through `points`.
Args:
library: The library whose `wires` name the style.
style_id: The id of one of its wire styles.
points: The corners in module units, as `Point`s or (x, y) pairs.
closed: True to join the last corner back to the first, so the closing corner is joined
like the others instead of ending in two butt caps (D95).
lanes: How many parallel polylines to draw. Lane 0 lies on `points`; lane k is moved
k * `pitch` towards +y on a horizontal run and +x on a vertical run, mitred at the
corners (D99).
pitch: The distance between lanes in module units; default `library.grid.wire_pitch`.
Returns:
An unverified element symbol with one polyline per lane in lane order, open unless
`closed`, and no ports, slots, nodes or paths.
Raises:
UnknownNameError: If the library has no wire style with this id.
InvalidValueError: If fewer than two points are given, or fewer than three when `closed`;
if `lanes` is below 1 or `pitch` is not above 0; if `lanes` is above 1 and the wire
is `closed`, or a run is not horizontal or vertical or has no length.