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), typedintpandint64, and returns a one-dimensional C-contiguous array ofszelements ofdtype_that starts at the addressptr_as_int.dtype_is anything thatnumpy.dtypeaccepts and numba supports, a structured dtype included; the object dtype fails to compile. The factory compiles the viewer under numbarrow’s jit options, asjit_with_options()describes, and each call builds a new viewer;arrays_viewersbuilds 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:
KeyErrorA
KeyErrorwhose message prints as written, without the quotes that a plainKeyErroradds.A plain
KeyErrorprints 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 KeyErrorstill catches aMissingKeyError; only the printed message differs. With no argument or with several, it prints as a plainKeyErrordoes.
- numbarrow.utils.arrow_array_utils.create_bitmap(bitmap_buf: Buffer | None, offset: int = 0, length: int = 0)[source]
Copy the validity bits of
lengthelements, from elementoffseton, into a new uint8 array.bitmap_bufis an Arrow validity buffer, such asarray.buffers()[0], andoffsetandlengthare usually the array’s own. Abitmap_bufofNonemeans that the array carries no validity buffer, and the result is thenNone. Otherwise the result holds one bit per element, from the least significant bit of its first byte on: bitiis 1 if elementoffset + iis valid, that is, not null, and 0 if it is null. This is the layout thatis_null()reads. The result has(length + 7) // 8bytes, none for alengthof 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).bitmapis the array’s validity bitmap fromcreate_bitmap(), orNoneif the array carries no validity buffer.dataholds 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.ValueErroris 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 ofexc.A
KeyErrorthat is not a pyarrow error comes back as aMissingKeyError, because aKeyErrorprints the repr of its argument, and one rebuilt from that text would quote the message twice. Otherwise the result keeps the class ofexcifexcis a pyarrow error, or if its class is exactlyTypeError,ValueError,NotImplementedErrororOverflowError; each of these can be built from one string. Any other exception, a subclass of those four included, comes back as aValueError. A class such asUnicodeDecodeError, whose constructor takes five arguments, would raise a second error while the result is built, and the prefix would be lost. Raise the resultfrom excto 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_bitmapis the validity bitmap of the struct’s rows, orNoneif the struct carries no validity buffer.bitmapsanddatasmap each field name, in field order, to the field’s validity bitmap and its data, adapted byarrow_array_adapter()as an array of the field’s type. A field’s bitmap marks only the field’s own nulls, and it isNoneif 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 tois_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 intodatetime64[D], and copies a string field into fixed-width Unicode.TypeErroris raised ifstruct_arrayis not apyarrow.StructArray.NotImplementedErroris raised for repeated field names and for a field of a union type. ANotImplementedError,ValueError,TypeErroror pyarrow error from the adapter of a field, such as the error for an unsupported type, is raised again throughrenamed(), withstruct 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 raisesNotImplementedError.
- 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: elementkof rowris at indexr * width + k, wherewidthis the common row length.struct_bitmaptherefore marks null elements, not null rows. Apyarrow.MapArrayis a list array whose elements are key and value structs, so it adapts to the two fieldskeyandvalue.TypeErroris raised iflist_arrayis not apyarrow.ListArray.NotImplementedErroris 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 thanTYPE_REPR_WIDTHcharacters, 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_dtypesmaps to a numpy dtype: float64, int32, int64 or uint8. Any other type raisesValueError, a boolean one included, because Arrow stores one bit per boolean value. A non-empty array without a data buffer raisesValueErroras well.bitmapis the array’s validity bitmap fromcreate_bitmap(), orNoneif the array carries no validity buffer.dataviews the array’s data buffer from the array’s offset on, and it keeps that buffer alive.datais read-only, because Arrow arrays are immutable, and itsWRITEABLEflag cannot be set. pyarrow’s ownArray.to_numpy(zero_copy_only=True)returns the same kind of view. A slice or reshape ofdatathat an@njitfunction 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 receivesdatawithreadonly=True; such a signature accepts writable arrays as well.