Scripting Quantum Metal and agent use

Quantum Metal builds a chip from Python objects, and everything between the first line and the GDS file runs without a window: no Qt, no prompts and no state outside the design object. That makes it a good fit for scripts, test suites, optimizers and coding assistants that generate a design, check it and iterate. This page shows the loop, how to make the design-rule check the pass or fail signal, and what to rely on from run to run.

It needs only the lite install, pip install quantum-metal (see Desktop GUI or headless).

The loop: build, check, export, analyze

The script below builds a transmon with a meandered readout resonator and a launchpad, checks the design, exports a picture and a GDS file, and estimates the transmon levels. It is tested with the rest of the suite, so it runs as shown. Download it as headless_chip.py.

 1"""Build, check, export and analyze a one-qubit chip without a GUI.
 2
 3Run it with ``python headless_chip.py chip_out``. It needs only the lite
 4install (``pip install quantum-metal``). Set ``SOURCE_DATE_EPOCH`` to get a
 5GDS file that is identical from run to run.
 6"""
 7
 8import hashlib
 9import sys
10from pathlib import Path
11
12import qiskit_metal as qm
13from qiskit_metal import designs
14from qiskit_metal.analyses.hamiltonian.transmon_charge_basis import Hcpb
15from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket
16from qiskit_metal.qlibrary.terminations.launchpad_wb import LaunchpadWirebond
17from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
18from qiskit_metal.validation import validate
19
20
21def build(resonator_length="6.0mm"):
22    """Return a fresh design: a transmon, a launchpad and a meandered resonator."""
23    design = designs.DesignPlanar()
24    design.overwrite_enabled = True
25    design.chips.main.size.size_x = "4mm"
26    design.chips.main.size.size_y = "3mm"
27
28    TransmonPocket(
29        design,
30        "Q1",
31        options=dict(
32            pos_x="-1.0mm",
33            pos_y="0.0mm",
34            connection_pads=dict(readout=dict(loc_W=+1, loc_H=+1, pad_gap="15um")),
35        ),
36    )
37    LaunchpadWirebond(
38        design, "LP1", options=dict(pos_x="1.6mm", pos_y="0.8mm", orientation="180")
39    )
40    RouteMeander(
41        design,
42        "readout",
43        options=dict(
44            pin_inputs=dict(
45                start_pin=dict(component="Q1", pin="readout"),
46                end_pin=dict(component="LP1", pin="tie"),
47            ),
48            total_length=resonator_length,
49            fillet="90um",
50            lead=dict(start_straight="0.3mm"),
51        ),
52    )
53    return design
54
55
56def fingerprint(design):
57    """A short hash of every polygon and path in the design, in a fixed order."""
58    h = hashlib.sha256()
59    for kind, table in sorted(design.qgeometry.tables.items()):
60        for _, row in table.sort_values(["component", "name"]).iterrows():
61            h.update(
62                f"{kind}|{row['component']}|{row['name']}|{row['geometry'].wkt}".encode()
63            )
64    return h.hexdigest()[:16]
65
66
67def main(out_dir="chip_out"):
68    out = Path(out_dir)
69    out.mkdir(exist_ok=True)
70
71    design = build()
72
73    # 1. Check. ERROR findings mean the geometry is wrong; raise on them.
74    result = validate(design)
75    print(result.report())
76    result.raise_if_errors()
77
78    # 2. Export: a picture for review and the mask for the fab.
79    qm.view(design).savefig(out / "chip.png", dpi=150)
80    design.renderers.gds.export_to_gds(str(out / "chip.gds"))
81
82    # 3. Analyze. Without a field solver, a transmon level estimate from Ej, Ec.
83    spectrum = Hcpb(nlevels=15, Ej=13000.0, Ec=300.0, ng=0.0)  # MHz
84    f01, f12 = spectrum.fij(0, 1), spectrum.fij(1, 2)
85    print(f"f01 = {f01 / 1000:.3f} GHz, anharmonicity = {f12 - f01:.0f} MHz")
86
87    print("geometry fingerprint:", fingerprint(design))
88    return out
89
90
91if __name__ == "__main__":
92    main(*sys.argv[1:])

Run it with python headless_chip.py chip_out. It prints

Design rules passed (11 rules ran, no findings).
f01 = 5.267 GHz, anharmonicity = -350 MHz
geometry fingerprint: 8463ea8fe7b47922

and writes chip.png and chip.gds.

The analysis step here is an estimate from \(E_J\) and \(E_C\). For capacitances, eigenmodes and couplings from a field solver, see Simulation pathways; the same script can hand the design to a solver renderer in place of that last step.

The design-rule check as the success signal

validate(design) runs the design rules and returns a result. A script or an agent needs three things from it:

  • result.ok is True when nothing of ERROR severity was found. ERROR means the geometry is wrong whatever the intent: a shape off the chip, a short between nets, a route too close to a qubit. A WARNING is legal geometry that is probably unintended, such as a straight segment too short for its fillet.

  • result.errors and result.warnings are lists of findings. Each has a severity, the rule that raised it, the components involved and a message that says what to change.

  • validate(design, strict=True) raises DesignRuleViolation on any ERROR, and result.raise_if_errors() does the same later. Use either as a gate in a build script or in CI.

For example, move the launchpad off the chip:

design = build()
design.components["LP1"].options.pos_x = "3.5mm"
design.rebuild()

result = validate(design)
for finding in result.errors:
    print(finding.rule, finding.components, finding.message)
chip-bounds ('LP1',) LP1 extends 1760.0 um beyond the 'main' chip outline
chip-bounds ('readout',) readout extends 1475.0 um beyond the 'main' chip outline

An optimizer can read these findings, change an option and rebuild until the result is clean. Findings you accept on purpose are recorded with validate(design, waivers=[...]), which keeps the reason in the report instead of hiding it. The rules and their thresholds are described in qiskit_metal.validation; a different process design kit is a constructor argument, not a fork.

Watch a script and see the chip update

While you edit a design script, python -m qiskit_metal.watch my_design.py re-runs it each time you save, writes watch_out/design.png, and prints the design-rule report. Add --gds to also write watch_out/design.gds, which KLayout can reload. The script only has to leave a QDesign in a variable named design (--var changes the name). An error in the script is printed and the watch keeps running. Nothing here needs Qt.

Getting the same answer twice

  • Geometry. Building the same options gives the same geometry. The script’s fingerprint function hashes every polygon and path in a fixed order, so two runs print the same value. Compare it in a test to catch a change that moves the layout.

  • The GDS file. A GDS file stores the time it was written, so two exports of one design differ by a few bytes. Set the standard SOURCE_DATE_EPOCH environment variable (seconds since 1970) and the export is identical byte for byte:

    SOURCE_DATE_EPOCH=1700000000 python headless_chip.py chip_out
    
  • The design as a script. design.to_python_script() returns the Python that rebuilds the design, which is a readable artifact to store next to the GDS.

What to rely on

Quantum Metal is a 0.x library, so a minor release can change behavior. Two habits keep a script safe:

  • Rely on the surface the API reference documents: QDesign and its subclasses, QComponent options, qm.view and qm.gui, validate, the renderers’ export methods and the analyses. Changes to those are listed in the changelog.

  • Read the Behavior changes part of the changelog when you upgrade. Every change that moves numbers or geometry is listed there, and the fingerprint above shows whether your design moved.

Pin the version in your environment (for example quantum-metal==<version>) so a run you want to repeat uses the same code.

Using a coding assistant

An assistant can drive the script above directly: ask it to change options, run validate, and keep going until result.ok is true, then export. Give it the validate output as feedback, since the finding messages say what is wrong.

The repository also carries task notes written for assistants, as plain Markdown files that any tool can read, under .claude/skills/:

  • chip-design: from a specification to a staged build with a check after every stage;

  • chip-layout-from-images: reproducing a published device from its figures;

  • chip-simulation: choosing a solver and extracting capacitances, frequencies and couplings;

  • tutorial-notebook: writing and re-running tutorial notebooks.

Point an assistant at the one that matches the task. The design-rule check is the success signal in all of them.

Where a script cannot go

Interactive editing needs the desktop GUI (GUI navigation and shortcuts). Ansys solves need an Ansys license, and the Ansys renderers run on a machine where Ansys is installed. Everything else on this page runs anywhere Python does, including Colab and a CI runner.