qualia_core_db/
qubo_compiler.rs1use crate::NQuin;
4
5pub const MAX_QUBO_VARS: usize = 128;
6
7#[derive(Debug, Clone)]
9pub struct QuboMatrix {
10 pub linear: Vec<f64>,
12 pub quadratic: Vec<(usize, usize, f64)>,
14 pub num_vars: usize,
16 pub coupler_count: usize,
18 pub couplers: Vec<Coupler>,
20 pub index_map: Vec<(u64, u64)>,
22 pub index_count: usize,
24}
25
26#[derive(Debug, Clone)]
28pub struct Coupler {
29 pub var_a: usize,
30 pub var_b: usize,
31 pub weight: f64,
32}
33
34impl Default for QuboMatrix {
35 fn default() -> Self {
36 Self::new(MAX_QUBO_VARS)
37 }
38}
39
40impl QuboMatrix {
41 pub fn new(num_vars: usize) -> Self {
43 Self {
44 linear: vec![0.0; num_vars],
45 quadratic: Vec::new(),
46 num_vars,
47 coupler_count: 0,
48 couplers: Vec::new(),
49 index_map: vec![(0, 0); num_vars],
50 index_count: 0,
51 }
52 }
53
54 pub fn set_linear(&mut self, var: usize, value: f64) {
56 if var < self.linear.len() {
57 self.linear[var] = value;
58 }
59 }
60
61 pub fn set_quadratic(&mut self, var1: usize, var2: usize, value: f64) {
63 if var1 < self.linear.len() && var2 < self.linear.len() {
64 self.coupler_count += 1;
65 self.couplers.push(Coupler {
66 var_a: var1,
67 var_b: var2,
68 weight: value,
69 });
70 self.quadratic.push((var1, var2, value));
71 }
72 }
73
74 pub fn emit_coupler(&mut self, var_a: usize, var_b: usize, weight: f64) {
76 self.couplers.push(Coupler {
77 var_a,
78 var_b,
79 weight,
80 });
81 self.coupler_count += 1;
82 }
83}
84
85pub fn calculate_energy(matrix: &QuboMatrix, assignment: &[u8]) -> f64 {
88 let mut energy = 0.0;
89 let n = matrix.num_vars.min(assignment.len());
90 for i in 0..n {
91 if assignment[i] == 1 {
92 energy += matrix.linear[i];
93 }
94 }
95 for coupler in &matrix.couplers {
96 if coupler.var_a < n && coupler.var_b < n {
97 if assignment[coupler.var_a] == 1 && assignment[coupler.var_b] == 1 {
98 energy += coupler.weight;
99 }
100 }
101 }
102 energy
103}
104
105pub fn solve_classical(matrix: &QuboMatrix, assignment: &mut [u8]) -> f32 {
107 let n = matrix.num_vars.min(assignment.len());
108 if n == 0 {
109 return 0.0;
110 }
111
112 for i in 0..n {
114 assignment[i] = if matrix.linear[i] < 0.0 { 1 } else { 0 };
115 }
116
117 let mut current_energy = calculate_energy(matrix, &assignment[..n]);
118 let mut best_assignment = assignment[..n].to_vec();
119 let mut best_energy = current_energy;
120
121 let mut t = 10.0f64;
123 let t_min = 0.001f64;
124 let alpha = 0.95f64;
125 let sweeps_per_temp = 50;
126 let mut lcg_state: u64 = 0x5155_B001_DEAD_BEEF;
127
128 while t > t_min {
129 for _ in 0..sweeps_per_temp {
130 lcg_state = lcg_state.wrapping_mul(6364136223846793005).wrapping_add(1);
131 let var = ((lcg_state >> 32) as usize) % n;
132
133 let old_val = assignment[var];
134 let new_val = 1 - old_val;
135
136 let sign: f64 = if new_val == 1 { 1.0 } else { -1.0 };
137 let mut delta = sign * matrix.linear[var];
138
139 for coupler in &matrix.couplers {
140 if coupler.var_a == var && coupler.var_b < n {
141 if assignment[coupler.var_b] == 1 {
142 delta += sign * coupler.weight;
143 }
144 } else if coupler.var_b == var && coupler.var_a < n {
145 if assignment[coupler.var_a] == 1 {
146 delta += sign * coupler.weight;
147 }
148 }
149 }
150
151 let accept = if delta <= 0.0 {
152 true
153 } else {
154 lcg_state = lcg_state.wrapping_mul(6364136223846793005).wrapping_add(1);
155 let rand_f = ((lcg_state >> 11) as f64) / ((1u64 << 53) as f64);
156 (-delta / t).exp() > rand_f
157 };
158
159 if accept {
160 assignment[var] = new_val;
161 current_energy += delta;
162 if current_energy < best_energy {
163 best_energy = current_energy;
164 best_assignment.copy_from_slice(&assignment[..n]);
165 }
166 }
167 }
168 t *= alpha;
169 }
170
171 assignment[..n].copy_from_slice(&best_assignment);
172 best_energy as f32
173}
174
175pub fn compile_quins_to_qubo(quins: &[NQuin], matrix: &mut QuboMatrix) -> Result<(), String> {
178 for quin in quins {
179 if matrix.index_count >= matrix.num_vars {
180 break;
181 }
182 let subj = quin.subject;
183 let pos = matrix.index_map[..matrix.index_count]
184 .iter()
185 .position(|&(s, _)| s == subj);
186 let var_idx = match pos {
187 Some(idx) => idx,
188 None => {
189 let idx = matrix.index_count;
190 matrix.index_map[idx] = (subj, quin.object);
191 matrix.index_count += 1;
192 idx
193 }
194 };
195
196 let weight = if (quin.object & 0x7FFF_FFFF) != 0 {
197 (quin.object as i32) as f64 / 1000.0
198 } else {
199 1.0
200 };
201
202 let opcode = (quin.predicate & 0xFF) as u8;
203 if opcode == 0x10 {
204 matrix.set_linear(var_idx, matrix.linear[var_idx] - weight);
205 } else if opcode == 0x12 {
206 matrix.set_linear(var_idx, matrix.linear[var_idx] + weight);
207 } else {
208 matrix.set_linear(var_idx, matrix.linear[var_idx] + (weight * 0.1));
209 }
210
211 if quin.context != 0 {
212 if let Some(other_idx) = matrix.index_map[..matrix.index_count]
213 .iter()
214 .position(|&(s, _)| s == quin.context)
215 {
216 if var_idx != other_idx {
217 matrix.set_quadratic(var_idx, other_idx, weight * 0.5);
218 }
219 }
220 }
221 }
222 Ok(())
223}
224
225pub fn rehydrate_solution(matrix: &mut QuboMatrix, assignment: &[u8], out: &mut [NQuin]) -> usize {
227 let mut count = 0;
228 for (i, &val) in assignment.iter().enumerate().take(out.len()) {
229 if i < matrix.index_count && count < out.len() {
230 let (subj, obj) = matrix.index_map[i];
231 let predicate = if val == 1 {
232 crate::q_hash("q42:selected")
233 } else {
234 crate::q_hash("q42:unselected")
235 };
236 out[count] = NQuin {
237 subject: subj,
238 predicate,
239 object: obj,
240 context: 0,
241 metadata: val as u64,
242 parity: subj ^ predicate ^ obj,
243 };
244 count += 1;
245 }
246 }
247 count
248}
249
250pub fn scrub_metadata(matrix: &mut QuboMatrix) {
252 matrix.index_map.clear();
253 matrix.index_count = 0;
254}
255
256pub fn serialize_matrix(matrix: &QuboMatrix) -> Vec<u8> {
258 let mut bytes = Vec::new();
259 bytes.extend_from_slice(b"HDF5_Q42_MAGIC");
260 bytes.extend_from_slice(&(matrix.num_vars as u64).to_le_bytes());
261 bytes.extend_from_slice(&(matrix.coupler_count as u64).to_le_bytes());
262 for &val in &matrix.linear {
263 bytes.extend_from_slice(&val.to_le_bytes());
264 }
265 for coupler in &matrix.couplers {
266 bytes.extend_from_slice(&(coupler.var_a as u64).to_le_bytes());
267 bytes.extend_from_slice(&(coupler.var_b as u64).to_le_bytes());
268 bytes.extend_from_slice(&coupler.weight.to_le_bytes());
269 }
270 bytes
271}
272
273#[cfg(not(target_arch = "wasm32"))]
275pub fn publish_to_commons(
276 matrix: &mut QuboMatrix,
277 storage_path: &std::path::Path,
278) -> Result<String, String> {
279 scrub_metadata(matrix);
280 let bytes = serialize_matrix(matrix);
281
282 let commons_dir = storage_path.join("commons");
283 std::fs::create_dir_all(&commons_dir).map_err(|e| e.to_string())?;
284
285 let file_path = commons_dir.join("quantum_cache.q42");
286 std::fs::write(&file_path, bytes).map_err(|e| e.to_string())?;
287
288 let info_hash = crate::webtorrent_seeder::sha1_file(&file_path)?;
289 let req = crate::webtorrent_seeder::RegisterSeedRequest {
290 info_hash: info_hash.clone(),
291 file_path: file_path.to_str().unwrap().to_string(),
292 display_name: "quantum_cache.q42".to_string(),
293 ontology_id: "quantum_commons".to_string(),
294 bandwidth_limit_kbps: 1024,
295 commons_asserted: true,
296 };
297
298 if let Some(_existing) = crate::webtorrent_seeder::lookup_seed(&info_hash) {
300 crate::webtorrent_seeder::deprecate_seed(&info_hash);
301 }
302
303 crate::webtorrent_seeder::register_seed(req)?;
304 Ok(crate::webtorrent_seeder::build_magnet_uri(
305 &info_hash,
306 "quantum_cache.q42",
307 4242,
308 ))
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 #[test]
316 fn test_qubo_simulated_annealing() {
317 let mut matrix = QuboMatrix::new(2);
318 matrix.set_linear(0, -2.0);
325 matrix.set_linear(1, -2.0);
326 matrix.set_quadratic(0, 1, 5.0);
327
328 let mut assignment = [0u8; 2];
329 let energy = solve_classical(&matrix, &mut assignment);
330 assert!((energy - (-2.0)).abs() < 1e-4);
331 assert!((assignment[0] == 1 && assignment[1] == 0) || (assignment[0] == 0 && assignment[1] == 1));
332 }
333}