Skip to content
Edit this page

ictdesigntools.draw

Drawings described once and written out as SVG, PDF or DXF.

A Drawing holds shapes (Rect, Circle, Ring, Polygon, Polyline, Arc, Line, Text, Dim, Earth) in real units, millimetres by default, with y down as in SVG. Group moves, turns or scales shapes together; a Component is a part drawn once and placed many times with Use. Shapes take their look from named Style\s, so colour and line weight live in one place and a theme can restyle a drawing for a dark page or for print. Meta marks what a part is (an id, a kind and data) so a page can make it interactive.

Outputs:

  • to_svg / svg_file: the standard library only.
  • draw.pdf.to_reportlab / draw.pdf.pdf_file: needs ictdesigntools[pdf].
  • draw.dxf.to_dxf: needs ictdesigntools[dxf]; components become blocks.

to_svg(classes=True) names each styled shape's class after its style, so a page's CSS can theme it (dark mode); to_svg(interactive=True) with interactive_script() served on the page makes parts with a Meta id hoverable, focusable and selectable.

draw.graph draws network topologies (a networkx graph, node-link JSON or its own Graph) in layered or tree layouts with attribute styles and highlighted routes.

draw.text estimates text widths to fit labels, and draw.layout places things in grids, stacks and rack units and wraps outlines around circles.

>>> from ictdesigntools.draw import Drawing, Rect, Text, to_svg
>>> d = Drawing(title="Panel").add(Rect(0, 0, 482.6, 44.45, stroke="#000"),
...                                Text(241.3, 22.2, "24-port patch panel", 8))
>>> to_svg(d.fit(5)).startswith("<svg")
True

Drawing dataclass

Drawing(
    view: tuple[float, float, float, float] = (
        0.0,
        0.0,
        100.0,
        100.0,
    ),
    items: list = list(),
    title: str = "",
    desc: str = "",
    units: str = "mm",
    stroke: float = 0.35,
    font: float = 2.5,
    layers: dict[str, Layer] = dict(),
    styles: dict[str, Style] = dict(),
)

A drawing in units ("mm", the default, or "in"), framed by view (x, y, width, height; fit() sets it from the content).

style

style(it, theme: dict[str, Style] | None = None) -> Style

