Renumber reference designators#

Use a session script to assign reference designators from component placement, review the proposed names, and save them through JITX’s configuration API. You can run the script again after moving or adding components. With the same placement and rules, it produces the same names.

This note targets JITX 4.6 and Python 3.12 or later. Start with the supplied two-sided demonstration board, then adapt the selectors and rules to your project. The example recomputes spatial numbering: inserting a component can renumber other components of the same prefix and side. Preserve components whose names must remain fixed.

Set up the demonstration#

Download the complete example project. Extract it, enter the reference-designators directory, and install the project into a virtual environment. On macOS or Linux:

python3 -m zipfile -e reference-designators.zip .
cd reference-designators
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -e .
jitx --version
jitx runtime introspect
jitx design find

In Windows PowerShell, create the environment with py -3 -m venv .venv and activate it with .\.venv\Scripts\Activate.ps1.

Use an installed, authorized JITX 4.6 runtime with this project. See environment setup if the environment or runtime needs configuration. Activate the environment in every terminal you use below, so each one selects the project’s jitx.

If you use uv, uv sync is an alternative to creating the environment and running pip. It records the exact Python package versions in uv.lock; keep that file with the project. Without activating the environment, prefix the commands below with uv run.

The design name is refdes_example.demo.Demo. Its R, C, U and J components are single-pad markers for inspecting numbering, not electrical models or orderable parts. The coupon includes components on both sides, nearby X coordinates, and a nested circuit rotated 90 degrees and flipped to the bottom side. fixed has J1 assigned in source. reserved keeps its automatically assigned name through the script’s preservation selector.

class Coupon(Circuit):
    # The nearby X coordinates share a 1 mm column; Y sets their order.
    resistors = [
        ResistorMarker().at(-8.8, 4),
        ResistorMarker().at(-8.2, 9),
        ResistorMarker().at(3, 4),
        ResistorMarker().at(-6, -6, on=Side.Bottom),
    ]
    capacitors = [
        CapacitorMarker().at(-4, 8),
        CapacitorMarker().at(4, -6, on=Side.Bottom),
    ]
    chips = [ChipMarker().at(-2, 0), ChipMarker().at(6, 0, on=Side.Bottom)]
    nested = Pair().at(10, 8, rotate=90, on=Side.Bottom)
    fixed = ConnectorMarker().at(-15, 0)
    reserved = ConnectorMarker().at(15, 0)

    def __init__(self) -> None:
        self.fixed.reference_designator = "J1"

1. Inspect the current design#

From the example project directory, with the environment active, start the runtime and a persistent session in Terminal A:

jitx runtime start --background
python check_source_names.py
jitx design session refdes_example.demo.Demo

The source-name check submits the design without capturing it and reports {"source_fixed": {"circuit.fixed": "J1"}}. Run it before starting the session; stop any existing session before rerunning it. When adapting another design, use the reported paths to fill in source_fixed_components(rd) as described below.

Leave that session running. In Terminal B, wait for this read-only probe to succeed, then inspect the board:

jitx --format json design exec refdes_example.demo.Demo -c "def main(rd): return rd.name"
jitx --format json design exec refdes_example.demo.Demo renumber.py -f inspect

If startup reports “message could not be delivered,” check Terminal A and retry the probe after the initial capture finishes. See AI Agent Integration for session readiness and error handling.

Inspection returns current names, structural paths, board bounds, board-absolute positions in millimeters, rotations in degrees, and Top/Bottom sides. circuit.nested.first is the path to rd.root.circuit.nested.first; a label such as R1 is not its Python attribute name. The collector composes parent and child placements, including flips. An unplaced component or ancestor gives no board position.

The board editor is optional:

jitx ui open --board --design refdes_example.demo.Demo

2. Choose the numbering rules#

Edit OPTIONS and the selectors near the top of renumber.py. The policy is a frozen options object:

@dataclass(frozen=True)
class Options:
    """Spatial numbering rules; distances and bin widths are millimeters.

    Bins are floor(coordinate / bin_mm), anchored at the board origin.
    A zero bin width sorts the exact primary coordinate instead.
    """

    corner: Corner = "top-left"
    primary_axis: Literal["x", "y"] = "x"
    bin_mm: float = 1.0
    top_start: int = 1
    bottom_start: int = 500
    preserve: frozenset[str] = frozenset()

Setting

Meaning

corner

top-left, top-right, bottom-left, or bottom-right. Here top means larger Y, and right means larger X.

primary_axis

x walks columns; y walks rows. The corner determines direction on both axes.

bin_mm

Primary-axis bin width in mm; 0 uses exact coordinates. Bins use floor(coordinate / bin_mm) with zero as their origin.

top_start, bottom_start

First available number for each prefix on each side.

preserve

A frozenset of current names to retain, such as frozenset({"J2", "MH1"}). Missing names are reported as errors.

With the defaults, each prefix is numbered independently: top-side R components start at R1, bottom-side R components at R500, and capacitors use their own C counters. The scan walks the leftmost column from larger Y to smaller Y, then moves right. Both sides use the same board coordinate frame; bottom-side X is not mirrored for a view from underneath.

Binning groups coordinates within the same fixed interval, not every pair closer than the bin width. For example, X = -8.8 and -8.2 share the interval [-9, -8), while -8.01 and -7.99 do not. Structural paths break ties, so the previous reference designators do not determine scan order.

Use PRESERVE_FILE = Path("preserved.txt") to read one name per line. Blank lines and # comments are allowed. The file and OPTIONS.preserve are combined with the components selected by preserved_components(rd).

Source-fixed and script-preserved names#

The configuration request must assign every component whose name is not set in source. A preserved component still needs its current name in that mapping. A component named in source must be omitted. Both kinds reserve their names so other components cannot receive them.

Before capture, import origin from jitx.proxy and check origin(component).reference_designator. If it is set, that component has a code-defined name: exclude it from renumbering candidates and the API mapping, or the runtime will reject the reassignment. Keep its existing name reserved so other components cannot receive it. The standalone check uses this distinction:

"""Find code-defined designators before capture in JITX 4.6.

Run with the project runtime running and no design session active. Replace the
Demo import and submit target when adapting another design. This submits the
design but does not capture it or request any reference designator changes.
"""

import json

import jitx
from jitx import Component
from jitx.proxy import origin

from refdes_example.demo import Demo


def main() -> None:
    """Print source-fixed component paths and names from an uncaptured design."""
    with jitx.runtime as runtime:
        design = runtime.submit(Demo)
        source_fixed = {
            str(trace.path): name
            for trace, component in design.query(Component)
            if (name := origin(component).reference_designator)
        }
    print(json.dumps({"source_fixed": source_fixed}, indent=2))


if __name__ == "__main__":
    main()

In released JITX 4.6.0, this check must run before capture. After capture, origin(component).reference_designator also contains runtime-assigned names. jitx design session captures during startup, before it accepts exec scripts, so testing origins inside a session script would exclude every named component. The captured component.reference_designator also includes runtime-assigned names and cannot distinguish their source.

For the JITX 4.6 session workflow, use the pre-capture report or the project source to list the code-defined components explicitly. Return their current captured objects; the demo lists circuit.fixed:

def source_fixed_components(rd: SyncRuntimeDesign) -> set[Component]:
    """Select code-defined names explicitly for captured JITX 4.6 designs.

    Run check_source_names.py before starting the session to find these paths.
    On 4.6.0, origin(component) after capture also contains runtime-assigned names.

    Args:
        rd: The freshly captured design.

    Returns:
        Objects to omit from the API mapping while reserving their names.
    """
    return {cast(Coupon, rd.root.circuit).fixed}

Use preserved_components(rd) for components whose current names should survive renumbering without assigning names in source. These components still belong in the API mapping. Both helpers return actual component objects from the fresh capture. They must not cache objects between commands; capture replaces the tree.

Labels outside the letters-plus-digits pattern, such as MOUNT_A, and unplaced components are also held unchanged. Their names remain in the mapping unless they are source-fixed. An unplaced part can enter spatial numbering once it is placed. Held numeric names reserve their numbers across both sides.

Optional groups after ordinary components#

late_components(rd) selects components that should follow the ordinary components of their prefix and side, continuing the same counter. The demo returns an empty set. For a custom model with component-based routing markers, return those Component objects to number them after ordinary U components.

The older XML approach recognized a TOPOLP package for this purpose. Current standard via structures contain native vias and do not supply those legacy component placeholders. A Via, ViaStructure, route point, or circuit itself cannot be a key in this component assignment mapping. Classify actual components from your own model rather than inferring a group from an XML package string.

3. Preview the proposed names#

Run the default entry point:

jitx --format json design exec refdes_example.demo.Demo renumber.py

It waits for layout work, captures fresh objects, validates the proposal, and writes refdes-map.csv. The JSON result contains the proposed names, board bounds, assignment count, and number of names that would change. It does not submit a reassignment request.

Review the report’s old/new names, paths, X/Y coordinates, sides, and reasons for held names. Set REPORT_FORMAT to csv, tsv, or txt and change REPORT_PATH to suit. Relative paths resolve in the session’s working directory.

These placements in the demo illustrate the default result:

Component path

Board position (mm)

Side

Proposed name

circuit.resistors[1]

(-8.2, 9)

Top

R1

circuit.resistors[0]

(-8.8, 4)

Top

R2

circuit.resistors[3]

(-6, -6)

Bottom

R500

circuit.nested.first

(10, 8)

Bottom

R501

The first two share a column; the higher one comes first despite its larger X.

If the proposed top and bottom numbering ranges overlap, validation fails with the conflicting components. Increase the bottom start or otherwise separate the ranges. No assignment request is sent for an invalid proposal.

4. Apply, restart, and verify#

Keep the layout and rules unchanged between reviewing the report and applying:

jitx --format json design exec refdes_example.demo.Demo renumber.py -f apply

The API call uses component objects as keys and strings as their new names:

def apply(rd: SyncRuntimeDesign) -> dict[str, object]:
    """Submit a fresh complete proposal, then save the expected reloaded state.

    Args:
        rd: The active session design; do not move parts after reviewing preview.

    Returns:
        The expected state and an explicit instruction to reload before verifying.
    """
    mapping, changes = _proposal(rd)
    expected = _snapshot(rd, changes)
    REPORT_PATH.write_text(report(changes, REPORT_FORMAT), encoding="utf-8")
    # This replaces the saved assignment set; preserved names belong in it too.
    rd.configuration.reassign_reference_designators(mapping)
    APPLIED_PATH.parent.mkdir(parents=True, exist_ok=True)
    APPLIED_PATH.write_text(json.dumps(expected, indent=2) + "\n", encoding="utf-8")
    return {**expected, "reload_required": True, "expected_state": str(APPLIED_PATH)}

_proposal() builds the complete mapping; even a policy that changes only resistors must retain all other automatically named components in that mapping. The runtime rejects missing assignments, source-fixed components in the mapping, empty names, duplicate names, or names that clash with source-fixed names.

An accepted reassignment changes the saved configuration for the next design load. It does not rename the live model. Calling rd.capture() alone does not activate the new names. Stop the session from Terminal B:

jitx design session refdes_example.demo.Demo --stop

Restart it in Terminal A with the same session command. Once the readiness probe succeeds, verify in Terminal B:

jitx --format json design exec refdes_example.demo.Demo renumber.py -f verify
jitx --format json design exec refdes_example.demo.Demo renumber.py

verify compares freshly captured names and placements with the accepted proposal in .jitx/refdes-applied.json. Positions, rotations and board bounds are compared to six decimal places. A successful result has verified: true. The second preview should have changed_count: 0. Stop/restart and verify again to check persistence; apply a second time and repeat to check repeated execution.

If a command fails, inspect the current state before retrying. An exception after the configuration request, including failure to save the verification file, does not undo accepted assignments. Verification failures also leave accepted assignments intact. Retain the traceback and check the session log.

When finished, stop the session. Keep the Python source and the project’s saved designs/<design>/design-info/ state through your normal version-control workflow. After accepting new names, regenerate affected BOMs, placement lists, schematics, and manufacturing outputs so they agree.

5. Adapt the scripts to your design#

Copy renumber.py and the refdes_example helper package into the existing project; demo.py is needed only for this coupon. Copy check_source_names.py as well, replace its demo import and submit target, and run it before starting the design session. Replace the demo import and all three selectors in renumber.py with your design’s types and object paths. Use the reported paths for source_fixed_components; an empty selector should return set(). Use the existing project’s pinned JITX environment and fully qualified design name.

Keep _collect()’s full component traversal and placement handling. Change selection and numbering policy separately: limiting the components that change must not produce a partial API mapping. For a new scheme, modify assign() and its tests while retaining unchanged names for every unaffected component.

Run the downloadable algorithm tests after editing the rules:

python -m unittest test_numbering

python check_live.py also runs the full workflow on a temporary copy using an authorized runtime. It checks repeated application, persistence, transformed placements, and numbering after moving and adding components.

Then exercise preview, apply, restart, and verify on a copy of the project. Move one component and add another to check how the intended spatial order changes. Restart the session after changing design definitions or modules it loaded at startup. Changes to the executed script itself are read on each exec.

An agent can adapt the example from a prompt such as:

Use this project's pinned JITX environment and the reference designator example.
Design: <fully qualified design name>.
Before starting the session, adapt and run check_source_names.py. It checks
origin(component).reference_designator before capture. Use those paths and the
source to fill source_fixed_components explicitly; the origin check cannot
distinguish source names after capture in released JITX 4.6.0.
Adapt all three selectors to actual component objects and preserve these
components by source path: <paths>. Use top-left, X-column scanning, 1 mm bins,
top start 1, bottom start 500, and shared board coordinates on both sides.
Retain every automatically named component in the assignment mapping, including
parts outside the group being renumbered. Resolve objects after every capture.
Run the policy tests and preview. Explain the proposed changes and held names.
Apply the reviewed proposal, restart the session, and verify names and placements.
Repeat with unchanged inputs and confirm zero changes. Report actual results.

The selectors and scan rules are the customization points. The complete-mapping contract, capture lifetimes, and next-load behavior belong to the JITX API.