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

geo-engine / geoengine / 12469296660

23 Dec 2024 03:15PM UTC coverage: 90.56% (-0.1%) from 90.695%
12469296660

push

github

web-flow
Merge pull request #998 from geo-engine/quota_log_wip

Quota and Data usage Logging

859 of 1214 new or added lines in 66 files covered. (70.76%)

3 existing lines in 2 files now uncovered.

133923 of 147883 relevant lines covered (90.56%)

54439.32 hits per line

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

88.56
/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)]
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

6✔
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
        )?;
6✔
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]
1✔
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>> {
7✔
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
                })?;
7✔
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✔
232
        )?;
6✔
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

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

NEW
302
    fn path(&self) -> WorkflowOperatorPath {
×
NEW
303
        self.path.clone()
×
NEW
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>>> {
6✔
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>> {
6✔
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(),
×
400
                })?;
6✔
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
        )?;
6✔
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

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

NEW
573
    fn path(&self) -> WorkflowOperatorPath {
×
NEW
574
        self.path.clone()
×
NEW
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>>> {
4✔
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✔
651
            )?;
4✔
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

4✔
664
            // return the adapter which will reproject the tiles and uses the fill adapter to inject missing tiles
4✔
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
            test::TestDefault,
739
            well_known_data::{
740
                COLOGNE_EPSG_4326, COLOGNE_EPSG_900_913, HAMBURG_EPSG_4326, HAMBURG_EPSG_900_913,
741
                MARBURG_EPSG_4326, MARBURG_EPSG_900_913,
742
            },
743
            Identifier,
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,
1✔
755
                COLOGNE_EPSG_4326,
1✔
756
                HAMBURG_EPSG_4326,
1✔
757
            ])
1✔
758
            .unwrap(),
1✔
759
            vec![TimeInterval::new_unchecked(0, 1); 3],
1✔
760
            Default::default(),
1✔
761
            CacheHint::default(),
1✔
762
        )?;
1✔
763

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

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

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

1✔
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

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

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

1✔
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

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

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

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

1✔
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

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

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

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

1✔
846
        let lines_source = MockFeatureCollectionSource::single(lines.clone()).boxed();
1✔
847

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

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

1✔
865
        let query_processor = initialized_operator.query_processor()?;
1✔
866

1✔
867
        let query_processor = query_processor.multi_line_string().unwrap();
1✔
868

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

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

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

1✔
888
        assert_eq!(result.len(), 1);
1✔
889

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

1✔
902
        Ok(())
1✔
903
    }
1✔
904

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

1✔
920
        let expected = [MultiPolygon::new(vec![vec![vec![
1✔
921
            MARBURG_EPSG_900_913,
1✔
922
            COLOGNE_EPSG_900_913,
1✔
923
            HAMBURG_EPSG_900_913,
1✔
924
            MARBURG_EPSG_900_913,
1✔
925
        ]]])
1✔
926
        .unwrap()];
1✔
927

1✔
928
        let polygon_source = MockFeatureCollectionSource::single(polygons.clone()).boxed();
1✔
929

1✔
930
        let target_spatial_reference =
1✔
931
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 900_913);
1✔
932

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

1✔
947
        let query_processor = initialized_operator.query_processor()?;
1✔
948

1✔
949
        let query_processor = query_processor.multi_polygon().unwrap();
1✔
950

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

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

1✔
965
        let result = query
1✔
966
            .map(Result::unwrap)
1✔
967
            .collect::<Vec<MultiPolygonCollection>>()
1✔
968
            .await;
1✔
969

1✔
970
        assert_eq!(result.len(), 1);
1✔
971

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

1✔
979
        Ok(())
1✔
980
    }
1✔
981

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

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

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

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

1✔
1053
        let query_ctx = MockQueryContext::test_default();
1✔
1054

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

1✔
1066
        let qp = initialized_operator
1✔
1067
            .query_processor()
1✔
1068
            .unwrap()
