API reference¶
Core¶
This module defines Circuit and the setting for circuit. Modernized for PyTorch Tensor Network backend integration in 2026.
- class blueqat.circuit.Circuit(n_qubits=0, ops=None)[source]¶
Store the gate operations and call the backends.
- dagger(ignore_measurement=False)[source]¶
Make Hermitian conjugate of the circuit.
If the circuit contains measurement or reset (which have no Hermitian conjugate), ValueError is raised, unless ignore_measurement is True, in which case those operations are simply dropped.
- run(backend=None, *args, **kwargs)[source]¶
Run the circuit. Passes parameters to the PyTorch-based backend.
- statevector(backend=None, **kwargs)[source]¶
Run the circuit and get a statevector as a PyTorch Tensor to keep gradients intact.
- Parameters:
backend (BackendUnion)
- Return type:
Tensor
- oneshot(backend=None, **kwargs)[source]¶
Run the circuit once and return the post-measurement statevector together with the single measured bitstring.
- depth()[source]¶
Circuit depth: length of the longest gate sequence on any qubit path, counting each expanded gate application (as in Qiskit). Barriers don’t add depth.
- Return type:
- probs(qubits=None, backend=None, **kwargs)[source]¶
Measurement probabilities of the circuit’s final state, optionally marginalized onto qubits (as in PennyLane’s qml.probs).
Returns a tensor of length 2**len(qubits) where index bit j is the outcome of qubits[j] (the first listed qubit is the least-significant bit, matching the SDK-wide convention). Differentiable.
- expect(hamiltonian, backend=None, **kwargs)[source]¶
Expectation value <psi|H|psi> of a Pauli-expression Hamiltonian on the circuit’s final state. Differentiable.
- Parameters:
hamiltonian (Any)
backend (BackendUnion)
- Return type:
Tensor
- block(name)[source]¶
Group the operations appended inside the with body into a named, nestable block (as in the sub-circuits of Shor’s algorithm):
c = Circuit(4) with c.block(“QFT”):
c.h[0].cphase(math.pi / 2)[0, 1] …
Blocks change nothing about execution – every backend transparently sees the inner gates – but the structure is kept in repr(), Circuit.tree(), and survives dagger() (as a mirrored block named name + ‘†’).
- Parameters:
name (str)
- Return type:
_BlockContext
- append_block(name, subcircuit, offset=0)[source]¶
Append an existing circuit as a named block.
offset shifts every qubit index of subcircuit, so a library circuit built on qubits 0..k can be placed anywhere. Shifting resolves slice targets against subcircuit.n_qubits and preserves any nested block structure inside subcircuit.
- tree()[source]¶
A text rendering of the circuit’s nested block structure:
Circuit(4) ├─ h[0] └─ QFT
├─ cphase(1.5708)[0, 1] └─ …
- Return type:
- ancilla(n=1, pos=None, stop=None, reset=True)[source]¶
Context manager allocating temporary ancilla qubit(s) for use inside the with block.
By default, appends n fresh qubits past the circuit’s current width:
- with c.ancilla() as a:
c.cx[0, a[0]]
pos/stop instead pin the ancilla range to specific qubit indices (range(pos, stop); stop defaults to pos + n):
- with c.ancilla(pos=4, stop=6, reset=True) as a:
c.cx[3, a[0]]
If reset is true (the default), a reset gate is appended for each ancilla qubit on exiting the block, so they’re back at
|0>and safe to reuse elsewhere in the circuit.
- class blueqat.circuit.BlueqatGlobalSetting[source]¶
Setting for Blueqat.
- static register_gate(name, gateclass, allow_overwrite=False)[source]¶
Register new gate to gate set.
- static unregister_gate(name)[source]¶
Unregister a gate from gate set.
- Parameters:
name (str)
- Return type:
None
- static unregister_backend(name)[source]¶
Unregister a backend.
- Parameters:
name (str)
- Return type:
None
gate module implements quantum gate operations. Modernized for PyTorch Tensor Network integration in 2026.
- class blueqat.gate.Operation(targets, params=())[source]¶
Abstract quantum circuit operation class.
- class blueqat.gate.OneQubitGate(targets, params=())[source]¶
Abstract quantum gate class for 1 qubit gate.
- class blueqat.gate.TwoQubitGate(targets, params=())[source]¶
Abstract quantum gate class for 2 qubits gate.
- property n_qargs¶
Number of qubit arguments of this gate.
- class blueqat.gate.HGate(targets, params=())[source]¶
Hadamard gate
- class blueqat.gate.IGate(targets, params=())[source]¶
Identity gate
- class blueqat.gate.Mat1Gate(targets, mat)[source]¶
Arbitrary 2x2 matrix gate
- Parameters:
mat (Tensor)
- class blueqat.gate.PhaseGate(targets, theta)[source]¶
Phase gate
- class blueqat.gate.RXGate(targets, theta)[source]¶
Rotate-X gate
- class blueqat.gate.RYGate(targets, theta)[source]¶
Rotate-Y gate
- class blueqat.gate.RZGate(targets, theta)[source]¶
Rotate-Z gate
- class blueqat.gate.SGate(targets, params=())[source]¶
S gate
- class blueqat.gate.SDagGate(targets, params=())[source]¶
Dagger of S gate
- class blueqat.gate.SXGate(targets, params=())[source]¶
sqrt(X) gate
- class blueqat.gate.SXDagGate(targets, params=())[source]¶
sqrt(X)† gate
- class blueqat.gate.TGate(targets, params=())[source]¶
T gate
- class blueqat.gate.TDagGate(targets, params=())[source]¶
Dagger of T gate
- class blueqat.gate.ToffoliGate(targets, params=())[source]¶
Toffoli (CCX) gate
- property n_qargs¶
Number of qubit arguments of this gate.
- class blueqat.gate.UGate(targets, theta, phi, lam, gamma=0.0)[source]¶
Arbitrary 1 qubit unitary gate
- class blueqat.gate.XGate(targets, params=())[source]¶
Pauli’s X gate
- class blueqat.gate.YGate(targets, params=())[source]¶
Pauli’s Y gate
- class blueqat.gate.ZGate(targets, params=())[source]¶
Pauli’s Z gate
- class blueqat.gate.CCZGate(targets, params=())[source]¶
2-Controlled Z gate
- property n_qargs¶
Number of qubit arguments of this gate.
- class blueqat.gate.CHGate(targets, params=())[source]¶
Controlled-H gate
- class blueqat.gate.CPhaseGate(targets, theta)[source]¶
Controlled Phase gate
- class blueqat.gate.CRXGate(targets, theta)[source]¶
Controlled RX gate
- class blueqat.gate.CRYGate(targets, theta)[source]¶
Controlled RY gate
- class blueqat.gate.CRZGate(targets, theta)[source]¶
Controlled RZ gate
- class blueqat.gate.CSwapGate(targets, params=())[source]¶
Controlled SWAP gate
- property n_qargs¶
Number of qubit arguments of this gate.
- class blueqat.gate.CUGate(targets, theta, phi, lam, gamma=0.0)[source]¶
Controlled-U gate
- class blueqat.gate.CXGate(targets, params=())[source]¶
Controlled-X (CNOT) gate
- class blueqat.gate.CYGate(targets, params=())[source]¶
Controlled-Y gate
- class blueqat.gate.CZGate(targets, params=())[source]¶
Controlled-Z gate
- class blueqat.gate.RXXGate(targets, theta)[source]¶
Rotate-XX gate
- class blueqat.gate.RYYGate(targets, theta)[source]¶
Rotate-YY gate
- class blueqat.gate.RZZGate(targets, theta)[source]¶
Rotate-ZZ gate
- class blueqat.gate.SwapGate(targets, params=())[source]¶
Swap gate
- class blueqat.gate.ZZGate(targets)[source]¶
ZZ gate
- class blueqat.gate.ZZDagGate(targets)[source]¶
Dagger of ZZ gate
- class blueqat.gate.ISwapGate(targets, params=())[source]¶
iSWAP gate: swaps two qubits and phases the swapped amplitudes by i.
- class blueqat.gate.ISwapDagGate(targets, params=())[source]¶
Dagger of iSWAP gate.
- class blueqat.gate.ExchangeGate(targets, theta)[source]¶
Heisenberg exchange pulse, the native primitive of exchange-only (EO) spin-qubit hardware: U(theta) = exp(-i theta/2 (SWAP - I)), i.e. identity on the triplet (symmetric) subspace and phase e^{i theta} on the singlet.
theta = J*t is the integrated pulse area (exchange integral x duration); theta = pi gives an exact SWAP, theta = pi/2 a sqrt-SWAP up to phase. Symmetric in its two qubits.
- class blueqat.gate.Barrier(targets, params=())[source]¶
Barrier: a no-op marker separating circuit sections (as in Qiskit and OpenQASM). Simulation backends treat it as the identity via its empty fallback; the QASM output backend emits a real barrier statement.
- class blueqat.gate.GateBlock(name, ops=None)[source]¶
A named group of operations, nestable to arbitrary depth.
Blocks give circuits the hierarchical structure of real algorithms (Shor = init + modular exponentiation + inverse QFT, each built from smaller blocks) without changing how they execute: every backend sees the inner operations through fallback(), so simulation, QASM output and transpilation are unaffected. The structure shows up in repr() and in Circuit.tree().
Build blocks with Circuit.block(name) (a context manager) or Circuit.append_block(name, subcircuit).
- class blueqat.gate.Measurement(targets, options)[source]¶
Measurement operation
Pauli operators, VQE and QAOA¶
Integrated Quantum Operators, Utilities, VQE, and QAOA module with PyTorch. Refactored and merged into a unified utils.py module with robust Autograd tracking.
- class blueqat.utils.Term(ops, coeff)[source]¶
- blueqat.utils.term_from_chars(chars)[source]¶
Make Pauli’s Term from chars written as ‘X’, ‘Y’, ‘Z’ or ‘I’.
- blueqat.utils.commutator(expr1, expr2)[source]¶
Returns [expr1, expr2] = expr1 * expr2 - expr2 * expr1.
- blueqat.utils.is_commutable(expr1, expr2, eps=1e-08)[source]¶
Test whether expr1 and expr2 are commutable.
- blueqat.utils.ignore_global_phase(statevec)[source]¶
Multiply e^-iθ to statevec where θ is a phase of first non-zero element.
- Parameters:
statevec (Tensor)
- Return type:
Tensor
- blueqat.utils.gen_gray_controls(n)[source]¶
Generate an iterator which returns bit indices for constructing Gray code based controlled gate.
- blueqat.utils.check_unitarity(mat)[source]¶
Check whether mat is a unitary matrix.
- Parameters:
mat (Tensor)
- Return type:
- blueqat.utils.sqrt_2x2_matrix(mat)[source]¶
Returns square root of a 2x2 matrix.
Reference: https://en.wikipedia.org/wiki/Square_root_of_a_2_by_2_matrix
- Parameters:
mat (Tensor)
- Return type:
Tensor
- class blueqat.utils.AnsatzBase(hamiltonian, n_params)[source]¶
Base class for Variational Quantum Eigensolver Ansatz using PyTorch.
- make_sparse(sparse=True, device=None)[source]¶
- Parameters:
sparse (bool)
device (device | None)
- Return type:
None
- get_energy(circuit, sampler)[source]¶
Calculate energy expectation value from circuit and sampler with Autograd support.
Whether the result carries a gradient back to circuit’s parameters depends on sampler: an exact sampler (e.g. non_sampling_sampler) keeps the autograd graph intact, while a genuinely stochastic one (e.g. one built from get_measurement_sampler) does not – real shot noise isn’t differentiable, so that is expected, not a bug.
- class blueqat.utils.QaoaAnsatz(hamiltonian, step=1, init_circuit=None, mixer=None)[source]¶
- class blueqat.utils.VqeResult(vqe: ForwardRef('Vqe') | None = None, params: torch.Tensor | None = None, circuit: blueqat.circuit.Circuit | None = None, _probs: Dict[Tuple[int, ...], float] | None = None)[source]¶
- Parameters:
- class blueqat.utils.Vqe(ansatz, optimizer_cls=<class 'torch.optim.adam.Adam'>, optimizer_kwargs=None, sampler=None)[source]¶
- Parameters:
- blueqat.utils.expect(qubits, meas)[source]¶
Marginal probabilities of meas qubits, as gradient-carrying tensors (not plain floats) so that AnsatzBase.get_energy can backprop through them when qubits came from a differentiable circuit run.
Backends¶
Base class and plugin registration system for Blueqat backends.
- class blueqat.backends.backendbase.Backend[source]¶
Abstract base class for all Blueqat simulation and compilation backends.
run has a default template-method implementation: a backend that doesn’t override run directly can instead define per-gate gate_{lowername}(self, gate, ctx) hook methods (e.g. gate_x, gate_cx), plus optionally _preprocess_run/_postprocess_run to build/consume its own ctx. See QasmOutputBackend for an example. Backends like TorchBackend that need a different execution model override run directly instead.
- blueqat.backends.backendbase.register_backend(name, backend_cls, overwrite=False)[source]¶
Register a new backend plugin dynamically.
This allows external packages (like a quimb or cuQuantum connector) to register themselves into Blueqat at runtime.
- blueqat.backends.backendbase.get_backend(name)[source]¶
Retrieve an instance of the registered backend by name.
Unified Differentiable Quantum Simulator Backend using PyTorch. Supports both pure Statevector and ultra-scalable Tensor Network contraction. Leverages opt_einsum for path optimization while executing fully via PyTorch.
- class blueqat.backends.torch_backend.TorchBackend(mode='tensornet', device=None, dtype=None)[source]¶
Unified PyTorch simulator backend supporting Autograd optimization.
- Parameters:
mode (str)
device (device | None)
dtype (dtype | None)
Exchange-only spin qubits¶
The 3-spin decoherence-free-subsystem (DFS) encoding of exchange-only qubits.
One logical qubit lives in the total-spin S=1/2 sector of 3 physical spins
(spin up = |0>, physical qubit 3i+k is spin k of logical qubit i, qubit 0 is
the least-significant statevector bit, as everywhere in this SDK):
|0_L>=|singlet(0,1)>|up(2)>|1_L>= sqrt(2/3)|T+(0,1)>|down(2)>- sqrt(1/3)|T0(0,1)>|up(2)>
Each logical state comes in two “gauge” copies, the total-Sz m=+1/2 sector above and its m=-1/2 partner; exchange acts identically on both, and any population in the fully symmetric S=3/2 quadruplet is leakage.
- blueqat.eo.encoding.codeword_basis(m='+')[source]¶
(8, 2) matrix whose columns are
|0_L>,|1_L>of the requested gauge sector (‘+’ for total Sz = +1/2, ‘-’ for -1/2).- Parameters:
m (str)
- Return type:
Tensor
- blueqat.eo.encoding.encode_state(logical_amplitudes, m='+')[source]¶
Encode a product state of logical qubits into 3n physical spins.
logical_amplitudes[i] is the (alpha, beta) pair of logical qubit i. Returns the 2**(3n) statevector (logical qubit 0’s spins are physical qubits 0..2, i.e. the least-significant bits).
- blueqat.eo.encoding.leakage(state, triple=0)[source]¶
Population outside the S=1/2 subspace of the given 3-spin triple, i.e. the weight in its fully symmetric S=3/2 quadruplet.
- blueqat.eo.encoding.logical_action(unitary8, m='+', atol=1e-09)[source]¶
Extract the 2x2 logical action of a 3-spin (8x8) unitary.
Raises ValueError if the unitary leaks out of the logical subspace of the requested gauge sector (the extracted block would then be non-unitary).
- blueqat.eo.encoding.logical_fidelity(actual, target)[source]¶
Phase-insensitive gate fidelity
|tr(A^dagger T)|^2 / d^2of two equally-sized unitaries.- Parameters:
actual (Tensor)
target (Tensor)
- Return type:
- blueqat.eo.encoding.two_qubit_codeword_basis(m1, m2)[source]¶
(64, 4) basis of a 2-logical-qubit (6-spin) sector: columns are
|00_L>,|01_L>,|10_L>,|11_L>with gauge m1 for logical qubit 0 (spins 0-2) and m2 for logical qubit 1 (spins 3-5).
- blueqat.eo.encoding.two_qubit_logical_action(unitary64, m1='+', m2='+', atol=1e-09)[source]¶
Extract the 4x4 logical action of a 6-spin unitary on the encoded pair.
Analytic exchange-pulse sequences for logical gates on encoded EO qubits.
A sequence is a list of ((i, j), theta) pairs in application order, where (i, j) are physical spin indices within the logical qubits involved and theta is the exchange pulse area for Circuit().exch(theta)[i, j]. All logical gates are exact up to a global phase.
Single-qubit tables and the serial Fong-Wandzura CNOT follow the constant- amplitude constructions used in eoqrid (MIT, https://github.com/samn33/eoqrid) and Weinstein et al., Nature 615, 817 (2023); the CNOT runs on the 6-spin linear chain t0-t1-t2-c2-c1-c0 (nearest-neighbor pulses only) in 28 pulses.
- blueqat.eo.sequences.rz_sequence(phase, offset=0)[source]¶
Logical RZ(phase): a single pulse on the (0,1) pair (the singlet in
|0_L>picks up e^{i theta}, giving RZ(-theta) up to global phase).
- blueqat.eo.sequences.y_sequence(offset=0)[source]¶
Logical Y = X after Z (equal to iY, a global phase).
- blueqat.eo.sequences.ry_sequence(phase, offset=0)[source]¶
Logical RY(phase) = S RX(phase) S^dagger (applied right-to-left).
- blueqat.eo.sequences.cx_sequence(control_offset, target_offset)[source]¶
Serial Fong-Wandzura CNOT: 28 exchange pulses on the linear chain t0-t1-t2-c2-c1-c0 (control spins c*, target spins t*), exact up to a global phase and independent of both qubits’ gauge states.
- blueqat.eo.sequences.cz_sequence(control_offset, target_offset)[source]¶
Encoded CZ = (I x H) CX (I x H) on the target logical qubit.
- blueqat.eo.sequences.swap_sequence(offset_a, offset_b)[source]¶
Encoded SWAP: swap the two triples spin-by-spin (3 full-SWAP pulses).
- blueqat.eo.sequences.sequence_to_circuit(sequence, n_physical_qubits)[source]¶
Build an exchange-pulse Circuit from a sequence of ((i, j), theta).
Differentiable synthesis of logical EO gates as short exchange-pulse sequences, using PyTorch autograd (the whole pipeline – pulse areas -> exchange matrices -> logical block -> fidelity – is differentiable).
This is what allows going beyond the fixed analytic gate tables: any target SU(2) can be compiled into a few constant-amplitude pulses.
- blueqat.eo.optimizer.synthesize_1q(target, n_pulses=4, n_restarts=8, max_iter=400, fidelity_goal=0.999999999, seed=0, offset=0)[source]¶
Synthesize a logical 1-qubit gate as n_pulses exchange pulses alternating on pairs (0,1) and (1,2) of one triple.
Returns the pulse sequence in application order (compatible with sequences.sequence_to_circuit). Raises RuntimeError if no restart reaches fidelity_goal – some targets need more pulses (4 suffices for generic SU(2) with these two 120-degree-tilted rotation axes).
- blueqat.eo.optimizer.synthesize_2q(target, pairs, initial_thetas=None, n_restarts=4, max_iter=1000, fidelity_goal=0.99999999, seed=0)[source]¶
Synthesize an encoded 2-logical-qubit gate (logical qubit 0 on spins 0-2, logical qubit 1 on spins 3-5) as exchange pulses on the given pair pattern.
The loss demands a gauge-independent, gauge-preserving implementation: the logical block must equal target with one common phase in all four total-Sz sectors (leakage automatically suppresses the fidelity, so it needs no separate penalty). Note that some natural constructions are gauge-permuting instead – e.g. the 3-pulse physical triple swap realizes an encoded SWAP but exchanges the two gauge states with it – and such gates cannot (and need not) be found by this loss.
Pass initial_thetas to refine a known sequence – e.g. to re-calibrate the Fong-Wandzura angles after hardware perturbations – instead of starting from random pulses; from-scratch synthesis of long 2-qubit sequences is a hard non-convex problem and may need many restarts.
- blueqat.eo.optimizer.quantize_sequence(sequence, step)[source]¶
Snap every pulse area to the nearest multiple of step and drop pulses that round to zero – the operational constraint of constant- amplitude hardware whose pulse durations come in discrete clock ticks.
Check the result’s fidelity yourself (e.g. via encoding.logical_action); a coarse step degrades the gate.
Pulse schedules: the hardware-facing time-resolved view of an exchange circuit.
to_schedule turns a sequence of exchange pulses (or a Circuit of exch gates) into a JSON-compatible dict with explicit start times, packing pulses on disjoint spin pairs in parallel (ASAP scheduling; pulses on disjoint pairs commute, so this never changes the unitary). The format is designed to be handed to pulse-level control stacks (e.g. spinQICK-style backends) or submitted through blueqat.cloud.
Schema:
{
"format": "blueqat-eo-schedule",
"version": "1",
"n_spins": 6,
"amplitude": 1.0, # exchange integral J during a pulse
"pulses": [
{"start": 0.0, "duration": 3.14159, "pair": [0, 1], "theta": 3.14159},
...
],
"total_duration": 12.56637
}
Durations are theta / amplitude (constant-amplitude pulses: the pulse area theta = J * t is what fixes the gate).
- blueqat.eo.schedule.to_schedule(source, amplitude=1.0, n_spins=0)[source]¶
Build a time-resolved pulse schedule with ASAP parallel packing.
Each pulse starts as soon as both of its spins are free; pulses touching disjoint pairs run simultaneously. Relative order of pulses sharing a spin is preserved, so the scheduled unitary equals the sequential one.
The exchange unitary is exactly 2*pi-periodic in the pulse area, so theta is canonicalized into [0, 2*pi) – a negative area (e.g. from a daggered circuit) becomes the equivalent positive-duration pulse, and pulses whose area is a multiple of 2*pi (no-ops) are dropped.
- blueqat.eo.schedule.from_schedule(schedule)[source]¶
Rebuild an exchange-pulse Circuit from a schedule dict.
Pulses are replayed in order of start time (ties broken by list order); since only disjoint pairs ever overlap, this reproduces the original unitary exactly.
- blueqat.eo.schedule.schedule_stats(schedule)[source]¶
Summary numbers: pulse count, serial vs scheduled duration, speedup.
The ‘eo’ backend: transpile a logical Circuit into exchange pulses.
import blueqat.eo # registers the backend physical = Circuit(2).h[0].cx[0, 1].run(backend=’eo’)
Logical qubit i is encoded in physical spins 3i, 3i+1, 3i+2, and the output is an ordinary Circuit containing only exch pulses, runnable on any simulation backend. All logical gates are exact up to global phase.
Topology note: the emitted pulses assume any pair inside the two triples involved in a gate can be pulsed (in particular, the Fong-Wandzura CNOT’s bridge pulse connects spin 3c+2 with spin 3t+2, and the encoded SWAP pulses pair the triples spin-by-spin). This is always fine for simulation; mapping onto strict nearest-neighbor-only hardware additionally requires dot orientation assignment and spin-level SWAP routing, which is future work (cf. exchange-pulse-optimizer).
Cloud¶
Groundwork for API-key based access to the Blueqat cloud service.
Credential resolution order:
An explicit configure(api_key=…) call in the current process.
The BLUEQAT_API_KEY environment variable.
The config file ~/.blueqat/config.json (written by save_api_key, created with owner-only permissions).
The cloud backend registered by this module serializes a circuit to the JSON wire format (see blueqat.circuit_funcs.json_serializer) and hands it to a transport. Until the public endpoint is live, the default transport raises a clear error; tests and early integrations can inject their own transport with configure(transport=…).
Importing this module registers the backend, so after import blueqat.cloud a circuit can be submitted with Circuit(…).run(backend=’cloud’).
- blueqat.cloud.config_path()[source]¶
Path of the persistent config file (override dir with BLUEQAT_CONFIG_DIR).
- Return type:
- blueqat.cloud.save_api_key(api_key, endpoint=None)[source]¶
Persist the API key to the config file with owner-only permissions.
- blueqat.cloud.delete_api_key()[source]¶
Remove the stored API key from the config file (if present).
- Return type:
None
- blueqat.cloud.get_api_key()[source]¶
Resolve the API key: configure() > environment > config file.
- Return type:
str | None
- blueqat.cloud.get_endpoint()[source]¶
Resolve the service endpoint: configure() > config file > default.
- Return type:
- blueqat.cloud.configure(api_key=None, endpoint=None, transport=None)[source]¶
Set session-level cloud settings (highest priority, not persisted).
transport is a callable receiving the JSON-compatible request dict and returning the job result; inject one for tests or early integrations.
- blueqat.cloud.reset_configuration()[source]¶
Clear session-level settings set by configure (env/file are untouched).
- Return type:
None
Circuit utilities¶
Parser for a practical subset of OpenQASM 2.0 (the qelib1.inc gate set) into a Circuit.
This is the reverse of Circuit.to_qasm().
- blueqat.circuit_funcs.qasm_parser.from_qasm(qasm)[source]¶
Parse an OpenQASM 2.0 program (the qelib1.inc gate set) into a Circuit.
Defines JSON serializer and deserializer for Blueqat circuits.
- blueqat.circuit_funcs.json_serializer.serialize(c)[source]¶
Serialize Circuit into JSON-compatible dictionary.
In this implementation, the serialized circuit is automatically flattened to break down multi-target operations into atomic gates.
- Parameters:
c (Circuit)
- Return type:
CircuitJsonDictV2
- blueqat.circuit_funcs.json_serializer.deserialize(data)[source]¶
Deserialize JSON-compatible dictionary back into a Circuit object.
- Parameters:
data (CircuitJsonDictV1 | CircuitJsonDictV2)
- Return type:
This module provides a feature to convert a quantum circuit to a unitary matrix.
- blueqat.circuit_funcs.circuit_to_unitary.circuit_to_unitary(circ, *runargs, **runkwargs)[source]¶
Convert a quantum circuit into its corresponding unitary matrix representation.
This function simulates the circuit for all computational basis states to construct the full unitary matrix.
- Parameters:
circ (Circuit) – The quantum circuit to be converted.
*runargs – Positional arguments passed to circuit execution backend.
**runkwargs – Keyword arguments passed to circuit execution backend.
- Returns:
The unitary matrix representing the total circuit operation.
- Return type:
np.ndarray
This module provides a feature to flatten circuit operations by expanding multi-targets.
- blueqat.circuit_funcs.flatten.flatten(c)[source]¶
Expands slice and multiple targets into single target operations.
This function normalizes the circuit so that each gate or measurement operation applies to explicit, un-sliced single qubits (or single pairs for two-qubit gates).
- Parameters:
c (Circuit) – The quantum circuit to flatten.
- Returns:
A new flattened Circuit object.
- Return type:
- Raises:
ValueError – If an unexpected or unprocessable operation type is encountered.