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