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

geo-engine / geoengine / 19240886216

10 Nov 2025 05:48PM UTC coverage: 88.94%. First build
19240886216

Pull #1083

github

web-flow
Merge eef5160d4 into 113de40ca
Pull Request #1083: feat: new gdal source workflow optimization

6215 of 7057 new or added lines in 71 files covered. (88.07%)

116335 of 130802 relevant lines covered (88.94%)

496353.73 hits per line

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

91.58
/operators/src/processing/downsample/mod.rs
1
use crate::adapters::{
2
    FoldTileAccu, FoldTileAccuMut, RasterSubQueryAdapter, SubQueryTileAggregator,
3
};
4
use crate::engine::{
5
    CanonicOperatorName, ExecutionContext, InitializedRasterOperator, InitializedSources, Operator,
6
    OperatorName, QueryContext, QueryProcessor, RasterOperator, RasterQueryProcessor,
7
    RasterResultDescriptor, SingleRasterSource, TypedRasterQueryProcessor, WorkflowOperatorPath,
8
};
9
use crate::optimization::{OptimizableOperator, OptimizationError};
10
use crate::util::Result;
11
use async_trait::async_trait;
12
use futures::future::BoxFuture;
13
use futures::stream::BoxStream;
14
use futures::{Future, FutureExt, TryFuture, TryFutureExt};
15
use geoengine_datatypes::primitives::{
16
    BandSelection, CacheHint, Coordinate2D, find_next_best_overview_level_resolution,
17
};
18
use geoengine_datatypes::primitives::{RasterQueryRectangle, SpatialResolution, TimeInterval};
19
use geoengine_datatypes::raster::{
20
    ChangeGridBounds, GeoTransform, GridBoundingBox2D, GridContains, GridIdx2D, GridIndexAccess,
21
    GridOrEmpty, Pixel, RasterTile2D, TileInformation, TilingSpecification,
22
    UpdateIndexedElementsParallel,
23
};
24
use rayon::ThreadPool;
25
use serde::{Deserialize, Serialize};
26
use snafu::{Snafu, ensure};
27
use std::marker::PhantomData;
28
use std::sync::Arc;
29

30
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
31
#[serde(rename_all = "camelCase")]
32
pub struct DownsamplingParams {
33
    pub sampling_method: DownsamplingMethod,
34
    pub output_resolution: DownsamplingResolution,
35
    pub output_origin_reference: Option<Coordinate2D>,
36
}
37

38
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
39
#[serde(rename_all = "camelCase", tag = "type")]
40
pub enum DownsamplingResolution {
41
    Resolution(SpatialResolution),
42
    Fraction { x: f64, y: f64 },
43
}
44

45
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
46
#[serde(rename_all = "camelCase")]
47
pub enum DownsamplingMethod {
48
    NearestNeighbor,
49
    // Mean,
50
}
51

52
#[derive(Debug, Snafu)]
53
#[snafu(visibility(pub(crate)), context(suffix(false)), module(error))]
54
pub enum DownsamplingError {
55
    #[snafu(display("The fraction used to downsample must be >= 1, was {f}."))]
56
    FractionMustBeOneOrLarger { f: f64 },
57
    #[snafu(display("The output resolution must be higher than the input resolution."))]
58
    OutputMustBeLowerResolutionThanInput {
59
        input: SpatialResolution,
60
        output: SpatialResolution,
61
    },
62
}
63

64
pub type Downsampling = Operator<DownsamplingParams, SingleRasterSource>;
65

66
impl OperatorName for Downsampling {
67
    const TYPE_NAME: &'static str = "Downsampling";
68
}
69

70
#[typetag::serde]
×
71
#[async_trait]
72
impl RasterOperator for Downsampling {
73
    async fn _initialize(
74
        self: Box<Self>,
75
        path: WorkflowOperatorPath,
76
        context: &dyn ExecutionContext,
77
    ) -> Result<Box<dyn InitializedRasterOperator>> {
10 ✔
78
        let name = CanonicOperatorName::from(&self);
79
        let initialized_source = self
80
            .sources
81
            .initialize_sources(path.clone(), context)
82
            .await?;
83
        InitializedDownsampling::new_with_source_and_params(
84
            name,
85
            path,
86
            initialized_source.raster,
87
            self.params,
88
            context.tiling_specification(),
89
        )
90
        .map(InitializedRasterOperator::boxed)
91
    }
10 ✔
92

93
    span_fn!(Downsampling);
94
}
95

96
pub struct InitializedDownsampling<O: InitializedRasterOperator> {
97
    name: CanonicOperatorName,
98
    path: WorkflowOperatorPath,
99
    output_result_descriptor: RasterResultDescriptor,
100
    raster_source: O,
101
    sampling_method: DownsamplingMethod,
102
    tiling_specification: TilingSpecification,
103
}
104

