Skip to main content

kitchen_contract/
params.rs

1//! What an op is tuned with ([standard ยง2.1](../../../standard/spec/02-ops.md), `params`).
2//!
3//! Parameters are numbers, whole numbers, switches, text or one of a list, with a default and, for
4//! numbers, a range and a unit. The same description draws the Inspector's controls, checks a
5//! pipeline's values and fills in what a pipeline leaves out.
6
7use std::collections::BTreeMap;
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13/// What kind of value a parameter takes.
14#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
15#[serde(tag = "kind", rename_all = "snake_case")]
16pub enum ParamKind {
17    /// A number, within `min`..=`max` when given, in `unit` (`px`, `Hz`, `ms`).
18    Number {
19        #[serde(default, skip_serializing_if = "Option::is_none")]
20        min: Option<f64>,
21        #[serde(default, skip_serializing_if = "Option::is_none")]
22        max: Option<f64>,
23        #[serde(default, skip_serializing_if = "Option::is_none")]
24        unit: Option<String>,
25    },
26    /// A whole number, within `min`..=`max` when given.
27    Integer {
28        #[serde(default, skip_serializing_if = "Option::is_none")]
29        min: Option<i64>,
30        #[serde(default, skip_serializing_if = "Option::is_none")]
31        max: Option<i64>,
32    },
33    /// On or off.
34    Switch,
35    /// Free text (a model's name, a column).
36    Text,
37    /// One of these.
38    Choice {
39        /// The choices.
40        options: Vec<String>,
41    },
42}
43
44/// A parameter's value.
45#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
46#[serde(untagged)]
47pub enum ParamValue {
48    /// On or off.
49    Switch(bool),
50    /// A whole number.
51    Integer(i64),
52    /// A number.
53    Number(f64),
54    /// Text, or a choice.
55    Text(String),
56}
57
58impl ParamValue {
59    /// As a number (whole numbers too).
60    pub fn as_f64(&self) -> Option<f64> {
61        match self {
62            ParamValue::Number(v) => Some(*v),
63            ParamValue::Integer(v) => Some(*v as f64),
64            _ => None,
65        }
66    }
67
68    /// As JSON, for a script.
69    pub fn to_json(&self) -> Value {
70        serde_json::to_value(self).unwrap_or(Value::Null)
71    }
72
73    /// From JSON, if it is a value a parameter takes.
74    pub fn from_json(v: &Value) -> Option<ParamValue> {
75        serde_json::from_value(v.clone()).ok()
76    }
77}
78
79/// A parameter of an op: the Inspector draws a control for it.
80#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
81pub struct ParamSpec {
82    /// Its name, as the function takes it (`sigma`).
83    pub name: String,
84    /// What it takes.
85    #[serde(flatten)]
86    pub kind: ParamKind,
87    /// Its value when a pipeline gives none.
88    pub default: ParamValue,
89    /// One line for people (the Inspector's tooltip).
90    #[serde(default, skip_serializing_if = "String::is_empty")]
91    pub hint: String,
92}
93
94impl ParamSpec {
95    /// A number `name`, `default` when not given.
96    pub fn number(name: impl Into<String>, default: f64) -> Self {
97        Self {
98            name: name.into(),
99            kind: ParamKind::Number { min: None, max: None, unit: None },
100            default: ParamValue::Number(default),
101            hint: String::new(),
102        }
103    }
104
105    /// A whole number `name`.
106    pub fn integer(name: impl Into<String>, default: i64) -> Self {
107        Self {
108            name: name.into(),
109            kind: ParamKind::Integer { min: None, max: None },
110            default: ParamValue::Integer(default),
111            hint: String::new(),
112        }
113    }
114
115    /// A switch `name`.
116    pub fn switch(name: impl Into<String>, default: bool) -> Self {
117        Self { name: name.into(), kind: ParamKind::Switch, default: ParamValue::Switch(default), hint: String::new() }
118    }
119
120    /// Text `name`.
121    pub fn text(name: impl Into<String>, default: impl Into<String>) -> Self {
122        Self {
123            name: name.into(),
124            kind: ParamKind::Text,
125            default: ParamValue::Text(default.into()),
126            hint: String::new(),
127        }
128    }
129
130    /// One of `options`, the first by default.
131    pub fn choice(name: impl Into<String>, options: &[&str]) -> Self {
132        let options: Vec<String> = options.iter().map(|s| s.to_string()).collect();
133        let default = ParamValue::Text(options.first().cloned().unwrap_or_default());
134        Self { name: name.into(), kind: ParamKind::Choice { options }, default, hint: String::new() }
135    }
136
137    /// The same parameter with a range (numbers and whole numbers).
138    pub fn range(mut self, lo: f64, hi: f64) -> Self {
139        match &mut self.kind {
140            ParamKind::Number { min, max, .. } => {
141                *min = Some(lo);
142                *max = Some(hi);
143            }
144            ParamKind::Integer { min, max } => {
145                *min = Some(lo as i64);
146                *max = Some(hi as i64);
147            }
148            _ => {}
149        }
150        self
151    }
152
153    /// The same number with a unit.
154    pub fn unit(mut self, u: impl Into<String>) -> Self {
155        if let ParamKind::Number { unit, .. } = &mut self.kind {
156            *unit = Some(u.into());
157        }
158        self
159    }
160
161    /// The same parameter with a line for people.
162    pub fn hint(mut self, hint: impl Into<String>) -> Self {
163        self.hint = hint.into();
164        self
165    }
166
167    /// `value` checked against this parameter, as the value to use (a whole number given for a
168    /// number becomes a number), or why it does not fit.
169    pub fn check(&self, value: &ParamValue) -> Result<ParamValue, String> {
170        let name = &self.name;
171        match (&self.kind, value) {
172            (ParamKind::Number { min, max, .. }, v) => {
173                let x = v.as_f64().ok_or_else(|| format!("{name} is a number"))?;
174                if !x.is_finite() {
175                    return Err(format!("{name} is a finite number"));
176                }
177                if let Some(lo) = min.filter(|lo| x < *lo) {
178                    return Err(format!("{name} is at least {lo} (got {x})"));
179                }
180                if let Some(hi) = max.filter(|hi| x > *hi) {
181                    return Err(format!("{name} is at most {hi} (got {x})"));
182                }
183                Ok(ParamValue::Number(x))
184            }
185            (ParamKind::Integer { min, max }, v) => {
186                let x = match v {
187                    ParamValue::Integer(i) => *i,
188                    ParamValue::Number(f) if f.fract() == 0.0 && f.is_finite() => *f as i64,
189                    _ => return Err(format!("{name} is a whole number")),
190                };
191                if let Some(lo) = min.filter(|lo| x < *lo) {
192                    return Err(format!("{name} is at least {lo} (got {x})"));
193                }
194                if let Some(hi) = max.filter(|hi| x > *hi) {
195                    return Err(format!("{name} is at most {hi} (got {x})"));
196                }
197                Ok(ParamValue::Integer(x))
198            }
199            (ParamKind::Switch, ParamValue::Switch(b)) => Ok(ParamValue::Switch(*b)),
200            (ParamKind::Switch, _) => Err(format!("{name} is on or off (true or false)")),
201            (ParamKind::Text, ParamValue::Text(t)) => Ok(ParamValue::Text(t.clone())),
202            (ParamKind::Text, _) => Err(format!("{name} is text")),
203            (ParamKind::Choice { options }, ParamValue::Text(t)) if options.contains(t) => {
204                Ok(ParamValue::Text(t.clone()))
205            }
206            (ParamKind::Choice { options }, _) => Err(format!("{name} is one of {}", options.join(", "))),
207        }
208    }
209}
210
211/// Checks `given` against `specs`: every value fits, no name is unknown, and what is missing takes
212/// its default. Returns the full set, or every problem.
213pub fn check_params(
214    specs: &[ParamSpec],
215    given: &BTreeMap<String, ParamValue>,
216) -> Result<BTreeMap<String, ParamValue>, Vec<String>> {
217    let mut out = BTreeMap::new();
218    let mut problems = Vec::new();
219    for spec in specs {
220        match given.get(&spec.name) {
221            Some(v) => match spec.check(v) {
222                Ok(v) => {
223                    out.insert(spec.name.clone(), v);
224                }
225                Err(e) => problems.push(e),
226            },
227            None => {
228                out.insert(spec.name.clone(), spec.default.clone());
229            }
230        }
231    }
232    for name in given.keys().filter(|n| !specs.iter().any(|s| &s.name == *n)) {
233        problems.push(format!("no parameter {name}"));
234    }
235    if problems.is_empty() { Ok(out) } else { Err(problems) }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn params_are_checked_and_filled() {
244        let specs = vec![
245            ParamSpec::number("sigma", 2.0).range(0.2, 20.0).unit("px"),
246            ParamSpec::integer("bins", 256).range(2.0, 4096.0),
247            ParamSpec::switch("invert", false),
248            ParamSpec::choice("band", &["highpass", "lowpass"]),
249        ];
250        let given: BTreeMap<String, ParamValue> =
251            [("sigma".to_string(), ParamValue::Integer(3)), ("band".to_string(), ParamValue::Text("lowpass".into()))]
252                .into();
253        let full = check_params(&specs, &given).unwrap();
254        assert_eq!(full["sigma"], ParamValue::Number(3.0), "a whole number given for a number");
255        assert_eq!(full["bins"], ParamValue::Integer(256), "the default");
256        assert_eq!(full["band"], ParamValue::Text("lowpass".into()));
257        let bad: BTreeMap<String, ParamValue> = [
258            ("sigma".to_string(), ParamValue::Number(50.0)),
259            ("bins".to_string(), ParamValue::Number(2.5)),
260            ("band".to_string(), ParamValue::Text("notch".into())),
261            ("gamma".to_string(), ParamValue::Number(1.0)),
262        ]
263        .into();
264        let problems = check_params(&specs, &bad).unwrap_err();
265        assert_eq!(problems.len(), 4, "{problems:?}");
266        assert!(problems.iter().any(|p| p.contains("at most 20")));
267        assert!(problems.iter().any(|p| p.contains("no parameter gamma")));
268    }
269
270    #[test]
271    fn values_read_from_json() {
272        let v: Vec<ParamValue> = serde_json::from_str(r#"[true, 3, 2.5, "x"]"#).unwrap();
273        assert_eq!(
274            v,
275            [ParamValue::Switch(true), ParamValue::Integer(3), ParamValue::Number(2.5), ParamValue::Text("x".into())]
276        );
277        let spec: ParamSpec =
278            serde_json::from_str(r#"{"name":"sigma","kind":"number","min":0.2,"default":2.0}"#).unwrap();
279        assert_eq!(spec.kind, ParamKind::Number { min: Some(0.2), max: None, unit: None });
280    }
281}