Spaces:
Runtime error
Runtime error
Download src/quantum_circuits/noisy_circuit_generator.py from QuantumGenAI/ErrorMitigation: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/QuantumGenAI/ErrorMitigation/resolve/main/src/quantum_circuits/noisy_circuit_generator.py
- Command line
-
hf download hf://spaces/QuantumGenAI/ErrorMitigation/src/quantum_circuits/noisy_circuit_generator.py
-
curl -L -o noisy_circuit_generator.py https://huggingface.co/spaces/QuantumGenAI/ErrorMitigation/resolve/main/src/quantum_circuits/noisy_circuit_generator.py
12.3 kB
| import pennylane as qml | |
| from pennylane import numpy as np | |
| from typing import Callable, Dict, List, Tuple, Union, Optional, Any | |
| class NoisyCircuit: | |
| """ | |
| Adds customizable noise to a quantum circuit in PennyLane using either a | |
| naive noise injection approach or an advanced QASM-based injection. | |
| Attributes: | |
| device (qml.Device): The quantum device. | |
| noise_operations (List[Tuple[Callable, float, List[int]]]): | |
| List of noise operations as (noise_gate, probability, target_wires). | |
| """ | |
| def __init__( | |
| self, | |
| device: qml.Device, | |
| noise_operations: Optional[List[Tuple[Callable, float, List[int]]]] = None, | |
| ) -> None: | |
| """ | |
| Args: | |
| device: The PennyLane quantum device. | |
| noise_operations: List of noise operations; if None, defaults to an empty list. | |
| """ | |
| self.device = device | |
| self.noise_operations = noise_operations if noise_operations is not None else [] | |
| def add_noise(self, circuit: Callable, wires: List[int]) -> Callable: | |
| """ | |
| Naively adds the specified noise gates directly to the circuit. | |
| Args: | |
| circuit: The user-defined noiseless circuit function. | |
| wires: List of system wires on which the circuit acts. | |
| Returns: | |
| A new circuit function that runs the original circuit then applies noise. | |
| """ | |
| def noisy_circuit(*params: Any, n_qubits: Optional[int] = None) -> None: | |
| # Run the noiseless circuit. | |
| circuit(*params, n_qubits=n_qubits) | |
| # Apply each noise gate to its target wires. | |
| for noise_op, prob, target_wires in self.noise_operations: | |
| for w in target_wires: | |
| noise_op(prob, wires=[w]) | |
| return noisy_circuit | |
| def noisy_qnode( | |
| self, circuit: Callable, wires: List[int], use_qasm: bool = True | |
| ) -> qml.QNode: | |
| """ | |
| Constructs a QNode that applies a noiseless circuit and then injects noise. | |
| If use_qasm is True, the advanced QASM-based injection via NoisyQNodeBuilder is used; | |
| otherwise, a naive approach is taken. | |
| Args: | |
| circuit: The noiseless circuit function. | |
| wires: List of system wires (e.g. [0, 1]). | |
| use_qasm: Whether to use QASM-based noise injection. Defaults to True. | |
| Returns: | |
| A QNode that returns expectation values of PauliZ on each system wire. | |
| """ | |
| if use_qasm: | |
| return NoisyQNodeBuilder.build_noisy_qnode_with_injections( | |
| noiseless_circuit=circuit, | |
| n_system_wires=len(wires), | |
| noise_channels=self.noise_operations, | |
| measurement_fn=lambda: [qml.expval(qml.PauliZ(w)) for w in wires], | |
| ) | |
| else: | |
| noisy_circ = self.add_noise(circuit, wires) | |
| def qnode(*params: Any, n_qubits: Optional[int] = None) -> List[float]: | |
| noisy_circ(*params, n_qubits=n_qubits) | |
| return [qml.expval(qml.PauliZ(w)) for w in wires] | |
| return qnode | |
| class NoisyQNodeBuilder: | |
| """ | |
| Constructs noisy QNodes by injecting noise channels (via Stinespring dilation) | |
| into a noiseless circuit. | |
| Supported noise channels: | |
| - BitFlip | |
| - PhaseFlip | |
| - PhaseDamping | |
| - AmplitudeDamping | |
| - Depolarizing (and alias DepolarizingChannel) | |
| The QNode is built on a device whose total wires equal the number of system wires plus | |
| the ancilla wires required for noise injection. | |
| """ | |
| def BitFlip(gamma: float, wires: List[int]) -> None: | |
| """ | |
| Applies a BitFlip noise channel via Stinespring dilation. | |
| Args: | |
| gamma: Flip probability. | |
| wires: [system_wire, ancilla_wire]. | |
| """ | |
| sys_wire, anc_wire = wires | |
| theta = 2 * np.arcsin(np.sqrt(gamma)) | |
| qml.RY(theta, wires=anc_wire) | |
| qml.CNOT(wires=[anc_wire, sys_wire]) | |
| def PhaseFlip(gamma: float, wires: List[int]) -> None: | |
| """ | |
| Applies a PhaseFlip noise channel via Stinespring dilation. | |
| Args: | |
| gamma: Noise parameter. | |
| wires: [system_wire, ancilla_wire]. | |
| """ | |
| sys_wire, anc_wire = wires | |
| theta = 2 * np.arcsin(np.sqrt(gamma)) | |
| qml.RY(theta, wires=anc_wire) | |
| qml.CZ(wires=[anc_wire, sys_wire]) | |
| def PhaseDamping(gamma: float, wires: List[int]) -> None: | |
| """ | |
| Applies a PhaseDamping noise channel via Stinespring dilation. | |
| Args: | |
| gamma: Noise parameter. | |
| wires: [system_wire, ancilla_wire]. | |
| """ | |
| sys_wire, anc_wire = wires | |
| qml.PauliX(wires=anc_wire) | |
| qml.CNOT(wires=[anc_wire, sys_wire]) | |
| alpha = 2 * np.arccos(np.sqrt(1 - gamma)) | |
| qml.RZ(alpha, wires=sys_wire) | |
| qml.CNOT(wires=[anc_wire, sys_wire]) | |
| qml.PauliX(wires=anc_wire) | |
| def AmplitudeDamping(gamma: float, wires: List[int]) -> None: | |
| """ | |
| Applies an AmplitudeDamping noise channel using a custom unitary. | |
| Args: | |
| gamma: Noise parameter. | |
| wires: Wires on which to apply the unitary. | |
| """ | |
| U = np.array( | |
| [ | |
| [1, 0, 0, 0], | |
| [0, 1, np.sqrt(gamma), 0], | |
| [0, 0, np.sqrt(1 - gamma), 0], | |
| [0, 0, 0, 1], | |
| ], | |
| dtype=complex, | |
| ) | |
| qml.QubitUnitary(U, wires=wires) | |
| def Depolarizing(p: float, wires: List[int]) -> None: | |
| """ | |
| Applies a Depolarizing noise channel via a 3-qubit unitary. | |
| Args: | |
| p: Depolarizing probability. | |
| wires: [system_wire, ancilla1, ancilla2]. | |
| """ | |
| U = NoisyQNodeBuilder._build_depolarizing_3qubit_unitary(p) | |
| qml.QubitUnitary(U, wires=wires) | |
| def _build_depolarizing_3qubit_unitary(p: float) -> np.ndarray: | |
| """ | |
| Constructs an 8x8 unitary for the depolarizing channel. | |
| Args: | |
| p: Depolarizing probability. | |
| Returns: | |
| 8x8 complex unitary matrix. | |
| """ | |
| def apply_X(s: int) -> Tuple[int, float]: | |
| return (1 - s), 1.0 | |
| def apply_Z(s: int) -> Tuple[int, float]: | |
| phase = -1.0 if s == 1 else 1.0 | |
| return s, phase | |
| def apply_Y(s: int) -> Tuple[int, complex]: | |
| return (1, 1.0j) if s == 0 else (0, -1.0j) | |
| amp_I = np.sqrt(1 - p) | |
| amp_X = amp_Y = amp_Z = np.sqrt(p / 3) | |
| U = np.zeros((8, 8), dtype=complex) | |
| def idx(s: int, a1: int, a2: int) -> int: | |
| return 4 * s + 2 * a1 + a2 | |
| for s in [0, 1]: | |
| for a1 in [0, 1]: | |
| for a2 in [0, 1]: | |
| col = idx(s, a1, a2) | |
| if (a1, a2) != (0, 0): | |
| row = idx(s, a1, a2) | |
| U[row, col] = 1.0 | |
| else: | |
| U[idx(s, 0, 0), col] += amp_I | |
| sX, phX = apply_X(s) | |
| U[idx(sX, 0, 1), col] += amp_X * phX | |
| sY, phY = apply_Y(s) | |
| U[idx(sY, 1, 0), col] += amp_Y * phY | |
| sZ, phZ = apply_Z(s) | |
| U[idx(sZ, 1, 1), col] += amp_Z * phZ | |
| return U | |
| NOISE_CHANNEL_METHODS: Dict[str, Callable] = { | |
| "BitFlip": BitFlip.__func__, | |
| "PhaseFlip": PhaseFlip.__func__, | |
| "PhaseDamping": PhaseDamping.__func__, | |
| "AmplitudeDamping": AmplitudeDamping.__func__, | |
| "Depolarizing": Depolarizing.__func__, | |
| "DepolarizingChannel": Depolarizing.__func__, | |
| } | |
| def build_noisy_qnode_with_injections( | |
| cls, | |
| noiseless_circuit: Callable, | |
| n_system_wires: int, | |
| noise_channels: List[Tuple[Union[str, Any], float, List[int]]], | |
| measurement_fn: Optional[Callable] = None, | |
| device_kwargs: Optional[Dict[str, Any]] = None, | |
| ) -> qml.QNode: | |
| """ | |
| Constructs a QNode that runs a noiseless circuit on the system wires, | |
| then sequentially injects noise channels (using fresh ancilla qubits), and finally | |
| performs a measurement. | |
| Args: | |
| noiseless_circuit: The noiseless circuit function. | |
| n_system_wires: Number of system wires. | |
| noise_channels: List of noise channel specifications in the form (noise_type, noise_param, wires_to_noise). | |
| measurement_fn: Function returning measurement result (defaults to qml.state() if not provided). | |
| device_kwargs: Additional device parameters. | |
| Returns: | |
| A PennyLane QNode representing the noisy circuit. | |
| """ | |
| noise_channels = cls._normalize_noise_channels(noise_channels) | |
| for noise_type, _, _ in noise_channels: | |
| if noise_type not in cls.NOISE_CHANNEL_METHODS: | |
| raise ValueError( | |
| f"Unknown noise type '{noise_type}'. Available types: {list(cls.NOISE_CHANNEL_METHODS.keys())}" | |
| ) | |
| ancilla_requirements = cls._calculate_ancilla_requirements(noise_channels) | |
| total_ancillas = sum(ancilla_requirements) | |
| def quantum_function(*args: Any, **kwargs: Any) -> Any: | |
| noiseless_circuit(*args, **kwargs) | |
| current_ancilla_start = ( | |
| n_system_wires # System wires are 0 .. n_system_wires-1 | |
| ) | |
| for i, (noise_type, noise_param, wires_to_noise) in enumerate( | |
| noise_channels | |
| ): | |
| noise_fn = cls.NOISE_CHANNEL_METHODS[noise_type] | |
| anc_per_wire = ( | |
| 2 if noise_type in ("Depolarizing", "DepolarizingChannel") else 1 | |
| ) | |
| for j, sys_wire in enumerate(wires_to_noise): | |
| anc_start = current_ancilla_start + j * anc_per_wire | |
| anc_wires = list(range(anc_start, anc_start + anc_per_wire)) | |
| noise_fn(noise_param, wires=[sys_wire] + anc_wires) | |
| current_ancilla_start += ancilla_requirements[i] | |
| return measurement_fn() if measurement_fn else qml.state() | |
| total_wires = n_system_wires + total_ancillas | |
| device_params = {"wires": total_wires, "shots": None} | |
| if device_kwargs: | |
| device_params.update(device_kwargs) | |
| dev = qml.device("default.mixed", **device_params) | |
| return qml.QNode(quantum_function, dev) | |
| def _normalize_noise_channels( | |
| cls, noise_channels: List[Tuple[Union[str, Any], float, List[int]]] | |
| ) -> List[Tuple[str, float, List[int]]]: | |
| transformed = [] | |
| for noise_type, noise_param, wires_to_noise in noise_channels: | |
| noise_type_str = ( | |
| noise_type.__name__ | |
| if isinstance(noise_type, type) | |
| and issubclass(noise_type, qml.operation.Operation) | |
| else str(noise_type) | |
| ) | |
| transformed.append((noise_type_str, noise_param, wires_to_noise)) | |
| return transformed | |
| def _calculate_ancilla_requirements( | |
| cls, noise_channels: List[Tuple[str, float, List[int]]] | |
| ) -> List[int]: | |
| requirements = [] | |
| for noise_type, _, wires_to_noise in noise_channels: | |
| anc_per_wire = ( | |
| 2 if noise_type in ("Depolarizing", "DepolarizingChannel") else 1 | |
| ) | |
| requirements.append(anc_per_wire * len(wires_to_noise)) | |
| return requirements | |
| def print_results( | |
| title: str, | |
| stine_res: Any, | |
| naive_res: Any, | |
| qnode_stine: qml.QNode, | |
| qnode_naive: qml.QNode, | |
| ) -> None: | |
| """ | |
| Helper function to print test results and circuit diagrams. | |
| """ | |
| print(f"\n--- {title} ---") | |
| print("Stinespring result on wires [0,1]:", stine_res) | |
| print("Naive result on wires [0,1]: ", naive_res) | |
| print("\nStinespring circuit diagram:") | |
| print(qml.draw(qnode_stine)()) | |
| print("\nNaive approach circuit diagram:") | |
| print(qml.draw(qnode_naive)()) | |
| print("-" * 60) | |