105
impl<O: InitializedRasterOperator> InitializedDownsampling<O> {
106
    pub fn new_with_source_and_params(
10 ✔
107
        name: CanonicOperatorName,
10 ✔
108
        path: WorkflowOperatorPath,
10 ✔
109
        raster_source: O,
10 ✔
110
        params: DownsamplingParams,
10 ✔
111
        tiling_specification: TilingSpecification,
10 ✔
112
    ) -> Result<Self> {
10 ✔
113
        let in_descriptor = raster_source.result_descriptor();
10 ✔
114

115
        let in_spatial_grid = in_descriptor.spatial_grid_descriptor();
10 ✔
116

117
        let output_resolution = match params.output_resolution {
10 ✔
118
            DownsamplingResolution::Resolution(res) => {
10 ✔
119
                ensure!(
10 ✔
120
                    res.x.abs() >= in_spatial_grid.spatial_resolution().x.abs(),
10 ✔
121
                    error::OutputMustBeLowerResolutionThanInput {
×
122
                        input: in_spatial_grid.spatial_resolution(),
×
123
                        output: res
×
124
                    }
×
125
                );
126
                ensure!(
10 ✔
127
                    res.y.abs() >= in_spatial_grid.spatial_resolution().y.abs(), // TODO: allow neg y size in SpatialResolution
10 ✔
128
                    error::OutputMustBeLowerResolutionThanInput {
×
129
                        input: in_spatial_grid.spatial_resolution(),
×
130
                        output: res
×
131
                    }
×
132
                );
133
                res
10 ✔
134
            }
135

136
            DownsamplingResolution::Fraction { x, y } => {
×
137
                ensure!(x >= 1.0, error::FractionMustBeOneOrLarger { f: x });
×
138
                ensure!(y >= 1.0, error::FractionMustBeOneOrLarger { f: y });
×
139

140
                SpatialResolution::new_unchecked(
×
141
                    in_spatial_grid.spatial_resolution().x * x,
×
142
                    in_spatial_grid.spatial_resolution().y.abs() * y, // TODO: allow negative size
×
143
                )
144
            }
145
        };
146

147
        let output_gspatial_grid = if let Some(oc) = params.output_origin_reference {
10 ✔
148
            in_spatial_grid
×
149
                .with_moved_origin_to_nearest_grid_edge(oc)
×
150
                .replace_origin(oc)
×
151
                .with_changed_resolution(output_resolution)
×
152
        } else {
153
            in_spatial_grid.with_changed_resolution(output_resolution)
10 ✔
154
        };
155

156
        let out_descriptor = RasterResultDescriptor {
10 ✔
157
            spatial_reference: in_descriptor.spatial_reference,
10 ✔
158
            data_type: in_descriptor.data_type, // TODO: datatype depends on resample method!
10 ✔
159
            time: in_descriptor.time,
10 ✔
160
            spatial_grid: output_gspatial_grid,
10 ✔
161
            bands: in_descriptor.bands.clone(),
10 ✔
162
        };
10 ✔
163

164
        Ok(InitializedDownsampling {
10 ✔
165
            name,
10 ✔
166
            path,
10 ✔
167
            output_result_descriptor: out_descriptor,
10 ✔
168
            raster_source,
10 ✔
169
            sampling_method: params.sampling_method,
10 ✔
170
            tiling_specification,
10 ✔
171
        })
10 ✔
172
    }
10 ✔
173
}
174

175
impl<O: InitializedRasterOperator> InitializedRasterOperator for InitializedDownsampling<O> {
176
    fn query_processor(&self) -> Result<TypedRasterQueryProcessor> {
5 ✔
177
        let source_processor = self.raster_source.query_processor()?;
5 ✔
178

179
        let res = call_on_generic_raster_processor!(
5 ✔
180
            source_processor, p => match self.sampling_method  {
5 ✔
181
                DownsamplingMethod::NearestNeighbor => DownsampleProcessor::<_,_>::new(
5 ✔
182
                        p,
5 ✔
183
                        self.output_result_descriptor.clone(),
5 ✔
184
                        self.tiling_specification,
5 ✔
185
                    ).boxed()
5 ✔
186
                    .into(),
5 ✔
187
            }
188
        );
189

190
        Ok(res)
5 ✔
191
    }
5 ✔
192

193
    fn result_descriptor(&self) -> &RasterResultDescriptor {
13 ✔
194
        &self.output_result_descriptor
13 ✔
195
    }
13 ✔
196

197
    fn canonic_name(&self) -> CanonicOperatorName {
×
198
        self.name.clone()
×
199
    }
×
200

201
    fn name(&self) -> &'static str {
3 ✔
202
        Downsampling::TYPE_NAME
3 ✔
203
    }
3 ✔
204

205
    fn path(&self) -> WorkflowOperatorPath {
3 ✔
206
        self.path.clone()
3 ✔
207
    }
3 ✔
208

209
    fn optimize(
2 ✔
210
        &self,
2 ✔
211
        target_resolution: SpatialResolution,
2 ✔
212
    ) -> Result<Box<dyn RasterOperator>, OptimizationError> {
2 ✔
213
        self.ensure_resolution_is_compatible_for_optimization(target_resolution)?;
2 ✔
214

215
        let out_descriptor = self.result_descriptor();
2 ✔
216
        let in_descriptor = self.raster_source.result_descriptor();
2 ✔
217

218
        let input_resolution = in_descriptor.spatial_grid.spatial_resolution();
2 ✔
219

220
        let new_origin = if in_descriptor.spatial_grid.geo_transform().origin_coordinate
2 ✔
221
            == out_descriptor
2 ✔
222
                .spatial_grid
2 ✔
223
                .geo_transform()
2 ✔
224
                .origin_coordinate
2 ✔
225
        {
226
            None
2 ✔
227
        } else {
NEW
228
            Some(
×
NEW
229
                out_descriptor
×
NEW
230
                    .spatial_grid
×
NEW
231
                    .geo_transform()
×
NEW
232
                    .origin_coordinate,
×
NEW
233
            )
×
234
        };
235

236
        if input_resolution == target_resolution {
2 ✔
237
            // special case where downsampling becomes redundant, unless it also regrids
238

239
            // TODO: source does not need to be optimized, but we need it as an `RasterOperator` and not `InitializedRasterOperator`
NEW
240
            let optimzed_source = self.raster_source.optimize(target_resolution)?;
×
241

NEW
242
            if new_origin.is_some() {
×
NEW
243
                return Ok(Downsampling {
×
NEW
244
                    params: DownsamplingParams {
×
NEW
245
                        sampling_method: self.sampling_method,
×
NEW
246
                        output_resolution: DownsamplingResolution::Resolution(target_resolution),
×
NEW
247
                        output_origin_reference: new_origin,
×
NEW
248
                    },
×
NEW
249
                    sources: SingleRasterSource {
×
NEW
250
                        raster: optimzed_source,
×
NEW
251
                    },
×
NEW
252
                }
×
NEW
253
                .boxed());
×
NEW
254
            }
×
NEW
255
            return Ok(optimzed_source);
×
256
        }
2 ✔
257

258
        // target resolution must be coarser than input
259
        debug_assert!(input_resolution < target_resolution);
2 ✔
260

261
        let snapped_input_resolution =
2 ✔
262
            find_next_best_overview_level_resolution(input_resolution, target_resolution);
2 ✔
263

264
        let optimzed_source = self.raster_source.optimize(snapped_input_resolution)?;
2 ✔
265

266
        Ok(Downsampling {
2 ✔
267
            params: DownsamplingParams {
2 ✔
268
                sampling_method: self.sampling_method,
2 ✔
269
                output_resolution: DownsamplingResolution::Resolution(target_resolution),
2 ✔
270
                output_origin_reference: new_origin,
2 ✔
271
            },
2 ✔
272
            sources: SingleRasterSource {
2 ✔
273
                raster: optimzed_source,
2 ✔
274
            },
2 ✔
275
        }
2 ✔
276
        .boxed())
2 ✔
277
    }
