qpe_toolbox.circuit.serialize_circuits¶
Functions¶
|
Apply a quantum gate to a |
|
Deserialize a gate dictionary into a |
Serialize a |
|
|
Serialize a list of |
|
Deserialize a gate dictionary into a Circuit up to a given depth. |
|
Deserialize a gate dictionary into a CircuitMPS or CircuitPermMPS. |
|
Export a |
|
Parse a QASM 2.0 file and reconstruct a Circuit. |
Module Contents¶
- qpe_toolbox.circuit.serialize_circuits.apply_gate_qiskit(qc, label, qubits, params)[source]¶
Apply a quantum gate to a
qiskitqiskit.QuantumCircuit using a string label.This function dispatches gate application based on:
the gate label (case-insensitive),
the number of target qubits (single- or two-qubit),
and whether the gate is parameterized.
It is inspired in the Circuit.apply_gate method from quimb’s Circuit.
The alias
"cnot"is automatically mapped to"cx".- Parameters:
qc (qiskit.QuantumCircuit) – The quantum circuit to which the gate is applied.
label (str) – Gate label identifying the quantum operation. The comparison is case-insensitive. For example,
"RX","rx", and"Rx"are treated identically. The label"cnot"is mapped internally to"cx".List of qubit indices the gate acts on. Supported values are:
length 1 for single-qubit gates,
length 2 for two-qubit gates.
Any other length raises a
ValueError.params (list[float]) – List of gate parameters. Use an empty list for non-parametrized gates. For parameterized gates, the number of parameters must match the gate definition (e.g. one parameter for
rx, three foru3).
- Raises:
ValueError – If the number of qubits is not supported (i.e. not 1 or 2).
AttributeError – If the gate label does not correspond to a qiskit gate.
Notes
Qubit index bounds are not checked and must be valid for the circuit.
Examples
Apply a single-qubit rotation:
>>> apply_gate_qiskit(qc, "RX", [0], [np.pi / 2])
Apply a controlled-NOT gate:
>>> apply_gate_qiskit(qc, "cnot", [0, 1], [])
Apply a two-qubit parameterized gate:
>>> apply_gate_qiskit(qc, "rxx", [0, 1], [0.3])
- qpe_toolbox.circuit.serialize_circuits.deserialize_to_qiskit_QuantumCircuit(full_gate_dict, *, max_depth=np.inf, measure=False)[source]¶
Deserialize a gate dictionary into a
qiskitqiskit.QuantumCircuit.This function reconstructs a qiskit.QuantumCircuit from a serialized gate representation, where gates are annotated with qubit indices, parameters, and a discrete circuit
round(layer index).Gates are applied in the order they appear in
full_gate_dict["gates"], subject to an optional depth cutoff.- Parameters:
full_gate_dict (dict) –
Dictionary encoding the quantum circuit. It must contain:
"n_qubits"intTotal number of qubits in the circuit.
"gates"list[dict]List of gate specifications. Each gate dictionary must contain:
"name"strGate label (passed to
apply_gate_qiskit()).
"qubits"list[int]Target qubit indices.
"params"list[float]Gate parameters (empty for non-parameterized gates).
"round"intLayer index at which the gate is applied.
max_depth (int or inf, optional) – Maximum circuit depth (number of rounds) to load. Only gates with
gate["round"] < max_depthare applied. Ifinf(default), the full circuit is reconstructed.measure (bool, optional) – If
True, a classical register of sizen_qubitsis added and all qubits are measured at the end of the circuit. Default isFalse.
- Returns:
qc – The reconstructed
qiskitquantum circuit.- Return type:
- Raises:
KeyError – If required keys are missing from
full_gate_dictor its gate entries.ValueError – If invalid gate specifications are encountered during deserialization (propagated from
apply_gate_qiskit()).
Notes
Gate ordering within the same round is preserved as given in the input.
No validation is performed on qubit index bounds.
Parameter consistency is delegated to
apply_gate_qiskit()andqiskit.
- qpe_toolbox.circuit.serialize_circuits.serialize_from_quimb_Circuit(qc)[source]¶
Serialize a
quimbcircuit into aJSON-compatible dictionary.This function converts a Circuit object into a plain
pythondictionary containing onlyJSON-serializable types. The resulting dictionary can be safely stored, transmitted, or deserialized into other circuit representations (e.g.qiskit).- Parameters:
qc (Circuit) – The
quimbcircuit to be serialized.- Returns:
Dictionary representation of the circuit with the following keys:
"n_qubits": int Number of qubits in the circuit."gates": list of dict Ordered list of gate specifications. Each gate dictionary contains:"name": str Gate label as used byquimb."qubits": list of int Target qubit indices."controls": listControl qubits’ indices.
"params": list of float Gate parameters (rounded to 4 decimal places)."round": int Circuit round (layer index) in which the gate appears.
- Return type:
See also
deserialize_to_quimb_CircuitReconstruct a
quimbCircuit from the serialized dictionary.deserialize_to_qiskit_QuantumCircuitReconstruct a
qiskitqiskit.QuantumCircuit from the serialized dictionary.
Notes
All numerical values are explicitly cast to built-in
pythontypes (intandfloat) to ensureJSONcompatibility.The ordering of gates in
qc.gatesis preserved, allowing faithful reconstruction of the circuit.The output format is designed to be compatible with downstream deserialization into other frameworks (e.g.
qiskit).
- qpe_toolbox.circuit.serialize_circuits.serialize_from_quimb_gates(n_qubits, gates_list)[source]¶
Serialize a list of
quimbgates into aJSON-compatible dictionary.This function converts a list of Gate objects into a plain
pythondictionary containing onlyJSON-serializable types. The resulting dictionary can be safely stored, transmitted, or deserialized into other circuit representations (e.g.qiskit).- Parameters:
- Returns:
Dictionary representation of the circuit with the following keys:
"n_qubits": int Number of qubits in the circuit."gates": list of dict Ordered list of gate specifications. Each gate dictionary contains:"name": str Gate label as used byquimb."qubits": list of int Target qubit indices."controls": listControl qubits’ indices.
"params": list of float Gate parameters (rounded to 4 decimal places)."round": int Circuit round (layer index) in which the gate appears.
- Return type:
See also
deserialize_to_quimb_CircuitReconstruct a
quimbCircuit from the serialized dictionary.deserialize_to_qiskit_QuantumCircuitReconstruct a
qiskitqiskit.QuantumCircuit from the serialized dictionary.
Notes
All numerical values are explicitly cast to built-in
pythontypes (intandfloat) to ensureJSONcompatibility.The ordering of gates is preserved, allowing faithful reconstruction of the circuit.
The output format is designed to be compatible with downstream deserialization into other frameworks (e.g.
qiskit).
- qpe_toolbox.circuit.serialize_circuits.deserialize_to_quimb_Circuit(full_gate_dict, *, max_depth=np.inf, contract=False, **gate_opts)[source]¶
Deserialize a gate dictionary into a Circuit up to a given depth.
This function reconstructs a circuit from a serialized representation of a quantum circuit (i.e. the one that can be saved as JSON). Only gates whose
roundindex is strictly smaller thanmax_depthare included, allowing for partial reconstruction of the circuit.- Parameters:
full_gate_dict (dict) –
Serialized circuit description. Must contain the following keys:
"n_qubits"int or strTotal number of qubits in the circuit.
"gates"list of dictList of gate specifications. Each gate dictionary must contain:
"name"strGate identifier understood by Circuit.apply_gate.
"params"listGate parameters (will be cast to
float).
"qubits"listQubit indices the gate acts on.
"controls": listControl qubits’ indices.
"round"int or strLayer / round index of the gate.
max_depth (int or inf, optional) – Maximum circuit depth to deserialize, i.e. if
round >= depththe gate is ignored. Default is inf, the full circuit is deserialized.contract (bool, optional) – Whether to contract the quimb Circuit. Default is False.
**gate_opts (dict) – Additional keyword arguments forwarded to Circuit.apply_gate. Override any default gate options.
- Returns:
qc – A
quimbcircuit instance containing all gates up to the specified depth.- Return type:
Notes
If the circuit is deserialized for plotting purposes, set
contract=False.This function assumes the serialized gate names and parameters are compatible with Circuit.apply_gate.
Useful when assessing the complexity of a circuit and its contraction layer-by-layer.
- qpe_toolbox.circuit.serialize_circuits.deserialize_to_quimb_CircuitMPS(full_gate_dict, max_bond, cutoff, *, max_depth=np.inf, perm=False, psi0=None)[source]¶
Deserialize a gate dictionary into a CircuitMPS or CircuitPermMPS.
Accepts the same serialized format as saved in JSON. Only gates whose
roundindex is strictly smaller thanmax_depthare applied, allowing for partial reconstruction of the circuit.- Parameters:
full_gate_dict (dict) –
Serialized circuit description. Must contain the following keys:
"n_qubits"int or strTotal number of qubits in the circuit.
"gates"listList of gate specifications. Each gate dictionary must contain:
"name"strGate identifier understood by CircuitMPS.apply_gate
"params"listGate parameters (will be cast to float).
"qubits"listQubit indices the gate acts on.
"controls": listControl qubits’ indices.
"round"int or strLayer/depth index of the gate.
max_bond (int) – Maximum bond dimension of the MPS.
cutoff (float) – Truncation cutoff for singular values when applying gates to the MPS.
max_depth (int or inf, optional) – Maximum circuit depth to deserialize, i.e. if
round >= max_depththe gate is ignored. Default is inf, the full circuit is deserialized.perm (bool, optional) – If
True, use CircuitPermMPS instead of CircuitMPS. Default is False.psi0 (MatrixProductState or None, optional) – Initial MPS state. If
None, the all-zeros computational basis state is used. Default is None.
- Returns:
cmps – An MPS representation of the reconstructed circuit containing all gates contracted up to the specified depth.
- Return type:
- qpe_toolbox.circuit.serialize_circuits.dump_quimb_Circuit_to_qasm(circ, savefile_base, *, save_rounds=True)[source]¶
Export a
quimbcircuit to anOpenQASM 2.0file.This function serializes a Circuit into a QASM 2.0-compatible text file. Optionally, the circuit round (layer index) of each gate is stored in a separate sidecar file.
- Parameters:
circ (Circuit) – The
quimbcircuit to export.savefile_base (str) –
Base filename (without extension) for the output files. The function writes:
<savefile_base>.qasm<savefile_base>_rounds.txt(ifsave_rounds=True)
save_rounds (bool, optional) – If
True(default), write the circuit round of each gate to a separate text file, with one integer per line.
- Raises:
ValueError – If a gate label is encountered that cannot be mapped to a supported OpenQASM 2.0 instruction.
Notes
Gate labels are converted to lowercase for QASM compatibility.
The gate label
"cnot"is automatically mapped to"cx", which is the canonical OpenQASM name.Gate parameters are converted to native Python
floatand formatted with limited precision to ensure portability.Circuit round information is not part of the QASM standard and is therefore stored separately.
- qpe_toolbox.circuit.serialize_circuits.load_qasm_to_quimb_Circuit(filename, *, with_rounds=False, max_depth=np.inf, gate_contract=False, min_layout=False)[source]¶
Parse a QASM 2.0 file and reconstruct a Circuit.
Optionally, this function can restore circuit round (layer) information from a sidecar file and load only a truncated circuit depth.
- Parameters:
filename (str) – Base filename (without extension) of the QASM file to load.
with_rounds (bool, optional) – If
True, load circuit round information fromfilename_rounds.txtand assign gates usinggate_round. Default isFalse.max_depth (int or inf, optional) – Maximum circuit depth to load. Gates with
gate_round >= max_depthare ignored. Default is inf, the full circuit is loaded.gate_contract (bool, optional) – Whether to immediately contract gates into the tensor network when applying them. Passed directly to
circ.apply_gate. Default isFalse.min_layout (bool, optional) – If
True, infer the number of qubits from the maximum qubit index appearing in the gates. IfFalse(default), read the register size from the QASM header.
- Returns:
circ – The reconstructed quimb circuit.
- Return type:
Notes
The QASM file is parsed using
parse_openqasm2_file.When
with_rounds=False, circuit round information is ignored and gates are loaded in sequential order.When
with_rounds=True, a sidecar file<filename>_rounds.txtmust exist and contain one integer per gate.This function assumes that the QASM file uses gate labels compatible with quimb.