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

geo-engine / geoengine / 16167706152

09 Jul 2025 11:08AM UTC coverage: 88.738% (-1.0%) from 89.762%
16167706152

push

github

web-flow
refactor: Updates-2025-07-02 (#1062)

* rust 1.88

* clippy auto-fixes

* manual clippy fixes

* update deps

* cargo update

* update onnx

* cargo fmt

* update sqlfluff

121 of 142 new or added lines in 29 files covered. (85.21%)

300 existing lines in 88 files now uncovered.

111259 of 125379 relevant lines covered (88.74%)

77910.92 hits per line

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

86.45
/operators/src/processing/reprojection.rs
1
use std::marker::PhantomData;
2

3
use super::map_query::MapQueryProcessor;
4
use crate::{
5
    adapters::{
6
        FillerTileCacheExpirationStrategy, FillerTimeBounds, RasterSubQueryAdapter,
7
        SparseTilesFillAdapter, TileReprojectionSubQuery, fold_by_coordinate_lookup_future,
8
    },
9
    engine::{
10
        CanonicOperatorName, ExecutionContext, InitializedRasterOperator, InitializedSources,
11
        InitializedVectorOperator, Operator, OperatorName, QueryContext, QueryProcessor,
12
        RasterOperator, RasterQueryProcessor, RasterResultDescriptor, SingleRasterOrVectorSource,
13
        TypedRasterQueryProcessor, TypedVectorQueryProcessor, VectorOperator, VectorQueryProcessor,
14
        VectorResultDescriptor, WorkflowOperatorPath,
15
    },
16
    error::{self, Error},
17
    util::Result,
18
};
19
use async_trait::async_trait;
20
use futures::stream::BoxStream;
21
use futures::{StreamExt, stream};
22
use geoengine_datatypes::{
23
    collections::FeatureCollection,
24
    operations::reproject::{
25
        CoordinateProjection, CoordinateProjector, Reproject, ReprojectClipped,
26
        reproject_and_unify_bbox, reproject_query, suggest_pixel_size_from_diag_cross_projected,
27
    },
28
    primitives::{
29
        BandSelection, BoundingBox2D, ColumnSelection, Geometry, RasterQueryRectangle,
30
        SpatialPartition2D, SpatialPartitioned, SpatialResolution, VectorQueryRectangle,
31
    },
32
    raster::{Pixel, RasterTile2D, TilingSpecification},
33
    spatial_reference::SpatialReference,
34
    util::arrow::ArrowTyped,
35
};
36
use serde::{Deserialize, Serialize};
37

38
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
39
#[serde(rename_all = "camelCase")]
40
pub struct ReprojectionParams {
41
    pub target_spatial_reference: SpatialReference,
42
}
43

44
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
45
pub struct ReprojectionBounds {
46
    valid_in_bounds: SpatialPartition2D,
47
    valid_out_bounds: SpatialPartition2D,
48
}
49

50
pub type Reprojection = Operator<ReprojectionParams, SingleRasterOrVectorSource>;
51

52
impl Reprojection {}
53

54
impl OperatorName for Reprojection {
55
    const TYPE_NAME: &'static str = "Reprojection";
56
}
57

58
pub struct InitializedVectorReprojection {
59
    name: CanonicOperatorName,
60
    path: WorkflowOperatorPath,
61
    result_descriptor: VectorResultDescriptor,
62
    source: Box<dyn InitializedVectorOperator>,
63
    source_srs: SpatialReference,
64
    target_srs: SpatialReference,
65
}
66

67
pub struct InitializedRasterReprojection {
68
    name: CanonicOperatorName,
69
    path: WorkflowOperatorPath,
70
    result_descriptor: RasterResultDescriptor,
71
    source: Box<dyn InitializedRasterOperator>,
72
    state: Option<ReprojectionBounds>,
73
    source_srs: SpatialReference,
74
    target_srs: SpatialReference,
75
    tiling_spec: TilingSpecification,
76
}
77

78
impl InitializedVectorReprojection {
79
    /// Create a new `InitializedVectorReprojection` instance.
80
    /// The `source` must have the same `SpatialReference` as `source_srs`.
81
    ///
82
    /// # Errors
83
    /// This function errors if the `source`'s `SpatialReference` is `None`.
84
    /// This function errors if the source's bounding box cannot be reprojected to the target's `SpatialReference`.
85
    pub fn try_new_with_input(
6✔
86
        name: CanonicOperatorName,
6✔
87
        path: WorkflowOperatorPath,
6✔
88
        params: ReprojectionParams,
6✔
89
        source_vector_operator: Box<dyn InitializedVectorOperator>,
6✔
90
    ) -> Result<Self> {
6✔
91
        let in_desc: VectorResultDescriptor = source_vector_operator.result_descriptor().clone();
6✔
92

93
        let in_srs = Into::<Option<SpatialReference>>::into(in_desc.spatial_reference)
6✔
94
            .ok_or(Error::AllSourcesMustHaveSameSpatialReference)?;
6✔
95

96
        let bbox = if let Some(bbox) = in_desc.bbox {
6✔
97
            let projector =
×
98
                CoordinateProjector::from_known_srs(in_srs, params.target_spatial_reference)?;
×
99

100
            bbox.reproject_clipped(&projector)? // TODO: if this is none then we could skip the whole reprojection similar to raster?
×
101
        } else {
102
            None
6✔
103
        };
104

105
        let out_desc = VectorResultDescriptor {
6✔
106
            spatial_reference: params.target_spatial_reference.into(),
6✔
107
            data_type: in_desc.data_type,
6✔
108
            columns: in_desc.columns.clone(),
6✔
109
            time: in_desc.time,
6✔
110
            bbox,
6✔
111
        };
6✔
112

113
        Ok(InitializedVectorReprojection {
6✔
114
            name,
6✔
115
            path,
6✔
116
            result_descriptor: out_desc,
6✔
117
            source: source_vector_operator,
6✔
118
            source_srs: in_srs,
6✔
119
            target_srs: params.target_spatial_reference,
6✔
120
        })
6✔
121
    }
6✔
122
}
123

124
impl InitializedRasterReprojection {
125
    pub fn try_new_with_input(
6✔
126
        name: CanonicOperatorName,
6✔
127
        path: WorkflowOperatorPath,
6✔
128
        params: ReprojectionParams,
6✔
129
        source_raster_operator: Box<dyn InitializedRasterOperator>,
6✔
130
        tiling_spec: TilingSpecification,
6✔
131
    ) -> Result<Self> {
6✔
132
        let in_desc: RasterResultDescriptor = source_raster_operator.result_descriptor().clone();
6✔
133

134
        let in_srs = Into::<Option<SpatialReference>>::into(in_desc.spatial_reference)
6✔
135
            .ok_or(Error::AllSourcesMustHaveSameSpatialReference)?;
6✔
136

137
        // calculate the intersection of input and output srs in both coordinate systems
138
        let (in_bounds, out_bounds, out_res) = Self::derive_raster_in_bounds_out_bounds_out_res(
6✔
139
            in_srs,
6✔
140
            params.target_spatial_reference,
6✔
141
            in_desc.resolution,
6✔
142
            in_desc.bbox,
6✔
143
        )?;
2✔
144

145
        let result_descriptor = RasterResultDescriptor {
4✔
146
            spatial_reference: params.target_spatial_reference.into(),
4✔
147
            data_type: in_desc.data_type,
4✔
148
            time: in_desc.time,
4✔
149
            bbox: out_bounds,
4✔
150
            resolution: out_res,
4✔
151
            bands: in_desc.bands.clone(),
4✔
152
        };
4✔
153

154
        let state = match (in_bounds, out_bounds) {
4✔
155
            (Some(in_bounds), Some(out_bounds)) => Some(ReprojectionBounds {
4✔
156
                valid_in_bounds: in_bounds,
4✔
157
                valid_out_bounds: out_bounds,
4✔
158
            }),
4✔
159
            _ => None,
×
160
        };
161

162
        Ok(InitializedRasterReprojection {
4✔
163
            name,
4✔
164
            path,
4✔
165
            result_descriptor,
4✔
166
            source: source_raster_operator,
4✔
167
            state,
4✔
168
            source_srs: in_srs,
4✔
169
            target_srs: params.target_spatial_reference,
4✔
170
            tiling_spec,
4✔
171
        })
4✔
172
    }
6✔
173

174
    fn derive_raster_in_bounds_out_bounds_out_res(
7✔
175
        source_srs: SpatialReference,
7✔
176
        target_srs: SpatialReference,
7✔
177
        source_spatial_resolution: Option<SpatialResolution>,
7✔
178
        source_bbox: Option<SpatialPartition2D>,
7✔
179
    ) -> Result<(
7✔
180
        Option<SpatialPartition2D>,
7✔
181
        Option<SpatialPartition2D>,
7✔
182
        Option<SpatialResolution>,
7✔
183
    )> {
7✔
184
        let (in_bbox, out_bbox) = if let Some(bbox) = source_bbox {
7✔
185
            reproject_and_unify_bbox(bbox, source_srs, target_srs)?
4✔
186
        } else {
187
            // use the parts of the area of use that are valid in both spatial references
188
            let valid_bounds_in = source_srs.area_of_use_intersection(&target_srs)?;
3✔
189
            let valid_bounds_out = target_srs.area_of_use_intersection(&source_srs)?;
3✔
190

191
            (valid_bounds_in, valid_bounds_out)
3✔
192
        };
193

194
        let out_res = match (source_spatial_resolution, in_bbox, out_bbox) {
5✔
195
            (Some(in_res), Some(in_bbox), Some(out_bbox)) => {
3✔
196
                suggest_pixel_size_from_diag_cross_projected(in_bbox, out_bbox, in_res).ok()
3✔
197
            }
198
            _ => None,
2✔
199
        };
200

201
        Ok((in_bbox, out_bbox, out_res))
5✔
202
    }
7✔
203
}
204

205
#[typetag::serde]
×
206
#[async_trait]
207
impl VectorOperator for Reprojection {
208
    async fn _initialize(
209
        self: Box<Self>,
210
        path: WorkflowOperatorPath,
211
        context: &dyn ExecutionContext,
212
    ) -> Result<Box<dyn InitializedVectorOperator>> {
14✔
213
        let name = CanonicOperatorName::from(&self);
7✔
214

215
        let vector_source =
6✔
216
            self.sources
7✔
217
                .vector()
7✔
218
                .ok_or_else(|| error::Error::InvalidOperatorType {
7✔
219
                    expected: "Vector".to_owned(),
1✔
220
                    found: "Raster".to_owned(),
1✔
221
                })?;
1✔
222

223
        let initialized_source = vector_source
6✔
224
            .initialize_sources(path.clone(), context)
6✔
225
            .await?;
6✔
226

227
        let initialized_operator = InitializedVectorReprojection::try_new_with_input(
6✔
228
            name,
6✔
229
            path,
6✔
230
            self.params,
6✔
231
            initialized_source.vector,
6✔
UNCOV
232
        )?;
×
233

234
        Ok(initialized_operator.boxed())
6✔
235
    }
14✔
236

237
    span_fn!(Reprojection);
238
}
239

240
impl InitializedVectorOperator for InitializedVectorReprojection {
241
    fn result_descriptor(&self) -> &VectorResultDescriptor {
×
242
        &self.result_descriptor
×
243
    }
×
244

245
    fn query_processor(&self) -> Result<TypedVectorQueryProcessor> {
6✔
246
        let source_srs = self.source_srs;
6✔
247
        let target_srs = self.target_srs;
6✔
248
        match self.source.query_processor()? {
6✔
249
            TypedVectorQueryProcessor::Data(source) => Ok(TypedVectorQueryProcessor::Data(
×
250
                MapQueryProcessor::new(
×
251
                    source,
×
252
                    self.result_descriptor.clone(),
×
253
                    move |query| reproject_query(query, source_srs, target_srs).map_err(From::from),
×
254
                    (),
×
255
                )
256
                .boxed(),
×
257
            )),
258
            TypedVectorQueryProcessor::MultiPoint(source) => {
4✔
259
                Ok(TypedVectorQueryProcessor::MultiPoint(
4✔
260
                    VectorReprojectionProcessor::new(
4✔
261
                        source,
4✔
262
                        self.result_descriptor.clone(),
4✔
263
                        source_srs,
4✔
264
                        target_srs,
4✔
265
                    )
4✔
266
                    .boxed(),
4✔
267
                ))
4✔
268
            }
269
            TypedVectorQueryProcessor::MultiLineString(source) => {
1✔
270
                Ok(TypedVectorQueryProcessor::MultiLineString(
1✔
271
                    VectorReprojectionProcessor::new(
1✔
272
                        source,
1✔
273
                        self.result_descriptor.clone(),
1✔
274
                        source_srs,
1✔
275
                        target_srs,
1✔
276
                    )
1✔
277
                    .boxed(),
1✔
278
                ))
1✔
279
            }
280
            TypedVectorQueryProcessor::MultiPolygon(source) => {
1✔
281
                Ok(TypedVectorQueryProcessor::MultiPolygon(
1✔
282
                    VectorReprojectionProcessor::new(
1✔
283
                        source,
1✔
284
                        self.result_descriptor.clone(),
1✔
285
                        source_srs,
1✔
286
                        target_srs,
1✔
287
                    )
1✔
288
                    .boxed(),
1✔
289
                ))
1✔
290
            }
291
        }
292
    }
6✔
293

294
    fn canonic_name(&self) -> CanonicOperatorName {
×
295
        self.name.clone()
×
296
    }
×
297

298
    fn name(&self) -> &'static str {
×
299
        Reprojection::TYPE_NAME
×
300
    }
×
301

302
    fn path(&self) -> WorkflowOperatorPath {
×
303
        self.path.clone()
×
304
    }
×
305
}
306

