quantrs2_sim/mixed_precision_impl/
simulator.rs1use crate::adaptive_gate_fusion::{FusedGateBlock, GateType, QuantumGate};
7use crate::error::{Result, SimulatorError};
8use crate::prelude::SciRS2Backend;
9use scirs2_core::ndarray::Array1;
10use scirs2_core::random::prelude::*;
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 const 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: {pauli}"
206 )))
207 }
208 }
209 }
210
211 expectation += (amplitude.conj() * amplitude * sign).re;
212 }
213
214 Ok(expectation)
215 }
216
217 pub fn analyze_precision(&mut self) -> Result<PrecisionAnalysis> {
219 Ok(self
220 .analyzer
221 .analyze_for_tolerance(self.config.error_tolerance))
222 }
223
224 pub const fn get_stats(&self) -> &MixedPrecisionStats {
226 &self.stats
227 }
228
229 pub fn reset(&mut self) -> Result<()> {
231 self.state = Some(MixedPrecisionStateVector::computational_basis(
232 self.num_qubits,
233 self.config.state_vector_precision,
234 ));
235 self.stats = MixedPrecisionStats::default();
236 self.analyzer.reset();
237 Ok(())
238 }
239
240 fn select_gate_precision(&self, gate: &QuantumGate) -> Result<QuantumPrecision> {
242 if !self.config.adaptive_precision {
243 return Ok(self.config.gate_precision);
244 }
245
246 let precision = match gate.gate_type {
248 GateType::PauliX
249 | GateType::PauliY
250 | GateType::PauliZ
251 | GateType::Hadamard
252 | GateType::Phase
253 | GateType::T
254 | GateType::RotationX
255 | GateType::RotationY
256 | GateType::RotationZ
257 | GateType::Identity => {
258 if self.config.gate_precision == QuantumPrecision::Adaptive {
260 QuantumPrecision::Single
261 } else {
262 self.config.gate_precision
263 }
264 }
265 GateType::CNOT | GateType::CZ | GateType::SWAP | GateType::ISwap => {
266 if self.config.gate_precision == QuantumPrecision::Adaptive {
268 if self.num_qubits > self.config.large_system_threshold {
269 QuantumPrecision::Single
270 } else {
271 QuantumPrecision::Double
272 }
273 } else {
274 self.config.gate_precision
275 }
276 }
277 GateType::Toffoli | GateType::Fredkin => {
278 if self.config.gate_precision == QuantumPrecision::Adaptive {
280 QuantumPrecision::Double
281 } else {
282 self.config.gate_precision
283 }
284 }
285 GateType::Custom(_) => {
286 QuantumPrecision::Double
288 }
289 };
290
291 Ok(precision)
292 }
293
294 const fn select_block_precision(&self, _block: &FusedGateBlock) -> Result<QuantumPrecision> {
296 if self.config.adaptive_precision {
298 Ok(QuantumPrecision::Single)
299 } else {
300 Ok(self.config.gate_precision)
301 }
302 }
303
304 fn adapt_state_precision(&mut self, target_precision: QuantumPrecision) -> Result<()> {
306 if let Some(ref state) = self.state {
307 if state.precision() != target_precision {
308 let new_state = state.to_precision(target_precision)?;
309 self.state = Some(new_state);
310 self.stats.precision_adaptations += 1;
311 }
312 }
313 Ok(())
314 }
315
316 fn apply_gate_with_precision(
318 &mut self,
319 gate: &QuantumGate,
320 _precision: QuantumPrecision,
321 ) -> Result<()> {
322 if let Some(ref mut state) = self.state {
325 let memory_usage = state.memory_usage();
330 self.stats
331 .memory_usage_by_precision
332 .insert(state.precision(), memory_usage);
333 }
334
335 Ok(())
336 }
337
338 fn collapse_state(&mut self, qubit: usize, result: bool) -> Result<()> {
340 if let Some(ref mut state) = self.state {
341 let mask = 1 << qubit;
342 let mut norm_factor = 0.0;
343
344 for i in 0..state.len() {
346 let bit_value = (i & mask) != 0;
347 if bit_value == result {
348 norm_factor += state.probability(i)?;
349 }
350 }
351
352 if norm_factor == 0.0 {
353 return Err(SimulatorError::InvalidInput(
354 "Invalid measurement result: zero probability".to_string(),
355 ));
356 }
357
358 norm_factor = norm_factor.sqrt();
359
360 for i in 0..state.len() {
362 let bit_value = (i & mask) != 0;
363 if bit_value == result {
364 let amplitude = state.amplitude(i)?;
365 state.set_amplitude(i, amplitude / norm_factor)?;
366 } else {
367 state.set_amplitude(i, Complex64::new(0.0, 0.0))?;
368 }
369 }
370 }
371
372 Ok(())
373 }
374}
375
376impl MixedPrecisionStats {
377 pub fn average_gate_time(&self) -> f64 {
379 if self.total_gates > 0 {
380 self.total_time_ms / self.total_gates as f64
381 } else {
382 0.0
383 }
384 }
385
386 pub fn total_memory_usage(&self) -> usize {
388 self.memory_usage_by_precision.values().sum()
389 }
390
391 pub fn adaptation_rate(&self) -> f64 {
393 if self.total_gates > 0 {
394 self.precision_adaptations as f64 / self.total_gates as f64
395 } else {
396 0.0
397 }
398 }
399
400 pub fn summary(&self) -> String {
402 format!(
403 "Gates: {}, Adaptations: {}, Avg Time: {:.2}ms, Total Memory: {}MB",
404 self.total_gates,
405 self.precision_adaptations,
406 self.average_gate_time(),
407 self.total_memory_usage() / (1024 * 1024)
408 )
409 }
410}
411
412pub mod utils {
414 use super::*;
415
416 pub fn convert_state_vector(
418 state: &Array1<Complex64>,
419 precision: QuantumPrecision,
420 ) -> Result<MixedPrecisionStateVector> {
421 let mut mp_state = MixedPrecisionStateVector::new(state.len(), precision);
422 for (i, &litude) in state.iter().enumerate() {
423 mp_state.set_amplitude(i, amplitude)?;
424 }
425 Ok(mp_state)
426 }
427
428 pub fn extract_state_vector(mp_state: &MixedPrecisionStateVector) -> Result<Array1<Complex64>> {
430 let mut state = Array1::zeros(mp_state.len());
431 for i in 0..mp_state.len() {
432 state[i] = mp_state.amplitude(i)?;
433 }
434 Ok(state)
435 }
436
437 pub fn memory_savings(config: &MixedPrecisionConfig, num_qubits: usize) -> f64 {
439 let double_precision_size = (1 << num_qubits) * std::mem::size_of::<Complex64>();
440 let mixed_precision_size = config.estimate_memory_usage(num_qubits);
441 1.0 - (mixed_precision_size as f64 / double_precision_size as f64)
442 }
443
444 pub fn performance_improvement_factor(precision: QuantumPrecision) -> f64 {
446 1.0 / precision.computation_factor()
447 }
448}