Spaces:
Sleeping
Sleeping
File size: 10,978 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 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 340 341 342 343 344 345 346 347 348 349 350 351 352 |
"""
Statevector Simulator - Lightweight ideal simulator for quantum circuits.
Calculates the final probability vector without noise.
"""
from typing import Any
import numpy as np
from ..creation.gate_library import GateLibrary
def simulate_statevector(
circuit_data: dict[str, Any],
initial_state: list[complex] | None = None
) -> dict[str, Any]:
"""
Simulate a quantum circuit and return the final statevector.
Args:
circuit_data: Circuit dictionary with gates
initial_state: Optional initial state (default: |0...0⟩)
Returns:
Simulation results with statevector and probabilities
"""
num_qubits = circuit_data.get("num_qubits", 0)
gates = circuit_data.get("gates", [])
if num_qubits > 20:
return {
"success": False,
"error": f"Circuit too large for statevector simulation ({num_qubits} qubits). "
f"Maximum supported: 20 qubits (2^20 = 1M amplitudes)."
}
dim = 2 ** num_qubits
# Initialize state
if initial_state:
statevector = np.array(initial_state, dtype=complex)
if len(statevector) != dim:
return {
"success": False,
"error": f"Initial state dimension ({len(statevector)}) doesn't match "
f"circuit dimension ({dim})"
}
else:
# Start in |0...0⟩
statevector = np.zeros(dim, dtype=complex)
statevector[0] = 1.0
# Apply gates
measurement_results: dict[int, int] = {} # qubit -> classical bit value
gates_applied = 0
for gate in gates:
name = gate.get("name", "").lower()
qubits = gate.get("qubits", [])
params = gate.get("params", [])
if name == "barrier":
continue
if name == "measure":
# Simulate measurement
for q in qubits:
prob_0, prob_1 = _get_qubit_probabilities(statevector, q, num_qubits)
# Deterministically collapse to most likely state for reproducibility
result = 0 if prob_0 >= prob_1 else 1
measurement_results[q] = result
statevector = _collapse_state(statevector, q, result, num_qubits)
continue
if name == "reset":
for q in qubits:
statevector = _reset_qubit(statevector, q, num_qubits)
continue
# Skip symbolic parameters
if any(isinstance(p, str) and p.startswith("param:") for p in params):
continue
try:
gate_matrix = GateLibrary.get_gate(name, params if params else None)
statevector = _apply_gate(statevector, gate_matrix, qubits, num_qubits)
gates_applied += 1
except Exception as e:
return {
"success": False,
"error": f"Failed to apply gate '{name}': {str(e)}"
}
# Calculate probabilities
probabilities = np.abs(statevector) ** 2
# Get most likely outcomes
sorted_indices = np.argsort(probabilities)[::-1]
top_outcomes = []
for idx in sorted_indices[:min(16, len(probabilities))]:
if probabilities[idx] > 1e-10:
bitstring = format(idx, f'0{num_qubits}b')
top_outcomes.append({
"state": f"|{bitstring}⟩",
"probability": float(probabilities[idx]),
"amplitude": {
"real": float(statevector[idx].real),
"imag": float(statevector[idx].imag)
}
})
return {
"success": True,
"num_qubits": num_qubits,
"gates_applied": gates_applied,
"statevector_dimension": dim,
"top_outcomes": top_outcomes,
"total_probability": float(np.sum(probabilities)),
"measurement_results": measurement_results,
"statevector": {
"real": statevector.real.tolist(),
"imag": statevector.imag.tolist()
} if num_qubits <= 6 else None, # Only include full statevector for small circuits
}
def _apply_gate(
statevector: np.ndarray,
gate_matrix: np.ndarray,
target_qubits: list[int],
num_qubits: int
) -> np.ndarray:
"""Apply a gate to specific qubits in the statevector."""
dim = 2 ** num_qubits
if len(target_qubits) == 1:
q = target_qubits[0]
new_state = np.zeros_like(statevector)
for i in range(dim):
# Get bit value at position q
bit_q = (i >> q) & 1
# Calculate partner index (flip bit q)
partner = i ^ (1 << q)
if bit_q == 0:
# Apply gate to [amplitude_0, amplitude_1]
amp_0 = statevector[i]
amp_1 = statevector[partner]
new_amp_0 = gate_matrix[0, 0] * amp_0 + gate_matrix[0, 1] * amp_1
new_amp_1 = gate_matrix[1, 0] * amp_0 + gate_matrix[1, 1] * amp_1
new_state[i] = new_amp_0
new_state[partner] = new_amp_1
return new_state
elif len(target_qubits) == 2:
q0, q1 = target_qubits
new_state = np.zeros_like(statevector)
processed = set()
for i in range(dim):
if i in processed:
continue
# Get all 4 basis states for this 2-qubit subspace
bit_q0 = (i >> q0) & 1
bit_q1 = (i >> q1) & 1
# Base index (both qubits = 0)
base = i & ~(1 << q0) & ~(1 << q1)
# Four indices in gate matrix order |control,target⟩:
# |00⟩, |01⟩ (target=1), |10⟩ (control=1), |11⟩
# For CX(control=q0, target=q1), the gate matrix expects this ordering
indices = [
base, # |00⟩
base | (1 << q1), # |01⟩ - target set
base | (1 << q0), # |10⟩ - control set
base | (1 << q0) | (1 << q1) # |11⟩
]
# Extract amplitudes
amps = np.array([statevector[idx] for idx in indices], dtype=complex)
# Apply gate
new_amps = gate_matrix @ amps
# Write back
for j, idx in enumerate(indices):
new_state[idx] = new_amps[j]
processed.add(idx)
return new_state
else:
# For 3+ qubit gates, use general approach
# This is computationally expensive but correct
return _apply_multiqubit_gate(statevector, gate_matrix, target_qubits, num_qubits)
def _apply_multiqubit_gate(
statevector: np.ndarray,
gate_matrix: np.ndarray,
target_qubits: list[int],
num_qubits: int
) -> np.ndarray:
"""Apply a multi-qubit gate using full matrix expansion."""
# Build full gate matrix by tensor products
n = len(target_qubits)
dim = 2 ** num_qubits
# For simplicity, use matrix-vector multiplication with full expansion
# This is O(4^n) but works for small circuits
full_gate = np.eye(dim, dtype=complex)
# This is a simplified implementation
# A proper implementation would use efficient tensor contractions
return full_gate @ statevector
def _get_qubit_probabilities(
statevector: np.ndarray,
qubit: int,
num_qubits: int
) -> tuple[float, float]:
"""Get probability of measuring 0 or 1 on a specific qubit."""
dim = 2 ** num_qubits
prob_0 = 0.0
prob_1 = 0.0
for i in range(dim):
amplitude_sq = abs(statevector[i]) ** 2
if (i >> qubit) & 1:
prob_1 += amplitude_sq
else:
prob_0 += amplitude_sq
return prob_0, prob_1
def _collapse_state(
statevector: np.ndarray,
qubit: int,
result: int,
num_qubits: int
) -> np.ndarray:
"""Collapse statevector after measurement."""
dim = 2 ** num_qubits
new_state = np.zeros_like(statevector)
for i in range(dim):
if ((i >> qubit) & 1) == result:
new_state[i] = statevector[i]
# Renormalize
norm = np.linalg.norm(new_state)
if norm > 0:
new_state /= norm
return new_state
def _reset_qubit(
statevector: np.ndarray,
qubit: int,
num_qubits: int
) -> np.ndarray:
"""Reset a qubit to |0⟩."""
dim = 2 ** num_qubits
new_state = np.zeros_like(statevector)
for i in range(dim):
bit_value = (i >> qubit) & 1
target_idx = i & ~(1 << qubit) # Set qubit to 0
new_state[target_idx] += statevector[i]
# Renormalize
norm = np.linalg.norm(new_state)
if norm > 0:
new_state /= norm
return new_state
def sample_circuit(
circuit_data: dict[str, Any],
shots: int = 1024
) -> dict[str, Any]:
"""
Sample measurement outcomes from a circuit.
Args:
circuit_data: Circuit dictionary
shots: Number of samples
Returns:
Histogram of measurement outcomes
"""
# First get the statevector
sim_result = simulate_statevector(circuit_data)
if not sim_result.get("success", False):
return sim_result
num_qubits = sim_result["num_qubits"]
dim = 2 ** num_qubits
# Get probabilities from statevector
sv = sim_result.get("statevector", {})
if sv:
real = np.array(sv["real"])
imag = np.array(sv["imag"])
statevector = real + 1j * imag
probabilities = np.abs(statevector) ** 2
else:
# Reconstruct from top outcomes
probabilities = np.zeros(dim)
for outcome in sim_result.get("top_outcomes", []):
state = outcome["state"]
bitstring = state[1:-1] # Remove |⟩
idx = int(bitstring, 2)
probabilities[idx] = outcome["probability"]
# Sample
indices = np.random.choice(dim, size=shots, p=probabilities)
counts: dict[str, int] = {}
for idx in indices:
bitstring = format(idx, f'0{num_qubits}b')
counts[bitstring] = counts.get(bitstring, 0) + 1
# Sort by count
sorted_counts = dict(sorted(counts.items(), key=lambda x: -x[1]))
# Build probabilities dict with bitstring keys
prob_dict: dict[str, float] = {}
for idx in range(dim):
prob = float(probabilities[idx])
if prob > 1e-10: # Only include non-zero probabilities
bitstring = format(idx, f'0{num_qubits}b')
prob_dict[bitstring] = prob
return {
"success": True,
"shots": shots,
"counts": sorted_counts,
"probabilities": prob_dict,
"most_frequent": list(sorted_counts.keys())[0] if sorted_counts else None,
}
|