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

geo-engine / geoengine / 11911118784

19 Nov 2024 10:06AM UTC coverage: 90.448% (-0.2%) from 90.687%
11911118784

push

github

web-flow
Merge pull request #994 from geo-engine/workspace-dependencies

use workspace dependencies, update toolchain, use global lock in expression

9 of 11 new or added lines in 6 files covered. (81.82%)

369 existing lines in 74 files now uncovered.

132871 of 146904 relevant lines covered (90.45%)

54798.62 hits per line

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

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

3
use super::map_query::MapQueryProcessor;
4
use crate::{
5
    adapters::{
6
        fold_by_coordinate_lookup_future, FillerTileCacheExpirationStrategy, FillerTimeBounds,
7
        RasterSubQueryAdapter, SparseTilesFillAdapter, TileReprojectionSubQuery,
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::{stream, StreamExt};
22
use geoengine_datatypes::{
23
    collections::FeatureCollection,
24
    operations::reproject::{
25
        reproject_and_unify_bbox, reproject_query, suggest_pixel_size_from_diag_cross_projected,
26
        CoordinateProjection, CoordinateProjector, Reproject, ReprojectClipped,
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)]
2✔
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
    result_descriptor: VectorResultDescriptor,
61
    source: Box<dyn InitializedVectorOperator>,
62
    source_srs: SpatialReference,
63
    target_srs: SpatialReference,
64
}
65

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

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

90
        let in_srs = Into::<Option<SpatialReference>>::into(in_desc.spatial_reference)
6✔
91
            .ok_or(Error::AllSourcesMustHaveSameSpatialReference)?;
6✔
92

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

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

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

6✔
110
        Ok(InitializedVectorReprojection {
6✔
111
            name,
6✔
112
            result_descriptor: out_desc,
6✔
113
            source: source_vector_operator,
6✔
114
            source_srs: in_srs,
6✔
115
            target_srs: params.target_spatial_reference,
6✔
116
        })
6✔
117
    }
6✔
118
}
119

120
impl InitializedRasterReprojection {
121
    pub fn try_new_with_input(
6✔
122
        name: CanonicOperatorName,
6✔
123
        params: ReprojectionParams,
6✔
124
        source_raster_operator: Box<dyn InitializedRasterOperator>,
6✔
125
        tiling_spec: TilingSpecification,
6✔
126
    ) -> Result<Self> {
6✔
127
        let in_desc: RasterResultDescriptor = source_raster_operator.result_descriptor().clone();
6✔
128

129
        let in_srs = Into::<Option<SpatialReference>>::into(in_desc.spatial_reference)
6✔
130
            .ok_or(Error::AllSourcesMustHaveSameSpatialReference)?;
6✔
131

132
        // calculate the intersection of input and output srs in both coordinate systems
133
        let (in_bounds, out_bounds, out_res) = Self::derive_raster_in_bounds_out_bounds_out_res(
6✔
134
            in_srs,
6✔
135
            params.target_spatial_reference,
6✔
136
            in_desc.resolution,
6✔
137
            in_desc.bbox,
6✔
138
        )?;
6✔
139

140
        let result_descriptor = RasterResultDescriptor {
4✔
141
            spatial_reference: params.target_spatial_reference.into(),
4✔
142
            data_type: in_desc.data_type,
4✔
143
            time: in_desc.time,
4✔
144
            bbox: out_bounds,
4✔
145
            resolution: out_res,
4✔
146
            bands: in_desc.bands.clone(),
4✔
147
        };
4✔
148

149
        let state = match (in_bounds, out_bounds) {
4✔
150
            (Some(in_bounds), Some(out_bounds)) => Some(ReprojectionBounds {
4✔
151
                valid_in_bounds: in_bounds,
4✔
152
                valid_out_bounds: out_bounds,
4✔
153
            }),
4✔
154
            _ => None,
×
155
        };
156

157
        Ok(InitializedRasterReprojection {
4✔
158
            name,
4✔
159
            result_descriptor,
4✔
160
            source: source_raster_operator,
4✔
161
            state,
4✔
162
            source_srs: in_srs,
4✔
163
            target_srs: params.target_spatial_reference,
4✔
164
            tiling_spec,
4✔
165
        })
4✔
166
    }
6✔
167

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

185
            (valid_bounds_in, valid_bounds_out)
3✔
186
        };
187

188
        let out_res = match (source_spatial_resolution, in_bbox, out_bbox) {
5✔
189
            (Some(in_res), Some(in_bbox), Some(out_bbox)) => {
3✔
190
                suggest_pixel_size_from_diag_cross_projected(in_bbox, out_bbox, in_res).ok()
3✔
191
            }
192
            _ => None,
2✔
193
        };
194

195
        Ok((in_bbox, out_bbox, out_res))
5✔
196
    }
7✔
197
}
198

199
#[typetag::serde]
1✔
200
#[async_trait]
201
impl VectorOperator for Reprojection {
202
    async fn _initialize(
203
        self: Box<Self>,
204
        path: WorkflowOperatorPath,
205
        context: &dyn ExecutionContext,
206
    ) -> Result<Box<dyn InitializedVectorOperator>> {
7✔
207
        let name = CanonicOperatorName::from(&self);
7✔
208

209
        let vector_source =
6✔
210
            self.sources
7✔
211
                .vector()
7✔
212
                .ok_or_else(|| error::Error::InvalidOperatorType {
7✔
213
                    expected: "Vector".to_owned(),
1✔
214
                    found: "Raster".to_owned(),
1✔
215
                })?;
7✔
216

217
        let initialized_source = vector_source.initialize_sources(path, context).await?;
6✔
218

219
        let initialized_operator = InitializedVectorReprojection::try_new_with_input(
6✔
220
            name,
6✔
221
            self.params,
6✔
222
            initialized_source.vector,
6✔
223
        )?;
6✔
224

225
        Ok(initialized_operator.boxed())
6✔
226
    }
14✔
227

228
    span_fn!(Reprojection);
229
}
230

231
impl InitializedVectorOperator for InitializedVectorReprojection {
232
    fn result_descriptor(&self) -> &VectorResultDescriptor {
×
233
        &self.result_descriptor
×
234
    }
×
235

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

285
    fn canonic_name(&self) -> CanonicOperatorName {
×
286
        self.name.clone()
×
287
    }
×
288
}
289

290
struct VectorReprojectionProcessor<Q, G>
291
where
292
    Q: VectorQueryProcessor<VectorType = FeatureCollection<G>>,
293
{
294
    source: Q,
295
    result_descriptor: VectorResultDescriptor,
296
    from: SpatialReference,
297
    to: SpatialReference,
298
}
299

300
impl<Q, G> VectorReprojectionProcessor<Q, G>
301
where
302
    Q: VectorQueryProcessor<VectorType = FeatureCollection<G>>,
303
{
304
    pub fn new(
6✔
305
        source: Q,
6✔
306
        result_descriptor: VectorResultDescriptor,
6✔
307
        from: SpatialReference,
6✔
308
        to: SpatialReference,
6✔
309
    ) -> Self {
6✔
310
        Self {
6✔
311
            source,
6✔
312
            result_descriptor,
6✔
313
            from,
6✔
314
            to,
6✔
315
        }
6✔
316
    }
6✔
317
}
318

319
#[async_trait]
320
impl<Q, G> QueryProcessor for VectorReprojectionProcessor<Q, G>
321
where
322
    Q: QueryProcessor<
323
        Output = FeatureCollection<G>,
324
        SpatialBounds = BoundingBox2D,
325
        Selection = ColumnSelection,
326
        ResultDescription = VectorResultDescriptor,
327
    >,
328
    FeatureCollection<G>: Reproject<CoordinateProjector, Out = FeatureCollection<G>>,
329
    G: Geometry + ArrowTyped,
330
{
331
    type Output = FeatureCollection<G>;
332
    type SpatialBounds = BoundingBox2D;
333
    type Selection = ColumnSelection;
334
    type ResultDescription = VectorResultDescriptor;
335

336
    async fn _query<'a>(
337
        &'a self,
338
        query: VectorQueryRectangle,
339
        ctx: &'a dyn QueryContext,
340
    ) -> Result<BoxStream<'a, Result<Self::Output>>> {
6✔
341
        let rewritten_query = reproject_query(query, self.from, self.to)?;
6✔
342

