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
18pub fn exclusive_probability_of(probability_a: f64, probability_b: f64) -> f64 {
21 probability_a + probability_b - 2.0 * probability_a * probability_b
22}
23
24pub fn union_probability_of(probability_a: f64, probability_b: f64) -> f64 {
31 probability_a + (1.0 - probability_a) * probability_b
32}
33
34#[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#[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
51pub 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 assert!(
87 crate::simulator::static_simulator::StaticSimulatorConfig::document()
88 .to_string()
89 .starts_with("<root> (Struct):")
90 );
91 }
92}