|
| 1 | +from typing import ( |
| 2 | + Optional, |
| 3 | + Tuple, |
| 4 | +) |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +from packaging import version |
| 8 | + |
| 9 | +from pandas.core.exchange.dataframe_protocol import ( |
| 10 | + Buffer, |
| 11 | + DlpackDeviceType, |
| 12 | +) |
| 13 | + |
| 14 | +_NUMPY_HAS_DLPACK = version.parse(np.__version__) >= version.parse("1.22.0") |
| 15 | + |
| 16 | + |
| 17 | +class PandasBuffer(Buffer): |
| 18 | + """ |
| 19 | + Data in the buffer is guaranteed to be contiguous in memory. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self, x: np.ndarray, allow_copy: bool = True) -> None: |
| 23 | + """ |
| 24 | + Handle only regular columns (= numpy arrays) for now. |
| 25 | + """ |
| 26 | + if not x.strides == (x.dtype.itemsize,): |
| 27 | + # The protocol does not support strided buffers, so a copy is |
| 28 | + # necessary. If that's not allowed, we need to raise an exception. |
| 29 | + if allow_copy: |
| 30 | + x = x.copy() |
| 31 | + else: |
| 32 | + raise RuntimeError( |
| 33 | + "Exports cannot be zero-copy in the case " |
| 34 | + "of a non-contiguous buffer" |
| 35 | + ) |
| 36 | + |
| 37 | + # Store the numpy array in which the data resides as a private |
| 38 | + # attribute, so we can use it to retrieve the public attributes |
| 39 | + self._x = x |
| 40 | + |
| 41 | + @property |
| 42 | + def bufsize(self) -> int: |
| 43 | + """ |
| 44 | + Buffer size in bytes. |
| 45 | + """ |
| 46 | + return self._x.size * self._x.dtype.itemsize |
| 47 | + |
| 48 | + @property |
| 49 | + def ptr(self) -> int: |
| 50 | + """ |
| 51 | + Pointer to start of the buffer as an integer. |
| 52 | + """ |
| 53 | + return self._x.__array_interface__["data"][0] |
| 54 | + |
| 55 | + def __dlpack__(self): |
| 56 | + """ |
| 57 | + Represent this structure as DLPack interface. |
| 58 | + """ |
| 59 | + if _NUMPY_HAS_DLPACK: |
| 60 | + return self._x.__dlpack__() |
| 61 | + raise NotImplementedError("__dlpack__") |
| 62 | + |
| 63 | + def __dlpack_device__(self) -> Tuple[DlpackDeviceType, Optional[int]]: |
| 64 | + """ |
| 65 | + Device type and device ID for where the data in the buffer resides. |
| 66 | + """ |
| 67 | + return (DlpackDeviceType.CPU, None) |
| 68 | + |
| 69 | + def __repr__(self) -> str: |
| 70 | + return ( |
| 71 | + "PandasBuffer(" |
| 72 | + + str( |
| 73 | + { |
| 74 | + "bufsize": self.bufsize, |
| 75 | + "ptr": self.ptr, |
| 76 | + "device": self.__dlpack_device__()[0].name, |
| 77 | + } |
| 78 | + ) |
| 79 | + + ")" |
| 80 | + ) |
0 commit comments