1✔
1069
            .get_u8()
1✔
1070
            .unwrap();
1✔
1071

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

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

1✔
1081
        let res = a
1✔
1082
            .map(Result::unwrap)
1✔
1083
            .collect::<Vec<RasterTile2D<u8>>>()
1✔
1084
            .await;
1✔
1085
        assert!(data.tiles_equal_ignoring_cache_hint(&res));
1✔
1086

1✔
1087
        Ok(())
1✔
1088
    }
1✔
1089

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

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

1✔
1104
        let gdal_op = GdalSource {
1✔
1105
            params: GdalSourceParameters { data: id.clone() },
1✔
1106
        }
1✔
1107
        .boxed();
1✔
1108

1✔
1109
        let projection = SpatialReference::new(
1✔
1110
            geoengine_datatypes::spatial_reference::SpatialReferenceAuthority::Epsg,
1✔
1111
            3857,
1✔
1112
        );
1✔
1113

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

1✔
1125
        let x_query_resolution = output_bounds.size_x() / output_shape.axis_size_x() as f64;
1✔
1126
        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✔
1127
        let spatial_resolution =
1✔
1128
            SpatialResolution::new_unchecked(x_query_resolution, y_query_resolution);
1✔
1129

1✔
1130
        let qp = initialized_operator
1✔
1131
            .query_processor()
1✔
1132
            .unwrap()
1✔
1133
            .get_u8()
1✔
1134
            .unwrap();
1✔
1135

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

1✔
1149
        let res = qs
1✔
1150
            .map(Result::unwrap)
1✔
1151
            .collect::<Vec<RasterTile2D<u8>>>()
1✔
1152
            .await;
1✔
1153

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

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

1✔
1162
        assert_eq!(
1✔
1163
            include_bytes!(
1✔
1164
                "../../../test_data/raster/modis_ndvi/projected_3857/MOD13A2_M_NDVI_2014-04-01_tile-20.rst"
1✔
1165
            ) as &[u8],
1✔
1166
            res[8].clone().into_materialized_tile().grid_array.inner_grid.data.as_slice()
1✔
1167
        );
1✔
1168

1✔
1169
        Ok(())
1✔
1170
    }
1✔
1171

1172
    #[test]
1173
    fn query_rewrite_4326_3857() {
1✔
1174
        let query = VectorQueryRectangle {
1✔
1175
            spatial_bounds: BoundingBox2D::new_unchecked((-180., -90.).into(), (180., 90.).into()),
1✔
1176
            time_interval: TimeInterval::default(),
1✔
1177
            spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1178
            attributes: ColumnSelection::all(),
1✔
1179
        };
1✔
1180

1✔
1181
        let expected = BoundingBox2D::new_unchecked(
1✔
1182
            (-20_037_508.342_789_244, -20_048_966.104_014_594).into(),
1✔
1183
            (20_037_508.342_789_244, 20_048_966.104_014_594).into(),
1✔
1184
        );
1✔
1185

1✔
1186
        let reprojected = reproject_query(
1✔
1187
            query,
1✔
1188
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 3857),
1✔
1189
            SpatialReference::epsg_4326(),
1✔
1190
        )
1✔
1191
        .unwrap()
1✔
1192
        .unwrap();
1✔
1193

1✔
1194
        assert!(approx_eq!(
1✔
1195
            BoundingBox2D,
1✔
1196
            expected,
1✔
1197
            reprojected.spatial_bounds,
1✔
1198
            epsilon = 0.000_001
1✔
1199
        ));
1✔
1200
    }
1✔
1201

1202
    #[tokio::test]
