1use crate::solvers::linear_algebra::{FixedLanczosEigensolver, Matrix4x4, Vector4};
2use crate::solvers::{SolverConfig, SolverResult, SolverState, SolversError};
3use crate::{q_hash, NQuin};
4
5pub const MANIFOLD_HEAD_PREDICATE: u64 = q_hash("q42:manifold10d:head");
6pub const MANIFOLD_TAIL_PREDICATE: u64 = q_hash("q42:manifold10d:tail");
7pub const MANIFOLD_THRESHOLD_HOLDS: u64 = q_hash("q42:manifold10d:threshold-holds");
8pub const MANIFOLD_THRESHOLD_MISS: u64 = q_hash("q42:manifold10d:threshold-miss");
9
10pub const MANIFOLD_ATOM_COHERENT: u64 = q_hash("q42:manifold10d:coherent");
11pub const MANIFOLD_ATOM_RECURRENT: u64 = q_hash("q42:manifold10d:recurrent");
12pub const MANIFOLD_ATOM_DENSE: u64 = q_hash("q42:manifold10d:dense");
13pub const MANIFOLD_ATOM_CURVED: u64 = q_hash("q42:manifold10d:curved");
14pub const MANIFOLD_ATOM_STABLE: u64 = q_hash("q42:manifold10d:stable-topology");
15pub const MANIFOLD_ASP_ATOMS: [u64; 5] = [
16 MANIFOLD_ATOM_COHERENT,
17 MANIFOLD_ATOM_RECURRENT,
18 MANIFOLD_ATOM_DENSE,
19 MANIFOLD_ATOM_CURVED,
20 MANIFOLD_ATOM_STABLE,
21];
22
23#[repr(C)]
64#[derive(Clone, Copy, Debug, Default, PartialEq)]
65pub struct ManifoldCoordinate10D {
66 pub scale: f32,
67 pub attention_depth: f32,
68 pub epistemic_weight: f32,
69 pub topological_spin: f32,
70 pub temporal_decay: f32,
71 pub entropy_bias: f32,
72 pub spatial_phase: f32,
73 pub recurrence_frequency: f32,
74 pub density_threshold: f32,
75 pub manifold_curvature: f32,
76}
77
78pub type Epistemic10D = ManifoldCoordinate10D;
83
84impl ManifoldCoordinate10D {
85 pub const DIMENSIONS: usize = 10;
86
87 pub fn as_f32_array(&self) -> [f32; Self::DIMENSIONS] {
89 [
90 self.scale,
91 self.attention_depth,
92 self.epistemic_weight,
93 self.topological_spin,
94 self.temporal_decay,
95 self.entropy_bias,
96 self.spatial_phase,
97 self.recurrence_frequency,
98 self.density_threshold,
99 self.manifold_curvature,
100 ]
101 }
102
103 pub fn from_p64_bytes(bytes: &[u8]) -> Result<Self, String> {
105 if bytes.len() < 40 {
106 return Err("p64: truncated 10D manifold coordinate".to_string());
107 }
108 let value = |index: usize| {
109 let start = index * 4;
110 f32::from_le_bytes(bytes[start..start + 4].try_into().unwrap())
111 };
112 let coordinate = Self {
113 scale: value(0),
114 attention_depth: value(1),
115 epistemic_weight: value(2),
116 topological_spin: value(3),
117 temporal_decay: value(4),
118 entropy_bias: value(5),
119 spatial_phase: value(6),
120 recurrence_frequency: value(7),
121 density_threshold: value(8),
122 manifold_curvature: value(9),
123 };
124 if coordinate
125 .as_f32_array()
126 .iter()
127 .any(|value| !value.is_finite())
128 {
129 return Err("p64: non-finite 10D manifold coordinate".to_string());
130 }
131 Ok(coordinate)
132 }
133
134 pub fn as_array(&self) -> [f64; 10] {
136 [
137 self.scale as f64,
138 self.attention_depth as f64,
139 self.epistemic_weight as f64,
140 self.topological_spin as f64,
141 self.temporal_decay as f64,
142 self.entropy_bias as f64,
143 self.spatial_phase as f64,
144 self.recurrence_frequency as f64,
145 self.density_threshold as f64,
146 self.manifold_curvature as f64,
147 ]
148 }
149
150 pub fn from_sequential_layer(layer: u32, total_layers: u32) -> Self {
152 let max_l = total_layers.max(1) as f32;
153 let l = layer as f32;
154 let depth = l / max_l;
155 Self {
156 scale: depth,
157 attention_depth: 1.0 - depth,
158 epistemic_weight: 1.0,
159 topological_spin: (depth * std::f32::consts::PI).sin(),
160 temporal_decay: 0.1,
161 entropy_bias: 0.5,
162 spatial_phase: (depth * std::f32::consts::TAU).cos(),
163 recurrence_frequency: 1.0,
164 density_threshold: 0.8,
165 manifold_curvature: 0.0,
166 }
167 }
168}
169
170#[repr(u8)]
171#[derive(Clone, Copy, Debug, PartialEq, Eq)]
172pub enum ManifoldDimension {
173 Scale = 0,
174 AttentionDepth = 1,
175 EpistemicWeight = 2,
176 TopologicalSpin = 3,
177 TemporalDecay = 4,
178 EntropyBias = 5,
179 SpatialPhase = 6,
180 RecurrenceFrequency = 7,
181 DensityThreshold = 8,
182 ManifoldCurvature = 9,
183}
184
185impl ManifoldDimension {
186 pub fn from_u8(value: u8) -> Option<Self> {
189 Some(match value {
190 0 => Self::Scale,
191 1 => Self::AttentionDepth,
192 2 => Self::EpistemicWeight,
193 3 => Self::TopologicalSpin,
194 4 => Self::TemporalDecay,
195 5 => Self::EntropyBias,
196 6 => Self::SpatialPhase,
197 7 => Self::RecurrenceFrequency,
198 8 => Self::DensityThreshold,
199 9 => Self::ManifoldCurvature,
200 _ => return None,
201 })
202 }
203
204 pub fn value(self, coordinate: &ManifoldCoordinate10D) -> f32 {
206 coordinate.as_f32_array()[self as usize]
207 }
208}
209
210#[repr(C)]
211#[derive(Clone, Copy, Debug, Default, PartialEq)]
212pub struct ManifoldState10D {
213 pub state_id: u64,
218 pub timestamp: u64,
219 pub coordinate: ManifoldCoordinate10D,
220}
221
222#[inline]
225fn pack_f32_pair(low: f32, high: f32) -> u64 {
226 low.to_bits() as u64 | ((high.to_bits() as u64) << 32)
227}
228
229#[inline]
231fn unpack_f32_pair(value: u64) -> (f32, f32) {
232 (
233 f32::from_bits(value as u32),
234 f32::from_bits((value >> 32) as u32),
235 )
236}
237
238#[inline]
241fn quin_with_parity(
242 subject: u64,
243 predicate: u64,
244 object: u64,
245 context: u64,
246 metadata: u64,
247) -> NQuin {
248 NQuin {
249 subject,
250 predicate,
251 object,
252 context,
253 metadata,
254 parity: subject ^ predicate ^ object ^ context,
255 }
256}
257
258pub fn encode_manifold_state(state: &ManifoldState10D, out: &mut [NQuin; 2]) {
266 let d = state.coordinate.as_f32_array();
267 out[0] = quin_with_parity(
268 state.state_id,
269 MANIFOLD_HEAD_PREDICATE,
270 pack_f32_pair(d[0], d[1]),
271 pack_f32_pair(d[2], d[3]),
272 pack_f32_pair(d[4], d[5]),
273 );
274 out[1] = quin_with_parity(
275 state.state_id,
276 MANIFOLD_TAIL_PREDICATE,
277 pack_f32_pair(d[6], d[7]),
278 pack_f32_pair(d[8], d[9]),
279 state.timestamp,
280 );
281}
282
283pub fn decode_manifold_state(head: &NQuin, tail: &NQuin) -> Option<ManifoldState10D> {
288 if head.subject != tail.subject
289 || head.predicate != MANIFOLD_HEAD_PREDICATE
290 || tail.predicate != MANIFOLD_TAIL_PREDICATE
291 || head.parity != head.subject ^ head.predicate ^ head.object ^ head.context
292 || tail.parity != tail.subject ^ tail.predicate ^ tail.object ^ tail.context
293 {
294 return None;
295 }
296 let (d0, d1) = unpack_f32_pair(head.object);
297 let (d2, d3) = unpack_f32_pair(head.context);
298 let (d4, d5) = unpack_f32_pair(head.metadata);
299 let (d6, d7) = unpack_f32_pair(tail.object);
300 let (d8, d9) = unpack_f32_pair(tail.context);
301 let coordinate = ManifoldCoordinate10D {
302 scale: d0,
303 attention_depth: d1,
304 epistemic_weight: d2,
305 topological_spin: d3,
306 temporal_decay: d4,
307 entropy_bias: d5,
308 spatial_phase: d6,
309 recurrence_frequency: d7,
310 density_threshold: d8,
311 manifold_curvature: d9,
312 };
313 if coordinate
314 .as_f32_array()
315 .iter()
316 .any(|value| !value.is_finite())
317 {
318 return None;
319 }
320 Some(ManifoldState10D {
321 state_id: head.subject,
322 timestamp: tail.metadata,
323 coordinate,
324 })
325}
326
327pub fn collect_manifold_states(quins: &[NQuin], out: &mut [ManifoldState10D]) -> usize {
330 let mut count = 0usize;
331 for head in quins {
332 if head.predicate != MANIFOLD_HEAD_PREDICATE || count == out.len() {
333 continue;
334 }
335 let Some(tail) = quins.iter().find(|candidate| {
336 candidate.subject == head.subject && candidate.predicate == MANIFOLD_TAIL_PREDICATE
337 }) else {
338 continue;
339 };
340 if let Some(state) = decode_manifold_state(head, tail) {
341 out[count] = state;
342 count += 1;
343 }
344 }
345 for index in 1..count {
347 let state = out[index];
348 let mut cursor = index;
349 while cursor > 0 && out[cursor - 1].timestamp > state.timestamp {
350 out[cursor] = out[cursor - 1];
351 cursor -= 1;
352 }
353 out[cursor] = state;
354 }
355 count
356}
357
358pub fn project_manifold_ltl_trace(
362 states: &[ManifoldState10D],
363 dimension: ManifoldDimension,
364 threshold: f32,
365 at_least: bool,
366 out: &mut [NQuin],
367) -> usize {
368 let count = states.len().min(out.len());
369 for (target, state) in out[..count].iter_mut().zip(states) {
370 let value = dimension.value(&state.coordinate);
371 let holds = if at_least {
372 value >= threshold
373 } else {
374 value <= threshold
375 };
376 *target = quin_with_parity(
377 state.state_id,
378 if holds {
379 MANIFOLD_THRESHOLD_HOLDS
380 } else {
381 MANIFOLD_THRESHOLD_MISS
382 },
383 value.to_bits() as u64,
384 dimension as u64,
385 state.timestamp,
386 );
387 }
388 count
389}
390
391pub fn evaluate_manifold_answer_sets(states: &[ManifoldState10D], out: &mut [u64]) -> usize {
394 use crate::modalities::asp::{compute_answer_sets, AspRule};
395
396 let mut facts = [false; 4];
397 for state in states {
398 let coordinate = &state.coordinate;
399 facts[0] |= coordinate.epistemic_weight >= coordinate.entropy_bias;
400 facts[1] |= coordinate.recurrence_frequency > coordinate.temporal_decay;
401 facts[2] |= coordinate.scale >= coordinate.density_threshold;
402 facts[3] |= coordinate.manifold_curvature.abs() > 0.25;
403 }
404
405 let mut rules = [AspRule::fact(0); 5];
406 let mut rule_count = 0usize;
407 for (present, atom) in facts.iter().zip(MANIFOLD_ASP_ATOMS.iter().take(4)) {
408 if *present {
409 rules[rule_count] = AspRule::fact(*atom);
410 rule_count += 1;
411 }
412 }
413 rules[rule_count] = AspRule::new(
415 MANIFOLD_ATOM_STABLE,
416 &[MANIFOLD_ATOM_COHERENT, MANIFOLD_ATOM_RECURRENT],
417 &[MANIFOLD_ATOM_CURVED],
418 );
419 rule_count += 1;
420 compute_answer_sets(&MANIFOLD_ASP_ATOMS, &rules[..rule_count], out)
421}
422
423pub fn project_10d_to_quaternion(parameters: &[f64; 10]) -> SolverResult<Vector4> {
426 let mut matrix = Matrix4x4::zero();
428 matrix.set(0, 0, parameters[0]);
429 matrix.set(0, 1, parameters[1]);
430 matrix.set(0, 2, parameters[2]);
431 matrix.set(0, 3, parameters[3]);
432
433 matrix.set(1, 0, parameters[1]);
434 matrix.set(1, 1, parameters[4]);
435 matrix.set(1, 2, parameters[5]);
436 matrix.set(1, 3, parameters[6]);
437
438 matrix.set(2, 0, parameters[2]);
439 matrix.set(2, 1, parameters[5]);
440 matrix.set(2, 2, parameters[7]);
441 matrix.set(2, 3, parameters[8]);
442
443 matrix.set(3, 0, parameters[3]);
444 matrix.set(3, 1, parameters[6]);
445 matrix.set(3, 2, parameters[8]);
446 matrix.set(3, 3, parameters[9]);
447
448 let mut solver = FixedLanczosEigensolver {
449 iteration: 0,
450 alpha: [0.0; 100],
451 beta: [0.0; 100],
452 vectors: [Vector4::zero(); 3],
453 eigenvalues: [0.0; 4],
454 config: SolverConfig::default(),
455 solver_state: SolverState::default(),
456 };
457
458 match solver.solve_smallest_eigenvector(&matrix) {
460 Ok(vec) => Ok(vec),
461 Err(e) => Err(e),
462 }
463}
464
465impl FixedLanczosEigensolver {
466 pub fn solve_smallest_eigenvector(&mut self, matrix: &Matrix4x4) -> SolverResult<Vector4> {
469 let mut v = Vector4 {
474 data: [1.0, 0.5, 0.25, 0.125],
475 };
476
477 let mut max_row_sum = 0.0;
478 for i in 0..4 {
479 let mut sum = 0.0;
480 for j in 0..4 {
481 sum += matrix.data[i][j].abs();
482 }
483 if sum > max_row_sum {
484 max_row_sum = sum;
485 }
486 }
487 let c = max_row_sum + 1.0; for _ in 0..self.config.max_iterations {
490 let mut shifted_matrix = Matrix4x4::zero();
491 for i in 0..4 {
492 for j in 0..4 {
493 if i == j {
494 shifted_matrix.set(i, j, c - matrix.get(i, j));
495 } else {
496 shifted_matrix.set(i, j, -matrix.get(i, j));
497 }
498 }
499 }
500
501 let mut next_v = shifted_matrix.multiply_vector(&v);
502
503 let norm = (next_v.data[0].powi(2)
505 + next_v.data[1].powi(2)
506 + next_v.data[2].powi(2)
507 + next_v.data[3].powi(2))
508 .sqrt();
509
510 if norm == 0.0 {
511 return Err(SolversError::SingularMatrix);
512 }
513
514 next_v.data[0] /= norm;
515 next_v.data[1] /= norm;
516 next_v.data[2] /= norm;
517 next_v.data[3] /= norm;
518
519 let mut diff = 0.0;
521 for i in 0..4 {
522 diff += (next_v.data[i] - v.data[i]).abs();
523 }
524
525 v = next_v;
526 self.iteration += 1;
527
528 if diff < self.config.tolerance {
529 self.solver_state.converged = true;
530 return Ok(v);
531 }
532 }
533
534 Err(SolversError::ConvergenceFailed)
535 }
536}
537
538#[cfg(test)]
539mod tests {
540 use super::*;
541 use crate::modalities::asp::atom_index;
542 use crate::modalities::temporal_ltl::{evaluate_ltl_trace, LtlFormula};
543
544 fn state(id: u64, timestamp: u64, scale: f32, curvature: f32) -> ManifoldState10D {
545 let mut coordinate = ManifoldCoordinate10D::from_sequential_layer(timestamp as u32, 10);
546 coordinate.scale = scale;
547 coordinate.density_threshold = 0.5;
548 coordinate.manifold_curvature = curvature;
549 ManifoldState10D {
550 state_id: id,
551 timestamp,
552 coordinate,
553 }
554 }
555
556 #[test]
557 fn two_quin_encoding_round_trips_and_sorts() {
558 let older = state(10, 1, 0.7, 0.0);
559 let newer = state(20, 2, 0.8, 0.0);
560 let mut older_pair = [NQuin::default(); 2];
561 let mut newer_pair = [NQuin::default(); 2];
562 encode_manifold_state(&older, &mut older_pair);
563 encode_manifold_state(&newer, &mut newer_pair);
564 assert_eq!(
565 decode_manifold_state(&older_pair[0], &older_pair[1]),
566 Some(older)
567 );
568
569 let arena_order = [newer_pair[1], older_pair[0], newer_pair[0], older_pair[1]];
570 let mut decoded = [ManifoldState10D::default(); 2];
571 let count = collect_manifold_states(&arena_order, &mut decoded);
572 assert_eq!(count, 2);
573 assert_eq!(decoded[0], older);
574 assert_eq!(decoded[1], newer);
575 }
576
577 #[test]
578 fn manifold_projection_drives_existing_ltl_evaluator() {
579 let states = [state(1, 1, 0.6, 0.0), state(2, 2, 0.9, 0.0)];
580 let mut trace = [NQuin::default(); 2];
581 let count =
582 project_manifold_ltl_trace(&states, ManifoldDimension::Scale, 0.5, true, &mut trace);
583 assert!(evaluate_ltl_trace(
584 &trace[..count],
585 &LtlFormula::Globally(MANIFOLD_THRESHOLD_HOLDS)
586 ));
587
588 let count =
589 project_manifold_ltl_trace(&states, ManifoldDimension::Scale, 0.8, true, &mut trace);
590 assert!(!evaluate_ltl_trace(
591 &trace[..count],
592 &LtlFormula::Globally(MANIFOLD_THRESHOLD_HOLDS)
593 ));
594 assert!(evaluate_ltl_trace(
595 &trace[..count],
596 &LtlFormula::Finally(MANIFOLD_THRESHOLD_HOLDS)
597 ));
598 }
599
600 #[test]
601 fn manifold_topology_drives_real_answer_set_semantics() {
602 let states = [state(1, 1, 0.7, 0.0), state(2, 2, 0.8, 0.0)];
603 let mut models = [0u64; 8];
604 let count = evaluate_manifold_answer_sets(&states, &mut models);
605 assert_eq!(count, 1);
606 let stable_index = atom_index(&MANIFOLD_ASP_ATOMS, MANIFOLD_ATOM_STABLE).unwrap();
607 assert_ne!(models[0] & (1u64 << stable_index), 0);
608
609 let curved = [state(3, 3, 0.8, 0.75)];
610 let count = evaluate_manifold_answer_sets(&curved, &mut models);
611 assert_eq!(count, 1);
612 assert_eq!(models[0] & (1u64 << stable_index), 0);
613 }
614
615 #[test]
618 fn t14_epistemic_10d_alias_exists() {
619 let coord: Epistemic10D = ManifoldCoordinate10D::default();
621 assert_eq!(coord.scale, 0.0);
622 let _: &ManifoldCoordinate10D = &coord;
624 }
625
626 #[test]
627 fn t14_two_tens_are_distinct_structs() {
628 use crate::tensor::Tensor10D;
633 let _pose = Tensor10D::default();
634 let _epistemic = Epistemic10D::default();
635 assert_ne!(
637 std::mem::size_of::<Tensor10D>(),
638 0, );
640 assert_ne!(
641 std::mem::size_of::<Epistemic10D>(),
642 0, );
644 assert_eq!(std::mem::size_of::<Tensor10D>(), 40);
646 assert_eq!(std::mem::size_of::<Epistemic10D>(), 40);
647 }
648
649 #[test]
650 fn t16_morphism_documented_in_source() {
651 let source = include_str!("manifold.rs");
654 assert!(source.contains("T14"), "missing T14 reference");
655 assert!(source.contains("T16"), "missing T16 reference");
656 assert!(source.contains("Epistemic10D"), "missing Epistemic10D name");
657 assert!(
658 source.contains("morphism"),
659 "missing morphism documentation"
660 );
661 assert!(
662 source.contains("Vibe never sees") || source.contains("VibeScript does NOT see"),
663 "missing rule that Vibe doesn't see Epistemic10D directly"
664 );
665 }
666}