307
struct VectorReprojectionProcessor<Q, G>
308
where
309
    Q: VectorQueryProcessor<VectorType = FeatureCollection<G>>,
310
{
311
    source: Q,
312
    result_descriptor: VectorResultDescriptor,
313
    from: SpatialReference,
314
    to: SpatialReference,
315
}
316

317
impl<Q, G> VectorReprojectionProcessor<Q, G>
318
where
319
    Q: VectorQueryProcessor<VectorType = FeatureCollection<G>>,
320
{
321
    pub fn new(
6✔
322
        source: Q,
6✔
323
        result_descriptor: VectorResultDescriptor,
6✔
324
        from: SpatialReference,
6✔
325
        to: SpatialReference,
6✔
326
    ) -> Self {
6✔
327
        Self {
6✔
328
            source,
6✔
329
            result_descriptor,
6✔
330
            from,
6✔
331
            to,
6✔
332
        }
6✔
333
    }
6✔
334
}
335

336
#[async_trait]
337
impl<Q, G> QueryProcessor for VectorReprojectionProcessor<Q, G>
338
where
339
    Q: QueryProcessor<
340
            Output = FeatureCollection<G>,
341
            SpatialBounds = BoundingBox2D,
342
            Selection = ColumnSelection,
343
            ResultDescription = VectorResultDescriptor,
344
        >,
345
    FeatureCollection<G>: Reproject<CoordinateProjector, Out = FeatureCollection<G>>,
346
    G: Geometry + ArrowTyped,
347
{
348
    type Output = FeatureCollection<G>;
349
    type SpatialBounds = BoundingBox2D;
350
    type Selection = ColumnSelection;
351
    type ResultDescription = VectorResultDescriptor;
352

353
    async fn _query<'a>(
354
        &'a self,
355
        query: VectorQueryRectangle,
356
        ctx: &'a dyn QueryContext,
357
    ) -> Result<BoxStream<'a, Result<Self::Output>>> {
12✔
358
        let rewritten_query = reproject_query(query, self.from, self.to)?;
6✔
359

360
        if let Some(rewritten_query) = rewritten_query {
6✔
361
            Ok(self
5✔
362
                .source
5✔
363
                .query(rewritten_query, ctx)
5✔
364
                .await?
5✔
365
                .map(move |collection_result| {
5✔
366
                    collection_result.and_then(|collection| {
5✔
367
                        CoordinateProjector::from_known_srs(self.from, self.to)
5✔
368
                            .and_then(|projector| collection.reproject(projector.as_ref()))
5✔
369
                            .map_err(Into::into)
5✔
370
                    })
5✔
371
                })
5✔
372
                .boxed())
5✔
373
        } else {
374
            let res = Ok(FeatureCollection::empty());
1✔
375
            Ok(Box::pin(stream::once(async { res })))
1✔
376
        }
377
    }
12✔
378

379
    fn result_descriptor(&self) -> &VectorResultDescriptor {
12✔
380
        &self.result_descriptor
12✔
381
    }
12✔
382
}
383

384
#[typetag::serde]
×
385
#[async_trait]
386
impl RasterOperator for Reprojection {
387
    async fn _initialize(
388
        self: Box<Self>,
389
        path: WorkflowOperatorPath,
390
        context: &dyn ExecutionContext,
391
    ) -> Result<Box<dyn InitializedRasterOperator>> {
12✔
392
        let name = CanonicOperatorName::from(&self);
6✔
393

394
        let raster_source =
6✔
395
            self.sources
6✔
396
                .raster()
6✔
397
                .ok_or_else(|| error::Error::InvalidOperatorType {
6✔
398
                    expected: "Raster".to_owned(),
×
399
                    found: "Vector".to_owned(),
×
UNCOV
400
                })?;
×
401

402
        let initialized_source = raster_source
6✔
403
            .initialize_sources(path.clone(), context)
6✔
404
            .await?;
6✔
405

406
        let initialized_operator = InitializedRasterReprojection::try_new_with_input(
6✔
407
            name,
6✔
408
            path,
6✔
409
            self.params,
6✔
410
            initialized_source.raster,
6✔
411
            context.tiling_specification(),
6✔
412
        )?;
2✔
413

414
        Ok(initialized_operator.boxed())
4✔
415
    }
12✔
416

417
    span_fn!(Reprojection);
418
}
419

