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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
| import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize from mpl_toolkits.mplot3d import Axes3D import seaborn as sns
np.random.seed(42)
class QuantumStateEstimator: """ A class for quantum state estimation using maximum likelihood estimation with Pauli measurements on a single qubit. """ def __init__(self): self.I = np.array([[1, 0], [0, 1]], dtype=complex) self.X = np.array([[0, 1], [1, 0]], dtype=complex) self.Y = np.array([[0, -1j], [1j, 0]], dtype=complex) self.Z = np.array([[1, 0], [0, -1]], dtype=complex) self.measurements = { 'X': [(self.I + self.X)/2, (self.I - self.X)/2], 'Y': [(self.I + self.Y)/2, (self.I - self.Y)/2], 'Z': [(self.I + self.Z)/2, (self.I - self.Z)/2] } def bloch_to_density_matrix(self, r): """ Convert Bloch vector to density matrix Args: r: Bloch vector [rx, ry, rz] Returns: 2x2 density matrix """ rx, ry, rz = r return 0.5 * (self.I + rx*self.X + ry*self.Y + rz*self.Z) def density_matrix_to_bloch(self, rho): """ Convert density matrix to Bloch vector Args: rho: 2x2 density matrix Returns: Bloch vector [rx, ry, rz] """ rx = 2 * np.real(rho[0, 1]) ry = 2 * np.imag(rho[1, 0]) rz = np.real(rho[0, 0] - rho[1, 1]) return np.array([rx, ry, rz]) def generate_measurements(self, true_state, num_measurements_per_basis=1000): """ Generate measurement data for a given quantum state Args: true_state: Bloch vector of the true state num_measurements_per_basis: Number of measurements per Pauli basis Returns: Dictionary containing measurement counts """ rho_true = self.bloch_to_density_matrix(true_state) measurement_data = {} for basis in ['X', 'Y', 'Z']: counts = {'positive': 0, 'negative': 0} for _ in range(num_measurements_per_basis): prob_positive = np.real(np.trace(rho_true @ self.measurements[basis][0])) prob_negative = np.real(np.trace(rho_true @ self.measurements[basis][1])) if np.random.random() < prob_positive: counts['positive'] += 1 else: counts['negative'] += 1 measurement_data[basis] = counts return measurement_data def likelihood_function(self, r, measurement_data): """ Calculate the likelihood function for given Bloch vector Args: r: Bloch vector [rx, ry, rz] measurement_data: Dictionary of measurement counts Returns: Negative log-likelihood (for minimization) """ if np.linalg.norm(r) > 1: return 1e10 rho = self.bloch_to_density_matrix(r) log_likelihood = 0 for basis in ['X', 'Y', 'Z']: prob_positive = np.real(np.trace(rho @ self.measurements[basis][0])) prob_negative = np.real(np.trace(rho @ self.measurements[basis][1])) epsilon = 1e-10 prob_positive = max(prob_positive, epsilon) prob_negative = max(prob_negative, epsilon) n_pos = measurement_data[basis]['positive'] n_neg = measurement_data[basis]['negative'] log_likelihood += n_pos * np.log(prob_positive) + n_neg * np.log(prob_negative) return -log_likelihood def estimate_state(self, measurement_data, initial_guess=None): """ Estimate quantum state using maximum likelihood estimation Args: measurement_data: Dictionary of measurement counts initial_guess: Initial guess for Bloch vector Returns: Estimated Bloch vector and optimization result """ if initial_guess is None: initial_guess = np.random.uniform(-0.5, 0.5, 3) constraint = {'type': 'ineq', 'fun': lambda r: 1 - np.linalg.norm(r)} result = minimize( self.likelihood_function, initial_guess, args=(measurement_data,), method='SLSQP', constraints=constraint, options={'maxiter': 1000} ) return result.x, result
def run_quantum_state_estimation(): """ Main function to run the quantum state estimation analysis """ estimator = QuantumStateEstimator() true_bloch_vector = np.array([1.0, 0.0, 0.0]) print("True Bloch vector:", true_bloch_vector) print("True state: |+⟩ = (|0⟩ + |1⟩)/√2") measurement_data = estimator.generate_measurements(true_bloch_vector, num_measurements_per_basis=1000) print("\nMeasurement data:") for basis, counts in measurement_data.items(): total = counts['positive'] + counts['negative'] print(f"{basis}-basis: +1 outcomes: {counts['positive']}/{total} ({counts['positive']/total:.3f})") estimated_bloch, optimization_result = estimator.estimate_state(measurement_data) print(f"\nEstimated Bloch vector: [{estimated_bloch[0]:.4f}, {estimated_bloch[1]:.4f}, {estimated_bloch[2]:.4f}]") print(f"Estimation error: {np.linalg.norm(estimated_bloch - true_bloch_vector):.4f}") print(f"Optimization success: {optimization_result.success}") def analyze_measurement_efficiency(): """ Analyze how estimation accuracy depends on the number of measurements """ measurement_counts = [50, 100, 200, 500, 1000, 2000, 5000] num_trials = 20 errors = [] error_std = [] for n_measurements in measurement_counts: trial_errors = [] for _ in range(num_trials): data = estimator.generate_measurements(true_bloch_vector, n_measurements) estimated, _ = estimator.estimate_state(data) error = np.linalg.norm(estimated - true_bloch_vector) trial_errors.append(error) errors.append(np.mean(trial_errors)) error_std.append(np.std(trial_errors)) return measurement_counts, errors, error_std print("\nAnalyzing measurement efficiency...") measurement_counts, errors, error_std = analyze_measurement_efficiency() print("\nAnalyzing convergence across multiple runs...") num_runs = 10 convergence_data = [] for run in range(num_runs): run_data = estimator.generate_measurements(true_bloch_vector, num_measurements_per_basis=1000) estimated_run, _ = estimator.estimate_state(run_data) error = np.linalg.norm(estimated_run - true_bloch_vector) convergence_data.append(error) plt.style.use('seaborn-v0_8') fig = plt.figure(figsize=(20, 15)) ax1 = fig.add_subplot(2, 3, 1, projection='3d') u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x_sphere = np.outer(np.cos(u), np.sin(v)) y_sphere = np.outer(np.sin(u), np.sin(v)) z_sphere = np.outer(np.ones(np.size(u)), np.cos(v)) ax1.plot_surface(x_sphere, y_sphere, z_sphere, alpha=0.1, color='lightblue') ax1.quiver(0, 0, 0, 1.2, 0, 0, color='red', arrow_length_ratio=0.1, linewidth=2) ax1.quiver(0, 0, 0, 0, 1.2, 0, color='green', arrow_length_ratio=0.1, linewidth=2) ax1.quiver(0, 0, 0, 0, 0, 1.2, color='blue', arrow_length_ratio=0.1, linewidth=2) ax1.quiver(0, 0, 0, true_bloch_vector[0], true_bloch_vector[1], true_bloch_vector[2], color='red', arrow_length_ratio=0.1, linewidth=4, label='True State') ax1.quiver(0, 0, 0, estimated_bloch[0], estimated_bloch[1], estimated_bloch[2], color='orange', arrow_length_ratio=0.1, linewidth=4, label='Estimated State') ax1.set_xlabel('X') ax1.set_ylabel('Y') ax1.set_zlabel('Z') ax1.set_title('Bloch Sphere Representation') ax1.legend() ax1.set_xlim([-1.5, 1.5]) ax1.set_ylim([-1.5, 1.5]) ax1.set_zlim([-1.5, 1.5]) ax2 = fig.add_subplot(2, 3, 2) bases = ['X', 'Y', 'Z'] positive_counts = [measurement_data[basis]['positive'] for basis in bases] negative_counts = [measurement_data[basis]['negative'] for basis in bases] x_pos = np.arange(len(bases)) width = 0.35 bars1 = ax2.bar(x_pos - width/2, positive_counts, width, label='+1 outcomes', color='skyblue') bars2 = ax2.bar(x_pos + width/2, negative_counts, width, label='-1 outcomes', color='lightcoral') ax2.set_xlabel('Measurement Basis') ax2.set_ylabel('Number of Measurements') ax2.set_title('Measurement Outcomes by Basis') ax2.set_xticks(x_pos) ax2.set_xticklabels(bases) ax2.legend() for bar in bars1: height = bar.get_height() ax2.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', ha='center', va='bottom') for bar in bars2: height = bar.get_height() ax2.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', ha='center', va='bottom') ax3 = fig.add_subplot(2, 3, 3) ax3.errorbar(measurement_counts, errors, yerr=error_std, marker='o', capsize=5, capthick=2, color='purple', linewidth=2, markersize=8) ax3.set_xlabel('Number of Measurements per Basis') ax3.set_ylabel('Estimation Error') ax3.set_title('Estimation Accuracy vs Measurement Count') ax3.grid(True, alpha=0.3) ax3.set_xscale('log') ax3.set_yscale('log') theoretical_scaling = 1.0 / np.sqrt(np.array(measurement_counts)) theoretical_scaling = theoretical_scaling * (errors[0] / theoretical_scaling[0]) ax3.plot(measurement_counts, theoretical_scaling, '--', color='red', linewidth=2, label=r'$1/\sqrt{N}$ scaling') ax3.legend() ax4 = fig.add_subplot(2, 3, 4) rx_range = np.linspace(-1, 1, 50) ry_range = np.linspace(-1, 1, 50) RX, RY = np.meshgrid(rx_range, ry_range) likelihood_values = np.zeros_like(RX) for i in range(len(rx_range)): for j in range(len(ry_range)): r = np.array([RX[j, i], RY[j, i], 0]) if np.linalg.norm(r) <= 1: likelihood_values[j, i] = -estimator.likelihood_function(r, measurement_data) else: likelihood_values[j, i] = np.nan contour = ax4.contourf(RX, RY, likelihood_values, levels=20, cmap='viridis') ax4.contour(RX, RY, likelihood_values, levels=20, colors='white', alpha=0.3, linewidths=0.5) plt.colorbar(contour, ax=ax4, label='Log-Likelihood') ax4.plot(true_bloch_vector[0], true_bloch_vector[1], 'r*', markersize=15, label='True State') ax4.plot(estimated_bloch[0], estimated_bloch[1], 'o', color='orange', markersize=10, label='Estimated State') ax4.set_xlabel('rx') ax4.set_ylabel('ry') ax4.set_title('Likelihood Landscape (rz = 0)') ax4.legend() ax4.set_aspect('equal') theta = np.linspace(0, 2*np.pi, 100) ax4.plot(np.cos(theta), np.sin(theta), 'k--', alpha=0.5, linewidth=2) ax5 = fig.add_subplot(2, 3, 5) bases = ['X', 'Y', 'Z'] true_probs = [] estimated_probs = [] measured_probs = [] rho_true = estimator.bloch_to_density_matrix(true_bloch_vector) rho_estimated = estimator.bloch_to_density_matrix(estimated_bloch) for basis in bases: prob_true = np.real(np.trace(rho_true @ estimator.measurements[basis][0])) true_probs.append(prob_true) prob_estimated = np.real(np.trace(rho_estimated @ estimator.measurements[basis][0])) estimated_probs.append(prob_estimated) total_measurements = measurement_data[basis]['positive'] + measurement_data[basis]['negative'] prob_measured = measurement_data[basis]['positive'] / total_measurements measured_probs.append(prob_measured) x_pos = np.arange(len(bases)) width = 0.25 bars1 = ax5.bar(x_pos - width, true_probs, width, label='True', color='blue', alpha=0.7) bars2 = ax5.bar(x_pos, estimated_probs, width, label='Estimated', color='orange', alpha=0.7) bars3 = ax5.bar(x_pos + width, measured_probs, width, label='Measured', color='green', alpha=0.7) ax5.set_xlabel('Measurement Basis') ax5.set_ylabel('Probability of +1 Outcome') ax5.set_title('Measurement Probabilities Comparison') ax5.set_xticks(x_pos) ax5.set_xticklabels(bases) ax5.legend() ax5.set_ylim(0, 1) for bars in [bars1, bars2, bars3]: for bar in bars: height = bar.get_height() ax5.text(bar.get_x() + bar.get_width()/2., height + 0.01, f'{height:.3f}', ha='center', va='bottom', fontsize=9) ax6 = fig.add_subplot(2, 3, 6) ax6.bar(range(1, num_runs + 1), convergence_data, color='lightblue', alpha=0.7) ax6.axhline(y=np.mean(convergence_data), color='red', linestyle='--', label=f'Mean Error: {np.mean(convergence_data):.4f}') ax6.set_xlabel('Run Number') ax6.set_ylabel('Estimation Error') ax6.set_title('Estimation Error Across Multiple Runs') ax6.legend() ax6.grid(True, alpha=0.3) plt.tight_layout() plt.show() print("\n" + "="*60) print("DETAILED ANALYSIS OF QUANTUM STATE ESTIMATION") print("="*60) print(f"\n1. STATE INFORMATION:") print(f" True Bloch vector: [{true_bloch_vector[0]:.4f}, {true_bloch_vector[1]:.4f}, {true_bloch_vector[2]:.4f}]") print(f" Estimated Bloch vector: [{estimated_bloch[0]:.4f}, {estimated_bloch[1]:.4f}, {estimated_bloch[2]:.4f}]") print(f" Estimation error: {np.linalg.norm(estimated_bloch - true_bloch_vector):.4f}") print(f"\n2. MEASUREMENT STATISTICS:") total_measurements = sum(measurement_data[basis]['positive'] + measurement_data[basis]['negative'] for basis in ['X', 'Y', 'Z']) print(f" Total measurements: {total_measurements}") for basis in ['X', 'Y', 'Z']: pos = measurement_data[basis]['positive'] neg = measurement_data[basis]['negative'] total = pos + neg print(f" {basis}-basis: {pos}/{total} positive ({pos/total:.3f})") print(f"\n3. EFFICIENCY ANALYSIS:") print(f" Minimum measurements needed for ~0.1 error: {measurement_counts[np.argmax(np.array(errors) < 0.1)]}") print(f" Error reduction factor (50→5000 measurements): {errors[0]/errors[-1]:.2f}x") print(f"\n4. STATISTICAL PROPERTIES:") print(f" Mean error across runs: {np.mean(convergence_data):.4f} ± {np.std(convergence_data):.4f}") print(f" Minimum error observed: {np.min(convergence_data):.4f}") print(f" Maximum error observed: {np.max(convergence_data):.4f}") print(f"\n5. FISHER INFORMATION BOUNDS:") fisher_info = 4 * 1000 cramer_rao_bound = 1 / np.sqrt(fisher_info) print(f" Theoretical Cramér-Rao bound: {cramer_rao_bound:.4f}") print(f" Actual error: {np.linalg.norm(estimated_bloch - true_bloch_vector):.4f}") print(f" Efficiency ratio: {cramer_rao_bound / np.linalg.norm(estimated_bloch - true_bloch_vector):.2f}") print("\n" + "="*60) return estimator, true_bloch_vector, estimated_bloch, measurement_data, errors, convergence_data
if __name__ == "__main__": results = run_quantum_state_estimation()
|