strange_loop/
quantum_enhanced_simple.rs1use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use nalgebra::Complex;
9use rand::{thread_rng, Rng};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct QuantumMeasurement {
14 pub bit_string: String,
16 pub probability: f64,
18 pub fidelity: f64,
20 pub entanglement_entropy: f64,
22 pub measurement_time_ns: u64,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct SuperpositionResult {
29 pub qubits: usize,
31 pub amplitudes: Vec<(f64, f64)>, pub state_labels: Vec<String>,
35 pub total_probability: f64,
37 pub creation_time_ns: u64,
39}
40
41#[derive(Debug)]
43pub struct SimpleQuantumContainer {
44 qubits: usize,
46 amplitudes: Vec<Complex<f64>>,
48 noise_level: f64,
50}
51
52impl SimpleQuantumContainer {
53 pub fn new(qubits: usize, enable_noise: bool) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
55 let num_states = 1 << qubits;
56 let mut amplitudes = vec![Complex::new(0.0, 0.0); num_states];
57 amplitudes[0] = Complex::new(1.0, 0.0); let noise_level = if enable_noise { 1e-4 } else { 0.0 };
60
61 Ok(Self {
62 qubits,
63 amplitudes,
64 noise_level,
65 })
66 }
67
68 pub async fn create_superposition(&mut self) -> Result<SuperpositionResult, Box<dyn std::error::Error + Send + Sync>> {
70 let start_time = std::time::Instant::now();
71 let num_states = self.amplitudes.len();
72
73 for qubit in 0..self.qubits {
75 self.apply_hadamard(qubit).await?;
76 }
77
78 if self.noise_level > 0.0 {
80 self.apply_noise().await?;
81 }
82
83 self.normalize_state();
85
86 let creation_time_ns = start_time.elapsed().as_nanos() as u64;
87
88 let amplitudes: Vec<(f64, f64)> = self.amplitudes.iter()
90 .map(|c| (c.norm(), c.arg()))
91 .collect();
92
93 let state_labels: Vec<String> = (0..num_states)
94 .map(|i| format!("{:0width$b}", i, width = self.qubits))
95 .collect();
96
97 let total_probability: f64 = self.amplitudes.iter()
98 .map(|c| c.norm_sqr())
99 .sum();
100
101 Ok(SuperpositionResult {
102 qubits: self.qubits,
103 amplitudes,
104 state_labels,
105 total_probability,
106 creation_time_ns,
107 })
108 }
109
110 pub async fn measure(&mut self) -> Result<QuantumMeasurement, Box<dyn std::error::Error + Send + Sync>> {
112 let start_time = std::time::Instant::now();
113 let mut rng = thread_rng();
114
115 let probabilities: Vec<f64> = self.amplitudes.iter()
117 .map(|c| c.norm_sqr())
118 .collect();
119
120 let random_value: f64 = rng.gen();
122 let mut cumulative_prob = 0.0;
123 let mut measured_state = 0;
124 let mut measurement_probability = 0.0;
125
126 for (state_idx, &prob) in probabilities.iter().enumerate() {
127 cumulative_prob += prob;
128 if random_value <= cumulative_prob {
129 measured_state = state_idx;
130 measurement_probability = prob;
131 break;
132 }
133 }
134
135 let bit_string = format!("{:0width$b}", measured_state, width = self.qubits);
137
138 let fidelity = measurement_probability;
140 let entanglement_entropy = self.calculate_entanglement_entropy();
141
142 self.collapse_to_state(measured_state);
144
145 let measurement_time_ns = start_time.elapsed().as_nanos() as u64;
146
147 Ok(QuantumMeasurement {
148 bit_string,
149 probability: measurement_probability,
150 fidelity,
151 entanglement_entropy,
152 measurement_time_ns,
153 })
154 }
155
156 async fn apply_hadamard(&mut self, target_qubit: usize) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
158 if target_qubit >= self.qubits {
159 return Err("Target qubit index out of range".into());
160 }
161
162 let num_states = self.amplitudes.len();
163 let mut new_amplitudes = self.amplitudes.clone();
164
165 let h_factor = 1.0 / 2.0_f64.sqrt();
168
169 for state in 0..num_states {
170 if (state >> target_qubit) & 1 == 0 {
171 let partner_state = state | (1 << target_qubit);
173 if partner_state < num_states {
174 let amp0 = self.amplitudes[state];
175 let amp1 = self.amplitudes[partner_state];
176
177 new_amplitudes[state] = h_factor * (amp0 + amp1);
178 new_amplitudes[partner_state] = h_factor * (amp0 - amp1);
179 }
180 }
181 }
182
183 self.amplitudes = new_amplitudes;
184 Ok(())
185 }
186
187 async fn apply_noise(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
189 let mut rng = thread_rng();
190
191 for amplitude in &mut self.amplitudes {
192 let phase_noise = rng.gen::<f64>() * self.noise_level * 2.0 * std::f64::consts::PI;
194 *amplitude *= Complex::new(0.0, phase_noise).exp();
195
196 let damping = 1.0 - self.noise_level;
198 *amplitude *= damping;
199 }
200
201 Ok(())
202 }
203
204 fn normalize_state(&mut self) {
206 let norm_sq: f64 = self.amplitudes.iter().map(|c| c.norm_sqr()).sum();
207 let norm = norm_sq.sqrt();
208
209 if norm > 1e-10 {
210 for amplitude in &mut self.amplitudes {
211 *amplitude /= norm;
212 }
213 }
214 }
215
216 fn calculate_entanglement_entropy(&self) -> f64 {
218 if self.qubits <= 1 {
219 return 0.0;
220 }
221
222 let mut entropy = 0.0;
224 let num_states = self.amplitudes.len();
225
226 for amplitude in &self.amplitudes {
227 let prob = amplitude.norm_sqr();
228 if prob > 1e-12 {
229 entropy -= prob * prob.ln();
230 }
231 }
232
233 let max_entropy = (num_states as f64).ln();
235 if max_entropy > 0.0 {
236 entropy / max_entropy
237 } else {
238 0.0
239 }
240 }
241
242 fn collapse_to_state(&mut self, state: usize) {
244 for (i, amplitude) in self.amplitudes.iter_mut().enumerate() {
245 if i == state {
246 *amplitude = Complex::new(1.0, 0.0);
247 } else {
248 *amplitude = Complex::new(0.0, 0.0);
249 }
250 }
251 }
252}
253
254pub async fn create_enhanced_quantum_container(
256 qubits: usize,
257 enable_noise: bool
258) -> Result<SimpleQuantumContainer, Box<dyn std::error::Error + Send + Sync>> {
259 SimpleQuantumContainer::new(qubits, enable_noise)
260}
261
262#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
264use wasm_bindgen::prelude::*;
265
266#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
267#[wasm_bindgen]
268pub async fn quantum_create_enhanced(qubits: usize) -> Result<String, JsValue> {
269 match create_enhanced_quantum_container(qubits, true).await {
270 Ok(mut container) => {
271 match container.create_superposition().await {
272 Ok(result) => Ok(serde_json::to_string(&result).map_err(|e| JsValue::from_str(&e.to_string()))?),
273 Err(e) => Err(JsValue::from_str(&format!("Superposition failed: {}", e))),
274 }
275 }
276 Err(e) => Err(JsValue::from_str(&format!("Container creation failed: {}", e))),
277 }
278}
279
280#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
281#[wasm_bindgen]
282pub async fn quantum_measure_enhanced(qubits: usize) -> Result<String, JsValue> {
283 match create_enhanced_quantum_container(qubits, true).await {
284 Ok(mut container) => {
285 container.create_superposition().await
287 .map_err(|e| JsValue::from_str(&format!("Superposition failed: {}", e)))?;
288
289 match container.measure().await {
291 Ok(result) => Ok(serde_json::to_string(&result).map_err(|e| JsValue::from_str(&e.to_string()))?),
292 Err(e) => Err(JsValue::from_str(&format!("Measurement failed: {}", e))),
293 }
294 }
295 Err(e) => Err(JsValue::from_str(&format!("Container creation failed: {}", e))),
296 }
297}