1203
    async fn raster_ndvi_3857_to_4326() -> Result<()> {
1✔
1204
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1205
        let query_ctx = MockQueryContext::test_default();
1✔
1206

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

1✔
1255
        let id: DataId = DatasetId::new().into();
1✔
1256
        let name = NamedData::with_system_name("ndvi");
1✔
1257
        exe_ctx.add_meta_data(id.clone(), name.clone(), Box::new(m));
1✔
1258

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

1✔
1261
        let output_bounds =
1✔
1262
            SpatialPartition2D::new_unchecked((-180., 90.).into(), (180., -90.).into());
1✔
1263
        let time_interval = TimeInterval::new_unchecked(1_396_310_400_000, 1_396_310_400_000);
1✔
1264
        // 2014-04-01
1✔
1265

1✔
1266
        let gdal_op = GdalSource {
1✔
1267
            params: GdalSourceParameters { data: name },
1✔
1268
        }
1✔
1269
        .boxed();
1✔
1270

1✔
1271
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1272
            params: ReprojectionParams {
1✔
1273
                target_spatial_reference: SpatialReference::epsg_4326(),
1✔
1274
            },
1✔
1275
            sources: SingleRasterOrVectorSource {
1✔
1276
                source: gdal_op.into(),
1✔
1277
            },
1✔
1278
        })
1✔
1279
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1280
        .await?;
1✔
1281

1✔
1282
        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✔
1283
        let y_query_resolution = output_bounds.size_y() / 240.; // *2 to account for the dataset aspect ratio 2:1
1✔
1284
        let spatial_resolution =
1✔
1285
            SpatialResolution::new_unchecked(x_query_resolution, y_query_resolution);
1✔
1286

1✔
1287
        let qp = initialized_operator
1✔
1288
            .query_processor()
1✔
1289
            .unwrap()
1✔
1290
            .get_u8()
1✔
1291
            .unwrap();
1✔
1292

1✔
1293
        let qs = qp
1✔
1294
            .raster_query(
1✔
1295
                QueryRectangle {
1✔
1296
                    spatial_bounds: output_bounds,
1✔
1297
                    time_interval,
1✔
1298
                    spatial_resolution,
1✔
1299
                    attributes: BandSelection::first(),
1✔
1300
                },
1✔
1301
                &query_ctx,
1✔
1302
            )
1✔
1303
            .await
1✔
1304
            .unwrap();
1✔
1305

1✔
1306
        let tiles = qs
1✔
1307
            .map(Result::unwrap)
1✔
1308
            .collect::<Vec<RasterTile2D<u8>>>()
1✔
1309
            .await;
1✔
1310

1✔
1311
        // the test must generate 8x4 tiles
1✔
1312
        assert_eq!(tiles.len(), 32);
1✔
1313

1✔
1314
        // none of the tiles should be empty
1✔
1315
        assert!(tiles.iter().all(|t| !t.is_empty()));
32✔
1316

1✔
1317
        Ok(())
1✔
1318
    }
1✔
1319

1320
    #[test]
1321
    fn source_resolution() {
1✔
1322
        let epsg_4326 = SpatialReference::epsg_4326();
1✔
1323
        let epsg_3857 = SpatialReference::new(SpatialReferenceAuthority::Epsg, 3857);
1✔
1324

1✔
1325
        // use ndvi dataset that was reprojected using gdal as ground truth
1✔
1326
        let dataset_4326 = gdal_open_dataset(test_data!(
1✔
1327
            "raster/modis_ndvi/MOD13A2_M_NDVI_2014-04-01.TIFF"
1✔
1328
        ))
1✔
1329
        .unwrap();
1✔
1330
        let geotransform_4326 = dataset_4326.geo_transform().unwrap();
1✔
1331
        let res_4326 = SpatialResolution::new(geotransform_4326[1], -geotransform_4326[5]).unwrap();
1✔
1332

1✔
1333
        let dataset_3857 = gdal_open_dataset(test_data!(
1✔
1334
            "raster/modis_ndvi/projected_3857/MOD13A2_M_NDVI_2014-04-01.TIFF"
1✔
1335
        ))
1✔
1336
        .unwrap();
1✔
1337
        let geotransform_3857 = dataset_3857.geo_transform().unwrap();
1✔
1338
        let res_3857 = SpatialResolution::new(geotransform_3857[1], -geotransform_3857[5]).unwrap();
1✔
1339

1✔
1340
        // ndvi was projected from 4326 to 3857. The calculated source_resolution for getting the raster in 3857 with `res_3857`
1✔
1341
        // should thus roughly be like the original `res_4326`
1✔
1342
        let result_res = suggest_pixel_size_from_diag_cross_projected::<SpatialPartition2D>(
1✔
1343
            epsg_3857.area_of_use_projected().unwrap(),
1✔
1344
            epsg_4326.area_of_use_projected().unwrap(),
1✔
1345
            res_3857,
1✔
1346
        )
1✔
1347
        .unwrap();
1✔
1348
        assert!(1. - (result_res.x / res_4326.x).abs() < 0.02);
1✔
1349
        assert!(1. - (result_res.y / res_4326.y).abs() < 0.02);
1✔
1350
    }