420
impl InitializedRasterOperator for InitializedRasterReprojection {
421
    fn result_descriptor(&self) -> &RasterResultDescriptor {
×
422
        &self.result_descriptor
×
423
    }
×
424

425
    // i know there is a macro somewhere. we need to re-work this when we have the no-data value anyway.
426
    #[allow(clippy::too_many_lines)]
427
    fn query_processor(&self) -> Result<TypedRasterQueryProcessor> {
4✔
428
        let q = self.source.query_processor()?;
4✔
429

430
        Ok(match self.result_descriptor.data_type {
4✔
431
            geoengine_datatypes::raster::RasterDataType::U8 => {
432
                let qt = q
4✔
433
                    .get_u8()
4✔
434
                    .expect("the result descriptor and query processor type should match");
4✔
435
                TypedRasterQueryProcessor::U8(Box::new(RasterReprojectionProcessor::new(
4✔
436
                    qt,
4✔
437
                    self.result_descriptor.clone(),
4✔
438
                    self.source_srs,
4✔
439
                    self.target_srs,
4✔
440
                    self.tiling_spec,
4✔
441
                    self.state,
4✔
442
                )))
4✔
443
            }
444
            geoengine_datatypes::raster::RasterDataType::U16 => {
445
                let qt = q
×
446
                    .get_u16()
×
447
                    .expect("the result descriptor and query processor type should match");
×
448
                TypedRasterQueryProcessor::U16(Box::new(RasterReprojectionProcessor::new(
×
449
                    qt,
×
450
                    self.result_descriptor.clone(),
×
451
                    self.source_srs,
×
452
                    self.target_srs,
×
453
                    self.tiling_spec,
×
454
                    self.state,
×
455
                )))
×
456
            }
457

458
            geoengine_datatypes::raster::RasterDataType::U32 => {
459
                let qt = q
×
460
                    .get_u32()
×
461
                    .expect("the result descriptor and query processor type should match");
×
462
                TypedRasterQueryProcessor::U32(Box::new(RasterReprojectionProcessor::new(
×
463
                    qt,
×
464
                    self.result_descriptor.clone(),
×
465
                    self.source_srs,
×
466
                    self.target_srs,
×
467
                    self.tiling_spec,
×
468
                    self.state,
×
469
                )))
×
470
            }
471
            geoengine_datatypes::raster::RasterDataType::U64 => {
472
                let qt = q
×
473
                    .get_u64()
×
474
                    .expect("the result descriptor and query processor type should match");
×
475
                TypedRasterQueryProcessor::U64(Box::new(RasterReprojectionProcessor::new(
×
476
                    qt,
×
477
                    self.result_descriptor.clone(),
×
478
                    self.source_srs,
×
479
                    self.target_srs,
×
480
                    self.tiling_spec,
×
481
                    self.state,
×
482
                )))
×
483
            }
484
            geoengine_datatypes::raster::RasterDataType::I8 => {
485
                let qt = q
×
486
                    .get_i8()
×
487
                    .expect("the result descriptor and query processor type should match");
×
488
                TypedRasterQueryProcessor::I8(Box::new(RasterReprojectionProcessor::new(
×
489
                    qt,
×
490
                    self.result_descriptor.clone(),
×
491
                    self.source_srs,
×
492
                    self.target_srs,
×
493
                    self.tiling_spec,
×
494
                    self.state,
×
495
                )))
×
496
            }
497
            geoengine_datatypes::raster::RasterDataType::I16 => {
498
                let qt = q
×
499
                    .get_i16()
×
500
                    .expect("the result descriptor and query processor type should match");
×
501
                TypedRasterQueryProcessor::I16(Box::new(RasterReprojectionProcessor::new(
×
502
                    qt,
×
503
                    self.result_descriptor.clone(),
×
504
                    self.source_srs,
×
505
                    self.target_srs,
×
506
                    self.tiling_spec,
×
507
                    self.state,
×
508
                )))
×
509
            }
510
            geoengine_datatypes::raster::RasterDataType::I32 => {
511
                let qt = q
×
512
                    .get_i32()
×
513
                    .expect("the result descriptor and query processor type should match");
×
514
                TypedRasterQueryProcessor::I32(Box::new(RasterReprojectionProcessor::new(
×
515
                    qt,
×
516
                    self.result_descriptor.clone(),
×
517
                    self.source_srs,
×
518
                    self.target_srs,
×
519
                    self.tiling_spec,
×
520
                    self.state,
×
521
                )))
×
522
            }
523
            geoengine_datatypes::raster::RasterDataType::I64 => {
524
                let qt = q
×
525
                    .get_i64()
×
526
                    .expect("the result descriptor and query processor type should match");
×
527
                TypedRasterQueryProcessor::I64(Box::new(RasterReprojectionProcessor::new(
×
528
                    qt,
×
529
                    self.result_descriptor.clone(),
×
530
                    self.source_srs,
×
531
                    self.target_srs,
×
532
                    self.tiling_spec,
×
533
                    self.state,
×
534
                )))
×
535
            }
536
            geoengine_datatypes::raster::RasterDataType::F32 => {
537
                let qt = q
×
538
                    .get_f32()
×
539
                    .expect("the result descriptor and query processor type should match");
×
540
                TypedRasterQueryProcessor::F32(Box::new(RasterReprojectionProcessor::new(
×
541
                    qt,
×
542
                    self.result_descriptor.clone(),
×
543
                    self.source_srs,
×
544
                    self.target_srs,
×
545
                    self.tiling_spec,
×
546
                    self.state,
×
547
                )))
×
548
            }
549
            geoengine_datatypes::raster::RasterDataType::F64 => {
550
                let qt = q
×
551
                    .get_f64()
×
552
                    .expect("the result descriptor and query processor type should match");
×
553
                TypedRasterQueryProcessor::F64(Box::new(RasterReprojectionProcessor::new(
×
554
                    qt,
×
555
                    self.result_descriptor.clone(),
×
556
                    self.source_srs,
×
557
                    self.target_srs,
×
558
                    self.tiling_spec,
×
559
                    self.state,
×
560
                )))
×
561
            }
562
        })
563
    }
4✔
564

565
    fn canonic_name(&self) -> CanonicOperatorName {
×
566
        self.name.clone()
×
567
    }
×
568

569
    fn name(&self) -> &'static str {
×
570
        Reprojection::TYPE_NAME
×
571
    }
×
572

573
    fn path(&self) -> WorkflowOperatorPath {
×
574
        self.path.clone()
×
575
    }
×
576
}
577

578
pub struct RasterReprojectionProcessor<Q, P>
579
where
580
    Q: RasterQueryProcessor<RasterType = P>,
581
{
582
    source: Q,
583
    result_descriptor: RasterResultDescriptor,
584
    from: SpatialReference,
585
    to: SpatialReference,
586
    tiling_spec: TilingSpecification,
587
    state: Option<ReprojectionBounds>,
588
    _phantom_data: PhantomData<P>,
589
}
590

591
impl<Q, P> RasterReprojectionProcessor<Q, P>
592
where
593
    Q: QueryProcessor<
594
            Output = RasterTile2D<P>,
595
            SpatialBounds = SpatialPartition2D,
596
            Selection = BandSelection,
597
            ResultDescription = RasterResultDescriptor,
598
        >,
599
    P: Pixel,
600
{
601
    pub fn new(
4✔
602
        source: Q,
4✔
603
        result_descriptor: RasterResultDescriptor,
4✔
604
        from: SpatialReference,
4✔
605
        to: SpatialReference,
4✔
606
        tiling_spec: TilingSpecification,
4✔
607
        state: Option<ReprojectionBounds>,
4✔
608
    ) -> Self {
4✔
609
        Self {
4✔
610
            source,
4✔
611
            result_descriptor,
4✔
612
            from,
4✔
613
            to,
4✔
614
            tiling_spec,
4✔
615
            state,
4✔
616
            _phantom_data: PhantomData,
4✔
617
        }
4✔
618
    }
4✔
619
}
620

621
#[async_trait]
622
impl<Q, P> QueryProcessor for RasterReprojectionProcessor<Q, P>
623
where
624
    Q: QueryProcessor<
625
            Output = RasterTile2D<P>,
626
            SpatialBounds = SpatialPartition2D,
627
            Selection = BandSelection,
628
            ResultDescription = RasterResultDescriptor,
629
        >,
630
    P: Pixel,
631
{
632
    type Output = RasterTile2D<P>;
633
    type SpatialBounds = SpatialPartition2D;
634
    type Selection = BandSelection;
635
    type ResultDescription = RasterResultDescriptor;
636

637
    async fn _query<'a>(
638
        &'a self,
639
        query: RasterQueryRectangle,
640
        ctx: &'a dyn QueryContext,
641
    ) -> Result<BoxStream<'a, Result<Self::Output>>> {
8✔
642
        if let Some(state) = &self.state {
4✔
643
            let valid_bounds_in = state.valid_in_bounds;
4✔
644
            let valid_bounds_out = state.valid_out_bounds;
4✔
645

646
            // calculate the spatial resolution the input data should have using the intersection and the requested resolution
647
            let in_spatial_res = suggest_pixel_size_from_diag_cross_projected(
4✔
648
                valid_bounds_out,
4✔
649
                valid_bounds_in,
4✔
650
                query.spatial_resolution,
4✔
UNCOV
651
            )?;
×
652

653
            // setup the subquery
654
            let sub_query_spec = TileReprojectionSubQuery {
4✔
655
                in_srs: self.from,
4✔
656
                out_srs: self.to,
4✔
657
                fold_fn: fold_by_coordinate_lookup_future,
4✔
658
                in_spatial_res,
4✔
659
                valid_bounds_in,
4✔
660
                valid_bounds_out,
4✔
661
                _phantom_data: PhantomData,
4✔
662
            };
4✔
663

664
            // return the adapter which will reproject the tiles and uses the fill adapter to inject missing tiles
665
            Ok(RasterSubQueryAdapter::<'a, P, _, _>::new(
4✔
666
                &self.source,
4✔
667
                query,
4✔
668
                self.tiling_spec,
4✔
669
                ctx,
4✔
670
                sub_query_spec,
4✔
671
            )
4✔
672
            .filter_and_fill(FillerTileCacheExpirationStrategy::DerivedFromSurroundingTiles))