2 ✔
278
}
279

280
pub struct DownsampleProcessor<Q, P>
281
where
282
    Q: RasterQueryProcessor<RasterType = P>,
283
    P: Copy,
284
{
285
    source: Q,
286
    out_result_descriptor: RasterResultDescriptor,
287
    tiling_specification: TilingSpecification,
288
}
289

290
impl<Q, P> DownsampleProcessor<Q, P>
291
where
292
    Q: RasterQueryProcessor<RasterType = P>,
293
    P: Copy,
294
{
295
    pub fn new(
5 ✔
296
        source: Q,
5 ✔
297
        out_result_descriptor: RasterResultDescriptor,
5 ✔
298
        tiling_specification: TilingSpecification,
5 ✔
299
    ) -> Self {
5 ✔
300
        Self {
5 ✔
301
            source,
5 ✔
302
            out_result_descriptor,
5 ✔
303
            tiling_specification,
5 ✔
304
        }
5 ✔
305
    }
5 ✔
306
}
307

308
#[async_trait]
309
impl<Q, P> RasterQueryProcessor for DownsampleProcessor<Q, P>
310
where
311
    Q: RasterQueryProcessor<RasterType = P>,
312
    P: Pixel,
313
{
314
    type RasterType = P;
315

316
    async fn _time_query<'a>(
317
        &'a self,
318
        query: geoengine_datatypes::primitives::TimeInterval,
319
        ctx: &'a dyn QueryContext,
320
    ) -> Result<BoxStream<'a, Result<geoengine_datatypes::primitives::TimeInterval>>> {
2 ✔
321
        self.source.time_query(query, ctx).await
322
    }
2 ✔
323
}
324

325
#[async_trait]
326
impl<Q, P> QueryProcessor for DownsampleProcessor<Q, P>
327
where
328
    Q: RasterQueryProcessor<RasterType = P>,
329
    P: Pixel,
330
{
331
    type Output = RasterTile2D<P>;
332
    type SpatialBounds = GridBoundingBox2D;
333
    type Selection = BandSelection;
334
    type ResultDescription = RasterResultDescriptor;
335

336
    async fn _query<'a>(
337
        &'a self,
338
        query: RasterQueryRectangle,
339
        ctx: &'a dyn QueryContext,
340
    ) -> Result<BoxStream<'a, Result<Self::Output>>> {
5 ✔
341
        // do not interpolate if the source resolution is already fine enough
342

343
        let in_spatial_grid = self.source.result_descriptor().spatial_grid_descriptor();
344
        let out_spatial_grid = self.result_descriptor().spatial_grid_descriptor();
345

346
        // if the output resolution is the same as the input resolution, we can just forward the query // TODO: except the origin changes?
347
        if in_spatial_grid == out_spatial_grid {
348
            return self.source.query(query, ctx).await;
349
        }
350

351
        let tiling_grid_definition =
352
            out_spatial_grid.tiling_grid_definition(ctx.tiling_specification());
353
        // This is the tiling strategy we want to fill
354
        let tiling_strategy: geoengine_datatypes::raster::TilingStrategy =
355
            tiling_grid_definition.generate_data_tiling_strategy();
356

357
        let sub_query = DownsampleSubQuery::<_, P> {
358
            input_geo_transform: in_spatial_grid
359
                .tiling_grid_definition(ctx.tiling_specification())
360
                .tiling_geo_transform(),
361
            output_geo_transform: tiling_grid_definition.tiling_geo_transform(),
362
            fold_fn: fold_future,
363
            tiling_specification: self.tiling_specification,
364
            _phantom_pixel_type: PhantomData,
365
        };
366

367
        let time_stream = self.time_query(query.time_interval(), ctx).await?;
368

369
        Ok(Box::pin(RasterSubQueryAdapter::<'a, P, _, _, _>::new(
370
            &self.source,
371
            query,
372
            tiling_strategy,
373
            ctx,
374
            sub_query,
375
            time_stream,
376
        )))
377
    }
5 ✔
378

379
    fn result_descriptor(&self) -> &RasterResultDescriptor {
26 ✔
380
        &self.out_result_descriptor
26 ✔
381
    }
26 ✔
382
}
383

384
#[derive(Debug, Clone)]
385
pub struct DownsampleSubQuery<F, T> {
386
    input_geo_transform: GeoTransform,
387
    output_geo_transform: GeoTransform,
388
    fold_fn: F,
389
    tiling_specification: TilingSpecification,
390
    _phantom_pixel_type: PhantomData<T>,
391
}
392

393
impl<'a, T, FoldM, FoldF> SubQueryTileAggregator<'a, T> for DownsampleSubQuery<FoldM, T>
394
where
395
    T: Pixel,
396
    FoldM: Send + Sync + 'a + Clone + Fn(DownsampleAccu<T>, RasterTile2D<T>) -> FoldF,
397
    FoldF: Send + TryFuture<Ok = DownsampleAccu<T>, Error = crate::error::Error>,
