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

geo-engine / geoengine / 9364358145

04 Jun 2024 09:08AM UTC coverage: 90.582% (+0.01%) from 90.571%
9364358145

push

github

web-flow
Merge pull request #958 from geo-engine/percentile_statistics

add percentiles to statistics operator

315 of 325 new or added lines in 6 files covered. (96.92%)

16 existing lines in 12 files now uncovered.

131329 of 144984 relevant lines covered (90.58%)

53359.25 hits per line

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

91.63
/operators/src/processing/raster_vector_join/mod.rs
1
mod aggregated;
2
mod aggregator;
3
mod non_aggregated;
4
mod util;
5

6
use crate::engine::{
7
    CanonicOperatorName, ExecutionContext, InitializedRasterOperator, InitializedVectorOperator,
8
    Operator, OperatorName, SingleVectorMultipleRasterSources, TypedRasterQueryProcessor,
9
    TypedVectorQueryProcessor, VectorColumnInfo, VectorOperator, VectorQueryProcessor,
10
    VectorResultDescriptor, WorkflowOperatorPath,
11
};
12
use crate::error::{self, ColumnNameConflict, Error};
13
use crate::processing::raster_vector_join::non_aggregated::RasterVectorJoinProcessor;
14
use crate::util::Result;
15

16
use crate::processing::raster_vector_join::aggregated::RasterVectorAggregateJoinProcessor;
17
use async_trait::async_trait;
18
use geoengine_datatypes::collections::VectorDataType;
19
use geoengine_datatypes::primitives::FeatureDataType;
20
use geoengine_datatypes::raster::{Pixel, RasterDataType, RenameBands};
21
use serde::{Deserialize, Serialize};
22
use snafu::ensure;
23

24
use self::aggregator::{
25
    Aggregator, FirstValueFloatAggregator, FirstValueIntAggregator, MeanValueAggregator,
26
    TypedAggregator,
27
};
28

29
/// An operator that attaches raster values to vector data
30
pub type RasterVectorJoin = Operator<RasterVectorJoinParams, SingleVectorMultipleRasterSources>;
31

32
impl OperatorName for RasterVectorJoin {
33
    const TYPE_NAME: &'static str = "RasterVectorJoin";
34
}
35

36
const MAX_NUMBER_OF_RASTER_INPUTS: usize = 8;
37

38
/// The parameter spec for `RasterVectorJoin`
39
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25✔
40
#[serde(rename_all = "camelCase")]
41
pub struct RasterVectorJoinParams {
42
    /// The names of the new columns are derived from the names of the raster bands.
43
    /// This parameter specifies how to perform the derivation.
44
    pub names: ColumnNames,
45

46
    /// Specifies which method is used for aggregating values for a feature
47
    pub feature_aggregation: FeatureAggregationMethod,
48

49
    /// Whether NO DATA values should be ignored in aggregating the joined feature data
50
    /// `false` by default
51
    #[serde(default)]
52
    pub feature_aggregation_ignore_no_data: bool,
53

54
    /// Specifies which method is used for aggregating values over time
55
    pub temporal_aggregation: TemporalAggregationMethod,
56

57
    /// Whether NO DATA values should be ignored in aggregating the joined temporal data
58
    /// `false` by default
59
    #[serde(default)]
60
    pub temporal_aggregation_ignore_no_data: bool,
61
}
62

63
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9✔
64
#[serde(rename_all = "camelCase", tag = "type", content = "values")]
65
pub enum ColumnNames {
66
    Default, // use the input band name and append " (n)" to the band name for the `n`-th conflict,
67
    Suffix(Vec<String>), // A suffix for every input, to be appended to the original band names
68
    Names(Vec<String>), // A column name for each band, to be used instead of the original band names
69
}
70

71
impl From<ColumnNames> for RenameBands {
72
    fn from(column_names: ColumnNames) -> Self {
5✔
73
        match column_names {
5✔
74
            ColumnNames::Default => RenameBands::Default,
4✔
75
            ColumnNames::Suffix(suffixes) => RenameBands::Suffix(suffixes),
×
76
            ColumnNames::Names(names) => RenameBands::Rename(names),
1✔
77
        }
78
    }
5✔
79
}
80

81
/// How to aggregate the values for the geometries inside a feature e.g.
82
/// the mean of all the raster values corresponding to the individual
83
/// points inside a `MultiPoint` feature.
84
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Copy)]
8✔
85
#[serde(rename_all = "camelCase")]
86
pub enum FeatureAggregationMethod {
87
    First,
88
    Mean,
89
}
90

91
/// How to aggregate the values over time
92
/// If there are multiple rasters valid during the validity of a feature
93
/// the featuer is either split into multiple (None-aggregation) or the
94
/// values are aggreagated
95
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Copy)]
8✔
96
#[serde(rename_all = "camelCase")]
97
pub enum TemporalAggregationMethod {
98
    None,
99
    First,
100
    Mean,
101
}
102

