1use crate::bounds::Bounds;
7use num_traits::Float;
8
9#[derive(Clone, Debug, PartialEq)]
11pub struct BoxGeometry {
12 pub dim: usize,
14 pub mean_width: f64,
16 pub aspect_ratio: f64,
18 pub widths: Vec<f64>,
20}
21
22pub fn box_geometry<T: Float>(bounds: &Bounds<T>) -> BoxGeometry {
24 let dim = bounds.dims;
25 if dim == 0 {
26 return BoxGeometry {
27 dim: 0,
28 mean_width: 1.0,
29 aspect_ratio: 1.0,
30 widths: vec![],
31 };
32 }
33 let mut widths = Vec::with_capacity(dim);
34 let mut min_w = f64::INFINITY;
35 let mut max_w = 0.0f64;
36 let mut sum = 0.0f64;
37 for j in 0..dim {
38 let lo = bounds.low[j].to_f64().unwrap_or(0.0);
39 let hi = bounds.high[j].to_f64().unwrap_or(1.0);
40 let mut w = hi - lo;
41 if !w.is_finite() || w <= 0.0 {
42 w = 1.0;
43 }
44 widths.push(w);
45 sum += w;
46 min_w = min_w.min(w);
47 max_w = max_w.max(w);
48 }
49 let aspect = if min_w > 0.0 && min_w.is_finite() {
50 (max_w / min_w).max(1.0)
51 } else {
52 1.0
53 };
54 BoxGeometry {
55 dim,
56 mean_width: sum / dim as f64,
57 aspect_ratio: aspect,
58 widths,
59 }
60}
61
62#[inline]
68pub fn compensated_delta(f_new: f64, f_cur: f64) -> f64 {
69 if !f_new.is_finite() || !f_cur.is_finite() {
70 return f_new - f_cur;
71 }
72 let a = f_new;
74 let b = -f_cur;
75 let s = a + b;
76 let bb = s - a;
77 let err = (a - (s - bb)) + (b - bb);
78 let out = s + err;
79 if out.is_finite() { out } else { f_new - f_cur }
80}
81
82#[inline]
86pub fn isotropic_proposal_scale(geom: &BoxGeometry, c: f64) -> f64 {
87 let d = geom.dim.max(1) as f64;
88 let c = if c.is_finite() && c > 0.0 { c } else { 0.25 };
89 (c * geom.mean_width / d.sqrt()).max(1e-12)
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95 use crate::bounds::Bounds;
96 use ndarray::{Array1, array};
97
98 #[test]
99 fn aspect_ratio_detects_elongation() {
100 let b = Bounds::new(array![0.0, 0.0], array![1.0, 100.0], 0.0);
101 let g = box_geometry(&b);
102 assert_eq!(g.dim, 2);
103 assert!((g.aspect_ratio - 100.0).abs() < 1e-12);
104 }
105
106 #[test]
107 fn compensated_delta_near_cancellation() {
108 let f_cur = 1.0 + 1e-12;
110 let f_new = 1.0 + 2e-12;
111 let d = compensated_delta(f_new, f_cur);
112 assert!(d.is_finite());
113 assert!(d > 0.0);
114 let naive = f_new - f_cur;
116 assert!((d - naive).abs() <= naive.abs().max(1e-18) * 1e-6 + 1e-18);
117 }
118
119 #[test]
120 fn isotropic_scale_shrinks_with_dim() {
121 let b2 = Bounds::new(array![0.0, 0.0], array![2.0, 2.0], 0.0);
122 let b8 = Bounds::new(Array1::from_elem(8, 0.0), Array1::from_elem(8, 2.0), 0.0);
123 let s2 = isotropic_proposal_scale(&box_geometry(&b2), 0.25);
124 let s8 = isotropic_proposal_scale(&box_geometry(&b8), 0.25);
125 assert!(s8 < s2);
126 }
127}