343
        if let Some(rewritten_query) = rewritten_query {
6✔
344
            Ok(self
5✔
345
                .source
5✔
346
                .query(rewritten_query, ctx)
5✔
UNCOV
347
                .await?
×
348
                .map(move |collection_result| {
5✔
349
                    collection_result.and_then(|collection| {
5✔
350
                        CoordinateProjector::from_known_srs(self.from, self.to)
5✔
351
                            .and_then(|projector| collection.reproject(projector.as_ref()))
5✔
352
                            .map_err(Into::into)
5✔
353
                    })
5✔
354
                })
5✔
355
                .boxed())
5✔
356
        } else {
357
            let res = Ok(FeatureCollection::empty());
1✔
358
            Ok(Box::pin(stream::once(async { res })))
1✔
359
        }
360
    }
12✔
361

362
    fn result_descriptor(&self) -> &VectorResultDescriptor {
12✔
363
        &self.result_descriptor
12✔
364
    }
12✔
365
}
366

367
#[typetag::serde]
×
368
#[async_trait]
369
impl RasterOperator for Reprojection {
370
    async fn _initialize(
371
        self: Box<Self>,
372
        path: WorkflowOperatorPath,
373
        context: &dyn ExecutionContext,
374
    ) -> Result<Box<dyn InitializedRasterOperator>> {
4✔
375
        let name = CanonicOperatorName::from(&self);
4✔
376

377
        let raster_source =
4✔
378
            self.sources
4✔
379
                .raster()
4✔
380
                .ok_or_else(|| error::Error::InvalidOperatorType {
4✔
381
                    expected: "Raster".to_owned(),
×
382
                    found: "Vector".to_owned(),
×
383
                })?;
4✔
384

385
        let initialized_source = raster_source.initialize_sources(path, context).await?;
4✔
386

387
        let initialized_operator = InitializedRasterReprojection::try_new_with_input(
4✔
388
            name,
4✔
389
            self.params,
4✔
390
            initialized_source.raster,
4✔
391
            context.tiling_specification(),
4✔
392
        )?;
4✔
393

394
        Ok(initialized_operator.boxed())
4✔
395
    }
8✔
396

397
    span_fn!(Reprojection);
398
}
399

400
impl InitializedRasterOperator for InitializedRasterReprojection {
401
    fn result_descriptor(&self) -> &RasterResultDescriptor {
×
402
        &self.result_descriptor
×
403
    }
×
404

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

410
        Ok(match self.result_descriptor.data_type {
4✔
411
            geoengine_datatypes::raster::RasterDataType::U8 => {
412
                let qt = q
4✔
413
                    .get_u8()
4✔
414
                    .expect("the result descriptor and query processor type should match");
4✔
415
                TypedRasterQueryProcessor::U8(Box::new(RasterReprojectionProcessor::new(
4✔
416
                    qt,
4✔
417
                    self.result_descriptor.clone(),
4✔
418
                    self.source_srs,
4✔
419
                    self.target_srs,
4✔
420
                    self.tiling_spec,
4✔
421
                    self.state,
4✔
422
                )))
4✔
423
            }
424
            geoengine_datatypes::raster::RasterDataType::U16 => {
425
                let qt = q
×
426
                    .get_u16()
×
427
                    .expect("the result descriptor and query processor type should match");
×
428
                TypedRasterQueryProcessor::U16(Box::new(RasterReprojectionProcessor::new(
×
429
                    qt,
×
430
                    self.result_descriptor.clone(),
×
431
                    self.source_srs,
×
432
                    self.target_srs,
×
433
                    self.tiling_spec,
×
434
                    self.state,
×
435
                )))
×
436
            }
437

438
            geoengine_datatypes::raster::RasterDataType::U32 => {
439
                let qt = q
×
440
                    .get_u32()
×
441
                    .expect("the result descriptor and query processor type should match");
×
442
                TypedRasterQueryProcessor::U32(Box::new(RasterReprojectionProcessor::new(
×
443
                    qt,
×
444
                    self.result_descriptor.clone(),
×
445
                    self.source_srs,
×
446
                    self.target_srs,
×
447
                    self.tiling_spec,
×
448
                    self.state,
×
449
                )))
×
450
            }
451
            geoengine_datatypes::raster::RasterDataType::U64 => {
452
                let qt = q
×
453
                    .get_u64()
×
454
                    .expect("the result descriptor and query processor type should match");
×
455
                TypedRasterQueryProcessor::U64(Box::new(RasterReprojectionProcessor::new(
×
456
                    qt,
×
457
                    self.result_descriptor.clone(),
×
458
                    self.source_srs,
×
459
                    self.target_srs,
×
460
                    self.tiling_spec,
×
461
                    self.state,
×
462
                )))
×
463
            }
464
            geoengine_datatypes::raster::RasterDataType::I8 => {
465
                let qt = q
×
466
                    .get_i8()
×
467
                    .expect("the result descriptor and query processor type should match");
×
468
                TypedRasterQueryProcessor::I8(Box::new(RasterReprojectionProcessor::new(
×
469
                    qt,
×
470
                    self.result_descriptor.clone(),
×
471
                    self.source_srs,
×
472
                    self.target_srs,
×
473
                    self.tiling_spec,
×
474
                    self.state,
×
475
                )))
×
476
            }
477
            geoengine_datatypes::raster::RasterDataType::I16 => {
478
                let qt = q
×
479
                    .get_i16()
×
480
                    .expect("the result descriptor and query processor type should match");
×
481
                TypedRasterQueryProcessor::I16(Box::new(RasterReprojectionProcessor::new(
×
482
                    qt,
×
483
                    self.result_descriptor.clone(),
×
484
                    self.source_srs,
×
485
                    self.target_srs,
×
486
                    self.tiling_spec,
×
487
                    self.state,
×
488
                )))
×
489
            }
490
            geoengine_datatypes::raster::RasterDataType::I32 => {
491
                let qt = q
×
492
                    .get_i32()
×
493
                    .expect("the result descriptor and query processor type should match");
×
494
                TypedRasterQueryProcessor::I32(Box::new(RasterReprojectionProcessor::new(
×
495
                    qt,
×
496
                    self.result_descriptor.clone(),
×
497
                    self.source_srs,
×
498
                    self.target_srs,
×
499
                    self.tiling_spec,
×
500
                    self.state,
×
501
                )))
×
502
            }
503
            geoengine_datatypes::raster::RasterDataType::I64 => {
504
                let qt = q
×
505
                    .get_i64()
×
506
                    .expect("the result descriptor and query processor type should match");
×
507
                TypedRasterQueryProcessor::I64(Box::new(RasterReprojectionProcessor::new(
×
508
                    qt,
×
509
                    self.result_descriptor.clone(),
×
510
                    self.source_srs,
×
511
                    self.target_srs,
×
512
                    self.tiling_spec,
×
513
                    self.state,
×
514
                )))
×
515
            }
516
            geoengine_datatypes::raster::RasterDataType::F32 => {
517
                let qt = q
×
518
                    .get_f32()
×
519
                    .expect("the result descriptor and query processor type should match");
×
520
                TypedRasterQueryProcessor::F32(Box::new(RasterReprojectionProcessor::new(
×
521
                    qt,
×
522
                    self.result_descriptor.clone(),
×
523
                    self.source_srs,
×
524
                    self.target_srs,
×
525
                    self.tiling_spec,
×
526
                    self.state,
×
527
                )))
×
528
            }
529
            geoengine_datatypes::raster::RasterDataType::F64 => {
530
                let qt = q
×
531
                    .get_f64()
×
532
                    .expect("the result descriptor and query processor type should match");
×
533
                TypedRasterQueryProcessor::F64(Box::new(RasterReprojectionProcessor::new(
×
534
                    qt,
×
535
                    self.result_descriptor.clone(),
×
536
                    self.source_srs,
×
537
                    self.target_srs,
×
538
                    self.tiling_spec,
×
539
                    self.state,
×
540
                )))
×
541
            }
542
        })
543
    }
4✔
544

545
    fn canonic_name(&self) -> CanonicOperatorName {
×
546
        self.name.clone()
×
547
    }
×
548
}
549

550
pub struct RasterReprojectionProcessor<Q, P>
551
where
552
    Q: RasterQueryProcessor<RasterType = P>,
553
{
554
    source: Q,
555
    result_descriptor: RasterResultDescriptor,
556
    from: SpatialReference,
557
    to: SpatialReference,
558
    tiling_spec: TilingSpecification,
559
    state: Option<ReprojectionBounds>,
560
    _phantom_data: PhantomData<P>,
561
}
562

563
impl<Q, P> RasterReprojectionProcessor<Q, P>
564
where
565
    Q: QueryProcessor<
