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
| import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize from mpl_toolkits.mplot3d import Axes3D import seaborn as sns
plt.style.use('default') sns.set_palette("husl")
class QuantumCorrelationOptimizer: """ A class to optimize quantum correlations in Bell-type experiments. Specifically designed for CHSH inequality optimization. """ def __init__(self): self.optimal_angles = None self.max_chsh_value = None def correlation_function(self, a, b): """ Correlation function for Bell state |ψ⟩ = (|00⟩ + |11⟩)/√2 Parameters: a, b: measurement angles for Alice and Bob Returns: Correlation E(a,b) = cos(a - b) """ return np.cos(a - b) def chsh_parameter(self, angles): """ Calculate CHSH parameter S for given measurement angles Parameters: angles: array [a1, a2, b1, b2] - measurement angles for Alice and Bob Returns: CHSH parameter S = |E(a1,b1) + E(a1,b2) + E(a2,b1) - E(a2,b2)| """ a1, a2, b1, b2 = angles E11 = self.correlation_function(a1, b1) E12 = self.correlation_function(a1, b2) E21 = self.correlation_function(a2, b1) E22 = self.correlation_function(a2, b2) S = abs(E11 + E12 + E21 - E22) return S def objective_function(self, angles): """ Objective function to minimize (negative CHSH parameter) """ return -self.chsh_parameter(angles) def optimize_correlations(self, num_trials=10): """ Optimize quantum correlations by maximizing CHSH parameter Parameters: num_trials: number of optimization trials with different initial conditions Returns: Dictionary containing optimization results """ best_result = None best_chsh = -np.inf results_history = [] for trial in range(num_trials): initial_angles = np.random.uniform(0, 2*np.pi, 4) result = minimize( self.objective_function, initial_angles, method='BFGS', options={'maxiter': 1000} ) chsh_value = -result.fun results_history.append({ 'trial': trial, 'angles': result.x, 'chsh_value': chsh_value, 'success': result.success }) if chsh_value > best_chsh: best_chsh = chsh_value best_result = result self.optimal_angles = best_result.x self.max_chsh_value = best_chsh return { 'optimal_angles': self.optimal_angles, 'max_chsh_value': self.max_chsh_value, 'all_results': results_history, 'theoretical_max': 2*np.sqrt(2) } def analyze_angle_sensitivity(self, resolution=100): """ Analyze sensitivity of CHSH parameter to angle variations """ if self.optimal_angles is None: raise ValueError("Run optimization first!") a1_opt, a2_opt, b1_opt, b2_opt = self.optimal_angles delta_range = np.linspace(-np.pi/4, np.pi/4, resolution) chsh_values = np.zeros((resolution, 4)) for i, delta in enumerate(delta_range): angles_a1 = [a1_opt + delta, a2_opt, b1_opt, b2_opt] angles_a2 = [a1_opt, a2_opt + delta, b1_opt, b2_opt] angles_b1 = [a1_opt, a2_opt, b1_opt + delta, b2_opt] angles_b2 = [a1_opt, a2_opt, b1_opt, b2_opt + delta] chsh_values[i, 0] = self.chsh_parameter(angles_a1) chsh_values[i, 1] = self.chsh_parameter(angles_a2) chsh_values[i, 2] = self.chsh_parameter(angles_b1) chsh_values[i, 3] = self.chsh_parameter(angles_b2) return delta_range, chsh_values
optimizer = QuantumCorrelationOptimizer() print("Optimizing quantum correlations for CHSH Bell inequality...") optimization_results = optimizer.optimize_correlations(num_trials=20)
print(f"\n=== Optimization Results ===") print(f"Maximum CHSH parameter: {optimization_results['max_chsh_value']:.6f}") print(f"Theoretical quantum bound: {optimization_results['theoretical_max']:.6f}") print(f"Violation ratio: {optimization_results['max_chsh_value']/2:.6f}")
optimal_angles = optimization_results['optimal_angles'] print(f"\nOptimal measurement angles (radians):") print(f"Alice's angles: a₁ = {optimal_angles[0]:.6f}, a₂ = {optimal_angles[1]:.6f}") print(f"Bob's angles: b₁ = {optimal_angles[2]:.6f}, b₂ = {optimal_angles[3]:.6f}")
print(f"\nOptimal measurement angles (degrees):") print(f"Alice's angles: a₁ = {np.degrees(optimal_angles[0]):.2f}°, a₂ = {np.degrees(optimal_angles[1]):.2f}°") print(f"Bob's angles: b₁ = {np.degrees(optimal_angles[2]):.2f}°, b₂ = {np.degrees(optimal_angles[3]):.2f}°")
all_results = optimization_results['all_results'] successful_trials = [r for r in all_results if r['success']] print(f"\nSuccessful optimization trials: {len(successful_trials)}/{len(all_results)}")
fig = plt.figure(figsize=(20, 15))
ax1 = plt.subplot(3, 3, 1) trial_numbers = [r['trial'] for r in all_results] chsh_values = [r['chsh_value'] for r in all_results] colors = ['green' if r['success'] else 'red' for r in all_results]
plt.scatter(trial_numbers, chsh_values, c=colors, alpha=0.7, s=60) plt.axhline(y=2*np.sqrt(2), color='blue', linestyle='--', linewidth=2, label='Quantum bound (2√2)') plt.axhline(y=2, color='red', linestyle='--', linewidth=2, label='Classical bound (2)') plt.xlabel('Trial Number') plt.ylabel('CHSH Parameter') plt.title('Optimization Convergence Across Trials') plt.legend() plt.grid(True, alpha=0.3)
delta_range, chsh_sensitivity = optimizer.analyze_angle_sensitivity(resolution=150)
ax2 = plt.subplot(3, 3, 2) angle_labels = ['a₁', 'a₂', 'b₁', 'b₂'] colors_sens = plt.cm.viridis(np.linspace(0, 1, 4))
for i in range(4): plt.plot(delta_range, chsh_sensitivity[:, i], label=f'{angle_labels[i]} variation', linewidth=2.5, color=colors_sens[i])
plt.axhline(y=optimization_results['max_chsh_value'], color='red', linestyle=':', alpha=0.7, label='Optimal CHSH') plt.xlabel('Angle Deviation (radians)') plt.ylabel('CHSH Parameter') plt.title('CHSH Sensitivity to Angle Variations') plt.legend() plt.grid(True, alpha=0.3)
ax3 = plt.subplot(3, 3, 3) angle_range = np.linspace(0, 2*np.pi, 100) a1_grid, b1_grid = np.meshgrid(angle_range, angle_range) chsh_grid = np.zeros_like(a1_grid)
a2_fixed, b2_fixed = optimal_angles[1], optimal_angles[3]
for i in range(100): for j in range(100): angles = [a1_grid[i,j], a2_fixed, b1_grid[i,j], b2_fixed] chsh_grid[i,j] = optimizer.chsh_parameter(angles)
im = plt.imshow(chsh_grid, extent=[0, 2*np.pi, 0, 2*np.pi], cmap='plasma', aspect='auto', origin='lower') plt.colorbar(im, ax=ax3, label='CHSH Parameter') plt.contour(a1_grid, b1_grid, chsh_grid, levels=10, colors='white', alpha=0.5) plt.xlabel('Alice angle a₁ (radians)') plt.ylabel('Bob angle b₁ (radians)') plt.title('CHSH Landscape (a₁, b₁)')
plt.plot(optimal_angles[0], optimal_angles[2], 'r*', markersize=15, label='Optimal') plt.legend()
ax4 = plt.subplot(3, 3, 4) angle_diff = np.linspace(-2*np.pi, 2*np.pi, 300) correlation = np.cos(angle_diff)
plt.plot(angle_diff, correlation, 'b-', linewidth=3, label='E(a,b) = cos(a-b)') plt.axhline(y=0, color='k', linestyle='-', alpha=0.3) plt.axvline(x=0, color='k', linestyle='-', alpha=0.3) plt.xlabel('Angle Difference (a - b)') plt.ylabel('Correlation E(a,b)') plt.title('Bell State Correlation Function') plt.grid(True, alpha=0.3) plt.legend()
opt_diffs = [ optimal_angles[0] - optimal_angles[2], optimal_angles[0] - optimal_angles[3], optimal_angles[1] - optimal_angles[2], optimal_angles[1] - optimal_angles[3] ]
for i, diff in enumerate(opt_diffs): plt.axvline(x=diff, color='red', linestyle='--', alpha=0.7)
ax5 = plt.subplot(3, 3, 5) successful_chsh = [r['chsh_value'] for r in successful_trials]
if successful_chsh: plt.hist(successful_chsh, bins=15, alpha=0.7, color='skyblue', edgecolor='black') plt.axvline(x=np.mean(successful_chsh), color='red', linestyle='--', linewidth=2, label=f'Mean: {np.mean(successful_chsh):.4f}') plt.axvline(x=optimization_results['max_chsh_value'], color='green', linestyle='-', linewidth=2, label=f'Best: {optimization_results["max_chsh_value"]:.4f}') plt.xlabel('CHSH Parameter') plt.ylabel('Frequency') plt.title('Distribution of Optimization Results') plt.legend() plt.grid(True, alpha=0.3)
ax6 = plt.subplot(3, 3, 6) angles_deg = np.degrees(optimal_angles)
theta = np.linspace(0, 2*np.pi, 100) plt.plot(np.cos(theta), np.sin(theta), 'k-', alpha=0.3)
angle_names = ['a₁', 'a₂', 'b₁', 'b₂'] colors_angles = ['red', 'orange', 'blue', 'cyan']
for i, (angle, name, color) in enumerate(zip(optimal_angles, angle_names, colors_angles)): x, y = np.cos(angle), np.sin(angle) plt.arrow(0, 0, x*0.8, y*0.8, head_width=0.05, head_length=0.05, fc=color, ec=color, linewidth=2) plt.text(x*0.9, y*0.9, f'{name}\n{np.degrees(angle):.1f}°', ha='center', va='center', fontsize=10, bbox=dict(boxstyle='round,pad=0.3', facecolor=color, alpha=0.3))
plt.xlim(-1.2, 1.2) plt.ylim(-1.2, 1.2) plt.axis('equal') plt.title('Optimal Measurement Angles') plt.grid(True, alpha=0.3)
ax7 = plt.subplot(3, 3, 7) classical_bound = 2 quantum_bound = 2 * np.sqrt(2) achieved_value = optimization_results['max_chsh_value']
categories = ['Classical\nBound', 'Achieved\nValue', 'Quantum\nBound'] values = [classical_bound, achieved_value, quantum_bound] colors_bar = ['red', 'green', 'blue']
bars = plt.bar(categories, values, color=colors_bar, alpha=0.7, edgecolor='black') plt.ylabel('CHSH Parameter') plt.title('Bell Inequality Violation') plt.grid(True, alpha=0.3, axis='y')
for bar, value in zip(bars, values): height = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2., height + 0.05, f'{value:.4f}', ha='center', va='bottom', fontweight='bold')
ax8 = plt.subplot(3, 3, 8) violation_ratio = achieved_value / classical_bound quantum_ratio = quantum_bound / classical_bound
plt.bar(['Classical Limit', 'Our Achievement', 'Quantum Limit'], [1, violation_ratio, quantum_ratio], color=['red', 'green', 'blue'], alpha=0.7, edgecolor='black') plt.ylabel('Violation Ratio (S/2)') plt.title('Bell Inequality Violation Ratio') plt.grid(True, alpha=0.3, axis='y')
plt.text(0, 1.05, '100%', ha='center', va='bottom', fontweight='bold') plt.text(1, violation_ratio + 0.02, f'{violation_ratio*100:.1f}%', ha='center', va='bottom', fontweight='bold') plt.text(2, quantum_ratio + 0.02, f'{quantum_ratio*100:.1f}%', ha='center', va='bottom', fontweight='bold')
ax9 = plt.subplot(3, 3, 9) ax9.axis('off')
summary_text = f""" OPTIMIZATION SUMMARY
Maximum CHSH Parameter: {optimization_results['max_chsh_value']:.6f} Theoretical Quantum Bound: {quantum_bound:.6f} Achievement Ratio: {(achieved_value/quantum_bound)*100:.2f}%
Optimal Angles (degrees): • Alice: a₁ = {angles_deg[0]:.1f}°, a₂ = {angles_deg[1]:.1f}° • Bob: b₁ = {angles_deg[2]:.1f}°, b₂ = {angles_deg[3]:.1f}°
Bell Inequality Violation: Classical bound: 2.0000 Our result: {achieved_value:.4f} Violation factor: {achieved_value/2:.4f}×
Success Rate: {len(successful_trials)}/{len(all_results)} trials """
plt.text(0.1, 0.9, summary_text, transform=ax9.transAxes, fontsize=11, verticalalignment='top', fontfamily='monospace', bbox=dict(boxstyle='round,pad=0.5', facecolor='lightgray', alpha=0.5))
plt.tight_layout() plt.suptitle('Quantum Correlation Optimization: CHSH Bell Inequality Analysis', fontsize=16, fontweight='bold', y=0.98) plt.show()
print(f"\n=== Theoretical Verification ===") print(f"Expected optimal angle differences for maximum CHSH:") print(f"Theoretical: π/4, 3π/4, π/4, -π/4 (or equivalent)")
actual_diffs = [ (optimal_angles[0] - optimal_angles[2]) % (2*np.pi), (optimal_angles[0] - optimal_angles[3]) % (2*np.pi), (optimal_angles[1] - optimal_angles[2]) % (2*np.pi), (optimal_angles[1] - optimal_angles[3]) % (2*np.pi) ]
print(f"Achieved differences (radians): {[f'{d:.4f}' for d in actual_diffs]}") print(f"Achieved differences (degrees): {[f'{np.degrees(d):.1f}°' for d in actual_diffs]}")
a1, a2, b1, b2 = optimal_angles E11 = optimizer.correlation_function(a1, b1) E12 = optimizer.correlation_function(a1, b2) E21 = optimizer.correlation_function(a2, b1) E22 = optimizer.correlation_function(a2, b2)
print(f"\nIndividual correlation terms:") print(f"E(a₁,b₁) = {E11:.6f}") print(f"E(a₁,b₂) = {E12:.6f}") print(f"E(a₂,b₁) = {E21:.6f}") print(f"E(a₂,b₂) = {E22:.6f}") print(f"CHSH = |{E11:.3f} + {E12:.3f} + {E21:.3f} - {E22:.3f}| = {abs(E11 + E12 + E21 - E22):.6f}")
|