Skip to main content

mln_style/expression/forms/
step.rs

1use crate::conversion::Convertible;
2use crate::expression::forms::interpolate::parse_stop_label;
3use crate::expression::parse::{ParseResult, ParsingContext};
4use crate::expression::stops::{Stops, covering_stops};
5use crate::expression::type_::Type;
6use crate::expression::{EvalResult, EvaluationContext, EvaluationError, Expr, Node, Output};
7use crate::feature::Value as FeatureValue;
8use crate::range::Range;
9
10/// `["step", input, output, label, output, ...]`.
11#[derive(Clone, PartialEq, mln_wire::Wire)]
12pub struct Step {
13    ty: Type,
14    input: Expr,
15    stops: Stops,
16}
17
18impl Step {
19    /// A step over `input`, which is a number.
20    #[must_use]
21    pub fn new_expr(ty: Type, input: Expr, stops: Stops) -> Expr {
22        assert_eq!(input.ty(), Type::Number);
23        Expr::new(Node::Step(Box::new(Step { ty, input, stops })))
24    }
25
26    pub(crate) fn ty(&self) -> &Type {
27        &self.ty
28    }
29
30    #[must_use]
31    pub(crate) fn input(&self) -> &Expr {
32        &self.input
33    }
34
35    #[must_use]
36    pub fn covering_stops(&self, lower: f64, upper: f64) -> Range<f64> {
37        covering_stops(&self.stops, lower, upper)
38    }
39
40    /// The inputs of the stops, in order.
41    pub(crate) fn stop_inputs(&self) -> impl Iterator<Item = f64> + '_ {
42        self.stops.iter().map(|(input, _)| input)
43    }
44
45    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
46        debug_assert!(value.is_array());
47
48        let length = value.array_length();
49
50        if length - 1 < 4 {
51            ctx.error(format!("Expected at least 4 arguments, but found only {}.", length - 1));
52            return None;
53        }
54
55        // [step, input, firstOutput_value, 2 * (n pairs)...]
56        if !(length - 1).is_multiple_of(2) {
57            ctx.error("Expected an even number of arguments.".to_owned());
58            return None;
59        }
60
61        let input = ctx.parse(&value.array_member(1), 1, Some(Type::Number), None)?;
62
63        let mut stops = Stops::new();
64        let mut output_type: Option<Type> = None;
65        if let Some(expected) = ctx.expected()
66            && expected != Type::Value
67        {
68            output_type = Some(expected);
69        }
70
71        let mut previous = f64::NEG_INFINITY;
72
73        // consume the first output value, which doesn't have a corresponding
74        // input value, before proceeding into the "stops" loop below.
75        let first_output = ctx.parse(&value.array_member(2), 2, output_type.clone(), None)?;
76        if output_type.is_none() {
77            output_type = Some(first_output.ty());
78        }
79        stops.emplace(f64::NEG_INFINITY, first_output);
80
81        let mut i = 3;
82        while i + 1 < length {
83            let Some(label) = parse_stop_label(&value.array_member(i)) else {
84                ctx.error_at(
85                    r#"Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values."#
86                        .to_owned(),
87                    i,
88                );
89                return None;
90            };
91
92            if label <= previous {
93                ctx.error_at(
94                    r#"Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order."#
95                        .to_owned(),
96                    i,
97                );
98                return None;
99            }
100            previous = label;
101
102            let output = ctx.parse(&value.array_member(i + 1), i + 1, output_type.clone(), None)?;
103            if output_type.is_none() {
104                output_type = Some(output.ty());
105            }
106
107            stops.emplace(label, output);
108            i += 2;
109        }
110
111        let Some(output_type) = output_type else {
112            ctx.error(format!("Expected at least 4 arguments, but found only {}.", length - 1));
113            return None;
114        };
115
116        Some(Step::new_expr(output_type, input, stops))
117    }
118
119    /// The output of the last stop at or below the input.
120    pub(crate) fn eval<'e, T: Output<'e>>(&'e self, params: &EvaluationContext<'_>) -> EvalResult<T> {
121        let x = self.input.eval_num(params)?;
122        if x.is_nan() {
123            return Err(EvaluationError::new("Input is not a number."));
124        }
125
126        if self.stops.is_empty() {
127            return Err(EvaluationError::new("No stops in step curve."));
128        }
129
130        let it = self.stops.upper_bound(x);
131        T::eval(self.stops.output(it.saturating_sub(1)), params)
132    }
133
134    pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
135        visit(&self.input);
136        self.each_output(visit);
137    }
138
139    pub(crate) fn each_output<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
140        self.stops.values().for_each(visit);
141    }
142
143    pub(crate) fn serialize(&self) -> FeatureValue {
144        let mut serialized = vec![FeatureValue::String("step".to_owned()), self.input.serialize()];
145        for (i, (k, v)) in self.stops.iter().enumerate() {
146            // The base output's label is -infinity, which isn't written.
147            if i > 0 {
148                serialized.push(FeatureValue::Double(k));
149            }
150            serialized.push(v.serialize());
151        }
152        FeatureValue::Array(serialized)
153    }
154}