aprender-simulate 0.30.0

Unified Simulation Engine for the Sovereign AI Stack
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Core simulation engine.
//!
//! Implements the central simulation loop with:
//! - Deterministic RNG (PCG with partitioned seeds)
//! - Event scheduling with deterministic ordering
//! - Jidoka guards for stop-on-error
//! - State management

pub mod clock;
pub mod jidoka;
pub mod rng;
pub mod scheduler;
pub mod state;

use serde::{Deserialize, Serialize};

pub use clock::SimClock;
pub use jidoka::{JidokaGuard, JidokaViolation};
pub use rng::SimRng;
pub use scheduler::{EventScheduler, ScheduledEvent};
pub use state::SimState;

use crate::config::{IntegratorType, PhysicsEngine as ConfigPhysicsEngine, SimConfig};
use crate::domains::physics::{
    CentralForceField, EulerIntegrator, ForceField, GravityField, Integrator, PhysicsEngine,
    RK4Integrator, VerletIntegrator,
};
use crate::engine::state::Vec3;
use crate::error::SimResult;

/// Simulation time representation.
///
/// Uses a fixed-point representation for reproducibility across platforms.
/// Internal representation is in nanoseconds to avoid floating-point issues.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
)]
pub struct SimTime {
    /// Time in nanoseconds from simulation start.
    nanos: u64,
}

impl SimTime {
    /// Zero time (simulation start).
    pub const ZERO: Self = Self { nanos: 0 };

    /// Create time from seconds.
    ///
    /// # Panics
    ///
    /// Panics if seconds is negative or not finite.
    #[must_use]
    pub fn from_secs(secs: f64) -> Self {
        assert!(secs >= 0.0, "SimTime cannot be negative");
        assert!(secs.is_finite(), "SimTime must be finite");
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let nanos = (secs * 1_000_000_000.0) as u64;
        Self { nanos }
    }

    /// Create time from nanoseconds.
    #[must_use]
    pub const fn from_nanos(nanos: u64) -> Self {
        Self { nanos }
    }

    /// Get time as seconds (f64).
    #[must_use]
    pub fn as_secs_f64(&self) -> f64 {
        self.nanos as f64 / 1_000_000_000.0
    }

    /// Get time as nanoseconds.
    #[must_use]
    pub const fn as_nanos(&self) -> u64 {
        self.nanos
    }

    /// Add duration to time.
    #[must_use]
    pub const fn add_nanos(self, nanos: u64) -> Self {
        Self {
            nanos: self.nanos + nanos,
        }
    }

    /// Subtract duration from time, saturating at zero.
    #[must_use]
    pub const fn saturating_sub_nanos(self, nanos: u64) -> Self {
        Self {
            nanos: self.nanos.saturating_sub(nanos),
        }
    }
}

impl std::ops::Add for SimTime {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self {
            nanos: self.nanos + rhs.nanos,
        }
    }
}

impl std::ops::Sub for SimTime {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            nanos: self.nanos.saturating_sub(rhs.nanos),
        }
    }
}

impl std::fmt::Display for SimTime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:.9}s", self.as_secs_f64())
    }
}

/// Main simulation engine.
///
/// Coordinates all subsystems:
/// - Event scheduling
/// - State management
/// - Jidoka monitoring
/// - Checkpointing
/// - Physics simulation
pub struct SimEngine {
    /// Current simulation state.
    state: SimState,
    /// Event scheduler.
    scheduler: EventScheduler,
    /// Jidoka guard for anomaly detection.
    jidoka: JidokaGuard,
    /// Simulation clock.
    clock: SimClock,
    /// Random number generator.
    rng: SimRng,
    /// Physics engine (optional).
    physics: Option<PhysicsEngine>,
    /// Configuration (stored for reference and future use).
    #[allow(dead_code)]
    config: SimConfig,
}

impl SimEngine {
    /// Create a new simulation engine from configuration.
    ///
    /// # Errors
    ///
    /// Returns error if configuration validation fails.
    pub fn new(config: SimConfig) -> SimResult<Self> {
        let seed = config.reproducibility.seed;
        let rng = SimRng::new(seed);
        let jidoka = JidokaGuard::from_config(&config);
        let clock = SimClock::new(config.get_timestep());

        // Initialize Physics Engine based on config
        let physics = if config.domains.physics.enabled {
            let integrator: Box<dyn Integrator + Send + Sync> =
                match config.domains.physics.integrator.integrator_type {
                    IntegratorType::Euler => Box::new(EulerIntegrator::new()),
                    IntegratorType::Rk4 => Box::new(RK4Integrator::new()),
                    // Default to Verlet for Verlet, Rk78, SymplecticEuler, etc.
                    _ => Box::new(VerletIntegrator::new()),
                };

            let force_field: Box<dyn ForceField + Send + Sync> = match config.domains.physics.engine
            {
                ConfigPhysicsEngine::Orbital => Box::new(CentralForceField::new(1.0, Vec3::zero())), // Default mu=1.0 for now
                // Default to GravityField for RigidBody, Fluid, Discrete, etc.
                _ => Box::new(GravityField::default()),
            };

            Some(PhysicsEngine::new_boxed(force_field, integrator))
        } else {
            None
        };

        Ok(Self {
            state: SimState::default(),
            scheduler: EventScheduler::new(),
            jidoka,
            clock,
            rng,
            physics,
            config,
        })
    }

    /// Get current simulation time.
    #[must_use]
    #[allow(clippy::missing_const_for_fn)] // Delegating to non-const method
    pub fn current_time(&self) -> SimTime {
        self.clock.current_time()
    }

    /// Get current simulation state.
    #[must_use]
    pub const fn state(&self) -> &SimState {
        &self.state
    }

    /// Get mutable reference to state.
    #[must_use]
    pub fn state_mut(&mut self) -> &mut SimState {
        &mut self.state
    }

    /// Get reference to RNG.
    #[must_use]
    pub const fn rng(&self) -> &SimRng {
        &self.rng
    }

    /// Get mutable reference to RNG.
    #[must_use]
    pub fn rng_mut(&mut self) -> &mut SimRng {
        &mut self.rng
    }

    /// Step the simulation forward by one timestep.
    ///
    /// # Errors
    ///
    /// Returns `SimError` if:
    /// - Jidoka violation detected (NaN, energy drift, constraint)
    /// - Domain engine error
    pub fn step(&mut self) -> SimResult<()> {
        // Advance clock
        self.clock.tick();

        // Process scheduled events
        while let Some(event) = self.scheduler.next_before(self.clock.current_time()) {
            self.state.apply_event(&event.event)?;
        }

        // Run Physics Step
        if let Some(physics) = &self.physics {
            physics.step(&mut self.state, self.clock.dt())?;
        }

        // Jidoka check (stop-on-error)
        self.jidoka.check(&self.state)?;

        Ok(())
    }

    /// Run simulation for specified duration.
    ///
    /// # Errors
    ///
    /// Returns error if any step fails.
    pub fn run_for(&mut self, duration: SimTime) -> SimResult<()> {
        let end_time = self.clock.current_time() + duration;

        while self.clock.current_time() < end_time {
            self.step()?;
        }

        Ok(())
    }

    /// Run simulation until predicate returns true.
    ///
    /// # Errors
    ///
    /// Returns error if any step fails.
    pub fn run_until<F>(&mut self, predicate: F) -> SimResult<()>
    where
        F: Fn(&SimState) -> bool,
    {
        while !predicate(&self.state) {
            self.step()?;
        }

        Ok(())
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::config::SimConfig;

    #[test]
    fn test_sim_time_creation() {
        let t1 = SimTime::from_secs(1.5);
        assert!((t1.as_secs_f64() - 1.5).abs() < 1e-9);

        let t2 = SimTime::from_nanos(1_500_000_000);
        assert_eq!(t1, t2);
    }

    #[test]
    fn test_sim_time_arithmetic() {
        let t1 = SimTime::from_secs(1.0);
        let t2 = SimTime::from_secs(0.5);

        let sum = t1 + t2;
        assert!((sum.as_secs_f64() - 1.5).abs() < 1e-9);

        let diff = t1 - t2;
        assert!((diff.as_secs_f64() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_sim_time_ordering() {
        let t1 = SimTime::from_secs(1.0);
        let t2 = SimTime::from_secs(2.0);

        assert!(t1 < t2);
        assert!(t2 > t1);
        assert_eq!(t1, t1);
    }

    #[test]
    fn test_sim_time_display() {
        let t = SimTime::from_secs(1.234_567_890);
        let s = t.to_string();
        assert!(s.contains("1.234567890"));
    }

    #[test]
    fn test_sim_time_zero() {
        let t = SimTime::ZERO;
        assert_eq!(t.as_nanos(), 0);
        assert!((t.as_secs_f64() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_sim_time_add_nanos() {
        let t = SimTime::from_secs(1.0);
        let t2 = t.add_nanos(500_000_000);
        assert!((t2.as_secs_f64() - 1.5).abs() < 1e-9);
    }

    #[test]
    fn test_sim_time_saturating_sub() {
        let t = SimTime::from_secs(1.0);
        let t2 = t.saturating_sub_nanos(500_000_000);
        assert!((t2.as_secs_f64() - 0.5).abs() < 1e-9);

        // Saturating at zero
        let t3 = t.saturating_sub_nanos(2_000_000_000);
        assert_eq!(t3.as_nanos(), 0);
    }

    #[test]
    fn test_sim_time_default() {
        let t: SimTime = Default::default();
        assert_eq!(t.as_nanos(), 0);
    }

    #[test]
    fn test_sim_time_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(SimTime::from_secs(1.0));
        set.insert(SimTime::from_secs(2.0));
        set.insert(SimTime::from_secs(1.0)); // Duplicate
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_sim_time_clone() {
        let t1 = SimTime::from_secs(1.0);
        let t2 = t1;
        assert_eq!(t1, t2);
    }

    #[test]
    fn test_sim_time_sub_saturating() {
        let t1 = SimTime::from_secs(1.0);
        let t2 = SimTime::from_secs(2.0);
        // Sub uses saturating_sub
        let diff = t1 - t2;
        assert_eq!(diff.as_nanos(), 0);
    }

    #[test]
    fn test_sim_engine_new() {
        let config = SimConfig::builder().seed(42).build();
        let engine = SimEngine::new(config);
        assert!(engine.is_ok());
    }

    #[test]
    fn test_sim_engine_initial_time() {
        let config = SimConfig::builder().seed(42).build();
        let engine = SimEngine::new(config).unwrap();
        assert_eq!(engine.current_time(), SimTime::ZERO);
    }

    #[test]
    fn test_sim_engine_state() {
        let config = SimConfig::builder().seed(42).build();
        let engine = SimEngine::new(config).unwrap();
        let state = engine.state();
        assert_eq!(state.num_bodies(), 0);
    }

    #[test]
    fn test_sim_engine_state_mut() {
        let config = SimConfig::builder().seed(42).build();
        let mut engine = SimEngine::new(config).unwrap();
        let state = engine.state_mut();
        // Add a body to test mutability
        state.add_body(1.0, state::Vec3::zero(), state::Vec3::zero());
        assert_eq!(state.num_bodies(), 1);
    }

    #[test]
    fn test_sim_engine_rng() {
        let config = SimConfig::builder().seed(42).build();
        let engine = SimEngine::new(config).unwrap();
        let _rng = engine.rng();
    }

    #[test]
    fn test_sim_engine_rng_mut() {
        let config = SimConfig::builder().seed(42).build();
        let mut engine = SimEngine::new(config).unwrap();
        let rng = engine.rng_mut();
        let _ = rng.gen_f64();
    }

    #[test]
    fn test_sim_engine_step() {
        let config = SimConfig::builder().seed(42).build();
        let mut engine = SimEngine::new(config).unwrap();
        let result = engine.step();
        assert!(result.is_ok());
        assert!(engine.current_time() > SimTime::ZERO);
    }

    #[test]
    fn test_sim_engine_multiple_steps() {
        let config = SimConfig::builder().seed(42).build();
        let mut engine = SimEngine::new(config).unwrap();

        for _ in 0..10 {
            engine.step().unwrap();
        }

        assert!(engine.current_time() > SimTime::ZERO);
    }

    #[test]
    fn test_sim_engine_run_for() {
        let config = SimConfig::builder().seed(42).build();
        let mut engine = SimEngine::new(config).unwrap();

        let duration = SimTime::from_secs(0.1);
        let result = engine.run_for(duration);
        assert!(result.is_ok());
        assert!(engine.current_time() >= duration);
    }

    #[test]
    fn test_sim_engine_run_until() {
        let config = SimConfig::builder().seed(42).timestep(0.001).build();
        let mut engine = SimEngine::new(config).unwrap();

        // Add a body so we have something to check
        engine
            .state_mut()
            .add_body(1.0, state::Vec3::zero(), state::Vec3::zero());

        // run_until checks predicate based on state
        // Stop when bodies exist (immediate)
        let result = engine.run_until(|state| state.num_bodies() > 0);

        // This is a test that it runs without error
        assert!(result.is_ok());
    }

    #[test]
    fn test_sim_engine_run_until_immediate() {
        let config = SimConfig::builder().seed(42).build();
        let mut engine = SimEngine::new(config).unwrap();

        // Predicate immediately true
        let result = engine.run_until(|_state| true);
        assert!(result.is_ok());
        assert_eq!(engine.current_time(), SimTime::ZERO);
    }
}