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