• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

geo-engine / geoengine / 47199962842

03 Dec 2026 08:28PM UTC coverage: 89.337% (+0.3%) from 89.043%
47199962842

push

github

web-flow
feat(backend): raster footprints, when and where a raster has data (#1508)

* feat(backend): raster footprints, when and where a raster has data

Consolidates #1415, #1416 and #1504.

* refactor(backend): address the review of the raster footprints

Loading info
- The loading info of the multi-band GDAL source is a stream of parts
  (`MultiBandGdalLoadingInfo` of `MultiBandGdalLoadingInfoPart`) instead of
  an answer with a `next` cursor. The Postgres provider computes the
  gap-free time steps once and not for every part.

Footprints endpoint
- `next` is the rest of the requested time interval, to send back as
  `timeInterval`. A test covers the paging.

STAC
- Whether a server answers `datetime_frequency` aggregations in the bucket
  size it is asked for is stated by the provider
  (`datetimeFrequencyAggregation`, migration 0042, off if omitted). The size
  of a single bucket is no longer guessed, and providers without it are not
  asked.
- The exemption of one-step requests from the search limit is decided for
  the whole request, not for each part. Such a request counts the cells that
  are not cached yet.
- With the cache off, the limit counts every step of every cell.
- A window over the cell limit asks no aggregation and stores no empty
  steps.
- `search_chunk_steps` cannot be 0.

* feat(backend): let the STAC discovery write the aggregation setting

`--datetime-frequency-aggregation` writes `datetimeFrequencyAggregation: true` into the discovered provider definition, for servers like CODE-DE. Without the flag the definition is unchanged.

* refactor(backend): ask the loading info with one value instead of detail and purpose

Two of the six combinations of `detail` and `purpose` made no sense.
`LoadingInfoDetail` now has the four cases that occur: `TimeSteps`, `Files`
for data, and `Availability` and `Coverage` for footprints.

* perf(backend): answer the availability of a cached view without a request

If every cell and time step of a part is... (continued)

5052 of 5218 new or added lines in 65 files covered. (96.82%)

1 existing line in 1 file now uncovered.

156208 of 174852 relevant lines covered (89.34%)

417614.24 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.22
/geoengine/operators/src/processing/expression/raster_query_processor.rs
1
use super::RasterExpressionError;
2
use crate::{
3
    engine::{
4
        BoxRasterQueryProcessor, Footprint, FootprintCombine, QueryContext, QueryProcessor,
5
        RasterQueryProcessor, RasterResultDescriptor, unknown_footprints, zip_footprints,
6
    },
7
    util::Result,
8
};
9
use async_trait::async_trait;
10
use futures::{StreamExt, TryStreamExt, stream::BoxStream};
11
use geoengine_datatypes::{
12
    primitives::{BandSelection, CacheHint, RasterQueryRectangle, TimeInterval},
13
    raster::{
14
        ConvertDataType, FromIndexFnParallel, GeoTransform, GridBoundingBox2D, GridIdx2D,
15
        GridIndexAccess, GridOrEmpty, GridOrEmpty2D, GridShape2D, GridShapeAccess,
16
        MapElementsParallel, MaskedGrid2D, Pixel, RasterTile2D,
17
    },
18
};
19
use geoengine_expression::LinkedExpression;
20
use libloading::Symbol;
21
use num_traits::AsPrimitive;
22
use std::{marker::PhantomData, sync::Arc};
23

24
pub struct ExpressionInput<const N: usize> {
25
    pub raster: BoxRasterQueryProcessor<f64>,
26
}
27

28
pub struct ExpressionQueryProcessor<TO, Sources>
29
where
30
    TO: Pixel,
31
{
32
    pub sources: Sources,
33
    pub result_descriptor: RasterResultDescriptor,
34
    pub phantom_data: PhantomData<TO>,
35
    pub program: Arc<LinkedExpression>,
36
    pub map_no_data: bool,
37
}
38

39
impl<TO, Sources> ExpressionQueryProcessor<TO, Sources>
40
where
41
    TO: Pixel,
42
{
43
    pub fn new(
31 ✔
44
        program: Arc<LinkedExpression>,
31 ✔
45
        sources: Sources,
31 ✔
46
        result_descriptor: RasterResultDescriptor,
31 ✔
47
        map_no_data: bool,
31 ✔
48
    ) -> Self {
31 ✔
49
        Self {
31 ✔
50
            sources,
31 ✔
51
            result_descriptor,
31 ✔
52
            program,
31 ✔
53
            phantom_data: PhantomData,
31 ✔
54
            map_no_data,
31 ✔
55
        }
31 ✔
56
    }
31 ✔
57
}
58

59
#[async_trait]
60
impl<TO, Tuple> QueryProcessor for ExpressionQueryProcessor<TO, Tuple>
61
where
62
    TO: Pixel,
63
    Tuple: ExpressionTupleProcessor<TO>,
64
{
65
    type Output = RasterTile2D<TO>;
66
    type SpatialBounds = GridBoundingBox2D;
67
    type Selection = BandSelection;
68
    type ResultDescription = RasterResultDescriptor;
69

70
    async fn _query<'b>(
71
        &'b self,
72
        query: RasterQueryRectangle,
73
        ctx: &'b dyn QueryContext,
74
    ) -> Result<BoxStream<'b, Result<Self::Output>>> {
36 ✔
75
        // rewrite query to request all input bands from the source. They are all combined in the single output band by means of the expression.
76
        let source_query = query.select_attributes(BandSelection::first_n(Tuple::num_bands()));
77
        // the result of a pixel whose inputs are all no data, the same for every tile
78
        let empty_result = if self.map_no_data {
79
            Tuple::no_data_result(&self.program)?
80
        } else {
81
            None
82
        };
83

84
        let stream =
85
            self.sources
86
                .zip_bands(source_query, ctx)
87
                .await?
88
                .and_then(move |rasters| async move {
199 ✔
89
                    if !self.map_no_data && Tuple::all_empty(&rasters) {
199 ✔
90
                        return Ok(Tuple::empty_raster(&rasters));
20 ✔
91
                    }
179 ✔
92

93
                    let (
94
                        out_time,
179 ✔
95
                        out_tile_position,
179 ✔
96
                        out_global_geo_transform,
179 ✔
97
                        _output_grid_shape,
179 ✔
98
                        cache_hint,
179 ✔
99
                    ) = Tuple::metadata(&rasters);
179 ✔
100

101
                    let program = self.program.clone();
179 ✔
102
                    let map_no_data: bool = self.map_no_data;
179 ✔
103

104
                    let out = crate::util::spawn_blocking_with_thread_pool(
179 ✔
105
                        ctx.thread_pool().clone(),
179 ✔
106
                        move || {
179 ✔
107
                            Tuple::compute_expression(rasters, &program, map_no_data, empty_result)
179 ✔
108
                        },
179 ✔
109
                    )
110
                    .await??;
179 ✔
111

112
                    Ok(RasterTile2D::new(
179 ✔
113
                        out_time,
179 ✔
114
                        out_tile_position,
179 ✔
115
                        0,
179 ✔
116
                        out_global_geo_transform,
179 ✔
117
                        out,
179 ✔
118
                        cache_hint,
179 ✔
119
                    ))
179 ✔
120
                });
398 ✔
121

122
        Ok(stream.boxed())
123
    }
