1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//! Pixel-level expression evaluator for raster bands
use super::ast::{BinaryOp, Expr, UnaryOp};
use crate::error::{AlgorithmError, Result};
use oxigdal_core::buffer::RasterBuffer;
#[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};
/// Evaluator for raster expressions.
///
/// `cache_slots` holds the original (pre-CSE-rewrite) expression for each CSE
/// slot. When `eval_pixel` encounters a `CacheRef(i)` it evaluates
/// `cache_slots[i]` lazily (computing it once per pixel) and stores the result
/// in the caller-supplied `pixel_cache` vector. For non-CSE expressions
/// `cache_slots` may be an empty slice and `pixel_cache` may be an empty vec.
pub(super) struct Evaluator<'a> {
bands: &'a [RasterBuffer],
cache_slots: &'a [Expr],
}
impl<'a> Evaluator<'a> {
pub(super) fn new(bands: &'a [RasterBuffer], cache_slots: &'a [Expr]) -> Self {
Self { bands, cache_slots }
}
/// Evaluate `expr` at pixel `(x, y)`.
///
/// `pixel_cache` is a per-pixel memoisation table with one `Option<f64>`
/// entry per CSE slot. It must be reset to all-`None` before each pixel.
/// When there are no CSE slots an empty `&mut Vec` may be passed.
pub(super) fn eval_pixel(
&self,
expr: &Expr,
x: u64,
y: u64,
pixel_cache: &mut Vec<Option<f64>>,
) -> Result<f64> {
match expr {
Expr::Number(n) => Ok(*n),
Expr::Band(b) => {
if *b == 0 || *b > self.bands.len() {
return Err(AlgorithmError::InvalidParameter {
parameter: "band",
message: format!("Band {} out of range (1-{})", b, self.bands.len()),
});
}
self.bands[b - 1]
.get_pixel(x, y)
.map_err(AlgorithmError::Core)
}
Expr::CacheRef(slot_id) => {
let idx = *slot_id as usize;
// Return cached value if already computed for this pixel
if let Some(cached) = pixel_cache.get(idx).and_then(|v| *v) {
return Ok(cached);
}
// Clone the slot expression so we can recurse without borrowing self
let slot_expr = self.cache_slots[idx].clone();
let value = self.eval_pixel(&slot_expr, x, y, pixel_cache)?;
// Store into cache — the vec is always pre-allocated to the right length
if idx < pixel_cache.len() {
pixel_cache[idx] = Some(value);
}
Ok(value)
}
Expr::BinaryOp { left, op, right } => {
let lval = self.eval_pixel(left, x, y, pixel_cache)?;
let rval = self.eval_pixel(right, x, y, pixel_cache)?;
let result = match op {
BinaryOp::Add => lval + rval,
BinaryOp::Subtract => lval - rval,
BinaryOp::Multiply => lval * rval,
BinaryOp::Divide => {
if rval.abs() < f64::EPSILON {
f64::NAN
} else {
lval / rval
}
}
BinaryOp::Power => lval.powf(rval),
BinaryOp::Greater => {
if lval > rval {
1.0
} else {
0.0
}
}
BinaryOp::Less => {
if lval < rval {
1.0
} else {
0.0
}
}
BinaryOp::GreaterEqual => {
if lval >= rval {
1.0
} else {
0.0
}
}
BinaryOp::LessEqual => {
if lval <= rval {
1.0
} else {
0.0
}
}
BinaryOp::Equal => {
if (lval - rval).abs() < f64::EPSILON {
1.0
} else {
0.0
}
}
BinaryOp::NotEqual => {
if (lval - rval).abs() >= f64::EPSILON {
1.0
} else {
0.0
}
}
BinaryOp::And => {
if lval != 0.0 && rval != 0.0 {
1.0
} else {
0.0
}
}
BinaryOp::Or => {
if lval != 0.0 || rval != 0.0 {
1.0
} else {
0.0
}
}
};
Ok(result)
}
Expr::UnaryOp { op, expr } => {
let val = self.eval_pixel(expr, x, y, pixel_cache)?;
match op {
UnaryOp::Negate => Ok(-val),
}
}
Expr::Function { name, args } => self.eval_function(name, args, x, y, pixel_cache),
Expr::Conditional {
condition,
then_expr,
else_expr,
} => {
let cond_val = self.eval_pixel(condition, x, y, pixel_cache)?;
if cond_val != 0.0 {
self.eval_pixel(then_expr, x, y, pixel_cache)
} else {
self.eval_pixel(else_expr, x, y, pixel_cache)
}
}
}
}
pub(super) fn eval_function(
&self,
name: &str,
args: &[Expr],
x: u64,
y: u64,
pixel_cache: &mut Vec<Option<f64>>,
) -> Result<f64> {
let arg_vals: Result<Vec<f64>> = args
.iter()
.map(|arg| self.eval_pixel(arg, x, y, pixel_cache))
.collect();
let arg_vals = arg_vals?;
let result = match name {
"sqrt" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "sqrt",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].sqrt()
}
"abs" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "abs",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].abs()
}
"log" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "log",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].ln()
}
"log10" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "log10",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].log10()
}
"exp" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "exp",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].exp()
}
"sin" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "sin",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].sin()
}
"cos" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "cos",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].cos()
}
"tan" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "tan",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].tan()
}
"floor" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "floor",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].floor()
}
"ceil" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "ceil",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].ceil()
}
"round" => {
if arg_vals.len() != 1 {
return Err(AlgorithmError::InvalidParameter {
parameter: "round",
message: "Expected 1 argument".to_string(),
});
}
arg_vals[0].round()
}
"min" => {
if arg_vals.is_empty() {
return Err(AlgorithmError::InvalidParameter {
parameter: "min",
message: "Expected at least 1 argument".to_string(),
});
}
arg_vals.iter().copied().fold(f64::INFINITY, f64::min)
}
"max" => {
if arg_vals.is_empty() {
return Err(AlgorithmError::InvalidParameter {
parameter: "max",
message: "Expected at least 1 argument".to_string(),
});
}
arg_vals.iter().copied().fold(f64::NEG_INFINITY, f64::max)
}
_ => {
return Err(AlgorithmError::InvalidParameter {
parameter: "function",
message: format!("Unknown function: {name}"),
});
}
};
Ok(result)
}
}