numbarrow.utils

The two modules of this package hold the code that numbarrow.core.adapters is built on. Most programs need neither: arrow_array_adapter() chooses the right conversion, and the arrays it returns stay valid for as long as the caller holds them.

numbarrow.utils.utils

Overview

The functions of this module let compiled code view raw memory as a numpy array. The dict arrays_viewers maps a numpy dtype to a jitted function, called a viewer, that takes a memory address and an element count. The viewer returns a numpy array of that dtype over the memory at the address, without a copy. The adapters pass a viewer the address of a pyarrow.Buffer, such as a validity buffer or the offsets of a string array, and they return copies, never the viewer’s array itself. arrays_viewers compiles a viewer the first time its dtype is requested and keeps it for the rest of the process.

A viewer’s array does not own its memory, does not keep that memory alive, and is not read-only. The array is valid only while that memory stays allocated, and a write through it changes the memory. arrow_array_adapter() returns read-only arrays that stay valid while you hold them: a view that keeps its Arrow buffer alive, or a copy that owns its memory. Use the adapter unless your code manages the memory itself.

Compiled functions, called viewers, that return a numpy array over the memory at a raw address without a copy.

A viewer takes an address, such as pyarrow.Buffer.address, and a number of elements, and returns a one-dimensional numpy array of one dtype over the memory there. numpy_array_from_ptr_factory() compiles the viewer for a dtype, and arrays_viewers keeps one viewer per key, such as np.uint8, compiled the first time the key is requested. The array that a viewer returns does not keep the memory alive, and it is writable. The adapters in numbarrow.utils.arrow_array_utils and numbarrow.core.adapters therefore use viewers only to read validity bitmaps, packed booleans and string offsets, and they return copies, never the views themselves.

numbarrow.utils.utils.numpy_array_from_ptr_factory(dtype_)[source]

Compile and return the viewer for dtype_: a function that views the memory at an address as a numpy array.

The viewer takes (ptr_as_int, sz), typed intp and int64, and returns a one-dimensional C-contiguous array of sz elements of dtype_ that starts at the address ptr_as_int. dtype_ is anything that numpy.dtype accepts and numba supports, a structured dtype included; the object dtype fails to compile. The factory compiles the viewer under numbarrow’s jit options, as jit_with_options() describes, and each call builds a new viewer; arrays_viewers builds one per key and keeps it.

The viewer copies nothing. Its array views the memory at the address without keeping that memory alive, and the array is writable. Reading it after the memory is freed is undefined behavior, and a write through it changes the memory. arrow_array_adapter() is the supported way to view an Arrow array, because it returns read-only arrays that keep their Arrow buffers alive.

numbarrow.utils.arrow_array_utils

Overview

This module holds the conversions that arrow_array_adapter() calls for numeric, string, struct and list arrays. uniform_arrow_array_adapter() views an array of fixed-width values, and create_str_array() copies a string array into fixed-width Unicode. structured_array_adapter() converts a struct array field by field, and structured_list_array_adapter() converts a list of structs. Each of them copies the validity bitmap with create_bitmap(), which takes an Arrow buffer, an offset and a length rather than an array.

Each of the four conversions takes the pyarrow array directly, but arrow_array_adapter is the function to call: it chooses the conversion by the class of the array and accepts every supported type. The reference below documents what each function returns and what it raises.

Functions that adapt pyarrow arrays of several layouts to numpy arrays, and helpers for readable error messages.

arrow_array_adapter() picks one of these adapters by the type of the array it is given. Each adapter returns the array’s data and its validity bitmap: a uint8 array of one bit per element, which is_null() reads, or None for an array without one. uniform_arrow_array_adapter() views fixed-width data without a copy, and create_str_array() copies strings into a fixed-width Unicode array. structured_array_adapter() and structured_list_array_adapter() adapt a struct array and a list of structs field by field. create_bitmap() copies a validity bitmap. type_repr(), renamed() and MissingKeyError keep the error messages of numbarrow short and readable.

exception numbarrow.utils.arrow_array_utils.MissingKeyError[source]

Bases: KeyError

A KeyError whose message prints as written, without the quotes that a plain KeyError adds.

A plain KeyError prints the repr of its one argument, so a sentence raised through it prints inside a second pair of quotes, and a sentence that holds quotes of its own can print with backslashes before them. except KeyError still catches a MissingKeyError; only the printed message differs. With no argument or with several, it prints as a plain KeyError does.

numbarrow.utils.arrow_array_utils.create_bitmap(bitmap_buf: Buffer | None, offset: int = 0, length: int = 0)[source]

Copy the validity bits of length elements, from element offset on, into a new uint8 array.

bitmap_buf is an Arrow validity buffer, such as array.buffers()[0], and offset and length are usually the array’s own. A bitmap_buf of None means that the array carries no validity buffer, and the result is then None. Otherwise the result holds one bit per element, from the least significant bit of its first byte on: bit i is 1 if element offset + i is valid, that is, not null, and 0 if it is null. This is the layout that is_null() reads. The result has (length + 7) // 8 bytes, none for a length of 0, and the bits after the last element have no defined value. The result owns its memory, so it stays correct after the Arrow array is freed. It is writable, and a write to it leaves the Arrow array unchanged.

numbarrow.utils.arrow_array_utils.create_str_array(pa_str_array: StringArray | LargeStringArray) → tuple[ndarray | None, ndarray][source]

Copy a string array into a read-only numpy array of fixed-width Unicode strings; return (bitmap, data).

bitmap is the array’s validity bitmap from create_bitmap(), or None if the array carries no validity buffer. data holds one string per element, and an empty string for a null element. Its width is the length, in characters, of the longest valid value, and at least one. Every element takes four bytes per character of that width, so one long value makes the whole array large. The bytes under a null element are never decoded and do not count toward the width.

ValueError is raised if a valid value is not UTF-8, if a valid value ends in a NUL character, and if a non-empty array lacks its offsets or data buffer. numpy pads a shorter value with NUL characters, so a value’s trailing NUL would be lost; a NUL at the start or in the middle of a value is kept.

numbarrow.utils.arrow_array_utils.renamed(exc: Exception, prefix: str) → Exception[source]

Return a new exception whose message is prefix, a colon and the message of exc.

A KeyError that is not a pyarrow error comes back as a MissingKeyError, because a KeyError prints the repr of its argument, and one rebuilt from that text would quote the message twice. Otherwise the result keeps the class of exc if exc is a pyarrow error, or if its class is exactly TypeError, ValueError, NotImplementedError or OverflowError; each of these can be built from one string. Any other exception, a subclass of those four included, comes back as a ValueError. A class such as UnicodeDecodeError, whose constructor takes five arguments, would raise a second error while the result is built, and the prefix would be lost. Raise the result from exc to keep the original traceback.

numbarrow.utils.arrow_array_utils.structured_array_adapter(struct_array: StructArray) → tuple[ndarray | None, dict[str, ndarray | None], dict[str, ndarray]][source]

Adapt a struct array field by field; return (struct_bitmap, bitmaps, datas).

struct_bitmap is the validity bitmap of the struct’s rows, or None if the struct carries no validity buffer. bitmaps and datas map each field name, in field order, to the field’s validity bitmap and its data, adapted by arrow_array_adapter() as an array of the field’s type. A field’s bitmap marks only the field’s own nulls, and it is None if the field carries no validity buffer. A row that is null as a whole need not be marked in a field’s bitmap, so pass both bitmaps to is_null_struct(). Under such a row, a string field holds an empty string, and any other field holds whatever its buffer holds there.

A field’s data is a read-only view of the field’s buffer if the field holds int32, int64, float64, uint8, date64 or timestamp values; the int64 values of a date64 or timestamp field need no conversion to datetime64. The data is a read-only copy for three kinds of field: numbarrow unpacks the bits of a boolean field, turns the int32 days of a date32 field into datetime64[D], and copies a string field into fixed-width Unicode.

TypeError is raised if struct_array is not a pyarrow.StructArray. NotImplementedError is raised for repeated field names and for a field of a union type. A NotImplementedError, ValueError, TypeError or pyarrow error from the adapter of a field, such as the error for an unsupported type, is raised again through renamed(), with struct field '<name>' and a colon in front of its message. A field that adapts but is itself a struct, a list of structs or a map raises NotImplementedError.

numbarrow.utils.arrow_array_utils.structured_list_array_adapter(list_array: ListArray) → tuple[ndarray | None, dict[str, ndarray | None], dict[str, ndarray]][source]

Adapt a list array of structs whose rows all have one length; return (struct_bitmap, bitmaps, datas).

The result is what structured_array_adapter() returns for the elements of all the array’s rows, in row order, so a field’s data is a view or a copy as that function describes. The result carries no offsets: element k of row r is at index r * width + k, where width is the common row length. struct_bitmap therefore marks null elements, not null rows. A pyarrow.MapArray is a list array whose elements are key and value structs, so it adapts to the two fields key and value.

TypeError is raised if list_array is not a pyarrow.ListArray. NotImplementedError is raised if its elements are not structs, if a row is null, and if the rows differ in length, an empty row among longer ones included. Without offsets, the order of the elements alone cannot say which row an element belongs to.

numbarrow.utils.arrow_array_utils.type_repr(arrow_type) → str[source]

Return str(arrow_type); if it is longer than TYPE_REPR_WIDTH characters, cut it there and add a note.

The note counts the characters cut and, for a struct type, the struct’s fields. A message that quotes a pyarrow type grows with the schema: the text of a struct of a thousand fields with short names runs to about 13,000 characters, and a message that long fills every log that records the traceback. A type whose text fits within the width, such as a struct of a few fields, comes back unchanged.

numbarrow.utils.arrow_array_utils.uniform_arrow_array_adapter(pa_array: Array) → tuple[ndarray | None, ndarray][source]

View the data of a fixed-width array as a read-only numpy array, without a copy; return (bitmap, data).

The array’s type must be one that arrow_to_numpy_dtypes maps to a numpy dtype: float64, int32, int64 or uint8. Any other type raises ValueError, a boolean one included, because Arrow stores one bit per boolean value. A non-empty array without a data buffer raises ValueError as well. bitmap is the array’s validity bitmap from create_bitmap(), or None if the array carries no validity buffer. data views the array’s data buffer from the array’s offset on, and it keeps that buffer alive.

data is read-only, because Arrow arrays are immutable, and its WRITEABLE flag cannot be set. pyarrow’s own Array.to_numpy(zero_copy_only=True) returns the same kind of view. A slice or reshape of data that an @njit function returns is a new array whose flag can be set, and a store through it then changes the Arrow array. Declare a numba signature that receives data with readonly=True; such a signature accepts writable arrays as well.