398
{
399
    type FoldFuture = FoldF;
400

401
    type FoldMethod = FoldM;
402

403
    type TileAccu = DownsampleAccu<T>;
404
    type TileAccuFuture = BoxFuture<'a, Result<Self::TileAccu>>;
405

406
    fn new_fold_accu(
22 ✔
407
        &self,
22 ✔
408
        tile_info: TileInformation,
22 ✔
409
        query_rect: RasterQueryRectangle,
22 ✔
410
        pool: &Arc<ThreadPool>,
22 ✔
411
    ) -> Self::TileAccuFuture {
22 ✔
412
        create_accu(
22 ✔
413
            self.input_geo_transform,
22 ✔
414
            self.output_geo_transform,
22 ✔
415
            tile_info,
22 ✔
416
            &query_rect,
22 ✔
417
            pool.clone(),
22 ✔
418
            self.tiling_specification,
22 ✔
419
        )
22 ✔
420
        .boxed()
22 ✔
421
    }
22 ✔
422

423
    fn tile_query_rectangle(
22 ✔
424
        &self,
22 ✔
425
        tile_info: TileInformation,
22 ✔
426
        _query_rect: RasterQueryRectangle,
22 ✔
427
        time: TimeInterval,
22 ✔
428
        band_idx: u32,
22 ✔
429
    ) -> Result<Option<RasterQueryRectangle>> {
22 ✔
430
        let out_tile_pixel_bounds = tile_info.global_pixel_bounds();
22 ✔
431
        //.intersection(&query_rect.spatial_query.grid_bounds());
432
        //let out_tile_pixel_bounds = out_tile_pixel_bounds;
433
        let out_tile_spatial_bounds = self
22 ✔
434
            .output_geo_transform
22 ✔
435
            .grid_to_spatial_bounds(&out_tile_pixel_bounds);
22 ✔
436
        let input_pixel_bounds = self
22 ✔
437
            .input_geo_transform
22 ✔
438
            .spatial_to_grid_bounds(&out_tile_spatial_bounds);
22 ✔
439

440
        Ok(Some(RasterQueryRectangle::new(
22 ✔
441
            input_pixel_bounds,
22 ✔
442
            time,
22 ✔
443
            BandSelection::new_single(band_idx),
22 ✔
444
        )))
22 ✔
445
    }
22 ✔
446

447
    fn fold_method(&self) -> Self::FoldMethod {
22 ✔
448
        self.fold_fn.clone()
22 ✔
449
    }
22 ✔
450
}
451

452
#[derive(Clone, Debug)]
453
pub struct DownsampleAccu<T: Pixel> {
454
    pub output_tile_info: TileInformation,
455
    pub output_grid: GridOrEmpty<GridBoundingBox2D, T>,
456
    pub input_global_geo_transform: GeoTransform,
457

458
    pub time: Option<TimeInterval>,
459
    pub cache_hint: CacheHint,
460
    pub pool: Arc<ThreadPool>,
461
}
462

463
impl<T: Pixel> DownsampleAccu<T> {
464
    pub fn new(
22 ✔
465
        output_tile_info: TileInformation,
22 ✔
466
        input_global_geo_transform: GeoTransform,
22 ✔
467
        time: Option<TimeInterval>,
22 ✔
468
        cache_hint: CacheHint,
22 ✔
469
        pool: Arc<ThreadPool>,
22 ✔
470
    ) -> Self {
22 ✔
471
        DownsampleAccu {
22 ✔
472
            output_tile_info,
22 ✔
473
            output_grid: GridOrEmpty::new_empty_shape(output_tile_info.global_pixel_bounds()),
22 ✔
474
            input_global_geo_transform,
22 ✔
475
            time,
22 ✔
476
            cache_hint,
22 ✔
477
            pool,
22 ✔
478
        }
22 ✔
479
    }
22 ✔
480
}
481

482
#[async_trait]
483
impl<T: Pixel> FoldTileAccu for DownsampleAccu<T> {
484
    type RasterType = T;
485

486
    async fn into_tile(self) -> Result<RasterTile2D<Self::RasterType>> {
22 ✔
487
        // TODO: later do conversation of accu into tile here
488

489
        let output_tile = RasterTile2D::new_with_tile_info(
490
            self.time.expect("there is at least one input"),
491
            self.output_tile_info,
492
            0, // TODO: need band?
493
            self.output_grid.unbounded(),
494
            self.cache_hint,
495
        );
496

497
        Ok(output_tile)
498
    }
22 ✔
499

500
    fn thread_pool(&self) -> &Arc<ThreadPool> {
×
501
        &self.pool
×
502
    }
×
503
}
504

505
impl<T: Pixel> FoldTileAccuMut for DownsampleAccu<T> {
506
    fn set_time(&mut self, time: TimeInterval) {
102 ✔
507
        self.time = Some(time);
102 ✔
508
    }
102 ✔
509

510
    fn set_cache_hint(&mut self, cache_hint: CacheHint) {
×
511
        self.cache_hint = cache_hint;
×
512
    }
×
513
}
514

515
pub fn create_accu<T: Pixel>(
22 ✔
516
    input_geo_transform: GeoTransform,
22 ✔
517
    _output_geo_transform: GeoTransform,
22 ✔
518
    tile_info: TileInformation,
22 ✔
519
    _query_rect: &RasterQueryRectangle,
22 ✔
520
    pool: Arc<ThreadPool>,
22 ✔
521
    _tiling_specification: TilingSpecification,
22 ✔
522
) -> impl Future<Output = Result<DownsampleAccu<T>>> + use<T> {
22 ✔
523
    crate::util::spawn_blocking(move || {
22 ✔
524
        DownsampleAccu::new(
22 ✔
525
            tile_info,
22 ✔
526
            input_geo_transform,
22 ✔
527
            None,
22 ✔
528
            CacheHint::max_duration(),
22 ✔
529
            pool.clone(),
22 ✔
530
        )
531
    })
22 ✔
532
    .map_err(From::from)
22 ✔
533
}
22 ✔
534

535
pub fn fold_future<T>(
102 ✔
536
    accu: DownsampleAccu<T>,
102 ✔
537
    tile: RasterTile2D<T>,
102 ✔
538
) -> impl Future<Output = Result<DownsampleAccu<T>>>
102 ✔
539
where
102 ✔
540
    T: Pixel,
