• 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

94.5
/operators/src/plot/histogram.rs
1
use crate::engine::{
2
    CanonicOperatorName, ExecutionContext, InitializedPlotOperator, InitializedRasterOperator,
3
    InitializedVectorOperator, Operator, OperatorName, PlotOperator, PlotQueryProcessor,
4
    PlotResultDescriptor, QueryContext, SingleRasterOrVectorSource, TypedPlotQueryProcessor,
5
    TypedRasterQueryProcessor, TypedVectorQueryProcessor,
6
};
7
use crate::engine::{QueryProcessor, WorkflowOperatorPath};
8
use crate::error;
9
use crate::error::Error;
10
use crate::string_token;
11
use crate::util::input::RasterOrVectorOperator;
12
use crate::util::Result;
13
use async_trait::async_trait;
14
use float_cmp::approx_eq;
15
use futures::stream::BoxStream;
16
use futures::{StreamExt, TryFutureExt};
17
use geoengine_datatypes::plots::{Plot, PlotData};
18
use geoengine_datatypes::primitives::{
19
    AxisAlignedRectangle, BandSelection, BoundingBox2D, DataRef, FeatureDataRef, FeatureDataType,
20
    Geometry, Measurement, PlotQueryRectangle, RasterQueryRectangle,
21
};
22
use geoengine_datatypes::raster::{Pixel, RasterTile2D};
23
use geoengine_datatypes::{
24
    collections::{FeatureCollection, FeatureCollectionInfos},
25
    raster::GridSize,
26
};
27
use serde::{Deserialize, Serialize};
28
use snafu::{ensure, OptionExt};
29
use std::convert::TryFrom;
30

31
pub const HISTOGRAM_OPERATOR_NAME: &str = "Histogram";
32

33
/// A histogram plot about either a raster or a vector input.
34
///
35
/// For vector inputs, it calculates the histogram on one of its attributes.
36
///
37
pub type Histogram = Operator<HistogramParams, SingleRasterOrVectorSource>;
38

39
impl OperatorName for Histogram {
40
    const TYPE_NAME: &'static str = "Histogram";
41
}
42

43
/// The parameter spec for `Histogram`
44
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29✔
45
#[serde(rename_all = "camelCase")]
46
pub struct HistogramParams {
47
    /// Name of the (numeric) attribute to compute the histogram on. Ignored for operation on rasters.
48
    pub column_name: Option<String>,
49
    /// The bounds (min/max) of the histogram.
50
    pub bounds: HistogramBounds,
51
    /// Specify the number of buckets or how it should be derived.
52
    pub buckets: HistogramBuckets,
53
    /// Whether to create an interactive output (`false` by default)
54
    #[serde(default)]
55
    pub interactive: bool,
56
}
57

58
/// Options for how to derive the histogram's number of buckets.
59
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20✔
60
#[serde(rename_all = "camelCase", tag = "type")]
61
pub enum HistogramBuckets {
62
    #[serde(rename_all = "camelCase")]
63
    Number { value: u8 },
64
    #[serde(rename_all = "camelCase")]
65
    SquareRootChoiceRule {
66
        #[serde(default = "default_max_number_of_buckets")]
67
        max_number_of_buckets: u8,
68
    },
69
}
70

71
fn default_max_number_of_buckets() -> u8 {
×
72
    100
×
73
}
×
74

75
string_token!(Data, "data");
76

77
/// Let the bounds either be computed or given.
78
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16✔
79
#[serde(untagged)]
80
pub enum HistogramBounds {
81
    Data(Data),
82
    Values { min: f64, max: f64 },
83
    // TODO: use bounds in measurement if they are available
84
}
85

86
#[typetag::serde]
1✔
87
#[async_trait]
88
impl PlotOperator for Histogram {
89
    async fn _initialize(
11✔
90
        self: Box<Self>,
11✔
91
        path: WorkflowOperatorPath,
11✔
92
        context: &dyn ExecutionContext,
11✔
93
    ) -> Result<Box<dyn InitializedPlotOperator>> {
11✔
94
        let name = CanonicOperatorName::from(&self);
11✔
95

11✔
96
        Ok(match self.sources.source {
11✔
97
            RasterOrVectorOperator::Raster(raster_source) => {
6✔
98
                ensure!(
6✔
99
                    self.params.column_name.is_none(),
6✔
100
                    error::InvalidOperatorSpec {
1✔
101
                        reason: "Histogram on raster input must not have `columnName` field set"
1✔
102
                            .to_string(),
1✔
103
                    }
1✔
104
                );
105

106
                let raster_source = raster_source
5✔
107
                    .initialize(path.clone_and_append(0), context)
5✔
108
                    .await?;
×
109

110
                let in_desc = raster_source.result_descriptor();
5✔
111

5✔
112
                // TODO: implement multi-band functionality and remove this check
5✔
113
                ensure!(
5✔
114
                    in_desc.bands.len() == 1,
5✔
NEW
115
                    crate::error::OperatorDoesNotSupportMultiBandsSourcesYet {
×
NEW
116
                        operator: Histogram::TYPE_NAME
×
NEW
117
                    }
×
118
                );
119

120
                InitializedHistogram::new(
5✔
121
                    name,
5✔
122
                    PlotResultDescriptor {
5✔
123
                        spatial_reference: in_desc.spatial_reference,
5✔
124
                        time: in_desc.time,
5✔
125
                        // converting `SpatialPartition2D` to `BoundingBox2D` is ok here, because is makes the covered area only larger
5✔
126
                        bbox: in_desc
5✔
127
                            .bbox
5✔
128
                            .and_then(|p| BoundingBox2D::new(p.lower_left(), p.upper_right()).ok()),
5✔
129
                    },
5✔
130
                    self.params,
5✔
131
                    raster_source,
5✔
132
                )
5✔
133
                .boxed()
5✔
134
            }
135
            RasterOrVectorOperator::Vector(vector_source) => {
5✔
136
                let column_name =
5✔
137
                    self.params
5✔
138
                        .column_name
5✔
139
                        .as_ref()
5✔
140
                        .context(error::InvalidOperatorSpec {
5✔
141
                            reason: "Histogram on vector input is missing `columnName` field"
5✔
142
                                .to_string(),
5✔
143
                        })?;
5✔
144

145
                let vector_source = vector_source
5✔
146
                    .initialize(path.clone_and_append(0), context)
5✔
147
                    .await?;
×
148

149
                match vector_source
5✔
150
                    .result_descriptor()
5✔
151
                    .column_data_type(column_name)
5✔
152
                {
153
                    None => {
154
                        return Err(Error::ColumnDoesNotExist {
×
155
                            column: column_name.to_string(),
×
156
                        });
×
157
                    }
158
                    Some(FeatureDataType::Category | FeatureDataType::Text) => {
159
                        // TODO: incorporate category data
160
                        return Err(Error::InvalidOperatorSpec {
1✔
161
                            reason: format!("column `{column_name}` must be numerical"),
1✔
162
                        });
1✔
163
                    }
164
                    Some(
165
                        FeatureDataType::Int
166
                        | FeatureDataType::Float
167
                        | FeatureDataType::Bool
168
                        | FeatureDataType::DateTime,
169
                    ) => {
4✔
170
                        // okay
4✔
171
                    }
4✔
172
                }
4✔
173

4✔
174
                let in_desc = vector_source.result_descriptor().clone();
4✔
175

4✔
176
                InitializedHistogram::new(name, in_desc.into(), self.params, vector_source).boxed()
4✔
177
            }
178
        })
179
    }
22✔
180

181
    span_fn!(Histogram);
×
182
}
183

184
/// The initialization of `Histogram`
185
pub struct InitializedHistogram<Op> {
186
    name: CanonicOperatorName,
187
    result_descriptor: PlotResultDescriptor,
188
    metadata: HistogramMetadataOptions,
189
    source: Op,
190
    interactive: bool,
191
    column_name: Option<String>,
192
}
193