566
        Output = RasterTile2D<P>,
567
        SpatialBounds = SpatialPartition2D,
568
        Selection = BandSelection,
569
        ResultDescription = RasterResultDescriptor,
570
    >,
571
    P: Pixel,
572
{
573
    pub fn new(
4✔
574
        source: Q,
4✔
575
        result_descriptor: RasterResultDescriptor,
4✔
576
        from: SpatialReference,
4✔
577
        to: SpatialReference,
4✔
578
        tiling_spec: TilingSpecification,
4✔
579
        state: Option<ReprojectionBounds>,
4✔
580
    ) -> Self {
4✔
581
        Self {
4✔
582
            source,
4✔
583
            result_descriptor,
4✔
584
            from,
4✔
585
            to,
4✔
586
            tiling_spec,
4✔
587
            state,
4✔
588
            _phantom_data: PhantomData,
4✔
589
        }
4✔
590
    }
4✔
591
}
592

593
#[async_trait]
594
impl<Q, P> QueryProcessor for RasterReprojectionProcessor<Q, P>
595
where
596
    Q: QueryProcessor<
597
        Output = RasterTile2D<P>,
598
        SpatialBounds = SpatialPartition2D,
599
        Selection = BandSelection,
600
        ResultDescription = RasterResultDescriptor,
601
    >,
602
    P: Pixel,
603
{
604
    type Output = RasterTile2D<P>;
605
    type SpatialBounds = SpatialPartition2D;
606
    type Selection = BandSelection;
607
    type ResultDescription = RasterResultDescriptor;
608

609
    async fn _query<'a>(
610
        &'a self,
611
        query: RasterQueryRectangle,
612
        ctx: &'a dyn QueryContext,
613
    ) -> Result<BoxStream<'a, Result<Self::Output>>> {
4✔
614
        if let Some(state) = &self.state {
4✔
615
            let valid_bounds_in = state.valid_in_bounds;
4✔
616
            let valid_bounds_out = state.valid_out_bounds;
4✔
617

618
            // calculate the spatial resolution the input data should have using the intersection and the requested resolution
619
            let in_spatial_res = suggest_pixel_size_from_diag_cross_projected(
4✔
620
                valid_bounds_out,
4✔
621
                valid_bounds_in,
4✔
622
                query.spatial_resolution,
4✔
623
            )?;
4✔
624

625
            // setup the subquery
626
            let sub_query_spec = TileReprojectionSubQuery {
4✔
627
                in_srs: self.from,
4✔
628
                out_srs: self.to,
4✔
629
                fold_fn: fold_by_coordinate_lookup_future,
4✔
630
                in_spatial_res,
4✔
631
                valid_bounds_in,
4✔
632
                valid_bounds_out,
4✔
633
                _phantom_data: PhantomData,
4✔
634
            };
4✔
635

4✔
636
            // return the adapter which will reproject the tiles and uses the fill adapter to inject missing tiles
4✔
637
            Ok(RasterSubQueryAdapter::<'a, P, _, _>::new(
4✔
638
                &self.source,
4✔
639
                query,
4✔
640
                self.tiling_spec,
4✔
641
                ctx,
4✔
642
                sub_query_spec,
4✔
643
            )
4✔
644
            .filter_and_fill(FillerTileCacheExpirationStrategy::DerivedFromSurroundingTiles))
4✔
645
        } else {
UNCOV
646
            log::debug!("No intersection between source data / srs and target srs");
×
647

UNCOV
648
            let tiling_strat = self
×
649
                .tiling_spec
×
650
                .strategy(query.spatial_resolution.x, -query.spatial_resolution.y);
×
651

×
652
            let grid_bounds = tiling_strat.tile_grid_box(query.spatial_partition());
×
653
            Ok(Box::pin(SparseTilesFillAdapter::new(
×
654
                stream::empty(),
×
655
                grid_bounds,
×
656
                query.attributes.count(),
×
657
                tiling_strat.geo_transform,
×
658
                self.tiling_spec.tile_size_in_pixels,
×
659
                FillerTileCacheExpirationStrategy::DerivedFromSurroundingTiles,
×
660
                query.time_interval,
×
661
                FillerTimeBounds::from(query.time_interval), // TODO: derive this from the query once the child query can provide this.
×
662
            )))
×
663
        }
664
    }
8✔
665

666
    fn result_descriptor(&self) -> &RasterResultDescriptor {
8✔
667
        &self.result_descriptor
8✔
668
    }
8✔
669
}
670

671
#[cfg(test)]
672
mod tests {
673
    use super::*;
674
    use crate::engine::{MockExecutionContext, MockQueryContext, RasterBandDescriptors};
675
    use crate::mock::MockFeatureCollectionSource;
676
    use crate::mock::{MockRasterSource, MockRasterSourceParams};
677
    use crate::{
678
        engine::{ChunkByteSize, VectorOperator},
679
        source::{
680
            FileNotFoundHandling, GdalDatasetGeoTransform, GdalDatasetParameters,
681
            GdalMetaDataRegular, GdalMetaDataStatic, GdalSource, GdalSourceParameters,
682
            GdalSourceTimePlaceholder, TimeReference,
683
        },
684
        test_data,
685
        util::gdal::{add_ndvi_dataset, gdal_open_dataset},
686
    };
687
    use float_cmp::approx_eq;
688
    use futures::StreamExt;
689
    use geoengine_datatypes::collections::IntoGeometryIterator;
690
    use geoengine_datatypes::dataset::NamedData;
691
    use geoengine_datatypes::primitives::{
692
        AxisAlignedRectangle, Coordinate2D, DateTimeParseFormat,
693
    };
694
    use geoengine_datatypes::primitives::{CacheHint, CacheTtlSeconds};
695
    use geoengine_datatypes::raster::TilesEqualIgnoringCacheHint;
696
    use geoengine_datatypes::{
697
        collections::{
698
            GeometryCollection, MultiLineStringCollection, MultiPointCollection,
699
            MultiPolygonCollection,
700
        },
701
        dataset::{DataId, DatasetId},
702
        hashmap,
703
        primitives::{
704
            BoundingBox2D, MultiLineString, MultiPoint, MultiPolygon, QueryRectangle,
705
            SpatialResolution, TimeGranularity, TimeInstance, TimeInterval, TimeStep,
706
        },
707
        raster::{Grid, GridShape, GridShape2D, GridSize, RasterDataType, RasterTile2D},
708
        spatial_reference::SpatialReferenceAuthority,
709
        util::{
710
            test::TestDefault,
711
            well_known_data::{
712
                COLOGNE_EPSG_4326, COLOGNE_EPSG_900_913, HAMBURG_EPSG_4326, HAMBURG_EPSG_900_913,
713
                MARBURG_EPSG_4326, MARBURG_EPSG_900_913,
714
            },
715
            Identifier,
716
        },
717
    };
718
    use std::collections::HashMap;
719
    use std::path::PathBuf;
720
    use std::str::FromStr;
721

722
    #[tokio::test]
723
    async fn multi_point() -> Result<()> {
1✔
724
        let points = MultiPointCollection::from_data(
1✔
725
            MultiPoint::many(vec![
1✔
726
                MARBURG_EPSG_4326,
1✔
727
                COLOGNE_EPSG_4326,
1✔
728
                HAMBURG_EPSG_4326,
1✔
729
            ])
1✔
730
            .unwrap(),
1✔
731
            vec![TimeInterval::new_unchecked(0, 1); 3],
1✔
732
            Default::default(),
1✔
733
            CacheHint::default(),
1✔
734
        )?;
1✔
735

1✔
736
        let expected = MultiPoint::many(vec![
1✔
737
            MARBURG_EPSG_900_913,
1✔
738
            COLOGNE_EPSG_900_913,
1✔
739
            HAMBURG_EPSG_900_913,
1✔
740
        ])
1✔
741
        .unwrap();
1✔
742

1✔
743
        let point_source = MockFeatureCollectionSource::single(points.clone()).boxed();
1✔
744

1✔
745
        let target_spatial_reference =
1✔
746
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 900_913);
1✔
747

1✔
748
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
749
            params: ReprojectionParams {
1✔
750
                target_spatial_reference,
1✔
751
            },
1✔
752
            sources: SingleRasterOrVectorSource {
1✔
753
                source: point_source.into(),
1✔
754
            },
1✔
755
        })
1✔
756
        .initialize(
1✔
757
            WorkflowOperatorPath::initialize_root(),
1✔
758
            &MockExecutionContext::test_default(),
1✔
759
        )
