Skip to main content

mln_expression/
step.rs

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