194
impl<Op> InitializedHistogram<Op> {
195
    pub fn new(
9✔
196
        name: CanonicOperatorName,
9✔
197
        result_descriptor: PlotResultDescriptor,
9✔
198
        params: HistogramParams,
9✔
199
        source: Op,
9✔
200
    ) -> Self {
9✔
201
        let (min, max) = if let HistogramBounds::Values { min, max } = params.bounds {
9✔
202
            (Some(min), Some(max))
3✔
203
        } else {
204
            (None, None)
6✔
205
        };
206

207
        let (number_of_buckets, max_number_of_buckets) = match params.buckets {
9✔
208
            HistogramBuckets::Number {
209
                value: number_of_buckets,
3✔
210
            } => (Some(number_of_buckets as usize), None),
3✔
211
            HistogramBuckets::SquareRootChoiceRule {
212
                max_number_of_buckets,
6✔
213
            } => (None, Some(max_number_of_buckets as usize)),
6✔
214
        };
215

216
        Self {
9✔
217
            name,
9✔
218
            result_descriptor,
9✔
219
            metadata: HistogramMetadataOptions {
9✔
220
                number_of_buckets,
9✔
221
                max_number_of_buckets,
9✔
222
                min,
9✔
223
                max,
9✔
224
            },
9✔
225
            source,
9✔
226
            interactive: params.interactive,
9✔
227
            column_name: params.column_name,
9✔
228
        }
9✔
229
    }
9✔
230
}
231

232
impl InitializedPlotOperator for InitializedHistogram<Box<dyn InitializedRasterOperator>> {
233
    fn query_processor(&self) -> Result<TypedPlotQueryProcessor> {
5✔
234
        let processor = HistogramRasterQueryProcessor {
5✔
235
            input: self.source.query_processor()?,
5✔
236
            measurement: self.source.result_descriptor().bands[0].measurement.clone(), // TODO: adjust for multibands
5✔
237
            metadata: self.metadata,
5✔
238
            interactive: self.interactive,
5✔
239
        };
5✔
240

5✔
241
        Ok(TypedPlotQueryProcessor::JsonVega(processor.boxed()))
5✔
242
    }
5✔
243

244
    fn result_descriptor(&self) -> &PlotResultDescriptor {
1✔
245
        &self.result_descriptor
1✔
246
    }
1✔
247

248
    fn canonic_name(&self) -> CanonicOperatorName {
×
249
        self.name.clone()
×
250
    }
×
251
}
252

253
impl InitializedPlotOperator for InitializedHistogram<Box<dyn InitializedVectorOperator>> {
254
    fn query_processor(&self) -> Result<TypedPlotQueryProcessor> {
4✔
255
        let processor = HistogramVectorQueryProcessor {
4✔
256
            input: self.source.query_processor()?,
4✔
257
            column_name: self.column_name.clone().unwrap_or_default(),
4✔
258
            measurement: self
4✔
259
                .source
4✔
260
                .result_descriptor()
4✔
261
                .column_measurement(self.column_name.as_deref().unwrap_or_default())
4✔
262
                .cloned()
4✔
263
                .into(),
4✔
264
            metadata: self.metadata,
4✔
265
            interactive: self.interactive,
4✔
266
        };
4✔
267

4✔
268
        Ok(TypedPlotQueryProcessor::JsonVega(processor.boxed()))
4✔
269
    }
4✔
270

271
    fn result_descriptor(&self) -> &PlotResultDescriptor {
×
272
        &self.result_descriptor
×
273
    }
×
274

275
    fn canonic_name(&self) -> CanonicOperatorName {
×
276
        self.name.clone()
×
277
    }
×
278
}
279

280
/// A query processor that calculates the Histogram about its raster inputs.
281
pub struct HistogramRasterQueryProcessor {
282
    input: TypedRasterQueryProcessor,
283
    measurement: Measurement,
284
    metadata: HistogramMetadataOptions,
285
    interactive: bool,
286
}
287

288
/// A query processor that calculates the Histogram about its vector inputs.
289
pub struct HistogramVectorQueryProcessor {
290
    input: TypedVectorQueryProcessor,
291
    column_name: String,
292
    measurement: Measurement,
293
    metadata: HistogramMetadataOptions,
294
    interactive: bool,
295
}
296

297
#[async_trait]
298
impl PlotQueryProcessor for HistogramRasterQueryProcessor {
299
    type OutputFormat = PlotData;
300

301
    fn plot_type(&self) -> &'static str {
1✔
302
        HISTOGRAM_OPERATOR_NAME
1✔
303
    }
1✔
304

305
    async fn plot_query<'p>(
5✔
306
        &'p self,
5✔
307
        query: PlotQueryRectangle,
5✔
308
        ctx: &'p dyn QueryContext,
5✔
309
    ) -> Result<Self::OutputFormat> {
5✔
310
        self.preprocess(query.clone(), ctx)
5✔
311
            .and_then(move |mut histogram_metadata| async move {
5✔
312
                histogram_metadata.sanitize();
5✔
313
                if histogram_metadata.has_invalid_parameters() {
5✔
314
                    // early return of empty histogram
315
                    return self.empty_histogram();
1✔
316
                }
4✔
317

4✔
318
                self.process(histogram_metadata, query, ctx).await
4✔
319
            })
5✔
320
            .await
×
321
    }
10✔
322
}
323

324
#[async_trait]
325
impl PlotQueryProcessor for HistogramVectorQueryProcessor {
326
    type OutputFormat = PlotData;
327

328
    fn plot_type(&self) -> &'static str {
×
329
        HISTOGRAM_OPERATOR_NAME
×
330
    }
×
331

332
    async fn plot_query<'p>(
4✔
333
        &'p self,
4✔
334
        query: PlotQueryRectangle,
4✔
335
        ctx: &'p dyn QueryContext,
4✔
336
    ) -> Result<Self::OutputFormat> {
4✔
337
        self.preprocess(query.clone(), ctx)
4✔
338
            .and_then(move |mut histogram_metadata| async move {
4✔
339
                histogram_metadata.sanitize();
4✔
340
                if histogram_metadata.has_invalid_parameters() {
4✔
341
                    // early return of empty histogram
342
                    return self.empty_histogram();
1✔
343
                }
3✔
344

3✔
345
                self.process(histogram_metadata, query, ctx).await
3✔
346
            })
4✔
347
            .await
×
348
    }
8✔
349
}
350

351
impl HistogramRasterQueryProcessor {
352
    async fn preprocess<'p>(
5✔
353
        &'p self,
5✔
354
        query: PlotQueryRectangle,
5✔
355
        ctx: &'p dyn QueryContext,
5✔
356
    ) -> Result<HistogramMetadata> {
5✔
357
        async fn process_metadata<T: Pixel>(
3✔
358
            mut input: BoxStream<'_, Result<RasterTile2D<T>>>,
3✔
359
            metadata: HistogramMetadataOptions,
3✔
360
        ) -> Result<HistogramMetadata> {
3✔
361
            let mut computed_metadata = HistogramMetadataInProgress::default();
3✔
362

363
            while let Some(tile) = input.next().await {
15✔
364
                match tile?.grid_array {
12✔
365
                    geoengine_datatypes::raster::GridOrEmpty::Grid(g) => {
2✔
366
                        computed_metadata.add_raster_batch(g.masked_element_deref_iterator());
2✔
367
                    }
2✔
368
                    geoengine_datatypes::raster::GridOrEmpty::Empty(_) => {} // TODO: find out if we really do nothing for empty tiles?
10✔
369
                }
370
            }
371

372
            Ok(metadata.merge_with(computed_metadata.into()))
3✔
373
        }
3✔
374

375
        if let Ok(metadata) = HistogramMetadata::try_from(self.metadata) {
5✔
376
            return Ok(metadata);
2✔
377
        }
3✔
378

3✔
379
        // TODO: compute only number of buckets if possible
3✔
380

3✔
381
        call_on_generic_raster_processor!(&self.input, processor => {
3✔
382
            process_metadata(processor.query(RasterQueryRectangle::from_qrect_and_bands(&query, BandSelection::first()), ctx).await?, self.metadata).await
3✔
383
        })
384
    }
