1use crate::sim::LocalSimulator;
2use core::f64::consts::FRAC_1_SQRT_2;
3use qualia_core_db::NQuin;
4
5use qualia_core_db::specialized_libs::category_theory::{Endomorphism, Morphism, Object};
6use qualia_core_db::specialized_libs::shared::ZeroHeapMatrix;
7
8pub struct HilbertSpace<'a> {
10 pub amplitudes: &'a mut [(f64, f64)],
11}
12
13impl<'a> Object for HilbertSpace<'a> {
14 type Properties = usize; fn properties(&self) -> Self::Properties {
16 self.amplitudes.len().trailing_zeros() as usize
17 }
18}
19
20pub struct GateApplication {
22 pub target: usize,
23 pub control: Option<usize>,
24 pub matrix_2x2: Option<ZeroHeapMatrix<(f64, f64), 2, 2>>,
25}
26
27impl<'a> Morphism<HilbertSpace<'a>, HilbertSpace<'a>> for GateApplication {
28 fn apply(&self, state: &mut HilbertSpace<'a>) -> Result<(), &'static str> {
29 let bit = 1 << self.target;
30
31 if let Some(control) = self.control {
32 let control_bit = 1 << control;
34 for i in 0..state.amplitudes.len() {
35 if (i & control_bit) != 0 && (i & bit) == 0 {
36 let pair_idx = i | bit;
37 state.amplitudes.swap(i, pair_idx);
38 }
39 }
40 } else if let Some(matrix) = self.matrix_2x2.as_ref() {
41 for i in 0..state.amplitudes.len() {
43 if (i & bit) == 0 {
44 let pair_idx = i | bit;
45 let a = state.amplitudes[i];
46 let b = state.amplitudes[pair_idx];
47
48 let m00 = matrix.data[0][0];
52 let m01 = matrix.data[0][1];
53 let m10 = matrix.data[1][0];
54 let m11 = matrix.data[1][1];
55
56 let c_mul = |c1: (f64, f64), c2: (f64, f64)| -> (f64, f64) {
58 (c1.0 * c2.0 - c1.1 * c2.1, c1.0 * c2.1 + c1.1 * c2.0)
59 };
60 let c_add = |c1: (f64, f64), c2: (f64, f64)| -> (f64, f64) {
61 (c1.0 + c2.0, c1.1 + c2.1)
62 };
63
64 state.amplitudes[i] = c_add(c_mul(m00, a), c_mul(m01, b));
65 state.amplitudes[pair_idx] = c_add(c_mul(m10, a), c_mul(m11, b));
66 }
67 }
68 }
69
70 Ok(())
71 }
72}
73
74pub struct StateVectorSimulator {
76 num_qubits: u32,
77}
78
79impl StateVectorSimulator {
80 pub fn new(num_qubits: u32) -> Self {
82 Self { num_qubits }
83 }
84}
85
86impl LocalSimulator for StateVectorSimulator {
87 fn execute_circuit(
88 &self,
89 state_vector: &mut [(f64, f64)],
90 instructions: &[NQuin],
91 ) -> Result<(), &'static str> {
92 let expected_len = 1 << self.num_qubits;
93 if state_vector.len() < expected_len {
94 return Err("State vector buffer too small");
95 }
96
97 for quin in instructions {
98 let opcode = (quin.object >> 56) & 0xFF;
103 let operand1 = ((quin.object >> 40) & 0xFFFF) as usize;
104 let operand2 = ((quin.object >> 24) & 0xFFFF) as usize;
105
106 let mut space = HilbertSpace {
107 amplitudes: state_vector,
108 };
109 let mut morphism = GateApplication {
110 target: operand1,
111 control: None,
112 matrix_2x2: None,
113 };
114
115 match opcode {
116 0x01 => {
118 morphism.matrix_2x2 = Some(ZeroHeapMatrix::new([
119 [(0.0, 0.0), (1.0, 0.0)],
120 [(1.0, 0.0), (0.0, 0.0)],
121 ]));
122 morphism.apply(&mut space)?;
123 }
124 0x02 => {
126 morphism.matrix_2x2 = Some(ZeroHeapMatrix::new([
127 [(1.0, 0.0), (0.0, 0.0)],
128 [(0.0, 0.0), (-1.0, 0.0)],
129 ]));
130 morphism.apply(&mut space)?;
131 }
132 0x03 => {
134 morphism.matrix_2x2 = Some(ZeroHeapMatrix::new([
135 [(FRAC_1_SQRT_2, 0.0), (FRAC_1_SQRT_2, 0.0)],
136 [(FRAC_1_SQRT_2, 0.0), (-FRAC_1_SQRT_2, 0.0)],
137 ]));
138 morphism.apply(&mut space)?;
139 }
140 0x04 => {
142 morphism.control = Some(operand1);
143 morphism.target = operand2;
144 morphism.apply(&mut space)?;
145 }
146 0x05 => {
148 morphism.matrix_2x2 = Some(ZeroHeapMatrix::new([
149 [(0.0, 0.0), (0.0, -1.0)],
150 [(0.0, 1.0), (0.0, 0.0)],
151 ]));
152 morphism.apply(&mut space)?;
153 }
154 0x06 => {
156 morphism.matrix_2x2 = Some(ZeroHeapMatrix::new([
157 [(1.0, 0.0), (0.0, 0.0)],
158 [(0.0, 0.0), (0.0, 1.0)],
159 ]));
160 morphism.apply(&mut space)?;
161 }
162 0x07 => {
164 morphism.matrix_2x2 = Some(ZeroHeapMatrix::new([
165 [(1.0, 0.0), (0.0, 0.0)],
166 [(0.0, 0.0), (FRAC_1_SQRT_2, FRAC_1_SQRT_2)],
167 ]));
168 morphism.apply(&mut space)?;
169 }
170 0x08 => {
172 let bit1 = 1 << operand1;
173 let bit2 = 1 << operand2;
174 for i in 0..space.amplitudes.len() {
175 let b1 = (i & bit1) != 0;
176 let b2 = (i & bit2) != 0;
177 if b1 && !b2 {
178 let pair_idx = (i & !bit1) | bit2;
179 space.amplitudes.swap(i, pair_idx);
180 }
181 }
182 }
183 _ => return Err("Unknown opcode"),
184 }
185 }
186
187 Ok(())
188 }
189
190 fn sample(
191 &self,
192 state_vector: &[(f64, f64)],
193 shots: u32,
194 out_samples: &mut [u64],
195 ) -> Result<usize, &'static str> {
196 if out_samples.len() < shots as usize {
197 return Err("Output buffer too small for shots");
198 }
199 if state_vector.is_empty() {
200 return Err("Empty state vector");
201 }
202
203 let mut total_norm = 0.0;
205 for amp in state_vector.iter() {
206 total_norm += amp.0 * amp.0 + amp.1 * amp.1;
207 }
208 if total_norm <= 0.0 {
209 total_norm = 1.0;
210 }
211
212 let mut seed: u64 = 0x2545f4914f6cdd1d;
213 for i in 0..shots as usize {
214 seed = seed.wrapping_add(0x9e3779b97f4a7c15);
216 let mut z = seed;
217 z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
218 z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
219 z ^= z >> 31;
220 let u = ((z >> 11) as f64) / ((1u64 << 53) as f64);
221 let target = u * total_norm;
222
223 let mut cumulative = 0.0;
224 let mut outcome = 0u64;
225 for (idx, amp) in state_vector.iter().enumerate() {
226 let p = amp.0 * amp.0 + amp.1 * amp.1;
227 cumulative += p;
228 if cumulative >= target || idx == state_vector.len() - 1 {
229 outcome = idx as u64;
230 break;
231 }
232 }
233 out_samples[i] = outcome;
234 }
235
236 Ok(shots as usize)
237 }
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
245 fn test_bell_state_and_full_sampling() {
246 let sim = StateVectorSimulator::new(2);
247 let mut sv = [(0.0, 0.0); 4];
248 sv[0] = (1.0, 0.0); let quin_h = NQuin {
252 subject: 0,
253 predicate: 0,
254 object: (0x03u64 << 56) | (0u64 << 40),
255 context: 0,
256 metadata: 0,
257 parity: 0,
258 };
259 let quin_cx = NQuin {
260 subject: 0,
261 predicate: 0,
262 object: (0x04u64 << 56) | (0u64 << 40) | (1u64 << 24),
263 context: 0,
264 metadata: 0,
265 parity: 0,
266 };
267
268 sim.execute_circuit(&mut sv, &[quin_h, quin_cx]).unwrap();
269 assert!((sv[0].0 - FRAC_1_SQRT_2).abs() < 1e-9);
271 assert!((sv[1].0).abs() < 1e-9);
272 assert!((sv[2].0).abs() < 1e-9);
273 assert!((sv[3].0 - FRAC_1_SQRT_2).abs() < 1e-9);
274
275 let mut samples = [0u64; 100];
277 let count = sim.sample(&sv, 100, &mut samples).unwrap();
278 assert_eq!(count, 100);
279 for &s in samples.iter() {
280 assert!(s == 0 || s == 3, "Outcome must be 0 or 3 in Bell state, got {s}");
281 }
282 }
283
284 #[test]
285 fn test_sampling_beyond_32_amplitudes() {
286 let sim = StateVectorSimulator::new(6); let mut sv = [(0.0, 0.0); 64];
288 sv[42] = (1.0, 0.0); let mut samples = [0u64; 10];
291 sim.sample(&sv, 10, &mut samples).unwrap();
292 for &s in samples.iter() {
293 assert_eq!(s, 42, "Basis state 42 must be sampled with certainty");
294 }
295 }
296}