4✔
673
        } else {
674
            log::debug!("No intersection between source data / srs and target srs");
×
675

676
            let tiling_strat = self
×
677
                .tiling_spec
×
678
                .strategy(query.spatial_resolution.x, -query.spatial_resolution.y);
×
679

680
            let grid_bounds = tiling_strat.tile_grid_box(query.spatial_partition());
×
681
            Ok(Box::pin(SparseTilesFillAdapter::new(
×
682
                stream::empty(),
×
683
                grid_bounds,
×
684
                query.attributes.count(),
×
685
                tiling_strat.geo_transform,
×
686
                self.tiling_spec.tile_size_in_pixels,
×
687
                FillerTileCacheExpirationStrategy::DerivedFromSurroundingTiles,
×
688
                query.time_interval,
×
689
                FillerTimeBounds::from(query.time_interval), // TODO: derive this from the query once the child query can provide this.
×
690
            )))
×
691
        }
692
    }
8✔
693

694
    fn result_descriptor(&self) -> &RasterResultDescriptor {
8✔
695
        &self.result_descriptor
8✔
696
    }
8✔
697
}
698

699
#[cfg(test)]
700
mod tests {
701
    use super::*;
702
    use crate::engine::{MockExecutionContext, MockQueryContext, RasterBandDescriptors};
703
    use crate::mock::MockFeatureCollectionSource;
704
    use crate::mock::{MockRasterSource, MockRasterSourceParams};
705
    use crate::{
706
        engine::{ChunkByteSize, VectorOperator},
707
        source::{
708
            FileNotFoundHandling, GdalDatasetGeoTransform, GdalDatasetParameters,
709
            GdalMetaDataRegular, GdalMetaDataStatic, GdalSource, GdalSourceParameters,
710
            GdalSourceTimePlaceholder, TimeReference,
711
        },
712
        test_data,
713
        util::gdal::{add_ndvi_dataset, gdal_open_dataset},
714
    };
715
    use float_cmp::approx_eq;
716
    use futures::StreamExt;
717
    use geoengine_datatypes::collections::IntoGeometryIterator;
718
    use geoengine_datatypes::dataset::NamedData;
719
    use geoengine_datatypes::primitives::{
720
        AxisAlignedRectangle, Coordinate2D, DateTimeParseFormat,
721
    };
722
    use geoengine_datatypes::primitives::{CacheHint, CacheTtlSeconds};
723
    use geoengine_datatypes::raster::TilesEqualIgnoringCacheHint;
724
    use geoengine_datatypes::{
725
        collections::{
726
            GeometryCollection, MultiLineStringCollection, MultiPointCollection,
727
            MultiPolygonCollection,
728
        },
729
        dataset::{DataId, DatasetId},
730
        hashmap,
731
        primitives::{
732
            BoundingBox2D, MultiLineString, MultiPoint, MultiPolygon, QueryRectangle,
733
            SpatialResolution, TimeGranularity, TimeInstance, TimeInterval, TimeStep,
734
        },
735
        raster::{Grid, GridShape, GridShape2D, GridSize, RasterDataType, RasterTile2D},
736
        spatial_reference::SpatialReferenceAuthority,
737
        util::{
738
            Identifier,
739
            test::TestDefault,
740
            well_known_data::{
741
                COLOGNE_EPSG_900_913, COLOGNE_EPSG_4326, HAMBURG_EPSG_900_913, HAMBURG_EPSG_4326,
742
                MARBURG_EPSG_900_913, MARBURG_EPSG_4326,
743
            },
744
        },
745
    };
746
    use std::collections::HashMap;
747
    use std::path::PathBuf;
748
    use std::str::FromStr;
749

750
    #[tokio::test]
751
    async fn multi_point() -> Result<()> {
1✔
752
        let points = MultiPointCollection::from_data(
1✔
753
            MultiPoint::many(vec![
1✔
754
                MARBURG_EPSG_4326,
755
                COLOGNE_EPSG_4326,
756
                HAMBURG_EPSG_4326,
757
            ])
758
            .unwrap(),
1✔
759
            vec![TimeInterval::new_unchecked(0, 1); 3],
1✔
760
            Default::default(),
1✔
761
            CacheHint::default(),
1✔
UNCOV
762
        )?;
×
763

764
        let expected = MultiPoint::many(vec![
1✔
765
            MARBURG_EPSG_900_913,
766
            COLOGNE_EPSG_900_913,
767
            HAMBURG_EPSG_900_913,
768
        ])
769
        .unwrap();
1✔
770

771
        let point_source = MockFeatureCollectionSource::single(points.clone()).boxed();
1✔
772

773
        let target_spatial_reference =
1✔
774
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 900_913);
1✔
775

776
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
777
            params: ReprojectionParams {
1✔
778
                target_spatial_reference,
1✔
779
            },
1✔
780
            sources: SingleRasterOrVectorSource {
1✔
781
                source: point_source.into(),
1✔
782
            },
1✔
783
        })
1✔
784
        .initialize(
1✔
785
            WorkflowOperatorPath::initialize_root(),
1✔
786
            &MockExecutionContext::test_default(),
1✔
787
        )
1✔
788
        .await?;
1✔
789

790
        let query_processor = initialized_operator.query_processor()?;
1✔
791

792
        let query_processor = query_processor.multi_point().unwrap();
1✔
793

794
        let query_rectangle = VectorQueryRectangle {
1✔
795
            spatial_bounds: BoundingBox2D::new(
1✔
796
                (COLOGNE_EPSG_4326.x, MARBURG_EPSG_4326.y).into(),
1✔
797
                (MARBURG_EPSG_4326.x, HAMBURG_EPSG_4326.y).into(),
1✔
798
            )
1✔
799
            .unwrap(),
1✔
800
            time_interval: TimeInterval::default(),
1✔
801
            spatial_resolution: SpatialResolution::zero_point_one(),
1✔
802
            attributes: ColumnSelection::all(),
1✔
803
        };
1✔
804
        let ctx = MockQueryContext::new(ChunkByteSize::MAX);
1✔
805

806
        let query = query_processor.query(query_rectangle, &ctx).await.unwrap();
1✔
807

808
        let result = query
1✔
809
            .map(Result::unwrap)
1✔
810
            .collect::<Vec<MultiPointCollection>>()
1✔
811
            .await;
1✔
812

813
        assert_eq!(result.len(), 1);
1✔
814

815
        result[0]
1✔
816
            .geometries()
1✔
817
            .zip(expected.iter())
1✔
818
            .for_each(|(a, e)| {
3✔
819
                assert!(approx_eq!(&MultiPoint, &a.into(), e, epsilon = 0.00001));
3✔
820
            });
3✔
821

822
        Ok(())
2✔
823
    }
1✔
824

825
    #[tokio::test]
826
    async fn multi_lines() -> Result<()> {
1✔
827
        let lines = MultiLineStringCollection::from_data(
1✔
828
            vec![
1✔
829
                MultiLineString::new(vec![vec![
1✔
830
                    MARBURG_EPSG_4326,
831
                    COLOGNE_EPSG_4326,
832
                    HAMBURG_EPSG_4326,
833
                ]])
834
                .unwrap(),
1✔
835
            ],
836
            vec![TimeInterval::new_unchecked(0, 1); 1],
1✔
837
            Default::default(),
1✔
838
            CacheHint::default(),
1✔
UNCOV
839
        )?;
×
840

841
        let expected = [MultiLineString::new(vec![vec![
1✔
842
            MARBURG_EPSG_900_913,
1✔
843
            COLOGNE_EPSG_900_913,
1✔
844
            HAMBURG_EPSG_900_913,
1✔
845
        ]])
1✔
846
        .unwrap()];
1✔
847

848
        let lines_source = MockFeatureCollectionSource::single(lines.clone()).boxed();
1✔
849

850
        let target_spatial_reference =
1✔
851
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 900_913);
1✔
852

853
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
854
            params: ReprojectionParams {
1✔
855
                target_spatial_reference,
1✔
856
            },
1✔
857
            sources: SingleRasterOrVectorSource {
1✔
858
                source: lines_source.into(),
1✔
859
            },
1✔
860
        })
1✔
861
        .initialize(
1✔
862
            WorkflowOperatorPath::initialize_root(),
1✔
863
            &MockExecutionContext::test_default(),
1✔
864
        )
1✔
865
        .await?;
1✔
866

867
        let query_processor = initialized_operator.query_processor()?;
1✔
868

869
        let query_processor = query_processor.multi_line_string().unwrap();
1✔
870

871
        let query_rectangle = VectorQueryRectangle {
1✔
872
            spatial_bounds: BoundingBox2D::new(
1✔
873
                (COLOGNE_EPSG_4326.x, MARBURG_EPSG_4326.y).into(),
1✔
874
                (MARBURG_EPSG_4326.x, HAMBURG_EPSG_4326.y).into(),
1✔
875
            )
1✔
876
            .unwrap(),
1✔
877
            time_interval: TimeInterval::default(),
1✔
878
            spatial_resolution: SpatialResolution::zero_point_one(),
1✔
879
            attributes: ColumnSelection::all(),
1✔
880
        };
1✔
881
        let ctx = MockQueryContext::new(ChunkByteSize::MAX);
1✔
882

883
        let query = query_processor.query(query_rectangle, &ctx).await.unwrap();
1✔
884

885
        let result = query
1✔
886
            .map(Result::unwrap)
1✔
887
            .collect::<Vec<MultiLineStringCollection>>()
1✔
888
            .await;
1✔
889

890
        assert_eq!(result.len(), 1);
1✔
891

892
        result[0]
1✔
893
            .geometries()
1✔
894
            .zip(expected.iter())
1✔
895
            .for_each(|(a, e)| {
1✔
896
                assert!(approx_eq!(
1✔
897
                    &MultiLineString,
898
                    &a.into(),
1✔
899
                    e,
1✔
900
                    epsilon = 0.00001
901
                ));
902
            });
1✔
903

904
        Ok(())
2✔
905
    }
1✔
906

907
    #[tokio::test]
908
    async fn multi_polygons() -> Result<()> {
1✔
909
        let polygons = MultiPolygonCollection::from_data(
1✔
910
            vec![
1✔
911
                MultiPolygon::new(vec![vec![vec![
1✔
912
                    MARBURG_EPSG_4326,
913
                    COLOGNE_EPSG_4326,
914
                    HAMBURG_EPSG_4326,
915
                    MARBURG_EPSG_4326,
916
                ]]])
917
                .unwrap(),
1✔
918
            ],
919
            vec![TimeInterval::new_unchecked(0, 1); 1],
1✔
920
            Default::default(),
1✔
921
            CacheHint::default(),
1✔
UNCOV
922
        )?;
×
923

924
        let expected = [MultiPolygon::new(vec![vec![vec![
1✔
925
            MARBURG_EPSG_900_913,
1✔
926
            COLOGNE_EPSG_900_913,
1✔
927
            HAMBURG_EPSG_900_913,
1✔
928
            MARBURG_EPSG_900_913,
1✔
929
        ]]])
1✔
930
        .unwrap()];
1✔
931

932
        let polygon_source = MockFeatureCollectionSource::single(polygons.clone()).boxed();
1✔
933

934
        let target_spatial_reference =
1✔
935
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 900_913);
1✔
936

937
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
938
            params: ReprojectionParams {
1✔
939
                target_spatial_reference,
1✔
940
            },
1✔
941
            sources: SingleRasterOrVectorSource {
1✔
942
                source: polygon_source.into(),
1✔
943
            },
1✔
944
        })
1✔
945
        .initialize(
1✔
946
            WorkflowOperatorPath::initialize_root(),
1✔
947
            &MockExecutionContext::test_default(),
1✔
948
        )
1✔
949
        .await?;
1✔
950

951
        let query_processor = initialized_operator.query_processor()?;
1✔
952

953
        let query_processor = query_processor.multi_polygon().unwrap();
1✔
954

955
        let query_rectangle = VectorQueryRectangle {
1✔
956
            spatial_bounds: BoundingBox2D::new(
1✔
957
                (COLOGNE_EPSG_4326.x, MARBURG_EPSG_4326.y).into(),
1✔
958
                (MARBURG_EPSG_4326.x, HAMBURG_EPSG_4326.y).into(),
1✔
959
            )
1✔
960
            .unwrap(),
1✔
961
            time_interval: TimeInterval::default(),
1✔
962
            spatial_resolution: SpatialResolution::zero_point_one(),
1✔
963
            attributes: ColumnSelection::all(),
1✔
964
        };
1✔
965
        let ctx = MockQueryContext::new(ChunkByteSize::MAX);
1✔
966

967
        let query = query_processor.query(query_rectangle, &ctx).await.unwrap();
1✔
968

969
        let result = query
1✔
970
            .map(Result::unwrap)
1✔
971
            .collect::<Vec<MultiPolygonCollection>>()
1✔
972
            .await;
1✔
973

974
        assert_eq!(result.len(), 1);
1✔
975

976
        result[0]
1✔
977
            .geometries()
1✔
978
            .zip(expected.iter())
1✔
979
            .for_each(|(a, e)| {
1✔
980
                assert!(approx_eq!(&MultiPolygon, &a.into(), e, epsilon = 0.00001));
1✔
981
            });
1✔
982

983
        Ok(())
2✔
984
    }
1✔
985

986
    #[tokio::test]
987
    async fn raster_identity() -> Result<()> {
1✔
988
        let projection = SpatialReference::new(
1✔
989
            geoengine_datatypes::spatial_reference::SpatialReferenceAuthority::Epsg,
1✔
990
            4326,
991
        );
992

993
        let data = vec![
1✔
994
            RasterTile2D {
1✔
995
                time: TimeInterval::new_unchecked(0, 5),
1✔
996
                tile_position: [-1, 0].into(),
1✔
997
                band: 0,
1✔
998
                global_geo_transform: TestDefault::test_default(),
1✔
999
                grid_array: Grid::new([2, 2].into(), vec![1, 2, 3, 4]).unwrap().into(),
1✔
1000
                properties: Default::default(),
1✔
1001
                cache_hint: CacheHint::default(),
1✔
1002
            },
1✔
1003
            RasterTile2D {
1✔
1004
                time: TimeInterval::new_unchecked(0, 5),
1✔
1005
                tile_position: [-1, 1].into(),
1✔
1006
                band: 0,
1✔
1007
                global_geo_transform: TestDefault::test_default(),
1✔
1008
                grid_array: Grid::new([2, 2].into(), vec![7, 8, 9, 10]).unwrap().into(),
1✔
1009
                properties: Default::default(),
1✔
1010
                cache_hint: CacheHint::default(),
1✔
1011
            },
1✔
1012
            RasterTile2D {
1✔
1013
                time: TimeInterval::new_unchecked(5, 10),
1✔
1014
                tile_position: [-1, 0].into(),
1✔
1015
                band: 0,
1✔
1016
                global_geo_transform: TestDefault::test_default(),
1✔
1017
                grid_array: Grid::new([2, 2].into(), vec![13, 14, 15, 16])
1✔
1018
                    .unwrap()
1✔
1019
                    .into(),
1✔
1020
                properties: Default::default(),
1✔
1021
                cache_hint: CacheHint::default(),
1✔
1022
            },
1✔
1023
            RasterTile2D {
1✔
1024
                time: TimeInterval::new_unchecked(5, 10),
1✔
1025
                tile_position: [-1, 1].into(),
1✔
1026
                band: 0,
1✔
1027
                global_geo_transform: TestDefault::test_default(),
1✔
1028
                grid_array: Grid::new([2, 2].into(), vec![19, 20, 21, 22])
1✔
1029
                    .unwrap()
1✔
1030
                    .into(),
1✔
1031
                properties: Default::default(),
1✔
1032
                cache_hint: CacheHint::default(),
1✔
1033
            },
1✔
1034
        ];
1035

1036
        let mrs1 = MockRasterSource {
1✔
1037
            params: MockRasterSourceParams {
1✔
1038
                data: data.clone(),
1✔
1039
                result_descriptor: RasterResultDescriptor {
1✔
1040
                    data_type: RasterDataType::U8,
1✔
1041
                    spatial_reference: SpatialReference::epsg_4326().into(),
1✔
1042
                    time: None,
1✔
1043
                    bbox: None,
1✔
1044
                    resolution: Some(SpatialResolution::one()),
1✔
1045
                    bands: RasterBandDescriptors::new_single_band(),
1✔
1046
                },
1✔
1047
            },
1✔
1048
        }
1✔
1049
        .boxed();
1✔
1050

1051
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1052
        exe_ctx.tiling_specification.tile_size_in_pixels = GridShape {
1✔
1053
            // we need a smaller tile size
1✔
1054
            shape_array: [2, 2],
1✔
1055
        };
1✔
1056

1057
        let query_ctx = MockQueryContext::test_default();
1✔
1058

1059
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1060
            params: ReprojectionParams {
1✔
1061
                target_spatial_reference: projection, // This test will do a identity reprojection
1✔
1062
            },
1✔
1063
            sources: SingleRasterOrVectorSource {
1✔
1064
                source: mrs1.into(),
1✔
1065
            },
1✔
1066
        })
1✔
1067
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1068
        .await?;
1✔
1069

1070
        let qp = initialized_operator
1✔
1071
            .query_processor()
1✔
1072
            .unwrap()
1✔
1073
            .get_u8()
1✔
1074
            .unwrap();
1✔
1075

1076
        let query_rect = RasterQueryRectangle {
1✔
1077
            spatial_bounds: SpatialPartition2D::new_unchecked((0., 1.).into(), (3., 0.).into()),
1✔
1078
            time_interval: TimeInterval::new_unchecked(0, 10),
1✔
1079
            spatial_resolution: SpatialResolution::one(),
1✔
1080
            attributes: BandSelection::first(),
1✔
1081
        };
1✔
1082

1083
        let a = qp.raster_query(query_rect, &query_ctx).await?;
1✔
1084

1085
        let res = a
1✔
1086
            .map(Result::unwrap)
1✔
1087
            .collect::<Vec<RasterTile2D<u8>>>()
1✔
1088
            .await;
1✔
1089
        assert!(data.tiles_equal_ignoring_cache_hint(&res));
1✔
1090

1091
        Ok(())
2✔
1092
    }
1✔
1093

1094
    #[tokio::test]
