mqt.core.mlir

MQT Core MLIR compiler bindings.

Package Contents

class QIRProfile

Bases: enum.Enum

QIR target profiles.

BASE = 0

The QIR Base Profile.

ADAPTIVE = 1

The QIR Adaptive Profile.

class OutputFormat

Bases: enum.Enum

Default compiler output formats.

QC_IMPORT = 0

QC directly after frontend import.

QCO = 1

QCO immediately after conversion, before optimization.

QCO_OPTIMIZED = 2

QCO after the configured optimization pipeline.

QC = 3

QC after the optimized QCO round trip.

OPENQASM2 = 9

OpenQASM 2 with bound parameters.

OPENQASM3 = 4

OpenQASM 3 after the optimized QCO round trip.

IQM_JSON = 8

An IQM circuit for an explicit physical target.

JEFF = 5

Serializable jeff MLIR.

QIR_BASE = 6

QIR for the Base Profile.

QIR_ADAPTIVE = 7

QIR for the Adaptive Profile.

QISKIT = 10

A Qiskit QuantumCircuit.

QPY = 11

A QPY 17 binary circuit.

class PayloadEncoding

Bases: enum.Enum

Text or binary program encoding.

TEXT = 0
BINARY = 1
class PayloadFormat(format_id: str, version: str, profile: str = '', encoding: PayloadEncoding = PayloadEncoding.TEXT)

Selected program format and accepted receiver versions.

property format_id: str
property version: str
property profile: str
property encoding: PayloadEncoding
class ProgramConstraint(constraint_id: str, value: int)

One limit on a supported program feature.

property constraint_id: str
property value: int
MAX_NESTING_DEPTH: str = 'max-control-flow-nesting-depth'
MAX_ITERATION_COUNT: str = 'max-iteration-count'
MAX_CASE_COUNT: str = 'max-case-count'
class ProgramCapability(capability_id: str, value: int = 0, constraints: Sequence[ProgramConstraint] = [])

One program feature supported for execution.

property capability_id: str
property value: int
property constraints: list[ProgramConstraint]
CLASSICAL_ASSIGNMENT: str = 'classical-assignment'
FORWARD_BRANCHING: str = 'forward-branching'
COUNTED_ITERATION: str = 'counted-iteration'
CONDITIONAL_LOOP: str = 'conditional-loop'
MULTIWAY_BRANCHING: str = 'multiway-branching'
class PayloadSpecification

Bases: Generic[_TargetResultT_co]

The format and program features selected for execution.

A device may accept several formats with different restrictions. This object records one selection: its format, version, encoding, and allowed features, such as branches or loops. Pair it with a CompilerTarget in a TargetEnvironment to compile for that combination.

static from_program_format(program_format: ProgramFormat) → PayloadSpecification[CompiledProgram]

The compiler-supported baseline features for a QDMI program format.

property format: PayloadFormat

The selected program format and accepted receiver versions.

property capabilities: list[ProgramCapability]

The program features allowed by this specification.

property optional_capabilities_known: bool

Whether optional capability metadata is complete.

class CompilerTarget(num_sites: int, *, connectivity: CompilerTarget, native_operations: CompilerTarget, duration_unit: CompilerTarget | None = None)
class CompilerTarget(name: str, num_sites: int, *, connectivity: CompilerTarget, native_operations: CompilerTarget, duration_unit: CompilerTarget | None = None)
class CompilerTarget(sites: Sequence[CompilerTarget], *, connectivity: CompilerTarget, native_operations: CompilerTarget, duration_unit: CompilerTarget | None = None)
class CompilerTarget(name: str, sites: Sequence[CompilerTarget], *, connectivity: CompilerTarget, native_operations: CompilerTarget, duration_unit: CompilerTarget | None = None)

Immutable MQT compiler target.

A target describes the hardware facts used during compilation without opening a device connection. Connectivity can be all-to-all or an explicit list of connections. Native operations can be unrestricted or listed individually with their supported sites and parameters. Use a TargetEnvironment to combine these hardware facts with the format and program features accepted for execution.

class DurationUnit(unit: str, scale_factor: float)

Unit for raw target timing metadata.

property unit: str

The reported duration unit.

property scale_factor: float

The multiplier applied to raw timing values.

class Site(site_id: int, name: str | None = None, t1: int | None = None, t2: int | None = None)

A hardware site and its optional metadata.

property id: int

The target-defined nonnegative site identifier.

property name: str | None

The reported site name, if available.

property t1: int | None

The raw T1 coherence time, if available.

property t2: int | None

The raw T2 coherence time, if available.

class SiteTuple(sites: Sequence[int], duration: int | None = None, fidelity: float | None = None)

A supported ordered placement with optional calibration.

property sites: list[int]

The ordered target site identifiers.

property duration: int | None

The raw operation duration, if available.

property fidelity: float | None

The operation fidelity, if available.

class OperationArityKind

Bases: enum.Enum

How an operation capability accepts qubit widths.

FIXED = 0
VARIADIC = 1
class OperationArity

Accepted operation qubit widths.

static fixed(value: int) → CompilerTarget

Create an exact operation arity.

static variadic(minimum: int) → CompilerTarget

Create an operation arity with an inclusive minimum.

Capability construction requires a positive minimum.

property kind: CompilerTarget

The arity kind.

property value: int

The exact arity or inclusive variadic minimum.

accepts(width: int) → bool

Whether this arity accepts a concrete width.

class OperationCapability(name: str, arity: int | CompilerTarget, num_parameters: int, site_tuples: Sequence[CompilerTarget | Sequence[int]] | None = None, duration: int | None = None, fidelity: float | None = None, *, fixed_parameters: Sequence[float | None] = (), canonical_name: str | None = None, parameter_bounds: Sequence[tuple[float, float] | None] = ())

A target operation capability, calibration, and ordered applicability.

property name: str

The exact reported operation name.

property canonical_name: str

The normalized compiler operation name.

property arity: CompilerTarget

The accepted operation arity.

property num_parameters: int

The number of real-valued parameters.

property site_tuples: list[CompilerTarget]

Supported ordered placements with optional calibration; empty means general applicability.

property parameter_bounds: list[tuple[float, float] | None]

Inclusive parameter intervals; None leaves a parameter unbounded.

property fixed_parameters: list[float | None]

Fixed values or None per parameter; empty means unrestricted.

Constants use absolute tolerance 1e-15 without angle wrapping.

property duration: int | None

The raw default duration, if available.

property fidelity: float | None

The default fidelity, if available.

class GateKind

Bases: enum.Enum

Recognized native gate capability.

U = 0
X = 1
SX = 2
RZ = 3
RX = 4
RY = 5
R = 6
RXX = 7
RYY = 8
RZX = 9
RZZ = 10
ISWAP = 11
CZ = 12
CX = 13
ECR = 14
SQRTISWAP = 15
class SingleQubitBasis

Bases: enum.Enum

Recognized target-wide single-qubit synthesis basis.

U = 0
ZSXX = 1
R = 2
GPI = 7
XZX = 3
XYX = 4
ZYZ = 5
ZXZ = 6
class AngleSupport

Bases: enum.Enum

Angle domain used by native entangler synthesis.

FIXED = 0
UNRESTRICTED = 1
ZERO_TO_HALF_PI = 2
class Entangler

A native synthesis entangler and its angle support.

property gate: CompilerTarget

The native gate kind.

property parameterized: bool

Whether synthesis can vary the entangler angle.

property angles: CompilerTarget

The angle domain used by synthesis.

class SynthesisBasis

One synthesis basis usable across the complete target.

property single_qubit: CompilerTarget

The single-qubit synthesis basis.

property entangler: CompilerTarget | None

The two-qubit entangler, or None when none is usable.

class ConnectivityKind

Bases: enum.Enum

The target connectivity model.

ALL_TO_ALL = 0
EXPLICIT = 1
class Connectivity(couplings: Sequence[tuple[int, int]])

A target connectivity model.

static all_to_all() → CompilerTarget

Create an all-to-all connectivity model.

property kind: CompilerTarget

The connectivity model.

property couplings: list[tuple[int, int]]

The explicit couplings, if present.

class NativeOperationsKind

Bases: enum.Enum

The native-operation support model.

UNRESTRICTED = 0
EXPLICIT = 1
class NativeOperations(operations: Sequence[CompilerTarget])

Native-operation support.

static from_qiskit(source: Target | BackendV2, *, operation_names: Iterable[str] | None = None) → CompilerTarget

Import gate capabilities and parameter constraints, ignoring physical placement.

Unsupported explicit selections raise ValueError; otherwise they warn and are omitted.

static unrestricted() → CompilerTarget

Create unrestricted native-operation support.

property kind: CompilerTarget

The native-operation support model.

property operations: list[CompilerTarget]

The explicit operations, if present.

static for_gate_set(native_operations: CompilerTarget) → CompilerTarget

Create a gate-set target without device constraints.

property has_device_constraints: bool

Whether compilation assigns program qubits to device sites.

static from_device(device: Device) → CompilerTarget

Snapshot a circuit-model QDMI device.

static from_qiskit(source: Target | BackendV2, *, operation_names: Iterable[str] | None = None, name: str | None = None) → CompilerTarget

Snapshot native operations and connectivity from Qiskit.

Parameters:
  • source – Qiskit Target or BackendV2. Physical import requires a known positive qubit count.

  • operation_names – Qiskit Target operation names to retain. By default, include every representable operation. Explicit selections must all be representable.

  • name – Override the target name. By default, use the backend name when source is a BackendV2; a Target produces an unnamed snapshot.

Returns:

An independent compiler target. Unrepresentable gates are omitted with warnings when operation_names is not set. Calibration and scheduling data are not included.

Raises:
  • TypeError – If source is neither a Target nor a BackendV2.

  • ValueError – If the selected operations or connectivity cannot be represented.

static from_device_id(device_id: str, *, driver_path: str | PathLike[str] | None = None, token: str | None = None, auth_file: str | PathLike[str] | None = None, auth_url: str | None = None, username: str | None = None, password: str | None = None, project_id: str | None = None, custom1: str | None = None, custom2: str | None = None, custom3: str | None = None, custom4: str | None = None, custom5: str | None = None) → CompilerTarget

Open a device through mqt.core.qdmi.open_device() and snapshot its compiler target.

property name: str | None

The target name, if available.

property duration_unit: CompilerTarget | None

The target timing unit, if available.

property placeable_sites: list[int]

Sites supporting a compiler-targetable single-qubit gate.

If the target supports measurement, these sites must also support readout.

property num_sites: int

The number of target sites.

property sites: list[CompilerTarget]

Detailed sites in compiler-vertex order.

property connectivity_kind: CompilerTarget

The target connectivity model.

property couplings: list[tuple[int, int]]

Canonical undirected couplings in target site IDs.

property native_operations_kind: CompilerTarget

The target native-operation support model.

property operations: list[CompilerTarget]

Operation capabilities in reported order.

property supported_gates: list[CompilerTarget]

Recognized native gates supported by the target.

property synthesis_basis: CompilerTarget | None

A target-wide single-qubit basis with an optional entangler, or None when no single-qubit basis is usable.

supports_operation(name: str, arity: int, num_parameters: int | None = None, sites: Sequence[int] | None = None, *, parameters: Sequence[float | None] = ()) → bool

Check whether the target supports an operation.

Parameters:
  • name – Operation name. Recognized aliases are normalized.

  • arity – Number of qubits used by the operation.

  • num_parameters – Number of real-valued parameters. None accepts any count.

  • sites – Ordered target site IDs. None checks support on any placement.

  • parameters – Known parameter values. Omitted or None values require unrestricted support.

class TargetEnvironment

Bases: Generic[_TargetResultT_co]

A compiler target paired with an execution format and its restrictions.

The target describes available gates and connectivity. The payload specification describes how the program will be represented and which classical operations and control flow it may use. Keep the environment to compile several programs for the same combination, or create one from a device with from_device().

static from_qiskit(source: Target | BackendV2, *, native_num_qubits: int | None = None, strict: bool = False) → TargetEnvironment[QuantumCircuit]

Snapshot a Qiskit target and its output capabilities.

Parameters:
  • source – Qiskit Target or BackendV2.

  • native_num_qubits – Build a gate-set target without device placement. Pass the circuit’s positive width to skip wider gates. None retains the device topology.

  • strict – Raise ValueError for an applicable gate or constraint that Core cannot represent. By default, warn and omit unsupported gates.

Returns:

The compiler target and supported Qiskit program features.

static from_device(device: Device | str, *, program_format: ProgramFormat | None = None) → TargetEnvironment[CompiledProgram]

Snapshot a QDMI device and select its execution format.

property target: CompilerTarget

The compiler target.

property payload_specification: PayloadSpecification[_TargetResultT_co]

The selected execution format and supported program features.

class Program

Base class for a typed MLIR compiler program.

Programs own their MLIR module. Conversions can consume a program; use is_valid to check whether it can still be used.

property is_valid: bool

Whether this program still owns its module.

operation_counts() → dict[str, int]

Count every operation by its full MLIR name.

Includes the root module, helper functions, modifier bodies, terminators, and nested modules.

property ir: str

The textual MLIR representation of this program.

class MappingOptions(*, trials: int | None = None, iterations: int = 2, lookahead: int = 20, search_memory_limit: int = 268435456)

Native mapping controls.

property trials: int | None

Positive trial count; None uses the available logical CPU count, with a minimum of 8.

property iterations: int

Forward/backward refinement rounds; zero scores each start directly.

property lookahead: int

Additional two-qubit gates considered during routing; zero disables lookahead.

property search_memory_limit: int

Estimated node and layout bytes per routing search, per concurrent trial.

Zero disables node expansion. Container overhead, caches, and IR are extra.

class CompilationOptions(*, seed: int | None = None, enable_timing: bool = False, enable_statistics: bool = False, mapping: MappingOptions = ..., trace_file: str | PathLike | None = None)

Shared compiler controls.

An explicit seed overrides all compiler randomness; None preserves pass defaults and custom pipeline seeds.

property seed: int | None
property enable_timing: bool
property enable_statistics: bool
property mapping: MappingOptions
property trace_file: Path | None

File for a Chrome trace of the native compilation, or None to disable tracing.

The trace records MLIR actions, such as pass runs and pattern applications. Each call overwrites the file. Program sequences reject this option.

class QuantumProgramInfo

Quantum resources and static IR statistics.

Use QCProgram.inspect() or QCOProgram.inspect() to collect a snapshot.

property num_qubits: int | None

Declared quantum capacity.

Counts allocated qubits or distinct static site IDs. None means the width is unknown. Resource inspection includes helper functions and excludes nested modules; it describes declared capacity rather than peak live width.

property static_qubits: list[int]

Sorted distinct physical site IDs.

Includes declarations in helper functions and excludes nested modules.

property has_control_flow: bool

Whether the module contains control flow.

Includes branches and region-control operations in helper functions, but excludes nested modules.

property num_gates: int

Core’s static entry-point gate count.

See QCProgram.num_gates().

property num_single_qubit_gates: int

Static single-qubit gate count.

See QCProgram.num_single_qubit_gates().

property num_two_qubit_gates: int

Static two-qubit gate count.

See QCProgram.num_two_qubit_gates().

property gate_counts: dict[str, int]

Entry-point gate histogram.

See QCProgram.gate_counts().

property control_flow_counts: dict[str, int]

Entry-point control-flow histogram.

See QCProgram.control_flow_counts().

property operation_counts: dict[str, int]

Full module operation histogram.

See Program.operation_counts().

class QCProgram

Bases: Program

A compiler program in the QC dialect.

QC programs use reference semantics and represent frontend quantum programs before conversion to QCO.

static from_mlir_str(source: str) → QCProgram

Parse a QC MLIR source string.

static from_mlir_file(path: str | PathLike) → QCProgram

Parse QC MLIR from a file.

static from_openqasm_str(source: str) → QCProgram

Translate supported OpenQASM to QC MLIR.

Accepts versionless input and versions 2.0, 3.0, and 3.1.

static from_openqasm_file(path: str | PathLike) → QCProgram

Translate a supported OpenQASM file to QC MLIR.

Accepts versionless input and versions 2.0, 3.0, and 3.1.

static from_qiskit(circuit: QuantumCircuit, *, native: bool = False) → QCProgram

Translate a Qiskit {py:class}`~qiskit.circuit.QuantumCircuit` to QC MLIR.

Parameters:
  • circuit – Circuit to import. A complete transpiler layout is retained as metadata.

  • native – Whether the circuit is already compiled for a device. Fixes circuit indices to device qubits and preserves gate names and operands without importing definitions. The caller validates device support and placements.

static from_pennylane(tape: QuantumScript, *, wires: Sequence[Hashable] | None = None) → QCProgram

Translate a preprocessed PennyLane {py:class}`~pennylane.tape.QuantumScript` to QC MLIR.

The tape must contain supported native gates after decomposition, measurement basis rotations, and mid-circuit measurement deferral. Touched wires are measured; untouched wires contribute known zeros. Results follow the supplied wire order (the tape’s wire order by default). PennyLane’s terminal measurements are evaluated from these samples by the device.

Parameters:
  • tape – Preprocessed tape to import.

  • wires – Wire order for the measured results. Defaults to the tape’s wire order.

copy() → QCProgram

Return an independent copy of this program.

cleanup() → None

Fold classical values and remove structural scaffolding in place.

Preserve supplied unitary gates. Use explicit quantum optimization passes to cancel, fuse, or specialize gates.

normalize_global_phases() → None

Normalize scoped global phases in place.

to_openqasm2(*, copy: bool = False) → OpenQASMProgram

Emit OpenQASM 2, discarding program-wide global phase.

Parameters must be bound, indices static, and classical storage limited to output registers written by measurements. Register-equality conditions can guard gates, resets, and measurements. Other runtime control flow and unsupported modifiers raise an error. Use compile_program to lower static loops before export.

The source is consumed, including on failure. Set copy=True to preserve it.

Parameters:

copy – Export a copy of the program.

to_openqasm3(*, copy: bool = False) → OpenQASMProgram

Emit this QC program as OpenQASM 3.

Classical memory and control flow are legalized for the source format. Use compile_program for optimization before export.

The source is consumed, including when export fails. Set copy=True to preserve it.

Parameters:

copy – Preserve the source program by exporting a copy.

to_qiskit(*, target: CompilerTarget | None = None, copy: bool = False) → QuantumCircuit

Convert this program to a Qiskit circuit.

The source is consumed, including when export fails. Set copy=True to preserve it. The exporter restores attached layout metadata when it is compatible with the selected target.

Parameters:
  • target – Map static site IDs to qubit indices in target site order. All qubits must be static sites of the target. Select applicable standard gate names without checking device execution support. None applies no target site mapping.

  • copy – Preserve the source program by exporting a copy.

to_qco(*, copy: bool = False) → QCOProgram

Convert this program to QCO.

The source is consumed even on failure. Set copy=True to preserve it.

to_iqm_json(target: CompilerTarget, *, copy: bool = False) → IQMJSONProgram

Serialize PRX/CZ gates and terminal readout as IQM JSON.

Qubits must be static target sites. Each output bit must have one terminal measurement. Entry-point global phases are normalized and discarded. This performs no routing, gate synthesis, or optimization. The source is consumed even on failure. Set copy=True to preserve it.

to_qir(profile: QIRProfile, *, copy: bool = False) → QIRProgram

Lower this program to QIR for the requested profile.

Entry results may be direct measurements or CBit registers. Adaptive Profile also supports computed Boolean (i1) results. Other scalar outputs are unsupported. The generated QIR returns a zero execution status. Base conversion requires straight-line quantum operations; Adaptive retains loops. Calls with quantum-register arguments must be inlined before conversion. Use compile_program for inlining, modifier expansion, and Base loop unrolling. The source is consumed even on failure. Set copy=True to preserve it.

inspect() → QuantumProgramInfo

Inspect quantum resources and static IR statistics.

Returns a QuantumProgramInfo snapshot with gate, control-flow, and full operation counts.

num_gates() → int

Return Core’s static gate count of the entry-point IR.

Unitary operations, measurements, and resets each count once. Barriers are excluded. Each modifier or call counts once without expanding its body. Gates in every control-flow region count once, regardless of runtime paths or loop iterations.

num_single_qubit_gates() → int

Count gates acting on exactly one qubit.

Uses the counting rules of num_gates(), including measurements and resets.

num_two_qubit_gates() → int

Count gates acting on exactly two qubits.

Uses the counting rules of num_gates().

gate_counts() → dict[str, int]

Count entry-point gates by name.

Uses the counting rules of num_gates(). Controls on a single primitive gate add a c per control: cx, ccx. Other single-gate modifiers use inv(h), pow(rx), or ctrl(inv(x)); multiple controls use ctrl(2,inv(x)). Parameters do not split buckets. Composite bodies or unused modifier targets retain ctrl, inv, or pow. Calls use the callee name; explicit phases use gphase.

control_flow_counts() → dict[str, int]

Count entry-point control-flow operations.

Keys are full MLIR names such as scf.for and qco.if. Every region is visited once, without expanding calls. Region terminators such as scf.yield are excluded.

property parameters: list[str]

Named f64 scalar and fixed-length array inputs in function argument order.

bind_parameters(values: Mapping[str, SupportsFloat | Sequence[SupportsFloat] | ndarray[tuple[int], dtype[floating[Any] | integer[Any]]]], *, copy: bool = False) → Self

Bind named scalar and array parameters and return the bound program.

Binding modifies this program unless copy=True requests an independent copy.

Inputs must be f64 scalars or fixed-length, one-dimensional f64 arrays. Supply arrays as sequences or NumPy arrays with the expected length. Partial binding preserves unbound inputs and their source identities. Unknown names, mismatched scalar or array values, incorrect lengths, non-finite values, and references to the entry point raise ValueError without changing the program.

Binding folds expressions using the bound values. Folding failures may leave the program modified. Use copy=True to preserve the input.

class QCOProgram

Bases: Program

A compiler program in the QCO dialect.

QCO programs use value semantics and expose optimization and transformation operations.

static from_mlir_str(source: str) → QCOProgram

Parse a QCO MLIR source string.

static from_mlir_file(path: str | PathLike) → QCOProgram

Parse QCO MLIR from a file.

copy() → QCOProgram

Return an independent copy of this program.

cleanup() → None

Fold classical values and remove structural scaffolding in place.

Preserve supplied unitary gates. Use explicit quantum optimization passes to cancel, fuse, or specialize gates.

normalize_global_phases() → None

Normalize scoped global phases in place.

run_pass_pipeline(pipeline: str, *, target_environment: TargetEnvironment | None = None, options: CompilationOptions = ..., preserve_layout: bool = False) → None

Run a textual MLIR pass pipeline in place.

The supplied target environment replaces the existing one after parsing succeeds and remains attached for subsequent passes. None retains the existing environment. Only the requested passes run; no default target compilation stages are added. Layout metadata is cleared unless preserve_layout=True. Set this only when the passes keep wire and site identities or update the layout to reflect changes. The flag itself does not create or validate a mapping. Execution failure can leave partial changes; use copy() to preserve the input.

merge_single_qubit_rotation_gates() → None

Merge compatible consecutive single-qubit rotation gates.

fuse_single_qubit_unitary_runs(*, basis: str = 'zyz') → None

Fuse single-qubit unitary runs into the chosen decomposition basis.

unroll_quantum_loops(*, unroll_factor: int = -1) → None

Unroll quantum loops, optionally using a maximum unroll factor.

lift_hadamards() → None

Move Hadamard gates through compatible operations.

reuse_qubits() → None

Reuse independent single-qubit allocations.

run_qubit_reuse_pipeline() → None

Prepare the program for qubit reuse and reuse eligible qubits.

decompose_multi_controlled(*, min_qubits: int = 3) → None

Decompose gates that act on at least min_qubits qubits.

Supports controlled X/Y/Z/P/SWAP and RX/RY/RZ gates and qco.rccx. min_qubits must be at least 3. The pass borrows and restores ancilla qubits when this reduces the estimated entangling cost. It allocates no additional qubits.

compile_for_target(target_environment: TargetEnvironment, *, options: CompilationOptions = ...) → None

Compile for the target and attach layout metadata when possible.

Reject existing layout metadata. Do not rely on program contents if compilation fails. Failures raise RuntimeError with MLIR diagnostics.

synthesize_for_target(target_environment: TargetEnvironment, *, options: CompilationOptions = ...) → None

Synthesize native operations without routing.

For device targets, allocated program qubits require all-to-all connectivity and receive layout metadata when possible. Static device-site references keep their IDs and must fit the target topology. Do not rely on the program contents if synthesis fails. Failures raise RuntimeError with the emitted MLIR diagnostics.

to_qiskit(*, target: CompilerTarget | None = None, copy: bool = False) → QuantumCircuit

Convert this program through QC to a Qiskit circuit.

The source is consumed, including when conversion or export fails. Set copy=True to preserve it. The exporter restores attached layout metadata when it is compatible with the selected target.

Parameters:
  • target – Map static site IDs to qubit indices in target site order. All qubits must be static sites of the target. Select applicable standard gate names without checking device execution support. None applies no target site mapping.

  • copy – Preserve the source program by exporting a copy.

to_qc(*, copy: bool = False) → QCProgram

Convert this program to QC.

The source is consumed even on failure. Set copy=True to preserve it.

to_jeff(*, copy: bool = False) → JeffProgram

Convert this program to jeff MLIR.

The source is consumed even on failure. Set copy=True to preserve it.

inspect() → QuantumProgramInfo

Inspect quantum resources and static IR statistics.

Returns a QuantumProgramInfo snapshot with gate, control-flow, and full operation counts.

num_gates() → int

Return Core’s static gate count of the entry-point IR.

Unitary operations, measurements, and resets each count once. Barriers are excluded. Each modifier or call counts once without expanding its body. Gates in every control-flow region count once, regardless of runtime paths or loop iterations.

num_single_qubit_gates() → int

Count gates acting on exactly one qubit.

Uses the counting rules of num_gates(), including measurements and resets.

num_two_qubit_gates() → int

Count gates acting on exactly two qubits.

Uses the counting rules of num_gates().

gate_counts() → dict[str, int]

Count entry-point gates by name.

Uses the counting rules of num_gates(). Controls on a single primitive gate add a c per control: cx, ccx. Other single-gate modifiers use inv(h), pow(rx), or ctrl(inv(x)); multiple controls use ctrl(2,inv(x)). Parameters do not split buckets. Composite bodies or unused modifier targets retain ctrl, inv, or pow. Calls use the callee name; explicit phases use gphase.

control_flow_counts() → dict[str, int]

Count entry-point control-flow operations.

Keys are full MLIR names such as scf.for and qco.if. Every region is visited once, without expanding calls. Region terminators such as scf.yield are excluded.

property parameters: list[str]

Named f64 scalar and fixed-length array inputs in function argument order.

bind_parameters(values: Mapping[str, SupportsFloat | Sequence[SupportsFloat] | ndarray[tuple[int], dtype[floating[Any] | integer[Any]]]], *, copy: bool = False) → Self

Bind named scalar and array parameters and return the bound program.

Binding modifies this program unless copy=True requests an independent copy.

Inputs must be f64 scalars or fixed-length, one-dimensional f64 arrays. Supply arrays as sequences or NumPy arrays with the expected length. Partial binding preserves unbound inputs and their source identities. Unknown names, mismatched scalar or array values, incorrect lengths, non-finite values, and references to the entry point raise ValueError without changing the program.

Binding folds expressions using the bound values. Folding failures may leave the program modified. Use copy=True to preserve the input.

build_functionality(dd_package: DDPackage) → MatrixDD

Build a matrix DD for a static unitary QCO program.

Parameters:

dd_package – DD package with enough qubits for the program.

Returns:

Matrix DD of the program functionality.

Raises:

ValueError – When the program is unsupported for functionality construction.

simulate(initial_state: VectorDD, dd_package: DDPackage, seed: int = 0) → VectorDD

Simulate a QCO program on a DD state.

Parameters:
  • initial_state – Input state DD that spans at least the program’s qubits and has a live reference in dd_package. Higher wires are preserved. A valid input reference is consumed.

  • dd_package – DD package with enough qubits for the program.

  • seed – RNG seed. 0 (default) selects nondeterministic seeding. Any other value produces reproducible measurement and reset results.

Returns:

Output state DD.

Raises:

ValueError – When initial_state has no live reference in dd_package, has too few qubits, or the program is unsupported for simulation.

expectation_values(observables: Sequence[Mapping[str, float]]) → list[float]

Evaluate Pauli observables on the state prepared by this program.

The calculation starts with all qubits in zero and evaluates every observable on the resulting state before measurement. It uses decision diagrams, so it does not need dense state or observable arrays. The program remains available after the call. Terminal measurements are deferred under the same conditions as mqt.core.mlir.simulate(); resets and measurement-dependent evolution are unsupported.

Parameters:

observables – Sequence of mappings from Pauli strings to finite real coefficients. Each string spans every program wire and contains only I, X, Y and Z, with the rightmost character acting on wire zero. An empty mapping represents the zero observable.

Returns:

Numerical expectation values in observable order.

Raises:

ValueError – When an observable is invalid or the program cannot prepare an uncollapsed state, or an expectation is not finite.

sample(shots: int = 1024, seed: int = 0) → dict[str, int]

Sample the declared outputs of a QCO program.

Parameters:
  • shots – Number of shots (default 1024).

  • seed – RNG seed. 0 (default) selects nondeterministic seeding. Any other value produces reproducible results.

Returns:

Histogram keys use conventional count-string order. The last returned CBit register or Boolean value comes first, and each register is MSB-first. Other classical output types are rejected. Without classical results, final measureAll bitstrings are used instead.

Raises:

ValueError – When the program is unsupported for sampling.

class JeffProgram

Bases: Program

A serializable compiler program in the jeff dialect.

jeff programs can be stored as bytes or files and converted back to QCO for further compilation.

static from_segments(segments: Sequence[bytes | bytearray | memoryview | ndarray]) → JeffProgram

Deserialize a jeff program from Cap’n Proto segments.

Each segment must be a contiguous one-dimensional byte buffer whose size is a multiple of eight. Keep the buffers unchanged until this call returns. Aligned buffers are borrowed; unaligned buffers are copied into aligned storage. The returned program does not retain the buffers.

static from_bytes(data: bytes) → JeffProgram

Deserialize a jeff program from bytes.

static from_file(path: str | PathLike) → JeffProgram

Read a jeff program from a file.

copy() → JeffProgram

Return an independent copy of this program.

cleanup() → None

Run the standard jeff cleanup pipeline in place.

to_segment_views() → list[memoryview]

Serialize this program into read-only Cap’n Proto segment views.

The views keep their message storage alive independently of this program. No segment data is copied or flattened.

to_bytes() → bytes

Serialize this program to its jeff byte representation.

write(path: str | PathLike) → None

Write this program to a jeff file.

to_qco(*, copy: bool = False) → QCOProgram

Convert this program to QCO.

The source is consumed even on failure. Set copy=True to preserve it.

class IQMJSONProgram

An immutable output-only IQM circuit object.

property source: str

The emitted IQM JSON source.

write(path: str | PathLike) → None

Write the IQM JSON source to a file.

class OpenQASMProgram

An immutable compiler program containing OpenQASM 3 source.

property source: str

The emitted OpenQASM 3 source.

write(path: str | PathLike) → None

Write the emitted source to a file.

class QIRProgram

Bases: Program

A compiler program lowered to QIR.

QIR programs retain their target profile and can be emitted as LLVM IR or LLVM bitcode.

simulate() → Annotated[numpy.typing.NDArray[numpy.complex128], {'shape': (None, ), 'order': 'C', 'device': 'cpu'}]

Return the uncollapsed statevector in QIR runtime qubit order; reset and measurement-dependent feedback are unsupported.

sample(shots: int = 1024, seed: int = 0) → dict[str, int]

Sample recorded outputs. Zero selects random seeding; fixed seeds must fit a positive signed 32-bit integer.

copy() → QIRProgram

Return an independent copy of this program.

cleanup() → None

Run the standard QIR cleanup pipeline in place.

property profile: QIRProfile

The QIR target profile used to produce this program.

to_llvm_ir(*, copy: bool = False) → str

Consume this program and emit LLVM IR text.

The source is consumed even on failure. Set copy=True to preserve it.

Parameters:

copy – Preserve the source program by exporting a copy.

to_bitcode(*, copy: bool = False) → bytes

Consume this program and emit LLVM bitcode.

The source is consumed even on failure. Set copy=True to preserve it.

Parameters:

copy – Preserve the source program by exporting a copy.

write_bitcode(path: str | PathLike, *, copy: bool = False) → None

Consume this program and write LLVM bitcode to a file.

The source is consumed even on failure. Set copy=True to preserve it.

Parameters:
  • path – Destination file.

  • copy – Preserve the source program by exporting a copy.

build_functionality(program: str | PathLike[str] | QuantumCircuit | QCProgram | QCOProgram | JeffProgram | OpenQASMProgram) → Annotated[numpy.typing.NDArray[numpy.complex128], {'shape': (None, None)}]

Build the full unitary matrix of a supported compiler input.

The DD package is managed internally. The matrix is materialized directly into the returned NumPy array without an additional copy. The full matrix grows exponentially, and the caller is responsible for requesting a result that fits in memory.

Raises:
  • MemoryError – When the dense matrix does not fit in memory.

  • ValueError – When the program is unsupported or the matrix dimensions exceed addressable memory.

simulate(program: str | PathLike[str] | QuantumCircuit | QCProgram | QCOProgram | JeffProgram | OpenQASMProgram | QIRProgram | bytes) → Annotated[numpy.typing.NDArray[numpy.complex128], {'shape': (None, )}]

Simulate a program with all inputs bound from the all-zero state.

The program must have no unbound inputs. This function returns the statevector before final measurements. Those measurements must be returned directly or stored in returned classical registers. MQT Core manages the decision diagram internally.

For a custom initial state, resets, or mid-circuit measurement feedback, use QCOProgram.simulate() with an explicit DD package.

Parameters:

program – Compiler input, compiled QIR, or QIR text/bitcode. QIR profile and version are read from module metadata. Other inputs lower to QCO.

Returns:

Full statevector in runtime qubit order, materialized into a NumPy array. Compiled QIR may remove or reorder source qubits.

Raises:
  • MemoryError – When the dense statevector does not fit in memory.

  • ValueError – When the program has unbound inputs, is unsupported for statevector simulation, or the statevector dimensions exceed addressable memory.

  • RuntimeError – When QIR execution fails.

sample(program: str | PathLike[str] | QuantumCircuit | QCProgram | QCOProgram | JeffProgram | OpenQASMProgram | QIRProgram | bytes, shots: int = 1024, seed: int = 0) → dict[str, int]

Sample a supported compiler input or QIR program.

An existing QCO program is used without copying. See QCOProgram.sample() for shot counts, seeds, result ordering, and errors. QIR text and bitcode run in the bundled DDSIM worker, which reads the profile and version from the module metadata. For QIR, use seed 0 for randomness or a positive signed 32-bit integer for reproducible sampling. Execute only trusted QIR: its profile declaration does not validate arbitrary LLVM code.

expectation_values(program: str | PathLike[str] | QuantumCircuit | QCProgram | QCOProgram | JeffProgram | OpenQASMProgram, observables: Sequence[Mapping[str, float]]) → list[float]

Evaluate Pauli observables after translating or converting an input to QCO.

An existing QCO program is used without copying. See QCOProgram.expectation_values() for supported observables, state preparation, and errors.

class ResultLayout

Reconstruct program output bits from device samples.

This map describes classical output order, not qubit placement. Entry i in bits gives the raw sample bit used for program output bit i, or None when that output is always zero. Both indices count from the least significant bit; displayed bitstrings put the most significant bit first.

property raw_width: int

The number of bits in each raw receiver sample.

property bits: list[int | None]

Program output bit to raw sample bit, or None for zero, in LSB-first order.

decode_bits(raw: str) → str

Decode one MSB-first binary sample to logical output order.

decode_counts(counts: Mapping[str, int], width: int | None, shots: int, layout: ResultLayout | None = None) → dict[str, int]

Validate binary counts and reconstruct logical outcomes, ignoring ASCII spaces.

decode_shots(samples: Sequence[str], width: int | None, shots: int, layout: ResultLayout | None = None) → list[str]

Validate and reconstruct logical samples in shot order, ignoring ASCII spaces.

class CompiledProgram

A serialized program ready for QDMI submission.

The object retains the target and format specification used for compilation. Submission checks that the destination supports them before creating a job. Its result layout reconstructs the program’s classical output order from device samples.

property result_width: int | None

Logical bit width, or None for non-bit outputs.

property result_layout: ResultLayout | None

Logical output reconstruction, or None for an identity layout.

property program_format: ProgramFormat

The exact QDMI program format.

property payload: str | bytes

The serialized program.

property target: CompilerTarget

The hardware snapshot used for compilation.

property payload_specification: PayloadSpecification[CompiledProgram]

The execution format and supported features used for compilation.

compile_program(program: _CompilerInput, *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → QCProgram
compile_program(program: _CompilerInput, *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → QCOProgram
compile_program(program: _CompilerInput, *, target: None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → QCProgram
compile_program(program: _CompilerInput, *, target: None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → QCOProgram
compile_program(program: _CompilerInput, *, target: _CompilerTarget | None = None, output: Literal[OutputFormat, OutputFormat], **kwargs: Unpack[_CompileOptions]) → OpenQASMProgram
compile_program(program: _CompilerInput, *, target: _CompilerTarget, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → IQMJSONProgram
compile_program(program: _CompilerInput, *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → JeffProgram
compile_program(program: _CompilerInput, *, target: _CompilerTarget | None = None, output: Literal[OutputFormat, OutputFormat], **kwargs: Unpack[_CompileOptions]) → QIRProgram
compile_program(program: _CompilerInput, *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → bytes
compile_program(program: _CompilerInput, *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → QuantumCircuit
compile_program(program: _CompilerInput, *, target: QDMIBackend, output: None = None, **kwargs: Unpack[_CompileOptions]) → CompiledProgram
compile_program(program: _CompilerInput, *, target: Target, output: None = None, **kwargs: Unpack[_CompileOptions]) → QuantumCircuit
compile_program(program: _CompilerInput, *, target: BackendV2 | Target, output: None = None, **kwargs: Unpack[_CompileOptions]) → QuantumCircuit | CompiledProgram
compile_program(program: _CompilerInput, *, target: TargetEnvironment[_TargetResultT_co], output: None = None, **kwargs: Unpack[_CompileOptions]) → _TargetResultT_co
compile_program(program: _CompilerInput, *, target: Device | str, output: None = None, **kwargs: Unpack[_CompileOptions]) → CompiledProgram
compile_program(program: _ProgramT, *, target: CompilerTarget | None = None, output: None = None, **kwargs: Unpack[_CompileOptions]) → _ProgramT
compile_program(program: str | PathLike[str], *, target: CompilerTarget | None = None, output: None = None, **kwargs: Unpack[_CompileOptions]) → QCProgram | JeffProgram | OpenQASMProgram
compile_program(program: _CompilerInput, *, target: _CompilerTarget | None = None, output: OutputFormat, **kwargs: Unpack[_CompileOptions]) → _CompilerOutput
compile_program(program: Sequence[_CompilerInputT], *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[QCProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[QCOProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[QCProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[QCOProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: _CompilerTarget | None = None, output: Literal[OutputFormat, OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[OpenQASMProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: _CompilerTarget, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[IQMJSONProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[JeffProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: _CompilerTarget | None = None, output: Literal[OutputFormat, OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[QIRProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[bytes]
compile_program(program: Sequence[_CompilerInputT], *, target: _CompilerTarget | None = None, output: Literal[OutputFormat], **kwargs: Unpack[_CompileOptions]) → list[QuantumCircuit]
compile_program(program: Sequence[_CompilerInputT], *, target: QDMIBackend, output: None = None, **kwargs: Unpack[_CompileOptions]) → list[CompiledProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: Target, output: None = None, **kwargs: Unpack[_CompileOptions]) → list[QuantumCircuit]
compile_program(program: Sequence[_CompilerInputT], *, target: BackendV2 | Target, output: None = None, **kwargs: Unpack[_CompileOptions]) → list[QuantumCircuit] | list[CompiledProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: TargetEnvironment[_TargetResultT_co], output: None = None, **kwargs: Unpack[_CompileOptions]) → list[_TargetResultT_co]
compile_program(program: Sequence[_CompilerInputT], *, target: Device | str, output: None = None, **kwargs: Unpack[_CompileOptions]) → list[CompiledProgram]
compile_program(program: Sequence[_ProgramT], *, target: CompilerTarget | None = None, output: None = None, **kwargs: Unpack[_CompileOptions]) → list[_ProgramT]
compile_program(program: Sequence[_SourceT], *, target: CompilerTarget | None = None, output: None = None, **kwargs: Unpack[_CompileOptions]) → list[QCProgram | JeffProgram | OpenQASMProgram]
compile_program(program: Sequence[_CompilerInputT], *, target: _CompilerTarget | None = None, output: OutputFormat, **kwargs: Unpack[_CompileOptions]) → list[_CompilerOutput]

Compile a program or a homogeneous sequence for a gate set or hardware target.

Pass one program to compile it, or a list or tuple of programs of the same input kind to compile a batch. A batch returns a list in input order, even when empty or containing only one program. Subclasses of supported input types are accepted. Strings and paths each represent one program; generators and binary buffers are unsupported.

An explicit output selects each result’s representation. Without it, a Qiskit target or environment using the Qiskit format selects QuantumCircuit. A QDMI backend, device or other device target environment selects CompiledProgram for submit_program(). Otherwise, each input retains its format family: OpenQASM source returns OpenQASMProgram, QC MLIR returns QCProgram, jeff files return JeffProgram, and QCO inputs return optimized QCO.

A target created by CompilerTarget.for_gate_set synthesizes gates without device placement. It preserves program-qubit order and idle qubits, including terminal permutations, and retains the input format family by default. Inputs must have fixed-width entry-block allocations and no static device-site references or layout metadata. Site-specific capabilities are rejected; NativeOperations.from_qiskit imports gates without physical placement.

Compilation takes ownership of typed MLIR inputs, making the original objects unusable. Set copy=True to compile copies when you need the originals again. Source text, paths, Qiskit circuits, and OpenQASM programs remain reusable.

For a batch, input kinds are checked before compilation starts. If compilation fails, no results are returned. Inputs processed up to and including the failing program may already have been consumed; later inputs remain usable.

Parameters:
  • program – Source text, a file path, a Qiskit circuit, a typed compiler program, or a homogeneous sequence of these inputs.

  • target – A CompilerTarget, TargetEnvironment, Qiskit BackendV2 or Target, QDMI Device, or device ID.

  • output – The returned representation. QC_IMPORT and raw QCO are checkpoints before target compilation and cannot be combined with a target.

  • copy – Preserve typed inputs by compiling copies. Defaults to False.

  • qco_pipeline – The QCO pipeline, defaulting to “mqt-qco-default”. Custom pipelines require no target.

  • options – Shared compilation controls.

  • ignore_input_layout – Treat the current wires of a Qiskit input as fresh program qubits. Defaults to False. True requires a Qiskit circuit input.

  • include_output_layout – Attach layout metadata to Qiskit and explicit QPY outputs when available. Defaults to True. Physical wire indices and measurement destinations are preserved either way. False requires Qiskit or explicit QPY output.

For a device, format selection prefers QPY when supported Qiskit is installed, then OpenQASM 3, Adaptive QIR (binary, then text), IQM JSON, Base QIR (binary, then text), and OpenQASM 2. Use a TargetEnvironment to select an exact execution format. An explicit output can instead request a representation for inspection or exchange; it need not be executable on the device. Jeff output does not retain hardware placement.

serialize_program(program: QCProgram | QuantumCircuit, *, target: TargetEnvironment | Device | str) → CompiledProgram

Serialize an already native circuit without compiling or routing it.

Use this for a circuit that already uses the device’s native gates and physical sites. The caller must validate those gates and placements. For programs with fixed physical sites, serialization arranges final measurements in site order and records how to restore the requested output order. Dynamically allocated programs retain their classical outputs. The input remains available after serialization.

Parameters:
  • program – A native Qiskit circuit or QC program with static target sites.

  • target – The destination device, registered device ID, or TargetEnvironment.

submit_program(program: str | PathLike[str] | QuantumCircuit | QCProgram | QCOProgram | JeffProgram | OpenQASMProgram | CompiledProgram, *, target: str | Device, num_shots: int = 1024, program_format: ProgramFormat | None = None, custom1: str | bool | float | bytes | None = None, custom2: str | bool | float | bytes | None = None, custom3: str | bool | float | bytes | None = None, custom4: str | bool | float | bytes | None = None, custom5: str | bool | float | bytes | None = None, options: CompilationOptions | None = None) → Job

Compile source or submit a compiled program to a device.

target accepts a registered device ID or an open device. For source input, program_format selects the exact QDMI execution format, including text or binary QIR; omitting it selects a supported native format.

A compiled program reuses its serialized data after checking compatibility with the destination. Job results use the device’s measurement order. When compiled.result_layout is present, use its decoding methods to restore the program’s output order. Source input that needs this mapping is rejected; compile it explicitly and keep the resulting CompiledProgram.