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

geo-engine / geoengine / 7006568925

27 Nov 2023 02:07PM UTC coverage: 89.651% (+0.2%) from 89.498%
7006568925

push

github

web-flow
Merge pull request #888 from geo-engine/raster_stacks

raster stacking

4032 of 4274 new or added lines in 107 files covered. (94.34%)

12 existing lines in 8 files now uncovered.

113020 of 126066 relevant lines covered (89.65%)

59901.79 hits per line

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

88.72
/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, TypedVectorQueryProcessor,
9
    VectorColumnInfo, VectorOperator, VectorQueryProcessor, VectorResultDescriptor,
10
    WorkflowOperatorPath,
11
};
12
use crate::error::{self, 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};
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
    /// Each name reflects the output column of the join result.
43
    /// For each raster input, one name must be defined.
44
    pub names: Vec<String>,
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
/// How to aggregate the values for the geometries inside a feature e.g.
64
/// the mean of all the raster values corresponding to the individual
65
/// points inside a `MultiPoint` feature.
66
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Copy)]
8✔
67
#[serde(rename_all = "camelCase")]
68
pub enum FeatureAggregationMethod {
69
    First,
70
    Mean,
71
}
72

73
/// How to aggregate the values over time
74
/// If there are multiple rasters valid during the validity of a feature
75
/// the featuer is either split into multiple (None-aggregation) or the
76
/// values are aggreagated
77
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Copy)]
8✔
78
#[serde(rename_all = "camelCase")]
79
pub enum TemporalAggregationMethod {
80
    None,
81
    First,
82
    Mean,
83
}
84

85
#[allow(clippy::too_many_lines)]
86
#[typetag::serde]
2✔
87
#[async_trait]
88
impl VectorOperator for RasterVectorJoin {
89
    async fn _initialize(
6✔
90
        mut self: Box<Self>,
6✔
91
        path: WorkflowOperatorPath,
6✔
92
        context: &dyn ExecutionContext,
6✔
93
    ) -> Result<Box<dyn InitializedVectorOperator>> {
6✔
94
        ensure!(
6✔
95
            (1..=MAX_NUMBER_OF_RASTER_INPUTS).contains(&self.sources.rasters.len()),
6✔
96
            error::InvalidNumberOfRasterInputs {
×
97
                expected: 1..MAX_NUMBER_OF_RASTER_INPUTS,
×
98
                found: self.sources.rasters.len()
×
99
            }
×
100
        );
101
        ensure!(
6✔
102
            self.sources.rasters.len() == self.params.names.len(),
6✔
103
            error::InvalidOperatorSpec {
×
104
                reason: "`rasters` must be of equal length as `names`"
×
105
            }
×
106
        );
107

108
        let name = CanonicOperatorName::from(&self);
6✔
109

110
        let vector_source = self
6✔
111
            .sources
6✔
112
            .vector
6✔
113
            .initialize(path.clone_and_append(0), context)
6✔
114
            .await?;
6✔
115

116
        let vector_rd = vector_source.result_descriptor();
6✔
117

6✔
118
        ensure!(
6✔
119
            vector_rd.data_type != VectorDataType::Data,
6✔
120
            error::InvalidType {
×
121
                expected: format!(
×
122
                    "{}, {} or {}",
×
123
                    VectorDataType::MultiPoint,
×
124
                    VectorDataType::MultiLineString,
×
125
                    VectorDataType::MultiPolygon
×
126
                ),
×
127
                found: VectorDataType::Data.to_string()
×
128
            },
×
129
        );
130

131
        let raster_sources = futures::future::try_join_all(
6✔
132
            self.sources
6✔
133
                .rasters
6✔
134
                .into_iter()
6✔
135
                .enumerate()
6✔
136
                .map(|(i, op)| op.initialize(path.clone_and_append(i as u8 + 1), context)),
7✔
137
        )
6✔
138
        .await?;
6✔
139

140
        let source_descriptors = raster_sources
6✔
141
            .iter()
6✔
142
            .map(InitializedRasterOperator::result_descriptor)
6✔
143
            .collect::<Vec<_>>();
6✔
144

145
        // TODO: implement multi-band functionality for aggregated join and remove this check
146
        ensure!(
6✔
147
            matches!(
5✔
148
                self.params.temporal_aggregation,
6✔
149
                TemporalAggregationMethod::None
150
            ) || source_descriptors.iter().all(|rd| rd.bands.len() == 1),
5✔
NEW
151
            crate::error::OperatorDoesNotSupportMultiBandsSourcesYet {
×
NEW
152
                operator: "RasterVectorAggregateJoin"
×
NEW
153
            }
×
154
        );
155

156
        let spatial_reference = vector_rd.spatial_reference;
6✔
157

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

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

5✔
176
        let params = self.params;
5✔
177

5✔
178
        let result_descriptor = vector_rd.map_columns(|columns| {
5✔
179
            let mut columns = columns.clone();
5✔
180
            for ((i, new_column_name), source_descriptor) in
6✔
181
                params.names.iter().enumerate().zip(&source_descriptors)
5✔
182
            {
183
                let feature_data_type = match params.temporal_aggregation {
6✔
184
                    TemporalAggregationMethod::First | TemporalAggregationMethod::None => {
185
                        match raster_sources[i].result_descriptor().data_type {
4✔
186
                            RasterDataType::U8
187
                            | RasterDataType::U16
188
                            | RasterDataType::U32
189
                            | RasterDataType::U64
190
                            | RasterDataType::I8
191
                            | RasterDataType::I16
192
                            | RasterDataType::I32
193
                            | RasterDataType::I64 => FeatureDataType::Int,
4✔
194
                            RasterDataType::F32 | RasterDataType::F64 => FeatureDataType::Float,
×
195
                        }
196
                    }
197
                    TemporalAggregationMethod::Mean => FeatureDataType::Float,
2✔
198
                };
199

200
                for (i, band) in source_descriptor.bands.iter().enumerate() {
9✔
201
                    let column_name = if i == 0 {
9✔
202
                        new_column_name.clone()
6✔
203
                    } else {
204
                        format!("{new_column_name}_{i}")
3✔
205
                    };
206

207
                    columns.insert(
9✔
208
                        column_name,
9✔
209
                        VectorColumnInfo {
9✔
210
                            data_type: feature_data_type,
9✔
211
                            measurement: band.measurement.clone(),
9✔
212
                        },
9✔
213
                    );
9✔
214
                }
215
            }
216
            columns
5✔
217
        });
5✔
218

5✔
219
        Ok(InitializedRasterVectorJoin {
5✔
220
            name,
5✔
221
            result_descriptor,
5✔
222
            vector_source,
5✔
223
            raster_sources,
5✔
224
            raster_sources_bands,
5✔
225
            state: params,
5✔
226
        }
5✔
227
        .boxed())
5✔
228
    }
12✔
229

230
    span_fn!(RasterVectorJoin);
×
231
}
232

233
pub struct InitializedRasterVectorJoin {
234
    name: CanonicOperatorName,
235
    result_descriptor: VectorResultDescriptor,
236
    vector_source: Box<dyn InitializedVectorOperator>,
237
    raster_sources: Vec<Box<dyn InitializedRasterOperator>>,
238
    raster_sources_bands: Vec<usize>,
239
    state: RasterVectorJoinParams,
240
}
241

242
impl InitializedVectorOperator for InitializedRasterVectorJoin {
243
    fn result_descriptor(&self) -> &VectorResultDescriptor {
2✔
244
        &self.result_descriptor
2✔
245
    }
2✔
246

247
    fn query_processor(&self) -> Result<TypedVectorQueryProcessor> {
4✔
248
        let typed_raster_processors = self
4✔
249
            .raster_sources
4✔
250
            .iter()
4✔
251
            .map(InitializedRasterOperator::query_processor)
4✔
252
            .collect::<Result<Vec<_>>>()?;
4✔
253

254
        Ok(match self.vector_source.query_processor()? {
4✔
255
            TypedVectorQueryProcessor::Data(_) => unreachable!(),
×
256
            TypedVectorQueryProcessor::MultiPoint(points) => {
4✔
257
                TypedVectorQueryProcessor::MultiPoint(match self.state.temporal_aggregation {
4✔
258
                    TemporalAggregationMethod::None => RasterVectorJoinProcessor::new(
×
259
                        points,
×
260
                        typed_raster_processors,
×
NEW
261
                        self.raster_sources_bands.clone(),
×
262
                        self.state.names.clone(),
×
263
                        self.state.feature_aggregation,
×
264
                        self.state.feature_aggregation_ignore_no_data,
×
265
                    )
×
266
                    .boxed(),
×
267
                    TemporalAggregationMethod::First | TemporalAggregationMethod::Mean => {
268
                        RasterVectorAggregateJoinProcessor::new(
4✔
269
                            points,
4✔
270
                            typed_raster_processors,
4✔
271
                            self.state.names.clone(),
4✔
272
                            self.state.feature_aggregation,
4✔
273
                            self.state.feature_aggregation_ignore_no_data,
4✔
274
                            self.state.temporal_aggregation,
4✔
275
                            self.state.temporal_aggregation_ignore_no_data,
4✔
276
                        )
4✔
277
                        .boxed()
4✔
278
                    }
279
                })
280
            }
281
            TypedVectorQueryProcessor::MultiPolygon(polygons) => {
×
282
                TypedVectorQueryProcessor::MultiPolygon(match self.state.temporal_aggregation {
×
283
                    TemporalAggregationMethod::None => RasterVectorJoinProcessor::new(
×
284
                        polygons,
×
285
                        typed_raster_processors,
×
NEW
286
                        self.raster_sources_bands.clone(),
×
287
                        self.state.names.clone(),
×
288
                        self.state.feature_aggregation,
×
289
                        self.state.feature_aggregation_ignore_no_data,
×
290
                    )
×
291
                    .boxed(),
×
292
                    TemporalAggregationMethod::First | TemporalAggregationMethod::Mean => {
293
                        RasterVectorAggregateJoinProcessor::new(
×
294
                            polygons,
×
295
                            typed_raster_processors,
×
296
                            self.state.names.clone(),
×
297
                            self.state.feature_aggregation,
×
298
                            self.state.feature_aggregation_ignore_no_data,
×
299
                            self.state.temporal_aggregation,
×
300
                            self.state.temporal_aggregation_ignore_no_data,
×
301
                        )
×
302
                        .boxed()
×
303
                    }
304
                })
305
            }
306
            TypedVectorQueryProcessor::MultiLineString(_) => return Err(Error::NotYetImplemented),
×
307
        })
308
    }
4✔
309

310
    fn canonic_name(&self) -> CanonicOperatorName {
×
311
        self.name.clone()
×
312
    }
×
313
}
314

315
pub fn create_feature_aggregator<P: Pixel>(
28✔
316
    number_of_features: usize,
28✔
317
    aggregation: FeatureAggregationMethod,
28✔
318
    ignore_no_data: bool,
28✔
319
) -> TypedAggregator {
28✔
320
    match aggregation {
28✔
321
        FeatureAggregationMethod::First => match P::TYPE {
16✔
322
            RasterDataType::U8
323
            | RasterDataType::U16
324
            | RasterDataType::U32
325
            | RasterDataType::U64
326
            | RasterDataType::I8
327
            | RasterDataType::I16
328
            | RasterDataType::I32
329
            | RasterDataType::I64 => {
330
                FirstValueIntAggregator::new(number_of_features, ignore_no_data).into_typed()
16✔
331
            }
332
            RasterDataType::F32 | RasterDataType::F64 => {
333
                FirstValueFloatAggregator::new(number_of_features, ignore_no_data).into_typed()
×
334
            }
335
        },
336
        FeatureAggregationMethod::Mean => {
337
            MeanValueAggregator::new(number_of_features, ignore_no_data).into_typed()
12✔
338
        }
339
    }
340
}
28✔
341

342
#[cfg(test)]
343
mod tests {
344
    use super::*;
345
    use std::str::FromStr;
346

347
    use crate::engine::{
348
        ChunkByteSize, MockExecutionContext, MockQueryContext, QueryProcessor,
349
        RasterBandDescriptor, RasterBandDescriptors, RasterOperator, RasterResultDescriptor,
350
    };
351
    use crate::mock::{MockFeatureCollectionSource, MockRasterSource, MockRasterSourceParams};
352
    use crate::source::{GdalSource, GdalSourceParameters};
353
    use crate::util::gdal::add_ndvi_dataset;
354
    use futures::StreamExt;
355
    use geoengine_datatypes::collections::{FeatureCollectionInfos, MultiPointCollection};
356
    use geoengine_datatypes::dataset::NamedData;
357
    use geoengine_datatypes::primitives::{
358
        BoundingBox2D, ColumnSelection, DataRef, DateTime, FeatureDataRef, MultiPoint,
359
        SpatialResolution, TimeInterval, VectorQueryRectangle,
360
    };
361
    use geoengine_datatypes::primitives::{CacheHint, Measurement};
362
    use geoengine_datatypes::raster::RasterTile2D;
363
    use geoengine_datatypes::spatial_reference::SpatialReference;
364
    use geoengine_datatypes::util::{gdal::hide_gdal_errors, test::TestDefault};
365
    use serde_json::json;
366

367
    #[test]
1✔
368
    fn serialization() {
1✔
369
        let raster_vector_join = RasterVectorJoin {
1✔
370
            params: RasterVectorJoinParams {
1✔
371
                names: ["foo", "bar"].iter().copied().map(str::to_string).collect(),
1✔
372
                feature_aggregation: FeatureAggregationMethod::First,
1✔
373
                feature_aggregation_ignore_no_data: false,
1✔
374
                temporal_aggregation: TemporalAggregationMethod::Mean,
1✔
375
                temporal_aggregation_ignore_no_data: false,
1✔
376
            },
1✔
377
            sources: SingleVectorMultipleRasterSources {
1✔
378
                vector: MockFeatureCollectionSource::<MultiPoint>::multiple(vec![]).boxed(),
1✔
379
                rasters: vec![],
1✔
380
            },
1✔
381
        };
1✔
382

1✔
383
        let serialized = json!({
1✔
384
            "type": "RasterVectorJoin",
1✔
385
            "params": {
1✔
386
                "names": ["foo", "bar"],
1✔
387
                "featureAggregation": "first",
1✔
388
                "temporalAggregation": "mean",
1✔
389
            },
1✔
390
            "sources": {
1✔
391
                "vector": {
1✔
392
                    "type": "MockFeatureCollectionSourceMultiPoint",
1✔
393
                    "params": {
1✔
394
                        "collections": [],
1✔
395
                        "spatialReference": "EPSG:4326",
1✔
396
                        "measurements": {},
1✔
397
                    }
1✔
398
                },
1✔
399
                "rasters": [],
1✔
400
            },
1✔
401
        })
1✔
402
        .to_string();
1✔
403

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

1✔
406
        assert_eq!(deserialized.params, raster_vector_join.params);
1✔
407
    }
1✔
408

409
    fn ndvi_source(name: NamedData) -> Box<dyn RasterOperator> {
4✔
410
        let gdal_source = GdalSource {
4✔
411
            params: GdalSourceParameters { data: name },
4✔
412
        };
4✔
413

4✔
414
        gdal_source.boxed()
4✔
415
    }
4✔
416

417
    #[tokio::test]
1✔
418
    async fn ndvi_time_point() {
1✔
419
        let point_source = MockFeatureCollectionSource::single(
1✔
420
            MultiPointCollection::from_data(
1✔
421
                MultiPoint::many(vec![
1✔
422
                    (-13.95, 20.05),
1✔
423
                    (-14.05, 20.05),
1✔
424
                    (-13.95, 19.95),
1✔
425
                    (-14.05, 19.95),
1✔
426
                ])
1✔
427
                .unwrap(),
1✔
428
                vec![
1✔
429
                    TimeInterval::new(
1✔
430
                        DateTime::new_utc(2014, 1, 1, 0, 0, 0),
1✔
431
                        DateTime::new_utc(2014, 1, 1, 0, 0, 0),
1✔
432
                    )
1✔
433
                    .unwrap();
1✔
434
                    4
1✔
435
                ],
1✔
436
                Default::default(),
1✔
437
                CacheHint::default(),
1✔
438
            )
1✔
439
            .unwrap(),
1✔
440
        )
1✔
441
        .boxed();
1✔
442

1✔
443
        let mut exe_ctc = MockExecutionContext::test_default();
1✔
444
        let ndvi_id = add_ndvi_dataset(&mut exe_ctc);
1✔
445

1✔
446
        let operator = RasterVectorJoin {
1✔
447
            params: RasterVectorJoinParams {
1✔
448
                names: vec!["ndvi".to_string()],
1✔
449
                feature_aggregation: FeatureAggregationMethod::First,
1✔
450
                feature_aggregation_ignore_no_data: false,
1✔
451
                temporal_aggregation: TemporalAggregationMethod::First,
1✔
452
                temporal_aggregation_ignore_no_data: false,
1✔
453
            },
1✔
454
            sources: SingleVectorMultipleRasterSources {
1✔
455
                vector: point_source,
1✔
456
                rasters: vec![ndvi_source(ndvi_id.clone())],
1✔
457
            },
1✔
458
        };
1✔
459

460
        let operator = operator
1✔
461
            .boxed()
1✔
462
            .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
463
            .await
×
464
            .unwrap();
1✔
465

1✔
466
        let query_processor = operator.query_processor().unwrap().multi_point().unwrap();
1✔
467

468
        let result = query_processor
1✔
469
            .query(
1✔
470
                VectorQueryRectangle {
1✔
471
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
472
                        .unwrap(),
1✔
473
                    time_interval: TimeInterval::default(),
1✔
474
                    spatial_resolution: SpatialResolution::new(0.1, 0.1).unwrap(),
1✔
475
                    attributes: ColumnSelection::all(),
1✔
476
                },
1✔
477
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
478
            )
1✔
479
            .await
×
480
            .unwrap()
1✔
481
            .map(Result::unwrap)
1✔
482
            .collect::<Vec<MultiPointCollection>>()
1✔
483
            .await;
32✔
484

485
        assert_eq!(result.len(), 1);
1✔
486

487
        let FeatureDataRef::Int(data) = result[0].data("ndvi").unwrap() else {
1✔
488
            unreachable!();
×
489
        };
490

491
        // these values are taken from loading the tiff in QGIS
492
        assert_eq!(data.as_ref(), &[54, 55, 51, 55]);
1✔
493
    }
494

495
    #[tokio::test]
1✔
496
    #[allow(clippy::float_cmp)]
497
    async fn ndvi_time_range() {
1✔
498
        let point_source = MockFeatureCollectionSource::single(
1✔
499
            MultiPointCollection::from_data(
1✔
500
                MultiPoint::many(vec![
1✔
501
                    (-13.95, 20.05),
1✔
502
                    (-14.05, 20.05),
1✔
503
                    (-13.95, 19.95),
1✔
504
                    (-14.05, 19.95),
1✔
505
                ])
1✔
506
                .unwrap(),
1✔
507
                vec![
1✔
508
                    TimeInterval::new(
1✔
509
                        DateTime::new_utc(2014, 1, 1, 0, 0, 0),
1✔
510
                        DateTime::new_utc(2014, 3, 1, 0, 0, 0),
1✔
511
                    )
1✔
512
                    .unwrap();
1✔
513
                    4
1✔
514
                ],
1✔
515
                Default::default(),
1✔
516
                CacheHint::default(),
1✔
517
            )
1✔
518
            .unwrap(),
1✔
519
        )
1✔
520
        .boxed();
1✔
521

1✔
522
        let mut exe_ctc = MockExecutionContext::test_default();
1✔
523
        let ndvi_id = add_ndvi_dataset(&mut exe_ctc);
1✔
524

1✔
525
        let operator = RasterVectorJoin {
1✔
526
            params: RasterVectorJoinParams {
1✔
527
                names: vec!["ndvi".to_string()],
1✔
528
                feature_aggregation: FeatureAggregationMethod::First,
1✔
529
                feature_aggregation_ignore_no_data: false,
1✔
530
                temporal_aggregation: TemporalAggregationMethod::Mean,
1✔
531
                temporal_aggregation_ignore_no_data: false,
1✔
532
            },
1✔
533
            sources: SingleVectorMultipleRasterSources {
1✔
534
                vector: point_source,
1✔
535
                rasters: vec![ndvi_source(ndvi_id.clone())],
1✔
536
            },
1✔
537
        };
1✔
538

539
        let operator = operator
1✔
540
            .boxed()
1✔
541
            .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
542
            .await
×
543
            .unwrap();
1✔
544

1✔
545
        let query_processor = operator.query_processor().unwrap().multi_point().unwrap();
1✔
546

547
        let result = query_processor
1✔
548
            .query(
1✔
549
                VectorQueryRectangle {
1✔
550
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
551
                        .unwrap(),
1✔
552
                    time_interval: TimeInterval::default(),
1✔
553
                    spatial_resolution: SpatialResolution::new(0.1, 0.1).unwrap(),
1✔
554
                    attributes: ColumnSelection::all(),
1✔
555
                },
1✔
556
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
557
            )
1✔
558
            .await
×
559
            .unwrap()
1✔
560
            .map(Result::unwrap)
1✔
561
            .collect::<Vec<MultiPointCollection>>()
1✔
562
            .await;
63✔
563

564
        assert_eq!(result.len(), 1);
1✔
565

566
        let FeatureDataRef::Float(data) = result[0].data("ndvi").unwrap() else {
1✔
567
            unreachable!();
×
568
        };
569

570
        // these values are taken from loading the tiff in QGIS
571
        assert_eq!(
1✔
572
            data.as_ref(),
1✔
573
            &[
1✔
574
                (54. + 52.) / 2.,
1✔
575
                (55. + 55.) / 2.,
1✔
576
                (51. + 50.) / 2.,
1✔
577
                (55. + 53.) / 2.,
1✔
578
            ]
1✔
579
        );
1✔
580
    }
581

582
    #[tokio::test]
1✔
583
    #[allow(clippy::float_cmp)]
584
    async fn ndvi_with_default_time() {
1✔
585
        hide_gdal_errors();
1✔
586

1✔
587
        let point_source = MockFeatureCollectionSource::single(
1✔
588
            MultiPointCollection::from_data(
1✔
589
                MultiPoint::many(vec![
1✔
590
                    (-13.95, 20.05),
1✔
591
                    (-14.05, 20.05),
1✔
592
                    (-13.95, 19.95),
1✔
593
                    (-14.05, 19.95),
1✔
594
                ])
1✔
595
                .unwrap(),
1✔
596
                vec![TimeInterval::default(); 4],
1✔
597
                Default::default(),
1✔
598
                CacheHint::default(),
1✔
599
            )
1✔
600
            .unwrap(),
1✔
601
        )
1✔
602
        .boxed();
1✔
603

1✔
604
        let mut exe_ctc = MockExecutionContext::test_default();
1✔
605
        let ndvi_id = add_ndvi_dataset(&mut exe_ctc);
1✔
606

1✔
607
        let operator = RasterVectorJoin {
1✔
608
            params: RasterVectorJoinParams {
1✔
609
                names: vec!["ndvi".to_string()],
1✔
610
                feature_aggregation: FeatureAggregationMethod::First,
1✔
611
                feature_aggregation_ignore_no_data: false,
1✔
612
                temporal_aggregation: TemporalAggregationMethod::Mean,
1✔
613
                temporal_aggregation_ignore_no_data: false,
1✔
614
            },
1✔
615
            sources: SingleVectorMultipleRasterSources {
1✔
616
                vector: point_source,
1✔
617
                rasters: vec![ndvi_source(ndvi_id.clone())],
1✔
618
            },
1✔
619
        };
1✔
620

621
        let operator = operator
1✔
622
            .boxed()
1✔
623
            .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
624
            .await
×
625
            .unwrap();
1✔
626

1✔
627
        let query_processor = operator.query_processor().unwrap().multi_point().unwrap();
1✔
628

629
        let result = query_processor
1✔
630
            .query(
1✔
631
                VectorQueryRectangle {
1✔
632
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
633
                        .unwrap(),
1✔
634
                    time_interval: TimeInterval::default(),
1✔
635
                    spatial_resolution: SpatialResolution::new(0.1, 0.1).unwrap(),
1✔
636
                    attributes: ColumnSelection::all(),
1✔
637
                },
1✔
638
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
639
            )
1✔
640
            .await
×
641
            .unwrap()
1✔
642
            .map(Result::unwrap)
1✔
643
            .collect::<Vec<MultiPointCollection>>()
1✔
644
            .await;
1✔
645

646
        assert_eq!(result.len(), 1);
1✔
647

648
        let FeatureDataRef::Float(data) = result[0].data("ndvi").unwrap() else {
1✔
649
            unreachable!();
×
650
        };
651

652
        assert_eq!(data.as_ref(), &[0., 0., 0., 0.]);
1✔
653

654
        assert_eq!(data.nulls(), vec![true, true, true, true]);
1✔
655
    }
656

657
    #[tokio::test]
1✔
658
    async fn it_checks_sref() {
1✔
659
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
660
            vec![MultiPointCollection::from_data(
1✔
661
                MultiPoint::many(vec![
1✔
662
                    (-13.95, 20.05),
1✔
663
                    (-14.05, 20.05),
1✔
664
                    (-13.95, 19.95),
1✔
665
                    (-14.05, 19.95),
1✔
666
                ])
1✔
667
                .unwrap(),
1✔
668
                vec![TimeInterval::default(); 4],
1✔
669
                Default::default(),
1✔
670
                CacheHint::default(),
1✔
671
            )
1✔
672
            .unwrap()],
1✔
673
            SpatialReference::from_str("EPSG:3857").unwrap(),
1✔
674
        )
1✔
675
        .boxed();
1✔
676

1✔
677
        let mut exe_ctc = MockExecutionContext::test_default();
1✔
678
        let ndvi_id = add_ndvi_dataset(&mut exe_ctc);
1✔
679

680
        let operator = RasterVectorJoin {
1✔
681
            params: RasterVectorJoinParams {
1✔
682
                names: vec!["ndvi".to_string()],
1✔
683
                feature_aggregation: FeatureAggregationMethod::First,
1✔
684
                feature_aggregation_ignore_no_data: false,
1✔
685
                temporal_aggregation: TemporalAggregationMethod::Mean,
1✔
686
                temporal_aggregation_ignore_no_data: false,
1✔
687
            },
1✔
688
            sources: SingleVectorMultipleRasterSources {
1✔
689
                vector: point_source,
1✔
690
                rasters: vec![ndvi_source(ndvi_id.clone())],
1✔
691
            },
1✔
692
        }
1✔
693
        .boxed()
1✔
694
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
695
        .await;
×
696

697
        assert!(matches!(
1✔
698
            operator,
1✔
699
            Err(Error::InvalidSpatialReference {
700
                expected: _,
701
                found: _,
702
            })
703
        ));
704
    }
705

706
    #[tokio::test]
1✔
707
    #[allow(clippy::too_many_lines)]
708
    async fn it_includes_bands_in_result_descriptor() {
1✔
709
        let point_source = MockFeatureCollectionSource::with_collections_and_sref(
1✔
710
            vec![MultiPointCollection::from_data(
1✔
711
                MultiPoint::many(vec![
1✔
712
                    (-13.95, 20.05),
1✔
713
                    (-14.05, 20.05),
1✔
714
                    (-13.95, 19.95),
1✔
715
                    (-14.05, 19.95),
1✔
716
                ])
1✔
717
                .unwrap(),
1✔
718
                vec![TimeInterval::default(); 4],
1✔
719
                Default::default(),
1✔
720
                CacheHint::default(),
1✔
721
            )
1✔
722
            .unwrap()],
1✔
723
            SpatialReference::from_str("EPSG:4326").unwrap(),
1✔
724
        )
1✔
725
        .boxed();
1✔
726

1✔
727
        let raster_source = MockRasterSource {
1✔
728
            params: MockRasterSourceParams {
1✔
729
                data: Vec::<RasterTile2D<u8>>::new(),
1✔
730
                result_descriptor: RasterResultDescriptor {
1✔
731
                    data_type: RasterDataType::U8,
1✔
732
                    spatial_reference: SpatialReference::epsg_4326().into(),
1✔
733
                    time: None,
1✔
734
                    bbox: None,
1✔
735
                    resolution: None,
1✔
736
                    bands: RasterBandDescriptors::new(vec![
1✔
737
                        RasterBandDescriptor::new_unitless("band_0".into()),
1✔
738
                        RasterBandDescriptor::new_unitless("band_1".into()),
1✔
739
                    ])
1✔
740
                    .unwrap(),
1✔
741
                },
1✔
742
            },
1✔
743
        }
1✔
744
        .boxed();
1✔
745

1✔
746
        let raster_source2 = MockRasterSource {
1✔
747
            params: MockRasterSourceParams {
1✔
748
                data: Vec::<RasterTile2D<u8>>::new(),
1✔
749
                result_descriptor: RasterResultDescriptor {
1✔
750
                    data_type: RasterDataType::U8,
1✔
751
                    spatial_reference: SpatialReference::epsg_4326().into(),
1✔
752
                    time: None,
1✔
753
                    bbox: None,
1✔
754
                    resolution: None,
1✔
755
                    bands: RasterBandDescriptors::new(vec![
1✔
756
                        RasterBandDescriptor::new_unitless("band_0".into()),
1✔
757
                        RasterBandDescriptor::new_unitless("band_1".into()),
1✔
758
                        RasterBandDescriptor::new_unitless("band_2".into()),
1✔
759
                    ])
1✔
760
                    .unwrap(),
1✔
761
                },
1✔
762
            },
1✔
763
        }
1✔
764
        .boxed();
1✔
765

1✔
766
        let exe_ctc = MockExecutionContext::test_default();
1✔
767

768
        let join = RasterVectorJoin {
1✔
769
            params: RasterVectorJoinParams {
1✔
770
                names: vec!["s0".to_string(), "s1".to_string()],
1✔
771
                feature_aggregation: FeatureAggregationMethod::First,
1✔
772
                feature_aggregation_ignore_no_data: false,
1✔
773
                temporal_aggregation: TemporalAggregationMethod::None,
1✔
774
                temporal_aggregation_ignore_no_data: false,
1✔
775
            },
1✔
776
            sources: SingleVectorMultipleRasterSources {
1✔
777
                vector: point_source,
1✔
778
                rasters: vec![raster_source, raster_source2],
1✔
779
            },
1✔
780
        }
1✔
781
        .boxed()
1✔
782
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctc)
1✔
NEW
783
        .await
×
784
        .unwrap();
1✔
785

1✔
786
        assert_eq!(
1✔
787
            join.result_descriptor(),
1✔
788
            &VectorResultDescriptor {
1✔
789
                data_type: VectorDataType::MultiPoint,
1✔
790
                spatial_reference: SpatialReference::epsg_4326().into(),
1✔
791
                columns: [
1✔
792
                    (
1✔
793
                        "s0".to_string(),
1✔
794
                        VectorColumnInfo {
1✔
795
                            data_type: FeatureDataType::Int,
1✔
796
                            measurement: Measurement::Unitless
1✔
797
                        }
1✔
798
                    ),
1✔
799
                    (
1✔
800
                        "s0_1".to_string(),
1✔
801
                        VectorColumnInfo {
1✔
802
                            data_type: FeatureDataType::Int,
1✔
803
                            measurement: Measurement::Unitless
1✔
804
                        }
1✔
805
                    ),
1✔
806
                    (
1✔
807
                        "s1".to_string(),
1✔
808
                        VectorColumnInfo {
1✔
809
                            data_type: FeatureDataType::Int,
1✔
810
                            measurement: Measurement::Unitless
1✔
811
                        }
1✔
812
                    ),
1✔
813
                    (
1✔
814
                        "s1_1".to_string(),
1✔
815
                        VectorColumnInfo {
1✔
816
                            data_type: FeatureDataType::Int,
1✔
817
                            measurement: Measurement::Unitless
1✔
818
                        }
1✔
819
                    ),
1✔
820
                    (
1✔
821
                        "s1_2".to_string(),
1✔
822
                        VectorColumnInfo {
1✔
823
                            data_type: FeatureDataType::Int,
1✔
824
                            measurement: Measurement::Unitless
1✔
825
                        }
1✔
826
                    )
1✔
827
                ]
1✔
828
                .into_iter()
1✔
829
                .collect(),
1✔
830
                time: None,
1✔
831
                bbox: None
1✔
832
            }
1✔
833
        );
1✔
834
    }
835
}
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