Skip to main content

qualia_core_db/modalities/
spatiotemporal_predicates.rs

1//! Spatiotemporal Datetime Predicates & Relativistic Coordinate Modality.
2//!
3//! Provides coordinate-anchored temporal reasoning across micro-to-macro scales:
4//! relativistic light-travel offsets, gravitational potential proper time gradients,
5//! quantum biological decoherence rates, temporal mereology, and ecological persistence horizons.
6//!
7//! Reference: `docs/plans/holo/Spatiotemporal Datetime Predicates in QualiaDB.md`
8
9use crate::NQuin;
10
11/// Physical constants
12pub const SPEED_OF_LIGHT_M_S: f64 = 299_792_458.0;
13pub const STANDARD_GRAVITY_M_S2: f64 = 9.80665;
14pub const C_SQUARED: f64 = SPEED_OF_LIGHT_M_S * SPEED_OF_LIGHT_M_S;
15
16/// Modality opcodes (0x70–0x7F reserved for Spatiotemporal according to AGENTS.md)
17pub const OP_SPATIOTEMPORAL_ANCHOR: u8 = 0x70;      // observer:referenceFrame / anchor
18pub const OP_TIME_AT_OBSERVER: u8 = 0x71;           // observer:timeAtObserver
19pub const OP_PROPER_TIME_GRADIENT: u8 = 0x72;       // quantum:properTimeGradient
20pub const OP_SPATIAL_DECOHERENCE: u8 = 0x73;        // quantum:spatialDecoherenceRate
21pub const OP_TEMPORAL_CONTAINMENT: u8 = 0x74;       // mereology:temporalContainment
22pub const OP_PERSISTENCE_HORIZON: u8 = 0x75;        // environmental:persistenceHorizon
23pub const OP_ECOLOGICAL_RESIDUE: u8 = 0x76;         // environmental:ecologicalResidue
24pub const OP_BIOMAGNIFICATION_LAG: u8 = 0x77;       // environmental:biomagnificationLag
25pub const OP_SPATIOTEMPORAL_COINCIDENCE: u8 = 0x78; // topology:spatiallyCoincident
26pub const OP_ASYMMETRIC_RECURRENCE: u8 = 0x79;      // temporal:asymmetricRecurrence
27pub const OP_LATENT_EPOCH: u8 = 0x7A;               // biological:latentEpoch
28pub const OP_CIRCADIAN_OVERRIDE: u8 = 0x7B;         // causality:circadianEntrainmentOverride
29pub const OP_MEREOLOGY_LIFESPAN: u8 = 0x7C;         // mereology:constituentLifespan
30pub const OP_INDIGENOUS_EPOCH: u8 = 0x7D;           // ecology:indigenousEpoch
31pub const OP_INTRODUCTION_EVENT: u8 = 0x7E;         // ecology:introductionEvent
32pub const OP_NATURALIZATION_ONSET: u8 = 0x7F;       // ecology:naturalizationOnset
33
34/// Observer status at perception time
35#[repr(u8)]
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ObserverStatus {
38    Stationary = 0,
39    InTransit = 1,
40    Accelerating = 2,
41    Obstructed = 3,
42}
43
44/// A precise spatiotemporal point anchoring a nanosecond timestamp to physical 3D space.
45#[repr(C)]
46#[derive(Debug, Clone, Copy, PartialEq)]
47pub struct SpatiotemporalPoint {
48    /// 3D coordinates (x, y, z) in meters relative to datum origin
49    pub pos_xyz_m: [f64; 3],
50    /// Geodetic Spatial Reference ID (e.g. 7844 for GDA2020, 4326 for WGS84, 5711 for AHD)
51    pub srid_code: u32,
52    /// Absolute POSIX timestamp in integer nanoseconds (10⁻⁹ s since UNIX epoch)
53    pub unix_time_nanos: u64,
54    /// Altitude above vertical datum in meters (AHD) for gravitational dilation
55    pub elevation_m: f64,
56    /// Velocity vector in meters/sec for kinematic Lorentz dilation
57    pub velocity_m_s: [f64; 3],
58    /// Unique identifier (FNV-1a hash) of the spatial reference frame
59    pub reference_frame_id: u64,
60    /// Observer status at timestamp
61    pub observer_status: ObserverStatus,
62}
63
64impl Default for SpatiotemporalPoint {
65    /// Origin at epoch 0 in GDA2020 (SRID 7844), stationary, no
66    /// elevation/velocity, unresolved frame (`reference_frame_id` 0).
67    fn default() -> Self {
68        Self {
69            pos_xyz_m: [0.0; 3],
70            srid_code: 7844, // GDA2020
71            unix_time_nanos: 0,
72            elevation_m: 0.0,
73            velocity_m_s: [0.0; 3],
74            reference_frame_id: 0,
75            observer_status: ObserverStatus::Stationary,
76        }
77    }
78}
79
80impl SpatiotemporalPoint {
81    /// A stationary point at `(x, y, z)` metres in spatial reference
82    /// `srid` at `nanos` ns since Unix epoch — velocity zeroed, frame
83    /// unresolved, `Stationary` status.
84    pub fn new(x: f64, y: f64, z: f64, srid: u32, nanos: u64, elevation_m: f64) -> Self {
85        Self {
86            pos_xyz_m: [x, y, z],
87            srid_code: srid,
88            unix_time_nanos: nanos,
89            elevation_m,
90            velocity_m_s: [0.0; 3],
91            reference_frame_id: 0,
92            observer_status: ObserverStatus::Stationary,
93        }
94    }
95
96    /// Evaluates scalar speed in m/s.
97    #[inline]
98    pub fn speed_m_s(&self) -> f64 {
99        let v2 = self.velocity_m_s[0] * self.velocity_m_s[0]
100            + self.velocity_m_s[1] * self.velocity_m_s[1]
101            + self.velocity_m_s[2] * self.velocity_m_s[2];
102        v2.sqrt()
103    }
104}
105
106/// Evaluates light-travel offset between source and observer in nanoseconds.
107///
108/// $\Delta t = \frac{\|\mathbf{x}_{\text{obs}} - \mathbf{x}_{\text{src}}\|}{c} \times 10^9$
109#[inline]
110pub fn evaluate_light_travel_offset_nanos(
111    source: &SpatiotemporalPoint,
112    observer: &SpatiotemporalPoint,
113) -> u64 {
114    let dx = observer.pos_xyz_m[0] - source.pos_xyz_m[0];
115    let dy = observer.pos_xyz_m[1] - source.pos_xyz_m[1];
116    let dz = observer.pos_xyz_m[2] - source.pos_xyz_m[2];
117    let distance_m = (dx * dx + dy * dy + dz * dz).sqrt();
118    let seconds = distance_m / SPEED_OF_LIGHT_M_S;
119    (seconds * 1_000_000_000.0).round() as u64
120}
121
122/// Evaluates the true source time given an observer timestamp and their respective positions.
123///
124/// $t_{\text{src}} = t_{\text{obs}} - \Delta t_{\text{light}}$
125#[inline]
126pub fn evaluate_observed_source_time(
127    observer_time_nanos: u64,
128    source: &SpatiotemporalPoint,
129    observer: &SpatiotemporalPoint,
130) -> u64 {
131    let offset_nanos = evaluate_light_travel_offset_nanos(source, observer);
132    observer_time_nanos.saturating_sub(offset_nanos)
133}
134
135/// Evaluates General Relativistic proper time rate $d\tau / dt$ at a given elevation and speed.
136///
137/// Combines gravitational blueshift ($+gh/c^2$) and kinematic dilation ($-v^2/2c^2$):
138/// $\frac{d\tau}{dt} \approx 1.0 + \frac{g \cdot h}{c^2} - \frac{v^2}{2 c^2}$
139#[inline]
140pub fn evaluate_proper_time_rate(elevation_ahd_m: f64, speed_m_s: f64) -> f64 {
141    let grav_term = (STANDARD_GRAVITY_M_S2 * elevation_ahd_m) / C_SQUARED;
142    let kin_term = (speed_m_s * speed_m_s) / (2.0 * C_SQUARED);
143    1.0 + grav_term - kin_term
144}
145
146/// Evaluates net proper time drift in nanoseconds relative to standard sea-level coordinate time
147/// over a given elapsed duration in seconds.
148///
149/// $\Delta \tau_{\text{drift}} = ( \frac{d\tau}{dt} - 1.0 ) \times \text{duration} \times 10^9$
150#[inline]
151pub fn evaluate_proper_time_drift_nanos(
152    elevation_ahd_m: f64,
153    speed_m_s: f64,
154    duration_seconds: f64,
155) -> f64 {
156    let rate = evaluate_proper_time_rate(elevation_ahd_m, speed_m_s);
157    (rate - 1.0) * duration_seconds * 1_000_000_000.0
158}
159
160/// Evaluates quantum proper time gradient across microscopic nodes.
161///
162/// $t_{\text{localized}} = \text{round}(t_{\text{base}} \times \text{dilation\_factor})$
163#[inline]
164pub fn evaluate_quantum_gradient_nanos(base_time_nanos: u64, dilation_factor: f64) -> u64 {
165    ((base_time_nanos as f64) * dilation_factor).round() as u64
166}
167
168/// Evaluates an anthropogenic chemical or pesticide persistence horizon in nanoseconds.
169///
170/// $t_{\text{horizon}} = t_{\text{application}} + (\text{half\_lives} \times t_{\text{half\_life}})$
171#[inline]
172pub fn evaluate_persistence_horizon_nanos(
173    app_time_nanos: u64,
174    half_life_nanos: u64,
175    half_lives: u32,
176) -> u64 {
177    app_time_nanos.saturating_add((half_lives as u64).saturating_mul(half_life_nanos))
178}
179
180/// Evaluates temporal collision and exposure window between two spatiotemporal intervals
181/// using Allen's Interval Algebra.
182///
183/// Returns `Some((exposure_start, exposure_end))` if the intervals overlap, or `None`.
184#[inline]
185pub fn evaluate_spatiotemporal_exposure_window(
186    subject_span: (u64, u64),
187    contaminant_span: (u64, u64),
188) -> Option<(u64, u64)> {
189    let (sub_start, sub_end) = subject_span;
190    let (con_start, con_end) = contaminant_span;
191
192    // Allen interval overlap condition: sub_start <= con_end && sub_end >= con_start
193    if sub_start <= con_end && sub_end >= con_start {
194        let start = sub_start.max(con_start);
195        let end = sub_end.min(con_end);
196        Some((start, end))
197    } else {
198        None
199    }
200}
201
202/// Evaluates temporal mereology containment: asserts that a child's lifecycle
203/// falls entirely within the parent organism or structure's lifespan.
204#[inline]
205pub fn evaluate_temporal_containment(
206    child_span: (u64, u64),
207    parent_span: (u64, u64),
208) -> bool {
209    child_span.0 >= parent_span.0 && child_span.1 <= parent_span.1
210}
211
212/// Evaluates spatial coincidence: checks if two 3D positions are within an epsilon tolerance.
213#[inline]
214pub fn evaluate_spatial_coincidence(
215    pos_a: &[f64; 3],
216    pos_b: &[f64; 3],
217    tolerance_m: f64,
218) -> bool {
219    let dx = pos_a[0] - pos_b[0];
220    let dy = pos_a[1] - pos_b[1];
221    let dz = pos_a[2] - pos_b[2];
222    (dx * dx + dy * dy + dz * dz) <= (tolerance_m * tolerance_m)
223}
224
225/// Compiles a coordinate-anchored spatiotemporal fact into a 48-byte Super-Quin (`NQuin`).
226///
227/// - `subject`: DID hash of the spatial entity or work
228/// - `predicate`: `opcode` in bits [0..7], property hash in [8..62]
229/// - `object`: nanosecond timestamp or scalar payload
230/// - `context`: world / bounding-box context DID hash
231/// - `metadata`: Lamport logical clock in [32..60], opcode in [0..7]
232/// - `parity`: XOR fold of subject ^ predicate ^ object ^ context
233pub fn compile_spatiotemporal_quin(
234    entity_did_hash: u64,
235    property_hash: u64,
236    opcode: u8,
237    timestamp_nanos: u64,
238    context_did_hash: u64,
239    lamport_clock: u32,
240) -> NQuin {
241    let predicate = ((property_hash & 0x007F_FFFF_FFFF_FFFF) << 8) | (opcode as u64);
242    let metadata = ((lamport_clock as u64 & 0x1FFF_FFFF) << 32) | (opcode as u64);
243    let parity = entity_did_hash ^ predicate ^ timestamp_nanos ^ context_did_hash;
244
245    NQuin {
246        subject: entity_did_hash,
247        predicate,
248        object: timestamp_nanos,
249        context: context_did_hash,
250        metadata,
251        parity,
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[test]
260    fn test_light_travel_offset_and_source_time() {
261        let src = SpatiotemporalPoint::new(0.0, 0.0, 0.0, 7844, 1_000_000_000, 385.0);
262        // Observer located 299,792.458 meters away (~300 km) -> exact 1 millisecond (1,000,000 ns)
263        let obs = SpatiotemporalPoint::new(SPEED_OF_LIGHT_M_S / 1000.0, 0.0, 0.0, 7844, 0, 385.0);
264
265        let dt_nanos = evaluate_light_travel_offset_nanos(&src, &obs);
266        assert_eq!(dt_nanos, 1_000_000); // 1.0 ms in nanoseconds
267
268        let obs_time = 2_000_000_000u64;
269        let deduced_src_time = evaluate_observed_source_time(obs_time, &src, &obs);
270        assert_eq!(deduced_src_time, 1_999_000_000u64);
271    }
272
273    #[test]
274    fn test_gravitational_and_kinematic_proper_time_dilation() {
275        // At sea level stationary: dtau/dt = 1.0
276        let rate_sea_level = evaluate_proper_time_rate(0.0, 0.0);
277        assert!((rate_sea_level - 1.0).abs() < 1e-15);
278
279        // At Mount Kosciuszko summit (2228m elevation): clocks tick faster
280        let rate_summit = evaluate_proper_time_rate(2228.0, 0.0);
281        assert!(rate_summit > 1.0);
282        let fractional_advance = rate_summit - 1.0;
283        // ~2.43e-13 advance per second
284        assert!(fractional_advance > 2.0e-13 && fractional_advance < 3.0e-13);
285
286        // Drift over 1 day (86,400 seconds) at Kosciuszko summit vs sea level
287        let drift_day_nanos = evaluate_proper_time_drift_nanos(2228.0, 0.0, 86400.0);
288        // ~21 nanoseconds/day faster
289        assert!(drift_day_nanos > 15.0 && drift_day_nanos < 25.0);
290    }
291
292    #[test]
293    fn test_quantum_proper_time_gradient() {
294        let base_nanos = 1_729_123_456_789_000_000u64;
295        let dilation_factor = 1.0000000000000002;
296        let target_nanos = evaluate_quantum_gradient_nanos(base_nanos, dilation_factor);
297        assert!(target_nanos >= base_nanos);
298    }
299
300    #[test]
301    fn test_persistence_horizon_and_allen_exposure() {
302        let app_time = 1_000_000_000u64;
303        let half_life = 40_000_000u64; // e.g. 40ms half-life for test
304        let horizon = evaluate_persistence_horizon_nanos(app_time, half_life, 5); // 5 half-lives
305        assert_eq!(horizon, 1_200_000_000);
306
307        // Case 1: Crop planted during active residue
308        let crop_span = (1_050_000_000, 1_300_000_000);
309        let residue_span = (app_time, horizon);
310        let exposure = evaluate_spatiotemporal_exposure_window(crop_span, residue_span);
311        assert_eq!(exposure, Some((1_050_000_000, 1_200_000_000)));
312
313        // Case 2: Crop planted after residue horizon has passed
314        let late_crop = (1_250_000_000, 1_400_000_000);
315        let no_exposure = evaluate_spatiotemporal_exposure_window(late_crop, residue_span);
316        assert_eq!(no_exposure, None);
317    }
318
319    #[test]
320    fn test_temporal_mereology_containment() {
321        let host_lifespan = (1_000_000_000u64, 5_000_000_000u64);
322        let rbc_lifespan = (2_000_000_000u64, 2_120_000_000u64); // Red blood cell ~120 days
323        assert!(evaluate_temporal_containment(rbc_lifespan, host_lifespan));
324
325        let out_of_bounds = (900_000_000u64, 2_000_000_000u64);
326        assert!(!evaluate_temporal_containment(out_of_bounds, host_lifespan));
327    }
328
329    #[test]
330    fn test_spatial_coincidence() {
331        let pos1 = [148.29, -35.78, 350.0];
332        let pos2 = [148.29, -35.78, 350.005]; // 5mm away
333        assert!(evaluate_spatial_coincidence(&pos1, &pos2, 0.01)); // within 1cm
334        assert!(!evaluate_spatial_coincidence(&pos1, &pos2, 0.001)); // outside 1mm
335    }
336
337    #[test]
338    fn test_compile_spatiotemporal_quin() {
339        let quin = compile_spatiotemporal_quin(
340            0x1234_5678,
341            0x9ABC_DEF0,
342            OP_SPATIOTEMPORAL_ANCHOR,
343            1_744_675_200_000_000_000,
344            0xFEED_FACE,
345            42,
346        );
347        assert_eq!(quin.subject, 0x1234_5678);
348        assert_eq!(quin.object, 1_744_675_200_000_000_000);
349        assert_eq!((quin.predicate & 0xFF) as u8, OP_SPATIOTEMPORAL_ANCHOR);
350        assert_eq!(
351            quin.parity,
352            quin.subject ^ quin.predicate ^ quin.object ^ quin.context
353        );
354    }
355}