1✔
1351

1352
    #[tokio::test]
1353
    async fn query_outside_projection_area_of_use_produces_empty_tiles() {
1✔
1354
        let mut exe_ctx = MockExecutionContext::test_default();
1✔
1355
        let query_ctx = MockQueryContext::test_default();
1✔
1356

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

1✔
1389
        let id: DataId = DatasetId::new().into();
1✔
1390
        let name = NamedData::with_system_name("ndvi");
1✔
1391
        exe_ctx.add_meta_data(id.clone(), name.clone(), Box::new(m));
1✔
1392

1✔
1393
        exe_ctx.tiling_specification =
1✔
1394
            TilingSpecification::new((0.0, 0.0).into(), [600, 600].into());
1✔
1395

1✔
1396
        let output_shape: GridShape2D = [1000, 1000].into();
1✔
1397
        let output_bounds =
1✔
1398
            SpatialPartition2D::new_unchecked((-180., 0.).into(), (180., -90.).into());
1✔
1399
        let time_interval = TimeInterval::new_instant(1_388_534_400_000).unwrap(); // 2014-01-01
1✔
1400

1✔
1401
        let gdal_op = GdalSource {
1✔
1402
            params: GdalSourceParameters { data: name },
1✔
1403
        }
1✔
1404
        .boxed();
1✔
1405

1✔
1406
        let initialized_operator = RasterOperator::boxed(Reprojection {
1✔
1407
            params: ReprojectionParams {
1✔
1408
                target_spatial_reference: SpatialReference::epsg_4326(),
1✔
1409
            },
1✔
1410
            sources: SingleRasterOrVectorSource {
1✔
1411
                source: gdal_op.into(),
1✔
1412
            },
1✔
1413
        })
1✔
1414
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1415
        .await
1✔
1416
        .unwrap();
1✔
1417

1✔
1418
        let x_query_resolution = output_bounds.size_x() / output_shape.axis_size_x() as f64;
1✔
1419
        let y_query_resolution = output_bounds.size_y() / (output_shape.axis_size_y()) as f64;
1✔
1420
        let spatial_resolution =
1✔
1421
            SpatialResolution::new_unchecked(x_query_resolution, y_query_resolution);
1✔
1422

1✔
1423
        let qp = initialized_operator
1✔
1424
            .query_processor()
1✔
1425
            .unwrap()
1✔
1426
            .get_u8()
1✔
1427
            .unwrap();
1✔
1428

1✔
1429
        let result = qp
1✔
1430
            .raster_query(
1✔
1431
                QueryRectangle {
1✔
1432
                    spatial_bounds: output_bounds,
1✔
1433
                    time_interval,
1✔
1434
                    spatial_resolution,
1✔
1435
                    attributes: BandSelection::first(),
1✔
1436
                },
1✔
1437
                &query_ctx,
1✔
1438
            )
1✔
1439
            .await
1✔
1440
            .unwrap()
1✔
1441
            .map(Result::unwrap)
1✔
1442
            .collect::<Vec<_>>()
1✔
1443
            .await;
1✔
1444

1✔
1445
        assert_eq!(result.len(), 4);
1✔
1446

1✔
1447
        for r in result {
5✔
1448
            assert!(r.is_empty());
4✔
1449
        }
1✔
1450
    }
1✔
1451

1452
    #[tokio::test]
1453
    async fn points_from_wgs84_to_utm36n() {
1✔
1454
        let exe_ctx = MockExecutionContext::test_default();
1✔
1455
        let query_ctx = MockQueryContext::test_default();
1✔
1456

1✔
1457
        let point_source = MockFeatureCollectionSource::single(
1✔
1458
            MultiPointCollection::from_data(
1✔
1459
                MultiPoint::many(vec![
1✔
1460
                    vec![(30.0, 0.0)], // lower left of utm36n area of use
1✔
1461
                    vec![(36.0, 84.0)],
1✔
1462
                    vec![(33.0, 42.0)], // upper right of utm36n area of use
1✔
1463
                ])
1✔
1464
                .unwrap(),
1✔
1465
                vec![TimeInterval::default(); 3],
1✔
1466
                HashMap::default(),
1✔
1467
                CacheHint::default(),
1✔
1468
            )
1✔
1469
            .unwrap(),
1✔
1470
        )
1✔
1471
        .boxed();
1✔
1472

1✔
1473
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
1474
            params: ReprojectionParams {
1✔
1475
                target_spatial_reference: SpatialReference::new(
1✔
1476
                    SpatialReferenceAuthority::Epsg,
1✔
1477
                    32636, // utm36n
1✔
1478
                ),
1✔
1479
            },
1✔
1480
            sources: SingleRasterOrVectorSource {
1✔
1481
                source: point_source.into(),
1✔
1482
            },
1✔
1483
        })
1✔
1484
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1485
        .await
1✔
1486
        .unwrap();
1✔
1487

1✔
1488
        let qp = initialized_operator
1✔
1489
            .query_processor()
1✔
1490
            .unwrap()
1✔
1491
            .multi_point()
1✔
1492
            .unwrap();
1✔
1493

1✔
1494
        let spatial_bounds = BoundingBox2D::new(
1✔
1495
            (166_021.44, 0.00).into(), // lower left of projected utm36n area of use
1✔
1496
            (534_994.666_6, 9_329_005.18).into(), // upper right of projected utm36n area of use
1✔
1497
        )
1✔
1498
        .unwrap();
1✔
1499

1✔
1500
        let qs = qp
1✔
1501
            .vector_query(
1✔
1502
                QueryRectangle {
1✔
1503
                    spatial_bounds,
1✔
1504
                    time_interval: TimeInterval::default(),
1✔
1505
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1506
                    attributes: ColumnSelection::all(),
1✔
1507
                },
1✔
1508
                &query_ctx,
1✔
1509
            )
1✔
1510
            .await
1✔
1511
            .unwrap();
1✔
1512

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

1✔
1515
        assert_eq!(points.len(), 1);
1✔
1516

1✔
1517
        let points = &points[0];
1✔
1518

1✔
1519
        assert_eq!(
1✔
1520
            points.coordinates(),
1✔
1521
            &[
1✔
1522
                (166_021.443_080_538_42, 0.0).into(),
1✔
1523
                (534_994.655_061_136_1, 9_329_005.182_447_437).into(),
1✔
1524
                (499_999.999_999_999_5, 4_649_776.224_819_178).into()
1✔
1525
            ]
1✔
1526
        );
1✔
1527
    }
1✔
1528

1529
    #[tokio::test]
