altium monkey v2026.11.26 · gobblerito
On This Page (5)

Examples Showcase / pcbdoc_inspect_layer_heights

Query PCB layer Z-heights, drill pairs, and rigid-flex regions

Query pcbdoc.layers() for substack thicknesses, outer surface layers, board regions, and drill pairs alongside board_stack_declaration_evidence() on rigid-flex and rigid boards.

pcbdocpcbdoclayer-contextlayer-stackrigid-flexz-height

Output Previews

rigid_flex_overview.svg
Open SVG
rigid_flex_overview.svg

Query a board's layer stack, Z-thicknesses, drill layer pairs, and rigid-flex board regions with pcbdoc.layers(), and inspect which stackup format saved the board via pcbdoc.board_stack_declaration_evidence().

What It Shows

  1. Querying pcbdoc.layers() (PcbLayerContext) on both a rigid-flex board (rigid_flex_topology_fixture.PcbDoc) and a 4-layer rigid board (RT_SUPER_C1.PCBdoc)
  2. Reading per-substack thickness and layer Z-heights in nanometres (ctx.envelope(sub.id), with z = 0 at the top surface) and outer copper, solder mask, and silkscreen layers (ctx.surface_layers(...))
  3. Listing board regions, bend lines, and drill layer pairs
  4. Resolving layer references without raising (ctx.resolve(...), ctx.by_token(...))
  5. Checking which stackup record format (V8, V9, or legacy) saved the board via pcbdoc.board_stack_declaration_evidence()

Run

From the repository root:

powershell
uv run python examples\pcbdoc_inspect_layer_heights\pcbdoc_inspect_layer_heights.py

Output

The script writes:

text
examples/pcbdoc_inspect_layer_heights/output/rigid_flex_overview.svg
examples/pcbdoc_inspect_layer_heights/output/layer_context_manifest.json

Source Code

examples/pcbdoc_inspect_layer_heights/pcbdoc_inspect_layer_heights.py
from __future__ import annotations

import json
import shutil
from pathlib import Path

from altium_monkey import AltiumPcbDoc, PcbLayerRef
from altium_monkey.altium_pcb_layer_context import PcbLayerFace

SAMPLE_DIR = Path(__file__).resolve().parent
EXAMPLES_DIR = SAMPLE_DIR.parent
RIGID_FLEX_PCBDOC = (
    EXAMPLES_DIR / "assets" / "pcbdoc" / "rigid_flex_topology_fixture.PcbDoc"
)
RIGID_PCBDOC = (
    EXAMPLES_DIR / "assets" / "projects" / "rt_super_c1" / "RT_SUPER_C1.PCBdoc"
)
OUTPUT_DIR = SAMPLE_DIR / "output"
SVG_PATH = OUTPUT_DIR / "rigid_flex_overview.svg"
MANIFEST_PATH = OUTPUT_DIR / "layer_context_manifest.json"


def _examples_relative(path: Path) -> str:
    return path.relative_to(EXAMPLES_DIR).as_posix()


def _sample_relative(path: Path) -> str:
    return path.relative_to(SAMPLE_DIR).as_posix()


def _inspect_board(path: Path) -> dict[str, object]:
    pcbdoc = AltiumPcbDoc.from_file(path)
    ctx = pcbdoc.layers()
    evidence = pcbdoc.board_stack_declaration_evidence()

    substacks_report: list[dict[str, object]] = []
    for sub in ctx.substacks:
        env = ctx.envelope(sub.id)
        top_surfaces = ctx.surface_layers(sub.id, PcbLayerFace.TOP)
        bot_surfaces = ctx.surface_layers(sub.id, PcbLayerFace.BOTTOM)
        substacks_report.append(
            {
                "id": sub.id,
                "name": sub.name,
                "kind": sub.kind.value,
                "is_primary": sub.id == ctx.primary,
                "layer_count": len(sub.layers),
                "total_thickness_nm": env.thickness_nm,
                "total_thickness_mm": round(env.thickness_nm / 1_000_000.0, 4),
                "envelope_complete": env.complete,
                "top_copper": (
                    ctx.layer(top_surfaces.copper).name
                    if top_surfaces.copper is not None
                    else None
                ),
                "bottom_copper": (
                    ctx.layer(bot_surfaces.copper).name
                    if bot_surfaces.copper is not None
                    else None
                ),
                "rows": [
                    {
                        "name": row.row.name,
                        "family": row.row.family.value,
                        "thickness_nm": row.row.thickness_nm,
                        "z_top_nm": row.z_top_nm,
                        "z_bottom_nm": row.z_bottom_nm,
                    }
                    for row in env.rows
                ],
            }
        )

    drill_pairs_report = [
        {
            "low": ctx.layer(pair.low).name,
            "high": ctx.layer(pair.high).name,
            "kind": pair.kind.name if pair.kind is not None else None,
            "backdrill": pair.backdrill,
            "inverted": pair.inverted,
        }
        for pair in ctx.drill_pairs
    ]

    regions_report = [
        {
            "name": reg.name,
            "substack_name": (
                ctx.substack(reg.substack).name if reg.substack is not None else None
            ),
            "bend_lines": reg.bend_lines,
            "locked_3d": reg.locked_3d,
        }
        for reg in ctx.board_regions
    ]

    # Demonstrate non-throwing PcbLayerLookup queries.
    top_lookup = ctx.resolve(PcbLayerRef.top())
    missing_lookup = ctx.by_token("MECHANICAL999")

    return {
        "pcbdoc": _examples_relative(path),
        "stack_evidence": {
            "status": evidence.status,
            "unresolved_reason": evidence.unresolved_reason,
            "present_declarations": [
                {"family": d.family, "source_key": d.source_key, "state": d.state}
                for d in evidence.declarations
                if d.state != "absent"
            ],
        },
        "layer_count": len(ctx.layers),
        "copper_layers": [
            {"name": layer.name, "token": layer.token, "kind": layer.kind.value}
            for layer in ctx.layers
            if layer.kind.is_copper
        ],
        "substacks": substacks_report,
        "board_regions": regions_report,
        "drill_pairs": drill_pairs_report,
        "lookup_examples": {
            "top_status": top_lookup.status.value,
            "top_name": (
                ctx.layer(top_lookup.found).name
                if top_lookup.found is not None
                else None
            ),
            "missing_status": missing_lookup.status.value,
        },
        "diagnostic_count": len(ctx.diagnostics),
    }