36 ✔
124

125
    fn result_descriptor(&self) -> &RasterResultDescriptor {
93 ✔
126
        &self.result_descriptor
93 ✔
127
    }
93 ✔
128
}
129

130
#[async_trait]
131
impl<TO, Tuple> RasterQueryProcessor for ExpressionQueryProcessor<TO, Tuple>
132
where
133
    TO: Pixel,
134
    Tuple: ExpressionTupleProcessor<TO>,
135
{
136
    type RasterType = TO;
137

138
    async fn _time_query<'a>(
139
        &'a self,
140
        query: geoengine_datatypes::primitives::TimeInterval,
141
        ctx: &'a dyn QueryContext,
142
    ) -> Result<BoxStream<'a, Result<geoengine_datatypes::primitives::TimeInterval>>> {
×
143
        self.sources.time_query(query, ctx).await
144
    }
×
145

146
    async fn _footprint_query<'a>(
147
        &'a self,
148
        query: RasterQueryRectangle,
149
        detail: crate::engine::FootprintDetail,
150
        ctx: &'a dyn QueryContext,
151
    ) -> Result<BoxStream<'a, Result<Footprint>>> {
4 ✔
152
        // A footprint is a superset, so an expression that turns data into no-data, like
153
        // `fn(A) -> NODATA`, needs no care. Only turning no-data into data matters:
154
        // - Without `map_no_data`, a pixel is no-data if any input is, without evaluating the
155
        //   expression. So there is data only where all inputs have data.
156
        // - With it, the expression gets the no-data inputs. Evaluated once with all inputs no-data,
157
        //   it tells whether a pixel without data in any input stays without data. If it does, as
158
        //   `A + B` or `fn(A) -> NODATA`, there is data only where an input has data. If not, as
159
        //   `fn(A) -> 1`, any pixel can have data.
160
        let combine = if !self.map_no_data {
161
            FootprintCombine::Intersection
162
        } else if Tuple::no_data_result(&self.program)?.is_none() {
163
            FootprintCombine::Union
164
        } else {
165
            // the expression can turn no-data into data anywhere
166
            let time_steps = self.time_query(query.time_interval(), ctx).await?;
167
            return Ok(unknown_footprints(time_steps));
168
        };
169

170
        // Each input band is asked for itself and the streams are zipped.
