Skip to main content

sim_components/
sensitivity.rs

1//! Global sensitivity of a cycle's results to the uncertain values of a config's `[bounds]`: which unknown parameters
2//! matter, with all of them moving at once (the one-at-a-time `analysis::sensitivity` and `verdict_bands` move one).
3//!
4//! Two methods on the unit cube, each parameter's range mapped to [0, 1]:
5//!
6//! - Morris' elementary effects (Morris 1991, with the mean of the absolute effects of Campolongo et al. 2007): a cheap
7//!   screening, `trajectories` (k + 1) runs. Per parameter μ* (how much it moves the result, over its whole range) and σ
8//!   (how much that depends on the others: interaction or a curve).
9//! - Sobol' indices (Saltelli 2002 sampling, Jansen 1999 estimators): first-order S_i (the share of the result's
10//!   variance the parameter explains alone) and total S_Ti (with all its interactions), `samples` (k + 2) runs, with
11//!   bootstrap 95 % confidence intervals.
12//!
13//! The results of a run are the verdicts' margins (`margin`: the room to the limit, in the check's unit) and per motor the peak and RMS torque and the winding's rise, and the tool's path error (peak and RMS) and its error in
14//! the dwells (settling). Each result is ranked on its own: the parameters at its top are the ones to measure first.
15
16use crate::analysis::{
17    AT_LEAST, CycleLoad, Verdict, analyse_cycle_with, followed, on_all_cores, set_bounded, verdicts,
18};
19use crate::sim::Sim;
20use sim_core::testkit::Noise;
21use sim_core::{Config, ConfigError, MachineEntry};
22
23/// The levels of Morris' grid: 0, 1/3, 2/3, 1 of each range; every step moves a parameter by `MORRIS_STEP`.
24pub const MORRIS_LEVELS: usize = 4;
25/// Morris' step, p / (2 (p - 1)) of the range: with it every level is visited equally often.
26pub const MORRIS_STEP: f64 = MORRIS_LEVELS as f64 / (2.0 * (MORRIS_LEVELS as f64 - 1.0));
27/// How many bootstrap resamples the Sobol' confidence intervals are taken from.
28pub const BOOTSTRAP: usize = 200;
29
30/// One parameter's elementary effects on one result, in the result's unit per the parameter's whole range.
31#[derive(Debug, Clone, PartialEq)]
32pub struct MorrisRow {
33    pub parameter: String,
34    /// Mean of the absolute effects: the ranking figure.
35    pub mu_star: f64,
36    /// Mean of the effects: near 0 with a large μ* where the sign changes over the range.
37    pub mu: f64,
38    /// Standard deviation of the effects: how much the effect depends on where the others are.
39    pub sigma: f64,
40}
41
42/// One parameter's Sobol' indices on one result, with their bootstrap 95 % intervals (low, high).
43#[derive(Debug, Clone, PartialEq)]
44pub struct SobolRow {
45    pub parameter: String,
46    pub first: f64,
47    pub first_ci: (f64, f64),
48    /// The ranking figure.
49    pub total: f64,
50    pub total_ci: (f64, f64),
51}
52
53/// The rows of one result, the parameter that matters most first.
54#[derive(Debug, Clone, PartialEq)]
55pub struct Ranking<T> {
56    pub result: String,
57    pub rows: Vec<T>,
58}
59
60/// The points of `trajectories` Morris trajectories in [0, 1]^k, k + 1 points each: a random start on the grid's lower
61/// half, then each parameter in a random order stepped once by `MORRIS_STEP`, up or down at random. Pseudo-random from
62/// `seed`.
63pub fn morris_points(k: usize, trajectories: usize, seed: u64) -> Vec<Vec<f64>> {
64    let mut random = Noise(seed);
65    let mut pick = |n: usize| ((random.uniform() * n as f64) as usize).min(n - 1);
66    let mut points = Vec::with_capacity(trajectories * (k + 1));
67    for _ in 0..trajectories {
68        // Each parameter's two ends: the lower one from the levels a step still fits above.
69        let (mut at, mut to) = (vec![0.0; k], vec![0.0; k]);
70        for i in 0..k {
71            let low = pick(MORRIS_LEVELS / 2) as f64 / (MORRIS_LEVELS - 1) as f64;
72            (at[i], to[i]) = if pick(2) == 0 { (low, low + MORRIS_STEP) } else { (low + MORRIS_STEP, low) };
73        }
74        let mut order: Vec<usize> = (0..k).collect();
75        for i in (1..k).rev() {
76            order.swap(i, pick(i + 1));
77        }
78        points.push(at.clone());
79        for i in order {
80            at[i] = to[i];
81            points.push(at.clone());
82        }
83    }
84    points
85}
86
87/// (μ*, μ, σ) per parameter of one result, from its values `y` at `morris_points(k, ..)`. The parameter a step moved is
88/// read from the points.
89pub fn morris_indices(k: usize, points: &[Vec<f64>], y: &[f64]) -> Vec<(f64, f64, f64)> {
90    let mut effects = vec![Vec::new(); k];
91    for (pair, out) in points.chunks(k + 1).zip(y.chunks(k + 1)) {
92        for s in 0..k {
93            let i = (0..k).find(|&i| pair[s + 1][i] != pair[s][i]).expect("a Morris step moves one parameter");
94            effects[i].push((out[s + 1] - out[s]) / (pair[s + 1][i] - pair[s][i]));
95        }
96    }
97    effects
98        .iter()
99        .map(|e| {
100            let r = e.len() as f64;
101            let mu = e.iter().sum::<f64>() / r;
102            let mu_star = e.iter().map(|d| d.abs()).sum::<f64>() / r;
103            let sigma =
104                if e.len() > 1 { (e.iter().map(|d| (d - mu).powi(2)).sum::<f64>() / (r - 1.0)).sqrt() } else { 0.0 };
105            (mu_star, mu, sigma)
106        })
107        .collect()
108}
109
110/// Saltelli's points in [0, 1]^k: n rows of A, n rows of B (both uniform at random from `seed`), then for each
111/// parameter i the n rows of A with column i taken from B. n (k + 2) points.
112pub fn saltelli_points(k: usize, n: usize, seed: u64) -> Vec<Vec<f64>> {
113    let mut random = Noise(seed);
114    let mut draw = || (0..n).map(|_| (0..k).map(|_| random.uniform()).collect::<Vec<f64>>()).collect::<Vec<_>>();
115    let (a, b) = (draw(), draw());
116    let mut points = [a.clone(), b.clone()].concat();
117    for i in 0..k {
118        points.extend(a.iter().zip(&b).map(|(a, b)| {
119            let mut ab = a.clone();
120            ab[i] = b[i];
121            ab
122        }));
123    }
124    points
125}
126
127/// Jansen's first-order and total index of each parameter, from the values at the rows `pick` of `saltelli_points`.
128fn jansen(k: usize, n: usize, y: &[f64], pick: &[usize]) -> Vec<(f64, f64)> {
129    let m = pick.len() as f64;
130    let (a, b) = (|j: usize| y[j], |j: usize| y[n + j]);
131    let mean = pick.iter().map(|&j| a(j) + b(j)).sum::<f64>() / (2.0 * m);
132    let variance = pick.iter().map(|&j| (a(j) - mean).powi(2) + (b(j) - mean).powi(2)).sum::<f64>() / (2.0 * m);
133    (0..k)
134        .map(|i| {
135            if variance <= 0.0 {
136                return (0.0, 0.0);
137            }
138            let ab = |j: usize| y[(2 + i) * n + j];
139            // Jansen 1999: V_Ti = E[(f(A) - f(AB_i))^2] / 2, V - V_i = E[(f(B) - f(AB_i))^2] / 2.
140            let total = pick.iter().map(|&j| (a(j) - ab(j)).powi(2)).sum::<f64>() / (2.0 * m);
141            let rest = pick.iter().map(|&j| (b(j) - ab(j)).powi(2)).sum::<f64>() / (2.0 * m);
142            ((variance - rest) / variance, total / variance)
143        })
144        .collect()
145}
146
147/// (S_i, its interval, S_Ti, its interval) per parameter of one result, from its values `y` at `saltelli_points(k, n,
148/// ..)`. The intervals are the 2.5 % and 97.5 % percentiles of `bootstrap` resamples of the n rows (with replacement,
149/// pseudo-random from `seed`). A result that does not vary has all indices 0.
150pub fn sobol_indices(k: usize, n: usize, y: &[f64], bootstrap: usize, seed: u64) -> Vec<SobolIndex> {
151    let all: Vec<usize> = (0..n).collect();
152    let point = jansen(k, n, y, &all);
153    let mut random = Noise(seed);
154    let resamples: Vec<Vec<(f64, f64)>> = (0..bootstrap)
155        .map(|_| {
156            let pick: Vec<usize> = (0..n).map(|_| ((random.uniform() * n as f64) as usize).min(n - 1)).collect();
157            jansen(k, n, y, &pick)
158        })
159        .collect();
160    let interval = |mut v: Vec<f64>| -> (f64, f64) {
161        if v.is_empty() {
162            return (f64::NAN, f64::NAN);
163        }
164        v.sort_by(f64::total_cmp);
165        let at = |q: f64| v[(q * (v.len() - 1) as f64).round() as usize];
166        (at(0.025), at(0.975))
167    };
168    (0..k)
169        .map(|i| SobolIndex {
170            first: point[i].0,
171            first_ci: interval(resamples.iter().map(|r| r[i].0).collect()),
172            total: point[i].1,
173            total_ci: interval(resamples.iter().map(|r| r[i].1).collect()),
174        })
175        .collect()
176}
177
178/// One parameter's Sobol' indices, without its name (`sobol_indices`).
179#[derive(Debug, Clone, Copy, PartialEq)]
180pub struct SobolIndex {
181    pub first: f64,
182    pub first_ci: (f64, f64),
183    pub total: f64,
184    pub total_ci: (f64, f64),
185}
186
187/// A verdict's margin: the room its value leaves to its limit, in the check's unit, negative where it fails. Not the
188/// utilisation (value over limit): "belt-least-tension" has the limit 0, where that is 0 whatever the tension. A bound on a rating
189/// moves the margin through the limit.
190pub fn margin(v: &Verdict) -> f64 {
191    if AT_LEAST.contains(&v.check) { v.value - v.limit } else { v.limit - v.value }
192}
193
194/// The results of one run, by name (see the module): verdicts as "check" or "check:motor", the figures as
195/// "peak-torque:motor", "rms-torque:motor", "winding-rise:motor", "path-error-peak", "path-error-rms", "dwell-error-peak".
196fn results(load: &CycleLoad, judged: &[Verdict], motors: &[String]) -> Vec<(String, f64)> {
197    let named = |what: &str, motor: Option<usize>| match motor {
198        Some(k) => format!("{what}:{}", motors[k]),
199        None => what.to_string(),
200    };
201    let mut out: Vec<(String, f64)> = judged.iter().map(|v| (named(v.check, v.motor), margin(v))).collect();
202    for (k, m) in load.motors.iter().enumerate() {
203        out.push((named("peak-torque", Some(k)), m.peak_torque));
204        out.push((named("rms-torque", Some(k)), m.rms_torque));
205        out.push((named("winding-rise", Some(k)), m.winding_rise));
206    }
207    out.push(("path-error-peak".into(), load.path_error_peak));
208    out.push(("path-error-rms".into(), load.path_error_rms));
209    out.push(("dwell-error-peak".into(), load.dwell_error_peak));
210    out
211}
212
213/// The cycle of `cfg` with the parameters of `bounds` at each point of the unit cube (0: low bound, 1: high), on all
214/// processors. Per result that came up in every run with a finite value its values, in the order of the points; a
215/// result missing from a run (a check only some values bring up) or not finite in one is left out.
216fn run_points(
217    entry: &MachineEntry,
218    cfg: &Config,
219    bounds: &[(String, f64, f64)],
220    points: &[Vec<f64>],
221) -> Result<Vec<(String, Vec<f64>)>, ConfigError> {
222    let resolved = &crate::catalog::resolve(entry, cfg)?;
223    let (bounds, cfg) = (&followed(cfg, resolved, bounds), resolved);
224    let motors: Vec<String> = (entry.build)(cfg)?.motors().iter().map(|m| m.id.to_string()).collect();
225    let runs = on_all_cores(points.len(), |r| -> Result<Vec<(String, f64)>, ConfigError> {
226        let mut changed = cfg.clone();
227        for ((path, low, high), u) in bounds.iter().zip(&points[r]) {
228            set_bounded(&mut changed, path, low + (high - low) * u)?;
229        }
230        let load = analyse_cycle_with(&mut Sim::new(entry, &changed)?, false)
231            .map_err(|e| ConfigError::Invalid(e.key.into()))?;
232        Ok(results(&load, &verdicts(&changed, &load)?, &motors))
233    });
234    let mut table: Vec<(String, Vec<f64>)> = Vec::new();
235    for (r, run) in runs.into_iter().enumerate() {
236        for (name, value) in run? {
237            match table.iter_mut().find(|(n, _)| *n == name) {
238                Some((_, values)) => values[r] = value,
239                None => {
240                    let mut values = vec![f64::NAN; points.len()];
241                    values[r] = value;
242                    table.push((name, values));
243                }
244            }
245        }
246    }
247    table.retain(|(_, values)| values.iter().all(|v| v.is_finite()));
248    Ok(table)
249}
250
251/// Morris screening of the cycle's results (see the module) over `bounds` (path, low, high; see `analysis::bounds`):
252/// `trajectories` (k + 1) runs on all processors. Per result the parameters by μ*, largest first. The same seed gives
253/// the same ranking.
254pub fn morris(
255    entry: &MachineEntry,
256    cfg: &Config,
257    bounds: &[(String, f64, f64)],
258    trajectories: usize,
259    seed: u64,
260) -> Result<Vec<Ranking<MorrisRow>>, ConfigError> {
261    if trajectories == 0 || bounds.is_empty() {
262        return Err(ConfigError::Invalid(if bounds.is_empty() { "bounds" } else { "samples" }.into()));
263    }
264    let k = bounds.len();
265    let points = morris_points(k, trajectories, seed);
266    Ok(run_points(entry, cfg, bounds, &points)?
267        .into_iter()
268        .map(|(result, y)| {
269            let mut rows: Vec<MorrisRow> = morris_indices(k, &points, &y)
270                .into_iter()
271                .zip(bounds)
272                .map(|((mu_star, mu, sigma), b)| MorrisRow { parameter: b.0.clone(), mu_star, mu, sigma })
273                .collect();
274            rows.sort_by(|a, b| b.mu_star.total_cmp(&a.mu_star));
275            Ranking { result, rows }
276        })
277        .collect())
278}
279
280/// Sobol' indices of the cycle's results (see the module) over `bounds`: `samples` (k + 2) runs on all processors, the
281/// intervals from `BOOTSTRAP` resamples. Per result the parameters by their total index, largest first. The same seed
282/// gives the same indices.
283pub fn sobol(
284    entry: &MachineEntry,
285    cfg: &Config,
286    bounds: &[(String, f64, f64)],
287    samples: usize,
288    seed: u64,
289) -> Result<Vec<Ranking<SobolRow>>, ConfigError> {
290    if samples < 2 || bounds.is_empty() {
291        return Err(ConfigError::Invalid(if bounds.is_empty() { "bounds" } else { "samples" }.into()));
292    }
293    let k = bounds.len();
294    let points = saltelli_points(k, samples, seed);
295    Ok(run_points(entry, cfg, bounds, &points)?
296        .into_iter()
297        .map(|(result, y)| {
298            let mut rows: Vec<SobolRow> = sobol_indices(k, samples, &y, BOOTSTRAP, seed)
299                .into_iter()
300                .zip(bounds)
301                .map(|(s, b)| SobolRow {
302                    parameter: b.0.clone(),
303                    first: s.first,
304                    first_ci: s.first_ci,
305                    total: s.total,
306                    total_ci: s.total_ci,
307                })
308                .collect();
309            rows.sort_by(|a, b| b.total.total_cmp(&a.total));
310            Ranking { result, rows }
311        })
312        .collect())
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use std::f64::consts::PI;
319
320    /// Ishigami & Homma 1990 on [-pi, pi]^3 with a = 7, b = 0.1, the unit cube mapped onto it.
321    fn ishigami(u: &[f64]) -> f64 {
322        let x: Vec<f64> = u.iter().map(|u| -PI + 2.0 * PI * u).collect();
323        x[0].sin() + 7.0 * x[1].sin().powi(2) + 0.1 * x[2].powi(4) * x[0].sin()
324    }
325
326    /// Its indices by hand (Sobol' & Levitan 1999; Saltelli et al. 2008, p. 179):
327    /// V1 = 1/2 (1 + b pi^4 / 5)^2 = 1/2 (1 + 9.7409 / 5)^2 = 4.3459; V2 = a^2 / 8 = 6.125;
328    /// V13 = b^2 pi^8 (1/18 - 1/50) = 0.01 * 9488.53 * 0.035556 = 3.3737; V = V1 + V2 + V13 = 13.8446 (V3 = 0).
329    /// S1 = 0.3139, S2 = 0.4424, S3 = 0; ST1 = (V1 + V13) / V = 0.5576, ST2 = 0.4424, ST3 = V13 / V = 0.2437.
330    const ISHIGAMI_FIRST: [f64; 3] = [0.3139, 0.4424, 0.0];
331    const ISHIGAMI_TOTAL: [f64; 3] = [0.5576, 0.4424, 0.2437];
332
333    #[test]
334    fn sobol_finds_the_ishigami_indices() {
335        let (k, n) = (3, 1 << 14);
336        let y: Vec<f64> = saltelli_points(k, n, 7).iter().map(|u| ishigami(u)).collect();
337        let s = sobol_indices(k, n, &y, 100, 7);
338        for i in 0..k {
339            assert!((s[i].first - ISHIGAMI_FIRST[i]).abs() < 0.03, "S{} = {}", i + 1, s[i].first);
340            assert!((s[i].total - ISHIGAMI_TOTAL[i]).abs() < 0.03, "ST{} = {}", i + 1, s[i].total);
341            assert!(s[i].first_ci.0 <= s[i].first_ci.1 && s[i].total_ci.0 <= s[i].total_ci.1);
342            // Intervals of a few hundredths at 16384 rows, and around the estimate.
343            assert!(s[i].total_ci.1 - s[i].total_ci.0 < 0.06, "{:?}", s[i].total_ci);
344            assert!(s[i].total_ci.0 <= s[i].total + 0.01 && s[i].total - 0.01 <= s[i].total_ci.1);
345        }
346    }
347
348    /// Y = sum a_i X_i with X_i uniform on [lo_i, hi_i]: Var(X_i) = (hi_i - lo_i)^2 / 12 and
349    /// S_i = S_Ti = a_i^2 Var_i / sum_j a_j^2 Var_j. With a = (1, -2, 0.5, 0), ranges 1, 1, 4, 3:
350    /// a_i^2 Var_i * 12 = 1, 4, 4, 0, sum 9, so S = (1/9, 4/9, 4/9, 0) = (0.1111, 0.4444, 0.4444, 0).
351    const A: [f64; 4] = [1.0, -2.0, 0.5, 0.0];
352    const RANGE: [(f64, f64); 4] = [(0.0, 1.0), (2.0, 3.0), (-2.0, 2.0), (5.0, 8.0)];
353    fn linear(u: &[f64]) -> f64 {
354        u.iter().zip(A).zip(RANGE).map(|((u, a), (lo, hi))| a * (lo + (hi - lo) * u)).sum()
355    }
356
357    #[test]
358    fn sobol_finds_the_shares_of_a_linear_model() {
359        let (k, n) = (4, 1 << 13);
360        let y: Vec<f64> = saltelli_points(k, n, 3).iter().map(|u| linear(u)).collect();
361        let s = sobol_indices(k, n, &y, 50, 3);
362        for (i, want) in [1.0 / 9.0, 4.0 / 9.0, 4.0 / 9.0, 0.0].into_iter().enumerate() {
363            assert!((s[i].first - want).abs() < 0.03, "S{} = {} against {want}", i + 1, s[i].first);
364            // A model without interactions: the total index is the first-order one.
365            assert!((s[i].total - want).abs() < 0.02, "ST{} = {} against {want}", i + 1, s[i].total);
366        }
367        // X4 does nothing: its total index is exactly 0 (f(A) = f(AB_4) row by row).
368        assert_eq!(s[3].total, 0.0);
369    }
370
371    #[test]
372    fn morris_on_a_linear_model_gives_the_slope_times_the_range_with_no_spread() {
373        // Each effect is exact: a_i (hi_i - lo_i) per whole range, so mu* = |a_i| (hi_i - lo_i) = 1, 2, 2, 0, sigma = 0.
374        let k = 4;
375        let points = morris_points(k, 10, 11);
376        assert_eq!(points.len(), 10 * (k + 1));
377        let y: Vec<f64> = points.iter().map(|u| linear(u)).collect();
378        for ((mu_star, mu, sigma), want) in morris_indices(k, &points, &y).into_iter().zip([1.0f64, -2.0, 2.0, 0.0]) {
379            assert!((mu_star - want.abs()).abs() < 1e-9 && (mu - want).abs() < 1e-9 && sigma < 1e-9);
380        }
381    }
382
383    #[test]
384    fn morris_sees_the_interaction_of_the_ishigami_function() {
385        // x3 explains nothing alone (S3 = 0) but acts through x1 (ST3 = 0.24): Morris gives it a mu* well above 0 and a
386        // sigma as large, and x2 (no interaction, but a curve: sin^2) a mu* well above it.
387        let k = 3;
388        let points = morris_points(k, 200, 5);
389        let y: Vec<f64> = points.iter().map(|u| ishigami(u)).collect();
390        let m = morris_indices(k, &points, &y);
391        assert!(m[2].0 > 1.0 && m[2].2 > 1.0, "x3: {:?}", m[2]);
392        assert!(m[1].0 > m[2].0, "{m:?}");
393    }
394
395    #[test]
396    fn the_same_seed_gives_the_same_points_and_another_seed_others() {
397        assert_eq!(morris_points(5, 4, 1), morris_points(5, 4, 1));
398        assert_ne!(morris_points(5, 4, 1), morris_points(5, 4, 2));
399        assert_eq!(saltelli_points(3, 8, 1), saltelli_points(3, 8, 1));
400        let y: Vec<f64> = saltelli_points(3, 256, 1).iter().map(|u| ishigami(u)).collect();
401        assert_eq!(sobol_indices(3, 256, &y, 50, 1), sobol_indices(3, 256, &y, 50, 1));
402    }
403
404    #[test]
405    fn every_morris_point_lies_on_the_grid_and_every_step_moves_one_parameter_by_the_step() {
406        let k = 6;
407        for t in morris_points(k, 20, 9).chunks(k + 1) {
408            for p in t.iter().flatten() {
409                assert!((p * 3.0 - (p * 3.0).round()).abs() < 1e-12 && (0.0..=1.0).contains(p));
410            }
411            let mut moved = vec![false; k];
412            for s in 0..k {
413                let changed: Vec<usize> = (0..k).filter(|&i| t[s + 1][i] != t[s][i]).collect();
414                assert_eq!(changed.len(), 1);
415                assert!(((t[s + 1][changed[0]] - t[s][changed[0]]).abs() - MORRIS_STEP).abs() < 1e-12);
416                moved[changed[0]] = true;
417            }
418            assert!(moved.iter().all(|m| *m));
419        }
420    }
421}