Skip to main content

vortex_spatial/scalar_fn/
make_line.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! `ST_MakeLine`: construct a native line string between two native points.
5
6use vortex_array::ArrayRef;
7use vortex_array::ExecutionCtx;
8use vortex_array::IntoArray;
9use vortex_array::arrays::ConstantArray;
10use vortex_array::arrays::ScalarFnArray;
11use vortex_array::arrays::StructArray;
12use vortex_array::dtype::DType;
13use vortex_array::dtype::Nullability;
14use vortex_array::dtype::extension::ExtDType;
15use vortex_array::scalar_fn::Arity;
16use vortex_array::scalar_fn::ChildName;
17use vortex_array::scalar_fn::EmptyOptions;
18use vortex_array::scalar_fn::ExecutionArgs;
19use vortex_array::scalar_fn::ScalarFnId;
20use vortex_array::scalar_fn::ScalarFnVTable;
21use vortex_array::scalar_fn::TypedScalarFnInstance;
22use vortex_array::validity::Validity;
23use vortex_error::VortexResult;
24use vortex_error::vortex_ensure;
25use vortex_error::vortex_ensure_eq;
26use vortex_error::vortex_err;
27use vortex_mask::Mask;
28use vortex_session::VortexSession;
29use vortex_session::registry::CachedId;
30
31use crate::extension::LineString;
32use crate::extension::Point;
33use crate::extension::SpatialMetadata;
34use crate::extension::coordinate::coordinate_dimension;
35use crate::extension::flatten_coordinates;
36use crate::extension::linestring_array_from_point_pairs;
37use crate::extension::linestring_storage_dtype;
38use crate::scalar_fn::execute::Execution;
39use crate::scalar_fn::execute::Operand;
40use crate::scalar_fn::execute::dispatch_binary;
41
42/// Validate the two point operands accepted by `ST_MakeLine`.
43fn validate_make_line_operands(dtypes: &[DType]) -> VortexResult<()> {
44    vortex_ensure_eq!(
45        dtypes.len(),
46        2,
47        "spatial: make_line requires exactly two point operands"
48    );
49    for dtype in dtypes {
50        vortex_ensure!(
51            dtype
52                .as_extension_opt()
53                .is_some_and(|extension| extension.is::<Point>()),
54            "spatial: make_line operand {dtype} is not a native point"
55        );
56    }
57    Ok(())
58}
59
60/// Resolve DuckDB's `ST_MakeLine` CRS propagation for two geometry operands.
61fn make_line_metadata(
62    left: &SpatialMetadata,
63    right: &SpatialMetadata,
64) -> VortexResult<SpatialMetadata> {
65    match (&left.crs, &right.crs) {
66        (Some(left_crs), Some(right_crs)) => {
67            vortex_ensure_eq!(
68                left_crs,
69                right_crs,
70                "spatial: make_line operands have different coordinate reference systems"
71            );
72            Ok(left.clone())
73        }
74        (Some(_), None) => Ok(left.clone()),
75        (None, Some(_)) => Ok(right.clone()),
76        (None, None) => Ok(SpatialMetadata::default()),
77    }
78}
79
80/// The native `LineString` dtype emitted by `ST_MakeLine`.
81fn make_line_dtype(dtypes: &[DType]) -> VortexResult<ExtDType<LineString>> {
82    validate_make_line_operands(dtypes)?;
83    let left = dtypes[0].as_extension();
84    let right = dtypes[1].as_extension();
85    let dimension = coordinate_dimension(left.storage_dtype())?
86        .promote(coordinate_dimension(right.storage_dtype())?);
87    let metadata = make_line_metadata(left.metadata::<Point>(), right.metadata::<Point>())?;
88    let nullability = Nullability::from(dtypes.iter().any(DType::is_nullable));
89    ExtDType::try_new(metadata, linestring_storage_dtype(dimension, nullability))
90}
91
92/// Expose a point operand as coordinate fields without expanding a constant into value buffers.
93fn point_coordinates(
94    operand: Operand,
95    len: usize,
96    ctx: &mut ExecutionCtx,
97) -> VortexResult<StructArray> {
98    match operand {
99        Operand::Column(points) => flatten_coordinates(&points, ctx),
100        Operand::Constant(point) => {
101            let storage = point.as_extension().to_storage_scalar();
102            let fields = storage.as_struct();
103            let names = fields.names().clone();
104            let arrays = names
105                .iter()
106                .map(|name| {
107                    fields
108                        .field(name)
109                        .map(|value| ConstantArray::new(value, len).into_array())
110                        .ok_or_else(|| vortex_err!("spatial: point coordinate missing {name}"))
111                })
112                .collect::<VortexResult<Vec<_>>>()?;
113            StructArray::try_new(names, arrays, len, Validity::NonNullable)
114        }
115    }
116}
117
118/// Build a native line-string column from dispatched point operands.
119fn build_make_lines(
120    operands: [Operand; 2],
121    len: usize,
122    valid: Mask,
123    output_dtype: &ExtDType<LineString>,
124    ctx: &mut ExecutionCtx,
125) -> VortexResult<ArrayRef> {
126    let [start, end] = operands;
127    let starts = point_coordinates(start, len, ctx)?;
128    let ends = point_coordinates(end, len, ctx)?;
129    linestring_array_from_point_pairs(
130        output_dtype,
131        &starts,
132        &ends,
133        Validity::from_mask(valid, output_dtype.storage_dtype().nullability()),
134    )
135}
136
137/// Execute `ST_MakeLine` after shared constant/column and null dispatch.
138fn execute_make_line(
139    execution: Execution<2>,
140    output_dtype: &ExtDType<LineString>,
141    ctx: &mut ExecutionCtx,
142) -> VortexResult<ArrayRef> {
143    match execution.operands {
144        [Operand::Constant(start), Operand::Constant(end)] => {
145            let one = build_make_lines(
146                [Operand::Constant(start), Operand::Constant(end)],
147                1,
148                Mask::new_true(1),
149                output_dtype,
150                ctx,
151            )?;
152            Ok(ConstantArray::new(one.execute_scalar(0, ctx)?, execution.len).into_array())
153        }
154        operands => build_make_lines(operands, execution.len, execution.valid, output_dtype, ctx),
155    }
156}
157
158/// Construct `LineString`s from paired native point operands. The output's vertices preserve all
159/// coordinate ordinates (`x`, `y`, and any `z`/`m`) and appear in operand order. When the points
160/// have different dimensions, it promotes to their union and fills absent `z`/`m` ordinates with
161/// zero.
162#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
163pub struct SpatialMakeLine;
164
165impl SpatialMakeLine {
166    /// A lazy `ScalarFnArray` constructing one two-vertex line string per pair of point operands.
167    pub fn try_new(a: ArrayRef, b: ArrayRef) -> VortexResult<ScalarFnArray> {
168        ScalarFnArray::try_new(
169            TypedScalarFnInstance::new(SpatialMakeLine, EmptyOptions).erased(),
170            vec![a, b],
171        )
172    }
173}
174
175impl ScalarFnVTable for SpatialMakeLine {
176    type Options = EmptyOptions;
177
178    fn id(&self) -> ScalarFnId {
179        static ID: CachedId = CachedId::new("vortex.st.make_line");
180        *ID
181    }
182
183    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
184        Ok(Some(vec![]))
185    }
186
187    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
188        Ok(EmptyOptions)
189    }
190
191    fn arity(&self, _: &Self::Options) -> Arity {
192        Arity::Exact(2)
193    }
194
195    fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName {
196        match child_idx {
197            0 => ChildName::from("start"),
198            1 => ChildName::from("end"),
199            _ => unreachable!("make_line has exactly two children"),
200        }
201    }
202
203    fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult<DType> {
204        Ok(DType::Extension(make_line_dtype(dtypes)?.erased()))
205    }
206
207    fn execute(
208        &self,
209        _: &Self::Options,
210        args: &dyn ExecutionArgs,
211        ctx: &mut ExecutionCtx,
212    ) -> VortexResult<ArrayRef> {
213        let a = args.get(0)?;
214        let b = args.get(1)?;
215        let output_dtype = make_line_dtype(&[a.dtype().clone(), b.dtype().clone()])?;
216        dispatch_binary(
217            &a,
218            &b,
219            DType::Extension(output_dtype.clone().erased()),
220            |execution, ctx| execute_make_line(execution, &output_dtype, ctx),
221            ctx,
222        )
223    }
224
225    fn is_strict(&self, _: &Self::Options) -> bool {
226        true
227    }
228
229    fn is_infallible(&self, _: &Self::Options) -> bool {
230        true
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use geo_types::Coord;
237    use geo_types::Geometry;
238    use geo_types::LineString as GeoLineString;
239    use rstest::rstest;
240    use vortex_array::ArrayRef;
241    use vortex_array::Columnar;
242    use vortex_array::ExecutionCtx;
243    use vortex_array::IntoArray;
244    use vortex_array::VortexSessionExecute;
245    use vortex_array::arrays::ConstantArray;
246    use vortex_array::arrays::ExtensionArray;
247    use vortex_array::arrays::PrimitiveArray;
248    use vortex_array::arrays::StructArray;
249    use vortex_array::dtype::DType;
250    use vortex_array::dtype::extension::ExtDType;
251    use vortex_array::scalar::Scalar;
252    use vortex_array::scalar_fn::EmptyOptions;
253    use vortex_array::scalar_fn::ScalarFnVTable;
254    use vortex_error::VortexResult;
255    use vortex_error::vortex_err;
256
257    use super::SpatialMakeLine;
258    use crate::extension::LineString;
259    use crate::extension::Point;
260    use crate::extension::SpatialMetadata;
261    use crate::extension::coordinate::Dimension;
262    use crate::extension::coordinate::coordinate_dimension;
263    use crate::extension::coordinate::ordinates;
264    use crate::extension::flatten_coordinates;
265    use crate::extension::geometries;
266    use crate::test_harness::point_column;
267
268    fn dimensional_point(
269        dimension: Dimension,
270        coordinate: [f64; 4],
271        crs: Option<&str>,
272    ) -> VortexResult<ArrayRef> {
273        let mut fields = vec![
274            ("x", PrimitiveArray::from_iter([coordinate[0]]).into_array()),
275            ("y", PrimitiveArray::from_iter([coordinate[1]]).into_array()),
276        ];
277        if matches!(dimension, Dimension::Xyz | Dimension::Xyzm) {
278            fields.push(("z", PrimitiveArray::from_iter([coordinate[2]]).into_array()));
279        }
280        if matches!(dimension, Dimension::Xym | Dimension::Xyzm) {
281            fields.push(("m", PrimitiveArray::from_iter([coordinate[3]]).into_array()));
282        }
283        let storage = StructArray::from_fields(&fields)?.into_array();
284        let dtype = ExtDType::<Point>::try_new(
285            SpatialMetadata {
286                crs: crs.map(str::to_owned),
287            },
288            storage.dtype().clone(),
289        )?;
290        Ok(ExtensionArray::try_new(dtype.erased(), storage)?.into_array())
291    }
292
293    fn point_constant(
294        x: f64,
295        y: f64,
296        len: usize,
297        ctx: &mut ExecutionCtx,
298    ) -> VortexResult<ArrayRef> {
299        let scalar = point_column(vec![x], vec![y])?.execute_scalar(0, ctx)?;
300        Ok(ConstantArray::new(scalar, len).into_array())
301    }
302
303    #[test]
304    fn connects_paired_points_in_operand_order() -> VortexResult<()> {
305        let session = vortex_array::array_session();
306        let mut ctx = session.create_execution_ctx();
307        let starts = point_column(vec![0.0, 3.0], vec![0.0, 4.0])?;
308        let ends = point_column(vec![3.0, 0.0], vec![4.0, 0.0])?;
309
310        let lines = SpatialMakeLine::try_new(starts, ends)?.into_array();
311        assert!(lines.dtype().as_extension().is::<LineString>());
312        assert_eq!(
313            geometries(&lines, &mut ctx)?,
314            vec![
315                Geometry::LineString(GeoLineString::new(vec![
316                    Coord { x: 0.0, y: 0.0 },
317                    Coord { x: 3.0, y: 4.0 },
318                ])),
319                Geometry::LineString(GeoLineString::new(vec![
320                    Coord { x: 3.0, y: 4.0 },
321                    Coord { x: 0.0, y: 0.0 },
322                ])),
323            ]
324        );
325        Ok(())
326    }
327
328    #[test]
329    fn two_constants_are_built_once_and_remain_constant() -> VortexResult<()> {
330        let session = vortex_array::array_session();
331        let mut ctx = session.create_execution_ctx();
332        let starts = point_constant(0.0, 0.0, 3, &mut ctx)?;
333        let ends = point_constant(3.0, 4.0, 3, &mut ctx)?;
334
335        let result = SpatialMakeLine::try_new(starts, ends)?
336            .into_array()
337            .execute::<Columnar>(&mut ctx)?;
338        let Columnar::Constant(lines) = result else {
339            return Err(vortex_err!(
340                "make_line of two constants should remain constant"
341            ));
342        };
343        assert_eq!(lines.len(), 3);
344        assert_eq!(
345            geometries(&lines.into_array(), &mut ctx)?,
346            vec![
347                Geometry::LineString(GeoLineString::new(vec![
348                    Coord { x: 0.0, y: 0.0 },
349                    Coord { x: 3.0, y: 4.0 },
350                ]));
351                3
352            ]
353        );
354        Ok(())
355    }
356
357    #[rstest]
358    #[case::constant_start(true)]
359    #[case::constant_end(false)]
360    fn constant_and_column_are_paired_by_row(#[case] constant_start: bool) -> VortexResult<()> {
361        let session = vortex_array::array_session();
362        let mut ctx = session.create_execution_ctx();
363        let constant = point_constant(0.0, 0.0, 2, &mut ctx)?;
364        let column = point_column(vec![3.0, 6.0], vec![4.0, 8.0])?;
365        let (starts, ends) = if constant_start {
366            (constant, column)
367        } else {
368            (column, constant)
369        };
370
371        let lines = SpatialMakeLine::try_new(starts, ends)?.into_array();
372        let endpoints = [(3.0, 4.0), (6.0, 8.0)];
373        let expected = endpoints
374            .into_iter()
375            .map(|(x, y)| {
376                let constant = Coord { x: 0.0, y: 0.0 };
377                let column = Coord { x, y };
378                Geometry::LineString(GeoLineString::new(if constant_start {
379                    vec![constant, column]
380                } else {
381                    vec![column, constant]
382                }))
383            })
384            .collect::<Vec<_>>();
385        assert_eq!(geometries(&lines, &mut ctx)?, expected);
386        Ok(())
387    }
388
389    #[test]
390    fn null_constant_is_all_null() -> VortexResult<()> {
391        let session = vortex_array::array_session();
392        let mut ctx = session.create_execution_ctx();
393        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
394        let starts = ConstantArray::new(Scalar::null(point_dtype), 2).into_array();
395        let ends = point_column(vec![3.0, 6.0], vec![4.0, 8.0])?;
396
397        let result = SpatialMakeLine::try_new(starts, ends)?
398            .into_array()
399            .execute::<Columnar>(&mut ctx)?;
400        let Columnar::Constant(lines) = result else {
401            return Err(vortex_err!(
402                "make_line with a null constant should remain constant"
403            ));
404        };
405        assert_eq!(lines.len(), 2);
406        assert!(lines.scalar().is_null());
407        assert!(lines.dtype().as_extension().is::<LineString>());
408        Ok(())
409    }
410
411    #[rstest]
412    #[case::xy_xyz(
413        Dimension::Xy,
414        [1.0, 2.0, 0.0, 0.0],
415        Dimension::Xyz,
416        [3.0, 4.0, 5.0, 0.0],
417        Dimension::Xyz,
418        Some([0.0, 5.0]),
419        None
420    )]
421    #[case::xyz_xy(
422        Dimension::Xyz,
423        [1.0, 2.0, 5.0, 0.0],
424        Dimension::Xy,
425        [3.0, 4.0, 0.0, 0.0],
426        Dimension::Xyz,
427        Some([5.0, 0.0]),
428        None
429    )]
430    #[case::xym_xyz(
431        Dimension::Xym,
432        [1.0, 2.0, 0.0, 6.0],
433        Dimension::Xyz,
434        [3.0, 4.0, 5.0, 0.0],
435        Dimension::Xyzm,
436        Some([0.0, 5.0]),
437        Some([6.0, 0.0])
438    )]
439    #[case::xyz_xym(
440        Dimension::Xyz,
441        [1.0, 2.0, 5.0, 0.0],
442        Dimension::Xym,
443        [3.0, 4.0, 0.0, 6.0],
444        Dimension::Xyzm,
445        Some([5.0, 0.0]),
446        Some([0.0, 6.0])
447    )]
448    fn promotes_mixed_point_dimensions(
449        #[case] start_dimension: Dimension,
450        #[case] start: [f64; 4],
451        #[case] end_dimension: Dimension,
452        #[case] end: [f64; 4],
453        #[case] expected_dimension: Dimension,
454        #[case] expected_z: Option<[f64; 2]>,
455        #[case] expected_m: Option<[f64; 2]>,
456    ) -> VortexResult<()> {
457        let session = vortex_array::array_session();
458        let mut ctx = session.create_execution_ctx();
459        let expected_x = [start[0], end[0]];
460        let expected_y = [start[1], end[1]];
461        let start = dimensional_point(start_dimension, start, None)?;
462        let end = dimensional_point(end_dimension, end, None)?;
463
464        let lines = SpatialMakeLine::try_new(start, end)?.into_array();
465        let vertices = flatten_coordinates(&lines, &mut ctx)?;
466        assert_eq!(coordinate_dimension(vertices.dtype())?, expected_dimension);
467        for (name, expected) in [("x", expected_x), ("y", expected_y)] {
468            assert_eq!(ordinates(&vertices, name, &mut ctx)?.as_slice(), expected);
469        }
470        for (name, expected) in [("z", expected_z), ("m", expected_m)] {
471            if let Some(expected) = expected {
472                assert_eq!(ordinates(&vertices, name, &mut ctx)?.as_slice(), expected);
473            }
474        }
475        Ok(())
476    }
477
478    #[rstest]
479    #[case::matching(Some("EPSG:4326"), Some("EPSG:4326"), Some("EPSG:4326"))]
480    #[case::left_only(Some("EPSG:4326"), None, Some("EPSG:4326"))]
481    #[case::right_only(None, Some("EPSG:3857"), Some("EPSG:3857"))]
482    #[case::unreferenced(None, None, None)]
483    fn propagates_compatible_crs(
484        #[case] left_crs: Option<&str>,
485        #[case] right_crs: Option<&str>,
486        #[case] expected: Option<&str>,
487    ) -> VortexResult<()> {
488        let left = dimensional_point(Dimension::Xy, [0.0; 4], left_crs)?;
489        let right = dimensional_point(Dimension::Xy, [1.0; 4], right_crs)?;
490
491        let dtype = SpatialMakeLine.return_dtype(
492            &EmptyOptions,
493            &[left.dtype().clone(), right.dtype().clone()],
494        )?;
495        assert_eq!(
496            dtype.as_extension().metadata::<LineString>().crs.as_deref(),
497            expected
498        );
499        Ok(())
500    }
501
502    #[test]
503    fn rejects_mismatched_crs() -> VortexResult<()> {
504        let left = dimensional_point(Dimension::Xy, [0.0; 4], Some("EPSG:4326"))?;
505        let right = dimensional_point(Dimension::Xy, [1.0; 4], Some("EPSG:3857"))?;
506        assert!(
507            SpatialMakeLine
508                .return_dtype(
509                    &EmptyOptions,
510                    &[left.dtype().clone(), right.dtype().clone()]
511                )
512                .is_err()
513        );
514        Ok(())
515    }
516
517    #[test]
518    fn rejects_non_point_dtype() -> VortexResult<()> {
519        let points = point_column(vec![0.0], vec![0.0])?;
520        assert!(
521            SpatialMakeLine
522                .return_dtype(&EmptyOptions, std::slice::from_ref(points.dtype()))
523                .is_err()
524        );
525        let non_point = DType::Bool(vortex_array::dtype::Nullability::NonNullable);
526        assert!(
527            SpatialMakeLine
528                .return_dtype(&EmptyOptions, &[points.dtype().clone(), non_point])
529                .is_err()
530        );
531        Ok(())
532    }
533}