use arrow_array::ArrayRef as ArrowArrayRef;
use arrow_schema::Field;
use arrow_schema::extension::ExtensionType;
use geo_traits::to_geo::ToGeoGeometry;
use geo_types::Geometry;
use geoarrow::array::GeoArrowArrayAccessor;
use geoarrow::array::IntoArrow;
use geoarrow::array::PointArray;
use geoarrow::datatypes::CoordType;
use geoarrow::datatypes::PointType;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::arrays::ExtensionArray;
use vortex_array::arrays::extension::ExtensionArrayExt;
use vortex_array::dtype::DType;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::extension::ExtDType;
use vortex_array::dtype::extension::ExtId;
use vortex_array::dtype::extension::ExtVTable;
use vortex_array::scalar::Scalar;
use vortex_array::scalar::ScalarValue;
use vortex_arrow::ArrowExport;
use vortex_arrow::ArrowExportOptions;
use vortex_arrow::ArrowExtVTable;
use vortex_arrow::ArrowImport;
use vortex_arrow::ArrowMetadataPolicy;
use vortex_arrow::ArrowSession;
use vortex_arrow::ArrowSessionExt;
use vortex_arrow::ExecuteArrowExt;
use vortex_error::VortexError;
use vortex_error::VortexResult;
use vortex_error::vortex_ensure;
use vortex_error::vortex_err;
use vortex_session::registry::CachedId;
use vortex_session::registry::Id;
use super::SpatialMetadata;
use super::coordinate::Coordinate;
use super::coordinate::Dimension;
use super::coordinate::coordinate_dimension;
use super::coordinate::coordinate_from_struct;
use super::coordinate::coordinate_storage_dtype;
use super::geoarrow_metadata;
use super::geoarrow_to_wkb;
use super::spatial_metadata_from_arrow;
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct Point;
impl ExtVTable for Point {
type Metadata = SpatialMetadata;
type StoredMetadata = super::SpatialStoredMetadata;
type NativeValue<'a> = Coordinate;
fn id(&self) -> ExtId {
static ID: CachedId = CachedId::new("vortex.st.point");
*ID
}
fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
Ok(metadata.serialize())
}
fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::StoredMetadata> {
super::SpatialStoredMetadata::deserialize(metadata)
}
fn metadata_from_storage(
&self,
stored_metadata: Self::StoredMetadata,
storage_dtype: &DType,
) -> VortexResult<Self::Metadata> {
Ok(SpatialMetadata::from_stored_metadata(
stored_metadata,
Some(coordinate_dimension(storage_dtype)?),
))
}
fn storage_dtype(metadata: &Self::Metadata) -> DType {
coordinate_storage_dtype(metadata.native_dimension(), Nullability::NonNullable)
}
fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
metadata.validate_native(Point.id())
}
fn unpack_native<'a>(
ext_dtype: &'a ExtDType<Self>,
storage_value: &'a ScalarValue,
) -> VortexResult<Coordinate> {
let storage = Scalar::try_new(
ext_dtype.storage_dtype().clone(),
Some(storage_value.clone()),
)?;
coordinate_from_struct(&storage)
}
}
static ARROW_POINT: CachedId = CachedId::new(PointType::NAME);
fn point_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> PointType {
PointType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
}
pub struct PointData(ExtensionArray);
impl TryFrom<ExtensionArray> for PointData {
type Error = VortexError;
fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
vortex_ensure!(
ext.ext_dtype().is::<Point>(),
"expected a Point extension array"
);
Ok(PointData(ext))
}
}
impl PointData {
pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
geoarrow_to_wkb(
&point_array(self.0.storage_array(), ctx)?,
&ctx.session().arrow(),
)
}
}
fn point_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PointArray> {
let point_type = point_type(
&SpatialMetadata::default(),
coordinate_dimension(storage.dtype())?,
);
let arrow = storage.clone().execute_arrow(None, ctx)?;
PointArray::try_from((arrow.as_ref(), point_type))
.map_err(|e| vortex_err!("failed to construct PointArray: {e}"))
}
pub(crate) fn point_geometries(
storage: &ArrayRef,
ctx: &mut ExecutionCtx,
) -> VortexResult<Vec<Geometry<f64>>> {
point_array(storage, ctx)?
.iter()
.map(|geometry| -> VortexResult<Geometry<f64>> {
Ok(geometry
.ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
.map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
.to_geometry())
})
.collect()
}
impl ArrowExtVTable for Point {
fn metadata_policy() -> ArrowMetadataPolicy {
ArrowMetadataPolicy::ArrowNative
}
fn arrow_ext_id(&self) -> Id {
*ARROW_POINT
}
fn to_arrow_field(
&self,
name: &str,
ext_dtype: &ExtDType<Self>,
session: &ArrowSession,
) -> VortexResult<Option<Field>> {
let spatial_metadata = ext_dtype.metadata();
let dimension = spatial_metadata.native_dimension();
let mut field = session.to_arrow_field(name, ext_dtype.storage_dtype())?;
field.try_with_extension_type(point_type(spatial_metadata, dimension))?;
Ok(Some(field))
}
fn execute_arrow(
&self,
array: ArrayRef,
target: &Field,
options: &ArrowExportOptions,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrowExport> {
let Ok(point_meta) = target.try_extension_type::<PointType>() else {
return Ok(ArrowExport::Unsupported(array));
};
if point_meta.coord_type() != CoordType::Separated {
return Ok(ArrowExport::Unsupported(array));
}
let executed = array.execute::<ExtensionArray>(ctx)?;
let storage = executed.storage_array().clone();
let storage_field = Field::new(
String::new(),
target.data_type().clone(),
target.is_nullable(),
);
let arrow_storage =
storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?;
let points = PointArray::try_from((arrow_storage.as_ref(), point_meta))
.map_err(|e| vortex_err!("failed to construct PointArray: {e}"))?;
Ok(ArrowExport::Exported(points.into_arrow()))
}
fn from_arrow_field(
field: &Field,
_session: &ArrowSession,
) -> VortexResult<Option<ExtDType<Self>>> {
let point_meta = field.try_extension_type::<PointType>()?;
vortex_ensure!(
point_meta.coord_type() == CoordType::Separated,
"geoarrow.point with interleaved coordinates is not supported; \
re-encode with separated (struct) coordinates"
);
let metadata = spatial_metadata_from_arrow(point_meta.metadata())
.with_dimension(point_meta.dimension().into());
Ok(Some(ExtDType::try_with_vtable(
Point,
metadata,
field.is_nullable().into(),
)?))
}
fn from_arrow_array(
array: ArrowArrayRef,
_field: &Field,
ext_dtype: &ExtDType<Self>,
session: &ArrowSession,
) -> VortexResult<ArrowImport> {
session
.from_arrow_storage(array, &ext_dtype.clone().erased())
.map(ArrowImport::Imported)
}
}
#[cfg(test)]
mod tests {
use std::sync::LazyLock;
use rstest::rstest;
use vortex_array::IntoArray;
use vortex_array::VortexSessionExecute;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::StructArray;
use vortex_array::dtype::DType;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::PType;
use vortex_array::dtype::extension::ExtDType;
use vortex_array::dtype::extension::ExtDTypePlugin;
use vortex_array::flatbuffers::WriteFlatBufferExt;
use vortex_error::VortexResult;
use vortex_session::VortexSession;
use super::Point;
use crate::extension::SpatialMetadata;
use crate::extension::coordinate::Coordinate;
use crate::extension::coordinate::Dimension;
use crate::extension::coordinate::coordinate_storage_dtype;
use crate::test_harness::coordinate_from_scalar;
use crate::test_harness::point_column;
use crate::test_harness::spatial_session;
static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
fn spatial_meta() -> SpatialMetadata {
SpatialMetadata::new(Some("EPSG:4326".to_string()))
}
#[rstest]
#[case::xy(Dimension::Xy)]
#[case::xyz(Dimension::Xyz)]
#[case::xym(Dimension::Xym)]
#[case::xyzm(Dimension::Xyzm)]
fn point_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
let storage = coordinate_storage_dtype(dim, Nullability::NonNullable);
Point.deserialize(&spatial_meta().serialize(), storage)?;
Ok(())
}
#[test]
fn point_dtype_roundtrips_through_flatbuffer() -> VortexResult<()> {
let metadata = spatial_meta().with_dimension(Dimension::Xyz);
let dtype =
DType::Extension(ExtDType::<Point>::try_new(metadata, Nullability::Nullable)?.erased());
let bytes = dtype.write_flatbuffer_bytes()?;
assert_eq!(DType::from_flatbuffer(bytes, &spatial_session())?, dtype);
Ok(())
}
#[test]
fn point_rejects_invalid_storage() -> VortexResult<()> {
let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
assert!(
Point
.deserialize(&spatial_meta().serialize(), primitive)
.is_err()
);
let wrong_fields = StructArray::from_fields(&[
("a", PrimitiveArray::from_iter(vec![0.0f64]).into_array()),
("b", PrimitiveArray::from_iter(vec![0.0f64]).into_array()),
])?
.into_array();
assert!(
Point
.deserialize(&spatial_meta().serialize(), wrong_fields.dtype().clone())
.is_err()
);
Ok(())
}
#[test]
fn point_unpacks_coordinates() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let points = point_column(vec![1.0, -111.7610], vec![2.0, 34.8697])?;
assert_eq!(
coordinate_from_scalar(&points.execute_scalar(0, &mut ctx)?)?,
Coordinate::xy(1.0, 2.0)
);
assert_eq!(
coordinate_from_scalar(&points.execute_scalar(1, &mut ctx)?)?,
Coordinate::xy(-111.7610, 34.8697)
);
Ok(())
}
}