def build_layer_context_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)

    rigid_flex_info = _inspect_board(RIGID_FLEX_PCBDOC)
    rigid_info = _inspect_board(RIGID_PCBDOC)

    # Render an SVG overview of the rigid-flex board via Fab.
    rf_board = AltiumPcbDoc.from_file(RIGID_FLEX_PCBDOC)
    rf_fab = rf_board.fab()
    rf_keys = [row.key for row in rf_fab.view().layers()]
    overview_layers = tuple(
        k
        for k in ("PROFILE", "BOTTOM", "MID2", "MID1", "TOP", "TOPOVERLAY", "DRILLS")
        if k == "DRILLS" or k in rf_keys
    )
    svg_out = rf_fab.to_svg(
        scale=6.0,
        layers=overview_layers,
        layer_colours={
            "PROFILE": "#163822",
            "BOTTOM": "#2B6CB0",
            "MID2": "#D69E2E",
            "MID1": "#38A169",
            "TOP": "#C93B2B",
            "TOPOVERLAY": "#F7F4EA",
            "DRILLS": "#FFFFFF",
        },
        metadata=True,
    )
    svg_text = svg_out["board.svg"].text
    # Render the rigid-flex board profile as a stroked outline with a light tint
    # rather than a solid filled slab (the fixture has board regions and bend
    # lines, no copper traces).
    import xml.etree.ElementTree as ET

    ET.register_namespace("", "http://www.w3.org/2000/svg")
    root = ET.fromstring(svg_text)
    view_box = root.get("viewBox")
    if view_box:
        parts = [float(v) for v in view_box.split()]
        if len(parts) == 4:
            x, y, w, h = parts
            pad = max(w, h) * 0.02
            root.set(
                "viewBox",
                f"{x - pad:.6g} {y - pad:.6g} {w + 2 * pad:.6g} {h + 2 * pad:.6g}",
            )
    for elem in root.iter():
        if elem.tag.endswith("path") and elem.get("data-kind") == "profile_board":
            elem.set("fill", "rgba(47, 133, 90, 0.14)")
            elem.set("stroke", "#2F855A")
            elem.set("stroke-width", "2.5")
            elem.set("stroke-linejoin", "round")
    svg_path = output_dir / "rigid_flex_overview.svg"
    svg_path.write_text(ET.tostring(root, encoding="unicode") + "\n", encoding="utf-8")

    manifest: dict[str, object] = {
        "boards": {
            "rigid_flex_fixture": rigid_flex_info,
            "rt_super_c1": rigid_info,
        },
        "preview_svg": _sample_relative(svg_path),
    }

    manifest_path = output_dir / "layer_context_manifest.json"
    manifest_path.write_text(
        json.dumps(manifest, indent=2) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    return manifest


def main() -> None:
    manifest = build_layer_context_example()
    boards = manifest["boards"]
    assert isinstance(boards, dict)
    for label, info in boards.items():
        print(
            f"[{label}] evidence={info['stack_evidence']['status']} "
            f"({len(info['stack_evidence']['present_declarations'])} present) "
            f"layers={info['layer_count']} substacks={len(info['substacks'])} "
            f"regions={len(info['board_regions'])} drill_pairs={len(info['drill_pairs'])}"
        )
        for sub in info["substacks"]:
            print(
                f"  substack {sub['name']!r} ({sub['kind']}): "
                f"{sub['total_thickness_mm']} mm ({sub['total_thickness_nm']} nm), "
                f"top={sub['top_copper']}, bottom={sub['bottom_copper']}"
            )
    print(f"Wrote SVG preview: {manifest['preview_svg']}")


if __name__ == "__main__":
    main()
altium-monkey v2026.11.26 · gobblerito·Docs updated 2026.11.29 17:55 UTC (0665053)