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

PcbDoc

AltiumPcbDoc is the public container for PCB documents. The current release supports parsing, extraction, SVG rendering, statistics, high-level helper-oriented authoring, and footprint insertion.

Use it when you need to:

  1. parse .PcbDoc files
  2. inspect board geometry, layers, drills, nets, and resolved components
  3. render PCB layers to SVG
  4. extract embedded fonts, 3D models, or footprints
  5. add board outlines, nets, PCB primitives, routes, pads, vias, and regions
  6. place footprints from .PcbLib
  7. add component bodies and embedded 3D model payloads
  8. inspect and author user-defined PCB unions
  9. inspect and author embedded board arrays for PCB panelization
  10. inventory extractable footprints and embedded payloads before selecting one

Loading And Validation Boundary

AltiumPcbDoc.from_file(...) and from_bytes(...) parse the requested board without building an additional whole-document record-state snapshot. This keeps ordinary inspection, rendering, and authoring proportional to the work the caller requested.

Loading proves that the supported document structures can be parsed; it does not certify that the source is a compiled, electrically valid, or otherwise known-good Altium design. Manufacturing and release workflows should begin from a caller-selected saved input and apply the validation required by their specific output.

Object Model

PcbDoc does not yet use the generic ObjectCollection API used by SchDoc and SchLib. SchDoc/SchLib typed views are live filtered query views with explicit structural APIs such as add_object(...), insert_object(...), and remove_object(...). PcbDoc instead exposes parsed records as typed lists such as pcbdoc.tracks, pcbdoc.arcs, pcbdoc.pads, pcbdoc.vias, pcbdoc.regions, pcbdoc.texts, and pcbdoc.components.

For authoring, prefer high-level helpers:

python
pcbdoc.add_track((1000, 1000), (2000, 1000), width_mils=8, net="GND")
pcbdoc.add_pad(
    designator="1",
    position_mils=(1500, 1500),
    width_mils=60,
    height_mils=80,
)
pcbdoc.add_via(position_mils=(1750, 1500), diameter_mils=24, hole_size_mils=12)
pcbdoc.save("updated.PcbDoc")

Direct edits to typed lists are advanced usage. They can be appropriate for read-preserving mutation, but callers are responsible for keeping indexes, ownership, stream order, and related binary state valid.

When a supported typed list is part of the document writer's owned state, save(...) writes its counted section atomically: the current record count in Header and the serialized records in Data are regenerated together. This also applies when removing the final record, where both the zero count and an empty Data stream must replace the source streams. Unsupported and otherwise unowned sections remain lossless passthrough. A source-backed save may still regenerate an owned section that the caller did not edit; streams outside the selected regenerated set remain byte-identical.

This count synchronization makes narrow direct-list insertion and deletion safe from stale-header corruption; it is not a generic PCB deletion or relationship-management API. Removing a component, pad, model, or another record can require coordinated updates to owner indexes, companion sections, or references. Prefer a high-level helper when one exists, and reopen advanced direct-list output in Altium Designer as an interoperability check.

User Unions

pcbdoc.union_name_records exposes the decoded union-name catalog. pcbdoc.smart_unions exposes read-only typed smart-union records. pcbdoc.user_unions returns named user-defined unions with member references.

Use create_user_union(...), rename_user_union(...), add_user_union_member(...), remove_user_union_member(...), and delete_user_union(...) for explicit user-union authoring. Typed smart unions, including drill tables, layer-stack tables, via stitching, via shielding, OLE/object unions, rectangles, and length tuning, are read-only.

create_user_union(...) auto-allocates a native union id by default. Use the optional union_index=... argument only when recreating an existing PcbDoc and preserving deterministic native union ids matters.

Passing a component to create_user_union(...) includes the component record and its authorable child primitives. Shape-based region membership is kept in sync with the paired standard region record when that pair exists.

PCB components are available through pcbdoc.components. Each AltiumPcbComponent row exposes the resolved designator, footprint, placement, rotation, side, component kind, and parsed PcbDoc component parameters. Use this surface when a PCB-backed BOM or placement list should reflect what is actually placed on the board.

Component source metadata is also exposed for boards produced from schematic compile/ECO flows. Use fields such as channel_offset, source_designator, source_unique_id_segments, source_hierarchy_segments, source_component_library, source_lib_reference, and footprint_description when repeated-sheet, channel, or library provenance is needed. Designator/comment autoposition uses the PcbTextAutoposition enum through name_auto_position and comment_auto_position; absent fields remain None rather than being invented by the writer.

