Skip to main content

deq_runtime/misc/
util.rs

1#[cfg(feature = "cli")]
2use structdoc::StructDoc;
3
4#[cfg(feature = "cli")]
5const STRUCT_DOC_PREFIX: &str = "<root> (Struct)";
6
7#[cfg(feature = "cli")]
8pub fn help_message<T: StructDoc>(struct_name: &str) -> String {
9    let doc_string = T::document().to_string();
10    debug_assert!(
11        doc_string.starts_with(STRUCT_DOC_PREFIX),
12        "the help message is expected to start with `{}`",
13        STRUCT_DOC_PREFIX
14    );
15    doc_string.replacen(STRUCT_DOC_PREFIX, struct_name, 1)
16}
17
18/// Given the probabilities of two independent events A and B, returns the
19/// probability that A occurs or B occurs, but not both.
20pub fn exclusive_probability_of(probability_a: f64, probability_b: f64) -> f64 {
21    probability_a + probability_b - 2.0 * probability_a * probability_b
22}
23
24/// Given the probabilities of two independent events A and B, returns the
25/// probability that at least one of them occurs.
26///
27/// Use this, not [`exclusive_probability_of`], whenever the events describe one
28/// lifetime rather than two toggles: an atom already lost stays lost, so a
29/// later loss opportunity only matters when the earlier one did not fire.
30pub fn union_probability_of(probability_a: f64, probability_b: f64) -> f64 {
31    probability_a + (1.0 - probability_a) * probability_b
32}
33
34/// Return the log-likelihood weight `-ln(p / (1 - p))`.
35///
36/// The endpoint values follow the extended-real limits: probability `0` has
37/// weight `+inf`, and probability `1` has weight `-inf`.
38#[must_use]
39pub fn weight_of(probability: f64) -> f64 {
40    debug_assert!(probability.is_finite() && (0.0..=1.0).contains(&probability));
41    -(probability / (1.0 - probability)).ln()
42}
43
44/// Return the probability corresponding to an log-likelihood weight.
45#[must_use]
46pub fn probability_of_weight(weight: f64) -> f64 {
47    debug_assert!(!weight.is_nan());
48    1.0 / (1.0 + weight.exp())
49}
50
51/// Returns nanoseconds elapsed since the first call to this function in the
52/// current process, using a monotonic clock.
53///
54/// Trace consumers only ever use timestamps relatively (deltas between events
55/// on the same shot), so a process-local monotonic origin is sufficient and
56/// avoids the cross-core wall-clock skew that can make `SystemTime::now()`
57/// non-monotonic on some platforms (notably aarch64 / virtualised CI).
58pub fn timestamp_ns() -> u64 {
59    static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
60    let origin = ORIGIN.get_or_init(std::time::Instant::now);
61    origin.elapsed().as_nanos() as u64
62}
63
64#[cfg(test)]
65mod tests {
66    use super::{probability_of_weight, weight_of};
67
68    #[test]
69    fn probability_and_weight_round_trip() {
70        for probability in [1e-6, 1e-3, 0.01, 0.2] {
71            let weight = weight_of(probability);
72            assert!((probability_of_weight(weight) - probability).abs() < 1e-12);
73        }
74        assert_eq!(weight_of(0.0), f64::INFINITY);
75        assert_eq!(weight_of(1.0), f64::NEG_INFINITY);
76        assert_eq!(probability_of_weight(f64::INFINITY), 0.0);
77        assert_eq!(probability_of_weight(f64::NEG_INFINITY), 1.0);
78    }
79
80    #[test]
81    #[cfg(all(feature = "cli", feature = "simulator"))]
82    fn help_message() {
83        use structdoc::StructDoc;
84        // cargo test help_message -- --nocapture
85        // we assumed that the help message starts with a line of `<root> (Struct):`
86        assert!(
87            crate::simulator::static_simulator::StaticSimulatorConfig::document()
88                .to_string()
89                .starts_with("<root> (Struct):")
90        );
91    }
92}