1use scirs2_core::Complex64;
7use scirs2_core::random::Rng;
8use std::collections::HashMap;
9
10use quantrs2_core::{
11 error::{QuantRS2Error, QuantRS2Result},
12 gate::GateOp,
13 qubit::QubitId,
14};
15
16use crate::calibration::{
17 DeviceCalibration, QubitCalibration, QubitReadoutData, SingleQubitGateData,
18 TwoQubitGateCalibration,
19};
20use scirs2_core::random::prelude::*;
21
22#[derive(Debug, Clone)]
24pub struct CalibrationNoiseModel {
25 pub device_id: String,
27 pub qubit_noise: HashMap<QubitId, QubitNoiseParams>,
29 pub gate_noise: HashMap<String, GateNoiseParams>,
31 pub two_qubit_noise: HashMap<(QubitId, QubitId), TwoQubitNoiseParams>,
33 pub readout_noise: HashMap<QubitId, ReadoutNoiseParams>,
35 pub crosstalk: CrosstalkNoise,
37 pub temperature: f64,
39}
40
41#[derive(Debug, Clone)]
43pub struct QubitNoiseParams {
44 pub gamma_1: f64,
46 pub gamma_phi: f64,
48 pub thermal_population: f64,
50 pub frequency_drift: f64,
52 pub flicker_noise: f64,
54}
55
56#[derive(Debug, Clone)]
58pub struct GateNoiseParams {
59 pub coherent_error: f64,
61 pub incoherent_error: f64,
63 pub duration: f64,
65 pub depolarizing_rate: f64,
67 pub amplitude_noise: f64,
69 pub phase_noise: f64,
71}
72
73#[derive(Debug, Clone)]
75pub struct TwoQubitNoiseParams {
76 pub gate_noise: GateNoiseParams,
78 pub zz_coupling: f64,
80 pub spectator_crosstalk: HashMap<QubitId, f64>,
82 pub directional_error: f64,
84}
85
86#[derive(Debug, Clone)]
88pub struct ReadoutNoiseParams {
89 pub assignment_matrix: [[f64; 2]; 2],
91 pub readout_excitation: f64,
93 pub readout_relaxation: f64,
95}
96
97#[derive(Debug, Clone)]
99pub struct CrosstalkNoise {
100 pub crosstalk_matrix: Vec<Vec<f64>>,
102 pub threshold: f64,
104 pub single_qubit_crosstalk: f64,
106 pub two_qubit_crosstalk: f64,
108}
109
110impl CalibrationNoiseModel {
111 pub fn from_calibration(calibration: &DeviceCalibration) -> Self {
113 let mut qubit_noise = HashMap::new();
114 let mut readout_noise = HashMap::new();
115
116 for (qubit_id, qubit_cal) in &calibration.qubit_calibrations {
118 qubit_noise.insert(
119 *qubit_id,
120 QubitNoiseParams {
121 gamma_1: 1.0 / qubit_cal.t1,
122 gamma_phi: 1.0 / qubit_cal.t2 - 0.5 / qubit_cal.t1,
123 thermal_population: qubit_cal.thermal_population,
124 frequency_drift: 1e3, flicker_noise: 1e-6, },
127 );
128 }
129
130 for (qubit_id, readout_data) in &calibration.readout_calibration.qubit_readout {
132 let p00 = readout_data.p0_given_0;
133 let p11 = readout_data.p1_given_1;
134
135 readout_noise.insert(
136 *qubit_id,
137 ReadoutNoiseParams {
138 assignment_matrix: [[p00, 1.0 - p11], [1.0 - p00, p11]],
139 readout_excitation: 0.001, readout_relaxation: 0.002, },
142 );
143 }
144
145 let mut gate_noise = HashMap::new();
147 for (gate_name, gate_cal) in &calibration.single_qubit_gates {
148 let mut total_error = 0.0;
150 let mut total_duration = 0.0;
151 let mut count = 0;
152
153 for gate_data in gate_cal.qubit_data.values() {
154 total_error += gate_data.error_rate;
155 total_duration += gate_data.duration;
156 count += 1;
157 }
158
159 if count > 0 {
160 let avg_error = total_error / count as f64;
161 let avg_duration = total_duration / count as f64;
162
163 gate_noise.insert(
164 gate_name.clone(),
165 GateNoiseParams {
166 coherent_error: avg_error * 0.3, incoherent_error: avg_error * 0.7, duration: avg_duration,
169 depolarizing_rate: avg_error / avg_duration,
170 amplitude_noise: 0.001, phase_noise: 0.002, },
173 );
174 }
175 }
176
177 let mut two_qubit_noise = HashMap::new();
179 for ((control, target), gate_cal) in &calibration.two_qubit_gates {
180 let base_noise = GateNoiseParams {
181 coherent_error: gate_cal.error_rate * 0.4,
182 incoherent_error: gate_cal.error_rate * 0.6,
183 duration: gate_cal.duration,
184 depolarizing_rate: gate_cal.error_rate / gate_cal.duration,
185 amplitude_noise: 0.002,
186 phase_noise: 0.003,
187 };
188
189 gate_noise.insert(gate_cal.gate_name.clone(), base_noise.clone());
191
192 let mut spectator_crosstalk = HashMap::new();
194
195 for offset in [-1, 1] {
197 let spectator_id = control.id() as i32 + offset;
198 if spectator_id >= 0 && spectator_id < calibration.topology.num_qubits as i32 {
199 spectator_crosstalk.insert(QubitId(spectator_id as u32), 0.001);
200 }
201
202 let spectator_id = target.id() as i32 + offset;
203 if spectator_id >= 0 && spectator_id < calibration.topology.num_qubits as i32 {
204 spectator_crosstalk.insert(QubitId(spectator_id as u32), 0.001);
205 }
206 }
207
208 two_qubit_noise.insert(
209 (*control, *target),
210 TwoQubitNoiseParams {
211 gate_noise: base_noise,
212 zz_coupling: 0.1, spectator_crosstalk,
214 directional_error: if gate_cal.directional { 0.01 } else { 0.0 },
215 },
216 );
217 }
218
219 let crosstalk = CrosstalkNoise {
221 crosstalk_matrix: calibration.crosstalk_matrix.matrix.clone(),
222 threshold: calibration.crosstalk_matrix.significance_threshold,
223 single_qubit_crosstalk: 0.001,
224 two_qubit_crosstalk: 0.01,
225 };
226
227 let temperature = calibration
229 .qubit_calibrations
230 .values()
231 .filter_map(|q| q.temperature)
232 .sum::<f64>()
233 / calibration.qubit_calibrations.len() as f64;
234
235 Self {
236 device_id: calibration.device_id.clone(),
237 qubit_noise,
238 gate_noise,
239 two_qubit_noise,
240 readout_noise,
241 crosstalk,
242 temperature,
243 }
244 }
245
246 pub fn apply_gate_noise(
248 &self,
249 state: &mut Vec<Complex64>,
250 gate: &dyn GateOp,
251 qubits: &[QubitId],
252 duration_ns: f64,
253 rng: &mut impl Rng,
254 ) -> QuantRS2Result<()> {
255 let gate_name = gate.name();
256
257 match qubits.len() {
258 1 => self.apply_single_qubit_noise(state, gate_name, qubits[0], duration_ns, rng),
259 2 => {
260 self.apply_two_qubit_noise(state, gate_name, qubits[0], qubits[1], duration_ns, rng)
261 }
262 _ => {
263 for &qubit in qubits {
265 self.apply_single_qubit_noise(
266 state,
267 gate_name,
268 qubit,
269 duration_ns / qubits.len() as f64,
270 rng,
271 )?;
272 }
273 Ok(())
274 }
275 }
276 }
277
278 fn apply_single_qubit_noise(
280 &self,
281 state: &mut Vec<Complex64>,
282 gate_name: &str,
283 qubit: QubitId,
284 duration_ns: f64,
285 rng: &mut impl Rng,
286 ) -> QuantRS2Result<()> {
287 let gate_params = self.gate_noise.get(gate_name);
289 let qubit_params = self.qubit_noise.get(&qubit);
290
291 if let Some(params) = gate_params {
292 if params.coherent_error > 0.0 {
294 let error_angle = rng.gen_range(-params.coherent_error..params.coherent_error);
295 self.apply_rotation_error(state, qubit, error_angle)?;
296 }
297
298 if params.amplitude_noise > 0.0 {
300 let amplitude_error =
301 1.0 + rng.gen_range(-params.amplitude_noise..params.amplitude_noise);
302 self.apply_amplitude_scaling(state, qubit, amplitude_error)?;
303 }
304
305 if params.phase_noise > 0.0 {
307 let phase_error = rng.gen_range(-params.phase_noise..params.phase_noise);
308 self.apply_phase_error(state, qubit, phase_error)?;
309 }
310 }
311
312 if let Some(qubit_params) = qubit_params {
314 let actual_duration = duration_ns / 1000.0; let decay_prob = 1.0 - (-actual_duration * qubit_params.gamma_1).exp();
318 if rng.gen::<f64>() < decay_prob {
319 self.apply_amplitude_damping(state, qubit, decay_prob)?;
320 }
321
322 let dephase_prob = 1.0 - (-actual_duration * qubit_params.gamma_phi).exp();
324 if rng.gen::<f64>() < dephase_prob {
325 self.apply_phase_damping(state, qubit, dephase_prob)?;
326 }
327 }
328
329 Ok(())
330 }
331
332 fn apply_two_qubit_noise(
334 &self,
335 state: &mut Vec<Complex64>,
336 gate_name: &str,
337 control: QubitId,
338 target: QubitId,
339 duration_ns: f64,
340 rng: &mut impl Rng,
341 ) -> QuantRS2Result<()> {
342 if let Some(params) = self.two_qubit_noise.get(&(control, target)) {
343 let gate_params = ¶ms.gate_noise;
345
346 if gate_params.coherent_error > 0.0 {
348 let error = rng.gen_range(-gate_params.coherent_error..gate_params.coherent_error);
349 self.apply_two_qubit_rotation_error(state, control, target, error)?;
350 }
351
352 if params.zz_coupling > 0.0 {
354 let zz_angle = params.zz_coupling * duration_ns / 1000.0; self.apply_zz_interaction(state, control, target, zz_angle)?;
356 }
357
358 for (&spectator, &coupling) in ¶ms.spectator_crosstalk {
360 if rng.gen::<f64>() < coupling {
361 self.apply_crosstalk_error(state, spectator, coupling * 0.1)?;
362 }
363 }
364
365 self.apply_single_qubit_noise(state, gate_name, control, duration_ns / 2.0, rng)?;
367 self.apply_single_qubit_noise(state, gate_name, target, duration_ns / 2.0, rng)?;
368 }
369
370 Ok(())
371 }
372
373 pub fn apply_readout_noise(&self, measurement: u8, qubit: QubitId, rng: &mut impl Rng) -> u8 {
375 if let Some(params) = self.readout_noise.get(&qubit) {
376 let prob = rng.gen::<f64>();
377
378 if measurement == 0 {
379 if prob > params.assignment_matrix[0][0] {
380 return 1;
381 }
382 } else {
383 if prob > params.assignment_matrix[1][1] {
384 return 0;
385 }
386 }
387 }
388
389 measurement
390 }
391
392 fn apply_rotation_error(
395 &self,
396 state: &mut Vec<Complex64>,
397 qubit: QubitId,
398 angle: f64,
399 ) -> QuantRS2Result<()> {
400 let n_qubits = (state.len() as f64).log2() as usize;
402 let qubit_idx = qubit.id() as usize;
403
404 for i in 0..state.len() {
405 if (i >> qubit_idx) & 1 == 1 {
406 state[i] *= Complex64::from_polar(1.0, angle);
407 }
408 }
409
410 Ok(())
411 }
412
413 fn apply_amplitude_scaling(
414 &self,
415 state: &mut Vec<Complex64>,
416 qubit: QubitId,
417 scale: f64,
418 ) -> QuantRS2Result<()> {
419 for amp in state.iter_mut() {
421 *amp *= scale;
422 }
423
424 let norm = state.iter().map(|a| a.norm_sqr()).sum::<f64>().sqrt();
426 for amp in state.iter_mut() {
427 *amp /= norm;
428 }
429
430 Ok(())
431 }
432
433 fn apply_phase_error(
434 &self,
435 state: &mut Vec<Complex64>,
436 qubit: QubitId,
437 phase: f64,
438 ) -> QuantRS2Result<()> {
439 let qubit_idx = qubit.id() as usize;
440
441 for i in 0..state.len() {
442 if (i >> qubit_idx) & 1 == 1 {
443 state[i] *= Complex64::from_polar(1.0, phase);
444 }
445 }
446
447 Ok(())
448 }
449
450 fn apply_amplitude_damping(
451 &self,
452 state: &mut Vec<Complex64>,
453 qubit: QubitId,
454 gamma: f64,
455 ) -> QuantRS2Result<()> {
456 let qubit_idx = qubit.id() as usize;
458 let damping_factor = (1.0 - gamma).sqrt();
459
460 for i in 0..state.len() {
461 if (i >> qubit_idx) & 1 == 1 {
462 state[i] *= damping_factor;
463 }
464 }
465
466 Ok(())
467 }
468
469 fn apply_phase_damping(
470 &self,
471 state: &mut Vec<Complex64>,
472 qubit: QubitId,
473 gamma: f64,
474 ) -> QuantRS2Result<()> {
475 let qubit_idx = qubit.id() as usize;
477
478 for i in 0..state.len() {
480 if (i >> qubit_idx) & 1 == 1 {
481 state[i] *= (1.0 - gamma).sqrt();
482 }
483 }
484
485 Ok(())
486 }
487
488 fn apply_two_qubit_rotation_error(
489 &self,
490 state: &mut Vec<Complex64>,
491 control: QubitId,
492 target: QubitId,
493 angle: f64,
494 ) -> QuantRS2Result<()> {
495 let control_idx = control.id() as usize;
497 let target_idx = target.id() as usize;
498
499 for i in 0..state.len() {
500 let control_bit = (i >> control_idx) & 1;
501 let target_bit = (i >> target_idx) & 1;
502
503 if control_bit == 1 && target_bit == 1 {
504 state[i] *= Complex64::from_polar(1.0, angle);
505 }
506 }
507
508 Ok(())
509 }
510
511 fn apply_zz_interaction(
512 &self,
513 state: &mut Vec<Complex64>,
514 qubit1: QubitId,
515 qubit2: QubitId,
516 angle: f64,
517 ) -> QuantRS2Result<()> {
518 let idx1 = qubit1.id() as usize;
519 let idx2 = qubit2.id() as usize;
520
521 for i in 0..state.len() {
522 let bit1 = (i >> idx1) & 1;
523 let bit2 = (i >> idx2) & 1;
524
525 let phase = if bit1 == bit2 { angle } else { -angle };
527 state[i] *= Complex64::from_polar(1.0, phase / 2.0);
528 }
529
530 Ok(())
531 }
532
533 fn apply_crosstalk_error(
534 &self,
535 state: &mut Vec<Complex64>,
536 qubit: QubitId,
537 strength: f64,
538 ) -> QuantRS2Result<()> {
539 self.apply_rotation_error(state, qubit, strength)
541 }
542}
543
544pub struct NoiseModelBuilder {
546 calibration: DeviceCalibration,
547 coherent_factor: f64,
548 thermal_factor: f64,
549 crosstalk_factor: f64,
550 readout_factor: f64,
551}
552
553impl NoiseModelBuilder {
554 pub fn from_calibration(calibration: DeviceCalibration) -> Self {
556 Self {
557 calibration,
558 coherent_factor: 1.0,
559 thermal_factor: 1.0,
560 crosstalk_factor: 1.0,
561 readout_factor: 1.0,
562 }
563 }
564
565 pub fn coherent_factor(mut self, factor: f64) -> Self {
567 self.coherent_factor = factor;
568 self
569 }
570
571 pub fn thermal_factor(mut self, factor: f64) -> Self {
573 self.thermal_factor = factor;
574 self
575 }
576
577 pub fn crosstalk_factor(mut self, factor: f64) -> Self {
579 self.crosstalk_factor = factor;
580 self
581 }
582
583 pub fn readout_factor(mut self, factor: f64) -> Self {
585 self.readout_factor = factor;
586 self
587 }
588
589 pub fn build(self) -> CalibrationNoiseModel {
591 let mut model = CalibrationNoiseModel::from_calibration(&self.calibration);
592
593 for noise in model.gate_noise.values_mut() {
595 noise.coherent_error *= self.coherent_factor;
596 }
597
598 for noise in model.qubit_noise.values_mut() {
599 noise.thermal_population *= self.thermal_factor;
600 }
601
602 for row in model.crosstalk.crosstalk_matrix.iter_mut() {
603 for val in row.iter_mut() {
604 *val *= self.crosstalk_factor;
605 }
606 }
607
608 for readout in model.readout_noise.values_mut() {
609 readout.assignment_matrix[0][1] *= self.readout_factor;
611 readout.assignment_matrix[1][0] *= self.readout_factor;
612 readout.assignment_matrix[0][0] = 1.0 - readout.assignment_matrix[0][1];
614 readout.assignment_matrix[1][1] = 1.0 - readout.assignment_matrix[1][0];
615 }
616
617 model
618 }
619}
620
621#[cfg(test)]
622mod tests {
623 use super::*;
624 use crate::calibration::create_ideal_calibration;
625
626 #[test]
627 fn test_noise_model_from_calibration() {
628 let cal = create_ideal_calibration("test".to_string(), 5);
629 let noise_model = CalibrationNoiseModel::from_calibration(&cal);
630
631 assert_eq!(noise_model.device_id, "test");
632 assert_eq!(noise_model.qubit_noise.len(), 5);
633 assert!(noise_model.gate_noise.contains_key("X"));
634 assert!(noise_model.gate_noise.contains_key("CNOT"));
635 }
636
637 #[test]
638 fn test_noise_model_builder() {
639 let cal = create_ideal_calibration("test".to_string(), 3);
640 let noise_model = NoiseModelBuilder::from_calibration(cal)
641 .coherent_factor(0.5)
642 .thermal_factor(2.0)
643 .crosstalk_factor(0.1)
644 .readout_factor(0.5)
645 .build();
646
647 let x_noise = noise_model.gate_noise.get("X").unwrap();
649 assert!(x_noise.coherent_error < 0.001); }
651}