1✔
760
        .await?;
1✔
761

1✔
762
        let query_processor = initialized_operator.query_processor()?;
1✔
763

1✔
764
        let query_processor = query_processor.multi_point().unwrap();
1✔
765

1✔
766
        let query_rectangle = VectorQueryRectangle {
1✔
767
            spatial_bounds: BoundingBox2D::new(
1✔
768
                (COLOGNE_EPSG_4326.x, MARBURG_EPSG_4326.y).into(),
1✔
769
                (MARBURG_EPSG_4326.x, HAMBURG_EPSG_4326.y).into(),
1✔
770
            )
1✔
771
            .unwrap(),
1✔
772
            time_interval: TimeInterval::default(),
1✔
773
            spatial_resolution: SpatialResolution::zero_point_one(),
1✔
774
            attributes: ColumnSelection::all(),
1✔
775
        };
1✔
776
        let ctx = MockQueryContext::new(ChunkByteSize::MAX);
1✔
777

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

1✔
780
        let result = query
1✔
781
            .map(Result::unwrap)
1✔
782
            .collect::<Vec<MultiPointCollection>>()
1✔
783
            .await;
1✔
784

1✔
785
        assert_eq!(result.len(), 1);
1✔
786

1✔
787
        result[0]
1✔
788
            .geometries()
1✔
789
            .zip(expected.iter())
1✔
790
            .for_each(|(a, e)| {
3✔
791
                assert!(approx_eq!(&MultiPoint, &a.into(), e, epsilon = 0.00001));
3✔
792
            });
3✔
793

1✔
794
        Ok(())
1✔
795
    }
1✔
796

797
    #[tokio::test]
798
    async fn multi_lines() -> Result<()> {
1✔
799
        let lines = MultiLineStringCollection::from_data(
1✔
800
            vec![MultiLineString::new(vec![vec![
1✔
801
                MARBURG_EPSG_4326,
1✔
802
                COLOGNE_EPSG_4326,
1✔
803
                HAMBURG_EPSG_4326,
1✔
804
            ]])
1✔
805
            .unwrap()],
1✔
806
            vec![TimeInterval::new_unchecked(0, 1); 1],
1✔
807
            Default::default(),
1✔
808
            CacheHint::default(),
1✔
809
        )?;
1✔
810

1✔
811
        let expected = [MultiLineString::new(vec![vec![
1✔
812
            MARBURG_EPSG_900_913,
1✔
813
            COLOGNE_EPSG_900_913,
1✔
814
            HAMBURG_EPSG_900_913,
1✔
815
        ]])
1✔
816
        .unwrap()];
1✔
817

1✔
818
        let lines_source = MockFeatureCollectionSource::single(lines.clone()).boxed();
1✔
819

1✔
820
        let target_spatial_reference =
1✔
821
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 900_913);
1✔
822

1✔
823
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
824
            params: ReprojectionParams {
1✔
825
                target_spatial_reference,
1✔
826
            },
1✔
827
            sources: SingleRasterOrVectorSource {
1✔
828
                source: lines_source.into(),
1✔
829
            },
1✔
830
        })
1✔
831
        .initialize(
1✔
832
            WorkflowOperatorPath::initialize_root(),
1✔
833
            &MockExecutionContext::test_default(),
1✔
834
        )
1✔
835
        .await?;
1✔
836

1✔
837
        let query_processor = initialized_operator.query_processor()?;
1✔
838

1✔
839
        let query_processor = query_processor.multi_line_string().unwrap();
1✔
840

1✔
841
        let query_rectangle = VectorQueryRectangle {
1✔
842
            spatial_bounds: BoundingBox2D::new(
1✔
843
                (COLOGNE_EPSG_4326.x, MARBURG_EPSG_4326.y).into(),
1✔
844
                (MARBURG_EPSG_4326.x, HAMBURG_EPSG_4326.y).into(),
1✔
845
            )
1✔
846
            .unwrap(),
1✔
847
            time_interval: TimeInterval::default(),
1✔
848
            spatial_resolution: SpatialResolution::zero_point_one(),
1✔
849
            attributes: ColumnSelection::all(),
1✔
850
        };
1✔
851
        let ctx = MockQueryContext::new(ChunkByteSize::MAX);
1✔
852

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

1✔
855
        let result = query
1✔
856
            .map(Result::unwrap)
1✔
857
            .collect::<Vec<MultiLineStringCollection>>()
1✔
858
            .await;
1✔
859

1✔
860
        assert_eq!(result.len(), 1);
1✔
861

1✔
862
        result[0]
1✔
863
            .geometries()
1✔
864
            .zip(expected.iter())
1✔
865
            .for_each(|(a, e)| {
1✔
866
                assert!(approx_eq!(
1✔
867
                    &MultiLineString,
1✔
868
                    &a.into(),
1✔
869
                    e,
1✔
870
                    epsilon = 0.00001
1✔
871
                ));
1✔
872
            });
1✔
873

1✔
874
        Ok(())
1✔
875
    }
1✔
876

877
    #[tokio::test]
878
    async fn multi_polygons() -> Result<()> {
1✔
879
        let polygons = MultiPolygonCollection::from_data(
1✔
880
            vec![MultiPolygon::new(vec![vec![vec![
1✔
881
                MARBURG_EPSG_4326,
1✔
882
                COLOGNE_EPSG_4326,
1✔
883
                HAMBURG_EPSG_4326,
1✔
884
                MARBURG_EPSG_4326,
1✔
885
            ]]])
1✔
886
            .unwrap()],
1✔
887
            vec![TimeInterval::new_unchecked(0, 1); 1],
1✔
888
            Default::default(),
1✔
889
            CacheHint::default(),
1✔
890
        )?;
1✔
891

1✔
892
        let expected = [MultiPolygon::new(vec![vec![vec![
1✔
893
            MARBURG_EPSG_900_913,
1✔
894
            COLOGNE_EPSG_900_913,
1✔
895
            HAMBURG_EPSG_900_913,
1✔
896
            MARBURG_EPSG_900_913,
1✔
897
        ]]])
1✔
898
        .unwrap()];
1✔
899

1✔
900
        let polygon_source = MockFeatureCollectionSource::single(polygons.clone()).boxed();
1✔
901

1✔
902
        let target_spatial_reference =
1✔
903
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 900_913);
1✔
904

1✔
905
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
906
            params: ReprojectionParams {
1✔
907
                target_spatial_reference,
1✔
908
            },
1✔
909
            sources: SingleRasterOrVectorSource {
1✔
910
                source: polygon_source.into(),
1✔
911
            },
1✔
912
        })
1✔
913
        .initialize(
1✔
914
            WorkflowOperatorPath::initialize_root(),
1✔
915
            &MockExecutionContext::test_default(),
1✔
916
        )
1✔
917
        .await?;
1✔
918

1✔
919
        let query_processor = initialized_operator.query_processor()?;
1✔
920

1✔
921
        let query_processor = query_processor.multi_polygon().unwrap();
1✔
922

1✔
923
        let query_rectangle = VectorQueryRectangle {
1✔
924
            spatial_bounds: BoundingBox2D::new(
1✔
925
                (COLOGNE_EPSG_4326.x, MARBURG_EPSG_4326.y).into(),
1✔
926
                (MARBURG_EPSG_4326.x, HAMBURG_EPSG_4326.y).into(),
1✔
927
            )
1✔
928
            .unwrap(),
1✔
929
            time_interval: TimeInterval::default(),
1✔
930
            spatial_resolution: SpatialResolution::zero_point_one(),
1✔
931
            attributes: ColumnSelection::all(),
1✔
932
        };
1✔
933
        let ctx = MockQueryContext::new(ChunkByteSize::MAX);
1✔
934

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

1✔
937
        let result = query
1✔
938
            .map(Result::unwrap)
1✔
939
            .collect::<Vec<MultiPolygonCollection>>()
1✔
940
            .await;
1✔
941

1✔
942
        assert_eq!(result.len(), 1);
1✔
943

1✔
944
        result[0]
1✔
945
            .geometries()
1✔
946
            .zip(expected.iter())
1✔
947
            .for_each(|(a, e)| {
1✔
948
                assert!(approx_eq!(&MultiPolygon, &a.into(), e, epsilon = 0.00001));
1✔
949
            });
1✔
950

1✔
951
        Ok(())
1✔
952
    }
1✔
953

954
    #[tokio::test]
955
    async fn raster_identity() -> Result<()> {
1✔
956
        let projection = SpatialReference::new(
1✔
957
            geoengine_datatypes::spatial_reference::SpatialReferenceAuthority::Epsg,
1✔
958
            4326,
1✔
959
        );
1✔
960

1✔
961
        let data = vec![
1✔
962
            RasterTile2D {
1✔
963
                time: TimeInterval::new_unchecked(0, 5),
1✔
964
                tile_position: [-1, 0].into(),
1✔
965
                band: 0,
1✔
966
                global_geo_transform: TestDefault::test_default(),
1✔
967
                grid_array: Grid::new([2, 2].into(), vec![1, 2, 3, 4]).unwrap().into(),
1✔
968
                properties: Default::default(),
1✔
969
                cache_hint: CacheHint::default(),
1✔
970
            },
1✔
971
            RasterTile2D {
1✔
972
                time: TimeInterval::new_unchecked(0, 5),
1✔
973
                tile_position: [-1, 1].into(),
1✔
974
                band: 0,
1✔
975
                global_geo_transform: TestDefault::test_default(),
1✔
976
                grid_array: Grid::new([2, 2].into(), vec![7, 8, 9, 10]).unwrap().into(),
1✔
977
                properties: Default::default(),
1✔
978
                cache_hint: CacheHint::default(),
1✔
979
            },
1✔
980
            RasterTile2D {
1✔
981
                time: TimeInterval::new_unchecked(5, 10),
1✔
982
                tile_position: [-1, 0].into(),
1✔
983
                band: 0,
1✔
984
                global_geo_transform: TestDefault::test_default(),
1✔
985
                grid_array: Grid::new([2, 2].into(), vec![13, 14, 15, 16])
1✔
986
                    .unwrap()
1✔
987
                    .into(),
1✔
988
                properties: Default::default(),
1✔
989
                cache_hint: CacheHint::default(),
1✔
990
            },
1✔
991
            RasterTile2D {
1✔
992
                time: TimeInterval::new_unchecked(5, 10),
1✔
993
                tile_position: [-1, 1].into(),
1✔
994
                band: 0,
1✔
995
                global_geo_transform: TestDefault::test_default(),
1✔
996
                grid_array: Grid::new([2, 2].into(), vec![19, 20, 21, 22])
1✔
997
                    .unwrap()
1✔
998
                    .into(),
1✔
999
                properties: Default::default(),
1✔
1000
                cache_hint: CacheHint::default(),
1✔
1001
            },
1✔
1002
        ];
1✔
1003

1✔
1004
        let mrs1 = MockRasterSource {
1✔
1005
            params: MockRasterSourceParams {
1✔
1006
                data: data.clone(),
1✔
1007
                result_descriptor: RasterResultDescriptor {
1✔
1008
                    data_type: RasterDataType::U8,
1✔
1009
                    spatial_reference: SpatialReference::epsg_4326().into(),
1✔
1010
                    time: None,
1✔
1011
                    bbox: None,
1✔
1012
                    resolution: Some(SpatialResolution::one()),
1✔
1013
                    bands: RasterBandDescriptors::new_single_band(),
1✔
1014
                },
1✔
1015
            },
1✔
1016
        }
1✔
1017
        .boxed();
1✔
1018

1✔
1019
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1020
        exe_ctx.tiling_specification.tile_size_in_pixels = GridShape {
1✔
1021
            // we need a smaller tile size
1✔
1022
            shape_array: [2, 2],
1✔
1023
        };
1✔
1024

1✔
1025
        let query_ctx = MockQueryContext::test_default();
1✔
1026

1✔
1027
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1028
            params: ReprojectionParams {
1✔
1029
                target_spatial_reference: projection, // This test will do a identity reprojection
1✔
1030
            },
1✔
1031
            sources: SingleRasterOrVectorSource {
1✔
1032
                source: mrs1.into(),
1✔
1033
            },
1✔
1034
        })
1✔
1035
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1036
        .await?;
1✔
1037

1✔
1038
        let qp = initialized_operator
1✔
1039
            .query_processor()
1✔
1040
            .unwrap()
1✔
1041
            .get_u8()
1✔
1042
            .unwrap();
1✔
1043

1✔
1044
        let query_rect = RasterQueryRectangle {
1✔
1045
            spatial_bounds: SpatialPartition2D::new_unchecked((0., 1.).into(), (3., 0.).into()),
1✔
1046
            time_interval: TimeInterval::new_unchecked(0, 10),
1✔
1047
            spatial_resolution: SpatialResolution::one(),
1✔
1048
            attributes: BandSelection::first(),
1✔
1049
        };
1✔
1050

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

1✔
1053
        let res = a
1✔
1054
            .map(Result::unwrap)
1✔
1055
            .collect::<Vec<RasterTile2D<u8>>>()
1✔
1056
            .await;
6✔
1057
        assert!(data.tiles_equal_ignoring_cache_hint(&res));
1✔
1058

1✔
1059
        Ok(())
1✔
1060
    }
1✔
1061

1062
    #[tokio::test]
1063
    async fn raster_ndvi_3857() -> Result<()> {
1✔
1064
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1065
        let query_ctx = MockQueryContext::test_default();
1✔
1066
        let id = add_ndvi_dataset(&mut exe_ctx);
1✔
1067
        exe_ctx.tiling_specification =
1✔
1068
            TilingSpecification::new((0.0, 0.0).into(), [450, 450].into());
1✔
1069

1✔
1070
        let output_shape: GridShape2D = [900, 1800].into();
1✔
1071
        let output_bounds =
1✔
1072
            SpatialPartition2D::new_unchecked((0., 20_000_000.).into(), (20_000_000., 0.).into());
1✔
1073
        let time_interval = TimeInterval::new_unchecked(1_388_534_400_000, 1_388_534_400_001);
1✔
1074
        // 2014-01-01
1✔
1075

1✔
1076
        let gdal_op = GdalSource {
1✔
1077
            params: GdalSourceParameters { data: id.clone() },
1✔
1078
        }
1✔
1079
        .boxed();
1✔
1080

1✔
1081
        let projection = SpatialReference::new(
1✔
1082
            geoengine_datatypes::spatial_reference::SpatialReferenceAuthority::Epsg,
1✔
1083
            3857,
1✔
1084
        );
1✔
1085

1✔
1086
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1087
            params: ReprojectionParams {
1✔
1088
                target_spatial_reference: projection,
1✔
1089
            },
1✔
1090
            sources: SingleRasterOrVectorSource {
1✔
1091
                source: gdal_op.into(),
1✔
1092
            },
1✔
1093
        })
1✔
1094
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1095
        .await?;
1✔
1096

1✔
1097
        let x_query_resolution = output_bounds.size_x() / output_shape.axis_size_x() as f64;
1✔
1098
        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✔
1099
        let spatial_resolution =
1✔
1100
            SpatialResolution::new_unchecked(x_query_resolution, y_query_resolution);
1✔
1101

1✔
1102
        let qp = initialized_operator
1✔
1103
            .query_processor()
1✔
1104
            .unwrap()
1✔
1105
            .get_u8()
1✔
1106
            .unwrap();
1✔
1107

1✔
1108
        let qs = qp
1✔
1109
            .raster_query(
1✔
1110
                RasterQueryRectangle {
1✔
1111
                    spatial_bounds: output_bounds,
1✔
1112
                    time_interval,
1✔
1113
                    spatial_resolution,
1✔
1114
                    attributes: BandSelection::first(),
1✔
1115
                },
1✔
1116
                &query_ctx,
1✔
1117
            )
1✔
1118
            .await
1✔
1119
            .unwrap();
1✔
1120

1✔
1121
        let res = qs
1✔
1122
            .map(Result::unwrap)
1✔
1123
            .collect::<Vec<RasterTile2D<u8>>>()
1✔
1124
            .await;
124✔
1125

1✔
1126
        // Write the tiles to a file
1✔
1127
        // let mut buffer = File::create("MOD13A2_M_NDVI_2014-04-01_tile-20.rst")?;
1✔
1128
        // buffer.write(res[8].clone().into_materialized_tile().grid_array.data.as_slice())?;
1✔
1129

1✔
1130
        // This check is against a tile produced by the operator itself. It was visually validated. TODO: rebuild when open issues are solved.
1✔
1131
        // A perfect validation would be against a GDAL output generated like this:
1✔
1132
        // 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
1✔
1133

1✔
1134
        assert_eq!(
1✔
1135
            include_bytes!(
1✔
1136
                "../../../test_data/raster/modis_ndvi/projected_3857/MOD13A2_M_NDVI_2014-04-01_tile-20.rst"
1✔
1137
            ) as &[u8],
1✔
1138
            res[8].clone().into_materialized_tile().grid_array.inner_grid.data.as_slice()
1✔
1139
        );
1✔
1140

1✔
1141
        Ok(())
1✔
1142
    }
1✔
1143

1144
    #[test]
1145
    fn query_rewrite_4326_3857() {
1✔
1146
        let query = VectorQueryRectangle {
1✔
1147
            spatial_bounds: BoundingBox2D::new_unchecked((-180., -90.).into(), (180., 90.).into()),
1✔
1148
            time_interval: TimeInterval::default(),
1✔
1149
            spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1150
            attributes: ColumnSelection::all(),
1✔
1151
        };
1✔
1152

1✔
1153
        let expected = BoundingBox2D::new_unchecked(
1✔
1154
            (-20_037_508.342_789_244, -20_048_966.104_014_594).into(),
1✔
1155
            (20_037_508.342_789_244, 20_048_966.104_014_594).into(),
1✔
1156
        );
1✔
1157

1✔
1158
        let reprojected = reproject_query(
1✔
1159
            query,
1✔
1160
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 3857),
1✔
1161
            SpatialReference::epsg_4326(),
1✔
1162
        )
1✔
1163
        .unwrap()
1✔
1164
        .unwrap();
1✔
1165

1✔
1166
        assert!(approx_eq!(
1✔
1167
            BoundingBox2D,
1✔
1168
            expected,
1✔
1169
            reprojected.spatial_bounds,
1✔
1170
            epsilon = 0.000_001
1✔
1171
        ));
1✔
1172
    }
1✔
1173

1174
    #[tokio::test]
1175
    async fn raster_ndvi_3857_to_4326() -> Result<()> {
1✔
1176
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1177
        let query_ctx = MockQueryContext::test_default();
1✔
1178

1✔
1179
        let m = GdalMetaDataRegular {
1✔
1180
            data_time: TimeInterval::new_unchecked(
1✔
1181
                TimeInstance::from_str("2014-01-01T00:00:00.000Z").unwrap(),
1✔
1182
                TimeInstance::from_str("2014-07-01T00:00:00.000Z").unwrap(),
1✔
1183
            ),
1✔
1184
            step: TimeStep {
1✔
1185
                granularity: TimeGranularity::Months,
1✔
1186
                step: 1,
1✔
1187
            },
1✔
1188
            time_placeholders: hashmap! {
1✔
1189
                "%_START_TIME_%".to_string() => GdalSourceTimePlaceholder {
1✔
1190
                    format: DateTimeParseFormat::custom("%Y-%m-%d".to_string()),
1✔
1191
                    reference: TimeReference::Start,
1✔
1192
                },
1✔
1193
            },
1✔
1194
            params: GdalDatasetParameters {
1✔
1195
                file_path: test_data!(
1✔
1196
                    "raster/modis_ndvi/projected_3857/MOD13A2_M_NDVI_%_START_TIME_%.TIFF"
1✔
1197
                )
1✔
1198
                .into(),
1✔
1199
                rasterband_channel: 1,
1✔
1200
                geo_transform: GdalDatasetGeoTransform {
1✔
1201
                    origin_coordinate: (-20_037_508.342_789_244, 19_971_868.880_408_563).into(),
1✔
1202
                    x_pixel_size: 14_052.950_258_048_739,
1✔
1203
                    y_pixel_size: -14_057.881_117_788_405,
1✔
1204
                },
1✔
1205
                width: 2851,
1✔
1206
                height: 2841,
1✔
1207
                file_not_found_handling: FileNotFoundHandling::Error,
1✔
1208
                no_data_value: Some(0.),
1✔
1209
                properties_mapping: None,
1✔
1210
                gdal_open_options: None,
1✔
1211
                gdal_config_options: None,
1✔
1212
                allow_alphaband_as_mask: true,
1✔
1213
                retry: None,
1✔
1214
            },
1✔
1215
            result_descriptor: RasterResultDescriptor {
1✔
1216
                data_type: RasterDataType::U8,
1✔
1217
                spatial_reference: SpatialReference::new(SpatialReferenceAuthority::Epsg, 3857)
1✔
1218
                    .into(),
1✔
1219
                time: None,
1✔
1220
                bbox: None,
1✔
1221
                resolution: None,
1✔
1222
                bands: RasterBandDescriptors::new_single_band(),
1✔
1223
            },
1✔
1224
            cache_ttl: CacheTtlSeconds::default(),
1✔
1225
        };
1✔
1226

1✔
1227
        let id: DataId = DatasetId::new().into();
1✔
1228
        let name = NamedData::with_system_name("ndvi");
1✔
1229
        exe_ctx.add_meta_data(id.clone(), name.clone(), Box::new(m));
1✔
1230

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

1✔
1233
        let output_bounds =
1✔
1234
            SpatialPartition2D::new_unchecked((-180., 90.).into(), (180., -90.).into());
1✔
1235
        let time_interval = TimeInterval::new_unchecked(1_396_310_400_000, 1_396_310_400_000);
1✔
1236
        // 2014-04-01
1✔
1237

1✔
1238
        let gdal_op = GdalSource {
1✔
1239
            params: GdalSourceParameters { data: name },
1✔
1240
        }
1✔
1241
        .boxed();
1✔
1242

1✔
1243
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1244
            params: ReprojectionParams {
1✔
1245
                target_spatial_reference: SpatialReference::epsg_4326(),
1✔
1246
            },
1✔
1247
            sources: SingleRasterOrVectorSource {
1✔
1248
                source: gdal_op.into(),
1✔
1249
            },
1✔
1250
        })
1✔
1251
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1252
        .await?;
1✔
1253

1✔
1254
        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✔
1255
        let y_query_resolution = output_bounds.size_y() / 240.; // *2 to account for the dataset aspect ratio 2:1
1✔
1256
        let spatial_resolution =
1✔
1257
            SpatialResolution::new_unchecked(x_query_resolution, y_query_resolution);
1✔
1258

1✔
1259
        let qp = initialized_operator
1✔
1260
            .query_processor()
1✔
1261
            .unwrap()
1✔
1262
            .get_u8()
1✔
1263
            .unwrap();
1✔
1264

1✔
1265
        let qs = qp
1✔
1266
            .raster_query(
1✔
1267
                QueryRectangle {
1✔
1268
                    spatial_bounds: output_bounds,
1✔
1269
                    time_interval,
1✔
1270
                    spatial_resolution,
1✔
1271
                    attributes: BandSelection::first(),
1✔
1272
                },
1✔
1273
                &query_ctx,
1✔
1274
            )
1✔
1275
            .await
1✔
1276
            .unwrap();
1✔
1277

1✔
1278
        let tiles = qs
1✔
1279
            .map(Result::unwrap)
1✔
1280
            .collect::<Vec<RasterTile2D<u8>>>()
1✔
1281
            .await;
246✔
1282

1✔
1283
        // the test must generate 8x4 tiles
1✔
1284
        assert_eq!(tiles.len(), 32);
1✔
1285

1✔
1286
        // none of the tiles should be empty
1✔
1287
        assert!(tiles.iter().all(|t| !t.is_empty()));
32✔
1288

1✔
1289
        Ok(())
1✔
1290
    }
1✔
1291

1292
    #[test]
1293
    fn source_resolution() {
1✔
1294
        let epsg_4326 = SpatialReference::epsg_4326();
1✔
1295
        let epsg_3857 = SpatialReference::new(SpatialReferenceAuthority::Epsg, 3857);
1✔
1296

1✔
1297
        // use ndvi dataset that was reprojected using gdal as ground truth
1✔
1298
        let dataset_4326 = gdal_open_dataset(test_data!(
1✔
1299
            "raster/modis_ndvi/MOD13A2_M_NDVI_2014-04-01.TIFF"
1✔
1300
        ))
1✔
1301
        .unwrap();
1✔
1302
        let geotransform_4326 = dataset_4326.geo_transform().unwrap();
1✔
1303
        let res_4326 = SpatialResolution::new(geotransform_4326[1], -geotransform_4326[5]).unwrap();
1✔
1304

1✔
1305
        let dataset_3857 = gdal_open_dataset(test_data!(
1✔
1306
            "raster/modis_ndvi/projected_3857/MOD13A2_M_NDVI_2014-04-01.TIFF"
1✔
1307
        ))
1✔
1308
        .unwrap();
1✔
1309
        let geotransform_3857 = dataset_3857.geo_transform().unwrap();
1✔
1310
        let res_3857 = SpatialResolution::new(geotransform_3857[1], -geotransform_3857[5]).unwrap();
1✔
1311

1✔
1312
        // ndvi was projected from 4326 to 3857. The calculated source_resolution for getting the raster in 3857 with `res_3857`
1✔
1313
        // should thus roughly be like the original `res_4326`
1✔
1314
        let result_res = suggest_pixel_size_from_diag_cross_projected::<SpatialPartition2D>(
1✔
1315
            epsg_3857.area_of_use_projected().unwrap(),
1✔
1316
            epsg_4326.area_of_use_projected().unwrap(),
1✔
1317
            res_3857,
1✔
1318
        )
1✔
1319
        .unwrap();
1✔
1320
        assert!(1. - (result_res.x / res_4326.x).abs() < 0.02);
1✔
1321
        assert!(1. - (result_res.y / res_4326.y).abs() < 0.02);
1✔
1322
    }
1✔
1323

1324
    #[tokio::test]
1325
    async fn query_outside_projection_area_of_use_produces_empty_tiles() {
1✔
1326
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1327
        let query_ctx = MockQueryContext::test_default();
1✔
1328

1✔
1329
        let m = GdalMetaDataStatic {
1✔
1330
            time: Some(TimeInterval::default()),
1✔
1331
            params: GdalDatasetParameters {
1✔
1332
                file_path: PathBuf::new(),
1✔
1333
                rasterband_channel: 1,
1✔
1334
                geo_transform: GdalDatasetGeoTransform {
1✔
1335
                    origin_coordinate: (166_021.44, 9_329_005.188).into(),
1✔
1336
                    x_pixel_size: (534_994.66 - 166_021.444) / 100.,
1✔
1337
                    y_pixel_size: -9_329_005.18 / 100.,
1✔
1338
                },
1✔
1339
                width: 100,
1✔
1340
                height: 100,
1✔
1341
                file_not_found_handling: FileNotFoundHandling::NoData,
1✔
1342
                no_data_value: Some(0.),
1✔
1343
                properties_mapping: None,
1✔
1344
                gdal_open_options: None,
1✔
1345
                gdal_config_options: None,
1✔
1346
                allow_alphaband_as_mask: true,
1✔
1347
                retry: None,
1✔
1348
            },
1✔
1349
            result_descriptor: RasterResultDescriptor {
1✔
1350
                data_type: RasterDataType::U8,
1✔
1351
                spatial_reference: SpatialReference::new(SpatialReferenceAuthority::Epsg, 32636)
1✔
1352
                    .into(),
1✔
1353
                time: None,
1✔
1354
                bbox: None,
1✔
1355
                resolution: None,
1✔
1356
                bands: RasterBandDescriptors::new_single_band(),
1✔
1357
            },
1✔
1358
            cache_ttl: CacheTtlSeconds::default(),
1✔
1359
        };
1✔
1360

1✔
1361
        let id: DataId = DatasetId::new().into();
1✔
1362
        let name = NamedData::with_system_name("ndvi");
1✔
1363
        exe_ctx.add_meta_data(id.clone(), name.clone(), Box::new(m));
1✔
1364

1✔
1365
        exe_ctx.tiling_specification =
1✔
1366
            TilingSpecification::new((0.0, 0.0).into(), [600, 600].into());
1✔
1367

1✔
1368
        let output_shape: GridShape2D = [1000, 1000].into();
1✔
1369
        let output_bounds =
1✔
1370
            SpatialPartition2D::new_unchecked((-180., 0.).into(), (180., -90.).into());
1✔
1371
        let time_interval = TimeInterval::new_instant(1_388_534_400_000).unwrap(); // 2014-01-01
1✔
1372

1✔
1373
        let gdal_op = GdalSource {
1✔
1374
            params: GdalSourceParameters { data: name },
1✔
1375
        }
1✔
1376
        .boxed();
1✔
1377

1✔
1378
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1379
            params: ReprojectionParams {
1✔
1380
                target_spatial_reference: SpatialReference::epsg_4326(),
1✔
1381
            },
1✔
1382
            sources: SingleRasterOrVectorSource {
1✔
1383
                source: gdal_op.into(),
1✔
1384
            },
1✔
1385
        })
1✔
1386
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1387
        .await
1✔
1388
        .unwrap();
1✔
1389

1✔
1390
        let x_query_resolution = output_bounds.size_x() / output_shape.axis_size_x() as f64;
1✔
1391
        let y_query_resolution = output_bounds.size_y() / (output_shape.axis_size_y()) as f64;
1✔
1392
        let spatial_resolution =
1✔
1393
            SpatialResolution::new_unchecked(x_query_resolution, y_query_resolution);
1✔
1394

1✔
1395
        let qp = initialized_operator
1✔
1396
            .query_processor()
1✔
1397
            .unwrap()
1✔
1398
            .get_u8()
1✔
1399
            .unwrap();
1✔
1400

1✔
1401
        let result = qp
1✔
1402
            .raster_query(
1✔
1403
                QueryRectangle {
1✔
1404
                    spatial_bounds: output_bounds,
1✔
1405
                    time_interval,
1✔
1406
                    spatial_resolution,
1✔
1407
                    attributes: BandSelection::first(),
1✔
1408
                },
1✔
1409
                &query_ctx,
1✔
1410
            )
1✔
1411
            .await
1✔
1412
            .unwrap()
1✔
1413
            .map(Result::unwrap)
1✔
1414
            .collect::<Vec<_>>()
1✔
1415
            .await;
1✔
1416

1✔
1417
        assert_eq!(result.len(), 4);
1✔
1418

1✔
1419
        for r in result {
5✔
1420
            assert!(r.is_empty());
4✔
1421
        }
1✔
1422
    }
1✔
1423

1424
    #[tokio::test]
1425
    async fn points_from_wgs84_to_utm36n() {
1✔
1426
        let exe_ctx = MockExecutionContext::test_default();
1✔
1427
        let query_ctx = MockQueryContext::test_default();
1✔
1428

1✔
1429
        let point_source = MockFeatureCollectionSource::single(
1✔
1430
            MultiPointCollection::from_data(
1✔
1431
                MultiPoint::many(vec![
1✔
1432
                    vec![(30.0, 0.0)], // lower left of utm36n area of use
1✔
1433
                    vec![(36.0, 84.0)],
1✔
1434
                    vec![(33.0, 42.0)], // upper right of utm36n area of use
1✔
1435
                ])
1✔
1436
                .unwrap(),
1✔
1437
                vec![TimeInterval::default(); 3],
1✔
1438
                HashMap::default(),
1✔
1439
                CacheHint::default(),
1✔
1440
            )
1✔
1441
            .unwrap(),
1✔
1442
        )
1✔
1443
        .boxed();
1✔
1444

1✔
1445
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
1446
            params: ReprojectionParams {
1✔
1447
                target_spatial_reference: SpatialReference::new(
1✔
1448
                    SpatialReferenceAuthority::Epsg,
1✔
1449
                    32636, // utm36n
1✔
1450
                ),
1✔
1451
            },
1✔
1452
            sources: SingleRasterOrVectorSource {
1✔
1453
                source: point_source.into(),
1✔
1454
            },
1✔
1455
        })
1✔
1456
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1457
        .await
1✔
1458
        .unwrap();
1✔
1459

1✔
1460
        let qp = initialized_operator
1✔
1461
            .query_processor()
1✔
1462
            .unwrap()
1✔
1463
            .multi_point()
1✔
1464
            .unwrap();
1✔
1465

1✔
1466
        let spatial_bounds = BoundingBox2D::new(
1✔
1467
            (166_021.44, 0.00).into(), // lower left of projected utm36n area of use
1✔
1468
            (534_994.666_6, 9_329_005.18).into(), // upper right of projected utm36n area of use
1✔
1469
        )
1✔
1470
        .unwrap();
1✔
1471

1✔
1472
        let qs = qp
1✔
1473
            .vector_query(
1✔
1474
                QueryRectangle {
1✔
1475
                    spatial_bounds,
1✔
1476
                    time_interval: TimeInterval::default(),
1✔
1477
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1478
                    attributes: ColumnSelection::all(),
1✔
1479
                },
1✔
1480
                &query_ctx,
1✔
1481
            )
1✔
1482
            .await
1✔
1483
            .unwrap();
1✔
1484

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

1✔
1487
        assert_eq!(points.len(), 1);
1✔
1488

1✔
1489
        let points = &points[0];
1✔
1490

1✔
1491
        assert_eq!(
1✔
1492
            points.coordinates(),
1✔
1493
            &[
1✔
1494
                (166_021.443_080_538_42, 0.0).into(),
1✔
1495
                (534_994.655_061_136_1, 9_329_005.182_447_437).into(),
1✔
1496
                (499_999.999_999_999_5, 4_649_776.224_819_178).into()
1✔
1497
            ]
1✔
1498
        );
1✔
1499
    }
1✔
1500

1501
    #[tokio::test]
1502
    async fn points_from_utm36n_to_wgs84() {
1✔
1503
        let exe_ctx = MockExecutionContext::test_default();
1✔
1504
        let query_ctx = MockQueryContext::test_default();
1✔
1505

1✔
1506
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
1507
            vec![MultiPointCollection::from_data(
1✔
1508
                MultiPoint::many(vec![
1✔
1509
                    vec![(166_021.443_080_538_42, 0.0)],
1✔
1510
                    vec![(534_994.655_061_136_1, 9_329_005.182_447_437)],
1✔
1511
                    vec![(499_999.999_999_999_5, 4_649_776.224_819_178)],
1✔
1512
                ])
1✔
1513
                .unwrap(),
1✔
1514
                vec![TimeInterval::default(); 3],
1✔
1515
                HashMap::default(),
1✔
1516
                CacheHint::default(),
1✔
1517
            )
1✔
1518
            .unwrap()],
1✔
1519
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 32636), //utm36n
1✔
1520
        )
1✔
1521
        .boxed();
1✔
1522

1✔
1523
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
1524
            params: ReprojectionParams {
1✔
1525
                target_spatial_reference: SpatialReference::new(
1✔
1526
                    SpatialReferenceAuthority::Epsg,
1✔
1527
                    4326, // utm36n
1✔
1528
                ),
1✔
1529
            },
1✔
1530
            sources: SingleRasterOrVectorSource {
1✔
1531
                source: point_source.into(),
1✔
1532
            },
1✔
1533
        })
1✔
1534
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1535
        .await
1✔
1536
        .unwrap();
1✔
1537

1✔
1538
        let qp = initialized_operator
1✔
1539
            .query_processor()
1✔
1540
            .unwrap()
1✔
1541
            .multi_point()
1✔
1542
            .unwrap();
1✔
1543

1✔
1544
        let spatial_bounds = BoundingBox2D::new(
1✔
1545
            (30.0, 0.0).into(),  // lower left of utm36n area of use
1✔
1546
            (33.0, 42.0).into(), // upper right of utm36n area of use
1✔
1547
        )
1✔
1548
        .unwrap();
1✔
1549

1✔
1550
        let qs = qp
1✔
1551
            .vector_query(
1✔
1552
                QueryRectangle {
1✔
1553
                    spatial_bounds,
1✔
1554
                    time_interval: TimeInterval::default(),
1✔
1555
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1556
                    attributes: ColumnSelection::all(),
1✔
1557
                },
1✔
1558
                &query_ctx,
1✔
1559
            )
1✔
1560
            .await
1✔
1561
            .unwrap();
1✔
1562

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

1✔
1565
        assert_eq!(points.len(), 1);
1✔
1566

1✔
1567
        let points = &points[0];
1✔
1568

1✔
1569
        assert!(approx_eq!(
1✔
1570
            &[Coordinate2D],
1✔
1571
            points.coordinates(),
1✔
1572
            &[
1✔
1573
                (30.0, 0.0).into(), // lower left of utm36n area of use
1✔
1574
                (36.0, 84.0).into(),
1✔
1575
                (33.0, 42.0).into(), // upper right of utm36n area of use
1✔
1576
            ]
1✔
1577
        ));
1✔
1578
    }
1✔
1579

1580
    #[tokio::test]
1581
    async fn points_from_utm36n_to_wgs84_out_of_area() {
1✔
1582
        // 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
1✔
1583

1✔
1584
        let exe_ctx = MockExecutionContext::test_default();
1✔
1585
        let query_ctx = MockQueryContext::test_default();
1✔
1586

1✔
1587
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
1588
            vec![MultiPointCollection::from_data(
1✔
1589
                MultiPoint::many(vec![
1✔
1590
                    vec![(758_565., 4_928_353.)], // (12.25, 44,46)
1✔
1591
                ])
1✔
1592
                .unwrap(),
1✔
1593
                vec![TimeInterval::default(); 1],
1✔
1594
                HashMap::default(),
1✔
1595
                CacheHint::default(),
1✔
1596
            )
1✔
1597
            .unwrap()],
1✔
1598
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 32636), //utm36n
1✔
1599
        )
1✔
1600
        .boxed();
1✔
1601

1✔
1602
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
1603
            params: ReprojectionParams {
1✔
1604
                target_spatial_reference: SpatialReference::new(
1✔
1605
                    SpatialReferenceAuthority::Epsg,
1✔
1606
                    4326, // utm36n
1✔
1607
                ),
1✔
1608
            },
1✔
1609
            sources: SingleRasterOrVectorSource {
1✔
1610
                source: point_source.into(),
1✔
1611
            },
1✔
1612
        })
1✔
1613
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1614
        .await
1✔
1615
        .unwrap();
1✔
1616

1✔
1617
        let qp = initialized_operator
1✔
1618
            .query_processor()
1✔
1619
            .unwrap()
1✔
1620
            .multi_point()
1✔
1621
            .unwrap();
1✔
1622

1✔
1623
        let spatial_bounds = BoundingBox2D::new(
1✔
1624
            (10.0, 0.0).into(),  // -20 x values left of lower left of utm36n area of use
1✔
1625
            (13.0, 42.0).into(), // -20 x values left of upper right of utm36n area of use
1✔
1626
        )
1✔
1627
        .unwrap();
1✔
1628

1✔
1629
        let qs = qp
1✔
1630
            .vector_query(
1✔
1631
                QueryRectangle {
1✔
1632
                    spatial_bounds,
1✔
1633
                    time_interval: TimeInterval::default(),
1✔
1634
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1635
                    attributes: ColumnSelection::all(),
1✔
1636
                },
1✔
1637
                &query_ctx,
1✔
1638
            )
1✔
1639
            .await
1✔
1640
            .unwrap();
1✔
1641

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

1✔
1644
        assert_eq!(points.len(), 1);
1✔
1645

1✔
1646
        let points = &points[0];
1✔
1647

1✔
1648
        assert!(geoengine_datatypes::collections::FeatureCollectionInfos::is_empty(points));
1✔
1649
        assert!(points.coordinates().is_empty());
1✔
1650
    }
1✔
1651

1652
    #[test]
1653
    fn it_derives_raster_result_descriptor() {
1✔
1654
        let in_proj = SpatialReference::epsg_4326();
1✔
1655
        let out_proj = SpatialReference::from_str("EPSG:3857").unwrap();
1✔
1656
        let bbox = Some(SpatialPartition2D::new_unchecked(
1✔
1657
            (-180., 90.).into(),
1✔
1658
            (180., -90.).into(),
1✔
1659
        ));
1✔
1660

1✔
1661
        let resolution = Some(SpatialResolution::new_unchecked(0.1, 0.1));
1✔
1662

1✔
1663
        let (in_bounds, out_bounds, out_res) =
1✔
1664
            InitializedRasterReprojection::derive_raster_in_bounds_out_bounds_out_res(
1✔
1665
                in_proj, out_proj, resolution, bbox,
1✔
1666
            )
1✔
1667
            .unwrap();
1✔
1668

1✔
1669
        assert_eq!(
1✔
1670
            in_bounds.unwrap(),
1✔
1671
            SpatialPartition2D::new_unchecked((-180., 85.06).into(), (180., -85.06).into(),)
1✔
1672
        );
1✔
1673

1674
        assert_eq!(
1✔
1675
            out_bounds.unwrap(),
1✔
1676
            out_proj
1✔
1677
                .area_of_use_projected::<SpatialPartition2D>()
1✔
1678
                .unwrap()
1✔
1679
        );
1✔
1680

1681
        // TODO: y resolution should be double the x resolution, but currently we only compute a uniform resolution
1682
        assert_eq!(
1✔
1683
            out_res.unwrap(),
1✔
1684
            SpatialResolution::new_unchecked(14_237.781_884_528_267, 14_237.781_884_528_267),
1✔
1685
        );
1✔
1686
    }
1✔
1687
}
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

© 2025 Coveralls, Inc