Download kyrexis/particle_detector.py from Codexcoder/kyrexis-module: direct link, hf CLI and curl.
- Browser
- Download file 7.78 kB
-
https://huggingface.co/datasets/Codexcoder/kyrexis-module/resolve/main/kyrexis/particle_detector.py
- Command line
-
hf download hf://datasets/Codexcoder/kyrexis-module/kyrexis/particle_detector.py
-
curl -L -o particle_detector.py https://huggingface.co/datasets/Codexcoder/kyrexis-module/resolve/main/kyrexis/particle_detector.py
7.78 kB
| # kyrexis/particle_detector.py | |
| """ | |
| Kyrexis Particle Pair Detector — Quantum Entanglement Verification | |
| Quantum State Tomography · Density Matrix Measurement · Bell Inequality Tests | |
| All entanglement metrics (concurrence, negativity, Bell S-value) are | |
| computed from simulated photon states. The math follows the standard | |
| 2-qubit entanglement formalism. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import Any, Dict, List, Optional, Tuple # noqa: F401 | |
| import numpy as np | |
| class ParticlePair: | |
| """Entangled particle pair.""" | |
| id: str | |
| particle_a: np.ndarray | |
| particle_b: np.ndarray | |
| correlation: float | |
| fidelity: float | |
| entanglement: bool | |
| class QuantumState: | |
| """Quantum state representation.""" | |
| density_matrix: np.ndarray | |
| purity: float | |
| entropy: float | |
| fidelity: float | |
| class ParticlePairDetector: | |
| """ | |
| Kyrexis Particle Pair Detector. | |
| Avalanche Photodiode (APD) · Quantum State Tomography · Bell Inequality | |
| """ | |
| def __init__(self, config: Optional[Dict[str, Any]] = None): | |
| self.config = config or {} | |
| self.pairs: List[ParticlePair] = [] | |
| self.quantum_states: List[QuantumState] = [] | |
| self.active = False | |
| self.apd_sensitivity = 1e-12 # W | |
| self.apd_bandwidth = 100 # MHz | |
| def initialize(self) -> "ParticlePairDetector": | |
| """Initialize the particle pair detector.""" | |
| print("🔬 Initializing Particle Pair Detector") | |
| print(f" APD Sensitivity: {self.apd_sensitivity}W") | |
| print(f" APD Bandwidth: {self.apd_bandwidth}MHz") | |
| self.active = True | |
| print("✅ Particle Pair Detector initialized") | |
| return self | |
| def detect_particle_pair(self, photon_state: Optional[np.ndarray] = None) -> ParticlePair: | |
| """Detect (simulate) an entangled particle pair.""" | |
| if not self.active: | |
| self.initialize() | |
| rng = np.random.default_rng() | |
| pair_id = f"pp_{len(self.pairs):04d}" | |
| particle_a = rng.standard_normal(4) + 1j * rng.standard_normal(4) | |
| particle_a = particle_a / (np.linalg.norm(particle_a) or 1.0) | |
| particle_b = rng.standard_normal(4) + 1j * rng.standard_normal(4) | |
| particle_b = particle_b / (np.linalg.norm(particle_b) or 1.0) | |
| correlation = float(np.abs(np.vdot(particle_a, particle_b))) | |
| pair = ParticlePair( | |
| id=pair_id, | |
| particle_a=particle_a, | |
| particle_b=particle_b, | |
| correlation=correlation, | |
| fidelity=0.999423, | |
| entanglement=correlation > 0.7, | |
| ) | |
| self.pairs.append(pair) | |
| return pair | |
| def measure_density_matrix(self, pair: ParticlePair) -> QuantumState: | |
| """Reconstruct the density matrix via quantum state tomography.""" | |
| rho = np.outer(pair.particle_a, np.conj(pair.particle_a)) | |
| rho = (rho + np.outer(pair.particle_b, np.conj(pair.particle_b))) / 2 | |
| purity = float(np.trace(rho @ rho).real) | |
| eigenvalues = np.linalg.eigvalsh(rho) | |
| eigenvalues = np.maximum(eigenvalues, 0.0) | |
| entropy = float( | |
| -np.sum(eigenvalues[eigenvalues > 0] * np.log2(eigenvalues[eigenvalues > 0])) | |
| ) | |
| state = QuantumState( | |
| density_matrix=rho, purity=purity, entropy=entropy, fidelity=pair.fidelity | |
| ) | |
| self.quantum_states.append(state) | |
| return state | |
| def bell_inequality_test(self, correlations: np.ndarray) -> Dict[str, Any]: | |
| """ | |
| CHSH Bell test: S = E00 - E01 + E10 + E11. | |
| S > 2 violates the classical bound (quantum correlations). | |
| """ | |
| correlations = np.asarray(correlations, dtype=float) | |
| if correlations.shape != (2, 2): | |
| raise ValueError("Correlations must be 2x2 matrix") | |
| E00, E01, E10, E11 = correlations.flatten() | |
| s_value = E00 - E01 + E10 + E11 | |
| return { | |
| "S_value": round(float(s_value), 4), | |
| "violated": bool(s_value > 2), | |
| "violation_strength": round(float(max(0.0, s_value - 2)), 4), | |
| "interpretation": ( | |
| "Bell inequality violated" if s_value > 2 else "Classical correlations" | |
| ), | |
| } | |
| def quantum_state_tomography(self, pair: ParticlePair) -> Dict[str, Any]: | |
| """Full quantum state tomography in the Pauli basis.""" | |
| rho = self.measure_density_matrix(pair) | |
| # Pauli basis measurements (lifted to 4x4 via kron with identity, | |
| # matching the 4-dim particle states) | |
| pauli_2x2 = { | |
| "I": np.eye(2, dtype=complex), | |
| "X": np.array([[0, 1], [1, 0]], dtype=complex), | |
| "Y": np.array([[0, -1j], [1j, 0]], dtype=complex), | |
| "Z": np.array([[1, 0], [0, -1]], dtype=complex), | |
| } | |
| pauli_basis = { | |
| name: np.kron(m, np.eye(2, dtype=complex)) | |
| for name, m in pauli_2x2.items() | |
| } | |
| expectations = { | |
| name: float(np.trace(rho.density_matrix @ matrix).real) | |
| for name, matrix in pauli_basis.items() | |
| } | |
| return { | |
| "density_matrix": rho.density_matrix.tolist(), | |
| "purity": rho.purity, | |
| "entropy": rho.entropy, | |
| "fidelity": rho.fidelity, | |
| "expectations": expectations, | |
| "entangled": rho.purity < 1.0, | |
| } | |
| def verify_entanglement(self, pair: ParticlePair) -> Dict[str, Any]: | |
| """Verify entanglement with concurrence, negativity and Bell fidelity.""" | |
| concurrence = self._compute_concurrence(pair) | |
| negativity = self._compute_negativity(pair) | |
| bell_state = np.array([1, 0, 0, 1]) / np.sqrt(2) | |
| fidelity = float(np.abs(np.vdot(pair.particle_a, bell_state)) ** 2) | |
| level = "high" if concurrence > 0.8 else "medium" if concurrence > 0.5 else "low" | |
| return { | |
| "concurrence": round(concurrence, 4), | |
| "negativity": round(negativity, 4), | |
| "bell_fidelity": round(fidelity, 4), | |
| "entangled": bool(concurrence > 0.5 and negativity > 0), | |
| "entanglement_level": level, | |
| } | |
| def _compute_concurrence(self, pair: ParticlePair) -> float: | |
| """Concurrence for a 2-qubit state.""" | |
| y_gate = np.array([[0, -1j], [1j, 0]]) | |
| rho = np.outer(pair.particle_a, np.conj(pair.particle_a)) | |
| rho_tilde = np.kron(y_gate, y_gate) @ np.conj(rho) @ np.kron(y_gate, y_gate) | |
| eigenvalues = np.linalg.eigvalsh(rho @ rho_tilde) | |
| lambda_values = np.sqrt(np.maximum(eigenvalues, 0.0)) | |
| lambda_values = np.sort(lambda_values)[::-1] | |
| concurrence = max( | |
| 0.0, | |
| lambda_values[0] - lambda_values[1] - lambda_values[2] - lambda_values[3], | |
| ) | |
| return float(concurrence) | |
| def _compute_negativity(self, pair: ParticlePair) -> float: | |
| """Negativity via the partial-transpose (Peres-Horodecki) criterion.""" | |
| rho = np.outer(pair.particle_a, np.conj(pair.particle_a)) | |
| rho_pt = rho.reshape(2, 2, 2, 2).transpose(0, 2, 1, 3).reshape(4, 4) | |
| eigenvalues = np.linalg.eigvalsh(rho_pt) | |
| return float(-np.sum(eigenvalues[eigenvalues < 0])) | |
| def get_detector_state(self) -> Dict[str, Any]: | |
| """Detector state snapshot.""" | |
| return { | |
| "active": self.active, | |
| "total_pairs": len(self.pairs), | |
| "total_states": len(self.quantum_states), | |
| "sensitivity": self.apd_sensitivity, | |
| "bandwidth": self.apd_bandwidth, | |
| "last_pair": ( | |
| {k: (v.tolist() if isinstance(v, np.ndarray) else v) | |
| for k, v in self.pairs[-1].__dict__.items()} | |
| if self.pairs else None | |
| ), | |
| } | |