102 ✔
541
{
542
    crate::util::spawn_blocking_with_thread_pool(accu.pool.clone(), || fold_impl(accu, tile)).then(
102 ✔
543
        |x| async move {
102 ✔
544
            match x {
102 ✔
545
                Ok(r) => Ok(r),
102 ✔
546
                Err(e) => Err(e.into()),
×
547
            }
548
        },
204 ✔
549
    )
550
}
102 ✔
551

552
pub fn fold_impl<T>(mut accu: DownsampleAccu<T>, tile: RasterTile2D<T>) -> DownsampleAccu<T>
102 ✔
553
where
102 ✔
554
    T: Pixel,
102 ✔
555
{
556
    // get the time now because it is not known when the accu was created
557
    accu.set_time(tile.time);
102 ✔
558
    accu.cache_hint.merge_with(&tile.cache_hint);
102 ✔
559

560
    // TODO: add a skip if both tiles are empty?
561
    if tile.is_empty() {
102 ✔
562
        // TODO: and ignore no-data.
563
        return accu;
64 ✔
564
    }
38 ✔
565

566
    // copy all input tiles into the accu to have all data for interpolation
567
    let mut accu_tile = accu.output_grid.into_materialized_masked_grid();
38 ✔
568
    let in_tile_grid = tile.into_inner_positioned_grid();
38 ✔
569
    let accu_geo_transform = accu.output_tile_info.global_geo_transform;
38 ✔
570
    let in_geo_transform = accu.input_global_geo_transform;
38 ✔
571

572
    let map_fn = |grid_idx: GridIdx2D, current_value: Option<T>| -> Option<T> {
8,119,441 ✔
573
        let accu_pixel_coord = accu_geo_transform.grid_idx_to_pixel_center_coordinate_2d(grid_idx); // use center coordinate similar to ArcGIS
8,119,441 ✔
574
        let source_pixel_idx = in_geo_transform.coordinate_to_grid_idx_2d(accu_pixel_coord);
8,119,441 ✔
575

576
        if in_tile_grid.contains(&source_pixel_idx) {
8,119,441 ✔
577
            in_tile_grid.get_at_grid_index_unchecked(source_pixel_idx)
3,143,720 ✔
578
        } else {
579
            current_value
4,975,721 ✔
580
        }
581
    };
8,119,441 ✔
582

583
    accu_tile.update_indexed_elements_parallel(map_fn);
38 ✔
584

585
    accu.output_grid = accu_tile.into();
38 ✔
586

587
    accu
38 ✔
588
}
102 ✔
589

590
#[cfg(test)]
591
mod tests {
592
    use super::*;
593
    use crate::engine::{
594
        ChunkByteSize, MockExecutionContext, RasterBandDescriptors, SpatialGridDescriptor,
595
        TimeDescriptor,
596
    };
597
    use crate::mock::{MockRasterSource, MockRasterSourceParams};
598
    use futures::StreamExt;
599
    use geoengine_datatypes::primitives::TimeStep;
600
    use geoengine_datatypes::raster::{Grid, GridShape2D, RasterDataType};
601
    use geoengine_datatypes::spatial_reference::SpatialReference;
602
    use geoengine_datatypes::util::test::TestDefault;
603

604
    #[allow(clippy::too_many_lines)]
605
    #[tokio::test]
606
    async fn nearest_neighbor_4() {
1 ✔
607
        // In this test, 2x2 tiles with 4x4 pixels are downsampled using nearest neighbor to one tile with 4x4 pixels. The resolution is now 1/2 of the original resolution.
608
        // The test uses the following input:
609
        //
610
        // _1, _2, _3, _4 | 21, 22, 23, 24
611
        // _5, _6, _7, _8 | 25, 26, 27, 28
612
        // _9, 10, 11, 12 | 29, 30, 31, 32
613
        // 13, 14, 15, 16 | 33, 34, 35, 36
614
        // ---------------+---------------
615
        // 41, 42, 43, 44 | 61, 62, 63, 64
616
        // 45, 46, 47, 48 | 65, 66, 67, 68
617
        // 49, 50, 51, 52 | 69, 70, 71, 72
618
        // 53, 54, 55, 56 | 73, 74, 75, 76
619
        //
620
        // The input is downsampled to:
621
        //
622
        // _6. _8, 26, 28
623
        // 14, 16, 33, 36
624
        // 46, 48, 66, 68
625
        // 54, 56, 74, 76
626
        //
627
        // The center of each pixel is mapped to a coordinate. Then, for this coordinate the nearest pixel center is selected.
628
        // In this case, we have the special case that the pixel center of the target pixel hits the edge between two original pixels.
629
        // The pixel which "owns" the edge is selected because pixels are defiend from the upper left edge.
630
        // E.g. _6 is selected for the first pixel since it owns the edge between _1, _2, _5_ and _6.
631

632
        let in_geo_transform = GeoTransform::new(Coordinate2D::new(0.0, 0.0), 1.0, -1.0);
1 ✔
633
        let out_geo_transform = GeoTransform::new(Coordinate2D::new(0.0, 0.0), 2.0, -2.0);
1 ✔
634
        let tile_size_in_pixels = GridShape2D {
1 ✔
635
            shape_array: [4, 4],
1 ✔
636
        };
1 ✔
637

638
        let exe_ctx = MockExecutionContext::new_with_tiling_spec_and_thread_count(
1 ✔
639
            TilingSpecification::new(tile_size_in_pixels),
1 ✔
640
            8,
641
        );
642

643
        let data: Vec<RasterTile2D<u8>> = vec![
1 ✔
644
            RasterTile2D {
1 ✔
645
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
646
                tile_position: [0, 0].into(),
1 ✔
647
                band: 0,
1 ✔
648
                global_geo_transform: in_geo_transform,
1 ✔
649
                grid_array: Grid::new(
1 ✔
650
                    tile_size_in_pixels,
1 ✔
651
                    vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
1 ✔
652
                )
1 ✔
653
                .unwrap()
1 ✔
654
                .into(),
1 ✔
655
                properties: Default::default(),
1 ✔
656
                cache_hint: CacheHint::default(),
1 ✔
657
            },
1 ✔
658
            RasterTile2D {
1 ✔
659
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
660
                tile_position: [0, 1].into(),
1 ✔
661
                band: 0,
1 ✔
662
                global_geo_transform: in_geo_transform,
1 ✔
663
                grid_array: Grid::new(
1 ✔
664
                    tile_size_in_pixels,
1 ✔
665
                    vec![
1 ✔
666
                        21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
1 ✔
667
                    ],
1 ✔
668
                )
1 ✔
669
                .unwrap()
1 ✔
670
                .into(),
1 ✔
671
                properties: Default::default(),
1 ✔
672
                cache_hint: CacheHint::default(),
1 ✔
673
            },
1 ✔
674
            RasterTile2D {
1 ✔
675
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
676
                tile_position: [1, 0].into(),
1 ✔
677
                band: 0,
1 ✔
678
                global_geo_transform: in_geo_transform,
1 ✔
679
                grid_array: Grid::new(
1 ✔
680
                    tile_size_in_pixels,
1 ✔
681
                    vec![
1 ✔
682
                        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
1 ✔
683
                    ],
1 ✔
684
                )
1 ✔
685
                .unwrap()
1 ✔
686
                .into(),
1 ✔
687
                properties: Default::default(),
1 ✔
688
                cache_hint: CacheHint::default(),
1 ✔
689
            },
1 ✔
690
            RasterTile2D {
1 ✔
691
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
692
                tile_position: [1, 1].into(),
1 ✔
693
                band: 0,
1 ✔
694
                global_geo_transform: in_geo_transform,
1 ✔
695
                grid_array: Grid::new(
1 ✔
696
                    tile_size_in_pixels,
1 ✔
697
                    vec![
1 ✔
698
                        61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
1 ✔
699
                    ],
1 ✔
700
                )
1 ✔
701
                .unwrap()
1 ✔
702
                .into(),
1 ✔
703
                properties: Default::default(),
1 ✔
704
                cache_hint: CacheHint::default(),
1 ✔
705
            },
1 ✔
706
        ];
707

708
        let result_descriptor = RasterResultDescriptor {
1 ✔
709
            data_type: RasterDataType::U8,
1 ✔
710
            spatial_reference: SpatialReference::epsg_4326().into(),
1 ✔
711
            time: TimeDescriptor::new_regular_with_epoch(
1 ✔
712
                Some(
1 ✔
713
                    TimeInterval::new(
1 ✔
714
                        data.first().unwrap().time.start(),
1 ✔
715
                        data.last().unwrap().time.end(),
1 ✔
716
                    )
1 ✔
717
                    .unwrap(),
1 ✔
718
                ),
1 ✔
719
                TimeStep::millis(5),
1 ✔
720
            ),
1 ✔
721
            spatial_grid: SpatialGridDescriptor::source_from_parts(
1 ✔
722
                in_geo_transform,
1 ✔
723
                GridBoundingBox2D::new_min_max(0, 7, 0, 7).unwrap(),
1 ✔
724
            ),
1 ✔
725
            bands: RasterBandDescriptors::new_single_band(),
1 ✔
726
        };
1 ✔
727

728
        let mrs1 = MockRasterSource {
1 ✔
729
            params: MockRasterSourceParams {
1 ✔
730
                data: data.clone(),
1 ✔
731
                result_descriptor: result_descriptor.clone(),
1 ✔
732
            },
1 ✔
733
        }
1 ✔
734
        .boxed();
1 ✔
735

736
        let downsampler = Downsampling {
1 ✔
737
            params: DownsamplingParams {
1 ✔
738
                sampling_method: DownsamplingMethod::NearestNeighbor,
1 ✔
739
                output_origin_reference: None,
1 ✔
740
                output_resolution: DownsamplingResolution::Resolution(SpatialResolution {
1 ✔
741
                    x: out_geo_transform.x_pixel_size(),
1 ✔
742
                    y: out_geo_transform.y_pixel_size().abs(),
1 ✔
743
                }),
1 ✔
744
            },
1 ✔
745
            sources: SingleRasterSource { raster: mrs1 },
1 ✔
746
        }
1 ✔
747
        .boxed();
1 ✔
748

749
        let query_rect = RasterQueryRectangle::new(
1 ✔
750
            GridBoundingBox2D::new_min_max(0, 3, 0, 3).unwrap(),
1 ✔
751
            TimeInterval::new_unchecked(0, 5),
1 ✔
752
            [0].try_into().unwrap(),
1 ✔
753
        );
754

755
        let query_ctx = exe_ctx.mock_query_context(ChunkByteSize::test_default());
1 ✔
756

757
        let op = downsampler
1 ✔
758
            .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1 ✔
759
            .await
1 ✔
760
            .unwrap();
1 ✔
761

762
        let qp = op.query_processor().unwrap().get_u8().unwrap();
1 ✔
763

764
        let result = qp
1 ✔
765
            .raster_query(query_rect, &query_ctx)
1 ✔
766
            .await
1 ✔
767
            .unwrap()
1 ✔
768
            .collect::<Vec<_>>()
1 ✔
769
            .await;
1 ✔
770

771
        assert_eq!(result.len(), 1);
1 ✔
772

773
        let tile = result[0].as_ref().unwrap();
1 ✔
774
        let grid = tile.grid_array.clone().into_materialized_masked_grid();
1 ✔
775
        // _6. _8, 26, 28
776
        // 14, 16, 33, 36
777
        // 46, 48, 66, 68
778
        // 54, 56, 74, 76
779
        assert_eq!(
1 ✔
780
            grid.inner_grid.data,
1 ✔
781
            &[6, 8, 26, 28, 14, 16, 34, 36, 46, 48, 66, 68, 54, 56, 74, 76]
1 ✔
782
        );
1 ✔
783
    }
1 ✔
784

785
    #[allow(clippy::too_many_lines)]
786
    #[tokio::test]
787
    async fn nearest_neighbor_3() {
1 ✔
788
        // In this test, 3x3 tiles with 3x3 pixels are downsampled using nearest neighbor to one tile with 3x3 pixels. The resolution is now 1/3 of the original resolution.
789
        // The test uses the following input:
790
        //
791
        // _0, _1, _2 | 10, 11, 12 | 20, 21, 22
792
        // _3, _4, _5 | 13, 14, 15 | 23, 24, 25
793
        // _6, _7, _8 | 16, 17, 18 | 26, 27, 28
794
        // -----------+------------+-----------
795
        // 30, 31, 32 | 40, 41, 42 | 50, 51, 52
796
        // 33, 34, 35 | 43, 44, 45 | 53, 54, 55
797
        // 36, 37, 38 | 46, 47, 48 | 56, 57, 58
798
        // -----------+------------+-----------
799
        // 60, 61, 62 | 70, 71, 72 | 80, 81, 82
800
        // 63, 64, 65 | 73, 74, 75 | 83, 84, 85
801
        // 66, 67, 68 | 76, 77, 78 | 86, 87, 88
802
        //
803
        // The input is downsampled to:
804
        //
805
        // _4. 14, 24
806
        // 34, 44, 54
807
        // 64, 74, 84
808
        //
809
        // The center of each pixel is mapped to a coordinate. Then, for this coordinate the nearest pixel center is selected.
810
        // In this case, each pixel corresponds to the center of the corresponding tile.
811
        // E.g. _4 is selected for the first pixel since it is in the center of the tile.
812

813
        let in_geo_transform = GeoTransform::new(Coordinate2D::new(0.0, 0.0), 1.0, -1.0);
1 ✔
814
        let out_geo_transform = GeoTransform::new(Coordinate2D::new(0.0, 0.0), 3.0, -3.0);
1 ✔
815
        let tile_size_in_pixels = GridShape2D {
1 ✔
816
            shape_array: [3, 3],
1 ✔
817
        };
1 ✔
818

819
        let exe_ctx = MockExecutionContext::new_with_tiling_spec_and_thread_count(
1 ✔
820
            TilingSpecification::new(tile_size_in_pixels),
1 ✔
821
            8,
822
        );
823

824
        let data: Vec<RasterTile2D<u8>> = vec![
1 ✔
825
            RasterTile2D {
1 ✔
826
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
827
                tile_position: [0, 0].into(),
1 ✔
828
                band: 0,
1 ✔
829
                global_geo_transform: in_geo_transform,
1 ✔
830
                grid_array: Grid::new(tile_size_in_pixels, vec![0, 1, 2, 3, 4, 5, 6, 7, 8])
1 ✔
831
                    .unwrap()
1 ✔
832
                    .into(),
1 ✔
833
                properties: Default::default(),
1 ✔
834
                cache_hint: CacheHint::default(),
1 ✔
835
            },
1 ✔
836
            RasterTile2D {
1 ✔
837
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
838
                tile_position: [0, 1].into(),
1 ✔
839
                band: 0,
1 ✔
840
                global_geo_transform: in_geo_transform,
1 ✔
841
                grid_array: Grid::new(
1 ✔
842
                    tile_size_in_pixels,
1 ✔
843
                    vec![10, 11, 12, 13, 14, 15, 16, 17, 18],
1 ✔
844
                )
1 ✔
845
                .unwrap()
1 ✔
846
                .into(),
1 ✔
847
                properties: Default::default(),
1 ✔
848
                cache_hint: CacheHint::default(),
1 ✔
849
            },
1 ✔
850
            RasterTile2D {
1 ✔
851
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
852
                tile_position: [0, 2].into(),
1 ✔
853
                band: 0,
1 ✔
854
                global_geo_transform: in_geo_transform,
1 ✔
855
                grid_array: Grid::new(
1 ✔
856
                    tile_size_in_pixels,
1 ✔
857
                    vec![20, 21, 22, 23, 24, 25, 26, 27, 28],
1 ✔
858
                )
1 ✔
859
                .unwrap()
1 ✔
860
                .into(),
1 ✔
861
                properties: Default::default(),
1 ✔
862
                cache_hint: CacheHint::default(),
1 ✔
863
            },
1 ✔
864
            RasterTile2D {
1 ✔
865
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
866
                tile_position: [1, 0].into(),
1 ✔
867
                band: 0,
1 ✔
868
                global_geo_transform: in_geo_transform,
1 ✔
869
                grid_array: Grid::new(
1 ✔
870
                    tile_size_in_pixels,
1 ✔
871
                    vec![30, 31, 32, 33, 34, 35, 36, 37, 38],
1 ✔
872
                )
1 ✔
873
                .unwrap()
1 ✔
874
                .into(),
1 ✔
875
                properties: Default::default(),
1 ✔
876
                cache_hint: CacheHint::default(),
1 ✔
877
            },
1 ✔
878
            RasterTile2D {
1 ✔
879
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
880
                tile_position: [1, 1].into(),
1 ✔
881
                band: 0,
1 ✔
882
                global_geo_transform: in_geo_transform,
1 ✔
883
                grid_array: Grid::new(
1 ✔
884
                    tile_size_in_pixels,
1 ✔
885
                    vec![40, 41, 42, 43, 44, 45, 46, 47, 48],
1 ✔
886
                )
1 ✔
887
                .unwrap()
1 ✔
888
                .into(),
1 ✔
889
                properties: Default::default(),
1 ✔
890
                cache_hint: CacheHint::default(),
1 ✔
891
            },
1 ✔
892
            RasterTile2D {
1 ✔
893
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
894
                tile_position: [1, 2].into(),
1 ✔
895
                band: 0,
1 ✔
896
                global_geo_transform: in_geo_transform,
1 ✔
897
                grid_array: Grid::new(
1 ✔
898
                    tile_size_in_pixels,
1 ✔
899
                    vec![50, 51, 52, 53, 54, 55, 56, 57, 58],
1 ✔
900
                )
1 ✔
901
                .unwrap()
1 ✔
902
                .into(),
1 ✔
903
                properties: Default::default(),
1 ✔
904
                cache_hint: CacheHint::default(),
1 ✔
905
            },
1 ✔
906
            RasterTile2D {
1 ✔
907
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
908
                tile_position: [2, 0].into(),
1 ✔
909
                band: 0,
1 ✔
910
                global_geo_transform: in_geo_transform,
1 ✔
911
                grid_array: Grid::new(
1 ✔
912
                    tile_size_in_pixels,
1 ✔
913
                    vec![60, 61, 62, 63, 64, 65, 66, 67, 68],
1 ✔
914
                )
1 ✔
915
                .unwrap()
1 ✔
916
                .into(),
1 ✔
917
                properties: Default::default(),
1 ✔
918
                cache_hint: CacheHint::default(),
1 ✔
919
            },
1 ✔
920
            RasterTile2D {
1 ✔
921
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
922
                tile_position: [2, 1].into(),
1 ✔
923
                band: 0,
1 ✔
924
                global_geo_transform: in_geo_transform,
1 ✔
925
                grid_array: Grid::new(
1 ✔
926
                    tile_size_in_pixels,
1 ✔
927
                    vec![70, 71, 72, 73, 74, 75, 76, 77, 78],
1 ✔
928
                )
1 ✔
929
                .unwrap()
1 ✔
930
                .into(),
1 ✔
931
                properties: Default::default(),
1 ✔
932
                cache_hint: CacheHint::default(),
1 ✔
933
            },
1 ✔
934
            RasterTile2D {
1 ✔
935
                time: TimeInterval::new_unchecked(0, 5),
1 ✔
936
                tile_position: [2, 2].into(),
1 ✔
937
                band: 0,
1 ✔
938
                global_geo_transform: in_geo_transform,
1 ✔
939
                grid_array: Grid::new(
1 ✔
940
                    tile_size_in_pixels,
1 ✔
941
                    vec![80, 81, 82, 83, 84, 85, 86, 87, 88],
1 ✔
942
                )
1 ✔
943
                .unwrap()
1 ✔
944
                .into(),
1 ✔
945
                properties: Default::default(),
1 ✔
946
                cache_hint: CacheHint::default(),
1 ✔
947
            },
1 ✔
948
        ];
949

950
        let result_descriptor = RasterResultDescriptor {
1 ✔
951
            data_type: RasterDataType::U8,
1 ✔
952
            spatial_reference: SpatialReference::epsg_4326().into(),
1 ✔
953
            time: TimeDescriptor::new_regular_with_epoch(
1 ✔
954
                Some(
1 ✔
955
                    TimeInterval::new(
1 ✔
956
                        data.first().unwrap().time.start(),
1 ✔
957
                        data.last().unwrap().time.end(),
1 ✔
958
                    )
1 ✔
959
                    .unwrap(),
1 ✔
960
                ),
1 ✔
961
                TimeStep::millis(5),
1 ✔
962
            ),
1 ✔
963
            spatial_grid: SpatialGridDescriptor::source_from_parts(
1 ✔
964
                in_geo_transform,
1 ✔
965
                GridBoundingBox2D::new_min_max(0, 8, 0, 8).unwrap(),
1 ✔
966
            ),
1 ✔
967
            bands: RasterBandDescriptors::new_single_band(),
1 ✔
968
        };
1 ✔
969

970
        let mrs1 = MockRasterSource {
1 ✔
971
            params: MockRasterSourceParams {
1 ✔
972
                data: data.clone(),
1 ✔
973
                result_descriptor: result_descriptor.clone(),
1 ✔
974
            },
1 ✔
975
        }
1 ✔
976
        .boxed();
1 ✔
977

978
        let downsampler = Downsampling {
1 ✔
979
            params: DownsamplingParams {
1 ✔
980
                sampling_method: DownsamplingMethod::NearestNeighbor,
1 ✔
981
                output_origin_reference: None,
1 ✔
982
                output_resolution: DownsamplingResolution::Resolution(SpatialResolution {
1 ✔
983
                    x: out_geo_transform.x_pixel_size(),
1 ✔
984
                    y: out_geo_transform.y_pixel_size().abs(),
1 ✔
985
                }),
1 ✔
986
            },
1 ✔
987
            sources: SingleRasterSource { raster: mrs1 },
1 ✔
988
        }
1 ✔
989
        .boxed();
1 ✔
990

991
        let query_rect = RasterQueryRectangle::new(
1 ✔
992
            GridBoundingBox2D::new_min_max(0, 2, 0, 2).unwrap(),
1 ✔
993
            TimeInterval::new_unchecked(0, 5),
1 ✔
994
            [0].try_into().unwrap(),
1 ✔
995
        );
996

997
        let query_ctx = exe_ctx.mock_query_context(ChunkByteSize::test_default());
1 ✔
998

999
        let op = downsampler
1 ✔
1000
            .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1 ✔
1001
            .await
1 ✔
1002
            .unwrap();
1 ✔
1003

1004
        let qp = op.query_processor().unwrap().get_u8().unwrap();
1 ✔
1005

1006
        let result = qp
1 ✔
1007
            .raster_query(query_rect, &query_ctx)
1 ✔
1008
            .await
1 ✔
1009
            .unwrap()
1 ✔
1010
            .collect::<Vec<_>>()
1 ✔
1011
            .await;
1 ✔
1012

1013
        assert_eq!(result.len(), 1);
1 ✔
1014

1015
        let tile = result[0].as_ref().unwrap();
1 ✔
1016
        let grid = tile.grid_array.clone().into_materialized_masked_grid();
1 ✔
1017
        // _4. 14, 24
1018
        // 34, 44, 54
1019
        // 64, 74, 84
1020

1021
        assert_eq!(grid.inner_grid.data, &[4, 14, 24, 34, 44, 54, 64, 74, 84]);
1 ✔
1022
    }
1 ✔
1023
}
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