171
        let mut streams = Vec::with_capacity(Tuple::num_bands() as usize);
172
        for band in 0..Tuple::num_bands() {
173
            streams.push(
174
                self.sources
175
                    .footprint_query(
176
                        query.select_attributes(BandSelection::new(vec![band])?),
177
                        detail,
178
                        ctx,
179
                    )
180
                    .await?,
181
            );
182
        }
183

184
        Ok(zip_footprints(
185
            streams,
186
            combine,
187
            ctx.footprint_boxes_per_step_limit(),
188
        ))
189
    }
4 ✔
190
}
191

192
#[async_trait]
193
trait ExpressionTupleProcessor<TO: Pixel>: Send + Sync {
194
    type Tuple: Send + 'static;
195

196
    async fn zip_bands<'a>(
197
        &'a self,
198
        query: RasterQueryRectangle,
199
        ctx: &'a dyn QueryContext,
200
    ) -> Result<BoxStream<'a, Result<Self::Tuple>>>;
201

202
    fn all_empty(tuple: &Self::Tuple) -> bool;
203

204
    fn empty_raster(tuple: &Self::Tuple) -> RasterTile2D<TO>;
205

206
    fn metadata(
207
        tuple: &Self::Tuple,
208
    ) -> (
209
        TimeInterval,
210
        GridIdx2D,
211
        GeoTransform,
212
        GridShape2D,
213
        CacheHint,
214
    );
215

216
    /// Computes the expression for each pixel. `empty_result` is the result of a pixel whose
217
    /// inputs are all no data, see [`Self::no_data_result`], and `None` without `map_no_data`.
218
    fn compute_expression(
219
        tuple: Self::Tuple,
220
        program: &LinkedExpression,
221
        map_no_data: bool,
222
        empty_result: Option<f64>,
223
    ) -> Result<GridOrEmpty2D<TO>>;
224

225
    fn num_bands() -> u32;
226

227
    /// The result of the expression if all of its inputs are no data, `None` for no data.
228
    fn no_data_result(program: &LinkedExpression) -> Result<Option<f64>>;
229

230
    async fn time_query<'a>(
231
        &'a self,
232
        query: geoengine_datatypes::primitives::TimeInterval,
233
        ctx: &'a dyn QueryContext,
234
    ) -> Result<BoxStream<'a, Result<geoengine_datatypes::primitives::TimeInterval>>>;
235

236
    /// The footprints of the input rasters, without the expression. The rule of the expression
237
    /// is applied to them in `ExpressionQueryProcessor::_footprint_query`.
238
    async fn footprint_query<'a>(
239
        &'a self,
240
        query: RasterQueryRectangle,
241
        detail: crate::engine::FootprintDetail,
242
        ctx: &'a dyn QueryContext,
243
    ) -> Result<BoxStream<'a, Result<Footprint>>>;
244
}
245

246
#[async_trait]
247
impl<TO> ExpressionTupleProcessor<TO> for ExpressionInput<1>
248
where
249
    TO: Pixel,
250
    f64: AsPrimitive<TO>,
251
{
252
    type Tuple = RasterTile2D<f64>;
253

254
    #[inline]
255
    async fn zip_bands<'a>(
256
        &'a self,
257
        query: RasterQueryRectangle,
258
        ctx: &'a dyn QueryContext,
259
    ) -> Result<BoxStream<'a, Result<Self::Tuple>>> {
15 ✔
260
        self.raster.query(query, ctx).await
261
    }
15 ✔
262

263
    #[inline]
264
    fn all_empty(tuple: &Self::Tuple) -> bool {
134 ✔
265
        tuple.grid_array.is_empty()
134 ✔
266
    }
134 ✔
267

268
    #[inline]
269
    fn empty_raster(tuple: &Self::Tuple) -> RasterTile2D<TO> {
16 ✔
270
        tuple.clone().convert_data_type()
16 ✔
271
    }
16 ✔
272

273
    #[inline]
274
    fn metadata(
127 ✔
275
        tuple: &Self::Tuple,
127 ✔
276
    ) -> (
127 ✔
277
        TimeInterval,
127 ✔
278
        GridIdx2D,
127 ✔
279
        GeoTransform,
127 ✔
280
        GridShape2D,
127 ✔
281
        CacheHint,
127 ✔
282
    ) {
127 ✔
283
        let raster = &tuple;
127 ✔
284

285
        (
127 ✔
286
            raster.time,
127 ✔
287
            raster.tile_position,
127 ✔
288
            raster.global_geo_transform,
127 ✔
289
            raster.grid_shape(),
127 ✔
290
            raster.cache_hint,
127 ✔
291
        )
127 ✔
292
    }
127 ✔
293

294
    #[inline]