5✔
385

386
    async fn process<'p>(
4✔
387
        &'p self,
4✔
388
        metadata: HistogramMetadata,
4✔
389
        query: PlotQueryRectangle,
4✔
390
        ctx: &'p dyn QueryContext,
4✔
391
    ) -> Result<<HistogramRasterQueryProcessor as PlotQueryProcessor>::OutputFormat> {
4✔
392
        let mut histogram = geoengine_datatypes::plots::Histogram::builder(
4✔
393
            metadata.number_of_buckets,
4✔
394
            metadata.min,
4✔
395
            metadata.max,
4✔
396
            self.measurement.clone(),
4✔
397
        )
4✔
398
        .build()
4✔
399
        .map_err(Error::from)?;
4✔
400

401
        call_on_generic_raster_processor!(&self.input, processor => {
4✔
402
            let mut query = processor.query(RasterQueryRectangle::from_qrect_and_bands(&query, BandSelection::first()), ctx).await?;
4✔
403

404
            while let Some(tile) = query.next().await {
20✔
405

406

407
                match tile?.grid_array {
16✔
408
                    geoengine_datatypes::raster::GridOrEmpty::Grid(g) => histogram.add_raster_data(g.masked_element_deref_iterator()),
4✔
409
                    geoengine_datatypes::raster::GridOrEmpty::Empty(n) => histogram.add_nodata_batch(n.number_of_elements() as u64) // TODO: why u64?
12✔
410
                }
411
            }
412
        });
413

414
        let chart = histogram.to_vega_embeddable(self.interactive)?;
4✔
415

416
        Ok(chart)
4✔
417
    }
4✔
418

419
    fn empty_histogram(
1✔
420
        &self,
1✔
421
    ) -> Result<<HistogramRasterQueryProcessor as PlotQueryProcessor>::OutputFormat> {
1✔
422
        let histogram =
1✔
423
            geoengine_datatypes::plots::Histogram::builder(1, 0., 0., self.measurement.clone())
1✔
424
                .build()
1✔
425
                .map_err(Error::from)?;
1✔
426

427
        let chart = histogram.to_vega_embeddable(self.interactive)?;
1✔
428

429
        Ok(chart)
1✔
430
    }
1✔
431
}
432

433
impl HistogramVectorQueryProcessor {
434
    async fn preprocess<'p>(
4✔
435
        &'p self,
4✔
436
        query: PlotQueryRectangle,
4✔
437
        ctx: &'p dyn QueryContext,
4✔
438
    ) -> Result<HistogramMetadata> {
4✔
439
        async fn process_metadata<'m, G>(
3✔
440
            mut input: BoxStream<'m, Result<FeatureCollection<G>>>,
3✔
441
            column_name: &'m str,
3✔
442
            metadata: HistogramMetadataOptions,
3✔
443
        ) -> Result<HistogramMetadata>
3✔
444
        where
3✔
445
            G: Geometry + 'static,
3✔
446
            FeatureCollection<G>: FeatureCollectionInfos,
3✔
447
        {
3✔
448
            let mut computed_metadata = HistogramMetadataInProgress::default();
3✔
449

450
            while let Some(collection) = input.next().await {
6✔
451
                let collection = collection?;
3✔
452

453
                let feature_data = collection.data(column_name).expect("check in param");
3✔
454
                computed_metadata.add_vector_batch(feature_data);
3✔
455
            }
456

457
            Ok(metadata.merge_with(computed_metadata.into()))
3✔
458
        }
3✔
459

460
        if let Ok(metadata) = HistogramMetadata::try_from(self.metadata) {
4✔
461
            return Ok(metadata);
1✔
462
        }
3✔
463

3✔
464
        // TODO: compute only number of buckets if possible
3✔
465

3✔
466
        call_on_generic_vector_processor!(&self.input, processor => {
3✔
467
            process_metadata(processor.query(query.into(), ctx).await?, &self.column_name, self.metadata).await
3✔
468
        })
469
    }
4✔
470

471
    async fn process<'p>(
3✔
472
        &'p self,
3✔
473
        metadata: HistogramMetadata,
3✔
474
        query: PlotQueryRectangle,
3✔
475
        ctx: &'p dyn QueryContext,
3✔
476
    ) -> Result<<HistogramRasterQueryProcessor as PlotQueryProcessor>::OutputFormat> {
3✔
477
        let mut histogram = geoengine_datatypes::plots::Histogram::builder(
3✔
478
            metadata.number_of_buckets,
3✔
479
            metadata.min,
3✔
480
            metadata.max,
3✔
481
            self.measurement.clone(),
3✔
482
        )
3✔
483
        .build()
3✔
484
        .map_err(Error::from)?;
3✔
485

486
        call_on_generic_vector_processor!(&self.input, processor => {
3✔
487
            let mut query = processor.query(query.into(), ctx).await?;
3✔
488

489
            while let Some(collection) = query.next().await {
7✔
490
                let collection = collection?;
4✔
491

492
                let feature_data = collection.data(&self.column_name).expect("checked in param");
4✔
493

494
                histogram.add_feature_data(feature_data)?;
4✔
495
            }
496
        });
497

498
        let chart = histogram.to_vega_embeddable(self.interactive)?;
3✔
499

500
        Ok(chart)
3✔
501
    }
3✔
502

503
    fn empty_histogram(
1✔
504
        &self,
1✔
505
    ) -> Result<<HistogramRasterQueryProcessor as PlotQueryProcessor>::OutputFormat> {
1✔
506
        let histogram =
1✔
507
            geoengine_datatypes::plots::Histogram::builder(1, 0., 0., self.measurement.clone())
1✔
508
                .build()
1✔
509
                .map_err(Error::from)?;
1✔
510

511
        let chart = histogram.to_vega_embeddable(self.interactive)?;
1✔
512

513
        Ok(chart)
1✔
514
    }
1✔
515
}
516

517
#[derive(Debug, Copy, Clone, PartialEq)]
×
518
struct HistogramMetadata {
519
    pub number_of_buckets: usize,
520
    pub min: f64,
521
    pub max: f64,
522
}
523

524
impl HistogramMetadata {
525
    /// Fix invalid configurations if they are fixeable
526
    fn sanitize(&mut self) {
9✔
527
        // prevent the rare case that min=max and you have more than one bucket
9✔
528
        if approx_eq!(f64, self.min, self.max) && self.number_of_buckets > 1 {
9✔
529
            self.number_of_buckets = 1;
1✔
530
        }
8✔
531
    }
9✔
532

533
    fn has_invalid_parameters(&self) -> bool {
9✔
534
        self.number_of_buckets == 0 || self.min > self.max
9✔
535
    }
9✔
536
}
537

538
#[derive(Debug, Copy, Clone, PartialEq)]
×
539
struct HistogramMetadataOptions {
540
    pub number_of_buckets: Option<usize>,
541
    pub max_number_of_buckets: Option<usize>,
542
    pub min: Option<f64>,
543
    pub max: Option<f64>,
544
}
545

546
impl TryFrom<HistogramMetadataOptions> for HistogramMetadata {
547
    type Error = ();
548

549
    fn try_from(options: HistogramMetadataOptions) -> Result<Self, Self::Error> {
550
        match (options.number_of_buckets, options.min, options.max) {
9✔
551
            (Some(number_of_buckets), Some(min), Some(max)) => Ok(Self {
3✔
552
                number_of_buckets,
3✔
553
                min,
3✔
554
                max,
3✔
555
            }),
3✔
556
            _ => Err(()),
6✔
557
        }
558
    }
9✔
559
}
560

561
impl HistogramMetadataOptions {
562
    fn merge_with(self, metadata: HistogramMetadata) -> HistogramMetadata {
6✔
563
        let number_of_buckets = if let Some(number_of_buckets) = self.number_of_buckets {
6✔
564
            number_of_buckets
×
565
        } else if let Some(max_number_of_buckets) = self.max_number_of_buckets {
6✔
566
            metadata.number_of_buckets.min(max_number_of_buckets)
6✔
567
        } else {
568
            metadata.number_of_buckets
×
569
        };
570

571
        HistogramMetadata {
6✔
572
            number_of_buckets,
6✔
573
            min: self.min.unwrap_or(metadata.min),
6✔
574
            max: self.max.unwrap_or(metadata.max),
6✔
575
        }
6✔
576
    }
6✔
577
}
578

579
#[derive(Debug, Copy, Clone, PartialEq)]
×
580
struct HistogramMetadataInProgress {
581
    pub n: usize,
582
    pub min: f64,
583
    pub max: f64,
584
}
585

586
impl Default for HistogramMetadataInProgress {
587
    fn default() -> Self {
6✔
588
        Self {
6✔
589
            n: 0,
6✔
590
            min: f64::MAX,
6✔
591
            max: f64::MIN,
6✔
592
        }
6✔
593
    }
6✔
594
}
595

596
impl HistogramMetadataInProgress {
597
    #[inline]
598
    fn add_raster_batch<T: Pixel, I: Iterator<Item = Option<T>>>(&mut self, values: I) {
2✔
599
        values.for_each(|pixel_option| {
2✔
600
            if let Some(p) = pixel_option {
12✔
601
                self.n += 1;
12✔
602
                self.update_minmax(p.as_());
12✔
603
            }
12✔
604
        });
12✔
605
    }
2✔
606

607
    #[inline]
608
    fn add_vector_batch(&mut self, values: FeatureDataRef) {
3✔
609
        fn add_data_ref<'d, D, T>(metadata: &mut HistogramMetadataInProgress, data_ref: &'d D)
3✔
610
        where
3✔
611
            D: DataRef<'d, T>,
3✔
612
            T: 'static,
3✔
613
        {
3✔
614
            for v in data_ref.float_options_iter().flatten() {
5✔
615
                metadata.n += 1;
5✔
616
                metadata.update_minmax(v);
5✔
617
            }
5✔
618
        }
3✔
619

3✔
620
        match values {
3✔
621
            FeatureDataRef::Int(values) => {
×
622
                add_data_ref(self, &values);
×
623
            }
×
624
            FeatureDataRef::Float(values) => {
3✔
625
                add_data_ref(self, &values);
3✔
626
            }
3✔
627
            FeatureDataRef::Bool(values) => {
×
628
                add_data_ref(self, &values);
×
629
            }
×
630
            FeatureDataRef::DateTime(values) => {
×
631
                add_data_ref(self, &values);
×
632
            }
×
633
            FeatureDataRef::Category(_) | FeatureDataRef::Text(_) => {
×
634
                // do nothing since we don't support them
×
635
                // TODO: fill with live once we support category and text types
×
636
            }
×
637
        }
638
    }
3✔
639

640
    #[inline]
641
    fn update_minmax(&mut self, value: f64) {
17✔
642
        self.min = f64::min(self.min, value);
17✔
643
        self.max = f64::max(self.max, value);
17✔
644
    }
17✔
645
}
646

647
impl From<HistogramMetadataInProgress> for HistogramMetadata {
648
    fn from(metadata: HistogramMetadataInProgress) -> Self {
6✔
649
        Self {
6✔
650
            number_of_buckets: f64::sqrt(metadata.n as f64) as usize,
6✔
651
            min: metadata.min,
6✔
652
            max: metadata.max,
6✔
653
        }
6✔
654
    }
6✔
655
}
656

657
#[cfg(test)]
658
mod tests {
659
    use super::*;
660

661
    use crate::engine::{
662
        ChunkByteSize, MockExecutionContext, MockQueryContext, RasterBandDescriptors,
663
        RasterOperator, RasterResultDescriptor, StaticMetaData, VectorColumnInfo, VectorOperator,
664
        VectorResultDescriptor,
665
    };
666
    use crate::mock::{MockFeatureCollectionSource, MockRasterSource, MockRasterSourceParams};
667
    use crate::source::{
668
        OgrSourceColumnSpec, OgrSourceDataset, OgrSourceDatasetTimeType, OgrSourceErrorSpec,
669
    };
670
    use crate::test_data;
671
    use geoengine_datatypes::dataset::{DataId, DatasetId, NamedData};
672
    use geoengine_datatypes::primitives::{
673
        BoundingBox2D, DateTime, FeatureData, NoGeometry, PlotSeriesSelection, SpatialResolution,
674
        TimeInterval, VectorQueryRectangle,
675
    };
676
    use geoengine_datatypes::primitives::{CacheHint, CacheTtlSeconds};
677
    use geoengine_datatypes::raster::{
678
        EmptyGrid2D, Grid2D, RasterDataType, RasterTile2D, TileInformation, TilingSpecification,
679
    };
680
    use geoengine_datatypes::spatial_reference::SpatialReference;
681
    use geoengine_datatypes::util::test::TestDefault;
682
    use geoengine_datatypes::util::Identifier;
683
    use geoengine_datatypes::{
684
        collections::{DataCollection, VectorDataType},
685
        primitives::MultiPoint,
686
    };
687
    use serde_json::json;
688

689
    #[test]
1✔
690
    fn serialization() {
1✔
691
        let histogram = Histogram {
1✔
692
            params: HistogramParams {
1✔
693
                column_name: Some("foobar".to_string()),
1✔
694
                bounds: HistogramBounds::Values {
1✔
695
                    min: 5.0,
1✔
696
                    max: 10.0,
1✔
697
                },
1✔
698
                buckets: HistogramBuckets::Number { value: 15 },
1✔
699
                interactive: false,
1✔
700
            },
1✔
701
            sources: MockFeatureCollectionSource::<MultiPoint>::multiple(vec![])
1✔
702
                .boxed()
1✔
703
                .into(),
1✔
704
        };
1✔
705

1✔
706
        let serialized = json!({
1✔
707
            "type": "Histogram",
1✔
708
            "params": {
1✔
709
                "columnName": "foobar",
1✔
710
                "bounds": {
1✔
711
                    "min": 5.0,
1✔
712
                    "max": 10.0,
1✔
713
                },
1✔
714
                "buckets": {
1✔
715
                    "type": "number",
1✔
716
                    "value": 15,
1✔
717
                },
1✔
718
                "interactivity": false,
1✔
719
            },
1✔
720
            "sources": {
1✔
721
                "source": {
1✔
722
                    "type": "MockFeatureCollectionSourceMultiPoint",
1✔
723
                    "params": {
1✔
724
                        "collections": [],
1✔
725
                        "spatialReference": "EPSG:4326",
1✔
726
                        "measurements": {},
1✔
727
                    }
1✔
728
                }
1✔
729
            }
1✔
730
        })
1✔
731
        .to_string();
1✔
732

1✔
733
        let deserialized: Histogram = serde_json::from_str(&serialized).unwrap();
1✔
734

1✔
735
        assert_eq!(deserialized.params, histogram.params);
1✔
736
    }
1✔
737

738
    #[test]
1✔
739
    fn serialization_alt() {
1✔
740
        let histogram = Histogram {
1✔
741
            params: HistogramParams {
1✔
742
                column_name: None,
1✔
743
                bounds: HistogramBounds::Data(Default::default()),
1✔
744
                buckets: HistogramBuckets::SquareRootChoiceRule {
1✔
745
                    max_number_of_buckets: 100,
1✔
746
                },
1✔
747
                interactive: false,
1✔
748
            },
1✔
749
            sources: MockFeatureCollectionSource::<MultiPoint>::multiple(vec![])
1✔
750
                .boxed()
1✔
751
                .into(),
1✔
752
        };
1✔
753

1✔
754
        let serialized = json!({
1✔
755
            "type": "Histogram",
1✔
756
            "params": {
1✔
757
                "bounds": "data",
1✔
758
                "buckets": {
1✔
759
                    "type": "squareRootChoiceRule",
1✔
760
                    "maxNumberOfBuckets": 100,
1✔
761
                },
1✔
762
            },
1✔
763
            "sources": {
1✔
764
                "source": {
1✔
765
                    "type": "MockFeatureCollectionSourceMultiPoint",
1✔
766
                    "params": {
1✔
767
                        "collections": [],
1✔
768
                        "spatialReference": "EPSG:4326",
1✔
769
                        "measurements": {},
1✔
770
                    }
1✔
771
                }
1✔
772
            }
1✔
773
        })
1✔
774
        .to_string();
1✔
775

1✔
776
        let deserialized: Histogram = serde_json::from_str(&serialized).unwrap();
1✔
777

1✔
778
        assert_eq!(deserialized.params, histogram.params);
1✔
779
    }
1✔
780

781
    #[tokio::test]
1✔
782
    async fn column_name_for_raster_source() {
1✔
783
        let histogram = Histogram {
1✔
784
            params: HistogramParams {
1✔
785
                column_name: Some("foo".to_string()),
1✔
786
                bounds: HistogramBounds::Values { min: 0.0, max: 8.0 },
1✔
787
                buckets: HistogramBuckets::Number { value: 3 },
1✔
788
                interactive: false,
1✔
789
            },
1✔
790
            sources: mock_raster_source().into(),
1✔
791
        };
1✔
792

1✔
793
        let execution_context = MockExecutionContext::test_default();
1✔
794

795
        assert!(histogram
1✔
796
            .boxed()
1✔
797
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
798
            .await
×
799
            .is_err());
1✔
800
    }
801

802
    fn mock_raster_source() -> Box<dyn RasterOperator> {
3✔
803
        MockRasterSource {
3✔
804
            params: MockRasterSourceParams {
3✔
805
                data: vec![RasterTile2D::new_with_tile_info(
3✔
806
                    TimeInterval::default(),
3✔
807
                    TileInformation {
3✔
808
                        global_geo_transform: TestDefault::test_default(),
3✔
809
                        global_tile_position: [0, 0].into(),
3✔
810
                        tile_size_in_pixels: [3, 2].into(),
3✔
811
                    },
3✔
812
                    0,
3✔
813
                    Grid2D::new([3, 2].into(), vec![1, 2, 3, 4, 5, 6])
3✔
814
                        .unwrap()
3✔
815
                        .into(),
3✔
816
                    CacheHint::default(),
3✔
817
                )],
3✔
818
                result_descriptor: RasterResultDescriptor {
3✔
819
                    data_type: RasterDataType::U8,
3✔
820
                    spatial_reference: SpatialReference::epsg_4326().into(),
3✔
821
                    time: None,
3✔
822
                    bbox: None,
3✔
823
                    resolution: None,
3✔
824
                    bands: RasterBandDescriptors::new_single_band(),
3✔
825
                },
3✔
826
            },
3✔
827
        }
3✔
828
        .boxed()
3✔
829
    }
3✔
830

831
    #[tokio::test]
1✔
832
    async fn simple_raster() {
1✔
833
        let tile_size_in_pixels = [3, 2].into();
1✔
834
        let tiling_specification = TilingSpecification {
1✔
835
            origin_coordinate: [0.0, 0.0].into(),
1✔
836
            tile_size_in_pixels,
1✔
837
        };
1✔
838
        let execution_context = MockExecutionContext::new_with_tiling_spec(tiling_specification);
1✔
839

1✔
840
        let histogram = Histogram {
1✔
841
            params: HistogramParams {
1✔
842
                column_name: None,
1✔
843
                bounds: HistogramBounds::Values { min: 0.0, max: 8.0 },
1✔
844
                buckets: HistogramBuckets::Number { value: 3 },
1✔
845
                interactive: false,
1✔
846
            },
1✔
847
            sources: mock_raster_source().into(),
1✔
848
        };
1✔
849

850
        let query_processor = histogram
1✔
851
            .boxed()
1✔
852
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
853
            .await
×
854
            .unwrap()
1✔
855
            .query_processor()
1✔
856
            .unwrap()
1✔
857
            .json_vega()
1✔
858
            .unwrap();
1✔
859

860
        let result = query_processor
1✔
861
            .plot_query(
1✔
862
                PlotQueryRectangle {
1✔
863
                    spatial_bounds: BoundingBox2D::new((0., -3.).into(), (2., 0.).into()).unwrap(),
1✔
864
                    time_interval: TimeInterval::default(),
1✔
865
                    spatial_resolution: SpatialResolution::one(),
1✔
866
                    attributes: PlotSeriesSelection::all(),
1✔
867
                },
1✔
868
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
869
            )
1✔
870
            .await
×
871
            .unwrap();
1✔
872

1✔
873
        assert_eq!(
1✔
874
            result,
1✔
875
            geoengine_datatypes::plots::Histogram::builder(3, 0., 8., Measurement::Unitless)
1✔
876
                .counts(vec![2, 3, 1])
1✔
877
                .build()
1✔
878
                .unwrap()
1✔
879
                .to_vega_embeddable(false)
1✔
880
                .unwrap()
1✔
881
        );
1✔
882
    }
883

884
    #[tokio::test]
1✔
885
    async fn simple_raster_without_spec() {
1✔
886
        let tile_size_in_pixels = [3, 2].into();
1✔
887
        let tiling_specification = TilingSpecification {
1✔
888
            origin_coordinate: [0.0, 0.0].into(),
1✔
889
            tile_size_in_pixels,
1✔
890
        };
1✔
891
        let execution_context = MockExecutionContext::new_with_tiling_spec(tiling_specification);
1✔
892

1✔
893
        let histogram = Histogram {
1✔
894
            params: HistogramParams {
1✔
895
                column_name: None,
1✔
896
                bounds: HistogramBounds::Data(Default::default()),
1✔
897
                buckets: HistogramBuckets::SquareRootChoiceRule {
1✔
898
                    max_number_of_buckets: 100,
1✔
899
                },
1✔
900
                interactive: false,
1✔
901
            },
1✔
902
            sources: mock_raster_source().into(),
1✔
903
        };
1✔
904

905
        let query_processor = histogram
1✔
906
            .boxed()
1✔
907
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
908
            .await
×
909
            .unwrap()
1✔
910
            .query_processor()
1✔
911
            .unwrap()
1✔
912
            .json_vega()
1✔
913
            .unwrap();
1✔
914

915
        let result = query_processor
1✔
916
            .plot_query(
1✔
917
                PlotQueryRectangle {
1✔
918
                    spatial_bounds: BoundingBox2D::new((0., -3.).into(), (2., 0.).into()).unwrap(),
1✔
919
                    time_interval: TimeInterval::default(),
1✔
920
                    spatial_resolution: SpatialResolution::one(),
1✔
921
                    attributes: PlotSeriesSelection::all(),
1✔
922
                },
1✔
923
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
924
            )
1✔
925
            .await
×
926
            .unwrap();
1✔
927

1✔
928
        assert_eq!(
1✔
929
            result,
1✔
930
            geoengine_datatypes::plots::Histogram::builder(2, 1., 6., Measurement::Unitless)
1✔
931
                .counts(vec![3, 3])
1✔
932
                .build()
1✔
933
                .unwrap()
1✔
934
                .to_vega_embeddable(false)
1✔
935
                .unwrap()
1✔
936
        );
1✔
937
    }
938

939
    #[tokio::test]
1✔
940
    async fn vector_data() {
1✔
941
        let vector_source = MockFeatureCollectionSource::multiple(vec![
1✔
942
            DataCollection::from_slices(
1✔
943
                &[] as &[NoGeometry],
1✔
944
                &[TimeInterval::default(); 8],
1✔
945
                &[("foo", FeatureData::Int(vec![1, 1, 2, 2, 3, 3, 4, 4]))],
1✔
946
            )
1✔
947
            .unwrap(),
1✔
948
            DataCollection::from_slices(
1✔
949
                &[] as &[NoGeometry],
1✔
950
                &[TimeInterval::default(); 4],
1✔
951
                &[("foo", FeatureData::Int(vec![5, 6, 7, 8]))],
1✔
952
            )
1✔
953
            .unwrap(),
1✔
954
        ])
1✔
955
        .boxed();
1✔
956

1✔
957
        let histogram = Histogram {
1✔
958
            params: HistogramParams {
1✔
959
                column_name: Some("foo".to_string()),
1✔
960
                bounds: HistogramBounds::Values { min: 0.0, max: 8.0 },
1✔
961
                buckets: HistogramBuckets::Number { value: 3 },
1✔
962
                interactive: true,
1✔
963
            },
1✔
964
            sources: vector_source.into(),
1✔
965
        };
1✔
966

1✔
967
        let execution_context = MockExecutionContext::test_default();
1✔
968

969
        let query_processor = histogram
1✔
970
            .boxed()
1✔
971
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
972
            .await
×
973
            .unwrap()
1✔
974
            .query_processor()
1✔
975
            .unwrap()
1✔
976
            .json_vega()
1✔
977
            .unwrap();
1✔
978

979
        let result = query_processor
1✔
980
            .plot_query(
1✔
981
                PlotQueryRectangle {
1✔
982
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
983
                        .unwrap(),
1✔
984
                    time_interval: TimeInterval::default(),
1✔
985
                    spatial_resolution: SpatialResolution::one(),
1✔
986
                    attributes: PlotSeriesSelection::all(),
1✔
987
                },
1✔
988
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
989
            )
1✔
990
            .await
×
991
            .unwrap();
1✔
992

1✔
993
        assert_eq!(
1✔
994
            result,
1✔
995
            geoengine_datatypes::plots::Histogram::builder(3, 0., 8., Measurement::Unitless)
1✔
996
                .counts(vec![4, 5, 3])
1✔
997
                .build()
1✔
998
                .unwrap()
1✔
999
                .to_vega_embeddable(true)
1✔
1000
                .unwrap()
1✔
1001
        );
1✔
1002
    }
1003

1004
    #[tokio::test]
1✔
1005
    async fn vector_data_with_nulls() {
1✔
1006
        let vector_source = MockFeatureCollectionSource::single(
1✔
1007
            DataCollection::from_slices(
1✔
1008
                &[] as &[NoGeometry],
1✔
1009
                &[TimeInterval::default(); 6],
1✔
1010
                &[(
1✔
1011
                    "foo",
1✔
1012
                    FeatureData::NullableFloat(vec![
1✔
1013
                        Some(1.),
1✔
1014
                        Some(2.),
1✔
1015
                        None,
1✔
1016
                        Some(4.),
1✔
1017
                        None,
1✔
1018
                        Some(5.),
1✔
1019
                    ]),
1✔
1020
                )],
1✔
1021
            )
1✔
1022
            .unwrap(),
1✔
1023
        )
1✔
1024
        .boxed();
1✔
1025

1✔
1026
        let histogram = Histogram {
1✔
1027
            params: HistogramParams {
1✔
1028
                column_name: Some("foo".to_string()),
1✔
1029
                bounds: HistogramBounds::Data(Default::default()),
1✔
1030
                buckets: HistogramBuckets::SquareRootChoiceRule {
1✔
1031
                    max_number_of_buckets: 100,
1✔
1032
                },
1✔
1033
                interactive: false,
1✔
1034
            },
1✔
1035
            sources: vector_source.into(),
1✔
1036
        };
1✔
1037

1✔
1038
        let execution_context = MockExecutionContext::test_default();
1✔
1039

1040
        let query_processor = histogram
1✔
1041
            .boxed()
1✔
1042
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
1043
            .await
×
1044
            .unwrap()
1✔
1045
            .query_processor()
1✔
1046
            .unwrap()
1✔
1047
            .json_vega()
1✔
1048
            .unwrap();
1✔
1049

1050
        let result = query_processor
1✔
1051
            .plot_query(
1✔
1052
                PlotQueryRectangle {
1✔
1053
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
1054
                        .unwrap(),
1✔
1055
                    time_interval: TimeInterval::default(),
1✔
1056
                    spatial_resolution: SpatialResolution::one(),
1✔
1057
                    attributes: PlotSeriesSelection::all(),
1✔
1058
                },
1✔
1059
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
1060
            )
1✔
1061
            .await
×
1062
            .unwrap();
1✔
1063

1✔
1064
        assert_eq!(
1✔
1065
            result,
1✔
1066
            geoengine_datatypes::plots::Histogram::builder(2, 1., 5., Measurement::Unitless)
1✔
1067
                .counts(vec![2, 2])
1✔
1068
                .build()
1✔
1069
                .unwrap()
1✔
1070
                .to_vega_embeddable(false)
1✔
1071
                .unwrap()
1✔
1072
        );
1✔
1073
    }
1074

1075
    #[tokio::test]
1✔
1076
    #[allow(clippy::too_many_lines)]
1077
    async fn text_attribute() {
1✔
1078
        let dataset_id = DatasetId::new();
1✔
1079
        let dataset_name = NamedData::with_system_name("ne_10m_ports");
1✔
1080

1✔
1081
        let workflow = serde_json::json!({
1✔
1082
            "type": "Histogram",
1✔
1083
            "params": {
1✔
1084
                "columnName": "featurecla",
1✔
1085
                "bounds": "data",
1✔
1086
                "buckets": {
1✔
1087
                    "type": "squareRootChoiceRule",
1✔
1088
                    "maxNumberOfBuckets": 100,
1✔
1089
                }
1✔
1090
            },
1✔
1091
            "sources": {
1✔
1092
                "source": {
1✔
1093
                    "type": "OgrSource",
1✔
1094
                    "params": {
1✔
1095
                        "data": dataset_name.clone(),
1✔
1096
                        "attributeProjection": null
1✔
1097
                    },
1✔
1098
                }
1✔
1099
            }
1✔
1100
        });
1✔
1101
        let histogram: Histogram = serde_json::from_value(workflow).unwrap();
1✔
1102

1✔
1103
        let mut execution_context = MockExecutionContext::test_default();
1✔
1104
        execution_context.add_meta_data::<_, _, VectorQueryRectangle>(
1✔
1105
            DataId::Internal { dataset_id },
1✔
1106
            dataset_name,
1✔
1107
            Box::new(StaticMetaData {
1✔
1108
                loading_info: OgrSourceDataset {
1✔
1109
                    file_name: test_data!("vector/data/ne_10m_ports/ne_10m_ports.shp").into(),
1✔
1110
                    layer_name: "ne_10m_ports".to_string(),
1✔
1111
                    data_type: Some(VectorDataType::MultiPoint),
1✔
1112
                    time: OgrSourceDatasetTimeType::None,
1✔
1113
                    default_geometry: None,
1✔
1114
                    columns: Some(OgrSourceColumnSpec {
1✔
1115
                        format_specifics: None,
1✔
1116
                        x: String::new(),
1✔
1117
                        y: None,
1✔
1118
                        int: vec!["natlscale".to_string()],
1✔
1119
                        float: vec!["scalerank".to_string()],
1✔
1120
                        text: vec![
1✔
1121
                            "featurecla".to_string(),
1✔
1122
                            "name".to_string(),
1✔
1123
                            "website".to_string(),
1✔
1124
                        ],
1✔
1125
                        bool: vec![],
1✔
1126
                        datetime: vec![],
1✔
1127
                        rename: None,
1✔
1128
                    }),
1✔
1129
                    force_ogr_time_filter: false,
1✔
1130
                    force_ogr_spatial_filter: false,
1✔
1131
                    on_error: OgrSourceErrorSpec::Ignore,
1✔
1132
                    sql_query: None,
1✔
1133
                    attribute_query: None,
1✔
1134
                    cache_ttl: CacheTtlSeconds::default(),
1✔
1135
                },
1✔
1136
                result_descriptor: VectorResultDescriptor {
1✔
1137
                    data_type: VectorDataType::MultiPoint,
1✔
1138
                    spatial_reference: SpatialReference::epsg_4326().into(),
1✔
1139
                    columns: [
1✔
1140
                        (
1✔
1141
                            "natlscale".to_string(),
1✔
1142
                            VectorColumnInfo {
1✔
1143
                                data_type: FeatureDataType::Float,
1✔
1144
                                measurement: Measurement::Unitless,
1✔
1145
                            },
1✔
1146
                        ),
1✔
1147
                        (
1✔
1148
                            "scalerank".to_string(),
1✔
1149
                            VectorColumnInfo {
1✔
1150
                                data_type: FeatureDataType::Int,
1✔
1151
                                measurement: Measurement::Unitless,
1✔
1152
                            },
1✔
1153
                        ),
1✔
1154
                        (
1✔
1155
                            "featurecla".to_string(),
1✔
1156
                            VectorColumnInfo {
1✔
1157
                                data_type: FeatureDataType::Text,
1✔
1158
                                measurement: Measurement::Unitless,
1✔
1159
                            },
1✔
1160
                        ),
1✔
1161
                        (
1✔
1162
                            "name".to_string(),
1✔
1163
                            VectorColumnInfo {
1✔
1164
                                data_type: FeatureDataType::Text,
1✔
1165
                                measurement: Measurement::Unitless,
1✔
1166
                            },
1✔
1167
                        ),
1✔
1168
                        (
1✔
1169
                            "website".to_string(),
1✔
1170
                            VectorColumnInfo {
1✔
1171
                                data_type: FeatureDataType::Text,
1✔
1172
                                measurement: Measurement::Unitless,
1✔
1173
                            },
1✔
1174
                        ),
1✔
1175
                    ]
1✔
1176
                    .iter()
1✔
1177
                    .cloned()
1✔
1178
                    .collect(),
1✔
1179
                    time: None,
1✔
1180
                    bbox: None,
1✔
1181
                },
1✔
1182
                phantom: Default::default(),
1✔
1183
            }),
1✔
1184
        );
1✔
1185

1186
        if let Err(Error::InvalidOperatorSpec { reason }) = histogram
1✔
1187
            .boxed()
1✔
1188
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
1189
            .await
×
1190
        {
1191
            assert_eq!(reason, "column `featurecla` must be numerical");
1✔
1192
        } else {
1193
            panic!("we currently don't support text features, but this went through");
×
1194
        }
1195
    }
1196

1197
    #[tokio::test]
1✔
1198
    async fn no_data_raster() {
1✔
1199
        let tile_size_in_pixels = [3, 2].into();
1✔
1200
        let tiling_specification = TilingSpecification {
1✔
1201
            origin_coordinate: [0.0, 0.0].into(),
1✔
1202
            tile_size_in_pixels,
1✔
1203
        };
1✔
1204
        let execution_context = MockExecutionContext::new_with_tiling_spec(tiling_specification);
1✔
1205
        let histogram = Histogram {
1✔
1206
            params: HistogramParams {
1✔
1207
                column_name: None,
1✔
1208
                bounds: HistogramBounds::Data(Data),
1✔
1209
                buckets: HistogramBuckets::SquareRootChoiceRule {
1✔
1210
                    max_number_of_buckets: 100,
1✔
1211
                },
1✔
1212
                interactive: false,
1✔
1213
            },
1✔
1214
            sources: MockRasterSource {
1✔
1215
                params: MockRasterSourceParams {
1✔
1216
                    data: vec![RasterTile2D::new_with_tile_info(
1✔
1217
                        TimeInterval::default(),
1✔
1218
                        TileInformation {
1✔
1219
                            global_geo_transform: TestDefault::test_default(),
1✔
1220
                            global_tile_position: [0, 0].into(),
1✔
1221
                            tile_size_in_pixels,
1✔
1222
                        },
1✔
1223
                        0,
1✔
1224
                        EmptyGrid2D::<u8>::new(tile_size_in_pixels).into(),
1✔
1225
                        CacheHint::default(),
1✔
1226
                    )],
1✔
1227
                    result_descriptor: RasterResultDescriptor {
1✔
1228
                        data_type: RasterDataType::U8,
1✔
1229
                        spatial_reference: SpatialReference::epsg_4326().into(),
1✔
1230
                        time: None,
1✔
1231
                        bbox: None,
1✔
1232
                        resolution: None,
1✔
1233
                        bands: RasterBandDescriptors::new_single_band(),
1✔
1234
                    },
1✔
1235
                },
1✔
1236
            }
1✔
1237
            .boxed()
1✔
1238
            .into(),
1✔
1239
        };
1✔
1240

1241
        let query_processor = histogram
1✔
1242
            .boxed()
1✔
1243
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
1244
            .await
×
1245
            .unwrap()
1✔
1246
            .query_processor()
1✔
1247
            .unwrap()
1✔
1248
            .json_vega()
1✔
1249
            .unwrap();
1✔
1250

1251
        let result = query_processor
1✔
1252
            .plot_query(
1✔
1253
                PlotQueryRectangle {
1✔
1254
                    spatial_bounds: BoundingBox2D::new((0., -3.).into(), (2., 0.).into()).unwrap(),
1✔
1255
                    time_interval: TimeInterval::default(),
1✔
1256
                    spatial_resolution: SpatialResolution::one(),
1✔
1257
                    attributes: PlotSeriesSelection::all(),
1✔
1258
                },
1✔
1259
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
1260
            )
1✔
1261
            .await
×
1262
            .unwrap();
1✔
1263

1✔
1264
        assert_eq!(
1✔
1265
            result,
1✔
1266
            geoengine_datatypes::plots::Histogram::builder(1, 0., 0., Measurement::Unitless)
1✔
1267
                .build()
1✔
1268
                .unwrap()
1✔
1269
                .to_vega_embeddable(false)
1✔
1270
                .unwrap()
1✔
1271
        );
1✔
1272
    }
1273

1274
    #[tokio::test]
1✔
1275
    async fn empty_feature_collection() {
1✔
1276
        let vector_source = MockFeatureCollectionSource::single(
1✔
1277
            DataCollection::from_slices(
1✔
1278
                &[] as &[NoGeometry],
1✔
1279
                &[] as &[TimeInterval],
1✔
1280
                &[("foo", FeatureData::Float(vec![]))],
1✔
1281
            )
1✔
1282
            .unwrap(),
1✔
1283
        )
1✔
1284
        .boxed();
1✔
1285

1✔
1286
        let histogram = Histogram {
1✔
1287
            params: HistogramParams {
1✔
1288
                column_name: Some("foo".to_string()),
1✔
1289
                bounds: HistogramBounds::Data(Default::default()),
1✔
1290
                buckets: HistogramBuckets::SquareRootChoiceRule {
1✔
1291
                    max_number_of_buckets: 100,
1✔
1292
                },
1✔
1293
                interactive: false,
1✔
1294
            },
1✔
1295
            sources: vector_source.into(),
1✔
1296
        };
1✔
1297

1✔
1298
        let execution_context = MockExecutionContext::test_default();
1✔
1299

1300
        let query_processor = histogram
1✔
1301
            .boxed()
1✔
1302
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
1303
            .await
×
1304
            .unwrap()
1✔
1305
            .query_processor()
1✔
1306
            .unwrap()
1✔
1307
            .json_vega()
1✔
1308
            .unwrap();
1✔
1309

1310
        let result = query_processor
1✔
1311
            .plot_query(
1✔
1312
                PlotQueryRectangle {
1✔
1313
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
1314
                        .unwrap(),
1✔
1315
                    time_interval: TimeInterval::default(),
1✔
1316
                    spatial_resolution: SpatialResolution::one(),
1✔
1317
                    attributes: PlotSeriesSelection::all(),
1✔
1318
                },
1✔
1319
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
1320
            )
1✔
1321
            .await
×
1322
            .unwrap();
1✔
1323

1✔
1324
        assert_eq!(
1✔
1325
            result,
1✔
1326
            geoengine_datatypes::plots::Histogram::builder(1, 0., 0., Measurement::Unitless)
1✔
1327
                .build()
1✔
1328
                .unwrap()
1✔
1329
                .to_vega_embeddable(false)
1✔
1330
                .unwrap()
1✔
1331
        );
1✔
1332
    }
1333

1334
    #[tokio::test]
1✔
1335
    async fn feature_collection_with_one_feature() {
1✔
1336
        let vector_source = MockFeatureCollectionSource::with_collections_and_measurements(
1✔
1337
            vec![DataCollection::from_slices(
1✔
1338
                &[] as &[NoGeometry],
1✔
1339
                &[TimeInterval::default()],
1✔
1340
                &[("foo", FeatureData::Float(vec![5.0]))],
1✔
1341
            )
1✔
1342
            .unwrap()],
1✔
1343
            [(
1✔
1344
                "foo".to_string(),
1✔
1345
                Measurement::continuous("bar".to_string(), None),
1✔
1346
            )]
1✔
1347
            .into_iter()
1✔
1348
            .collect(),
1✔
1349
        )
1✔
1350
        .boxed();
1✔
1351

1✔
1352
        let histogram = Histogram {
1✔
1353
            params: HistogramParams {
1✔
1354
                column_name: Some("foo".to_string()),
1✔
1355
                bounds: HistogramBounds::Data(Default::default()),
1✔
1356
                buckets: HistogramBuckets::SquareRootChoiceRule {
1✔
1357
                    max_number_of_buckets: 100,
1✔
1358
                },
1✔
1359
                interactive: false,
1✔
1360
            },
1✔
1361
            sources: vector_source.into(),
1✔
1362
        };
1✔
1363

1✔
1364
        let execution_context = MockExecutionContext::test_default();
1✔
1365

1366
        let query_processor = histogram
1✔
1367
            .boxed()
1✔
1368
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
1369
            .await
×
1370
            .unwrap()
1✔
1371
            .query_processor()
1✔
1372
            .unwrap()
1✔
1373
            .json_vega()
1✔
1374
            .unwrap();
1✔
1375

1376
        let result = query_processor
1✔
1377
            .plot_query(
1✔
1378
                PlotQueryRectangle {
1✔
1379
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
1380
                        .unwrap(),
1✔
1381
                    time_interval: TimeInterval::default(),
1✔
1382
                    spatial_resolution: SpatialResolution::one(),
1✔
1383
                    attributes: PlotSeriesSelection::all(),
1✔
1384
                },
1✔
1385
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
1386
            )
1✔
1387
            .await
×
1388
            .unwrap();
1✔
1389

1✔
1390
        assert_eq!(
1✔
1391
            result,
1✔
1392
            geoengine_datatypes::plots::Histogram::builder(
1✔
1393
                1,
1✔
1394
                5.,
1✔
1395
                5.,
1✔
1396
                Measurement::continuous("bar".to_string(), None)
1✔
1397
            )
1✔
1398
            .counts(vec![1])
1✔
1399
            .build()
1✔
1400
            .unwrap()
1✔
1401
            .to_vega_embeddable(false)
1✔
1402
            .unwrap()
1✔
1403
        );
1✔
1404
    }
1405

1406
    #[tokio::test]
1✔
1407
    async fn single_value_raster_stream() {
1✔
1408
        let tile_size_in_pixels = [3, 2].into();
1✔
1409
        let tiling_specification = TilingSpecification {
1✔
1410
            origin_coordinate: [0.0, 0.0].into(),
1✔
1411
            tile_size_in_pixels,
1✔
1412
        };
1✔
1413
        let execution_context = MockExecutionContext::new_with_tiling_spec(tiling_specification);
1✔
1414
        let histogram = Histogram {
1✔
1415
            params: HistogramParams {
1✔
1416
                column_name: None,
1✔
1417
                bounds: HistogramBounds::Data(Data),
1✔
1418
                buckets: HistogramBuckets::SquareRootChoiceRule {
1✔
1419
                    max_number_of_buckets: 100,
1✔
1420
                },
1✔
1421
                interactive: false,
1✔
1422
            },
1✔
1423
            sources: MockRasterSource {
1✔
1424
                params: MockRasterSourceParams {
1✔
1425
                    data: vec![RasterTile2D::new_with_tile_info(
1✔
1426
                        TimeInterval::default(),
1✔
1427
                        TileInformation {
1✔
1428
                            global_geo_transform: TestDefault::test_default(),
1✔
1429
                            global_tile_position: [0, 0].into(),
1✔
1430
                            tile_size_in_pixels,
1✔
1431
                        },
1✔
1432
                        0,
1✔
1433
                        Grid2D::new(tile_size_in_pixels, vec![4; 6]).unwrap().into(),
1✔
1434
                        CacheHint::default(),
1✔
1435
                    )],
1✔
1436
                    result_descriptor: RasterResultDescriptor {
1✔
1437
                        data_type: RasterDataType::U8,
1✔
1438
                        spatial_reference: SpatialReference::epsg_4326().into(),
1✔
1439
                        time: None,
1✔
1440
                        bbox: None,
1✔
1441
                        resolution: None,
1✔
1442
                        bands: RasterBandDescriptors::new_single_band(),
1✔
1443
                    },
1✔
1444
                },
1✔
1445
            }
1✔
1446
            .boxed()
1✔
1447
            .into(),
1✔
1448
        };
1✔
1449

1450
        let query_processor = histogram
1✔
1451
            .boxed()
1✔
1452
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
1453
            .await
×
1454
            .unwrap()
1✔
1455
            .query_processor()
1✔
1456
            .unwrap()
1✔
1457
            .json_vega()
1✔
1458
            .unwrap();
1✔
1459

1460
        let result = query_processor
1✔
1461
            .plot_query(
1✔
1462
                PlotQueryRectangle {
1✔
1463
                    spatial_bounds: BoundingBox2D::new((0., -3.).into(), (2., 0.).into()).unwrap(),
1✔
1464
                    time_interval: TimeInterval::new_instant(DateTime::new_utc(
1✔
1465
                        2013, 12, 1, 12, 0, 0,
1✔
1466
                    ))
1✔
1467
                    .unwrap(),
1✔
1468
                    spatial_resolution: SpatialResolution::one(),
1✔
1469
                    attributes: PlotSeriesSelection::all(),
1✔
1470
                },
1✔
1471
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
1472
            )
1✔
1473
            .await
×
1474
            .unwrap();
1✔
1475

1✔
1476
        assert_eq!(
1✔
1477
            result,
1✔
1478
            geoengine_datatypes::plots::Histogram::builder(1, 4., 4., Measurement::Unitless)
1✔
1479
                .counts(vec![6])
1✔
1480
                .build()
1✔
1481
                .unwrap()
1✔
1482
                .to_vega_embeddable(false)
1✔
1483
                .unwrap()
1✔
1484
        );
1✔
1485
    }
1486
}
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