Skip to main content

somatize_study/
point.rs

1//! One configuration: what each knob was set to.
2//!
3//! It writes itself down — `batch=32,lr=0.001` — because that is a trial's
4//! **name**: what a record is filed under. Derived from the values in the
5//! space's order, so two machines that never spoke file it identically.
6
7use std::fmt;
8
9/// What one knob was set to.
10#[derive(Debug, Clone, PartialEq)]
11pub enum Setting {
12    /// A [`Real`](crate::Dimension::Real) dimension's value.
13    Real(f64),
14    /// An [`Int`](crate::Dimension::Int) dimension's value.
15    Int(i64),
16    /// Which of a [`Choice`](crate::Dimension::Choice)'s options.
17    Choice(String),
18}
19
20impl fmt::Display for Setting {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        match self {
23            Self::Real(value) => write!(f, "{value}"),
24            Self::Int(value) => write!(f, "{value}"),
25            Self::Choice(option) => f.write_str(option),
26        }
27    }
28}
29
30/// One point of the space: every knob, set.
31#[derive(Debug, Clone, PartialEq)]
32pub struct Point {
33    settings: Vec<(String, Setting)>,
34}
35
36impl Point {
37    /// A point from its settings, in the space's order.
38    pub fn of(settings: Vec<(String, Setting)>) -> Self {
39        Self { settings }
40    }
41
42    /// What that knob was set to, or `None` if this point does not have it.
43    pub fn get(&self, name: &str) -> Option<&Setting> {
44        self.settings
45            .iter()
46            .find(|(taken, _)| taken == name)
47            .map(|(_, setting)| setting)
48    }
49
50    /// Every knob, in the space's order.
51    pub fn settings(&self) -> &[(String, Setting)] {
52        &self.settings
53    }
54
55    /// How many knobs are set.
56    pub fn len(&self) -> usize {
57        self.settings.len()
58    }
59
60    /// Whether nothing is set.
61    pub fn is_empty(&self) -> bool {
62        self.settings.is_empty()
63    }
64}
65
66impl fmt::Display for Point {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        let said: Vec<String> = self
69            .settings
70            .iter()
71            .map(|(name, setting)| format!("{name}={setting}"))
72            .collect();
73        f.write_str(&said.join(","))
74    }
75}