uniqc.circuit_builder.qcircuit module

Quantum circuit builder with OriginIR and OpenQASM 2.0 output.

This module provides a Circuit class for building quantum circuits programmatically. It supports various quantum gates, controlled operations, dagger (adjoint) blocks, and measurement operations. The circuit can be exported to OriginIR or OpenQASM format.

Key exports:

Circuit: Main quantum circuit builder class. OpcodeType: Type alias for opcode tuples.

class uniqc.circuit_builder.qcircuit.Circuit(qregs=None, param_dict=None)[source]

Bases: object

Quantum circuit builder that generates OriginIR and OpenQASM output.

Variables:
  • used_qubit_list (list[int]) – Qubits referenced in the circuit.

  • circuit_str (str) – Raw string builder used by context managers.

  • max_qubit (int) – Highest qubit index used.

  • qubit_num (int) – Total number of qubits.

  • cbit_num (int) – Total number of classical bits.

  • measure_list (list[int]) – Qubits scheduled for measurement.

  • opcode_list (list[OpCode]) – Internal list of gate opcodes.

  • _qregs (dict[str, QReg]) – Named quantum registers (if created with qregs parameter).

  • rubric: (..) – AnyQuantumCircuit — the universal input type:

Parameters:

:ivar Most public APIs (compile(),: :ivar Simulator, submit_task()): :ivar accept AnyQuantumCircuit, which is a union of: :ivar * Circuit — this class: :ivar * str — OriginIR or OpenQASM 2.0 (auto-detected from content): :ivar * qiskit.QuantumCircuit — converted via QASM round-trip: :ivar * pyqpanda3.QProg — converted via OriginIR round-trip: :ivar Use to_qiskit_circuit() or to_pyqpanda3_circuit() to: :ivar convert back to external formats.:

add_circuit(other)[source]

Add all gates from another circuit into this circuit.

Parameters:

other (Circuit)

Return type:

None

add_gate(operation, qubits, cbits=None, params=None, dagger=False, control_qubits=None, has_param=False, trainable=True, init_params=None)[source]

Add a gate to the circuit.

Parameters:
  • operation (str) – Gate name (e.g., “H”, “CNOT”, “RX”)

  • qubits (QubitInput) – Target qubit(s) - can be int, Qubit, QRegSlice, or list

  • cbits (CbitSpec) – Classical bit(s) for measurement

  • params (ParamSpec) – Gate parameters

  • dagger (bool) – Whether to apply dagger (adjoint)

  • control_qubits (QubitInput) – Control qubit(s)

  • has_param (bool) – If True, automatically create an nn.Parameter for this gate’s rotation angle(s). The created parameter is stored in :pyattr:`_auto_params` and registered in :pyattr:`param_map`. Requires PyTorch.

  • trainable (bool) – Whether the auto-created parameter is trainable (requires_grad). Only used when has_param=True.

  • init_params (object) – Custom initial value(s) for the auto-created parameter. A scalar or list/tuple matching the gate’s num_params. Defaults to Uniform(-π, π) (TorchQuantum convention). Only used when has_param=True.

Return type:

None

barrier(*qubits)[source]

Insert a barrier across the specified qubits.

Parameters:

*qubits (QubitInput) – Qubits to include in the barrier.

Return type:

None

cbit_num: int
property circuit: str

Generate the circuit in OriginIR format.

circuit_str: str
cnot(controller, target)[source]

Apply CNOT (controlled-X) gate.

Parameters:
  • controller (QubitInput) – Control qubit - can be int, Qubit, or QRegSlice

  • target (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

control(*args)[source]

Return a context manager that wraps gates in a CONTROL block.

All gates added inside the with block will be executed only when all specified control qubits are in state |1>.

Parameters:

*args (QubitInput) – One or more control qubits - can be int, Qubit, or QRegSlice

Returns:

A CircuitControlContext context manager.

Raises:

ValueError – No control qubits were supplied.

Return type:

CircuitControlContext

copy()[source]

Return a deep copy of this circuit.

Return type:

Circuit

cp(control, target, lam)[source]

Apply controlled-phase gate (equivalent to CU1).

Parameters:
  • control (QubitInput) – Control qubit.

  • target (QubitInput) – Target qubit.

  • lam (float) – Phase angle in radians.

Return type:

None

crx(control, target, theta)[source]

Apply controlled-RX gate.

Parameters:
  • control (QubitInput) – Control qubit.

  • target (QubitInput) – Target qubit.

  • theta (float) – Rotation angle in radians.

Return type:

None

cry(control, target, theta)[source]

Apply controlled-RY gate.

Parameters:
  • control (QubitInput) – Control qubit.

  • target (QubitInput) – Target qubit.

  • theta (float) – Rotation angle in radians.

Return type:

None

crz(control, target, theta)[source]

Apply controlled-RZ gate.

Parameters:
  • control (QubitInput) – Control qubit.

  • target (QubitInput) – Target qubit.

  • theta (float) – Rotation angle in radians.

Return type:

None

cswap(q1, q2, q3)[source]

Apply CSWAP (Fredkin) gate to three qubits.

Parameters:
  • q1 (QubitInput) – Control qubit - can be int, Qubit, or QRegSlice

  • q2 (QubitInput) – First target qubit

  • q3 (QubitInput) – Second target qubit

Return type:

None

cu(control, target, theta, phi, lam)[source]

Apply controlled-U3 gate.

Parameters:
  • control (QubitInput) – Control qubit.

  • target (QubitInput) – Target qubit.

  • theta (float) – Rotation angle in radians.

  • phi (float) – Phi angle in radians.

  • lam (float) – Lambda angle in radians.

Return type:

None

cx(controller, target)[source]

Apply CX gate (alias for CNOT).

Parameters:
  • controller (QubitInput) – Control qubit - can be int, Qubit, or QRegSlice

  • target (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

cz(q1, q2)[source]

Apply controlled-Z gate to two qubits.

Parameters:
  • q1 (QubitInput) – First qubit - can be int, Qubit, or QRegSlice

  • q2 (QubitInput) – Second qubit - can be int, Qubit, or QRegSlice

Return type:

None

dagger()[source]

Return a context manager that wraps gates in a DAGGER block.

All gates added inside the with block will be conjugate-transposed (adjoint).

Returns:

A CircuitDagContext context manager.

Return type:

CircuitDagContext

property depth: int

Calculate the depth of the quantum circuit.

classmethod from_originir(originir_str)[source]

Create a Circuit from an OriginIR string.

Parameters:

originir_str (str) – OriginIR formatted circuit string.

Returns:

A new Circuit instance.

Return type:

Circuit

classmethod from_originir_ext(originir_ext_str)[source]

Create a Circuit from an OriginIR-ext string.

Equivalent to from_originir() — both parse the same superset syntax. This alias makes the intent explicit when working with OriginIR-ext source.

Parameters:

originir_ext_str (str)

Return type:

Circuit

classmethod from_qasm(qasm_str)[source]

Create a Circuit from an OpenQASM 2.0 string.

Parameters:

qasm_str (str) – OpenQASM 2.0 formatted circuit string.

Returns:

A new Circuit instance.

Return type:

Circuit

get_matrix()[source]

Return the full unitary matrix of this circuit as np.ndarray.

Qubit 0 is treated as the least-significant bit of the statevector index. The returned matrix uses the convention state_out = U @ state_in and gates are applied in the same order as opcode_list.

Raises:

NotMatrixableError – If the circuit contains MEASURE / CONTROL / DAGGER scope opcodes that have no unitary representation.

get_param(opcode_idx)[source]

Get the tensor parameter registered for opcode_idx.

Raises:

KeyError – If no tensor is registered for this opcode.

Parameters:

opcode_idx (int)

get_params_by_gate(gate_name)[source]

Return auto-created parameters for gates named gate_name.

Example:

>>> c = Circuit(2)
>>> c.ry(0, has_param=True)
>>> c.ry(1, has_param=True)
>>> c.rz(0, has_param=True)
>>> len(c.get_params_by_gate("RY"))
2
Parameters:

gate_name (str)

Return type:

list

get_qreg(name)[source]

Get a named quantum register by name.

Parameters:

name (str) – Register name

Returns:

QReg object

Raises:

KeyError – If register name not found

Return type:

QReg

h(qn)[source]

Apply single-qubit Hadamard gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

property has_param: bool

TorchQuantum-aligned alias for has_tensor_params().

Returns True only when at least one parameter is a tensor (i.e., actually trainable). Pure Python-float parameters return False.

This is a no-argument property, distinct from the has_param keyword argument on add_gate() / convenience gate methods (which opts-in to auto-creating an nn.Parameter for that gate).

has_tensor_params()[source]

Check whether this circuit has any registered tensor parameters.

Return type:

bool

identity(qn)[source]

Apply the identity (no-op) gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

iswap(q1, q2)[source]

Apply iSWAP gate to two qubits.

Parameters:
  • q1 (QubitInput) – First qubit - can be int, Qubit, or QRegSlice

  • q2 (QubitInput) – Second qubit - can be int, Qubit, or QRegSlice

Return type:

None

max_qubit: int
measure(*qubits)[source]

Schedule qubits for measurement.

Each qubit may be measured at most once per circuit. Calling measure(0) and then measure(0) again — or passing the same qubit twice in a single call (measure(0, 0)) — raises ValueError. This guards against the common mistake of using measure(0, 1) to measure two qubits when cbit is meant to be implicit; use one measure(q) call per qubit instead, or pass distinct qubit indices.

Parameters:

*qubits (QubitInput) – One or more qubits to measure — can be int, Qubit, or QRegSlice.

Raises:

ValueError – Called inside an active CONTROL or DAGGER context block, or any qubit would be measured more than once.

Return type:

None

measure_list: list[int]
opcode_list: list[OpCode]
property originir: str

Generate the circuit in OriginIR format.

property originir_official: str

Generate the circuit in strict official OriginIR format.

p(qn, lam)[source]

Apply phase gate P(λ), equivalent to U1.

Parameters:
  • qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

  • lam (float) – Phase angle in radians.

Return type:

None

property param_dict: dict[str, object] | None

The named parameter dictionary, if provided at construction.

property params: list

All auto-created nn.Parameter tensors (flat list for optimizers).

phase2q(q1, q2, theta1, theta2, thetazz)[source]

Apply two-qubit phase gate with local and ZZ terms.

Parameters:
  • q1 (QubitInput) – First qubit - can be int, Qubit, or QRegSlice

  • q2 (QubitInput) – Second qubit - can be int, Qubit, or QRegSlice

  • theta1 (float) – Local phase angle for q1 in radians.

  • theta2 (float) – Local phase angle for q2 in radians.

  • thetazz (float) – ZZ interaction angle in radians.

Return type:

None

property qasm: str

Generate the circuit in OpenQASM format.

qram_call(name, *qubits)[source]

Add a QRAM call to the circuit.

Parameters:
  • name (str) – Name of a previously declared QRAM.

  • *qubits (QubitInput) – Qubit list (addr bits followed by data bits).

Return type:

None

qram_declare(name, addr_size, data_size)[source]

Declare a QRAM with the given address and data sizes.

Parameters:
  • name (str) – Unique name for this QRAM.

  • addr_size (int) – Number of address qubits.

  • data_size (int) – Number of data qubits.

Return type:

None

property qregs: dict[str, QReg]

Return the named quantum registers.

qubit_num: int
record_qubit(qubits)[source]

Record the qubits used in the circuit.

Parameters:

qubits (int | list[int])

Return type:

None

remapping(mapping)[source]

Create a new circuit with qubits remapped according to mapping.

Parameters:

mapping (dict[int, int])

Return type:

Circuit

rphi(qn, theta=None, phi=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply RPhi rotation gate.

Parameters:
Return type:

None

rx(qn, theta=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply RX rotation gate.

Parameters:
  • qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

  • theta (float) – Rotation angle in radians. Omit when has_param=True.

  • has_param (bool) – Auto-create an nn.Parameter for this gate.

  • trainable (bool) – Whether the parameter is trainable (only with has_param).

  • init_params (object) – Custom initial value. Default: Uniform(-π, π).

Return type:

None

ry(qn, theta=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply RY rotation gate.

Parameters:
Return type:

None

rz(qn, theta=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply RZ rotation gate.

Parameters:
Return type:

None

s(qn)[source]

Apply S (phase) gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

sdg(qn)[source]

Apply S-dagger (inverse phase) gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

set_control(*args)[source]

Manually open a CONTROL block (low-level API; prefer control()).

Parameters:

*args (QubitInput) – Control qubits - can be int, Qubit, or QRegSlice

Return type:

None

set_dagger()[source]

Manually open a DAGGER block (low-level API; prefer dagger()).

Return type:

None

set_param(opcode_idx, tensor)[source]

Register a differentiable tensor for the parametric gate at opcode_idx.

Parameters:
Raises:

IndexError – If opcode_idx is out of range.

Return type:

None

set_param_last(tensor)[source]

Register a tensor for the most recently added gate.

Convenience wrapper around :pymeth:`set_param` for the common pattern of registering a parameter immediately after adding a gate.

Returns:

The opcode index that was registered.

Raises:

IndexError – If the circuit has no gates.

Return type:

int

swap(q1, q2)[source]

Apply SWAP gate to two qubits.

Parameters:
  • q1 (QubitInput) – First qubit - can be int, Qubit, or QRegSlice

  • q2 (QubitInput) – Second qubit - can be int, Qubit, or QRegSlice

Return type:

None

sx(qn)[source]

Apply square-root-of-X (SX) gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

sxdg(qn)[source]

Apply conjugate-transpose of SX gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

t(qn)[source]

Apply T gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

tdg(qn)[source]

Apply T-dagger (inverse T) gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

property tensor_params: list

Return all registered tensor parameters (for passing to an optimizer).

to_extended_originir()[source]

Export the circuit in extended OriginIR format (full form with QINIT/CREG/MEASURE).

Return type:

str

to_originir()[source]

Export the circuit as an OriginIR string.

Return type:

str

to_originir_official()[source]

Export the circuit as strict official OriginIR.

Extended gates are decomposed to the official gate set, and inline dagger / controlled_by syntax is replaced with block-level DAGGER / CONTROL delimiters. The output is suitable for submission to OriginQ cloud.

Return type:

str

to_pyqpanda3_circuit()[source]

Convert to a pyqpanda3 QProg.

Returns:

pyqpanda3 QProg equivalent of this circuit.

Raises:

ImportError – If pyqpanda3 is not installed.

to_qasm()[source]

Export the circuit as an OpenQASM 2.0 string.

Return type:

str

to_qiskit_circuit()[source]

Convert to a qiskit.QuantumCircuit.

Returns:

qiskit.QuantumCircuit equivalent of this circuit.

Raises:

ImportError – If qiskit is not installed.

toffoli(q1, q2, q3)[source]

Apply Toffoli (CCNOT) gate to three qubits.

Parameters:
  • q1 (QubitInput) – First control qubit

  • q2 (QubitInput) – Second control qubit

  • q3 (QubitInput) – Target qubit

Return type:

None

u1(qn, lam=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply U1 single-parameter unitary gate.

Parameters:
Return type:

None

u2(qn, phi=None, lam=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply U2 two-parameter unitary gate.

Parameters:
Return type:

None

u3(qn, theta=None, phi=None, lam=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply U3 three-parameter unitary gate.

Parameters:
Return type:

None

unset_control()[source]

Manually close a CONTROL block (low-level API; prefer control()).

Return type:

None

unset_dagger()[source]

Manually close a DAGGER block (low-level API; prefer dagger()).

Return type:

None

used_qubit_list: list[int]
uu15(q1, q2, params)[source]

Apply general two-qubit UU15 gate with 15 parameters.

Parameters:
  • q1 (QubitInput) – First qubit - can be int, Qubit, or QRegSlice

  • q2 (QubitInput) – Second qubit - can be int, Qubit, or QRegSlice

  • params (list[float]) – List of 15 rotation parameters in radians.

Return type:

None

x(qn)[source]

Apply Pauli-X (NOT) gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

xx(q1, q2, theta=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply XX Ising interaction gate.

Parameters:
  • q1 (QubitInput)

  • q2 (QubitInput)

  • theta (float)

  • has_param (bool)

  • trainable (bool)

  • init_params (object)

Return type:

None

xy(q1, q2, theta)[source]

Apply XY Ising interaction gate.

Parameters:
  • q1 (QubitInput) – First qubit - can be int, Qubit, or QRegSlice

  • q2 (QubitInput) – Second qubit - can be int, Qubit, or QRegSlice

  • theta (float) – Interaction angle in radians.

Return type:

None

y(qn)[source]

Apply Pauli-Y gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

yy(q1, q2, theta=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply YY Ising interaction gate.

Parameters:
  • q1 (QubitInput)

  • q2 (QubitInput)

  • theta (float)

  • has_param (bool)

  • trainable (bool)

  • init_params (object)

Return type:

None

z(qn)[source]

Apply Pauli-Z gate to qubit.

Parameters:

qn (QubitInput) – Target qubit - can be int, Qubit, or QRegSlice

Return type:

None

zz(q1, q2, theta=None, *, has_param=False, trainable=True, init_params=None)[source]

Apply ZZ Ising interaction gate.

Parameters:
  • q1 (QubitInput)

  • q2 (QubitInput)

  • theta (float)

  • has_param (bool)

  • trainable (bool)

  • init_params (object)

Return type:

None

class uniqc.circuit_builder.qcircuit.CircuitControlContext(c, control_list)[source]

Bases: object

Context manager for controlled gate blocks.

Parameters:
c: Circuit
control_list: tuple[int, ...]
class uniqc.circuit_builder.qcircuit.CircuitDagContext(c)[source]

Bases: object

Context manager for dagger (adjoint) gate blocks.

Parameters:

c (Circuit)

c: Circuit