295
    fn compute_expression(
127 ✔
296
        raster: Self::Tuple,
127 ✔
297
        program: &LinkedExpression,
127 ✔
298
        _map_no_data: bool,
127 ✔
299
        empty_result: Option<f64>,
127 ✔
300
    ) -> Result<GridOrEmpty2D<TO>> {
127 ✔
301
        let expression = unsafe {
127 ✔
302
            // we have to "trust" that the function has the signature we expect
303
            program
127 ✔
304
                .function_1::<Option<f64>>()
127 ✔
305
                .map_err(RasterExpressionError::from)?
127 ✔
306
        };
307
        let empty_result = empty_result.map(TO::from_);
127 ✔
308

309
        if raster.is_empty() {
127 ✔
310
            return match empty_result {
×
311
                Some(value) => Ok(GridOrEmpty::new_grid(MaskedGrid2D::new_filled(
×
312
                    raster.grid_shape(),
×
313
                    value,
×
314
                ))),
×
315
                None => Ok(GridOrEmpty::new_empty_shape(raster.grid_shape())),
×
316
            };
317
        }
127 ✔
318

319
        let map_fn = |in_value: Option<f64>| {
29,884,494 ✔
320
            // TODO: could be a |in_value: T1| if map no data is false!
321
            if in_value.is_none() {
29,884,494 ✔
322
                return empty_result;
4,327,496 ✔
323
            }
25,556,998 ✔
324

325
            let result = expression(in_value);
25,556,998 ✔
326

327
            result.map(TO::from_)
25,556,998 ✔
328
        };
29,884,494 ✔
329

330
        let res = raster.grid_array.map_elements_parallel(map_fn);
127 ✔
331

332
        Result::Ok(res)
127 ✔
333
    }
127 ✔
334

335
    fn num_bands() -> u32 {
15 ✔
336
        1
15 ✔
337
    }
15 ✔
338

339
    fn no_data_result(program: &LinkedExpression) -> Result<Option<f64>> {
5 ✔
340
        let expression = unsafe {
5 ✔
341
            // we have to "trust" that the function has the signature we expect
342
            program
5 ✔
343
                .function_1::<Option<f64>>()
5 ✔
344
                .map_err(RasterExpressionError::from)?
5 ✔
345
        };
346
        Ok(expression(None))
5 ✔
347
    }
5 ✔
348

349
    async fn time_query<'a>(
350
        &'a self,
351
        query: geoengine_datatypes::primitives::TimeInterval,
352
        ctx: &'a dyn QueryContext,
353
    ) -> Result<BoxStream<'a, Result<geoengine_datatypes::primitives::TimeInterval>>> {
×
354
        self.raster.time_query(query, ctx).await
355
    }
×
356

357
    async fn footprint_query<'a>(
358
        &'a self,
359
        query: RasterQueryRectangle,
360
        detail: crate::engine::FootprintDetail,
361
        ctx: &'a dyn QueryContext,
NEW
362
    ) -> Result<BoxStream<'a, Result<Footprint>>> {
×
363
        self.raster.footprint_query(query, detail, ctx).await
NEW
364
    }
×
365
}
366

367
// TODO: implement this via macro for 2-8 sources
368
#[async_trait]
369
impl<TO> ExpressionTupleProcessor<TO> for ExpressionInput<2>
370
where
371
    TO: Pixel,
372
    f64: AsPrimitive<TO>,
373
{
374
    type Tuple = (RasterTile2D<f64>, RasterTile2D<f64>);
375

376
    #[inline]
377
    async fn zip_bands<'a>(
378
        &'a self,
379
        query: RasterQueryRectangle,
380
        ctx: &'a dyn QueryContext,
381
    ) -> Result<BoxStream<'a, Result<Self::Tuple>>> {
18 ✔
382
        // chunk up the stream to get all bands for a spatial tile at once
383
        let stream = self.raster.query(query, ctx).await?.chunks(2).map(|chunk| {
53 ✔
384
            if chunk.len() != 2 {
53 ✔
385
                // if there are not exactly two tiles, it should mean the last tile was an error and the chunker ended prematurely
386
                if let Some(Err(e)) = chunk.into_iter().next_back() {
×
387
                    return Err(e);
×
388
                }
×
389
                // if there is no error, the source did not produce all bands, which likely means a bug in an operator
390
                return Err(crate::error::Error::MustNotHappen {
×
391
                    message: "source did not produce all bands (N: 2)".to_string(),
×
392
                });
×
393
            }
53 ✔
394

395
            let [a, b]: [Result<RasterTile2D<f64>>; 2] = chunk
53 ✔
396
                .try_into()
53 ✔
397
                .expect("all chunks should be of length 2 because it was checked above");
53 ✔
398
            match (a, b) {
53 ✔
399
                (Ok(t0), Ok(t1)) => Ok((t0, t1)),
53 ✔
400
                (Err(e), _) | (_, Err(e)) => Err(e),
×
401
            }
402
        });
53 ✔
403

404
        Ok(stream.boxed())
405
    }
18 ✔
406