103
#[allow(clippy::too_many_lines)]
104
#[typetag::serde]
2✔
105
#[async_trait]
106
impl VectorOperator for RasterVectorJoin {
107
    async fn _initialize(
6✔
108
        mut self: Box<Self>,
6✔
109
        path: WorkflowOperatorPath,
6✔
110
        context: &dyn ExecutionContext,
6✔
111
    ) -> Result<Box<dyn InitializedVectorOperator>> {
6✔
112
        ensure!(
6✔
113
            (1..=MAX_NUMBER_OF_RASTER_INPUTS).contains(&self.sources.rasters.len()),
6✔
114
            error::InvalidNumberOfRasterInputs {
×
115
                expected: 1..MAX_NUMBER_OF_RASTER_INPUTS,
×
116
                found: self.sources.rasters.len()
×
117
            }
×
118
        );
119

120
        let name = CanonicOperatorName::from(&self);
6✔
121

122
        let vector_source = self
6✔
123
            .sources
6✔
124
            .vector
6✔
125
            .initialize(path.clone_and_append(0), context)
6✔
UNCOV
126
            .await?;
×
127

128
        let vector_rd = vector_source.result_descriptor();
6✔
129

6✔
130
        ensure!(
6✔
131
            vector_rd.data_type != VectorDataType::Data,
6✔
132
            error::InvalidType {
×
133
                expected: format!(
×
134
                    "{}, {} or {}",
×
135
                    VectorDataType::MultiPoint,
×
136
                    VectorDataType::MultiLineString,
×
137
                    VectorDataType::MultiPolygon
×
138
                ),
×
139
                found: VectorDataType::Data.to_string()
×
140
            },
×
141
        );
142

143
        let raster_sources = futures::future::try_join_all(
6✔
144
            self.sources
6✔
145
                .rasters
6✔
146
                .into_iter()
6✔
147
                .enumerate()
6✔
148
                .map(|(i, op)| op.initialize(path.clone_and_append(i as u8 + 1), context)),
7✔
149
        )
6✔
UNCOV
150
        .await?;
×
151

152
        let source_descriptors = raster_sources
6✔
153
            .iter()
6✔
154
            .map(InitializedRasterOperator::result_descriptor)
6✔
155
            .collect::<Vec<_>>();
6✔
156

6✔
157
        let spatial_reference = vector_rd.spatial_reference;
6✔
158

159
        for other_spatial_reference in source_descriptors
7✔
160
            .iter()
6✔
161
            .map(|source_descriptor| source_descriptor.spatial_reference)
7✔
162
        {
163
            ensure!(
7✔
164
                spatial_reference == other_spatial_reference,
7✔
165
                crate::error::InvalidSpatialReference {
1✔
166
                    expected: spatial_reference,
1✔
167
                    found: other_spatial_reference,
1✔
168
                }
1✔
169
            );
170
        }
171

172
        let raster_sources_bands = source_descriptors
5✔
173
            .iter()
5✔
174
            .map(|rd| rd.bands.count() as usize)
6✔
175
            .collect::<Vec<_>>();
5✔
176

5✔
177
        let rename_bands: RenameBands = self.params.names.clone().into();
5✔
178

179
        let new_column_names = rename_bands.apply(
5✔
180
            source_descriptors
5✔
181
                .iter()
5✔
182
                .map(|d| d.bands.iter().map(|b| b.name.clone()).collect())
9✔
183
                .collect(),
5✔
184
        )?;
5✔
185

186
        for name in vector_rd.columns.keys() {
5✔
187
            ensure!(
×
188
                !new_column_names.contains(name),
×
189
                ColumnNameConflict { name }
×
190
            );
191
        }
192

193
        let params = self.params;
5✔
194

5✔
195
        let result_descriptor = vector_rd.map_columns(|columns| {
5✔
196
            let mut columns = columns.clone();
5✔
197
            let mut new_column_name_idx = 0;
5✔
198

199
            for source_descriptor in &source_descriptors {
11✔
200
                let feature_data_type = match params.temporal_aggregation {
6✔
201
                    TemporalAggregationMethod::First | TemporalAggregationMethod::None => {
202
                        match source_descriptor.data_type {
4✔
203
                            RasterDataType::U8
204
                            | RasterDataType::U16
205
                            | RasterDataType::U32
206
                            | RasterDataType::U64
207
                            | RasterDataType::I8
208
                            | RasterDataType::I16
209
                            | RasterDataType::I32
210
                            | RasterDataType::I64 => FeatureDataType::Int,
4✔
211
                            RasterDataType::F32 | RasterDataType::F64 => FeatureDataType::Float,
×
212
                        }
213
                    }
214
                    TemporalAggregationMethod::Mean => FeatureDataType::Float,
2✔
215
                };
216

217
                for band in source_descriptor.bands.iter() {
9✔
218
                    let column_name = new_column_names[new_column_name_idx].clone();
9✔
219
                    new_column_name_idx += 1;
9✔
220

9✔
221
                    columns.insert(
9✔
222
                        column_name,
9✔
223
                        VectorColumnInfo {
9✔
224
                            data_type: feature_data_type,
9✔
225
                            measurement: band.measurement.clone(),
9✔
226
                        },
9✔
227
                    );
9✔
228
                }
9✔
229
            }
230
            columns
5✔
231
        });
5✔
232

5✔
233
        Ok(InitializedRasterVectorJoin {
5✔
234
            name,
5✔
235
            result_descriptor,
5✔
236
            vector_source,
5✔
237
            raster_sources,
5✔
238
            raster_sources_bands,
5✔
239
            state: params,
5✔
240
            new_column_names,
5✔
241
        }
5✔
242
        .boxed())
5✔
243
    }
18✔
244

245
    span_fn!(RasterVectorJoin);
×
246
}
247