1095
    async fn raster_ndvi_3857() -> Result<()> {
1✔
1096
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1097
        let query_ctx = MockQueryContext::test_default();
1✔
1098
        let id = add_ndvi_dataset(&mut exe_ctx);
1✔
1099
        exe_ctx.tiling_specification =
1✔
1100
            TilingSpecification::new((0.0, 0.0).into(), [450, 450].into());
1✔
1101

1102
        let output_shape: GridShape2D = [900, 1800].into();
1✔
1103
        let output_bounds =
1✔
1104
            SpatialPartition2D::new_unchecked((0., 20_000_000.).into(), (20_000_000., 0.).into());
1✔
1105
        let time_interval = TimeInterval::new_unchecked(1_388_534_400_000, 1_388_534_400_001);
1✔
1106
        // 2014-01-01
1107

1108
        let gdal_op = GdalSource {
1✔
1109
            params: GdalSourceParameters { data: id.clone() },
1✔
1110
        }
1✔
1111
        .boxed();
1✔
1112

1113
        let projection = SpatialReference::new(
1✔
1114
            geoengine_datatypes::spatial_reference::SpatialReferenceAuthority::Epsg,
1✔
1115
            3857,
1116
        );
1117

1118
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1119
            params: ReprojectionParams {
1✔
1120
                target_spatial_reference: projection,
1✔
1121
            },
1✔
1122
            sources: SingleRasterOrVectorSource {
1✔
1123
                source: gdal_op.into(),
1✔
1124
            },
1✔
1125
        })
1✔
1126
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1127
        .await?;
1✔
1128

1129
        let x_query_resolution = output_bounds.size_x() / output_shape.axis_size_x() as f64;
1✔
1130
        let y_query_resolution = output_bounds.size_y() / (output_shape.axis_size_y() * 2) as f64; // *2 to account for the dataset aspect ratio 2:1
1✔
1131
        let spatial_resolution =
1✔
1132
            SpatialResolution::new_unchecked(x_query_resolution, y_query_resolution);
1✔
1133

1134
        let qp = initialized_operator
1✔
1135
            .query_processor()
1✔
1136
            .unwrap()
1✔
1137
            .get_u8()
1✔
1138
            .unwrap();
1✔
1139

1140
        let qs = qp
1✔
1141
            .raster_query(
1✔
1142
                RasterQueryRectangle {
1✔
1143
                    spatial_bounds: output_bounds,
1✔
1144
                    time_interval,
1✔
1145
                    spatial_resolution,
1✔
1146
                    attributes: BandSelection::first(),
1✔
1147
                },
1✔
1148
                &query_ctx,
1✔
1149
            )
1✔
1150
            .await
1✔
1151
            .unwrap();
1✔
1152

1153
        let res = qs
1✔
1154
            .map(Result::unwrap)
1✔
1155
            .collect::<Vec<RasterTile2D<u8>>>()
1✔
1156
            .await;
1✔
1157

1158
        // Write the tiles to a file
1159
        // let mut buffer = File::create("MOD13A2_M_NDVI_2014-04-01_tile-20.rst")?;
1160
        // buffer.write(res[8].clone().into_materialized_tile().grid_array.data.as_slice())?;
1161

1162
        // This check is against a tile produced by the operator itself. It was visually validated. TODO: rebuild when open issues are solved.
1163
        // A perfect validation would be against a GDAL output generated like this:
1164
        // gdalwarp -t_srs EPSG:3857 -tr 11111.11111111 11111.11111111 -r near -te 0.0 5011111.111111112 5000000.0 10011111.111111112 -te_srs EPSG:3857 -of GTiff ./MOD13A2_M_NDVI_2014-04-01.TIFF ./MOD13A2_M_NDVI_2014-04-01_tile-20.rst
1165

1166
        assert_eq!(
1✔
1167
            include_bytes!(
1168
                "../../../test_data/raster/modis_ndvi/projected_3857/MOD13A2_M_NDVI_2014-04-01_tile-20.rst"
1169
            ) as &[u8],
1✔
1170
            res[8]
1✔
1171
                .clone()
1✔
1172
                .into_materialized_tile()
1✔
1173
                .grid_array
1✔
1174
                .inner_grid
1✔
1175
                .data
1✔
1176
                .as_slice()
1✔
1177
        );
1178

1179
        Ok(())
2✔
1180
    }
1✔
1181

1182
    #[test]
1183
    fn query_rewrite_4326_3857() {
1✔
1184
        let query = VectorQueryRectangle {
1✔
1185
            spatial_bounds: BoundingBox2D::new_unchecked((-180., -90.).into(), (180., 90.).into()),
1✔
1186
            time_interval: TimeInterval::default(),
1✔
1187
            spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1188
            attributes: ColumnSelection::all(),
1✔
1189
        };
1✔
1190

1191
        let expected = BoundingBox2D::new_unchecked(
1✔
1192
            (-20_037_508.342_789_244, -20_048_966.104_014_594).into(),
1✔
1193
            (20_037_508.342_789_244, 20_048_966.104_014_594).into(),
1✔
1194
        );
1195

1196
        let reprojected = reproject_query(
1✔
1197
            query,
1✔
1198
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 3857),
1✔
1199
            SpatialReference::epsg_4326(),
1✔
1200
        )
1201
        .unwrap()
1✔
1202
        .unwrap();
1✔
1203

1204
        assert!(approx_eq!(
1✔
1205
            BoundingBox2D,
1206
            expected,
1✔
1207
            reprojected.spatial_bounds,
1✔
1208
            epsilon = 0.000_001
1209
        ));
1210
    }
1✔
1211

1212
    #[tokio::test]
1213
    async fn raster_ndvi_3857_to_4326() -> Result<()> {
1✔
1214
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1215
        let query_ctx = MockQueryContext::test_default();
1✔
1216

1217
        let m = GdalMetaDataRegular {
1✔
1218
            data_time: TimeInterval::new_unchecked(
1✔
1219
                TimeInstance::from_str("2014-01-01T00:00:00.000Z").unwrap(),
1✔
1220
                TimeInstance::from_str("2014-07-01T00:00:00.000Z").unwrap(),
1✔
1221
            ),
1✔
1222
            step: TimeStep {
1✔
1223
                granularity: TimeGranularity::Months,
1✔
1224
                step: 1,
1✔
1225
            },
1✔
1226
            time_placeholders: hashmap! {
1✔
1227
                "%_START_TIME_%".to_string() => GdalSourceTimePlaceholder {
1✔
1228
                    format: DateTimeParseFormat::custom("%Y-%m-%d".to_string()),
1✔
1229
                    reference: TimeReference::Start,
1✔
1230
                },
1✔
1231
            },
1✔
1232
            params: GdalDatasetParameters {
1✔
1233
                file_path: test_data!(
1✔
1234
                    "raster/modis_ndvi/projected_3857/MOD13A2_M_NDVI_%_START_TIME_%.TIFF"
1✔
1235
                )
1✔
1236
                .into(),
1✔
1237
                rasterband_channel: 1,
1✔
1238
                geo_transform: GdalDatasetGeoTransform {
1✔
1239
                    origin_coordinate: (-20_037_508.342_789_244, 19_971_868.880_408_563).into(),
1✔
1240
                    x_pixel_size: 14_052.950_258_048_739,
1✔
1241
                    y_pixel_size: -14_057.881_117_788_405,
1✔
1242
                },
1✔
1243
                width: 2851,
1✔
1244
                height: 2841,
1✔
1245
                file_not_found_handling: FileNotFoundHandling::Error,
1✔
1246
                no_data_value: Some(0.),
1✔
1247
                properties_mapping: None,
1✔
1248
                gdal_open_options: None,
1✔
1249
                gdal_config_options: None,
1✔
1250
                allow_alphaband_as_mask: true,
1✔
1251
                retry: None,
1✔
1252
            },
1✔
1253
            result_descriptor: RasterResultDescriptor {
1✔
1254
                data_type: RasterDataType::U8,
1✔
1255
                spatial_reference: SpatialReference::new(SpatialReferenceAuthority::Epsg, 3857)
1✔
1256
                    .into(),
1✔
1257
                time: None,
1✔
1258
                bbox: None,
1✔
1259
                resolution: None,
1✔
1260
                bands: RasterBandDescriptors::new_single_band(),
1✔
1261
            },
1✔
1262
            cache_ttl: CacheTtlSeconds::default(),
1✔
1263
        };
1✔
1264

1265
        let id: DataId = DatasetId::new().into();
1✔
1266
        let name = NamedData::with_system_name("ndvi");
1✔
1267
        exe_ctx.add_meta_data(id.clone(), name.clone(), Box::new(m));
1✔
1268

1269
        exe_ctx.tiling_specification = TilingSpecification::new((0.0, 0.0).into(), [60, 60].into());
1✔
1270

1271
        let output_bounds =
1✔
1272
            SpatialPartition2D::new_unchecked((-180., 90.).into(), (180., -90.).into());
1✔
1273
        let time_interval = TimeInterval::new_unchecked(1_396_310_400_000, 1_396_310_400_000);
1✔
1274
        // 2014-04-01
1275

1276
        let gdal_op = GdalSource {
1✔
1277
            params: GdalSourceParameters { data: name },
1✔
1278
        }
1✔
1279
        .boxed();
1✔
1280

1281
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1282
            params: ReprojectionParams {
1✔
1283
                target_spatial_reference: SpatialReference::epsg_4326(),
1✔
1284
            },
1✔
1285
            sources: SingleRasterOrVectorSource {
1✔
1286
                source: gdal_op.into(),
1✔
1287
            },
1✔
1288
        })
1✔
1289
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1290
        .await?;
1✔
1291

1292
        let x_query_resolution = output_bounds.size_x() / 480.; // since we request x -180 to 180 and y -90 to 90 with 60x60 tiles this will result in 8 x 4 tiles
1✔
1293
        let y_query_resolution = output_bounds.size_y() / 240.; // *2 to account for the dataset aspect ratio 2:1
1✔
1294
        let spatial_resolution =
1✔
1295
            SpatialResolution::new_unchecked(x_query_resolution, y_query_resolution);
1✔
1296

1297
        let qp = initialized_operator
1✔
1298
            .query_processor()
1✔
1299
            .unwrap()
1✔
1300
            .get_u8()
1✔
1301
            .unwrap();
1✔
1302

1303
        let qs = qp
1✔
1304
            .raster_query(
1✔
1305
                QueryRectangle {
1✔
1306
                    spatial_bounds: output_bounds,
1✔
1307
                    time_interval,
1✔
1308
                    spatial_resolution,
1✔
1309
                    attributes: BandSelection::first(),
1✔
1310
                },
1✔
1311
                &query_ctx,
1✔
1312
            )
1✔
1313
            .await
1✔
1314
            .unwrap();
1✔
1315

1316
        let tiles = qs
1✔
1317
            .map(Result::unwrap)
1✔
1318
            .collect::<Vec<RasterTile2D<u8>>>()
1✔
1319
            .await;
1✔
1320

1321
        // the test must generate 8x4 tiles
1322
        assert_eq!(tiles.len(), 32);
1✔
1323

1324
        // none of the tiles should be empty
1325
        assert!(tiles.iter().all(|t| !t.is_empty()));
32✔
1326

1327
        Ok(())
2✔
1328
    }
1✔
1329

1330
    #[test]
1331
    fn source_resolution() {
1✔
1332
        let epsg_4326 = SpatialReference::epsg_4326();
1✔
1333
        let epsg_3857 = SpatialReference::new(SpatialReferenceAuthority::Epsg, 3857);
1✔
1334

1335
        // use ndvi dataset that was reprojected using gdal as ground truth
1336
        let dataset_4326 = gdal_open_dataset(test_data!(
1✔
1337
            "raster/modis_ndvi/MOD13A2_M_NDVI_2014-04-01.TIFF"
1338
        ))
1339
        .unwrap();
1✔
1340
        let geotransform_4326 = dataset_4326.geo_transform().unwrap();
1✔
1341
        let res_4326 = SpatialResolution::new(geotransform_4326[1], -geotransform_4326[5]).unwrap();
1✔
1342

1343
        let dataset_3857 = gdal_open_dataset(test_data!(
1✔
1344
            "raster/modis_ndvi/projected_3857/MOD13A2_M_NDVI_2014-04-01.TIFF"
1345
        ))
1346
        .unwrap();
1✔
1347
        let geotransform_3857 = dataset_3857.geo_transform().unwrap();
1✔
1348
        let res_3857 = SpatialResolution::new(geotransform_3857[1], -geotransform_3857[5]).unwrap();
1✔
1349

1350
        // ndvi was projected from 4326 to 3857. The calculated source_resolution for getting the raster in 3857 with `res_3857`
1351
        // should thus roughly be like the original `res_4326`
1352
        let result_res = suggest_pixel_size_from_diag_cross_projected::<SpatialPartition2D>(
1✔
1353
            epsg_3857.area_of_use_projected().unwrap(),
1✔
1354
            epsg_4326.area_of_use_projected().unwrap(),
1✔
1355
            res_3857,
1✔
1356
        )
1357
        .unwrap();
1✔
1358
        assert!(1. - (result_res.x / res_4326.x).abs() < 0.02);
1✔
1359
        assert!(1. - (result_res.y / res_4326.y).abs() < 0.02);
1✔
1360
    }
1✔
1361

1362
    #[tokio::test]
1363
    async fn query_outside_projection_area_of_use_produces_empty_tiles() {
1✔
1364
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1365
        let query_ctx = MockQueryContext::test_default();
1✔
1366

1367
        let m = GdalMetaDataStatic {
1✔
1368
            time: Some(TimeInterval::default()),
1✔
1369
            params: GdalDatasetParameters {
1✔
1370
                file_path: PathBuf::new(),
1✔
1371
                rasterband_channel: 1,
1✔
1372
                geo_transform: GdalDatasetGeoTransform {
1✔
1373
                    origin_coordinate: (166_021.44, 9_329_005.188).into(),
1✔
1374
                    x_pixel_size: (534_994.66 - 166_021.444) / 100.,
1✔
1375
                    y_pixel_size: -9_329_005.18 / 100.,
1✔
1376
                },
1✔
1377
                width: 100,
1✔
1378
                height: 100,
1✔
1379
                file_not_found_handling: FileNotFoundHandling::NoData,
1✔
1380
                no_data_value: Some(0.),
1✔
1381
                properties_mapping: None,
1✔
1382
                gdal_open_options: None,
1✔
1383
                gdal_config_options: None,
1✔
1384
                allow_alphaband_as_mask: true,
1✔
1385
                retry: None,
1✔
1386
            },
1✔
1387
            result_descriptor: RasterResultDescriptor {
1✔
1388
                data_type: RasterDataType::U8,
1✔
1389
                spatial_reference: SpatialReference::new(SpatialReferenceAuthority::Epsg, 32636)
1✔
1390
                    .into(),
1✔
1391
                time: None,
1✔
1392
                bbox: None,
1✔
1393
                resolution: None,
1✔
1394
                bands: RasterBandDescriptors::new_single_band(),
1✔
1395
            },
1✔
1396
            cache_ttl: CacheTtlSeconds::default(),
1✔
1397
        };
1✔
1398

1399
        let id: DataId = DatasetId::new().into();
1✔
1400
        let name = NamedData::with_system_name("ndvi");
1✔
1401
        exe_ctx.add_meta_data(id.clone(), name.clone(), Box::new(m));
1✔
1402

1403
        exe_ctx.tiling_specification =
1✔
1404
            TilingSpecification::new((0.0, 0.0).into(), [600, 600].into());
1✔
1405

1406
        let output_shape: GridShape2D = [1000, 1000].into();
1✔
1407
        let output_bounds =
1✔
1408
            SpatialPartition2D::new_unchecked((-180., 0.).into(), (180., -90.).into());
1✔
1409
        let time_interval = TimeInterval::new_instant(1_388_534_400_000).unwrap(); // 2014-01-01
1✔
1410

1411
        let gdal_op = GdalSource {
1✔
1412
            params: GdalSourceParameters { data: name },
1✔
1413
        }
1✔
1414
        .boxed();
1✔
1415

1416
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1417
            params: ReprojectionParams {
1✔
1418
                target_spatial_reference: SpatialReference::epsg_4326(),
1✔
1419
            },
1✔
1420
            sources: SingleRasterOrVectorSource {
1✔
1421
                source: gdal_op.into(),
1✔
1422
            },
1✔
1423
        })
1✔
1424
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1425
        .await
1✔
1426
        .unwrap();
1✔
1427

1428
        let x_query_resolution = output_bounds.size_x() / output_shape.axis_size_x() as f64;
1✔
1429
        let y_query_resolution = output_bounds.size_y() / (output_shape.axis_size_y()) as f64;
1✔
1430
        let spatial_resolution =
1✔
1431
            SpatialResolution::new_unchecked(x_query_resolution, y_query_resolution);
1✔
1432

1433
        let qp = initialized_operator
1✔
1434
            .query_processor()
1✔
1435
            .unwrap()
1✔
1436
            .get_u8()
1✔
1437
            .unwrap();
1✔
1438

1439
        let result = qp
1✔
1440
            .raster_query(
1✔
1441
                QueryRectangle {
1✔
1442
                    spatial_bounds: output_bounds,
1✔
1443
                    time_interval,
1✔
1444
                    spatial_resolution,
1✔
1445
                    attributes: BandSelection::first(),
1✔
1446
                },
1✔
1447
                &query_ctx,
1✔
1448
            )
1✔
1449
            .await
1✔
1450
            .unwrap()
1✔
1451
            .map(Result::unwrap)
1✔
1452
            .collect::<Vec<_>>()
1✔
1453
            .await;
1✔
1454

1455
        assert_eq!(result.len(), 4);
1✔
1456

1457
        for r in result {
5✔
1458
            assert!(r.is_empty());
4✔
1459
        }
1✔
1460
    }
1✔
1461

1462
    #[tokio::test]
1463
    async fn points_from_wgs84_to_utm36n() {
1✔
1464
        let exe_ctx = MockExecutionContext::test_default();
1✔
1465
        let query_ctx = MockQueryContext::test_default();
1✔
1466

1467
        let point_source = MockFeatureCollectionSource::single(
1✔
1468
            MultiPointCollection::from_data(
1✔
1469
                MultiPoint::many(vec![
1✔
1470
                    vec![(30.0, 0.0)], // lower left of utm36n area of use
1✔
1471
                    vec![(36.0, 84.0)],
1✔
1472
                    vec![(33.0, 42.0)], // upper right of utm36n area of use
1✔
1473
                ])
1474
                .unwrap(),
1✔
1475
                vec![TimeInterval::default(); 3],
1✔
1476
                HashMap::default(),
1✔
1477
                CacheHint::default(),
1✔
1478
            )
1479
            .unwrap(),
1✔
1480
        )
1481
        .boxed();
1✔
1482

1483
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
1484
            params: ReprojectionParams {
1✔
1485
                target_spatial_reference: SpatialReference::new(
1✔
1486
                    SpatialReferenceAuthority::Epsg,
1✔
1487
                    32636, // utm36n
1✔
1488
                ),
1✔
1489
            },
1✔
1490
            sources: SingleRasterOrVectorSource {
1✔
1491
                source: point_source.into(),
1✔
1492
            },
1✔
1493
        })
1✔
1494
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1495
        .await
1✔
1496
        .unwrap();
1✔
1497

1498
        let qp = initialized_operator
1✔
1499
            .query_processor()
1✔
1500
            .unwrap()
1✔
1501
            .multi_point()
1✔
1502
            .unwrap();
1✔
1503

1504
        let spatial_bounds = BoundingBox2D::new(
1✔
1505
            (166_021.44, 0.00).into(), // lower left of projected utm36n area of use
1✔
1506
            (534_994.666_6, 9_329_005.18).into(), // upper right of projected utm36n area of use
1✔
1507
        )
1508
        .unwrap();
1✔
1509

1510
        let qs = qp
1✔
1511
            .vector_query(
1✔
1512
                QueryRectangle {
1✔
1513
                    spatial_bounds,
1✔
1514
                    time_interval: TimeInterval::default(),
1✔
1515
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1516
                    attributes: ColumnSelection::all(),
1✔
1517
                },
1✔
1518
                &query_ctx,
1✔
1519
            )
1✔
1520
            .await
1✔
1521
            .unwrap();
1✔
1522

1523
        let points = qs.map(Result::unwrap).collect::<Vec<_>>().await;
1✔
1524

1525
        assert_eq!(points.len(), 1);
1✔
1526

1527
        let points = &points[0];
1✔
1528

1529
        assert_eq!(
1✔
1530
            points.coordinates(),
1✔
1531
            &[
1✔
1532
                (166_021.443_080_538_42, 0.0).into(),
1✔
1533
                (534_994.655_061_136_1, 9_329_005.182_447_437).into(),
1✔
1534
                (499_999.999_999_999_5, 4_649_776.224_819_178).into()
1✔
1535
            ]
1✔
1536
        );
1✔
1537
    }
1✔
1538

1539
    #[tokio::test]
1540
    async fn points_from_utm36n_to_wgs84() {
1✔
1541
        let exe_ctx = MockExecutionContext::test_default();
1✔
1542
        let query_ctx = MockQueryContext::test_default();
1✔
1543

1544
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
1545
            vec![
1✔
1546
                MultiPointCollection::from_data(
1✔
1547
                    MultiPoint::many(vec![
1✔
1548
                        vec![(166_021.443_080_538_42, 0.0)],
1✔
1549
                        vec![(534_994.655_061_136_1, 9_329_005.182_447_437)],
1✔
1550
                        vec![(499_999.999_999_999_5, 4_649_776.224_819_178)],
1✔
1551
                    ])
1552
                    .unwrap(),
1✔
1553
                    vec![TimeInterval::default(); 3],
1✔
1554
                    HashMap::default(),
1✔
1555
                    CacheHint::default(),
1✔
1556
                )
1557
                .unwrap(),
1✔
1558
            ],
1559
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 32636), //utm36n
1✔
1560
        )
1561
        .boxed();
1✔
1562

1563
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
1564
            params: ReprojectionParams {
1✔
1565
                target_spatial_reference: SpatialReference::new(
1✔
1566
                    SpatialReferenceAuthority::Epsg,
1✔
1567
                    4326, // utm36n
1✔
1568
                ),
1✔
1569
            },
1✔
1570
            sources: SingleRasterOrVectorSource {
1✔
1571
                source: point_source.into(),
1✔
1572
            },
1✔
1573
        })
1✔
1574
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1575
        .await
1✔
1576
        .unwrap();
1✔
1577

1578
        let qp = initialized_operator
1✔
1579
            .query_processor()
1✔
1580
            .unwrap()
1✔
1581
            .multi_point()
1✔
1582
            .unwrap();
1✔
1583

1584
        let spatial_bounds = BoundingBox2D::new(
1✔
1585
            (30.0, 0.0).into(),  // lower left of utm36n area of use
1✔
1586
            (33.0, 42.0).into(), // upper right of utm36n area of use
1✔
1587
        )
1588
        .unwrap();
1✔
1589

1590
        let qs = qp
1✔
1591
            .vector_query(
1✔
1592
                QueryRectangle {
1✔
1593
                    spatial_bounds,
1✔
1594
                    time_interval: TimeInterval::default(),
1✔
1595
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1596
                    attributes: ColumnSelection::all(),
1✔
1597
                },
1✔
1598
                &query_ctx,
1✔
1599
            )
1✔
1600
            .await
1✔
1601
            .unwrap();
1✔
1602

1603
        let points = qs.map(Result::unwrap).collect::<Vec<_>>().await;
1✔
1604

1605
        assert_eq!(points.len(), 1);
1✔
1606

1607
        let points = &points[0];
1✔
1608

1609
        assert!(approx_eq!(
1✔
1610
            &[Coordinate2D],
1✔
1611
            points.coordinates(),
1✔
1612
            &[
1✔
1613
                (30.0, 0.0).into(), // lower left of utm36n area of use
1✔
1614
                (36.0, 84.0).into(),
1✔
1615
                (33.0, 42.0).into(), // upper right of utm36n area of use
1✔
1616
            ]
1✔
1617
        ));
1✔
1618
    }
1✔
1619

1620
    #[tokio::test]
1621
    async fn points_from_utm36n_to_wgs84_out_of_area() {
1✔
1622
        // This test checks that points that are outside the area of use of the target spatial reference are not projected and an empty collection is returned
1623

1624
        let exe_ctx = MockExecutionContext::test_default();
1✔
1625
        let query_ctx = MockQueryContext::test_default();
1✔
1626

1627
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
1628
            vec![
1✔
1629
                MultiPointCollection::from_data(
1✔
1630
                    MultiPoint::many(vec![
1✔
1631
                        vec![(758_565., 4_928_353.)], // (12.25, 44,46)
1✔
1632
                    ])
1633
                    .unwrap(),
1✔
1634
                    vec![TimeInterval::default(); 1],
1✔
1635
                    HashMap::default(),
1✔
1636
                    CacheHint::default(),
1✔
1637
                )
1638
                .unwrap(),
1✔
1639
            ],
1640
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 32636), //utm36n
1✔
1641
        )
1642
        .boxed();
1✔
1643

1644
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
1645
            params: ReprojectionParams {
1✔
1646
                target_spatial_reference: SpatialReference::new(
1✔
1647
                    SpatialReferenceAuthority::Epsg,
1✔
1648
                    4326, // utm36n
1✔
1649
                ),
1✔
1650
            },
1✔
1651
            sources: SingleRasterOrVectorSource {
1✔
1652
                source: point_source.into(),
1✔
1653
            },
1✔
1654
        })
1✔
1655
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1656
        .await
1✔
1657
        .unwrap();
1✔
1658

1659
        let qp = initialized_operator
1✔
1660
            .query_processor()
1✔
1661
            .unwrap()
1✔
1662
            .multi_point()
1✔
1663
            .unwrap();
1✔
1664

1665
        let spatial_bounds = BoundingBox2D::new(
1✔
1666
            (10.0, 0.0).into(),  // -20 x values left of lower left of utm36n area of use
1✔
1667
            (13.0, 42.0).into(), // -20 x values left of upper right of utm36n area of use
1✔
1668
        )
1669
        .unwrap();
1✔
1670

1671
        let qs = qp
1✔
1672
            .vector_query(
1✔
1673
                QueryRectangle {
1✔
1674
                    spatial_bounds,
1✔
1675
                    time_interval: TimeInterval::default(),
1✔
1676
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1677
                    attributes: ColumnSelection::all(),
1✔
1678
                },
1✔
1679
                &query_ctx,
1✔
1680
            )
1✔
1681
            .await
1✔
1682
            .unwrap();
1✔
1683

1684
        let points = qs.map(Result::unwrap).collect::<Vec<_>>().await;
1✔
1685

1686
        assert_eq!(points.len(), 1);
1✔
1687

1688
        let points = &points[0];
1✔
1689

1690
        assert!(geoengine_datatypes::collections::FeatureCollectionInfos::is_empty(points));
1✔
1691
        assert!(points.coordinates().is_empty());
1✔
1692
    }
1✔
1693

1694
    #[test]
1695
    fn it_derives_raster_result_descriptor() {
1✔
1696
        let in_proj = SpatialReference::epsg_4326();
1✔
1697
        let out_proj = SpatialReference::from_str("EPSG:3857").unwrap();
1✔
1698
        let bbox = Some(SpatialPartition2D::new_unchecked(
1✔
1699
            (-180., 90.).into(),
1✔
1700
            (180., -90.).into(),
1✔
1701
        ));
1✔
1702

1703
        let resolution = Some(SpatialResolution::new_unchecked(0.1, 0.1));
1✔
1704

1705
        let (in_bounds, out_bounds, out_res) =
1✔
1706
            InitializedRasterReprojection::derive_raster_in_bounds_out_bounds_out_res(
1✔
1707
                in_proj, out_proj, resolution, bbox,
1✔
1708
            )
1✔
1709
            .unwrap();
1✔
1710

1711
        assert_eq!(
1✔
1712
            in_bounds.unwrap(),
1✔
1713
            SpatialPartition2D::new_unchecked((-180., 85.06).into(), (180., -85.06).into(),)
1✔
1714
        );
1715

1716
        assert_eq!(
1✔
1717
            out_bounds.unwrap(),
1✔
1718
            out_proj
1✔
1719
                .area_of_use_projected::<SpatialPartition2D>()
1✔
1720
                .unwrap()
1✔
1721
        );
1722

1723
        // TODO: y resolution should be double the x resolution, but currently we only compute a uniform resolution
1724
        assert_eq!(
1✔
1725
            out_res.unwrap(),
1✔
1726
            SpatialResolution::new_unchecked(14_237.781_884_528_267, 14_237.781_884_528_267),
1✔
1727
        );
1728
    }
1✔
1729
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc