On This Page (5)
Examples Showcase / multiboard_system_netlist_and_c0
Inspect a multi-board system netlist and C0 system compilation
Synthesize a two-board, three-module system with a repeated sensor board, inspect AltiumPrjMbd and AltiumMbsDoc, build a V1 cross-board system netlist, render Paper and Dark system topology SVGs, and trace repeated-instance impacts and graphics via AltiumSystem.
Output Previews
Build a self-contained two-board (three-module, including a repeated sensor board) multi-board system (.PrjMbd + .MbsDoc + child .PrjPcb/.SchDoc projects), then inspect it through the full read-only multi-board stack: AltiumPrjMbd, AltiumMbsDoc, AltiumMultiboardProject.system_netlist(), and AltiumSystem, and render a data-driven top-level Multi-Board System Topology SVG in both Paper and Dark themes.
What It Shows
- Reading project membership and module resolution with
AltiumPrjMbdandAltiumMultiboardProject.resolve_modules() - Reading the logical connectivity graph with
AltiumMbsDocand verifyingconnectivity_complete - Computing cross-board connected components and rename-ready aliases with
project.system_netlist()and validatingaltium_monkey.multiboard.system_netlist.v1JSON viaload_system_netlist_json(...) - Compiling the full system with
AltiumSystem.from_file(...), tracing cross-board authored source fields (fields_for_net,impacts_for_field) across repeated board instances, and rendering instance-scoped schematic SVGs viasystem.schematic_graphics(page_ref, instance_path=[...]) - Rendering a data-driven Multi-Board System Topology diagram (
render_system_topology_svg) in both Paper (system_topology.svg) and Dark (system_topology_dark.svg) themes directly from liveAltiumMbsDoc,MbsSystemNetlist, andAltiumSystemobjects
Run
From the repository root:
uv run python examples\multiboard_system_netlist_and_c0\multiboard_system_netlist_and_c0.pyOutput
The script writes:
examples/multiboard_system_netlist_and_c0/output/system_topology.svg
examples/multiboard_system_netlist_and_c0/output/system_topology_dark.svg
examples/multiboard_system_netlist_and_c0/output/controller_board.svg
examples/multiboard_system_netlist_and_c0/output/sensor_instance_1.svg
examples/multiboard_system_netlist_and_c0/output/system_netlist_v1.json
examples/multiboard_system_netlist_and_c0/output/multiboard_manifest.json
examples/multiboard_system_netlist_and_c0/output/workspace/Source Code
from __future__ import annotations
import html
import json
import shutil
import zipfile
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Literal
from altium_monkey import (
AltiumSchDoc,
AltiumSchLib,
ColorValue,
LineWidth,
PinElectrical,
Rotation90,
SchFontSpec,
SchPointMils,
SchRectMils,
TextJustification,
TextOrientation,
make_sch_net_label,
make_sch_pin,
make_sch_rectangle,
make_sch_wire,
)
from altium_monkey.altium_mbsdoc import AltiumMbsDoc
from altium_monkey.altium_multiboard import AltiumMultiboardProject
from altium_monkey.altium_multiboard_netlist import (
MbsSystemNetlist,
load_system_netlist_json,
)
from altium_monkey.altium_prjmbd import AltiumPrjMbd
from altium_monkey.altium_system import AltiumSystem
SAMPLE_DIR = Path(__file__).resolve().parent
OUTPUT_DIR = SAMPLE_DIR / "output"
WORKSPACE_DIR = OUTPUT_DIR / "workspace"
TOPOLOGY_SVG_PATH = OUTPUT_DIR / "system_topology.svg"
TOPOLOGY_DARK_SVG_PATH = OUTPUT_DIR / "system_topology_dark.svg"
CTRL_SVG_PATH = OUTPUT_DIR / "controller_board.svg"
SENSOR_SVG_PATH = OUTPUT_DIR / "sensor_instance_1.svg"
NETLIST_JSON_PATH = OUTPUT_DIR / "system_netlist_v1.json"
MANIFEST_PATH = OUTPUT_DIR / "multiboard_manifest.json"
CONNECTOR_SYMBOL = "HDR_3PIN"
def _sample_relative(path: Path) -> str:
return path.relative_to(SAMPLE_DIR).as_posix()
def _build_connector_lib(lib_path: Path) -> Path:
lib_path.parent.mkdir(parents=True, exist_ok=True)
lib = AltiumSchLib()
sym = lib.add_symbol(CONNECTOR_SYMBOL)
sym.set_description("3-pin board-to-board connector")
# Generous 600 x 440 mil body so pin names fit comfortably inside the symbol.
sym.add_object(
make_sch_rectangle(
bounds_mils=SchRectMils.from_corners_mils(-300, 220, 300, -220),
color=ColorValue.from_hex("#800000"),
fill_color=ColorValue.from_hex("#FFFFB0"),
line_width=LineWidth.SMALL,
fill_background=True,
transparent_fill=False,
)
)
for pin_num, y_mil, pin_name in (
(1, 100, "PWR"),
(2, 0, "DATA"),
(3, -100, "GND"),
):
sym.add_pin(
make_sch_pin(
designator=str(pin_num),
name=pin_name,
location_mils=SchPointMils.from_mils(300, y_mil),
orientation=Rotation90.DEG_0,
length_mils=200,
electrical_type=PinElectrical.PASSIVE,
owner_part_id=1,
owner_part_display_mode=0,
)
)
sym.add_designator("J?", -280, 270)
sym.add_parameter("Comment", "HDR_3PIN", x=-280, y=-340)
sym.add_parameter("System", "Connector", x=-280, y=-460, is_hidden=True)
lib.save(lib_path)
return lib_path
def _wire_connector_nets(
schdoc: AltiumSchDoc,
x_comp: int,
y_comp: int,
net_names: tuple[str, str, str],
) -> None:
font = SchFontSpec(name="Arial", size=10)
wire_color = ColorValue.from_hex("#000080")
for offset_y, net_name in zip((100, 0, -100), net_names, strict=True):
pin_tip_x = x_comp + 500
pin_tip_y = y_comp + offset_y
end_x = pin_tip_x + 700
schdoc.add_object(
make_sch_wire(
points_mils=[
SchPointMils.from_mils(pin_tip_x, pin_tip_y),
SchPointMils.from_mils(end_x, pin_tip_y),
],
color=wire_color,
line_width=LineWidth.SMALL,
)
)
schdoc.add_object(
make_sch_net_label(
location_mils=SchPointMils.from_mils(pin_tip_x + 120, pin_tip_y),
text=net_name,
font=font,
color=wire_color,
orientation=TextOrientation.DEGREES_0,
justification=TextJustification.BOTTOM_LEFT,
mirrored=False,
)
)
def _write_prjpcb(path: Path, schdoc_filename: str, document_uid: str) -> None:
text = (
"[Design]\n"
"Version=1.0\n"
"HierarchyMode=0\n"
"[Document1]\n"
f"DocumentPath={schdoc_filename}\n"
f"DocumentUniqueId={document_uid}\n"
)
path.write_text(text, encoding="utf-8", newline="\n")
def _extract_connector_ids(
schdoc_path: Path, expected_designators: tuple[str, ...]
) -> tuple[str, dict[str, dict[str, object]]]:
reopened = AltiumSchDoc(schdoc_path)
sheet_uid = str(getattr(reopened, "unique_id", "") or "")
if not sheet_uid:
for obj in reopened.to_json().get("Objects", []):
if obj.get("ObjectType") == "Sheet" and obj.get("UniqueID"):
sheet_uid = str(obj["UniqueID"])
break
connectors: dict[str, dict[str, object]] = {}
for des, comp in zip(expected_designators, reopened.components, strict=True):
comp_uid = str(comp.unique_id)
pins: dict[str, str] = {}
pin_names: dict[str, str] = {}
for pin in comp.pins:
pins[str(pin.designator)] = str(pin.unique_id)
pin_names[str(pin.designator)] = str(pin.name)
connectors[des] = {
"unique_id": comp_uid,
"pins": pins,
"pin_names": pin_names,
}
return sheet_uid, connectors
def _build_demo_workspace(workspace_dir: Path) -> Path:
ctrl_dir = workspace_dir / "ctrl_board"
sensor_dir = workspace_dir / "sensor_board"
sys_dir = workspace_dir / "system"
for folder in (ctrl_dir, sensor_dir, sys_dir):
folder.mkdir(parents=True, exist_ok=True)
# 1. Controller board with two connectors (J_A and J_B) on shared rails.
ctrl_lib = _build_connector_lib(ctrl_dir / "connector.SchLib")
ctrl_sch = AltiumSchDoc()
ctrl_sch.add_component_from_library(
library_path=ctrl_lib,
symbol_name=CONNECTOR_SYMBOL,
designator="J_A",
x=4200,
y=5600,
)
_wire_connector_nets(ctrl_sch, 4200, 5600, ("3V3", "I2C_SDA", "GND"))
ctrl_sch.add_component_from_library(
library_path=ctrl_lib,
symbol_name=CONNECTOR_SYMBOL,
designator="J_B",
x=4200,
y=4200,
)
_wire_connector_nets(ctrl_sch, 4200, 4200, ("3V3", "I2C_SDA", "GND"))
ctrl_sch_path = ctrl_dir / "ctrl.SchDoc"
ctrl_sch.save(ctrl_sch_path)
ctrl_doc_uid = "CTRLSH01"
_write_prjpcb(ctrl_dir / "ctrl_board.PrjPcb", "ctrl.SchDoc", ctrl_doc_uid)
# 2. Sensor board with one connector (J1) using local net names VIN / SDA / GND.
sensor_lib = _build_connector_lib(sensor_dir / "connector.SchLib")
sensor_sch = AltiumSchDoc()
sensor_sch.add_component_from_library(
library_path=sensor_lib,
symbol_name=CONNECTOR_SYMBOL,
designator="J1",
x=4400,
y=4900,
)
_wire_connector_nets(sensor_sch, 4400, 4900, ("VIN", "SDA", "GND"))
sensor_sch_path = sensor_dir / "sensor.SchDoc"
sensor_sch.save(sensor_sch_path)
sensor_doc_uid = "SNSSH001"
_write_prjpcb(sensor_dir / "sensor_board.PrjPcb", "sensor.SchDoc", sensor_doc_uid)
_, ctrl_conns = _extract_connector_ids(ctrl_sch_path, ("J_A", "J_B"))
_, sensor_conns = _extract_connector_ids(sensor_sch_path, ("J1",))
ctrl_sheet_uid = ctrl_doc_uid
sensor_sheet_uid = sensor_doc_uid
# 3. Synthesize DemoSystem.MbsDoc linking M_CTRL to two instances of sensor_board.
next_id = 10
def alloc() -> int:
nonlocal next_id
val = next_id
next_id += 1
return val
def make_module(
*,
designator: str,
title: str,
project_rel: str,
source_name: str,
sheet_uid: str,
conn_specs: list[tuple[str, dict[str, object], tuple[str, str, str]]],
) -> tuple[dict[str, object], dict[str, tuple[int, dict[str, int]]]]:
mod_id = alloc()
components: list[dict[str, object]] = []
entries: list[dict[str, object]] = []
entry_pin_map: list[dict[str, int]] = []
handle_by_conn: dict[str, tuple[int, dict[str, int]]] = {}
for conn_des, conn_info, ext_nets in conn_specs:
comp_id = alloc()
comp_uid = f"\\{conn_info['unique_id']}"
pin_uids = conn_info["pins"]
pin_names = conn_info.get("pin_names", {})
assert isinstance(pin_uids, dict)
assert isinstance(pin_names, dict)
entry_id = alloc()
pin_ids: dict[str, int] = {}
pin_objs: list[dict[str, object]] = []
for pin_num, ext_net in zip(("1", "2", "3"), ext_nets, strict=True):
pid = alloc()
pin_ids[pin_num] = pid
pin_objs.append(
{
"pinId": pin_num,
"name": str(pin_names.get(pin_num, pin_num)),
"number": pin_num,
"parameters": [
{
"name": "SourceId",
"value": pin_uids[pin_num],
"id": alloc(),
},
{
"name": "ParentSourceId",
"value": comp_uid,
"id": alloc(),
},
{
"name": "ExternalNetName",
"value": ext_net,
"id": alloc(),
},
],
"id": pid,
}
)
entry_pin_map.append({"key": pid, "value": entry_id})
components.append(
{
"designator": conn_des,
"comment": CONNECTOR_SYMBOL,
"pins": pin_objs,
"parameters": [
{"name": "ParentSourceId", "value": sheet_uid, "id": alloc()},
{"name": "PhysicalPath", "value": source_name, "id": alloc()},
{"name": "SourceId", "value": comp_uid, "id": alloc()},
],
"id": comp_id,
}
)
entries.append(
{
"calculatedDesignator": conn_des,
"parameters": [],
"id": entry_id,
}
)
handle_by_conn[conn_des] = (entry_id, pin_ids)
module_obj: dict[str, object] = {
"designator": designator,
"title": title,
"source": {"sourceProject": project_rel},
"functionalBlocks": [],
"components": components,
"entries": entries,
"entryPinMap": {"map": entry_pin_map},
"parameters": [
{"name": "SourceId", "value": f"{source_name}.PrjPcb", "id": alloc()}
],
"id": mod_id,
}
return module_obj, handle_by_conn
mod_ctrl, ctrl_handles = make_module(
designator="M_CTRL",
title="Controller",
project_rel="..\\ctrl_board\\ctrl_board.PrjPcb",
source_name="ctrl_board",
sheet_uid=ctrl_sheet_uid,
conn_specs=[
("J_A", ctrl_conns["J_A"], ("3V3", "I2C_SDA", "GND")),
("J_B", ctrl_conns["J_B"], ("3V3", "I2C_SDA", "GND")),
],
)
mod_sns1, sns1_handles = make_module(
designator="M_SNS1",
title="Sensor A",
project_rel="..\\sensor_board\\sensor_board.PrjPcb",
source_name="sensor_board",
sheet_uid=sensor_sheet_uid,
conn_specs=[("J1", sensor_conns["J1"], ("VIN", "SDA", "GND"))],
)
mod_sns2, sns2_handles = make_module(
designator="M_SNS2",
title="Sensor B",
project_rel="..\\sensor_board\\sensor_board.PrjPcb",
source_name="sensor_board",
sheet_uid=sensor_sheet_uid,
conn_specs=[("J1", sensor_conns["J1"], ("VIN", "SDA", "GND"))],
)
def make_direct_connection(
designator: str,
entry1: int,
pins1: dict[str, int],
entry2: int,
pins2: dict[str, int],
defined_names: dict[str, str],
) -> dict[str, object]:
conn_id = alloc()
phys: list[dict[str, object]] = []
for idx, pin_num in enumerate(("1", "2", "3"), start=1):
pair: dict[str, object] = {
"pin1": pins1[pin_num],
"pin2": pins2[pin_num],
"parameters": [],
"id": alloc(),
}
if pin_num in defined_names:
pair["definedName"] = defined_names[pin_num]
phys.append(
{
"$type": "__logicalPinToPinConnection",
"pinPair": pair,
"designator": str(idx),
"parameters": [],
"id": alloc(),
}
)
return {
"$type": "__logicalDirectConnection",
"designator": designator,
"entriesConnection": {
"entry1": entry1,
"entry2": entry2,
"physicalConnections": phys,
"id": alloc(),
},
"parameters": [],
"id": conn_id,
}
conn1 = make_direct_connection(
"C_1",
ctrl_handles["J_A"][0],
ctrl_handles["J_A"][1],
sns1_handles["J1"][0],
sns1_handles["J1"][1],
{"1": "SYS_3V3", "2": "SYS_I2C_SDA", "3": "SYS_GND"},
)
conn2 = make_direct_connection(
"C_2",
ctrl_handles["J_B"][0],
ctrl_handles["J_B"][1],
sns2_handles["J1"][0],
sns2_handles["J1"][1],
{"1": "SYS_3V3", "2": "SYS_I2C_SDA", "3": "SYS_GND"},
)
# Wire back logicalConnection on entries.
mod_ctrl["entries"][0]["logicalConnection"] = conn1["id"]
mod_ctrl["entries"][1]["logicalConnection"] = conn2["id"]
mod_sns1["entries"][0]["logicalConnection"] = conn1["id"]
mod_sns2["entries"][0]["logicalConnection"] = conn2["id"]
logical_doc = {
"uniqueId": "9c25b140-4a8e-4e7b-9d14-202611260001",
"modules": [mod_ctrl, mod_sns1, mod_sns2],
"powerPorts": [],
"connections": [conn1, conn2],
"conflicts": [],
"placeableComponents": [],
"virtualModules": [],
"parameters": [],
}
core_doc = {
"version": 1,
"modified": "2026-11-26T00:00:00.0000000Z",
}
mbsdoc_path = sys_dir / "DemoSystem.MbsDoc"
with zipfile.ZipFile(mbsdoc_path, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr("styles.json", "{}")
archive.writestr("core.json", json.dumps(core_doc, indent=2))
archive.writestr("parameters.json", "{}")
archive.writestr("logical.json", json.dumps(logical_doc, indent=2))
archive.writestr("options.json", "{}")
archive.writestr("defaults.json", "{}")
prjmbd_path = sys_dir / "DemoSystem.PrjMbd"
prjmbd_path.write_text(
"[Design]\n"
"Version=1.0\n"
"[Document1]\n"
"DocumentPath=DemoSystem.MbsDoc\n"
"[Document2]\n"
"DocumentPath=..\\ctrl_board\\ctrl_board.PrjPcb\n"
"[Document3]\n"
"DocumentPath=..\\sensor_board\\sensor_board.PrjPcb\n",
encoding="utf-8",
newline="\n",
)
return prjmbd_path
_FONT_SANS = "'Segoe UI', 'DejaVu Sans', 'Liberation Sans', Arial, sans-serif"
_FONT_MONO = "'Consolas', 'DejaVu Sans Mono', 'Liberation Mono', monospace"
@dataclass(frozen=True)
class _ThemePalette:
bg: str
grid_dot: str
frame_stroke: str
header_bg: str
header_border: str
header_accent: str
card_bg: str
card_stroke: str
card_shadow: str
card_shadow_opacity: float
card_header_bg: str
subcard_bg: str
subcard_stroke: str
conn_bg: str
conn_stroke: str
conn_header_bg: str
conn_header_text: str
conn_header_muted: str
row_alt: str
divider: str
text_primary: str
text_secondary: str
text_muted: str
pill_bg: str
pill_stroke: str
pill_text: str
ok_bg: str
ok_stroke: str
ok_text: str
ok_dot: str
warn_bg: str
warn_stroke: str
warn_text: str
warn_dot: str
hub_accent: str
leaf_accent: str
repeated_bg: str
repeated_stroke: str
repeated_text: str
hole_ring: str
hole_drill: str
sheath_bg: str
sheath_stroke: str
sheath_collar: str
wire_halo: str
wire_halo_opacity: float
wire_halo_width: float
wire_width: float
wire_tag_bg: str
impact_banner_bg: str
impact_banner_stroke: str
impact_badge_bg: str
impact_badge_text: str
net_power: str
net_data: str
net_ground: str
net_extra: tuple[str, ...]
_TOPOLOGY_THEMES: dict[Literal["paper", "dark"], _ThemePalette] = {
"paper": _ThemePalette(
bg="#fbfaf5",
grid_dot="#e2dfd2",
frame_stroke="#d8d3c4",
header_bg="#ffffff",
header_border="#e3ded0",
header_accent="#0f766e",
card_bg="#ffffff",
card_stroke="#cbd5e1",
card_shadow="#0f172a",
card_shadow_opacity=0.06,
card_header_bg="#f6f4ec",
subcard_bg="#f8fafc",
subcard_stroke="#cbd5e1",
conn_bg="#f8fafc",
conn_stroke="#94a3b8",
conn_header_bg="#334155",
conn_header_text="#f8fafc",
conn_header_muted="#cbd5e1",
row_alt="#f8f7f2",
divider="#e2e8f0",
text_primary="#0f172a",
text_secondary="#334155",
text_muted="#64748b",
pill_bg="#f1f5f9",
pill_stroke="#cbd5e1",
pill_text="#334155",
ok_bg="#ecfdf5",
ok_stroke="#6ee7b7",
ok_text="#047857",
ok_dot="#10b981",
warn_bg="#fffbeb",
warn_stroke="#fcd34d",
warn_text="#b45309",
warn_dot="#f59e0b",
hub_accent="#0f766e",
leaf_accent="#2563eb",
repeated_bg="#eff6ff",
repeated_stroke="#93c5fd",
repeated_text="#1d4ed8",
hole_ring="#d97706",
hole_drill="#fbfaf5",
sheath_bg="#eef2f6",
sheath_stroke="#cbd5e1",
sheath_collar="#64748b",
wire_halo="#fbfaf5",
wire_halo_opacity=0.88,
wire_halo_width=5.2,
wire_width=2.5,
wire_tag_bg="#ffffff",
impact_banner_bg="#fffbeb",
impact_banner_stroke="#f59e0b",
impact_badge_bg="#d97706",
impact_badge_text="#ffffff",
net_power="#dc2626",
net_data="#0284c7",
net_ground="#0d9488",
net_extra=("#7c3aed", "#d97706", "#db2777", "#4f46e5"),
),
"dark": _ThemePalette(
bg="#161b22",
grid_dot="#263142",
frame_stroke="#2d3a4d",
header_bg="#1b2330",
header_border="#2d3a4d",
header_accent="#14b8a6",
card_bg="#1b2330",
card_stroke="#334155",
card_shadow="#000000",
card_shadow_opacity=0.35,
card_header_bg="#222c3c",
subcard_bg="#151c27",
subcard_stroke="#334155",
conn_bg="#131a24",
conn_stroke="#475569",
conn_header_bg="#253347",
conn_header_text="#f1f5f9",
conn_header_muted="#94a3b8",
row_alt="#1f2837",
divider="#2d3a4d",
text_primary="#e6edf3",
text_secondary="#b6c3d4",
text_muted="#8395ad",
pill_bg="#222c3c",
pill_stroke="#3b4b63",
pill_text="#cbd5e1",
ok_bg="#0d2b22",
ok_stroke="#1f7a5c",
ok_text="#34d399",
ok_dot="#10b981",
warn_bg="#332309",
warn_stroke="#925e10",
warn_text="#fbbf24",
warn_dot="#f59e0b",
hub_accent="#14b8a6",
leaf_accent="#3b82f6",
repeated_bg="#172a4a",
repeated_stroke="#3b82f6",
repeated_text="#93c5fd",
hole_ring="#eab308",
hole_drill="#161b22",
sheath_bg="#1c2636",
sheath_stroke="#3b4d66",
sheath_collar="#64748b",
wire_halo="",
wire_halo_opacity=0.22,
wire_halo_width=7.0,
wire_width=2.6,
wire_tag_bg="#161b22",
impact_banner_bg="#2c2212",
impact_banner_stroke="#b45309",
impact_badge_bg="#f59e0b",
impact_badge_text="#161b22",
net_power="#f87171",
net_data="#38bdf8",
net_ground="#2dd4bf",
net_extra=("#a78bfa", "#fbbf24", "#f472b6", "#818cf8"),
),
}
def _esc(text: str) -> str:
return html.escape(text, quote=True)
def _basename(raw_path: str) -> str:
normalized = raw_path.replace("\\", "/").strip()
return normalized.rsplit("/", 1)[-1] if normalized else ""
def _net_color(names: tuple[str, ...], net_index: int, pal: _ThemePalette) -> str:
joined = " ".join(names).upper()
tokens = {
tok
for part in names
for tok in part.upper().replace("-", "_").replace("/", "_").split("_")
if tok
}
if tokens & {"GND", "VSS", "DGND", "AGND", "PGND", "RTN"} or "GND" in joined:
return pal.net_ground
if tokens & {
"VCC",
"VDD",
"VIN",
"VBUS",
"PWR",
"POWER",
"3V3",
"5V",
"12V",
"1V8",
"3V",
}:
return pal.net_power
if tokens & {
"SDA",
"SCL",
"I2C",
"SPI",
"UART",
"TX",
"RX",
"DATA",
"CLK",
"MOSI",
"MISO",
"CAN",
"USB",
}:
return pal.net_data
return pal.net_extra[net_index % len(pal.net_extra)]
def _estimate_text_w(text: str, font_size: float, *, mono: bool = False) -> float:
factor = 0.61 if mono else 0.56
return len(text) * font_size * factor
def _extract_repeated_field_impacts(
mbsdoc: AltiumMbsDoc,
netlist: MbsSystemNetlist,
system: AltiumSystem,
) -> tuple[dict[str, object] | None, int]:
"""Query AltiumSystem C0 impact traces across repeated board instances."""
graph_dto = system.structural_graph.to_dto()
root_def = next(
d for d in graph_dto.definitions if d.id == graph_dto.root_definition_ref
)
# Map terminal_ref -> system net index & canonical name.
term_to_net: dict[str, tuple[int, str]] = {}
for snet in netlist.nets:
canonical = snet.names[0] if snet.names else f"NET_{snet.index}"
for tref in snet.terminals:
term_to_net[tref.full_id] = (snet.index, canonical)
# Map (module_source_key, child_net_id) -> (system_net_index, canonical_name).
mod_net_to_sys: dict[tuple[str, str], tuple[int, str]] = {}
for ep in system.endpoints:
child_net_id = getattr(ep.endpoint, "net_id", None)
if child_net_id and ep.terminal_source_key in term_to_net:
mod_net_to_sys[(str(ep.module_source_key), str(child_net_id))] = (
term_to_net[ep.terminal_source_key]
)
mod_info_by_key = {
mod.ref.full_id: (mod.designator, mod.title) for mod in mbsdoc.modules
}
candidates: list[tuple[int, str, dict[str, object]]] = []
seen_fields: set[tuple[str, str, str]] = set()
for rnet in root_def.nets:
for field_entry in system.fields_for_net(rnet.id):
sf = field_entry.source_field
field_sig = (
field_entry.definition_id,
str(sf.selector.object_uid),
str(sf.selector.field),
)
if field_sig in seen_fields:
continue
impacts = system.impacts_for_field(field_entry.definition_id, sf)
distinct_mods = sorted({str(imp.module_source_key) for imp in impacts})
if len(distinct_mods) < 2:
continue
seen_fields.add(field_sig)
matched_net_idx = 999
matched_net_name = sf.raw_value
impacted_rows: list[dict[str, object]] = []
for imp in impacts:
mkey = str(imp.module_source_key)
des, title = mod_info_by_key.get(mkey, (mkey.rsplit("\\", 1)[-1], ""))
sys_match = mod_net_to_sys.get((mkey, str(imp.net_id)))
if sys_match is not None:
matched_net_idx, matched_net_name = sys_match
impacted_rows.append(
{
"module_source_key": mkey,
"designator": des,
"title": title,
"system_net_index": matched_net_idx,
"system_net_name": matched_net_name,
}
)
impacted_rows.sort(key=lambda r: str(r["designator"]))
record: dict[str, object] = {
"system_net_id": rnet.id,
"system_net_index": matched_net_idx,
"system_net_name": matched_net_name,
"definition_id": field_entry.definition_id,
"project_name": field_entry.project_path.name,
"document_name": sf.document_path.name,
"object_kind": str(sf.selector.object_kind),
"object_uid": str(sf.selector.object_uid),
"field_name": str(sf.selector.field),
"raw_value": str(sf.raw_value),
"impacted_modules": distinct_mods,
"impacted_rows": impacted_rows,
"impact_count": len(impacts),
}
candidates.append((matched_net_idx, str(sf.raw_value), record))
candidates.sort(key=lambda item: (item[0], item[1]))
primary = candidates[0][2] if candidates else None
return primary, len(candidates)
def render_system_topology_svg(
mbsdoc: AltiumMbsDoc,
netlist: MbsSystemNetlist,
system: AltiumSystem,
*,
theme: Literal["paper", "dark"] = "paper",
project_name: str = "DemoSystem.PrjMbd",
mbsdoc_name: str = "DemoSystem.MbsDoc",
) -> str:
"""Render a data-driven Multi-Board System topology diagram in Paper or Dark theme.
Reads modules, repeated-board occurrences, connectors, pins, local board nets,
mated pin-to-pin harness links, compiled system nets + aliases, and C0
``impacts_for_field()`` traces directly from the live objects.
"""
pal = _TOPOLOGY_THEMES[theme]
# --- 1. Index live metadata from mbsdoc, netlist, and system ---
occ_by_mod = {occ.module_ref.full_id: occ for occ in netlist.occurrences}
term_by_ref = {term.ref.full_id: term for term in netlist.terminals}
entry_owner: dict[str, str] = {}
entry_des: dict[str, str] = {}
for mod in mbsdoc.modules:
mkey = mod.ref.full_id
for ent in mod.entries:
ekey = ent.ref.full_id
entry_owner[ekey] = mkey
entry_des[ekey] = str(
ent.defined_designator or ent.calculated_designator or ekey
)
# Map each terminal to its compiled system net & color.
term_net_idx: dict[str, int] = {}
net_colors: dict[int, str] = {}
net_canonical: dict[int, str] = {}
for snet in netlist.nets:
names = tuple(str(n) for n in snet.names)
net_colors[snet.index] = _net_color(names, snet.index, pal)
net_canonical[snet.index] = names[0] if names else f"NET_{snet.index}"
for tref in snet.terminals:
term_net_idx[tref.full_id] = snet.index
# Map module_source_key -> (definition_id, source schematic filename).
comp_dto = system.compilation.to_dto()
defs_by_id = {d.id: d for d in comp_dto.definitions}
mod_def_id: dict[str, str] = {}
mod_sch_name: dict[str, str] = {}
for ep in system.endpoints:
mkey = str(ep.module_source_key)
mod_def_id.setdefault(mkey, str(ep.definition_id))
for mkey, def_id in mod_def_id.items():
cdef = defs_by_id.get(def_id)
if cdef is not None and cdef.schematic.pages:
page_path = str(
getattr(cdef.schematic.pages[0], "document_path", "")
or getattr(cdef.schematic.pages[0], "name", "")
)
if page_path:
mod_sch_name[mkey] = _basename(page_path)
# Fallback schematic filename from netlist.child_nets contributors.
unit_sch_name: dict[str, str] = {}
for cnet in netlist.child_nets:
if cnet.contributors:
doc_p = str(getattr(cnet.contributors[0], "document_path", ""))
if doc_p:
unit_sch_name.setdefault(cnet.design_unit, _basename(doc_p))
# Count repeated-board occurrences by normalized board project / design unit.
unit_members: dict[str, list[str]] = defaultdict(list)
mod_unit: dict[str, str] = {}
for mod in mbsdoc.modules:
mkey = mod.ref.full_id
occ = occ_by_mod.get(mkey)
raw_unit = (
occ.design_unit
if occ is not None and occ.design_unit
else (mod.source.source_project if mod.source else mod.designator)
)
norm_unit = str(raw_unit or mod.designator).replace("\\", "/")
mod_unit[mkey] = norm_unit
unit_members[norm_unit].append(mkey)
unique_board_count = len(unit_members)
# Determine module adjacency from mated links to split Hub (left) vs Leaf (right).
peer_mods: dict[str, set[str]] = defaultdict(set)
for link in netlist.links:
if len(link.endpoints) >= 2:
t0 = term_by_ref.get(link.endpoints[0].full_id)
t1 = term_by_ref.get(link.endpoints[1].full_id)
if t0 is not None and t1 is not None:
m0, m1 = t0.owner_ref.full_id, t1.owner_ref.full_id
if m0 != m1:
peer_mods[m0].add(m1)
peer_mods[m1].add(m0)
mod_by_key = {mod.ref.full_id: mod for mod in mbsdoc.modules}
left_keys = [
mod.ref.full_id
for mod in mbsdoc.modules
if len(peer_mods.get(mod.ref.full_id, ())) > 1
]
if not left_keys and mbsdoc.modules:
left_keys = [mbsdoc.modules[0].ref.full_id]
left_set = set(left_keys)
right_keys = [mod.ref.full_id for mod in mbsdoc.modules if mod.ref.full_id not in left_set]
# Order right-column modules to match connector order on left-column hubs (minimize crossings).
right_order_rank: dict[str, int] = {}
rank_counter = 0
for lkey in left_keys:
lmod = mod_by_key[lkey]
for ent in lmod.entries:
ekey = ent.ref.full_id
for conn in mbsdoc.connections:
for ec in conn.entries_connections:
e1, e2 = ec.entry1.full_id, ec.entry2.full_id
peer_e = e2 if e1 == ekey else (e1 if e2 == ekey else None)
if peer_e is not None:
pm = entry_owner.get(peer_e)
if pm in right_keys and pm not in right_order_rank:
right_order_rank[pm] = rank_counter
rank_counter += 1
right_keys.sort(key=lambda k: (right_order_rank.get(k, 999), mod_by_key[k].designator))
# --- 2. Compute layout geometry ---
svg_w = 1280
header_h = 82
stage_top = 98
card_w = 384
left_x = 36
right_x = svg_w - 36 - card_w # 860
conn_w = 236
row_h = 30
conn_hdr_h = 26
conn_pad_b = 6
card_hdr_h = 66
conn_gap = 24
card_gap = 22
def _module_connectors(mkey: str) -> list[dict[str, object]]:
mod = mod_by_key[mkey]
comp_by_pin = {
pin.ref.full_id: comp for comp in mod.components for pin in comp.pins
}
pin_by_ref = {
pin.ref.full_id: pin for comp in mod.components for pin in comp.pins
}
result: list[dict[str, object]] = []
if mod.entries:
for ent in mod.entries:
comp = None
pin_rows: list[dict[str, str]] = []
for pref in ent.pins:
pkey = pref.full_id
pin = pin_by_ref.get(pkey)
if comp is None:
comp = comp_by_pin.get(pkey)
term = term_by_ref.get(pkey)
pnum = (
str(term.pin_number)
if term is not None and term.pin_number
else str(pin.number if pin is not None else "")
)
pname = (
str(pin.name)
if pin is not None and pin.name
else str(term.pin_name if term is not None else "")
)
if pname == pnum:
pname = ""
local_net = ""
child_net_ref = ""
if term is not None:
if term.child_join is not None and term.child_join.child_net_name:
local_net = str(term.child_join.child_net_name)
child_net_ref = str(term.child_join.child_net_ref or "")
elif term.resolved_snapshot_name:
local_net = str(term.resolved_snapshot_name)
elif term.snapshot_name:
local_net = str(term.snapshot_name)
if not local_net and pin is not None:
for param in pin.parameters:
if param.name == "ExternalNetName":
local_net = str(param.value)
break
pin_rows.append(
{
"ref": pkey,
"number": pnum,
"name": pname,
"local_net": local_net or "NC",
"child_net_ref": child_net_ref,
}
)
cdes = str(
ent.defined_designator
or ent.calculated_designator
or (comp.designator if comp is not None else "J?")
)
comment = str(comp.comment) if comp is not None and comp.comment else ""
result.append(
{
"entry_ref": ent.ref.full_id,
"designator": cdes,
"comment": comment,
"pins": pin_rows,
}
)
return result
mod_conns = {m.ref.full_id: _module_connectors(m.ref.full_id) for m in mbsdoc.modules}
def _conn_height(conn_data: dict[str, object]) -> int:
pins = conn_data["pins"]
assert isinstance(pins, list)
return conn_hdr_h + max(len(pins), 1) * row_h + conn_pad_b
def _card_min_height(mkey: str) -> int:
conns = mod_conns[mkey]
body_h = sum(_conn_height(c) for c in conns) + max(len(conns) - 1, 0) * conn_gap
return card_hdr_h + 14 + body_h + 28
left_natural = (
sum(_card_min_height(k) for k in left_keys)
+ max(len(left_keys) - 1, 0) * card_gap
)
right_natural = (
sum(_card_min_height(k) for k in right_keys)
+ max(len(right_keys) - 1, 0) * card_gap
)
stage_content_h = max(left_natural, right_natural, 424)
stage_bottom = stage_top + stage_content_h + 16
# Position cards cleanly in left and right columns.
card_boxes: dict[str, tuple[int, int, int, int]] = {} # x, y, w, h
pin_coords: dict[str, tuple[float, float, str]] = {} # ref -> (x, y, side)
conn_boxes: dict[str, tuple[int, int, int, int]] = {} # entry_ref -> (x, y, w, h)
# Right column stacked evenly from stage_top + 8.
ry = stage_top + 8 + max(0, (stage_content_h - right_natural) // 2)
for rkey in right_keys:
ch = _card_min_height(rkey)
card_boxes[rkey] = (right_x, ry, card_w, ch)
ry += ch + card_gap
# Left column: if single hub spans alongside multiple right cards, stretch card nicely.
if len(left_keys) == 1 and right_keys:
lkey = left_keys[0]
top_y = min(card_boxes[k][1] for k in right_keys)
bot_y = max(card_boxes[k][1] + card_boxes[k][3] for k in right_keys)
span_h = max(_card_min_height(lkey), bot_y - top_y)
card_boxes[lkey] = (left_x, top_y, card_w, span_h)
else:
ly = stage_top + 8 + max(0, (stage_content_h - left_natural) // 2)
for lkey in left_keys:
ch = _card_min_height(lkey)
card_boxes[lkey] = (left_x, ly, card_w, ch)
ly += ch + card_gap
# Assign connector and pin coordinates within each module card (clearing bottom holes).
for mkey, (bx, by, bw, bh) in card_boxes.items():
side = "right" if mkey in left_set else "left"
conns = mod_conns[mkey]
total_ch = sum(_conn_height(c) for c in conns)
avail_h = bh - card_hdr_h - 14 - 28
if len(conns) > 1 and avail_h > total_ch:
# Distribute connectors evenly with generous spacing so harnesses fan cleanly.
extra = avail_h - total_ch
top_pad = min(24, extra // 4)
gap = (extra - 2 * top_pad) // (len(conns) - 1)
cy = by + card_hdr_h + 14 + top_pad
else:
gap = conn_gap
cy = by + card_hdr_h + 14 + max(0, (avail_h - total_ch) // 2)
cx = (bx + bw - conn_w) if side == "right" else bx
for cdata in conns:
ch = _conn_height(cdata)
eref = str(cdata["entry_ref"])
conn_boxes[eref] = (cx, cy, conn_w, ch)
pins = cdata["pins"]
assert isinstance(pins, list)
px = float(cx + conn_w) if side == "right" else float(cx)
for idx, prow in enumerate(pins):
py = float(cy + conn_hdr_h + idx * row_h + row_h / 2)
pin_coords[str(prow["ref"])] = (px, py, side)
cy += ch + gap
# Bottom analytics strip coordinates.
analytics_top = stage_bottom + 12
net_row_h = 38
analytics_h = max(204, 72 + len(netlist.nets) * net_row_h + 24)
svg_h = analytics_top + analytics_h + 26
# --- 3. Query C0 repeated-board field impact ---
primary_impact, total_repeated_fields = _extract_repeated_field_impacts(
mbsdoc, netlist, system
)
# --- 4. Assemble SVG elements ---
out: list[str] = [
f'<svg xmlns="http://www.w3.org/2000/svg" width="{svg_w}" height="{svg_h}" '
f'viewBox="0 0 {svg_w} {svg_h}" role="img" '
f'aria-label="Multi-Board System Topology ({_esc(project_name)})">',
"<defs>",
' <pattern id="bg-dots" width="24" height="24" patternUnits="userSpaceOnUse">',
f' <circle cx="12" cy="12" r="1.05" fill="{pal.grid_dot}"/>',
" </pattern>",
"</defs>",
# Canvas background & subtle engineering dot grid
f'<rect x="0" y="0" width="{svg_w}" height="{svg_h}" fill="{pal.bg}"/>',
f'<rect x="0" y="0" width="{svg_w}" height="{svg_h}" fill="url(#bg-dots)"/>',
f'<rect x="0.75" y="0.75" width="{svg_w - 1.5}" height="{svg_h - 1.5}" '
f'fill="none" stroke="{pal.frame_stroke}" stroke-width="1.5"/>',
]
# --- Header Bar ---
out.extend(
[
f'<rect x="0" y="0" width="{svg_w}" height="{header_h}" fill="{pal.header_bg}"/>',
f'<rect x="0" y="0" width="{svg_w}" height="4" fill="{pal.header_accent}"/>',
f'<line x1="0" y1="{header_h}" x2="{svg_w}" y2="{header_h}" '
f'stroke="{pal.header_border}" stroke-width="1.2"/>',
f'<text x="28" y="25" font-family="{_FONT_SANS}" font-size="9.5" '
f'font-weight="700" letter-spacing="1.4" fill="{pal.header_accent}">'
f"MULTI-BOARD SYSTEM TOPOLOGY · ALTIUM MONKEY</text>",
f'<text x="28" y="50" font-family="{_FONT_SANS}" font-size="20" '
f'font-weight="700" fill="{pal.text_primary}">{_esc(project_name)}'
f'<tspan dx="8" font-family="{_FONT_MONO}" font-size="13" font-weight="500" '
f'fill="{pal.text_muted}">/ {_esc(mbsdoc_name)}</tspan></text>',
f'<text x="28" y="69" font-family="{_FONT_SANS}" font-size="11" '
f'fill="{pal.text_muted}">Live graph from AltiumMbsDoc · MbsSystemNetlist (v1) · AltiumSystem (C0)</text>',
]
)
# Header KPI badges (right-aligned, auto-sized).
complete_ok = bool(mbsdoc.connectivity_complete and netlist.connectivity_complete)
kpis: list[tuple[str, bool, bool]] = [
(f"{unique_board_count} Boards", False, False),
(f"{len(mbsdoc.modules)} Module Instances", False, False),
(f"{len(netlist.nets)} Cross-Board Nets", False, False),
(f"{len(netlist.links)} Mated Links", False, False),
(
"Connectivity: Complete" if complete_ok else "Connectivity: Incomplete",
True,
complete_ok,
),
]
pill_h = 28
pill_y = 28
pill_gap = 8
pill_specs: list[tuple[str, float, bool, bool]] = []
for label, is_status, is_ok in kpis:
pw = round(_estimate_text_w(label, 11.0) + (34 if is_status else 22))
pill_specs.append((label, pw, is_status, is_ok))
cursor_x = float(svg_w - 28)
for label, pw, is_status, is_ok in reversed(pill_specs):
cursor_x -= pw
if is_status:
bg = pal.ok_bg if is_ok else pal.warn_bg
st = pal.ok_stroke if is_ok else pal.warn_stroke
fg = pal.ok_text if is_ok else pal.warn_text
dot = pal.ok_dot if is_ok else pal.warn_dot
out.append(
f'<rect x="{cursor_x:.1f}" y="{pill_y}" width="{pw:.1f}" height="{pill_h}" '
f'rx="14" fill="{bg}" stroke="{st}" stroke-width="1.1"/>'
)
out.append(
f'<circle cx="{cursor_x + 13:.1f}" cy="{pill_y + pill_h / 2:.1f}" '
f'r="4" fill="{dot}"/>'
)
out.append(
f'<text x="{cursor_x + 23:.1f}" y="{pill_y + 18}" '
f'font-family="{_FONT_SANS}" font-size="11" font-weight="600" '
f'fill="{fg}">{_esc(label)}</text>'
)
else:
out.append(
f'<rect x="{cursor_x:.1f}" y="{pill_y}" width="{pw:.1f}" height="{pill_h}" '
f'rx="14" fill="{pal.pill_bg}" stroke="{pal.pill_stroke}" stroke-width="1"/>'
)
out.append(
f'<text x="{cursor_x + pw / 2:.1f}" y="{pill_y + 18}" '
f'text-anchor="middle" font-family="{_FONT_SANS}" font-size="11" '
f'font-weight="600" fill="{pal.pill_text}">{_esc(label)}</text>'
)
cursor_x -= pill_gap
# --- 5. Render Cross-Board Harnesses & Mated Links (under connector contact pads) ---
links_by_group: dict[str, list[object]] = defaultdict(list)
for link in netlist.links:
links_by_group[link.link_group_ref.full_id].append(link)
mbs_conn_by_ref = {conn.ref.full_id: conn for conn in mbsdoc.connections}
wire_tags: list[tuple[float, float, str, str]] = [] # mx, my, label, color
out.append('<g id="harnesses">')
for group_ref, group_links in links_by_group.items():
mbs_conn = mbs_conn_by_ref.get(group_ref)
routed_wires: list[tuple[float, float, float, float, str, str]] = []
left_entry_name = ""
right_entry_name = ""
for link in group_links:
if len(link.endpoints) < 2:
continue
r0, r1 = link.endpoints[0].full_id, link.endpoints[1].full_id
c0, c1 = pin_coords.get(r0), pin_coords.get(r1)
if c0 is None or c1 is None:
continue
if c0[0] > c1[0]:
r0, r1 = r1, r0
c0, c1 = c1, c0
t0, t1 = term_by_ref.get(r0), term_by_ref.get(r1)
if t0 is not None and not left_entry_name:
left_entry_name = entry_des.get(t0.entry_ref.full_id, "")
if t1 is not None and not right_entry_name:
right_entry_name = entry_des.get(t1.entry_ref.full_id, "")
nidx = term_net_idx.get(r0, term_net_idx.get(r1, 0))
color = net_colors.get(nidx, pal.net_data)
label = str(
link.effective_name
or link.defined_name
or net_canonical.get(nidx, f"NET_{nidx}")
)
routed_wires.append((c0[0], c0[1], c1[0], c1[1], color, label))
if not routed_wires:
continue
# Sort wires top-to-bottom by midpoint Y.
routed_wires.sort(key=lambda w: (w[1] + w[3]) / 2.0)
mx = (routed_wires[0][0] + routed_wires[0][2]) / 2.0
mid_ys = [(w[1] + w[3]) / 2.0 for w in routed_wires]
sheath_w = 188.0
sheath_x = mx - sheath_w / 2.0
sheath_top = min(mid_ys) - 18.0
sheath_bot = max(mid_ys) + 18.0
sheath_h = sheath_bot - sheath_top
# Cable harness sheath & cable-tie end collars
out.append(
f' <rect x="{sheath_x:.1f}" y="{sheath_top:.1f}" '
f'width="{sheath_w:.1f}" height="{sheath_h:.1f}" rx="11" '
f'fill="{pal.sheath_bg}" fill-opacity="0.78" '
f'stroke="{pal.sheath_stroke}" stroke-width="1" stroke-dasharray="4 3"/>'
)
collar_h = max(14.0, sheath_h - 14.0)
out.append(
f' <rect x="{sheath_x - 2.5:.1f}" y="{sheath_top + 7.0:.1f}" '
f'width="5" height="{collar_h:.1f}" rx="2.5" fill="{pal.sheath_collar}"/>'
)
out.append(
f' <rect x="{sheath_x + sheath_w - 2.5:.1f}" y="{sheath_top + 7.0:.1f}" '
f'width="5" height="{collar_h:.1f}" rx="2.5" fill="{pal.sheath_collar}"/>'
)
# Harness header pill above sheath
conn_des = mbs_conn.designator if mbs_conn is not None else "LINK"
conn_kind = mbs_conn.kind.value if mbs_conn is not None else "direct"
pair_txt = (
f"{left_entry_name} ↔ {right_entry_name}"
if left_entry_name and right_entry_name
else f"{len(routed_wires)} pins"
)
hdr_label = f"{conn_des} · {conn_kind} · {pair_txt}"
hdr_w = max(148.0, round(_estimate_text_w(hdr_label, 10.0, mono=True) + 22))
hdr_x = mx - hdr_w / 2.0
hdr_y = sheath_top - 25.0
out.append(
f' <rect x="{hdr_x:.1f}" y="{hdr_y:.1f}" width="{hdr_w:.1f}" height="20" '
f'rx="10" fill="{pal.card_bg}" stroke="{pal.card_stroke}" stroke-width="1"/>'
)
out.append(
f' <text x="{mx:.1f}" y="{hdr_y + 13.5:.1f}" text-anchor="middle" '
f'font-family="{_FONT_MONO}" font-size="10" font-weight="600" '
f'fill="{pal.text_secondary}">{_esc(hdr_label)}</text>'
)
# Smooth cubic Bézier wires
for x1, y1, x2, y2, color, label in routed_wires:
path_d = (
f"M {x1:.1f},{y1:.1f} "
f"C {mx:.1f},{y1:.1f} {mx:.1f},{y2:.1f} {x2:.1f},{y2:.1f}"
)
halo_color = pal.wire_halo if pal.wire_halo else color
out.append(
f' <path d="{path_d}" fill="none" stroke="{halo_color}" '
f'stroke-width="{pal.wire_halo_width}" '
f'stroke-opacity="{pal.wire_halo_opacity}" stroke-linecap="round"/>'
)
out.append(
f' <path d="{path_d}" fill="none" stroke="{color}" '
f'stroke-width="{pal.wire_width}" stroke-linecap="round"/>'
)
wire_tags.append((mx, (y1 + y2) / 2.0, label, color))
# Draw wire net label pills on top of all wires so they remain razor sharp.
for mx, my, label, color in wire_tags:
lbl_w = _estimate_text_w(label, 10.0, mono=True)
tw = max(84.0, round(lbl_w + 30.0))
tx = mx - tw / 2.0
ty = my - 10.0
content_w = 13.0 + lbl_w
content_x = mx - content_w / 2.0
out.append(
f' <rect x="{tx:.1f}" y="{ty:.1f}" width="{tw:.1f}" height="20" rx="10" '
f'fill="{pal.wire_tag_bg}" stroke="{color}" stroke-width="1.35"/>'
)
out.append(
f' <circle cx="{content_x + 3.2:.1f}" cy="{my:.1f}" r="3.2" fill="{color}"/>'
)
out.append(
f' <text x="{content_x + 11.5:.1f}" y="{my + 3.5:.1f}" '
f'font-family="{_FONT_MONO}" font-size="10" font-weight="700" '
f'fill="{pal.text_primary}">{_esc(label)}</text>'
)
out.append("</g>")
# --- 6. Render Module PCB Cards & Docked Connectors ---
out.append('<g id="modules">')
for mkey, (bx, by, bw, bh) in card_boxes.items():
mod = mod_by_key[mkey]
is_hub = mkey in left_set
accent = pal.hub_accent if is_hub else pal.leaf_accent
norm_unit = mod_unit[mkey]
proj_basename = _basename(norm_unit)
siblings = unit_members[norm_unit]
occ_idx = siblings.index(mkey) + 1
occ_total = len(siblings)
is_repeated = occ_total > 1
conns = mod_conns[mkey]
total_pins = sum(len(c["pins"]) for c in conns if isinstance(c["pins"], list))
conn_word = "connector" if len(conns) == 1 else "connectors"
# Soft drop shadow + PCB card body
out.append(
f' <rect x="{bx + 3}" y="{by + 4}" width="{bw}" height="{bh}" rx="10" '
f'fill="{pal.card_shadow}" fill-opacity="{pal.card_shadow_opacity}"/>'
)
out.append(
f' <rect x="{bx}" y="{by}" width="{bw}" height="{bh}" rx="10" '
f'fill="{pal.card_bg}" stroke="{pal.card_stroke}" stroke-width="1.4"/>'
)
# Top inset accent bar
out.append(
f' <rect x="{bx + 14}" y="{by + 1.5}" width="{bw - 28}" height="4" '
f'rx="2" fill="{accent}"/>'
)
# 4 PCB corner mounting holes (copper pad ring + drill center)
for hx, hy in (
(bx + 14, by + 15),
(bx + bw - 14, by + 15),
(bx + 14, by + bh - 14),
(bx + bw - 14, by + bh - 14),
):
out.append(
f' <circle cx="{hx}" cy="{hy}" r="5.2" fill="{pal.hole_ring}" '
f'fill-opacity="0.28" stroke="{pal.hole_ring}" stroke-width="1.2"/>'
)
out.append(
f' <circle cx="{hx}" cy="{hy}" r="2.3" fill="{pal.hole_drill}"/>'
)
# Module header text (clear of mounting holes)
title_tspan = (
f'<tspan dx="6" font-size="12.5" font-weight="500" '
f'fill="{pal.text_secondary}">· {_esc(mod.title)}</tspan>'
if mod.title
else ""
)
out.append(
f' <text x="{bx + 28}" y="{by + 31}" font-family="{_FONT_SANS}" '
f'font-size="15.5" font-weight="700" fill="{pal.text_primary}">'
f"{_esc(mod.designator)}{title_tspan}</text>"
)
# Top-right instance role badge (clear of top-right mounting hole)
if is_repeated:
badge_txt = f"REPEATED · {occ_idx}/{occ_total}"
b_bg, b_st, b_fg = pal.repeated_bg, pal.repeated_stroke, pal.repeated_text
elif is_hub:
badge_txt = f"HUB · {occ_idx}/{occ_total}"
b_bg, b_st, b_fg = pal.pill_bg, pal.pill_stroke, pal.hub_accent
else:
badge_txt = f"BOARD · {occ_idx}/{occ_total}"
b_bg, b_st, b_fg = pal.pill_bg, pal.pill_stroke, pal.pill_text
badge_w = round(_estimate_text_w(badge_txt, 9.5) + 18)
badge_x = bx + bw - 28 - badge_w
out.append(
f' <rect x="{badge_x}" y="{by + 15}" width="{badge_w}" height="21" '
f'rx="10.5" fill="{b_bg}" stroke="{b_st}" stroke-width="1"/>'
)
out.append(
f' <text x="{badge_x + badge_w / 2:.1f}" y="{by + 28.8}" '
f'text-anchor="middle" font-family="{_FONT_SANS}" font-size="9.5" '
f'font-weight="700" letter-spacing="0.4" fill="{b_fg}">'
f"{_esc(badge_txt)}</text>"
)
# Subtitle: source .PrjPcb & pin/connector counts
out.append(
f' <text x="{bx + 28}" y="{by + 51}" font-family="{_FONT_MONO}" '
f'font-size="10.8" font-weight="600" fill="{pal.text_secondary}">'
f'{_esc(proj_basename)}<tspan dx="6" font-family="{_FONT_SANS}" '
f'font-size="10.5" font-weight="400" fill="{pal.text_muted}">'
f"· {len(conns)} {conn_word} · {total_pins} pins</tspan></text>"
)
out.append(
f' <line x1="{bx + 16}" y1="{by + card_hdr_h - 3}" '
f'x2="{bx + bw - 16}" y2="{by + card_hdr_h - 3}" '
f'stroke="{pal.divider}" stroke-width="1"/>'
)
# Internal shared PCB net rails (drawn dynamically when 2+ connectors share child_net_ref!)
if is_hub and len(conns) >= 2:
pins_by_child_net: dict[str, list[tuple[float, int]]] = defaultdict(list)
for cdata in conns:
pins = cdata["pins"]
assert isinstance(pins, list)
for prow in pins:
cref = str(prow["child_net_ref"])
pref = str(prow["ref"])
if cref and pref in pin_coords:
pins_by_child_net[cref].append(
(pin_coords[pref][1], term_net_idx.get(pref, 0))
)
shared_rails = [
(min(ys_n[1] for ys_n in pts), sorted(p[0] for p in pts))
for pts in pins_by_child_net.values()
if len(pts) >= 2
]
shared_rails.sort(key=lambda r: r[0])
if shared_rails:
conn_left_x = bx + bw - conn_w
out.append(
f' <text x="{bx + 22}" y="{by + card_hdr_h + 15}" '
f'font-family="{_FONT_SANS}" font-size="9" font-weight="700" '
f'letter-spacing="0.9" fill="{pal.text_muted}">'
f"SHARED PCB RAILS</text>"
)
rail_spacing = min(28, max(16, 92 // max(len(shared_rails), 1)))
first_rail_x = conn_left_x - 32
for ridx, (nidx, ys) in enumerate(shared_rails):
rx = first_rail_x - ridx * rail_spacing
rcol = net_colors.get(nidx, pal.text_muted)
y_top, y_bot = ys[0], ys[-1]
# Vertical bus trunk
out.append(
f' <line x1="{rx}" y1="{y_top:.1f}" x2="{rx}" y2="{y_bot:.1f}" '
f'stroke="{rcol}" stroke-width="2" stroke-opacity="0.72" '
f'stroke-linecap="round"/>'
)
# Horizontal stubs into each connector + via/junction pads
for py in ys:
out.append(
f' <line x1="{rx}" y1="{py:.1f}" x2="{conn_left_x}" '
f'y2="{py:.1f}" stroke="{rcol}" stroke-width="1.8" '
f'stroke-opacity="0.72"/>'
)
out.append(
f' <circle cx="{rx}" cy="{py:.1f}" r="3.2" '
f'fill="{pal.card_bg}" stroke="{rcol}" stroke-width="1.8"/>'
)
elif not is_hub:
# Subtle board definition metadata box on the right interior of leaf cards
meta_x = bx + conn_w + 14
meta_w = bw - conn_w - 28
meta_h = 88
first_conn_box = (
conn_boxes[str(conns[0]["entry_ref"])] if conns else (bx, by + card_hdr_h + 14, conn_w, meta_h)
)
meta_y = first_conn_box[1] + max(0, (first_conn_box[3] - meta_h) // 2)
sch_name = mod_sch_name.get(mkey) or unit_sch_name.get(norm_unit, "")
def_short = mod_def_id.get(mkey, "")[:8]
out.append(
f' <rect x="{meta_x}" y="{meta_y}" width="{meta_w}" height="{meta_h}" '
f'rx="7" fill="{pal.subcard_bg}" stroke="{pal.subcard_stroke}" '
f'stroke-width="1" stroke-dasharray="3 2.5"/>'
)
out.append(
f' <text x="{meta_x + 10}" y="{meta_y + 18}" '
f'font-family="{_FONT_SANS}" font-size="8.8" font-weight="700" '
f'letter-spacing="0.8" fill="{pal.text_muted}">SOURCE SCHEMATIC</text>'
)
out.append(
f' <text x="{meta_x + 10}" y="{meta_y + 36}" '
f'font-family="{_FONT_MONO}" font-size="11" font-weight="700" '
f'fill="{pal.text_primary}">{_esc(sch_name or proj_basename)}</text>'
)
def_label = "Shared C0 Def" if is_repeated else "Compiled C0 Def"
out.append(
f' <text x="{meta_x + 10}" y="{meta_y + 57}" '
f'font-family="{_FONT_SANS}" font-size="9.5" '
f'fill="{pal.text_muted}">{_esc(def_label)}</text>'
)
if def_short:
out.append(
f' <text x="{meta_x + 10}" y="{meta_y + 73}" '
f'font-family="{_FONT_MONO}" font-size="10" font-weight="600" '
f'fill="{accent}">def:{_esc(def_short)}…</text>'
)
# Docked connector blocks
side = "right" if is_hub else "left"
for cdata in conns:
eref = str(cdata["entry_ref"])
cx, cy, cw, ch = conn_boxes[eref]
cdes = str(cdata["designator"])
comment = str(cdata["comment"])
pins = cdata["pins"]
assert isinstance(pins, list)
out.append(
f' <rect x="{cx}" y="{cy}" width="{cw}" height="{ch}" rx="6" '
f'fill="{pal.conn_bg}" stroke="{pal.conn_stroke}" stroke-width="1.2"/>'
)
# Connector header strip
out.append(
f' <rect x="{cx + 0.6}" y="{cy + 0.6}" width="{cw - 1.2}" '
f'height="{conn_hdr_h}" rx="5" fill="{pal.conn_header_bg}"/>'
)
out.append(
f' <rect x="{cx + 0.6}" y="{cy + conn_hdr_h - 5}" width="{cw - 1.2}" '
f'height="5.6" fill="{pal.conn_header_bg}"/>'
)
out.append(
f' <text x="{cx + 10}" y="{cy + 17}" font-family="{_FONT_MONO}" '
f'font-size="11.5" font-weight="700" fill="{pal.conn_header_text}">'
f"{_esc(cdes)}</text>"
)
if comment:
out.append(
f' <text x="{cx + cw - 10}" y="{cy + 16.5}" text-anchor="end" '
f'font-family="{_FONT_MONO}" font-size="9.5" '
f'fill="{pal.conn_header_muted}">{_esc(comment)}</text>'
)
# Pin rows
for idx, prow in enumerate(pins):
pref = str(prow["ref"])
pnum = str(prow["number"])
pname = str(prow["name"])
local_net = str(prow["local_net"])
nidx = term_net_idx.get(pref, idx)
pcol = net_colors.get(nidx, pal.net_data)
ry_top = cy + conn_hdr_h + idx * row_h
py = ry_top + row_h / 2.0
if idx % 2 == 1:
out.append(
f' <rect x="{cx + 1}" y="{ry_top}" width="{cw - 2}" '
f'height="{row_h}" fill="{pal.row_alt}" fill-opacity="0.55"/>'
)
if side == "right":
# [Local Net Pill] [Pin Name] [Pin#] --- (●)
net_x, net_w = cx + 8, 92
out.append(
f' <rect x="{net_x}" y="{py - 10:.1f}" width="{net_w}" '
f'height="20" rx="4" fill="{pal.card_bg}" '
f'stroke="{pal.divider}" stroke-width="1"/>'
)
out.append(
f' <rect x="{net_x}" y="{py - 10:.1f}" width="3.5" '
f'height="20" rx="1.5" fill="{pcol}"/>'
)
out.append(
f' <text x="{net_x + 9}" y="{py + 3.6:.1f}" '
f'font-family="{_FONT_MONO}" font-size="10.5" font-weight="700" '
f'fill="{pal.text_primary}">{_esc(local_net)}</text>'
)
if pname:
out.append(
f' <text x="{cx + 112}" y="{py + 3.6:.1f}" '
f'font-family="{_FONT_SANS}" font-size="10.2" '
f'font-weight="600" fill="{pal.text_secondary}">'
f"{_esc(pname)}</text>"
)
pbox_x = cx + cw - 66
out.append(
f' <rect x="{pbox_x}" y="{py - 9:.1f}" width="22" height="18" '
f'rx="4" fill="{pal.pill_bg}" stroke="{pal.pill_stroke}" '
f'stroke-width="0.9"/>'
)
out.append(
f' <text x="{pbox_x + 11}" y="{py + 3.5:.1f}" '
f'text-anchor="middle" font-family="{_FONT_MONO}" '
f'font-size="10" font-weight="700" fill="{pal.pill_text}">'
f"{_esc(pnum)}</text>"
)
pad_x = cx + cw
out.append(
f' <line x1="{pbox_x + 22}" y1="{py:.1f}" x2="{pad_x - 5.5}" '
f'y2="{py:.1f}" stroke="{pcol}" stroke-width="2"/>'
)
out.append(
f' <circle cx="{pad_x}" cy="{py:.1f}" r="5.5" '
f'fill="{pal.card_bg}" stroke="{pcol}" stroke-width="2.2"/>'
)
out.append(
f' <circle cx="{pad_x}" cy="{py:.1f}" r="2.2" fill="{pcol}"/>'
)
else:
# (●) --- [Pin#] [Pin Name] [Local Net Pill]
pad_x = cx
pbox_x = cx + 44
out.append(
f' <line x1="{pad_x + 5.5}" y1="{py:.1f}" x2="{pbox_x}" '
f'y2="{py:.1f}" stroke="{pcol}" stroke-width="2"/>'
)
out.append(
f' <circle cx="{pad_x}" cy="{py:.1f}" r="5.5" '
f'fill="{pal.card_bg}" stroke="{pcol}" stroke-width="2.2"/>'
)
out.append(
f' <circle cx="{pad_x}" cy="{py:.1f}" r="2.2" fill="{pcol}"/>'
)
out.append(
f' <rect x="{pbox_x}" y="{py - 9:.1f}" width="22" height="18" '
f'rx="4" fill="{pal.pill_bg}" stroke="{pal.pill_stroke}" '
f'stroke-width="0.9"/>'
)
out.append(
f' <text x="{pbox_x + 11}" y="{py + 3.5:.1f}" '
f'text-anchor="middle" font-family="{_FONT_MONO}" '
f'font-size="10" font-weight="700" fill="{pal.pill_text}">'
f"{_esc(pnum)}</text>"
)
if pname:
out.append(
f' <text x="{pbox_x + 32}" y="{py + 3.6:.1f}" '
f'font-family="{_FONT_SANS}" font-size="10.2" '
f'font-weight="600" fill="{pal.text_secondary}">'
f"{_esc(pname)}</text>"
)
net_w = 92
net_x = cx + cw - 8 - net_w
out.append(
f' <rect x="{net_x}" y="{py - 10:.1f}" width="{net_w}" '
f'height="20" rx="4" fill="{pal.card_bg}" '
f'stroke="{pal.divider}" stroke-width="1"/>'
)
out.append(
f' <rect x="{net_x + net_w - 3.5:.1f}" y="{py - 10:.1f}" '
f'width="3.5" height="20" rx="1.5" fill="{pcol}"/>'
)
out.append(
f' <text x="{net_x + 9}" y="{py + 3.6:.1f}" '
f'font-family="{_FONT_MONO}" font-size="10.5" font-weight="700" '
f'fill="{pal.text_primary}">{_esc(local_net)}</text>'
)
out.append("</g>")
# --- 7. Bottom Analytics Strip (2 side-by-side cards) ---
panel_gap = 20
panel_w = (svg_w - 72 - panel_gap) // 2 # 594
left_panel_x = 36
right_panel_x = left_panel_x + panel_w + panel_gap
panel_hdr_h = 34
# Helper to draw an analytics card frame.
def _draw_panel_frame(px: int, title: str, right_badge: str) -> None:
out.append(
f' <rect x="{px + 2}" y="{analytics_top + 3}" width="{panel_w}" '
f'height="{analytics_h}" rx="10" fill="{pal.card_shadow}" '
f'fill-opacity="{pal.card_shadow_opacity}"/>'
)
out.append(
f' <rect x="{px}" y="{analytics_top}" width="{panel_w}" '
f'height="{analytics_h}" rx="10" fill="{pal.card_bg}" '
f'stroke="{pal.card_stroke}" stroke-width="1.2"/>'
)
out.append(
f' <rect x="{px + 0.6}" y="{analytics_top + 0.6}" '
f'width="{panel_w - 1.2}" height="{panel_hdr_h}" rx="9" '
f'fill="{pal.card_header_bg}"/>'
)
out.append(
f' <rect x="{px + 0.6}" y="{analytics_top + panel_hdr_h - 6}" '
f'width="{panel_w - 1.2}" height="6.6" fill="{pal.card_header_bg}"/>'
)
out.append(
f' <line x1="{px}" y1="{analytics_top + panel_hdr_h}" '
f'x2="{px + panel_w}" y2="{analytics_top + panel_hdr_h}" '
f'stroke="{pal.divider}" stroke-width="1"/>'
)
out.append(
f' <text x="{px + 16}" y="{analytics_top + 21}" '
f'font-family="{_FONT_SANS}" font-size="11" font-weight="700" '
f'letter-spacing="0.9" fill="{pal.text_primary}">{_esc(title)}</text>'
)
bw_est = round(_estimate_text_w(right_badge, 9.8, mono=True) + 16)
bx_r = px + panel_w - 14 - bw_est
out.append(
f' <rect x="{bx_r}" y="{analytics_top + 7}" width="{bw_est}" '
f'height="20" rx="10" fill="{pal.pill_bg}" stroke="{pal.pill_stroke}" '
f'stroke-width="0.9"/>'
)
out.append(
f' <text x="{bx_r + bw_est / 2:.1f}" y="{analytics_top + 20.5}" '
f'text-anchor="middle" font-family="{_FONT_MONO}" font-size="9.8" '
f'font-weight="600" fill="{pal.pill_text}">{_esc(right_badge)}</text>'
)
out.append('<g id="analytics">')
# --- Left Panel: Compiled System Nets ---
_draw_panel_frame(left_panel_x, "COMPILED SYSTEM NETS", "system_netlist.v1")
col_net_x = left_panel_x + 18
col_alias_x = left_panel_x + 178
col_term_x = left_panel_x + 452
col_link_x = left_panel_x + 534
col_hdr_y = analytics_top + panel_hdr_h + 18
for cx_h, label_h, anchor in (
(col_net_x, "SYSTEM NET", "start"),
(col_alias_x, "CROSS-BOARD ALIASES", "start"),
(col_term_x + 26, "TERMINALS", "middle"),
(col_link_x + 22, "LINKS", "middle"),
):
out.append(
f' <text x="{cx_h}" y="{col_hdr_y}" text-anchor="{anchor}" '
f'font-family="{_FONT_SANS}" font-size="9.2" font-weight="700" '
f'letter-spacing="0.7" fill="{pal.text_muted}">{label_h}</text>'
)
out.append(
f' <line x1="{left_panel_x + 14}" y1="{col_hdr_y + 6}" '
f'x2="{left_panel_x + panel_w - 14}" y2="{col_hdr_y + 6}" '
f'stroke="{pal.divider}" stroke-width="1"/>'
)
# Order design units left-to-right for alias display.
ordered_units: list[str] = []
for k in [*left_keys, *right_keys]:
u = mod_unit[k]
if u not in ordered_units:
ordered_units.append(u)
row_start_y = col_hdr_y + 10
for ridx, snet in enumerate(netlist.nets):
ry_t = row_start_y + ridx * net_row_h
ry_m = ry_t + net_row_h / 2.0
col = net_colors.get(snet.index, pal.net_data)
cname = net_canonical.get(snet.index, f"NET_{snet.index}")
if ridx % 2 == 1:
out.append(
f' <rect x="{left_panel_x + 10}" y="{ry_t}" width="{panel_w - 20}" '
f'height="{net_row_h}" rx="5" fill="{pal.row_alt}"/>'
)
out.append(
f' <circle cx="{col_net_x + 5}" cy="{ry_m:.1f}" r="4.8" fill="{col}"/>'
)
out.append(
f' <text x="{col_net_x + 18}" y="{ry_m + 4:.1f}" '
f'font-family="{_FONT_MONO}" font-size="11.5" font-weight="700" '
f'fill="{pal.text_primary}">{_esc(cname)}</text>'
)
# Extract per-board local net names from compiled child_nets / terminals.
local_by_unit: dict[str, str] = {}
for cn in snet.child_nets:
u_norm = str(cn.design_unit).replace("\\", "/")
# child_net_ref format is e.g. "compiled_net:2:3V3"; prefer terminal child_join name
if u_norm not in local_by_unit:
parts = str(cn.child_net_ref).split(":", 2)
local_by_unit[u_norm] = parts[2] if len(parts) == 3 else str(cn.child_net_ref)
for tref in snet.terminals:
t = term_by_ref.get(tref.full_id)
if t is not None and t.child_join is not None and t.child_join.child_net_name:
u_norm = str(t.child_join.design_unit).replace("\\", "/")
local_by_unit[u_norm] = str(t.child_join.child_net_name)
board_aliases = [
local_by_unit[u] for u in ordered_units if u in local_by_unit
]
if not board_aliases:
board_aliases = [str(n) for n in snet.names if str(n) != cname][:2]
# Render alias chips with ↔ bridge
ax = float(col_alias_x)
for aidx, alias_name in enumerate(board_aliases[:3]):
if aidx > 0:
out.append(
f' <text x="{ax + 9:.1f}" y="{ry_m + 3.8:.1f}" '
f'text-anchor="middle" font-family="{_FONT_SANS}" font-size="12" '
f'font-weight="700" fill="{col}">↔</text>'
)
ax += 19.0
aw = max(46.0, round(_estimate_text_w(alias_name, 10.5, mono=True) + 20))
out.append(
f' <rect x="{ax:.1f}" y="{ry_m - 10:.1f}" width="{aw:.1f}" '
f'height="20" rx="4" fill="{pal.subcard_bg}" '
f'stroke="{pal.subcard_stroke}" stroke-width="1"/>'
)
out.append(
f' <text x="{ax + aw / 2:.1f}" y="{ry_m + 3.6:.1f}" '
f'text-anchor="middle" font-family="{_FONT_MONO}" font-size="10.5" '
f'font-weight="700" fill="{pal.text_primary}">{_esc(alias_name)}</text>'
)
ax += aw + 2.0
# Terminal & link counts
term_lbl = f"{len(snet.terminals)} pins"
out.append(
f' <rect x="{col_term_x}" y="{ry_m - 10:.1f}" width="54" height="20" '
f'rx="10" fill="{pal.pill_bg}" stroke="{pal.pill_stroke}" stroke-width="0.9"/>'
)
out.append(
f' <text x="{col_term_x + 27}" y="{ry_m + 3.5:.1f}" text-anchor="middle" '
f'font-family="{_FONT_SANS}" font-size="10.2" font-weight="600" '
f'fill="{pal.pill_text}">{_esc(term_lbl)}</text>'
)
link_lbl = f"{len(snet.links)} links"
out.append(
f' <rect x="{col_link_x - 4}" y="{ry_m - 10:.1f}" width="52" height="20" '
f'rx="10" fill="{pal.pill_bg}" stroke="{pal.pill_stroke}" stroke-width="0.9"/>'
)
out.append(
f' <text x="{col_link_x + 22}" y="{ry_m + 3.5:.1f}" text-anchor="middle" '
f'font-family="{_FONT_SANS}" font-size="10.2" font-weight="600" '
f'fill="{pal.pill_text}">{_esc(link_lbl)}</text>'
)
out.append(
f' <text x="{left_panel_x + 18}" y="{analytics_top + analytics_h - 12}" '
f'font-family="{_FONT_SANS}" font-size="10.2" fill="{pal.text_muted}">'
f"{len(netlist.nets)} connected components · {len(netlist.terminals)} resolved terminals · "
f"{len(netlist.diagnostics)} diagnostics</text>"
)
# --- Right Panel: C0 Source-Field Impact ---
_draw_panel_frame(
right_panel_x,
"C0 SOURCE-FIELD IMPACT",
"AltiumSystem.impacts_for_field()",
)
if primary_impact is not None:
imp_doc = str(primary_impact["document_name"])
imp_proj = str(primary_impact["project_name"])
imp_kind = str(primary_impact["object_kind"])
imp_field = str(primary_impact["field_name"])
imp_val = str(primary_impact["raw_value"])
imp_uid = str(primary_impact["object_uid"])
imp_def = str(primary_impact["definition_id"])[:8]
imp_rows = primary_impact["impacted_rows"]
assert isinstance(imp_rows, list)
# Query callout banner
banner_x = right_panel_x + 16
banner_w = panel_w - 32
banner_y = analytics_top + panel_hdr_h + 12
out.append(
f' <rect x="{banner_x}" y="{banner_y}" width="{banner_w}" height="32" '
f'rx="6" fill="{pal.impact_banner_bg}" stroke="{pal.impact_banner_stroke}" '
f'stroke-width="1"/>'
)
out.append(
f' <rect x="{banner_x + 7}" y="{banner_y + 6}" width="88" height="20" '
f'rx="4" fill="{pal.impact_badge_bg}"/>'
)
out.append(
f' <text x="{banner_x + 51}" y="{banner_y + 19.5}" text-anchor="middle" '
f'font-family="{_FONT_SANS}" font-size="9.2" font-weight="700" '
f'letter-spacing="0.4" fill="{pal.impact_badge_text}">1 SOURCE EDIT</text>'
)
trace_txt = (
f'{imp_doc} · {imp_kind}.{imp_field} = "{imp_val}" · uid: {imp_uid}'
)
out.append(
f' <text x="{banner_x + 106}" y="{banner_y + 20}" '
f'font-family="{_FONT_MONO}" font-size="10.5" font-weight="600" '
f'fill="{pal.text_primary}">{_esc(trace_txt)}</text>'
)
# Fan-out diagram: 1 Source Board Definition -> N Placed Module Instances
src_x = right_panel_x + 16
src_w = 186
src_h = 58
fan_top = banner_y + 44
src_y = fan_top + 12
src_cy = src_y + src_h / 2.0
out.append(
f' <rect x="{src_x}" y="{src_y}" width="{src_w}" height="{src_h}" '
f'rx="8" fill="{pal.subcard_bg}" stroke="{pal.leaf_accent}" '
f'stroke-width="1.3"/>'
)
out.append(
f' <text x="{src_x + 12}" y="{src_y + 22}" font-family="{_FONT_MONO}" '
f'font-size="11" font-weight="700" fill="{pal.text_primary}">'
f"{_esc(imp_proj)}</text>"
)
out.append(
f' <text x="{src_x + 12}" y="{src_y + 39}" font-family="{_FONT_SANS}" '
f'font-size="9.8" fill="{pal.text_muted}">Shared Board Definition</text>'
)
out.append(
f' <text x="{src_x + 12}" y="{src_y + 52}" font-family="{_FONT_MONO}" '
f'font-size="9.5" font-weight="600" fill="{pal.leaf_accent}">'
f"def:{_esc(imp_def)}…</text>"
)
out.append(
f' <circle cx="{src_x + src_w}" cy="{src_cy:.1f}" r="4.2" '
f'fill="{pal.leaf_accent}"/>'
)
dst_x = src_x + src_w + 68
dst_w = (right_panel_x + panel_w - 16) - dst_x
row_box_h = 34
row_box_gap = 12
shown_rows = imp_rows[:2]
for ridx, rinfo in enumerate(shown_rows):
ry_b = fan_top + ridx * (row_box_h + row_box_gap)
ry_mid = ry_b + row_box_h / 2.0
nidx_i = int(rinfo["system_net_index"])
nname_i = str(rinfo["system_net_name"])
ncol_i = net_colors.get(nidx_i, pal.net_power)
mdes_i = str(rinfo["designator"])
mtitle_i = str(rinfo["title"])
# Smooth branching Bezier arrow from source board to impacted instance
sx1 = float(src_x + src_w + 4)
sx2 = float(dst_x - 6)
smx = (sx1 + sx2) / 2.0
out.append(
f' <path d="M {sx1:.1f},{src_cy:.1f} C {smx:.1f},{src_cy:.1f} '
f'{smx:.1f},{ry_mid:.1f} {sx2:.1f},{ry_mid:.1f}" fill="none" '
f'stroke="{ncol_i}" stroke-width="2" stroke-linecap="round"/>'
)
out.append(
f' <polygon points="{dst_x - 1:.1f},{ry_mid:.1f} '
f'{dst_x - 8:.1f},{ry_mid - 4:.1f} {dst_x - 8:.1f},{ry_mid + 4:.1f}" '
f'fill="{ncol_i}"/>'
)
# Impacted module instance card
out.append(
f' <rect x="{dst_x}" y="{ry_b}" width="{dst_w}" height="{row_box_h}" '
f'rx="7" fill="{pal.subcard_bg}" stroke="{pal.subcard_stroke}" '
f'stroke-width="1.1"/>'
)
title_span_i = (
f'<tspan dx="6" font-family="{_FONT_SANS}" font-size="10.2" '
f'font-weight="400" fill="{pal.text_muted}">· {_esc(mtitle_i)}</tspan>'
if mtitle_i
else ""
)
out.append(
f' <text x="{dst_x + 12}" y="{ry_mid + 4:.1f}" '
f'font-family="{_FONT_MONO}" font-size="11.2" font-weight="700" '
f'fill="{pal.text_primary}">{_esc(mdes_i)}{title_span_i}</text>'
)
# Target system net chip on right edge of impacted row
nw_lbl = _estimate_text_w(nname_i, 10.0, mono=True)
nw = max(78.0, round(nw_lbl + 28.0))
nx = dst_x + dst_w - 8 - nw
nc_x = nx + (nw - (13.0 + nw_lbl)) / 2.0
out.append(
f' <rect x="{nx:.1f}" y="{ry_mid - 10:.1f}" width="{nw:.1f}" '
f'height="20" rx="10" fill="{pal.card_bg}" stroke="{ncol_i}" '
f'stroke-width="1.2"/>'
)
out.append(
f' <circle cx="{nc_x + 3.2:.1f}" cy="{ry_mid:.1f}" r="3.2" fill="{ncol_i}"/>'
)
out.append(
f' <text x="{nc_x + 11.5:.1f}" y="{ry_mid + 3.5:.1f}" '
f'font-family="{_FONT_MONO}" font-size="10" font-weight="700" '
f'fill="{pal.text_primary}">{_esc(nname_i)}</text>'
)
out.append(
f' <text x="{right_panel_x + 18}" y="{analytics_top + analytics_h - 12}" '
f'font-family="{_FONT_SANS}" font-size="10.2" fill="{pal.text_muted}">'
f"1 authored net label impacts {primary_impact['impact_count']} placed instances "
f"({total_repeated_fields} shared fields across {_esc(imp_proj)})</text>"
)
else:
out.append(
f' <text x="{right_panel_x + 18}" y="{analytics_top + 80}" '
f'font-family="{_FONT_SANS}" font-size="11.5" fill="{pal.text_muted}">'
f"No repeated-board field impacts detected in this system.</text>"
)
out.append("</g>")
# --- 8. Footer strip ---
footer_y = svg_h - 9
out.append(
f'<text x="36" y="{footer_y}" font-family="{_FONT_SANS}" font-size="9.5" '
f'fill="{pal.text_muted}">Rendered directly from AltiumMbsDoc, '
f"MbsSystemNetlist, and AltiumSystem C0 outputs</text>"
)
out.append(
f'<text x="{svg_w - 36}" y="{footer_y}" text-anchor="end" '
f'font-family="{_FONT_MONO}" font-size="9.5" fill="{pal.text_muted}">'
f"altium-monkey · multiboard_system_netlist_and_c0 ({theme})</text>"
)
out.append("</svg>\n")
return "\n".join(out)
def build_multiboard_example(output_dir: Path = OUTPUT_DIR) -> dict[str, object]:
if output_dir.exists():
shutil.rmtree(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
prjmbd_path = _build_demo_workspace(output_dir / "workspace")
# 1. Inspect the manifest and logical graph independently.
prjmbd = AltiumPrjMbd.from_file(prjmbd_path)
mbsdoc_path = prjmbd_path.with_name("DemoSystem.MbsDoc")
mbsdoc = AltiumMbsDoc.from_file(mbsdoc_path)
# 2. Resolve modules and build the cross-board system netlist.
mb_project = AltiumMultiboardProject.from_file(prjmbd_path)
resolutions = mb_project.resolve_modules()
netlist = mb_project.system_netlist()
netlist_json = netlist.to_json()
netlist_dto = load_system_netlist_json(netlist_json)
netlist_path = output_dir / "system_netlist_v1.json"
netlist_path.write_bytes(netlist_json)
# 3. Compile the full system C0 stack with AltiumSystem.
system = AltiumSystem.from_file(prjmbd_path)
graph_dto = system.structural_graph.to_dto()
comp_dto = system.compilation.to_dto()
root_def = next(
d for d in graph_dto.definitions if d.id == graph_dto.root_definition_ref
)
defs_by_id = {d.id: d for d in comp_dto.definitions}
# Trace cross-board impacts of an authored field on the repeated sensor board.
primary_impact, _ = _extract_repeated_field_impacts(mbsdoc, netlist, system)
repeated_impact: dict[str, object] | None = None
if primary_impact is not None:
repeated_impact = {
"system_net_id": primary_impact["system_net_id"],
"definition_id": primary_impact["definition_id"],
"impacted_modules": primary_impact["impacted_modules"],
"impact_count": primary_impact["impact_count"],
}
# 4. Render top-level Multi-Board System Topology SVGs in Paper and Dark themes.
topology_svg_path = output_dir / "system_topology.svg"
topology_dark_svg_path = output_dir / "system_topology_dark.svg"
topology_svg_path.write_text(
render_system_topology_svg(
mbsdoc,
netlist,
system,
theme="paper",
project_name=prjmbd_path.name,
mbsdoc_name=mbsdoc_path.name,
),
encoding="utf-8",
newline="\n",
)
topology_dark_svg_path.write_text(
render_system_topology_svg(
mbsdoc,
netlist,
system,
theme="dark",
project_name=prjmbd_path.name,
mbsdoc_name=mbsdoc_path.name,
),
encoding="utf-8",
newline="\n",
)
# Render instance-scoped SVGs for controller and first repeated sensor board.
ctrl_svg_path = output_dir / "controller_board.svg"
sensor_svg_path = output_dir / "sensor_instance_1.svg"
rendered_instances: list[dict[str, object]] = []
for inst in root_def.instances:
child_def = defs_by_id[inst.definition_ref]
if not child_def.schematic.pages:
continue
page_ref = child_def.schematic.pages[0].id
gfx = system.schematic_graphics(page_ref, instance_path=[inst.id])
entry = {
"instance_id": inst.id,
"definition_ref": inst.definition_ref,
"page_ref": page_ref,
"svg_bytes": len(gfx.svg),
}
if not ctrl_svg_path.exists() and "ctrl" in inst.definition_ref.lower():
ctrl_svg_path.write_bytes(gfx.svg)
entry["svg"] = _sample_relative(ctrl_svg_path)
elif not sensor_svg_path.exists() and "sensor" in inst.definition_ref.lower():
sensor_svg_path.write_bytes(gfx.svg)
entry["svg"] = _sample_relative(sensor_svg_path)
rendered_instances.append(entry)
# Fallback if definition_ref is opaque hash: write first two instances.
if not ctrl_svg_path.exists() and root_def.instances:
inst0 = root_def.instances[0]
p0 = defs_by_id[inst0.definition_ref].schematic.pages[0].id
ctrl_svg_path.write_bytes(
system.schematic_graphics(p0, instance_path=[inst0.id]).svg
)
if not sensor_svg_path.exists() and len(root_def.instances) >= 2:
inst1 = root_def.instances[1]
p1 = defs_by_id[inst1.definition_ref].schematic.pages[0].id
sensor_svg_path.write_bytes(
system.schematic_graphics(p1, instance_path=[inst1.id]).svg
)
manifest: dict[str, object] = {
"prjmbd_member_count": len(prjmbd.members),
"mbsdoc_connectivity_complete": mbsdoc.connectivity_complete,
"mbsdoc_diagnostic_count": len(mbsdoc.diagnostics),
"module_resolutions": [
{
"module_id": res.module_ref.full_id,
"status": res.status.value,
"rule": res.rule.value if res.rule is not None else None,
"member_path": res.member.normalized_path if res.member else None,
}
for res in resolutions
],
"system_netlist": {
"schema": netlist_dto.schema,
"connectivity_complete": netlist.connectivity_complete,
"diagnostic_count": len(netlist.diagnostics),
"system_net_count": len(netlist.nets),
"link_count": len(netlist.links),
"nets": [
{
"index": net.index,
"names": list(net.names),
"terminal_count": len(net.terminals),
"alias_count": len(net.aliases),
}
for net in netlist.nets
],
},
"altium_system": {
"definition_count": len(comp_dto.definitions),
"root_instance_count": len(root_def.instances),
"endpoint_count": len(system.endpoints),
"repeated_board_field_impact": repeated_impact,
"rendered_instances": rendered_instances,
},
"outputs": {
"system_topology_svg": _sample_relative(topology_svg_path),
"system_topology_dark_svg": _sample_relative(topology_dark_svg_path),
"controller_svg": _sample_relative(ctrl_svg_path),
"sensor_svg": _sample_relative(sensor_svg_path),
"system_netlist_json": _sample_relative(netlist_path),
},
}
manifest_path = output_dir / "multiboard_manifest.json"
manifest_path.write_text(
json.dumps(manifest, indent=2) + "\n",
encoding="utf-8",
newline="\n",
)
return manifest
def main() -> None:
manifest = build_multiboard_example()
nl = manifest["system_netlist"]
sys_info = manifest["altium_system"]
assert isinstance(nl, dict)
assert isinstance(sys_info, dict)
print(f"MbsDoc connectivity_complete: {manifest['mbsdoc_connectivity_complete']}")
print(
f"System netlist ({nl['schema']}): {nl['system_net_count']} system nets, "
f"{nl['link_count']} links, complete={nl['connectivity_complete']}"
)
print(
f"AltiumSystem: {sys_info['definition_count']} definitions, "
f"{sys_info['root_instance_count']} module instances, "
f"{sys_info['endpoint_count']} endpoints"
)
print(f"Repeated-board impact: {sys_info['repeated_board_field_impact']}")
if __name__ == "__main__":
main()