Skip to main content

qualia_core_db/tensor/
mod.rs

1//! 10D Volumetric Tensor System
2//!
3//! Implements the 10-dimensional tensor coordinate system [q, v, w, x, y, z, t, α, μ, σ]
4//! for the Q42 volumetric tensor system with zero-heap hot path guarantees.
5
6pub mod bake_pipeline;
7pub mod buffer_export;
8pub mod coordinate;
9pub mod gsr;
10pub mod kv_provenance;
11pub mod manifold;
12pub mod payload;
13pub mod q42_integration;
14pub mod quantum;
15pub mod resident_substrate;
16pub mod spacetime;
17pub mod spectral;
18pub mod topology;
19pub mod volume_gpu;
20
21use bytemuck::{Pod, Zeroable};
22use serde::{Deserialize, Serialize};
23
24/// 10D Tensor coordinate system [q, v, w, x, y, z, t, α, μ, σ]
25///
26/// Zero-heap compatible, stack-allocated structure for hot path operations.
27/// Uses fixed-size f32 values for GPU/SIMD compatibility and quantization.
28#[repr(C)]
29#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable, Serialize, Deserialize)]
30pub struct Tensor10D {
31    /// Quantum Context / Superposition Index (10th dimension)
32    /// q = 0: Collapsed Ground Truth
33    /// q > 0: Parallel epistemic contexts, pending resolutions
34    pub q: f32,
35
36    /// Topological / Algebraic Variety Class
37    /// v = 0: Euclidean, v = 1: Cyclic/Toroidal, v = 2: Hyperbolic/Tree, v = 3+: Boundary Cliques
38    pub v: f32,
39
40    /// Manifold / Domain Index (Multi-Head Bifurcation)
41    /// w = 0: Medical, w = 1: Legal, w = 2: Personal, w = 3: Environmental, w = 4: Socioeconomic
42    pub w: f32,
43
44    /// Semantic Topology X coordinate
45    pub x: f32,
46
47    /// Semantic Topology Y coordinate
48    pub y: f32,
49
50    /// Semantic Topology Z coordinate
51    pub z: f32,
52
53    /// Temporal State / Provenance Ledger
54    pub t: f32,
55
56    /// Spectral Amplitude / Dynamic Range / Confidence Weight
57    pub alpha: f32,
58
59    /// Spectral Modulation / Phase / Metadata Carrier
60    pub mu: f32,
61
62    /// Spectral Signature / Logical Class Index
63    pub sigma: f32,
64}
65
66impl Default for Tensor10D {
67    fn default() -> Self {
68        Self {
69            q: 0.0, // Ground truth by default
70            v: 0.0, // Euclidean topology by default
71            w: 0.0, // Medical domain by default
72            x: 0.0,
73            y: 0.0,
74            z: 0.0,
75            t: 0.0,     // Initial time slice
76            alpha: 1.0, // Full confidence/amplitude by default
77            mu: 0.0,
78            sigma: 0.0,
79        }
80    }
81}
82
83impl Tensor10D {
84    /// Creates a new tensor with specified coordinates
85    #[inline]
86    pub fn new(
87        q: f32,
88        v: f32,
89        w: f32,
90        x: f32,
91        y: f32,
92        z: f32,
93        t: f32,
94        alpha: f32,
95        mu: f32,
96        sigma: f32,
97    ) -> Self {
98        Self {
99            q,
100            v,
101            w,
102            x,
103            y,
104            z,
105            t,
106            alpha,
107            mu,
108            sigma,
109        }
110    }
111
112    /// Creates a ground truth tensor (q = 0)
113    #[inline]
114    pub fn ground_truth(
115        v: f32,
116        w: f32,
117        x: f32,
118        y: f32,
119        z: f32,
120        t: f32,
121        alpha: f32,
122        mu: f32,
123        sigma: f32,
124    ) -> Self {
125        Self {
126            q: 0.0,
127            v,
128            w,
129            x,
130            y,
131            z,
132            t,
133            alpha,
134            mu,
135            sigma,
136        }
137    }
138
139    /// Creates a parallel context tensor (q > 0)
140    #[inline]
141    pub fn parallel_context(
142        q: f32,
143        v: f32,
144        w: f32,
145        x: f32,
146        y: f32,
147        z: f32,
148        t: f32,
149        alpha: f32,
150        mu: f32,
151        sigma: f32,
152    ) -> Self {
153        Self {
154            q,
155            v,
156            w,
157            x,
158            y,
159            z,
160            t,
161            alpha,
162            mu,
163            sigma,
164        }
165    }
166
167    /// Returns true if this is a ground truth tensor (q = 0)
168    #[inline]
169    pub fn is_ground_truth(&self) -> bool {
170        self.q == 0.0
171    }
172
173    /// Calculates Euclidean distance between spatial coordinates (x, y, z)
174    #[inline]
175    pub fn spatial_distance(&self, other: &Self) -> f32 {
176        let dx = self.x - other.x;
177        let dy = self.y - other.y;
178        let dz = self.z - other.z;
179        (dx * dx + dy * dy + dz * dz).sqrt()
180    }
181
182    /// Calculates full 10D distance considering topological adjustments
183    #[inline]
184    pub fn full_distance(&self, other: &Self) -> f32 {
185        // Use topological class to determine distance metric
186        match self.v as u32 {
187            0 => self.euclidean_distance(other),  // Euclidean
188            1 => self.cyclic_distance(other),     // Cyclic/Toroidal
189            2 => self.hyperbolic_distance(other), // Hyperbolic/Tree
190            _ => self.boundary_distance(other),   // Boundary Cliques
191        }
192    }
193
194    /// Euclidean distance (standard straight-line)
195    #[inline]
196    fn euclidean_distance(&self, other: &Self) -> f32 {
197        let spatial = self.spatial_distance(other);
198        let temporal = (self.t - other.t).abs();
199        let spectral = ((self.alpha - other.alpha).powi(2)
200            + (self.mu - other.mu).powi(2)
201            + (self.sigma - other.sigma).powi(2))
202        .sqrt();
203        (spatial.powi(2) + temporal.powi(2) + spectral.powi(2)).sqrt()
204    }
205
206    /// Cyclic distance (modulo arithmetic for toroidal topology)
207    #[inline]
208    fn cyclic_distance(&self, other: &Self) -> f32 {
209        let dx = (self.x - other.x).abs().min(1.0 - (self.x - other.x).abs());
210        let dy = (self.y - other.y).abs().min(1.0 - (self.y - other.y).abs());
211        let dz = (self.z - other.z).abs().min(1.0 - (self.z - other.z).abs());
212        (dx * dx + dy * dy + dz * dz).sqrt()
213    }
214
215    /// Hyperbolic distance (exponential hierarchy)
216    #[inline]
217    fn hyperbolic_distance(&self, other: &Self) -> f32 {
218        let dx = (self.x - other.x).abs();
219        let dy = (self.y - other.y).abs();
220        let dz = (self.z - other.z).abs();
221        (dx.exp() + dy.exp() + dz.exp()).ln()
222    }
223
224    /// Boundary clique distance (byte comparison)
225    #[inline]
226    fn boundary_distance(&self, other: &Self) -> f32 {
227        if self.v == other.v {
228            0.0
229        } else {
230            1.0
231        }
232    }
233
234    /// Returns true if this is a parallel context tensor (q > 0)
235    #[inline]
236    pub fn is_parallel_context(&self) -> bool {
237        self.q > 0.0
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn test_tensor_default() {
247        let tensor = Tensor10D::default();
248        assert_eq!(tensor.q, 0.0);
249        assert_eq!(tensor.v, 0.0);
250        assert_eq!(tensor.w, 0.0);
251        assert!(tensor.is_ground_truth());
252        assert!(!tensor.is_parallel_context());
253    }
254
255    #[test]
256    fn test_tensor_new() {
257        let tensor = Tensor10D::new(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);
258        assert_eq!(tensor.q, 1.0);
259        assert_eq!(tensor.v, 2.0);
260        assert_eq!(tensor.w, 3.0);
261        assert!(tensor.is_parallel_context());
262    }
263
264    #[test]
265    fn test_ground_truth() {
266        let tensor = Tensor10D::ground_truth(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 0.0, 0.0);
267        assert!(tensor.is_ground_truth());
268        assert!(!tensor.is_parallel_context());
269        assert_eq!(tensor.q, 0.0);
270    }
271
272    #[test]
273    fn test_spatial_distance() {
274        let t1 = Tensor10D::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0);
275        let t2 = Tensor10D::new(0.0, 0.0, 0.0, 3.0, 4.0, 0.0, 0.0, 1.0, 0.0, 0.0);
276        let distance = t1.spatial_distance(&t2);
277        assert!((distance - 5.0).abs() < 0.001); // 3-4-5 triangle
278    }
279
280    #[test]
281    fn test_full_distance() {
282        let t1 = Tensor10D::default();
283        let t2 = Tensor10D::default();
284        assert_eq!(t1.full_distance(&t2), 0.0);
285    }
286
287    #[test]
288    fn test_pod_zeroable() {
289        // Test that Tensor10D satisfies Pod and Zeroable traits
290        let tensor = Tensor10D::default();
291        assert_eq!(tensor.q, 0.0);
292        assert_eq!(tensor.v, 0.0);
293
294        // Test byte-level equality for Pod
295        let t1 = Tensor10D::new(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);
296        let bytes: &[u8] = bytemuck::bytes_of(&t1);
297        assert_eq!(bytes.len(), std::mem::size_of::<Tensor10D>());
298    }
299
300    // ───────────────────────────────────────────────────────────────────
301    //  P7.9 — Axis-completeness regression guards
302    //
303    //  Decision: documented-limit path (option b). The `.10d` header's
304    //  metric-completeness descriptor declares which axes each v-branch
305    //  folds, and `metric_check::verify_descriptor_against_reality`
306    //  enforces that the declaration matches `full_distance`'s actual
307    //  behaviour. These tests guard the decision: the Euclidean branch
308    //  (v=0) is axis-complete (folds all 7 COORDINATE axes), while the
309    //  non-Euclidean branches (v=1,2,3+) are documented as NOT folding
310    //  α/μ/σ/t. If a future change makes a non-Euclidean branch
311    //  axis-complete, these tests must be updated AND the descriptor
312    //  in `metric_check::proposed_metric_descriptor` must be updated.
313    // ───────────────────────────────────────────────────────────────────
314
315    #[test]
316    fn p7_9_v0_euclidean_alpha_changes_distance() {
317        let base = Tensor10D::default();
318        let mut perturbed = base;
319        perturbed.alpha += 0.25;
320        assert!(
321            base.full_distance(&perturbed) > 1e-6,
322            "v=0: changing α must change distance (axis-complete)"
323        );
324    }
325
326    #[test]
327    fn p7_9_v0_euclidean_mu_changes_distance() {
328        let base = Tensor10D::default();
329        let mut perturbed = base;
330        perturbed.mu += 0.25;
331        assert!(
332            base.full_distance(&perturbed) > 1e-6,
333            "v=0: changing μ must change distance (axis-complete)"
334        );
335    }
336
337    #[test]
338    fn p7_9_v0_euclidean_sigma_changes_distance() {
339        let base = Tensor10D::default();
340        let mut perturbed = base;
341        perturbed.sigma += 0.25;
342        assert!(
343            base.full_distance(&perturbed) > 1e-6,
344            "v=0: changing σ must change distance (axis-complete)"
345        );
346    }
347
348    #[test]
349    fn p7_9_v0_euclidean_t_changes_distance() {
350        let base = Tensor10D::default();
351        let mut perturbed = base;
352        perturbed.t += 0.25;
353        assert!(
354            base.full_distance(&perturbed) > 1e-6,
355            "v=0: changing t must change distance (axis-complete)"
356        );
357    }
358
359    #[test]
360    fn p7_9_v1_cyclic_alpha_does_not_change_distance() {
361        let mut base = Tensor10D::default();
362        base.v = 1.0;
363        let mut perturbed = base;
364        perturbed.alpha += 0.25;
365        assert!(
366            base.full_distance(&perturbed) < 1e-6,
367            "v=1: changing α must NOT change distance (documented limit)"
368        );
369    }
370
371    #[test]
372    fn p7_9_v1_cyclic_sigma_does_not_change_distance() {
373        let mut base = Tensor10D::default();
374        base.v = 1.0;
375        let mut perturbed = base;
376        perturbed.sigma += 0.25;
377        assert!(
378            base.full_distance(&perturbed) < 1e-6,
379            "v=1: changing σ must NOT change distance (documented limit)"
380        );
381    }
382
383    #[test]
384    fn p7_9_v2_hyperbolic_t_does_not_change_distance() {
385        let mut base = Tensor10D::default();
386        base.v = 2.0;
387        let mut perturbed = base;
388        perturbed.t += 0.25;
389        let d_base = base.full_distance(&base);
390        let d_perturbed = base.full_distance(&perturbed);
391        assert!(
392            (d_perturbed - d_base).abs() < 1e-6,
393            "v=2: changing t must NOT change distance (documented limit): {} vs {}",
394            d_base,
395            d_perturbed
396        );
397    }
398
399    #[test]
400    fn p7_9_v3_boundary_alpha_does_not_change_distance() {
401        let mut base = Tensor10D::default();
402        base.v = 3.0;
403        let mut perturbed = base;
404        perturbed.alpha += 0.25;
405        assert!(
406            base.full_distance(&perturbed) < 1e-6,
407            "v>=3: changing α must NOT change distance (documented limit)"
408        );
409    }
410
411    #[test]
412    fn p7_9_v0_euclidean_q_does_not_change_distance() {
413        let base = Tensor10D::default();
414        let mut perturbed = base;
415        perturbed.q += 0.25;
416        assert!(
417            base.full_distance(&perturbed) < 1e-6,
418            "v=0: q is a SELECTOR, must NOT change distance"
419        );
420    }
421
422    #[test]
423    fn p7_9_v0_euclidean_w_does_not_change_distance() {
424        let base = Tensor10D::default();
425        let mut perturbed = base;
426        perturbed.w += 0.25;
427        assert!(
428            base.full_distance(&perturbed) < 1e-6,
429            "v=0: w is a SELECTOR, must NOT change distance"
430        );
431    }
432}