PCB classes are available through pcbdoc.net_classes. The historical AltiumPcbNetClass name is retained for compatibility, but Classes6/Data also stores component classes, pad classes, layer classes, polygon classes, from-to classes, and differential-pair classes. A differential-pair class has kind == PcbNetClassKind.DIFF_PAIR; its members are differential-pair names such as TX0 or RX0, not the positive/negative net names.

Concrete DifferentialPairs6/Data pair objects are available through pcbdoc.differential_pairs. Each AltiumPcbDifferentialPair exposes name, positive_net_name, negative_net_name, gather_control, and unique_id. Use pcbdoc.get_differential_pair(name), pcbdoc.differential_pairs_by_net_name, and pcbdoc.differential_pair_classes for common lookup paths.

python
pair = pcbdoc.get_differential_pair("USB_D")
if pair is not None:
    print(pair.positive_net_name, pair.negative_net_name)

New pair objects can be authored explicitly:

python
pcbdoc.add_differential_pair(
    name="USB_D",
    positive_net_name="USB_D_P",
    negative_net_name="USB_D_N",
)
pcbdoc.save("updated.PcbDoc")

gather_control is Altium's raw pair-level gather-control flag used around uncoupled differential-pair fanout handling. It is preserved and writable, but callers should keep the raw boolean meaning until their workflow has been verified in Altium Designer.

Units

Public PcbDoc authoring helpers use explicit *_mils parameter names. PCB workflows are often metric, so convert metric source data before calling these methods until metric helper functions are added.

Low-level PCB record fields may expose Altium internal integer units. Prefer public helper methods for authored geometry.

Layer Arguments

PcbDoc primitive authoring helpers keep PcbLayer as the legacy enum and use PcbLayerRef for V7-aware layer identity. Arguments named layer, layer_start, and layer_end accept documented PcbLayer values and supported layer-name tokens such as "Top Layer".

PcbLayer mirrors Altium's compact legacy/TV6 enum. It includes Top, Mid1 through Mid30, Bottom, and Mechanical 1 through Mechanical 16 only; values 73, 74, and 75 are Drill Drawing, Multi-Layer, and Connect. Do not pass serialized V7 saved layer ids such as 16908305 for Mechanical 17 or 16777248 for Mid31 as layer= unless a method explicitly documents a V7 override.

For extended mechanical and AD 26.8 128-signal-layer workflows, pass PcbLayerRef values or documented semantic tokens. Track, arc, fill, text, region, and component-body helpers can author ordinary numbered mechanical layers through Mechanical53. Track, arc, fill, text, and region helpers can author V7-only signal refs such as PcbLayerRef.mid_layer(126) when a matching enabled layer stack has been attached with set_layer_stack_document(...), normally from .stackupx.

See PCB Layers & Layer Stacks for the complete layer ID systems, stackup models, and authoring matrix (including the still-gated pad/via and PcbLib signal-layer cases).

Pads

AltiumPcbDoc.add_pad(...) accepts hole_shape="round", "square", or "slot" through PadHoleShape. Square holes require a positive drill size. Slotted holes require slot_length_mils.

add_pad(...) accepts fractional corner_radius_percent values for rounded-rectangle pads on the top or bottom layer, matching Altium's dual-lane storage (the pad record carries the legacy rounded integer percent per layer, while the board CornerRadiusChamfer stream stores exact fractional percents). Read values back with pad.corner_radius_percentage, pad.corner_radius_percent_exact, pad.exact_corner_radius_percent_by_layer, or resolve the effective radius with pad.corner_radius_mils_on_layer(layer). Whole-number percents write only the legacy integer lane so existing output is unchanged; round-tripped documents preserve both lanes.

Parsed component pads expose their stored removed-copper-land state through pad.removed_copper_layers and pad.is_copper_land_removed(layer). Change one legacy Top/Mid1..Mid30/Bottom state explicitly with:

python
pad.set_copper_land_removed(PcbLayer.MID1, True)
pcbdoc.save("updated.PcbDoc")