The look of a shape: its own values, then its named style (from theme first, then the drawing's), then the defaults.

Source code in src/ictdesigntools/draw/drawing.py
def style(self, it, theme: dict[str, Style] | None = None) -> Style:
    """The look of a shape: its own values, then its named style (from ``theme`` first,
    then the drawing's), then the defaults."""
    named = Style()
    name = getattr(it, "style", "")
    if name:
        if theme and name in theme:
            named = theme[name].over(self.styles.get(name, Style()))
        else:
            named = self.styles.get(name, Style())
    s = own_style(it).over(named).over(DEFAULT_STYLE)
    if s.stroke is None and isinstance(it, (Line, Polyline, Arc)):  # lines are always inked
        s = Style(stroke=INK).over(s)
    return s

components

components() -> list[Component]

Every component placed, inner ones first, each once.

Source code in src/ictdesigntools/draw/drawing.py
def components(self) -> list[Component]:
    """Every component placed, inner ones first, each once."""
    found: dict[str, Component] = {}

    def visit(items):
        for it in items:
            if isinstance(it, Group):
                visit(it.items)
            elif isinstance(it, Use):
                c = it.component
                if c.name in found:
                    if found[c.name] is not c and found[c.name] != c:
                        raise ValueError(f"Two different components are named {c.name!r}.")
                    continue
                visit(c.items)
                found[c.name] = c

    visit(self.items)
    return list(found.values())

walk

Every shape with its transform to the drawing and its layer, components expanded.

Source code in src/ictdesigntools/draw/drawing.py
def walk(self) -> Iterator[tuple[object, Transform, str]]:
    """Every shape with its transform to the drawing and its layer, components expanded."""
    yield from walk(self.items)

bounds

bounds() -> tuple[float, float, float, float] | None

The content's extent (x0, y0, x1, y1), or None when empty.

Source code in src/ictdesigntools/draw/drawing.py
def bounds(self) -> tuple[float, float, float, float] | None:
    """The content's extent (x0, y0, x1, y1), or None when empty."""
    boxes = [b for it, t, _ in self.walk() if (b := shape_bounds(it, t, self.font))]
    if not boxes:
        return None
    return (min(b[0] for b in boxes), min(b[1] for b in boxes),
            max(b[2] for b in boxes), max(b[3] for b in boxes))  # fmt: skip

fit

fit(margin: float = 0.0) -> Drawing

Frame the content with margin around it.

Source code in src/ictdesigntools/draw/drawing.py
def fit(self, margin: float = 0.0) -> Drawing:
    """Frame the content with ``margin`` around it."""
    b = self.bounds()
    if b:
        self.view = (b[0] - margin, b[1] - margin, b[2] - b[0] + 2 * margin,
                     b[3] - b[1] + 2 * margin)  # fmt: skip
    return self

Layer dataclass

Layer(color: int = 7, linetype: str = '')

A CAD layer: an AutoCAD colour index and an optional linetype.

Arc dataclass

Arc(
    cx: float,
    cy: float,
    r: float,
    start: float,
    end: float,
    stroke: str | None = None,
    width: float | None = None,
    dash: bool | None = None,
    layer: str = "0",
    style: str = "",
    meta: Meta = Meta(),
)

Part of a circle from start to end degrees, counter-clockwise as seen on the page, with 0 pointing right.

Component dataclass

Component(name: str, items: tuple = (), title: str = '')

A part drawn once, in its own coordinates, and placed many times with Use: a 1U panel, a connector, a duct bundle. SVG writes it once in <defs>; DXF makes it a block. name must be unique in the drawing.

Dim dataclass

Dim(
    x1: float,
    y1: float,
    x2: float,
    y2: float,
    text: str,
    offset: float,
    vertical: bool = False,
    layer: str = "DIM",
)

A linear dimension between two points, drawn offset to one side. Its text size is the drawing's font.

Earth dataclass

Earth(
    x: float,
    y: float,
    w: float,
    h: float,
    holes: tuple[
        tuple[float, float, float, float], ...
    ] = (),
    tile: float = 25.0,
    layer: str = "EARTH",
)

Soil in the CAD "EARTH" style over a rectangle, leaving out the holes (rectangles): alternating tiles of three horizontal and three vertical strokes. In DXF it is a native EARTH hatch, so CAD users can edit it.

Group dataclass

Group(
    items: tuple = (),
    transform: Transform = IDENTITY,
    title: str = "",
    layer: str = "",
    meta: Meta = Meta(),
)

Shapes moved, turned or scaled together. layer, when set, is given to children left on layer "0".

Hatch dataclass

Hatch(
    pattern: str = "SOLID",
    scale: float = 1.0,
    color: int | None = None,
    angle: float = 0.0,
    outline: bool = False,
)

How a closed shape is filled in CAD: "SOLID" or a named pattern such as "AR-CONC", "ANSI31" or "EARTH", with its scale and an AutoCAD colour index (None: the layer's colour).

Meta dataclass

Meta(
    id: str = "",
    kind: str = "",
    data: tuple[tuple[str, str], ...] = (),
)

What a part is, for interactive pages and cross-references: an id unique in the drawing, a kind ("port", "conduit", …) and string data. The SVG output writes them as data-id, data-kind and data-<key> attributes.

Polygon dataclass

Polygon(
    points: tuple[tuple[float, float], ...],
    fill: str | None = None,
    stroke: str | None = None,
    width: float | None = None,
    dash: bool | None = None,
    layer: str = "0",
    title: str = "",
    style: str = "",
    meta: Meta = Meta(),
)

A closed outline through points.

Polyline dataclass

Polyline(
    points: tuple[tuple[float, float], ...],
    stroke: str | None = None,
    width: float | None = None,
    dash: bool | None = None,
    layer: str = "0",
    title: str = "",
    style: str = "",
    meta: Meta = Meta(),
)

An open path through points, e.g. a cable's route or a leader.

Ring dataclass

Ring(
    cx: float,
    cy: float,
    r_outer: float,
    r_inner: float,
    color: str,
    bore: str = "#fcfcfb",
    layer: str = "0",
    title: str = "",
    edge: str | None = None,
    cad_color: bool = False,
    meta: Meta = Meta(),
    style: str = "",
)

A tube wall between two radii, with its bore filled: a conduit, duct or tube in section. edge outlines both radii so a light wall still shows; cad_color carries the wall colour into CAD.

Style dataclass

Style(
    fill: str | None = None,
    stroke: str | None = None,
    width: float | None = None,
    dash: bool | None = None,
    color: str | None = None,
    hatch: Hatch | None = None,
    cad_color: bool | None = None,
)

A named look. None leaves a value to the next style down (the drawing's, then the built-in default); colours are CSS hex strings.

over

over(base: Style) -> Style

This style with base filling what it leaves unset.

Source code in src/ictdesigntools/draw/shapes.py
def over(self, base: Style) -> Style:
    """This style with ``base`` filling what it leaves unset."""
    pairs = zip(_fields(self), _fields(base), strict=True)
    return Style(*(mine if mine is not None else theirs for mine, theirs in pairs))

Use dataclass

Use(
    component: Component,
    transform: Transform = IDENTITY,
    title: str = "",
    layer: str = "",
    meta: Meta = Meta(),
)

A component placed by transform.

Transform dataclass

Transform(
    a: float = 1.0,
    b: float = 0.0,
    c: float = 0.0,
    d: float = 1.0,
    e: float = 0.0,
    f: float = 0.0,
)

scale_factor property

scale_factor: float

How much lengths grow, for a similarity (uniform scale with rotation or mirror).

is_similarity property

is_similarity: bool

True when circles stay circles: no shear or uneven scale.

rotation property

rotation: float

The page rotation of the x axis, in degrees counter-clockwise as seen on the page.

rotate staticmethod

rotate(
    degrees: float, cx: float = 0.0, cy: float = 0.0
) -> Transform

Counter-clockwise as seen on the page (y down), about (cx, cy).

Source code in src/ictdesigntools/draw/transform.py
@staticmethod
def rotate(degrees: float, cx: float = 0.0, cy: float = 0.0) -> Transform:
    """Counter-clockwise as seen on the page (y down), about (cx, cy)."""
    t = math.radians(-degrees)
    cos, sin = math.cos(t), math.sin(t)
    r = Transform(cos, sin, -sin, cos)
    if cx or cy:
        return Transform.translate(cx, cy) @ r @ Transform.translate(-cx, -cy)
    return r

mirror_x staticmethod

mirror_x() -> Transform

Mirror left to right (about the y axis).

Source code in src/ictdesigntools/draw/transform.py
@staticmethod
def mirror_x() -> Transform:
    """Mirror left to right (about the y axis)."""
    return Transform(-1.0, 0.0, 0.0, 1.0)

then

then(other: Transform) -> Transform

This transform followed by other: Transform.rotate(90).then(translate(5)).

Source code in src/ictdesigntools/draw/transform.py
def then(self, other: Transform) -> Transform:
    """This transform followed by ``other``: ``Transform.rotate(90).then(translate(5))``."""
    return other @ self

vector

vector(x: float, y: float) -> tuple[float, float]

A direction, without the translation.

Source code in src/ictdesigntools/draw/transform.py
def vector(self, x: float, y: float) -> tuple[float, float]:
    """A direction, without the translation."""
    return self.a * x + self.c * y, self.b * x + self.d * y

svg

svg() -> str

The SVG transform attribute value.

Source code in src/ictdesigntools/draw/transform.py
def svg(self) -> str:
    """The SVG ``transform`` attribute value."""
    if self.a == 1 and self.b == 0 and self.c == 0 and self.d == 1:
        return f"translate({_f(self.e)} {_f(self.f)})"
    return "matrix(" + " ".join(_f(v) for v in (self.a, self.b, self.c, self.d, self.e,
                                                 self.f)) + ")"  # fmt: skip

interactive_css

interactive_css() -> str

A starting stylesheet for the classes the script sets.

Source code in src/ictdesigntools/draw/assets.py
def interactive_css() -> str:
    """A starting stylesheet for the classes the script sets."""
    return files(__package__).joinpath("static/interactive.css").read_text(encoding="utf-8")

interactive_script

interactive_script() -> str

The JavaScript (no dependencies) for interactive drawings.

Source code in src/ictdesigntools/draw/assets.py
def interactive_script() -> str:
    """The JavaScript (no dependencies) for interactive drawings."""
    return files(__package__).joinpath("static/interactive.js").read_text(encoding="utf-8")

circle_hull

circle_hull(
    circles, steps: int = 72
) -> tuple[tuple[float, float], ...]

The convex outline around circles (cx, cy, r): how a sheath shrinks onto what it holds, whatever their sizes.

Source code in src/ictdesigntools/draw/layout.py
def circle_hull(circles, steps: int = 72) -> tuple[tuple[float, float], ...]:
    """The convex outline around circles (cx, cy, r): how a sheath shrinks onto what it
    holds, whatever their sizes."""
    return convex_hull(
        (round(cx + r * math.cos(a), 9), round(cy + r * math.sin(a), 9))
        for cx, cy, r in circles
        for a in (2 * math.pi * i / steps for i in range(steps))
    )

convex_hull

convex_hull(points) -> tuple[tuple[float, float], ...]

The convex outline around points, anticlockwise (Andrew's monotone chain).

Source code in src/ictdesigntools/draw/layout.py
def convex_hull(points) -> tuple[tuple[float, float], ...]:
    """The convex outline around points, anticlockwise (Andrew's monotone chain)."""
    pts = sorted(set(points))
    if len(pts) < 3:
        return tuple(pts)

    def cross(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

    lower, upper = [], []
    for p in pts:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    for p in reversed(pts):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    return tuple(lower[:-1] + upper[:-1])

grid

grid(
    count: int,
    columns: int,
    pitch_x: float,
    pitch_y: float,
    x: float = 0.0,
    y: float = 0.0,
) -> list[tuple[float, float]]

count positions filling rows of columns left to right, then top to bottom.

Source code in src/ictdesigntools/draw/layout.py
def grid(count: int, columns: int, pitch_x: float, pitch_y: float, x: float = 0.0,
         y: float = 0.0) -> list[tuple[float, float]]:  # fmt: skip
    """``count`` positions filling rows of ``columns`` left to right, then top to bottom."""
    if columns < 1:
        raise ValueError("columns must be at least 1")
    return [(x + (i % columns) * pitch_x, y + (i // columns) * pitch_y) for i in range(count)]

rack_y

rack_y(
    u: float, height_u: float, rack_u: int, top: float = 0.0
) -> float

The top edge of equipment height_u high whose lowest unit is u (numbered 1 from the bottom, as on the rails) in a rack rack_u high drawn from top down.

Source code in src/ictdesigntools/draw/layout.py
def rack_y(u: float, height_u: float, rack_u: int, top: float = 0.0) -> float:
    """The top edge of equipment ``height_u`` high whose lowest unit is ``u`` (numbered 1 from
    the bottom, as on the rails) in a rack ``rack_u`` high drawn from ``top`` down."""
    if not (1 <= u and u + height_u - 1 <= rack_u):
        raise ValueError(f"U{u:g} to U{u + height_u - 1:g} is outside a {rack_u}U rack.")
    return top + (rack_u - (u + height_u - 1)) * RACK_UNIT_MM

stack

stack(
    sizes: list[float], gap: float = 0.0, start: float = 0.0
) -> list[float]

Where each of a run of sizes starts when laid end to end with gap between them.

Source code in src/ictdesigntools/draw/layout.py
def stack(sizes: list[float], gap: float = 0.0, start: float = 0.0) -> list[float]:
    """Where each of a run of sizes starts when laid end to end with ``gap`` between them."""
    out, at = [], start
    for s in sizes:
        out.append(at)
        at += s + gap
    return out

svg_file

svg_file(
    drawing: Drawing, theme: dict[str, Style] | None = None
) -> bytes

A standalone SVG file, at full size in the drawing's units.

Source code in src/ictdesigntools/draw/svg.py
def svg_file(drawing: Drawing, theme: dict[str, Style] | None = None) -> bytes:
    """A standalone SVG file, at full size in the drawing's units."""
    body = to_svg(drawing, standalone=True, theme=theme)
    return ('<?xml version="1.0" encoding="UTF-8"?>\n' + body + "\n").encode("utf-8")

to_svg

to_svg(
    drawing: Drawing,
    css_class: str = "",
    standalone: bool = False,
    theme: dict[str, Style] | None = None,
    id_prefix: str = "",
    classes: bool = False,
    class_prefix: str = "d-",
    interactive: bool = False,
) -> str

The drawing as an <svg> element.

standalone adds the namespace and a physical size for a file; id_prefix keeps component ids unique when a page holds several drawings; theme overrides named styles. classes also gives every shape with a named style the class <class_prefix><name>, so a page's stylesheet can restyle it (a dark theme, a highlight) over the colours written as attributes, which stay as the fallback. interactive marks the drawing for the optional script (interactive_script()): hover, select, keyboard focus and a draw:select event for parts that carry a Meta id.

Source code in src/ictdesigntools/draw/svg.py
def to_svg(drawing: Drawing, css_class: str = "", standalone: bool = False,
           theme: dict[str, Style] | None = None, id_prefix: str = "", classes: bool = False,
           class_prefix: str = "d-", interactive: bool = False) -> str:  # fmt: skip
    """The drawing as an ``<svg>`` element.

    ``standalone`` adds the namespace and a physical size for a file; ``id_prefix`` keeps
    component ids unique when a page holds several drawings; ``theme`` overrides named styles.
    ``classes`` also gives every shape with a named style the class ``<class_prefix><name>``, so
    a page's stylesheet can restyle it (a dark theme, a highlight) over the colours written as
    attributes, which stay as the fallback. ``interactive`` marks the drawing for the optional
    script (``interactive_script()``): hover, select, keyboard focus and a ``draw:select``
    event for parts that carry a ``Meta`` id."""
    x, y, w, h = drawing.view
    out = [
        f'<svg viewBox="{_f(x)} {_f(y)} {_f(w)} {_f(h)}" role="img"',
        f' class="{escape(css_class)}"' if css_class else "",
        " data-draw-interactive" if interactive else "",
        ' xmlns="http://www.w3.org/2000/svg"' if standalone else "",
        f' width="{_f(w)}{drawing.units}" height="{_f(h)}{drawing.units}"' if standalone else "",
        ' font-family="Helvetica, Arial, sans-serif">',
        f"<title>{escape(drawing.title)}</title>" if drawing.title else "",
        f"<desc>{escape(drawing.desc)}</desc>" if drawing.desc else "",
    ]
    r = _Renderer(drawing, theme, id_prefix, class_prefix if classes else None)
    components = drawing.components()
    if components:
        out.append("<defs>")
        for c in components:
            out.append(f'<g id="{r.component_id(c)}">')
            r.items(c.items, out)
            out.append("</g>")
        out.append("</defs>")
    r.items(drawing.items, out)
    out.append("</svg>")
    return "".join(out)

fit_size

fit_size(
    text: str,
    size: float,
    width: float,
    smallest: float = 0.0,
) -> float | None

The largest size up to size at which text fits in width, or None when it would have to be smaller than smallest.

Source code in src/ictdesigntools/draw/text.py
def fit_size(text: str, size: float, width: float, smallest: float = 0.0) -> float | None:
    """The largest size up to ``size`` at which ``text`` fits in ``width``, or None when it
    would have to be smaller than ``smallest``."""
    natural = text_width(text, size)
    if natural <= width:
        return size
    fitted = size * width / natural
    return fitted if fitted >= smallest and fitted > 0 else None

text_width

text_width(text: str, size: float) -> float

The width of text set at size (the em height), in the same units.

Source code in src/ictdesigntools/draw/text.py
def text_width(text: str, size: float) -> float:
    """The width of ``text`` set at ``size`` (the em height), in the same units."""
    total = 0
    for ch in text:
        i = ord(ch) - 32
        total += _WIDTHS[i] if 0 <= i < len(_WIDTHS) else _EXTRA.get(ch, _OTHER)
    return total * size / 1000

truncate

truncate(
    text: str,
    size: float,
    width: float,
    ellipsis: str = "…",
) -> str

text cut short with ellipsis to fit width at size; "" if nothing fits.

Source code in src/ictdesigntools/draw/text.py
def truncate(text: str, size: float, width: float, ellipsis: str = "…") -> str:
    """``text`` cut short with ``ellipsis`` to fit ``width`` at ``size``; "" if nothing fits."""
    if text_width(text, size) <= width:
        return text
    room = width - text_width(ellipsis, size)
    out = ""
    for ch in text:
        if text_width(out + ch, size) > room:
            break
        out += ch
    return out.rstrip() + ellipsis if out.strip() else ""

wrap

wrap(text: str, size: float, width: float) -> list[str]

text broken into lines at spaces to fit width; a word longer than the width is left on a line of its own.

Source code in src/ictdesigntools/draw/text.py
def wrap(text: str, size: float, width: float) -> list[str]:
    """``text`` broken into lines at spaces to fit ``width``; a word longer than the width is
    left on a line of its own."""
    lines: list[str] = []
    line = ""
    for word in text.split():
        trial = f"{line} {word}" if line else word
        if line and text_width(trial, size) > width:
            lines.append(line)
            line = word
        else:
            line = trial
    if line:
        lines.append(line)
    return lines