Skip to main content

ballistics_engine/
monte_carlo.rs

1//! Monte Carlo simulation support with statistical analysis
2//!
3//! This module provides core statistical functions for Monte Carlo trajectory analysis,
4//! including CEP (Circular Error Probable), confidence ellipses, and trajectory evaluation.
5//!
6//! MBA-157: Upstreamed from ballistics_rust for shared use across the ecosystem
7
8use crate::atmosphere::calculate_atmosphere;
9use crate::fast_trajectory::{fast_integrate, FastIntegrationParams};
10use crate::wind::WindSock;
11use crate::BallisticInputs;
12use nalgebra::Vector3;
13
14/// Simple trajectory output for Monte Carlo analysis
15#[derive(Debug, Clone)]
16pub struct TrajectoryOutput {
17    pub drop: f64,       // meters
18    pub wind_drift: f64, // meters
19    pub time: f64,       // seconds
20    pub velocity: f64,   // m/s
21    pub energy: f64,     // joules
22    pub mach: f64,       // mach number
23    pub spin_drift: f64, // meters
24    pub distance: f64,   // meters
25}
26
27/// Solve trajectory for Monte Carlo run
28///
29/// This function evaluates a single trajectory with the given inputs and returns
30/// simplified output suitable for statistical analysis.
31pub fn solve_trajectory_for_monte_carlo(
32    inputs: &BallisticInputs,
33) -> Result<TrajectoryOutput, String> {
34    // BallisticInputs is SI-canonical (meters, m/s, kg, radians).
35    let target_distance_m = inputs.target_distance; // meters
36    let muzzle_velocity_mps = inputs.muzzle_velocity; // m/s
37    let mass_kg = inputs.bullet_mass; // kg
38
39    // Guard a non-finite or non-positive target distance: los_y (and the wind segment /
40    // params.horiz) divide by or scale with target_distance_m, so 0/NaN/negative/+inf would
41    // yield a silently-NaN-or-inf result that poisons mean/stddev/CEP aggregation. The
42    // is_finite() check also rejects +inf, which `> 0.0` alone lets through. Engine default
43    // is 100 m.
44    if !(target_distance_m.is_finite() && target_distance_m > 0.0) {
45        return Err("target_distance must be a positive, finite distance".to_string());
46    }
47
48    // Calculate atmosphere at altitude. resolve_station_pressure / _temperature keep explicit
49    // values authoritative (no altitude double-count) but return None when left at the sea-level
50    // default, so altitude drives BOTH the base station pressure AND the lapse-rate temperature
51    // via the ICAO standard (this base_ratio feeds the fast/Monte-Carlo kernel's base_density).
52    // Matches calculate_air_density.
53    let (air_density, speed_of_sound) = calculate_atmosphere(
54        inputs.altitude, // meters
55        crate::atmosphere::resolve_station_temperature(inputs.temperature, inputs.altitude),
56        crate::atmosphere::resolve_station_pressure(inputs.pressure, inputs.altitude),
57        // BallisticInputs.humidity is a 0-1 fraction; calculate_atmosphere expects 0-100 percent
58        // (matching AtmosphericConditions.humidity). Passing the raw fraction under-applied
59        // humidity 100x.
60        (inputs.humidity * 100.0).clamp(0.0, 100.0),
61    );
62
63    // Create wind segments. WindSock expects (speed_kmh, angle_deg, until_distance_m);
64    // convert from the SI fields (m/s, radians) at this boundary.
65    let wind_segments = vec![(
66        inputs.wind_speed * 3.6,          // m/s -> km/h
67        inputs.wind_angle.to_degrees(),   // radians -> degrees
68        target_distance_m * 2.0,          // wind extends beyond target
69    )];
70    let wind_sock = WindSock::new(wind_segments);
71
72    // Set up initial state
73    let muzzle_angle_rad = inputs.muzzle_angle;
74    // McCoy: X=downrange, Y=vertical, Z=lateral
75    let initial_velocity = Vector3::new(
76        muzzle_velocity_mps * muzzle_angle_rad.cos(),
77        muzzle_velocity_mps * muzzle_angle_rad.sin(),
78        0.0,
79    );
80
81    let initial_position = Vector3::new(0.0, inputs.sight_height, 0.0); // meters
82    let mut initial_state_array = [0.0; 6];
83    initial_state_array[0..3].copy_from_slice(&[
84        initial_position.x,
85        initial_position.y,
86        initial_position.z,
87    ]);
88    initial_state_array[3..6].copy_from_slice(&[
89        initial_velocity.x,
90        initial_velocity.y,
91        initial_velocity.z,
92    ]);
93
94    // Create integration params. fast_integrate's atmo_params is
95    // (base_alt_m, base_temp_c, base_press_hpa, base_ratio) — NOT
96    // (temp, pressure, density, sound). Packing it wrong scrambled the base
97    // density (~417 kg/m^3) and produced ~340x drag. base_ratio is the
98    // density relative to 1.225 (get_local_atmosphere returns base_ratio*1.225
99    // at the base altitude), so derive it from the computed air density.
100    let base_ratio = air_density / 1.225;
101    let params = FastIntegrationParams {
102        initial_state: initial_state_array,
103        t_span: (0.0, 30.0),
104        horiz: target_distance_m,
105        vert: 0.0, // Target at ground level
106        atmo_params: (inputs.altitude, inputs.temperature, inputs.pressure, base_ratio),
107    };
108
109    // Solve trajectory
110    let solution = fast_integrate(inputs, &wind_sock, params);
111
112    if solution.t.is_empty() {
113        return Err("Empty trajectory solution".to_string());
114    }
115
116    // Get final state
117    // FastSolution.y is Vec<Vec<f64>> where y[i] is the ith state variable across all time points
118    let final_idx = solution.t.len() - 1;
119
120    let final_downrange = solution.y[0][final_idx]; // McCoy: X=downrange
121
122    // Exclude runs that did not reach the target distance (a short/steep/subsonic shot, or any
123    // residual time-budget truncation) instead of silently reporting their too-short impact
124    // metrics at the target downrange, which would poison the mean / stddev / CEP aggregation.
125    if final_downrange < target_distance_m * 0.999 {
126        return Err("trajectory did not reach target distance".to_string());
127    }
128
129    let final_y = solution.y[1][final_idx]; // vertical
130    let final_lateral = solution.y[2][final_idx]; // McCoy: Z=lateral drift
131
132    let final_vx = solution.y[3][final_idx];
133    let final_vy = solution.y[4][final_idx];
134    let final_vz = solution.y[5][final_idx];
135
136    let final_speed = (final_vx * final_vx + final_vy * final_vy + final_vz * final_vz).sqrt();
137    let final_mach = final_speed / speed_of_sound;
138    let final_energy = 0.5 * mass_kg * final_speed * final_speed;
139
140    // Calculate line-of-sight drop
141    let sight_height_m = inputs.sight_height; // meters
142    let los_y = sight_height_m + (0.0 - sight_height_m) * (final_downrange / target_distance_m);
143    let drop = los_y - final_y;
144
145    Ok(TrajectoryOutput {
146        drop,
147        wind_drift: final_lateral,
148        time: solution.t[final_idx],
149        velocity: final_speed,
150        energy: final_energy,
151        mach: final_mach,
152        spin_drift: final_lateral, // Approximation for now
153        distance: final_downrange,
154    })
155}
156
157/// Calculate CEP (Circular Error Probable) from impact points
158///
159/// CEP is the radius of a circle centered at the mean point of impact,
160/// within which 50% of the shots fall. It's a standard measure of precision.
161pub fn calculate_cep(wind_drift_values: &[f64], drop_values: &[f64]) -> f64 {
162    if wind_drift_values.len() != drop_values.len() || wind_drift_values.is_empty() {
163        return 0.0;
164    }
165
166    // Calculate mean point of impact
167    let mean_x = wind_drift_values.iter().sum::<f64>() / wind_drift_values.len() as f64;
168    let mean_y = drop_values.iter().sum::<f64>() / drop_values.len() as f64;
169
170    // Calculate distance from each point to mean
171    let mut distances: Vec<f64> = wind_drift_values
172        .iter()
173        .zip(drop_values.iter())
174        .map(|(x, y)| {
175            let dx = x - mean_x;
176            let dy = y - mean_y;
177            (dx * dx + dy * dy).sqrt()
178        })
179        .collect();
180
181    // Sort distances to find median (50th percentile)
182    distances.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
183
184    // CEP is the median distance from center
185    percentile(&distances, 0.50)
186}
187
188/// Calculate 95% confidence ellipse parameters using covariance matrix
189///
190/// Returns (center_x, center_y, semi_major_axis, semi_minor_axis, rotation_degrees)
191pub fn calculate_confidence_ellipse(
192    wind_drift_values: &[f64],
193    drop_values: &[f64],
194) -> (f64, f64, f64, f64, f64) {
195    if wind_drift_values.len() != drop_values.len() || wind_drift_values.len() < 2 {
196        return (0.0, 0.0, 0.0, 0.0, 0.0);
197    }
198
199    let n = wind_drift_values.len() as f64;
200
201    // Calculate means
202    let mean_x = wind_drift_values.iter().sum::<f64>() / n;
203    let mean_y = drop_values.iter().sum::<f64>() / n;
204
205    // Calculate covariance matrix elements
206    let mut cov_xx = 0.0;
207    let mut cov_yy = 0.0;
208    let mut cov_xy = 0.0;
209
210    for (x, y) in wind_drift_values.iter().zip(drop_values.iter()) {
211        let dx = x - mean_x;
212        let dy = y - mean_y;
213        cov_xx += dx * dx;
214        cov_yy += dy * dy;
215        cov_xy += dx * dy;
216    }
217
218    cov_xx /= n - 1.0;
219    cov_yy /= n - 1.0;
220    cov_xy /= n - 1.0;
221
222    // Calculate eigenvalues of covariance matrix
223    // For 2x2 matrix: [[cov_xx, cov_xy], [cov_xy, cov_yy]]
224    let trace = cov_xx + cov_yy;
225    let det = cov_xx * cov_yy - cov_xy * cov_xy;
226    let discriminant = (trace * trace / 4.0 - det).max(0.0).sqrt();
227
228    let lambda1 = trace / 2.0 + discriminant; // Larger eigenvalue
229    let lambda2 = trace / 2.0 - discriminant; // Smaller eigenvalue
230
231    // 95% confidence interval chi-square value for 2 DOF is 5.991
232    let scale_factor = 5.991_f64.sqrt();
233    let semi_major = lambda1.max(0.0).sqrt() * scale_factor;
234    let semi_minor = lambda2.max(0.0).sqrt() * scale_factor;
235
236    // Calculate rotation angle (angle of major axis)
237    let rotation_rad = if cov_xy.abs() < 1e-10 {
238        if cov_xx >= cov_yy {
239            0.0
240        } else {
241            std::f64::consts::PI / 2.0
242        }
243    } else {
244        ((lambda1 - cov_xx) / cov_xy).atan()
245    };
246
247    let rotation_deg = rotation_rad.to_degrees();
248
249    (mean_x, mean_y, semi_major, semi_minor, rotation_deg)
250}
251
252/// Sample points for visualization (limit to avoid huge payloads)
253pub fn sample_points_for_visualization(
254    wind_drift_values: &[f64],
255    drop_values: &[f64],
256    max_points: usize,
257) -> Vec<(f64, f64)> {
258    let n = wind_drift_values.len();
259    if n == 0 {
260        return Vec::new();
261    }
262
263    if n <= max_points {
264        // Return all points
265        wind_drift_values
266            .iter()
267            .zip(drop_values.iter())
268            .map(|(x, y)| (*x, *y))
269            .collect()
270    } else {
271        // Sample evenly spaced points
272        let step = n as f64 / max_points as f64;
273        (0..max_points)
274            .map(|i| {
275                let idx = (i as f64 * step) as usize;
276                (wind_drift_values[idx], drop_values[idx])
277            })
278            .collect()
279    }
280}
281
282/// Calculate percentile from sorted values
283pub fn percentile(sorted_values: &[f64], p: f64) -> f64 {
284    if sorted_values.is_empty() {
285        return 0.0;
286    }
287
288    if sorted_values.len() == 1 {
289        return sorted_values[0];
290    }
291
292    // Clamp p to [0,1]: percentile is public (callable from ballistics_rust / FFI). p > 1 made
293    // upper_idx exceed the slice and panic; p < 0 silently returned a wrong value.
294    let p = p.clamp(0.0, 1.0);
295    let rank = p * (sorted_values.len() - 1) as f64;
296    let lower_idx = rank.floor() as usize;
297    let upper_idx = rank.ceil() as usize;
298    let fraction = rank - lower_idx as f64;
299
300    if lower_idx == upper_idx {
301        sorted_values[lower_idx]
302    } else {
303        sorted_values[lower_idx] * (1.0 - fraction) + sorted_values[upper_idx] * fraction
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    #[test]
312    fn test_calculate_cep() {
313        let wind_drift = vec![0.0, 1.0, -1.0, 0.5, -0.5];
314        let drop = vec![0.0, 0.5, -0.5, 1.0, -1.0];
315
316        let cep = calculate_cep(&wind_drift, &drop);
317        assert!(cep > 0.0);
318        assert!(cep < 2.0); // Reasonable range
319    }
320
321    #[test]
322    fn test_calculate_confidence_ellipse() {
323        let wind_drift = vec![0.0, 1.0, -1.0, 0.5, -0.5];
324        let drop = vec![0.0, 0.5, -0.5, 1.0, -1.0];
325
326        let (cx, cy, major, minor, _rotation) = calculate_confidence_ellipse(&wind_drift, &drop);
327
328        // Center should be near origin
329        assert!(cx.abs() < 0.5);
330        assert!(cy.abs() < 0.5);
331
332        // Axes should be positive
333        assert!(major > 0.0);
334        assert!(minor > 0.0);
335        assert!(major >= minor); // Major axis should be >= minor axis
336    }
337
338    #[test]
339    fn test_sample_points() {
340        let wind_drift = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
341        let drop = vec![0.0, 0.1, 0.2, 0.3, 0.4, 0.5];
342
343        let sampled = sample_points_for_visualization(&wind_drift, &drop, 3);
344        assert_eq!(sampled.len(), 3);
345    }
346
347    #[test]
348    fn test_percentile() {
349        let values = vec![1.0, 2.0, 3.0, 4.0, 5.0];
350
351        assert_eq!(percentile(&values, 0.0), 1.0);
352        assert_eq!(percentile(&values, 0.5), 3.0);
353        assert_eq!(percentile(&values, 1.0), 5.0);
354    }
355}