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