Skip to main content

vortex_spatial/extension/
coordinate.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Coordinate building blocks for geometry extension types: the `Struct<x, y[, z][, m]>` storage
5//! of non-nullable `f64` fields, its [`Dimension`], and the decoded [`Coordinate`] value.
6//!
7//! The coordinate fields are:
8//! - `x` — longitude or easting
9//! - `y` — latitude or northing
10//! - `z` (optional) — elevation
11//! - `m` (optional) — measure: an arbitrary per-point value such as distance along a route or a
12//!   timestamp
13
14use std::fmt::Display;
15use std::fmt::Formatter;
16
17use geoarrow::datatypes::Dimension as GeoArrowDimension;
18use vortex_array::ExecutionCtx;
19use vortex_array::arrays::StructArray;
20use vortex_array::arrays::struct_::StructArrayExt;
21use vortex_array::dtype::DType;
22use vortex_array::dtype::FieldNames;
23use vortex_array::dtype::Nullability;
24use vortex_array::dtype::PType;
25use vortex_array::dtype::StructFields;
26use vortex_array::scalar::Scalar;
27use vortex_buffer::Buffer;
28use vortex_error::VortexResult;
29use vortex_error::vortex_bail;
30use vortex_error::vortex_ensure;
31use vortex_error::vortex_err;
32
33/// Coordinate dimensions, matching GeoArrow. Field order is fixed: `x`, `y`, then `z` before `m`.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum Dimension {
36    /// 2D: `x`, `y`.
37    Xy,
38    /// 3D with elevation: `x`, `y`, `z`.
39    Xyz,
40    /// 3D with a measure: `x`, `y`, `m`.
41    Xym,
42    /// 4D: `x`, `y`, `z`, `m`.
43    Xyzm,
44}
45
46impl Dimension {
47    /// Recover the dimension from a coordinate's field names, in GeoArrow order.
48    pub(crate) fn from_field_names(names: &FieldNames) -> VortexResult<Dimension> {
49        let mut strs = [""; 4];
50        vortex_ensure!(
51            names.len() <= strs.len(),
52            "not a valid GeoArrow coordinate dimension: {names:?}"
53        );
54        for (slot, name) in strs.iter_mut().zip(names.iter()) {
55            *slot = name.as_ref();
56        }
57        Ok(match &strs[..names.len()] {
58            ["x", "y"] => Dimension::Xy,
59            ["x", "y", "z"] => Dimension::Xyz,
60            ["x", "y", "m"] => Dimension::Xym,
61            ["x", "y", "z", "m"] => Dimension::Xyzm,
62            _ => {
63                vortex_bail!("not a valid GeoArrow coordinate dimension: {names:?}")
64            }
65        })
66    }
67
68    /// The coordinate field names of this dimension, in GeoArrow order.
69    pub(crate) fn field_names(self) -> &'static [&'static str] {
70        match self {
71            Dimension::Xy => &["x", "y"],
72            Dimension::Xyz => &["x", "y", "z"],
73            Dimension::Xym => &["x", "y", "m"],
74            Dimension::Xyzm => &["x", "y", "z", "m"],
75        }
76    }
77
78    /// Promote two coordinate dimensions to the smallest dimension that represents both.
79    ///
80    /// Missing `z`/`m` ordinates are materialized as zero when values are converted to this
81    /// dimension, matching DuckDB Spatial's `ST_MakeLine` promotion.
82    pub(crate) fn promote(self, other: Self) -> Self {
83        match (self, other) {
84            (Self::Xyzm, _) | (_, Self::Xyzm) | (Self::Xyz, Self::Xym) | (Self::Xym, Self::Xyz) => {
85                Self::Xyzm
86            }
87            (Self::Xyz, _) | (_, Self::Xyz) => Self::Xyz,
88            (Self::Xym, _) | (_, Self::Xym) => Self::Xym,
89            (Self::Xy, Self::Xy) => Self::Xy,
90        }
91    }
92}
93
94impl From<GeoArrowDimension> for Dimension {
95    fn from(dim: GeoArrowDimension) -> Self {
96        match dim {
97            GeoArrowDimension::XY => Dimension::Xy,
98            GeoArrowDimension::XYZ => Dimension::Xyz,
99            GeoArrowDimension::XYM => Dimension::Xym,
100            GeoArrowDimension::XYZM => Dimension::Xyzm,
101        }
102    }
103}
104
105impl From<Dimension> for GeoArrowDimension {
106    fn from(dim: Dimension) -> Self {
107        match dim {
108            Dimension::Xy => GeoArrowDimension::XY,
109            Dimension::Xyz => GeoArrowDimension::XYZ,
110            Dimension::Xym => GeoArrowDimension::XYM,
111            Dimension::Xyzm => GeoArrowDimension::XYZM,
112        }
113    }
114}
115
116/// A decoded coordinate. `z`/`m` are `Some` iff the storage dimension includes them.
117///
118/// This is the native value produced when unpacking a [`Point`](crate::extension::Point) scalar;
119/// the rest of the coordinate machinery is crate-internal.
120#[derive(Debug, Clone, Copy, PartialEq)]
121pub struct Coordinate {
122    /// The x (longitude/easting) ordinate.
123    pub x: f64,
124    /// The y (latitude/northing) ordinate.
125    pub y: f64,
126    /// The optional `z` (elevation) ordinate.
127    pub z: Option<f64>,
128    /// The optional `m` (measure) ordinate.
129    pub m: Option<f64>,
130}
131
132impl Coordinate {
133    /// A 2D coordinate (`z`/`m` unset).
134    pub fn xy(x: f64, y: f64) -> Self {
135        Coordinate {
136            x,
137            y,
138            z: None,
139            m: None,
140        }
141    }
142}
143
144impl Display for Coordinate {
145    fn fmt(&self, fmt: &mut Formatter<'_>) -> std::fmt::Result {
146        match (self.z, self.m) {
147            (None, None) => write!(fmt, "POINT({} {})", self.x, self.y),
148            (Some(z), None) => write!(fmt, "POINT Z ({} {} {})", self.x, self.y, z),
149            (None, Some(m)) => write!(fmt, "POINT M ({} {} {})", self.x, self.y, m),
150            (Some(z), Some(m)) => write!(fmt, "POINT ZM ({} {} {} {})", self.x, self.y, z, m),
151        }
152    }
153}
154
155/// Returns the [`Dimension`] from a coordinate `Struct`'s field names in GeoArrow order.
156///
157/// Field dtypes and nullability are not checked. Reads compare the complete storage dtype with
158/// the declaration after recovering the dimension, so a mismatch reports both storage dtypes.
159pub(crate) fn coordinate_dimension(dtype: &DType) -> VortexResult<Dimension> {
160    let DType::Struct(fields, _) = dtype else {
161        vortex_bail!("coordinate storage must be a Struct, got {dtype}");
162    };
163    Dimension::from_field_names(fields.names())
164}
165
166/// The canonical storage dtype for `dim`: a `Struct` of non-nullable `f64` coordinate fields,
167/// with `nullability` at the struct (per-point) level. Inverse of [`coordinate_dimension`].
168pub(crate) fn coordinate_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
169    let names = dim.field_names();
170    let fields = std::iter::repeat_n(
171        DType::Primitive(PType::F64, Nullability::NonNullable),
172        names.len(),
173    )
174    .collect::<Vec<_>>();
175    DType::Struct(
176        StructFields::new(FieldNames::from(names), fields),
177        nullability,
178    )
179}
180
181/// Decode a [`Coordinate`] from a coordinate `Struct<x, y[, z][, m]>` scalar (`z`/`m` read iff
182/// present, so the same decoder serves every dimension).
183pub(crate) fn coordinate_from_struct(scalar: &Scalar) -> VortexResult<Coordinate> {
184    let fields = scalar.as_struct();
185    let required = |name: &str| -> VortexResult<f64> {
186        f64::try_from(
187            &fields
188                .field(name)
189                .ok_or_else(|| vortex_err!("coordinate missing {name}"))?,
190        )
191    };
192    let optional = |name: &str| -> VortexResult<Option<f64>> {
193        fields
194            .field(name)
195            .map(|value| f64::try_from(&value))
196            .transpose()
197    };
198    Ok(Coordinate {
199        x: required("x")?,
200        y: required("y")?,
201        z: optional("z")?,
202        m: optional("m")?,
203    })
204}
205
206/// Materialize the named ordinate (`x`, `y`, ...) of a coordinate `Struct` column as a flat
207/// [`Buffer`] for bulk reads.
208pub(crate) fn ordinates(
209    coords: &StructArray,
210    name: &str,
211    ctx: &mut ExecutionCtx,
212) -> VortexResult<Buffer<f64>> {
213    coords
214        .unmasked_field_by_name(name)?
215        .clone()
216        .execute::<Buffer<f64>>(ctx)
217}
218
219/// The corners of the box containing the `(xs, ys)` coordinates, in
220/// `[xmin, ymin, xmax, ymax]` order.
221pub(crate) fn box_corners(xs: &[f64], ys: &[f64]) -> [f64; 4] {
222    let (mut xmin, mut ymin) = (f64::INFINITY, f64::INFINITY);
223    let (mut xmax, mut ymax) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
224    for (&x, &y) in xs.iter().zip(ys) {
225        xmin = xmin.min(x);
226        ymin = ymin.min(y);
227        xmax = xmax.max(x);
228        ymax = ymax.max(y);
229    }
230    [xmin, ymin, xmax, ymax]
231}
232
233#[cfg(test)]
234mod tests {
235    use rstest::rstest;
236    use vortex_array::dtype::Nullability;
237    use vortex_error::VortexResult;
238
239    use super::Coordinate;
240    use super::Dimension;
241    use super::coordinate_dimension;
242    use super::coordinate_storage_dtype;
243
244    /// Each dimension round-trips through its field names and canonical storage dtype.
245    #[rstest]
246    #[case::xy(Dimension::Xy, &["x", "y"])]
247    #[case::xyz(Dimension::Xyz, &["x", "y", "z"])]
248    #[case::xym(Dimension::Xym, &["x", "y", "m"])]
249    #[case::xyzm(Dimension::Xyzm, &["x", "y", "z", "m"])]
250    fn storage_dtype_roundtrips_dimension(
251        #[case] dim: Dimension,
252        #[case] names: &[&str],
253    ) -> VortexResult<()> {
254        assert_eq!(dim.field_names(), names);
255        let dtype = coordinate_storage_dtype(dim, Nullability::NonNullable);
256        assert_eq!(coordinate_dimension(&dtype)?, dim);
257        Ok(())
258    }
259
260    /// Display emits WKT, including `z`/`m` when present.
261    #[rstest]
262    #[case::xy(None, None, "POINT(1 2)")]
263    #[case::xyz(Some(3.0), None, "POINT Z (1 2 3)")]
264    #[case::xym(None, Some(4.0), "POINT M (1 2 4)")]
265    #[case::xyzm(Some(3.0), Some(4.0), "POINT ZM (1 2 3 4)")]
266    fn display_is_wkt(#[case] z: Option<f64>, #[case] m: Option<f64>, #[case] expected: &str) {
267        let coordinate = Coordinate {
268            x: 1.0,
269            y: 2.0,
270            z,
271            m,
272        };
273        assert_eq!(coordinate.to_string(), expected);
274    }
275}