1use crate::model::validate_pauli_channel_weights;
2use crate::pauli::pauli_to_xz;
3use crate::{word_count, Mask, NpError, NpResult, SmallRng};
4
5pub const TWO_QUBIT_DEPOLARIZING_EVENTS: [(bool, bool, bool, bool); 15] = [
6 (false, false, true, false),
7 (false, false, true, true),
8 (false, false, false, true),
9 (true, false, false, false),
10 (true, false, true, false),
11 (true, false, true, true),
12 (true, false, false, true),
13 (true, true, false, false),
14 (true, true, true, false),
15 (true, true, true, true),
16 (true, true, false, true),
17 (false, true, false, false),
18 (false, true, true, false),
19 (false, true, true, true),
20 (false, true, false, true),
21];
22
23#[derive(Debug, Clone, PartialEq)]
24pub struct CompiledPauliEvent {
25 pub x: Vec<bool>,
26 pub z: Vec<bool>,
27 pub weight: f64,
28}
29
30pub fn bernoulli_mask(rng: &mut SmallRng, shots: usize, rate: f64) -> Mask {
31 if rate <= 0.0 {
32 return Mask::zero(word_count(shots));
33 }
34 if rate >= 1.0 {
35 return Mask::all(shots);
36 }
37 let mut mask = Mask::zero(word_count(shots));
38 for_each_bernoulli_event(rng, shots, rate, |shot, _| set_shot_bit(&mut mask, shot));
39 mask
40}
41
42pub fn for_each_bernoulli_event<F>(rng: &mut SmallRng, shots: usize, rate: f64, mut visit: F)
43where
44 F: FnMut(usize, &mut SmallRng),
45{
46 if rate <= 0.0 {
47 return;
48 }
49 if rate >= 1.0 {
50 for shot in 0..shots {
51 visit(shot, rng);
52 }
53 return;
54 }
55 let log1mp = (-rate).ln_1p();
56 let mut shot = 0usize;
57 loop {
58 let skip = (positive_unit_f64(rng).ln() / log1mp).floor() as usize;
59 match shot.checked_add(skip) {
60 Some(next) if next < shots => shot = next,
61 _ => break,
62 }
63 visit(shot, rng);
64 shot += 1;
65 if shot >= shots {
66 break;
67 }
68 }
69}
70
71pub fn positive_unit_f64(rng: &mut SmallRng) -> f64 {
72 rng.next_f64().max(f64::MIN_POSITIVE)
73}
74
75pub fn random_bit_mask(rng: &mut SmallRng, words: usize, shots: usize) -> Mask {
76 let mut mask = Mask::zero(words);
77 for word in &mut mask.words {
78 *word = rng.next_u64();
79 }
80 mask.clear_unused(shots);
81 mask
82}
83
84pub fn set_shot_bit(mask: &mut Mask, shot: usize) {
85 mask.words[shot / 64] |= 1u64 << (shot % 64);
86}
87
88pub fn compile_pauli_channel_events(
89 qubits: &[usize],
90 weights: &[(String, f64)],
91) -> NpResult<Vec<CompiledPauliEvent>> {
92 let event_length = validate_pauli_channel_weights(weights, "PauliChannel")?;
93 if event_length != qubits.len() {
94 return Err(NpError::new(
95 "PauliChannel event length does not match qubits",
96 ));
97 }
98
99 let mut events = Vec::new();
100 for (event, weight) in weights {
101 if *weight == 0.0 {
102 continue;
103 }
104 let mut x = Vec::with_capacity(event.len());
105 let mut z = Vec::with_capacity(event.len());
106 for local in event.chars() {
107 let (px, pz) = pauli_to_xz(local)?;
108 x.push(px != 0);
109 z.push(pz != 0);
110 }
111 events.push(CompiledPauliEvent {
112 x,
113 z,
114 weight: *weight,
115 });
116 }
117 Ok(events)
118}
119
120pub fn choose_weighted_event(
121 events: &[CompiledPauliEvent],
122 total: f64,
123 rng: &mut SmallRng,
124) -> usize {
125 let mut threshold = rng.next_f64() * total;
126 for (idx, event) in events.iter().enumerate() {
127 if threshold < event.weight {
128 return idx;
129 }
130 threshold -= event.weight;
131 }
132 events.len() - 1
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn bernoulli_mask_handles_extreme_rates() {
141 let mut rng = SmallRng::new(1);
142
143 assert_eq!(bernoulli_mask(&mut rng, 70, 0.0), Mask::zero(2));
144 assert_eq!(bernoulli_mask(&mut rng, 70, 1.0), Mask::all(70));
145 }
146
147 #[test]
148 fn compiles_pauli_channel_events() {
149 let events = compile_pauli_channel_events(&[0, 1], &[("XI".to_string(), 2.0)]).unwrap();
150
151 assert_eq!(events.len(), 1);
152 assert_eq!(events[0].x, vec![true, false]);
153 assert_eq!(events[0].z, vec![false, false]);
154 assert_eq!(events[0].weight, 2.0);
155 }
156
157 #[test]
158 fn rejects_negative_channel_weights() {
159 let err = compile_pauli_channel_events(&[0], &[("X".to_string(), -1.0)]).unwrap_err();
160
161 assert!(err.message().contains("non-negative"));
162 }
163
164 #[test]
165 fn rejects_non_finite_and_non_event_channel_weights() {
166 let invalid_weights = vec![
167 vec![("X".to_string(), f64::NAN)],
168 vec![("X".to_string(), f64::INFINITY)],
169 vec![(String::new(), 1.0)],
170 vec![("I".to_string(), 1.0)],
171 vec![("X".to_string(), 0.0)],
172 ];
173
174 for weights in invalid_weights {
175 assert!(
176 compile_pauli_channel_events(&[0], &weights).is_err(),
177 "accepted invalid weights {weights:?}"
178 );
179 }
180 }
181}