vortex_spatial/extension/
coordinate.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum Dimension {
36 Xy,
38 Xyz,
40 Xym,
42 Xyzm,
44}
45
46impl Dimension {
47 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 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 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#[derive(Debug, Clone, Copy, PartialEq)]
121pub struct Coordinate {
122 pub x: f64,
124 pub y: f64,
126 pub z: Option<f64>,
128 pub m: Option<f64>,
130}
131
132impl Coordinate {
133 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
155pub(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
166pub(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
181pub(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
206pub(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
219pub(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 #[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 #[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}