248
pub struct RasterInput {
249
    pub processor: TypedRasterQueryProcessor,
250
    pub column_names: Vec<String>,
251
}
252

253
pub struct InitializedRasterVectorJoin {
254
    name: CanonicOperatorName,
255
    result_descriptor: VectorResultDescriptor,
256
    vector_source: Box<dyn InitializedVectorOperator>,
257
    raster_sources: Vec<Box<dyn InitializedRasterOperator>>,
258
    raster_sources_bands: Vec<usize>,
259
    state: RasterVectorJoinParams,
260
    new_column_names: Vec<String>,
261
}
262

263
impl InitializedVectorOperator for InitializedRasterVectorJoin {
264
    fn result_descriptor(&self) -> &VectorResultDescriptor {
2✔
265
        &self.result_descriptor
2✔
266
    }
2✔
267

268
    fn query_processor(&self) -> Result<TypedVectorQueryProcessor> {
4✔
269
        let mut raster_inputs = vec![];
4✔
270

4✔
271
        let mut names = self.new_column_names.clone();
4✔
272
        for (raster_source, num_bands) in self
4✔
273
            .raster_sources
4✔
274
            .iter()
4✔
275
            .zip(self.raster_sources_bands.iter())
4✔
276
        {
4✔
277
            let processor = raster_source.query_processor()?;
4✔
278
            let column_names = names.drain(0..*num_bands).collect::<Vec<_>>();
4✔
279

4✔
280
            raster_inputs.push(RasterInput {
4✔
281
                processor,
4✔
282
                column_names,
4✔
283
            });
4✔
284
        }
285

286
        Ok(match self.vector_source.query_processor()? {
4✔
287
            TypedVectorQueryProcessor::Data(_) => unreachable!(),
×
288
            TypedVectorQueryProcessor::MultiPoint(points) => {
4✔
289
                TypedVectorQueryProcessor::MultiPoint(match self.state.temporal_aggregation {
4✔
290
                    TemporalAggregationMethod::None => RasterVectorJoinProcessor::new(
×
291
                        points,
×
292
                        self.result_descriptor.clone(),
×
293
                        raster_inputs,
×
294
                        self.state.feature_aggregation,
×
295
                        self.state.feature_aggregation_ignore_no_data,
×
296
                    )
×
297
                    .boxed(),
×
298
                    TemporalAggregationMethod::First | TemporalAggregationMethod::Mean => {
299
                        RasterVectorAggregateJoinProcessor::new(
4✔
300
                            points,
4✔
301
                            self.result_descriptor.clone(),
4✔
302
                            raster_inputs,
4✔
303
                            self.state.feature_aggregation,
4✔
304
                            self.state.feature_aggregation_ignore_no_data,
4✔
305
                            self.state.temporal_aggregation,
4✔
306
                            self.state.temporal_aggregation_ignore_no_data,
4✔
307
                        )
4✔
308
                        .boxed()
4✔
309
                    }
310
                })
311
            }
312
            TypedVectorQueryProcessor::MultiPolygon(polygons) => {
×
313
                TypedVectorQueryProcessor::MultiPolygon(match self.state.temporal_aggregation {
×
314
                    TemporalAggregationMethod::None => RasterVectorJoinProcessor::new(
×
315
                        polygons,
×
316
                        self.result_descriptor.clone(),
×
317
                        raster_inputs,
×
318
                        self.state.feature_aggregation,
×
319
                        self.state.feature_aggregation_ignore_no_data,
×
320
                    )
×
321
                    .boxed(),
×
322
                    TemporalAggregationMethod::First | TemporalAggregationMethod::Mean => {
323
                        RasterVectorAggregateJoinProcessor::new(
×
324
                            polygons,
×
325
                            self.result_descriptor.clone(),
×
326
                            raster_inputs,
×
327
                            self.state.feature_aggregation,
×
328
                            self.state.feature_aggregation_ignore_no_data,
×
329
                            self.state.temporal_aggregation,
×
330
                            self.state.temporal_aggregation_ignore_no_data,
×
331
                        )
×
332
                        .boxed()
×
333
                    }
334
                })
335
            }
336
            TypedVectorQueryProcessor::MultiLineString(_) => return Err(Error::NotYetImplemented),
×
337
        })
338
    }
4✔
339

340
    fn canonic_name(&self) -> CanonicOperatorName {
×
341
        self.name.clone()
×
342
    }
×
343
}
344

345
pub fn create_feature_aggregator<P: Pixel>(
31✔
346
    number_of_features: usize,
31✔
347
    aggregation: FeatureAggregationMethod,
31✔
348
    ignore_no_data: bool,
31✔
349
) -> TypedAggregator {
31✔
350
    match aggregation {
31✔
351
        FeatureAggregationMethod::First => match P::TYPE {
16✔
352
            RasterDataType::U8
353
            | RasterDataType::U16
354
            | RasterDataType::U32
355
            | RasterDataType::U64
356
            | RasterDataType::I8
357
            | RasterDataType::I16
358
            | RasterDataType::I32
359
            | RasterDataType::I64 => {
360
                FirstValueIntAggregator::new(number_of_features, ignore_no_data).into_typed()
16✔
361
            }
362
            RasterDataType::F32 | RasterDataType::F64 => {
363
                FirstValueFloatAggregator::new(number_of_features, ignore_no_data).into_typed()
×
364
            }
365
        },
366
        FeatureAggregationMethod::Mean => {
367
            MeanValueAggregator::new(number_of_features, ignore_no_data).into_typed()
15✔
368
        }
369
    }
370
}
31✔
371

372
#[cfg(test)]
373
mod tests {
374
    use super::*;
375
    use std::str::FromStr;
376

377
    use crate::engine::{
378
        ChunkByteSize, MockExecutionContext, MockQueryContext, QueryProcessor,
379
        RasterBandDescriptor, RasterBandDescriptors, RasterOperator, RasterResultDescriptor,
380
    };
381
    use crate::mock::{MockFeatureCollectionSource, MockRasterSource, MockRasterSourceParams};
382
    use crate::source::{GdalSource, GdalSourceParameters};
383
    use crate::util::gdal::add_ndvi_dataset;
384
    use futures::StreamExt;
385
    use geoengine_datatypes::collections::{FeatureCollectionInfos, MultiPointCollection};
386
    use geoengine_datatypes::dataset::NamedData;
387
    use geoengine_datatypes::primitives::{
388
        BoundingBox2D, ColumnSelection, DataRef, DateTime, FeatureDataRef, MultiPoint,
389
        SpatialResolution, TimeInterval, VectorQueryRectangle,
390
    };
391
    use geoengine_datatypes::primitives::{CacheHint, Measurement};
392
    use geoengine_datatypes::raster::RasterTile2D;
393
    use geoengine_datatypes::spatial_reference::SpatialReference;
394
    use geoengine_datatypes::util::{gdal::hide_gdal_errors, test::TestDefault};
395
    use serde_json::json;
396

397
    #[test]
1✔
398
    fn serialization() {
1✔
399
        let raster_vector_join = RasterVectorJoin {
1✔
400
            params: RasterVectorJoinParams {
1✔
401
                names: ColumnNames::Names(vec!["foo".to_string(), "bar".to_string()]),
1✔
402
                feature_aggregation: FeatureAggregationMethod::First,
1✔
403
                feature_aggregation_ignore_no_data: false,
1✔
404
                temporal_aggregation: TemporalAggregationMethod::Mean,
1✔
405
                temporal_aggregation_ignore_no_data: false,
1✔
406
            },
1✔
407
            sources: SingleVectorMultipleRasterSources {
1✔
408
                vector: MockFeatureCollectionSource::<MultiPoint>::multiple(vec![]).boxed(),
1✔
409
                rasters: vec![],
1✔
410
            },
1✔
411
        };
1✔
412

1✔
413
        let serialized = json!({
1✔
414
            "type": "RasterVectorJoin",
1✔
415
            "params": {
1✔
416
                "names": {
1✔
417
                    "type": "names",
1✔
418
                    "values": ["foo", "bar"],
1✔
419
                },
1✔
420
                "featureAggregation": "first",
1✔
421
                "temporalAggregation": "mean",
1✔
422
            },
1✔
423
            "sources": {
1✔
424
                "vector": {
1✔
425
                    "type": "MockFeatureCollectionSourceMultiPoint",
1✔
426
                    "params": {
1✔
427
                        "collections": [],
1✔
428
                        "spatialReference": "EPSG:4326",
1✔
429
                        "measurements": {},
1✔
430
                    }
1✔
431
                },
1✔
432
                "rasters": [],
1✔
433
            },
1✔
434
        })
1✔
435
        .to_string();
1✔
436

1✔
437
        let deserialized: RasterVectorJoin = serde_json::from_str(&serialized).unwrap();
1✔
438

1✔
439
        assert_eq!(deserialized.params, raster_vector_join.params);
1✔
440
    }
1✔
441

442
    fn ndvi_source(name: NamedData) -> Box<dyn RasterOperator> {
4✔
443
        let gdal_source = GdalSource {
4✔
444
            params: GdalSourceParameters { data: name },
4✔
445
        };
4✔
446

4✔
447
        gdal_source.boxed()
4✔
448
    }
4✔
449

450
    #[tokio::test]
1✔
451
    async fn ndvi_time_point() {
1✔
452
        let point_source = MockFeatureCollectionSource::single(
1✔
453
            MultiPointCollection::from_data(
1✔
454
                MultiPoint::many(vec![
1✔
455
                    (-13.95, 20.05),
1✔
456
                    (-14.05, 20.05),
1✔
457
                    (-13.95, 19.95),
1✔
458
                    (-14.05, 19.95),
1✔
459
                ])
1✔
460
                .unwrap(),
1✔
461
                vec![
1✔
462
                    TimeInterval::new(
1✔
463
                        DateTime::new_utc(2014, 1, 1, 0, 0, 0),
1✔
464
                        DateTime::new_utc(2014, 1, 1, 0, 0, 0),
1✔
465
                    )
1✔
466
                    .unwrap();
1✔
467
                    4
1✔
468
                ],
1✔
469
                Default::default(),
1✔
470
                CacheHint::default(),
1✔
471
            )
1✔
472
            .unwrap(),
1✔
473
        )
1✔
474
        .boxed();
1✔
475

1✔
476
        let mut exe_ctc = MockExecutionContext::test_default();
1✔
477
        let ndvi_id = add_ndvi_dataset(&mut exe_ctc);
1✔
478

1✔
479
        let operator = RasterVectorJoin {
1✔
480
            params: RasterVectorJoinParams {
1✔
481
                names: ColumnNames::Default,
1✔
482
                feature_aggregation: FeatureAggregationMethod::First,
1✔
483
                feature_aggregation_ignore_no_data: false,
1✔
484
                temporal_aggregation: TemporalAggregationMethod::First,
1✔
485
                temporal_aggregation_ignore_no_data: false,
1✔
486
            },
1✔
487
            sources: SingleVectorMultipleRasterSources {
1✔
488
                vector: point_source,
1✔
489
                rasters: vec![ndvi_source(ndvi_id.clone())],
1✔
490
            },
1✔
491
        };
1✔
492

1✔
493
        let operator = operator
1✔
494
            .boxed()
1✔
495
            .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
496
            .await
1✔
497
            .unwrap();
1✔
498

1✔
499
        let query_processor = operator.query_processor().unwrap().multi_point().unwrap();
1✔
500

1✔
501
        let result = query_processor
1✔
502
            .query(
1✔
503
                VectorQueryRectangle {
1✔
504
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
505
                        .unwrap(),
1✔
506
                    time_interval: TimeInterval::default(),
1✔
507
                    spatial_resolution: SpatialResolution::new(0.1, 0.1).unwrap(),
1✔
508
                    attributes: ColumnSelection::all(),
1✔
509
                },
1✔
510
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
511
            )
1✔
512
            .await
1✔
513
            .unwrap()
1✔
514
            .map(Result::unwrap)
1✔
515
            .collect::<Vec<MultiPointCollection>>()
1✔
516
            .await;
33✔
517

1✔
518
        assert_eq!(result.len(), 1);
1✔
519

1✔
520
        let FeatureDataRef::Int(data) = result[0].data("ndvi").unwrap() else {
1✔
521
            unreachable!();
1✔
522
        };
1✔
523

1✔
524
        // these values are taken from loading the tiff in QGIS
1✔
525
        assert_eq!(data.as_ref(), &[54, 55, 51, 55]);
1✔
526
    }
1✔
527

528
    #[tokio::test]
1✔
529
    #[allow(clippy::float_cmp)]
530
    async fn ndvi_time_range() {
1✔
531
        let point_source = MockFeatureCollectionSource::single(
1✔
532
            MultiPointCollection::from_data(
1✔
533
                MultiPoint::many(vec![
1✔
534
                    (-13.95, 20.05),
1✔
535
                    (-14.05, 20.05),
1✔
536
                    (-13.95, 19.95),
1✔
537
                    (-14.05, 19.95),
1✔
538
                ])
1✔
539
                .unwrap(),
1✔
540
                vec![
1✔
541
                    TimeInterval::new(
1✔
542
                        DateTime::new_utc(2014, 1, 1, 0, 0, 0),
1✔
543
                        DateTime::new_utc(2014, 3, 1, 0, 0, 0),
1✔
544
                    )
1✔
545
                    .unwrap();
1✔
546
                    4
1✔
547
                ],
1✔
548
                Default::default(),
1✔
549
                CacheHint::default(),
1✔
550
            )
1✔
551
            .unwrap(),
1✔
552
        )
1✔
553
        .boxed();
1✔
554

1✔
555
        let mut exe_ctc = MockExecutionContext::test_default();
1✔
556
        let ndvi_id = add_ndvi_dataset(&mut exe_ctc);
1✔
557

1✔
558
        let operator = RasterVectorJoin {
1✔
559
            params: RasterVectorJoinParams {
1✔
560
                names: ColumnNames::Default,
1✔
561
                feature_aggregation: FeatureAggregationMethod::First,
1✔
562
                feature_aggregation_ignore_no_data: false,
1✔
563
                temporal_aggregation: TemporalAggregationMethod::Mean,
1✔
564
                temporal_aggregation_ignore_no_data: false,
1✔
565
            },
1✔
566
            sources: SingleVectorMultipleRasterSources {
1✔
567
                vector: point_source,
1✔
568
                rasters: vec![ndvi_source(ndvi_id.clone())],
1✔
569
            },
1✔
570
        };
1✔
571

1✔
572
        let operator = operator
1✔
573
            .boxed()
1✔
574
            .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
575
            .await
1✔
576
            .unwrap();
1✔
577

1✔
578
        let query_processor = operator.query_processor().unwrap().multi_point().unwrap();
1✔
579

1✔
580
        let result = query_processor
1✔
581
            .query(
1✔
582
                VectorQueryRectangle {
1✔
583
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
584
                        .unwrap(),
1✔
585
                    time_interval: TimeInterval::default(),
1✔
586
                    spatial_resolution: SpatialResolution::new(0.1, 0.1).unwrap(),
1✔
587
                    attributes: ColumnSelection::all(),
1✔
588
                },
1✔
589
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
590
            )
1✔
591
            .await
1✔
592
            .unwrap()
1✔
593
            .map(Result::unwrap)
1✔
594
            .collect::<Vec<MultiPointCollection>>()
1✔
595
            .await;
64✔
596

1✔
597
        assert_eq!(result.len(), 1);
1✔
598

1✔
599
        let FeatureDataRef::Float(data) = result[0].data("ndvi").unwrap() else {
1✔
600
            unreachable!();
1✔
601
        };
1✔
602

1✔
603
        // these values are taken from loading the tiff in QGIS
1✔
604
        assert_eq!(
1✔
605
            data.as_ref(),
1✔
606
            &[
1✔
607
                (54. + 52.) / 2.,
1✔
608
                (55. + 55.) / 2.,
1✔
609
                (51. + 50.) / 2.,
1✔
610
                (55. + 53.) / 2.,
1✔
611
            ]
1✔
612
        );
1✔
613
    }
1✔
614

615
    #[tokio::test]
1✔
616
    #[allow(clippy::float_cmp)]
617
    async fn ndvi_with_default_time() {
1✔
618
        hide_gdal_errors();
1✔
619

1✔
620
        let point_source = MockFeatureCollectionSource::single(
1✔
621
            MultiPointCollection::from_data(
1✔
622
                MultiPoint::many(vec![
1✔
623
                    (-13.95, 20.05),
1✔
624
                    (-14.05, 20.05),
1✔
625
                    (-13.95, 19.95),
1✔
626
                    (-14.05, 19.95),
1✔
627
                ])
1✔
628
                .unwrap(),
1✔
629
                vec![TimeInterval::default(); 4],
1✔
630
                Default::default(),
1✔
631
                CacheHint::default(),
1✔
632
            )
1✔
633
            .unwrap(),
1✔
634
        )
1✔
635
        .boxed();
1✔
636

1✔
637
        let mut exe_ctc = MockExecutionContext::test_default();
1✔
638
        let ndvi_id = add_ndvi_dataset(&mut exe_ctc);
1✔
639

1✔
640
        let operator = RasterVectorJoin {
1✔
641
            params: RasterVectorJoinParams {
1✔
642
                names: ColumnNames::Default,
1✔
643
                feature_aggregation: FeatureAggregationMethod::First,
1✔
644
                feature_aggregation_ignore_no_data: false,
1✔
645
                temporal_aggregation: TemporalAggregationMethod::Mean,
1✔
646
                temporal_aggregation_ignore_no_data: false,
1✔
647
            },
1✔
648
            sources: SingleVectorMultipleRasterSources {
1✔
649
                vector: point_source,
1✔
650
                rasters: vec![ndvi_source(ndvi_id.clone())],
1✔
651
            },
1✔
652
        };
1✔
653

1✔
654
        let operator = operator
1✔
655
            .boxed()
1✔
656
            .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
657
            .await
1✔
658
            .unwrap();
1✔
659

1✔
660
        let query_processor = operator.query_processor().unwrap().multi_point().unwrap();
1✔
661

1✔
662
        let result = query_processor
1✔
663
            .query(
1✔
664
                VectorQueryRectangle {
1✔
665
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
666
                        .unwrap(),
1✔
667
                    time_interval: TimeInterval::default(),
1✔
668
                    spatial_resolution: SpatialResolution::new(0.1, 0.1).unwrap(),
1✔
669
                    attributes: ColumnSelection::all(),
1✔
670
                },
1✔
671
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
672
            )
1✔
673
            .await
1✔
674
            .unwrap()
1✔
675
            .map(Result::unwrap)
1✔
676
            .collect::<Vec<MultiPointCollection>>()
1✔
677
            .await;
9✔
678

1✔
679
        assert_eq!(result.len(), 1);
1✔
680

1✔
681
        let FeatureDataRef::Float(data) = result[0].data("ndvi").unwrap() else {
1✔
682
            unreachable!();
1✔
683
        };
1✔
684

1✔
685
        assert_eq!(data.as_ref(), &[0., 0., 0., 0.]);
1✔
686

1✔
687
        assert_eq!(data.nulls(), vec![true, true, true, true]);
1✔
688
    }
1✔
689

690
    #[tokio::test]
1✔
691
    async fn it_checks_sref() {
1✔
692
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
693
            vec![MultiPointCollection::from_data(
1✔
694
                MultiPoint::many(vec![
1✔
695
                    (-13.95, 20.05),
1✔
696
                    (-14.05, 20.05),
1✔
697
                    (-13.95, 19.95),
1✔
698
                    (-14.05, 19.95),
1✔
699
                ])
1✔
700
                .unwrap(),
1✔
701
                vec![TimeInterval::default(); 4],
1✔
702
                Default::default(),
1✔
703
                CacheHint::default(),
1✔
704
            )
1✔
705
            .unwrap()],
1✔
706
            SpatialReference::from_str("EPSG:3857").unwrap(),
1✔
707
        )
1✔
708
        .boxed();
1✔
709

1✔
710
        let mut exe_ctc = MockExecutionContext::test_default();
1✔
711
        let ndvi_id = add_ndvi_dataset(&mut exe_ctc);
1✔
712

1✔
713
        let operator = RasterVectorJoin {
1✔
714
            params: RasterVectorJoinParams {
1✔
715
                names: ColumnNames::Default,
1✔
716
                feature_aggregation: FeatureAggregationMethod::First,
1✔
717
                feature_aggregation_ignore_no_data: false,
1✔
718
                temporal_aggregation: TemporalAggregationMethod::Mean,
1✔
719
                temporal_aggregation_ignore_no_data: false,
1✔
720
            },
1✔
721
            sources: SingleVectorMultipleRasterSources {
1✔
722
                vector: point_source,
1✔
723
                rasters: vec![ndvi_source(ndvi_id.clone())],
1✔
724
            },
1✔
725
        }
1✔
726
        .boxed()
1✔
727
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
728
        .await;
1✔
729

1✔
730
        assert!(matches!(
1✔
731
            operator,
1✔
732
            Err(Error::InvalidSpatialReference {
1✔
733
                expected: _,
1✔
734
                found: _,
1✔
735
            })
1✔
736
        ));
1✔
737
    }
1✔
738

739
    #[tokio::test]
1✔
740
    #[allow(clippy::too_many_lines)]
741
    async fn it_includes_bands_in_result_descriptor() {
1✔
742
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
743
            vec![MultiPointCollection::from_data(
1✔
744
                MultiPoint::many(vec![
1✔
745
                    (-13.95, 20.05),
1✔
746
                    (-14.05, 20.05),
1✔
747
                    (-13.95, 19.95),
1✔
748
                    (-14.05, 19.95),
1✔
749
                ])
1✔
750
                .unwrap(),
1✔
751
                vec![TimeInterval::default(); 4],
1✔
752
                Default::default(),
1✔
753
                CacheHint::default(),
1✔
754
            )
1✔
755
            .unwrap()],
1✔
756
            SpatialReference::from_str("EPSG:4326").unwrap(),
1✔
757
        )
1✔
758
        .boxed();
1✔
759

1✔
760
        let raster_source = MockRasterSource {
1✔
761
            params: MockRasterSourceParams {
1✔
762
                data: Vec::<RasterTile2D<u8>>::new(),
1✔
763
                result_descriptor: RasterResultDescriptor {
1✔
764
                    data_type: RasterDataType::U8,
1✔
765
                    spatial_reference: SpatialReference::epsg_4326().into(),
1✔
766
                    time: None,
1✔
767
                    bbox: None,
1✔
768
                    resolution: None,
1✔
769
                    bands: RasterBandDescriptors::new(vec![
1✔
770
                        RasterBandDescriptor::new_unitless("band_0".into()),
1✔
771
                        RasterBandDescriptor::new_unitless("band_1".into()),
1✔
772
                    ])
1✔
773
                    .unwrap(),
1✔
774
                },
1✔
775
            },
1✔
776
        }
