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

geo-engine / geoengine / 19537157963

20 Nov 2025 12:39PM UTC coverage: 88.458%. First build
19537157963

Pull #1083

github

web-flow
Merge 49b049e99 into ba34db99d
Pull Request #1083: feat: new gdal source workflow optimization

6339 of 7660 new or added lines in 79 files covered. (82.75%)

116533 of 131738 relevant lines covered (88.46%)

492817.7 hits per line

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

91.14
/operators/src/processing/expression/vector_operator.rs
1
use super::{
2
    AsExpressionGeo, FromExpressionGeo, VectorExpressionError, canonicalize_name,
3
    error::vector as error, get_expression_dependencies,
4
};
5
use crate::{
6
    engine::{
7
        CanonicOperatorName, ExecutionContext, InitializedSources, InitializedVectorOperator,
8
        Operator, OperatorName, QueryContext, SingleVectorSource, TypedVectorQueryProcessor,
9
        VectorColumnInfo, VectorOperator, VectorQueryProcessor, VectorResultDescriptor,
10
        WorkflowOperatorPath,
11
    },
12
    optimization::OptimizationError,
13
    util::Result,
14
};
15
use async_trait::async_trait;
16
use futures::StreamExt;
17
use futures::stream::BoxStream;
18
use geoengine_datatypes::primitives::{
19
    FeatureData, FeatureDataRef, FeatureDataType, FloatOptionsParIter, Geometry, Measurement,
20
    MultiLineString, MultiPoint, MultiPolygon, SpatialResolution, VectorQueryRectangle,
21
};
22
use geoengine_datatypes::util::arrow::ArrowTyped;
23
use geoengine_datatypes::{
24
    collections::{
25
        FeatureCollection, FeatureCollectionInfos, FeatureCollectionModifications,
26
        GeoFeatureCollectionModifications, GeoVectorDataType, IntoGeometryOptionsIterator,
27
        VectorDataType,
28
    },
29
    primitives::NoGeometry,
30
};
31
use geoengine_expression::{
32
    DataType, ExpressionParser, LinkedExpression, Parameter as ExpressionParameter,
33
    is_allowed_variable_name,
34
};
35
use rayon::iter::{
36
    FromParallelIterator, IndexedParallelIterator, IntoParallelIterator, ParallelIterator,
37
};
38
use serde::{Deserialize, Serialize};
39
use snafu::ResultExt;
40
use std::collections::HashMap;
41
use std::marker::PhantomData;
42
use std::sync::Arc;
43

44
/// A vector expression creates or replaces a column in a `FeatureCollection` by evaluating an expression.
45
/// The expression receives the feature's columns as variables.
46
pub type VectorExpression = Operator<VectorExpressionParams, SingleVectorSource>;
47

48
impl OperatorName for VectorExpression {
49
    const TYPE_NAME: &'static str = "VectorExpression";
50
}
51

52
const MAX_INPUT_COLUMNS: usize = 8;
53
const PARALLEL_MIN_BATCH_SIZE: usize = 32; // TODO: find good default
54
const EXPRESSION_MAIN_NAME: &str = "expression";
55

56
#[derive(Debug, Clone, Deserialize, Serialize)]
57
#[serde(rename_all = "camelCase")]
58
pub struct VectorExpressionParams {
59
    /// The columns to use as variables in the expression.
60
    ///
61
    /// For usage in the expression, all special characters are replaced by underscores.
62
    /// E.g., `precipitation.cm` becomes `precipitation_cm`.
63
    ///
64
    /// If the column name starts with a number, an underscore is prepended.
65
    /// E.g., `1column` becomes `_1column`.
66
    ///
67
    pub input_columns: Vec<String>,
68

69
    /// The expression to evaluate.
70
    pub expression: String,
71

72
    /// The type and name of the new column.
73
    pub output_column: OutputColumn,
74

75
    /// The expression will always include the geometry column.
76
    /// Thus, it is necessary to specify the variable name of the geometry column.
77
    /// The default is `geom`.
78
    #[serde(default = "geometry_default_column_name")]
79
    pub geometry_column_name: String,
80

81
    /// The measurement of the new column.
82
    /// The default is [`Measurement::Unitless`].
83
    #[serde(default)]
84
    pub output_measurement: Measurement,
85
}
86

87
fn geometry_default_column_name() -> String {
×
88
    "geom".into()
×
89
}
×
90

91
/// Specify the output of the expression.
92
#[derive(Debug, Clone, Deserialize, Serialize)]
93
#[serde(tag = "type", content = "value", rename_all = "camelCase")]
94
pub enum OutputColumn {
95
    /// The expression will override the current geometry
96
    Geometry(GeoVectorDataType),
97
    /// The expression will append a new `Float` column
98
    // TODO: allow more types than `Float`s
99
    Column(String),
100
}
101

102
struct InitializedVectorExpression {
103
    name: CanonicOperatorName,
104
    path: WorkflowOperatorPath,
105
    params: VectorExpressionParams,
106
    result_descriptor: VectorResultDescriptor,
107
    features: Box<dyn InitializedVectorOperator>,
108
    expression: Arc<LinkedExpression>,
109
    input_columns: Vec<String>,
110
    output_column: OutputColumn,
111
}
112

113
#[typetag::serde]
×
114
#[async_trait]
115
impl VectorOperator for VectorExpression {
116
    async fn _initialize(
117
        self: Box<Self>,
118
        path: WorkflowOperatorPath,
119
        context: &dyn ExecutionContext,
120
    ) -> Result<Box<dyn InitializedVectorOperator>> {
5 ✔
121
        // TODO: This is super ugly to being forced to do this on every operator. This must be refactored.
122
        let name = CanonicOperatorName::from(&self);
123

124
        if self.params.input_columns.len() > MAX_INPUT_COLUMNS {
125
            Err(VectorExpressionError::TooManyInputColumns {
126
                max: MAX_INPUT_COLUMNS,
127
                found: self.params.input_columns.len(),
128
            })?;
129
        }
130

131
        let initialized_source = self
132
            .sources
133
            .initialize_sources(path.clone(), context)
134
            .await?;
135

136
        // we can reuse the result descriptor, because we only add a column later on
137
        let mut result_descriptor = initialized_source.vector.result_descriptor().clone();
138

139
        check_input_column_validity(&result_descriptor.columns, &self.params.input_columns)?;
140
        check_output_column_validity(&self.params.output_column)?;
141

142
        let expression_geom_input_type = result_descriptor.data_type;
143
        let expression_output_type = match &self.params.output_column {
144
            OutputColumn::Geometry(vector_data_type) => {
145
                result_descriptor.data_type = (*vector_data_type).into();
146
                match vector_data_type {
147
                    GeoVectorDataType::MultiPoint => DataType::MultiPoint,
148
                    GeoVectorDataType::MultiLineString => DataType::MultiLineString,
149
                    GeoVectorDataType::MultiPolygon => DataType::MultiPolygon,
150
                }
151
            }
152
            OutputColumn::Column(output_column_name) => {
153
                insert_new_column(
154
                    &mut result_descriptor.columns,
155
                    output_column_name.clone(),
156
                    self.params.output_measurement.clone(),
157
                )?;
158
                DataType::Number
159
            }
160
        };
161

162
        let mut expression_input_names = Vec::with_capacity(self.params.input_columns.len());
163
        for input_column in &self.params.input_columns {
164
            let variable_name = canonicalize_name(input_column);
165

166
            if !is_allowed_variable_name(&variable_name) {
167
                return Err(VectorExpressionError::ColumnNameContainsSpecialCharacters {
168
                    name: variable_name,
169
                })?;
170
            }
171

172
            expression_input_names.push(variable_name);
173
        }
174

175
        let expression = {
176
            let expression_code = self.params.expression.clone();
177
            let geometry_column_name = self.params.geometry_column_name.clone();
178

179
            crate::util::spawn_blocking(move || {
5 ✔
180
                compile_expression(
5 ✔
181
                    &expression_code,
5 ✔
182
                    geometry_column_name,
5 ✔
183
                    expression_geom_input_type,
5 ✔
184
                    &expression_input_names,
5 ✔
185
                    expression_output_type,
5 ✔
186
                )
187
                .map(Arc::new)
5 ✔
188
            })
5 ✔
189
            .await
190
            .map_err(|source| VectorExpressionError::CompilationTask { source })??
×
191
        };
192

193
        let initialized_operator = InitializedVectorExpression {
194
            name,
195
            path,
196
            params: self.params.clone(),
197
            result_descriptor,
198
            features: initialized_source.vector,
199
            expression,
200
            input_columns: self.params.input_columns,
201
            output_column: self.params.output_column,
202
        };
203

204
        Ok(initialized_operator.boxed())
205
    }
5 ✔
206

207
    span_fn!(VectorExpression);
208
}
209

210
fn check_input_column_validity(
5 ✔
211
    columns: &HashMap<String, VectorColumnInfo>,
5 ✔
212
    input_columns: &[String],
5 ✔
213
) -> Result<(), VectorExpressionError> {
5 ✔
214
    for input_column in input_columns {
16 ✔
215
        if input_column.contains(|c: char| !c.is_alphanumeric()) {
25 ✔
216
            Err(VectorExpressionError::ColumnNameContainsSpecialCharacters {
×
217
                name: input_column.clone(),
×
218
            })?;
×
219
        }
11 ✔
220

221
        let Some(column_info) = columns.get(input_column) else {
11 ✔
222
            return Err(VectorExpressionError::InputColumnNotExisting {
×
223
                name: input_column.clone(),
×
224
            });
×
225
        };
226

227
        match column_info.data_type {
11 ✔
228
            FeatureDataType::Float | FeatureDataType::Int => {}
11 ✔
229
            _ => Err(VectorExpressionError::InputColumnNotNumeric {
×
230
                name: input_column.clone(),
×
231
            })?,
×
232
        }
233
    }
234

235
    Ok(())
5 ✔
236
}
5 ✔
237

238
fn check_output_column_validity(output_column: &OutputColumn) -> Result<(), VectorExpressionError> {
5 ✔
239
    match output_column {
5 ✔
240
        OutputColumn::Geometry(_) => {}
1 ✔
241
        OutputColumn::Column(column) => {
4 ✔
242
            if column.contains(|c: char| !c.is_alphanumeric()) {
13 ✔
243
                Err(VectorExpressionError::ColumnNameContainsSpecialCharacters {
×
244
                    name: column.clone(),
×
245
                })?;
×
246
            }
4 ✔
247
        }
248
    }
249

250
    Ok(())
5 ✔
251
}
5 ✔
252

253
fn insert_new_column(
4 ✔
254
    columns: &mut HashMap<String, VectorColumnInfo>,
4 ✔
255
    name: String,
4 ✔
256
    measurement: Measurement,
4 ✔
257
) -> Result<(), VectorExpressionError> {
4 ✔
258
    let output_column_collision = columns.insert(
4 ✔
259
        name.clone(),
4 ✔
260
        VectorColumnInfo {
4 ✔
261
            data_type: FeatureDataType::Float,
4 ✔
262
            measurement,
4 ✔
263
        },
4 ✔
264
    );
265

266
    if output_column_collision.is_some() {
4 ✔
267
        return Err(VectorExpressionError::OutputColumnCollision { name });
×
268
    }
4 ✔
269

270
    Ok(())
4 ✔
271
}
4 ✔
272

273
fn compile_expression(
5 ✔
274
    expression_code: &str,
5 ✔
275
    geom_name: String,
5 ✔
276
    geom_type: VectorDataType,
5 ✔
277
    parameters: &[String],
5 ✔
278
    output_type: DataType,
5 ✔
279
) -> Result<LinkedExpression, VectorExpressionError> {
5 ✔
280
    let geom_parameter = match geom_type {
5 ✔
281
        VectorDataType::Data | VectorDataType::MultiPoint => {
282
            ExpressionParameter::MultiPoint(geom_name.into())
3 ✔
283
        }
284
        VectorDataType::MultiLineString => ExpressionParameter::MultiLineString(geom_name.into()),
×
285
        VectorDataType::MultiPolygon => ExpressionParameter::MultiPolygon(geom_name.into()),
2 ✔
286
    };
287
    let mut expression_parameters = Vec::with_capacity(parameters.len() + 1);
5 ✔
288
    expression_parameters.push(geom_parameter);
5 ✔
289
    expression_parameters.extend(
5 ✔
290
        parameters
5 ✔
291
            .iter()
5 ✔
292
            .map(|p| ExpressionParameter::Number(p.into())),
11 ✔
293
    );
294
    let expression = ExpressionParser::new(&expression_parameters, output_type)?
5 ✔
295
        .parse(EXPRESSION_MAIN_NAME, expression_code)?;
5 ✔
296

297
    let expression_dependencies = get_expression_dependencies().context(error::Dependencies)?;
5 ✔
298

299
    Ok(LinkedExpression::from_ast(
5 ✔
300
        &expression,
5 ✔
301
        expression_dependencies,
5 ✔
302
    )?)
×
303
}
5 ✔
304

305
impl InitializedVectorExpression {
306
    #[inline]
307
    fn column_processor<G>(
4 ✔
308
        &self,
4 ✔
309
        source: Box<dyn VectorQueryProcessor<VectorType = FeatureCollection<G>>>,
4 ✔
310
        output_column: String,
4 ✔
311
    ) -> TypedVectorQueryProcessor
4 ✔
312
    where
4 ✔
313
        G: Geometry + ArrowTyped + 'static,
4 ✔
314
        FeatureCollection<G>: for<'g> IntoGeometryOptionsIterator<'g> + 'static,
4 ✔
315
        for<'g> <FeatureCollection<G> as IntoGeometryOptionsIterator<'g>>::GeometryType:
4 ✔
316
            AsExpressionGeo + Send,
4 ✔
317
        for<'g> <<FeatureCollection<G> as IntoGeometryOptionsIterator<'g>>::GeometryOptionIterator as IntoParallelIterator>::Iter:
4 ✔
318
        IndexedParallelIterator + Send,
4 ✔
319
        TypedVectorQueryProcessor: From<Box<dyn VectorQueryProcessor<VectorType = FeatureCollection<G>>>>,
4 ✔
320
    {
321
        VectorExpressionColumnProcessor {
4 ✔
322
            source,
4 ✔
323
            result_descriptor: self.result_descriptor.clone(),
4 ✔
324
            expression: self.expression.clone(),
4 ✔
325
            input_columns: self.input_columns.clone(),
4 ✔
326
            output_column,
4 ✔
327
        }
4 ✔
328
        .boxed()
4 ✔
329
        .into()
4 ✔
330
    }
4 ✔
331

332
    #[inline]
333
    fn geometry_processor<GIn, GOut>(
1 ✔
334
        &self,
1 ✔
335
        source: Box<dyn VectorQueryProcessor<VectorType = FeatureCollection<GIn>>>,
1 ✔
336
    ) -> TypedVectorQueryProcessor
1 ✔
337
    where
1 ✔
338
        GIn: Geometry + ArrowTyped + Send + Sync + 'static + Sized,
1 ✔
339
        GOut: Geometry
1 ✔
340
            + ArrowTyped
1 ✔
341
            + FromExpressionGeo
1 ✔
342
            + Send
1 ✔
343
            + Sync
1 ✔
344
            + 'static
1 ✔
345
            + Sized,
1 ✔
346
        FeatureCollection<GIn>: GeoFeatureCollectionModifications<GOut> + for<'g> IntoGeometryOptionsIterator<'g>,
1 ✔
347
        for<'g> <<FeatureCollection<GIn> as IntoGeometryOptionsIterator<'g>>::GeometryOptionIterator as IntoParallelIterator>::Iter:
1 ✔
348
            IndexedParallelIterator + Send,
1 ✔
349
        for<'g> <FeatureCollection<GIn> as IntoGeometryOptionsIterator<'g>>::GeometryType: AsExpressionGeo,
1 ✔
350
        TypedVectorQueryProcessor: From<Box<dyn VectorQueryProcessor<VectorType = FeatureCollection<GOut>>>>,
1 ✔
351
    {
352
        VectorExpressionGeometryProcessor {
1 ✔
353
            source,
1 ✔
354
            result_descriptor: self.result_descriptor.clone(),
1 ✔
355
            expression: self.expression.clone(),
1 ✔
356
            input_columns: self.input_columns.clone(),
1 ✔
357
            _out: PhantomData::<GOut>,
1 ✔
358
        }
1 ✔
359
        .boxed()
1 ✔
360
        .into()
1 ✔
361
    }
1 ✔
362

363
    #[inline]
364
    fn dispatch_float_column_output(
4 ✔
365
        &self,
4 ✔
366
        source_processor: TypedVectorQueryProcessor,
4 ✔
367
        output_column: String,
4 ✔
368
    ) -> TypedVectorQueryProcessor {
4 ✔
369
        match source_processor {
4 ✔
370
            TypedVectorQueryProcessor::Data(source) => {
×
371
                self.column_processor::<NoGeometry>(source, output_column)
×
372
            }
373
            TypedVectorQueryProcessor::MultiPoint(source) => {
3 ✔
374
                self.column_processor::<MultiPoint>(source, output_column)
3 ✔
375
            }
376
            TypedVectorQueryProcessor::MultiLineString(source) => {
×
377
                self.column_processor::<MultiLineString>(source, output_column)
×
378
            }
379
            TypedVectorQueryProcessor::MultiPolygon(source) => {
1 ✔
380
                self.column_processor::<MultiPolygon>(source, output_column)
1 ✔
381
            }
382
        }
383
    }
4 ✔
384

385
    #[inline]
386
    fn dispatch_geometry_output_for_type<GOut>(
1 ✔
387
        &self,
1 ✔
388
        source_processor: TypedVectorQueryProcessor,
1 ✔
389
    ) -> TypedVectorQueryProcessor
1 ✔
390
    where
1 ✔
391
        GOut: Geometry + ArrowTyped + FromExpressionGeo + Send + Sync + 'static + Sized,
1 ✔
392
        TypedVectorQueryProcessor:
1 ✔
393
            From<Box<dyn VectorQueryProcessor<VectorType = FeatureCollection<GOut>>>>,
1 ✔
394
    {
395
        match source_processor {
1 ✔
396
            TypedVectorQueryProcessor::Data(source) => {
×
397
                self.geometry_processor::<NoGeometry, GOut>(source)
×
398
            }
399
            TypedVectorQueryProcessor::MultiPoint(source) => {
×
400
                self.geometry_processor::<MultiPoint, GOut>(source)
×
401
            }
402
            TypedVectorQueryProcessor::MultiLineString(source) => {
×
403
                self.geometry_processor::<MultiLineString, GOut>(source)
×
404
            }
405
            TypedVectorQueryProcessor::MultiPolygon(source) => {
1 ✔
406
                self.geometry_processor::<MultiPolygon, GOut>(source)
1 ✔
407
            }
408
        }
409
    }
1 ✔
410

411
    #[inline]
412
    fn dispatch_geometry_output(
1 ✔
413
        &self,
1 ✔
414
        source_processor: TypedVectorQueryProcessor,
1 ✔
415
        vector_data_type: GeoVectorDataType,
1 ✔
416
    ) -> TypedVectorQueryProcessor {
1 ✔
417
        match vector_data_type {
1 ✔
418
            GeoVectorDataType::MultiPoint => {
419
                self.dispatch_geometry_output_for_type::<MultiPoint>(source_processor)
1 ✔
420
            }
421
            GeoVectorDataType::MultiLineString => {
422
                self.dispatch_geometry_output_for_type::<MultiLineString>(source_processor)
×
423
            }
424
            GeoVectorDataType::MultiPolygon => {
425
                self.dispatch_geometry_output_for_type::<MultiPolygon>(source_processor)
×
426
            }
427
        }
428
    }
1 ✔
429
}
430

431
impl InitializedVectorOperator for InitializedVectorExpression {
432
    fn result_descriptor(&self) -> &VectorResultDescriptor {
×
433
        &self.result_descriptor
×
434
    }
×
435

436
    fn query_processor(&self) -> Result<TypedVectorQueryProcessor> {
5 ✔
437
        let source_processor = self.features.query_processor()?;
5 ✔
438

439
        Ok(match self.output_column.clone() {
5 ✔
440
            OutputColumn::Geometry(vector_data_type) => {
1 ✔
441
                self.dispatch_geometry_output(source_processor, vector_data_type)
1 ✔
442
            }
443
            OutputColumn::Column(output_column) => {
4 ✔
444
                self.dispatch_float_column_output(source_processor, output_column)
4 ✔
445
            }
446
        })
447
    }
5 ✔
448

449
    fn canonic_name(&self) -> CanonicOperatorName {
×
450
        self.name.clone()
×
451
    }
×
452

453
    fn name(&self) -> &'static str {
×
454
        VectorExpression::TYPE_NAME
×
455
    }
×
456

457
    fn path(&self) -> WorkflowOperatorPath {
×
458
        self.path.clone()
×
459
    }
×
460

NEW
461
    fn optimize(
×
NEW
462
        &self,
×
NEW
463
        target_resolution: SpatialResolution,
×
NEW
464
    ) -> Result<Box<dyn VectorOperator>, OptimizationError> {
×
465
        Ok(VectorExpression {
NEW
466
            params: self.params.clone(),
×
467
            sources: SingleVectorSource {
NEW
468
                vector: self.features.optimize(target_resolution)?,
×
469
            },
470
        }
NEW
471
        .boxed())
×
NEW
472
    }
×
473
}
474

475
/// A processor that evaluates an expression on the columns of a `FeatureCollection`.
476
/// The result is a new `FeatureCollection` with the evaluated column added.
477
pub struct VectorExpressionColumnProcessor<Q, G>
478
where
479
    G: Geometry,
480
    Q: VectorQueryProcessor<VectorType = FeatureCollection<G>>,
481
{
482
    source: Q,
483
    result_descriptor: VectorResultDescriptor,
484
    expression: Arc<LinkedExpression>,
485
    input_columns: Vec<String>,
486
    output_column: String,
487
}
488

489
/// A processor that evaluates an expression on the columns of a `FeatureCollection`.
490
/// The result is a new `FeatureCollection` with a replaced geometry column.
491
pub struct VectorExpressionGeometryProcessor<Q, GIn, GOut>
492
where
493
    GIn: Geometry,
494
    GOut: Geometry,
495
    Q: VectorQueryProcessor<VectorType = FeatureCollection<GIn>>,
496
{
497
    source: Q,
498
    result_descriptor: VectorResultDescriptor,
499
    expression: Arc<LinkedExpression>,
500
    input_columns: Vec<String>,
501
    _out: PhantomData<GOut>,
502
}
503

504
type ExpressionGeometryType<'g, G> = <<FeatureCollection<G> as IntoGeometryOptionsIterator<'g>>::GeometryType as AsExpressionGeo>::ExpressionGeometryType;
505

506
#[async_trait]
507
impl<Q, G> VectorQueryProcessor for VectorExpressionColumnProcessor<Q, G>
508
where
509
    Q: VectorQueryProcessor<VectorType = FeatureCollection<G>>,
510
    G: Geometry + ArrowTyped + 'static,
511
    FeatureCollection<G>: for<'g> IntoGeometryOptionsIterator<'g> + 'static,
512
    for<'g> <FeatureCollection<G> as IntoGeometryOptionsIterator<'g>>::GeometryType:
513
        AsExpressionGeo + Send,
514
    for<'g> <<FeatureCollection<G> as IntoGeometryOptionsIterator<'g>>::GeometryOptionIterator as IntoParallelIterator>::Iter:
515
        IndexedParallelIterator + Send,
516
{
517
    type VectorType = FeatureCollection<G>;
518

519

520
    async fn vector_query<'a>(
521
        &'a self,
522
        query: VectorQueryRectangle,
523
        ctx: &'a dyn QueryContext,
524
    ) -> Result<BoxStream<'a, Result<Self::VectorType>>> {
4 ✔
525
        let stream = self.source.vector_query(query, ctx).await?;
526

527
        let stream = stream.then(move |collection| async move {
4 ✔
528
            let collection = collection?;
4 ✔
529
            let input_columns = self.input_columns.clone();
4 ✔
530
            let output_column = self.output_column.clone();
4 ✔
531
            let expression = self.expression.clone();
4 ✔
532

533
            crate::util::spawn_blocking_with_thread_pool(ctx.thread_pool().clone(), move || {
4 ✔
534
                let result: Vec<Option<f64>> = call_expression_function(
4 ✔
535
                    &expression,
4 ✔
536
                    &collection,
4 ✔
537
                    &input_columns,
4 ✔
538
                    std::convert::identity,
4 ✔
539
                )?;
×
540

541
                Ok(collection
4 ✔
542
                    .add_column(&output_column, FeatureData::NullableFloat(result))
4 ✔
543
                    .context(error::AddColumn {
4 ✔
544
                        name: output_column,
4 ✔
545
                    })?)
4 ✔
546
            })
4 ✔
547
            .await?
4 ✔
548
        });
8 ✔
549

550
        Ok(stream.boxed())
551
    }
4 ✔
552

553
    fn vector_result_descriptor(&self) -> &VectorResultDescriptor {
4 ✔
554
        &self.result_descriptor
4 ✔
555
    }
4 ✔
556
}
557

558
#[async_trait]
559
impl<Q, GIn, GOut> VectorQueryProcessor
560
    for VectorExpressionGeometryProcessor<Q, GIn, GOut>
561
where
562
    Q: VectorQueryProcessor<VectorType = FeatureCollection<GIn>> + 'static + Sized,
563
    GIn: Geometry + ArrowTyped + Send + Sync + 'static + Sized,
564
    GOut: Geometry
565
        + ArrowTyped
566
        + FromExpressionGeo
567
        + Send
568
        + Sync
569
        + 'static
570
        + Sized,
571
    FeatureCollection<GIn>: GeoFeatureCollectionModifications<GOut> + for<'g> IntoGeometryOptionsIterator<'g>,
572
    for<'g> <<FeatureCollection<GIn> as IntoGeometryOptionsIterator<'g>>::GeometryOptionIterator as IntoParallelIterator>::Iter:
573
        IndexedParallelIterator + Send,
574
    for<'g> <FeatureCollection<GIn> as IntoGeometryOptionsIterator<'g>>::GeometryType: AsExpressionGeo,
575
    Vec<Option<GOut>>: FromParallelIterator<Option<GOut>>,
576
{
577
    type VectorType = FeatureCollection<GOut>;
578

579
    async fn vector_query<'a>(
580
        &'a self,
581
        query: VectorQueryRectangle,
582
        ctx: &'a dyn QueryContext,
583
    ) -> Result<BoxStream<'a, Result<Self::VectorType>>> {
1 ✔
584
        let stream = self.source.vector_query(query, ctx).await?;
585

586
        let stream = stream.then(move |collection| async move {
1 ✔
587
            let collection = collection?;
1 ✔
588
            let input_columns = self.input_columns.clone();
1 ✔
589
            let expression = self.expression.clone();
1 ✔
590

591
            crate::util::spawn_blocking_with_thread_pool(ctx.thread_pool().clone(), move || {
1 ✔
592
                let (geometry_options, row_filter): (Vec<Option<GOut>>, Vec<bool>) = call_expression_function(
1 ✔
593
                    &expression,
1 ✔
594
                    &collection,
1 ✔
595
                    &input_columns,
1 ✔
596
                    |geom_option| {
2 ✔
597
                        let geom_option = geom_option.and_then(<GOut as FromExpressionGeo>::from_expression_geo);
2 ✔
598

599
                        let row_filter = geom_option.is_some();
2 ✔
600

601
                        (geom_option, row_filter)
2 ✔
602
                    },
2 ✔
603
                )?;
×
604

605
                // remove all `None`s and output only the geometries
606
                let geometries = geometry_options.into_par_iter().with_min_len(PARALLEL_MIN_BATCH_SIZE).filter_map(std::convert::identity).collect::<Vec<_>>();
1 ✔
607

608
                Ok(collection
1 ✔
609
                    .filter(row_filter) // we have to filter out the rows with empty geometries
1 ✔
610
                    .context(error::FilterEmptyGeometries)?
1 ✔
611
                    .replace_geometries(geometries)
1 ✔
612
                    .context(error::ReplaceGeometries)?)
1 ✔
613
            })
1 ✔
614
            .await?
1 ✔
615
        });
2 ✔
616

617
        Ok(stream.boxed())
618
    }
1 ✔
619

620
    fn vector_result_descriptor(&self) -> &VectorResultDescriptor {
1 ✔
621
        &self.result_descriptor
1 ✔
622
    }
1 ✔
623
}
624

625
fn call_expression_function<GIn, ExprOut, MapOut, Out>(
5 ✔
626
    expression: &Arc<LinkedExpression>,
5 ✔
627
    collection: &FeatureCollection<GIn>,
5 ✔
628
    input_columns: &[String],
5 ✔
629
    map_fn: fn(Option<ExprOut>) -> MapOut,
5 ✔
630
) -> Result<Out, VectorExpressionError>
5 ✔
631
where
5 ✔
632
    GIn: Geometry + ArrowTyped + 'static,
5 ✔
633
    for<'i> FeatureCollection<GIn>: IntoGeometryOptionsIterator<'i>,
5 ✔
634
    for<'g> <<FeatureCollection<GIn> as IntoGeometryOptionsIterator<'g>>::GeometryOptionIterator as IntoParallelIterator>::Iter:
5 ✔
635
        IndexedParallelIterator + Send,
5 ✔
636
    for<'g> <FeatureCollection<GIn> as IntoGeometryOptionsIterator<'g>>::GeometryType: AsExpressionGeo,
5 ✔
637
    ExprOut: Send,
5 ✔
638
    MapOut: Send,
5 ✔
639
    Out: FromParallelIterator<MapOut> + Send,
5 ✔
640
{
641
    let data_columns: Vec<FeatureDataRef> = input_columns
5 ✔
642
        .iter()
5 ✔
643
        .map(|input_column| {
11 ✔
644
            collection
11 ✔
645
                .data(input_column)
11 ✔
646
                .expect("was checked durin initialization")
11 ✔
647
        })
11 ✔
648
        .collect();
5 ✔
649

650
    let float_inputs: Vec<FloatOptionsParIter> = data_columns
5 ✔
651
        .iter()
5 ✔
652
        .map(FeatureDataRef::float_options_par_iter)
5 ✔
653
        .collect::<Vec<_>>();
5 ✔
654

655
    let geom_input = collection
5 ✔
656
        .geometry_options()
5 ✔
657
        .into_par_iter()
5 ✔
658
        .map(|geometry_option| {
112 ✔
659
            if let Some(geometry) = geometry_option.as_ref() {
112 ✔
660
                geometry.as_expression_geo()
112 ✔
661
            } else {
662
                None
×
663
            }
664
        });
112 ✔
665

666
    macro_rules! impl_expression_subcall {
667
        ($n:literal, $($i:ident),*) => {
668
            {
669
                let [ $($i),* ] = <[_; $n]>::try_from(float_inputs).expect("it matches the match condition");
670
                let f = unsafe {
671
                    expression.function_nary::<fn(
672
                        Option<ExpressionGeometryType<'_, GIn>>,
673
                        $( impl_expression_subcall!(@float_option $i), )*
674
                    ) -> Option<ExprOut>>()
675
                }
676
                .map_err(VectorExpressionError::from)?;
677

678
                (geom_input, $($i),*)
679
                    .into_par_iter()
680
                    .with_min_len(PARALLEL_MIN_BATCH_SIZE)
681
                    .map(|(geom, $($i),*)| map_fn(f(geom, $($i),*)))
108 ✔
682
                    .collect()
683
            }
684
        };
685
        // Create one float option for each float input
686
        (@float_option $i:ident) => {
687
            Option<f64>
688
        };
689
    }
690

691
    Ok(match float_inputs.len() {
5 ✔
692
        0 => {
693
            let f = unsafe {
2 ✔
694
                expression.function_nary::<fn(
2 ✔
695
                    Option<ExpressionGeometryType<'_, GIn>>,
2 ✔
696
                ) -> Option<ExprOut>>()
2 ✔
697
            }
698
            .map_err(VectorExpressionError::from)?;
2 ✔
699

700
            geom_input
2 ✔
701
                .with_min_len(PARALLEL_MIN_BATCH_SIZE)
2 ✔
702
                .map(|geom| map_fn(f(geom)))
4 ✔
703
                .collect()
2 ✔
704
        }
705
        1 => impl_expression_subcall!(1, i1),
1 ✔
706
        2 => impl_expression_subcall!(2, i1, i2),
1 ✔
707
        3 => impl_expression_subcall!(3, i1, i2, i3),
×
708
        4 => impl_expression_subcall!(4, i1, i2, i3, i4),
×
709
        5 => impl_expression_subcall!(5, i1, i2, i3, i4, i5),
×
710
        6 => impl_expression_subcall!(6, i1, i2, i3, i4, i5, i6),
×
711
        7 => impl_expression_subcall!(7, i1, i2, i3, i4, i5, i6, i7),
×
712
        8 => impl_expression_subcall!(8, i1, i2, i3, i4, i5, i6, i7, i8),
1 ✔
713
        other => Err(VectorExpressionError::TooManyInputColumns {
×
714
            max: MAX_INPUT_COLUMNS,
×
715
            found: other,
×
716
        })?,
×
717
    })
718
}
5 ✔
719

720
#[cfg(test)]
721
mod tests {
722
    use super::*;
723
    use crate::{
724
        engine::{ChunkByteSize, MockExecutionContext, QueryProcessor},
725
        mock::MockFeatureCollectionSource,
726
    };
727
    use geoengine_datatypes::{
728
        collections::{
729
            ChunksEqualIgnoringCacheHint, IntoGeometryIterator, MultiPointCollection,
730
            MultiPolygonCollection,
731
        },
732
        primitives::{BoundingBox2D, ColumnSelection, MultiPoint, MultiPolygon, TimeInterval},
733
        util::test::TestDefault,
734
    };
735

736
    #[test]
737
    fn it_deserializes_the_operator() {
1 ✔
738
        let def: Operator<VectorExpressionParams, SingleVectorSource> = VectorExpression {
1 ✔
739
            params: VectorExpressionParams {
1 ✔
740
                input_columns: vec!["foo".into(), "bar".into()],
1 ✔
741
                expression: "foo + bar".into(),
1 ✔
742
                output_column: OutputColumn::Column("baz".into()),
1 ✔
743
                output_measurement: Measurement::Unitless,
1 ✔
744
                geometry_column_name: "geom".to_string(),
1 ✔
745
            },
1 ✔
746
            sources: MockFeatureCollectionSource::<MultiPoint>::multiple(vec![])
1 ✔
747
                .boxed()
1 ✔
748
                .into(),
1 ✔
749
        };
1 ✔
750

751
        let json = serde_json::json!({
1 ✔
752
            "params": {
1 ✔
753
                "inputColumns": ["foo", "bar"],
1 ✔
754
                "expression": "foo + bar",
1 ✔
755
                "outputColumn": {
1 ✔
756
                    "type": "column",
1 ✔
757
                    "value": "baz",
1 ✔
758
                },
759
                "outputMeasurement": {
1 ✔
760
                    "type": "unitless",
1 ✔
761
                },
762
                "geometryColumnName": "geom",
1 ✔
763
            },
764
            "sources": {
1 ✔
765
                "vector": {
1 ✔
766
                    "type": "MockFeatureCollectionSourceMultiPoint",
1 ✔
767
                    "params": {
1 ✔
768
                        "collections": [],
1 ✔
769
                        "spatialReference": "EPSG:4326",
1 ✔
770
                        "measurements": null,
1 ✔
771
                    }
772
                }
773
            }
774
        });
775

776
        assert_eq!(serde_json::to_value(&def).unwrap(), json.clone());
1 ✔
777
        let _operator: VectorExpression = serde_json::from_value(json).unwrap();
1 ✔
778
    }
1 ✔
779

780
    #[tokio::test]
781
    async fn it_computes_unary_float_expressions() {
1 ✔
782
        let points = MultiPointCollection::from_slices(
1 ✔
783
            MultiPoint::many(vec![(0.0, 0.1), (1.0, 1.1), (2.0, 3.1)])
1 ✔
784
                .unwrap()
1 ✔
785
                .as_ref(),
1 ✔
786
            &[TimeInterval::new_unchecked(0, 1); 3],
1 ✔
787
            &[(
1 ✔
788
                "foo",
1 ✔
789
                FeatureData::NullableFloat(vec![Some(1.0), None, Some(3.0)]),
1 ✔
790
            )],
1 ✔
791
        )
792
        .unwrap();
1 ✔
793

794
        let point_source = MockFeatureCollectionSource::single(points.clone()).boxed();
1 ✔
795

796
        let exe_ctx = MockExecutionContext::test_default();
1 ✔
797

798
        let operator = VectorExpression {
1 ✔
799
            params: VectorExpressionParams {
1 ✔
800
                input_columns: vec!["foo".into()],
1 ✔
801
                expression: "2 * foo".into(),
1 ✔
802
                output_column: OutputColumn::Column("bar".into()),
1 ✔
803
                output_measurement: Measurement::Unitless,
1 ✔
804
                geometry_column_name: "geom".to_string(),
1 ✔
805
            },
1 ✔
806
            sources: point_source.into(),
1 ✔
807
        }
1 ✔
808
        .boxed()
1 ✔
809
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1 ✔
810
        .await
1 ✔
811
        .unwrap();
1 ✔
812

813
        let query_processor = operator.query_processor().unwrap().multi_point().unwrap();
1 ✔
814

815
        let query_rectangle = VectorQueryRectangle::new(
1 ✔
816
            BoundingBox2D::new((0., 0.).into(), (10., 10.).into()).unwrap(),
1 ✔
817
            TimeInterval::default(),
1 ✔
818
            ColumnSelection::all(),
1 ✔
819
        );
820
        let ctx = exe_ctx.mock_query_context(ChunkByteSize::MAX);
1 ✔
821

822
        let query = query_processor.query(query_rectangle, &ctx).await.unwrap();
1 ✔
823

824
        let mut result = query
1 ✔
825
            .map(Result::unwrap)
1 ✔
826
            .collect::<Vec<MultiPointCollection>>()
1 ✔
827
            .await;
1 ✔
828

829
        assert_eq!(result.len(), 1);
1 ✔
830
        let result = result.remove(0);
1 ✔
831

832
        let expected_result = MultiPointCollection::from_slices(
1 ✔
833
            MultiPoint::many(vec![(0.0, 0.1), (1.0, 1.1), (2.0, 3.1)])
1 ✔
834
                .unwrap()
1 ✔
835
                .as_ref(),
1 ✔
836
            &[TimeInterval::new_unchecked(0, 1); 3],
1 ✔
837
            &[
1 ✔
838
                (
1 ✔
839
                    "foo",
1 ✔
840
                    FeatureData::NullableFloat(vec![Some(1.0), None, Some(3.0)]),
1 ✔
841
                ),
1 ✔
842
                (
1 ✔
843
                    "bar",
1 ✔
844
                    FeatureData::NullableFloat(vec![Some(2.0), None, Some(6.0)]),
1 ✔
845
                ),
1 ✔
846
            ],
1 ✔
847
        )
848
        .unwrap();
1 ✔
849

850
        // TODO: maybe it is nicer to have something wrapping the actual data that we care about and just adds some cache info
851
        assert!(
1 ✔
852
            result.chunks_equal_ignoring_cache_hint(&expected_result),
1 ✔
853
            "{result:#?} != {expected_result:#?}",
1 ✔
854
        );
1 ✔
855
    }
1 ✔
856

857
    #[tokio::test]
858
    async fn it_computes_binary_float_expressions() {
1 ✔
859
        let points = MultiPointCollection::from_slices(
1 ✔
860
            MultiPoint::many(vec![
1 ✔
861
                (0.0, 0.1),
1 ✔
862
                (1.0, 1.1),
1 ✔
863
                (2.0, 2.1),
1 ✔
864
                (3.0, 3.1),
1 ✔
865
                (4.0, 4.1),
1 ✔
866
            ])
1 ✔
867
            .unwrap()
1 ✔
868
            .as_ref(),
1 ✔
869
            &[TimeInterval::new_unchecked(0, 1); 5],
1 ✔
870
            &[
1 ✔
871
                (
1 ✔
872
                    "foo",
1 ✔
873
                    FeatureData::NullableFloat(vec![Some(1.0), None, Some(3.0), None, Some(5.0)]),
1 ✔
874
                ),
1 ✔
875
                (
1 ✔
876
                    "bar",
1 ✔
877
                    FeatureData::NullableInt(vec![Some(10), None, None, Some(40), Some(50)]),
1 ✔
878
                ),
1 ✔
879
            ],
1 ✔
880
        )
881
        .unwrap();
1 ✔
882

883
        let point_source = MockFeatureCollectionSource::single(points.clone()).boxed();
1 ✔
884
        let exe_ctx = MockExecutionContext::test_default();
1 ✔
885

886
        let operator = VectorExpression {
1 ✔
887
            params: VectorExpressionParams {
1 ✔
888
                input_columns: vec!["foo".into(), "bar".into()],
1 ✔
889
                expression: "foo + bar".into(),
1 ✔
890
                output_column: OutputColumn::Column("baz".into()),
1 ✔
891
                output_measurement: Measurement::Unitless,
1 ✔
892
                geometry_column_name: "geom".to_string(),
1 ✔
893
            },
1 ✔
894
            sources: point_source.into(),
1 ✔
895
        }
1 ✔
896
        .boxed()
1 ✔
897
        .initialize(WorkflowOperatorPath::initialize_root(), &exe_ctx)
1 ✔
898
        .await
1 ✔
899
        .unwrap();
1 ✔
900

901
        let query_processor = operator.query_processor().unwrap().multi_point().unwrap();
1 ✔
902

903
        let query_rectangle = VectorQueryRectangle::new(
1 ✔
904
            BoundingBox2D::new((0., 0.).into(), (10., 10.).into()).unwrap(),
1 ✔
905
            TimeInterval::default(),
1 ✔
906
            ColumnSelection::all(),
1 ✔
907
        );
908
        let ctx = exe_ctx.mock_query_context(ChunkByteSize::MAX);
1 ✔
909

910
        let query = query_processor.query(query_rectangle, &ctx).await.unwrap();
1 ✔
911

912
        let mut result = query
1 ✔
913
            .map(Result::unwrap)
1 ✔
914
            .collect::<Vec<MultiPointCollection>>()
1 ✔
915
            .await;
1 ✔
916

917
        assert_eq!(result.len(), 1);
1 ✔
918
        let result = result.remove(0);
1 ✔
919

920
        let expected_result = MultiPointCollection::from_slices(
1 ✔
921
            MultiPoint::many(vec![
1 ✔
922
                (0.0, 0.1),
1 ✔
923
                (1.0, 1.1),
1 ✔
924
                (2.0, 2.1),
1 ✔
925
                (3.0, 3.1),
1 ✔
926
                (4.0, 4.1),
1 ✔
927
            ])
1 ✔
928
            .unwrap()
1 ✔
929
            .as_ref(),
1 ✔
930
            &[TimeInterval::new_unchecked(0, 1); 5],
1 ✔
931
            &[
1 ✔
932
                (
1 ✔
933
                    "foo",
1 ✔
934
                    FeatureData::NullableFloat(vec![Some(1.0), None, Some(3.0), None, Some(5.0)]),
1 ✔
935
                ),
1 ✔
936
                (
1 ✔
937
                    "bar",
1 ✔
938
                    FeatureData::NullableInt(vec![Some(10), None, None, Some(40), Some(50)]),
1 ✔
939
                ),
1 ✔
940
                (
1 ✔
941
                    "baz",
1 ✔
942
                    FeatureData::NullableFloat(vec![Some(11.0), None, None, None, Some(55.0)]),
1 ✔
943
                ),
1 ✔
944
            ],
1 ✔
945
        )
946
        .unwrap();
1 ✔
947

948
        // TODO: maybe it is nicer to have something wrapping the actual data that we care about and just adds some cache info
949
        assert!(
1 ✔
950
            result.chunks_equal_ignoring_cache_hint(&expected_result),
1 ✔
951
            "{result:#?} != {expected_result:#?}",
1 ✔
952
        );
1 ✔
953
    }
1 ✔
954

955
    #[tokio::test]
956
    async fn it_computes_the_area_from_a_geom() {
1 ✔
957
        let polygons = MockFeatureCollectionSource::single(
1 ✔
958
            MultiPolygonCollection::from_slices(
1 ✔
959
                &[
1 ✔
960
                    MultiPolygon::new(vec![vec![vec![
1 ✔
961
                        (0.5, -0.5).into(),
1 ✔
962
                        (4., -1.).into(),
1 ✔
963
                        (0.5, -2.5).into(),
1 ✔
964
                        (0.5, -0.5).into(),
1 ✔
965
                    ]]])
1 ✔
966
                    .unwrap(),
1 ✔
967
                    MultiPolygon::new(vec![vec![vec![
1 ✔
968
                        (1.0, -1.0).into(),
1 ✔
969
                        (8., -2.).into(),
1 ✔
970
                        (1.0, -5.0).into(),
1 ✔
971
                        (1.0, -1.0).into(),
1 ✔
972
                    ]]])
1 ✔
973
                    .unwrap(),
1 ✔
974
                ],
1 ✔
975
                &[TimeInterval::new_unchecked(0, 1); 2],
1 ✔
976
                &[("foo", FeatureData::NullableFloat(vec![Some(1.0), None]))],
1 ✔
977
            )
978
            .unwrap(),
1 ✔
979
        )
980
        .boxed();
1 ✔
981

982
        let result = compute_result::<MultiPolygonCollection>(
1 ✔
983
            VectorExpression {
1 ✔
984
                params: VectorExpressionParams {
1 ✔
985
                    input_columns: vec![],
1 ✔
986
                    expression: "area(geom)".into(),
1 ✔
987
                    output_column: OutputColumn::Column("area".into()),
1 ✔
988
                    output_measurement: Measurement::Unitless,
1 ✔
989
                    geometry_column_name: "geom".to_string(),
1 ✔
990
                },
1 ✔
991
                sources: polygons.into(),
1 ✔
992
            },
1 ✔
993
            VectorQueryRectangle::new(
1 ✔
994
                BoundingBox2D::new((0., 0.).into(), (10., 10.).into()).unwrap(),
1 ✔
995
                TimeInterval::default(),
1 ✔
996
                ColumnSelection::all(),
1 ✔
997
            ),
1 ✔
998
        )
1 ✔
999
        .await;
1 ✔
1000

1001
        let expected_result = MultiPolygonCollection::from_slices(
1 ✔
1002
            &[
1 ✔
1003
                MultiPolygon::new(vec![vec![vec![
1 ✔
1004
                    (0.5, -0.5).into(),
1 ✔
1005
                    (4., -1.).into(),
1 ✔
1006
                    (0.5, -2.5).into(),
1 ✔
1007
                    (0.5, -0.5).into(),
1 ✔
1008
                ]]])
1 ✔
1009
                .unwrap(),
1 ✔
1010
                MultiPolygon::new(vec![vec![vec![
1 ✔
1011
                    (1.0, -1.0).into(),
1 ✔
1012
                    (8., -2.).into(),
1 ✔
1013
                    (1.0, -5.0).into(),
1 ✔
1014
                    (1.0, -1.0).into(),
1 ✔
1015
                ]]])
1 ✔
1016
                .unwrap(),
1 ✔
1017
            ],
1 ✔
1018
            &[TimeInterval::new_unchecked(0, 1); 2],
1 ✔
1019
            &[
1 ✔
1020
                ("foo", FeatureData::NullableFloat(vec![Some(1.0), None])),
1 ✔
1021
                (
1 ✔
1022
                    "area",
1 ✔
1023
                    FeatureData::NullableFloat(vec![Some(3.5), Some(14.0)]),
1 ✔
1024
                ),
1 ✔
1025
            ],
1 ✔
1026
        )
1027
        .unwrap();
1 ✔
1028

1029
        // TODO: maybe it is nicer to have something wrapping the actual data that we care about and just adds some cache info
1030
        assert!(
1 ✔
1031
            result.chunks_equal_ignoring_cache_hint(&expected_result),
1 ✔
1032
            "{result:#?} != {expected_result:#?}",
1 ✔
1033
        );
1 ✔
1034
    }
1 ✔
1035

1036
    #[tokio::test]
1037
    async fn it_computes_the_centroid_of_a_geom() {
1 ✔
1038
        let polygons = MockFeatureCollectionSource::single(
1 ✔
1039
            MultiPolygonCollection::from_slices(
1 ✔
1040
                &[
1 ✔
1041
                    MultiPolygon::new(vec![vec![vec![
1 ✔
1042
                        (0., 0.).into(),
1 ✔
1043
                        (5., 0.).into(),
1 ✔
1044
                        (5., 6.).into(),
1 ✔
1045
                        (0., 6.).into(),
1 ✔
1046
                        (0., 0.).into(),
1 ✔
1047
                    ]]])
1 ✔
1048
                    .unwrap(),
1 ✔
1049
                    MultiPolygon::new(vec![vec![vec![
1 ✔
1050
                        (0.5, -0.5).into(),
1 ✔
1051
                        (4., -1.).into(),
1 ✔
1052
                        (0.5, -2.5).into(),
1 ✔
1053
                        (0.5, -0.5).into(),
1 ✔
1054
                    ]]])
1 ✔
1055
                    .unwrap(),
1 ✔
1056
                ],
1 ✔
1057
                &[TimeInterval::new_unchecked(0, 1); 2],
1 ✔
1058
                &[("foo", FeatureData::NullableFloat(vec![Some(1.0), None]))],
1 ✔
1059
            )
1060
            .unwrap(),
1 ✔
1061
        )
1062
        .boxed();
1 ✔
1063

1064
        let result = compute_result::<MultiPointCollection>(
1 ✔
1065
            VectorExpression {
1 ✔
1066
                params: VectorExpressionParams {
1 ✔
1067
                    input_columns: vec![],
1 ✔
1068
                    expression: "centroid(geom)".into(),
1 ✔
1069
                    output_column: OutputColumn::Geometry(GeoVectorDataType::MultiPoint),
1 ✔
1070
                    output_measurement: Measurement::Unitless,
1 ✔
1071
                    geometry_column_name: "geom".to_string(),
1 ✔
1072
                },
1 ✔
1073
                sources: polygons.into(),
1 ✔
1074
            },
1 ✔
1075
            VectorQueryRectangle::new(
1 ✔
1076
                BoundingBox2D::new((0., 0.).into(), (10., 10.).into()).unwrap(),
1 ✔
1077
                TimeInterval::default(),
1 ✔
1078
                ColumnSelection::all(),
1 ✔
1079
            ),
1 ✔
1080
        )
1 ✔
1081
        .await;
1 ✔
1082

1083
        let expected_result = MultiPointCollection::from_slices(
1 ✔
1084
            MultiPoint::many(vec![
1 ✔
1085
                (2.5, 3.0),
1 ✔
1086
                (1.666_666_666_666_666_7, -1.333_333_333_333_333_5),
1 ✔
1087
            ])
1 ✔
1088
            .unwrap()
1 ✔
1089
            .as_ref(),
1 ✔
1090
            &[TimeInterval::new_unchecked(0, 1); 2],
1 ✔
1091
            &[("foo", FeatureData::NullableFloat(vec![Some(1.0), None]))],
1 ✔
1092
        )
1093
        .unwrap();
1 ✔
1094

1095
        // TODO: maybe it is nicer to have something wrapping the actual data that we care about and just adds some cache info
1096
        assert!(
1 ✔
1097
            result.chunks_equal_ignoring_cache_hint(&expected_result),
1 ✔
1098
            "{result_geometries:#?} != {expected_result_geometries:#?}",
1 ✔
1099
            result_geometries = result.geometries().collect::<Vec<_>>(),
1 ✔
1100
            expected_result_geometries = expected_result.geometries().collect::<Vec<_>>(),
1 ✔
1101
        );
1 ✔
1102
    }
1 ✔
1103

1104
    #[tokio::test]
1105
    async fn it_computes_eight_larger_inputs() {
1 ✔
1106
        const NUMBER_OF_ROWS: usize = 100;
1107
        let points = MultiPointCollection::from_slices(
1 ✔
1108
            MultiPoint::many((0..NUMBER_OF_ROWS).map(|i| (i as f64, i as f64)).collect())
100 ✔
1109
                .unwrap()
1 ✔
1110
                .as_ref(),
1 ✔
1111
            &[TimeInterval::new_unchecked(0, 1); NUMBER_OF_ROWS],
1 ✔
1112
            &[
1113
                (
1114
                    "f1",
1115
                    FeatureData::Float((0..NUMBER_OF_ROWS).map(|i| i as f64).collect()),
100 ✔
1116
                ),
1117
                (
1118
                    "f2",
1 ✔
1119
                    FeatureData::Float((0..NUMBER_OF_ROWS).map(|i| i as f64).collect()),
100 ✔
1120
                ),
1121
                (
1122
                    "f3",
1 ✔
1123
                    FeatureData::Float((0..NUMBER_OF_ROWS).map(|i| i as f64).collect()),
100 ✔
1124
                ),
1125
                (
1126
                    "f4",
1 ✔
1127
                    FeatureData::Float((0..NUMBER_OF_ROWS).map(|i| i as f64).collect()),
100 ✔
1128
                ),
1129
                (
1130
                    "f5",
1 ✔
1131
                    FeatureData::Float((0..NUMBER_OF_ROWS).map(|i| i as f64).collect()),
100 ✔
1132
                ),
1133
                (
1134
                    "f6",
1 ✔
1135
                    FeatureData::Float((0..NUMBER_OF_ROWS).map(|i| i as f64).collect()),
100 ✔
1136
                ),
1137
                (
1138
                    "f7",
1 ✔
1139
                    FeatureData::Float((0..NUMBER_OF_ROWS).map(|i| i as f64).collect()),
100 ✔
1140
                ),
1141
                (
1142
                    "f8",
1 ✔
1143
                    FeatureData::Float((0..NUMBER_OF_ROWS).map(|i| i as f64).collect()),
100 ✔
1144
                ),
1145
            ],
1146
        )
1147
        .unwrap();
1 ✔
1148

1149
        let result = compute_result::<MultiPointCollection>(
1 ✔
1150
            VectorExpression {
1 ✔
1151
                params: VectorExpressionParams {
1 ✔
1152
                    input_columns: vec![
1 ✔
1153
                        "f1".into(),
1 ✔
1154
                        "f2".into(),
1 ✔
1155
                        "f3".into(),
1 ✔
1156
                        "f4".into(),
1 ✔
1157
                        "f5".into(),
1 ✔
1158
                        "f6".into(),
1 ✔
1159
                        "f7".into(),
1 ✔
1160
                        "f8".into(),
1 ✔
1161
                    ],
1 ✔
1162
                    expression: "f1 + f2 + f3 + f4 + f5 + f6 + f7 + f8".into(),
1 ✔
1163
                    output_column: OutputColumn::Column("new".into()),
1 ✔
1164
                    output_measurement: Measurement::Unitless,
1 ✔
1165
                    geometry_column_name: "geom".to_string(),
1 ✔
1166
                },
1 ✔
1167
                sources: MockFeatureCollectionSource::single(points.clone())
1 ✔
1168
                    .boxed()
1 ✔
1169
                    .into(),
1 ✔
1170
            },
1 ✔
1171
            VectorQueryRectangle::new(
1 ✔
1172
                BoundingBox2D::new(
1 ✔
1173
                    (0., 0.).into(),
1 ✔
1174
                    (NUMBER_OF_ROWS as f64, NUMBER_OF_ROWS as f64).into(),
1 ✔
1175
                )
1 ✔
1176
                .unwrap(),
1 ✔
1177
                TimeInterval::default(),
1 ✔
1178
                ColumnSelection::all(),
1 ✔
1179
            ),
1 ✔
1180
        )
1 ✔
1181
        .await;
1 ✔
1182

1183
        let expected_result = points
1 ✔
1184
            .add_column(
1 ✔
1185
                "new",
1 ✔
1186
                FeatureData::Float((0..NUMBER_OF_ROWS).map(|i| 8.0 * i as f64).collect()),
100 ✔
1187
            )
1188
            .unwrap();
1 ✔
1189

1190
        // TODO: maybe it is nicer to have something wrapping the actual data that we care about and just adds some cache info
1191
        assert!(
1 ✔
1192
            result.chunks_equal_ignoring_cache_hint(&expected_result),
1 ✔
1193
            "{result_geometries:#?} != {expected_result_geometries:#?}",
1 ✔
1194
            result_geometries = result.geometries().collect::<Vec<_>>(),
1 ✔
1195
            expected_result_geometries = expected_result.geometries().collect::<Vec<_>>(),
1 ✔
1196
        );
1 ✔
1197
    }
1 ✔
1198

1199
    async fn compute_result<C>(operator: VectorExpression, query_rectangle: VectorQueryRectangle) -> C
3 ✔
1200
    where
3 ✔
1201
        C: 'static,
3 ✔
1202
        Box<dyn VectorQueryProcessor<VectorType = C>>: TryFrom<TypedVectorQueryProcessor>,
3 ✔
1203
        <Box<dyn VectorQueryProcessor<VectorType = C>> as TryFrom<TypedVectorQueryProcessor>>::Error: std::fmt::Debug,
3 ✔
1204
    {
3 ✔
1205
        let operator = operator
3 ✔
1206
            .boxed()
3 ✔
1207
            .initialize(
3 ✔
1208
                WorkflowOperatorPath::initialize_root(),
3 ✔
1209
                &MockExecutionContext::test_default(),
3 ✔
1210
            )
3 ✔
1211
            .await
3 ✔
1212
            .unwrap();
3 ✔
1213

1214
        let query_processor: Box<dyn VectorQueryProcessor<VectorType = C>> =
3 ✔
1215
            operator.query_processor().unwrap().try_into().unwrap();
3 ✔
1216

1217
        let ecx = MockExecutionContext::test_default();
3 ✔
1218
        let ctx = ecx.mock_query_context(ChunkByteSize::MAX);
3 ✔
1219

1220
        let query = query_processor.query(query_rectangle, &ctx).await.unwrap();
3 ✔
1221

1222
        let mut result = query.map(Result::unwrap).collect::<Vec<C>>().await;
3 ✔
1223

1224
        assert_eq!(result.len(), 1);
3 ✔
1225
        result.remove(0)
3 ✔
1226
    }
3 ✔
1227
}
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