Spaces:
Sleeping
Sleeping
File size: 9,028 Bytes
6ce350d |
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 |
"""
Gate Library - Definitions of standard quantum gates and their matrix representations.
"""
import numpy as np
from typing import Callable
import math
# Type alias for gate matrices
GateMatrix = np.ndarray
class GateLibrary:
"""
Library of standard quantum gates with their matrix representations.
Follows IBM Qiskit conventions for gate definitions.
"""
# Pauli gates
@staticmethod
def I() -> GateMatrix:
"""Identity gate."""
return np.array([[1, 0], [0, 1]], dtype=complex)
@staticmethod
def X() -> GateMatrix:
"""Pauli-X (NOT) gate."""
return np.array([[0, 1], [1, 0]], dtype=complex)
@staticmethod
def Y() -> GateMatrix:
"""Pauli-Y gate."""
return np.array([[0, -1j], [1j, 0]], dtype=complex)
@staticmethod
def Z() -> GateMatrix:
"""Pauli-Z gate."""
return np.array([[1, 0], [0, -1]], dtype=complex)
# Hadamard and phase gates
@staticmethod
def H() -> GateMatrix:
"""Hadamard gate - creates superposition."""
return np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
@staticmethod
def S() -> GateMatrix:
"""S gate (sqrt(Z))."""
return np.array([[1, 0], [0, 1j]], dtype=complex)
@staticmethod
def Sdg() -> GateMatrix:
"""S-dagger gate."""
return np.array([[1, 0], [0, -1j]], dtype=complex)
@staticmethod
def T() -> GateMatrix:
"""T gate (sqrt(S))."""
return np.array([[1, 0], [0, np.exp(1j * np.pi / 4)]], dtype=complex)
@staticmethod
def Tdg() -> GateMatrix:
"""T-dagger gate."""
return np.array([[1, 0], [0, np.exp(-1j * np.pi / 4)]], dtype=complex)
@staticmethod
def SX() -> GateMatrix:
"""Sqrt(X) gate."""
return np.array([[1+1j, 1-1j], [1-1j, 1+1j]], dtype=complex) / 2
# Rotation gates
@staticmethod
def Rx(theta: float) -> GateMatrix:
"""Rotation around X-axis."""
c = np.cos(theta / 2)
s = np.sin(theta / 2)
return np.array([[c, -1j*s], [-1j*s, c]], dtype=complex)
@staticmethod
def Ry(theta: float) -> GateMatrix:
"""Rotation around Y-axis."""
c = np.cos(theta / 2)
s = np.sin(theta / 2)
return np.array([[c, -s], [s, c]], dtype=complex)
@staticmethod
def Rz(phi: float) -> GateMatrix:
"""Rotation around Z-axis."""
return np.array([
[np.exp(-1j * phi / 2), 0],
[0, np.exp(1j * phi / 2)]
], dtype=complex)
@staticmethod
def P(phi: float) -> GateMatrix:
"""Phase gate."""
return np.array([[1, 0], [0, np.exp(1j * phi)]], dtype=complex)
@staticmethod
def U(theta: float, phi: float, lam: float) -> GateMatrix:
"""General single-qubit unitary U3 gate."""
c = np.cos(theta / 2)
s = np.sin(theta / 2)
return np.array([
[c, -np.exp(1j * lam) * s],
[np.exp(1j * phi) * s, np.exp(1j * (phi + lam)) * c]
], dtype=complex)
# Two-qubit gates (4x4 matrices)
@staticmethod
def CX() -> GateMatrix:
"""Controlled-X (CNOT) gate."""
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]
], dtype=complex)
@staticmethod
def CY() -> GateMatrix:
"""Controlled-Y gate."""
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, -1j],
[0, 0, 1j, 0]
], dtype=complex)
@staticmethod
def CZ() -> GateMatrix:
"""Controlled-Z gate."""
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, -1]
], dtype=complex)
@staticmethod
def SWAP() -> GateMatrix:
"""SWAP gate."""
return np.array([
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]
], dtype=complex)
@staticmethod
def iSWAP() -> GateMatrix:
"""iSWAP gate."""
return np.array([
[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1]
], dtype=complex)
@staticmethod
def CP(phi: float) -> GateMatrix:
"""Controlled-Phase gate."""
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, np.exp(1j * phi)]
], dtype=complex)
@staticmethod
def CRx(theta: float) -> GateMatrix:
"""Controlled-Rx gate."""
c = np.cos(theta / 2)
s = np.sin(theta / 2)
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, c, -1j*s],
[0, 0, -1j*s, c]
], dtype=complex)
@staticmethod
def CRy(theta: float) -> GateMatrix:
"""Controlled-Ry gate."""
c = np.cos(theta / 2)
s = np.sin(theta / 2)
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, c, -s],
[0, 0, s, c]
], dtype=complex)
@staticmethod
def CRz(theta: float) -> GateMatrix:
"""Controlled-Rz gate."""
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, np.exp(-1j * theta / 2), 0],
[0, 0, 0, np.exp(1j * theta / 2)]
], dtype=complex)
# Three-qubit gates (8x8 matrices)
@staticmethod
def CCX() -> GateMatrix:
"""Toffoli (CCX) gate."""
mat = np.eye(8, dtype=complex)
mat[6, 6] = 0
mat[7, 7] = 0
mat[6, 7] = 1
mat[7, 6] = 1
return mat
@staticmethod
def CSWAP() -> GateMatrix:
"""Fredkin (CSWAP) gate."""
mat = np.eye(8, dtype=complex)
mat[5, 5] = 0
mat[6, 6] = 0
mat[5, 6] = 1
mat[6, 5] = 1
return mat
@classmethod
def get_gate(cls, name: str, params: list[float] | None = None) -> GateMatrix:
"""Get gate matrix by name with optional parameters."""
name = name.lower()
params = params or []
gate_map: dict[str, Callable[..., GateMatrix]] = {
'id': cls.I,
'i': cls.I,
'x': cls.X,
'y': cls.Y,
'z': cls.Z,
'h': cls.H,
's': cls.S,
'sdg': cls.Sdg,
't': cls.T,
'tdg': cls.Tdg,
'sx': cls.SX,
'rx': cls.Rx,
'ry': cls.Ry,
'rz': cls.Rz,
'p': cls.P,
'u': cls.U,
'u3': cls.U,
'cx': cls.CX,
'cnot': cls.CX,
'cy': cls.CY,
'cz': cls.CZ,
'swap': cls.SWAP,
'iswap': cls.iSWAP,
'cp': cls.CP,
'crx': cls.CRx,
'cry': cls.CRy,
'crz': cls.CRz,
'ccx': cls.CCX,
'toffoli': cls.CCX,
'cswap': cls.CSWAP,
'fredkin': cls.CSWAP,
}
if name not in gate_map:
raise ValueError(f"Unknown gate: {name}")
gate_func = gate_map[name]
# Check parameter count
if name in ('rx', 'ry', 'rz', 'p', 'crx', 'cry', 'crz', 'cp'):
if len(params) != 1:
raise ValueError(f"Gate {name} requires 1 parameter")
return gate_func(params[0])
elif name in ('u', 'u3'):
if len(params) != 3:
raise ValueError(f"Gate {name} requires 3 parameters")
return gate_func(*params)
else:
return gate_func()
@classmethod
def get_gate_info(cls, name: str) -> dict[str, any]:
"""Get information about a gate."""
name = name.lower()
single_gates = {'id', 'i', 'x', 'y', 'z', 'h', 's', 'sdg', 't', 'tdg', 'sx'}
param_single_gates = {'rx', 'ry', 'rz', 'p'}
u_gates = {'u', 'u3'}
two_qubit_gates = {'cx', 'cnot', 'cy', 'cz', 'swap', 'iswap'}
param_two_qubit_gates = {'cp', 'crx', 'cry', 'crz'}
three_qubit_gates = {'ccx', 'toffoli', 'cswap', 'fredkin'}
if name in single_gates:
return {'qubits': 1, 'params': 0, 'type': 'single'}
elif name in param_single_gates:
return {'qubits': 1, 'params': 1, 'type': 'single_param'}
elif name in u_gates:
return {'qubits': 1, 'params': 3, 'type': 'single_param'}
elif name in two_qubit_gates:
return {'qubits': 2, 'params': 0, 'type': 'two'}
elif name in param_two_qubit_gates:
return {'qubits': 2, 'params': 1, 'type': 'two_param'}
elif name in three_qubit_gates:
return {'qubits': 3, 'params': 0, 'type': 'three'}
else:
raise ValueError(f"Unknown gate: {name}")
|