1✔
777
        .boxed();
1✔
778

1✔
779
        let raster_source2 = MockRasterSource {
1✔
780
            params: MockRasterSourceParams {
1✔
781
                data: Vec::<RasterTile2D<u8>>::new(),
1✔
782
                result_descriptor: RasterResultDescriptor {
1✔
783
                    data_type: RasterDataType::U8,
1✔
784
                    spatial_reference: SpatialReference::epsg_4326().into(),
1✔
785
                    time: None,
1✔
786
                    bbox: None,
1✔
787
                    resolution: None,
1✔
788
                    bands: RasterBandDescriptors::new(vec![
1✔
789
                        RasterBandDescriptor::new_unitless("band_0".into()),
1✔
790
                        RasterBandDescriptor::new_unitless("band_1".into()),
1✔
791
                        RasterBandDescriptor::new_unitless("band_2".into()),
1✔
792
                    ])
1✔
793
                    .unwrap(),
1✔
794
                },
1✔
795
            },
1✔
796
        }
1✔
797
        .boxed();
1✔
798

1✔
799
        let exe_ctc = MockExecutionContext::test_default();
1✔
800

1✔
801
        let join = RasterVectorJoin {
1✔
802
            params: RasterVectorJoinParams {
1✔
803
                names: ColumnNames::Default,
1✔
804
                feature_aggregation: FeatureAggregationMethod::First,
1✔
805
                feature_aggregation_ignore_no_data: false,
1✔
806
                temporal_aggregation: TemporalAggregationMethod::None,
1✔
807
                temporal_aggregation_ignore_no_data: false,
1✔
808
            },
1✔
809
            sources: SingleVectorMultipleRasterSources {
1✔
810
                vector: point_source,
1✔
811
                rasters: vec![raster_source, raster_source2],
1✔
812
            },
1✔
813
        }
1✔
814
        .boxed()
1✔
815
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
816
        .await
1✔
817
        .unwrap();
1✔
818

1✔
819
        assert_eq!(
1✔
820
            join.result_descriptor(),
1✔
821
            &VectorResultDescriptor {
1✔
822
                data_type: VectorDataType::MultiPoint,
1✔
823
                spatial_reference: SpatialReference::epsg_4326().into(),
1✔
824
                columns: [
1✔
825
                    (
1✔
826
                        "band_0".to_string(),
1✔
827
                        VectorColumnInfo {
1✔
828
                            data_type: FeatureDataType::Int,
1✔
829
                            measurement: Measurement::Unitless
1✔
830
                        }
1✔
831
                    ),
1✔
832
                    (
1✔
833
                        "band_1".to_string(),
1✔
834
                        VectorColumnInfo {
1✔
835
                            data_type: FeatureDataType::Int,
1✔
836
                            measurement: Measurement::Unitless
1✔
837
                        }
1✔
838
                    ),
1✔
839
                    (
1✔
840
                        "band_0 (1)".to_string(),
1✔
841
                        VectorColumnInfo {
1✔
842
                            data_type: FeatureDataType::Int,
1✔
843
                            measurement: Measurement::Unitless
1✔
844
                        }
1✔
845
                    ),
1✔
846
                    (
1✔
847
                        "band_1 (1)".to_string(),
1✔
848
                        VectorColumnInfo {
1✔
849
                            data_type: FeatureDataType::Int,
1✔
850
                            measurement: Measurement::Unitless
1✔
851
                        }
1✔
852
                    ),
1✔
853
                    (
1✔
854
                        "band_2".to_string(),
1✔
855
                        VectorColumnInfo {
1✔
856
                            data_type: FeatureDataType::Int,
1✔
857
                            measurement: Measurement::Unitless
1✔
858
                        }
1✔
859
                    )
1✔
860
                ]
1✔
861
                .into_iter()
1✔
862
                .collect(),
1✔
863
                time: None,
1✔
864
                bbox: None
1✔
865
            }
1✔
866
        );
1✔
867
    }
1✔
868
}
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