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

geo-engine / geoengine / 18554766227

16 Oct 2025 08:12AM UTC coverage: 88.843% (+0.3%) from 88.543%
18554766227

push

github

web-flow
build: update dependencies (#1081)

* update sqlfluff

* clippy autofix

* manual clippy fixes

* removal of unused code

* update deps

* upgrade packages

* enable cargo lints

* make sqlfluff happy

* fix chrono parsin error

* clippy

* byte_size

* fix image cmp with tiffs

* remove debug

177 of 205 new or added lines in 38 files covered. (86.34%)

41 existing lines in 20 files now uncovered.

106415 of 119779 relevant lines covered (88.84%)

84190.21 hits per line

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

96.8
/operators/src/plot/class_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::util::Result;
11
use crate::util::input::RasterOrVectorOperator;
12
use async_trait::async_trait;
13
use futures::StreamExt;
14
use geoengine_datatypes::collections::FeatureCollectionInfos;
15
use geoengine_datatypes::plots::{BarChart, Plot, PlotData};
16
use geoengine_datatypes::primitives::{
17
    AxisAlignedRectangle, BandSelection, BoundingBox2D, ClassificationMeasurement, FeatureDataType,
18
    Measurement, PlotQueryRectangle, RasterQueryRectangle,
19
};
20
use num_traits::AsPrimitive;
21
use serde::{Deserialize, Serialize};
22
use snafu::{OptionExt, ensure};
23
use std::collections::HashMap;
24

25
pub const CLASS_HISTOGRAM_OPERATOR_NAME: &str = "ClassHistogram";
26

27
/// A class histogram plot about either a raster or a vector input.
28
///
29
/// For vector inputs, it calculates the histogram on one of its attributes.
30
///
31
pub type ClassHistogram = Operator<ClassHistogramParams, SingleRasterOrVectorSource>;
32

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

37
/// The parameter spec for `Histogram`
38
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39
#[serde(rename_all = "camelCase")]
40
pub struct ClassHistogramParams {
41
    /// Name of the (numeric) attribute to compute the histogram on. Fails if set for rasters.
42
    pub column_name: Option<String>,
43
}
44

45
#[typetag::serde]
×
46
#[async_trait]
47
impl PlotOperator for ClassHistogram {
48
    async fn _initialize(
49
        self: Box<Self>,
50
        path: WorkflowOperatorPath,
51
        context: &dyn ExecutionContext,
52
    ) -> Result<Box<dyn InitializedPlotOperator>> {
9✔
53
        let name = CanonicOperatorName::from(&self);
54

55
        Ok(match self.sources.source {
56
            RasterOrVectorOperator::Raster(raster_source) => {
57
                ensure!(
58
                    self.params.column_name.is_none(),
59
                    error::InvalidOperatorSpec {
60
                        reason: "Histogram on raster input must not have `columnName` field set"
61
                            .to_string(),
62
                    }
63
                );
64

65
                let raster_source = raster_source
66
                    .initialize(path.clone_and_append(0), context)
67
                    .await?;
68

69
                let in_desc = raster_source.result_descriptor();
70

71
                ensure!(
72
                    in_desc.bands.len() == 1,
73
                    crate::error::OperatorDoesNotSupportMultiBandsSourcesYet {
74
                        operator: ClassHistogram::TYPE_NAME
75
                    }
76
                );
77

78
                let source_measurement = match &in_desc.bands[0].measurement {
79
                    Measurement::Classification(measurement) => measurement.clone(),
80
                    _ => {
81
                        return Err(Error::InvalidOperatorSpec {
82
                            reason: "Source measurement mut be classification".to_string(),
83
                        });
84
                    }
85
                };
86

87
                InitializedClassHistogram::new(
88
                    name,
89
                    PlotResultDescriptor {
90
                        spatial_reference: in_desc.spatial_reference,
91
                        time: in_desc.time,
92
                        // converting `SpatialPartition2D` to `BoundingBox2D` is ok here, because is makes the covered area only larger
93
                        bbox: in_desc
94
                            .bbox
UNCOV
95
                            .and_then(|p| BoundingBox2D::new(p.lower_left(), p.upper_right()).ok()),
×
96
                    },
97
                    self.params.column_name,
98
                    source_measurement,
99
                    raster_source,
100
                )
101
                .boxed()
102
            }
103
            RasterOrVectorOperator::Vector(vector_source) => {
104
                let column_name =
105
                    self.params
106
                        .column_name
107
                        .as_ref()
108
                        .context(error::InvalidOperatorSpec {
109
                            reason: "Histogram on vector input is missing `columnName` field"
110
                                .to_string(),
111
                        })?;
112

113
                let vector_source = vector_source
114
                    .initialize(path.clone_and_append(0), context)
115
                    .await?;
116

117
                match vector_source
118
                    .result_descriptor()
119
                    .column_data_type(column_name)
120
                {
121
                    None => {
122
                        return Err(Error::ColumnDoesNotExist {
123
                            column: column_name.to_string(),
124
                        });
125
                    }
126
                    Some(FeatureDataType::Text | FeatureDataType::DateTime) => {
127
                        return Err(Error::InvalidOperatorSpec {
128
                            reason: format!("column `{column_name}` must be numerical"),
129
                        });
130
                    }
131
                    Some(
132
                        FeatureDataType::Int
133
                        | FeatureDataType::Float
134
                        | FeatureDataType::Bool
135
                        | FeatureDataType::Category,
136
                    ) => {
137
                        // okay
138
                    }
139
                }
140

141
                let in_desc = vector_source.result_descriptor().clone();
142

143
                let source_measurement = match in_desc.column_measurement(column_name) {
144
                    Some(Measurement::Classification(measurement)) => measurement.clone(),
145
                    _ => {
146
                        return Err(Error::InvalidOperatorSpec {
147
                            reason: "Source measurement mut be classification".to_string(),
148
                        });
149
                    }
150
                };
151

152
                InitializedClassHistogram::new(
153
                    name,
154
                    in_desc.into(),
155
                    self.params.column_name,
156
                    source_measurement,
157
                    vector_source,
158
                )
159
                .boxed()
160
            }
161
        })
162
    }
9✔
163

164
    span_fn!(ClassHistogram);
165
}
166

167
/// The initialization of `Histogram`
168
pub struct InitializedClassHistogram<Op> {
169
    name: CanonicOperatorName,
170
    result_descriptor: PlotResultDescriptor,
171
    source_measurement: ClassificationMeasurement,
172
    source: Op,
173
    column_name: Option<String>,
174
}
175

176
impl<Op> InitializedClassHistogram<Op> {
177
    pub fn new(
7✔
178
        name: CanonicOperatorName,
7✔
179
        result_descriptor: PlotResultDescriptor,
7✔
180
        column_name: Option<String>,
7✔
181
        source_measurement: ClassificationMeasurement,
7✔
182
        source: Op,
7✔
183
    ) -> Self {
7✔
184
        Self {
7✔
185
            name,
7✔
186
            result_descriptor,
7✔
187
            source_measurement,
7✔
188
            source,
7✔
189
            column_name,
7✔
190
        }
7✔
191
    }
7✔
192
}
193

194
impl InitializedPlotOperator for InitializedClassHistogram<Box<dyn InitializedRasterOperator>> {
195
    fn query_processor(&self) -> Result<TypedPlotQueryProcessor> {
3✔
196
        let processor = ClassHistogramRasterQueryProcessor {
3✔
197
            input: self.source.query_processor()?,
3✔
198
            measurement: self.source_measurement.clone(),
3✔
199
        };
200

201
        Ok(TypedPlotQueryProcessor::JsonVega(processor.boxed()))
3✔
202
    }
3✔
203

204
    fn result_descriptor(&self) -> &PlotResultDescriptor {
×
205
        &self.result_descriptor
×
206
    }
×
207

208
    fn canonic_name(&self) -> CanonicOperatorName {
×
209
        self.name.clone()
×
210
    }
×
211
}
212

213
impl InitializedPlotOperator for InitializedClassHistogram<Box<dyn InitializedVectorOperator>> {
214
    fn query_processor(&self) -> Result<TypedPlotQueryProcessor> {
4✔
215
        let processor = ClassHistogramVectorQueryProcessor {
4✔
216
            input: self.source.query_processor()?,
4✔
217
            column_name: self.column_name.clone().unwrap_or_default(),
4✔
218
            measurement: self.source_measurement.clone(),
4✔
219
        };
220

221
        Ok(TypedPlotQueryProcessor::JsonVega(processor.boxed()))
4✔
222
    }
4✔
223

224
    fn result_descriptor(&self) -> &PlotResultDescriptor {
×
225
        &self.result_descriptor
×
226
    }
×
227

228
    fn canonic_name(&self) -> CanonicOperatorName {
×
229
        self.name.clone()
×
230
    }
×
231
}
232

233
/// A query processor that calculates the Histogram about its raster inputs.
234
pub struct ClassHistogramRasterQueryProcessor {
235
    input: TypedRasterQueryProcessor,
236
    measurement: ClassificationMeasurement,
237
}
238

239
/// A query processor that calculates the Histogram about its vector inputs.
240
pub struct ClassHistogramVectorQueryProcessor {
241
    input: TypedVectorQueryProcessor,
242
    column_name: String,
243
    measurement: ClassificationMeasurement,
244
}
245

246
#[async_trait]
247
impl PlotQueryProcessor for ClassHistogramRasterQueryProcessor {
248
    type OutputFormat = PlotData;
249

250
    fn plot_type(&self) -> &'static str {
×
251
        CLASS_HISTOGRAM_OPERATOR_NAME
×
252
    }
×
253

254
    async fn plot_query<'p>(
255
        &'p self,
256
        query: PlotQueryRectangle,
257
        ctx: &'p dyn QueryContext,
258
    ) -> Result<Self::OutputFormat> {
3✔
259
        self.process(query, ctx).await
260
    }
3✔
261
}
262

263
#[async_trait]
264
impl PlotQueryProcessor for ClassHistogramVectorQueryProcessor {
265
    type OutputFormat = PlotData;
266

267
    fn plot_type(&self) -> &'static str {
×
268
        CLASS_HISTOGRAM_OPERATOR_NAME
×
269
    }
×
270

271
    async fn plot_query<'p>(
272
        &'p self,
273
        query: PlotQueryRectangle,
274
        ctx: &'p dyn QueryContext,
275
    ) -> Result<Self::OutputFormat> {
4✔
276
        self.process(query, ctx).await
277
    }
4✔
278
}
279

280
impl ClassHistogramRasterQueryProcessor {
281
    async fn process<'p>(
3✔
282
        &'p self,
3✔
283
        query: PlotQueryRectangle,
3✔
284
        ctx: &'p dyn QueryContext,
3✔
285
    ) -> Result<<ClassHistogramRasterQueryProcessor as PlotQueryProcessor>::OutputFormat> {
3✔
286
        let mut class_counts: HashMap<u8, u64> = self
3✔
287
            .measurement
3✔
288
            .classes
3✔
289
            .keys()
3✔
290
            .map(|key| (*key, 0))
8✔
291
            .collect();
3✔
292

293
        call_on_generic_raster_processor!(&self.input, processor => {
3✔
294
            let mut query = processor.query(RasterQueryRectangle::from_qrect_and_bands(&query, BandSelection::first()), ctx).await?;
×
295

296
            while let Some(tile) = query.next().await {
×
297
                match tile?.grid_array {
×
298
                    geoengine_datatypes::raster::GridOrEmpty::Grid(g) => {
×
299
                        g.masked_element_deref_iterator().for_each(|value_option| {
18✔
300
                            if let Some(v) = value_option
18✔
301
                                && let Some(count) = class_counts.get_mut(&v.as_()) {
18✔
302
                                    *count += 1;
12✔
303
                                }
12✔
304
                        });
18✔
305
                    },
306
                    geoengine_datatypes::raster::GridOrEmpty::Empty(_) => (), // ignore no data,
×
307
                }
308
            }
309
        });
310

311
        // TODO: display NO-DATA count?
312

313
        let bar_chart = BarChart::new(
3✔
314
            class_counts
3✔
315
                .into_iter()
3✔
316
                .map(|(class, count)| {
8✔
317
                    (
8✔
318
                        self.measurement
8✔
319
                            .classes
8✔
320
                            .get(&class)
8✔
321
                            .cloned()
8✔
322
                            .unwrap_or_default(),
8✔
323
                        count,
8✔
324
                    )
8✔
325
                })
8✔
326
                .collect(),
3✔
327
            Measurement::Classification(self.measurement.clone()).to_string(),
3✔
328
            "Frequency".to_string(),
3✔
329
        );
330
        let chart = bar_chart.to_vega_embeddable(false)?;
3✔
331

332
        Ok(chart)
3✔
333
    }
3✔
334
}
335

336
impl ClassHistogramVectorQueryProcessor {
337
    async fn process<'p>(
4✔
338
        &'p self,
4✔
339
        query: PlotQueryRectangle,
4✔
340
        ctx: &'p dyn QueryContext,
4✔
341
    ) -> Result<<ClassHistogramRasterQueryProcessor as PlotQueryProcessor>::OutputFormat> {
4✔
342
        let mut class_counts: HashMap<u8, u64> = self
4✔
343
            .measurement
4✔
344
            .classes
4✔
345
            .keys()
4✔
346
            .map(|key| (*key, 0))
8✔
347
            .collect();
4✔
348

349
        call_on_generic_vector_processor!(&self.input, processor => {
4✔
350
            let mut query = processor.query(query.into(), ctx).await?;
4✔
351

352
            while let Some(collection) = query.next().await {
9✔
353
                let collection = collection?;
5✔
354

355
                let feature_data = collection.data(&self.column_name).expect("checked in param");
5✔
356

357
                for v in feature_data.float_options_iter() {
19✔
358
                    match v {
19✔
359
                        None => (), // ignore no data
2✔
360
                        Some(index) => if let Some(count) = class_counts.get_mut(&(index as u8)) {
17✔
361
                            *count += 1;
16✔
362
                        },
16✔
363
                        // else… ignore values that are not in the class list
364
                    }
365

366
                }
367

368
            }
369
        });
370

371
        // TODO: display NO-DATA count?
372

373
        let bar_chart = BarChart::new(
4✔
374
            class_counts
4✔
375
                .into_iter()
4✔
376
                .map(|(class, count)| {
8✔
377
                    (
8✔
378
                        self.measurement
8✔
379
                            .classes
8✔
380
                            .get(&class)
8✔
381
                            .cloned()
8✔
382
                            .unwrap_or_default(),
8✔
383
                        count,
8✔
384
                    )
8✔
385
                })
8✔
386
                .collect(),
4✔
387
            Measurement::Classification(self.measurement.clone()).to_string(),
4✔
388
            "Frequency".to_string(),
4✔
389
        );
390
        let chart = bar_chart.to_vega_embeddable(false)?;
4✔
391

392
        Ok(chart)
4✔
393
    }
4✔
394
}
395

396
#[cfg(test)]
397
mod tests {
398
    use super::*;
399

400
    use crate::engine::{
401
        ChunkByteSize, MockExecutionContext, MockQueryContext, RasterBandDescriptor,
402
        RasterBandDescriptors, RasterOperator, RasterResultDescriptor, StaticMetaData,
403
        VectorColumnInfo, VectorOperator, VectorResultDescriptor,
404
    };
405
    use crate::mock::{MockFeatureCollectionSource, MockRasterSource, MockRasterSourceParams};
406
    use crate::source::{
407
        OgrSourceColumnSpec, OgrSourceDataset, OgrSourceDatasetTimeType, OgrSourceErrorSpec,
408
    };
409
    use crate::test_data;
410
    use geoengine_datatypes::dataset::{DataId, DatasetId, NamedData};
411
    use geoengine_datatypes::primitives::{
412
        BoundingBox2D, DateTime, FeatureData, NoGeometry, PlotSeriesSelection, SpatialResolution,
413
        TimeInterval, VectorQueryRectangle,
414
    };
415
    use geoengine_datatypes::primitives::{CacheHint, CacheTtlSeconds};
416
    use geoengine_datatypes::raster::{
417
        Grid2D, RasterDataType, RasterTile2D, TileInformation, TilingSpecification,
418
    };
419
    use geoengine_datatypes::spatial_reference::SpatialReference;
420
    use geoengine_datatypes::util::Identifier;
421
    use geoengine_datatypes::util::test::TestDefault;
422
    use geoengine_datatypes::{
423
        collections::{DataCollection, VectorDataType},
424
        primitives::MultiPoint,
425
    };
426
    use serde_json::json;
427

428
    #[test]
429
    fn serialization() {
1✔
430
        let histogram = ClassHistogram {
1✔
431
            params: ClassHistogramParams {
1✔
432
                column_name: Some("foobar".to_string()),
1✔
433
            },
1✔
434
            sources: MockFeatureCollectionSource::<MultiPoint>::multiple(vec![])
1✔
435
                .boxed()
1✔
436
                .into(),
1✔
437
        };
1✔
438

439
        let serialized = json!({
1✔
440
            "type": "ClassHistogram",
1✔
441
            "params": {
1✔
442
                "columnName": "foobar",
1✔
443
            },
444
            "sources": {
1✔
445
                "source": {
1✔
446
                    "type": "MockFeatureCollectionSourceMultiPoint",
1✔
447
                    "params": {
1✔
448
                        "collections": [],
1✔
449
                        "spatialReference": "EPSG:4326",
1✔
450
                        "measurements": {},
1✔
451
                    }
452
                }
453
            }
454
        })
455
        .to_string();
1✔
456

457
        let deserialized: ClassHistogram = serde_json::from_str(&serialized).unwrap();
1✔
458

459
        assert_eq!(deserialized.params, histogram.params);
1✔
460
    }
1✔
461

462
    #[tokio::test]
463
    async fn column_name_for_raster_source() {
1✔
464
        let histogram = ClassHistogram {
1✔
465
            params: ClassHistogramParams {
1✔
466
                column_name: Some("foo".to_string()),
1✔
467
            },
1✔
468
            sources: mock_raster_source().into(),
1✔
469
        };
1✔
470

471
        let execution_context = MockExecutionContext::test_default();
1✔
472

473
        assert!(
1✔
474
            histogram
1✔
475
                .boxed()
1✔
476
                .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
477
                .await
1✔
478
                .is_err()
1✔
479
        );
1✔
480
    }
1✔
481

482
    fn mock_raster_source() -> Box<dyn RasterOperator> {
2✔
483
        MockRasterSource {
2✔
484
            params: MockRasterSourceParams {
2✔
485
                data: vec![RasterTile2D::new_with_tile_info(
2✔
486
                    TimeInterval::default(),
2✔
487
                    TileInformation {
2✔
488
                        global_geo_transform: TestDefault::test_default(),
2✔
489
                        global_tile_position: [0, 0].into(),
2✔
490
                        tile_size_in_pixels: [3, 2].into(),
2✔
491
                    },
2✔
492
                    0,
2✔
493
                    Grid2D::new([3, 2].into(), vec![1, 2, 3, 4, 5, 6])
2✔
494
                        .unwrap()
2✔
495
                        .into(),
2✔
496
                    CacheHint::default(),
2✔
497
                )],
2✔
498
                result_descriptor: RasterResultDescriptor {
2✔
499
                    data_type: RasterDataType::U8,
2✔
500
                    spatial_reference: SpatialReference::epsg_4326().into(),
2✔
501
                    time: None,
2✔
502
                    bbox: None,
2✔
503
                    resolution: None,
2✔
504
                    bands: RasterBandDescriptors::new(vec![RasterBandDescriptor::new(
2✔
505
                        "bands".into(),
2✔
506
                        Measurement::classification(
2✔
507
                            "test-class".to_string(),
2✔
508
                            [
2✔
509
                                (1, "A".to_string()),
2✔
510
                                (2, "B".to_string()),
2✔
511
                                (3, "C".to_string()),
2✔
512
                                (4, "D".to_string()),
2✔
513
                                (5, "E".to_string()),
2✔
514
                                (6, "F".to_string()),
2✔
515
                            ]
2✔
516
                            .into_iter()
2✔
517
                            .collect(),
2✔
518
                        ),
2✔
519
                    )])
2✔
520
                    .unwrap(),
2✔
521
                },
2✔
522
            },
2✔
523
        }
2✔
524
        .boxed()
2✔
525
    }
2✔
526

527
    #[tokio::test]
528
    async fn simple_raster() {
1✔
529
        let tile_size_in_pixels = [3, 2].into();
1✔
530
        let tiling_specification = TilingSpecification {
1✔
531
            origin_coordinate: [0.0, 0.0].into(),
1✔
532
            tile_size_in_pixels,
1✔
533
        };
1✔
534
        let execution_context = MockExecutionContext::new_with_tiling_spec(tiling_specification);
1✔
535

536
        let histogram = ClassHistogram {
1✔
537
            params: ClassHistogramParams { column_name: None },
1✔
538
            sources: mock_raster_source().into(),
1✔
539
        };
1✔
540

541
        let query_processor = histogram
1✔
542
            .boxed()
1✔
543
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
544
            .await
1✔
545
            .unwrap()
1✔
546
            .query_processor()
1✔
547
            .unwrap()
1✔
548
            .json_vega()
1✔
549
            .unwrap();
1✔
550

551
        let result = query_processor
1✔
552
            .plot_query(
1✔
553
                PlotQueryRectangle {
1✔
554
                    spatial_bounds: BoundingBox2D::new((0., -3.).into(), (2., 0.).into()).unwrap(),
1✔
555
                    time_interval: TimeInterval::default(),
1✔
556
                    spatial_resolution: SpatialResolution::one(),
1✔
557
                    attributes: PlotSeriesSelection::all(),
1✔
558
                },
1✔
559
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
560
            )
1✔
561
            .await
1✔
562
            .unwrap();
1✔
563

564
        assert_eq!(
1✔
565
            result,
1✔
566
            BarChart::new(
1✔
567
                [
1✔
568
                    ("A".to_string(), 1),
1✔
569
                    ("B".to_string(), 1),
1✔
570
                    ("C".to_string(), 1),
1✔
571
                    ("D".to_string(), 1),
1✔
572
                    ("E".to_string(), 1),
1✔
573
                    ("F".to_string(), 1),
1✔
574
                ]
1✔
575
                .into_iter()
1✔
576
                .collect(),
1✔
577
                "test-class".to_string(),
1✔
578
                "Frequency".to_string()
1✔
579
            )
1✔
580
            .to_vega_embeddable(true)
1✔
581
            .unwrap()
1✔
582
        );
1✔
583
    }
1✔
584

585
    #[tokio::test]
586
    async fn vector_data() {
1✔
587
        let measurement = Measurement::classification(
1✔
588
            "foo".to_string(),
1✔
589
            [
1✔
590
                (1, "A".to_string()),
1✔
591
                (2, "B".to_string()),
1✔
592
                (3, "C".to_string()),
1✔
593
            ]
1✔
594
            .into_iter()
1✔
595
            .collect(),
1✔
596
        );
597

598
        let vector_source = MockFeatureCollectionSource::with_collections_and_measurements(
1✔
599
            vec![
1✔
600
                DataCollection::from_slices(
1✔
601
                    &[] as &[NoGeometry],
1✔
602
                    &[TimeInterval::default(); 8],
1✔
603
                    &[("foo", FeatureData::Int(vec![1, 1, 2, 2, 3, 3, 1, 2]))],
1✔
604
                )
605
                .unwrap(),
1✔
606
                DataCollection::from_slices(
1✔
607
                    &[] as &[NoGeometry],
1✔
608
                    &[TimeInterval::default(); 4],
1✔
609
                    &[("foo", FeatureData::Int(vec![1, 1, 2, 3]))],
1✔
610
                )
611
                .unwrap(),
1✔
612
            ],
613
            [("foo".to_string(), measurement)].into_iter().collect(),
1✔
614
        )
615
        .boxed();
1✔
616

617
        let histogram = ClassHistogram {
1✔
618
            params: ClassHistogramParams {
1✔
619
                column_name: Some("foo".to_string()),
1✔
620
            },
1✔
621
            sources: vector_source.into(),
1✔
622
        };
1✔
623

624
        let execution_context = MockExecutionContext::test_default();
1✔
625

626
        let query_processor = histogram
1✔
627
            .boxed()
1✔
628
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
629
            .await
1✔
630
            .unwrap()
1✔
631
            .query_processor()
1✔
632
            .unwrap()
1✔
633
            .json_vega()
1✔
634
            .unwrap();
1✔
635

636
        let result = query_processor
1✔
637
            .plot_query(
1✔
638
                PlotQueryRectangle {
1✔
639
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
640
                        .unwrap(),
1✔
641
                    time_interval: TimeInterval::default(),
1✔
642
                    spatial_resolution: SpatialResolution::one(),
1✔
643
                    attributes: PlotSeriesSelection::all(),
1✔
644
                },
1✔
645
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
646
            )
1✔
647
            .await
1✔
648
            .unwrap();
1✔
649

650
        assert_eq!(
1✔
651
            result,
1✔
652
            BarChart::new(
1✔
653
                [
1✔
654
                    ("A".to_string(), 5),
1✔
655
                    ("B".to_string(), 4),
1✔
656
                    ("C".to_string(), 3),
1✔
657
                ]
1✔
658
                .into_iter()
1✔
659
                .collect(),
1✔
660
                "foo".to_string(),
1✔
661
                "Frequency".to_string()
1✔
662
            )
1✔
663
            .to_vega_embeddable(true)
1✔
664
            .unwrap()
1✔
665
        );
1✔
666
    }
1✔
667

668
    #[tokio::test]
669
    async fn vector_data_with_nulls() {
1✔
670
        let measurement = Measurement::classification(
1✔
671
            "foo".to_string(),
1✔
672
            [
1✔
673
                (1, "A".to_string()),
1✔
674
                (2, "B".to_string()),
1✔
675
                (4, "C".to_string()),
1✔
676
            ]
1✔
677
            .into_iter()
1✔
678
            .collect(),
1✔
679
        );
680

681
        let vector_source = MockFeatureCollectionSource::with_collections_and_measurements(
1✔
682
            vec![
1✔
683
                DataCollection::from_slices(
1✔
684
                    &[] as &[NoGeometry],
1✔
685
                    &[TimeInterval::default(); 6],
1✔
686
                    &[(
1✔
687
                        "foo",
1✔
688
                        FeatureData::NullableFloat(vec![
1✔
689
                            Some(1.),
1✔
690
                            Some(2.),
1✔
691
                            None,
1✔
692
                            Some(4.),
1✔
693
                            None,
1✔
694
                            Some(5.),
1✔
695
                        ]),
1✔
696
                    )],
1✔
697
                )
698
                .unwrap(),
1✔
699
            ],
700
            [("foo".to_string(), measurement)].into_iter().collect(),
1✔
701
        )
702
        .boxed();
1✔
703

704
        let histogram = ClassHistogram {
1✔
705
            params: ClassHistogramParams {
1✔
706
                column_name: Some("foo".to_string()),
1✔
707
            },
1✔
708
            sources: vector_source.into(),
1✔
709
        };
1✔
710

711
        let execution_context = MockExecutionContext::test_default();
1✔
712

713
        let query_processor = histogram
1✔
714
            .boxed()
1✔
715
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
716
            .await
1✔
717
            .unwrap()
1✔
718
            .query_processor()
1✔
719
            .unwrap()
1✔
720
            .json_vega()
1✔
721
            .unwrap();
1✔
722

723
        let result = query_processor
1✔
724
            .plot_query(
1✔
725
                PlotQueryRectangle {
1✔
726
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
727
                        .unwrap(),
1✔
728
                    time_interval: TimeInterval::default(),
1✔
729
                    spatial_resolution: SpatialResolution::one(),
1✔
730
                    attributes: PlotSeriesSelection::all(),
1✔
731
                },
1✔
732
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
733
            )
1✔
734
            .await
1✔
735
            .unwrap();
1✔
736

737
        assert_eq!(
1✔
738
            result,
1✔
739
            BarChart::new(
1✔
740
                [
1✔
741
                    ("A".to_string(), 1),
1✔
742
                    ("B".to_string(), 1),
1✔
743
                    ("C".to_string(), 1),
1✔
744
                ]
1✔
745
                .into_iter()
1✔
746
                .collect(),
1✔
747
                "foo".to_string(),
1✔
748
                "Frequency".to_string()
1✔
749
            )
1✔
750
            .to_vega_embeddable(true)
1✔
751
            .unwrap()
1✔
752
        );
1✔
753
    }
1✔
754

755
    #[tokio::test]
756
    #[allow(clippy::too_many_lines)]
757
    async fn text_attribute() {
1✔
758
        let dataset_id = DatasetId::new();
1✔
759
        let dataset_name = NamedData::with_system_name("ne_10m_ports");
1✔
760

761
        let workflow = serde_json::json!({
1✔
762
            "type": "Histogram",
1✔
763
            "params": {
1✔
764
                "columnName": "featurecla",
1✔
765
            },
766
            "sources": {
1✔
767
                "source": {
1✔
768
                    "type": "OgrSource",
1✔
769
                    "params": {
1✔
770
                        "data": dataset_name.clone(),
1✔
771
                        "attributeProjection": null
1✔
772
                    },
773
                }
774
            }
775
        });
776
        let histogram: ClassHistogram = serde_json::from_value(workflow).unwrap();
1✔
777

778
        let mut execution_context = MockExecutionContext::test_default();
1✔
779
        execution_context.add_meta_data::<_, _, VectorQueryRectangle>(
1✔
780
            DataId::Internal { dataset_id },
1✔
781
            dataset_name.clone(),
1✔
782
            Box::new(StaticMetaData {
1✔
783
                loading_info: OgrSourceDataset {
1✔
784
                    file_name: test_data!("vector/data/ne_10m_ports/ne_10m_ports.shp").into(),
1✔
785
                    layer_name: "ne_10m_ports".to_string(),
1✔
786
                    data_type: Some(VectorDataType::MultiPoint),
1✔
787
                    time: OgrSourceDatasetTimeType::None,
1✔
788
                    default_geometry: None,
1✔
789
                    columns: Some(OgrSourceColumnSpec {
1✔
790
                        format_specifics: None,
1✔
791
                        x: String::new(),
1✔
792
                        y: None,
1✔
793
                        int: vec!["natlscale".to_string()],
1✔
794
                        float: vec!["scalerank".to_string()],
1✔
795
                        text: vec![
1✔
796
                            "featurecla".to_string(),
1✔
797
                            "name".to_string(),
1✔
798
                            "website".to_string(),
1✔
799
                        ],
1✔
800
                        bool: vec![],
1✔
801
                        datetime: vec![],
1✔
802
                        rename: None,
1✔
803
                    }),
1✔
804
                    force_ogr_time_filter: false,
1✔
805
                    force_ogr_spatial_filter: false,
1✔
806
                    on_error: OgrSourceErrorSpec::Ignore,
1✔
807
                    sql_query: None,
1✔
808
                    attribute_query: None,
1✔
809
                    cache_ttl: CacheTtlSeconds::default(),
1✔
810
                },
1✔
811
                result_descriptor: VectorResultDescriptor {
1✔
812
                    data_type: VectorDataType::MultiPoint,
1✔
813
                    spatial_reference: SpatialReference::epsg_4326().into(),
1✔
814
                    columns: [
1✔
815
                        (
1✔
816
                            "natlscale".to_string(),
1✔
817
                            VectorColumnInfo {
1✔
818
                                data_type: FeatureDataType::Float,
1✔
819
                                measurement: Measurement::Unitless,
1✔
820
                            },
1✔
821
                        ),
1✔
822
                        (
1✔
823
                            "scalerank".to_string(),
1✔
824
                            VectorColumnInfo {
1✔
825
                                data_type: FeatureDataType::Int,
1✔
826
                                measurement: Measurement::Unitless,
1✔
827
                            },
1✔
828
                        ),
1✔
829
                        (
1✔
830
                            "featurecla".to_string(),
1✔
831
                            VectorColumnInfo {
1✔
832
                                data_type: FeatureDataType::Text,
1✔
833
                                measurement: Measurement::Unitless,
1✔
834
                            },
1✔
835
                        ),
1✔
836
                        (
1✔
837
                            "name".to_string(),
1✔
838
                            VectorColumnInfo {
1✔
839
                                data_type: FeatureDataType::Text,
1✔
840
                                measurement: Measurement::Unitless,
1✔
841
                            },
1✔
842
                        ),
1✔
843
                        (
1✔
844
                            "website".to_string(),
1✔
845
                            VectorColumnInfo {
1✔
846
                                data_type: FeatureDataType::Text,
1✔
847
                                measurement: Measurement::Unitless,
1✔
848
                            },
1✔
849
                        ),
1✔
850
                    ]
1✔
851
                    .iter()
1✔
852
                    .cloned()
1✔
853
                    .collect(),
1✔
854
                    time: None,
1✔
855
                    bbox: None,
1✔
856
                },
1✔
857
                phantom: Default::default(),
1✔
858
            }),
1✔
859
        );
860

861
        if let Err(Error::InvalidOperatorSpec { reason }) = histogram
1✔
862
            .boxed()
1✔
863
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
864
            .await
1✔
865
        {
1✔
866
            assert_eq!(reason, "column `featurecla` must be numerical");
1✔
867
        } else {
1✔
868
            panic!("we currently don't support text features, but this went through");
1✔
869
        }
1✔
870
    }
1✔
871

872
    #[tokio::test]
873
    async fn no_data_raster() {
1✔
874
        let tile_size_in_pixels = [3, 2].into();
1✔
875
        let tiling_specification = TilingSpecification {
1✔
876
            origin_coordinate: [0.0, 0.0].into(),
1✔
877
            tile_size_in_pixels,
1✔
878
        };
1✔
879
        let execution_context = MockExecutionContext::new_with_tiling_spec(tiling_specification);
1✔
880

881
        let measurement = Measurement::classification(
1✔
882
            "foo".to_string(),
1✔
883
            [(1, "A".to_string())].into_iter().collect(),
1✔
884
        );
885

886
        let histogram = ClassHistogram {
1✔
887
            params: ClassHistogramParams { column_name: None },
1✔
888
            sources: MockRasterSource {
1✔
889
                params: MockRasterSourceParams {
1✔
890
                    data: vec![RasterTile2D::new_with_tile_info(
1✔
891
                        TimeInterval::default(),
1✔
892
                        TileInformation {
1✔
893
                            global_geo_transform: TestDefault::test_default(),
1✔
894
                            global_tile_position: [0, 0].into(),
1✔
895
                            tile_size_in_pixels,
1✔
896
                        },
1✔
897
                        0,
1✔
898
                        Grid2D::new(tile_size_in_pixels, vec![0, 0, 0, 0, 0, 0])
1✔
899
                            .unwrap()
1✔
900
                            .into(),
1✔
901
                        CacheHint::default(),
1✔
902
                    )],
1✔
903
                    result_descriptor: RasterResultDescriptor {
1✔
904
                        data_type: RasterDataType::U8,
1✔
905
                        spatial_reference: SpatialReference::epsg_4326().into(),
1✔
906
                        time: None,
1✔
907
                        bbox: None,
1✔
908
                        resolution: None,
1✔
909
                        bands: RasterBandDescriptors::new(vec![RasterBandDescriptor::new(
1✔
910
                            "band".into(),
1✔
911
                            measurement,
1✔
912
                        )])
1✔
913
                        .unwrap(),
1✔
914
                    },
1✔
915
                },
1✔
916
            }
1✔
917
            .boxed()
1✔
918
            .into(),
1✔
919
        };
1✔
920

921
        let query_processor = histogram
1✔
922
            .boxed()
1✔
923
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
924
            .await
1✔
925
            .unwrap()
1✔
926
            .query_processor()
1✔
927
            .unwrap()
1✔
928
            .json_vega()
1✔
929
            .unwrap();
1✔
930

931
        let result = query_processor
1✔
932
            .plot_query(
1✔
933
                PlotQueryRectangle {
1✔
934
                    spatial_bounds: BoundingBox2D::new((0., -3.).into(), (2., 0.).into()).unwrap(),
1✔
935
                    time_interval: TimeInterval::default(),
1✔
936
                    spatial_resolution: SpatialResolution::one(),
1✔
937
                    attributes: PlotSeriesSelection::all(),
1✔
938
                },
1✔
939
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
940
            )
1✔
941
            .await
1✔
942
            .unwrap();
1✔
943

944
        assert_eq!(
1✔
945
            result,
1✔
946
            BarChart::new(
1✔
947
                [("A".to_string(), 0)].into_iter().collect(),
1✔
948
                "foo".to_string(),
1✔
949
                "Frequency".to_string()
1✔
950
            )
1✔
951
            .to_vega_embeddable(true)
1✔
952
            .unwrap()
1✔
953
        );
1✔
954
    }
1✔
955

956
    #[tokio::test]
957
    async fn empty_feature_collection() {
1✔
958
        let measurement = Measurement::classification(
1✔
959
            "foo".to_string(),
1✔
960
            [(1, "A".to_string())].into_iter().collect(),
1✔
961
        );
962

963
        let vector_source = MockFeatureCollectionSource::with_collections_and_measurements(
1✔
964
            vec![
1✔
965
                DataCollection::from_slices(
1✔
966
                    &[] as &[NoGeometry],
1✔
967
                    &[] as &[TimeInterval],
1✔
968
                    &[("foo", FeatureData::Float(vec![]))],
1✔
969
                )
970
                .unwrap(),
1✔
971
            ],
972
            [("foo".to_string(), measurement)].into_iter().collect(),
1✔
973
        )
974
        .boxed();
1✔
975

976
        let histogram = ClassHistogram {
1✔
977
            params: ClassHistogramParams {
1✔
978
                column_name: Some("foo".to_string()),
1✔
979
            },
1✔
980
            sources: vector_source.into(),
1✔
981
        };
1✔
982

983
        let execution_context = MockExecutionContext::test_default();
1✔
984

985
        let query_processor = histogram
1✔
986
            .boxed()
1✔
987
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
988
            .await
1✔
989
            .unwrap()
1✔
990
            .query_processor()
1✔
991
            .unwrap()
1✔
992
            .json_vega()
1✔
993
            .unwrap();
1✔
994

995
        let result = query_processor
1✔
996
            .plot_query(
1✔
997
                PlotQueryRectangle {
1✔
998
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
999
                        .unwrap(),
1✔
1000
                    time_interval: TimeInterval::default(),
1✔
1001
                    spatial_resolution: SpatialResolution::one(),
1✔
1002
                    attributes: PlotSeriesSelection::all(),
1✔
1003
                },
1✔
1004
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
1005
            )
1✔
1006
            .await
1✔
1007
            .unwrap();
1✔
1008

1009
        assert_eq!(
1✔
1010
            result,
1✔
1011
            BarChart::new(
1✔
1012
                [("A".to_string(), 0)].into_iter().collect(),
1✔
1013
                "foo".to_string(),
1✔
1014
                "Frequency".to_string()
1✔
1015
            )
1✔
1016
            .to_vega_embeddable(true)
1✔
1017
            .unwrap()
1✔
1018
        );
1✔
1019
    }
1✔
1020

1021
    #[tokio::test]
1022
    async fn feature_collection_with_one_feature() {
1✔
1023
        let measurement = Measurement::classification(
1✔
1024
            "foo".to_string(),
1✔
1025
            [(5, "A".to_string())].into_iter().collect(),
1✔
1026
        );
1027

1028
        let vector_source = MockFeatureCollectionSource::with_collections_and_measurements(
1✔
1029
            vec![
1✔
1030
                DataCollection::from_slices(
1✔
1031
                    &[] as &[NoGeometry],
1✔
1032
                    &[TimeInterval::default()],
1✔
1033
                    &[("foo", FeatureData::Float(vec![5.0]))],
1✔
1034
                )
1035
                .unwrap(),
1✔
1036
            ],
1037
            [("foo".to_string(), measurement)].into_iter().collect(),
1✔
1038
        )
1039
        .boxed();
1✔
1040

1041
        let histogram = ClassHistogram {
1✔
1042
            params: ClassHistogramParams {
1✔
1043
                column_name: Some("foo".to_string()),
1✔
1044
            },
1✔
1045
            sources: vector_source.into(),
1✔
1046
        };
1✔
1047

1048
        let execution_context = MockExecutionContext::test_default();
1✔
1049

1050
        let query_processor = histogram
1✔
1051
            .boxed()
1✔
1052
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
1053
            .await
1✔
1054
            .unwrap()
1✔
1055
            .query_processor()
1✔
1056
            .unwrap()
1✔
1057
            .json_vega()
1✔
1058
            .unwrap();
1✔
1059

1060
        let result = query_processor
1✔
1061
            .plot_query(
1✔
1062
                PlotQueryRectangle {
1✔
1063
                    spatial_bounds: BoundingBox2D::new((-180., -90.).into(), (180., 90.).into())
1✔
1064
                        .unwrap(),
1✔
1065
                    time_interval: TimeInterval::default(),
1✔
1066
                    spatial_resolution: SpatialResolution::one(),
1✔
1067
                    attributes: PlotSeriesSelection::all(),
1✔
1068
                },
1✔
1069
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
1070
            )
1✔
1071
            .await
1✔
1072
            .unwrap();
1✔
1073

1074
        assert_eq!(
1✔
1075
            result,
1✔
1076
            BarChart::new(
1✔
1077
                [("A".to_string(), 1)].into_iter().collect(),
1✔
1078
                "foo".to_string(),
1✔
1079
                "Frequency".to_string()
1✔
1080
            )
1✔
1081
            .to_vega_embeddable(true)
1✔
1082
            .unwrap()
1✔
1083
        );
1✔
1084
    }
1✔
1085

1086
    #[tokio::test]
1087
    async fn single_value_raster_stream() {
1✔
1088
        let tile_size_in_pixels = [3, 2].into();
1✔
1089
        let tiling_specification = TilingSpecification {
1✔
1090
            origin_coordinate: [0.0, 0.0].into(),
1✔
1091
            tile_size_in_pixels,
1✔
1092
        };
1✔
1093
        let execution_context = MockExecutionContext::new_with_tiling_spec(tiling_specification);
1✔
1094

1095
        let measurement = Measurement::classification(
1✔
1096
            "foo".to_string(),
1✔
1097
            [(4, "D".to_string())].into_iter().collect(),
1✔
1098
        );
1099

1100
        let histogram = ClassHistogram {
1✔
1101
            params: ClassHistogramParams { column_name: None },
1✔
1102
            sources: MockRasterSource {
1✔
1103
                params: MockRasterSourceParams {
1✔
1104
                    data: vec![RasterTile2D::new_with_tile_info(
1✔
1105
                        TimeInterval::default(),
1✔
1106
                        TileInformation {
1✔
1107
                            global_geo_transform: TestDefault::test_default(),
1✔
1108
                            global_tile_position: [0, 0].into(),
1✔
1109
                            tile_size_in_pixels,
1✔
1110
                        },
1✔
1111
                        0,
1✔
1112
                        Grid2D::new(tile_size_in_pixels, vec![4; 6]).unwrap().into(),
1✔
1113
                        CacheHint::default(),
1✔
1114
                    )],
1✔
1115
                    result_descriptor: RasterResultDescriptor {
1✔
1116
                        data_type: RasterDataType::U8,
1✔
1117
                        spatial_reference: SpatialReference::epsg_4326().into(),
1✔
1118
                        time: None,
1✔
1119
                        bbox: None,
1✔
1120
                        resolution: None,
1✔
1121
                        bands: RasterBandDescriptors::new(vec![RasterBandDescriptor::new(
1✔
1122
                            "band".into(),
1✔
1123
                            measurement,
1✔
1124
                        )])
1✔
1125
                        .unwrap(),
1✔
1126
                    },
1✔
1127
                },
1✔
1128
            }
1✔
1129
            .boxed()
1✔
1130
            .into(),
1✔
1131
        };
1✔
1132

1133
        let query_processor = histogram
1✔
1134
            .boxed()
1✔
1135
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1✔
1136
            .await
1✔
1137
            .unwrap()
1✔
1138
            .query_processor()
1✔
1139
            .unwrap()
1✔
1140
            .json_vega()
1✔
1141
            .unwrap();
1✔
1142

1143
        let result = query_processor
1✔
1144
            .plot_query(
1✔
1145
                PlotQueryRectangle {
1✔
1146
                    spatial_bounds: BoundingBox2D::new((0., -3.).into(), (2., 0.).into()).unwrap(),
1✔
1147
                    time_interval: TimeInterval::new_instant(DateTime::new_utc(
1✔
1148
                        2013, 12, 1, 12, 0, 0,
1✔
1149
                    ))
1✔
1150
                    .unwrap(),
1✔
1151
                    spatial_resolution: SpatialResolution::one(),
1✔
1152
                    attributes: PlotSeriesSelection::all(),
1✔
1153
                },
1✔
1154
                &MockQueryContext::new(ChunkByteSize::MIN),
1✔
1155
            )
1✔
1156
            .await
1✔
1157
            .unwrap();
1✔
1158

1159
        assert_eq!(
1✔
1160
            result,
1✔
1161
            BarChart::new(
1✔
1162
                [("D".to_string(), 6)].into_iter().collect(),
1✔
1163
                "foo".to_string(),
1✔
1164
                "Frequency".to_string()
1✔
1165
            )
1✔
1166
            .to_vega_embeddable(true)
1✔
1167
            .unwrap()
1✔
1168
        );
1✔
1169
    }
1✔
1170
}
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