1530
    async fn points_from_utm36n_to_wgs84() {
1✔
1531
        let exe_ctx = MockExecutionContext::test_default();
1✔
1532
        let query_ctx = MockQueryContext::test_default();
1✔
1533

1✔
1534
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
1535
            vec![MultiPointCollection::from_data(
1✔
1536
                MultiPoint::many(vec![
1✔
1537
                    vec![(166_021.443_080_538_42, 0.0)],
1✔
1538
                    vec![(534_994.655_061_136_1, 9_329_005.182_447_437)],
1✔
1539
                    vec![(499_999.999_999_999_5, 4_649_776.224_819_178)],
1✔
1540
                ])
1✔
1541
                .unwrap(),
1✔
1542
                vec![TimeInterval::default(); 3],
1✔
1543
                HashMap::default(),
1✔
1544
                CacheHint::default(),
1✔
1545
            )
1✔
1546
            .unwrap()],
1✔
1547
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 32636), //utm36n
1✔
1548
        )
1✔
1549
        .boxed();
1✔
1550

1✔
1551
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
1552
            params: ReprojectionParams {
1✔
1553
                target_spatial_reference: SpatialReference::new(
1✔
1554
                    SpatialReferenceAuthority::Epsg,
1✔
1555
                    4326, // utm36n
1✔
1556
                ),
1✔
1557
            },
1✔
1558
            sources: SingleRasterOrVectorSource {
1✔
1559
                source: point_source.into(),
1✔
1560
            },
1✔
1561
        })
1✔
1562
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1563
        .await
1✔
1564
        .unwrap();
1✔
1565

1✔
1566
        let qp = initialized_operator
1✔
1567
            .query_processor()
1✔
1568
            .unwrap()
1✔
1569
            .multi_point()
1✔
1570
            .unwrap();
1✔
1571

1✔
1572
        let spatial_bounds = BoundingBox2D::new(
1✔
1573
            (30.0, 0.0).into(),  // lower left of utm36n area of use
1✔
1574
            (33.0, 42.0).into(), // upper right of utm36n area of use
1✔
1575
        )
1✔
1576
        .unwrap();
1✔
1577

1✔
1578
        let qs = qp
1✔
1579
            .vector_query(
1✔
1580
                QueryRectangle {
1✔
1581
                    spatial_bounds,
1✔
1582
                    time_interval: TimeInterval::default(),
1✔
1583
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1584
                    attributes: ColumnSelection::all(),
1✔
1585
                },
1✔
1586
                &query_ctx,
1✔
1587
            )
1✔
1588
            .await
1✔
1589
            .unwrap();
1✔
1590

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

1✔
1593
        assert_eq!(points.len(), 1);
1✔
1594

1✔
1595
        let points = &points[0];
1✔
1596

1✔
1597
        assert!(approx_eq!(
1✔
1598
            &[Coordinate2D],
1✔
1599
            points.coordinates(),
1✔
1600
            &[
1✔
1601
                (30.0, 0.0).into(), // lower left of utm36n area of use
1✔
1602
                (36.0, 84.0).into(),
1✔
1603
                (33.0, 42.0).into(), // upper right of utm36n area of use
1✔
1604
            ]
1✔
1605
        ));
1✔
1606
    }
1✔
1607

1608
    #[tokio::test]
1609
    async fn points_from_utm36n_to_wgs84_out_of_area() {
1✔
1610
        // 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✔
1611

1✔
1612
        let exe_ctx = MockExecutionContext::test_default();
1✔
1613
        let query_ctx = MockQueryContext::test_default();
1✔
1614

1✔
1615
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
1616
            vec![MultiPointCollection::from_data(
1✔
1617
                MultiPoint::many(vec![
1✔
1618
                    vec![(758_565., 4_928_353.)], // (12.25, 44,46)
1✔
1619
                ])
1✔
1620
                .unwrap(),
1✔
1621
                vec![TimeInterval::default(); 1],
1✔
1622
                HashMap::default(),
1✔
1623
                CacheHint::default(),
1✔
1624
            )
1✔
1625
            .unwrap()],
1✔
1626
            SpatialReference::new(SpatialReferenceAuthority::Epsg, 32636), //utm36n
1✔
1627
        )
1✔
1628
        .boxed();
1✔
1629

1✔
1630
        let initialized_operator = VectorOperator::boxed(Reprojection {
1✔
1631
            params: ReprojectionParams {
1✔
1632
                target_spatial_reference: SpatialReference::new(
1✔
1633
                    SpatialReferenceAuthority::Epsg,
1✔
1634
                    4326, // utm36n
1✔
1635
                ),
1✔
1636
            },
1✔
1637
            sources: SingleRasterOrVectorSource {
1✔
1638
                source: point_source.into(),
1✔
1639
            },
1✔
1640
        })
1✔
1641
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1✔
1642
        .await
1✔
1643
        .unwrap();
1✔
1644

1✔
1645
        let qp = initialized_operator
1✔
1646
            .query_processor()
1✔
1647
            .unwrap()
1✔
1648
            .multi_point()
1✔
1649
            .unwrap();
1✔
1650

1✔
1651
        let spatial_bounds = BoundingBox2D::new(
1✔
1652
            (10.0, 0.0).into(),  // -20 x values left of lower left of utm36n area of use
1✔
1653
            (13.0, 42.0).into(), // -20 x values left of upper right of utm36n area of use
1✔
1654
        )
1✔
1655
        .unwrap();
1✔
1656

1✔
1657
        let qs = qp
1✔
1658
            .vector_query(
1✔
1659
                QueryRectangle {
1✔
1660
                    spatial_bounds,
1✔
1661
                    time_interval: TimeInterval::default(),
1✔
1662
                    spatial_resolution: SpatialResolution::zero_point_one(),
1✔
1663
                    attributes: ColumnSelection::all(),
1✔
1664
                },
1✔
1665
                &query_ctx,
1✔
1666
            )
1✔
1667
            .await
1✔
1668
            .unwrap();
1✔
1669

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

1✔
1672
        assert_eq!(points.len(), 1);
1✔
1673

1✔
1674
        let points = &points[0];
1✔
1675

1✔
1676
        assert!(geoengine_datatypes::collections::FeatureCollectionInfos::is_empty(points));
1✔
1677
        assert!(points.coordinates().is_empty());
1✔
1678
    }
1✔
1679

1680
    #[test]
1681
    fn it_derives_raster_result_descriptor() {
1✔
1682
        let in_proj = SpatialReference::epsg_4326();
1✔
1683
        let out_proj = SpatialReference::from_str("EPSG:3857").unwrap();
1✔
1684
        let bbox = Some(SpatialPartition2D::new_unchecked(
1✔
1685
            (-180., 90.).into(),
1✔
1686
            (180., -90.).into(),
1✔
1687
        ));
1✔
1688

1✔
1689
        let resolution = Some(SpatialResolution::new_unchecked(0.1, 0.1));
1✔
1690

1✔
1691
        let (in_bounds, out_bounds, out_res) =
1✔
1692
            InitializedRasterReprojection::derive_raster_in_bounds_out_bounds_out_res(
1✔
1693
                in_proj, out_proj, resolution, bbox,
1✔
1694
            )
1✔
1695
            .unwrap();
1✔
1696

1✔
1697
        assert_eq!(
1✔
1698
            in_bounds.unwrap(),
1✔
1699
            SpatialPartition2D::new_unchecked((-180., 85.06).into(), (180., -85.06).into(),)
1✔
1700
        );
1✔
1701

1702
        assert_eq!(
1✔
1703
            out_bounds.unwrap(),
1✔
1704
            out_proj
1✔
1705
                .area_of_use_projected::<SpatialPartition2D>()
1✔
1706
                .unwrap()
1✔
1707
        );
1✔
1708

1709
        // TODO: y resolution should be double the x resolution, but currently we only compute a uniform resolution
1710
        assert_eq!(
1✔
1711
            out_res.unwrap(),
1✔
1712
            SpatialResolution::new_unchecked(14_237.781_884_528_267, 14_237.781_884_528_267),
1✔
1713
        );
1✔
1714
    }
1✔
1715
}
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