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 (resolved_temp_c, resolved_pressure_hpa) = crate::atmosphere::resolve_station_conditions(
54        inputs.temperature,
55        inputs.pressure,
56        inputs.altitude,
57    );
58    let (air_density, speed_of_sound) = calculate_atmosphere(
59        inputs.altitude, // meters
60        Some(resolved_temp_c),
61        Some(resolved_pressure_hpa),
62        // BallisticInputs.humidity is a 0-1 fraction; calculate_atmosphere expects 0-100 percent
63        // (matching AtmosphericConditions.humidity). Passing the raw fraction under-applied
64        // humidity 100x. Centralized in humidity_percent() (MBA-722).
65        inputs.humidity_percent(),
66    );
67
68    // Create wind segments. WindSock expects (speed_kmh, angle_deg, until_distance_m);
69    // convert from the SI fields (m/s, radians) at this boundary.
70    let wind_segments = vec![(
71        inputs.wind_speed * 3.6,        // m/s -> km/h
72        inputs.wind_angle.to_degrees(), // radians -> degrees
73        target_distance_m * 2.0,        // wind extends beyond target
74    )];
75    let wind_sock = WindSock::new(wind_segments);
76
77    // Set up initial state
78    let muzzle_angle_rad = inputs.muzzle_angle;
79    // McCoy: X=downrange, Y=vertical, Z=lateral
80    let initial_velocity = Vector3::new(
81        muzzle_velocity_mps * muzzle_angle_rad.cos(),
82        muzzle_velocity_mps * muzzle_angle_rad.sin(),
83        0.0,
84    );
85
86    let initial_position = Vector3::new(0.0, inputs.sight_height, 0.0); // meters
87    let mut initial_state_array = [0.0; 6];
88    initial_state_array[0..3].copy_from_slice(&[
89        initial_position.x,
90        initial_position.y,
91        initial_position.z,
92    ]);
93    initial_state_array[3..6].copy_from_slice(&[
94        initial_velocity.x,
95        initial_velocity.y,
96        initial_velocity.z,
97    ]);
98
99    // Create integration params. fast_integrate's atmo_params is
100    // (base_alt_m, base_temp_c, base_press_hpa, base_ratio) — NOT
101    // (temp, pressure, density, sound). Packing it wrong scrambled the base
102    // density (~417 kg/m^3) and produced ~340x drag. base_ratio is the
103    // density relative to 1.225 (get_local_atmosphere returns base_ratio*1.225
104    // at the base altitude), so derive it from the computed air density.
105    let base_ratio = air_density / 1.225;
106    let params = FastIntegrationParams {
107        initial_state: initial_state_array,
108        t_span: (0.0, 30.0),
109        horiz: target_distance_m,
110        vert: 0.0, // Target at ground level
111        atmo_params: (
112            inputs.altitude,
113            resolved_temp_c,
114            resolved_pressure_hpa,
115            base_ratio,
116        ),
117    };
118
119    // Solve trajectory
120    let solution = fast_integrate(inputs, &wind_sock, params);
121
122    if solution.t.is_empty() {
123        return Err("Empty trajectory solution".to_string());
124    }
125
126    // Get final state
127    // FastSolution.y is Vec<Vec<f64>> where y[i] is the ith state variable across all time points
128    let final_idx = solution.t.len() - 1;
129
130    let final_downrange = solution.y[0][final_idx]; // McCoy: X=downrange
131
132    // Exclude runs that did not reach the target distance (a short/steep/subsonic shot, or any
133    // residual time-budget truncation) instead of silently reporting their too-short impact
134    // metrics at the target downrange, which would poison the mean / stddev / CEP aggregation.
135    if final_downrange < target_distance_m * 0.999 {
136        return Err("trajectory did not reach target distance".to_string());
137    }
138
139    let final_y = solution.y[1][final_idx]; // vertical
140    let final_lateral = solution.y[2][final_idx]; // McCoy: Z=lateral drift
141
142    let final_vx = solution.y[3][final_idx];
143    let final_vy = solution.y[4][final_idx];
144    let final_vz = solution.y[5][final_idx];
145
146    let final_speed = (final_vx * final_vx + final_vy * final_vy + final_vz * final_vz).sqrt();
147    let final_mach = final_speed / speed_of_sound;
148    let final_energy = 0.5 * mass_kg * final_speed * final_speed;
149
150    // Calculate line-of-sight drop
151    let sight_height_m = inputs.sight_height; // meters
152    let los_y = sight_height_m + (0.0 - sight_height_m) * (final_downrange / target_distance_m);
153    let drop = los_y - final_y;
154
155    // MBA-1134 (rank 6/10): the canonical empirical Litz spin drift is now applied INSIDE
156    // fast_integrate itself (post-process on the state lateral), so `final_lateral` already
157    // includes it — matching cli_api::apply_spin_drift and fast_integrate_with_segments. We
158    // therefore must NOT add it a second time here (doing so double-counted the drift, ~2x).
159    // We still recompute the Litz component with the SAME muzzle Sg for the reported
160    // `spin_drift` field (the old `// Approximation for now` had copied total lateral).
161    let spin_drift_m = if inputs.use_enhanced_spin_drift {
162        let sg = crate::spin_drift::effective_sg_from_inputs(
163            inputs,
164            resolved_temp_c,
165            resolved_pressure_hpa,
166        );
167        crate::spin_drift::litz_drift_meters(sg, solution.t[final_idx], inputs.is_twist_right)
168    } else {
169        0.0
170    };
171
172    Ok(TrajectoryOutput {
173        drop,
174        // final_lateral already carries the Litz spin drift (applied in fast_integrate).
175        wind_drift: final_lateral,
176        time: solution.t[final_idx],
177        velocity: final_speed,
178        energy: final_energy,
179        mach: final_mach,
180        spin_drift: spin_drift_m,
181        distance: final_downrange,
182    })
183}
184
185/// Calculate CEP (Circular Error Probable) from impact points
186///
187/// CEP is the radius of a circle centered at the mean point of impact,
188/// within which 50% of the shots fall. It's a standard measure of precision.
189pub fn calculate_cep(wind_drift_values: &[f64], drop_values: &[f64]) -> f64 {
190    if wind_drift_values.len() != drop_values.len() || wind_drift_values.is_empty() {
191        return 0.0;
192    }
193
194    // Calculate mean point of impact
195    let mean_x = wind_drift_values.iter().sum::<f64>() / wind_drift_values.len() as f64;
196    let mean_y = drop_values.iter().sum::<f64>() / drop_values.len() as f64;
197
198    // Calculate distance from each point to mean
199    let mut distances: Vec<f64> = wind_drift_values
200        .iter()
201        .zip(drop_values.iter())
202        .map(|(x, y)| {
203            let dx = x - mean_x;
204            let dy = y - mean_y;
205            (dx * dx + dy * dy).sqrt()
206        })
207        .collect();
208
209    // Sort distances to find median (50th percentile)
210    distances.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
211
212    // CEP is the median distance from center
213    percentile(&distances, 0.50)
214}
215
216/// Calculate 95% confidence ellipse parameters using covariance matrix
217///
218/// Returns (center_x, center_y, semi_major_axis, semi_minor_axis, rotation_degrees)
219pub fn calculate_confidence_ellipse(
220    wind_drift_values: &[f64],
221    drop_values: &[f64],
222) -> (f64, f64, f64, f64, f64) {
223    if wind_drift_values.len() != drop_values.len() || wind_drift_values.len() < 2 {
224        return (0.0, 0.0, 0.0, 0.0, 0.0);
225    }
226
227    let n = wind_drift_values.len() as f64;
228
229    // Calculate means
230    let mean_x = wind_drift_values.iter().sum::<f64>() / n;
231    let mean_y = drop_values.iter().sum::<f64>() / n;
232
233    // Calculate covariance matrix elements
234    let mut cov_xx = 0.0;
235    let mut cov_yy = 0.0;
236    let mut cov_xy = 0.0;
237
238    for (x, y) in wind_drift_values.iter().zip(drop_values.iter()) {
239        let dx = x - mean_x;
240        let dy = y - mean_y;
241        cov_xx += dx * dx;
242        cov_yy += dy * dy;
243        cov_xy += dx * dy;
244    }
245
246    cov_xx /= n - 1.0;
247    cov_yy /= n - 1.0;
248    cov_xy /= n - 1.0;
249
250    // Calculate eigenvalues of covariance matrix
251    // For 2x2 matrix: [[cov_xx, cov_xy], [cov_xy, cov_yy]]
252    let trace = cov_xx + cov_yy;
253    let det = cov_xx * cov_yy - cov_xy * cov_xy;
254    let discriminant = (trace * trace / 4.0 - det).max(0.0).sqrt();
255
256    let lambda1 = trace / 2.0 + discriminant; // Larger eigenvalue
257    let lambda2 = trace / 2.0 - discriminant; // Smaller eigenvalue
258
259    // 95% confidence interval chi-square value for 2 DOF is 5.991
260    let scale_factor = 5.991_f64.sqrt();
261    let semi_major = lambda1.max(0.0).sqrt() * scale_factor;
262    let semi_minor = lambda2.max(0.0).sqrt() * scale_factor;
263
264    // Calculate rotation angle (angle of major axis)
265    let rotation_rad = if cov_xy.abs() < 1e-10 {
266        if cov_xx >= cov_yy {
267            0.0
268        } else {
269            std::f64::consts::PI / 2.0
270        }
271    } else {
272        ((lambda1 - cov_xx) / cov_xy).atan()
273    };
274
275    let rotation_deg = rotation_rad.to_degrees();
276
277    (mean_x, mean_y, semi_major, semi_minor, rotation_deg)
278}
279
280/// Sample points for visualization (limit to avoid huge payloads)
281pub fn sample_points_for_visualization(
282    wind_drift_values: &[f64],
283    drop_values: &[f64],
284    max_points: usize,
285) -> Vec<(f64, f64)> {
286    let n = wind_drift_values.len();
287    if n == 0 {
288        return Vec::new();
289    }
290
291    if n <= max_points {
292        // Return all points
293        wind_drift_values
294            .iter()
295            .zip(drop_values.iter())
296            .map(|(x, y)| (*x, *y))
297            .collect()
298    } else {
299        // Sample evenly spaced points
300        let step = n as f64 / max_points as f64;
301        (0..max_points)
302            .map(|i| {
303                let idx = (i as f64 * step) as usize;
304                (wind_drift_values[idx], drop_values[idx])
305            })
306            .collect()
307    }
308}
309
310/// Calculate percentile from sorted values
311pub fn percentile(sorted_values: &[f64], p: f64) -> f64 {
312    if sorted_values.is_empty() {
313        return 0.0;
314    }
315
316    if sorted_values.len() == 1 {
317        return sorted_values[0];
318    }
319
320    // Clamp p to [0,1]: percentile is public (callable from ballistics_rust / FFI). p > 1 made
321    // upper_idx exceed the slice and panic; p < 0 silently returned a wrong value.
322    let p = p.clamp(0.0, 1.0);
323    let rank = p * (sorted_values.len() - 1) as f64;
324    let lower_idx = rank.floor() as usize;
325    let upper_idx = rank.ceil() as usize;
326    let fraction = rank - lower_idx as f64;
327
328    if lower_idx == upper_idx {
329        sorted_values[lower_idx]
330    } else {
331        sorted_values[lower_idx] * (1.0 - fraction) + sorted_values[upper_idx] * fraction
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338
339    #[test]
340    fn test_calculate_cep() {
341        let wind_drift = vec![0.0, 1.0, -1.0, 0.5, -0.5];
342        let drop = vec![0.0, 0.5, -0.5, 1.0, -1.0];
343
344        let cep = calculate_cep(&wind_drift, &drop);
345        assert!(cep > 0.0);
346        assert!(cep < 2.0); // Reasonable range
347    }
348
349    #[test]
350    fn test_calculate_confidence_ellipse() {
351        let wind_drift = vec![0.0, 1.0, -1.0, 0.5, -0.5];
352        let drop = vec![0.0, 0.5, -0.5, 1.0, -1.0];
353
354        let (cx, cy, major, minor, _rotation) = calculate_confidence_ellipse(&wind_drift, &drop);
355
356        // Center should be near origin
357        assert!(cx.abs() < 0.5);
358        assert!(cy.abs() < 0.5);
359
360        // Axes should be positive
361        assert!(major > 0.0);
362        assert!(minor > 0.0);
363        assert!(major >= minor); // Major axis should be >= minor axis
364    }
365
366    #[test]
367    fn test_sample_points() {
368        let wind_drift = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
369        let drop = vec![0.0, 0.1, 0.2, 0.3, 0.4, 0.5];
370
371        let sampled = sample_points_for_visualization(&wind_drift, &drop, 3);
372        assert_eq!(sampled.len(), 3);
373    }
374
375    #[test]
376    fn test_percentile() {
377        let values = vec![1.0, 2.0, 3.0, 4.0, 5.0];
378
379        assert_eq!(percentile(&values, 0.0), 1.0);
380        assert_eq!(percentile(&values, 0.5), 3.0);
381        assert_eq!(percentile(&values, 1.0), 5.0);
382    }
383}