Skip to content

Python API and CLI

The uniwire package exposes a small functional API around the Document model, and a uniwire command-line tool. To write documents in Python, see the code-first API.

pip install uniwire            # add [pdf] for PDF output, [iec81346] for the IEC 81346-2 class table,
                               # [native] for the compiled link router (same drawings, faster)

Loading and validating

import uniwire

doc = uniwire.load("house.uniwire.json")      # path, pathlib.Path or an already-parsed dict
print(doc.meta.title, len(doc.sources))

load() parses the JSON, validates it against the model (closed types: unknown fields are errors), applies templates, assigns missing identifiers and checks integrity (unique ids, existing link endpoints, enclosure members). Units given as strings ("16 A", "2,5 mm²") are converted to the canonical numeric fields.

On failure it raises uniwire.UniwireError, whose issues attribute lists every problem found:

try:
    doc = uniwire.load({"sources": [{"type": "grid", "children": [{"type": "breaker", "calibre": 16}]}]})
except uniwire.UniwireError as e:
    for issue in e.issues:
        print(issue)          # ... unknown field (typo? use 'ext' for extensions)

uniwire.dump(doc) returns the resolved document as canonical JSON (templates applied, ids assigned, numbers in the unit of each field).

Checking rules

findings = uniwire.check(doc)                          # core + the profiles listed in doc.profiles
findings = uniwire.check(doc, ["nfc15100", "iec60364"]) # core + explicit profiles
for f in findings:
    print(f.level, f.rule, f.node, f.message, f.source)

Each Finding has a level (error, warning, info), a stable rule id, the node id concerned, a translated message and, for standard-based rules, the source it relies on. Rule metadata is available in uniwire.rules.RULE_INFO. See Rules.

Rendering

paths = uniwire.render_svg(doc, "out/house", stem="house")   # list of SVG files, one per sheet
pdf = uniwire.render_pdf(doc, "out/house.pdf")               # one multi-page PDF (needs uniwire[pdf])
# with the page "About this document" after the sheets (checks, contact; About(doc_id) names the online copy)
from uniwire.render.about import About
pdf = uniwire.render_pdf(doc, "out/house.pdf", about=About())
pages = uniwire.render_pages(doc)                            # in-memory pages (layout primitives)

Both functions accept an optional view (a View from doc.views); by default the first view, or a default single-line view, is used. Large installations are split across sheets automatically (folio_split; no sheet is drawn below scale 0.6), with cross-references between sheets and a title block on each, the scale of the sheet written in it.

The views of a document make one drawing set: their sheets are numbered one after the other (SPEC §7, first_folio). A declared view drawn on its own prints the numbers it has in the set, so its sheets match the PDF of every view.

pdf = uniwire.render_pdf(doc, "out/set.pdf", all_views=True)   # every view of the document, one drawing set

from uniwire.render import drawing_set_findings, render_views
counts = []
pages = render_views(doc, counts=counts)        # the sheets of every view; counts: each view and its sheets
for f in drawing_set_findings(counts):          # core.folio-overlap: known only once the views are drawn
    print(f.level, f.rule, f.message)

render_pdf(..., findings=[]) fills the list with the same findings.

The multi-line power diagram (one line per conductor, see SPEC §7.1) is a view of kind multi-line:

from uniwire.render import default_view

view = default_view(doc, kind="multi-line")    # the document's multi-line view, or one derived from the first view
uniwire.render_svg(doc, "out/house-ml", stem="house-ml", view=view)

The language of the drawing (title block, table headings, type labels) follows meta.lang of the document: "en" (default), "fr", "de", "es", "pt", "it", "nl", "pl", "tr", "hr", "sr", "bs" (Croatian, Serbian and Bosnian in Latin script; "sr-Cyrl" for Serbian in Cyrillic), "ru", "zh" (Simplified Chinese) or "ja" (Japanese). Another language falls back to English for the texts uniwire writes; the texts of the document are drawn as written.

Colours: a view with color set (conductors, phase, source, status, voltage, SPEC §7) recolours the strokes and adds a legend on each sheet, in SVG and PDF alike:

view = default_view(doc, kind="multi-line").model_copy(update={"color": "conductors", "conductor_colors": "us"})
uniwire.render_svg(doc, "out/house-colour", view=view)

PDF output has one bookmark per sheet ("Sheet n: title") and every cross-sheet reference (off-page arrow, "→ sheet n" label, busbar continuation, cross-sheet link end, incoming feed) is a link to its sheet.

SVG structure

Each SVG sheet carries the meaning of what it draws, so a viewer or another tool can find the drawing of a node, a link or a conductor without parsing geometry. Units are mm (viewBox = sheet size). Ids are those of the document (id of nodes, id or index of links). The structure below is stable within format 1.x; new classes / attributes may be added.

Element Class / attributes What it holds
root <svg> data-uw-sheet="n" (1-based position in the rendered set), data-uw-folio="n" (the sheet number printed in its title block, its number in the drawing set), data-uw-view-kind="single-line" or "multi-line" one sheet
node <g class="sym sym-… uw-node" data-uw-id="ID"> (multi-line: ml-sym …); a board is its frame and name: <g class="board uw-node" data-uw-id="ID"> symbol of a node of the tree, of an auxiliary device (devices), of a device carried by a link (then also data-uw-link="KEY", and data-uw-id only if the device has an id)
tree edge <g class="uw-edge" data-uw-edge="CHILD" data-uw-parent="PARENT"> the conductor(s) feeding CHILD from its parent or from the busbar tap; multi-line: one sub-group per conductor (data-uw-cond)
busbar <g class="uw-busbar" data-uw-id="OWNER">; multi-line: one per rail, with data-uw-cond busbar of the node with several outgoing feeders (riser from its output included)
link <g class="uw-link" data-uw-link="KEY" data-uw-kind="KIND" data-uw-from="ID" data-uw-to="ID"> drawn path(s) (in pieces where a dashed signal link crosses a conductor, each with its stroke-dashoffset; an interrupted line: its two stubs, arrows and texts), carried device, label, plus a last child <g class="uw-hit" pointer-events="stroke">: the same paths with stroke="transparent", 3 mm wide, for easy hovering. KEY = link id, else its index in links. A link drawn on a trunk (single-line: three links or more of one kind sharing one end) also has data-uw-trunk="ID:KIND" (the shared end and the kind): it draws its tap and the piece of the trunk before it, and its hit path is its whole route
conductor data-uw-cond="L1" (L2, L3, N, PE, PEN, L+, L-) on a small <g> (or on a pole group class="pole") multi-line only: one conductor segment, inside the edge / busbar / link / node it belongs to. With wire marking (SPEC §7.2), the conductor groups of the edge fed by a marked cable also carry data-uw-mark="101" (the mark, also written next to the line when there is room)
reference <g class="uw-ref" data-uw-target-sheet="n" data-uw-target-id="ID"> (n empty when unknown) off-page arrow of a board drawn on its own sheet (and its "→ sheet n" schedule label), busbar continuation, cross-sheet link end, incoming feed of a detached board (target: the feeding node)
schedule column <g class="uw-cell" data-uw-id="ID">, one <g data-uw-field="FIELD"> per cell feeder-table column of a leaf / feeder node
legend <g class="uw-legend"> colour legend (colour modes)

Other groups (annotation, conductors, cartouche, title-block, notes, page) carry no ids. Selectors should use the classes (.uw-node[data-uw-id="Q1"]), as data-uw-id is also found on busbars and schedule columns.

Each SVG embeds a small <style> so that, opened alone in a browser, hovering a node, edge, busbar or link turns its strokes orange (@media screen only: printing is unchanged).

import xml.etree.ElementTree as ET

NS = "{http://www.w3.org/2000/svg}"
svg = ET.parse("out/house/house.svg").getroot()
feeders = {g.get("data-uw-edge"): g.get("data-uw-parent") for g in svg.iter(NS + "g")
           if "uw-edge" in (g.get("class") or "").split()}

pip install "uniwire[native]" adds the package uniwire-native, a compiled (Rust) version of the search of the link router. The library uses it when it is installed and loads; the drawings are exactly the same as without it, large drawings with many links are drawn several times faster. Without it, when it cannot be loaded or was built for another version, or with the environment variable UNIWIRE_NATIVE=0, the pure Python search is used, with no message. The web editor loads a build of it for the browser when one is served (Web viewer).

Bill of materials and graph

from uniwire.bom import bom, bom_csv
from uniwire.graph import to_graph

rows = bom(doc)        # [{"manufacturer", "part_number", "range", "description", "type", "spec", "quantity", "length_m", "refs"}, ...]
csv_text = bom_csv(doc)
graph = to_graph(doc)  # {"components": [...], "connectivity_nodes": [...], "signals": [...]}

The bill of materials aggregates every node and PLC module that carries a product (or manufacturer / part_number), including product accessories. The graph is the derived terminal / connectivity-node form described in the specification §8, with CIM / IFC / SCL mappings.

Wire marks and wiring exports

The conductors of the cables of the power tree, with their marks (SPEC §7.2, subset of UEP-0001):

from uniwire.marks import marked_wires, freeze
from uniwire.exports import wires_csv, markers_csv, cables_csv

view = default_view(doc, "marks")                 # a view with "wire_marking"
for w in marked_wires(doc, view):                 # numbering order
    print(w.id, w.mark, w.from_display, w.to_display, w.cable_ref)   # M1.cable.L1 101 -KM1 -M1 W11
csv_text = wires_csv(doc, view)                   # also markers_csv(doc, view), cables_csv(doc)

marked_wires(doc) without a view gives the manual marks (cable.marks) only. freeze(data, doc, wires) writes the marks into the cable.marks of the parsed JSON data (what uniwire marks --write does).

I/O list and terminal strips

The control side that the document already describes (SPEC §3b): the channels of the PLC modules, the links that address them (from_port / to_port = slot.channel) and the terminal blocks.

from uniwire.exports import io_rows, terminal_rows, io_csv, terminals_csv, declared_terminals

for r in io_rows(doc):          # one row per channel of each I/O module, connected or spare
    print(r["plc_display"], r["address"], r["io_type"], r["label"], r["device_display"], r["terminal"])
    # -A1 0.2 DI Pump on -S1 -X2:3
for r in terminal_rows(doc, view):   # one row per terminal of each terminal block
    print(r["strip_display"], r["terminal"], r["from_display"], r["to_display"], r["from_mark"])
csv_text = io_csv(doc)               # also terminals_csv(doc, view)

I/O list columns: plc, plc_display, slot, module, module_kind, io_type, channel, address, direction, signal, un_V, label, device, device_display, device_port, terminal, link_kind, cable, status. Every channel of an I/O module (di, do, relay_out, ai, ao, mixed_io, counter, temperature, safety, power_measurement, motor) gets a row, connected or spare; links on other modules (comm...) and links without a channel follow. io_type comes from the module kind (DI, DO, AI, AO...; a mixed_io channel takes the direction of its link). When several modules share a slot (built-in I/O, slot 0), an output link (control from the PLC) goes to the output module and an input link (measure, or a link to the PLC) to the input module. label is the module's channel_labels entry, else the link label. When the link ends on a numbered terminal of a terminal block (to_port) and another link leaves that terminal, device is the device beyond the block and terminal names the terminal (-X2:3). Only control, measure, data, trip, interlock and key links are I/O.

Terminal strip columns: strip, strip_display, terminal, function, from, from_display, from_port, from_mark, from_cable, to, to_display, to_port, to_mark, to_cable, link_kind, label. The terminals are those listed in the block's terminals field ("X1.1-X1.12", "1-12", "1, 2, PE", "1=L; 2=N; 3=PE", spare ones included; other text stays a description) and those named by the link ports on the block side, in natural order. A link arriving on the block (to) fills from, a link leaving it fills to; a link end without a terminal number gets a row of its own. A block in the power tree also lists the conductors of its cable and of its children's cables, with their wire marks; a function in terminals (L1, N, PE, U/V/W for the phases, L for the only line conductor) places each conductor on its terminal.

Registry

from uniwire import registry

registry.label("rcd", "fr")          # 'Interrupteur différentiel' (type label in a given language)
registry.category("breaker")         # 'protection'
registry.iec81346_class("breaker")   # 'QAB'
registry.iec81346_table()            # full IEC 81346-2 table if uniwire[iec81346] is installed, else {}

Symbol sets

A document names the set of symbols it is drawn with in symbols (iec by default, the set built into the library). A set is registered under a name, and gives only the symbols it changes: the others are drawn as in iec.

from uniwire.render.scene import THIN, Line, Rect, Style
from uniwire.symbols import SYMBOLS, Symbol, register_symbol_set, symbol_sets

def breaker(node=None, *variants, **named):   # node: the node drawn (None on the symbol sheet)
    return Symbol("my-breaker", [Line((0, 0), (0, 3)), Rect(-2.5, 3, 5, 5, Style(width=THIN)), Line((0, 8), (0, 11))],
                  height=11.0)

register_symbol_set("mine", {"breaker": breaker})   # keys: names of SYMBOLS (node types and "offpage")
symbol_sets()                                       # ['iec', 'mine']

A factory takes the arguments of the built-in function of the same name in uniwire.symbols (the node first; some take variants, such as motor(node, live, dc) or generator(node, system)) and returns a Symbol in millimetres: input terminal at (0, 0), y pointing down, output terminal at (0, height), left and right its width on each side of the conductor. A symbol that replaces plc keeps the extra values the built-in one sets (ports, port_y, slot_w): the layout places the links and widens the modules from them; the simplest way is to start from the built-in symbol and change its drawing. Registering again under the same name adds or replaces symbols; iec cannot be replaced.

A package makes its set available to every program that uses uniwire with an entry point in the group uniwire.symbol_sets: its name is the set's name, its object the mapping (or a function returning it).

[project.entry-points."uniwire.symbol_sets"]
mine = "my_package.symbols:SYMBOLS"

A document naming a set that is not installed is drawn with the iec symbols, with the finding core.symbol-set-unknown. A package that fails to load, or a factory that raises or returns something else than a Symbol, does not stop the drawing: the iec symbol is drawn instead and core.symbol-set-error gives the error (uniwire.symbols.FAILURES keeps them). The layout knows a symbol by the name it is registered under, not by Symbol.name, which only names the SVG class (sym-<name>). In multi-line views, switching and protective devices are drawn pole by pole by the renderer: a symbol set does not change them. uniwire symbols --set mine draws every symbol of a set. Example: examples/code/symbol_set.py.

Command line

Command Purpose
uniwire validate FILE... Validate one or more documents (schema + integrity)
uniwire check FILE... [--profile P] Validate, then apply the rule profiles; exit code 1 if any error
uniwire render FILE [-f svg\|pdf] [-o OUT] [--view ID] [--kind single-line\|multi-line] [--about] [--doc-id ID] Draw the sheets (SVG directory by default, out/<name>/). --view picks a view by id; --kind multi-line draws the multi-line power diagram even if the document declares no such view (files named <name>-multiline). The PDF of a document with several views holds every view, unless --view or --kind picks one, and the drawing set findings are printed (core.folio-overlap). --about adds the page "About this document" (checks, contact), --doc-id names the online copy there
uniwire schema [-o FILE] Write the JSON Schema
uniwire graph FILE Print the derived terminal / connectivity-node graph (JSON)
uniwire bom FILE [-o FILE] Bill of materials as CSV (semicolon-separated)
uniwire wires FILE [--view ID] [-o FILE] Wire list as CSV: one row per conductor of the cables of the power tree, with its mark (--all accepted: in the current format every wire is an implicit power connection)
uniwire markers FILE [--view ID] [-o FILE] Wire marker list as CSV (one row per end of a marked wire, quantity)
uniwire cables FILE [-o FILE] Cable schedule as CSV
uniwire io FILE [-o FILE] I/O list of the PLCs as CSV: one row per channel, connected or spare, with the device linked to it
uniwire terminals FILE [--view ID] [-o FILE] Terminal strip table as CSV: one row per terminal of each terminal block, what arrives and what leaves (wire marks of the view)
uniwire marks FILE [--view ID] [--write] [-o FILE] Print the wire marks of a view; --write freezes them into the cables' marks (in place, or into -o FILE; the JSON is rewritten with 2-space indentation)
uniwire symbols [-o FILE] [--set NAME] SVG sheet of all symbols (of the symbol set NAME, iec by default)
uniwire normalize FILE Print the resolved document (templates applied, ids assigned, canonical units)
uniwire card, describe, link, patch Tools for assistants: reference card, outline with stable ids, web editor link, edits by id (LLM tools)
uniwire validate examples/*.uniwire.json
uniwire check house.uniwire.json --profile iec60364
uniwire render house.uniwire.json -f pdf -o house.pdf
uniwire render house.uniwire.json --kind multi-line      # multi-line power diagram
uniwire bom house.uniwire.json -o house.bom.csv
uniwire markers mcc.uniwire.json --view marks -o mcc.markers.csv   # ferrules for a marker printer
uniwire marks mcc.uniwire.json --view marks --write              # freeze the generated marks

CLI output, validation errors and rule findings follow the UNIWIRE_LANG environment variable (en by default). French covers everything; German, Spanish, Portuguese, Italian, Dutch, Polish, Turkish, Croatian, Serbian (sr, and sr-Cyrl in Cyrillic), Bosnian, Russian, Chinese and Japanese cover the rule findings, the CLI and validation messages staying in English:

UNIWIRE_LANG=fr uniwire check house.uniwire.json