Spaces:
Runtime error
Runtime error
File size: 12,281 Bytes
fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 e0d7f28 fc34b65 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | 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)
@qml.qnode(self.device)
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.
"""
@staticmethod
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])
@staticmethod
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])
@staticmethod
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)
@staticmethod
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)
@staticmethod
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)
@staticmethod
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__,
}
@classmethod
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)
@classmethod
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
@classmethod
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)
|