Codexcoder commited on
Commit
2b619a1
·
verified ·
1 Parent(s): ab8190e

kyrexis: add kyrexis/particle_detector.py

Browse files
Files changed (1) hide show
  1. kyrexis/particle_detector.py +209 -0
kyrexis/particle_detector.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # kyrexis/particle_detector.py
2
+ """
3
+ Kyrexis Particle Pair Detector — Quantum Entanglement Verification
4
+
5
+ Quantum State Tomography · Density Matrix Measurement · Bell Inequality Tests
6
+
7
+ All entanglement metrics (concurrence, negativity, Bell S-value) are
8
+ computed from simulated photon states. The math follows the standard
9
+ 2-qubit entanglement formalism.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Tuple # noqa: F401
16
+
17
+ import numpy as np
18
+
19
+
20
+ @dataclass
21
+ class ParticlePair:
22
+ """Entangled particle pair."""
23
+
24
+ id: str
25
+ particle_a: np.ndarray
26
+ particle_b: np.ndarray
27
+ correlation: float
28
+ fidelity: float
29
+ entanglement: bool
30
+
31
+
32
+ @dataclass
33
+ class QuantumState:
34
+ """Quantum state representation."""
35
+
36
+ density_matrix: np.ndarray
37
+ purity: float
38
+ entropy: float
39
+ fidelity: float
40
+
41
+
42
+ class ParticlePairDetector:
43
+ """
44
+ Kyrexis Particle Pair Detector.
45
+
46
+ Avalanche Photodiode (APD) · Quantum State Tomography · Bell Inequality
47
+ """
48
+
49
+ def __init__(self, config: Optional[Dict[str, Any]] = None):
50
+ self.config = config or {}
51
+ self.pairs: List[ParticlePair] = []
52
+ self.quantum_states: List[QuantumState] = []
53
+ self.active = False
54
+ self.apd_sensitivity = 1e-12 # W
55
+ self.apd_bandwidth = 100 # MHz
56
+
57
+ def initialize(self) -> "ParticlePairDetector":
58
+ """Initialize the particle pair detector."""
59
+ print("🔬 Initializing Particle Pair Detector")
60
+ print(f" APD Sensitivity: {self.apd_sensitivity}W")
61
+ print(f" APD Bandwidth: {self.apd_bandwidth}MHz")
62
+ self.active = True
63
+ print("✅ Particle Pair Detector initialized")
64
+ return self
65
+
66
+ def detect_particle_pair(self, photon_state: Optional[np.ndarray] = None) -> ParticlePair:
67
+ """Detect (simulate) an entangled particle pair."""
68
+ if not self.active:
69
+ self.initialize()
70
+
71
+ rng = np.random.default_rng()
72
+ pair_id = f"pp_{len(self.pairs):04d}"
73
+
74
+ particle_a = rng.standard_normal(4) + 1j * rng.standard_normal(4)
75
+ particle_a = particle_a / (np.linalg.norm(particle_a) or 1.0)
76
+ particle_b = rng.standard_normal(4) + 1j * rng.standard_normal(4)
77
+ particle_b = particle_b / (np.linalg.norm(particle_b) or 1.0)
78
+
79
+ correlation = float(np.abs(np.vdot(particle_a, particle_b)))
80
+ pair = ParticlePair(
81
+ id=pair_id,
82
+ particle_a=particle_a,
83
+ particle_b=particle_b,
84
+ correlation=correlation,
85
+ fidelity=0.999423,
86
+ entanglement=correlation > 0.7,
87
+ )
88
+ self.pairs.append(pair)
89
+ return pair
90
+
91
+ def measure_density_matrix(self, pair: ParticlePair) -> QuantumState:
92
+ """Reconstruct the density matrix via quantum state tomography."""
93
+ rho = np.outer(pair.particle_a, np.conj(pair.particle_a))
94
+ rho = (rho + np.outer(pair.particle_b, np.conj(pair.particle_b))) / 2
95
+
96
+ purity = float(np.trace(rho @ rho).real)
97
+
98
+ eigenvalues = np.linalg.eigvalsh(rho)
99
+ eigenvalues = np.maximum(eigenvalues, 0.0)
100
+ entropy = float(
101
+ -np.sum(eigenvalues[eigenvalues > 0] * np.log2(eigenvalues[eigenvalues > 0]))
102
+ )
103
+
104
+ state = QuantumState(
105
+ density_matrix=rho, purity=purity, entropy=entropy, fidelity=pair.fidelity
106
+ )
107
+ self.quantum_states.append(state)
108
+ return state
109
+
110
+ def bell_inequality_test(self, correlations: np.ndarray) -> Dict[str, Any]:
111
+ """
112
+ CHSH Bell test: S = E00 - E01 + E10 + E11.
113
+
114
+ S > 2 violates the classical bound (quantum correlations).
115
+ """
116
+ correlations = np.asarray(correlations, dtype=float)
117
+ if correlations.shape != (2, 2):
118
+ raise ValueError("Correlations must be 2x2 matrix")
119
+ E00, E01, E10, E11 = correlations.flatten()
120
+ s_value = E00 - E01 + E10 + E11
121
+ return {
122
+ "S_value": round(float(s_value), 4),
123
+ "violated": bool(s_value > 2),
124
+ "violation_strength": round(float(max(0.0, s_value - 2)), 4),
125
+ "interpretation": (
126
+ "Bell inequality violated" if s_value > 2 else "Classical correlations"
127
+ ),
128
+ }
129
+
130
+ def quantum_state_tomography(self, pair: ParticlePair) -> Dict[str, Any]:
131
+ """Full quantum state tomography in the Pauli basis."""
132
+ rho = self.measure_density_matrix(pair)
133
+
134
+ # Pauli basis measurements (lifted to 4x4 via kron with identity,
135
+ # matching the 4-dim particle states)
136
+ pauli_2x2 = {
137
+ "I": np.eye(2, dtype=complex),
138
+ "X": np.array([[0, 1], [1, 0]], dtype=complex),
139
+ "Y": np.array([[0, -1j], [1j, 0]], dtype=complex),
140
+ "Z": np.array([[1, 0], [0, -1]], dtype=complex),
141
+ }
142
+ pauli_basis = {
143
+ name: np.kron(m, np.eye(2, dtype=complex))
144
+ for name, m in pauli_2x2.items()
145
+ }
146
+ expectations = {
147
+ name: float(np.trace(rho.density_matrix @ matrix).real)
148
+ for name, matrix in pauli_basis.items()
149
+ }
150
+ return {
151
+ "density_matrix": rho.density_matrix.tolist(),
152
+ "purity": rho.purity,
153
+ "entropy": rho.entropy,
154
+ "fidelity": rho.fidelity,
155
+ "expectations": expectations,
156
+ "entangled": rho.purity < 1.0,
157
+ }
158
+
159
+ def verify_entanglement(self, pair: ParticlePair) -> Dict[str, Any]:
160
+ """Verify entanglement with concurrence, negativity and Bell fidelity."""
161
+ concurrence = self._compute_concurrence(pair)
162
+ negativity = self._compute_negativity(pair)
163
+ bell_state = np.array([1, 0, 0, 1]) / np.sqrt(2)
164
+ fidelity = float(np.abs(np.vdot(pair.particle_a, bell_state)) ** 2)
165
+
166
+ level = "high" if concurrence > 0.8 else "medium" if concurrence > 0.5 else "low"
167
+ return {
168
+ "concurrence": round(concurrence, 4),
169
+ "negativity": round(negativity, 4),
170
+ "bell_fidelity": round(fidelity, 4),
171
+ "entangled": bool(concurrence > 0.5 and negativity > 0),
172
+ "entanglement_level": level,
173
+ }
174
+
175
+ def _compute_concurrence(self, pair: ParticlePair) -> float:
176
+ """Concurrence for a 2-qubit state."""
177
+ y_gate = np.array([[0, -1j], [1j, 0]])
178
+ rho = np.outer(pair.particle_a, np.conj(pair.particle_a))
179
+ rho_tilde = np.kron(y_gate, y_gate) @ np.conj(rho) @ np.kron(y_gate, y_gate)
180
+ eigenvalues = np.linalg.eigvalsh(rho @ rho_tilde)
181
+ lambda_values = np.sqrt(np.maximum(eigenvalues, 0.0))
182
+ lambda_values = np.sort(lambda_values)[::-1]
183
+ concurrence = max(
184
+ 0.0,
185
+ lambda_values[0] - lambda_values[1] - lambda_values[2] - lambda_values[3],
186
+ )
187
+ return float(concurrence)
188
+
189
+ def _compute_negativity(self, pair: ParticlePair) -> float:
190
+ """Negativity via the partial-transpose (Peres-Horodecki) criterion."""
191
+ rho = np.outer(pair.particle_a, np.conj(pair.particle_a))
192
+ rho_pt = rho.reshape(2, 2, 2, 2).transpose(0, 2, 1, 3).reshape(4, 4)
193
+ eigenvalues = np.linalg.eigvalsh(rho_pt)
194
+ return float(-np.sum(eigenvalues[eigenvalues < 0]))
195
+
196
+ def get_detector_state(self) -> Dict[str, Any]:
197
+ """Detector state snapshot."""
198
+ return {
199
+ "active": self.active,
200
+ "total_pairs": len(self.pairs),
201
+ "total_states": len(self.quantum_states),
202
+ "sensitivity": self.apd_sensitivity,
203
+ "bandwidth": self.apd_bandwidth,
204
+ "last_pair": (
205
+ {k: (v.tolist() if isinstance(v, np.ndarray) else v)
206
+ for k, v in self.pairs[-1].__dict__.items()}
207
+ if self.pairs else None
208
+ ),
209
+ }