qpe_toolbox.circuit.serialize_circuits

Functions

apply_gate_qiskit(qc, label, qubits, params)

Apply a quantum gate to a qiskit qiskit.QuantumCircuit using a string label.

deserialize_to_qiskit_QuantumCircuit(full_gate_dict, *)

Deserialize a gate dictionary into a qiskit qiskit.QuantumCircuit.

serialize_from_quimb_Circuit(qc)

Serialize a quimb circuit into a JSON-compatible dictionary.

serialize_from_quimb_gates(n_qubits, gates_list)

Serialize a list of quimb gates into a JSON-compatible dictionary.

deserialize_to_quimb_Circuit(full_gate_dict, *[, ...])

Deserialize a gate dictionary into a Circuit up to a given depth.

deserialize_to_quimb_CircuitMPS(full_gate_dict, ...[, ...])

Deserialize a gate dictionary into a CircuitMPS or CircuitPermMPS.

dump_quimb_Circuit_to_qasm(circ, savefile_base, *[, ...])

Export a quimb circuit to an OpenQASM 2.0 file.

load_qasm_to_quimb_Circuit(filename, *[, with_rounds, ...])

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 qiskit qiskit.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".

  • qubits (list[int]) –

    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 for u3).

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 qiskit qiskit.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"int

      Total number of qubits in the circuit.

    • "gates"list[dict]

      List of gate specifications. Each gate dictionary must contain:

      • "name"str

        Gate label (passed to apply_gate_qiskit()).

      • "qubits"list[int]

        Target qubit indices.

      • "params"list[float]

        Gate parameters (empty for non-parameterized gates).

      • "round"int

        Layer 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_depth are applied. If inf (default), the full circuit is reconstructed.

  • measure (bool, optional) – If True, a classical register of size n_qubits is added and all qubits are measured at the end of the circuit. Default is False.

Returns:

qc – The reconstructed qiskit quantum circuit.

Return type:

qiskit.QuantumCircuit

Raises:
  • KeyError – If required keys are missing from full_gate_dict or 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() and qiskit.

qpe_toolbox.circuit.serialize_circuits.serialize_from_quimb_Circuit(qc)[source]

Serialize a quimb circuit into a JSON-compatible dictionary.

This function converts a Circuit object into a plain python dictionary containing only JSON-serializable types. The resulting dictionary can be safely stored, transmitted, or deserialized into other circuit representations (e.g. qiskit).

Parameters:

qc (Circuit) – The quimb circuit 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 by quimb.

    • "qubits" : list of int Target qubit indices.

    • "controls": list

      Control 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:

dict

See also

deserialize_to_quimb_Circuit

Reconstruct a quimb Circuit from the serialized dictionary.

deserialize_to_qiskit_QuantumCircuit

Reconstruct a qiskit qiskit.QuantumCircuit from the serialized dictionary.

Notes

  • All numerical values are explicitly cast to built-in python types (int and float) to ensure JSON compatibility.

  • The ordering of gates in qc.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.serialize_from_quimb_gates(n_qubits, gates_list)[source]

Serialize a list of quimb gates into a JSON-compatible dictionary.

This function converts a list of Gate objects into a plain python dictionary containing only JSON-serializable types. The resulting dictionary can be safely stored, transmitted, or deserialized into other circuit representations (e.g. qiskit).

Parameters:
  • n_qubits (int) – Total number of qubits in the circuit.

  • gates_list (list) – The list of quimb gates 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 by quimb.

    • "qubits" : list of int Target qubit indices.

    • "controls": list

      Control 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:

dict

See also

deserialize_to_quimb_Circuit

Reconstruct a quimb Circuit from the serialized dictionary.

deserialize_to_qiskit_QuantumCircuit

Reconstruct a qiskit qiskit.QuantumCircuit from the serialized dictionary.

Notes

  • All numerical values are explicitly cast to built-in python types (int and float) to ensure JSON compatibility.

  • 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 round index is strictly smaller than max_depth are 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 str

      Total number of qubits in the circuit.

    • "gates"list of dict

      List of gate specifications. Each gate dictionary must contain:

      • "name"str

        Gate identifier understood by Circuit.apply_gate.

      • "params"list

        Gate parameters (will be cast to float).

      • "qubits"list

        Qubit indices the gate acts on.

      • "controls": list

        Control qubits’ indices.

      • "round"int or str

        Layer / round index of the gate.

  • max_depth (int or inf, optional) – Maximum circuit depth to deserialize, i.e. if round >= depth the 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 quimb circuit instance containing all gates up to the specified depth.

Return type:

Circuit

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 round index is strictly smaller than max_depth are 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 str

      Total number of qubits in the circuit.

    • "gates"list

      List of gate specifications. Each gate dictionary must contain:

      • "name"str

        Gate identifier understood by CircuitMPS.apply_gate

      • "params"list

        Gate parameters (will be cast to float).

      • "qubits"list

        Qubit indices the gate acts on.

      • "controls": list

        Control qubits’ indices.

      • "round"int or str

        Layer/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_depth the 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:

CircuitMPS or CircuitPermMPS

qpe_toolbox.circuit.serialize_circuits.dump_quimb_Circuit_to_qasm(circ, savefile_base, *, save_rounds=True)[source]

Export a quimb circuit to an OpenQASM 2.0 file.

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 quimb circuit to export.

  • savefile_base (str) –

    Base filename (without extension) for the output files. The function writes:

    • <savefile_base>.qasm

    • <savefile_base>_rounds.txt (if save_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 float and 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 from filename_rounds.txt and assign gates using gate_round. Default is False.

  • max_depth (int or inf, optional) – Maximum circuit depth to load. Gates with gate_round >= max_depth are 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 is False.

  • min_layout (bool, optional) – If True, infer the number of qubits from the maximum qubit index appearing in the gates. If False (default), read the register size from the QASM header.

Returns:

circ – The reconstructed quimb circuit.

Return type:

Circuit

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.txt must exist and contain one integer per gate.

  • This function assumes that the QASM file uses gate labels compatible with quimb.