quantrs2_sim/mixed_precision_impl/
simulator.rs1use crate::adaptive_gate_fusion::{FusedGateBlock, GateType, QuantumGate};
7use scirs2_core::random::prelude::*;
8use crate::error::{Result, SimulatorError};
9use crate::prelude::SciRS2Backend;
10use scirs2_core::ndarray::Array1;
11use scirs2_core::Complex64;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14
15use super::analysis::{PrecisionAnalysis, PrecisionAnalyzer};
16use super::config::{MixedPrecisionConfig, QuantumPrecision};
17use super::state_vector::MixedPrecisionStateVector;
18
19pub struct MixedPrecisionSimulator {
21 config: MixedPrecisionConfig,
23 state: Option<MixedPrecisionStateVector>,
25 num_qubits: usize,
27 #[cfg(feature = "advanced_math")]
29 backend: Option<SciRS2Backend>,
30 stats: MixedPrecisionStats,
32 analyzer: PrecisionAnalyzer,
34}
35
36#[derive(Debug, Clone, Default, Serialize, Deserialize)]
38pub struct MixedPrecisionStats {
39 pub total_gates: usize,
41 pub precision_adaptations: usize,
43 pub total_time_ms: f64,
45 pub memory_usage_by_precision: HashMap<QuantumPrecision, usize>,
47 pub gate_time_by_precision: HashMap<QuantumPrecision, f64>,
49 pub error_estimates: HashMap<QuantumPrecision, f64>,
51}
52
53impl MixedPrecisionSimulator {
54 pub fn new(num_qubits: usize, config: MixedPrecisionConfig) -> Result<Self> {
56 config.validate()?;
57
58 let state = Some(MixedPrecisionStateVector::computational_basis(
59 num_qubits,
60 config.state_vector_precision,
61 ));
62
63 Ok(Self {
64 config,
65 state,
66 num_qubits,
67 #[cfg(feature = "advanced_math")]
68 backend: None,
69 stats: MixedPrecisionStats::default(),
70 analyzer: PrecisionAnalyzer::new(),
71 })
72 }
73
74 #[cfg(feature = "advanced_math")]
76 pub fn with_backend(mut self) -> Result<Self> {
77 self.backend = Some(SciRS2Backend::new());
78 Ok(self)
79 }
80
81 pub fn apply_gate(&mut self, gate: &QuantumGate) -> Result<()> {
83 let start_time = std::time::Instant::now();
84
85 let gate_precision = self.select_gate_precision(gate)?;
87
88 self.adapt_state_precision(gate_precision)?;
90
91 self.apply_gate_with_precision(gate, gate_precision)?;
93
94 let execution_time = start_time.elapsed().as_millis() as f64;
96 self.stats.total_gates += 1;
97 self.stats.total_time_ms += execution_time;
98 *self
99 .stats
100 .gate_time_by_precision
101 .entry(gate_precision)
102 .or_insert(0.0) += execution_time;
103
104 Ok(())
105 }
106
107 pub fn apply_fused_block(&mut self, block: &FusedGateBlock) -> Result<()> {
109 let optimal_precision = self.select_block_precision(block)?;
110 self.adapt_state_precision(optimal_precision)?;
111
112 for gate in &block.gates {
114 self.apply_gate_with_precision(gate, optimal_precision)?;
115 }
116
117 Ok(())
118 }
119
120 pub fn measure_qubit(&mut self, qubit: usize) -> Result<bool> {
122 if qubit >= self.num_qubits {
123 return Err(SimulatorError::InvalidInput(format!(
124 "Qubit {} out of range for {}-qubit system",
125 qubit, self.num_qubits
126 )));
127 }
128
129 self.adapt_state_precision(self.config.measurement_precision)?;
131
132 let state = self.state.as_ref().unwrap();
133
134 let mut prob_one = 0.0;
136 let mask = 1 << qubit;
137 for i in 0..state.len() {
138 if i & mask != 0 {
139 prob_one += state.probability(i)?;
140 }
141 }
142
143 let result = thread_rng().gen::<f64>() < prob_one;
145
146 self.collapse_state(qubit, result)?;
148
149 Ok(result)
150 }
151
152 pub fn measure_all(&mut self) -> Result<Vec<bool>> {
154 let mut results = Vec::new();
155 for qubit in 0..self.num_qubits {
156 results.push(self.measure_qubit(qubit)?);
157 }
158 Ok(results)
159 }
160
161 pub fn get_state(&self) -> Option<&MixedPrecisionStateVector> {
163 self.state.as_ref()
164 }
165
166 pub fn expectation_value(&self, pauli_string: &str) -> Result<f64> {
168 if pauli_string.len() != self.num_qubits {
169 return Err(SimulatorError::InvalidInput(
170 "Pauli string length must match number of qubits".to_string(),
171 ));
172 }
173
174 let state = self.state.as_ref().unwrap();
175 let mut expectation = 0.0;
176
177 for i in 0..state.len() {
178 let mut sign = 1.0;
179 let mut amplitude = state.amplitude(i)?;
180
181 for (qubit, pauli) in pauli_string.chars().enumerate() {
183 match pauli {
184 'I' => {} 'X' => {
186 let flipped = i ^ (1 << qubit);
188 amplitude = state.amplitude(flipped)?;
189 }
190 'Y' => {
191 if i & (1 << qubit) != 0 {
193 sign *= -1.0;
194 }
195 amplitude *= Complex64::new(0.0, sign);
196 }
197 'Z' => {
198 if i & (1 << qubit) != 0 {
200 sign *= -1.0;
201 }
202 }
203 _ => {
204 return Err(SimulatorError::InvalidInput(format!(
205 "Invalid Pauli operator: {}",
206 pauli
207 )))
208 }
209 }
210 }
211
212 expectation += (amplitude.conj() * amplitude * sign).re;
213 }
214
215 Ok(expectation)
216 }
217
218 pub fn analyze_precision(&mut self) -> Result<PrecisionAnalysis> {
220 Ok(self
221 .analyzer
222 .analyze_for_tolerance(self.config.error_tolerance))
223 }
224
225 pub fn get_stats(&self) -> &MixedPrecisionStats {
227 &self.stats
228 }
229
230 pub fn reset(&mut self) -> Result<()> {
232 self.state = Some(MixedPrecisionStateVector::computational_basis(
233 self.num_qubits,
234 self.config.state_vector_precision,
235 ));
236 self.stats = MixedPrecisionStats::default();
237 self.analyzer.reset();
238 Ok(())
239 }
240
241 fn select_gate_precision(&self, gate: &QuantumGate) -> Result<QuantumPrecision> {
243 if !self.config.adaptive_precision {
244 return Ok(self.config.gate_precision);
245 }
246
247 let precision = match gate.gate_type {
249 GateType::PauliX
250 | GateType::PauliY
251 | GateType::PauliZ
252 | GateType::Hadamard
253 | GateType::Phase
254 | GateType::T
255 | GateType::RotationX
256 | GateType::RotationY
257 | GateType::RotationZ
258 | GateType::Identity => {
259 if self.config.gate_precision == QuantumPrecision::Adaptive {
261 QuantumPrecision::Single
262 } else {
263 self.config.gate_precision
264 }
265 }
266 GateType::CNOT | GateType::CZ | GateType::SWAP | GateType::ISwap => {
267 if self.config.gate_precision == QuantumPrecision::Adaptive {
269 if self.num_qubits > self.config.large_system_threshold {
270 QuantumPrecision::Single
271 } else {
272 QuantumPrecision::Double
273 }
274 } else {
275 self.config.gate_precision
276 }
277 }
278 GateType::Toffoli | GateType::Fredkin => {
279 if self.config.gate_precision == QuantumPrecision::Adaptive {
281 QuantumPrecision::Double
282 } else {
283 self.config.gate_precision
284 }
285 }
286 GateType::Custom(_) => {
287 QuantumPrecision::Double
289 }
290 };
291
292 Ok(precision)
293 }
294
295 fn select_block_precision(&self, _block: &FusedGateBlock) -> Result<QuantumPrecision> {
297 if self.config.adaptive_precision {
299 Ok(QuantumPrecision::Single)
300 } else {
301 Ok(self.config.gate_precision)
302 }
303 }
304
305 fn adapt_state_precision(&mut self, target_precision: QuantumPrecision) -> Result<()> {
307 if let Some(ref state) = self.state {
308 if state.precision() != target_precision {
309 let new_state = state.to_precision(target_precision)?;
310 self.state = Some(new_state);
311 self.stats.precision_adaptations += 1;
312 }
313 }
314 Ok(())
315 }
316
317 fn apply_gate_with_precision(
319 &mut self,
320 gate: &QuantumGate,
321 _precision: QuantumPrecision,
322 ) -> Result<()> {
323 if let Some(ref mut state) = self.state {
326 let memory_usage = state.memory_usage();
331 self.stats
332 .memory_usage_by_precision
333 .insert(state.precision(), memory_usage);
334 }
335
336 Ok(())
337 }
338
339 fn collapse_state(&mut self, qubit: usize, result: bool) -> Result<()> {
341 if let Some(ref mut state) = self.state {
342 let mask = 1 << qubit;
343 let mut norm_factor = 0.0;
344
345 for i in 0..state.len() {
347 let bit_value = (i & mask) != 0;
348 if bit_value == result {
349 norm_factor += state.probability(i)?;
350 }
351 }
352
353 if norm_factor == 0.0 {
354 return Err(SimulatorError::InvalidInput(
355 "Invalid measurement result: zero probability".to_string(),
356 ));
357 }
358
359 norm_factor = norm_factor.sqrt();
360
361 for i in 0..state.len() {
363 let bit_value = (i & mask) != 0;
364 if bit_value == result {
365 let amplitude = state.amplitude(i)?;
366 state.set_amplitude(i, amplitude / norm_factor)?;
367 } else {
368 state.set_amplitude(i, Complex64::new(0.0, 0.0))?;
369 }
370 }
371 }
372
373 Ok(())
374 }
375}
376
377impl MixedPrecisionStats {
378 pub fn average_gate_time(&self) -> f64 {
380 if self.total_gates > 0 {
381 self.total_time_ms / self.total_gates as f64
382 } else {
383 0.0
384 }
385 }
386
387 pub fn total_memory_usage(&self) -> usize {
389 self.memory_usage_by_precision.values().sum()
390 }
391
392 pub fn adaptation_rate(&self) -> f64 {
394 if self.total_gates > 0 {
395 self.precision_adaptations as f64 / self.total_gates as f64
396 } else {
397 0.0
398 }
399 }
400
401 pub fn summary(&self) -> String {
403 format!(
404 "Gates: {}, Adaptations: {}, Avg Time: {:.2}ms, Total Memory: {}MB",
405 self.total_gates,
406 self.precision_adaptations,
407 self.average_gate_time(),
408 self.total_memory_usage() / (1024 * 1024)
409 )
410 }
411}
412
413pub mod utils {
415 use super::*;
416
417 pub fn convert_state_vector(
419 state: &Array1<Complex64>,
420 precision: QuantumPrecision,
421 ) -> Result<MixedPrecisionStateVector> {
422 let mut mp_state = MixedPrecisionStateVector::new(state.len(), precision);
423 for (i, &litude) in state.iter().enumerate() {
424 mp_state.set_amplitude(i, amplitude)?;
425 }
426 Ok(mp_state)
427 }
428
429 pub fn extract_state_vector(mp_state: &MixedPrecisionStateVector) -> Result<Array1<Complex64>> {
431 let mut state = Array1::zeros(mp_state.len());
432 for i in 0..mp_state.len() {
433 state[i] = mp_state.amplitude(i)?;
434 }
435 Ok(state)
436 }
437
438 pub fn memory_savings(config: &MixedPrecisionConfig, num_qubits: usize) -> f64 {
440 let double_precision_size = (1 << num_qubits) * std::mem::size_of::<Complex64>();
441 let mixed_precision_size = config.estimate_memory_usage(num_qubits);
442 1.0 - (mixed_precision_size as f64 / double_precision_size as f64)
443 }
444
445 pub fn performance_improvement_factor(precision: QuantumPrecision) -> f64 {
447 1.0 / precision.computation_factor()
448 }
449}