407
    #[inline]
408
    fn all_empty(tuple: &Self::Tuple) -> bool {
20 ✔
409
        tuple.0.grid_array.is_empty() && tuple.1.grid_array.is_empty()
20 ✔
410
    }
20 ✔
411

412
    #[inline]
413
    fn empty_raster(tuple: &Self::Tuple) -> RasterTile2D<TO> {
4 ✔
414
        tuple.0.clone().convert_data_type()
4 ✔
415
    }
4 ✔
416

417
    #[inline]
418
    fn metadata(
49 ✔
419
        tuple: &Self::Tuple,
49 ✔
420
    ) -> (
49 ✔
421
        TimeInterval,
49 ✔
422
        GridIdx2D,
49 ✔
423
        GeoTransform,
49 ✔
424
        GridShape2D,
49 ✔
425
        CacheHint,
49 ✔
426
    ) {
49 ✔
427
        let raster = &tuple.0;
49 ✔
428

429
        (
49 ✔
430
            raster.time,
49 ✔
431
            raster.tile_position,
49 ✔
432
            raster.global_geo_transform,
49 ✔
433
            raster.grid_shape(),
49 ✔
434
            tuple.0.cache_hint.merged(&tuple.1.cache_hint),
49 ✔
435
        )
49 ✔
436
    }
49 ✔
437

438
    #[inline]
439
    fn compute_expression(
49 ✔
440
        rasters: Self::Tuple,
49 ✔
441
        program: &LinkedExpression,
49 ✔
442
        map_no_data: bool,
49 ✔
443
        empty_result: Option<f64>,
49 ✔
444
    ) -> Result<GridOrEmpty2D<TO>> {
49 ✔
445
        let expression = unsafe {
49 ✔
446
            // we have to "trust" that the function has the signature we expect
447
            program
49 ✔
448
                .function_2::<Option<f64>, Option<f64>>()
49 ✔
449
                .map_err(RasterExpressionError::from)?
49 ✔
450
        };
451

452
        if rasters.0.is_empty() && rasters.1.is_empty() {
49 ✔
453
            let empty_result = empty_result.map(TO::from_);
16 ✔
454
            return match empty_result {
16 ✔
455
                Some(value) => Ok(GridOrEmpty::new_grid(MaskedGrid2D::new_filled(
2 ✔
456
                    rasters.0.grid_shape(),
2 ✔
457
                    value,
2 ✔
458
                ))),
2 ✔
459
                None => Ok(GridOrEmpty::new_empty_shape(rasters.0.grid_shape())),
14 ✔
460
            };
461
        }
33 ✔
462

463
        let map_fn = |lin_idx: usize| {
3,932,262 ✔
464
            let t0_value = rasters.0.get_at_grid_index_unchecked(lin_idx);
3,932,262 ✔
465
            let t1_value = rasters.1.get_at_grid_index_unchecked(lin_idx);
3,932,262 ✔
466

467
            if !map_no_data && (t0_value.is_none() || t1_value.is_none()) {
3,932,262 ✔
468
                return None;
111 ✔
469
            }
3,932,151 ✔
470

471
            let result = expression(t0_value, t1_value);
3,932,151 ✔
472

473
            result.map(TO::from_)
3,932,151 ✔
474
        };
3,932,262 ✔
475

476
        let grid_shape = rasters.0.grid_shape();
33 ✔
477
        let out = GridOrEmpty::from_index_fn_parallel(&grid_shape, map_fn);
33 ✔
478

479
        let out_or_empty = match out {
33 ✔
480
            GridOrEmpty::Empty(t) => GridOrEmpty::Empty(t),
5 ✔
481
            GridOrEmpty::Grid(t) => {
28 ✔
482
                if t.validity_mask.data.iter().all(|&t| !t) {
1,407,639 ✔
483
                    tracing::trace!("Converting empty expression output to EmptyGrid");
×
484
                    GridOrEmpty::new_empty_shape(t.grid_shape())
×
485
                } else {
486
                    GridOrEmpty::Grid(t)
28 ✔
487
                }
488
            }
489
        };
490

491
        Result::Ok(out_or_empty)
33 ✔
492
    }
49 ✔
493

494
    fn num_bands() -> u32 {
24 ✔
495
        2
24 ✔
496
    }
24 ✔
497

498
    fn no_data_result(program: &LinkedExpression) -> Result<Option<f64>> {
9 ✔
499
        let expression = unsafe {
9 ✔
500
            // we have to "trust" that the function has the signature we expect
501
            program
9 ✔
502
                .function_2::<Option<f64>, Option<f64>>()
9 ✔
503
                .map_err(RasterExpressionError::from)?
9 ✔
504
        };
505
        Ok(expression(None, None))
9 ✔
506
    }
9 ✔
507

508
    async fn time_query<'a>(
509
        &'a self,
510
        query: geoengine_datatypes::primitives::TimeInterval,
511
        ctx: &'a dyn QueryContext,
512
    ) -> Result<BoxStream<'a, Result<geoengine_datatypes::primitives::TimeInterval>>> {
×
513
        self.raster.time_query(query, ctx).await
514
    }
×
515

516
    async fn footprint_query<'a>(
517
        &'a self,
518
        query: RasterQueryRectangle,
519
        detail: crate::engine::FootprintDetail,
520
        ctx: &'a dyn QueryContext,
521
    ) -> Result<BoxStream<'a, Result<Footprint>>> {
6 ✔
522
        self.raster.footprint_query(query, detail, ctx).await
523
    }
6 ✔
524
}
525

526
type Function3 = fn(Option<f64>, Option<f64>, Option<f64>) -> Option<f64>;
527
type Function4 = fn(Option<f64>, Option<f64>, Option<f64>, Option<f64>) -> Option<f64>;
528
type Function5 = fn(Option<f64>, Option<f64>, Option<f64>, Option<f64>, Option<f64>) -> Option<f64>;
529
type Function6 =
530
    fn(Option<f64>, Option<f64>, Option<f64>, Option<f64>, Option<f64>, Option<f64>) -> Option<f64>;
531
type Function7 = fn(
532
    Option<f64>,
533
    Option<f64>,
534
    Option<f64>,
535
    Option<f64>,
536
    Option<f64>,
537
    Option<f64>,
538
    Option<f64>,
539
) -> Option<f64>;
540
type Function8 = fn(
541
    Option<f64>,
542
    Option<f64>,
543
    Option<f64>,
544
    Option<f64>,
545
    Option<f64>,
546
    Option<f64>,
547
    Option<f64>,
548
    Option<f64>,
549
) -> Option<f64>;
550

