Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 58.1.1

### Bug fixes

- `GeoArrowVctr`'s chunk accessors now honour the vctr's selection. A `nanoarrow_vctr` is an integer vector of 1 based rows into its chunks, and slicing one in R usually narrows those integers while leaving the chunks whole. The accessors read only the chunks, so a slice was silently ignored and the caller got every row: `as_point_chunks()` on a 3 row slice of a 100 row column returned all 100. Rows are now selected in the order the vctr gives them, with `NA` read as a null element. A contiguous run is a zero copy slice and the unsliced case still returns the chunks untouched, so neither pays for the fix.

## 58.1.0

### New features
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "arrow_extendr"
version = "58.1.0"
version = "58.1.1"
edition = "2024"
# matches arrow
rust-version = "1.85.0"
Expand Down
139 changes: 135 additions & 4 deletions src/geoarrow/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ use std::sync::Arc;

use anyhow::{anyhow, bail};
use arrow::{
array::{Array, make_array},
array::{Array, UInt32Array, make_array},
compute::take,
datatypes::Field,
ffi::{self, FFI_ArrowSchema},
};
Expand Down Expand Up @@ -174,6 +175,12 @@ impl_to_arrow_robj_geoarrow!(
/// with a list of `chunks` where each is its own geoarrow array
/// the `schema` is stored in the attribute `schema`
/// classes are: "geoarrow_vctr" "nanoarrow_vctr"
///
/// The integer vector itself is the selection: each element is a 1 based row
/// into the chunks laid end to end, and `NA` is a null element. The `offsets`
/// attribute says where each chunk starts in that run. Slicing a vctr in R
/// usually narrows the integers and leaves the chunks whole, so the chunk
/// accessors apply the selection rather than returning the chunks as they are.
pub struct GeoArrowVctr(Integers);

impl TryFrom<&Robj> for GeoArrowVctr {
Expand Down Expand Up @@ -215,18 +222,142 @@ impl GeoArrowVctr {
.ok_or_else(|| anyhow!("`schema` attribute missing"))
}

/// Where each chunk starts among the rows the index vector addresses.
fn offsets(&self) -> anyhow::Result<Vec<usize>> {
let attr = self
.0
.get_attrib("offsets")
.ok_or_else(|| anyhow!("`offsets` attribute missing"))?;
let offsets = Integers::try_from(attr).map_err(|e| anyhow!("{e}"))?;
offsets
.iter()
.map(|o| {
Option::<i32>::from(o)
.filter(|v| *v >= 0)
.map(|v| v as usize)
.ok_or_else(|| anyhow!("`offsets` must hold no NA or negative value"))
})
.collect()
}

/// Which chunk a 1 based row falls in, or `None` when the row is `NA`.
fn chunk_of(
offsets: &[usize],
row: Option<i32>,
total: usize,
) -> anyhow::Result<Option<usize>> {
let Some(row) = row else {
return Ok(None);
};
if row < 1 || row as usize > total {
bail!("row {row} is out of bounds for a vctr of {total} rows");
}
// partition_point rather than binary_search, so a zero length chunk is skipped
Ok(Some(offsets.partition_point(|&o| o < row as usize) - 1))
}

/// Pull one run of rows, all in the same chunk or all `NA`, out as a single array.
fn gather(
chunks: &[Arc<dyn Array>],
offsets: &[usize],
chunk: Option<usize>,
rows: &[Option<i32>],
) -> anyhow::Result<Arc<dyn Array>> {
let Some(chunk) = chunk else {
// an NA row is a null element, which a null index makes for any type
let nulls = UInt32Array::from(vec![None; rows.len()]);
return Ok(take(chunks[0].as_ref(), &nulls, None)?);
};

let base = offsets[chunk];
let positions = rows
.iter()
.filter_map(|row| *row)
.map(|row| (row as usize - 1 - base) as u32)
.collect::<Vec<_>>();

// a contiguous ascending run is a slice, which copies nothing
if positions.windows(2).all(|w| w[1] == w[0] + 1) {
if let Some(first) = positions.first().copied() {
return Ok(chunks[chunk].slice(first as usize, positions.len()));
}
}

let idx = UInt32Array::from(positions);
Ok(take(chunks[chunk].as_ref(), &idx, None)?)
}

/// Narrow the chunks to the rows the vctr selects, in the order it selects them.
fn select(&self, chunks: Vec<Arc<dyn Array>>) -> anyhow::Result<Vec<Arc<dyn Array>>> {
let offsets = self.offsets()?;
if offsets.len() != chunks.len() + 1 {
bail!(
"`offsets` has {} entries for {} chunks, expected {}",
offsets.len(),
chunks.len(),
chunks.len() + 1
);
}
if offsets[0] != 0 {
bail!("`offsets` must start at 0, got {}", offsets[0]);
}

let total = offsets[chunks.len()];
let rows = self.0.iter().map(Option::<i32>::from).collect::<Vec<_>>();

// the whole vctr in order, where the chunks already are the answer
if rows.len() == total
&& rows
.iter()
.enumerate()
.all(|(i, row)| *row == Some(i as i32 + 1))
{
return Ok(chunks);
}

if chunks.is_empty() {
return Ok(chunks);
}

let mut out = Vec::new();
let mut start = 0;
while start < rows.len() {
let here = Self::chunk_of(&offsets, rows[start], total)?;
let mut end = start + 1;
while end < rows.len() && Self::chunk_of(&offsets, rows[end], total)? == here {
end += 1;
}
out.push(Self::gather(&chunks, &offsets, here, &rows[start..end])?);
start = end;
}

// an empty selection still needs a chunk to carry the type
if out.is_empty() {
out.push(chunks[0].slice(0, 0));
}

Ok(out)
}

fn iter_arrow(&self) -> anyhow::Result<Vec<(Arc<dyn Array>, Field)>> {
let schema = self.schema()?;
let ffi_schema = crate::nanoarrow::c_export_schema(&schema)?;
let field = Field::try_from(ffi_schema)?;
self.chunks()?
let chunks = self
.chunks()?
.iter()
.map(|(_, chunk)| {
let ffi_array = crate::nanoarrow::c_export_array(&chunk)?;
let array_data = unsafe { ffi::from_ffi(ffi_array, ffi_schema)? };
Ok((make_array(array_data), field.clone()))
Ok(make_array(array_data))
})
.collect()
.collect::<anyhow::Result<Vec<_>>>()?;

Ok(self
.select(chunks)?
.into_iter()
.map(|array| (array, field.clone()))
.collect())
}

pub fn as_point_chunks(&self) -> anyhow::Result<Vec<PointArray>> {
Expand Down
108 changes: 108 additions & 0 deletions tests/geoarrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,111 @@ fn test_geoarrow_geometry_collection_roundtrip() -> anyhow::Result<()> {
.map_err(|e| anyhow::anyhow!("{e}"))?;
Ok(())
}

/// The WKT of every row the chunks hold, laid end to end, as R sees it.
fn chunks_wkt(chunks: Vec<PointArray>) -> extendr_api::Result<extendr_api::Robj> {
let parts = chunks
.into_iter()
.map(|chunk| chunk.into_arrow_robj())
.collect::<extendr_api::Result<Vec<_>>>()?;
let list = extendr_api::prelude::List::from_values(parts);
R!("unlist(lapply({{list}}, function(a) geoarrow::geoarrow_handle(a, wk::wkt_writer())))")
}

fn point_chunks_of(r_expr: &str) -> extendr_api::Result<Vec<PointArray>> {
let vctr = extendr_api::eval_string(r_expr)?;
arrow_extendr::geoarrow::GeoArrowVctr::try_from(&vctr)
.and_then(|v| v.as_point_chunks())
.map_err(|e| extendr_api::Error::Other(e.to_string()))
}

fn assert_wkt(r_expr: &str, expected: &str) -> anyhow::Result<()> {
with_r(|| {
let chunks = point_chunks_of(r_expr)?;
let got = chunks_wkt(chunks)?;
let report = format!("{got:?}");
let expected_robj = extendr_api::eval_string(expected)?;
let same = R!("identical({{got}}, {{expected_robj}})")?;
assert!(
same.as_logical().map(|v| v.is_true()).unwrap_or(false),
"{r_expr} gave {report}, expected {expected}"
);
Ok::<(), extendr_api::Error>(())
})
.map_err(|e| anyhow::anyhow!("{e}"))?;
Ok(())
}

const PTS: &str = "geoarrow::as_geoarrow_vctr(wk::xy(1:5, 6:10))";

#[test]
#[serial]
fn test_geoarrow_vctr_reads_every_row() -> anyhow::Result<()> {
assert_wkt(
PTS,
"c('POINT (1 6)', 'POINT (2 7)', 'POINT (3 8)', 'POINT (4 9)', 'POINT (5 10)')",
)
}

#[test]
#[serial]
fn test_geoarrow_vctr_respects_a_contiguous_slice() -> anyhow::Result<()> {
assert_wkt(
&format!("{PTS}[2:4]"),
"c('POINT (2 7)', 'POINT (3 8)', 'POINT (4 9)')",
)
}

#[test]
#[serial]
fn test_geoarrow_vctr_respects_a_single_row() -> anyhow::Result<()> {
assert_wkt(&format!("{PTS}[4]"), "'POINT (4 9)'")
}

#[test]
#[serial]
fn test_geoarrow_vctr_respects_a_reordering() -> anyhow::Result<()> {
assert_wkt(
&format!("{PTS}[c(5L, 1L, 3L)]"),
"c('POINT (5 10)', 'POINT (1 6)', 'POINT (3 8)')",
)
}

#[test]
#[serial]
fn test_geoarrow_vctr_respects_a_repeat() -> anyhow::Result<()> {
assert_wkt(
&format!("{PTS}[c(2L, 2L)]"),
"c('POINT (2 7)', 'POINT (2 7)')",
)
}

#[test]
#[serial]
fn test_geoarrow_vctr_reads_na_as_a_null() -> anyhow::Result<()> {
assert_wkt(&format!("{PTS}[NA_integer_]"), "NA_character_")
}

#[test]
#[serial]
fn test_geoarrow_vctr_reads_an_empty_selection() -> anyhow::Result<()> {
with_r(|| {
let chunks = point_chunks_of(&format!("{PTS}[0]"))?;
assert_eq!(chunks.iter().map(|c| c.len()).sum::<usize>(), 0);
// an empty selection still carries the type, so callers can read it
assert_eq!(chunks.len(), 1);
Ok::<(), extendr_api::Error>(())
})
.map_err(|e| anyhow::anyhow!("{e}"))?;
Ok(())
}

#[test]
#[serial]
fn test_geoarrow_vctr_slices_across_chunks() -> anyhow::Result<()> {
let two = format!("vctrs::vec_c({PTS}, {PTS})");
assert_wkt(
&format!("{two}[4:7]"),
"c('POINT (4 9)', 'POINT (5 10)', 'POINT (1 6)', 'POINT (2 7)')",
)
}
Loading