Skip to main content

qualia_core_db/specialized_libs/physics_simulation/
population.rs

1use super::*;
2
3impl PhysicsSimulationLibrary {
4    /// Biophysics — logistic population dynamics `dN/dt = r·N·(1 − N/K)`, integrated by
5    /// `integrate_dopri5`. Matches the analytic logistic curve
6    /// `N(t) = K / (1 + ((K−N₀)/N₀)·e^{−r·t})`.
7    pub fn run_logistic_growth(
8        &self,
9        n0: f64,
10        growth_rate: f64,
11        carrying_capacity: f64,
12        total_time: f64,
13        num_samples: usize,
14    ) -> Result<PopulationDynamicsResult, PhysicsError> {
15        if !(n0 >= 0.0 && carrying_capacity > 0.0 && total_time > 0.0) {
16            return Err(PhysicsError::InvalidConfiguration(
17                "require n0 >= 0, carrying_capacity > 0, total_time > 0".to_string(),
18            ));
19        }
20        let r = growth_rate;
21        let k = carrying_capacity;
22        let deriv = move |_t: f64, y: &[f64], dy: &mut [f64]| -> Result<(), OdeError> {
23            dy[0] = r * y[0] * (1.0 - y[0] / k);
24            Ok(())
25        };
26        let (_final, snapshots, accepted, rejected) =
27            self.integrate_ode_samples(vec![n0], total_time, num_samples, deriv)?;
28        let n_pts = snapshots.len();
29        let times: Vec<f64> = (0..n_pts)
30            .map(|kk| total_time * kk as f64 / (n_pts - 1).max(1) as f64)
31            .collect();
32        let population: Vec<f64> = snapshots.iter().map(|s| s[0]).collect();
33        Ok(PopulationDynamicsResult {
34            times,
35            population,
36            carrying_capacity: k,
37            growth_rate: r,
38            steps_accepted: accepted,
39            steps_rejected: rejected,
40        })
41    }
42}
43
44/// A 3D boid agent for avian flocking or fish schooling simulation (Tier-1 Zero-Heap).
45#[repr(C)]
46#[derive(Debug, Clone, Copy, PartialEq, bytemuck::Pod, bytemuck::Zeroable, Default)]
47pub struct BoidAgent {
48    pub position: [f32; 3],
49    pub velocity: [f32; 3],
50}
51
52/// Behavioral tuning parameters for flocking simulation.
53#[derive(Debug, Clone, Copy, PartialEq)]
54pub struct FlockingParameters {
55    pub separation_radius: f32,
56    pub neighbor_radius: f32,
57    pub separation_weight: f32,
58    pub alignment_weight: f32,
59    pub cohesion_weight: f32,
60    pub max_speed: f32,
61    pub min_speed: f32,
62}
63
64impl Default for FlockingParameters {
65    fn default() -> Self {
66        Self {
67            separation_radius: 1.5,
68            neighbor_radius: 6.0,
69            separation_weight: 1.5,
70            alignment_weight: 1.0,
71            cohesion_weight: 1.0,
72            max_speed: 12.0,
73            min_speed: 2.0,
74        }
75    }
76}
77
78/// Step flocking simulation for a slice of boids in-place (Tier-1 HotZeroHeap).
79/// Evaluates Separation, Alignment, and Cohesion forces in caller-owned slices.
80pub fn step_flocking_simulation(boids: &mut [BoidAgent], params: &FlockingParameters, dt: f32) {
81    let n = boids.len();
82    if n <= 1 || dt <= 0.0 {
83        return;
84    }
85
86    let sep_r2 = params.separation_radius * params.separation_radius;
87    let nbr_r2 = params.neighbor_radius * params.neighbor_radius;
88
89    // Use a fixed stack scratch for acceleration deltas if n <= 256
90    // Otherwise operate on chunks to preserve zero heap
91    for i in 0..n {
92        let pi = boids[i].position;
93        let vi = boids[i].velocity;
94
95        let mut sep = [0.0f32; 3];
96        let mut ali = [0.0f32; 3];
97        let mut coh_center = [0.0f32; 3];
98        let mut nbr_count = 0usize;
99
100        for j in 0..n {
101            if i == j {
102                continue;
103            }
104            let pj = boids[j].position;
105            let dx = pi[0] - pj[0];
106            let dy = pi[1] - pj[1];
107            let dz = pi[2] - pj[2];
108            let dist2 = dx * dx + dy * dy + dz * dz;
109
110            if dist2 < sep_r2 && dist2 > 1e-6 {
111                let dist = dist2.sqrt();
112                sep[0] += (dx / dist) / dist;
113                sep[1] += (dy / dist) / dist;
114                sep[2] += (dz / dist) / dist;
115            }
116
117            if dist2 < nbr_r2 {
118                ali[0] += boids[j].velocity[0];
119                ali[1] += boids[j].velocity[1];
120                ali[2] += boids[j].velocity[2];
121
122                coh_center[0] += pj[0];
123                coh_center[1] += pj[1];
124                coh_center[2] += pj[2];
125
126                nbr_count += 1;
127            }
128        }
129
130        let mut accel = [0.0f32; 3];
131        accel[0] += sep[0] * params.separation_weight;
132        accel[1] += sep[1] * params.separation_weight;
133        accel[2] += sep[2] * params.separation_weight;
134
135        if nbr_count > 0 {
136            let inv_n = 1.0 / nbr_count as f32;
137            let avg_v = [ali[0] * inv_n, ali[1] * inv_n, ali[2] * inv_n];
138            accel[0] += (avg_v[0] - vi[0]) * params.alignment_weight;
139            accel[1] += (avg_v[1] - vi[1]) * params.alignment_weight;
140            accel[2] += (avg_v[2] - vi[2]) * params.alignment_weight;
141
142            let center = [
143                coh_center[0] * inv_n,
144                coh_center[1] * inv_n,
145                coh_center[2] * inv_n,
146            ];
147            accel[0] += (center[0] - pi[0]) * params.cohesion_weight;
148            accel[1] += (center[1] - pi[1]) * params.cohesion_weight;
149            accel[2] += (center[2] - pi[2]) * params.cohesion_weight;
150        }
151
152        let mut new_v = [
153            vi[0] + accel[0] * dt,
154            vi[1] + accel[1] * dt,
155            vi[2] + accel[2] * dt,
156        ];
157
158        let speed = (new_v[0] * new_v[0] + new_v[1] * new_v[1] + new_v[2] * new_v[2]).sqrt();
159        if speed > params.max_speed && speed > 1e-5 {
160            let scale = params.max_speed / speed;
161            new_v[0] *= scale;
162            new_v[1] *= scale;
163            new_v[2] *= scale;
164        } else if speed < params.min_speed && speed > 1e-5 {
165            let scale = params.min_speed / speed;
166            new_v[0] *= scale;
167            new_v[1] *= scale;
168            new_v[2] *= scale;
169        }
170
171        boids[i].velocity = new_v;
172        boids[i].position[0] += new_v[0] * dt;
173        boids[i].position[1] += new_v[1] * dt;
174        boids[i].position[2] += new_v[2] * dt;
175    }
176}