The setter requires an actual legacy copper PcbLayer and a bool. Saving a valid record preserves its per-layer geometry and full-stack data while updating the map. Ambiguous, partial, noncanonical, or malformed source maps reject mutation rather than guessing. Use pad.has_stored_copper_land_on_layer(layer) when you need the structural stored-land applicability; it does not alter geometry or replace rendering or manufacturing policy. Pad and via removed-layer storage are independent. For an all-false map-only legacy pad, save and reopen after the first removal before applying another layer removal.

AltiumPcbDoc.add_custom_pad(...) authors a board custom pad as an anchor pad plus native custom-shape region records. outline_points_mils and hole_points_mils describe the primary layer body and holes. Pass outline_vertices for line/arc segment semantics, and use PcbCustomPadLayerShapeSpec entries in layer_shapes for additional layer-specific bodies and holes that share the same anchor pad. Custom-pad anchors can also carry ordinary pad drill fields such as hole_size_mils, plated, hole_shape, and slot/tolerance parameters.

AltiumPcbDoc.add_region(...) also accepts outline_vertices for line/arc-preserving shape-based-region authoring. Region and PcbDoc custom-pad body helpers share the same outline normalization path; custom pads add the anchor pad and native CustomShapes/* attachment records around that region body.

Keepout Restrictions

Object-specific PCB keepouts preserve Altium's raw keepout_restrictions integer. Use PcbKeepoutRestriction, decode_pcb_keepout_restrictions(...), encode_pcb_keepout_restrictions(...), pcb_keepout_restriction_names(...), and pcb_keepout_restriction_unknown_bits(...) when you need named access to the confirmed mask bits for via, track, copper, SMD pad, and through-hole pad restrictions. Keep the raw integer as the stored field for round-trip preservation.

Dimensions

AltiumPcbDoc.add_dimension_record(...) and PcbDocBuilder.add_dimension_record(...) append raw native Dimensions6/Data records from record_type, record_leader, and payload bytes. This is a preservation/transcode API for imported dimensions, not a high-level dimension construction API or full object-oriented dimension model.

Text & Barcodes

AltiumPcbDoc.add_text(...) accepts font_kind="stroke", "truetype", or "barcode" (PcbTextKind.STROKE, TRUETYPE, BARCODE). Stroke text accepts stroke_font_type="default", "sans-serif", or "serif" (native ids 1, 2, and 3). This is the same stroke-font vocabulary used by PcbLib footprint text helpers.

Barcodes (1D & 2D)

AltiumPcbDoc.add_text(...) (and AltiumPcbFootprint.add_text(...) / PcbDocBuilder.add_text(...)) supports all four Altium PCB barcode symbologies via PcbBarcodeKind and PcbBarcodeRenderMode:

SymbologyTypeNotes
CODE_39 (0)1DISO/IEC 16388 full-ASCII ('H'/'h' fixed, AOD-011)
CODE_128 (1)1DArbitrary-length ASCII with Code A/B switching (non-ASCII refused, AOD-012)
QR_CODE (2)2DECC Level M, versions 1–40, automatic numeric, alphanumeric, or byte encoding
DATA_MATRIX (3)2DECC 200, square sizes 10×10..144×144, ASCII encodation

Key barcode options and defaults on add_text(..., font_kind=PcbTextKind.BARCODE):

python
from altium_monkey import (
    AltiumPcbDoc,
    PcbBarcodeKind,
    PcbBarcodeRenderMode,
    PcbLayer,
    PcbTextKind,
)

pcbdoc = AltiumPcbDoc()
pcbdoc.add_text(
    text="SN-2026-0042",
    position_mils=(500.0, 500.0),
    height_mils=60.0,
    layer=PcbLayer.TOP_OVERLAY,
    font_kind=PcbTextKind.BARCODE,
    barcode_kind=PcbBarcodeKind.QR_CODE,
    barcode_render_mode=PcbBarcodeRenderMode.BY_MIN_WIDTH,
    barcode_min_width_mils=12.0,
    barcode_show_text=True,
    barcode_inverted=False,
)

Parsed barcode records expose barcode_kind, barcode_render_mode, barcode_full_width_mils, barcode_full_height_mils, barcode_min_width_mils, barcode_inverted, barcode_show_text, and barcode_font_name on AltiumPcbText. All four symbologies render natively in Fab outputs (Gerber, IPC-2581, and SVG); see pcbdoc_barcodes_1d_and_2d.

In the fabrication outputs, TrueType text, barcodes and keepout Text differ from Altium's in a few places. The Altium output differences register lists what differs and why (TrueType outlines AOD-009, font aliases AOD-010, embedded font collection faces AOD-034, fonts the machine lacks AOD-049, Code 39 AOD-011, Code 128 AOD-012, keepout Text AOD-042; AOD-033 and AOD-048 record where the font choice matches Altium's). The Text & Font Rendering page explains how Stroke, TrueType, and Barcode text are resolved and flattened across platforms.

Special strings in text

A .Name in a PCB text draws the value of the special string or project parameter Name (.PCB_PART_NUMBER, .Layer_Name, .Hole_Count; names match without case). substitute_pcb_special_strings(text, params, multiline=...) and the Fab views draw them as Altium 26.10's Gerber and IPC-2581 outputs do:

Embedded 3D Models

AltiumPcbDoc.add_embedded_3d_model(...) can embed a STEP payload and create the matching component-body projection. When callers omit explicit placement geometry, STEP-derived rectangular bounds are inferred through wn-geometer.

If STEP bounds cannot be computed on the current host, the helper can fall back to an axis-aligned rectangle around available SMD/through-hole pads. That fallback is a recovery projection for authoring a usable board body; it is not a geometry-equivalent STEP import.

Use explicit bounds_mils, projection_outline_mils, and overall_height_mils when the package projection or height is known.

Embedded Asset Inventory

AltiumPcbDoc.embedded_asset_inventory(include_hashes=False) lists embedded 3D models and embedded TrueType fonts without writing files. The focused inventory returns typed model/font summaries and can emit the altium_monkey.pcb.embedded_assets.a0 JSON shape through to_dict().

Use direct indexed payload helpers when a consumer wants one embedded payload:

python
inventory = pcbdoc.embedded_asset_inventory(include_hashes=True)
model = next((item for item in inventory.models if item.payload_available), None)
if model is None:
    raise RuntimeError("no available embedded model payload found")
payload = pcbdoc.get_embedded_model_payload(model.index)

Corrupt supported payloads remain visible in the inventory with payload_available=False, no hash, and no decompressed size. Selecting that payload raises a clear decompression error. For the focused JSON contract, see Asset & Library Extraction.

Extractable Assets

AltiumPcbDoc.asset_inventory(include_hashes=False) lists selectable board assets, including embedded 3D models, embedded fonts, and footprints extracted from placed components. Use the returned AltiumAssetRef with extract_asset(...) to extract exactly one payload or one footprint.

python
inventory = pcbdoc.asset_inventory(include_hashes=True)
footprint = next(
    (item for item in inventory.by_kind("pcb_footprint") if item.can_extract),
    None,
)
if footprint is None:
    raise RuntimeError("no extractable footprint found")
selected = pcbdoc.extract_asset(footprint.ref)
selected.pcblib.save("selected_footprint.PcbLib")

Embedded payload selections return payload bytes and a suggested extraction_filename. Footprint selections return a single-footprint AltiumPcbLib. The JSON-ready inventory uses altium_monkey.extractable_assets.a0. For the shared reference and JSON contract, see Asset & Library Extraction.

Fabrication & Manufacturing Outputs

Use board.fab(...) to normalize a .PcbDoc once through Altium's rules and emit Gerber X2/X1 (to_gerbers), NC Drill (to_nc_drill), IPC-2581B (to_ipc2581), PCB SVG (to_svg, to_layer_svgs), Pick and Place CSV (to_pnp), and PCB BOM CSV (to_bom), or query the resolved geometry directly via fab.view(). Every to_* method is also available as a one-call shortcut directly on AltiumPcbDoc and returns an in-memory FabOutput.

python
board = AltiumPcbDoc.from_file("board.PcbDoc")
fab = board.fab()
fab.to_gerbers().write("out/gerber")
fab.to_nc_drill().write("out/gerber")
fab.to_ipc2581().write("out/ipc2581")

See the dedicated Fab & FabView guide for the full workflow, options, layer keys, custom FabView queries, and Altium output differences.

SVG Rendering

AltiumPcbDoc.to_svg(**options) and to_layer_svgs(**options) take the board's inputs (ContextOptions; project parameters as parameters) and the Fab SVG options (SvgOptions: layers, layer_colours, scale, mirror, clip_to_outline, clip_holes, metadata, hidden_component_texts, degenerate_strokes, annotations) and return a FabOutput: to_svg gives board.svg, to_layer_svgs one <key>.svg per layer key of the board's Fab view and DRILLS.svg. layers=["PROFILE"] draws the board outline alone.

python
board = AltiumPcbDoc.from_file("board.PcbDoc")
svg = board.to_svg(scale=10.0, metadata=True)["board.svg"].text
layers = board.to_layer_svgs(layers=("TOP", "DRILLS"))

Layer identifiers remain token-based for the current public SVG contract. PcbLayer.to_json_name() returns legacy tokens such as TOP, BOTTOM, and TOPOVERLAY; PcbLayerRef covers V7 tokens such as MECHANICAL33 and MID126. PcbLayer.to_display_name() returns default user-facing labels such as Top Layer and Top Overlay. For parsed PcbDoc files, use pcbdoc.layers() (PcbLayerContext) when actual board-specific layer names, substacks, regions, or physical envelopes are required; Fab SVG emits data-key and data-layer (Altium's resolved display name for the layer). Supported simple primitives on Mechanical17 through Mechanical53 and StackUpX-backed Mid31 through Mid126 render/select by their FabView keys and do not invent legacy layer ids.

Layer Stack Inspection

For a complete map of Altium's layer ID schemes, PcbLayerContext, V8/V9 storage precedence, .stackup/.stackupx rules, and authoring gotchas, see PCB Layers & Layer Stacks.

AltiumLayerStackDocument is the source-aware layer-stack model for PcbDoc inspection and canonical empty-board stack synthesis. It preserves native stack source evidence while exposing deterministic objects for physical stacks, registry entries, substacks, board regions, bend lines, and layer pairs.

Use AltiumLayerStackDocument.from_pcbdoc(...) for read-only inspection and AltiumLayerStackDocument.canonical_empty() plus to_canonical_empty_board_data() when creating a canonical empty PcbDoc through PcbDocBuilder.

For new rigid-board documents, AltiumLayerStackDocument.from_rigid_stack(...) accepts typed AltiumRigidCopperLayerSpec and AltiumRigidDielectricLayerSpec rows for copper names/thicknesses and dielectric names, thicknesses, material, dielectric constant, dielectric type, and loss tangent. Emit the stack into a new builder with PcbDocBuilder.set_layer_stack_document(...).

Use AltiumLayerStackDocument.from_rigid_layer_rows(...) when the physical row sequence matters. It accepts ordered AltiumRigidStackRowSpec rows, or existing parsed AltiumStackLayer rows, and preserves solder-mask, overlay, surface-finish, adjacent dielectric/prepreg/core rows, StackupX type IDs, StackupX properties, layer-pair spans, typed stackup settings, and impedance profiles/transmission lines for rigid new-board authoring. This is the programmatic equivalent of starting from a rigid .stackup or .stackupx file, but keeps the stack definition in Python code.

Use the semantic row constructors for normal authoring. They fill the native Layer Stack Manager type IDs and StackupX property type names internally. Use AltiumStackupSettings for stackup-level electrical settings such as roughness model, copper resistance, via plating thickness, and temperatures:

python
from altium_monkey import (
    AltiumComponentPlacement,
    AltiumCopperMaterialSpec,
    AltiumDielectricMaterialSpec,
    AltiumLayerPair,
    AltiumLayerStackDocument,
    AltiumRigidStackRowSpec,
    AltiumStackupRoughnessModel,
    AltiumStackupSettings,
    PcbDocBuilder,
)

np_155f_1080 = AltiumDielectricMaterialSpec(
    name="NP-155F",
    construction="1080",
    resin="67%",
    frequency="1GHz",
    dielectric_constant=3.91,
    loss_tangent=0.02,
    glass_transition_temperature="150C",
    manufacturer="Nan Ya Plastics",
)
copper_foil = AltiumCopperMaterialSpec(
    weight="1oz",
    process="ED",
    manufacturer="Altium Designer",
    description="Copper Foil",
)

stack = AltiumLayerStackDocument.from_rigid_layer_rows(
    name="vendor-8-layer",
    rows=(
        AltiumRigidStackRowSpec.overlay("Top Overlay"),
        AltiumRigidStackRowSpec.solder_mask(
            "Top Solder",
            thickness_mils=0.6,
            material="Solder Resist",
            dielectric_constant=3.8,
        ),
        AltiumRigidStackRowSpec.copper(
            "Top Layer",
            thickness_mm=0.035,
            component_placement=AltiumComponentPlacement.BODY_UP,
            material=copper_foil,
        ),
        AltiumRigidStackRowSpec.prepreg(
            "Dielectric 1",
            thickness_mm=0.069,
            material=np_155f_1080,
        ),
        AltiumRigidStackRowSpec.copper(
            "Inner Layer 1",
            thickness_mm=0.03,
            component_placement=AltiumComponentPlacement.NONE,
            material=copper_foil,
        ),
        # Add the remaining rows in the exact physical sequence.
    ),
    layer_pairs=(AltiumLayerPair(0, "TOP", "BOTTOM"),),
    stackup_settings=AltiumStackupSettings(
        roughness_model=AltiumStackupRoughnessModel.MODIFIED_HAMMERSTAD,
        roughness_factor_model_sr="1um",
        roughness_factor_model_rf="2%",
        via_plating_thickness="18um",
    ),
)
builder = PcbDocBuilder()
builder.set_layer_stack_document(stack)
builder.save("vendor_stack.PcbDoc")
stack.to_stackup().write("vendor_stack.stackup")
stack.to_stackupx().write("vendor_stack.stackupx")

The direct AltiumRigidStackRowSpec(...) constructor and stackupx_properties tuples are still available as advanced escape hatches for preserving unsupported source metadata, but they should not be needed for ordinary rigid stack creation.

See pcbdoc_create_jlcpcb_rigid_stack for a complete JLCPCB eight-layer stack authored entirely from Python row and material constants.

For simple rigid boards, exported .stackup and .stackupx files can also be used as new-board inputs:

python
stack = AltiumLayerStackDocument.from_stackupx("source.stackupx")
builder = PcbDocBuilder()
builder.set_layer_stack_document(stack)
builder.save("from_stackupx.PcbDoc")

Use the same pattern with from_stackup(...) for .stackup text exports. The writer regenerates native PcbDoc stack rows from the imported semantic model; reopen the generated PcbDoc with AltiumPcbDoc and AltiumLayerStackDocument to verify readback. See pcbdoc_create_from_stackup_files for a complete .stackup and .stackupx input example.

For new rigid-flex documents, construct a typed AltiumLayerStackDocument with physical stack rows, AltiumStackSubstack definitions, AltiumStackRegion geometry, optional AltiumStackBendLine entries, and optional AltiumStackBranch topology. Emit it with PcbDocBuilder.set_layer_stack_document(...), save the PcbDoc, and re-open it with AltiumPcbDoc plus AltiumLayerStackDocument to verify the generated native topology.

For rigid-flex and multi-stack inspection, use native ids for joins. A substack's source_stackup_ref is the stable id; board regions point back to it through layerstack_id. Altium stores the same GUIDs with mixed spelling across sources, so helpers such as substack_by_source_ref(...), board_regions_for_layerstack_id(...), layers_for_substack(...), layers_for_board_region(...), and branches_for_stack_ref(...) accept refs with or without braces. Treat substack and region names as display labels that may collide or be renamed.

Use pcbdoc.layers() (PcbLayerContext) as the canonical read-only view for layer names, enabled-layer checks, regions, faces, mounts, drill pairs, and nanometre Z envelopes (the older ResolvedLayerStack helper is deprecated). Use AltiumLayerStackDocument whenever you need to write stack data for a new board, export .stackup/.stackupx, or inspect source-aware topology, branch, or bend-line evidence, and use pcbdoc.board_stack_declaration_evidence() to audit raw Board6 stack keys without inflating embedded XML. See pcbdoc_flex_topology_report and PCB Layers & Layer Stacks.

Arbitrary in-place layer-stack editing of already-loaded .PcbDoc files is not yet part of the public writer contract; use PcbDocBuilder.set_layer_stack_document(...) when synthesizing new rigid or rigid-flex boards, or set_layer_stack_template(...) for the established two-layer/four-layer template shortcut.

Mechanical Layer Kinds

Mechanical layer display names, enabled flags, and mirror pairs are stored in the Board6 layer registry. Semantic layer roles are stored separately in LayerKindMapping/Data and are exposed through MechanicalLayerKind. Authored output also synchronizes Altium's Board6 MECHKIND layer-table/cache fields so the assignments are visible in Altium's layer manager.

Use mechanical_layer_kinds to inspect the parsed mapping, and use get_mechanical_layer_kind(...) / set_mechanical_layer_kind(...) for common lookup and authoring:

python
from altium_monkey import AltiumPcbDoc, MechanicalLayerKind

pcbdoc = AltiumPcbDoc()
pcbdoc.set_mechanical_layer("MECHANICAL13", name="3D Bodies", enabled=True)
pcbdoc.set_mechanical_layer_kind("MECHANICAL13", MechanicalLayerKind.BODY_3D_TOP)
pcbdoc.save("mechanical_kind.PcbDoc")

Mechanical layers 1 through 16 use classic PCB layer ids (57..72) in the mapping. Mechanical layers 17 through 32 use Altium's runtime TV7_Layer mechanical encoding (0x04000000 | mechanical_number) — distinct from both the legacy PcbLayer enum and serialized V7 saved-layer ids (0x01020000 + n).

Via Protection, Tenting, And Delay

AltiumPcbDoc.add_via(...) can author ordinary through vias and promoted via metadata:

python
from altium_monkey import (
    AltiumPcbDoc,
    PcbIpc4761ViaType,
    PcbViaStructureFeatureSide,
    PcbViaStructureFeatureType,
)

pcbdoc = AltiumPcbDoc()
via = pcbdoc.add_via(
    position_mils=(1000, 1000),
    diameter_mils=24,
    hole_size_mils=10,
    ipc4761_via_type=PcbIpc4761ViaType.TYPE_7_FILLING_AND_CAPPING,
    propagation_delay_ps=12.5,
    is_tent_top=True,
    is_tent_bottom=True,
)
via.set_ipc4761_feature_side(
    PcbViaStructureFeatureType.FILLING,
    PcbViaStructureFeatureSide.BOTH,
)
via.set_ipc4761_feature_material(PcbViaStructureFeatureType.FILLING, "EPOXY")

Parsed vias are available through pcbdoc.vias. Each AltiumPcbVia exposes ipc4761_via_type, via_structure, propagation_delay_ps, ordinary top/bottom tenting flags, fabrication testpoint flags, and assembly testpoint flags. The feature-table helpers get_ipc4761_feature(...), set_ipc4761_feature(...), set_ipc4761_feature_side(...), and set_ipc4761_feature_material(...) mirror the IPC-4761 feature rows shown by Altium Designer.

The public propagation-delay unit is picoseconds. Altium stores this field as a seconds value in the underlying VIA payload, but callers should use propagation_delay_ps.

Solder-mask expansion fields on a via are low-level record fields in Altium internal units. They remain available for careful mutation and round-trip preservation; use the via examples below when authoring tenting or manual mask expansion for Altium Designer review.

Hole Tolerances

Pads and vias expose Altium's drill-hole tolerance fields as positive and negative magnitudes. Use the *_mils helpers for normal public code:

python
pad = pcbdoc.add_pad(
    designator="1",
    position_mils=(1000, 1000),
    width_mils=150,
    height_mils=150,
    layer=PcbLayer.MULTI_LAYER,
    hole_size_mils=50,
    hole_positive_tolerance_mils=3.0,
    hole_negative_tolerance_mils=2.0,
)

via = pcbdoc.add_via(
    position_mils=(1400, 1000),
    diameter_mils=28,
    hole_size_mils=12,
    hole_positive_tolerance_mils=1.5,
    hole_negative_tolerance_mils=0.5,
)

For mutation, assign pad.hole_positive_tolerance_mils, pad.hole_negative_tolerance_mils, via.hole_positive_tolerance_mils, or via.hole_negative_tolerance_mils. A value of None represents Altium's N/A state; the raw fields remain available as internal-unit integers for advanced round-trip work.

Embedded Board Arrays (Panelization)

Altium panel .PcbDoc files store child-board repeats and viewports in EmbeddedBoards6. AltiumPcbDoc parses the full section on load into pcbdoc.embedded_boards (tuple[AltiumPcbEmbeddedBoard, ...]) and pcbdoc.embedded_board_section_diagnostics.

To inspect embedded board records as typed values without raising on partial or unusual fields, use interpret_embedded_board(...) or interpret_embedded_boards(...) from altium_monkey.altium_pcb_embedded_board:

python
from altium_monkey import AltiumPcbDoc
from altium_monkey.altium_pcb_embedded_board import (
    PcbEmbeddedBoardKind,
    PcbEmbeddedBoardOriginMode,
    interpret_embedded_boards,
)

panel = AltiumPcbDoc.from_file("panel.PcbDoc")
for src in interpret_embedded_boards(panel.embedded_boards):
    if src.kind == PcbEmbeddedBoardKind.ARRAY:
        print(
            src.document_path,
            f"{src.rows}x{src.columns}",
            f"rot={src.rotation_degrees} mirror={src.mirror}",
            f"origin={src.origin_anchor}",
        )

Authoring Embedded Board Arrays

Append a new embedded board array to an AltiumPcbDoc with pcbdoc.add_embedded_board_array(...) (positions and pitches are in mils):

python
from altium_monkey import AltiumPcbDoc, PcbLayer
from altium_monkey.altium_pcb_embedded_board import PcbEmbeddedBoardOriginMode

child = AltiumPcbDoc.from_file("child.PcbDoc")
panel = AltiumPcbDoc()
panel.add_embedded_board_array(
    child,
    position_mils=(500.0, 500.0),
    rows=2,
    columns=3,
    row_pitch_mils=2200.0,
    column_pitch_mils=3200.0,
    rotation_degrees=0.0,
    mirror=False,
    origin_mode=PcbEmbeddedBoardOriginMode.BOTTOM_LEFT,
    layer=PcbLayer.TOP,
    untransmitted_layers=(PcbLayer.MECHANICAL_15,),
)
panel.save("panel.PcbDoc")

Guarantees & Stability Boundaries

Examples

Start with:

  1. hello_pcbdoc
  2. pcbdoc_stats
  3. pcbdoc_inspect_layer_stack
  4. pcbdoc_create_layer_stack
  5. pcbdoc_create_mechanical_layer_kinds
  6. pcbdoc_create_custom_rigid_stack
  7. pcbdoc_create_jlcpcb_rigid_stack
  8. pcbdoc_create_impedance_rigid_stack
  9. pcbdoc_create_flex_stiffener
  10. pcbdoc_create_rigid_flex_split_lines
  11. pcbdoc_create_flex_in_cutout
  12. pcbdoc_create_rigid_flex_branch
  13. pcbdoc_create_rigid_flex_branch_intrusion
  14. pcbdoc_create_rigid_flex_two_branch
  15. pcbdoc_create_rigid_flex_impedance_backdrill
  16. pcbdoc_create_cavity_placements
  17. pcbdoc_create_rigid_flex_multibranch
  18. pcbdoc_flex_topology_report
  19. pcbdoc_bom
  20. pcbdoc_pick_n_place
  21. pcbdoc_svg
  22. pcbdoc_netclass_svg
  23. pcbdoc_add_track
  24. pcbdoc_user_union
  25. pcbdoc_add_arc
  26. pcbdoc_add_pad
  27. pcbdoc_add_hole_tolerances
  28. pcbdoc_add_via_ipc4761_matrix
  29. pcbdoc_add_differential_pairs
  30. pcbdoc_diff_pair_report
  31. pcbdoc_mutate_via_ipc4761
  32. pcbdoc_add_text
  33. pcbdoc_add_filled_region
  34. pcbdoc_add_custom_pad_region_outline
  35. pcbdoc_insert_nets_route
  36. pcbdoc_insert_footprint_from_pcblib
  37. pcbdoc_add_free_3d_extruded
  38. pcbdoc_add_free_3d_step
  39. pcbdoc_extract_pcblib
  40. pcbdoc_extract_embedded_3d_models
  41. pcbdoc_extract_embedded_fonts
  42. embedded_asset_inventory
  43. pcbdoc_128_signal_layers
  44. pcbdoc_extended_mechanical_layers
  45. pcbdoc_inspect_layer_heights
  46. pcbdoc_barcodes_1d_and_2d
  47. pcbdoc_embedded_board_panel
  48. pcbdoc_vgroove_panel

See API patterns for public vs careful mutation guidance.

altium-monkey v2026.11.26 · gobblerito·Docs updated 2026.11.29 17:55 UTC (0665053)