Skip to content
Open
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
2 changes: 2 additions & 0 deletions vortex-python/python/vortex/_lib/arrays.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ class ConstantArray(Array):
@final
class ChunkedArray(Array):
def chunks(self) -> list[Array]: ...
@staticmethod
def from_chunks(chunks: list[Array], *, dtype: DType | None = None) -> ChunkedArray: ...

@final
class ByteBoolArray(Array): ...
Expand Down
71 changes: 71 additions & 0 deletions vortex-python/src/arrays/builtins/chunked.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use pyo3::Bound;
use pyo3::PyRef;
use pyo3::exceptions::PyValueError;
use pyo3::pyclass;
use pyo3::pymethods;
use vortex::array::ArrayRef;
use vortex::array::IntoArray;
use vortex::array::arrays::Chunked;
use vortex::array::arrays::ChunkedArray;
use vortex::array::arrays::chunked::ChunkedArrayExt;

use crate::arrays::PyArrayRef;
use crate::arrays::native::EncodingSubclass;
use crate::arrays::native::PyNativeArray;
use crate::dtype::PyDType;
use crate::error::PyVortexResult;

/// Concrete class for arrays with `vortex.chunked` encoding.
#[pyclass(name = "ChunkedArray", module = "vortex", extends=PyNativeArray, frozen)]
Expand All @@ -30,4 +37,68 @@ impl PyChunkedArray {
.map(|chunk| PyArrayRef::from(chunk.clone()))
.collect()
}

/// Combine arrays of one data type into a chunked array, with no copy.
///
/// The chunks of a chunked array in `chunks` become chunks of the result, so the result has
/// one level of chunks. For example, the arrays that `read_all` gives for several files
/// combine into one array, and one `take` then reads rows of all the files.
///
/// Parameters
/// ----------
/// chunks: list[vortex.Array]
/// The arrays to combine, in order. They must all have the same data type.
/// dtype: vortex.DType | None
/// The data type of the result. It is necessary only when `chunks` is empty.
///
/// Returns
/// -------
/// :class:`~vortex.ChunkedArray`
///
/// Examples
/// --------
///
/// ```python
/// >>> a = vx.array([1, 2, 3])
/// >>> b = vx.array([4, 5])
/// >>> chunked = vx.ChunkedArray.from_chunks([a, b])
/// >>> chunked.take(vx.array([4, 0])).to_arrow_array()
/// <pyarrow.lib.Int64Array object at ...>
/// [
/// 5,
/// 1
/// ]
/// ```
#[staticmethod]
#[pyo3(signature = (chunks, *, dtype = None))]
fn from_chunks(
chunks: Vec<PyArrayRef>,
dtype: Option<Bound<PyDType>>,
) -> PyVortexResult<PyArrayRef> {
let mut flat: Vec<ArrayRef> = Vec::with_capacity(chunks.len());

for chunk in chunks {
let chunk = chunk.into_inner();

match chunk.as_opt::<Chunked>() {
Some(chunked) => flat.extend(chunked.iter_chunks().cloned()),
None => flat.push(chunk),
}
}

let dtype = match (dtype, flat.first()) {
(Some(dtype), _) => dtype.get().inner().clone(),
(None, Some(first)) => first.dtype().clone(),
(None, None) => {
return Err(PyValueError::new_err(
"Cannot infer the dtype of a chunked array with no chunks; pass dtype.",
)
.into());
}
};

Ok(PyArrayRef::from(
ChunkedArray::try_new(flat, dtype)?.into_array(),
))
}
}
30 changes: 30 additions & 0 deletions vortex-python/test/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,36 @@ def test_chunked_array_with_nulls_round_trip() -> None:
assert arr.to_arrow_array() == a


def test_chunked_array_from_chunks_takes_across_chunks() -> None:
a = vortex.array(pa.chunked_array([[0, 1, 2], [3, 4]]))
b = vortex.array(pa.array([5, 6, 7]))

chunked = vortex.ChunkedArray.from_chunks([a, b])

# The chunks of a chunked input become chunks of the result.
assert len(chunked.chunks()) == 3
assert len(chunked) == 8

taken = chunked.take(vortex.array(pa.array([7, 0, 3, 3, 5], type=pa.uint64())))
assert taken.to_arrow_array().equals(pa.array([7, 0, 3, 3, 5]))


def test_chunked_array_from_chunks_empty() -> None:
dtype = vortex.array(pa.array([1])).dtype

empty = vortex.ChunkedArray.from_chunks([], dtype=dtype)
assert len(empty) == 0
assert empty.dtype == dtype

with pytest.raises(ValueError):
vortex.ChunkedArray.from_chunks([])


def test_chunked_array_from_chunks_rejects_mixed_dtypes() -> None:
with pytest.raises(Exception):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pytest.raises(Exception) passes for any failure, including a bug in argument handling. Matching the specific error, for example with match="expected type", would show that the dtype check is what rejects it.

vortex.ChunkedArray.from_chunks([vortex.array(pa.array([1])), vortex.array(pa.array(["a"]))])


def test_decimal_array() -> None:
a = pa.array([decimal.Decimal("1.23"), None], type=pa.decimal128(10, 2))
arr = vortex.array(a)
Expand Down
Loading