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

geo-engine / geoengine / 19148930607

06 Nov 2025 08:28PM UTC coverage: 88.827%. First build
19148930607

Pull #1083

github

web-flow
Merge 287fd2af8 into 113de40ca
Pull Request #1083: feat: new gdal source workflow optimization

6168 of 7008 new or added lines in 71 files covered. (88.01%)

116144 of 130753 relevant lines covered (88.83%)

496539.53 hits per line

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

96.57
/operators/src/plot/scatter_plot.rs
1
use async_trait::async_trait;
2
use futures::StreamExt;
3
use serde::{Deserialize, Serialize};
4

5
use geoengine_datatypes::collections::FeatureCollectionInfos;
6
use geoengine_datatypes::plots::{Histogram2D, HistogramDimension, Plot, PlotData};
7

8
use crate::engine::{
9
    CanonicOperatorName, ExecutionContext, InitializedPlotOperator, InitializedSources,
10
    InitializedVectorOperator, Operator, OperatorName, PlotOperator, PlotQueryProcessor,
11
    PlotResultDescriptor, QueryContext, QueryProcessor, SingleVectorSource,
12
    TypedPlotQueryProcessor, TypedVectorQueryProcessor, WorkflowOperatorPath,
13
};
14
use crate::error::Error;
15
use crate::optimization::OptimizationError;
16
use crate::util::Result;
17
use geoengine_datatypes::primitives::{
18
    ColumnSelection, Coordinate2D, PlotQueryRectangle, SpatialResolution,
19
};
20

21
pub const SCATTERPLOT_OPERATOR_NAME: &str = "ScatterPlot";
22

23
/// The maximum number of elements for a scatter plot
24
const SCATTER_PLOT_THRESHOLD: usize = 500;
25

26
/// The number of elements to process at once (i.e., without switching from scatter-plot to histogram)
27
const BATCH_SIZE: usize = 1000;
28

29
/// The maximum number of elements before we turn the collector into a histogram.
30
/// At this point, the bounds of the histogram are fixed (i.e., further values exceeding
31
/// the min/max seen so far are ignored)
32
const COLLECTOR_TO_HISTOGRAM_THRESHOLD: usize = BATCH_SIZE * 10;
33

34
/// A scatter plot about two attributes of a vector dataset. If the
35
/// dataset contains more then `SCATTER_PLOT_THRESHOLD` elements, this
36
/// operator creates a 2D histogram.
37
pub type ScatterPlot = Operator<ScatterPlotParams, SingleVectorSource>;
38

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

43
/// The parameter spec for `ScatterPlot`
44
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45
#[serde(rename_all = "camelCase")]
46
pub struct ScatterPlotParams {
47
    /// Name of the (numeric) attribute for the x-axis.
48
    pub column_x: String,
49
    /// Name of the (numeric) attribute for the y-axis.
50
    pub column_y: String,
51
}
52

53
#[typetag::serde]
×
54
#[async_trait]
55
impl PlotOperator for ScatterPlot {
56
    async fn _initialize(
57
        self: Box<Self>,
58
        path: WorkflowOperatorPath,
59
        context: &dyn ExecutionContext,
60
    ) -> Result<Box<dyn InitializedPlotOperator>> {
10 ✔
61
        let name = CanonicOperatorName::from(&self);
62

63
        let initialized_sources = self
64
            .sources
65
            .initialize_sources(path.clone(), context)
66
            .await?;
67
        let source = initialized_sources.vector;
68
        for cn in [&self.params.column_x, &self.params.column_y] {
69
            match source.result_descriptor().column_data_type(cn.as_str()) {
70
                Some(column) if !column.is_numeric() => {
71
                    return Err(Error::InvalidOperatorSpec {
72
                        reason: format!("Column '{cn}' is not numeric."),
73
                    });
74
                }
75
                Some(_) => {
76
                    // OK
77
                }
78
                None => {
79
                    return Err(Error::ColumnDoesNotExist { column: cn.clone() });
80
                }
81
            }
82
        }
83

84
        let in_desc = source.result_descriptor().clone();
85

86
        Ok(InitializedScatterPlot::new(name, in_desc.into(), self.params, source).boxed())
87
    }
10 ✔
88

89
    span_fn!(ScatterPlot);
90
}
91

92
/// The initialization of `Histogram`
93
pub struct InitializedScatterPlot<Op> {
94
    name: CanonicOperatorName,
95
    result_descriptor: PlotResultDescriptor,
96
    column_x: String,
97
    column_y: String,
98
    source: Op,
99
}
100

101
impl<Op> InitializedScatterPlot<Op> {
102
    pub fn new(
6 ✔
103
        name: CanonicOperatorName,
6 ✔
104
        result_descriptor: PlotResultDescriptor,
6 ✔
105
        params: ScatterPlotParams,
6 ✔
106
        source: Op,
6 ✔
107
    ) -> Self {
6 ✔
108
        Self {
6 ✔
109
            name,
6 ✔
110
            result_descriptor,
6 ✔
111
            column_x: params.column_x,
6 ✔
112
            column_y: params.column_y,
6 ✔
113
            source,
6 ✔
114
        }
6 ✔
115
    }
6 ✔
116
}
117
impl InitializedPlotOperator for InitializedScatterPlot<Box<dyn InitializedVectorOperator>> {
118
    fn result_descriptor(&self) -> &PlotResultDescriptor {
×
119
        &self.result_descriptor
×
120
    }
×
121

122
    fn query_processor(&self) -> Result<TypedPlotQueryProcessor> {
6 ✔
123
        let processor = ScatterPlotQueryProcessor {
6 ✔
124
            input: self.source.query_processor()?,
6 ✔
125
            column_x: self.column_x.clone(),
6 ✔
126
            column_y: self.column_y.clone(),
6 ✔
127
        };
128

129
        Ok(TypedPlotQueryProcessor::JsonVega(processor.boxed()))
6 ✔
130
    }
6 ✔
131

132
    fn canonic_name(&self) -> CanonicOperatorName {
×
133
        self.name.clone()
×
134
    }
×
135

NEW
136
    fn optimize(
×
NEW
137
        &self,
×
NEW
138
        target_resolution: SpatialResolution,
×
NEW
139
    ) -> Result<Box<dyn PlotOperator>, OptimizationError> {
×
140
        Ok(ScatterPlot {
NEW
141
            params: ScatterPlotParams {
×
NEW
142
                column_x: self.column_x.clone(),
×
NEW
143
                column_y: self.column_y.clone(),
×
NEW
144
            },
×
145
            sources: SingleVectorSource {
NEW
146
                vector: self.source.optimize(target_resolution)?,
×
147
            },
148
        }
NEW
149
        .boxed())
×
NEW
150
    }
×
151
}
152

153
/// A query processor that calculates the scatter plot about its vector input.
154
pub struct ScatterPlotQueryProcessor {
155
    input: TypedVectorQueryProcessor,
156
    column_x: String,
157
    column_y: String,
158
}
159

160
#[async_trait]
161
impl PlotQueryProcessor for ScatterPlotQueryProcessor {
162
    type OutputFormat = PlotData;
163

164
    fn plot_type(&self) -> &'static str {
×
165
        SCATTERPLOT_OPERATOR_NAME
×
166
    }
×
167

168
    async fn plot_query<'p>(
169
        &'p self,
170
        query: PlotQueryRectangle,
171
        ctx: &'p dyn QueryContext,
172
    ) -> Result<Self::OutputFormat> {
6 ✔
173
        let mut collector =
174
            CollectorKind::Values(Collector::new(self.column_x.clone(), self.column_y.clone()));
175

176
        let query = query.select_attributes(ColumnSelection::all());
177

178
        call_on_generic_vector_processor!(&self.input, processor => {
179
            let mut query = processor.query(query, ctx).await?;
180
            while let Some(collection) = query.next().await {
181
                let collection = collection?;
182

183
                let data_x = collection.data(&self.column_x).expect("checked in param");
184
                let data_y = collection.data(&self.column_y).expect("checked in param");
185

186
                let valid_points = data_x.float_options_iter().zip(data_y.float_options_iter()).filter_map(|(a,b)| match (a,b) {
18,717 ✔
187
                    (Some(x),Some(y)) if x.is_finite() && y.is_finite() => Some(Coordinate2D::new(x,y)),
18,714 ✔
188
                    _ => None
6 ✔
189
                });
18,717 ✔
190

191
                for chunk in &itertools::Itertools::chunks(valid_points, BATCH_SIZE) {
192
                    collector.add_batch( chunk )?;
193
                }
194
            }
195
        });
196
        Ok(collector.into_plot()?.to_vega_embeddable(false)?)
197
    }
6 ✔
198
}
199

200
struct Collector {
201
    elements: Vec<Coordinate2D>,
202
    column_x: String,
203
    column_y: String,
204
    bounds_x: (f64, f64),
205
    bounds_y: (f64, f64),
206
}
207

208
impl Collector {
209
    fn new(column_x: String, column_y: String) -> Self {
12 ✔
210
        Collector {
12 ✔
211
            column_x,
12 ✔
212
            column_y,
12 ✔
213
            elements: Vec::with_capacity(SCATTER_PLOT_THRESHOLD),
12 ✔
214
            bounds_x: (f64::INFINITY, f64::NEG_INFINITY),
12 ✔
215
            bounds_y: (f64::INFINITY, f64::NEG_INFINITY),
12 ✔
216
        }
12 ✔
217
    }
12 ✔
218

219
    fn element_count(&self) -> usize {
35 ✔
220
        self.elements.len()
35 ✔
221
    }
35 ✔
222

223
    fn add_batch(&mut self, values: impl Iterator<Item = Coordinate2D>) {
21 ✔
224
        for v in values {
42,985 ✔
225
            self.add(v);
42,964 ✔
226
        }
42,964 ✔
227
    }
21 ✔
228

229
    fn add(&mut self, value: Coordinate2D) {
42,964 ✔
230
        if value.x.is_finite() && value.y.is_finite() {
42,964 ✔
231
            self.bounds_x.0 = std::cmp::min_by(self.bounds_x.0, value.x, |a, b| {
42,964 ✔
232
                a.partial_cmp(b).expect("checked")
42,964 ✔
233
            });
42,964 ✔
234
            self.bounds_x.1 = std::cmp::max_by(self.bounds_x.1, value.x, |a, b| {
42,964 ✔
235
                a.partial_cmp(b).expect("checked")
42,964 ✔
236
            });
42,964 ✔
237
            self.bounds_y.0 = std::cmp::min_by(self.bounds_y.0, value.y, |a, b| {
42,964 ✔
238
                a.partial_cmp(b).expect("checked")
42,964 ✔
239
            });
42,964 ✔
240
            self.bounds_y.1 = std::cmp::max_by(self.bounds_y.1, value.y, |a, b| {
42,964 ✔
241
                a.partial_cmp(b).expect("checked")
42,964 ✔
242
            });
42,964 ✔
243
            self.elements.push(value);
42,964 ✔
244
        }
×
245
    }
42,964 ✔
246
}
247

248
enum CollectorKind {
249
    Values(Collector),
250
    Histogram(Histogram2D),
251
}
252

253
impl CollectorKind {
254
    fn histogram_from_collector(value: &Collector) -> Result<Histogram2D> {
6 ✔
255
        let bucket_count = std::cmp::min(100, f64::sqrt(value.element_count() as f64) as usize);
6 ✔
256

257
        let dim_x = HistogramDimension::new(
6 ✔
258
            value.column_x.clone(),
6 ✔
259
            value.bounds_x.0,
6 ✔
260
            value.bounds_x.1,
6 ✔
261
            bucket_count,
6 ✔
262
        )?;
×
263
        let dim_y = HistogramDimension::new(
6 ✔
264
            value.column_y.clone(),
6 ✔
265
            value.bounds_y.0,
6 ✔
266
            value.bounds_y.1,
6 ✔
267
            bucket_count,
6 ✔
268
        )?;
×
269

270
        let mut result = Histogram2D::new(dim_x, dim_y);
6 ✔
271
        result.update_batch(value.elements.iter().copied());
6 ✔
272
        Ok(result)
6 ✔
273
    }
6 ✔
274

275
    fn add_batch(&mut self, values: impl Iterator<Item = Coordinate2D>) -> Result<()> {
30 ✔
276
        match self {
30 ✔
277
            Self::Values(c) => {
21 ✔
278
                c.add_batch(values);
21 ✔
279
                if c.element_count() > COLLECTOR_TO_HISTOGRAM_THRESHOLD {
21 ✔
280
                    *self = Self::Histogram(Self::histogram_from_collector(c)?);
4 ✔
281
                }
17 ✔
282
            }
283
            Self::Histogram(h) => {
9 ✔
284
                h.update_batch(values);
9 ✔
285
            }
9 ✔
286
        }
287
        Ok(())
30 ✔
288
    }
30 ✔
289

290
    fn into_plot(self) -> Result<Box<dyn Plot>> {
12 ✔
291
        match self {
8 ✔
292
            Self::Histogram(h) => Ok(Box::new(h)),
4 ✔
293
            Self::Values(v) if v.element_count() <= SCATTER_PLOT_THRESHOLD => Ok(Box::new(
8 ✔
294
                geoengine_datatypes::plots::ScatterPlot::new_with_data(
6 ✔
295
                    v.column_x, v.column_y, v.elements,
6 ✔
296
                ),
6 ✔
297
            )),
6 ✔
298
            Self::Values(v) => Ok(Box::new(Self::histogram_from_collector(&v)?)),
2 ✔
299
        }
300
    }
12 ✔
301
}
302

303
#[cfg(test)]
304
mod tests {
305
    use crate::engine::{ChunkByteSize, MockExecutionContext, VectorOperator};
306
    use crate::mock::MockFeatureCollectionSource;
307
    use geoengine_datatypes::primitives::{
308
        BoundingBox2D, FeatureData, NoGeometry, PlotQueryRectangle, PlotSeriesSelection,
309
        TimeInterval,
310
    };
311
    use geoengine_datatypes::util::test::TestDefault;
312
    use geoengine_datatypes::{collections::DataCollection, primitives::MultiPoint};
313
    use serde_json::json;
314

315
    use super::*;
316

317
    #[test]
318
    fn serialization() {
1 ✔
319
        let scatter_plot = ScatterPlot {
1 ✔
320
            params: ScatterPlotParams {
1 ✔
321
                column_x: "foo".to_owned(),
1 ✔
322
                column_y: "bar".to_owned(),
1 ✔
323
            },
1 ✔
324
            sources: MockFeatureCollectionSource::<MultiPoint>::multiple(vec![])
1 ✔
325
                .boxed()
1 ✔
326
                .into(),
1 ✔
327
        };
1 ✔
328

329
        let serialized = json!({
1 ✔
330
            "type": "ScatterPlot",
1 ✔
331
            "params": {
1 ✔
332
                "columnX": "foo",
1 ✔
333
                "columnY": "bar",
1 ✔
334
            },
335
            "sources": {
1 ✔
336
                "vector": {
1 ✔
337
                    "type": "MockFeatureCollectionSourceMultiPoint",
1 ✔
338
                    "params": {
1 ✔
339
                        "collections": [],
1 ✔
340
                        "spatialReference": "EPSG:4326",
1 ✔
341
                        "measurements": {},
1 ✔
342
                    }
343
                }
344
            }
345
        })
346
        .to_string();
1 ✔
347

348
        let deserialized: ScatterPlot = serde_json::from_str(&serialized).unwrap();
1 ✔
349

350
        assert_eq!(deserialized.params, scatter_plot.params);
1 ✔
351
    }
1 ✔
352

353
    #[tokio::test]
354
    async fn vector_data() {
1 ✔
355
        let vector_source = MockFeatureCollectionSource::multiple(vec![
1 ✔
356
            DataCollection::from_slices(
1 ✔
357
                &[] as &[NoGeometry],
1 ✔
358
                &[TimeInterval::default(); 4],
1 ✔
359
                &[
1 ✔
360
                    ("foo", FeatureData::Int(vec![1, 2, 3, 4])),
1 ✔
361
                    ("bar", FeatureData::Int(vec![1, 2, 3, 4])),
1 ✔
362
                ],
1 ✔
363
            )
364
            .unwrap(),
1 ✔
365
            DataCollection::from_slices(
1 ✔
366
                &[] as &[NoGeometry],
1 ✔
367
                &[TimeInterval::default(); 4],
1 ✔
368
                &[
1 ✔
369
                    ("foo", FeatureData::Int(vec![5, 6, 7, 8])),
1 ✔
370
                    ("bar", FeatureData::Int(vec![5, 6, 7, 8])),
1 ✔
371
                ],
1 ✔
372
            )
373
            .unwrap(),
1 ✔
374
        ])
375
        .boxed();
1 ✔
376

377
        let box_plot = ScatterPlot {
1 ✔
378
            params: ScatterPlotParams {
1 ✔
379
                column_x: "foo".to_string(),
1 ✔
380
                column_y: "bar".to_string(),
1 ✔
381
            },
1 ✔
382
            sources: vector_source.into(),
1 ✔
383
        };
1 ✔
384

385
        let execution_context = MockExecutionContext::test_default();
1 ✔
386

387
        let query_processor = box_plot
1 ✔
388
            .boxed()
1 ✔
389
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
390
            .await
1 ✔
391
            .unwrap()
1 ✔
392
            .query_processor()
1 ✔
393
            .unwrap()
1 ✔
394
            .json_vega()
1 ✔
395
            .unwrap();
1 ✔
396

397
        let result = query_processor
1 ✔
398
            .plot_query(
1 ✔
399
                PlotQueryRectangle::new(
1 ✔
400
                    BoundingBox2D::new((-180., -90.).into(), (180., 90.).into()).unwrap(),
1 ✔
401
                    TimeInterval::default(),
1 ✔
402
                    PlotSeriesSelection::all(),
1 ✔
403
                ),
1 ✔
404
                &execution_context.mock_query_context(ChunkByteSize::MIN),
1 ✔
405
            )
1 ✔
406
            .await
1 ✔
407
            .unwrap();
1 ✔
408

409
        let mut expected =
1 ✔
410
            geoengine_datatypes::plots::ScatterPlot::new("foo".to_string(), "bar".to_string());
1 ✔
411
        for i in 1..=8 {
9 ✔
412
            expected.update(Coordinate2D::new(f64::from(i), f64::from(i)));
8 ✔
413
        }
8 ✔
414
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), result);
1 ✔
415
    }
1 ✔
416

417
    #[tokio::test]
418
    async fn vector_data_with_nulls_and_nan() {
1 ✔
419
        let vector_source = MockFeatureCollectionSource::multiple(vec![
1 ✔
420
            DataCollection::from_slices(
1 ✔
421
                &[] as &[NoGeometry],
1 ✔
422
                &[TimeInterval::default(); 7],
1 ✔
423
                &[
1 ✔
424
                    (
1 ✔
425
                        "foo",
1 ✔
426
                        FeatureData::NullableFloat(vec![
1 ✔
427
                            Some(1.0),
1 ✔
428
                            None,
1 ✔
429
                            Some(3.0),
1 ✔
430
                            None,
1 ✔
431
                            Some(f64::NAN),
1 ✔
432
                            Some(6.0),
1 ✔
433
                            Some(f64::NAN),
1 ✔
434
                        ]),
1 ✔
435
                    ),
1 ✔
436
                    (
1 ✔
437
                        "bar",
1 ✔
438
                        FeatureData::NullableFloat(vec![
1 ✔
439
                            Some(1.0),
1 ✔
440
                            Some(2.0),
1 ✔
441
                            None,
1 ✔
442
                            None,
1 ✔
443
                            Some(5.0),
1 ✔
444
                            Some(f64::NAN),
1 ✔
445
                            Some(f64::NAN),
1 ✔
446
                        ]),
1 ✔
447
                    ),
1 ✔
448
                ],
1 ✔
449
            )
450
            .unwrap(),
1 ✔
451
        ])
452
        .boxed();
1 ✔
453

454
        let box_plot = ScatterPlot {
1 ✔
455
            params: ScatterPlotParams {
1 ✔
456
                column_x: "foo".to_string(),
1 ✔
457
                column_y: "bar".to_string(),
1 ✔
458
            },
1 ✔
459
            sources: vector_source.into(),
1 ✔
460
        };
1 ✔
461

462
        let execution_context = MockExecutionContext::test_default();
1 ✔
463

464
        let query_processor = box_plot
1 ✔
465
            .boxed()
1 ✔
466
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
467
            .await
1 ✔
468
            .unwrap()
1 ✔
469
            .query_processor()
1 ✔
470
            .unwrap()
1 ✔
471
            .json_vega()
1 ✔
472
            .unwrap();
1 ✔
473

474
        let result = query_processor
1 ✔
475
            .plot_query(
1 ✔
476
                PlotQueryRectangle::new(
1 ✔
477
                    BoundingBox2D::new((-180., -90.).into(), (180., 90.).into()).unwrap(),
1 ✔
478
                    TimeInterval::default(),
1 ✔
479
                    PlotSeriesSelection::all(),
1 ✔
480
                ),
1 ✔
481
                &execution_context.mock_query_context(ChunkByteSize::MIN),
1 ✔
482
            )
1 ✔
483
            .await
1 ✔
484
            .unwrap();
1 ✔
485

486
        let mut expected =
1 ✔
487
            geoengine_datatypes::plots::ScatterPlot::new("foo".to_string(), "bar".to_string());
1 ✔
488
        expected.update(Coordinate2D::new(1.0, 1.0));
1 ✔
489
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), result);
1 ✔
490
    }
1 ✔
491

492
    #[tokio::test]
493
    async fn vector_data_text_column_x() {
1 ✔
494
        let vector_source = MockFeatureCollectionSource::single(
1 ✔
495
            DataCollection::from_slices(
1 ✔
496
                &[] as &[NoGeometry],
1 ✔
497
                &[TimeInterval::default(); 1],
1 ✔
498
                &[
1 ✔
499
                    ("foo", FeatureData::Text(vec!["test".to_string()])),
1 ✔
500
                    ("bar", FeatureData::Int(vec![64])),
1 ✔
501
                ],
1 ✔
502
            )
503
            .unwrap(),
1 ✔
504
        )
505
        .boxed();
1 ✔
506

507
        let box_plot = ScatterPlot {
1 ✔
508
            params: ScatterPlotParams {
1 ✔
509
                column_x: "foo".to_string(),
1 ✔
510
                column_y: "bar".to_string(),
1 ✔
511
            },
1 ✔
512
            sources: vector_source.into(),
1 ✔
513
        };
1 ✔
514

515
        let execution_context = MockExecutionContext::test_default();
1 ✔
516

517
        let init = box_plot
1 ✔
518
            .boxed()
1 ✔
519
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
520
            .await;
1 ✔
521

522
        assert!(init.is_err());
1 ✔
523
    }
1 ✔
524

525
    #[tokio::test]
526
    async fn vector_data_text_column_y() {
1 ✔
527
        let vector_source = MockFeatureCollectionSource::single(
1 ✔
528
            DataCollection::from_slices(
1 ✔
529
                &[] as &[NoGeometry],
1 ✔
530
                &[TimeInterval::default(); 1],
1 ✔
531
                &[
1 ✔
532
                    ("foo", FeatureData::Text(vec!["test".to_string()])),
1 ✔
533
                    ("bar", FeatureData::Int(vec![64])),
1 ✔
534
                ],
1 ✔
535
            )
536
            .unwrap(),
1 ✔
537
        )
538
        .boxed();
1 ✔
539

540
        let box_plot = ScatterPlot {
1 ✔
541
            params: ScatterPlotParams {
1 ✔
542
                column_x: "bar".to_string(),
1 ✔
543
                column_y: "foo".to_string(),
1 ✔
544
            },
1 ✔
545
            sources: vector_source.into(),
1 ✔
546
        };
1 ✔
547

548
        let execution_context = MockExecutionContext::test_default();
1 ✔
549

550
        let init = box_plot
1 ✔
551
            .boxed()
1 ✔
552
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
553
            .await;
1 ✔
554

555
        assert!(init.is_err());
1 ✔
556
    }
1 ✔
557

558
    #[tokio::test]
559
    async fn vector_data_missing_column_x() {
1 ✔
560
        let vector_source = MockFeatureCollectionSource::single(
1 ✔
561
            DataCollection::from_slices(
1 ✔
562
                &[] as &[NoGeometry],
1 ✔
563
                &[TimeInterval::default(); 1],
1 ✔
564
                &[
1 ✔
565
                    ("foo", FeatureData::Text(vec!["test".to_string()])),
1 ✔
566
                    ("bar", FeatureData::Int(vec![64])),
1 ✔
567
                ],
1 ✔
568
            )
569
            .unwrap(),
1 ✔
570
        )
571
        .boxed();
1 ✔
572

573
        let box_plot = ScatterPlot {
1 ✔
574
            params: ScatterPlotParams {
1 ✔
575
                column_x: "fo".to_string(),
1 ✔
576
                column_y: "bar".to_string(),
1 ✔
577
            },
1 ✔
578
            sources: vector_source.into(),
1 ✔
579
        };
1 ✔
580

581
        let execution_context = MockExecutionContext::test_default();
1 ✔
582

583
        let init = box_plot
1 ✔
584
            .boxed()
1 ✔
585
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
586
            .await;
1 ✔
587

588
        assert!(init.is_err());
1 ✔
589
    }
1 ✔
590

591
    #[tokio::test]
592
    async fn vector_data_missing_column_y() {
1 ✔
593
        let vector_source = MockFeatureCollectionSource::single(
1 ✔
594
            DataCollection::from_slices(
1 ✔
595
                &[] as &[NoGeometry],
1 ✔
596
                &[TimeInterval::default(); 1],
1 ✔
597
                &[
1 ✔
598
                    ("foo", FeatureData::Text(vec!["test".to_string()])),
1 ✔
599
                    ("bar", FeatureData::Int(vec![64])),
1 ✔
600
                ],
1 ✔
601
            )
602
            .unwrap(),
1 ✔
603
        )
604
        .boxed();
1 ✔
605

606
        let box_plot = ScatterPlot {
1 ✔
607
            params: ScatterPlotParams {
1 ✔
608
                column_x: "foo".to_string(),
1 ✔
609
                column_y: "ba".to_string(),
1 ✔
610
            },
1 ✔
611
            sources: vector_source.into(),
1 ✔
612
        };
1 ✔
613

614
        let execution_context = MockExecutionContext::test_default();
1 ✔
615

616
        let init = box_plot
1 ✔
617
            .boxed()
1 ✔
618
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
619
            .await;
1 ✔
620

621
        assert!(init.is_err());
1 ✔
622
    }
1 ✔
623

624
    #[tokio::test]
625
    async fn vector_data_single_feature() {
1 ✔
626
        let vector_source = MockFeatureCollectionSource::multiple(vec![
1 ✔
627
            DataCollection::from_slices(
1 ✔
628
                &[] as &[NoGeometry],
1 ✔
629
                &[TimeInterval::default(); 1],
1 ✔
630
                &[
1 ✔
631
                    ("foo", FeatureData::Int(vec![1])),
1 ✔
632
                    ("bar", FeatureData::Int(vec![1])),
1 ✔
633
                ],
1 ✔
634
            )
635
            .unwrap(),
1 ✔
636
        ])
637
        .boxed();
1 ✔
638

639
        let box_plot = ScatterPlot {
1 ✔
640
            params: ScatterPlotParams {
1 ✔
641
                column_x: "foo".to_string(),
1 ✔
642
                column_y: "bar".to_string(),
1 ✔
643
            },
1 ✔
644
            sources: vector_source.into(),
1 ✔
645
        };
1 ✔
646

647
        let execution_context = MockExecutionContext::test_default();
1 ✔
648

649
        let query_processor = box_plot
1 ✔
650
            .boxed()
1 ✔
651
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
652
            .await
1 ✔
653
            .unwrap()
1 ✔
654
            .query_processor()
1 ✔
655
            .unwrap()
1 ✔
656
            .json_vega()
1 ✔
657
            .unwrap();
1 ✔
658

659
        let result = query_processor
1 ✔
660
            .plot_query(
1 ✔
661
                PlotQueryRectangle::new(
1 ✔
662
                    BoundingBox2D::new((-180., -90.).into(), (180., 90.).into()).unwrap(),
1 ✔
663
                    TimeInterval::default(),
1 ✔
664
                    PlotSeriesSelection::all(),
1 ✔
665
                ),
1 ✔
666
                &execution_context.mock_query_context(ChunkByteSize::MIN),
1 ✔
667
            )
1 ✔
668
            .await
1 ✔
669
            .unwrap();
1 ✔
670

671
        let mut expected =
1 ✔
672
            geoengine_datatypes::plots::ScatterPlot::new("foo".to_string(), "bar".to_string());
1 ✔
673
        expected.update(Coordinate2D::new(1.0, 1.0));
1 ✔
674
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), result);
1 ✔
675
    }
1 ✔
676

677
    #[tokio::test]
678
    async fn vector_data_empty() {
1 ✔
679
        let vector_source = MockFeatureCollectionSource::multiple(vec![
1 ✔
680
            DataCollection::from_slices(
1 ✔
681
                &[] as &[NoGeometry],
1 ✔
682
                &[] as &[TimeInterval],
1 ✔
683
                &[
1 ✔
684
                    ("foo", FeatureData::Int(vec![])),
1 ✔
685
                    ("bar", FeatureData::Int(vec![])),
1 ✔
686
                ],
1 ✔
687
            )
688
            .unwrap(),
1 ✔
689
        ])
690
        .boxed();
1 ✔
691

692
        let box_plot = ScatterPlot {
1 ✔
693
            params: ScatterPlotParams {
1 ✔
694
                column_x: "foo".to_string(),
1 ✔
695
                column_y: "bar".to_string(),
1 ✔
696
            },
1 ✔
697
            sources: vector_source.into(),
1 ✔
698
        };
1 ✔
699

700
        let execution_context = MockExecutionContext::test_default();
1 ✔
701

702
        let query_processor = box_plot
1 ✔
703
            .boxed()
1 ✔
704
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
705
            .await
1 ✔
706
            .unwrap()
1 ✔
707
            .query_processor()
1 ✔
708
            .unwrap()
1 ✔
709
            .json_vega()
1 ✔
710
            .unwrap();
1 ✔
711

712
        let result = query_processor
1 ✔
713
            .plot_query(
1 ✔
714
                PlotQueryRectangle::new(
1 ✔
715
                    BoundingBox2D::new((-180., -90.).into(), (180., 90.).into()).unwrap(),
1 ✔
716
                    TimeInterval::default(),
1 ✔
717
                    PlotSeriesSelection::all(),
1 ✔
718
                ),
1 ✔
719
                &execution_context.mock_query_context(ChunkByteSize::MIN),
1 ✔
720
            )
1 ✔
721
            .await
1 ✔
722
            .unwrap();
1 ✔
723

724
        let expected =
1 ✔
725
            geoengine_datatypes::plots::ScatterPlot::new("foo".to_string(), "bar".to_string());
1 ✔
726
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), result);
1 ✔
727
    }
1 ✔
728

729
    #[tokio::test]
730
    async fn to_histogram_at_end() {
1 ✔
731
        let mut values = vec![1; 700];
1 ✔
732
        values.push(2);
1 ✔
733

734
        let vector_source = MockFeatureCollectionSource::multiple(vec![
1 ✔
735
            DataCollection::from_slices(
1 ✔
736
                &[] as &[NoGeometry],
1 ✔
737
                &[TimeInterval::default(); 701],
1 ✔
738
                &[
1 ✔
739
                    ("foo", FeatureData::Int(values.clone())),
1 ✔
740
                    ("bar", FeatureData::Int(values.clone())),
1 ✔
741
                ],
1 ✔
742
            )
743
            .unwrap(),
1 ✔
744
        ])
745
        .boxed();
1 ✔
746

747
        let box_plot = ScatterPlot {
1 ✔
748
            params: ScatterPlotParams {
1 ✔
749
                column_x: "foo".to_string(),
1 ✔
750
                column_y: "bar".to_string(),
1 ✔
751
            },
1 ✔
752
            sources: vector_source.into(),
1 ✔
753
        };
1 ✔
754

755
        let execution_context = MockExecutionContext::test_default();
1 ✔
756

757
        let query_processor = box_plot
1 ✔
758
            .boxed()
1 ✔
759
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
760
            .await
1 ✔
761
            .unwrap()
1 ✔
762
            .query_processor()
1 ✔
763
            .unwrap()
1 ✔
764
            .json_vega()
1 ✔
765
            .unwrap();
1 ✔
766

767
        let result = query_processor
1 ✔
768
            .plot_query(
1 ✔
769
                PlotQueryRectangle::new(
1 ✔
770
                    BoundingBox2D::new((-180., -90.).into(), (180., 90.).into()).unwrap(),
1 ✔
771
                    TimeInterval::default(),
1 ✔
772
                    PlotSeriesSelection::all(),
1 ✔
773
                ),
1 ✔
774
                &execution_context.mock_query_context(ChunkByteSize::MIN),
1 ✔
775
            )
1 ✔
776
            .await
1 ✔
777
            .unwrap();
1 ✔
778

779
        let dim_x = HistogramDimension::new("foo".to_string(), 1.0, 2.0, 26).unwrap();
1 ✔
780
        let dim_y = HistogramDimension::new("bar".to_string(), 1.0, 2.0, 26).unwrap();
1 ✔
781

782
        let mut expected = geoengine_datatypes::plots::Histogram2D::new(dim_x, dim_y);
1 ✔
783
        expected.update_batch(
1 ✔
784
            values
1 ✔
785
                .into_iter()
1 ✔
786
                .map(|x| Coordinate2D::new(x as f64, x as f64)),
701 ✔
787
        );
788
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), result);
1 ✔
789
    }
1 ✔
790

791
    #[tokio::test]
792
    async fn to_histogram_while_iterating() {
1 ✔
793
        let mut values = vec![1; 5999];
1 ✔
794
        values.push(2);
1 ✔
795

796
        let vector_source = MockFeatureCollectionSource::multiple(vec![
1 ✔
797
            DataCollection::from_slices(
1 ✔
798
                &[] as &[NoGeometry],
1 ✔
799
                &[TimeInterval::default(); 6000],
1 ✔
800
                &[
1 ✔
801
                    ("foo", FeatureData::Int(values.clone())),
1 ✔
802
                    ("bar", FeatureData::Int(values.clone())),
1 ✔
803
                ],
1 ✔
804
            )
805
            .unwrap(),
1 ✔
806
            DataCollection::from_slices(
1 ✔
807
                &[] as &[NoGeometry],
1 ✔
808
                &[TimeInterval::default(); 6000],
1 ✔
809
                &[
1 ✔
810
                    ("foo", FeatureData::Int(values.clone())),
1 ✔
811
                    ("bar", FeatureData::Int(values.clone())),
1 ✔
812
                ],
1 ✔
813
            )
814
            .unwrap(),
1 ✔
815
            DataCollection::from_slices(
1 ✔
816
                &[] as &[NoGeometry],
1 ✔
817
                &[TimeInterval::default(); 6000],
1 ✔
818
                &[
1 ✔
819
                    ("foo", FeatureData::Int(values.clone())),
1 ✔
820
                    ("bar", FeatureData::Int(values.clone())),
1 ✔
821
                ],
1 ✔
822
            )
823
            .unwrap(),
1 ✔
824
        ])
825
        .boxed();
1 ✔
826

827
        let box_plot = ScatterPlot {
1 ✔
828
            params: ScatterPlotParams {
1 ✔
829
                column_x: "foo".to_string(),
1 ✔
830
                column_y: "bar".to_string(),
1 ✔
831
            },
1 ✔
832
            sources: vector_source.into(),
1 ✔
833
        };
1 ✔
834

835
        let execution_context = MockExecutionContext::test_default();
1 ✔
836

837
        let query_processor = box_plot
1 ✔
838
            .boxed()
1 ✔
839
            .initialize(WorkflowOperatorPath::initialize_root(), &execution_context)
1 ✔
840
            .await
1 ✔
841
            .unwrap()
1 ✔
842
            .query_processor()
1 ✔
843
            .unwrap()
1 ✔
844
            .json_vega()
1 ✔
845
            .unwrap();
1 ✔
846

847
        let result = query_processor
1 ✔
848
            .plot_query(
1 ✔
849
                PlotQueryRectangle::new(
1 ✔
850
                    BoundingBox2D::new((-180., -90.).into(), (180., 90.).into()).unwrap(),
1 ✔
851
                    TimeInterval::default(),
1 ✔
852
                    PlotSeriesSelection::all(),
1 ✔
853
                ),
1 ✔
854
                &execution_context.mock_query_context(ChunkByteSize::MIN),
1 ✔
855
            )
1 ✔
856
            .await
1 ✔
857
            .unwrap();
1 ✔
858

859
        let dim_x = HistogramDimension::new("foo".to_string(), 1.0, 2.0, 100).unwrap();
1 ✔
860
        let dim_y = HistogramDimension::new("bar".to_string(), 1.0, 2.0, 100).unwrap();
1 ✔
861

862
        let mut expected = geoengine_datatypes::plots::Histogram2D::new(dim_x, dim_y);
1 ✔
863
        expected.update_batch(
1 ✔
864
            values
1 ✔
865
                .iter()
1 ✔
866
                .map(|x| Coordinate2D::new(*x as f64, *x as f64)),
6,000 ✔
867
        );
868
        expected.update_batch(
1 ✔
869
            values
1 ✔
870
                .iter()
1 ✔
871
                .map(|x| Coordinate2D::new(*x as f64, *x as f64)),
6,000 ✔
872
        );
873
        expected.update_batch(
1 ✔
874
            values
1 ✔
875
                .iter()
1 ✔
876
                .map(|x| Coordinate2D::new(*x as f64, *x as f64)),
6,000 ✔
877
        );
878
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), result);
1 ✔
879
    }
1 ✔
880

881
    #[test]
882
    fn test_collector_kind_empty() {
1 ✔
883
        let cx = "x".to_string();
1 ✔
884
        let cy = "y".to_string();
1 ✔
885

886
        let c = CollectorKind::Values(Collector::new(cx.clone(), cy.clone()));
1 ✔
887
        let res = c.into_plot().unwrap().to_vega_embeddable(false).unwrap();
1 ✔
888

889
        let expected = geoengine_datatypes::plots::ScatterPlot::new(cx, cy)
1 ✔
890
            .to_vega_embeddable(false)
1 ✔
891
            .unwrap();
1 ✔
892

893
        assert_eq!(expected, res);
1 ✔
894
    }
1 ✔
895

896
    #[test]
897
    fn test_collector_kind_scatter_plot() {
1 ✔
898
        let cx = "x".to_string();
1 ✔
899
        let cy = "y".to_string();
1 ✔
900

901
        let mut values = Vec::with_capacity(200);
1 ✔
902
        for i in 0..SCATTER_PLOT_THRESHOLD / 2 {
250 ✔
903
            values.push(Coordinate2D::new(i as f64, i as f64));
250 ✔
904
        }
250 ✔
905

906
        let mut c = CollectorKind::Values(Collector::new(cx.clone(), cy.clone()));
1 ✔
907

908
        c.add_batch(values.clone().into_iter()).unwrap();
1 ✔
909

910
        assert!(matches!(c, CollectorKind::Values(_)));
1 ✔
911

912
        let res = c.into_plot().unwrap().to_vega_embeddable(false).unwrap();
1 ✔
913

914
        let mut expected = geoengine_datatypes::plots::ScatterPlot::new(cx, cy);
1 ✔
915
        expected.update_batch(values.into_iter());
1 ✔
916

917
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), res);
1 ✔
918
    }
1 ✔
919

920
    #[test]
921
    fn test_collector_kind_histogram_end() {
1 ✔
922
        let cx = "x".to_string();
1 ✔
923
        let cy = "y".to_string();
1 ✔
924

925
        let element_count = SCATTER_PLOT_THRESHOLD * 2;
1 ✔
926

927
        let mut values = Vec::with_capacity(element_count);
1 ✔
928
        for i in 0..element_count {
1,000 ✔
929
            values.push(Coordinate2D::new(i as f64, i as f64));
1,000 ✔
930
        }
1,000 ✔
931

932
        let mut c = CollectorKind::Values(Collector::new(cx.clone(), cy.clone()));
1 ✔
933
        c.add_batch(values.clone().into_iter()).unwrap();
1 ✔
934

935
        assert!(matches!(c, CollectorKind::Values(_)));
1 ✔
936

937
        let res = c.into_plot().unwrap().to_vega_embeddable(false).unwrap();
1 ✔
938

939
        // expected
940
        let bucket_count = std::cmp::min(100, f64::sqrt(element_count as f64) as usize);
1 ✔
941
        let dimx =
1 ✔
942
            HistogramDimension::new(cx, 0.0, (element_count - 1) as f64, bucket_count).unwrap();
1 ✔
943

944
        let dimy =
1 ✔
945
            HistogramDimension::new(cy, 0.0, (element_count - 1) as f64, bucket_count).unwrap();
1 ✔
946

947
        let mut expected = geoengine_datatypes::plots::Histogram2D::new(dimx, dimy);
1 ✔
948
        expected.update_batch(values.into_iter());
1 ✔
949

950
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), res);
1 ✔
951
    }
1 ✔
952
    #[test]
953
    fn test_collector_kind_histogram_in_flight() {
1 ✔
954
        let cx = "x".to_string();
1 ✔
955
        let cy = "y".to_string();
1 ✔
956

957
        let element_count = COLLECTOR_TO_HISTOGRAM_THRESHOLD + 1;
1 ✔
958

959
        let mut values = Vec::with_capacity(element_count);
1 ✔
960
        for i in 0..element_count {
10,001 ✔
961
            values.push(Coordinate2D::new(i as f64, i as f64));
10,001 ✔
962
        }
10,001 ✔
963

964
        let mut c = CollectorKind::Values(Collector::new(cx.clone(), cy.clone()));
1 ✔
965
        c.add_batch(values.clone().into_iter()).unwrap();
1 ✔
966

967
        assert!(matches!(c, CollectorKind::Histogram(_)));
1 ✔
968

969
        let res = c.into_plot().unwrap().to_vega_embeddable(false).unwrap();
1 ✔
970

971
        // expected
972
        let bucket_count = std::cmp::min(100, f64::sqrt(element_count as f64) as usize);
1 ✔
973
        let dimx =
1 ✔
974
            HistogramDimension::new(cx, 0.0, (element_count - 1) as f64, bucket_count).unwrap();
1 ✔
975

976
        let dimy =
1 ✔
977
            HistogramDimension::new(cy, 0.0, (element_count - 1) as f64, bucket_count).unwrap();
1 ✔
978

979
        let mut expected = geoengine_datatypes::plots::Histogram2D::new(dimx, dimy);
1 ✔
980
        expected.update_batch(values.into_iter());
1 ✔
981

982
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), res);
1 ✔
983
    }
1 ✔
984

985
    #[test]
986
    fn test_collector_kind_histogram_out_of_range() {
1 ✔
987
        let cx = "x".to_string();
1 ✔
988
        let cy = "y".to_string();
1 ✔
989

990
        let element_count = COLLECTOR_TO_HISTOGRAM_THRESHOLD + 1;
1 ✔
991

992
        let mut values = Vec::with_capacity(element_count);
1 ✔
993
        for i in 0..element_count {
10,001 ✔
994
            values.push(Coordinate2D::new(i as f64, i as f64));
10,001 ✔
995
        }
10,001 ✔
996

997
        let mut c = CollectorKind::Values(Collector::new(cx.clone(), cy.clone()));
1 ✔
998
        c.add_batch(values.clone().into_iter()).unwrap();
1 ✔
999

1000
        assert!(matches!(c, CollectorKind::Histogram(_)));
1 ✔
1001

1002
        // This value should be skipped
1003
        c.add_batch(
1 ✔
1004
            [Coordinate2D::new(
1 ✔
1005
                element_count as f64,
1 ✔
1006
                element_count as f64,
1 ✔
1007
            )]
1 ✔
1008
            .into_iter(),
1 ✔
1009
        )
1010
        .unwrap();
1 ✔
1011

1012
        let res = c.into_plot().unwrap().to_vega_embeddable(false).unwrap();
1 ✔
1013

1014
        // expected
1015
        let bucket_count = std::cmp::min(100, f64::sqrt(element_count as f64) as usize);
1 ✔
1016
        let dimx =
1 ✔
1017
            HistogramDimension::new(cx, 0.0, (element_count - 1) as f64, bucket_count).unwrap();
1 ✔
1018

1019
        let dimy =
1 ✔
1020
            HistogramDimension::new(cy, 0.0, (element_count - 1) as f64, bucket_count).unwrap();
1 ✔
1021

1022
        let mut expected = geoengine_datatypes::plots::Histogram2D::new(dimx, dimy);
1 ✔
1023
        expected.update_batch(values.into_iter());
1 ✔
1024

1025
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), res);
1 ✔
1026
    }
1 ✔
1027

1028
    #[test]
1029
    fn test_collector_kind_histogram_infinite() {
1 ✔
1030
        let cx = "x".to_string();
1 ✔
1031
        let cy = "y".to_string();
1 ✔
1032

1033
        let element_count = COLLECTOR_TO_HISTOGRAM_THRESHOLD + 1;
1 ✔
1034

1035
        let mut values = Vec::with_capacity(element_count);
1 ✔
1036
        for i in 0..element_count {
10,001 ✔
1037
            values.push(Coordinate2D::new(i as f64, i as f64));
10,001 ✔
1038
        }
10,001 ✔
1039

1040
        let mut c = CollectorKind::Values(Collector::new(cx.clone(), cy.clone()));
1 ✔
1041
        c.add_batch(values.clone().into_iter()).unwrap();
1 ✔
1042

1043
        assert!(matches!(c, CollectorKind::Histogram(_)));
1 ✔
1044

1045
        // This value should be skipped
1046
        c.add_batch([Coordinate2D::new(f64::NAN, f64::NAN)].into_iter())
1 ✔
1047
            .unwrap();
1 ✔
1048

1049
        let res = c.into_plot().unwrap().to_vega_embeddable(false).unwrap();
1 ✔
1050

1051
        // expected
1052
        let bucket_count = std::cmp::min(100, f64::sqrt(element_count as f64) as usize);
1 ✔
1053
        let dimx =
1 ✔
1054
            HistogramDimension::new(cx, 0.0, (element_count - 1) as f64, bucket_count).unwrap();
1 ✔
1055

1056
        let dimy =
1 ✔
1057
            HistogramDimension::new(cy, 0.0, (element_count - 1) as f64, bucket_count).unwrap();
1 ✔
1058

1059
        let mut expected = geoengine_datatypes::plots::Histogram2D::new(dimx, dimy);
1 ✔
1060
        expected.update_batch(values.into_iter());
1 ✔
1061

1062
        assert_eq!(expected.to_vega_embeddable(false).unwrap(), res);
1 ✔
1063
    }
1 ✔
1064
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc