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 std::sync::LazyLock;
237
238    use geo_types::Coord;
239    use geo_types::Geometry;
240    use geo_types::LineString as GeoLineString;
241    use rstest::rstest;
242    use vortex_array::ArrayRef;
243    use vortex_array::Columnar;
244    use vortex_array::ExecutionCtx;
245    use vortex_array::IntoArray;
246    use vortex_array::VortexSessionExecute;
247    use vortex_array::arrays::ConstantArray;
248    use vortex_array::arrays::ExtensionArray;
249    use vortex_array::arrays::PrimitiveArray;
250    use vortex_array::arrays::StructArray;
251    use vortex_array::dtype::DType;
252    use vortex_array::dtype::extension::ExtDType;
253    use vortex_array::scalar::Scalar;
254    use vortex_array::scalar_fn::EmptyOptions;
255    use vortex_array::scalar_fn::ScalarFnVTable;
256    use vortex_error::VortexResult;
257    use vortex_error::vortex_err;
258    use vortex_session::VortexSession;
259
260    use super::SpatialMakeLine;
261    use crate::extension::LineString;
262    use crate::extension::Point;
263    use crate::extension::SpatialMetadata;
264    use crate::extension::coordinate::Dimension;
265    use crate::extension::coordinate::coordinate_dimension;
266    use crate::extension::coordinate::ordinates;
267    use crate::extension::flatten_coordinates;
268    use crate::extension::geometries;
269    use crate::test_harness::point_column;
270
271    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
272
273    fn dimensional_point(
274        dimension: Dimension,
275        coordinate: [f64; 4],
276        crs: Option<&str>,
277    ) -> VortexResult<ArrayRef> {
278        let mut fields = vec![
279            ("x", PrimitiveArray::from_iter([coordinate[0]]).into_array()),
280            ("y", PrimitiveArray::from_iter([coordinate[1]]).into_array()),
281        ];
282        if matches!(dimension, Dimension::Xyz | Dimension::Xyzm) {
283            fields.push(("z", PrimitiveArray::from_iter([coordinate[2]]).into_array()));
284        }
285        if matches!(dimension, Dimension::Xym | Dimension::Xyzm) {
286            fields.push(("m", PrimitiveArray::from_iter([coordinate[3]]).into_array()));
287        }
288        let storage = StructArray::from_fields(&fields)?.into_array();
289        let dtype = ExtDType::<Point>::try_new(
290            SpatialMetadata {
291                crs: crs.map(str::to_owned),
292            },
293            storage.dtype().clone(),
294        )?;
295        Ok(ExtensionArray::try_new(dtype.erased(), storage)?.into_array())
296    }
297
298    fn point_constant(
299        x: f64,
300        y: f64,
301        len: usize,
302        ctx: &mut ExecutionCtx,
303    ) -> VortexResult<ArrayRef> {
304        let scalar = point_column(vec![x], vec![y])?.execute_scalar(0, ctx)?;
305        Ok(ConstantArray::new(scalar, len).into_array())
306    }
307
308    #[test]
309    fn connects_paired_points_in_operand_order() -> VortexResult<()> {
310        let mut ctx = SESSION.create_execution_ctx();
311        let starts = point_column(vec![0.0, 3.0], vec![0.0, 4.0])?;
312        let ends = point_column(vec![3.0, 0.0], vec![4.0, 0.0])?;
313
314        let lines = SpatialMakeLine::try_new(starts, ends)?.into_array();
315        assert!(lines.dtype().as_extension().is::<LineString>());
316        assert_eq!(
317            geometries(&lines, &mut ctx)?,
318            vec![
319                Geometry::LineString(GeoLineString::new(vec![
320                    Coord { x: 0.0, y: 0.0 },
321                    Coord { x: 3.0, y: 4.0 },
322                ])),
323                Geometry::LineString(GeoLineString::new(vec![
324                    Coord { x: 3.0, y: 4.0 },
325                    Coord { x: 0.0, y: 0.0 },
326                ])),
327            ]
328        );
329        Ok(())
330    }
331
332    #[test]
333    fn two_constants_are_built_once_and_remain_constant() -> VortexResult<()> {
334        let mut ctx = SESSION.create_execution_ctx();
335        let starts = point_constant(0.0, 0.0, 3, &mut ctx)?;
336        let ends = point_constant(3.0, 4.0, 3, &mut ctx)?;
337
338        let result = SpatialMakeLine::try_new(starts, ends)?
339            .into_array()
340            .execute::<Columnar>(&mut ctx)?;
341        let Columnar::Constant(lines) = result else {
342            return Err(vortex_err!(
343                "make_line of two constants should remain constant"
344            ));
345        };
346        assert_eq!(lines.len(), 3);
347        assert_eq!(
348            geometries(&lines.into_array(), &mut ctx)?,
349            vec![
350                Geometry::LineString(GeoLineString::new(vec![
351                    Coord { x: 0.0, y: 0.0 },
352                    Coord { x: 3.0, y: 4.0 },
353                ]));
354                3
355            ]
356        );
357        Ok(())
358    }
359
360    #[rstest]
361    #[case::constant_start(true)]
362    #[case::constant_end(false)]
363    fn constant_and_column_are_paired_by_row(#[case] constant_start: bool) -> VortexResult<()> {
364        let mut ctx = SESSION.create_execution_ctx();
365        let constant = point_constant(0.0, 0.0, 2, &mut ctx)?;
366        let column = point_column(vec![3.0, 6.0], vec![4.0, 8.0])?;
367        let (starts, ends) = if constant_start {
368            (constant, column)
369        } else {
370            (column, constant)
371        };
372
373        let lines = SpatialMakeLine::try_new(starts, ends)?.into_array();
374        let endpoints = [(3.0, 4.0), (6.0, 8.0)];
375        let expected = endpoints
376            .into_iter()
377            .map(|(x, y)| {
378                let constant = Coord { x: 0.0, y: 0.0 };
379                let column = Coord { x, y };
380                Geometry::LineString(GeoLineString::new(if constant_start {
381                    vec![constant, column]
382                } else {
383                    vec![column, constant]
384                }))
385            })
386            .collect::<Vec<_>>();
387        assert_eq!(geometries(&lines, &mut ctx)?, expected);
388        Ok(())
389    }
390
391    #[test]
392    fn null_constant_is_all_null() -> VortexResult<()> {
393        let mut ctx = SESSION.create_execution_ctx();
394        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
395        let starts = ConstantArray::new(Scalar::null(point_dtype), 2).into_array();
396        let ends = point_column(vec![3.0, 6.0], vec![4.0, 8.0])?;
397
398        let result = SpatialMakeLine::try_new(starts, ends)?
399            .into_array()
400            .execute::<Columnar>(&mut ctx)?;
401        let Columnar::Constant(lines) = result else {
402            return Err(vortex_err!(
403                "make_line with a null constant should remain constant"
404            ));
405        };
406        assert_eq!(lines.len(), 2);
407        assert!(lines.scalar().is_null());
408        assert!(lines.dtype().as_extension().is::<LineString>());
409        Ok(())
410    }
411
412    #[rstest]
413    #[case::xy_xyz(
414        Dimension::Xy,
415        [1.0, 2.0, 0.0, 0.0],
416        Dimension::Xyz,
417        [3.0, 4.0, 5.0, 0.0],
418        Dimension::Xyz,
419        Some([0.0, 5.0]),
420        None
421    )]
422    #[case::xyz_xy(
423        Dimension::Xyz,
424        [1.0, 2.0, 5.0, 0.0],
425        Dimension::Xy,
426        [3.0, 4.0, 0.0, 0.0],
427        Dimension::Xyz,
428        Some([5.0, 0.0]),
429        None
430    )]
431    #[case::xym_xyz(
432        Dimension::Xym,
433        [1.0, 2.0, 0.0, 6.0],
434        Dimension::Xyz,
435        [3.0, 4.0, 5.0, 0.0],
436        Dimension::Xyzm,
437        Some([0.0, 5.0]),
438        Some([6.0, 0.0])
439    )]
440    #[case::xyz_xym(
441        Dimension::Xyz,
442        [1.0, 2.0, 5.0, 0.0],
443        Dimension::Xym,
444        [3.0, 4.0, 0.0, 6.0],
445        Dimension::Xyzm,
446        Some([5.0, 0.0]),
447        Some([0.0, 6.0])
448    )]
449    fn promotes_mixed_point_dimensions(
450        #[case] start_dimension: Dimension,
451        #[case] start: [f64; 4],
452        #[case] end_dimension: Dimension,
453        #[case] end: [f64; 4],
454        #[case] expected_dimension: Dimension,
455        #[case] expected_z: Option<[f64; 2]>,
456        #[case] expected_m: Option<[f64; 2]>,
457    ) -> VortexResult<()> {
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}