551
macro_rules! impl_expression_tuple_processor {
552
    ( $i:tt => $( $x:tt ),+ ) => {
553
        paste::paste! {
554
            impl_expression_tuple_processor!(
555
                @inner
556
                $i
557
                |
558
                $( $x ),*
559
                |
560
                $( [< pixel_ $x >] ),*
561
                |
562
                $( [< is_nodata_ $x >] ),*
563
                |
564
                [< Function $i >]
565
            );
566
        }
567
    };
568

569
    // We have `0, 1, 2, …` and `T0, T1, T2, …`
570
    (@inner $N:tt | $( $I:tt ),+ | $( $PIXEL:tt ),+ | $( $IS_NODATA:tt ),+ | $FN_T:ty ) => {
571
        #[async_trait]
572
        impl<TO> ExpressionTupleProcessor<TO> for ExpressionInput<$N>
573
        where
574
            TO: Pixel,
575
            f64: AsPrimitive<TO>,
576
        {
577
            type Tuple = [RasterTile2D<f64>; $N];
578

579
            #[inline]
580
            async fn zip_bands<'a>(
581
                &'a self,
582
                query: RasterQueryRectangle,
583
                ctx: &'a dyn QueryContext,
584
            ) -> Result<BoxStream<'a, Result<Self::Tuple>>> {
585
                // chunk up the stream to get all bands for a spatial tile at once
586
                let stream = self.raster.query(query, ctx).await?.chunks($N).map(|chunk| {
3 ✔
587
                    if chunk.len() != $N {
1 ✔
588
                        // if there are not exactly N tiles, it should mean the last tile was an error and the chunker ended prematurely
589
                        if let Some(Err(e)) = chunk.into_iter().last() {
×
590
                            return Err(e);
×
591
                        }
×
592
                        // if there is no error, the source did not produce all bands, which likely means a bug in an operator
593
                        return Err(crate::error::Error::MustNotHappen {
×
594
                            message: format!("source did not produce all bands, (N: {})", $N),
×
595
                        });
×
596
                    }
3 ✔
597

598
                    let mut ok_tiles = Vec::with_capacity($N);
3 ✔
599

600
                    for tile in chunk {
14 ✔
601
                        match tile {
14 ✔
602
                            Ok(tile) => ok_tiles.push(tile),
14 ✔
603
                            Err(e) => return Err(e),
×
604
                        }
605
                    }
606

607
                    let tuple: [RasterTile2D<f64>; $N] = ok_tiles
3 ✔
608
                        .try_into()
3 ✔
609
                        .expect("all chunks should be of the expected langth because it was checked above");
3 ✔
610

611
                    Ok(tuple)
3 ✔
612
                });
3 ✔
613

614
                Ok(stream.boxed())
615
            }
3 ✔
616

617
            #[inline]
618
            fn all_empty(tuple: &Self::Tuple) -> bool {
3 ✔
619
                $( tuple[$I].grid_array.is_empty() )&&*
×
620
            }
3 ✔
621

622
            #[inline]
623
            fn empty_raster(tuple: &Self::Tuple) -> RasterTile2D<TO> {
×
624
                tuple[0].clone().convert_data_type()
×
625
            }
×
626

627
            #[inline]
628
            fn metadata(tuple: &Self::Tuple) -> (TimeInterval, GridIdx2D, GeoTransform, GridShape2D, CacheHint) {
3 ✔
629
                let raster = &tuple[0];
3 ✔
630

631
                (
632
                    raster.time,
3 ✔
633
                    raster.tile_position,
3 ✔
634
                    raster.global_geo_transform,
3 ✔
635
                    raster.grid_shape(),
3 ✔
636
                    tuple.iter().fold(CacheHint::max_duration(), |acc, r| acc.merged(&r.cache_hint)),
14 ✔
637
                )
638
            }
3 ✔
639

640
            fn compute_expression(
3 ✔
641
                rasters: Self::Tuple,
3 ✔
642
                program: &LinkedExpression,
3 ✔
643
                map_no_data: bool,
3 ✔
644
                empty_result: Option<f64>,
3 ✔
645
            ) -> Result<GridOrEmpty2D<TO>> {
3 ✔
646
                let expression: Symbol<$FN_T> = unsafe {
3 ✔
647
                    // we have to "trust" that the function has the signature we expect
648
                    program.function_nary().map_err(RasterExpressionError::from)?
3 ✔
649
                };
650

651
                if rasters.iter().all(|r| r.grid_array.is_empty()) {
3 ✔
NEW
652
                    return match empty_result.map(TO::from_) {
×
653
                        Some(value) => Ok(GridOrEmpty::new_grid(MaskedGrid2D::new_filled(
×
654
                            rasters[0].grid_shape(),
×
655
                            value,
×
656
                        ))),
×
657
                        None => Ok(GridOrEmpty::new_empty_shape(rasters[0].grid_shape())),
×
658
                    };
659
                }
3 ✔
660

661
                let map_fn = |lin_idx: usize| {
18 ✔
662
                    $(
663
                        let $PIXEL = rasters[$I].get_at_grid_index_unchecked(lin_idx);
18 ✔
664
                        let $IS_NODATA = $PIXEL.is_none();
18 ✔
665
                    )*
666

667
                    if !map_no_data && ( $($IS_NODATA)||* ) {
18 ✔
668
                        return None;
1 ✔
669
                    }
17 ✔
670

671
                    let result = expression(
17 ✔
672
                        $(
17 ✔
673
                            $PIXEL
17 ✔
674
                        ),*
17 ✔
675
                    );
17 ✔
676

677
                    result.map(TO::from_)
17 ✔
678
                };
18 ✔
679

680
                let grid_shape = rasters[0].grid_shape();
3 ✔
681
                let out = GridOrEmpty::from_index_fn_parallel(&grid_shape, map_fn);
3 ✔
682

683
                Result::Ok(out)
3 ✔
684
            }
3 ✔
685

686
            fn num_bands() -> u32 {
3 ✔
687
                $N
688
            }
3 ✔
689

NEW
690
            fn no_data_result(program: &LinkedExpression) -> Result<Option<f64>> {
×
NEW
691
                let expression: Symbol<$FN_T> = unsafe {
×
692
                    // we have to "trust" that the function has the signature we expect
NEW
693
                    program.function_nary().map_err(RasterExpressionError::from)?
×
694
                };
695
                // call expression with $N None values correctly:
NEW
696
                Ok(expression(
×
NEW
697
                    $(
×
NEW
698
                        { let _ = $I; None } // this is a nice trick to get the correct number of None values for the function call
×
NEW
699
                    ),+
×
NEW
700
                ))
×
NEW
701
            }
×
702

703
            async fn time_query<'a>(
704
                &'a self,
705
                query: geoengine_datatypes::primitives::TimeInterval,
706
                ctx: &'a dyn QueryContext,
707
                ) -> Result<BoxStream<'a, Result<geoengine_datatypes::primitives::TimeInterval>>> {
708
                    self.raster.time_query(query, ctx).await
709
                }
×
710

711
            async fn footprint_query<'a>(
712
                &'a self,
713
                query: RasterQueryRectangle,
714
                detail: crate::engine::FootprintDetail,
715
                ctx: &'a dyn QueryContext,
716
            ) -> Result<BoxStream<'a, Result<Footprint>>> {
717
                self.raster.footprint_query(query, detail, ctx).await
NEW
718
            }
×
719
        }
720

721

722
    };
723

724
    // For any input, generate `f64, bool`
725
    (@input_dtypes $x:tt) => {
726
        f64, bool
727
    };
728
}
729

730
impl_expression_tuple_processor!(3 => 0, 1, 2);
731
impl_expression_tuple_processor!(4 => 0, 1, 2, 3);
732
impl_expression_tuple_processor!(5 => 0, 1, 2, 3, 4);
733
impl_expression_tuple_processor!(6 => 0, 1, 2, 3, 4, 5);
734
impl_expression_tuple_processor!(7 => 0, 1, 2, 3, 4, 5, 6);
735
impl_expression_tuple_processor!(8 => 0, 1, 2, 3, 4, 5, 6, 7);
736

737
#[cfg(test)]
738
mod footprint_tests {
739
    use crate::engine::footprint_test_util::*;
740
    use crate::engine::{FootprintBounds, RasterOperator, SingleRasterSource, TypedRasterOperator};
741
    use crate::processing::{Expression, ExpressionParams};
742
    use geoengine_datatypes::raster::RasterDataType;
743

744
    fn expression_of(expression: &str, map_no_data: bool) -> TypedRasterOperator {
3 ✔
745
        Expression {
3 ✔
746
            params: ExpressionParams {
3 ✔
747
                expression: expression.to_string(),
3 ✔
748
                output_type: RasterDataType::U8,
3 ✔
749
                output_band: None,
3 ✔
750
                map_no_data,
3 ✔
751
            },
3 ✔
752
            sources: SingleRasterSource {
3 ✔
753
                raster: stack(stack_inputs()),
3 ✔
754
            },
3 ✔
755
        }
3 ✔
756
        .typed()
3 ✔
757
    }
3 ✔
758

759
    fn expression(map_no_data: bool) -> TypedRasterOperator {
2 ✔
760
        expression_of("A + B", map_no_data)
2 ✔
761
    }
2 ✔
762

763
    #[tokio::test]
764
    async fn it_expression_has_data_only_where_all_inputs_have() {
1 ✔
765
        // the inputs have data in different tiles, so no pixel has data in both
766
        let footprints = checked_footprints(expression(false), &[0]).await;
1 ✔
767
        assert_eq!(step_boxes(&footprints), [[].as_slice(), [].as_slice()]);
1 ✔
768

769
        // here both have data in tile 1, and only the first in tile 0
770
        let overlapping = Expression {
1 ✔
771
            params: ExpressionParams {
1 ✔
772
                expression: "A + B".to_string(),
1 ✔
773
                output_type: RasterDataType::U8,
1 ✔
774
                output_band: None,
1 ✔
775
                map_no_data: false,
1 ✔
776
            },
1 ✔
777
            sources: SingleRasterSource {
1 ✔
778
                raster: stack(vec![
1 ✔
779
                    source(
1 ✔
780
                        vec![
1 ✔
781
                            tile(0, 0, 0, true),
1 ✔
782
                            tile(0, 1, 0, true),
1 ✔
783
                            tile(5, 0, 0, false),
1 ✔
784
                            tile(5, 1, 0, false),
1 ✔
785
                        ],
1 ✔
786
                        1,
1 ✔
787
                        regular_time(),
1 ✔
788
                    ),
1 ✔
789
                    source(
1 ✔
790
                        vec![
1 ✔
791
                            tile(0, 0, 0, false),
1 ✔
792
                            tile(0, 1, 0, true),
1 ✔
793
                            tile(5, 0, 0, false),
1 ✔
794
                            tile(5, 1, 0, false),
1 ✔
795
                        ],
1 ✔
796
                        1,
1 ✔
797
                        regular_time(),
1 ✔
798
                    ),
1 ✔
799
                ]),
1 ✔
800
            },
1 ✔
801
        }
1 ✔
802
        .typed();
1 ✔
803
        let footprints = checked_footprints(overlapping, &[0]).await;
1 ✔
804
        assert_eq!(
1 ✔
805
            step_boxes(&footprints),
1 ✔
806
            [[tile_box(1)].as_slice(), [].as_slice()]
1 ✔
807
        );
1 ✔
808
    }
1 ✔
809

810
    #[tokio::test]
811
    async fn it_expression_with_map_no_data_has_data_where_any_input_has() {
1 ✔
812
        // `A + B` gives no data for inputs without data, so there is data where an input has some
813
        let footprints = checked_footprints(expression(true), &[0]).await;
1 ✔
814

815
        assert_eq!(
1 ✔
816
            step_boxes(&footprints),
1 ✔
817
            [[tile_box(0), tile_box(1)].as_slice(), [].as_slice()]
1 ✔
818
        );
1 ✔
819
    }
1 ✔
820

821
    #[tokio::test]
822
    async fn it_expression_that_makes_data_of_no_data_cannot_tell() {
1 ✔
823
        let footprints =
1 ✔
824
            checked_footprints(expression_of("if A IS NODATA { 1 } else { A }", true), &[0]).await;
1 ✔
825

826
        assert_eq!(footprints.len(), 2);
1 ✔
827
        assert!(
1 ✔
828
            footprints
1 ✔
829
                .iter()
1 ✔
830
                .all(|step| step.bounds == FootprintBounds::Unknown)
2 ✔
831
        );
1 ✔
832
    }
1 ✔
833
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc