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