Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +9 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_cpu_dispatcher.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_deprecations.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_hashtable.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_scalarinherit.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_scalarprint.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/_natype.py +198 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/examples/cython/checks.pyx +268 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/examples/limited_api/limited_api1.c +17 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/examples/limited_api/setup.py +22 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/test_abc.py +54 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/test_arraymethod.py +87 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/test_cpu_dispatcher.py +45 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/test_mem_overlap.py +933 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/test_mem_policy.py +450 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/test_overrides.py +739 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/test_stringdtype.py +1694 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/test_strings.py +1205 -0
- parrot/lib/python3.10/site-packages/numpy/_core/tests/test_umath_accuracy.py +119 -0
- videollama2/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/__init__.py +9 -0
- videollama2/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/__pycache__/rnn.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/activation.py +465 -0
- videollama2/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/rnn.py +406 -0
- videollama2/lib/python3.10/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/rnn.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/outlines_core/fsm/outlines_core_rs.cpython-310-x86_64-linux-gnu.so +3 -0
- vllm/lib/python3.10/site-packages/pyarrow/__init__.pxd +42 -0
- vllm/lib/python3.10/site-packages/pyarrow/_acero.pxd +44 -0
- vllm/lib/python3.10/site-packages/pyarrow/_cuda.pxd +67 -0
- vllm/lib/python3.10/site-packages/pyarrow/_cuda.pyx +1080 -0
- vllm/lib/python3.10/site-packages/pyarrow/_dataset.cpython-310-x86_64-linux-gnu.so +3 -0
- vllm/lib/python3.10/site-packages/pyarrow/_dataset.pxd +183 -0
- vllm/lib/python3.10/site-packages/pyarrow/_dataset.pyx +0 -0
- vllm/lib/python3.10/site-packages/pyarrow/_orc.cpython-310-x86_64-linux-gnu.so +3 -0
- vllm/lib/python3.10/site-packages/pyarrow/_parquet_encryption.pxd +56 -0
- vllm/lib/python3.10/site-packages/pyarrow/_s3fs.cpython-310-x86_64-linux-gnu.so +3 -0
- vllm/lib/python3.10/site-packages/pyarrow/benchmark.py +21 -0
- vllm/lib/python3.10/site-packages/pyarrow/builder.pxi +150 -0
- vllm/lib/python3.10/site-packages/pyarrow/csv.py +22 -0
- vllm/lib/python3.10/site-packages/pyarrow/gandiva.pyx +760 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/__init__.pxd +0 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/common.pxd +175 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow.pxd +0 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_cuda.pxd +109 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_dataset.pxd +418 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_dataset_parquet.pxd +105 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_feather.pxd +50 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_flight.pxd +622 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_fs.pxd +357 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_substrait.pxd +77 -0
- vllm/lib/python3.10/site-packages/pyarrow/includes/libgandiva.pxd +298 -0
.gitattributes
CHANGED
|
@@ -1399,3 +1399,12 @@ vllm/lib/python3.10/site-packages/pyarrow/_dataset_parquet.cpython-310-x86_64-li
|
|
| 1399 |
vllm/lib/python3.10/site-packages/pyarrow/_csv.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1400 |
vllm/lib/python3.10/site-packages/pyarrow/_gcsfs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1401 |
vllm/lib/python3.10/site-packages/textual/__pycache__/app.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1399 |
vllm/lib/python3.10/site-packages/pyarrow/_csv.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1400 |
vllm/lib/python3.10/site-packages/pyarrow/_gcsfs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1401 |
vllm/lib/python3.10/site-packages/textual/__pycache__/app.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1402 |
+
vllm/lib/python3.10/site-packages/pyarrow/libarrow_python_flight.so filter=lfs diff=lfs merge=lfs -text
|
| 1403 |
+
vllm/lib/python3.10/site-packages/pyarrow/lib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1404 |
+
vllm/lib/python3.10/site-packages/textual/__pycache__/widget.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1405 |
+
vllm/lib/python3.10/site-packages/pyarrow/_dataset.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1406 |
+
vllm/lib/python3.10/site-packages/pyarrow/_orc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1407 |
+
vllm/lib/python3.10/site-packages/outlines_core/fsm/outlines_core_rs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1408 |
+
vllm/lib/python3.10/site-packages/pyarrow/_s3fs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1409 |
+
vllm/lib/python3.10/site-packages/pyarrow/libarrow_python.so filter=lfs diff=lfs merge=lfs -text
|
| 1410 |
+
vllm/lib/python3.10/site-packages/pyarrow/libarrow_flight.so.1801 filter=lfs diff=lfs merge=lfs -text
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_cpu_dispatcher.cpython-310.pyc
ADDED
|
Binary file (1.05 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_deprecations.cpython-310.pyc
ADDED
|
Binary file (35.7 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_hashtable.cpython-310.pyc
ADDED
|
Binary file (1.13 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_scalarinherit.cpython-310.pyc
ADDED
|
Binary file (4.04 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_scalarprint.cpython-310.pyc
ADDED
|
Binary file (11.6 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/_natype.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vendored implementation of pandas.NA, adapted from pandas/_libs/missing.pyx
|
| 2 |
+
#
|
| 3 |
+
# This is vendored to avoid adding pandas as a test dependency.
|
| 4 |
+
|
| 5 |
+
__all__ = ["pd_NA"]
|
| 6 |
+
|
| 7 |
+
import numbers
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
def _create_binary_propagating_op(name, is_divmod=False):
|
| 12 |
+
is_cmp = name.strip("_") in ["eq", "ne", "le", "lt", "ge", "gt"]
|
| 13 |
+
|
| 14 |
+
def method(self, other):
|
| 15 |
+
if (
|
| 16 |
+
other is pd_NA
|
| 17 |
+
or isinstance(other, (str, bytes))
|
| 18 |
+
or isinstance(other, (numbers.Number, np.bool))
|
| 19 |
+
or isinstance(other, np.ndarray)
|
| 20 |
+
and not other.shape
|
| 21 |
+
):
|
| 22 |
+
# Need the other.shape clause to handle NumPy scalars,
|
| 23 |
+
# since we do a setitem on `out` below, which
|
| 24 |
+
# won't work for NumPy scalars.
|
| 25 |
+
if is_divmod:
|
| 26 |
+
return pd_NA, pd_NA
|
| 27 |
+
else:
|
| 28 |
+
return pd_NA
|
| 29 |
+
|
| 30 |
+
elif isinstance(other, np.ndarray):
|
| 31 |
+
out = np.empty(other.shape, dtype=object)
|
| 32 |
+
out[:] = pd_NA
|
| 33 |
+
|
| 34 |
+
if is_divmod:
|
| 35 |
+
return out, out.copy()
|
| 36 |
+
else:
|
| 37 |
+
return out
|
| 38 |
+
|
| 39 |
+
elif is_cmp and isinstance(other, (np.datetime64, np.timedelta64)):
|
| 40 |
+
return pd_NA
|
| 41 |
+
|
| 42 |
+
elif isinstance(other, np.datetime64):
|
| 43 |
+
if name in ["__sub__", "__rsub__"]:
|
| 44 |
+
return pd_NA
|
| 45 |
+
|
| 46 |
+
elif isinstance(other, np.timedelta64):
|
| 47 |
+
if name in ["__sub__", "__rsub__", "__add__", "__radd__"]:
|
| 48 |
+
return pd_NA
|
| 49 |
+
|
| 50 |
+
return NotImplemented
|
| 51 |
+
|
| 52 |
+
method.__name__ = name
|
| 53 |
+
return method
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _create_unary_propagating_op(name: str):
|
| 57 |
+
def method(self):
|
| 58 |
+
return pd_NA
|
| 59 |
+
|
| 60 |
+
method.__name__ = name
|
| 61 |
+
return method
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class NAType:
|
| 65 |
+
def __repr__(self) -> str:
|
| 66 |
+
return "<NA>"
|
| 67 |
+
|
| 68 |
+
def __format__(self, format_spec) -> str:
|
| 69 |
+
try:
|
| 70 |
+
return self.__repr__().__format__(format_spec)
|
| 71 |
+
except ValueError:
|
| 72 |
+
return self.__repr__()
|
| 73 |
+
|
| 74 |
+
def __bool__(self):
|
| 75 |
+
raise TypeError("boolean value of NA is ambiguous")
|
| 76 |
+
|
| 77 |
+
def __hash__(self):
|
| 78 |
+
exponent = 31 if is_32bit else 61
|
| 79 |
+
return 2**exponent - 1
|
| 80 |
+
|
| 81 |
+
def __reduce__(self):
|
| 82 |
+
return "pd_NA"
|
| 83 |
+
|
| 84 |
+
# Binary arithmetic and comparison ops -> propagate
|
| 85 |
+
|
| 86 |
+
__add__ = _create_binary_propagating_op("__add__")
|
| 87 |
+
__radd__ = _create_binary_propagating_op("__radd__")
|
| 88 |
+
__sub__ = _create_binary_propagating_op("__sub__")
|
| 89 |
+
__rsub__ = _create_binary_propagating_op("__rsub__")
|
| 90 |
+
__mul__ = _create_binary_propagating_op("__mul__")
|
| 91 |
+
__rmul__ = _create_binary_propagating_op("__rmul__")
|
| 92 |
+
__matmul__ = _create_binary_propagating_op("__matmul__")
|
| 93 |
+
__rmatmul__ = _create_binary_propagating_op("__rmatmul__")
|
| 94 |
+
__truediv__ = _create_binary_propagating_op("__truediv__")
|
| 95 |
+
__rtruediv__ = _create_binary_propagating_op("__rtruediv__")
|
| 96 |
+
__floordiv__ = _create_binary_propagating_op("__floordiv__")
|
| 97 |
+
__rfloordiv__ = _create_binary_propagating_op("__rfloordiv__")
|
| 98 |
+
__mod__ = _create_binary_propagating_op("__mod__")
|
| 99 |
+
__rmod__ = _create_binary_propagating_op("__rmod__")
|
| 100 |
+
__divmod__ = _create_binary_propagating_op("__divmod__", is_divmod=True)
|
| 101 |
+
__rdivmod__ = _create_binary_propagating_op("__rdivmod__", is_divmod=True)
|
| 102 |
+
# __lshift__ and __rshift__ are not implemented
|
| 103 |
+
|
| 104 |
+
__eq__ = _create_binary_propagating_op("__eq__")
|
| 105 |
+
__ne__ = _create_binary_propagating_op("__ne__")
|
| 106 |
+
__le__ = _create_binary_propagating_op("__le__")
|
| 107 |
+
__lt__ = _create_binary_propagating_op("__lt__")
|
| 108 |
+
__gt__ = _create_binary_propagating_op("__gt__")
|
| 109 |
+
__ge__ = _create_binary_propagating_op("__ge__")
|
| 110 |
+
|
| 111 |
+
# Unary ops
|
| 112 |
+
|
| 113 |
+
__neg__ = _create_unary_propagating_op("__neg__")
|
| 114 |
+
__pos__ = _create_unary_propagating_op("__pos__")
|
| 115 |
+
__abs__ = _create_unary_propagating_op("__abs__")
|
| 116 |
+
__invert__ = _create_unary_propagating_op("__invert__")
|
| 117 |
+
|
| 118 |
+
# pow has special
|
| 119 |
+
def __pow__(self, other):
|
| 120 |
+
if other is pd_NA:
|
| 121 |
+
return pd_NA
|
| 122 |
+
elif isinstance(other, (numbers.Number, np.bool)):
|
| 123 |
+
if other == 0:
|
| 124 |
+
# returning positive is correct for +/- 0.
|
| 125 |
+
return type(other)(1)
|
| 126 |
+
else:
|
| 127 |
+
return pd_NA
|
| 128 |
+
elif util.is_array(other):
|
| 129 |
+
return np.where(other == 0, other.dtype.type(1), pd_NA)
|
| 130 |
+
|
| 131 |
+
return NotImplemented
|
| 132 |
+
|
| 133 |
+
def __rpow__(self, other):
|
| 134 |
+
if other is pd_NA:
|
| 135 |
+
return pd_NA
|
| 136 |
+
elif isinstance(other, (numbers.Number, np.bool)):
|
| 137 |
+
if other == 1:
|
| 138 |
+
return other
|
| 139 |
+
else:
|
| 140 |
+
return pd_NA
|
| 141 |
+
elif util.is_array(other):
|
| 142 |
+
return np.where(other == 1, other, pd_NA)
|
| 143 |
+
return NotImplemented
|
| 144 |
+
|
| 145 |
+
# Logical ops using Kleene logic
|
| 146 |
+
|
| 147 |
+
def __and__(self, other):
|
| 148 |
+
if other is False:
|
| 149 |
+
return False
|
| 150 |
+
elif other is True or other is pd_NA:
|
| 151 |
+
return pd_NA
|
| 152 |
+
return NotImplemented
|
| 153 |
+
|
| 154 |
+
__rand__ = __and__
|
| 155 |
+
|
| 156 |
+
def __or__(self, other):
|
| 157 |
+
if other is True:
|
| 158 |
+
return True
|
| 159 |
+
elif other is False or other is pd_NA:
|
| 160 |
+
return pd_NA
|
| 161 |
+
return NotImplemented
|
| 162 |
+
|
| 163 |
+
__ror__ = __or__
|
| 164 |
+
|
| 165 |
+
def __xor__(self, other):
|
| 166 |
+
if other is False or other is True or other is pd_NA:
|
| 167 |
+
return pd_NA
|
| 168 |
+
return NotImplemented
|
| 169 |
+
|
| 170 |
+
__rxor__ = __xor__
|
| 171 |
+
|
| 172 |
+
__array_priority__ = 1000
|
| 173 |
+
_HANDLED_TYPES = (np.ndarray, numbers.Number, str, np.bool)
|
| 174 |
+
|
| 175 |
+
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
|
| 176 |
+
types = self._HANDLED_TYPES + (NAType,)
|
| 177 |
+
for x in inputs:
|
| 178 |
+
if not isinstance(x, types):
|
| 179 |
+
return NotImplemented
|
| 180 |
+
|
| 181 |
+
if method != "__call__":
|
| 182 |
+
raise ValueError(f"ufunc method '{method}' not supported for NA")
|
| 183 |
+
result = maybe_dispatch_ufunc_to_dunder_op(
|
| 184 |
+
self, ufunc, method, *inputs, **kwargs
|
| 185 |
+
)
|
| 186 |
+
if result is NotImplemented:
|
| 187 |
+
# For a NumPy ufunc that's not a binop, like np.logaddexp
|
| 188 |
+
index = [i for i, x in enumerate(inputs) if x is pd_NA][0]
|
| 189 |
+
result = np.broadcast_arrays(*inputs)[index]
|
| 190 |
+
if result.ndim == 0:
|
| 191 |
+
result = result.item()
|
| 192 |
+
if ufunc.nout > 1:
|
| 193 |
+
result = (pd_NA,) * ufunc.nout
|
| 194 |
+
|
| 195 |
+
return result
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
pd_NA = NAType()
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/examples/cython/checks.pyx
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#cython: language_level=3
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Functions in this module give python-space wrappers for cython functions
|
| 5 |
+
exposed in numpy/__init__.pxd, so they can be tested in test_cython.py
|
| 6 |
+
"""
|
| 7 |
+
cimport numpy as cnp
|
| 8 |
+
cnp.import_array()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def is_td64(obj):
|
| 12 |
+
return cnp.is_timedelta64_object(obj)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def is_dt64(obj):
|
| 16 |
+
return cnp.is_datetime64_object(obj)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_dt64_value(obj):
|
| 20 |
+
return cnp.get_datetime64_value(obj)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_td64_value(obj):
|
| 24 |
+
return cnp.get_timedelta64_value(obj)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_dt64_unit(obj):
|
| 28 |
+
return cnp.get_datetime64_unit(obj)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def is_integer(obj):
|
| 32 |
+
return isinstance(obj, (cnp.integer, int))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_datetime_iso_8601_strlen():
|
| 36 |
+
return cnp.get_datetime_iso_8601_strlen(0, cnp.NPY_FR_ns)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def convert_datetime64_to_datetimestruct():
|
| 40 |
+
cdef:
|
| 41 |
+
cnp.npy_datetimestruct dts
|
| 42 |
+
cnp.PyArray_DatetimeMetaData meta
|
| 43 |
+
cnp.int64_t value = 1647374515260292
|
| 44 |
+
# i.e. (time.time() * 10**6) at 2022-03-15 20:01:55.260292 UTC
|
| 45 |
+
|
| 46 |
+
meta.base = cnp.NPY_FR_us
|
| 47 |
+
meta.num = 1
|
| 48 |
+
cnp.convert_datetime64_to_datetimestruct(&meta, value, &dts)
|
| 49 |
+
return dts
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def make_iso_8601_datetime(dt: "datetime"):
|
| 53 |
+
cdef:
|
| 54 |
+
cnp.npy_datetimestruct dts
|
| 55 |
+
char result[36] # 36 corresponds to NPY_FR_s passed below
|
| 56 |
+
int local = 0
|
| 57 |
+
int utc = 0
|
| 58 |
+
int tzoffset = 0
|
| 59 |
+
|
| 60 |
+
dts.year = dt.year
|
| 61 |
+
dts.month = dt.month
|
| 62 |
+
dts.day = dt.day
|
| 63 |
+
dts.hour = dt.hour
|
| 64 |
+
dts.min = dt.minute
|
| 65 |
+
dts.sec = dt.second
|
| 66 |
+
dts.us = dt.microsecond
|
| 67 |
+
dts.ps = dts.as = 0
|
| 68 |
+
|
| 69 |
+
cnp.make_iso_8601_datetime(
|
| 70 |
+
&dts,
|
| 71 |
+
result,
|
| 72 |
+
sizeof(result),
|
| 73 |
+
local,
|
| 74 |
+
utc,
|
| 75 |
+
cnp.NPY_FR_s,
|
| 76 |
+
tzoffset,
|
| 77 |
+
cnp.NPY_NO_CASTING,
|
| 78 |
+
)
|
| 79 |
+
return result
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
cdef cnp.broadcast multiiter_from_broadcast_obj(object bcast):
|
| 83 |
+
cdef dict iter_map = {
|
| 84 |
+
1: cnp.PyArray_MultiIterNew1,
|
| 85 |
+
2: cnp.PyArray_MultiIterNew2,
|
| 86 |
+
3: cnp.PyArray_MultiIterNew3,
|
| 87 |
+
4: cnp.PyArray_MultiIterNew4,
|
| 88 |
+
5: cnp.PyArray_MultiIterNew5,
|
| 89 |
+
}
|
| 90 |
+
arrays = [x.base for x in bcast.iters]
|
| 91 |
+
cdef cnp.broadcast result = iter_map[len(arrays)](*arrays)
|
| 92 |
+
return result
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def get_multiiter_size(bcast: "broadcast"):
|
| 96 |
+
cdef cnp.broadcast multi = multiiter_from_broadcast_obj(bcast)
|
| 97 |
+
return multi.size
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def get_multiiter_number_of_dims(bcast: "broadcast"):
|
| 101 |
+
cdef cnp.broadcast multi = multiiter_from_broadcast_obj(bcast)
|
| 102 |
+
return multi.nd
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def get_multiiter_current_index(bcast: "broadcast"):
|
| 106 |
+
cdef cnp.broadcast multi = multiiter_from_broadcast_obj(bcast)
|
| 107 |
+
return multi.index
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_multiiter_num_of_iterators(bcast: "broadcast"):
|
| 111 |
+
cdef cnp.broadcast multi = multiiter_from_broadcast_obj(bcast)
|
| 112 |
+
return multi.numiter
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def get_multiiter_shape(bcast: "broadcast"):
|
| 116 |
+
cdef cnp.broadcast multi = multiiter_from_broadcast_obj(bcast)
|
| 117 |
+
return tuple([multi.dimensions[i] for i in range(bcast.nd)])
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def get_multiiter_iters(bcast: "broadcast"):
|
| 121 |
+
cdef cnp.broadcast multi = multiiter_from_broadcast_obj(bcast)
|
| 122 |
+
return tuple([<cnp.flatiter>multi.iters[i] for i in range(bcast.numiter)])
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_default_integer():
|
| 126 |
+
if cnp.NPY_DEFAULT_INT == cnp.NPY_LONG:
|
| 127 |
+
return cnp.dtype("long")
|
| 128 |
+
if cnp.NPY_DEFAULT_INT == cnp.NPY_INTP:
|
| 129 |
+
return cnp.dtype("intp")
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
def get_ravel_axis():
|
| 133 |
+
return cnp.NPY_RAVEL_AXIS
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def conv_intp(cnp.intp_t val):
|
| 137 |
+
return val
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_dtype_flags(cnp.dtype dtype):
|
| 141 |
+
return dtype.flags
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
cdef cnp.NpyIter* npyiter_from_nditer_obj(object it):
|
| 145 |
+
"""A function to create a NpyIter struct from a nditer object.
|
| 146 |
+
|
| 147 |
+
This function is only meant for testing purposes and only extracts the
|
| 148 |
+
necessary info from nditer to test the functionality of NpyIter methods
|
| 149 |
+
"""
|
| 150 |
+
cdef:
|
| 151 |
+
cnp.NpyIter* cit
|
| 152 |
+
cnp.PyArray_Descr* op_dtypes[3]
|
| 153 |
+
cnp.npy_uint32 op_flags[3]
|
| 154 |
+
cnp.PyArrayObject* ops[3]
|
| 155 |
+
cnp.npy_uint32 flags = 0
|
| 156 |
+
|
| 157 |
+
if it.has_index:
|
| 158 |
+
flags |= cnp.NPY_ITER_C_INDEX
|
| 159 |
+
if it.has_delayed_bufalloc:
|
| 160 |
+
flags |= cnp.NPY_ITER_BUFFERED | cnp.NPY_ITER_DELAY_BUFALLOC
|
| 161 |
+
if it.has_multi_index:
|
| 162 |
+
flags |= cnp.NPY_ITER_MULTI_INDEX
|
| 163 |
+
|
| 164 |
+
# one of READWRITE, READONLY and WRTIEONLY at the minimum must be specified for op_flags
|
| 165 |
+
for i in range(it.nop):
|
| 166 |
+
op_flags[i] = cnp.NPY_ITER_READONLY
|
| 167 |
+
|
| 168 |
+
for i in range(it.nop):
|
| 169 |
+
op_dtypes[i] = cnp.PyArray_DESCR(it.operands[i])
|
| 170 |
+
ops[i] = <cnp.PyArrayObject*>it.operands[i]
|
| 171 |
+
|
| 172 |
+
cit = cnp.NpyIter_MultiNew(it.nop, &ops[0], flags, cnp.NPY_KEEPORDER,
|
| 173 |
+
cnp.NPY_NO_CASTING, &op_flags[0],
|
| 174 |
+
<cnp.PyArray_Descr**>NULL)
|
| 175 |
+
return cit
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def get_npyiter_size(it: "nditer"):
|
| 179 |
+
cdef cnp.NpyIter* cit = npyiter_from_nditer_obj(it)
|
| 180 |
+
result = cnp.NpyIter_GetIterSize(cit)
|
| 181 |
+
cnp.NpyIter_Deallocate(cit)
|
| 182 |
+
return result
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def get_npyiter_ndim(it: "nditer"):
|
| 186 |
+
cdef cnp.NpyIter* cit = npyiter_from_nditer_obj(it)
|
| 187 |
+
result = cnp.NpyIter_GetNDim(cit)
|
| 188 |
+
cnp.NpyIter_Deallocate(cit)
|
| 189 |
+
return result
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def get_npyiter_nop(it: "nditer"):
|
| 193 |
+
cdef cnp.NpyIter* cit = npyiter_from_nditer_obj(it)
|
| 194 |
+
result = cnp.NpyIter_GetNOp(cit)
|
| 195 |
+
cnp.NpyIter_Deallocate(cit)
|
| 196 |
+
return result
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_npyiter_operands(it: "nditer"):
|
| 200 |
+
cdef cnp.NpyIter* cit = npyiter_from_nditer_obj(it)
|
| 201 |
+
try:
|
| 202 |
+
arr = cnp.NpyIter_GetOperandArray(cit)
|
| 203 |
+
return tuple([<cnp.ndarray>arr[i] for i in range(it.nop)])
|
| 204 |
+
finally:
|
| 205 |
+
cnp.NpyIter_Deallocate(cit)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def get_npyiter_itviews(it: "nditer"):
|
| 209 |
+
cdef cnp.NpyIter* cit = npyiter_from_nditer_obj(it)
|
| 210 |
+
result = tuple([cnp.NpyIter_GetIterView(cit, i) for i in range(it.nop)])
|
| 211 |
+
cnp.NpyIter_Deallocate(cit)
|
| 212 |
+
return result
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def get_npyiter_dtypes(it: "nditer"):
|
| 216 |
+
cdef cnp.NpyIter* cit = npyiter_from_nditer_obj(it)
|
| 217 |
+
try:
|
| 218 |
+
arr = cnp.NpyIter_GetDescrArray(cit)
|
| 219 |
+
return tuple([<cnp.dtype>arr[i] for i in range(it.nop)])
|
| 220 |
+
finally:
|
| 221 |
+
cnp.NpyIter_Deallocate(cit)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def npyiter_has_delayed_bufalloc(it: "nditer"):
|
| 225 |
+
cdef cnp.NpyIter* cit = npyiter_from_nditer_obj(it)
|
| 226 |
+
result = cnp.NpyIter_HasDelayedBufAlloc(cit)
|
| 227 |
+
cnp.NpyIter_Deallocate(cit)
|
| 228 |
+
return result
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def npyiter_has_index(it: "nditer"):
|
| 232 |
+
cdef cnp.NpyIter* cit = npyiter_from_nditer_obj(it)
|
| 233 |
+
result = cnp.NpyIter_HasIndex(cit)
|
| 234 |
+
cnp.NpyIter_Deallocate(cit)
|
| 235 |
+
return result
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def npyiter_has_multi_index(it: "nditer"):
|
| 239 |
+
cdef cnp.NpyIter* cit = npyiter_from_nditer_obj(it)
|
| 240 |
+
result = cnp.NpyIter_HasMultiIndex(cit)
|
| 241 |
+
cnp.NpyIter_Deallocate(cit)
|
| 242 |
+
return result
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def npyiter_has_finished(it: "nditer"):
|
| 246 |
+
cdef cnp.NpyIter* cit
|
| 247 |
+
try:
|
| 248 |
+
cit = npyiter_from_nditer_obj(it)
|
| 249 |
+
cnp.NpyIter_GotoIterIndex(cit, it.index)
|
| 250 |
+
return not (cnp.NpyIter_GetIterIndex(cit) < cnp.NpyIter_GetIterSize(cit))
|
| 251 |
+
finally:
|
| 252 |
+
cnp.NpyIter_Deallocate(cit)
|
| 253 |
+
|
| 254 |
+
def compile_fillwithbyte():
|
| 255 |
+
# Regression test for gh-25878, mostly checks it compiles.
|
| 256 |
+
cdef cnp.npy_intp dims[2]
|
| 257 |
+
dims = (1, 2)
|
| 258 |
+
pos = cnp.PyArray_ZEROS(2, dims, cnp.NPY_UINT8, 0)
|
| 259 |
+
cnp.PyArray_FILLWBYTE(pos, 1)
|
| 260 |
+
return pos
|
| 261 |
+
|
| 262 |
+
def inc2_cfloat_struct(cnp.ndarray[cnp.cfloat_t] arr):
|
| 263 |
+
# This works since we compile in C mode, it will fail in cpp mode
|
| 264 |
+
arr[1].real += 1
|
| 265 |
+
arr[1].imag += 1
|
| 266 |
+
# This works in both modes
|
| 267 |
+
arr[1].real = arr[1].real + 1
|
| 268 |
+
arr[1].imag = arr[1].imag + 1
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/examples/limited_api/limited_api1.c
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#define Py_LIMITED_API 0x03060000
|
| 2 |
+
|
| 3 |
+
#include <Python.h>
|
| 4 |
+
#include <numpy/arrayobject.h>
|
| 5 |
+
#include <numpy/ufuncobject.h>
|
| 6 |
+
|
| 7 |
+
static PyModuleDef moduledef = {
|
| 8 |
+
.m_base = PyModuleDef_HEAD_INIT,
|
| 9 |
+
.m_name = "limited_api1"
|
| 10 |
+
};
|
| 11 |
+
|
| 12 |
+
PyMODINIT_FUNC PyInit_limited_api1(void)
|
| 13 |
+
{
|
| 14 |
+
import_array();
|
| 15 |
+
import_umath();
|
| 16 |
+
return PyModule_Create(&moduledef);
|
| 17 |
+
}
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/examples/limited_api/setup.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Build an example package using the limited Python C API.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from setuptools import setup, Extension
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
macros = [("NPY_NO_DEPRECATED_API", 0), ("Py_LIMITED_API", "0x03060000")]
|
| 10 |
+
|
| 11 |
+
limited_api = Extension(
|
| 12 |
+
"limited_api",
|
| 13 |
+
sources=[os.path.join('.', "limited_api.c")],
|
| 14 |
+
include_dirs=[np.get_include()],
|
| 15 |
+
define_macros=macros,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
extensions = [limited_api]
|
| 19 |
+
|
| 20 |
+
setup(
|
| 21 |
+
ext_modules=extensions
|
| 22 |
+
)
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/test_abc.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy.testing import assert_
|
| 2 |
+
|
| 3 |
+
import numbers
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from numpy._core.numerictypes import sctypes
|
| 7 |
+
|
| 8 |
+
class TestABC:
|
| 9 |
+
def test_abstract(self):
|
| 10 |
+
assert_(issubclass(np.number, numbers.Number))
|
| 11 |
+
|
| 12 |
+
assert_(issubclass(np.inexact, numbers.Complex))
|
| 13 |
+
assert_(issubclass(np.complexfloating, numbers.Complex))
|
| 14 |
+
assert_(issubclass(np.floating, numbers.Real))
|
| 15 |
+
|
| 16 |
+
assert_(issubclass(np.integer, numbers.Integral))
|
| 17 |
+
assert_(issubclass(np.signedinteger, numbers.Integral))
|
| 18 |
+
assert_(issubclass(np.unsignedinteger, numbers.Integral))
|
| 19 |
+
|
| 20 |
+
def test_floats(self):
|
| 21 |
+
for t in sctypes['float']:
|
| 22 |
+
assert_(isinstance(t(), numbers.Real),
|
| 23 |
+
f"{t.__name__} is not instance of Real")
|
| 24 |
+
assert_(issubclass(t, numbers.Real),
|
| 25 |
+
f"{t.__name__} is not subclass of Real")
|
| 26 |
+
assert_(not isinstance(t(), numbers.Rational),
|
| 27 |
+
f"{t.__name__} is instance of Rational")
|
| 28 |
+
assert_(not issubclass(t, numbers.Rational),
|
| 29 |
+
f"{t.__name__} is subclass of Rational")
|
| 30 |
+
|
| 31 |
+
def test_complex(self):
|
| 32 |
+
for t in sctypes['complex']:
|
| 33 |
+
assert_(isinstance(t(), numbers.Complex),
|
| 34 |
+
f"{t.__name__} is not instance of Complex")
|
| 35 |
+
assert_(issubclass(t, numbers.Complex),
|
| 36 |
+
f"{t.__name__} is not subclass of Complex")
|
| 37 |
+
assert_(not isinstance(t(), numbers.Real),
|
| 38 |
+
f"{t.__name__} is instance of Real")
|
| 39 |
+
assert_(not issubclass(t, numbers.Real),
|
| 40 |
+
f"{t.__name__} is subclass of Real")
|
| 41 |
+
|
| 42 |
+
def test_int(self):
|
| 43 |
+
for t in sctypes['int']:
|
| 44 |
+
assert_(isinstance(t(), numbers.Integral),
|
| 45 |
+
f"{t.__name__} is not instance of Integral")
|
| 46 |
+
assert_(issubclass(t, numbers.Integral),
|
| 47 |
+
f"{t.__name__} is not subclass of Integral")
|
| 48 |
+
|
| 49 |
+
def test_uint(self):
|
| 50 |
+
for t in sctypes['uint']:
|
| 51 |
+
assert_(isinstance(t(), numbers.Integral),
|
| 52 |
+
f"{t.__name__} is not instance of Integral")
|
| 53 |
+
assert_(issubclass(t, numbers.Integral),
|
| 54 |
+
f"{t.__name__} is not subclass of Integral")
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/test_arraymethod.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This file tests the generic aspects of ArrayMethod. At the time of writing
|
| 3 |
+
this is private API, but when added, public API may be added here.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import sys
|
| 9 |
+
import types
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
from numpy._core._multiarray_umath import _get_castingimpl as get_castingimpl
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TestResolveDescriptors:
|
| 19 |
+
# Test mainly error paths of the resolve_descriptors function,
|
| 20 |
+
# note that the `casting_unittests` tests exercise this non-error paths.
|
| 21 |
+
|
| 22 |
+
# Casting implementations are the main/only current user:
|
| 23 |
+
method = get_castingimpl(type(np.dtype("d")), type(np.dtype("f")))
|
| 24 |
+
|
| 25 |
+
@pytest.mark.parametrize("args", [
|
| 26 |
+
(True,), # Not a tuple.
|
| 27 |
+
((None,)), # Too few elements
|
| 28 |
+
((None, None, None),), # Too many
|
| 29 |
+
((None, None),), # Input dtype is None, which is invalid.
|
| 30 |
+
((np.dtype("d"), True),), # Output dtype is not a dtype
|
| 31 |
+
((np.dtype("f"), None),), # Input dtype does not match method
|
| 32 |
+
])
|
| 33 |
+
def test_invalid_arguments(self, args):
|
| 34 |
+
with pytest.raises(TypeError):
|
| 35 |
+
self.method._resolve_descriptors(*args)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestSimpleStridedCall:
|
| 39 |
+
# Test mainly error paths of the resolve_descriptors function,
|
| 40 |
+
# note that the `casting_unittests` tests exercise this non-error paths.
|
| 41 |
+
|
| 42 |
+
# Casting implementations are the main/only current user:
|
| 43 |
+
method = get_castingimpl(type(np.dtype("d")), type(np.dtype("f")))
|
| 44 |
+
|
| 45 |
+
@pytest.mark.parametrize(["args", "error"], [
|
| 46 |
+
((True,), TypeError), # Not a tuple
|
| 47 |
+
(((None,),), TypeError), # Too few elements
|
| 48 |
+
((None, None), TypeError), # Inputs are not arrays.
|
| 49 |
+
(((None, None, None),), TypeError), # Too many
|
| 50 |
+
(((np.arange(3), np.arange(3)),), TypeError), # Incorrect dtypes
|
| 51 |
+
(((np.ones(3, dtype=">d"), np.ones(3, dtype="<f")),),
|
| 52 |
+
TypeError), # Does not support byte-swapping
|
| 53 |
+
(((np.ones((2, 2), dtype="d"), np.ones((2, 2), dtype="f")),),
|
| 54 |
+
ValueError), # not 1-D
|
| 55 |
+
(((np.ones(3, dtype="d"), np.ones(4, dtype="f")),),
|
| 56 |
+
ValueError), # different length
|
| 57 |
+
(((np.frombuffer(b"\0x00"*3*2, dtype="d"),
|
| 58 |
+
np.frombuffer(b"\0x00"*3, dtype="f")),),
|
| 59 |
+
ValueError), # output not writeable
|
| 60 |
+
])
|
| 61 |
+
def test_invalid_arguments(self, args, error):
|
| 62 |
+
# This is private API, which may be modified freely
|
| 63 |
+
with pytest.raises(error):
|
| 64 |
+
self.method._simple_strided_call(*args)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@pytest.mark.parametrize(
|
| 68 |
+
"cls", [
|
| 69 |
+
np.ndarray, np.recarray, np.char.chararray, np.matrix, np.memmap
|
| 70 |
+
]
|
| 71 |
+
)
|
| 72 |
+
class TestClassGetItem:
|
| 73 |
+
def test_class_getitem(self, cls: type[np.ndarray]) -> None:
|
| 74 |
+
"""Test `ndarray.__class_getitem__`."""
|
| 75 |
+
alias = cls[Any, Any]
|
| 76 |
+
assert isinstance(alias, types.GenericAlias)
|
| 77 |
+
assert alias.__origin__ is cls
|
| 78 |
+
|
| 79 |
+
@pytest.mark.parametrize("arg_len", range(4))
|
| 80 |
+
def test_subscript_tup(self, cls: type[np.ndarray], arg_len: int) -> None:
|
| 81 |
+
arg_tup = (Any,) * arg_len
|
| 82 |
+
if arg_len in (1, 2):
|
| 83 |
+
assert cls[arg_tup]
|
| 84 |
+
else:
|
| 85 |
+
match = f"Too {'few' if arg_len == 0 else 'many'} arguments"
|
| 86 |
+
with pytest.raises(TypeError, match=match):
|
| 87 |
+
cls[arg_tup]
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/test_cpu_dispatcher.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy._core._multiarray_umath import (
|
| 2 |
+
__cpu_features__, __cpu_baseline__, __cpu_dispatch__
|
| 3 |
+
)
|
| 4 |
+
from numpy._core import _umath_tests
|
| 5 |
+
from numpy.testing import assert_equal
|
| 6 |
+
|
| 7 |
+
def test_dispatcher():
|
| 8 |
+
"""
|
| 9 |
+
Testing the utilities of the CPU dispatcher
|
| 10 |
+
"""
|
| 11 |
+
targets = (
|
| 12 |
+
"SSE2", "SSE41", "AVX2",
|
| 13 |
+
"VSX", "VSX2", "VSX3",
|
| 14 |
+
"NEON", "ASIMD", "ASIMDHP",
|
| 15 |
+
"VX", "VXE"
|
| 16 |
+
)
|
| 17 |
+
highest_sfx = "" # no suffix for the baseline
|
| 18 |
+
all_sfx = []
|
| 19 |
+
for feature in reversed(targets):
|
| 20 |
+
# skip baseline features, by the default `CCompilerOpt` do not generate separated objects
|
| 21 |
+
# for the baseline, just one object combined all of them via 'baseline' option
|
| 22 |
+
# within the configuration statements.
|
| 23 |
+
if feature in __cpu_baseline__:
|
| 24 |
+
continue
|
| 25 |
+
# check compiler and running machine support
|
| 26 |
+
if feature not in __cpu_dispatch__ or not __cpu_features__[feature]:
|
| 27 |
+
continue
|
| 28 |
+
|
| 29 |
+
if not highest_sfx:
|
| 30 |
+
highest_sfx = "_" + feature
|
| 31 |
+
all_sfx.append("func" + "_" + feature)
|
| 32 |
+
|
| 33 |
+
test = _umath_tests.test_dispatch()
|
| 34 |
+
assert_equal(test["func"], "func" + highest_sfx)
|
| 35 |
+
assert_equal(test["var"], "var" + highest_sfx)
|
| 36 |
+
|
| 37 |
+
if highest_sfx:
|
| 38 |
+
assert_equal(test["func_xb"], "func" + highest_sfx)
|
| 39 |
+
assert_equal(test["var_xb"], "var" + highest_sfx)
|
| 40 |
+
else:
|
| 41 |
+
assert_equal(test["func_xb"], "nobase")
|
| 42 |
+
assert_equal(test["var_xb"], "nobase")
|
| 43 |
+
|
| 44 |
+
all_sfx.append("func") # add the baseline
|
| 45 |
+
assert_equal(test["all"], all_sfx)
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/test_mem_overlap.py
ADDED
|
@@ -0,0 +1,933 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numpy._core._multiarray_tests import solve_diophantine, internal_overlap
|
| 6 |
+
from numpy._core import _umath_tests
|
| 7 |
+
from numpy.lib.stride_tricks import as_strided
|
| 8 |
+
from numpy.testing import (
|
| 9 |
+
assert_, assert_raises, assert_equal, assert_array_equal
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
ndims = 2
|
| 14 |
+
size = 10
|
| 15 |
+
shape = tuple([size] * ndims)
|
| 16 |
+
|
| 17 |
+
MAY_SHARE_BOUNDS = 0
|
| 18 |
+
MAY_SHARE_EXACT = -1
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _indices_for_nelems(nelems):
|
| 22 |
+
"""Returns slices of length nelems, from start onwards, in direction sign."""
|
| 23 |
+
|
| 24 |
+
if nelems == 0:
|
| 25 |
+
return [size // 2] # int index
|
| 26 |
+
|
| 27 |
+
res = []
|
| 28 |
+
for step in (1, 2):
|
| 29 |
+
for sign in (-1, 1):
|
| 30 |
+
start = size // 2 - nelems * step * sign // 2
|
| 31 |
+
stop = start + nelems * step * sign
|
| 32 |
+
res.append(slice(start, stop, step * sign))
|
| 33 |
+
|
| 34 |
+
return res
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _indices_for_axis():
|
| 38 |
+
"""Returns (src, dst) pairs of indices."""
|
| 39 |
+
|
| 40 |
+
res = []
|
| 41 |
+
for nelems in (0, 2, 3):
|
| 42 |
+
ind = _indices_for_nelems(nelems)
|
| 43 |
+
res.extend(itertools.product(ind, ind)) # all assignments of size "nelems"
|
| 44 |
+
|
| 45 |
+
return res
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _indices(ndims):
|
| 49 |
+
"""Returns ((axis0_src, axis0_dst), (axis1_src, axis1_dst), ... ) index pairs."""
|
| 50 |
+
|
| 51 |
+
ind = _indices_for_axis()
|
| 52 |
+
return itertools.product(ind, repeat=ndims)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _check_assignment(srcidx, dstidx):
|
| 56 |
+
"""Check assignment arr[dstidx] = arr[srcidx] works."""
|
| 57 |
+
|
| 58 |
+
arr = np.arange(np.prod(shape)).reshape(shape)
|
| 59 |
+
|
| 60 |
+
cpy = arr.copy()
|
| 61 |
+
|
| 62 |
+
cpy[dstidx] = arr[srcidx]
|
| 63 |
+
arr[dstidx] = arr[srcidx]
|
| 64 |
+
|
| 65 |
+
assert_(np.all(arr == cpy),
|
| 66 |
+
'assigning arr[%s] = arr[%s]' % (dstidx, srcidx))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_overlapping_assignments():
|
| 70 |
+
# Test automatically generated assignments which overlap in memory.
|
| 71 |
+
|
| 72 |
+
inds = _indices(ndims)
|
| 73 |
+
|
| 74 |
+
for ind in inds:
|
| 75 |
+
srcidx = tuple([a[0] for a in ind])
|
| 76 |
+
dstidx = tuple([a[1] for a in ind])
|
| 77 |
+
|
| 78 |
+
_check_assignment(srcidx, dstidx)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@pytest.mark.slow
|
| 82 |
+
def test_diophantine_fuzz():
|
| 83 |
+
# Fuzz test the diophantine solver
|
| 84 |
+
rng = np.random.RandomState(1234)
|
| 85 |
+
|
| 86 |
+
max_int = np.iinfo(np.intp).max
|
| 87 |
+
|
| 88 |
+
for ndim in range(10):
|
| 89 |
+
feasible_count = 0
|
| 90 |
+
infeasible_count = 0
|
| 91 |
+
|
| 92 |
+
min_count = 500//(ndim + 1)
|
| 93 |
+
|
| 94 |
+
while min(feasible_count, infeasible_count) < min_count:
|
| 95 |
+
# Ensure big and small integer problems
|
| 96 |
+
A_max = 1 + rng.randint(0, 11, dtype=np.intp)**6
|
| 97 |
+
U_max = rng.randint(0, 11, dtype=np.intp)**6
|
| 98 |
+
|
| 99 |
+
A_max = min(max_int, A_max)
|
| 100 |
+
U_max = min(max_int-1, U_max)
|
| 101 |
+
|
| 102 |
+
A = tuple(int(rng.randint(1, A_max+1, dtype=np.intp))
|
| 103 |
+
for j in range(ndim))
|
| 104 |
+
U = tuple(int(rng.randint(0, U_max+2, dtype=np.intp))
|
| 105 |
+
for j in range(ndim))
|
| 106 |
+
|
| 107 |
+
b_ub = min(max_int-2, sum(a*ub for a, ub in zip(A, U)))
|
| 108 |
+
b = int(rng.randint(-1, b_ub+2, dtype=np.intp))
|
| 109 |
+
|
| 110 |
+
if ndim == 0 and feasible_count < min_count:
|
| 111 |
+
b = 0
|
| 112 |
+
|
| 113 |
+
X = solve_diophantine(A, U, b)
|
| 114 |
+
|
| 115 |
+
if X is None:
|
| 116 |
+
# Check the simplified decision problem agrees
|
| 117 |
+
X_simplified = solve_diophantine(A, U, b, simplify=1)
|
| 118 |
+
assert_(X_simplified is None, (A, U, b, X_simplified))
|
| 119 |
+
|
| 120 |
+
# Check no solution exists (provided the problem is
|
| 121 |
+
# small enough so that brute force checking doesn't
|
| 122 |
+
# take too long)
|
| 123 |
+
ranges = tuple(range(0, a*ub+1, a) for a, ub in zip(A, U))
|
| 124 |
+
|
| 125 |
+
size = 1
|
| 126 |
+
for r in ranges:
|
| 127 |
+
size *= len(r)
|
| 128 |
+
if size < 100000:
|
| 129 |
+
assert_(not any(sum(w) == b for w in itertools.product(*ranges)))
|
| 130 |
+
infeasible_count += 1
|
| 131 |
+
else:
|
| 132 |
+
# Check the simplified decision problem agrees
|
| 133 |
+
X_simplified = solve_diophantine(A, U, b, simplify=1)
|
| 134 |
+
assert_(X_simplified is not None, (A, U, b, X_simplified))
|
| 135 |
+
|
| 136 |
+
# Check validity
|
| 137 |
+
assert_(sum(a*x for a, x in zip(A, X)) == b)
|
| 138 |
+
assert_(all(0 <= x <= ub for x, ub in zip(X, U)))
|
| 139 |
+
feasible_count += 1
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def test_diophantine_overflow():
|
| 143 |
+
# Smoke test integer overflow detection
|
| 144 |
+
max_intp = np.iinfo(np.intp).max
|
| 145 |
+
max_int64 = np.iinfo(np.int64).max
|
| 146 |
+
|
| 147 |
+
if max_int64 <= max_intp:
|
| 148 |
+
# Check that the algorithm works internally in 128-bit;
|
| 149 |
+
# solving this problem requires large intermediate numbers
|
| 150 |
+
A = (max_int64//2, max_int64//2 - 10)
|
| 151 |
+
U = (max_int64//2, max_int64//2 - 10)
|
| 152 |
+
b = 2*(max_int64//2) - 10
|
| 153 |
+
|
| 154 |
+
assert_equal(solve_diophantine(A, U, b), (1, 1))
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def check_may_share_memory_exact(a, b):
|
| 158 |
+
got = np.may_share_memory(a, b, max_work=MAY_SHARE_EXACT)
|
| 159 |
+
|
| 160 |
+
assert_equal(np.may_share_memory(a, b),
|
| 161 |
+
np.may_share_memory(a, b, max_work=MAY_SHARE_BOUNDS))
|
| 162 |
+
|
| 163 |
+
a.fill(0)
|
| 164 |
+
b.fill(0)
|
| 165 |
+
a.fill(1)
|
| 166 |
+
exact = b.any()
|
| 167 |
+
|
| 168 |
+
err_msg = ""
|
| 169 |
+
if got != exact:
|
| 170 |
+
err_msg = " " + "\n ".join([
|
| 171 |
+
"base_a - base_b = %r" % (a.__array_interface__['data'][0] - b.__array_interface__['data'][0],),
|
| 172 |
+
"shape_a = %r" % (a.shape,),
|
| 173 |
+
"shape_b = %r" % (b.shape,),
|
| 174 |
+
"strides_a = %r" % (a.strides,),
|
| 175 |
+
"strides_b = %r" % (b.strides,),
|
| 176 |
+
"size_a = %r" % (a.size,),
|
| 177 |
+
"size_b = %r" % (b.size,)
|
| 178 |
+
])
|
| 179 |
+
|
| 180 |
+
assert_equal(got, exact, err_msg=err_msg)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_may_share_memory_manual():
|
| 184 |
+
# Manual test cases for may_share_memory
|
| 185 |
+
|
| 186 |
+
# Base arrays
|
| 187 |
+
xs0 = [
|
| 188 |
+
np.zeros([13, 21, 23, 22], dtype=np.int8),
|
| 189 |
+
np.zeros([13, 21, 23*2, 22], dtype=np.int8)[:,:,::2,:]
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
# Generate all negative stride combinations
|
| 193 |
+
xs = []
|
| 194 |
+
for x in xs0:
|
| 195 |
+
for ss in itertools.product(*(([slice(None), slice(None, None, -1)],)*4)):
|
| 196 |
+
xp = x[ss]
|
| 197 |
+
xs.append(xp)
|
| 198 |
+
|
| 199 |
+
for x in xs:
|
| 200 |
+
# The default is a simple extent check
|
| 201 |
+
assert_(np.may_share_memory(x[:,0,:], x[:,1,:]))
|
| 202 |
+
assert_(np.may_share_memory(x[:,0,:], x[:,1,:], max_work=None))
|
| 203 |
+
|
| 204 |
+
# Exact checks
|
| 205 |
+
check_may_share_memory_exact(x[:,0,:], x[:,1,:])
|
| 206 |
+
check_may_share_memory_exact(x[:,::7], x[:,3::3])
|
| 207 |
+
|
| 208 |
+
try:
|
| 209 |
+
xp = x.ravel()
|
| 210 |
+
if xp.flags.owndata:
|
| 211 |
+
continue
|
| 212 |
+
xp = xp.view(np.int16)
|
| 213 |
+
except ValueError:
|
| 214 |
+
continue
|
| 215 |
+
|
| 216 |
+
# 0-size arrays cannot overlap
|
| 217 |
+
check_may_share_memory_exact(x.ravel()[6:6],
|
| 218 |
+
xp.reshape(13, 21, 23, 11)[:,::7])
|
| 219 |
+
|
| 220 |
+
# Test itemsize is dealt with
|
| 221 |
+
check_may_share_memory_exact(x[:,::7],
|
| 222 |
+
xp.reshape(13, 21, 23, 11))
|
| 223 |
+
check_may_share_memory_exact(x[:,::7],
|
| 224 |
+
xp.reshape(13, 21, 23, 11)[:,3::3])
|
| 225 |
+
check_may_share_memory_exact(x.ravel()[6:7],
|
| 226 |
+
xp.reshape(13, 21, 23, 11)[:,::7])
|
| 227 |
+
|
| 228 |
+
# Check unit size
|
| 229 |
+
x = np.zeros([1], dtype=np.int8)
|
| 230 |
+
check_may_share_memory_exact(x, x)
|
| 231 |
+
check_may_share_memory_exact(x, x.copy())
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def iter_random_view_pairs(x, same_steps=True, equal_size=False):
|
| 235 |
+
rng = np.random.RandomState(1234)
|
| 236 |
+
|
| 237 |
+
if equal_size and same_steps:
|
| 238 |
+
raise ValueError()
|
| 239 |
+
|
| 240 |
+
def random_slice(n, step):
|
| 241 |
+
start = rng.randint(0, n+1, dtype=np.intp)
|
| 242 |
+
stop = rng.randint(start, n+1, dtype=np.intp)
|
| 243 |
+
if rng.randint(0, 2, dtype=np.intp) == 0:
|
| 244 |
+
stop, start = start, stop
|
| 245 |
+
step *= -1
|
| 246 |
+
return slice(start, stop, step)
|
| 247 |
+
|
| 248 |
+
def random_slice_fixed_size(n, step, size):
|
| 249 |
+
start = rng.randint(0, n+1 - size*step)
|
| 250 |
+
stop = start + (size-1)*step + 1
|
| 251 |
+
if rng.randint(0, 2) == 0:
|
| 252 |
+
stop, start = start-1, stop-1
|
| 253 |
+
if stop < 0:
|
| 254 |
+
stop = None
|
| 255 |
+
step *= -1
|
| 256 |
+
return slice(start, stop, step)
|
| 257 |
+
|
| 258 |
+
# First a few regular views
|
| 259 |
+
yield x, x
|
| 260 |
+
for j in range(1, 7, 3):
|
| 261 |
+
yield x[j:], x[:-j]
|
| 262 |
+
yield x[...,j:], x[...,:-j]
|
| 263 |
+
|
| 264 |
+
# An array with zero stride internal overlap
|
| 265 |
+
strides = list(x.strides)
|
| 266 |
+
strides[0] = 0
|
| 267 |
+
xp = as_strided(x, shape=x.shape, strides=strides)
|
| 268 |
+
yield x, xp
|
| 269 |
+
yield xp, xp
|
| 270 |
+
|
| 271 |
+
# An array with non-zero stride internal overlap
|
| 272 |
+
strides = list(x.strides)
|
| 273 |
+
if strides[0] > 1:
|
| 274 |
+
strides[0] = 1
|
| 275 |
+
xp = as_strided(x, shape=x.shape, strides=strides)
|
| 276 |
+
yield x, xp
|
| 277 |
+
yield xp, xp
|
| 278 |
+
|
| 279 |
+
# Then discontiguous views
|
| 280 |
+
while True:
|
| 281 |
+
steps = tuple(rng.randint(1, 11, dtype=np.intp)
|
| 282 |
+
if rng.randint(0, 5, dtype=np.intp) == 0 else 1
|
| 283 |
+
for j in range(x.ndim))
|
| 284 |
+
s1 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps))
|
| 285 |
+
|
| 286 |
+
t1 = np.arange(x.ndim)
|
| 287 |
+
rng.shuffle(t1)
|
| 288 |
+
|
| 289 |
+
if equal_size:
|
| 290 |
+
t2 = t1
|
| 291 |
+
else:
|
| 292 |
+
t2 = np.arange(x.ndim)
|
| 293 |
+
rng.shuffle(t2)
|
| 294 |
+
|
| 295 |
+
a = x[s1]
|
| 296 |
+
|
| 297 |
+
if equal_size:
|
| 298 |
+
if a.size == 0:
|
| 299 |
+
continue
|
| 300 |
+
|
| 301 |
+
steps2 = tuple(rng.randint(1, max(2, p//(1+pa)))
|
| 302 |
+
if rng.randint(0, 5) == 0 else 1
|
| 303 |
+
for p, s, pa in zip(x.shape, s1, a.shape))
|
| 304 |
+
s2 = tuple(random_slice_fixed_size(p, s, pa)
|
| 305 |
+
for p, s, pa in zip(x.shape, steps2, a.shape))
|
| 306 |
+
elif same_steps:
|
| 307 |
+
steps2 = steps
|
| 308 |
+
else:
|
| 309 |
+
steps2 = tuple(rng.randint(1, 11, dtype=np.intp)
|
| 310 |
+
if rng.randint(0, 5, dtype=np.intp) == 0 else 1
|
| 311 |
+
for j in range(x.ndim))
|
| 312 |
+
|
| 313 |
+
if not equal_size:
|
| 314 |
+
s2 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps2))
|
| 315 |
+
|
| 316 |
+
a = a.transpose(t1)
|
| 317 |
+
b = x[s2].transpose(t2)
|
| 318 |
+
|
| 319 |
+
yield a, b
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def check_may_share_memory_easy_fuzz(get_max_work, same_steps, min_count):
|
| 323 |
+
# Check that overlap problems with common strides are solved with
|
| 324 |
+
# little work.
|
| 325 |
+
x = np.zeros([17,34,71,97], dtype=np.int16)
|
| 326 |
+
|
| 327 |
+
feasible = 0
|
| 328 |
+
infeasible = 0
|
| 329 |
+
|
| 330 |
+
pair_iter = iter_random_view_pairs(x, same_steps)
|
| 331 |
+
|
| 332 |
+
while min(feasible, infeasible) < min_count:
|
| 333 |
+
a, b = next(pair_iter)
|
| 334 |
+
|
| 335 |
+
bounds_overlap = np.may_share_memory(a, b)
|
| 336 |
+
may_share_answer = np.may_share_memory(a, b)
|
| 337 |
+
easy_answer = np.may_share_memory(a, b, max_work=get_max_work(a, b))
|
| 338 |
+
exact_answer = np.may_share_memory(a, b, max_work=MAY_SHARE_EXACT)
|
| 339 |
+
|
| 340 |
+
if easy_answer != exact_answer:
|
| 341 |
+
# assert_equal is slow...
|
| 342 |
+
assert_equal(easy_answer, exact_answer)
|
| 343 |
+
|
| 344 |
+
if may_share_answer != bounds_overlap:
|
| 345 |
+
assert_equal(may_share_answer, bounds_overlap)
|
| 346 |
+
|
| 347 |
+
if bounds_overlap:
|
| 348 |
+
if exact_answer:
|
| 349 |
+
feasible += 1
|
| 350 |
+
else:
|
| 351 |
+
infeasible += 1
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@pytest.mark.slow
|
| 355 |
+
def test_may_share_memory_easy_fuzz():
|
| 356 |
+
# Check that overlap problems with common strides are always
|
| 357 |
+
# solved with little work.
|
| 358 |
+
|
| 359 |
+
check_may_share_memory_easy_fuzz(get_max_work=lambda a, b: 1,
|
| 360 |
+
same_steps=True,
|
| 361 |
+
min_count=2000)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
@pytest.mark.slow
|
| 365 |
+
def test_may_share_memory_harder_fuzz():
|
| 366 |
+
# Overlap problems with not necessarily common strides take more
|
| 367 |
+
# work.
|
| 368 |
+
#
|
| 369 |
+
# The work bound below can't be reduced much. Harder problems can
|
| 370 |
+
# also exist but not be detected here, as the set of problems
|
| 371 |
+
# comes from RNG.
|
| 372 |
+
|
| 373 |
+
check_may_share_memory_easy_fuzz(get_max_work=lambda a, b: max(a.size, b.size)//2,
|
| 374 |
+
same_steps=False,
|
| 375 |
+
min_count=2000)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def test_shares_memory_api():
|
| 379 |
+
x = np.zeros([4, 5, 6], dtype=np.int8)
|
| 380 |
+
|
| 381 |
+
assert_equal(np.shares_memory(x, x), True)
|
| 382 |
+
assert_equal(np.shares_memory(x, x.copy()), False)
|
| 383 |
+
|
| 384 |
+
a = x[:,::2,::3]
|
| 385 |
+
b = x[:,::3,::2]
|
| 386 |
+
assert_equal(np.shares_memory(a, b), True)
|
| 387 |
+
assert_equal(np.shares_memory(a, b, max_work=None), True)
|
| 388 |
+
assert_raises(
|
| 389 |
+
np.exceptions.TooHardError, np.shares_memory, a, b, max_work=1
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def test_may_share_memory_bad_max_work():
|
| 394 |
+
x = np.zeros([1])
|
| 395 |
+
assert_raises(OverflowError, np.may_share_memory, x, x, max_work=10**100)
|
| 396 |
+
assert_raises(OverflowError, np.shares_memory, x, x, max_work=10**100)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def test_internal_overlap_diophantine():
|
| 400 |
+
def check(A, U, exists=None):
|
| 401 |
+
X = solve_diophantine(A, U, 0, require_ub_nontrivial=1)
|
| 402 |
+
|
| 403 |
+
if exists is None:
|
| 404 |
+
exists = (X is not None)
|
| 405 |
+
|
| 406 |
+
if X is not None:
|
| 407 |
+
assert_(sum(a*x for a, x in zip(A, X)) == sum(a*u//2 for a, u in zip(A, U)))
|
| 408 |
+
assert_(all(0 <= x <= u for x, u in zip(X, U)))
|
| 409 |
+
assert_(any(x != u//2 for x, u in zip(X, U)))
|
| 410 |
+
|
| 411 |
+
if exists:
|
| 412 |
+
assert_(X is not None, repr(X))
|
| 413 |
+
else:
|
| 414 |
+
assert_(X is None, repr(X))
|
| 415 |
+
|
| 416 |
+
# Smoke tests
|
| 417 |
+
check((3, 2), (2*2, 3*2), exists=True)
|
| 418 |
+
check((3*2, 2), (15*2, (3-1)*2), exists=False)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def test_internal_overlap_slices():
|
| 422 |
+
# Slicing an array never generates internal overlap
|
| 423 |
+
|
| 424 |
+
x = np.zeros([17,34,71,97], dtype=np.int16)
|
| 425 |
+
|
| 426 |
+
rng = np.random.RandomState(1234)
|
| 427 |
+
|
| 428 |
+
def random_slice(n, step):
|
| 429 |
+
start = rng.randint(0, n+1, dtype=np.intp)
|
| 430 |
+
stop = rng.randint(start, n+1, dtype=np.intp)
|
| 431 |
+
if rng.randint(0, 2, dtype=np.intp) == 0:
|
| 432 |
+
stop, start = start, stop
|
| 433 |
+
step *= -1
|
| 434 |
+
return slice(start, stop, step)
|
| 435 |
+
|
| 436 |
+
cases = 0
|
| 437 |
+
min_count = 5000
|
| 438 |
+
|
| 439 |
+
while cases < min_count:
|
| 440 |
+
steps = tuple(rng.randint(1, 11, dtype=np.intp)
|
| 441 |
+
if rng.randint(0, 5, dtype=np.intp) == 0 else 1
|
| 442 |
+
for j in range(x.ndim))
|
| 443 |
+
t1 = np.arange(x.ndim)
|
| 444 |
+
rng.shuffle(t1)
|
| 445 |
+
s1 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps))
|
| 446 |
+
a = x[s1].transpose(t1)
|
| 447 |
+
|
| 448 |
+
assert_(not internal_overlap(a))
|
| 449 |
+
cases += 1
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def check_internal_overlap(a, manual_expected=None):
|
| 453 |
+
got = internal_overlap(a)
|
| 454 |
+
|
| 455 |
+
# Brute-force check
|
| 456 |
+
m = set()
|
| 457 |
+
ranges = tuple(range(n) for n in a.shape)
|
| 458 |
+
for v in itertools.product(*ranges):
|
| 459 |
+
offset = sum(s*w for s, w in zip(a.strides, v))
|
| 460 |
+
if offset in m:
|
| 461 |
+
expected = True
|
| 462 |
+
break
|
| 463 |
+
else:
|
| 464 |
+
m.add(offset)
|
| 465 |
+
else:
|
| 466 |
+
expected = False
|
| 467 |
+
|
| 468 |
+
# Compare
|
| 469 |
+
if got != expected:
|
| 470 |
+
assert_equal(got, expected, err_msg=repr((a.strides, a.shape)))
|
| 471 |
+
if manual_expected is not None and expected != manual_expected:
|
| 472 |
+
assert_equal(expected, manual_expected)
|
| 473 |
+
return got
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def test_internal_overlap_manual():
|
| 477 |
+
# Stride tricks can construct arrays with internal overlap
|
| 478 |
+
|
| 479 |
+
# We don't care about memory bounds, the array is not
|
| 480 |
+
# read/write accessed
|
| 481 |
+
x = np.arange(1).astype(np.int8)
|
| 482 |
+
|
| 483 |
+
# Check low-dimensional special cases
|
| 484 |
+
|
| 485 |
+
check_internal_overlap(x, False) # 1-dim
|
| 486 |
+
check_internal_overlap(x.reshape([]), False) # 0-dim
|
| 487 |
+
|
| 488 |
+
a = as_strided(x, strides=(3, 4), shape=(4, 4))
|
| 489 |
+
check_internal_overlap(a, False)
|
| 490 |
+
|
| 491 |
+
a = as_strided(x, strides=(3, 4), shape=(5, 4))
|
| 492 |
+
check_internal_overlap(a, True)
|
| 493 |
+
|
| 494 |
+
a = as_strided(x, strides=(0,), shape=(0,))
|
| 495 |
+
check_internal_overlap(a, False)
|
| 496 |
+
|
| 497 |
+
a = as_strided(x, strides=(0,), shape=(1,))
|
| 498 |
+
check_internal_overlap(a, False)
|
| 499 |
+
|
| 500 |
+
a = as_strided(x, strides=(0,), shape=(2,))
|
| 501 |
+
check_internal_overlap(a, True)
|
| 502 |
+
|
| 503 |
+
a = as_strided(x, strides=(0, -9993), shape=(87, 22))
|
| 504 |
+
check_internal_overlap(a, True)
|
| 505 |
+
|
| 506 |
+
a = as_strided(x, strides=(0, -9993), shape=(1, 22))
|
| 507 |
+
check_internal_overlap(a, False)
|
| 508 |
+
|
| 509 |
+
a = as_strided(x, strides=(0, -9993), shape=(0, 22))
|
| 510 |
+
check_internal_overlap(a, False)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def test_internal_overlap_fuzz():
|
| 514 |
+
# Fuzz check; the brute-force check is fairly slow
|
| 515 |
+
|
| 516 |
+
x = np.arange(1).astype(np.int8)
|
| 517 |
+
|
| 518 |
+
overlap = 0
|
| 519 |
+
no_overlap = 0
|
| 520 |
+
min_count = 100
|
| 521 |
+
|
| 522 |
+
rng = np.random.RandomState(1234)
|
| 523 |
+
|
| 524 |
+
while min(overlap, no_overlap) < min_count:
|
| 525 |
+
ndim = rng.randint(1, 4, dtype=np.intp)
|
| 526 |
+
|
| 527 |
+
strides = tuple(rng.randint(-1000, 1000, dtype=np.intp)
|
| 528 |
+
for j in range(ndim))
|
| 529 |
+
shape = tuple(rng.randint(1, 30, dtype=np.intp)
|
| 530 |
+
for j in range(ndim))
|
| 531 |
+
|
| 532 |
+
a = as_strided(x, strides=strides, shape=shape)
|
| 533 |
+
result = check_internal_overlap(a)
|
| 534 |
+
|
| 535 |
+
if result:
|
| 536 |
+
overlap += 1
|
| 537 |
+
else:
|
| 538 |
+
no_overlap += 1
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def test_non_ndarray_inputs():
|
| 542 |
+
# Regression check for gh-5604
|
| 543 |
+
|
| 544 |
+
class MyArray:
|
| 545 |
+
def __init__(self, data):
|
| 546 |
+
self.data = data
|
| 547 |
+
|
| 548 |
+
@property
|
| 549 |
+
def __array_interface__(self):
|
| 550 |
+
return self.data.__array_interface__
|
| 551 |
+
|
| 552 |
+
class MyArray2:
|
| 553 |
+
def __init__(self, data):
|
| 554 |
+
self.data = data
|
| 555 |
+
|
| 556 |
+
def __array__(self, dtype=None, copy=None):
|
| 557 |
+
return self.data
|
| 558 |
+
|
| 559 |
+
for cls in [MyArray, MyArray2]:
|
| 560 |
+
x = np.arange(5)
|
| 561 |
+
|
| 562 |
+
assert_(np.may_share_memory(cls(x[::2]), x[1::2]))
|
| 563 |
+
assert_(not np.shares_memory(cls(x[::2]), x[1::2]))
|
| 564 |
+
|
| 565 |
+
assert_(np.shares_memory(cls(x[1::3]), x[::2]))
|
| 566 |
+
assert_(np.may_share_memory(cls(x[1::3]), x[::2]))
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def view_element_first_byte(x):
|
| 570 |
+
"""Construct an array viewing the first byte of each element of `x`"""
|
| 571 |
+
from numpy.lib._stride_tricks_impl import DummyArray
|
| 572 |
+
interface = dict(x.__array_interface__)
|
| 573 |
+
interface['typestr'] = '|b1'
|
| 574 |
+
interface['descr'] = [('', '|b1')]
|
| 575 |
+
return np.asarray(DummyArray(interface, x))
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def assert_copy_equivalent(operation, args, out, **kwargs):
|
| 579 |
+
"""
|
| 580 |
+
Check that operation(*args, out=out) produces results
|
| 581 |
+
equivalent to out[...] = operation(*args, out=out.copy())
|
| 582 |
+
"""
|
| 583 |
+
|
| 584 |
+
kwargs['out'] = out
|
| 585 |
+
kwargs2 = dict(kwargs)
|
| 586 |
+
kwargs2['out'] = out.copy()
|
| 587 |
+
|
| 588 |
+
out_orig = out.copy()
|
| 589 |
+
out[...] = operation(*args, **kwargs2)
|
| 590 |
+
expected = out.copy()
|
| 591 |
+
out[...] = out_orig
|
| 592 |
+
|
| 593 |
+
got = operation(*args, **kwargs).copy()
|
| 594 |
+
|
| 595 |
+
if (got != expected).any():
|
| 596 |
+
assert_equal(got, expected)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
class TestUFunc:
|
| 600 |
+
"""
|
| 601 |
+
Test ufunc call memory overlap handling
|
| 602 |
+
"""
|
| 603 |
+
|
| 604 |
+
def check_unary_fuzz(self, operation, get_out_axis_size, dtype=np.int16,
|
| 605 |
+
count=5000):
|
| 606 |
+
shapes = [7, 13, 8, 21, 29, 32]
|
| 607 |
+
|
| 608 |
+
rng = np.random.RandomState(1234)
|
| 609 |
+
|
| 610 |
+
for ndim in range(1, 6):
|
| 611 |
+
x = rng.randint(0, 2**16, size=shapes[:ndim]).astype(dtype)
|
| 612 |
+
|
| 613 |
+
it = iter_random_view_pairs(x, same_steps=False, equal_size=True)
|
| 614 |
+
|
| 615 |
+
min_count = count // (ndim + 1)**2
|
| 616 |
+
|
| 617 |
+
overlapping = 0
|
| 618 |
+
while overlapping < min_count:
|
| 619 |
+
a, b = next(it)
|
| 620 |
+
|
| 621 |
+
a_orig = a.copy()
|
| 622 |
+
b_orig = b.copy()
|
| 623 |
+
|
| 624 |
+
if get_out_axis_size is None:
|
| 625 |
+
assert_copy_equivalent(operation, [a], out=b)
|
| 626 |
+
|
| 627 |
+
if np.shares_memory(a, b):
|
| 628 |
+
overlapping += 1
|
| 629 |
+
else:
|
| 630 |
+
for axis in itertools.chain(range(ndim), [None]):
|
| 631 |
+
a[...] = a_orig
|
| 632 |
+
b[...] = b_orig
|
| 633 |
+
|
| 634 |
+
# Determine size for reduction axis (None if scalar)
|
| 635 |
+
outsize, scalarize = get_out_axis_size(a, b, axis)
|
| 636 |
+
if outsize == 'skip':
|
| 637 |
+
continue
|
| 638 |
+
|
| 639 |
+
# Slice b to get an output array of the correct size
|
| 640 |
+
sl = [slice(None)] * ndim
|
| 641 |
+
if axis is None:
|
| 642 |
+
if outsize is None:
|
| 643 |
+
sl = [slice(0, 1)] + [0]*(ndim - 1)
|
| 644 |
+
else:
|
| 645 |
+
sl = [slice(0, outsize)] + [0]*(ndim - 1)
|
| 646 |
+
else:
|
| 647 |
+
if outsize is None:
|
| 648 |
+
k = b.shape[axis]//2
|
| 649 |
+
if ndim == 1:
|
| 650 |
+
sl[axis] = slice(k, k + 1)
|
| 651 |
+
else:
|
| 652 |
+
sl[axis] = k
|
| 653 |
+
else:
|
| 654 |
+
assert b.shape[axis] >= outsize
|
| 655 |
+
sl[axis] = slice(0, outsize)
|
| 656 |
+
b_out = b[tuple(sl)]
|
| 657 |
+
|
| 658 |
+
if scalarize:
|
| 659 |
+
b_out = b_out.reshape([])
|
| 660 |
+
|
| 661 |
+
if np.shares_memory(a, b_out):
|
| 662 |
+
overlapping += 1
|
| 663 |
+
|
| 664 |
+
# Check result
|
| 665 |
+
assert_copy_equivalent(operation, [a], out=b_out, axis=axis)
|
| 666 |
+
|
| 667 |
+
@pytest.mark.slow
|
| 668 |
+
def test_unary_ufunc_call_fuzz(self):
|
| 669 |
+
self.check_unary_fuzz(np.invert, None, np.int16)
|
| 670 |
+
|
| 671 |
+
@pytest.mark.slow
|
| 672 |
+
def test_unary_ufunc_call_complex_fuzz(self):
|
| 673 |
+
# Complex typically has a smaller alignment than itemsize
|
| 674 |
+
self.check_unary_fuzz(np.negative, None, np.complex128, count=500)
|
| 675 |
+
|
| 676 |
+
def test_binary_ufunc_accumulate_fuzz(self):
|
| 677 |
+
def get_out_axis_size(a, b, axis):
|
| 678 |
+
if axis is None:
|
| 679 |
+
if a.ndim == 1:
|
| 680 |
+
return a.size, False
|
| 681 |
+
else:
|
| 682 |
+
return 'skip', False # accumulate doesn't support this
|
| 683 |
+
else:
|
| 684 |
+
return a.shape[axis], False
|
| 685 |
+
|
| 686 |
+
self.check_unary_fuzz(np.add.accumulate, get_out_axis_size,
|
| 687 |
+
dtype=np.int16, count=500)
|
| 688 |
+
|
| 689 |
+
def test_binary_ufunc_reduce_fuzz(self):
|
| 690 |
+
def get_out_axis_size(a, b, axis):
|
| 691 |
+
return None, (axis is None or a.ndim == 1)
|
| 692 |
+
|
| 693 |
+
self.check_unary_fuzz(np.add.reduce, get_out_axis_size,
|
| 694 |
+
dtype=np.int16, count=500)
|
| 695 |
+
|
| 696 |
+
def test_binary_ufunc_reduceat_fuzz(self):
|
| 697 |
+
def get_out_axis_size(a, b, axis):
|
| 698 |
+
if axis is None:
|
| 699 |
+
if a.ndim == 1:
|
| 700 |
+
return a.size, False
|
| 701 |
+
else:
|
| 702 |
+
return 'skip', False # reduceat doesn't support this
|
| 703 |
+
else:
|
| 704 |
+
return a.shape[axis], False
|
| 705 |
+
|
| 706 |
+
def do_reduceat(a, out, axis):
|
| 707 |
+
if axis is None:
|
| 708 |
+
size = len(a)
|
| 709 |
+
step = size//len(out)
|
| 710 |
+
else:
|
| 711 |
+
size = a.shape[axis]
|
| 712 |
+
step = a.shape[axis] // out.shape[axis]
|
| 713 |
+
idx = np.arange(0, size, step)
|
| 714 |
+
return np.add.reduceat(a, idx, out=out, axis=axis)
|
| 715 |
+
|
| 716 |
+
self.check_unary_fuzz(do_reduceat, get_out_axis_size,
|
| 717 |
+
dtype=np.int16, count=500)
|
| 718 |
+
|
| 719 |
+
def test_binary_ufunc_reduceat_manual(self):
|
| 720 |
+
def check(ufunc, a, ind, out):
|
| 721 |
+
c1 = ufunc.reduceat(a.copy(), ind.copy(), out=out.copy())
|
| 722 |
+
c2 = ufunc.reduceat(a, ind, out=out)
|
| 723 |
+
assert_array_equal(c1, c2)
|
| 724 |
+
|
| 725 |
+
# Exactly same input/output arrays
|
| 726 |
+
a = np.arange(10000, dtype=np.int16)
|
| 727 |
+
check(np.add, a, a[::-1].copy(), a)
|
| 728 |
+
|
| 729 |
+
# Overlap with index
|
| 730 |
+
a = np.arange(10000, dtype=np.int16)
|
| 731 |
+
check(np.add, a, a[::-1], a)
|
| 732 |
+
|
| 733 |
+
@pytest.mark.slow
|
| 734 |
+
def test_unary_gufunc_fuzz(self):
|
| 735 |
+
shapes = [7, 13, 8, 21, 29, 32]
|
| 736 |
+
gufunc = _umath_tests.euclidean_pdist
|
| 737 |
+
|
| 738 |
+
rng = np.random.RandomState(1234)
|
| 739 |
+
|
| 740 |
+
for ndim in range(2, 6):
|
| 741 |
+
x = rng.rand(*shapes[:ndim])
|
| 742 |
+
|
| 743 |
+
it = iter_random_view_pairs(x, same_steps=False, equal_size=True)
|
| 744 |
+
|
| 745 |
+
min_count = 500 // (ndim + 1)**2
|
| 746 |
+
|
| 747 |
+
overlapping = 0
|
| 748 |
+
while overlapping < min_count:
|
| 749 |
+
a, b = next(it)
|
| 750 |
+
|
| 751 |
+
if min(a.shape[-2:]) < 2 or min(b.shape[-2:]) < 2 or a.shape[-1] < 2:
|
| 752 |
+
continue
|
| 753 |
+
|
| 754 |
+
# Ensure the shapes are so that euclidean_pdist is happy
|
| 755 |
+
if b.shape[-1] > b.shape[-2]:
|
| 756 |
+
b = b[...,0,:]
|
| 757 |
+
else:
|
| 758 |
+
b = b[...,:,0]
|
| 759 |
+
|
| 760 |
+
n = a.shape[-2]
|
| 761 |
+
p = n * (n - 1) // 2
|
| 762 |
+
if p <= b.shape[-1] and p > 0:
|
| 763 |
+
b = b[...,:p]
|
| 764 |
+
else:
|
| 765 |
+
n = max(2, int(np.sqrt(b.shape[-1]))//2)
|
| 766 |
+
p = n * (n - 1) // 2
|
| 767 |
+
a = a[...,:n,:]
|
| 768 |
+
b = b[...,:p]
|
| 769 |
+
|
| 770 |
+
# Call
|
| 771 |
+
if np.shares_memory(a, b):
|
| 772 |
+
overlapping += 1
|
| 773 |
+
|
| 774 |
+
with np.errstate(over='ignore', invalid='ignore'):
|
| 775 |
+
assert_copy_equivalent(gufunc, [a], out=b)
|
| 776 |
+
|
| 777 |
+
def test_ufunc_at_manual(self):
|
| 778 |
+
def check(ufunc, a, ind, b=None):
|
| 779 |
+
a0 = a.copy()
|
| 780 |
+
if b is None:
|
| 781 |
+
ufunc.at(a0, ind.copy())
|
| 782 |
+
c1 = a0.copy()
|
| 783 |
+
ufunc.at(a, ind)
|
| 784 |
+
c2 = a.copy()
|
| 785 |
+
else:
|
| 786 |
+
ufunc.at(a0, ind.copy(), b.copy())
|
| 787 |
+
c1 = a0.copy()
|
| 788 |
+
ufunc.at(a, ind, b)
|
| 789 |
+
c2 = a.copy()
|
| 790 |
+
assert_array_equal(c1, c2)
|
| 791 |
+
|
| 792 |
+
# Overlap with index
|
| 793 |
+
a = np.arange(10000, dtype=np.int16)
|
| 794 |
+
check(np.invert, a[::-1], a)
|
| 795 |
+
|
| 796 |
+
# Overlap with second data array
|
| 797 |
+
a = np.arange(100, dtype=np.int16)
|
| 798 |
+
ind = np.arange(0, 100, 2, dtype=np.int16)
|
| 799 |
+
check(np.add, a, ind, a[25:75])
|
| 800 |
+
|
| 801 |
+
def test_unary_ufunc_1d_manual(self):
|
| 802 |
+
# Exercise ufunc fast-paths (that avoid creation of an `np.nditer`)
|
| 803 |
+
|
| 804 |
+
def check(a, b):
|
| 805 |
+
a_orig = a.copy()
|
| 806 |
+
b_orig = b.copy()
|
| 807 |
+
|
| 808 |
+
b0 = b.copy()
|
| 809 |
+
c1 = ufunc(a, out=b0)
|
| 810 |
+
c2 = ufunc(a, out=b)
|
| 811 |
+
assert_array_equal(c1, c2)
|
| 812 |
+
|
| 813 |
+
# Trigger "fancy ufunc loop" code path
|
| 814 |
+
mask = view_element_first_byte(b).view(np.bool)
|
| 815 |
+
|
| 816 |
+
a[...] = a_orig
|
| 817 |
+
b[...] = b_orig
|
| 818 |
+
c1 = ufunc(a, out=b.copy(), where=mask.copy()).copy()
|
| 819 |
+
|
| 820 |
+
a[...] = a_orig
|
| 821 |
+
b[...] = b_orig
|
| 822 |
+
c2 = ufunc(a, out=b, where=mask.copy()).copy()
|
| 823 |
+
|
| 824 |
+
# Also, mask overlapping with output
|
| 825 |
+
a[...] = a_orig
|
| 826 |
+
b[...] = b_orig
|
| 827 |
+
c3 = ufunc(a, out=b, where=mask).copy()
|
| 828 |
+
|
| 829 |
+
assert_array_equal(c1, c2)
|
| 830 |
+
assert_array_equal(c1, c3)
|
| 831 |
+
|
| 832 |
+
dtypes = [np.int8, np.int16, np.int32, np.int64, np.float32,
|
| 833 |
+
np.float64, np.complex64, np.complex128]
|
| 834 |
+
dtypes = [np.dtype(x) for x in dtypes]
|
| 835 |
+
|
| 836 |
+
for dtype in dtypes:
|
| 837 |
+
if np.issubdtype(dtype, np.integer):
|
| 838 |
+
ufunc = np.invert
|
| 839 |
+
else:
|
| 840 |
+
ufunc = np.reciprocal
|
| 841 |
+
|
| 842 |
+
n = 1000
|
| 843 |
+
k = 10
|
| 844 |
+
indices = [
|
| 845 |
+
np.index_exp[:n],
|
| 846 |
+
np.index_exp[k:k+n],
|
| 847 |
+
np.index_exp[n-1::-1],
|
| 848 |
+
np.index_exp[k+n-1:k-1:-1],
|
| 849 |
+
np.index_exp[:2*n:2],
|
| 850 |
+
np.index_exp[k:k+2*n:2],
|
| 851 |
+
np.index_exp[2*n-1::-2],
|
| 852 |
+
np.index_exp[k+2*n-1:k-1:-2],
|
| 853 |
+
]
|
| 854 |
+
|
| 855 |
+
for xi, yi in itertools.product(indices, indices):
|
| 856 |
+
v = np.arange(1, 1 + n*2 + k, dtype=dtype)
|
| 857 |
+
x = v[xi]
|
| 858 |
+
y = v[yi]
|
| 859 |
+
|
| 860 |
+
with np.errstate(all='ignore'):
|
| 861 |
+
check(x, y)
|
| 862 |
+
|
| 863 |
+
# Scalar cases
|
| 864 |
+
check(x[:1], y)
|
| 865 |
+
check(x[-1:], y)
|
| 866 |
+
check(x[:1].reshape([]), y)
|
| 867 |
+
check(x[-1:].reshape([]), y)
|
| 868 |
+
|
| 869 |
+
def test_unary_ufunc_where_same(self):
|
| 870 |
+
# Check behavior at wheremask overlap
|
| 871 |
+
ufunc = np.invert
|
| 872 |
+
|
| 873 |
+
def check(a, out, mask):
|
| 874 |
+
c1 = ufunc(a, out=out.copy(), where=mask.copy())
|
| 875 |
+
c2 = ufunc(a, out=out, where=mask)
|
| 876 |
+
assert_array_equal(c1, c2)
|
| 877 |
+
|
| 878 |
+
# Check behavior with same input and output arrays
|
| 879 |
+
x = np.arange(100).astype(np.bool)
|
| 880 |
+
check(x, x, x)
|
| 881 |
+
check(x, x.copy(), x)
|
| 882 |
+
check(x, x, x.copy())
|
| 883 |
+
|
| 884 |
+
@pytest.mark.slow
|
| 885 |
+
def test_binary_ufunc_1d_manual(self):
|
| 886 |
+
ufunc = np.add
|
| 887 |
+
|
| 888 |
+
def check(a, b, c):
|
| 889 |
+
c0 = c.copy()
|
| 890 |
+
c1 = ufunc(a, b, out=c0)
|
| 891 |
+
c2 = ufunc(a, b, out=c)
|
| 892 |
+
assert_array_equal(c1, c2)
|
| 893 |
+
|
| 894 |
+
for dtype in [np.int8, np.int16, np.int32, np.int64,
|
| 895 |
+
np.float32, np.float64, np.complex64, np.complex128]:
|
| 896 |
+
# Check different data dependency orders
|
| 897 |
+
|
| 898 |
+
n = 1000
|
| 899 |
+
k = 10
|
| 900 |
+
|
| 901 |
+
indices = []
|
| 902 |
+
for p in [1, 2]:
|
| 903 |
+
indices.extend([
|
| 904 |
+
np.index_exp[:p*n:p],
|
| 905 |
+
np.index_exp[k:k+p*n:p],
|
| 906 |
+
np.index_exp[p*n-1::-p],
|
| 907 |
+
np.index_exp[k+p*n-1:k-1:-p],
|
| 908 |
+
])
|
| 909 |
+
|
| 910 |
+
for x, y, z in itertools.product(indices, indices, indices):
|
| 911 |
+
v = np.arange(6*n).astype(dtype)
|
| 912 |
+
x = v[x]
|
| 913 |
+
y = v[y]
|
| 914 |
+
z = v[z]
|
| 915 |
+
|
| 916 |
+
check(x, y, z)
|
| 917 |
+
|
| 918 |
+
# Scalar cases
|
| 919 |
+
check(x[:1], y, z)
|
| 920 |
+
check(x[-1:], y, z)
|
| 921 |
+
check(x[:1].reshape([]), y, z)
|
| 922 |
+
check(x[-1:].reshape([]), y, z)
|
| 923 |
+
check(x, y[:1], z)
|
| 924 |
+
check(x, y[-1:], z)
|
| 925 |
+
check(x, y[:1].reshape([]), z)
|
| 926 |
+
check(x, y[-1:].reshape([]), z)
|
| 927 |
+
|
| 928 |
+
def test_inplace_op_simple_manual(self):
|
| 929 |
+
rng = np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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import gc
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import threading
|
| 6 |
+
import warnings
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from numpy.testing import extbuild, assert_warns, IS_WASM, IS_EDITABLE
|
| 12 |
+
from numpy._core.multiarray import get_handler_name
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture
|
| 16 |
+
def get_module(tmp_path):
|
| 17 |
+
""" Add a memory policy that returns a false pointer 64 bytes into the
|
| 18 |
+
actual allocation, and fill the prefix with some text. Then check at each
|
| 19 |
+
memory manipulation that the prefix exists, to make sure all alloc/realloc/
|
| 20 |
+
free/calloc go via the functions here.
|
| 21 |
+
"""
|
| 22 |
+
if sys.platform.startswith('cygwin'):
|
| 23 |
+
pytest.skip('link fails on cygwin')
|
| 24 |
+
if IS_WASM:
|
| 25 |
+
pytest.skip("Can't build module inside Wasm")
|
| 26 |
+
if IS_EDITABLE:
|
| 27 |
+
pytest.skip("Can't build module for editable install")
|
| 28 |
+
|
| 29 |
+
functions = [
|
| 30 |
+
("get_default_policy", "METH_NOARGS", """
|
| 31 |
+
Py_INCREF(PyDataMem_DefaultHandler);
|
| 32 |
+
return PyDataMem_DefaultHandler;
|
| 33 |
+
"""),
|
| 34 |
+
("set_secret_data_policy", "METH_NOARGS", """
|
| 35 |
+
PyObject *secret_data =
|
| 36 |
+
PyCapsule_New(&secret_data_handler, "mem_handler", NULL);
|
| 37 |
+
if (secret_data == NULL) {
|
| 38 |
+
return NULL;
|
| 39 |
+
}
|
| 40 |
+
PyObject *old = PyDataMem_SetHandler(secret_data);
|
| 41 |
+
Py_DECREF(secret_data);
|
| 42 |
+
return old;
|
| 43 |
+
"""),
|
| 44 |
+
("set_wrong_capsule_name_data_policy", "METH_NOARGS", """
|
| 45 |
+
PyObject *wrong_name_capsule =
|
| 46 |
+
PyCapsule_New(&secret_data_handler, "not_mem_handler", NULL);
|
| 47 |
+
if (wrong_name_capsule == NULL) {
|
| 48 |
+
return NULL;
|
| 49 |
+
}
|
| 50 |
+
PyObject *old = PyDataMem_SetHandler(wrong_name_capsule);
|
| 51 |
+
Py_DECREF(wrong_name_capsule);
|
| 52 |
+
return old;
|
| 53 |
+
"""),
|
| 54 |
+
("set_old_policy", "METH_O", """
|
| 55 |
+
PyObject *old;
|
| 56 |
+
if (args != NULL && PyCapsule_CheckExact(args)) {
|
| 57 |
+
old = PyDataMem_SetHandler(args);
|
| 58 |
+
}
|
| 59 |
+
else {
|
| 60 |
+
old = PyDataMem_SetHandler(NULL);
|
| 61 |
+
}
|
| 62 |
+
return old;
|
| 63 |
+
"""),
|
| 64 |
+
("get_array", "METH_NOARGS", """
|
| 65 |
+
char *buf = (char *)malloc(20);
|
| 66 |
+
npy_intp dims[1];
|
| 67 |
+
dims[0] = 20;
|
| 68 |
+
PyArray_Descr *descr = PyArray_DescrNewFromType(NPY_UINT8);
|
| 69 |
+
return PyArray_NewFromDescr(&PyArray_Type, descr, 1, dims, NULL,
|
| 70 |
+
buf, NPY_ARRAY_WRITEABLE, NULL);
|
| 71 |
+
"""),
|
| 72 |
+
("set_own", "METH_O", """
|
| 73 |
+
if (!PyArray_Check(args)) {
|
| 74 |
+
PyErr_SetString(PyExc_ValueError,
|
| 75 |
+
"need an ndarray");
|
| 76 |
+
return NULL;
|
| 77 |
+
}
|
| 78 |
+
PyArray_ENABLEFLAGS((PyArrayObject*)args, NPY_ARRAY_OWNDATA);
|
| 79 |
+
// Maybe try this too?
|
| 80 |
+
// PyArray_BASE(PyArrayObject *)args) = NULL;
|
| 81 |
+
Py_RETURN_NONE;
|
| 82 |
+
"""),
|
| 83 |
+
("get_array_with_base", "METH_NOARGS", """
|
| 84 |
+
char *buf = (char *)malloc(20);
|
| 85 |
+
npy_intp dims[1];
|
| 86 |
+
dims[0] = 20;
|
| 87 |
+
PyArray_Descr *descr = PyArray_DescrNewFromType(NPY_UINT8);
|
| 88 |
+
PyObject *arr = PyArray_NewFromDescr(&PyArray_Type, descr, 1, dims,
|
| 89 |
+
NULL, buf,
|
| 90 |
+
NPY_ARRAY_WRITEABLE, NULL);
|
| 91 |
+
if (arr == NULL) return NULL;
|
| 92 |
+
PyObject *obj = PyCapsule_New(buf, "buf capsule",
|
| 93 |
+
(PyCapsule_Destructor)&warn_on_free);
|
| 94 |
+
if (obj == NULL) {
|
| 95 |
+
Py_DECREF(arr);
|
| 96 |
+
return NULL;
|
| 97 |
+
}
|
| 98 |
+
if (PyArray_SetBaseObject((PyArrayObject *)arr, obj) < 0) {
|
| 99 |
+
Py_DECREF(arr);
|
| 100 |
+
Py_DECREF(obj);
|
| 101 |
+
return NULL;
|
| 102 |
+
}
|
| 103 |
+
return arr;
|
| 104 |
+
|
| 105 |
+
"""),
|
| 106 |
+
]
|
| 107 |
+
prologue = '''
|
| 108 |
+
#define NPY_TARGET_VERSION NPY_1_22_API_VERSION
|
| 109 |
+
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
|
| 110 |
+
#include <numpy/arrayobject.h>
|
| 111 |
+
/*
|
| 112 |
+
* This struct allows the dynamic configuration of the allocator funcs
|
| 113 |
+
* of the `secret_data_allocator`. It is provided here for
|
| 114 |
+
* demonstration purposes, as a valid `ctx` use-case scenario.
|
| 115 |
+
*/
|
| 116 |
+
typedef struct {
|
| 117 |
+
void *(*malloc)(size_t);
|
| 118 |
+
void *(*calloc)(size_t, size_t);
|
| 119 |
+
void *(*realloc)(void *, size_t);
|
| 120 |
+
void (*free)(void *);
|
| 121 |
+
} SecretDataAllocatorFuncs;
|
| 122 |
+
|
| 123 |
+
NPY_NO_EXPORT void *
|
| 124 |
+
shift_alloc(void *ctx, size_t sz) {
|
| 125 |
+
SecretDataAllocatorFuncs *funcs = (SecretDataAllocatorFuncs *)ctx;
|
| 126 |
+
char *real = (char *)funcs->malloc(sz + 64);
|
| 127 |
+
if (real == NULL) {
|
| 128 |
+
return NULL;
|
| 129 |
+
}
|
| 130 |
+
snprintf(real, 64, "originally allocated %ld", (unsigned long)sz);
|
| 131 |
+
return (void *)(real + 64);
|
| 132 |
+
}
|
| 133 |
+
NPY_NO_EXPORT void *
|
| 134 |
+
shift_zero(void *ctx, size_t sz, size_t cnt) {
|
| 135 |
+
SecretDataAllocatorFuncs *funcs = (SecretDataAllocatorFuncs *)ctx;
|
| 136 |
+
char *real = (char *)funcs->calloc(sz + 64, cnt);
|
| 137 |
+
if (real == NULL) {
|
| 138 |
+
return NULL;
|
| 139 |
+
}
|
| 140 |
+
snprintf(real, 64, "originally allocated %ld via zero",
|
| 141 |
+
(unsigned long)sz);
|
| 142 |
+
return (void *)(real + 64);
|
| 143 |
+
}
|
| 144 |
+
NPY_NO_EXPORT void
|
| 145 |
+
shift_free(void *ctx, void * p, npy_uintp sz) {
|
| 146 |
+
SecretDataAllocatorFuncs *funcs = (SecretDataAllocatorFuncs *)ctx;
|
| 147 |
+
if (p == NULL) {
|
| 148 |
+
return ;
|
| 149 |
+
}
|
| 150 |
+
char *real = (char *)p - 64;
|
| 151 |
+
if (strncmp(real, "originally allocated", 20) != 0) {
|
| 152 |
+
fprintf(stdout, "uh-oh, unmatched shift_free, "
|
| 153 |
+
"no appropriate prefix\\n");
|
| 154 |
+
/* Make C runtime crash by calling free on the wrong address */
|
| 155 |
+
funcs->free((char *)p + 10);
|
| 156 |
+
/* funcs->free(real); */
|
| 157 |
+
}
|
| 158 |
+
else {
|
| 159 |
+
npy_uintp i = (npy_uintp)atoi(real +20);
|
| 160 |
+
if (i != sz) {
|
| 161 |
+
fprintf(stderr, "uh-oh, unmatched shift_free"
|
| 162 |
+
"(ptr, %ld) but allocated %ld\\n", sz, i);
|
| 163 |
+
/* This happens in some places, only print */
|
| 164 |
+
funcs->free(real);
|
| 165 |
+
}
|
| 166 |
+
else {
|
| 167 |
+
funcs->free(real);
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
NPY_NO_EXPORT void *
|
| 172 |
+
shift_realloc(void *ctx, void * p, npy_uintp sz) {
|
| 173 |
+
SecretDataAllocatorFuncs *funcs = (SecretDataAllocatorFuncs *)ctx;
|
| 174 |
+
if (p != NULL) {
|
| 175 |
+
char *real = (char *)p - 64;
|
| 176 |
+
if (strncmp(real, "originally allocated", 20) != 0) {
|
| 177 |
+
fprintf(stdout, "uh-oh, unmatched shift_realloc\\n");
|
| 178 |
+
return realloc(p, sz);
|
| 179 |
+
}
|
| 180 |
+
return (void *)((char *)funcs->realloc(real, sz + 64) + 64);
|
| 181 |
+
}
|
| 182 |
+
else {
|
| 183 |
+
char *real = (char *)funcs->realloc(p, sz + 64);
|
| 184 |
+
if (real == NULL) {
|
| 185 |
+
return NULL;
|
| 186 |
+
}
|
| 187 |
+
snprintf(real, 64, "originally allocated "
|
| 188 |
+
"%ld via realloc", (unsigned long)sz);
|
| 189 |
+
return (void *)(real + 64);
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
/* As an example, we use the standard {m|c|re}alloc/free funcs. */
|
| 193 |
+
static SecretDataAllocatorFuncs secret_data_handler_ctx = {
|
| 194 |
+
malloc,
|
| 195 |
+
calloc,
|
| 196 |
+
realloc,
|
| 197 |
+
free
|
| 198 |
+
};
|
| 199 |
+
static PyDataMem_Handler secret_data_handler = {
|
| 200 |
+
"secret_data_allocator",
|
| 201 |
+
1,
|
| 202 |
+
{
|
| 203 |
+
&secret_data_handler_ctx, /* ctx */
|
| 204 |
+
shift_alloc, /* malloc */
|
| 205 |
+
shift_zero, /* calloc */
|
| 206 |
+
shift_realloc, /* realloc */
|
| 207 |
+
shift_free /* free */
|
| 208 |
+
}
|
| 209 |
+
};
|
| 210 |
+
void warn_on_free(void *capsule) {
|
| 211 |
+
PyErr_WarnEx(PyExc_UserWarning, "in warn_on_free", 1);
|
| 212 |
+
void * obj = PyCapsule_GetPointer(capsule,
|
| 213 |
+
PyCapsule_GetName(capsule));
|
| 214 |
+
free(obj);
|
| 215 |
+
};
|
| 216 |
+
'''
|
| 217 |
+
more_init = "import_array();"
|
| 218 |
+
try:
|
| 219 |
+
import mem_policy
|
| 220 |
+
return mem_policy
|
| 221 |
+
except ImportError:
|
| 222 |
+
pass
|
| 223 |
+
# if it does not exist, build and load it
|
| 224 |
+
return extbuild.build_and_import_extension('mem_policy',
|
| 225 |
+
functions,
|
| 226 |
+
prologue=prologue,
|
| 227 |
+
include_dirs=[np.get_include()],
|
| 228 |
+
build_dir=tmp_path,
|
| 229 |
+
more_init=more_init)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def test_set_policy(get_module):
|
| 233 |
+
|
| 234 |
+
get_handler_name = np._core.multiarray.get_handler_name
|
| 235 |
+
get_handler_version = np._core.multiarray.get_handler_version
|
| 236 |
+
orig_policy_name = get_handler_name()
|
| 237 |
+
|
| 238 |
+
a = np.arange(10).reshape((2, 5)) # a doesn't own its own data
|
| 239 |
+
assert get_handler_name(a) is None
|
| 240 |
+
assert get_handler_version(a) is None
|
| 241 |
+
assert get_handler_name(a.base) == orig_policy_name
|
| 242 |
+
assert get_handler_version(a.base) == 1
|
| 243 |
+
|
| 244 |
+
orig_policy = get_module.set_secret_data_policy()
|
| 245 |
+
|
| 246 |
+
b = np.arange(10).reshape((2, 5)) # b doesn't own its own data
|
| 247 |
+
assert get_handler_name(b) is None
|
| 248 |
+
assert get_handler_version(b) is None
|
| 249 |
+
assert get_handler_name(b.base) == 'secret_data_allocator'
|
| 250 |
+
assert get_handler_version(b.base) == 1
|
| 251 |
+
|
| 252 |
+
if orig_policy_name == 'default_allocator':
|
| 253 |
+
get_module.set_old_policy(None) # tests PyDataMem_SetHandler(NULL)
|
| 254 |
+
assert get_handler_name() == 'default_allocator'
|
| 255 |
+
else:
|
| 256 |
+
get_module.set_old_policy(orig_policy)
|
| 257 |
+
assert get_handler_name() == orig_policy_name
|
| 258 |
+
|
| 259 |
+
with pytest.raises(ValueError,
|
| 260 |
+
match="Capsule must be named 'mem_handler'"):
|
| 261 |
+
get_module.set_wrong_capsule_name_data_policy()
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def test_default_policy_singleton(get_module):
|
| 265 |
+
get_handler_name = np._core.multiarray.get_handler_name
|
| 266 |
+
|
| 267 |
+
# set the policy to default
|
| 268 |
+
orig_policy = get_module.set_old_policy(None)
|
| 269 |
+
|
| 270 |
+
assert get_handler_name() == 'default_allocator'
|
| 271 |
+
|
| 272 |
+
# re-set the policy to default
|
| 273 |
+
def_policy_1 = get_module.set_old_policy(None)
|
| 274 |
+
|
| 275 |
+
assert get_handler_name() == 'default_allocator'
|
| 276 |
+
|
| 277 |
+
# set the policy to original
|
| 278 |
+
def_policy_2 = get_module.set_old_policy(orig_policy)
|
| 279 |
+
|
| 280 |
+
# since default policy is a singleton,
|
| 281 |
+
# these should be the same object
|
| 282 |
+
assert def_policy_1 is def_policy_2 is get_module.get_default_policy()
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def test_policy_propagation(get_module):
|
| 286 |
+
# The memory policy goes hand-in-hand with flags.owndata
|
| 287 |
+
|
| 288 |
+
class MyArr(np.ndarray):
|
| 289 |
+
pass
|
| 290 |
+
|
| 291 |
+
get_handler_name = np._core.multiarray.get_handler_name
|
| 292 |
+
orig_policy_name = get_handler_name()
|
| 293 |
+
a = np.arange(10).view(MyArr).reshape((2, 5))
|
| 294 |
+
assert get_handler_name(a) is None
|
| 295 |
+
assert a.flags.owndata is False
|
| 296 |
+
|
| 297 |
+
assert get_handler_name(a.base) is None
|
| 298 |
+
assert a.base.flags.owndata is False
|
| 299 |
+
|
| 300 |
+
assert get_handler_name(a.base.base) == orig_policy_name
|
| 301 |
+
assert a.base.base.flags.owndata is True
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
async def concurrent_context1(get_module, orig_policy_name, event):
|
| 305 |
+
if orig_policy_name == 'default_allocator':
|
| 306 |
+
get_module.set_secret_data_policy()
|
| 307 |
+
assert get_handler_name() == 'secret_data_allocator'
|
| 308 |
+
else:
|
| 309 |
+
get_module.set_old_policy(None)
|
| 310 |
+
assert get_handler_name() == 'default_allocator'
|
| 311 |
+
event.set()
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
async def concurrent_context2(get_module, orig_policy_name, event):
|
| 315 |
+
await event.wait()
|
| 316 |
+
# the policy is not affected by changes in parallel contexts
|
| 317 |
+
assert get_handler_name() == orig_policy_name
|
| 318 |
+
# change policy in the child context
|
| 319 |
+
if orig_policy_name == 'default_allocator':
|
| 320 |
+
get_module.set_secret_data_policy()
|
| 321 |
+
assert get_handler_name() == 'secret_data_allocator'
|
| 322 |
+
else:
|
| 323 |
+
get_module.set_old_policy(None)
|
| 324 |
+
assert get_handler_name() == 'default_allocator'
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
async def async_test_context_locality(get_module):
|
| 328 |
+
orig_policy_name = np._core.multiarray.get_handler_name()
|
| 329 |
+
|
| 330 |
+
event = asyncio.Event()
|
| 331 |
+
# the child contexts inherit the parent policy
|
| 332 |
+
concurrent_task1 = asyncio.create_task(
|
| 333 |
+
concurrent_context1(get_module, orig_policy_name, event))
|
| 334 |
+
concurrent_task2 = asyncio.create_task(
|
| 335 |
+
concurrent_context2(get_module, orig_policy_name, event))
|
| 336 |
+
await concurrent_task1
|
| 337 |
+
await concurrent_task2
|
| 338 |
+
|
| 339 |
+
# the parent context is not affected by child policy changes
|
| 340 |
+
assert np._core.multiarray.get_handler_name() == orig_policy_name
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def test_context_locality(get_module):
|
| 344 |
+
if (sys.implementation.name == 'pypy'
|
| 345 |
+
and sys.pypy_version_info[:3] < (7, 3, 6)):
|
| 346 |
+
pytest.skip('no context-locality support in PyPy < 7.3.6')
|
| 347 |
+
asyncio.run(async_test_context_locality(get_module))
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def concurrent_thread1(get_module, event):
|
| 351 |
+
get_module.set_secret_data_policy()
|
| 352 |
+
assert np._core.multiarray.get_handler_name() == 'secret_data_allocator'
|
| 353 |
+
event.set()
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def concurrent_thread2(get_module, event):
|
| 357 |
+
event.wait()
|
| 358 |
+
# the policy is not affected by changes in parallel threads
|
| 359 |
+
assert np._core.multiarray.get_handler_name() == 'default_allocator'
|
| 360 |
+
# change policy in the child thread
|
| 361 |
+
get_module.set_secret_data_policy()
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def test_thread_locality(get_module):
|
| 365 |
+
orig_policy_name = np._core.multiarray.get_handler_name()
|
| 366 |
+
|
| 367 |
+
event = threading.Event()
|
| 368 |
+
# the child threads do not inherit the parent policy
|
| 369 |
+
concurrent_task1 = threading.Thread(target=concurrent_thread1,
|
| 370 |
+
args=(get_module, event))
|
| 371 |
+
concurrent_task2 = threading.Thread(target=concurrent_thread2,
|
| 372 |
+
args=(get_module, event))
|
| 373 |
+
concurrent_task1.start()
|
| 374 |
+
concurrent_task2.start()
|
| 375 |
+
concurrent_task1.join()
|
| 376 |
+
concurrent_task2.join()
|
| 377 |
+
|
| 378 |
+
# the parent thread is not affected by child policy changes
|
| 379 |
+
assert np._core.multiarray.get_handler_name() == orig_policy_name
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
@pytest.mark.skip(reason="too slow, see gh-23975")
|
| 383 |
+
def test_new_policy(get_module):
|
| 384 |
+
a = np.arange(10)
|
| 385 |
+
orig_policy_name = np._core.multiarray.get_handler_name(a)
|
| 386 |
+
|
| 387 |
+
orig_policy = get_module.set_secret_data_policy()
|
| 388 |
+
|
| 389 |
+
b = np.arange(10)
|
| 390 |
+
assert np._core.multiarray.get_handler_name(b) == 'secret_data_allocator'
|
| 391 |
+
|
| 392 |
+
# test array manipulation. This is slow
|
| 393 |
+
if orig_policy_name == 'default_allocator':
|
| 394 |
+
# when the np._core.test tests recurse into this test, the
|
| 395 |
+
# policy will be set so this "if" will be false, preventing
|
| 396 |
+
# infinite recursion
|
| 397 |
+
#
|
| 398 |
+
# if needed, debug this by
|
| 399 |
+
# - running tests with -- -s (to not capture stdout/stderr
|
| 400 |
+
# - setting verbose=2
|
| 401 |
+
# - setting extra_argv=['-vv'] here
|
| 402 |
+
assert np._core.test('full', verbose=1, extra_argv=[])
|
| 403 |
+
# also try the ma tests, the pickling test is quite tricky
|
| 404 |
+
assert np.ma.test('full', verbose=1, extra_argv=[])
|
| 405 |
+
|
| 406 |
+
get_module.set_old_policy(orig_policy)
|
| 407 |
+
|
| 408 |
+
c = np.arange(10)
|
| 409 |
+
assert np._core.multiarray.get_handler_name(c) == orig_policy_name
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
@pytest.mark.xfail(sys.implementation.name == "pypy",
|
| 413 |
+
reason=("bad interaction between getenv and "
|
| 414 |
+
"os.environ inside pytest"))
|
| 415 |
+
@pytest.mark.parametrize("policy", ["0", "1", None])
|
| 416 |
+
def test_switch_owner(get_module, policy):
|
| 417 |
+
a = get_module.get_array()
|
| 418 |
+
assert np._core.multiarray.get_handler_name(a) is None
|
| 419 |
+
get_module.set_own(a)
|
| 420 |
+
|
| 421 |
+
if policy is None:
|
| 422 |
+
# See what we expect to be set based on the env variable
|
| 423 |
+
policy = os.getenv("NUMPY_WARN_IF_NO_MEM_POLICY", "0") == "1"
|
| 424 |
+
oldval = None
|
| 425 |
+
else:
|
| 426 |
+
policy = policy == "1"
|
| 427 |
+
oldval = np._core._multiarray_umath._set_numpy_warn_if_no_mem_policy(
|
| 428 |
+
policy)
|
| 429 |
+
try:
|
| 430 |
+
# The policy should be NULL, so we have to assume we can call
|
| 431 |
+
# "free". A warning is given if the policy == "1"
|
| 432 |
+
if policy:
|
| 433 |
+
with assert_warns(RuntimeWarning) as w:
|
| 434 |
+
del a
|
| 435 |
+
gc.collect()
|
| 436 |
+
else:
|
| 437 |
+
del a
|
| 438 |
+
gc.collect()
|
| 439 |
+
|
| 440 |
+
finally:
|
| 441 |
+
if oldval is not None:
|
| 442 |
+
np._core._multiarray_umath._set_numpy_warn_if_no_mem_policy(oldval)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def test_owner_is_base(get_module):
|
| 446 |
+
a = get_module.get_array_with_base()
|
| 447 |
+
with pytest.warns(UserWarning, match='warn_on_free'):
|
| 448 |
+
del a
|
| 449 |
+
gc.collect()
|
| 450 |
+
gc.collect()
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/test_overrides.py
ADDED
|
@@ -0,0 +1,739 @@
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import sys
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
from io import StringIO
|
| 6 |
+
from unittest import mock
|
| 7 |
+
import pickle
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from numpy.testing import (
|
| 13 |
+
assert_, assert_equal, assert_raises, assert_raises_regex)
|
| 14 |
+
from numpy._core.overrides import (
|
| 15 |
+
_get_implementing_args, array_function_dispatch,
|
| 16 |
+
verify_matching_signatures)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _return_not_implemented(self, *args, **kwargs):
|
| 20 |
+
return NotImplemented
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# need to define this at the top level to test pickling
|
| 24 |
+
@array_function_dispatch(lambda array: (array,))
|
| 25 |
+
def dispatched_one_arg(array):
|
| 26 |
+
"""Docstring."""
|
| 27 |
+
return 'original'
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@array_function_dispatch(lambda array1, array2: (array1, array2))
|
| 31 |
+
def dispatched_two_arg(array1, array2):
|
| 32 |
+
"""Docstring."""
|
| 33 |
+
return 'original'
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TestGetImplementingArgs:
|
| 37 |
+
|
| 38 |
+
def test_ndarray(self):
|
| 39 |
+
array = np.array(1)
|
| 40 |
+
|
| 41 |
+
args = _get_implementing_args([array])
|
| 42 |
+
assert_equal(list(args), [array])
|
| 43 |
+
|
| 44 |
+
args = _get_implementing_args([array, array])
|
| 45 |
+
assert_equal(list(args), [array])
|
| 46 |
+
|
| 47 |
+
args = _get_implementing_args([array, 1])
|
| 48 |
+
assert_equal(list(args), [array])
|
| 49 |
+
|
| 50 |
+
args = _get_implementing_args([1, array])
|
| 51 |
+
assert_equal(list(args), [array])
|
| 52 |
+
|
| 53 |
+
def test_ndarray_subclasses(self):
|
| 54 |
+
|
| 55 |
+
class OverrideSub(np.ndarray):
|
| 56 |
+
__array_function__ = _return_not_implemented
|
| 57 |
+
|
| 58 |
+
class NoOverrideSub(np.ndarray):
|
| 59 |
+
pass
|
| 60 |
+
|
| 61 |
+
array = np.array(1).view(np.ndarray)
|
| 62 |
+
override_sub = np.array(1).view(OverrideSub)
|
| 63 |
+
no_override_sub = np.array(1).view(NoOverrideSub)
|
| 64 |
+
|
| 65 |
+
args = _get_implementing_args([array, override_sub])
|
| 66 |
+
assert_equal(list(args), [override_sub, array])
|
| 67 |
+
|
| 68 |
+
args = _get_implementing_args([array, no_override_sub])
|
| 69 |
+
assert_equal(list(args), [no_override_sub, array])
|
| 70 |
+
|
| 71 |
+
args = _get_implementing_args(
|
| 72 |
+
[override_sub, no_override_sub])
|
| 73 |
+
assert_equal(list(args), [override_sub, no_override_sub])
|
| 74 |
+
|
| 75 |
+
def test_ndarray_and_duck_array(self):
|
| 76 |
+
|
| 77 |
+
class Other:
|
| 78 |
+
__array_function__ = _return_not_implemented
|
| 79 |
+
|
| 80 |
+
array = np.array(1)
|
| 81 |
+
other = Other()
|
| 82 |
+
|
| 83 |
+
args = _get_implementing_args([other, array])
|
| 84 |
+
assert_equal(list(args), [other, array])
|
| 85 |
+
|
| 86 |
+
args = _get_implementing_args([array, other])
|
| 87 |
+
assert_equal(list(args), [array, other])
|
| 88 |
+
|
| 89 |
+
def test_ndarray_subclass_and_duck_array(self):
|
| 90 |
+
|
| 91 |
+
class OverrideSub(np.ndarray):
|
| 92 |
+
__array_function__ = _return_not_implemented
|
| 93 |
+
|
| 94 |
+
class Other:
|
| 95 |
+
__array_function__ = _return_not_implemented
|
| 96 |
+
|
| 97 |
+
array = np.array(1)
|
| 98 |
+
subarray = np.array(1).view(OverrideSub)
|
| 99 |
+
other = Other()
|
| 100 |
+
|
| 101 |
+
assert_equal(_get_implementing_args([array, subarray, other]),
|
| 102 |
+
[subarray, array, other])
|
| 103 |
+
assert_equal(_get_implementing_args([array, other, subarray]),
|
| 104 |
+
[subarray, array, other])
|
| 105 |
+
|
| 106 |
+
def test_many_duck_arrays(self):
|
| 107 |
+
|
| 108 |
+
class A:
|
| 109 |
+
__array_function__ = _return_not_implemented
|
| 110 |
+
|
| 111 |
+
class B(A):
|
| 112 |
+
__array_function__ = _return_not_implemented
|
| 113 |
+
|
| 114 |
+
class C(A):
|
| 115 |
+
__array_function__ = _return_not_implemented
|
| 116 |
+
|
| 117 |
+
class D:
|
| 118 |
+
__array_function__ = _return_not_implemented
|
| 119 |
+
|
| 120 |
+
a = A()
|
| 121 |
+
b = B()
|
| 122 |
+
c = C()
|
| 123 |
+
d = D()
|
| 124 |
+
|
| 125 |
+
assert_equal(_get_implementing_args([1]), [])
|
| 126 |
+
assert_equal(_get_implementing_args([a]), [a])
|
| 127 |
+
assert_equal(_get_implementing_args([a, 1]), [a])
|
| 128 |
+
assert_equal(_get_implementing_args([a, a, a]), [a])
|
| 129 |
+
assert_equal(_get_implementing_args([a, d, a]), [a, d])
|
| 130 |
+
assert_equal(_get_implementing_args([a, b]), [b, a])
|
| 131 |
+
assert_equal(_get_implementing_args([b, a]), [b, a])
|
| 132 |
+
assert_equal(_get_implementing_args([a, b, c]), [b, c, a])
|
| 133 |
+
assert_equal(_get_implementing_args([a, c, b]), [c, b, a])
|
| 134 |
+
|
| 135 |
+
def test_too_many_duck_arrays(self):
|
| 136 |
+
namespace = dict(__array_function__=_return_not_implemented)
|
| 137 |
+
types = [type('A' + str(i), (object,), namespace) for i in range(65)]
|
| 138 |
+
relevant_args = [t() for t in types]
|
| 139 |
+
|
| 140 |
+
actual = _get_implementing_args(relevant_args[:64])
|
| 141 |
+
assert_equal(actual, relevant_args[:64])
|
| 142 |
+
|
| 143 |
+
with assert_raises_regex(TypeError, 'distinct argument types'):
|
| 144 |
+
_get_implementing_args(relevant_args)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class TestNDArrayArrayFunction:
|
| 148 |
+
|
| 149 |
+
def test_method(self):
|
| 150 |
+
|
| 151 |
+
class Other:
|
| 152 |
+
__array_function__ = _return_not_implemented
|
| 153 |
+
|
| 154 |
+
class NoOverrideSub(np.ndarray):
|
| 155 |
+
pass
|
| 156 |
+
|
| 157 |
+
class OverrideSub(np.ndarray):
|
| 158 |
+
__array_function__ = _return_not_implemented
|
| 159 |
+
|
| 160 |
+
array = np.array([1])
|
| 161 |
+
other = Other()
|
| 162 |
+
no_override_sub = array.view(NoOverrideSub)
|
| 163 |
+
override_sub = array.view(OverrideSub)
|
| 164 |
+
|
| 165 |
+
result = array.__array_function__(func=dispatched_two_arg,
|
| 166 |
+
types=(np.ndarray,),
|
| 167 |
+
args=(array, 1.), kwargs={})
|
| 168 |
+
assert_equal(result, 'original')
|
| 169 |
+
|
| 170 |
+
result = array.__array_function__(func=dispatched_two_arg,
|
| 171 |
+
types=(np.ndarray, Other),
|
| 172 |
+
args=(array, other), kwargs={})
|
| 173 |
+
assert_(result is NotImplemented)
|
| 174 |
+
|
| 175 |
+
result = array.__array_function__(func=dispatched_two_arg,
|
| 176 |
+
types=(np.ndarray, NoOverrideSub),
|
| 177 |
+
args=(array, no_override_sub),
|
| 178 |
+
kwargs={})
|
| 179 |
+
assert_equal(result, 'original')
|
| 180 |
+
|
| 181 |
+
result = array.__array_function__(func=dispatched_two_arg,
|
| 182 |
+
types=(np.ndarray, OverrideSub),
|
| 183 |
+
args=(array, override_sub),
|
| 184 |
+
kwargs={})
|
| 185 |
+
assert_equal(result, 'original')
|
| 186 |
+
|
| 187 |
+
with assert_raises_regex(TypeError, 'no implementation found'):
|
| 188 |
+
np.concatenate((array, other))
|
| 189 |
+
|
| 190 |
+
expected = np.concatenate((array, array))
|
| 191 |
+
result = np.concatenate((array, no_override_sub))
|
| 192 |
+
assert_equal(result, expected.view(NoOverrideSub))
|
| 193 |
+
result = np.concatenate((array, override_sub))
|
| 194 |
+
assert_equal(result, expected.view(OverrideSub))
|
| 195 |
+
|
| 196 |
+
def test_no_wrapper(self):
|
| 197 |
+
# This shouldn't happen unless a user intentionally calls
|
| 198 |
+
# __array_function__ with invalid arguments, but check that we raise
|
| 199 |
+
# an appropriate error all the same.
|
| 200 |
+
array = np.array(1)
|
| 201 |
+
func = lambda x: x
|
| 202 |
+
with assert_raises_regex(AttributeError, '_implementation'):
|
| 203 |
+
array.__array_function__(func=func, types=(np.ndarray,),
|
| 204 |
+
args=(array,), kwargs={})
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class TestArrayFunctionDispatch:
|
| 208 |
+
|
| 209 |
+
def test_pickle(self):
|
| 210 |
+
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
|
| 211 |
+
roundtripped = pickle.loads(
|
| 212 |
+
pickle.dumps(dispatched_one_arg, protocol=proto))
|
| 213 |
+
assert_(roundtripped is dispatched_one_arg)
|
| 214 |
+
|
| 215 |
+
def test_name_and_docstring(self):
|
| 216 |
+
assert_equal(dispatched_one_arg.__name__, 'dispatched_one_arg')
|
| 217 |
+
if sys.flags.optimize < 2:
|
| 218 |
+
assert_equal(dispatched_one_arg.__doc__, 'Docstring.')
|
| 219 |
+
|
| 220 |
+
def test_interface(self):
|
| 221 |
+
|
| 222 |
+
class MyArray:
|
| 223 |
+
def __array_function__(self, func, types, args, kwargs):
|
| 224 |
+
return (self, func, types, args, kwargs)
|
| 225 |
+
|
| 226 |
+
original = MyArray()
|
| 227 |
+
(obj, func, types, args, kwargs) = dispatched_one_arg(original)
|
| 228 |
+
assert_(obj is original)
|
| 229 |
+
assert_(func is dispatched_one_arg)
|
| 230 |
+
assert_equal(set(types), {MyArray})
|
| 231 |
+
# assert_equal uses the overloaded np.iscomplexobj() internally
|
| 232 |
+
assert_(args == (original,))
|
| 233 |
+
assert_equal(kwargs, {})
|
| 234 |
+
|
| 235 |
+
def test_not_implemented(self):
|
| 236 |
+
|
| 237 |
+
class MyArray:
|
| 238 |
+
def __array_function__(self, func, types, args, kwargs):
|
| 239 |
+
return NotImplemented
|
| 240 |
+
|
| 241 |
+
array = MyArray()
|
| 242 |
+
with assert_raises_regex(TypeError, 'no implementation found'):
|
| 243 |
+
dispatched_one_arg(array)
|
| 244 |
+
|
| 245 |
+
def test_where_dispatch(self):
|
| 246 |
+
|
| 247 |
+
class DuckArray:
|
| 248 |
+
def __array_function__(self, ufunc, method, *inputs, **kwargs):
|
| 249 |
+
return "overridden"
|
| 250 |
+
|
| 251 |
+
array = np.array(1)
|
| 252 |
+
duck_array = DuckArray()
|
| 253 |
+
|
| 254 |
+
result = np.std(array, where=duck_array)
|
| 255 |
+
|
| 256 |
+
assert_equal(result, "overridden")
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class TestVerifyMatchingSignatures:
|
| 260 |
+
|
| 261 |
+
def test_verify_matching_signatures(self):
|
| 262 |
+
|
| 263 |
+
verify_matching_signatures(lambda x: 0, lambda x: 0)
|
| 264 |
+
verify_matching_signatures(lambda x=None: 0, lambda x=None: 0)
|
| 265 |
+
verify_matching_signatures(lambda x=1: 0, lambda x=None: 0)
|
| 266 |
+
|
| 267 |
+
with assert_raises(RuntimeError):
|
| 268 |
+
verify_matching_signatures(lambda a: 0, lambda b: 0)
|
| 269 |
+
with assert_raises(RuntimeError):
|
| 270 |
+
verify_matching_signatures(lambda x: 0, lambda x=None: 0)
|
| 271 |
+
with assert_raises(RuntimeError):
|
| 272 |
+
verify_matching_signatures(lambda x=None: 0, lambda y=None: 0)
|
| 273 |
+
with assert_raises(RuntimeError):
|
| 274 |
+
verify_matching_signatures(lambda x=1: 0, lambda y=1: 0)
|
| 275 |
+
|
| 276 |
+
def test_array_function_dispatch(self):
|
| 277 |
+
|
| 278 |
+
with assert_raises(RuntimeError):
|
| 279 |
+
@array_function_dispatch(lambda x: (x,))
|
| 280 |
+
def f(y):
|
| 281 |
+
pass
|
| 282 |
+
|
| 283 |
+
# should not raise
|
| 284 |
+
@array_function_dispatch(lambda x: (x,), verify=False)
|
| 285 |
+
def f(y):
|
| 286 |
+
pass
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def _new_duck_type_and_implements():
|
| 290 |
+
"""Create a duck array type and implements functions."""
|
| 291 |
+
HANDLED_FUNCTIONS = {}
|
| 292 |
+
|
| 293 |
+
class MyArray:
|
| 294 |
+
def __array_function__(self, func, types, args, kwargs):
|
| 295 |
+
if func not in HANDLED_FUNCTIONS:
|
| 296 |
+
return NotImplemented
|
| 297 |
+
if not all(issubclass(t, MyArray) for t in types):
|
| 298 |
+
return NotImplemented
|
| 299 |
+
return HANDLED_FUNCTIONS[func](*args, **kwargs)
|
| 300 |
+
|
| 301 |
+
def implements(numpy_function):
|
| 302 |
+
"""Register an __array_function__ implementations."""
|
| 303 |
+
def decorator(func):
|
| 304 |
+
HANDLED_FUNCTIONS[numpy_function] = func
|
| 305 |
+
return func
|
| 306 |
+
return decorator
|
| 307 |
+
|
| 308 |
+
return (MyArray, implements)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class TestArrayFunctionImplementation:
|
| 312 |
+
|
| 313 |
+
def test_one_arg(self):
|
| 314 |
+
MyArray, implements = _new_duck_type_and_implements()
|
| 315 |
+
|
| 316 |
+
@implements(dispatched_one_arg)
|
| 317 |
+
def _(array):
|
| 318 |
+
return 'myarray'
|
| 319 |
+
|
| 320 |
+
assert_equal(dispatched_one_arg(1), 'original')
|
| 321 |
+
assert_equal(dispatched_one_arg(MyArray()), 'myarray')
|
| 322 |
+
|
| 323 |
+
def test_optional_args(self):
|
| 324 |
+
MyArray, implements = _new_duck_type_and_implements()
|
| 325 |
+
|
| 326 |
+
@array_function_dispatch(lambda array, option=None: (array,))
|
| 327 |
+
def func_with_option(array, option='default'):
|
| 328 |
+
return option
|
| 329 |
+
|
| 330 |
+
@implements(func_with_option)
|
| 331 |
+
def my_array_func_with_option(array, new_option='myarray'):
|
| 332 |
+
return new_option
|
| 333 |
+
|
| 334 |
+
# we don't need to implement every option on __array_function__
|
| 335 |
+
# implementations
|
| 336 |
+
assert_equal(func_with_option(1), 'default')
|
| 337 |
+
assert_equal(func_with_option(1, option='extra'), 'extra')
|
| 338 |
+
assert_equal(func_with_option(MyArray()), 'myarray')
|
| 339 |
+
with assert_raises(TypeError):
|
| 340 |
+
func_with_option(MyArray(), option='extra')
|
| 341 |
+
|
| 342 |
+
# but new options on implementations can't be used
|
| 343 |
+
result = my_array_func_with_option(MyArray(), new_option='yes')
|
| 344 |
+
assert_equal(result, 'yes')
|
| 345 |
+
with assert_raises(TypeError):
|
| 346 |
+
func_with_option(MyArray(), new_option='no')
|
| 347 |
+
|
| 348 |
+
def test_not_implemented(self):
|
| 349 |
+
MyArray, implements = _new_duck_type_and_implements()
|
| 350 |
+
|
| 351 |
+
@array_function_dispatch(lambda array: (array,), module='my')
|
| 352 |
+
def func(array):
|
| 353 |
+
return array
|
| 354 |
+
|
| 355 |
+
array = np.array(1)
|
| 356 |
+
assert_(func(array) is array)
|
| 357 |
+
assert_equal(func.__module__, 'my')
|
| 358 |
+
|
| 359 |
+
with assert_raises_regex(
|
| 360 |
+
TypeError, "no implementation found for 'my.func'"):
|
| 361 |
+
func(MyArray())
|
| 362 |
+
|
| 363 |
+
@pytest.mark.parametrize("name", ["concatenate", "mean", "asarray"])
|
| 364 |
+
def test_signature_error_message_simple(self, name):
|
| 365 |
+
func = getattr(np, name)
|
| 366 |
+
try:
|
| 367 |
+
# all of these functions need an argument:
|
| 368 |
+
func()
|
| 369 |
+
except TypeError as e:
|
| 370 |
+
exc = e
|
| 371 |
+
|
| 372 |
+
assert exc.args[0].startswith(f"{name}()")
|
| 373 |
+
|
| 374 |
+
def test_signature_error_message(self):
|
| 375 |
+
# The lambda function will be named "<lambda>", but the TypeError
|
| 376 |
+
# should show the name as "func"
|
| 377 |
+
def _dispatcher():
|
| 378 |
+
return ()
|
| 379 |
+
|
| 380 |
+
@array_function_dispatch(_dispatcher)
|
| 381 |
+
def func():
|
| 382 |
+
pass
|
| 383 |
+
|
| 384 |
+
try:
|
| 385 |
+
func._implementation(bad_arg=3)
|
| 386 |
+
except TypeError as e:
|
| 387 |
+
expected_exception = e
|
| 388 |
+
|
| 389 |
+
try:
|
| 390 |
+
func(bad_arg=3)
|
| 391 |
+
raise AssertionError("must fail")
|
| 392 |
+
except TypeError as exc:
|
| 393 |
+
if exc.args[0].startswith("_dispatcher"):
|
| 394 |
+
# We replace the qualname currently, but it used `__name__`
|
| 395 |
+
# (relevant functions have the same name and qualname anyway)
|
| 396 |
+
pytest.skip("Python version is not using __qualname__ for "
|
| 397 |
+
"TypeError formatting.")
|
| 398 |
+
|
| 399 |
+
assert exc.args == expected_exception.args
|
| 400 |
+
|
| 401 |
+
@pytest.mark.parametrize("value", [234, "this func is not replaced"])
|
| 402 |
+
def test_dispatcher_error(self, value):
|
| 403 |
+
# If the dispatcher raises an error, we must not attempt to mutate it
|
| 404 |
+
error = TypeError(value)
|
| 405 |
+
|
| 406 |
+
def dispatcher():
|
| 407 |
+
raise error
|
| 408 |
+
|
| 409 |
+
@array_function_dispatch(dispatcher)
|
| 410 |
+
def func():
|
| 411 |
+
return 3
|
| 412 |
+
|
| 413 |
+
try:
|
| 414 |
+
func()
|
| 415 |
+
raise AssertionError("must fail")
|
| 416 |
+
except TypeError as exc:
|
| 417 |
+
assert exc is error # unmodified exception
|
| 418 |
+
|
| 419 |
+
def test_properties(self):
|
| 420 |
+
# Check that str and repr are sensible
|
| 421 |
+
func = dispatched_two_arg
|
| 422 |
+
assert str(func) == str(func._implementation)
|
| 423 |
+
repr_no_id = repr(func).split("at ")[0]
|
| 424 |
+
repr_no_id_impl = repr(func._implementation).split("at ")[0]
|
| 425 |
+
assert repr_no_id == repr_no_id_impl
|
| 426 |
+
|
| 427 |
+
@pytest.mark.parametrize("func", [
|
| 428 |
+
lambda x, y: 0, # no like argument
|
| 429 |
+
lambda like=None: 0, # not keyword only
|
| 430 |
+
lambda *, like=None, a=3: 0, # not last (not that it matters)
|
| 431 |
+
])
|
| 432 |
+
def test_bad_like_sig(self, func):
|
| 433 |
+
# We sanity check the signature, and these should fail.
|
| 434 |
+
with pytest.raises(RuntimeError):
|
| 435 |
+
array_function_dispatch()(func)
|
| 436 |
+
|
| 437 |
+
def test_bad_like_passing(self):
|
| 438 |
+
# Cover internal sanity check for passing like as first positional arg
|
| 439 |
+
def func(*, like=None):
|
| 440 |
+
pass
|
| 441 |
+
|
| 442 |
+
func_with_like = array_function_dispatch()(func)
|
| 443 |
+
with pytest.raises(TypeError):
|
| 444 |
+
func_with_like()
|
| 445 |
+
with pytest.raises(TypeError):
|
| 446 |
+
func_with_like(like=234)
|
| 447 |
+
|
| 448 |
+
def test_too_many_args(self):
|
| 449 |
+
# Mainly a unit-test to increase coverage
|
| 450 |
+
objs = []
|
| 451 |
+
for i in range(80):
|
| 452 |
+
class MyArr:
|
| 453 |
+
def __array_function__(self, *args, **kwargs):
|
| 454 |
+
return NotImplemented
|
| 455 |
+
|
| 456 |
+
objs.append(MyArr())
|
| 457 |
+
|
| 458 |
+
def _dispatch(*args):
|
| 459 |
+
return args
|
| 460 |
+
|
| 461 |
+
@array_function_dispatch(_dispatch)
|
| 462 |
+
def func(*args):
|
| 463 |
+
pass
|
| 464 |
+
|
| 465 |
+
with pytest.raises(TypeError, match="maximum number"):
|
| 466 |
+
func(*objs)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
class TestNDArrayMethods:
|
| 471 |
+
|
| 472 |
+
def test_repr(self):
|
| 473 |
+
# gh-12162: should still be defined even if __array_function__ doesn't
|
| 474 |
+
# implement np.array_repr()
|
| 475 |
+
|
| 476 |
+
class MyArray(np.ndarray):
|
| 477 |
+
def __array_function__(*args, **kwargs):
|
| 478 |
+
return NotImplemented
|
| 479 |
+
|
| 480 |
+
array = np.array(1).view(MyArray)
|
| 481 |
+
assert_equal(repr(array), 'MyArray(1)')
|
| 482 |
+
assert_equal(str(array), '1')
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
class TestNumPyFunctions:
|
| 486 |
+
|
| 487 |
+
def test_set_module(self):
|
| 488 |
+
assert_equal(np.sum.__module__, 'numpy')
|
| 489 |
+
assert_equal(np.char.equal.__module__, 'numpy.char')
|
| 490 |
+
assert_equal(np.fft.fft.__module__, 'numpy.fft')
|
| 491 |
+
assert_equal(np.linalg.solve.__module__, 'numpy.linalg')
|
| 492 |
+
|
| 493 |
+
def test_inspect_sum(self):
|
| 494 |
+
signature = inspect.signature(np.sum)
|
| 495 |
+
assert_('axis' in signature.parameters)
|
| 496 |
+
|
| 497 |
+
def test_override_sum(self):
|
| 498 |
+
MyArray, implements = _new_duck_type_and_implements()
|
| 499 |
+
|
| 500 |
+
@implements(np.sum)
|
| 501 |
+
def _(array):
|
| 502 |
+
return 'yes'
|
| 503 |
+
|
| 504 |
+
assert_equal(np.sum(MyArray()), 'yes')
|
| 505 |
+
|
| 506 |
+
def test_sum_on_mock_array(self):
|
| 507 |
+
|
| 508 |
+
# We need a proxy for mocks because __array_function__ is only looked
|
| 509 |
+
# up in the class dict
|
| 510 |
+
class ArrayProxy:
|
| 511 |
+
def __init__(self, value):
|
| 512 |
+
self.value = value
|
| 513 |
+
def __array_function__(self, *args, **kwargs):
|
| 514 |
+
return self.value.__array_function__(*args, **kwargs)
|
| 515 |
+
def __array__(self, *args, **kwargs):
|
| 516 |
+
return self.value.__array__(*args, **kwargs)
|
| 517 |
+
|
| 518 |
+
proxy = ArrayProxy(mock.Mock(spec=ArrayProxy))
|
| 519 |
+
proxy.value.__array_function__.return_value = 1
|
| 520 |
+
result = np.sum(proxy)
|
| 521 |
+
assert_equal(result, 1)
|
| 522 |
+
proxy.value.__array_function__.assert_called_once_with(
|
| 523 |
+
np.sum, (ArrayProxy,), (proxy,), {})
|
| 524 |
+
proxy.value.__array__.assert_not_called()
|
| 525 |
+
|
| 526 |
+
def test_sum_forwarding_implementation(self):
|
| 527 |
+
|
| 528 |
+
class MyArray(np.ndarray):
|
| 529 |
+
|
| 530 |
+
def sum(self, axis, out):
|
| 531 |
+
return 'summed'
|
| 532 |
+
|
| 533 |
+
def __array_function__(self, func, types, args, kwargs):
|
| 534 |
+
return super().__array_function__(func, types, args, kwargs)
|
| 535 |
+
|
| 536 |
+
# note: the internal implementation of np.sum() calls the .sum() method
|
| 537 |
+
array = np.array(1).view(MyArray)
|
| 538 |
+
assert_equal(np.sum(array), 'summed')
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class TestArrayLike:
|
| 542 |
+
def setup_method(self):
|
| 543 |
+
class MyArray:
|
| 544 |
+
def __init__(self, function=None):
|
| 545 |
+
self.function = function
|
| 546 |
+
|
| 547 |
+
def __array_function__(self, func, types, args, kwargs):
|
| 548 |
+
assert func is getattr(np, func.__name__)
|
| 549 |
+
try:
|
| 550 |
+
my_func = getattr(self, func.__name__)
|
| 551 |
+
except AttributeError:
|
| 552 |
+
return NotImplemented
|
| 553 |
+
return my_func(*args, **kwargs)
|
| 554 |
+
|
| 555 |
+
self.MyArray = MyArray
|
| 556 |
+
|
| 557 |
+
class MyNoArrayFunctionArray:
|
| 558 |
+
def __init__(self, function=None):
|
| 559 |
+
self.function = function
|
| 560 |
+
|
| 561 |
+
self.MyNoArrayFunctionArray = MyNoArrayFunctionArray
|
| 562 |
+
|
| 563 |
+
def add_method(self, name, arr_class, enable_value_error=False):
|
| 564 |
+
def _definition(*args, **kwargs):
|
| 565 |
+
# Check that `like=` isn't propagated downstream
|
| 566 |
+
assert 'like' not in kwargs
|
| 567 |
+
|
| 568 |
+
if enable_value_error and 'value_error' in kwargs:
|
| 569 |
+
raise ValueError
|
| 570 |
+
|
| 571 |
+
return arr_class(getattr(arr_class, name))
|
| 572 |
+
setattr(arr_class, name, _definition)
|
| 573 |
+
|
| 574 |
+
def func_args(*args, **kwargs):
|
| 575 |
+
return args, kwargs
|
| 576 |
+
|
| 577 |
+
def test_array_like_not_implemented(self):
|
| 578 |
+
self.add_method('array', self.MyArray)
|
| 579 |
+
|
| 580 |
+
ref = self.MyArray.array()
|
| 581 |
+
|
| 582 |
+
with assert_raises_regex(TypeError, 'no implementation found'):
|
| 583 |
+
array_like = np.asarray(1, like=ref)
|
| 584 |
+
|
| 585 |
+
_array_tests = [
|
| 586 |
+
('array', *func_args((1,))),
|
| 587 |
+
('asarray', *func_args((1,))),
|
| 588 |
+
('asanyarray', *func_args((1,))),
|
| 589 |
+
('ascontiguousarray', *func_args((2, 3))),
|
| 590 |
+
('asfortranarray', *func_args((2, 3))),
|
| 591 |
+
('require', *func_args((np.arange(6).reshape(2, 3),),
|
| 592 |
+
requirements=['A', 'F'])),
|
| 593 |
+
('empty', *func_args((1,))),
|
| 594 |
+
('full', *func_args((1,), 2)),
|
| 595 |
+
('ones', *func_args((1,))),
|
| 596 |
+
('zeros', *func_args((1,))),
|
| 597 |
+
('arange', *func_args(3)),
|
| 598 |
+
('frombuffer', *func_args(b'\x00' * 8, dtype=int)),
|
| 599 |
+
('fromiter', *func_args(range(3), dtype=int)),
|
| 600 |
+
('fromstring', *func_args('1,2', dtype=int, sep=',')),
|
| 601 |
+
('loadtxt', *func_args(lambda: StringIO('0 1\n2 3'))),
|
| 602 |
+
('genfromtxt', *func_args(lambda: StringIO('1,2.1'),
|
| 603 |
+
dtype=[('int', 'i8'), ('float', 'f8')],
|
| 604 |
+
delimiter=',')),
|
| 605 |
+
]
|
| 606 |
+
|
| 607 |
+
@pytest.mark.parametrize('function, args, kwargs', _array_tests)
|
| 608 |
+
@pytest.mark.parametrize('numpy_ref', [True, False])
|
| 609 |
+
def test_array_like(self, function, args, kwargs, numpy_ref):
|
| 610 |
+
self.add_method('array', self.MyArray)
|
| 611 |
+
self.add_method(function, self.MyArray)
|
| 612 |
+
np_func = getattr(np, function)
|
| 613 |
+
my_func = getattr(self.MyArray, function)
|
| 614 |
+
|
| 615 |
+
if numpy_ref is True:
|
| 616 |
+
ref = np.array(1)
|
| 617 |
+
else:
|
| 618 |
+
ref = self.MyArray.array()
|
| 619 |
+
|
| 620 |
+
like_args = tuple(a() if callable(a) else a for a in args)
|
| 621 |
+
array_like = np_func(*like_args, **kwargs, like=ref)
|
| 622 |
+
|
| 623 |
+
if numpy_ref is True:
|
| 624 |
+
assert type(array_like) is np.ndarray
|
| 625 |
+
|
| 626 |
+
np_args = tuple(a() if callable(a) else a for a in args)
|
| 627 |
+
np_arr = np_func(*np_args, **kwargs)
|
| 628 |
+
|
| 629 |
+
# Special-case np.empty to ensure values match
|
| 630 |
+
if function == "empty":
|
| 631 |
+
np_arr.fill(1)
|
| 632 |
+
array_like.fill(1)
|
| 633 |
+
|
| 634 |
+
assert_equal(array_like, np_arr)
|
| 635 |
+
else:
|
| 636 |
+
assert type(array_like) is self.MyArray
|
| 637 |
+
assert array_like.function is my_func
|
| 638 |
+
|
| 639 |
+
@pytest.mark.parametrize('function, args, kwargs', _array_tests)
|
| 640 |
+
@pytest.mark.parametrize('ref', [1, [1], "MyNoArrayFunctionArray"])
|
| 641 |
+
def test_no_array_function_like(self, function, args, kwargs, ref):
|
| 642 |
+
self.add_method('array', self.MyNoArrayFunctionArray)
|
| 643 |
+
self.add_method(function, self.MyNoArrayFunctionArray)
|
| 644 |
+
np_func = getattr(np, function)
|
| 645 |
+
|
| 646 |
+
# Instantiate ref if it's the MyNoArrayFunctionArray class
|
| 647 |
+
if ref == "MyNoArrayFunctionArray":
|
| 648 |
+
ref = self.MyNoArrayFunctionArray.array()
|
| 649 |
+
|
| 650 |
+
like_args = tuple(a() if callable(a) else a for a in args)
|
| 651 |
+
|
| 652 |
+
with assert_raises_regex(TypeError,
|
| 653 |
+
'The `like` argument must be an array-like that implements'):
|
| 654 |
+
np_func(*like_args, **kwargs, like=ref)
|
| 655 |
+
|
| 656 |
+
@pytest.mark.parametrize('numpy_ref', [True, False])
|
| 657 |
+
def test_array_like_fromfile(self, numpy_ref):
|
| 658 |
+
self.add_method('array', self.MyArray)
|
| 659 |
+
self.add_method("fromfile", self.MyArray)
|
| 660 |
+
|
| 661 |
+
if numpy_ref is True:
|
| 662 |
+
ref = np.array(1)
|
| 663 |
+
else:
|
| 664 |
+
ref = self.MyArray.array()
|
| 665 |
+
|
| 666 |
+
data = np.random.random(5)
|
| 667 |
+
|
| 668 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 669 |
+
fname = os.path.join(tmpdir, "testfile")
|
| 670 |
+
data.tofile(fname)
|
| 671 |
+
|
| 672 |
+
array_like = np.fromfile(fname, like=ref)
|
| 673 |
+
if numpy_ref is True:
|
| 674 |
+
assert type(array_like) is np.ndarray
|
| 675 |
+
np_res = np.fromfile(fname, like=ref)
|
| 676 |
+
assert_equal(np_res, data)
|
| 677 |
+
assert_equal(array_like, np_res)
|
| 678 |
+
else:
|
| 679 |
+
assert type(array_like) is self.MyArray
|
| 680 |
+
assert array_like.function is self.MyArray.fromfile
|
| 681 |
+
|
| 682 |
+
def test_exception_handling(self):
|
| 683 |
+
self.add_method('array', self.MyArray, enable_value_error=True)
|
| 684 |
+
|
| 685 |
+
ref = self.MyArray.array()
|
| 686 |
+
|
| 687 |
+
with assert_raises(TypeError):
|
| 688 |
+
# Raises the error about `value_error` being invalid first
|
| 689 |
+
np.array(1, value_error=True, like=ref)
|
| 690 |
+
|
| 691 |
+
@pytest.mark.parametrize('function, args, kwargs', _array_tests)
|
| 692 |
+
def test_like_as_none(self, function, args, kwargs):
|
| 693 |
+
self.add_method('array', self.MyArray)
|
| 694 |
+
self.add_method(function, self.MyArray)
|
| 695 |
+
np_func = getattr(np, function)
|
| 696 |
+
|
| 697 |
+
like_args = tuple(a() if callable(a) else a for a in args)
|
| 698 |
+
# required for loadtxt and genfromtxt to init w/o error.
|
| 699 |
+
like_args_exp = tuple(a() if callable(a) else a for a in args)
|
| 700 |
+
|
| 701 |
+
array_like = np_func(*like_args, **kwargs, like=None)
|
| 702 |
+
expected = np_func(*like_args_exp, **kwargs)
|
| 703 |
+
# Special-case np.empty to ensure values match
|
| 704 |
+
if function == "empty":
|
| 705 |
+
array_like.fill(1)
|
| 706 |
+
expected.fill(1)
|
| 707 |
+
assert_equal(array_like, expected)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def test_function_like():
|
| 711 |
+
# We provide a `__get__` implementation, make sure it works
|
| 712 |
+
assert type(np.mean) is np._core._multiarray_umath._ArrayFunctionDispatcher
|
| 713 |
+
|
| 714 |
+
class MyClass:
|
| 715 |
+
def __array__(self, dtype=None, copy=None):
|
| 716 |
+
# valid argument to mean:
|
| 717 |
+
return np.arange(3)
|
| 718 |
+
|
| 719 |
+
func1 = staticmethod(np.mean)
|
| 720 |
+
func2 = np.mean
|
| 721 |
+
func3 = classmethod(np.mean)
|
| 722 |
+
|
| 723 |
+
m = MyClass()
|
| 724 |
+
assert m.func1([10]) == 10
|
| 725 |
+
assert m.func2() == 1 # mean of the arange
|
| 726 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 727 |
+
# Tries to operate on the class
|
| 728 |
+
m.func3()
|
| 729 |
+
|
| 730 |
+
# Manual binding also works (the above may shortcut):
|
| 731 |
+
bound = np.mean.__get__(m, MyClass)
|
| 732 |
+
assert bound() == 1
|
| 733 |
+
|
| 734 |
+
bound = np.mean.__get__(None, MyClass) # unbound actually
|
| 735 |
+
assert bound([10]) == 10
|
| 736 |
+
|
| 737 |
+
bound = np.mean.__get__(MyClass) # classmethod
|
| 738 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 739 |
+
bound()
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/test_stringdtype.py
ADDED
|
@@ -0,0 +1,1694 @@
|
|
|
|
|
|
|
|
|
|
|
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 7 |
+
import tempfile
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from numpy.dtypes import StringDType
|
| 13 |
+
from numpy._core.tests._natype import pd_NA
|
| 14 |
+
from numpy.testing import assert_array_equal, IS_WASM, IS_PYPY
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture
|
| 18 |
+
def string_list():
|
| 19 |
+
return ["abc", "def", "ghi" * 10, "A¢☃€ 😊" * 100, "Abc" * 1000, "DEF"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@pytest.fixture
|
| 23 |
+
def random_string_list():
|
| 24 |
+
chars = list(string.ascii_letters + string.digits)
|
| 25 |
+
chars = np.array(chars, dtype="U1")
|
| 26 |
+
ret = np.random.choice(chars, size=100 * 10, replace=True)
|
| 27 |
+
return ret.view("U100")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.fixture(params=[True, False])
|
| 31 |
+
def coerce(request):
|
| 32 |
+
return request.param
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.fixture(
|
| 36 |
+
params=["unset", None, pd_NA, np.nan, float("nan"), "__nan__"],
|
| 37 |
+
ids=["unset", "None", "pandas.NA", "np.nan", "float('nan')", "string nan"],
|
| 38 |
+
)
|
| 39 |
+
def na_object(request):
|
| 40 |
+
return request.param
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_dtype(na_object, coerce=True):
|
| 44 |
+
# explicit is check for pd_NA because != with pd_NA returns pd_NA
|
| 45 |
+
if na_object is pd_NA or na_object != "unset":
|
| 46 |
+
return StringDType(na_object=na_object, coerce=coerce)
|
| 47 |
+
else:
|
| 48 |
+
return StringDType(coerce=coerce)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@pytest.fixture()
|
| 52 |
+
def dtype(na_object, coerce):
|
| 53 |
+
return get_dtype(na_object, coerce)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# second copy for cast tests to do a cartesian product over dtypes
|
| 57 |
+
@pytest.fixture(params=[True, False])
|
| 58 |
+
def coerce2(request):
|
| 59 |
+
return request.param
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@pytest.fixture(
|
| 63 |
+
params=["unset", None, pd_NA, np.nan, float("nan"), "__nan__"],
|
| 64 |
+
ids=["unset", "None", "pandas.NA", "np.nan", "float('nan')", "string nan"],
|
| 65 |
+
)
|
| 66 |
+
def na_object2(request):
|
| 67 |
+
return request.param
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@pytest.fixture()
|
| 71 |
+
def dtype2(na_object2, coerce2):
|
| 72 |
+
# explicit is check for pd_NA because != with pd_NA returns pd_NA
|
| 73 |
+
if na_object2 is pd_NA or na_object2 != "unset":
|
| 74 |
+
return StringDType(na_object=na_object2, coerce=coerce2)
|
| 75 |
+
else:
|
| 76 |
+
return StringDType(coerce=coerce2)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_dtype_creation():
|
| 80 |
+
hashes = set()
|
| 81 |
+
dt = StringDType()
|
| 82 |
+
assert not hasattr(dt, "na_object") and dt.coerce is True
|
| 83 |
+
hashes.add(hash(dt))
|
| 84 |
+
|
| 85 |
+
dt = StringDType(na_object=None)
|
| 86 |
+
assert dt.na_object is None and dt.coerce is True
|
| 87 |
+
hashes.add(hash(dt))
|
| 88 |
+
|
| 89 |
+
dt = StringDType(coerce=False)
|
| 90 |
+
assert not hasattr(dt, "na_object") and dt.coerce is False
|
| 91 |
+
hashes.add(hash(dt))
|
| 92 |
+
|
| 93 |
+
dt = StringDType(na_object=None, coerce=False)
|
| 94 |
+
assert dt.na_object is None and dt.coerce is False
|
| 95 |
+
hashes.add(hash(dt))
|
| 96 |
+
|
| 97 |
+
assert len(hashes) == 4
|
| 98 |
+
|
| 99 |
+
dt = np.dtype("T")
|
| 100 |
+
assert dt == StringDType()
|
| 101 |
+
assert dt.kind == "T"
|
| 102 |
+
assert dt.char == "T"
|
| 103 |
+
|
| 104 |
+
hashes.add(hash(dt))
|
| 105 |
+
assert len(hashes) == 4
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_dtype_equality(dtype):
|
| 109 |
+
assert dtype == dtype
|
| 110 |
+
for ch in "SU":
|
| 111 |
+
assert dtype != np.dtype(ch)
|
| 112 |
+
assert dtype != np.dtype(f"{ch}8")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_dtype_repr(dtype):
|
| 116 |
+
if not hasattr(dtype, "na_object") and dtype.coerce:
|
| 117 |
+
assert repr(dtype) == "StringDType()"
|
| 118 |
+
elif dtype.coerce:
|
| 119 |
+
assert repr(dtype) == f"StringDType(na_object={repr(dtype.na_object)})"
|
| 120 |
+
elif not hasattr(dtype, "na_object"):
|
| 121 |
+
assert repr(dtype) == "StringDType(coerce=False)"
|
| 122 |
+
else:
|
| 123 |
+
assert (
|
| 124 |
+
repr(dtype)
|
| 125 |
+
== f"StringDType(na_object={repr(dtype.na_object)}, coerce=False)"
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_create_with_na(dtype):
|
| 130 |
+
if not hasattr(dtype, "na_object"):
|
| 131 |
+
pytest.skip("does not have an na object")
|
| 132 |
+
na_val = dtype.na_object
|
| 133 |
+
string_list = ["hello", na_val, "world"]
|
| 134 |
+
arr = np.array(string_list, dtype=dtype)
|
| 135 |
+
assert str(arr) == "[" + " ".join([repr(s) for s in string_list]) + "]"
|
| 136 |
+
assert arr[1] is dtype.na_object
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@pytest.mark.parametrize("i", list(range(5)))
|
| 140 |
+
def test_set_replace_na(i):
|
| 141 |
+
# Test strings of various lengths can be set to NaN and then replaced.
|
| 142 |
+
s_empty = ""
|
| 143 |
+
s_short = "0123456789"
|
| 144 |
+
s_medium = "abcdefghijklmnopqrstuvwxyz"
|
| 145 |
+
s_long = "-=+" * 100
|
| 146 |
+
strings = [s_medium, s_empty, s_short, s_medium, s_long]
|
| 147 |
+
a = np.array(strings, StringDType(na_object=np.nan))
|
| 148 |
+
for s in [a[i], s_medium+s_short, s_short, s_empty, s_long]:
|
| 149 |
+
a[i] = np.nan
|
| 150 |
+
assert np.isnan(a[i])
|
| 151 |
+
a[i] = s
|
| 152 |
+
assert a[i] == s
|
| 153 |
+
assert_array_equal(a, strings[:i] + [s] + strings[i+1:])
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_null_roundtripping():
|
| 157 |
+
data = ["hello\0world", "ABC\0DEF\0\0"]
|
| 158 |
+
arr = np.array(data, dtype="T")
|
| 159 |
+
assert data[0] == arr[0]
|
| 160 |
+
assert data[1] == arr[1]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def test_string_too_large_error():
|
| 164 |
+
arr = np.array(["a", "b", "c"], dtype=StringDType())
|
| 165 |
+
with pytest.raises(MemoryError):
|
| 166 |
+
arr * (2**63 - 2)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@pytest.mark.parametrize(
|
| 170 |
+
"data",
|
| 171 |
+
[
|
| 172 |
+
["abc", "def", "ghi"],
|
| 173 |
+
["🤣", "📵", "😰"],
|
| 174 |
+
["🚜", "🙃", "😾"],
|
| 175 |
+
["😹", "🚠", "🚌"],
|
| 176 |
+
],
|
| 177 |
+
)
|
| 178 |
+
def test_array_creation_utf8(dtype, data):
|
| 179 |
+
arr = np.array(data, dtype=dtype)
|
| 180 |
+
assert str(arr) == "[" + " ".join(["'" + str(d) + "'" for d in data]) + "]"
|
| 181 |
+
assert arr.dtype == dtype
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@pytest.mark.parametrize(
|
| 185 |
+
"data",
|
| 186 |
+
[
|
| 187 |
+
[1, 2, 3],
|
| 188 |
+
[b"abc", b"def", b"ghi"],
|
| 189 |
+
[object, object, object],
|
| 190 |
+
],
|
| 191 |
+
)
|
| 192 |
+
def test_scalars_string_conversion(data, dtype):
|
| 193 |
+
if dtype.coerce:
|
| 194 |
+
assert_array_equal(
|
| 195 |
+
np.array(data, dtype=dtype),
|
| 196 |
+
np.array([str(d) for d in data], dtype=dtype),
|
| 197 |
+
)
|
| 198 |
+
else:
|
| 199 |
+
with pytest.raises(ValueError):
|
| 200 |
+
np.array(data, dtype=dtype)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@pytest.mark.parametrize(
|
| 204 |
+
("strings"),
|
| 205 |
+
[
|
| 206 |
+
["this", "is", "an", "array"],
|
| 207 |
+
["€", "", "😊"],
|
| 208 |
+
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
|
| 209 |
+
],
|
| 210 |
+
)
|
| 211 |
+
def test_self_casts(dtype, dtype2, strings):
|
| 212 |
+
if hasattr(dtype, "na_object"):
|
| 213 |
+
strings = strings + [dtype.na_object]
|
| 214 |
+
elif hasattr(dtype2, "na_object"):
|
| 215 |
+
strings = strings + [""]
|
| 216 |
+
arr = np.array(strings, dtype=dtype)
|
| 217 |
+
newarr = arr.astype(dtype2)
|
| 218 |
+
|
| 219 |
+
if hasattr(dtype, "na_object") and not hasattr(dtype2, "na_object"):
|
| 220 |
+
assert newarr[-1] == str(dtype.na_object)
|
| 221 |
+
with pytest.raises(TypeError):
|
| 222 |
+
arr.astype(dtype2, casting="safe")
|
| 223 |
+
elif hasattr(dtype, "na_object") and hasattr(dtype2, "na_object"):
|
| 224 |
+
assert newarr[-1] is dtype2.na_object
|
| 225 |
+
arr.astype(dtype2, casting="safe")
|
| 226 |
+
elif hasattr(dtype2, "na_object"):
|
| 227 |
+
assert newarr[-1] == ""
|
| 228 |
+
arr.astype(dtype2, casting="safe")
|
| 229 |
+
else:
|
| 230 |
+
arr.astype(dtype2, casting="safe")
|
| 231 |
+
|
| 232 |
+
if hasattr(dtype, "na_object") and hasattr(dtype2, "na_object"):
|
| 233 |
+
na1 = dtype.na_object
|
| 234 |
+
na2 = dtype2.na_object
|
| 235 |
+
if (na1 is not na2 and
|
| 236 |
+
# check for pd_NA first because bool(pd_NA) is an error
|
| 237 |
+
((na1 is pd_NA or na2 is pd_NA) or
|
| 238 |
+
# the second check is a NaN check, spelled this way
|
| 239 |
+
# to avoid errors from math.isnan and np.isnan
|
| 240 |
+
(na1 != na2 and not (na1 != na1 and na2 != na2)))):
|
| 241 |
+
with pytest.raises(TypeError):
|
| 242 |
+
arr[:-1] == newarr[:-1]
|
| 243 |
+
return
|
| 244 |
+
assert_array_equal(arr[:-1], newarr[:-1])
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@pytest.mark.parametrize(
|
| 248 |
+
("strings"),
|
| 249 |
+
[
|
| 250 |
+
["this", "is", "an", "array"],
|
| 251 |
+
["€", "", "😊"],
|
| 252 |
+
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
|
| 253 |
+
],
|
| 254 |
+
)
|
| 255 |
+
class TestStringLikeCasts:
|
| 256 |
+
def test_unicode_casts(self, dtype, strings):
|
| 257 |
+
arr = np.array(strings, dtype=np.str_).astype(dtype)
|
| 258 |
+
expected = np.array(strings, dtype=dtype)
|
| 259 |
+
assert_array_equal(arr, expected)
|
| 260 |
+
|
| 261 |
+
arr_as_U8 = expected.astype("U8")
|
| 262 |
+
assert_array_equal(arr_as_U8, np.array(strings, dtype="U8"))
|
| 263 |
+
assert_array_equal(arr_as_U8.astype(dtype), arr)
|
| 264 |
+
arr_as_U3 = expected.astype("U3")
|
| 265 |
+
assert_array_equal(arr_as_U3, np.array(strings, dtype="U3"))
|
| 266 |
+
assert_array_equal(
|
| 267 |
+
arr_as_U3.astype(dtype),
|
| 268 |
+
np.array([s[:3] for s in strings], dtype=dtype),
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
def test_void_casts(self, dtype, strings):
|
| 272 |
+
sarr = np.array(strings, dtype=dtype)
|
| 273 |
+
utf8_bytes = [s.encode("utf-8") for s in strings]
|
| 274 |
+
void_dtype = f"V{max([len(s) for s in utf8_bytes])}"
|
| 275 |
+
varr = np.array(utf8_bytes, dtype=void_dtype)
|
| 276 |
+
assert_array_equal(varr, sarr.astype(void_dtype))
|
| 277 |
+
assert_array_equal(varr.astype(dtype), sarr)
|
| 278 |
+
|
| 279 |
+
def test_bytes_casts(self, dtype, strings):
|
| 280 |
+
sarr = np.array(strings, dtype=dtype)
|
| 281 |
+
try:
|
| 282 |
+
utf8_bytes = [s.encode("ascii") for s in strings]
|
| 283 |
+
bytes_dtype = f"S{max([len(s) for s in utf8_bytes])}"
|
| 284 |
+
barr = np.array(utf8_bytes, dtype=bytes_dtype)
|
| 285 |
+
assert_array_equal(barr, sarr.astype(bytes_dtype))
|
| 286 |
+
assert_array_equal(barr.astype(dtype), sarr)
|
| 287 |
+
except UnicodeEncodeError:
|
| 288 |
+
with pytest.raises(UnicodeEncodeError):
|
| 289 |
+
sarr.astype("S20")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_additional_unicode_cast(random_string_list, dtype):
|
| 293 |
+
arr = np.array(random_string_list, dtype=dtype)
|
| 294 |
+
# test that this short-circuits correctly
|
| 295 |
+
assert_array_equal(arr, arr.astype(arr.dtype))
|
| 296 |
+
# tests the casts via the comparison promoter
|
| 297 |
+
assert_array_equal(arr, arr.astype(random_string_list.dtype))
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def test_insert_scalar(dtype, string_list):
|
| 301 |
+
"""Test that inserting a scalar works."""
|
| 302 |
+
arr = np.array(string_list, dtype=dtype)
|
| 303 |
+
scalar_instance = "what"
|
| 304 |
+
arr[1] = scalar_instance
|
| 305 |
+
assert_array_equal(
|
| 306 |
+
arr,
|
| 307 |
+
np.array(string_list[:1] + ["what"] + string_list[2:], dtype=dtype),
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
comparison_operators = [
|
| 312 |
+
np.equal,
|
| 313 |
+
np.not_equal,
|
| 314 |
+
np.greater,
|
| 315 |
+
np.greater_equal,
|
| 316 |
+
np.less,
|
| 317 |
+
np.less_equal,
|
| 318 |
+
]
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
@pytest.mark.parametrize("op", comparison_operators)
|
| 322 |
+
@pytest.mark.parametrize("o_dtype", [np.str_, object, StringDType()])
|
| 323 |
+
def test_comparisons(string_list, dtype, op, o_dtype):
|
| 324 |
+
sarr = np.array(string_list, dtype=dtype)
|
| 325 |
+
oarr = np.array(string_list, dtype=o_dtype)
|
| 326 |
+
|
| 327 |
+
# test that comparison operators work
|
| 328 |
+
res = op(sarr, sarr)
|
| 329 |
+
ores = op(oarr, oarr)
|
| 330 |
+
# test that promotion works as well
|
| 331 |
+
orres = op(sarr, oarr)
|
| 332 |
+
olres = op(oarr, sarr)
|
| 333 |
+
|
| 334 |
+
assert_array_equal(res, ores)
|
| 335 |
+
assert_array_equal(res, orres)
|
| 336 |
+
assert_array_equal(res, olres)
|
| 337 |
+
|
| 338 |
+
# test we get the correct answer for unequal length strings
|
| 339 |
+
sarr2 = np.array([s + "2" for s in string_list], dtype=dtype)
|
| 340 |
+
oarr2 = np.array([s + "2" for s in string_list], dtype=o_dtype)
|
| 341 |
+
|
| 342 |
+
res = op(sarr, sarr2)
|
| 343 |
+
ores = op(oarr, oarr2)
|
| 344 |
+
olres = op(oarr, sarr2)
|
| 345 |
+
orres = op(sarr, oarr2)
|
| 346 |
+
|
| 347 |
+
assert_array_equal(res, ores)
|
| 348 |
+
assert_array_equal(res, olres)
|
| 349 |
+
assert_array_equal(res, orres)
|
| 350 |
+
|
| 351 |
+
res = op(sarr2, sarr)
|
| 352 |
+
ores = op(oarr2, oarr)
|
| 353 |
+
olres = op(oarr2, sarr)
|
| 354 |
+
orres = op(sarr2, oarr)
|
| 355 |
+
|
| 356 |
+
assert_array_equal(res, ores)
|
| 357 |
+
assert_array_equal(res, olres)
|
| 358 |
+
assert_array_equal(res, orres)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def test_isnan(dtype, string_list):
|
| 362 |
+
if not hasattr(dtype, "na_object"):
|
| 363 |
+
pytest.skip("no na support")
|
| 364 |
+
sarr = np.array(string_list + [dtype.na_object], dtype=dtype)
|
| 365 |
+
is_nan = isinstance(dtype.na_object, float) and np.isnan(dtype.na_object)
|
| 366 |
+
bool_errors = 0
|
| 367 |
+
try:
|
| 368 |
+
bool(dtype.na_object)
|
| 369 |
+
except TypeError:
|
| 370 |
+
bool_errors = 1
|
| 371 |
+
if is_nan or bool_errors:
|
| 372 |
+
# isnan is only true when na_object is a NaN
|
| 373 |
+
assert_array_equal(
|
| 374 |
+
np.isnan(sarr),
|
| 375 |
+
np.array([0] * len(string_list) + [1], dtype=np.bool),
|
| 376 |
+
)
|
| 377 |
+
else:
|
| 378 |
+
assert not np.any(np.isnan(sarr))
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def test_pickle(dtype, string_list):
|
| 382 |
+
arr = np.array(string_list, dtype=dtype)
|
| 383 |
+
|
| 384 |
+
with tempfile.NamedTemporaryFile("wb", delete=False) as f:
|
| 385 |
+
pickle.dump([arr, dtype], f)
|
| 386 |
+
|
| 387 |
+
with open(f.name, "rb") as f:
|
| 388 |
+
res = pickle.load(f)
|
| 389 |
+
|
| 390 |
+
assert_array_equal(res[0], arr)
|
| 391 |
+
assert res[1] == dtype
|
| 392 |
+
|
| 393 |
+
os.remove(f.name)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
@pytest.mark.parametrize(
|
| 397 |
+
"strings",
|
| 398 |
+
[
|
| 399 |
+
["left", "right", "leftovers", "righty", "up", "down"],
|
| 400 |
+
[
|
| 401 |
+
"left" * 10,
|
| 402 |
+
"right" * 10,
|
| 403 |
+
"leftovers" * 10,
|
| 404 |
+
"righty" * 10,
|
| 405 |
+
"up" * 10,
|
| 406 |
+
],
|
| 407 |
+
["🤣🤣", "🤣", "📵", "😰"],
|
| 408 |
+
["🚜", "🙃", "😾"],
|
| 409 |
+
["😹", "🚠", "🚌"],
|
| 410 |
+
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
|
| 411 |
+
],
|
| 412 |
+
)
|
| 413 |
+
def test_sort(dtype, strings):
|
| 414 |
+
"""Test that sorting matches python's internal sorting."""
|
| 415 |
+
|
| 416 |
+
def test_sort(strings, arr_sorted):
|
| 417 |
+
arr = np.array(strings, dtype=dtype)
|
| 418 |
+
np.random.default_rng().shuffle(arr)
|
| 419 |
+
na_object = getattr(arr.dtype, "na_object", "")
|
| 420 |
+
if na_object is None and None in strings:
|
| 421 |
+
with pytest.raises(
|
| 422 |
+
ValueError,
|
| 423 |
+
match="Cannot compare null that is not a nan-like value",
|
| 424 |
+
):
|
| 425 |
+
arr.sort()
|
| 426 |
+
else:
|
| 427 |
+
arr.sort()
|
| 428 |
+
assert np.array_equal(arr, arr_sorted, equal_nan=True)
|
| 429 |
+
|
| 430 |
+
# make a copy so we don't mutate the lists in the fixture
|
| 431 |
+
strings = strings.copy()
|
| 432 |
+
arr_sorted = np.array(sorted(strings), dtype=dtype)
|
| 433 |
+
test_sort(strings, arr_sorted)
|
| 434 |
+
|
| 435 |
+
if not hasattr(dtype, "na_object"):
|
| 436 |
+
return
|
| 437 |
+
|
| 438 |
+
# make sure NAs get sorted to the end of the array and string NAs get
|
| 439 |
+
# sorted like normal strings
|
| 440 |
+
strings.insert(0, dtype.na_object)
|
| 441 |
+
strings.insert(2, dtype.na_object)
|
| 442 |
+
# can't use append because doing that with NA converts
|
| 443 |
+
# the result to object dtype
|
| 444 |
+
if not isinstance(dtype.na_object, str):
|
| 445 |
+
arr_sorted = np.array(
|
| 446 |
+
arr_sorted.tolist() + [dtype.na_object, dtype.na_object],
|
| 447 |
+
dtype=dtype,
|
| 448 |
+
)
|
| 449 |
+
else:
|
| 450 |
+
arr_sorted = np.array(sorted(strings), dtype=dtype)
|
| 451 |
+
|
| 452 |
+
test_sort(strings, arr_sorted)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
@pytest.mark.parametrize(
|
| 456 |
+
"strings",
|
| 457 |
+
[
|
| 458 |
+
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
|
| 459 |
+
["A¢☃€ 😊", "", " ", " "],
|
| 460 |
+
["", "a", "😸", "ááðfáíóåéë"],
|
| 461 |
+
],
|
| 462 |
+
)
|
| 463 |
+
def test_nonzero(strings, na_object):
|
| 464 |
+
dtype = get_dtype(na_object)
|
| 465 |
+
arr = np.array(strings, dtype=dtype)
|
| 466 |
+
is_nonzero = np.array(
|
| 467 |
+
[i for i, item in enumerate(strings) if len(item) != 0])
|
| 468 |
+
assert_array_equal(arr.nonzero()[0], is_nonzero)
|
| 469 |
+
|
| 470 |
+
if na_object is not pd_NA and na_object == 'unset':
|
| 471 |
+
return
|
| 472 |
+
|
| 473 |
+
strings_with_na = np.array(strings + [na_object], dtype=dtype)
|
| 474 |
+
is_nan = np.isnan(np.array([dtype.na_object], dtype=dtype))[0]
|
| 475 |
+
|
| 476 |
+
if is_nan:
|
| 477 |
+
assert strings_with_na.nonzero()[0][-1] == 4
|
| 478 |
+
else:
|
| 479 |
+
assert strings_with_na.nonzero()[0][-1] == 3
|
| 480 |
+
|
| 481 |
+
# check that the casting to bool and nonzero give consistent results
|
| 482 |
+
assert_array_equal(strings_with_na[strings_with_na.nonzero()],
|
| 483 |
+
strings_with_na[strings_with_na.astype(bool)])
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def test_where(string_list, na_object):
|
| 487 |
+
dtype = get_dtype(na_object)
|
| 488 |
+
a = np.array(string_list, dtype=dtype)
|
| 489 |
+
b = a[::-1]
|
| 490 |
+
res = np.where([True, False, True, False, True, False], a, b)
|
| 491 |
+
assert_array_equal(res, [a[0], b[1], a[2], b[3], a[4], b[5]])
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def test_fancy_indexing(string_list):
|
| 495 |
+
sarr = np.array(string_list, dtype="T")
|
| 496 |
+
assert_array_equal(sarr, sarr[np.arange(sarr.shape[0])])
|
| 497 |
+
|
| 498 |
+
# see gh-27003 and gh-27053
|
| 499 |
+
for ind in [[True, True], [0, 1], ...]:
|
| 500 |
+
for lop in [['a'*16, 'b'*16], ['', '']]:
|
| 501 |
+
a = np.array(lop, dtype="T")
|
| 502 |
+
rop = ['d'*16, 'e'*16]
|
| 503 |
+
for b in [rop, np.array(rop, dtype="T")]:
|
| 504 |
+
a[ind] = b
|
| 505 |
+
assert_array_equal(a, b)
|
| 506 |
+
assert a[0] == 'd'*16
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def test_creation_functions():
|
| 510 |
+
assert_array_equal(np.zeros(3, dtype="T"), ["", "", ""])
|
| 511 |
+
assert_array_equal(np.empty(3, dtype="T"), ["", "", ""])
|
| 512 |
+
|
| 513 |
+
assert np.zeros(3, dtype="T")[0] == ""
|
| 514 |
+
assert np.empty(3, dtype="T")[0] == ""
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def test_concatenate(string_list):
|
| 518 |
+
sarr = np.array(string_list, dtype="T")
|
| 519 |
+
sarr_cat = np.array(string_list + string_list, dtype="T")
|
| 520 |
+
|
| 521 |
+
assert_array_equal(np.concatenate([sarr], axis=0), sarr)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def test_resize_method(string_list):
|
| 525 |
+
sarr = np.array(string_list, dtype="T")
|
| 526 |
+
if IS_PYPY:
|
| 527 |
+
sarr.resize(len(string_list)+3, refcheck=False)
|
| 528 |
+
else:
|
| 529 |
+
sarr.resize(len(string_list)+3)
|
| 530 |
+
assert_array_equal(sarr, np.array(string_list + ['']*3, dtype="T"))
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def test_create_with_copy_none(string_list):
|
| 534 |
+
arr = np.array(string_list, dtype=StringDType())
|
| 535 |
+
# create another stringdtype array with an arena that has a different
|
| 536 |
+
# in-memory layout than the first array
|
| 537 |
+
arr_rev = np.array(string_list[::-1], dtype=StringDType())
|
| 538 |
+
|
| 539 |
+
# this should create a copy and the resulting array
|
| 540 |
+
# shouldn't share an allocator or arena with arr_rev, despite
|
| 541 |
+
# explicitly passing arr_rev.dtype
|
| 542 |
+
arr_copy = np.array(arr, copy=None, dtype=arr_rev.dtype)
|
| 543 |
+
np.testing.assert_array_equal(arr, arr_copy)
|
| 544 |
+
assert arr_copy.base is None
|
| 545 |
+
|
| 546 |
+
with pytest.raises(ValueError, match="Unable to avoid copy"):
|
| 547 |
+
np.array(arr, copy=False, dtype=arr_rev.dtype)
|
| 548 |
+
|
| 549 |
+
# because we're using arr's dtype instance, the view is safe
|
| 550 |
+
arr_view = np.array(arr, copy=None, dtype=arr.dtype)
|
| 551 |
+
np.testing.assert_array_equal(arr, arr)
|
| 552 |
+
np.testing.assert_array_equal(arr_view[::-1], arr_rev)
|
| 553 |
+
assert arr_view is arr
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def test_astype_copy_false():
|
| 557 |
+
orig_dt = StringDType()
|
| 558 |
+
arr = np.array(["hello", "world"], dtype=StringDType())
|
| 559 |
+
assert not arr.astype(StringDType(coerce=False), copy=False).dtype.coerce
|
| 560 |
+
|
| 561 |
+
assert arr.astype(orig_dt, copy=False).dtype is orig_dt
|
| 562 |
+
|
| 563 |
+
@pytest.mark.parametrize(
|
| 564 |
+
"strings",
|
| 565 |
+
[
|
| 566 |
+
["left", "right", "leftovers", "righty", "up", "down"],
|
| 567 |
+
["🤣🤣", "🤣", "📵", "😰"],
|
| 568 |
+
["🚜", "🙃", "😾"],
|
| 569 |
+
["😹", "🚠", "🚌"],
|
| 570 |
+
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
|
| 571 |
+
],
|
| 572 |
+
)
|
| 573 |
+
def test_argmax(strings):
|
| 574 |
+
"""Test that argmax/argmin matches what python calculates."""
|
| 575 |
+
arr = np.array(strings, dtype="T")
|
| 576 |
+
assert np.argmax(arr) == strings.index(max(strings))
|
| 577 |
+
assert np.argmin(arr) == strings.index(min(strings))
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
@pytest.mark.parametrize(
|
| 581 |
+
"arrfunc,expected",
|
| 582 |
+
[
|
| 583 |
+
[np.sort, None],
|
| 584 |
+
[np.nonzero, (np.array([], dtype=np.int_),)],
|
| 585 |
+
[np.argmax, 0],
|
| 586 |
+
[np.argmin, 0],
|
| 587 |
+
],
|
| 588 |
+
)
|
| 589 |
+
def test_arrfuncs_zeros(arrfunc, expected):
|
| 590 |
+
arr = np.zeros(10, dtype="T")
|
| 591 |
+
result = arrfunc(arr)
|
| 592 |
+
if expected is None:
|
| 593 |
+
expected = arr
|
| 594 |
+
assert_array_equal(result, expected, strict=True)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
@pytest.mark.parametrize(
|
| 598 |
+
("strings", "cast_answer", "any_answer", "all_answer"),
|
| 599 |
+
[
|
| 600 |
+
[["hello", "world"], [True, True], True, True],
|
| 601 |
+
[["", ""], [False, False], False, False],
|
| 602 |
+
[["hello", ""], [True, False], True, False],
|
| 603 |
+
[["", "world"], [False, True], True, False],
|
| 604 |
+
],
|
| 605 |
+
)
|
| 606 |
+
def test_cast_to_bool(strings, cast_answer, any_answer, all_answer):
|
| 607 |
+
sarr = np.array(strings, dtype="T")
|
| 608 |
+
assert_array_equal(sarr.astype("bool"), cast_answer)
|
| 609 |
+
|
| 610 |
+
assert np.any(sarr) == any_answer
|
| 611 |
+
assert np.all(sarr) == all_answer
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
@pytest.mark.parametrize(
|
| 615 |
+
("strings", "cast_answer"),
|
| 616 |
+
[
|
| 617 |
+
[[True, True], ["True", "True"]],
|
| 618 |
+
[[False, False], ["False", "False"]],
|
| 619 |
+
[[True, False], ["True", "False"]],
|
| 620 |
+
[[False, True], ["False", "True"]],
|
| 621 |
+
],
|
| 622 |
+
)
|
| 623 |
+
def test_cast_from_bool(strings, cast_answer):
|
| 624 |
+
barr = np.array(strings, dtype=bool)
|
| 625 |
+
assert_array_equal(barr.astype("T"), np.array(cast_answer, dtype="T"))
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
@pytest.mark.parametrize("bitsize", [8, 16, 32, 64])
|
| 629 |
+
@pytest.mark.parametrize("signed", [True, False])
|
| 630 |
+
def test_sized_integer_casts(bitsize, signed):
|
| 631 |
+
idtype = f"int{bitsize}"
|
| 632 |
+
if signed:
|
| 633 |
+
inp = [-(2**p - 1) for p in reversed(range(bitsize - 1))]
|
| 634 |
+
inp += [2**p - 1 for p in range(1, bitsize - 1)]
|
| 635 |
+
else:
|
| 636 |
+
idtype = "u" + idtype
|
| 637 |
+
inp = [2**p - 1 for p in range(bitsize)]
|
| 638 |
+
ainp = np.array(inp, dtype=idtype)
|
| 639 |
+
assert_array_equal(ainp, ainp.astype("T").astype(idtype))
|
| 640 |
+
|
| 641 |
+
# safe casting works
|
| 642 |
+
ainp.astype("T", casting="safe")
|
| 643 |
+
|
| 644 |
+
with pytest.raises(TypeError):
|
| 645 |
+
ainp.astype("T").astype(idtype, casting="safe")
|
| 646 |
+
|
| 647 |
+
oob = [str(2**bitsize), str(-(2**bitsize))]
|
| 648 |
+
with pytest.raises(OverflowError):
|
| 649 |
+
np.array(oob, dtype="T").astype(idtype)
|
| 650 |
+
|
| 651 |
+
with pytest.raises(ValueError):
|
| 652 |
+
np.array(["1", np.nan, "3"],
|
| 653 |
+
dtype=StringDType(na_object=np.nan)).astype(idtype)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
@pytest.mark.parametrize("typename", ["byte", "short", "int", "longlong"])
|
| 657 |
+
@pytest.mark.parametrize("signed", ["", "u"])
|
| 658 |
+
def test_unsized_integer_casts(typename, signed):
|
| 659 |
+
idtype = f"{signed}{typename}"
|
| 660 |
+
|
| 661 |
+
inp = [1, 2, 3, 4]
|
| 662 |
+
ainp = np.array(inp, dtype=idtype)
|
| 663 |
+
assert_array_equal(ainp, ainp.astype("T").astype(idtype))
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
@pytest.mark.parametrize(
|
| 667 |
+
"typename",
|
| 668 |
+
[
|
| 669 |
+
pytest.param(
|
| 670 |
+
"longdouble",
|
| 671 |
+
marks=pytest.mark.xfail(
|
| 672 |
+
np.dtypes.LongDoubleDType() != np.dtypes.Float64DType(),
|
| 673 |
+
reason="numpy lacks an ld2a implementation",
|
| 674 |
+
strict=True,
|
| 675 |
+
),
|
| 676 |
+
),
|
| 677 |
+
"float64",
|
| 678 |
+
"float32",
|
| 679 |
+
"float16",
|
| 680 |
+
],
|
| 681 |
+
)
|
| 682 |
+
def test_float_casts(typename):
|
| 683 |
+
inp = [1.1, 2.8, -3.2, 2.7e4]
|
| 684 |
+
ainp = np.array(inp, dtype=typename)
|
| 685 |
+
assert_array_equal(ainp, ainp.astype("T").astype(typename))
|
| 686 |
+
|
| 687 |
+
inp = [0.1]
|
| 688 |
+
sres = np.array(inp, dtype=typename).astype("T")
|
| 689 |
+
res = sres.astype(typename)
|
| 690 |
+
assert_array_equal(np.array(inp, dtype=typename), res)
|
| 691 |
+
assert sres[0] == "0.1"
|
| 692 |
+
|
| 693 |
+
if typename == "longdouble":
|
| 694 |
+
# let's not worry about platform-dependent rounding of longdouble
|
| 695 |
+
return
|
| 696 |
+
|
| 697 |
+
fi = np.finfo(typename)
|
| 698 |
+
|
| 699 |
+
inp = [1e-324, fi.smallest_subnormal, -1e-324, -fi.smallest_subnormal]
|
| 700 |
+
eres = [0, fi.smallest_subnormal, -0, -fi.smallest_subnormal]
|
| 701 |
+
res = np.array(inp, dtype=typename).astype("T").astype(typename)
|
| 702 |
+
assert_array_equal(eres, res)
|
| 703 |
+
|
| 704 |
+
inp = [2e308, fi.max, -2e308, fi.min]
|
| 705 |
+
eres = [np.inf, fi.max, -np.inf, fi.min]
|
| 706 |
+
res = np.array(inp, dtype=typename).astype("T").astype(typename)
|
| 707 |
+
assert_array_equal(eres, res)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
@pytest.mark.parametrize(
|
| 711 |
+
"typename",
|
| 712 |
+
[
|
| 713 |
+
"csingle",
|
| 714 |
+
"cdouble",
|
| 715 |
+
pytest.param(
|
| 716 |
+
"clongdouble",
|
| 717 |
+
marks=pytest.mark.xfail(
|
| 718 |
+
np.dtypes.CLongDoubleDType() != np.dtypes.Complex128DType(),
|
| 719 |
+
reason="numpy lacks an ld2a implementation",
|
| 720 |
+
strict=True,
|
| 721 |
+
),
|
| 722 |
+
),
|
| 723 |
+
],
|
| 724 |
+
)
|
| 725 |
+
def test_cfloat_casts(typename):
|
| 726 |
+
inp = [1.1 + 1.1j, 2.8 + 2.8j, -3.2 - 3.2j, 2.7e4 + 2.7e4j]
|
| 727 |
+
ainp = np.array(inp, dtype=typename)
|
| 728 |
+
assert_array_equal(ainp, ainp.astype("T").astype(typename))
|
| 729 |
+
|
| 730 |
+
inp = [0.1 + 0.1j]
|
| 731 |
+
sres = np.array(inp, dtype=typename).astype("T")
|
| 732 |
+
res = sres.astype(typename)
|
| 733 |
+
assert_array_equal(np.array(inp, dtype=typename), res)
|
| 734 |
+
assert sres[0] == "(0.1+0.1j)"
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def test_take(string_list):
|
| 738 |
+
sarr = np.array(string_list, dtype="T")
|
| 739 |
+
res = sarr.take(np.arange(len(string_list)))
|
| 740 |
+
assert_array_equal(sarr, res)
|
| 741 |
+
|
| 742 |
+
# make sure it also works for out
|
| 743 |
+
out = np.empty(len(string_list), dtype="T")
|
| 744 |
+
out[0] = "hello"
|
| 745 |
+
res = sarr.take(np.arange(len(string_list)), out=out)
|
| 746 |
+
assert res is out
|
| 747 |
+
assert_array_equal(sarr, res)
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
@pytest.mark.parametrize("use_out", [True, False])
|
| 751 |
+
@pytest.mark.parametrize(
|
| 752 |
+
"ufunc_name,func",
|
| 753 |
+
[
|
| 754 |
+
("min", min),
|
| 755 |
+
("max", max),
|
| 756 |
+
],
|
| 757 |
+
)
|
| 758 |
+
def test_ufuncs_minmax(string_list, ufunc_name, func, use_out):
|
| 759 |
+
"""Test that the min/max ufuncs match Python builtin min/max behavior."""
|
| 760 |
+
arr = np.array(string_list, dtype="T")
|
| 761 |
+
uarr = np.array(string_list, dtype=str)
|
| 762 |
+
res = np.array(func(string_list), dtype="T")
|
| 763 |
+
assert_array_equal(getattr(arr, ufunc_name)(), res)
|
| 764 |
+
|
| 765 |
+
ufunc = getattr(np, ufunc_name + "imum")
|
| 766 |
+
|
| 767 |
+
if use_out:
|
| 768 |
+
res = ufunc(arr, arr, out=arr)
|
| 769 |
+
else:
|
| 770 |
+
res = ufunc(arr, arr)
|
| 771 |
+
|
| 772 |
+
assert_array_equal(uarr, res)
|
| 773 |
+
assert_array_equal(getattr(arr, ufunc_name)(), func(string_list))
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
def test_max_regression():
|
| 777 |
+
arr = np.array(['y', 'y', 'z'], dtype="T")
|
| 778 |
+
assert arr.max() == 'z'
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
@pytest.mark.parametrize("use_out", [True, False])
|
| 782 |
+
@pytest.mark.parametrize(
|
| 783 |
+
"other_strings",
|
| 784 |
+
[
|
| 785 |
+
["abc", "def" * 500, "ghi" * 16, "🤣" * 100, "📵", "😰"],
|
| 786 |
+
["🚜", "🙃", "😾", "😹", "🚠", "🚌"],
|
| 787 |
+
["🥦", "¨", "⨯", "∰ ", "⨌ ", "⎶ "],
|
| 788 |
+
],
|
| 789 |
+
)
|
| 790 |
+
def test_ufunc_add(dtype, string_list, other_strings, use_out):
|
| 791 |
+
arr1 = np.array(string_list, dtype=dtype)
|
| 792 |
+
arr2 = np.array(other_strings, dtype=dtype)
|
| 793 |
+
result = np.array([a + b for a, b in zip(arr1, arr2)], dtype=dtype)
|
| 794 |
+
|
| 795 |
+
if use_out:
|
| 796 |
+
res = np.add(arr1, arr2, out=arr1)
|
| 797 |
+
else:
|
| 798 |
+
res = np.add(arr1, arr2)
|
| 799 |
+
|
| 800 |
+
assert_array_equal(res, result)
|
| 801 |
+
|
| 802 |
+
if not hasattr(dtype, "na_object"):
|
| 803 |
+
return
|
| 804 |
+
|
| 805 |
+
is_nan = isinstance(dtype.na_object, float) and np.isnan(dtype.na_object)
|
| 806 |
+
is_str = isinstance(dtype.na_object, str)
|
| 807 |
+
bool_errors = 0
|
| 808 |
+
try:
|
| 809 |
+
bool(dtype.na_object)
|
| 810 |
+
except TypeError:
|
| 811 |
+
bool_errors = 1
|
| 812 |
+
|
| 813 |
+
arr1 = np.array([dtype.na_object] + string_list, dtype=dtype)
|
| 814 |
+
arr2 = np.array(other_strings + [dtype.na_object], dtype=dtype)
|
| 815 |
+
|
| 816 |
+
if is_nan or bool_errors or is_str:
|
| 817 |
+
res = np.add(arr1, arr2)
|
| 818 |
+
assert_array_equal(res[1:-1], arr1[1:-1] + arr2[1:-1])
|
| 819 |
+
if not is_str:
|
| 820 |
+
assert res[0] is dtype.na_object and res[-1] is dtype.na_object
|
| 821 |
+
else:
|
| 822 |
+
assert res[0] == dtype.na_object + arr2[0]
|
| 823 |
+
assert res[-1] == arr1[-1] + dtype.na_object
|
| 824 |
+
else:
|
| 825 |
+
with pytest.raises(ValueError):
|
| 826 |
+
np.add(arr1, arr2)
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def test_ufunc_add_reduce(dtype):
|
| 830 |
+
values = ["a", "this is a long string", "c"]
|
| 831 |
+
arr = np.array(values, dtype=dtype)
|
| 832 |
+
out = np.empty((), dtype=dtype)
|
| 833 |
+
|
| 834 |
+
expected = np.array("".join(values), dtype=dtype)
|
| 835 |
+
assert_array_equal(np.add.reduce(arr), expected)
|
| 836 |
+
|
| 837 |
+
np.add.reduce(arr, out=out)
|
| 838 |
+
assert_array_equal(out, expected)
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
def test_add_promoter(string_list):
|
| 842 |
+
arr = np.array(string_list, dtype=StringDType())
|
| 843 |
+
lresult = np.array(["hello" + s for s in string_list], dtype=StringDType())
|
| 844 |
+
rresult = np.array([s + "hello" for s in string_list], dtype=StringDType())
|
| 845 |
+
|
| 846 |
+
for op in ["hello", np.str_("hello"), np.array(["hello"])]:
|
| 847 |
+
assert_array_equal(op + arr, lresult)
|
| 848 |
+
assert_array_equal(arr + op, rresult)
|
| 849 |
+
|
| 850 |
+
# The promoter should be able to handle things if users pass `dtype=`
|
| 851 |
+
res = np.add("hello", string_list, dtype=StringDType)
|
| 852 |
+
assert res.dtype == StringDType()
|
| 853 |
+
|
| 854 |
+
# The promoter should not kick in if users override the input,
|
| 855 |
+
# which means arr is cast, this fails because of the unknown length.
|
| 856 |
+
with pytest.raises(TypeError, match="cannot cast dtype"):
|
| 857 |
+
np.add(arr, "add", signature=("U", "U", None), casting="unsafe")
|
| 858 |
+
|
| 859 |
+
# But it must simply reject the following:
|
| 860 |
+
with pytest.raises(TypeError, match=".*did not contain a loop"):
|
| 861 |
+
np.add(arr, "add", signature=(None, "U", None))
|
| 862 |
+
|
| 863 |
+
with pytest.raises(TypeError, match=".*did not contain a loop"):
|
| 864 |
+
np.add("a", "b", signature=("U", "U", StringDType))
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
def test_add_no_legacy_promote_with_signature():
|
| 868 |
+
# Possibly misplaced, but useful to test with string DType. We check that
|
| 869 |
+
# if there is clearly no loop found, a stray `dtype=` doesn't break things
|
| 870 |
+
# Regression test for the bad error in gh-26735
|
| 871 |
+
# (If legacy promotion is gone, this can be deleted...)
|
| 872 |
+
with pytest.raises(TypeError, match=".*did not contain a loop"):
|
| 873 |
+
np.add("3", 6, dtype=StringDType)
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
def test_add_promoter_reduce():
|
| 877 |
+
# Exact TypeError could change, but ensure StringDtype doesn't match
|
| 878 |
+
with pytest.raises(TypeError, match="the resolved dtypes are not"):
|
| 879 |
+
np.add.reduce(np.array(["a", "b"], dtype="U"))
|
| 880 |
+
|
| 881 |
+
# On the other hand, using `dtype=T` in the *ufunc* should work.
|
| 882 |
+
np.add.reduce(np.array(["a", "b"], dtype="U"), dtype=np.dtypes.StringDType)
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
def test_multiply_reduce():
|
| 886 |
+
# At the time of writing (NumPy 2.0) this is very limited (and rather
|
| 887 |
+
# ridiculous anyway). But it works and actually makes some sense...
|
| 888 |
+
# (NumPy does not allow non-scalar initial values)
|
| 889 |
+
repeats = np.array([2, 3, 4])
|
| 890 |
+
val = "school-🚌"
|
| 891 |
+
res = np.multiply.reduce(repeats, initial=val, dtype=np.dtypes.StringDType)
|
| 892 |
+
assert res == val * np.prod(repeats)
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def test_multiply_two_string_raises():
|
| 896 |
+
arr = np.array(["hello", "world"], dtype="T")
|
| 897 |
+
with pytest.raises(np._core._exceptions._UFuncNoLoopError):
|
| 898 |
+
np.multiply(arr, arr)
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
@pytest.mark.parametrize("use_out", [True, False])
|
| 902 |
+
@pytest.mark.parametrize("other", [2, [2, 1, 3, 4, 1, 3]])
|
| 903 |
+
@pytest.mark.parametrize(
|
| 904 |
+
"other_dtype",
|
| 905 |
+
[
|
| 906 |
+
None,
|
| 907 |
+
"int8",
|
| 908 |
+
"int16",
|
| 909 |
+
"int32",
|
| 910 |
+
"int64",
|
| 911 |
+
"uint8",
|
| 912 |
+
"uint16",
|
| 913 |
+
"uint32",
|
| 914 |
+
"uint64",
|
| 915 |
+
"short",
|
| 916 |
+
"int",
|
| 917 |
+
"intp",
|
| 918 |
+
"long",
|
| 919 |
+
"longlong",
|
| 920 |
+
"ushort",
|
| 921 |
+
"uint",
|
| 922 |
+
"uintp",
|
| 923 |
+
"ulong",
|
| 924 |
+
"ulonglong",
|
| 925 |
+
],
|
| 926 |
+
)
|
| 927 |
+
def test_ufunc_multiply(dtype, string_list, other, other_dtype, use_out):
|
| 928 |
+
"""Test the two-argument ufuncs match python builtin behavior."""
|
| 929 |
+
arr = np.array(string_list, dtype=dtype)
|
| 930 |
+
if other_dtype is not None:
|
| 931 |
+
other_dtype = np.dtype(other_dtype)
|
| 932 |
+
try:
|
| 933 |
+
len(other)
|
| 934 |
+
result = [s * o for s, o in zip(string_list, other)]
|
| 935 |
+
other = np.array(other)
|
| 936 |
+
if other_dtype is not None:
|
| 937 |
+
other = other.astype(other_dtype)
|
| 938 |
+
except TypeError:
|
| 939 |
+
if other_dtype is not None:
|
| 940 |
+
other = other_dtype.type(other)
|
| 941 |
+
result = [s * other for s in string_list]
|
| 942 |
+
|
| 943 |
+
if use_out:
|
| 944 |
+
arr_cache = arr.copy()
|
| 945 |
+
lres = np.multiply(arr, other, out=arr)
|
| 946 |
+
assert_array_equal(lres, result)
|
| 947 |
+
arr[:] = arr_cache
|
| 948 |
+
assert lres is arr
|
| 949 |
+
arr *= other
|
| 950 |
+
assert_array_equal(arr, result)
|
| 951 |
+
arr[:] = arr_cache
|
| 952 |
+
rres = np.multiply(other, arr, out=arr)
|
| 953 |
+
assert rres is arr
|
| 954 |
+
assert_array_equal(rres, result)
|
| 955 |
+
else:
|
| 956 |
+
lres = arr * other
|
| 957 |
+
assert_array_equal(lres, result)
|
| 958 |
+
rres = other * arr
|
| 959 |
+
assert_array_equal(rres, result)
|
| 960 |
+
|
| 961 |
+
if not hasattr(dtype, "na_object"):
|
| 962 |
+
return
|
| 963 |
+
|
| 964 |
+
is_nan = np.isnan(np.array([dtype.na_object], dtype=dtype))[0]
|
| 965 |
+
is_str = isinstance(dtype.na_object, str)
|
| 966 |
+
bool_errors = 0
|
| 967 |
+
try:
|
| 968 |
+
bool(dtype.na_object)
|
| 969 |
+
except TypeError:
|
| 970 |
+
bool_errors = 1
|
| 971 |
+
|
| 972 |
+
arr = np.array(string_list + [dtype.na_object], dtype=dtype)
|
| 973 |
+
|
| 974 |
+
try:
|
| 975 |
+
len(other)
|
| 976 |
+
other = np.append(other, 3)
|
| 977 |
+
if other_dtype is not None:
|
| 978 |
+
other = other.astype(other_dtype)
|
| 979 |
+
except TypeError:
|
| 980 |
+
pass
|
| 981 |
+
|
| 982 |
+
if is_nan or bool_errors or is_str:
|
| 983 |
+
for res in [arr * other, other * arr]:
|
| 984 |
+
assert_array_equal(res[:-1], result)
|
| 985 |
+
if not is_str:
|
| 986 |
+
assert res[-1] is dtype.na_object
|
| 987 |
+
else:
|
| 988 |
+
try:
|
| 989 |
+
assert res[-1] == dtype.na_object * other[-1]
|
| 990 |
+
except (IndexError, TypeError):
|
| 991 |
+
assert res[-1] == dtype.na_object * other
|
| 992 |
+
else:
|
| 993 |
+
with pytest.raises(TypeError):
|
| 994 |
+
arr * other
|
| 995 |
+
with pytest.raises(TypeError):
|
| 996 |
+
other * arr
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
DATETIME_INPUT = [
|
| 1000 |
+
np.datetime64("1923-04-14T12:43:12"),
|
| 1001 |
+
np.datetime64("1994-06-21T14:43:15"),
|
| 1002 |
+
np.datetime64("2001-10-15T04:10:32"),
|
| 1003 |
+
np.datetime64("NaT"),
|
| 1004 |
+
np.datetime64("1995-11-25T16:02:16"),
|
| 1005 |
+
np.datetime64("2005-01-04T03:14:12"),
|
| 1006 |
+
np.datetime64("2041-12-03T14:05:03"),
|
| 1007 |
+
]
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
TIMEDELTA_INPUT = [
|
| 1011 |
+
np.timedelta64(12358, "s"),
|
| 1012 |
+
np.timedelta64(23, "s"),
|
| 1013 |
+
np.timedelta64(74, "s"),
|
| 1014 |
+
np.timedelta64("NaT"),
|
| 1015 |
+
np.timedelta64(23, "s"),
|
| 1016 |
+
np.timedelta64(73, "s"),
|
| 1017 |
+
np.timedelta64(7, "s"),
|
| 1018 |
+
]
|
| 1019 |
+
|
| 1020 |
+
|
| 1021 |
+
@pytest.mark.parametrize(
|
| 1022 |
+
"input_data, input_dtype",
|
| 1023 |
+
[
|
| 1024 |
+
(DATETIME_INPUT, "M8[s]"),
|
| 1025 |
+
(TIMEDELTA_INPUT, "m8[s]")
|
| 1026 |
+
]
|
| 1027 |
+
)
|
| 1028 |
+
def test_datetime_timedelta_cast(dtype, input_data, input_dtype):
|
| 1029 |
+
|
| 1030 |
+
a = np.array(input_data, dtype=input_dtype)
|
| 1031 |
+
|
| 1032 |
+
has_na = hasattr(dtype, "na_object")
|
| 1033 |
+
is_str = isinstance(getattr(dtype, "na_object", None), str)
|
| 1034 |
+
|
| 1035 |
+
if not has_na or is_str:
|
| 1036 |
+
a = np.delete(a, 3)
|
| 1037 |
+
|
| 1038 |
+
sa = a.astype(dtype)
|
| 1039 |
+
ra = sa.astype(a.dtype)
|
| 1040 |
+
|
| 1041 |
+
if has_na and not is_str:
|
| 1042 |
+
assert sa[3] is dtype.na_object
|
| 1043 |
+
assert np.isnat(ra[3])
|
| 1044 |
+
|
| 1045 |
+
assert_array_equal(a, ra)
|
| 1046 |
+
|
| 1047 |
+
if has_na and not is_str:
|
| 1048 |
+
# don't worry about comparing how NaT is converted
|
| 1049 |
+
sa = np.delete(sa, 3)
|
| 1050 |
+
a = np.delete(a, 3)
|
| 1051 |
+
|
| 1052 |
+
if input_dtype.startswith("M"):
|
| 1053 |
+
assert_array_equal(sa, a.astype("U"))
|
| 1054 |
+
else:
|
| 1055 |
+
# The timedelta to unicode cast produces strings
|
| 1056 |
+
# that aren't round-trippable and we don't want to
|
| 1057 |
+
# reproduce that behavior in stringdtype
|
| 1058 |
+
assert_array_equal(sa, a.astype("int64").astype("U"))
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
def test_nat_casts():
|
| 1062 |
+
s = 'nat'
|
| 1063 |
+
all_nats = itertools.product(*zip(s.upper(), s.lower()))
|
| 1064 |
+
all_nats = list(map(''.join, all_nats))
|
| 1065 |
+
NaT_dt = np.datetime64('NaT')
|
| 1066 |
+
NaT_td = np.timedelta64('NaT')
|
| 1067 |
+
for na_object in [np._NoValue, None, np.nan, 'nat', '']:
|
| 1068 |
+
# numpy treats empty string and all case combinations of 'nat' as NaT
|
| 1069 |
+
dtype = StringDType(na_object=na_object)
|
| 1070 |
+
arr = np.array([''] + all_nats, dtype=dtype)
|
| 1071 |
+
dt_array = arr.astype('M8[s]')
|
| 1072 |
+
td_array = arr.astype('m8[s]')
|
| 1073 |
+
assert_array_equal(dt_array, NaT_dt)
|
| 1074 |
+
assert_array_equal(td_array, NaT_td)
|
| 1075 |
+
|
| 1076 |
+
if na_object is np._NoValue:
|
| 1077 |
+
output_object = 'NaT'
|
| 1078 |
+
else:
|
| 1079 |
+
output_object = na_object
|
| 1080 |
+
|
| 1081 |
+
for arr in [dt_array, td_array]:
|
| 1082 |
+
assert_array_equal(
|
| 1083 |
+
arr.astype(dtype),
|
| 1084 |
+
np.array([output_object]*arr.size, dtype=dtype))
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
def test_nat_conversion():
|
| 1088 |
+
for nat in [np.datetime64("NaT", "s"), np.timedelta64("NaT", "s")]:
|
| 1089 |
+
with pytest.raises(ValueError, match="string coercion is disabled"):
|
| 1090 |
+
np.array(["a", nat], dtype=StringDType(coerce=False))
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
def test_growing_strings(dtype):
|
| 1094 |
+
# growing a string leads to a heap allocation, this tests to make sure
|
| 1095 |
+
# we do that bookkeeping correctly for all possible starting cases
|
| 1096 |
+
data = [
|
| 1097 |
+
"hello", # a short string
|
| 1098 |
+
"abcdefghijklmnopqestuvwxyz", # a medium heap-allocated string
|
| 1099 |
+
"hello" * 200, # a long heap-allocated string
|
| 1100 |
+
]
|
| 1101 |
+
|
| 1102 |
+
arr = np.array(data, dtype=dtype)
|
| 1103 |
+
uarr = np.array(data, dtype=str)
|
| 1104 |
+
|
| 1105 |
+
for _ in range(5):
|
| 1106 |
+
arr = arr + arr
|
| 1107 |
+
uarr = uarr + uarr
|
| 1108 |
+
|
| 1109 |
+
assert_array_equal(arr, uarr)
|
| 1110 |
+
|
| 1111 |
+
|
| 1112 |
+
@pytest.mark.skipif(IS_WASM, reason="no threading support in wasm")
|
| 1113 |
+
def test_threaded_access_and_mutation(dtype, random_string_list):
|
| 1114 |
+
# this test uses an RNG and may crash or cause deadlocks if there is a
|
| 1115 |
+
# threading bug
|
| 1116 |
+
rng = np.random.default_rng(0x4D3D3D3)
|
| 1117 |
+
|
| 1118 |
+
def func(arr):
|
| 1119 |
+
rnd = rng.random()
|
| 1120 |
+
# either write to random locations in the array, compute a ufunc, or
|
| 1121 |
+
# re-initialize the array
|
| 1122 |
+
if rnd < 0.25:
|
| 1123 |
+
num = np.random.randint(0, arr.size)
|
| 1124 |
+
arr[num] = arr[num] + "hello"
|
| 1125 |
+
elif rnd < 0.5:
|
| 1126 |
+
if rnd < 0.375:
|
| 1127 |
+
np.add(arr, arr)
|
| 1128 |
+
else:
|
| 1129 |
+
np.add(arr, arr, out=arr)
|
| 1130 |
+
elif rnd < 0.75:
|
| 1131 |
+
if rnd < 0.875:
|
| 1132 |
+
np.multiply(arr, np.int64(2))
|
| 1133 |
+
else:
|
| 1134 |
+
np.multiply(arr, np.int64(2), out=arr)
|
| 1135 |
+
else:
|
| 1136 |
+
arr[:] = random_string_list
|
| 1137 |
+
|
| 1138 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as tpe:
|
| 1139 |
+
arr = np.array(random_string_list, dtype=dtype)
|
| 1140 |
+
futures = [tpe.submit(func, arr) for _ in range(500)]
|
| 1141 |
+
|
| 1142 |
+
for f in futures:
|
| 1143 |
+
f.result()
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
UFUNC_TEST_DATA = [
|
| 1147 |
+
"hello" * 10,
|
| 1148 |
+
"Ae¢☃€ 😊" * 20,
|
| 1149 |
+
"entry\nwith\nnewlines",
|
| 1150 |
+
"entry\twith\ttabs",
|
| 1151 |
+
]
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
@pytest.fixture
|
| 1155 |
+
def string_array(dtype):
|
| 1156 |
+
return np.array(UFUNC_TEST_DATA, dtype=dtype)
|
| 1157 |
+
|
| 1158 |
+
|
| 1159 |
+
@pytest.fixture
|
| 1160 |
+
def unicode_array():
|
| 1161 |
+
return np.array(UFUNC_TEST_DATA, dtype=np.str_)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
NAN_PRESERVING_FUNCTIONS = [
|
| 1165 |
+
"capitalize",
|
| 1166 |
+
"expandtabs",
|
| 1167 |
+
"lower",
|
| 1168 |
+
"lstrip",
|
| 1169 |
+
"rstrip",
|
| 1170 |
+
"splitlines",
|
| 1171 |
+
"strip",
|
| 1172 |
+
"swapcase",
|
| 1173 |
+
"title",
|
| 1174 |
+
"upper",
|
| 1175 |
+
]
|
| 1176 |
+
|
| 1177 |
+
BOOL_OUTPUT_FUNCTIONS = [
|
| 1178 |
+
"isalnum",
|
| 1179 |
+
"isalpha",
|
| 1180 |
+
"isdigit",
|
| 1181 |
+
"islower",
|
| 1182 |
+
"isspace",
|
| 1183 |
+
"istitle",
|
| 1184 |
+
"isupper",
|
| 1185 |
+
"isnumeric",
|
| 1186 |
+
"isdecimal",
|
| 1187 |
+
]
|
| 1188 |
+
|
| 1189 |
+
UNARY_FUNCTIONS = [
|
| 1190 |
+
"str_len",
|
| 1191 |
+
"capitalize",
|
| 1192 |
+
"expandtabs",
|
| 1193 |
+
"isalnum",
|
| 1194 |
+
"isalpha",
|
| 1195 |
+
"isdigit",
|
| 1196 |
+
"islower",
|
| 1197 |
+
"isspace",
|
| 1198 |
+
"istitle",
|
| 1199 |
+
"isupper",
|
| 1200 |
+
"lower",
|
| 1201 |
+
"lstrip",
|
| 1202 |
+
"rstrip",
|
| 1203 |
+
"splitlines",
|
| 1204 |
+
"strip",
|
| 1205 |
+
"swapcase",
|
| 1206 |
+
"title",
|
| 1207 |
+
"upper",
|
| 1208 |
+
"isnumeric",
|
| 1209 |
+
"isdecimal",
|
| 1210 |
+
"isalnum",
|
| 1211 |
+
"islower",
|
| 1212 |
+
"istitle",
|
| 1213 |
+
"isupper",
|
| 1214 |
+
]
|
| 1215 |
+
|
| 1216 |
+
UNIMPLEMENTED_VEC_STRING_FUNCTIONS = [
|
| 1217 |
+
"capitalize",
|
| 1218 |
+
"expandtabs",
|
| 1219 |
+
"lower",
|
| 1220 |
+
"splitlines",
|
| 1221 |
+
"swapcase",
|
| 1222 |
+
"title",
|
| 1223 |
+
"upper",
|
| 1224 |
+
]
|
| 1225 |
+
|
| 1226 |
+
ONLY_IN_NP_CHAR = [
|
| 1227 |
+
"join",
|
| 1228 |
+
"split",
|
| 1229 |
+
"rsplit",
|
| 1230 |
+
"splitlines"
|
| 1231 |
+
]
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
@pytest.mark.parametrize("function_name", UNARY_FUNCTIONS)
|
| 1235 |
+
def test_unary(string_array, unicode_array, function_name):
|
| 1236 |
+
if function_name in ONLY_IN_NP_CHAR:
|
| 1237 |
+
func = getattr(np.char, function_name)
|
| 1238 |
+
else:
|
| 1239 |
+
func = getattr(np.strings, function_name)
|
| 1240 |
+
dtype = string_array.dtype
|
| 1241 |
+
sres = func(string_array)
|
| 1242 |
+
ures = func(unicode_array)
|
| 1243 |
+
if sres.dtype == StringDType():
|
| 1244 |
+
ures = ures.astype(StringDType())
|
| 1245 |
+
assert_array_equal(sres, ures)
|
| 1246 |
+
|
| 1247 |
+
if not hasattr(dtype, "na_object"):
|
| 1248 |
+
return
|
| 1249 |
+
|
| 1250 |
+
is_nan = np.isnan(np.array([dtype.na_object], dtype=dtype))[0]
|
| 1251 |
+
is_str = isinstance(dtype.na_object, str)
|
| 1252 |
+
na_arr = np.insert(string_array, 0, dtype.na_object)
|
| 1253 |
+
|
| 1254 |
+
if function_name in UNIMPLEMENTED_VEC_STRING_FUNCTIONS:
|
| 1255 |
+
if not is_str:
|
| 1256 |
+
# to avoid these errors we'd need to add NA support to _vec_string
|
| 1257 |
+
with pytest.raises((ValueError, TypeError)):
|
| 1258 |
+
func(na_arr)
|
| 1259 |
+
else:
|
| 1260 |
+
if function_name == "splitlines":
|
| 1261 |
+
assert func(na_arr)[0] == func(dtype.na_object)[()]
|
| 1262 |
+
else:
|
| 1263 |
+
assert func(na_arr)[0] == func(dtype.na_object)
|
| 1264 |
+
return
|
| 1265 |
+
if function_name == "str_len" and not is_str:
|
| 1266 |
+
# str_len always errors for any non-string null, even NA ones because
|
| 1267 |
+
# it has an integer result
|
| 1268 |
+
with pytest.raises(ValueError):
|
| 1269 |
+
func(na_arr)
|
| 1270 |
+
return
|
| 1271 |
+
if function_name in BOOL_OUTPUT_FUNCTIONS:
|
| 1272 |
+
if is_nan:
|
| 1273 |
+
assert func(na_arr)[0] is np.False_
|
| 1274 |
+
elif is_str:
|
| 1275 |
+
assert func(na_arr)[0] == func(dtype.na_object)
|
| 1276 |
+
else:
|
| 1277 |
+
with pytest.raises(ValueError):
|
| 1278 |
+
func(na_arr)
|
| 1279 |
+
return
|
| 1280 |
+
if not (is_nan or is_str):
|
| 1281 |
+
with pytest.raises(ValueError):
|
| 1282 |
+
func(na_arr)
|
| 1283 |
+
return
|
| 1284 |
+
res = func(na_arr)
|
| 1285 |
+
if is_nan and function_name in NAN_PRESERVING_FUNCTIONS:
|
| 1286 |
+
assert res[0] is dtype.na_object
|
| 1287 |
+
elif is_str:
|
| 1288 |
+
assert res[0] == func(dtype.na_object)
|
| 1289 |
+
|
| 1290 |
+
|
| 1291 |
+
unicode_bug_fail = pytest.mark.xfail(
|
| 1292 |
+
reason="unicode output width is buggy", strict=True
|
| 1293 |
+
)
|
| 1294 |
+
|
| 1295 |
+
# None means that the argument is a string array
|
| 1296 |
+
BINARY_FUNCTIONS = [
|
| 1297 |
+
("add", (None, None)),
|
| 1298 |
+
("multiply", (None, 2)),
|
| 1299 |
+
("mod", ("format: %s", None)),
|
| 1300 |
+
("center", (None, 25)),
|
| 1301 |
+
("count", (None, "A")),
|
| 1302 |
+
("encode", (None, "UTF-8")),
|
| 1303 |
+
("endswith", (None, "lo")),
|
| 1304 |
+
("find", (None, "A")),
|
| 1305 |
+
("index", (None, "e")),
|
| 1306 |
+
("join", ("-", None)),
|
| 1307 |
+
("ljust", (None, 12)),
|
| 1308 |
+
("lstrip", (None, "A")),
|
| 1309 |
+
("partition", (None, "A")),
|
| 1310 |
+
("replace", (None, "A", "B")),
|
| 1311 |
+
("rfind", (None, "A")),
|
| 1312 |
+
("rindex", (None, "e")),
|
| 1313 |
+
("rjust", (None, 12)),
|
| 1314 |
+
("rsplit", (None, "A")),
|
| 1315 |
+
("rstrip", (None, "A")),
|
| 1316 |
+
("rpartition", (None, "A")),
|
| 1317 |
+
("split", (None, "A")),
|
| 1318 |
+
("strip", (None, "A")),
|
| 1319 |
+
("startswith", (None, "A")),
|
| 1320 |
+
("zfill", (None, 12)),
|
| 1321 |
+
]
|
| 1322 |
+
|
| 1323 |
+
PASSES_THROUGH_NAN_NULLS = [
|
| 1324 |
+
"add",
|
| 1325 |
+
"center",
|
| 1326 |
+
"ljust",
|
| 1327 |
+
"multiply",
|
| 1328 |
+
"replace",
|
| 1329 |
+
"rjust",
|
| 1330 |
+
"strip",
|
| 1331 |
+
"lstrip",
|
| 1332 |
+
"rstrip",
|
| 1333 |
+
"replace"
|
| 1334 |
+
"zfill",
|
| 1335 |
+
]
|
| 1336 |
+
|
| 1337 |
+
NULLS_ARE_FALSEY = [
|
| 1338 |
+
"startswith",
|
| 1339 |
+
"endswith",
|
| 1340 |
+
]
|
| 1341 |
+
|
| 1342 |
+
NULLS_ALWAYS_ERROR = [
|
| 1343 |
+
"count",
|
| 1344 |
+
"find",
|
| 1345 |
+
"rfind",
|
| 1346 |
+
]
|
| 1347 |
+
|
| 1348 |
+
SUPPORTS_NULLS = (
|
| 1349 |
+
PASSES_THROUGH_NAN_NULLS +
|
| 1350 |
+
NULLS_ARE_FALSEY +
|
| 1351 |
+
NULLS_ALWAYS_ERROR
|
| 1352 |
+
)
|
| 1353 |
+
|
| 1354 |
+
|
| 1355 |
+
def call_func(func, args, array, sanitize=True):
|
| 1356 |
+
if args == (None, None):
|
| 1357 |
+
return func(array, array)
|
| 1358 |
+
if args[0] is None:
|
| 1359 |
+
if sanitize:
|
| 1360 |
+
san_args = tuple(
|
| 1361 |
+
np.array(arg, dtype=array.dtype) if isinstance(arg, str) else
|
| 1362 |
+
arg for arg in args[1:]
|
| 1363 |
+
)
|
| 1364 |
+
else:
|
| 1365 |
+
san_args = args[1:]
|
| 1366 |
+
return func(array, *san_args)
|
| 1367 |
+
if args[1] is None:
|
| 1368 |
+
return func(args[0], array)
|
| 1369 |
+
# shouldn't ever happen
|
| 1370 |
+
assert 0
|
| 1371 |
+
|
| 1372 |
+
|
| 1373 |
+
@pytest.mark.parametrize("function_name, args", BINARY_FUNCTIONS)
|
| 1374 |
+
def test_binary(string_array, unicode_array, function_name, args):
|
| 1375 |
+
if function_name in ONLY_IN_NP_CHAR:
|
| 1376 |
+
func = getattr(np.char, function_name)
|
| 1377 |
+
else:
|
| 1378 |
+
func = getattr(np.strings, function_name)
|
| 1379 |
+
sres = call_func(func, args, string_array)
|
| 1380 |
+
ures = call_func(func, args, unicode_array, sanitize=False)
|
| 1381 |
+
if not isinstance(sres, tuple) and sres.dtype == StringDType():
|
| 1382 |
+
ures = ures.astype(StringDType())
|
| 1383 |
+
assert_array_equal(sres, ures)
|
| 1384 |
+
|
| 1385 |
+
dtype = string_array.dtype
|
| 1386 |
+
if function_name not in SUPPORTS_NULLS or not hasattr(dtype, "na_object"):
|
| 1387 |
+
return
|
| 1388 |
+
|
| 1389 |
+
na_arr = np.insert(string_array, 0, dtype.na_object)
|
| 1390 |
+
is_nan = np.isnan(np.array([dtype.na_object], dtype=dtype))[0]
|
| 1391 |
+
is_str = isinstance(dtype.na_object, str)
|
| 1392 |
+
should_error = not (is_nan or is_str)
|
| 1393 |
+
|
| 1394 |
+
if (
|
| 1395 |
+
(function_name in NULLS_ALWAYS_ERROR and not is_str)
|
| 1396 |
+
or (function_name in PASSES_THROUGH_NAN_NULLS and should_error)
|
| 1397 |
+
or (function_name in NULLS_ARE_FALSEY and should_error)
|
| 1398 |
+
):
|
| 1399 |
+
with pytest.raises((ValueError, TypeError)):
|
| 1400 |
+
call_func(func, args, na_arr)
|
| 1401 |
+
return
|
| 1402 |
+
|
| 1403 |
+
res = call_func(func, args, na_arr)
|
| 1404 |
+
|
| 1405 |
+
if is_str:
|
| 1406 |
+
assert res[0] == call_func(func, args, na_arr[:1])
|
| 1407 |
+
elif function_name in NULLS_ARE_FALSEY:
|
| 1408 |
+
assert res[0] is np.False_
|
| 1409 |
+
elif function_name in PASSES_THROUGH_NAN_NULLS:
|
| 1410 |
+
assert res[0] is dtype.na_object
|
| 1411 |
+
else:
|
| 1412 |
+
# shouldn't ever get here
|
| 1413 |
+
assert 0
|
| 1414 |
+
|
| 1415 |
+
|
| 1416 |
+
@pytest.mark.parametrize("function, expected", [
|
| 1417 |
+
(np.strings.find, [[2, -1], [1, -1]]),
|
| 1418 |
+
(np.strings.startswith, [[False, False], [True, False]])])
|
| 1419 |
+
@pytest.mark.parametrize("start, stop", [
|
| 1420 |
+
(1, 4),
|
| 1421 |
+
(np.int8(1), np.int8(4)),
|
| 1422 |
+
(np.array([1, 1], dtype='u2'), np.array([4, 4], dtype='u2'))])
|
| 1423 |
+
def test_non_default_start_stop(function, start, stop, expected):
|
| 1424 |
+
a = np.array([["--🐍--", "--🦜--"],
|
| 1425 |
+
["-🐍---", "-🦜---"]], "T")
|
| 1426 |
+
indx = function(a, "🐍", start, stop)
|
| 1427 |
+
assert_array_equal(indx, expected)
|
| 1428 |
+
|
| 1429 |
+
|
| 1430 |
+
@pytest.mark.parametrize("count", [2, np.int8(2), np.array([2, 2], 'u2')])
|
| 1431 |
+
def test_replace_non_default_repeat(count):
|
| 1432 |
+
a = np.array(["🐍--", "🦜-🦜-"], "T")
|
| 1433 |
+
result = np.strings.replace(a, "🦜-", "🦜†", count)
|
| 1434 |
+
assert_array_equal(result, np.array(["🐍--", "🦜†🦜†"], "T"))
|
| 1435 |
+
|
| 1436 |
+
|
| 1437 |
+
def test_strip_ljust_rjust_consistency(string_array, unicode_array):
|
| 1438 |
+
rjs = np.char.rjust(string_array, 1000)
|
| 1439 |
+
rju = np.char.rjust(unicode_array, 1000)
|
| 1440 |
+
|
| 1441 |
+
ljs = np.char.ljust(string_array, 1000)
|
| 1442 |
+
lju = np.char.ljust(unicode_array, 1000)
|
| 1443 |
+
|
| 1444 |
+
assert_array_equal(
|
| 1445 |
+
np.char.lstrip(rjs),
|
| 1446 |
+
np.char.lstrip(rju).astype(StringDType()),
|
| 1447 |
+
)
|
| 1448 |
+
|
| 1449 |
+
assert_array_equal(
|
| 1450 |
+
np.char.rstrip(ljs),
|
| 1451 |
+
np.char.rstrip(lju).astype(StringDType()),
|
| 1452 |
+
)
|
| 1453 |
+
|
| 1454 |
+
assert_array_equal(
|
| 1455 |
+
np.char.strip(ljs),
|
| 1456 |
+
np.char.strip(lju).astype(StringDType()),
|
| 1457 |
+
)
|
| 1458 |
+
|
| 1459 |
+
assert_array_equal(
|
| 1460 |
+
np.char.strip(rjs),
|
| 1461 |
+
np.char.strip(rju).astype(StringDType()),
|
| 1462 |
+
)
|
| 1463 |
+
|
| 1464 |
+
|
| 1465 |
+
def test_unset_na_coercion():
|
| 1466 |
+
# a dtype instance with an unset na object is compatible
|
| 1467 |
+
# with a dtype that has one set
|
| 1468 |
+
|
| 1469 |
+
# this test uses the "add" and "equal" ufunc but all ufuncs that
|
| 1470 |
+
# accept more than one string argument and produce a string should
|
| 1471 |
+
# behave this way
|
| 1472 |
+
# TODO: generalize to more ufuncs
|
| 1473 |
+
inp = ["hello", "world"]
|
| 1474 |
+
arr = np.array(inp, dtype=StringDType(na_object=None))
|
| 1475 |
+
for op_dtype in [None, StringDType(), StringDType(coerce=False),
|
| 1476 |
+
StringDType(na_object=None)]:
|
| 1477 |
+
if op_dtype is None:
|
| 1478 |
+
op = "2"
|
| 1479 |
+
else:
|
| 1480 |
+
op = np.array("2", dtype=op_dtype)
|
| 1481 |
+
res = arr + op
|
| 1482 |
+
assert_array_equal(res, ["hello2", "world2"])
|
| 1483 |
+
|
| 1484 |
+
# dtype instances with distinct explicitly set NA objects are incompatible
|
| 1485 |
+
for op_dtype in [StringDType(na_object=pd_NA), StringDType(na_object="")]:
|
| 1486 |
+
op = np.array("2", dtype=op_dtype)
|
| 1487 |
+
with pytest.raises(TypeError):
|
| 1488 |
+
arr + op
|
| 1489 |
+
|
| 1490 |
+
# comparisons only consider the na_object
|
| 1491 |
+
for op_dtype in [None, StringDType(), StringDType(coerce=True),
|
| 1492 |
+
StringDType(na_object=None)]:
|
| 1493 |
+
if op_dtype is None:
|
| 1494 |
+
op = inp
|
| 1495 |
+
else:
|
| 1496 |
+
op = np.array(inp, dtype=op_dtype)
|
| 1497 |
+
assert_array_equal(arr, op)
|
| 1498 |
+
|
| 1499 |
+
for op_dtype in [StringDType(na_object=pd_NA),
|
| 1500 |
+
StringDType(na_object=np.nan)]:
|
| 1501 |
+
op = np.array(inp, dtype=op_dtype)
|
| 1502 |
+
with pytest.raises(TypeError):
|
| 1503 |
+
arr == op
|
| 1504 |
+
|
| 1505 |
+
|
| 1506 |
+
class TestImplementation:
|
| 1507 |
+
"""Check that strings are stored in the arena when possible.
|
| 1508 |
+
|
| 1509 |
+
This tests implementation details, so should be adjusted if
|
| 1510 |
+
the implementation changes.
|
| 1511 |
+
"""
|
| 1512 |
+
|
| 1513 |
+
@classmethod
|
| 1514 |
+
def setup_class(self):
|
| 1515 |
+
self.MISSING = 0x80
|
| 1516 |
+
self.INITIALIZED = 0x40
|
| 1517 |
+
self.OUTSIDE_ARENA = 0x20
|
| 1518 |
+
self.LONG = 0x10
|
| 1519 |
+
self.dtype = StringDType(na_object=np.nan)
|
| 1520 |
+
self.sizeofstr = self.dtype.itemsize
|
| 1521 |
+
sp = self.dtype.itemsize // 2 # pointer size = sizeof(size_t)
|
| 1522 |
+
# Below, size is not strictly correct, since it really uses
|
| 1523 |
+
# 7 (or 3) bytes, but good enough for the tests here.
|
| 1524 |
+
self.view_dtype = np.dtype([
|
| 1525 |
+
('offset', f'u{sp}'),
|
| 1526 |
+
('size', f'u{sp // 2}'),
|
| 1527 |
+
('xsiz', f'V{sp // 2 - 1}'),
|
| 1528 |
+
('size_and_flags', 'u1'),
|
| 1529 |
+
] if sys.byteorder == 'little' else [
|
| 1530 |
+
('size_and_flags', 'u1'),
|
| 1531 |
+
('xsiz', f'V{sp // 2 - 1}'),
|
| 1532 |
+
('size', f'u{sp // 2}'),
|
| 1533 |
+
('offset', f'u{sp}'),
|
| 1534 |
+
])
|
| 1535 |
+
self.s_empty = ""
|
| 1536 |
+
self.s_short = "01234"
|
| 1537 |
+
self.s_medium = "abcdefghijklmnopqrstuvwxyz"
|
| 1538 |
+
self.s_long = "-=+" * 100
|
| 1539 |
+
self.a = np.array(
|
| 1540 |
+
[self.s_empty, self.s_short, self.s_medium, self.s_long],
|
| 1541 |
+
self.dtype)
|
| 1542 |
+
|
| 1543 |
+
def get_view(self, a):
|
| 1544 |
+
# Cannot view a StringDType as anything else directly, since
|
| 1545 |
+
# it has references. So, we use a stride trick hack.
|
| 1546 |
+
from numpy.lib._stride_tricks_impl import DummyArray
|
| 1547 |
+
interface = dict(a.__array_interface__)
|
| 1548 |
+
interface['descr'] = self.view_dtype.descr
|
| 1549 |
+
interface['typestr'] = self.view_dtype.str
|
| 1550 |
+
return np.asarray(DummyArray(interface, base=a))
|
| 1551 |
+
|
| 1552 |
+
def get_flags(self, a):
|
| 1553 |
+
return self.get_view(a)['size_and_flags'] & 0xf0
|
| 1554 |
+
|
| 1555 |
+
def is_short(self, a):
|
| 1556 |
+
return self.get_flags(a) == self.INITIALIZED | self.OUTSIDE_ARENA
|
| 1557 |
+
|
| 1558 |
+
def is_on_heap(self, a):
|
| 1559 |
+
return self.get_flags(a) == (self.INITIALIZED
|
| 1560 |
+
| self.OUTSIDE_ARENA
|
| 1561 |
+
| self.LONG)
|
| 1562 |
+
|
| 1563 |
+
def is_missing(self, a):
|
| 1564 |
+
return self.get_flags(a) & self.MISSING == self.MISSING
|
| 1565 |
+
|
| 1566 |
+
def in_arena(self, a):
|
| 1567 |
+
return (self.get_flags(a) & (self.INITIALIZED | self.OUTSIDE_ARENA)
|
| 1568 |
+
== self.INITIALIZED)
|
| 1569 |
+
|
| 1570 |
+
def test_setup(self):
|
| 1571 |
+
is_short = self.is_short(self.a)
|
| 1572 |
+
length = np.strings.str_len(self.a)
|
| 1573 |
+
assert_array_equal(is_short, (length > 0) & (length <= 15))
|
| 1574 |
+
assert_array_equal(self.in_arena(self.a), [False, False, True, True])
|
| 1575 |
+
assert_array_equal(self.is_on_heap(self.a), False)
|
| 1576 |
+
assert_array_equal(self.is_missing(self.a), False)
|
| 1577 |
+
view = self.get_view(self.a)
|
| 1578 |
+
sizes = np.where(is_short, view['size_and_flags'] & 0xf,
|
| 1579 |
+
view['size'])
|
| 1580 |
+
assert_array_equal(sizes, np.strings.str_len(self.a))
|
| 1581 |
+
assert_array_equal(view['xsiz'][2:],
|
| 1582 |
+
np.void(b'\x00' * (self.sizeofstr // 4 - 1)))
|
| 1583 |
+
# Check that the medium string uses only 1 byte for its length
|
| 1584 |
+
# in the arena, while the long string takes 8 (or 4).
|
| 1585 |
+
offsets = view['offset']
|
| 1586 |
+
assert offsets[2] == 1
|
| 1587 |
+
assert offsets[3] == 1 + len(self.s_medium) + self.sizeofstr // 2
|
| 1588 |
+
|
| 1589 |
+
def test_empty(self):
|
| 1590 |
+
e = np.empty((3,), self.dtype)
|
| 1591 |
+
assert_array_equal(self.get_flags(e), 0)
|
| 1592 |
+
assert_array_equal(e, "")
|
| 1593 |
+
|
| 1594 |
+
def test_zeros(self):
|
| 1595 |
+
z = np.zeros((2,), self.dtype)
|
| 1596 |
+
assert_array_equal(self.get_flags(z), 0)
|
| 1597 |
+
assert_array_equal(z, "")
|
| 1598 |
+
|
| 1599 |
+
def test_copy(self):
|
| 1600 |
+
c = self.a.copy()
|
| 1601 |
+
assert_array_equal(self.get_flags(c), self.get_flags(self.a))
|
| 1602 |
+
assert_array_equal(c, self.a)
|
| 1603 |
+
offsets = self.get_view(c)['offset']
|
| 1604 |
+
assert offsets[2] == 1
|
| 1605 |
+
assert offsets[3] == 1 + len(self.s_medium) + self.sizeofstr // 2
|
| 1606 |
+
|
| 1607 |
+
def test_arena_use_with_setting(self):
|
| 1608 |
+
c = np.zeros_like(self.a)
|
| 1609 |
+
assert_array_equal(self.get_flags(c), 0)
|
| 1610 |
+
c[:] = self.a
|
| 1611 |
+
assert_array_equal(self.get_flags(c), self.get_flags(self.a))
|
| 1612 |
+
assert_array_equal(c, self.a)
|
| 1613 |
+
|
| 1614 |
+
def test_arena_reuse_with_setting(self):
|
| 1615 |
+
c = self.a.copy()
|
| 1616 |
+
c[:] = self.a
|
| 1617 |
+
assert_array_equal(self.get_flags(c), self.get_flags(self.a))
|
| 1618 |
+
assert_array_equal(c, self.a)
|
| 1619 |
+
|
| 1620 |
+
def test_arena_reuse_after_missing(self):
|
| 1621 |
+
c = self.a.copy()
|
| 1622 |
+
c[:] = np.nan
|
| 1623 |
+
assert np.all(self.is_missing(c))
|
| 1624 |
+
# Replacing with the original strings, the arena should be reused.
|
| 1625 |
+
c[:] = self.a
|
| 1626 |
+
assert_array_equal(self.get_flags(c), self.get_flags(self.a))
|
| 1627 |
+
assert_array_equal(c, self.a)
|
| 1628 |
+
|
| 1629 |
+
def test_arena_reuse_after_empty(self):
|
| 1630 |
+
c = self.a.copy()
|
| 1631 |
+
c[:] = ""
|
| 1632 |
+
assert_array_equal(c, "")
|
| 1633 |
+
# Replacing with the original strings, the arena should be reused.
|
| 1634 |
+
c[:] = self.a
|
| 1635 |
+
assert_array_equal(self.get_flags(c), self.get_flags(self.a))
|
| 1636 |
+
assert_array_equal(c, self.a)
|
| 1637 |
+
|
| 1638 |
+
def test_arena_reuse_for_shorter(self):
|
| 1639 |
+
c = self.a.copy()
|
| 1640 |
+
# A string slightly shorter than the shortest in the arena
|
| 1641 |
+
# should be used for all strings in the arena.
|
| 1642 |
+
c[:] = self.s_medium[:-1]
|
| 1643 |
+
assert_array_equal(c, self.s_medium[:-1])
|
| 1644 |
+
# first empty string in original was never initialized, so
|
| 1645 |
+
# filling it in now leaves it initialized inside the arena.
|
| 1646 |
+
# second string started as a short string so it can never live
|
| 1647 |
+
# in the arena.
|
| 1648 |
+
in_arena = np.array([True, False, True, True])
|
| 1649 |
+
assert_array_equal(self.in_arena(c), in_arena)
|
| 1650 |
+
# But when a short string is replaced, it will go on the heap.
|
| 1651 |
+
assert_array_equal(self.is_short(c), False)
|
| 1652 |
+
assert_array_equal(self.is_on_heap(c), ~in_arena)
|
| 1653 |
+
# We can put the originals back, and they'll still fit,
|
| 1654 |
+
# and short strings are back as short strings
|
| 1655 |
+
c[:] = self.a
|
| 1656 |
+
assert_array_equal(c, self.a)
|
| 1657 |
+
assert_array_equal(self.in_arena(c), in_arena)
|
| 1658 |
+
assert_array_equal(self.is_short(c), self.is_short(self.a))
|
| 1659 |
+
assert_array_equal(self.is_on_heap(c), False)
|
| 1660 |
+
|
| 1661 |
+
def test_arena_reuse_if_possible(self):
|
| 1662 |
+
c = self.a.copy()
|
| 1663 |
+
# A slightly longer string will not fit in the arena for
|
| 1664 |
+
# the medium string, but will fit for the longer one.
|
| 1665 |
+
c[:] = self.s_medium + "±"
|
| 1666 |
+
assert_array_equal(c, self.s_medium + "±")
|
| 1667 |
+
in_arena_exp = np.strings.str_len(self.a) >= len(self.s_medium) + 1
|
| 1668 |
+
# first entry started uninitialized and empty, so filling it leaves
|
| 1669 |
+
# it in the arena
|
| 1670 |
+
in_arena_exp[0] = True
|
| 1671 |
+
assert not np.all(in_arena_exp == self.in_arena(self.a))
|
| 1672 |
+
assert_array_equal(self.in_arena(c), in_arena_exp)
|
| 1673 |
+
assert_array_equal(self.is_short(c), False)
|
| 1674 |
+
assert_array_equal(self.is_on_heap(c), ~in_arena_exp)
|
| 1675 |
+
# And once outside arena, it stays outside, since offset is lost.
|
| 1676 |
+
# But short strings are used again.
|
| 1677 |
+
c[:] = self.a
|
| 1678 |
+
is_short_exp = self.is_short(self.a)
|
| 1679 |
+
assert_array_equal(c, self.a)
|
| 1680 |
+
assert_array_equal(self.in_arena(c), in_arena_exp)
|
| 1681 |
+
assert_array_equal(self.is_short(c), is_short_exp)
|
| 1682 |
+
assert_array_equal(self.is_on_heap(c), ~in_arena_exp & ~is_short_exp)
|
| 1683 |
+
|
| 1684 |
+
def test_arena_no_reuse_after_short(self):
|
| 1685 |
+
c = self.a.copy()
|
| 1686 |
+
# If we replace a string with a short string, it cannot
|
| 1687 |
+
# go into the arena after because the offset is lost.
|
| 1688 |
+
c[:] = self.s_short
|
| 1689 |
+
assert_array_equal(c, self.s_short)
|
| 1690 |
+
assert_array_equal(self.in_arena(c), False)
|
| 1691 |
+
c[:] = self.a
|
| 1692 |
+
assert_array_equal(c, self.a)
|
| 1693 |
+
assert_array_equal(self.in_arena(c), False)
|
| 1694 |
+
assert_array_equal(self.is_on_heap(c), self.in_arena(self.a))
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/test_strings.py
ADDED
|
@@ -0,0 +1,1205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import operator
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from numpy.testing import assert_array_equal, assert_raises, IS_PYPY
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
COMPARISONS = [
|
| 11 |
+
(operator.eq, np.equal, "=="),
|
| 12 |
+
(operator.ne, np.not_equal, "!="),
|
| 13 |
+
(operator.lt, np.less, "<"),
|
| 14 |
+
(operator.le, np.less_equal, "<="),
|
| 15 |
+
(operator.gt, np.greater, ">"),
|
| 16 |
+
(operator.ge, np.greater_equal, ">="),
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
MAX = np.iinfo(np.int64).max
|
| 20 |
+
|
| 21 |
+
IS_PYPY_LT_7_3_16 = IS_PYPY and sys.implementation.version < (7, 3, 16)
|
| 22 |
+
|
| 23 |
+
@pytest.mark.parametrize(["op", "ufunc", "sym"], COMPARISONS)
|
| 24 |
+
def test_mixed_string_comparison_ufuncs_fail(op, ufunc, sym):
|
| 25 |
+
arr_string = np.array(["a", "b"], dtype="S")
|
| 26 |
+
arr_unicode = np.array(["a", "c"], dtype="U")
|
| 27 |
+
|
| 28 |
+
with pytest.raises(TypeError, match="did not contain a loop"):
|
| 29 |
+
ufunc(arr_string, arr_unicode)
|
| 30 |
+
|
| 31 |
+
with pytest.raises(TypeError, match="did not contain a loop"):
|
| 32 |
+
ufunc(arr_unicode, arr_string)
|
| 33 |
+
|
| 34 |
+
@pytest.mark.parametrize(["op", "ufunc", "sym"], COMPARISONS)
|
| 35 |
+
def test_mixed_string_comparisons_ufuncs_with_cast(op, ufunc, sym):
|
| 36 |
+
arr_string = np.array(["a", "b"], dtype="S")
|
| 37 |
+
arr_unicode = np.array(["a", "c"], dtype="U")
|
| 38 |
+
|
| 39 |
+
# While there is no loop, manual casting is acceptable:
|
| 40 |
+
res1 = ufunc(arr_string, arr_unicode, signature="UU->?", casting="unsafe")
|
| 41 |
+
res2 = ufunc(arr_string, arr_unicode, signature="SS->?", casting="unsafe")
|
| 42 |
+
|
| 43 |
+
expected = op(arr_string.astype("U"), arr_unicode)
|
| 44 |
+
assert_array_equal(res1, expected)
|
| 45 |
+
assert_array_equal(res2, expected)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@pytest.mark.parametrize(["op", "ufunc", "sym"], COMPARISONS)
|
| 49 |
+
@pytest.mark.parametrize("dtypes", [
|
| 50 |
+
("S2", "S2"), ("S2", "S10"),
|
| 51 |
+
("<U1", "<U1"), ("<U1", ">U1"), (">U1", ">U1"),
|
| 52 |
+
("<U1", "<U10"), ("<U1", ">U10")])
|
| 53 |
+
@pytest.mark.parametrize("aligned", [True, False])
|
| 54 |
+
def test_string_comparisons(op, ufunc, sym, dtypes, aligned):
|
| 55 |
+
# ensure native byte-order for the first view to stay within unicode range
|
| 56 |
+
native_dt = np.dtype(dtypes[0]).newbyteorder("=")
|
| 57 |
+
arr = np.arange(2**15).view(native_dt).astype(dtypes[0])
|
| 58 |
+
if not aligned:
|
| 59 |
+
# Make `arr` unaligned:
|
| 60 |
+
new = np.zeros(arr.nbytes + 1, dtype=np.uint8)[1:].view(dtypes[0])
|
| 61 |
+
new[...] = arr
|
| 62 |
+
arr = new
|
| 63 |
+
|
| 64 |
+
arr2 = arr.astype(dtypes[1], copy=True)
|
| 65 |
+
np.random.shuffle(arr2)
|
| 66 |
+
arr[0] = arr2[0] # make sure one matches
|
| 67 |
+
|
| 68 |
+
expected = [op(d1, d2) for d1, d2 in zip(arr.tolist(), arr2.tolist())]
|
| 69 |
+
assert_array_equal(op(arr, arr2), expected)
|
| 70 |
+
assert_array_equal(ufunc(arr, arr2), expected)
|
| 71 |
+
assert_array_equal(
|
| 72 |
+
np.char.compare_chararrays(arr, arr2, sym, False), expected
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
expected = [op(d2, d1) for d1, d2 in zip(arr.tolist(), arr2.tolist())]
|
| 76 |
+
assert_array_equal(op(arr2, arr), expected)
|
| 77 |
+
assert_array_equal(ufunc(arr2, arr), expected)
|
| 78 |
+
assert_array_equal(
|
| 79 |
+
np.char.compare_chararrays(arr2, arr, sym, False), expected
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@pytest.mark.parametrize(["op", "ufunc", "sym"], COMPARISONS)
|
| 84 |
+
@pytest.mark.parametrize("dtypes", [
|
| 85 |
+
("S2", "S2"), ("S2", "S10"), ("<U1", "<U1"), ("<U1", ">U10")])
|
| 86 |
+
def test_string_comparisons_empty(op, ufunc, sym, dtypes):
|
| 87 |
+
arr = np.empty((1, 0, 1, 5), dtype=dtypes[0])
|
| 88 |
+
arr2 = np.empty((100, 1, 0, 1), dtype=dtypes[1])
|
| 89 |
+
|
| 90 |
+
expected = np.empty(np.broadcast_shapes(arr.shape, arr2.shape), dtype=bool)
|
| 91 |
+
assert_array_equal(op(arr, arr2), expected)
|
| 92 |
+
assert_array_equal(ufunc(arr, arr2), expected)
|
| 93 |
+
assert_array_equal(
|
| 94 |
+
np.char.compare_chararrays(arr, arr2, sym, False), expected
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@pytest.mark.parametrize("str_dt", ["S", "U"])
|
| 99 |
+
@pytest.mark.parametrize("float_dt", np.typecodes["AllFloat"])
|
| 100 |
+
def test_float_to_string_cast(str_dt, float_dt):
|
| 101 |
+
float_dt = np.dtype(float_dt)
|
| 102 |
+
fi = np.finfo(float_dt)
|
| 103 |
+
arr = np.array([np.nan, np.inf, -np.inf, fi.max, fi.min], dtype=float_dt)
|
| 104 |
+
expected = ["nan", "inf", "-inf", str(fi.max), str(fi.min)]
|
| 105 |
+
if float_dt.kind == "c":
|
| 106 |
+
expected = [f"({r}+0j)" for r in expected]
|
| 107 |
+
|
| 108 |
+
res = arr.astype(str_dt)
|
| 109 |
+
assert_array_equal(res, np.array(expected, dtype=str_dt))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@pytest.mark.parametrize("dt", ["S", "U", "T"])
|
| 113 |
+
class TestMethods:
|
| 114 |
+
|
| 115 |
+
@pytest.mark.parametrize("in1,in2,out", [
|
| 116 |
+
("", "", ""),
|
| 117 |
+
("abc", "abc", "abcabc"),
|
| 118 |
+
("12345", "12345", "1234512345"),
|
| 119 |
+
("MixedCase", "MixedCase", "MixedCaseMixedCase"),
|
| 120 |
+
("12345 \0 ", "12345 \0 ", "12345 \0 12345 \0 "),
|
| 121 |
+
("UPPER", "UPPER", "UPPERUPPER"),
|
| 122 |
+
(["abc", "def"], ["hello", "world"], ["abchello", "defworld"]),
|
| 123 |
+
])
|
| 124 |
+
def test_add(self, in1, in2, out, dt):
|
| 125 |
+
in1 = np.array(in1, dtype=dt)
|
| 126 |
+
in2 = np.array(in2, dtype=dt)
|
| 127 |
+
out = np.array(out, dtype=dt)
|
| 128 |
+
assert_array_equal(np.strings.add(in1, in2), out)
|
| 129 |
+
|
| 130 |
+
@pytest.mark.parametrize("in1,in2,out", [
|
| 131 |
+
("abc", 3, "abcabcabc"),
|
| 132 |
+
("abc", 0, ""),
|
| 133 |
+
("abc", -1, ""),
|
| 134 |
+
(["abc", "def"], [1, 4], ["abc", "defdefdefdef"]),
|
| 135 |
+
])
|
| 136 |
+
def test_multiply(self, in1, in2, out, dt):
|
| 137 |
+
in1 = np.array(in1, dtype=dt)
|
| 138 |
+
out = np.array(out, dtype=dt)
|
| 139 |
+
assert_array_equal(np.strings.multiply(in1, in2), out)
|
| 140 |
+
|
| 141 |
+
def test_multiply_raises(self, dt):
|
| 142 |
+
with pytest.raises(TypeError, match="unsupported type"):
|
| 143 |
+
np.strings.multiply(np.array("abc", dtype=dt), 3.14)
|
| 144 |
+
|
| 145 |
+
with pytest.raises(MemoryError):
|
| 146 |
+
np.strings.multiply(np.array("abc", dtype=dt), sys.maxsize)
|
| 147 |
+
|
| 148 |
+
@pytest.mark.parametrize("i_dt", [np.int8, np.int16, np.int32,
|
| 149 |
+
np.int64, np.int_])
|
| 150 |
+
def test_multiply_integer_dtypes(self, i_dt, dt):
|
| 151 |
+
a = np.array("abc", dtype=dt)
|
| 152 |
+
i = np.array(3, dtype=i_dt)
|
| 153 |
+
res = np.array("abcabcabc", dtype=dt)
|
| 154 |
+
assert_array_equal(np.strings.multiply(a, i), res)
|
| 155 |
+
|
| 156 |
+
@pytest.mark.parametrize("in_,out", [
|
| 157 |
+
("", False),
|
| 158 |
+
("a", True),
|
| 159 |
+
("A", True),
|
| 160 |
+
("\n", False),
|
| 161 |
+
("abc", True),
|
| 162 |
+
("aBc123", False),
|
| 163 |
+
("abc\n", False),
|
| 164 |
+
(["abc", "aBc123"], [True, False]),
|
| 165 |
+
])
|
| 166 |
+
def test_isalpha(self, in_, out, dt):
|
| 167 |
+
in_ = np.array(in_, dtype=dt)
|
| 168 |
+
assert_array_equal(np.strings.isalpha(in_), out)
|
| 169 |
+
|
| 170 |
+
@pytest.mark.parametrize("in_,out", [
|
| 171 |
+
('', False),
|
| 172 |
+
('a', True),
|
| 173 |
+
('A', True),
|
| 174 |
+
('\n', False),
|
| 175 |
+
('123abc456', True),
|
| 176 |
+
('a1b3c', True),
|
| 177 |
+
('aBc000 ', False),
|
| 178 |
+
('abc\n', False),
|
| 179 |
+
])
|
| 180 |
+
def test_isalnum(self, in_, out, dt):
|
| 181 |
+
in_ = np.array(in_, dtype=dt)
|
| 182 |
+
assert_array_equal(np.strings.isalnum(in_), out)
|
| 183 |
+
|
| 184 |
+
@pytest.mark.parametrize("in_,out", [
|
| 185 |
+
("", False),
|
| 186 |
+
("a", False),
|
| 187 |
+
("0", True),
|
| 188 |
+
("012345", True),
|
| 189 |
+
("012345a", False),
|
| 190 |
+
(["a", "012345"], [False, True]),
|
| 191 |
+
])
|
| 192 |
+
def test_isdigit(self, in_, out, dt):
|
| 193 |
+
in_ = np.array(in_, dtype=dt)
|
| 194 |
+
assert_array_equal(np.strings.isdigit(in_), out)
|
| 195 |
+
|
| 196 |
+
@pytest.mark.parametrize("in_,out", [
|
| 197 |
+
("", False),
|
| 198 |
+
("a", False),
|
| 199 |
+
("1", False),
|
| 200 |
+
(" ", True),
|
| 201 |
+
("\t", True),
|
| 202 |
+
("\r", True),
|
| 203 |
+
("\n", True),
|
| 204 |
+
(" \t\r \n", True),
|
| 205 |
+
(" \t\r\na", False),
|
| 206 |
+
(["\t1", " \t\r \n"], [False, True])
|
| 207 |
+
])
|
| 208 |
+
def test_isspace(self, in_, out, dt):
|
| 209 |
+
in_ = np.array(in_, dtype=dt)
|
| 210 |
+
assert_array_equal(np.strings.isspace(in_), out)
|
| 211 |
+
|
| 212 |
+
@pytest.mark.parametrize("in_,out", [
|
| 213 |
+
('', False),
|
| 214 |
+
('a', True),
|
| 215 |
+
('A', False),
|
| 216 |
+
('\n', False),
|
| 217 |
+
('abc', True),
|
| 218 |
+
('aBc', False),
|
| 219 |
+
('abc\n', True),
|
| 220 |
+
])
|
| 221 |
+
def test_islower(self, in_, out, dt):
|
| 222 |
+
in_ = np.array(in_, dtype=dt)
|
| 223 |
+
assert_array_equal(np.strings.islower(in_), out)
|
| 224 |
+
|
| 225 |
+
@pytest.mark.parametrize("in_,out", [
|
| 226 |
+
('', False),
|
| 227 |
+
('a', False),
|
| 228 |
+
('A', True),
|
| 229 |
+
('\n', False),
|
| 230 |
+
('ABC', True),
|
| 231 |
+
('AbC', False),
|
| 232 |
+
('ABC\n', True),
|
| 233 |
+
])
|
| 234 |
+
def test_isupper(self, in_, out, dt):
|
| 235 |
+
in_ = np.array(in_, dtype=dt)
|
| 236 |
+
assert_array_equal(np.strings.isupper(in_), out)
|
| 237 |
+
|
| 238 |
+
@pytest.mark.parametrize("in_,out", [
|
| 239 |
+
('', False),
|
| 240 |
+
('a', False),
|
| 241 |
+
('A', True),
|
| 242 |
+
('\n', False),
|
| 243 |
+
('A Titlecased Line', True),
|
| 244 |
+
('A\nTitlecased Line', True),
|
| 245 |
+
('A Titlecased, Line', True),
|
| 246 |
+
('Not a capitalized String', False),
|
| 247 |
+
('Not\ta Titlecase String', False),
|
| 248 |
+
('Not--a Titlecase String', False),
|
| 249 |
+
('NOT', False),
|
| 250 |
+
])
|
| 251 |
+
def test_istitle(self, in_, out, dt):
|
| 252 |
+
in_ = np.array(in_, dtype=dt)
|
| 253 |
+
assert_array_equal(np.strings.istitle(in_), out)
|
| 254 |
+
|
| 255 |
+
@pytest.mark.parametrize("in_,out", [
|
| 256 |
+
("", 0),
|
| 257 |
+
("abc", 3),
|
| 258 |
+
("12345", 5),
|
| 259 |
+
("MixedCase", 9),
|
| 260 |
+
("12345 \x00 ", 8),
|
| 261 |
+
("UPPER", 5),
|
| 262 |
+
(["abc", "12345 \x00 "], [3, 8]),
|
| 263 |
+
])
|
| 264 |
+
def test_str_len(self, in_, out, dt):
|
| 265 |
+
in_ = np.array(in_, dtype=dt)
|
| 266 |
+
assert_array_equal(np.strings.str_len(in_), out)
|
| 267 |
+
|
| 268 |
+
@pytest.mark.parametrize("a,sub,start,end,out", [
|
| 269 |
+
("abcdefghiabc", "abc", 0, None, 0),
|
| 270 |
+
("abcdefghiabc", "abc", 1, None, 9),
|
| 271 |
+
("abcdefghiabc", "def", 4, None, -1),
|
| 272 |
+
("abc", "", 0, None, 0),
|
| 273 |
+
("abc", "", 3, None, 3),
|
| 274 |
+
("abc", "", 4, None, -1),
|
| 275 |
+
("rrarrrrrrrrra", "a", 0, None, 2),
|
| 276 |
+
("rrarrrrrrrrra", "a", 4, None, 12),
|
| 277 |
+
("rrarrrrrrrrra", "a", 4, 6, -1),
|
| 278 |
+
("", "", 0, None, 0),
|
| 279 |
+
("", "", 1, 1, -1),
|
| 280 |
+
("", "", MAX, 0, -1),
|
| 281 |
+
("", "xx", 0, None, -1),
|
| 282 |
+
("", "xx", 1, 1, -1),
|
| 283 |
+
("", "xx", MAX, 0, -1),
|
| 284 |
+
pytest.param(99*"a" + "b", "b", 0, None, 99,
|
| 285 |
+
id="99*a+b-b-0-None-99"),
|
| 286 |
+
pytest.param(98*"a" + "ba", "ba", 0, None, 98,
|
| 287 |
+
id="98*a+ba-ba-0-None-98"),
|
| 288 |
+
pytest.param(100*"a", "b", 0, None, -1,
|
| 289 |
+
id="100*a-b-0-None--1"),
|
| 290 |
+
pytest.param(30000*"a" + 100*"b", 100*"b", 0, None, 30000,
|
| 291 |
+
id="30000*a+100*b-100*b-0-None-30000"),
|
| 292 |
+
pytest.param(30000*"a", 100*"b", 0, None, -1,
|
| 293 |
+
id="30000*a-100*b-0-None--1"),
|
| 294 |
+
pytest.param(15000*"a" + 15000*"b", 15000*"b", 0, None, 15000,
|
| 295 |
+
id="15000*a+15000*b-15000*b-0-None-15000"),
|
| 296 |
+
pytest.param(15000*"a" + 15000*"b", 15000*"c", 0, None, -1,
|
| 297 |
+
id="15000*a+15000*b-15000*c-0-None--1"),
|
| 298 |
+
(["abcdefghiabc", "rrarrrrrrrrra"], ["def", "arr"], [0, 3],
|
| 299 |
+
None, [3, -1]),
|
| 300 |
+
("Ae¢☃€ 😊" * 2, "😊", 0, None, 6),
|
| 301 |
+
("Ae¢☃€ 😊" * 2, "😊", 7, None, 13),
|
| 302 |
+
])
|
| 303 |
+
def test_find(self, a, sub, start, end, out, dt):
|
| 304 |
+
if "😊" in a and dt == "S":
|
| 305 |
+
pytest.skip("Bytes dtype does not support non-ascii input")
|
| 306 |
+
a = np.array(a, dtype=dt)
|
| 307 |
+
sub = np.array(sub, dtype=dt)
|
| 308 |
+
assert_array_equal(np.strings.find(a, sub, start, end), out)
|
| 309 |
+
|
| 310 |
+
@pytest.mark.parametrize("a,sub,start,end,out", [
|
| 311 |
+
("abcdefghiabc", "abc", 0, None, 9),
|
| 312 |
+
("abcdefghiabc", "", 0, None, 12),
|
| 313 |
+
("abcdefghiabc", "abcd", 0, None, 0),
|
| 314 |
+
("abcdefghiabc", "abcz", 0, None, -1),
|
| 315 |
+
("abc", "", 0, None, 3),
|
| 316 |
+
("abc", "", 3, None, 3),
|
| 317 |
+
("abc", "", 4, None, -1),
|
| 318 |
+
("rrarrrrrrrrra", "a", 0, None, 12),
|
| 319 |
+
("rrarrrrrrrrra", "a", 4, None, 12),
|
| 320 |
+
("rrarrrrrrrrra", "a", 4, 6, -1),
|
| 321 |
+
(["abcdefghiabc", "rrarrrrrrrrra"], ["abc", "a"], [0, 0],
|
| 322 |
+
None, [9, 12]),
|
| 323 |
+
("Ae¢☃€ 😊" * 2, "😊", 0, None, 13),
|
| 324 |
+
("Ae¢☃€ 😊" * 2, "😊", 0, 7, 6),
|
| 325 |
+
])
|
| 326 |
+
def test_rfind(self, a, sub, start, end, out, dt):
|
| 327 |
+
if "😊" in a and dt == "S":
|
| 328 |
+
pytest.skip("Bytes dtype does not support non-ascii input")
|
| 329 |
+
a = np.array(a, dtype=dt)
|
| 330 |
+
sub = np.array(sub, dtype=dt)
|
| 331 |
+
assert_array_equal(np.strings.rfind(a, sub, start, end), out)
|
| 332 |
+
|
| 333 |
+
@pytest.mark.parametrize("a,sub,start,end,out", [
|
| 334 |
+
("aaa", "a", 0, None, 3),
|
| 335 |
+
("aaa", "b", 0, None, 0),
|
| 336 |
+
("aaa", "a", 1, None, 2),
|
| 337 |
+
("aaa", "a", 10, None, 0),
|
| 338 |
+
("aaa", "a", -1, None, 1),
|
| 339 |
+
("aaa", "a", -10, None, 3),
|
| 340 |
+
("aaa", "a", 0, 1, 1),
|
| 341 |
+
("aaa", "a", 0, 10, 3),
|
| 342 |
+
("aaa", "a", 0, -1, 2),
|
| 343 |
+
("aaa", "a", 0, -10, 0),
|
| 344 |
+
("aaa", "", 1, None, 3),
|
| 345 |
+
("aaa", "", 3, None, 1),
|
| 346 |
+
("aaa", "", 10, None, 0),
|
| 347 |
+
("aaa", "", -1, None, 2),
|
| 348 |
+
("aaa", "", -10, None, 4),
|
| 349 |
+
("aaa", "aaaa", 0, None, 0),
|
| 350 |
+
pytest.param(98*"a" + "ba", "ba", 0, None, 1,
|
| 351 |
+
id="98*a+ba-ba-0-None-1"),
|
| 352 |
+
pytest.param(30000*"a" + 100*"b", 100*"b", 0, None, 1,
|
| 353 |
+
id="30000*a+100*b-100*b-0-None-1"),
|
| 354 |
+
pytest.param(30000*"a", 100*"b", 0, None, 0,
|
| 355 |
+
id="30000*a-100*b-0-None-0"),
|
| 356 |
+
pytest.param(30000*"a" + 100*"ab", "ab", 0, None, 100,
|
| 357 |
+
id="30000*a+100*ab-ab-0-None-100"),
|
| 358 |
+
pytest.param(15000*"a" + 15000*"b", 15000*"b", 0, None, 1,
|
| 359 |
+
id="15000*a+15000*b-15000*b-0-None-1"),
|
| 360 |
+
pytest.param(15000*"a" + 15000*"b", 15000*"c", 0, None, 0,
|
| 361 |
+
id="15000*a+15000*b-15000*c-0-None-0"),
|
| 362 |
+
("", "", 0, None, 1),
|
| 363 |
+
("", "", 1, 1, 0),
|
| 364 |
+
("", "", MAX, 0, 0),
|
| 365 |
+
("", "xx", 0, None, 0),
|
| 366 |
+
("", "xx", 1, 1, 0),
|
| 367 |
+
("", "xx", MAX, 0, 0),
|
| 368 |
+
(["aaa", ""], ["a", ""], [0, 0], None, [3, 1]),
|
| 369 |
+
("Ae¢☃€ 😊" * 100, "😊", 0, None, 100),
|
| 370 |
+
])
|
| 371 |
+
def test_count(self, a, sub, start, end, out, dt):
|
| 372 |
+
if "😊" in a and dt == "S":
|
| 373 |
+
pytest.skip("Bytes dtype does not support non-ascii input")
|
| 374 |
+
a = np.array(a, dtype=dt)
|
| 375 |
+
sub = np.array(sub, dtype=dt)
|
| 376 |
+
assert_array_equal(np.strings.count(a, sub, start, end), out)
|
| 377 |
+
|
| 378 |
+
@pytest.mark.parametrize("a,prefix,start,end,out", [
|
| 379 |
+
("hello", "he", 0, None, True),
|
| 380 |
+
("hello", "hello", 0, None, True),
|
| 381 |
+
("hello", "hello world", 0, None, False),
|
| 382 |
+
("hello", "", 0, None, True),
|
| 383 |
+
("hello", "ello", 0, None, False),
|
| 384 |
+
("hello", "ello", 1, None, True),
|
| 385 |
+
("hello", "o", 4, None, True),
|
| 386 |
+
("hello", "o", 5, None, False),
|
| 387 |
+
("hello", "", 5, None, True),
|
| 388 |
+
("hello", "lo", 6, None, False),
|
| 389 |
+
("helloworld", "lowo", 3, None, True),
|
| 390 |
+
("helloworld", "lowo", 3, 7, True),
|
| 391 |
+
("helloworld", "lowo", 3, 6, False),
|
| 392 |
+
("", "", 0, 1, True),
|
| 393 |
+
("", "", 0, 0, True),
|
| 394 |
+
("", "", 1, 0, False),
|
| 395 |
+
("hello", "he", 0, -1, True),
|
| 396 |
+
("hello", "he", -53, -1, True),
|
| 397 |
+
("hello", "hello", 0, -1, False),
|
| 398 |
+
("hello", "hello world", -1, -10, False),
|
| 399 |
+
("hello", "ello", -5, None, False),
|
| 400 |
+
("hello", "ello", -4, None, True),
|
| 401 |
+
("hello", "o", -2, None, False),
|
| 402 |
+
("hello", "o", -1, None, True),
|
| 403 |
+
("hello", "", -3, -3, True),
|
| 404 |
+
("hello", "lo", -9, None, False),
|
| 405 |
+
(["hello", ""], ["he", ""], [0, 0], None, [True, True]),
|
| 406 |
+
])
|
| 407 |
+
def test_startswith(self, a, prefix, start, end, out, dt):
|
| 408 |
+
a = np.array(a, dtype=dt)
|
| 409 |
+
prefix = np.array(prefix, dtype=dt)
|
| 410 |
+
assert_array_equal(np.strings.startswith(a, prefix, start, end), out)
|
| 411 |
+
|
| 412 |
+
@pytest.mark.parametrize("a,suffix,start,end,out", [
|
| 413 |
+
("hello", "lo", 0, None, True),
|
| 414 |
+
("hello", "he", 0, None, False),
|
| 415 |
+
("hello", "", 0, None, True),
|
| 416 |
+
("hello", "hello world", 0, None, False),
|
| 417 |
+
("helloworld", "worl", 0, None, False),
|
| 418 |
+
("helloworld", "worl", 3, 9, True),
|
| 419 |
+
("helloworld", "world", 3, 12, True),
|
| 420 |
+
("helloworld", "lowo", 1, 7, True),
|
| 421 |
+
("helloworld", "lowo", 2, 7, True),
|
| 422 |
+
("helloworld", "lowo", 3, 7, True),
|
| 423 |
+
("helloworld", "lowo", 4, 7, False),
|
| 424 |
+
("helloworld", "lowo", 3, 8, False),
|
| 425 |
+
("ab", "ab", 0, 1, False),
|
| 426 |
+
("ab", "ab", 0, 0, False),
|
| 427 |
+
("", "", 0, 1, True),
|
| 428 |
+
("", "", 0, 0, True),
|
| 429 |
+
("", "", 1, 0, False),
|
| 430 |
+
("hello", "lo", -2, None, True),
|
| 431 |
+
("hello", "he", -2, None, False),
|
| 432 |
+
("hello", "", -3, -3, True),
|
| 433 |
+
("hello", "hello world", -10, -2, False),
|
| 434 |
+
("helloworld", "worl", -6, None, False),
|
| 435 |
+
("helloworld", "worl", -5, -1, True),
|
| 436 |
+
("helloworld", "worl", -5, 9, True),
|
| 437 |
+
("helloworld", "world", -7, 12, True),
|
| 438 |
+
("helloworld", "lowo", -99, -3, True),
|
| 439 |
+
("helloworld", "lowo", -8, -3, True),
|
| 440 |
+
("helloworld", "lowo", -7, -3, True),
|
| 441 |
+
("helloworld", "lowo", 3, -4, False),
|
| 442 |
+
("helloworld", "lowo", -8, -2, False),
|
| 443 |
+
(["hello", "helloworld"], ["lo", "worl"], [0, -6], None,
|
| 444 |
+
[True, False]),
|
| 445 |
+
])
|
| 446 |
+
def test_endswith(self, a, suffix, start, end, out, dt):
|
| 447 |
+
a = np.array(a, dtype=dt)
|
| 448 |
+
suffix = np.array(suffix, dtype=dt)
|
| 449 |
+
assert_array_equal(np.strings.endswith(a, suffix, start, end), out)
|
| 450 |
+
|
| 451 |
+
@pytest.mark.parametrize("a,chars,out", [
|
| 452 |
+
("", None, ""),
|
| 453 |
+
(" hello ", None, "hello "),
|
| 454 |
+
("hello", None, "hello"),
|
| 455 |
+
(" \t\n\r\f\vabc \t\n\r\f\v", None, "abc \t\n\r\f\v"),
|
| 456 |
+
([" hello ", "hello"], None, ["hello ", "hello"]),
|
| 457 |
+
("", "", ""),
|
| 458 |
+
("", "xyz", ""),
|
| 459 |
+
("hello", "", "hello"),
|
| 460 |
+
("xyzzyhelloxyzzy", "xyz", "helloxyzzy"),
|
| 461 |
+
("hello", "xyz", "hello"),
|
| 462 |
+
("xyxz", "xyxz", ""),
|
| 463 |
+
("xyxzx", "x", "yxzx"),
|
| 464 |
+
(["xyzzyhelloxyzzy", "hello"], ["xyz", "xyz"],
|
| 465 |
+
["helloxyzzy", "hello"]),
|
| 466 |
+
(["ba", "ac", "baa", "bba"], "b", ["a", "ac", "aa", "a"]),
|
| 467 |
+
])
|
| 468 |
+
def test_lstrip(self, a, chars, out, dt):
|
| 469 |
+
a = np.array(a, dtype=dt)
|
| 470 |
+
out = np.array(out, dtype=dt)
|
| 471 |
+
if chars is not None:
|
| 472 |
+
chars = np.array(chars, dtype=dt)
|
| 473 |
+
assert_array_equal(np.strings.lstrip(a, chars), out)
|
| 474 |
+
else:
|
| 475 |
+
assert_array_equal(np.strings.lstrip(a), out)
|
| 476 |
+
|
| 477 |
+
@pytest.mark.parametrize("a,chars,out", [
|
| 478 |
+
("", None, ""),
|
| 479 |
+
(" hello ", None, " hello"),
|
| 480 |
+
("hello", None, "hello"),
|
| 481 |
+
(" \t\n\r\f\vabc \t\n\r\f\v", None, " \t\n\r\f\vabc"),
|
| 482 |
+
([" hello ", "hello"], None, [" hello", "hello"]),
|
| 483 |
+
("", "", ""),
|
| 484 |
+
("", "xyz", ""),
|
| 485 |
+
("hello", "", "hello"),
|
| 486 |
+
(["hello ", "abcdefghijklmnop"], None,
|
| 487 |
+
["hello", "abcdefghijklmnop"]),
|
| 488 |
+
("xyzzyhelloxyzzy", "xyz", "xyzzyhello"),
|
| 489 |
+
("hello", "xyz", "hello"),
|
| 490 |
+
("xyxz", "xyxz", ""),
|
| 491 |
+
(" ", None, ""),
|
| 492 |
+
("xyxzx", "x", "xyxz"),
|
| 493 |
+
(["xyzzyhelloxyzzy", "hello"], ["xyz", "xyz"],
|
| 494 |
+
["xyzzyhello", "hello"]),
|
| 495 |
+
(["ab", "ac", "aab", "abb"], "b", ["a", "ac", "aa", "a"]),
|
| 496 |
+
])
|
| 497 |
+
def test_rstrip(self, a, chars, out, dt):
|
| 498 |
+
a = np.array(a, dtype=dt)
|
| 499 |
+
out = np.array(out, dtype=dt)
|
| 500 |
+
if chars is not None:
|
| 501 |
+
chars = np.array(chars, dtype=dt)
|
| 502 |
+
assert_array_equal(np.strings.rstrip(a, chars), out)
|
| 503 |
+
else:
|
| 504 |
+
assert_array_equal(np.strings.rstrip(a), out)
|
| 505 |
+
|
| 506 |
+
@pytest.mark.parametrize("a,chars,out", [
|
| 507 |
+
("", None, ""),
|
| 508 |
+
(" hello ", None, "hello"),
|
| 509 |
+
("hello", None, "hello"),
|
| 510 |
+
(" \t\n\r\f\vabc \t\n\r\f\v", None, "abc"),
|
| 511 |
+
([" hello ", "hello"], None, ["hello", "hello"]),
|
| 512 |
+
("", "", ""),
|
| 513 |
+
("", "xyz", ""),
|
| 514 |
+
("hello", "", "hello"),
|
| 515 |
+
("xyzzyhelloxyzzy", "xyz", "hello"),
|
| 516 |
+
("hello", "xyz", "hello"),
|
| 517 |
+
("xyxz", "xyxz", ""),
|
| 518 |
+
("xyxzx", "x", "yxz"),
|
| 519 |
+
(["xyzzyhelloxyzzy", "hello"], ["xyz", "xyz"],
|
| 520 |
+
["hello", "hello"]),
|
| 521 |
+
(["bab", "ac", "baab", "bbabb"], "b", ["a", "ac", "aa", "a"]),
|
| 522 |
+
])
|
| 523 |
+
def test_strip(self, a, chars, out, dt):
|
| 524 |
+
a = np.array(a, dtype=dt)
|
| 525 |
+
if chars is not None:
|
| 526 |
+
chars = np.array(chars, dtype=dt)
|
| 527 |
+
out = np.array(out, dtype=dt)
|
| 528 |
+
assert_array_equal(np.strings.strip(a, chars), out)
|
| 529 |
+
|
| 530 |
+
@pytest.mark.parametrize("buf,old,new,count,res", [
|
| 531 |
+
("", "", "", -1, ""),
|
| 532 |
+
("", "", "A", -1, "A"),
|
| 533 |
+
("", "A", "", -1, ""),
|
| 534 |
+
("", "A", "A", -1, ""),
|
| 535 |
+
("", "", "", 100, ""),
|
| 536 |
+
("", "", "A", 100, "A"),
|
| 537 |
+
("A", "", "", -1, "A"),
|
| 538 |
+
("A", "", "*", -1, "*A*"),
|
| 539 |
+
("A", "", "*1", -1, "*1A*1"),
|
| 540 |
+
("A", "", "*-#", -1, "*-#A*-#"),
|
| 541 |
+
("AA", "", "*-", -1, "*-A*-A*-"),
|
| 542 |
+
("AA", "", "*-", -1, "*-A*-A*-"),
|
| 543 |
+
("AA", "", "*-", 4, "*-A*-A*-"),
|
| 544 |
+
("AA", "", "*-", 3, "*-A*-A*-"),
|
| 545 |
+
("AA", "", "*-", 2, "*-A*-A"),
|
| 546 |
+
("AA", "", "*-", 1, "*-AA"),
|
| 547 |
+
("AA", "", "*-", 0, "AA"),
|
| 548 |
+
("A", "A", "", -1, ""),
|
| 549 |
+
("AAA", "A", "", -1, ""),
|
| 550 |
+
("AAA", "A", "", -1, ""),
|
| 551 |
+
("AAA", "A", "", 4, ""),
|
| 552 |
+
("AAA", "A", "", 3, ""),
|
| 553 |
+
("AAA", "A", "", 2, "A"),
|
| 554 |
+
("AAA", "A", "", 1, "AA"),
|
| 555 |
+
("AAA", "A", "", 0, "AAA"),
|
| 556 |
+
("AAAAAAAAAA", "A", "", -1, ""),
|
| 557 |
+
("ABACADA", "A", "", -1, "BCD"),
|
| 558 |
+
("ABACADA", "A", "", -1, "BCD"),
|
| 559 |
+
("ABACADA", "A", "", 5, "BCD"),
|
| 560 |
+
("ABACADA", "A", "", 4, "BCD"),
|
| 561 |
+
("ABACADA", "A", "", 3, "BCDA"),
|
| 562 |
+
("ABACADA", "A", "", 2, "BCADA"),
|
| 563 |
+
("ABACADA", "A", "", 1, "BACADA"),
|
| 564 |
+
("ABACADA", "A", "", 0, "ABACADA"),
|
| 565 |
+
("ABCAD", "A", "", -1, "BCD"),
|
| 566 |
+
("ABCADAA", "A", "", -1, "BCD"),
|
| 567 |
+
("BCD", "A", "", -1, "BCD"),
|
| 568 |
+
("*************", "A", "", -1, "*************"),
|
| 569 |
+
("^"+"A"*1000+"^", "A", "", 999, "^A^"),
|
| 570 |
+
("the", "the", "", -1, ""),
|
| 571 |
+
("theater", "the", "", -1, "ater"),
|
| 572 |
+
("thethe", "the", "", -1, ""),
|
| 573 |
+
("thethethethe", "the", "", -1, ""),
|
| 574 |
+
("theatheatheathea", "the", "", -1, "aaaa"),
|
| 575 |
+
("that", "the", "", -1, "that"),
|
| 576 |
+
("thaet", "the", "", -1, "thaet"),
|
| 577 |
+
("here and there", "the", "", -1, "here and re"),
|
| 578 |
+
("here and there and there", "the", "", -1, "here and re and re"),
|
| 579 |
+
("here and there and there", "the", "", 3, "here and re and re"),
|
| 580 |
+
("here and there and there", "the", "", 2, "here and re and re"),
|
| 581 |
+
("here and there and there", "the", "", 1, "here and re and there"),
|
| 582 |
+
("here and there and there", "the", "", 0, "here and there and there"),
|
| 583 |
+
("here and there and there", "the", "", -1, "here and re and re"),
|
| 584 |
+
("abc", "the", "", -1, "abc"),
|
| 585 |
+
("abcdefg", "the", "", -1, "abcdefg"),
|
| 586 |
+
("bbobob", "bob", "", -1, "bob"),
|
| 587 |
+
("bbobobXbbobob", "bob", "", -1, "bobXbob"),
|
| 588 |
+
("aaaaaaabob", "bob", "", -1, "aaaaaaa"),
|
| 589 |
+
("aaaaaaa", "bob", "", -1, "aaaaaaa"),
|
| 590 |
+
("Who goes there?", "o", "o", -1, "Who goes there?"),
|
| 591 |
+
("Who goes there?", "o", "O", -1, "WhO gOes there?"),
|
| 592 |
+
("Who goes there?", "o", "O", -1, "WhO gOes there?"),
|
| 593 |
+
("Who goes there?", "o", "O", 3, "WhO gOes there?"),
|
| 594 |
+
("Who goes there?", "o", "O", 2, "WhO gOes there?"),
|
| 595 |
+
("Who goes there?", "o", "O", 1, "WhO goes there?"),
|
| 596 |
+
("Who goes there?", "o", "O", 0, "Who goes there?"),
|
| 597 |
+
("Who goes there?", "a", "q", -1, "Who goes there?"),
|
| 598 |
+
("Who goes there?", "W", "w", -1, "who goes there?"),
|
| 599 |
+
("WWho goes there?WW", "W", "w", -1, "wwho goes there?ww"),
|
| 600 |
+
("Who goes there?", "?", "!", -1, "Who goes there!"),
|
| 601 |
+
("Who goes there??", "?", "!", -1, "Who goes there!!"),
|
| 602 |
+
("Who goes there?", ".", "!", -1, "Who goes there?"),
|
| 603 |
+
("This is a tissue", "is", "**", -1, "Th** ** a t**sue"),
|
| 604 |
+
("This is a tissue", "is", "**", -1, "Th** ** a t**sue"),
|
| 605 |
+
("This is a tissue", "is", "**", 4, "Th** ** a t**sue"),
|
| 606 |
+
("This is a tissue", "is", "**", 3, "Th** ** a t**sue"),
|
| 607 |
+
("This is a tissue", "is", "**", 2, "Th** ** a tissue"),
|
| 608 |
+
("This is a tissue", "is", "**", 1, "Th** is a tissue"),
|
| 609 |
+
("This is a tissue", "is", "**", 0, "This is a tissue"),
|
| 610 |
+
("bobob", "bob", "cob", -1, "cobob"),
|
| 611 |
+
("bobobXbobobob", "bob", "cob", -1, "cobobXcobocob"),
|
| 612 |
+
("bobob", "bot", "bot", -1, "bobob"),
|
| 613 |
+
("Reykjavik", "k", "KK", -1, "ReyKKjaviKK"),
|
| 614 |
+
("Reykjavik", "k", "KK", -1, "ReyKKjaviKK"),
|
| 615 |
+
("Reykjavik", "k", "KK", 2, "ReyKKjaviKK"),
|
| 616 |
+
("Reykjavik", "k", "KK", 1, "ReyKKjavik"),
|
| 617 |
+
("Reykjavik", "k", "KK", 0, "Reykjavik"),
|
| 618 |
+
("A.B.C.", ".", "----", -1, "A----B----C----"),
|
| 619 |
+
("Reykjavik", "q", "KK", -1, "Reykjavik"),
|
| 620 |
+
("spam, spam, eggs and spam", "spam", "ham", -1,
|
| 621 |
+
"ham, ham, eggs and ham"),
|
| 622 |
+
("spam, spam, eggs and spam", "spam", "ham", -1,
|
| 623 |
+
"ham, ham, eggs and ham"),
|
| 624 |
+
("spam, spam, eggs and spam", "spam", "ham", 4,
|
| 625 |
+
"ham, ham, eggs and ham"),
|
| 626 |
+
("spam, spam, eggs and spam", "spam", "ham", 3,
|
| 627 |
+
"ham, ham, eggs and ham"),
|
| 628 |
+
("spam, spam, eggs and spam", "spam", "ham", 2,
|
| 629 |
+
"ham, ham, eggs and spam"),
|
| 630 |
+
("spam, spam, eggs and spam", "spam", "ham", 1,
|
| 631 |
+
"ham, spam, eggs and spam"),
|
| 632 |
+
("spam, spam, eggs and spam", "spam", "ham", 0,
|
| 633 |
+
"spam, spam, eggs and spam"),
|
| 634 |
+
("bobobob", "bobob", "bob", -1, "bobob"),
|
| 635 |
+
("bobobobXbobobob", "bobob", "bob", -1, "bobobXbobob"),
|
| 636 |
+
("BOBOBOB", "bob", "bobby", -1, "BOBOBOB"),
|
| 637 |
+
("one!two!three!", "!", "@", 1, "one@two!three!"),
|
| 638 |
+
("one!two!three!", "!", "", -1, "onetwothree"),
|
| 639 |
+
("one!two!three!", "!", "@", 2, "one@two@three!"),
|
| 640 |
+
("one!two!three!", "!", "@", 3, "one@two@three@"),
|
| 641 |
+
("one!two!three!", "!", "@", 4, "one@two@three@"),
|
| 642 |
+
("one!two!three!", "!", "@", 0, "one!two!three!"),
|
| 643 |
+
("one!two!three!", "!", "@", -1, "one@two@three@"),
|
| 644 |
+
("one!two!three!", "x", "@", -1, "one!two!three!"),
|
| 645 |
+
("one!two!three!", "x", "@", 2, "one!two!three!"),
|
| 646 |
+
("abc", "", "-", -1, "-a-b-c-"),
|
| 647 |
+
("abc", "", "-", 3, "-a-b-c"),
|
| 648 |
+
("abc", "", "-", 0, "abc"),
|
| 649 |
+
("abc", "ab", "--", 0, "abc"),
|
| 650 |
+
("abc", "xy", "--", -1, "abc"),
|
| 651 |
+
(["abbc", "abbd"], "b", "z", [1, 2], ["azbc", "azzd"]),
|
| 652 |
+
])
|
| 653 |
+
def test_replace(self, buf, old, new, count, res, dt):
|
| 654 |
+
if "😊" in buf and dt == "S":
|
| 655 |
+
pytest.skip("Bytes dtype does not support non-ascii input")
|
| 656 |
+
buf = np.array(buf, dtype=dt)
|
| 657 |
+
old = np.array(old, dtype=dt)
|
| 658 |
+
new = np.array(new, dtype=dt)
|
| 659 |
+
res = np.array(res, dtype=dt)
|
| 660 |
+
assert_array_equal(np.strings.replace(buf, old, new, count), res)
|
| 661 |
+
|
| 662 |
+
@pytest.mark.parametrize("buf,sub,start,end,res", [
|
| 663 |
+
("abcdefghiabc", "", 0, None, 0),
|
| 664 |
+
("abcdefghiabc", "def", 0, None, 3),
|
| 665 |
+
("abcdefghiabc", "abc", 0, None, 0),
|
| 666 |
+
("abcdefghiabc", "abc", 1, None, 9),
|
| 667 |
+
])
|
| 668 |
+
def test_index(self, buf, sub, start, end, res, dt):
|
| 669 |
+
buf = np.array(buf, dtype=dt)
|
| 670 |
+
sub = np.array(sub, dtype=dt)
|
| 671 |
+
assert_array_equal(np.strings.index(buf, sub, start, end), res)
|
| 672 |
+
|
| 673 |
+
@pytest.mark.parametrize("buf,sub,start,end", [
|
| 674 |
+
("abcdefghiabc", "hib", 0, None),
|
| 675 |
+
("abcdefghiab", "abc", 1, None),
|
| 676 |
+
("abcdefghi", "ghi", 8, None),
|
| 677 |
+
("abcdefghi", "ghi", -1, None),
|
| 678 |
+
("rrarrrrrrrrra", "a", 4, 6),
|
| 679 |
+
])
|
| 680 |
+
def test_index_raises(self, buf, sub, start, end, dt):
|
| 681 |
+
buf = np.array(buf, dtype=dt)
|
| 682 |
+
sub = np.array(sub, dtype=dt)
|
| 683 |
+
with pytest.raises(ValueError, match="substring not found"):
|
| 684 |
+
np.strings.index(buf, sub, start, end)
|
| 685 |
+
|
| 686 |
+
@pytest.mark.parametrize("buf,sub,start,end,res", [
|
| 687 |
+
("abcdefghiabc", "", 0, None, 12),
|
| 688 |
+
("abcdefghiabc", "def", 0, None, 3),
|
| 689 |
+
("abcdefghiabc", "abc", 0, None, 9),
|
| 690 |
+
("abcdefghiabc", "abc", 0, -1, 0),
|
| 691 |
+
])
|
| 692 |
+
def test_rindex(self, buf, sub, start, end, res, dt):
|
| 693 |
+
buf = np.array(buf, dtype=dt)
|
| 694 |
+
sub = np.array(sub, dtype=dt)
|
| 695 |
+
assert_array_equal(np.strings.rindex(buf, sub, start, end), res)
|
| 696 |
+
|
| 697 |
+
@pytest.mark.parametrize("buf,sub,start,end", [
|
| 698 |
+
("abcdefghiabc", "hib", 0, None),
|
| 699 |
+
("defghiabc", "def", 1, None),
|
| 700 |
+
("defghiabc", "abc", 0, -1),
|
| 701 |
+
("abcdefghi", "ghi", 0, 8),
|
| 702 |
+
("abcdefghi", "ghi", 0, -1),
|
| 703 |
+
("rrarrrrrrrrra", "a", 4, 6),
|
| 704 |
+
])
|
| 705 |
+
def test_rindex_raises(self, buf, sub, start, end, dt):
|
| 706 |
+
buf = np.array(buf, dtype=dt)
|
| 707 |
+
sub = np.array(sub, dtype=dt)
|
| 708 |
+
with pytest.raises(ValueError, match="substring not found"):
|
| 709 |
+
np.strings.rindex(buf, sub, start, end)
|
| 710 |
+
|
| 711 |
+
@pytest.mark.parametrize("buf,tabsize,res", [
|
| 712 |
+
("abc\rab\tdef\ng\thi", 8, "abc\rab def\ng hi"),
|
| 713 |
+
("abc\rab\tdef\ng\thi", 4, "abc\rab def\ng hi"),
|
| 714 |
+
("abc\r\nab\tdef\ng\thi", 8, "abc\r\nab def\ng hi"),
|
| 715 |
+
("abc\r\nab\tdef\ng\thi", 4, "abc\r\nab def\ng hi"),
|
| 716 |
+
("abc\r\nab\r\ndef\ng\r\nhi", 4, "abc\r\nab\r\ndef\ng\r\nhi"),
|
| 717 |
+
(" \ta\n\tb", 1, " a\n b"),
|
| 718 |
+
])
|
| 719 |
+
def test_expandtabs(self, buf, tabsize, res, dt):
|
| 720 |
+
buf = np.array(buf, dtype=dt)
|
| 721 |
+
res = np.array(res, dtype=dt)
|
| 722 |
+
assert_array_equal(np.strings.expandtabs(buf, tabsize), res)
|
| 723 |
+
|
| 724 |
+
def test_expandtabs_raises_overflow(self, dt):
|
| 725 |
+
with pytest.raises(OverflowError, match="new string is too long"):
|
| 726 |
+
np.strings.expandtabs(np.array("\ta\n\tb", dtype=dt), sys.maxsize)
|
| 727 |
+
np.strings.expandtabs(np.array("\ta\n\tb", dtype=dt), 2**61)
|
| 728 |
+
|
| 729 |
+
FILL_ERROR = "The fill character must be exactly one character long"
|
| 730 |
+
|
| 731 |
+
def test_center_raises_multiple_character_fill(self, dt):
|
| 732 |
+
buf = np.array("abc", dtype=dt)
|
| 733 |
+
fill = np.array("**", dtype=dt)
|
| 734 |
+
with pytest.raises(TypeError, match=self.FILL_ERROR):
|
| 735 |
+
np.strings.center(buf, 10, fill)
|
| 736 |
+
|
| 737 |
+
def test_ljust_raises_multiple_character_fill(self, dt):
|
| 738 |
+
buf = np.array("abc", dtype=dt)
|
| 739 |
+
fill = np.array("**", dtype=dt)
|
| 740 |
+
with pytest.raises(TypeError, match=self.FILL_ERROR):
|
| 741 |
+
np.strings.ljust(buf, 10, fill)
|
| 742 |
+
|
| 743 |
+
def test_rjust_raises_multiple_character_fill(self, dt):
|
| 744 |
+
buf = np.array("abc", dtype=dt)
|
| 745 |
+
fill = np.array("**", dtype=dt)
|
| 746 |
+
with pytest.raises(TypeError, match=self.FILL_ERROR):
|
| 747 |
+
np.strings.rjust(buf, 10, fill)
|
| 748 |
+
|
| 749 |
+
@pytest.mark.parametrize("buf,width,fillchar,res", [
|
| 750 |
+
('abc', 10, ' ', ' abc '),
|
| 751 |
+
('abc', 6, ' ', ' abc '),
|
| 752 |
+
('abc', 3, ' ', 'abc'),
|
| 753 |
+
('abc', 2, ' ', 'abc'),
|
| 754 |
+
('abc', 10, '*', '***abc****'),
|
| 755 |
+
])
|
| 756 |
+
def test_center(self, buf, width, fillchar, res, dt):
|
| 757 |
+
buf = np.array(buf, dtype=dt)
|
| 758 |
+
fillchar = np.array(fillchar, dtype=dt)
|
| 759 |
+
res = np.array(res, dtype=dt)
|
| 760 |
+
assert_array_equal(np.strings.center(buf, width, fillchar), res)
|
| 761 |
+
|
| 762 |
+
@pytest.mark.parametrize("buf,width,fillchar,res", [
|
| 763 |
+
('abc', 10, ' ', 'abc '),
|
| 764 |
+
('abc', 6, ' ', 'abc '),
|
| 765 |
+
('abc', 3, ' ', 'abc'),
|
| 766 |
+
('abc', 2, ' ', 'abc'),
|
| 767 |
+
('abc', 10, '*', 'abc*******'),
|
| 768 |
+
])
|
| 769 |
+
def test_ljust(self, buf, width, fillchar, res, dt):
|
| 770 |
+
buf = np.array(buf, dtype=dt)
|
| 771 |
+
fillchar = np.array(fillchar, dtype=dt)
|
| 772 |
+
res = np.array(res, dtype=dt)
|
| 773 |
+
assert_array_equal(np.strings.ljust(buf, width, fillchar), res)
|
| 774 |
+
|
| 775 |
+
@pytest.mark.parametrize("buf,width,fillchar,res", [
|
| 776 |
+
('abc', 10, ' ', ' abc'),
|
| 777 |
+
('abc', 6, ' ', ' abc'),
|
| 778 |
+
('abc', 3, ' ', 'abc'),
|
| 779 |
+
('abc', 2, ' ', 'abc'),
|
| 780 |
+
('abc', 10, '*', '*******abc'),
|
| 781 |
+
])
|
| 782 |
+
def test_rjust(self, buf, width, fillchar, res, dt):
|
| 783 |
+
buf = np.array(buf, dtype=dt)
|
| 784 |
+
fillchar = np.array(fillchar, dtype=dt)
|
| 785 |
+
res = np.array(res, dtype=dt)
|
| 786 |
+
assert_array_equal(np.strings.rjust(buf, width, fillchar), res)
|
| 787 |
+
|
| 788 |
+
@pytest.mark.parametrize("buf,width,res", [
|
| 789 |
+
('123', 2, '123'),
|
| 790 |
+
('123', 3, '123'),
|
| 791 |
+
('0123', 4, '0123'),
|
| 792 |
+
('+123', 3, '+123'),
|
| 793 |
+
('+123', 4, '+123'),
|
| 794 |
+
('+123', 5, '+0123'),
|
| 795 |
+
('+0123', 5, '+0123'),
|
| 796 |
+
('-123', 3, '-123'),
|
| 797 |
+
('-123', 4, '-123'),
|
| 798 |
+
('-0123', 5, '-0123'),
|
| 799 |
+
('000', 3, '000'),
|
| 800 |
+
('34', 1, '34'),
|
| 801 |
+
('0034', 4, '0034'),
|
| 802 |
+
])
|
| 803 |
+
def test_zfill(self, buf, width, res, dt):
|
| 804 |
+
buf = np.array(buf, dtype=dt)
|
| 805 |
+
res = np.array(res, dtype=dt)
|
| 806 |
+
assert_array_equal(np.strings.zfill(buf, width), res)
|
| 807 |
+
|
| 808 |
+
@pytest.mark.parametrize("buf,sep,res1,res2,res3", [
|
| 809 |
+
("this is the partition method", "ti", "this is the par",
|
| 810 |
+
"ti", "tion method"),
|
| 811 |
+
("http://www.python.org", "://", "http", "://", "www.python.org"),
|
| 812 |
+
("http://www.python.org", "?", "http://www.python.org", "", ""),
|
| 813 |
+
("http://www.python.org", "http://", "", "http://", "www.python.org"),
|
| 814 |
+
("http://www.python.org", "org", "http://www.python.", "org", ""),
|
| 815 |
+
("http://www.python.org", ["://", "?", "http://", "org"],
|
| 816 |
+
["http", "http://www.python.org", "", "http://www.python."],
|
| 817 |
+
["://", "", "http://", "org"],
|
| 818 |
+
["www.python.org", "", "www.python.org", ""]),
|
| 819 |
+
("mississippi", "ss", "mi", "ss", "issippi"),
|
| 820 |
+
("mississippi", "i", "m", "i", "ssissippi"),
|
| 821 |
+
("mississippi", "w", "mississippi", "", ""),
|
| 822 |
+
])
|
| 823 |
+
def test_partition(self, buf, sep, res1, res2, res3, dt):
|
| 824 |
+
buf = np.array(buf, dtype=dt)
|
| 825 |
+
sep = np.array(sep, dtype=dt)
|
| 826 |
+
res1 = np.array(res1, dtype=dt)
|
| 827 |
+
res2 = np.array(res2, dtype=dt)
|
| 828 |
+
res3 = np.array(res3, dtype=dt)
|
| 829 |
+
act1, act2, act3 = np.strings.partition(buf, sep)
|
| 830 |
+
assert_array_equal(act1, res1)
|
| 831 |
+
assert_array_equal(act2, res2)
|
| 832 |
+
assert_array_equal(act3, res3)
|
| 833 |
+
assert_array_equal(act1 + act2 + act3, buf)
|
| 834 |
+
|
| 835 |
+
@pytest.mark.parametrize("buf,sep,res1,res2,res3", [
|
| 836 |
+
("this is the partition method", "ti", "this is the parti",
|
| 837 |
+
"ti", "on method"),
|
| 838 |
+
("http://www.python.org", "://", "http", "://", "www.python.org"),
|
| 839 |
+
("http://www.python.org", "?", "", "", "http://www.python.org"),
|
| 840 |
+
("http://www.python.org", "http://", "", "http://", "www.python.org"),
|
| 841 |
+
("http://www.python.org", "org", "http://www.python.", "org", ""),
|
| 842 |
+
("http://www.python.org", ["://", "?", "http://", "org"],
|
| 843 |
+
["http", "", "", "http://www.python."],
|
| 844 |
+
["://", "", "http://", "org"],
|
| 845 |
+
["www.python.org", "http://www.python.org", "www.python.org", ""]),
|
| 846 |
+
("mississippi", "ss", "missi", "ss", "ippi"),
|
| 847 |
+
("mississippi", "i", "mississipp", "i", ""),
|
| 848 |
+
("mississippi", "w", "", "", "mississippi"),
|
| 849 |
+
])
|
| 850 |
+
def test_rpartition(self, buf, sep, res1, res2, res3, dt):
|
| 851 |
+
buf = np.array(buf, dtype=dt)
|
| 852 |
+
sep = np.array(sep, dtype=dt)
|
| 853 |
+
res1 = np.array(res1, dtype=dt)
|
| 854 |
+
res2 = np.array(res2, dtype=dt)
|
| 855 |
+
res3 = np.array(res3, dtype=dt)
|
| 856 |
+
act1, act2, act3 = np.strings.rpartition(buf, sep)
|
| 857 |
+
assert_array_equal(act1, res1)
|
| 858 |
+
assert_array_equal(act2, res2)
|
| 859 |
+
assert_array_equal(act3, res3)
|
| 860 |
+
assert_array_equal(act1 + act2 + act3, buf)
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
@pytest.mark.parametrize("dt", ["U", "T"])
|
| 864 |
+
class TestMethodsWithUnicode:
|
| 865 |
+
@pytest.mark.parametrize("in_,out", [
|
| 866 |
+
("", False),
|
| 867 |
+
("a", False),
|
| 868 |
+
("0", True),
|
| 869 |
+
("\u2460", False), # CIRCLED DIGIT 1
|
| 870 |
+
("\xbc", False), # VULGAR FRACTION ONE QUARTER
|
| 871 |
+
("\u0660", True), # ARABIC_INDIC DIGIT ZERO
|
| 872 |
+
("012345", True),
|
| 873 |
+
("012345a", False),
|
| 874 |
+
(["0", "a"], [True, False]),
|
| 875 |
+
])
|
| 876 |
+
def test_isdecimal_unicode(self, in_, out, dt):
|
| 877 |
+
buf = np.array(in_, dtype=dt)
|
| 878 |
+
assert_array_equal(np.strings.isdecimal(buf), out)
|
| 879 |
+
|
| 880 |
+
@pytest.mark.parametrize("in_,out", [
|
| 881 |
+
("", False),
|
| 882 |
+
("a", False),
|
| 883 |
+
("0", True),
|
| 884 |
+
("\u2460", True), # CIRCLED DIGIT 1
|
| 885 |
+
("\xbc", True), # VULGAR FRACTION ONE QUARTER
|
| 886 |
+
("\u0660", True), # ARABIC_INDIC DIGIT ZERO
|
| 887 |
+
("012345", True),
|
| 888 |
+
("012345a", False),
|
| 889 |
+
(["0", "a"], [True, False]),
|
| 890 |
+
])
|
| 891 |
+
def test_isnumeric_unicode(self, in_, out, dt):
|
| 892 |
+
buf = np.array(in_, dtype=dt)
|
| 893 |
+
assert_array_equal(np.strings.isnumeric(buf), out)
|
| 894 |
+
|
| 895 |
+
@pytest.mark.parametrize("buf,old,new,count,res", [
|
| 896 |
+
("...\u043c......<", "<", "<", -1, "...\u043c......<"),
|
| 897 |
+
("Ae¢☃€ 😊" * 2, "A", "B", -1, "Be¢☃€ 😊Be¢☃€ 😊"),
|
| 898 |
+
("Ae¢☃€ 😊" * 2, "😊", "B", -1, "Ae¢☃€ BAe¢☃€ B"),
|
| 899 |
+
])
|
| 900 |
+
def test_replace_unicode(self, buf, old, new, count, res, dt):
|
| 901 |
+
buf = np.array(buf, dtype=dt)
|
| 902 |
+
old = np.array(old, dtype=dt)
|
| 903 |
+
new = np.array(new, dtype=dt)
|
| 904 |
+
res = np.array(res, dtype=dt)
|
| 905 |
+
assert_array_equal(np.strings.replace(buf, old, new, count), res)
|
| 906 |
+
|
| 907 |
+
@pytest.mark.parametrize("in_", [
|
| 908 |
+
'\U00010401',
|
| 909 |
+
'\U00010427',
|
| 910 |
+
'\U00010429',
|
| 911 |
+
'\U0001044E',
|
| 912 |
+
'\U0001D7F6',
|
| 913 |
+
'\U00011066',
|
| 914 |
+
'\U000104A0',
|
| 915 |
+
pytest.param('\U0001F107', marks=pytest.mark.xfail(
|
| 916 |
+
sys.platform == 'win32' and IS_PYPY_LT_7_3_16,
|
| 917 |
+
reason="PYPY bug in Py_UNICODE_ISALNUM",
|
| 918 |
+
strict=True)),
|
| 919 |
+
])
|
| 920 |
+
def test_isalnum_unicode(self, in_, dt):
|
| 921 |
+
in_ = np.array(in_, dtype=dt)
|
| 922 |
+
assert_array_equal(np.strings.isalnum(in_), True)
|
| 923 |
+
|
| 924 |
+
@pytest.mark.parametrize("in_,out", [
|
| 925 |
+
('\u1FFc', False),
|
| 926 |
+
('\u2167', False),
|
| 927 |
+
('\U00010401', False),
|
| 928 |
+
('\U00010427', False),
|
| 929 |
+
('\U0001F40D', False),
|
| 930 |
+
('\U0001F46F', False),
|
| 931 |
+
('\u2177', True),
|
| 932 |
+
pytest.param('\U00010429', True, marks=pytest.mark.xfail(
|
| 933 |
+
sys.platform == 'win32' and IS_PYPY_LT_7_3_16,
|
| 934 |
+
reason="PYPY bug in Py_UNICODE_ISLOWER",
|
| 935 |
+
strict=True)),
|
| 936 |
+
('\U0001044E', True),
|
| 937 |
+
])
|
| 938 |
+
def test_islower_unicode(self, in_, out, dt):
|
| 939 |
+
in_ = np.array(in_, dtype=dt)
|
| 940 |
+
assert_array_equal(np.strings.islower(in_), out)
|
| 941 |
+
|
| 942 |
+
@pytest.mark.parametrize("in_,out", [
|
| 943 |
+
('\u1FFc', False),
|
| 944 |
+
('\u2167', True),
|
| 945 |
+
('\U00010401', True),
|
| 946 |
+
('\U00010427', True),
|
| 947 |
+
('\U0001F40D', False),
|
| 948 |
+
('\U0001F46F', False),
|
| 949 |
+
('\u2177', False),
|
| 950 |
+
pytest.param('\U00010429', False, marks=pytest.mark.xfail(
|
| 951 |
+
sys.platform == 'win32' and IS_PYPY_LT_7_3_16,
|
| 952 |
+
reason="PYPY bug in Py_UNICODE_ISUPPER",
|
| 953 |
+
strict=True)),
|
| 954 |
+
('\U0001044E', False),
|
| 955 |
+
])
|
| 956 |
+
def test_isupper_unicode(self, in_, out, dt):
|
| 957 |
+
in_ = np.array(in_, dtype=dt)
|
| 958 |
+
assert_array_equal(np.strings.isupper(in_), out)
|
| 959 |
+
|
| 960 |
+
@pytest.mark.parametrize("in_,out", [
|
| 961 |
+
('\u1FFc', True),
|
| 962 |
+
('Greek \u1FFcitlecases ...', True),
|
| 963 |
+
pytest.param('\U00010401\U00010429', True, marks=pytest.mark.xfail(
|
| 964 |
+
sys.platform == 'win32' and IS_PYPY_LT_7_3_16,
|
| 965 |
+
reason="PYPY bug in Py_UNICODE_ISISTITLE",
|
| 966 |
+
strict=True)),
|
| 967 |
+
('\U00010427\U0001044E', True),
|
| 968 |
+
pytest.param('\U00010429', False, marks=pytest.mark.xfail(
|
| 969 |
+
sys.platform == 'win32' and IS_PYPY_LT_7_3_16,
|
| 970 |
+
reason="PYPY bug in Py_UNICODE_ISISTITLE",
|
| 971 |
+
strict=True)),
|
| 972 |
+
('\U0001044E', False),
|
| 973 |
+
('\U0001F40D', False),
|
| 974 |
+
('\U0001F46F', False),
|
| 975 |
+
])
|
| 976 |
+
def test_istitle_unicode(self, in_, out, dt):
|
| 977 |
+
in_ = np.array(in_, dtype=dt)
|
| 978 |
+
assert_array_equal(np.strings.istitle(in_), out)
|
| 979 |
+
|
| 980 |
+
@pytest.mark.parametrize("buf,sub,start,end,res", [
|
| 981 |
+
("Ae¢☃€ 😊" * 2, "😊", 0, None, 6),
|
| 982 |
+
("Ae¢☃€ 😊" * 2, "😊", 7, None, 13),
|
| 983 |
+
])
|
| 984 |
+
def test_index_unicode(self, buf, sub, start, end, res, dt):
|
| 985 |
+
buf = np.array(buf, dtype=dt)
|
| 986 |
+
sub = np.array(sub, dtype=dt)
|
| 987 |
+
assert_array_equal(np.strings.index(buf, sub, start, end), res)
|
| 988 |
+
|
| 989 |
+
def test_index_raises_unicode(self, dt):
|
| 990 |
+
with pytest.raises(ValueError, match="substring not found"):
|
| 991 |
+
np.strings.index("Ae¢☃€ 😊", "😀")
|
| 992 |
+
|
| 993 |
+
@pytest.mark.parametrize("buf,res", [
|
| 994 |
+
("Ae¢☃€ \t 😊", "Ae¢☃€ 😊"),
|
| 995 |
+
("\t\U0001044E", " \U0001044E"),
|
| 996 |
+
])
|
| 997 |
+
def test_expandtabs(self, buf, res, dt):
|
| 998 |
+
buf = np.array(buf, dtype=dt)
|
| 999 |
+
res = np.array(res, dtype=dt)
|
| 1000 |
+
assert_array_equal(np.strings.expandtabs(buf), res)
|
| 1001 |
+
|
| 1002 |
+
@pytest.mark.parametrize("buf,width,fillchar,res", [
|
| 1003 |
+
('x', 2, '\U0001044E', 'x\U0001044E'),
|
| 1004 |
+
('x', 3, '\U0001044E', '\U0001044Ex\U0001044E'),
|
| 1005 |
+
('x', 4, '\U0001044E', '\U0001044Ex\U0001044E\U0001044E'),
|
| 1006 |
+
])
|
| 1007 |
+
def test_center(self, buf, width, fillchar, res, dt):
|
| 1008 |
+
buf = np.array(buf, dtype=dt)
|
| 1009 |
+
fillchar = np.array(fillchar, dtype=dt)
|
| 1010 |
+
res = np.array(res, dtype=dt)
|
| 1011 |
+
assert_array_equal(np.strings.center(buf, width, fillchar), res)
|
| 1012 |
+
|
| 1013 |
+
@pytest.mark.parametrize("buf,width,fillchar,res", [
|
| 1014 |
+
('x', 2, '\U0001044E', 'x\U0001044E'),
|
| 1015 |
+
('x', 3, '\U0001044E', 'x\U0001044E\U0001044E'),
|
| 1016 |
+
('x', 4, '\U0001044E', 'x\U0001044E\U0001044E\U0001044E'),
|
| 1017 |
+
])
|
| 1018 |
+
def test_ljust(self, buf, width, fillchar, res, dt):
|
| 1019 |
+
buf = np.array(buf, dtype=dt)
|
| 1020 |
+
fillchar = np.array(fillchar, dtype=dt)
|
| 1021 |
+
res = np.array(res, dtype=dt)
|
| 1022 |
+
assert_array_equal(np.strings.ljust(buf, width, fillchar), res)
|
| 1023 |
+
|
| 1024 |
+
@pytest.mark.parametrize("buf,width,fillchar,res", [
|
| 1025 |
+
('x', 2, '\U0001044E', '\U0001044Ex'),
|
| 1026 |
+
('x', 3, '\U0001044E', '\U0001044E\U0001044Ex'),
|
| 1027 |
+
('x', 4, '\U0001044E', '\U0001044E\U0001044E\U0001044Ex'),
|
| 1028 |
+
])
|
| 1029 |
+
def test_rjust(self, buf, width, fillchar, res, dt):
|
| 1030 |
+
buf = np.array(buf, dtype=dt)
|
| 1031 |
+
fillchar = np.array(fillchar, dtype=dt)
|
| 1032 |
+
res = np.array(res, dtype=dt)
|
| 1033 |
+
assert_array_equal(np.strings.rjust(buf, width, fillchar), res)
|
| 1034 |
+
|
| 1035 |
+
@pytest.mark.parametrize("buf,sep,res1,res2,res3", [
|
| 1036 |
+
("āāāāĀĀĀĀ", "Ă", "āāāāĀĀĀĀ", "", ""),
|
| 1037 |
+
("āāāāĂĀĀĀĀ", "Ă", "āāāā", "Ă", "ĀĀĀĀ"),
|
| 1038 |
+
("āāāāĂĂĀĀĀĀ", "ĂĂ", "āāāā", "ĂĂ", "ĀĀĀĀ"),
|
| 1039 |
+
("𐌁𐌁𐌁𐌁𐌀𐌀𐌀𐌀", "𐌂", "𐌁𐌁𐌁𐌁𐌀𐌀𐌀𐌀", "", ""),
|
| 1040 |
+
("𐌁𐌁𐌁𐌁𐌂𐌀𐌀𐌀𐌀", "𐌂", "𐌁𐌁𐌁𐌁", "𐌂", "𐌀𐌀𐌀𐌀"),
|
| 1041 |
+
("𐌁𐌁𐌁𐌁𐌂𐌂𐌀𐌀𐌀𐌀", "𐌂𐌂", "𐌁𐌁𐌁𐌁", "𐌂𐌂", "𐌀𐌀𐌀𐌀"),
|
| 1042 |
+
("𐌁𐌁𐌁𐌁𐌂𐌂𐌂𐌂𐌀𐌀𐌀𐌀", "𐌂𐌂𐌂𐌂", "𐌁𐌁𐌁𐌁", "𐌂𐌂𐌂𐌂", "𐌀𐌀𐌀𐌀"),
|
| 1043 |
+
])
|
| 1044 |
+
def test_partition(self, buf, sep, res1, res2, res3, dt):
|
| 1045 |
+
buf = np.array(buf, dtype=dt)
|
| 1046 |
+
sep = np.array(sep, dtype=dt)
|
| 1047 |
+
res1 = np.array(res1, dtype=dt)
|
| 1048 |
+
res2 = np.array(res2, dtype=dt)
|
| 1049 |
+
res3 = np.array(res3, dtype=dt)
|
| 1050 |
+
act1, act2, act3 = np.strings.partition(buf, sep)
|
| 1051 |
+
assert_array_equal(act1, res1)
|
| 1052 |
+
assert_array_equal(act2, res2)
|
| 1053 |
+
assert_array_equal(act3, res3)
|
| 1054 |
+
assert_array_equal(act1 + act2 + act3, buf)
|
| 1055 |
+
|
| 1056 |
+
@pytest.mark.parametrize("buf,sep,res1,res2,res3", [
|
| 1057 |
+
("āāāāĀĀĀĀ", "Ă", "", "", "āāāāĀĀĀĀ"),
|
| 1058 |
+
("āāāāĂĀĀĀĀ", "Ă", "āāāā", "Ă", "ĀĀĀĀ"),
|
| 1059 |
+
("āāāāĂĂĀĀĀĀ", "ĂĂ", "āāāā", "ĂĂ", "ĀĀĀĀ"),
|
| 1060 |
+
("𐌁𐌁𐌁𐌁𐌀𐌀𐌀𐌀", "𐌂", "", "", "𐌁𐌁𐌁𐌁𐌀𐌀𐌀𐌀"),
|
| 1061 |
+
("𐌁𐌁𐌁𐌁𐌂𐌀𐌀𐌀𐌀", "𐌂", "𐌁𐌁𐌁𐌁", "𐌂", "𐌀𐌀𐌀𐌀"),
|
| 1062 |
+
("𐌁𐌁𐌁𐌁𐌂𐌂𐌀𐌀𐌀𐌀", "𐌂𐌂", "𐌁𐌁𐌁𐌁", "𐌂𐌂", "𐌀𐌀𐌀𐌀"),
|
| 1063 |
+
])
|
| 1064 |
+
def test_rpartition(self, buf, sep, res1, res2, res3, dt):
|
| 1065 |
+
buf = np.array(buf, dtype=dt)
|
| 1066 |
+
sep = np.array(sep, dtype=dt)
|
| 1067 |
+
res1 = np.array(res1, dtype=dt)
|
| 1068 |
+
res2 = np.array(res2, dtype=dt)
|
| 1069 |
+
res3 = np.array(res3, dtype=dt)
|
| 1070 |
+
act1, act2, act3 = np.strings.rpartition(buf, sep)
|
| 1071 |
+
assert_array_equal(act1, res1)
|
| 1072 |
+
assert_array_equal(act2, res2)
|
| 1073 |
+
assert_array_equal(act3, res3)
|
| 1074 |
+
assert_array_equal(act1 + act2 + act3, buf)
|
| 1075 |
+
|
| 1076 |
+
@pytest.mark.parametrize("method", ["strip", "lstrip", "rstrip"])
|
| 1077 |
+
@pytest.mark.parametrize(
|
| 1078 |
+
"source,strip",
|
| 1079 |
+
[
|
| 1080 |
+
("λμ", "μ"),
|
| 1081 |
+
("λμ", "λ"),
|
| 1082 |
+
("λ"*5 + "μ"*2, "μ"),
|
| 1083 |
+
("λ" * 5 + "μ" * 2, "λ"),
|
| 1084 |
+
("λ" * 5 + "A" + "μ" * 2, "μλ"),
|
| 1085 |
+
("λμ" * 5, "μ"),
|
| 1086 |
+
("λμ" * 5, "λ"),
|
| 1087 |
+
])
|
| 1088 |
+
def test_strip_functions_unicode(self, source, strip, method, dt):
|
| 1089 |
+
src_array = np.array([source], dtype=dt)
|
| 1090 |
+
|
| 1091 |
+
npy_func = getattr(np.strings, method)
|
| 1092 |
+
py_func = getattr(str, method)
|
| 1093 |
+
|
| 1094 |
+
expected = np.array([py_func(source, strip)], dtype=dt)
|
| 1095 |
+
actual = npy_func(src_array, strip)
|
| 1096 |
+
|
| 1097 |
+
assert_array_equal(actual, expected)
|
| 1098 |
+
|
| 1099 |
+
|
| 1100 |
+
class TestMixedTypeMethods:
|
| 1101 |
+
def test_center(self):
|
| 1102 |
+
buf = np.array("😊", dtype="U")
|
| 1103 |
+
fill = np.array("*", dtype="S")
|
| 1104 |
+
res = np.array("*😊*", dtype="U")
|
| 1105 |
+
assert_array_equal(np.strings.center(buf, 3, fill), res)
|
| 1106 |
+
|
| 1107 |
+
buf = np.array("s", dtype="S")
|
| 1108 |
+
fill = np.array("*", dtype="U")
|
| 1109 |
+
res = np.array("*s*", dtype="S")
|
| 1110 |
+
assert_array_equal(np.strings.center(buf, 3, fill), res)
|
| 1111 |
+
|
| 1112 |
+
with pytest.raises(ValueError, match="'ascii' codec can't encode"):
|
| 1113 |
+
buf = np.array("s", dtype="S")
|
| 1114 |
+
fill = np.array("😊", dtype="U")
|
| 1115 |
+
np.strings.center(buf, 3, fill)
|
| 1116 |
+
|
| 1117 |
+
def test_ljust(self):
|
| 1118 |
+
buf = np.array("😊", dtype="U")
|
| 1119 |
+
fill = np.array("*", dtype="S")
|
| 1120 |
+
res = np.array("😊**", dtype="U")
|
| 1121 |
+
assert_array_equal(np.strings.ljust(buf, 3, fill), res)
|
| 1122 |
+
|
| 1123 |
+
buf = np.array("s", dtype="S")
|
| 1124 |
+
fill = np.array("*", dtype="U")
|
| 1125 |
+
res = np.array("s**", dtype="S")
|
| 1126 |
+
assert_array_equal(np.strings.ljust(buf, 3, fill), res)
|
| 1127 |
+
|
| 1128 |
+
with pytest.raises(ValueError, match="'ascii' codec can't encode"):
|
| 1129 |
+
buf = np.array("s", dtype="S")
|
| 1130 |
+
fill = np.array("😊", dtype="U")
|
| 1131 |
+
np.strings.ljust(buf, 3, fill)
|
| 1132 |
+
|
| 1133 |
+
def test_rjust(self):
|
| 1134 |
+
buf = np.array("😊", dtype="U")
|
| 1135 |
+
fill = np.array("*", dtype="S")
|
| 1136 |
+
res = np.array("**😊", dtype="U")
|
| 1137 |
+
assert_array_equal(np.strings.rjust(buf, 3, fill), res)
|
| 1138 |
+
|
| 1139 |
+
buf = np.array("s", dtype="S")
|
| 1140 |
+
fill = np.array("*", dtype="U")
|
| 1141 |
+
res = np.array("**s", dtype="S")
|
| 1142 |
+
assert_array_equal(np.strings.rjust(buf, 3, fill), res)
|
| 1143 |
+
|
| 1144 |
+
with pytest.raises(ValueError, match="'ascii' codec can't encode"):
|
| 1145 |
+
buf = np.array("s", dtype="S")
|
| 1146 |
+
fill = np.array("😊", dtype="U")
|
| 1147 |
+
np.strings.rjust(buf, 3, fill)
|
| 1148 |
+
|
| 1149 |
+
|
| 1150 |
+
class TestUnicodeOnlyMethodsRaiseWithBytes:
|
| 1151 |
+
def test_isdecimal_raises(self):
|
| 1152 |
+
in_ = np.array(b"1")
|
| 1153 |
+
with assert_raises(TypeError):
|
| 1154 |
+
np.strings.isdecimal(in_)
|
| 1155 |
+
|
| 1156 |
+
def test_isnumeric_bytes(self):
|
| 1157 |
+
in_ = np.array(b"1")
|
| 1158 |
+
with assert_raises(TypeError):
|
| 1159 |
+
np.strings.isnumeric(in_)
|
| 1160 |
+
|
| 1161 |
+
|
| 1162 |
+
def check_itemsize(n_elem, dt):
|
| 1163 |
+
if dt == "T":
|
| 1164 |
+
return np.dtype(dt).itemsize
|
| 1165 |
+
if dt == "S":
|
| 1166 |
+
return n_elem
|
| 1167 |
+
if dt == "U":
|
| 1168 |
+
return n_elem * 4
|
| 1169 |
+
|
| 1170 |
+
@pytest.mark.parametrize("dt", ["S", "U", "T"])
|
| 1171 |
+
class TestReplaceOnArrays:
|
| 1172 |
+
|
| 1173 |
+
def test_replace_count_and_size(self, dt):
|
| 1174 |
+
a = np.array(["0123456789" * i for i in range(4)], dtype=dt)
|
| 1175 |
+
r1 = np.strings.replace(a, "5", "ABCDE")
|
| 1176 |
+
assert r1.dtype.itemsize == check_itemsize(3*10 + 3*4, dt)
|
| 1177 |
+
r1_res = np.array(["01234ABCDE6789" * i for i in range(4)], dtype=dt)
|
| 1178 |
+
assert_array_equal(r1, r1_res)
|
| 1179 |
+
r2 = np.strings.replace(a, "5", "ABCDE", 1)
|
| 1180 |
+
assert r2.dtype.itemsize == check_itemsize(3*10 + 4, dt)
|
| 1181 |
+
r3 = np.strings.replace(a, "5", "ABCDE", 0)
|
| 1182 |
+
assert r3.dtype.itemsize == a.dtype.itemsize
|
| 1183 |
+
assert_array_equal(r3, a)
|
| 1184 |
+
# Negative values mean to replace all.
|
| 1185 |
+
r4 = np.strings.replace(a, "5", "ABCDE", -1)
|
| 1186 |
+
assert r4.dtype.itemsize == check_itemsize(3*10 + 3*4, dt)
|
| 1187 |
+
assert_array_equal(r4, r1)
|
| 1188 |
+
# We can do count on an element-by-element basis.
|
| 1189 |
+
r5 = np.strings.replace(a, "5", "ABCDE", [-1, -1, -1, 1])
|
| 1190 |
+
assert r5.dtype.itemsize == check_itemsize(3*10 + 4, dt)
|
| 1191 |
+
assert_array_equal(r5, np.array(
|
| 1192 |
+
["01234ABCDE6789" * i for i in range(3)]
|
| 1193 |
+
+ ["01234ABCDE6789" + "0123456789" * 2], dtype=dt))
|
| 1194 |
+
|
| 1195 |
+
def test_replace_broadcasting(self, dt):
|
| 1196 |
+
a = np.array("0,0,0", dtype=dt)
|
| 1197 |
+
r1 = np.strings.replace(a, "0", "1", np.arange(3))
|
| 1198 |
+
assert r1.dtype == a.dtype
|
| 1199 |
+
assert_array_equal(r1, np.array(["0,0,0", "1,0,0", "1,1,0"], dtype=dt))
|
| 1200 |
+
r2 = np.strings.replace(a, "0", [["1"], ["2"]], np.arange(1, 4))
|
| 1201 |
+
assert_array_equal(r2, np.array([["1,0,0", "1,1,0", "1,1,1"],
|
| 1202 |
+
["2,0,0", "2,2,0", "2,2,2"]],
|
| 1203 |
+
dtype=dt))
|
| 1204 |
+
r3 = np.strings.replace(a, ["0", "0,0", "0,0,0"], "X")
|
| 1205 |
+
assert_array_equal(r3, np.array(["X,X,X", "X,0", "X"], dtype=dt))
|
parrot/lib/python3.10/site-packages/numpy/_core/tests/test_umath_accuracy.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import os
|
| 3 |
+
from os import path
|
| 4 |
+
import sys
|
| 5 |
+
import pytest
|
| 6 |
+
from ctypes import c_longlong, c_double, c_float, c_int, cast, pointer, POINTER
|
| 7 |
+
from numpy.testing import assert_array_max_ulp
|
| 8 |
+
from numpy.testing._private.utils import _glibc_older_than
|
| 9 |
+
from numpy._core._multiarray_umath import __cpu_features__
|
| 10 |
+
|
| 11 |
+
UNARY_UFUNCS = [obj for obj in np._core.umath.__dict__.values() if
|
| 12 |
+
isinstance(obj, np.ufunc)]
|
| 13 |
+
UNARY_OBJECT_UFUNCS = [uf for uf in UNARY_UFUNCS if "O->O" in uf.types]
|
| 14 |
+
|
| 15 |
+
# Remove functions that do not support `floats`
|
| 16 |
+
UNARY_OBJECT_UFUNCS.remove(getattr(np, 'invert'))
|
| 17 |
+
UNARY_OBJECT_UFUNCS.remove(getattr(np, 'bitwise_count'))
|
| 18 |
+
|
| 19 |
+
IS_AVX = __cpu_features__.get('AVX512F', False) or \
|
| 20 |
+
(__cpu_features__.get('FMA3', False) and __cpu_features__.get('AVX2', False))
|
| 21 |
+
|
| 22 |
+
IS_AVX512FP16 = __cpu_features__.get('AVX512FP16', False)
|
| 23 |
+
|
| 24 |
+
# only run on linux with AVX, also avoid old glibc (numpy/numpy#20448).
|
| 25 |
+
runtest = (sys.platform.startswith('linux')
|
| 26 |
+
and IS_AVX and not _glibc_older_than("2.17"))
|
| 27 |
+
platform_skip = pytest.mark.skipif(not runtest,
|
| 28 |
+
reason="avoid testing inconsistent platform "
|
| 29 |
+
"library implementations")
|
| 30 |
+
|
| 31 |
+
# convert string to hex function taken from:
|
| 32 |
+
# https://stackoverflow.com/questions/1592158/convert-hex-to-float #
|
| 33 |
+
def convert(s, datatype="np.float32"):
|
| 34 |
+
i = int(s, 16) # convert from hex to a Python int
|
| 35 |
+
if (datatype == "np.float64"):
|
| 36 |
+
cp = pointer(c_longlong(i)) # make this into a c long long integer
|
| 37 |
+
fp = cast(cp, POINTER(c_double)) # cast the int pointer to a double pointer
|
| 38 |
+
else:
|
| 39 |
+
cp = pointer(c_int(i)) # make this into a c integer
|
| 40 |
+
fp = cast(cp, POINTER(c_float)) # cast the int pointer to a float pointer
|
| 41 |
+
|
| 42 |
+
return fp.contents.value # dereference the pointer, get the float
|
| 43 |
+
|
| 44 |
+
str_to_float = np.vectorize(convert)
|
| 45 |
+
|
| 46 |
+
class TestAccuracy:
|
| 47 |
+
@platform_skip
|
| 48 |
+
def test_validate_transcendentals(self):
|
| 49 |
+
with np.errstate(all='ignore'):
|
| 50 |
+
data_dir = path.join(path.dirname(__file__), 'data')
|
| 51 |
+
files = os.listdir(data_dir)
|
| 52 |
+
files = list(filter(lambda f: f.endswith('.csv'), files))
|
| 53 |
+
for filename in files:
|
| 54 |
+
filepath = path.join(data_dir, filename)
|
| 55 |
+
with open(filepath) as fid:
|
| 56 |
+
file_without_comments = (r for r in fid if not r[0] in ('$', '#'))
|
| 57 |
+
data = np.genfromtxt(file_without_comments,
|
| 58 |
+
dtype=('|S39','|S39','|S39',int),
|
| 59 |
+
names=('type','input','output','ulperr'),
|
| 60 |
+
delimiter=',',
|
| 61 |
+
skip_header=1)
|
| 62 |
+
npname = path.splitext(filename)[0].split('-')[3]
|
| 63 |
+
npfunc = getattr(np, npname)
|
| 64 |
+
for datatype in np.unique(data['type']):
|
| 65 |
+
data_subset = data[data['type'] == datatype]
|
| 66 |
+
inval = np.array(str_to_float(data_subset['input'].astype(str), data_subset['type'].astype(str)), dtype=eval(datatype))
|
| 67 |
+
outval = np.array(str_to_float(data_subset['output'].astype(str), data_subset['type'].astype(str)), dtype=eval(datatype))
|
| 68 |
+
perm = np.random.permutation(len(inval))
|
| 69 |
+
inval = inval[perm]
|
| 70 |
+
outval = outval[perm]
|
| 71 |
+
maxulperr = data_subset['ulperr'].max()
|
| 72 |
+
assert_array_max_ulp(npfunc(inval), outval, maxulperr)
|
| 73 |
+
|
| 74 |
+
@pytest.mark.skipif(IS_AVX512FP16,
|
| 75 |
+
reason = "SVML FP16 have slightly higher ULP errors")
|
| 76 |
+
@pytest.mark.parametrize("ufunc", UNARY_OBJECT_UFUNCS)
|
| 77 |
+
def test_validate_fp16_transcendentals(self, ufunc):
|
| 78 |
+
with np.errstate(all='ignore'):
|
| 79 |
+
arr = np.arange(65536, dtype=np.int16)
|
| 80 |
+
datafp16 = np.frombuffer(arr.tobytes(), dtype=np.float16)
|
| 81 |
+
datafp32 = datafp16.astype(np.float32)
|
| 82 |
+
assert_array_max_ulp(ufunc(datafp16), ufunc(datafp32),
|
| 83 |
+
maxulp=1, dtype=np.float16)
|
| 84 |
+
|
| 85 |
+
@pytest.mark.skipif(not IS_AVX512FP16,
|
| 86 |
+
reason="lower ULP only apply for SVML FP16")
|
| 87 |
+
def test_validate_svml_fp16(self):
|
| 88 |
+
max_ulp_err = {
|
| 89 |
+
"arccos": 2.54,
|
| 90 |
+
"arccosh": 2.09,
|
| 91 |
+
"arcsin": 3.06,
|
| 92 |
+
"arcsinh": 1.51,
|
| 93 |
+
"arctan": 2.61,
|
| 94 |
+
"arctanh": 1.88,
|
| 95 |
+
"cbrt": 1.57,
|
| 96 |
+
"cos": 1.43,
|
| 97 |
+
"cosh": 1.33,
|
| 98 |
+
"exp2": 1.33,
|
| 99 |
+
"exp": 1.27,
|
| 100 |
+
"expm1": 0.53,
|
| 101 |
+
"log": 1.80,
|
| 102 |
+
"log10": 1.27,
|
| 103 |
+
"log1p": 1.88,
|
| 104 |
+
"log2": 1.80,
|
| 105 |
+
"sin": 1.88,
|
| 106 |
+
"sinh": 2.05,
|
| 107 |
+
"tan": 2.26,
|
| 108 |
+
"tanh": 3.00,
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
with np.errstate(all='ignore'):
|
| 112 |
+
arr = np.arange(65536, dtype=np.int16)
|
| 113 |
+
datafp16 = np.frombuffer(arr.tobytes(), dtype=np.float16)
|
| 114 |
+
datafp32 = datafp16.astype(np.float32)
|
| 115 |
+
for func in max_ulp_err:
|
| 116 |
+
ufunc = getattr(np, func)
|
| 117 |
+
ulp = np.ceil(max_ulp_err[func])
|
| 118 |
+
assert_array_max_ulp(ufunc(datafp16), ufunc(datafp32),
|
| 119 |
+
maxulp=ulp, dtype=np.float16)
|
videollama2/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .activation import MultiheadAttention
|
| 2 |
+
from .rnn import LSTM
|
| 3 |
+
from .rnn import LSTMCell
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
'LSTM',
|
| 7 |
+
'LSTMCell',
|
| 8 |
+
'MultiheadAttention',
|
| 9 |
+
]
|
videollama2/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/__pycache__/rnn.cpython-310.pyc
ADDED
|
Binary file (12.4 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/activation.py
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.jit # this is needed to avoid a circular import
|
| 3 |
+
from torch import nn
|
| 4 |
+
import torch.nn.functional as nnF
|
| 5 |
+
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from typing import Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import warnings
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"MultiheadAttention"
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
class MultiheadAttention(nn.MultiheadAttention):
|
| 16 |
+
_FLOAT_MODULE = nn.MultiheadAttention
|
| 17 |
+
|
| 18 |
+
r"""Quantizable implementation of the MultiheadAttention.
|
| 19 |
+
|
| 20 |
+
Note::
|
| 21 |
+
Please, refer to :class:`~torch.nn.MultiheadAttention` for more
|
| 22 |
+
information
|
| 23 |
+
|
| 24 |
+
Allows the model to jointly attend to information from different
|
| 25 |
+
representation subspaces.
|
| 26 |
+
See reference: Attention Is All You Need
|
| 27 |
+
|
| 28 |
+
The original MHA module is not quantizable.
|
| 29 |
+
This reimplements it by explicitly instantiating the linear layers.
|
| 30 |
+
|
| 31 |
+
.. math::
|
| 32 |
+
\text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
|
| 33 |
+
\text{where} head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
embed_dim: total dimension of the model.
|
| 37 |
+
num_heads: parallel attention heads.
|
| 38 |
+
dropout: a Dropout layer on attn_output_weights. Default: 0.0.
|
| 39 |
+
bias: add bias as module parameter. Default: True.
|
| 40 |
+
add_bias_kv: add bias to the key and value sequences at dim=0.
|
| 41 |
+
add_zero_attn: add a new batch of zeros to the key and
|
| 42 |
+
value sequences at dim=1.
|
| 43 |
+
kdim: total number of features in key. Default: None.
|
| 44 |
+
vdim: total number of features in value. Default: None.
|
| 45 |
+
batch_first: If ``True``, then the input and output tensors are provided
|
| 46 |
+
as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
|
| 47 |
+
|
| 48 |
+
Note that if :attr:`kdim` and :attr:`vdim` are None, they will be set
|
| 49 |
+
to :attr:`embed_dim` such that query, key, and value have the same
|
| 50 |
+
number of features.
|
| 51 |
+
|
| 52 |
+
Examples::
|
| 53 |
+
|
| 54 |
+
>>> import torch.ao.nn.quantizable as nnqa
|
| 55 |
+
>>> multihead_attn = nnqa.MultiheadAttention(embed_dim, num_heads)
|
| 56 |
+
>>> attn_output, attn_output_weights = multihead_attn(query, key, value)
|
| 57 |
+
|
| 58 |
+
Note::
|
| 59 |
+
Please, follow the quantization flow to convert the quantizable MHA.
|
| 60 |
+
"""
|
| 61 |
+
__constants__ = ['batch_first']
|
| 62 |
+
|
| 63 |
+
def __init__(self, embed_dim: int, num_heads: int,
|
| 64 |
+
dropout: float = 0., bias: bool = True,
|
| 65 |
+
add_bias_kv: bool = False, add_zero_attn: bool = False,
|
| 66 |
+
kdim: Optional[int] = None, vdim: Optional[int] = None, batch_first: bool = False,
|
| 67 |
+
device=None, dtype=None) -> None:
|
| 68 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 69 |
+
super().__init__(embed_dim, num_heads, dropout,
|
| 70 |
+
bias, add_bias_kv,
|
| 71 |
+
add_zero_attn, kdim, vdim, batch_first,
|
| 72 |
+
**factory_kwargs)
|
| 73 |
+
self.linear_Q = nn.Linear(self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs)
|
| 74 |
+
self.linear_K = nn.Linear(self.kdim, self.embed_dim, bias=bias, **factory_kwargs)
|
| 75 |
+
self.linear_V = nn.Linear(self.vdim, self.embed_dim, bias=bias, **factory_kwargs)
|
| 76 |
+
# for the type: ignore, see https://github.com/pytorch/pytorch/issues/58969
|
| 77 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs) # type: ignore[assignment]
|
| 78 |
+
|
| 79 |
+
# Functionals
|
| 80 |
+
self.q_scaling_product = torch.ao.nn.quantized.FloatFunctional()
|
| 81 |
+
# note: importing torch.ao.nn.quantized at top creates a circular import
|
| 82 |
+
|
| 83 |
+
# Quant/Dequant
|
| 84 |
+
self.quant_attn_output = torch.ao.quantization.QuantStub()
|
| 85 |
+
self.quant_attn_output_weights = torch.ao.quantization.QuantStub()
|
| 86 |
+
self.dequant_q = torch.ao.quantization.DeQuantStub()
|
| 87 |
+
self.dequant_k = torch.ao.quantization.DeQuantStub()
|
| 88 |
+
self.dequant_v = torch.ao.quantization.DeQuantStub()
|
| 89 |
+
|
| 90 |
+
def _get_name(self):
|
| 91 |
+
return 'QuantizableMultiheadAttention'
|
| 92 |
+
|
| 93 |
+
@classmethod
|
| 94 |
+
def from_float(cls, other):
|
| 95 |
+
assert type(other) == cls._FLOAT_MODULE
|
| 96 |
+
assert hasattr(other, 'qconfig'), "The float module must have 'qconfig'"
|
| 97 |
+
# Setting the dropout to 0.0!
|
| 98 |
+
observed = cls(other.embed_dim, other.num_heads, other.dropout,
|
| 99 |
+
(other.in_proj_bias is not None),
|
| 100 |
+
(other.bias_k is not None),
|
| 101 |
+
other.add_zero_attn, other.kdim, other.vdim,
|
| 102 |
+
other.batch_first)
|
| 103 |
+
observed.bias_k = other.bias_k
|
| 104 |
+
observed.bias_v = other.bias_v
|
| 105 |
+
observed.qconfig = other.qconfig
|
| 106 |
+
|
| 107 |
+
# Set the linear weights
|
| 108 |
+
# for the type: ignores, see https://github.com/pytorch/pytorch/issues/58969
|
| 109 |
+
observed.out_proj.weight = other.out_proj.weight # type: ignore[has-type]
|
| 110 |
+
observed.out_proj.bias = other.out_proj.bias # type: ignore[has-type]
|
| 111 |
+
if other._qkv_same_embed_dim:
|
| 112 |
+
# Use separate params
|
| 113 |
+
bias = other.in_proj_bias
|
| 114 |
+
_start = 0
|
| 115 |
+
_end = _start + other.embed_dim
|
| 116 |
+
weight = other.in_proj_weight[_start:_end, :]
|
| 117 |
+
if bias is not None:
|
| 118 |
+
bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)
|
| 119 |
+
observed.linear_Q.weight = torch.nn.Parameter(weight,
|
| 120 |
+
weight.requires_grad)
|
| 121 |
+
observed.linear_Q.bias = bias
|
| 122 |
+
|
| 123 |
+
bias = other.in_proj_bias
|
| 124 |
+
_start = _end
|
| 125 |
+
_end = _start + other.embed_dim
|
| 126 |
+
weight = other.in_proj_weight[_start:_end, :]
|
| 127 |
+
if bias is not None:
|
| 128 |
+
bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)
|
| 129 |
+
observed.linear_K.weight = torch.nn.Parameter(weight,
|
| 130 |
+
weight.requires_grad)
|
| 131 |
+
observed.linear_K.bias = bias
|
| 132 |
+
|
| 133 |
+
bias = other.in_proj_bias
|
| 134 |
+
_start = _end
|
| 135 |
+
weight = other.in_proj_weight[_start:, :]
|
| 136 |
+
if bias is not None:
|
| 137 |
+
bias = torch.nn.Parameter(bias[_start:], bias.requires_grad)
|
| 138 |
+
observed.linear_V.weight = torch.nn.Parameter(weight,
|
| 139 |
+
weight.requires_grad)
|
| 140 |
+
observed.linear_V.bias = bias
|
| 141 |
+
else:
|
| 142 |
+
observed.linear_Q.weight = nn.Parameter(other.q_proj_weight)
|
| 143 |
+
observed.linear_K.weight = nn.Parameter(other.k_proj_weight)
|
| 144 |
+
observed.linear_V.weight = nn.Parameter(other.v_proj_weight)
|
| 145 |
+
if other.in_proj_bias is None:
|
| 146 |
+
observed.linear_Q.bias = None # type: ignore[assignment]
|
| 147 |
+
observed.linear_K.bias = None # type: ignore[assignment]
|
| 148 |
+
observed.linear_V.bias = None # type: ignore[assignment]
|
| 149 |
+
else:
|
| 150 |
+
observed.linear_Q.bias = nn.Parameter(other.in_proj_bias[0:other.embed_dim])
|
| 151 |
+
observed.linear_K.bias = nn.Parameter(other.in_proj_bias[other.embed_dim:(other.embed_dim * 2)])
|
| 152 |
+
observed.linear_V.bias = nn.Parameter(other.in_proj_bias[(other.embed_dim * 2):])
|
| 153 |
+
observed.eval()
|
| 154 |
+
# Explicit prepare
|
| 155 |
+
observed = torch.ao.quantization.prepare(observed, inplace=True)
|
| 156 |
+
return observed
|
| 157 |
+
|
| 158 |
+
@torch.jit.unused
|
| 159 |
+
def dequantize(self):
|
| 160 |
+
r"""Utility to convert the quantized MHA back to float.
|
| 161 |
+
|
| 162 |
+
The motivation for this is that it is not trivial to conver the weights
|
| 163 |
+
from the format that is used in the quantized version back to the
|
| 164 |
+
float.
|
| 165 |
+
"""
|
| 166 |
+
fp = self._FLOAT_MODULE(self.embed_dim, self.num_heads, self.dropout,
|
| 167 |
+
(self.linear_Q._weight_bias()[1] is not None),
|
| 168 |
+
(self.bias_k is not None),
|
| 169 |
+
self.add_zero_attn, self.kdim, self.vdim, self.batch_first)
|
| 170 |
+
assert fp._qkv_same_embed_dim == self._qkv_same_embed_dim
|
| 171 |
+
if self.bias_k is not None:
|
| 172 |
+
fp.bias_k = nn.Parameter(self.bias_k.dequantize())
|
| 173 |
+
if self.bias_v is not None:
|
| 174 |
+
fp.bias_v = nn.Parameter(self.bias_v.dequantize())
|
| 175 |
+
|
| 176 |
+
# Set the linear weights
|
| 177 |
+
# Note: Because the linear layers are quantized, mypy does not nkow how
|
| 178 |
+
# to deal with them -- might need to ignore the typing checks.
|
| 179 |
+
# for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969
|
| 180 |
+
w, b = self.out_proj._weight_bias() # type: ignore[operator, has-type]
|
| 181 |
+
fp.out_proj.weight = nn.Parameter(w.dequantize())
|
| 182 |
+
if b is not None:
|
| 183 |
+
fp.out_proj.bias = nn.Parameter(b)
|
| 184 |
+
|
| 185 |
+
wQ, bQ = self.linear_Q._weight_bias() # type: ignore[operator]
|
| 186 |
+
wQ = wQ.dequantize()
|
| 187 |
+
wK, bK = self.linear_K._weight_bias() # type: ignore[operator]
|
| 188 |
+
wK = wK.dequantize()
|
| 189 |
+
wV, bV = self.linear_V._weight_bias() # type: ignore[operator]
|
| 190 |
+
wV = wV.dequantize()
|
| 191 |
+
if fp._qkv_same_embed_dim:
|
| 192 |
+
# Use separate params
|
| 193 |
+
_start = 0
|
| 194 |
+
_end = _start + fp.embed_dim
|
| 195 |
+
fp.in_proj_weight[_start:_end, :] = wQ
|
| 196 |
+
if fp.in_proj_bias is not None:
|
| 197 |
+
assert all(bQ == 0)
|
| 198 |
+
fp.in_proj_bias[_start:_end] = bQ
|
| 199 |
+
|
| 200 |
+
_start = _end
|
| 201 |
+
_end = _start + fp.embed_dim
|
| 202 |
+
fp.in_proj_weight[_start:_end, :] = wK
|
| 203 |
+
if fp.in_proj_bias is not None:
|
| 204 |
+
assert all(bK == 0)
|
| 205 |
+
fp.in_proj_bias[_start:_end] = bK
|
| 206 |
+
|
| 207 |
+
_start = _end
|
| 208 |
+
fp.in_proj_weight[_start:, :] = wV
|
| 209 |
+
if fp.in_proj_bias is not None:
|
| 210 |
+
assert all(bV == 0)
|
| 211 |
+
fp.in_proj_bias[_start:] = bV
|
| 212 |
+
else:
|
| 213 |
+
fp.q_proj_weight = nn.Parameter(wQ)
|
| 214 |
+
fp.k_proj_weight = nn.Parameter(wK)
|
| 215 |
+
fp.v_proj_weight = nn.Parameter(wV)
|
| 216 |
+
if fp.in_proj_bias is None:
|
| 217 |
+
self.linear_Q.bias = None
|
| 218 |
+
self.linear_K.bias = None
|
| 219 |
+
self.linear_V.bias = None
|
| 220 |
+
else:
|
| 221 |
+
fp.in_proj_bias[0:fp.embed_dim] = bQ
|
| 222 |
+
fp.in_proj_bias[fp.embed_dim:(fp.embed_dim * 2)] = bK
|
| 223 |
+
fp.in_proj_bias[(fp.embed_dim * 2):] = bV
|
| 224 |
+
|
| 225 |
+
return fp
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@classmethod
|
| 229 |
+
def from_observed(cls, other):
|
| 230 |
+
# The whole flow is float -> observed -> quantized
|
| 231 |
+
# This class does float -> observed only
|
| 232 |
+
# See nn.quantized.MultiheadAttention
|
| 233 |
+
raise NotImplementedError("It looks like you are trying to prepare an "
|
| 234 |
+
"MHA module. Please, see "
|
| 235 |
+
"the examples on quantizable MHAs.")
|
| 236 |
+
|
| 237 |
+
def forward(self,
|
| 238 |
+
query: Tensor,
|
| 239 |
+
key: Tensor,
|
| 240 |
+
value: Tensor,
|
| 241 |
+
key_padding_mask: Optional[Tensor] = None,
|
| 242 |
+
need_weights: bool = True,
|
| 243 |
+
attn_mask: Optional[Tensor] = None,
|
| 244 |
+
average_attn_weights: bool = True,
|
| 245 |
+
is_causal: bool = False) -> Tuple[Tensor, Optional[Tensor]]:
|
| 246 |
+
r"""
|
| 247 |
+
Note::
|
| 248 |
+
Please, refer to :func:`~torch.nn.MultiheadAttention.forward` for more
|
| 249 |
+
information
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
query, key, value: map a query and a set of key-value pairs to an output.
|
| 253 |
+
See "Attention Is All You Need" for more details.
|
| 254 |
+
key_padding_mask: if provided, specified padding elements in the key will
|
| 255 |
+
be ignored by the attention. When given a binary mask and a value is True,
|
| 256 |
+
the corresponding value on the attention layer will be ignored.
|
| 257 |
+
need_weights: output attn_output_weights.
|
| 258 |
+
attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
|
| 259 |
+
the batches while a 3D mask allows to specify a different mask for the entries of each batch.
|
| 260 |
+
|
| 261 |
+
Shape:
|
| 262 |
+
- Inputs:
|
| 263 |
+
- query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
|
| 264 |
+
the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.
|
| 265 |
+
- key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
|
| 266 |
+
the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.
|
| 267 |
+
- value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
|
| 268 |
+
the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.
|
| 269 |
+
- key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
|
| 270 |
+
If a BoolTensor is provided, the positions with the
|
| 271 |
+
value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
|
| 272 |
+
- attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
|
| 273 |
+
3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
|
| 274 |
+
S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked
|
| 275 |
+
positions. If a BoolTensor is provided, positions with ``True``
|
| 276 |
+
is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
|
| 277 |
+
is provided, it will be added to the attention weight.
|
| 278 |
+
- is_causal: If specified, applies a causal mask as attention mask. Mutually exclusive with providing attn_mask.
|
| 279 |
+
Default: ``False``.
|
| 280 |
+
- average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
|
| 281 |
+
heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
|
| 282 |
+
effect when ``need_weights=True.``. Default: True (i.e. average weights across heads)
|
| 283 |
+
|
| 284 |
+
- Outputs:
|
| 285 |
+
- attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
|
| 286 |
+
E is the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.
|
| 287 |
+
- attn_output_weights: If ``average_attn_weights=True``, returns attention weights averaged
|
| 288 |
+
across heads of shape :math:`(N, L, S)`, where N is the batch size, L is the target sequence length,
|
| 289 |
+
S is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
|
| 290 |
+
head of shape :math:`(N, num_heads, L, S)`.
|
| 291 |
+
"""
|
| 292 |
+
return self._forward_impl(query, key, value, key_padding_mask,
|
| 293 |
+
need_weights, attn_mask, average_attn_weights,
|
| 294 |
+
is_causal)
|
| 295 |
+
|
| 296 |
+
def _forward_impl(self,
|
| 297 |
+
query: Tensor,
|
| 298 |
+
key: Tensor,
|
| 299 |
+
value: Tensor,
|
| 300 |
+
key_padding_mask: Optional[Tensor] = None,
|
| 301 |
+
need_weights: bool = True,
|
| 302 |
+
attn_mask: Optional[Tensor] = None,
|
| 303 |
+
average_attn_weights: bool = True,
|
| 304 |
+
is_causal: bool = False) -> Tuple[Tensor, Optional[Tensor]]:
|
| 305 |
+
# This version will not deal with the static key/value pairs.
|
| 306 |
+
# Keeping it here for future changes.
|
| 307 |
+
#
|
| 308 |
+
# TODO: This method has some duplicate lines with the
|
| 309 |
+
# `torch.nn.functional.multi_head_attention`. Will need to refactor.
|
| 310 |
+
static_k = None
|
| 311 |
+
static_v = None
|
| 312 |
+
|
| 313 |
+
if attn_mask is not None and is_causal:
|
| 314 |
+
raise AssertionError("Only allow causal mask or attn_mask")
|
| 315 |
+
|
| 316 |
+
if is_causal:
|
| 317 |
+
raise AssertionError("causal mask not supported by AO MHA module")
|
| 318 |
+
|
| 319 |
+
if self.batch_first:
|
| 320 |
+
query, key, value = (x.transpose(0, 1) for x in (query, key, value))
|
| 321 |
+
|
| 322 |
+
tgt_len, bsz, embed_dim_to_check = query.size()
|
| 323 |
+
assert self.embed_dim == embed_dim_to_check
|
| 324 |
+
# allow MHA to have different sizes for the feature dimension
|
| 325 |
+
assert key.size(0) == value.size(0) and key.size(1) == value.size(1)
|
| 326 |
+
|
| 327 |
+
head_dim = self.embed_dim // self.num_heads
|
| 328 |
+
assert head_dim * self.num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
|
| 329 |
+
scaling = float(head_dim) ** -0.5
|
| 330 |
+
|
| 331 |
+
q = self.linear_Q(query)
|
| 332 |
+
k = self.linear_K(key)
|
| 333 |
+
v = self.linear_V(value)
|
| 334 |
+
|
| 335 |
+
q = self.q_scaling_product.mul_scalar(q, scaling)
|
| 336 |
+
|
| 337 |
+
if attn_mask is not None:
|
| 338 |
+
if attn_mask.dtype == torch.uint8:
|
| 339 |
+
warnings.warn("Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.")
|
| 340 |
+
attn_mask = attn_mask.to(torch.bool)
|
| 341 |
+
assert attn_mask.is_floating_point() or attn_mask.dtype == torch.bool, \
|
| 342 |
+
f'Only float and bool types are supported for attn_mask, not {attn_mask.dtype}'
|
| 343 |
+
|
| 344 |
+
if attn_mask.dim() == 2:
|
| 345 |
+
attn_mask = attn_mask.unsqueeze(0)
|
| 346 |
+
if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
|
| 347 |
+
raise RuntimeError('The size of the 2D attn_mask is not correct.')
|
| 348 |
+
elif attn_mask.dim() == 3:
|
| 349 |
+
if list(attn_mask.size()) != [bsz * self.num_heads, query.size(0), key.size(0)]:
|
| 350 |
+
raise RuntimeError('The size of the 3D attn_mask is not correct.')
|
| 351 |
+
else:
|
| 352 |
+
raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
|
| 353 |
+
# attn_mask's dim is 3 now.
|
| 354 |
+
|
| 355 |
+
# convert ByteTensor key_padding_mask to bool
|
| 356 |
+
if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
|
| 357 |
+
warnings.warn("Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.")
|
| 358 |
+
key_padding_mask = key_padding_mask.to(torch.bool)
|
| 359 |
+
if self.bias_k is not None and self.bias_v is not None:
|
| 360 |
+
if static_k is None and static_v is None:
|
| 361 |
+
|
| 362 |
+
# Explicitly assert that bias_k and bias_v are not None
|
| 363 |
+
# in a way that TorchScript can understand.
|
| 364 |
+
bias_k = self.bias_k
|
| 365 |
+
assert bias_k is not None
|
| 366 |
+
bias_v = self.bias_v
|
| 367 |
+
assert bias_v is not None
|
| 368 |
+
|
| 369 |
+
k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
|
| 370 |
+
v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
|
| 371 |
+
if attn_mask is not None:
|
| 372 |
+
attn_mask = nnF.pad(attn_mask, (0, 1))
|
| 373 |
+
if key_padding_mask is not None:
|
| 374 |
+
key_padding_mask = nnF.pad(key_padding_mask, (0, 1))
|
| 375 |
+
else:
|
| 376 |
+
assert static_k is None, "bias cannot be added to static key."
|
| 377 |
+
assert static_v is None, "bias cannot be added to static value."
|
| 378 |
+
else:
|
| 379 |
+
assert self.bias_k is None
|
| 380 |
+
assert self.bias_v is None
|
| 381 |
+
|
| 382 |
+
q = q.contiguous().view(tgt_len, bsz * self.num_heads, head_dim).transpose(0, 1)
|
| 383 |
+
if k is not None:
|
| 384 |
+
k = k.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)
|
| 385 |
+
if v is not None:
|
| 386 |
+
v = v.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)
|
| 387 |
+
|
| 388 |
+
if static_k is not None:
|
| 389 |
+
assert static_k.size(0) == bsz * self.num_heads
|
| 390 |
+
assert static_k.size(2) == head_dim
|
| 391 |
+
k = static_k
|
| 392 |
+
|
| 393 |
+
if static_v is not None:
|
| 394 |
+
assert static_v.size(0) == bsz * self.num_heads
|
| 395 |
+
assert static_v.size(2) == head_dim
|
| 396 |
+
v = static_v
|
| 397 |
+
|
| 398 |
+
src_len = k.size(1)
|
| 399 |
+
|
| 400 |
+
if key_padding_mask is not None:
|
| 401 |
+
assert key_padding_mask.size(0) == bsz
|
| 402 |
+
assert key_padding_mask.size(1) == src_len
|
| 403 |
+
|
| 404 |
+
if self.add_zero_attn:
|
| 405 |
+
src_len += 1
|
| 406 |
+
k_zeros = torch.zeros((k.size(0), 1) + k.size()[2:])
|
| 407 |
+
if k.is_quantized:
|
| 408 |
+
k_zeros = torch.quantize_per_tensor(k_zeros, k.q_scale(), k.q_zero_point(), k.dtype)
|
| 409 |
+
k = torch.cat([k, k_zeros], dim=1)
|
| 410 |
+
v_zeros = torch.zeros((v.size(0), 1) + k.size()[2:])
|
| 411 |
+
if v.is_quantized:
|
| 412 |
+
v_zeros = torch.quantize_per_tensor(v_zeros, v.q_scale(), v.q_zero_point(), v.dtype)
|
| 413 |
+
v = torch.cat([v, v_zeros], dim=1)
|
| 414 |
+
|
| 415 |
+
if attn_mask is not None:
|
| 416 |
+
attn_mask = nnF.pad(attn_mask, (0, 1))
|
| 417 |
+
if key_padding_mask is not None:
|
| 418 |
+
key_padding_mask = nnF.pad(key_padding_mask, (0, 1))
|
| 419 |
+
|
| 420 |
+
# Leaving the quantized zone here
|
| 421 |
+
q = self.dequant_q(q)
|
| 422 |
+
k = self.dequant_k(k)
|
| 423 |
+
v = self.dequant_v(v)
|
| 424 |
+
attn_output_weights = torch.bmm(q, k.transpose(1, 2))
|
| 425 |
+
assert list(attn_output_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
|
| 426 |
+
|
| 427 |
+
if attn_mask is not None:
|
| 428 |
+
if attn_mask.dtype == torch.bool:
|
| 429 |
+
attn_output_weights.masked_fill_(attn_mask, float('-inf'))
|
| 430 |
+
else:
|
| 431 |
+
attn_output_weights += attn_mask
|
| 432 |
+
|
| 433 |
+
if key_padding_mask is not None:
|
| 434 |
+
attn_output_weights = attn_output_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 435 |
+
attn_output_weights = attn_output_weights.masked_fill(
|
| 436 |
+
key_padding_mask.unsqueeze(1).unsqueeze(2),
|
| 437 |
+
float('-inf'),
|
| 438 |
+
)
|
| 439 |
+
attn_output_weights = attn_output_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 440 |
+
|
| 441 |
+
attn_output_weights = nnF.softmax(
|
| 442 |
+
attn_output_weights, dim=-1)
|
| 443 |
+
attn_output_weights = nnF.dropout(attn_output_weights, p=self.dropout, training=self.training)
|
| 444 |
+
|
| 445 |
+
attn_output = torch.bmm(attn_output_weights, v)
|
| 446 |
+
assert list(attn_output.size()) == [bsz * self.num_heads, tgt_len, head_dim]
|
| 447 |
+
if self.batch_first:
|
| 448 |
+
attn_output = attn_output.view(bsz, tgt_len, self.embed_dim)
|
| 449 |
+
else:
|
| 450 |
+
attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, self.embed_dim)
|
| 451 |
+
|
| 452 |
+
# Reentering the quantized zone
|
| 453 |
+
attn_output = self.quant_attn_output(attn_output)
|
| 454 |
+
# for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969
|
| 455 |
+
attn_output = self.out_proj(attn_output) # type: ignore[has-type]
|
| 456 |
+
attn_output_weights = self.quant_attn_output_weights(attn_output_weights)
|
| 457 |
+
|
| 458 |
+
if need_weights:
|
| 459 |
+
# average attention weights over heads
|
| 460 |
+
attn_output_weights = attn_output_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 461 |
+
if average_attn_weights:
|
| 462 |
+
attn_output_weights = attn_output_weights.mean(dim=1)
|
| 463 |
+
return attn_output, attn_output_weights
|
| 464 |
+
else:
|
| 465 |
+
return attn_output, None
|
videollama2/lib/python3.10/site-packages/torch/ao/nn/quantizable/modules/rnn.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 5 |
+
import torch
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
We will recreate all the RNN modules as we require the modules to be decomposed
|
| 10 |
+
into its building blocks to be able to observe.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"LSTMCell",
|
| 15 |
+
"LSTM"
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
class LSTMCell(torch.nn.Module):
|
| 19 |
+
r"""A quantizable long short-term memory (LSTM) cell.
|
| 20 |
+
|
| 21 |
+
For the description and the argument types, please, refer to :class:`~torch.nn.LSTMCell`
|
| 22 |
+
|
| 23 |
+
Examples::
|
| 24 |
+
|
| 25 |
+
>>> import torch.ao.nn.quantizable as nnqa
|
| 26 |
+
>>> rnn = nnqa.LSTMCell(10, 20)
|
| 27 |
+
>>> input = torch.randn(6, 10)
|
| 28 |
+
>>> hx = torch.randn(3, 20)
|
| 29 |
+
>>> cx = torch.randn(3, 20)
|
| 30 |
+
>>> output = []
|
| 31 |
+
>>> for i in range(6):
|
| 32 |
+
... hx, cx = rnn(input[i], (hx, cx))
|
| 33 |
+
... output.append(hx)
|
| 34 |
+
"""
|
| 35 |
+
_FLOAT_MODULE = torch.nn.LSTMCell
|
| 36 |
+
|
| 37 |
+
def __init__(self, input_dim: int, hidden_dim: int, bias: bool = True,
|
| 38 |
+
device=None, dtype=None) -> None:
|
| 39 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.input_size = input_dim
|
| 42 |
+
self.hidden_size = hidden_dim
|
| 43 |
+
self.bias = bias
|
| 44 |
+
|
| 45 |
+
self.igates = torch.nn.Linear(input_dim, 4 * hidden_dim, bias=bias, **factory_kwargs)
|
| 46 |
+
self.hgates = torch.nn.Linear(hidden_dim, 4 * hidden_dim, bias=bias, **factory_kwargs)
|
| 47 |
+
self.gates = torch.ao.nn.quantized.FloatFunctional()
|
| 48 |
+
|
| 49 |
+
self.input_gate = torch.nn.Sigmoid()
|
| 50 |
+
self.forget_gate = torch.nn.Sigmoid()
|
| 51 |
+
self.cell_gate = torch.nn.Tanh()
|
| 52 |
+
self.output_gate = torch.nn.Sigmoid()
|
| 53 |
+
|
| 54 |
+
self.fgate_cx = torch.ao.nn.quantized.FloatFunctional()
|
| 55 |
+
self.igate_cgate = torch.ao.nn.quantized.FloatFunctional()
|
| 56 |
+
self.fgate_cx_igate_cgate = torch.ao.nn.quantized.FloatFunctional()
|
| 57 |
+
|
| 58 |
+
self.ogate_cy = torch.ao.nn.quantized.FloatFunctional()
|
| 59 |
+
|
| 60 |
+
self.initial_hidden_state_qparams: Tuple[float, int] = (1.0, 0)
|
| 61 |
+
self.initial_cell_state_qparams: Tuple[float, int] = (1.0, 0)
|
| 62 |
+
self.hidden_state_dtype: torch.dtype = torch.quint8
|
| 63 |
+
self.cell_state_dtype: torch.dtype = torch.quint8
|
| 64 |
+
|
| 65 |
+
def forward(self, x: Tensor, hidden: Optional[Tuple[Tensor, Tensor]] = None) -> Tuple[Tensor, Tensor]:
|
| 66 |
+
if hidden is None or hidden[0] is None or hidden[1] is None:
|
| 67 |
+
hidden = self.initialize_hidden(x.shape[0], x.is_quantized)
|
| 68 |
+
hx, cx = hidden
|
| 69 |
+
|
| 70 |
+
igates = self.igates(x)
|
| 71 |
+
hgates = self.hgates(hx)
|
| 72 |
+
gates = self.gates.add(igates, hgates)
|
| 73 |
+
|
| 74 |
+
input_gate, forget_gate, cell_gate, out_gate = gates.chunk(4, 1)
|
| 75 |
+
|
| 76 |
+
input_gate = self.input_gate(input_gate)
|
| 77 |
+
forget_gate = self.forget_gate(forget_gate)
|
| 78 |
+
cell_gate = self.cell_gate(cell_gate)
|
| 79 |
+
out_gate = self.output_gate(out_gate)
|
| 80 |
+
|
| 81 |
+
fgate_cx = self.fgate_cx.mul(forget_gate, cx)
|
| 82 |
+
igate_cgate = self.igate_cgate.mul(input_gate, cell_gate)
|
| 83 |
+
fgate_cx_igate_cgate = self.fgate_cx_igate_cgate.add(fgate_cx, igate_cgate)
|
| 84 |
+
cy = fgate_cx_igate_cgate
|
| 85 |
+
|
| 86 |
+
# TODO: make this tanh a member of the module so its qparams can be configured
|
| 87 |
+
tanh_cy = torch.tanh(cy)
|
| 88 |
+
hy = self.ogate_cy.mul(out_gate, tanh_cy)
|
| 89 |
+
return hy, cy
|
| 90 |
+
|
| 91 |
+
def initialize_hidden(self, batch_size: int, is_quantized: bool = False) -> Tuple[Tensor, Tensor]:
|
| 92 |
+
h, c = torch.zeros((batch_size, self.hidden_size)), torch.zeros((batch_size, self.hidden_size))
|
| 93 |
+
if is_quantized:
|
| 94 |
+
(h_scale, h_zp) = self.initial_hidden_state_qparams
|
| 95 |
+
(c_scale, c_zp) = self.initial_cell_state_qparams
|
| 96 |
+
h = torch.quantize_per_tensor(h, scale=h_scale, zero_point=h_zp, dtype=self.hidden_state_dtype)
|
| 97 |
+
c = torch.quantize_per_tensor(c, scale=c_scale, zero_point=c_zp, dtype=self.cell_state_dtype)
|
| 98 |
+
return h, c
|
| 99 |
+
|
| 100 |
+
def _get_name(self):
|
| 101 |
+
return 'QuantizableLSTMCell'
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def from_params(cls, wi, wh, bi=None, bh=None):
|
| 105 |
+
"""Uses the weights and biases to create a new LSTM cell.
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
wi, wh: Weights for the input and hidden layers
|
| 109 |
+
bi, bh: Biases for the input and hidden layers
|
| 110 |
+
"""
|
| 111 |
+
assert (bi is None) == (bh is None) # Either both None or both have values
|
| 112 |
+
input_size = wi.shape[1]
|
| 113 |
+
hidden_size = wh.shape[1]
|
| 114 |
+
cell = cls(input_dim=input_size, hidden_dim=hidden_size,
|
| 115 |
+
bias=(bi is not None))
|
| 116 |
+
cell.igates.weight = torch.nn.Parameter(wi)
|
| 117 |
+
if bi is not None:
|
| 118 |
+
cell.igates.bias = torch.nn.Parameter(bi)
|
| 119 |
+
cell.hgates.weight = torch.nn.Parameter(wh)
|
| 120 |
+
if bh is not None:
|
| 121 |
+
cell.hgates.bias = torch.nn.Parameter(bh)
|
| 122 |
+
return cell
|
| 123 |
+
|
| 124 |
+
@classmethod
|
| 125 |
+
def from_float(cls, other):
|
| 126 |
+
assert type(other) == cls._FLOAT_MODULE
|
| 127 |
+
assert hasattr(other, 'qconfig'), "The float module must have 'qconfig'"
|
| 128 |
+
observed = cls.from_params(other.weight_ih, other.weight_hh,
|
| 129 |
+
other.bias_ih, other.bias_hh)
|
| 130 |
+
observed.qconfig = other.qconfig
|
| 131 |
+
observed.igates.qconfig = other.qconfig
|
| 132 |
+
observed.hgates.qconfig = other.qconfig
|
| 133 |
+
return observed
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class _LSTMSingleLayer(torch.nn.Module):
|
| 137 |
+
r"""A single one-directional LSTM layer.
|
| 138 |
+
|
| 139 |
+
The difference between a layer and a cell is that the layer can process a
|
| 140 |
+
sequence, while the cell only expects an instantaneous value.
|
| 141 |
+
"""
|
| 142 |
+
def __init__(self, input_dim: int, hidden_dim: int, bias: bool = True,
|
| 143 |
+
device=None, dtype=None) -> None:
|
| 144 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 145 |
+
super().__init__()
|
| 146 |
+
self.cell = LSTMCell(input_dim, hidden_dim, bias=bias, **factory_kwargs)
|
| 147 |
+
|
| 148 |
+
def forward(self, x: Tensor, hidden: Optional[Tuple[Tensor, Tensor]] = None):
|
| 149 |
+
result = []
|
| 150 |
+
seq_len = x.shape[0]
|
| 151 |
+
for i in range(seq_len):
|
| 152 |
+
hidden = self.cell(x[i], hidden)
|
| 153 |
+
result.append(hidden[0]) # type: ignore[index]
|
| 154 |
+
result_tensor = torch.stack(result, 0)
|
| 155 |
+
return result_tensor, hidden
|
| 156 |
+
|
| 157 |
+
@classmethod
|
| 158 |
+
def from_params(cls, *args, **kwargs):
|
| 159 |
+
cell = LSTMCell.from_params(*args, **kwargs)
|
| 160 |
+
layer = cls(cell.input_size, cell.hidden_size, cell.bias)
|
| 161 |
+
layer.cell = cell
|
| 162 |
+
return layer
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class _LSTMLayer(torch.nn.Module):
|
| 166 |
+
r"""A single bi-directional LSTM layer."""
|
| 167 |
+
def __init__(self, input_dim: int, hidden_dim: int, bias: bool = True,
|
| 168 |
+
batch_first: bool = False, bidirectional: bool = False,
|
| 169 |
+
device=None, dtype=None) -> None:
|
| 170 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.batch_first = batch_first
|
| 173 |
+
self.bidirectional = bidirectional
|
| 174 |
+
self.layer_fw = _LSTMSingleLayer(input_dim, hidden_dim, bias=bias, **factory_kwargs)
|
| 175 |
+
if self.bidirectional:
|
| 176 |
+
self.layer_bw = _LSTMSingleLayer(input_dim, hidden_dim, bias=bias, **factory_kwargs)
|
| 177 |
+
|
| 178 |
+
def forward(self, x: Tensor, hidden: Optional[Tuple[Tensor, Tensor]] = None):
|
| 179 |
+
if self.batch_first:
|
| 180 |
+
x = x.transpose(0, 1)
|
| 181 |
+
if hidden is None:
|
| 182 |
+
hx_fw, cx_fw = (None, None)
|
| 183 |
+
else:
|
| 184 |
+
hx_fw, cx_fw = hidden
|
| 185 |
+
hidden_bw: Optional[Tuple[Tensor, Tensor]] = None
|
| 186 |
+
if self.bidirectional:
|
| 187 |
+
if hx_fw is None:
|
| 188 |
+
hx_bw = None
|
| 189 |
+
else:
|
| 190 |
+
hx_bw = hx_fw[1]
|
| 191 |
+
hx_fw = hx_fw[0]
|
| 192 |
+
if cx_fw is None:
|
| 193 |
+
cx_bw = None
|
| 194 |
+
else:
|
| 195 |
+
cx_bw = cx_fw[1]
|
| 196 |
+
cx_fw = cx_fw[0]
|
| 197 |
+
if hx_bw is not None and cx_bw is not None:
|
| 198 |
+
hidden_bw = hx_bw, cx_bw
|
| 199 |
+
if hx_fw is None and cx_fw is None:
|
| 200 |
+
hidden_fw = None
|
| 201 |
+
else:
|
| 202 |
+
hidden_fw = torch.jit._unwrap_optional(hx_fw), torch.jit._unwrap_optional(cx_fw)
|
| 203 |
+
result_fw, hidden_fw = self.layer_fw(x, hidden_fw)
|
| 204 |
+
|
| 205 |
+
if hasattr(self, 'layer_bw') and self.bidirectional:
|
| 206 |
+
x_reversed = x.flip(0)
|
| 207 |
+
result_bw, hidden_bw = self.layer_bw(x_reversed, hidden_bw)
|
| 208 |
+
result_bw = result_bw.flip(0)
|
| 209 |
+
|
| 210 |
+
result = torch.cat([result_fw, result_bw], result_fw.dim() - 1)
|
| 211 |
+
if hidden_fw is None and hidden_bw is None:
|
| 212 |
+
h = None
|
| 213 |
+
c = None
|
| 214 |
+
elif hidden_fw is None:
|
| 215 |
+
(h, c) = torch.jit._unwrap_optional(hidden_bw)
|
| 216 |
+
elif hidden_bw is None:
|
| 217 |
+
(h, c) = torch.jit._unwrap_optional(hidden_fw)
|
| 218 |
+
else:
|
| 219 |
+
h = torch.stack([hidden_fw[0], hidden_bw[0]], 0) # type: ignore[list-item]
|
| 220 |
+
c = torch.stack([hidden_fw[1], hidden_bw[1]], 0) # type: ignore[list-item]
|
| 221 |
+
else:
|
| 222 |
+
result = result_fw
|
| 223 |
+
h, c = torch.jit._unwrap_optional(hidden_fw) # type: ignore[assignment]
|
| 224 |
+
|
| 225 |
+
if self.batch_first:
|
| 226 |
+
result.transpose_(0, 1)
|
| 227 |
+
|
| 228 |
+
return result, (h, c)
|
| 229 |
+
|
| 230 |
+
@classmethod
|
| 231 |
+
def from_float(cls, other, layer_idx=0, qconfig=None, **kwargs):
|
| 232 |
+
r"""
|
| 233 |
+
There is no FP equivalent of this class. This function is here just to
|
| 234 |
+
mimic the behavior of the `prepare` within the `torch.ao.quantization`
|
| 235 |
+
flow.
|
| 236 |
+
"""
|
| 237 |
+
assert hasattr(other, 'qconfig') or (qconfig is not None)
|
| 238 |
+
|
| 239 |
+
input_size = kwargs.get('input_size', other.input_size)
|
| 240 |
+
hidden_size = kwargs.get('hidden_size', other.hidden_size)
|
| 241 |
+
bias = kwargs.get('bias', other.bias)
|
| 242 |
+
batch_first = kwargs.get('batch_first', other.batch_first)
|
| 243 |
+
bidirectional = kwargs.get('bidirectional', other.bidirectional)
|
| 244 |
+
|
| 245 |
+
layer = cls(input_size, hidden_size, bias, batch_first, bidirectional)
|
| 246 |
+
layer.qconfig = getattr(other, 'qconfig', qconfig)
|
| 247 |
+
wi = getattr(other, f'weight_ih_l{layer_idx}')
|
| 248 |
+
wh = getattr(other, f'weight_hh_l{layer_idx}')
|
| 249 |
+
bi = getattr(other, f'bias_ih_l{layer_idx}', None)
|
| 250 |
+
bh = getattr(other, f'bias_hh_l{layer_idx}', None)
|
| 251 |
+
|
| 252 |
+
layer.layer_fw = _LSTMSingleLayer.from_params(wi, wh, bi, bh)
|
| 253 |
+
|
| 254 |
+
if other.bidirectional:
|
| 255 |
+
wi = getattr(other, f'weight_ih_l{layer_idx}_reverse')
|
| 256 |
+
wh = getattr(other, f'weight_hh_l{layer_idx}_reverse')
|
| 257 |
+
bi = getattr(other, f'bias_ih_l{layer_idx}_reverse', None)
|
| 258 |
+
bh = getattr(other, f'bias_hh_l{layer_idx}_reverse', None)
|
| 259 |
+
layer.layer_bw = _LSTMSingleLayer.from_params(wi, wh, bi, bh)
|
| 260 |
+
return layer
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class LSTM(torch.nn.Module):
|
| 264 |
+
r"""A quantizable long short-term memory (LSTM).
|
| 265 |
+
|
| 266 |
+
For the description and the argument types, please, refer to :class:`~torch.nn.LSTM`
|
| 267 |
+
|
| 268 |
+
Attributes:
|
| 269 |
+
layers : instances of the `_LSTMLayer`
|
| 270 |
+
|
| 271 |
+
.. note::
|
| 272 |
+
To access the weights and biases, you need to access them per layer.
|
| 273 |
+
See examples below.
|
| 274 |
+
|
| 275 |
+
Examples::
|
| 276 |
+
|
| 277 |
+
>>> import torch.ao.nn.quantizable as nnqa
|
| 278 |
+
>>> rnn = nnqa.LSTM(10, 20, 2)
|
| 279 |
+
>>> input = torch.randn(5, 3, 10)
|
| 280 |
+
>>> h0 = torch.randn(2, 3, 20)
|
| 281 |
+
>>> c0 = torch.randn(2, 3, 20)
|
| 282 |
+
>>> output, (hn, cn) = rnn(input, (h0, c0))
|
| 283 |
+
>>> # To get the weights:
|
| 284 |
+
>>> # xdoctest: +SKIP
|
| 285 |
+
>>> print(rnn.layers[0].weight_ih)
|
| 286 |
+
tensor([[...]])
|
| 287 |
+
>>> print(rnn.layers[0].weight_hh)
|
| 288 |
+
AssertionError: There is no reverse path in the non-bidirectional layer
|
| 289 |
+
"""
|
| 290 |
+
_FLOAT_MODULE = torch.nn.LSTM
|
| 291 |
+
|
| 292 |
+
def __init__(self, input_size: int, hidden_size: int,
|
| 293 |
+
num_layers: int = 1, bias: bool = True,
|
| 294 |
+
batch_first: bool = False, dropout: float = 0.,
|
| 295 |
+
bidirectional: bool = False,
|
| 296 |
+
device=None, dtype=None) -> None:
|
| 297 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 298 |
+
super().__init__()
|
| 299 |
+
self.input_size = input_size
|
| 300 |
+
self.hidden_size = hidden_size
|
| 301 |
+
self.num_layers = num_layers
|
| 302 |
+
self.bias = bias
|
| 303 |
+
self.batch_first = batch_first
|
| 304 |
+
self.dropout = float(dropout)
|
| 305 |
+
self.bidirectional = bidirectional
|
| 306 |
+
self.training = False # We don't want to train using this module
|
| 307 |
+
num_directions = 2 if bidirectional else 1
|
| 308 |
+
|
| 309 |
+
if not isinstance(dropout, numbers.Number) or not 0 <= dropout <= 1 or \
|
| 310 |
+
isinstance(dropout, bool):
|
| 311 |
+
raise ValueError("dropout should be a number in range [0, 1] "
|
| 312 |
+
"representing the probability of an element being "
|
| 313 |
+
"zeroed")
|
| 314 |
+
if dropout > 0:
|
| 315 |
+
warnings.warn("dropout option for quantizable LSTM is ignored. "
|
| 316 |
+
"If you are training, please, use nn.LSTM version "
|
| 317 |
+
"followed by `prepare` step.")
|
| 318 |
+
if num_layers == 1:
|
| 319 |
+
warnings.warn("dropout option adds dropout after all but last "
|
| 320 |
+
"recurrent layer, so non-zero dropout expects "
|
| 321 |
+
f"num_layers greater than 1, but got dropout={dropout} "
|
| 322 |
+
f"and num_layers={num_layers}")
|
| 323 |
+
|
| 324 |
+
layers = [_LSTMLayer(self.input_size, self.hidden_size,
|
| 325 |
+
self.bias, batch_first=False,
|
| 326 |
+
bidirectional=self.bidirectional, **factory_kwargs)]
|
| 327 |
+
for layer in range(1, num_layers):
|
| 328 |
+
layers.append(_LSTMLayer(self.hidden_size, self.hidden_size,
|
| 329 |
+
self.bias, batch_first=False,
|
| 330 |
+
bidirectional=self.bidirectional,
|
| 331 |
+
**factory_kwargs))
|
| 332 |
+
self.layers = torch.nn.ModuleList(layers)
|
| 333 |
+
|
| 334 |
+
def forward(self, x: Tensor, hidden: Optional[Tuple[Tensor, Tensor]] = None):
|
| 335 |
+
if self.batch_first:
|
| 336 |
+
x = x.transpose(0, 1)
|
| 337 |
+
|
| 338 |
+
max_batch_size = x.size(1)
|
| 339 |
+
num_directions = 2 if self.bidirectional else 1
|
| 340 |
+
if hidden is None:
|
| 341 |
+
zeros = torch.zeros(num_directions, max_batch_size,
|
| 342 |
+
self.hidden_size, dtype=torch.float,
|
| 343 |
+
device=x.device)
|
| 344 |
+
zeros.squeeze_(0)
|
| 345 |
+
if x.is_quantized:
|
| 346 |
+
zeros = torch.quantize_per_tensor(zeros, scale=1.0,
|
| 347 |
+
zero_point=0, dtype=x.dtype)
|
| 348 |
+
hxcx = [(zeros, zeros) for _ in range(self.num_layers)]
|
| 349 |
+
else:
|
| 350 |
+
hidden_non_opt = torch.jit._unwrap_optional(hidden)
|
| 351 |
+
if isinstance(hidden_non_opt[0], Tensor):
|
| 352 |
+
hx = hidden_non_opt[0].reshape(self.num_layers, num_directions,
|
| 353 |
+
max_batch_size,
|
| 354 |
+
self.hidden_size)
|
| 355 |
+
cx = hidden_non_opt[1].reshape(self.num_layers, num_directions,
|
| 356 |
+
max_batch_size,
|
| 357 |
+
self.hidden_size)
|
| 358 |
+
hxcx = [(hx[idx].squeeze(0), cx[idx].squeeze(0)) for idx in range(self.num_layers)]
|
| 359 |
+
else:
|
| 360 |
+
hxcx = hidden_non_opt
|
| 361 |
+
|
| 362 |
+
hx_list = []
|
| 363 |
+
cx_list = []
|
| 364 |
+
for idx, layer in enumerate(self.layers):
|
| 365 |
+
x, (h, c) = layer(x, hxcx[idx])
|
| 366 |
+
hx_list.append(torch.jit._unwrap_optional(h))
|
| 367 |
+
cx_list.append(torch.jit._unwrap_optional(c))
|
| 368 |
+
hx_tensor = torch.stack(hx_list)
|
| 369 |
+
cx_tensor = torch.stack(cx_list)
|
| 370 |
+
|
| 371 |
+
# We are creating another dimension for bidirectional case
|
| 372 |
+
# need to collapse it
|
| 373 |
+
hx_tensor = hx_tensor.reshape(-1, hx_tensor.shape[-2], hx_tensor.shape[-1])
|
| 374 |
+
cx_tensor = cx_tensor.reshape(-1, cx_tensor.shape[-2], cx_tensor.shape[-1])
|
| 375 |
+
|
| 376 |
+
if self.batch_first:
|
| 377 |
+
x = x.transpose(0, 1)
|
| 378 |
+
|
| 379 |
+
return x, (hx_tensor, cx_tensor)
|
| 380 |
+
|
| 381 |
+
def _get_name(self):
|
| 382 |
+
return 'QuantizableLSTM'
|
| 383 |
+
|
| 384 |
+
@classmethod
|
| 385 |
+
def from_float(cls, other, qconfig=None):
|
| 386 |
+
assert isinstance(other, cls._FLOAT_MODULE)
|
| 387 |
+
assert (hasattr(other, 'qconfig') or qconfig)
|
| 388 |
+
observed = cls(other.input_size, other.hidden_size, other.num_layers,
|
| 389 |
+
other.bias, other.batch_first, other.dropout,
|
| 390 |
+
other.bidirectional)
|
| 391 |
+
observed.qconfig = getattr(other, 'qconfig', qconfig)
|
| 392 |
+
for idx in range(other.num_layers):
|
| 393 |
+
observed.layers[idx] = _LSTMLayer.from_float(other, idx, qconfig,
|
| 394 |
+
batch_first=False)
|
| 395 |
+
# TODO: Remove setting observed to eval to enable QAT.
|
| 396 |
+
observed.eval()
|
| 397 |
+
observed = torch.ao.quantization.prepare(observed, inplace=True)
|
| 398 |
+
return observed
|
| 399 |
+
|
| 400 |
+
@classmethod
|
| 401 |
+
def from_observed(cls, other):
|
| 402 |
+
# The whole flow is float -> observed -> quantized
|
| 403 |
+
# This class does float -> observed only
|
| 404 |
+
raise NotImplementedError("It looks like you are trying to convert a "
|
| 405 |
+
"non-quantizable LSTM module. Please, see "
|
| 406 |
+
"the examples on quantizable LSTMs.")
|
videollama2/lib/python3.10/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/rnn.cpython-310.pyc
ADDED
|
Binary file (34.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/outlines_core/fsm/outlines_core_rs.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e9a231bd30ef80646ad76cd96b9cb9023ead8ad388ad2074cce366f24da30d28
|
| 3 |
+
size 686840
|
vllm/lib/python3.10/site-packages/pyarrow/__init__.pxd
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
from libcpp.memory cimport shared_ptr
|
| 19 |
+
from pyarrow.includes.libarrow cimport (CArray, CBuffer, CDataType,
|
| 20 |
+
CField, CRecordBatch, CSchema,
|
| 21 |
+
CTable, CTensor, CSparseCOOTensor,
|
| 22 |
+
CSparseCSRMatrix, CSparseCSCMatrix,
|
| 23 |
+
CSparseCSFTensor)
|
| 24 |
+
|
| 25 |
+
cdef extern from "arrow/python/pyarrow.h" namespace "arrow::py":
|
| 26 |
+
cdef int import_pyarrow() except -1
|
| 27 |
+
cdef object wrap_buffer(const shared_ptr[CBuffer]& buffer)
|
| 28 |
+
cdef object wrap_data_type(const shared_ptr[CDataType]& type)
|
| 29 |
+
cdef object wrap_field(const shared_ptr[CField]& field)
|
| 30 |
+
cdef object wrap_schema(const shared_ptr[CSchema]& schema)
|
| 31 |
+
cdef object wrap_array(const shared_ptr[CArray]& sp_array)
|
| 32 |
+
cdef object wrap_tensor(const shared_ptr[CTensor]& sp_tensor)
|
| 33 |
+
cdef object wrap_sparse_tensor_coo(
|
| 34 |
+
const shared_ptr[CSparseCOOTensor]& sp_sparse_tensor)
|
| 35 |
+
cdef object wrap_sparse_tensor_csr(
|
| 36 |
+
const shared_ptr[CSparseCSRMatrix]& sp_sparse_tensor)
|
| 37 |
+
cdef object wrap_sparse_tensor_csc(
|
| 38 |
+
const shared_ptr[CSparseCSCMatrix]& sp_sparse_tensor)
|
| 39 |
+
cdef object wrap_sparse_tensor_csf(
|
| 40 |
+
const shared_ptr[CSparseCSFTensor]& sp_sparse_tensor)
|
| 41 |
+
cdef object wrap_table(const shared_ptr[CTable]& ctable)
|
| 42 |
+
cdef object wrap_batch(const shared_ptr[CRecordBatch]& cbatch)
|
vllm/lib/python3.10/site-packages/pyarrow/_acero.pxd
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# cython: language_level = 3
|
| 19 |
+
|
| 20 |
+
from pyarrow.lib cimport *
|
| 21 |
+
from pyarrow.includes.common cimport *
|
| 22 |
+
from pyarrow.includes.libarrow cimport *
|
| 23 |
+
from pyarrow.includes.libarrow_acero cimport *
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
cdef class ExecNodeOptions(_Weakrefable):
|
| 27 |
+
cdef:
|
| 28 |
+
shared_ptr[CExecNodeOptions] wrapped
|
| 29 |
+
|
| 30 |
+
cdef void init(self, const shared_ptr[CExecNodeOptions]& sp)
|
| 31 |
+
cdef inline shared_ptr[CExecNodeOptions] unwrap(self) nogil
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
cdef class Declaration(_Weakrefable):
|
| 35 |
+
|
| 36 |
+
cdef:
|
| 37 |
+
CDeclaration decl
|
| 38 |
+
|
| 39 |
+
cdef void init(self, const CDeclaration& c_decl)
|
| 40 |
+
|
| 41 |
+
@staticmethod
|
| 42 |
+
cdef wrap(const CDeclaration& c_decl)
|
| 43 |
+
|
| 44 |
+
cdef inline CDeclaration unwrap(self) nogil
|
vllm/lib/python3.10/site-packages/pyarrow/_cuda.pxd
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# cython: language_level = 3
|
| 19 |
+
|
| 20 |
+
from pyarrow.lib cimport *
|
| 21 |
+
from pyarrow.includes.common cimport *
|
| 22 |
+
from pyarrow.includes.libarrow cimport *
|
| 23 |
+
from pyarrow.includes.libarrow_cuda cimport *
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
cdef class Context(_Weakrefable):
|
| 27 |
+
cdef:
|
| 28 |
+
shared_ptr[CCudaContext] context
|
| 29 |
+
int device_number
|
| 30 |
+
|
| 31 |
+
cdef void init(self, const shared_ptr[CCudaContext]& ctx)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
cdef class IpcMemHandle(_Weakrefable):
|
| 35 |
+
cdef:
|
| 36 |
+
shared_ptr[CCudaIpcMemHandle] handle
|
| 37 |
+
|
| 38 |
+
cdef void init(self, shared_ptr[CCudaIpcMemHandle]& h)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
cdef class CudaBuffer(Buffer):
|
| 42 |
+
cdef:
|
| 43 |
+
shared_ptr[CCudaBuffer] cuda_buffer
|
| 44 |
+
object base
|
| 45 |
+
|
| 46 |
+
cdef void init_cuda(self,
|
| 47 |
+
const shared_ptr[CCudaBuffer]& buffer,
|
| 48 |
+
object base)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
cdef class HostBuffer(Buffer):
|
| 52 |
+
cdef:
|
| 53 |
+
shared_ptr[CCudaHostBuffer] host_buffer
|
| 54 |
+
|
| 55 |
+
cdef void init_host(self, const shared_ptr[CCudaHostBuffer]& buffer)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
cdef class BufferReader(NativeFile):
|
| 59 |
+
cdef:
|
| 60 |
+
CCudaBufferReader* reader
|
| 61 |
+
CudaBuffer buffer
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
cdef class BufferWriter(NativeFile):
|
| 65 |
+
cdef:
|
| 66 |
+
CCudaBufferWriter* writer
|
| 67 |
+
CudaBuffer buffer
|
vllm/lib/python3.10/site-packages/pyarrow/_cuda.pyx
ADDED
|
@@ -0,0 +1,1080 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
from pyarrow.lib cimport *
|
| 20 |
+
from pyarrow.includes.libarrow_cuda cimport *
|
| 21 |
+
from pyarrow.lib import allocate_buffer, as_buffer, ArrowTypeError
|
| 22 |
+
from pyarrow.util import get_contiguous_span
|
| 23 |
+
cimport cpython as cp
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
cdef class Context(_Weakrefable):
|
| 27 |
+
"""
|
| 28 |
+
CUDA driver context.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, *args, **kwargs):
|
| 32 |
+
"""
|
| 33 |
+
Create a CUDA driver context for a particular device.
|
| 34 |
+
|
| 35 |
+
If a CUDA context handle is passed, it is wrapped, otherwise
|
| 36 |
+
a default CUDA context for the given device is requested.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
device_number : int (default 0)
|
| 41 |
+
Specify the GPU device for which the CUDA driver context is
|
| 42 |
+
requested.
|
| 43 |
+
handle : int, optional
|
| 44 |
+
Specify CUDA handle for a shared context that has been created
|
| 45 |
+
by another library.
|
| 46 |
+
"""
|
| 47 |
+
# This method exposed because autodoc doesn't pick __cinit__
|
| 48 |
+
|
| 49 |
+
def __cinit__(self, int device_number=0, uintptr_t handle=0):
|
| 50 |
+
cdef CCudaDeviceManager* manager
|
| 51 |
+
manager = GetResultValue(CCudaDeviceManager.Instance())
|
| 52 |
+
cdef int n = manager.num_devices()
|
| 53 |
+
if device_number >= n or device_number < 0:
|
| 54 |
+
self.context.reset()
|
| 55 |
+
raise ValueError('device_number argument must be '
|
| 56 |
+
'non-negative less than %s' % (n))
|
| 57 |
+
if handle == 0:
|
| 58 |
+
self.context = GetResultValue(manager.GetContext(device_number))
|
| 59 |
+
else:
|
| 60 |
+
self.context = GetResultValue(manager.GetSharedContext(
|
| 61 |
+
device_number, <void*>handle))
|
| 62 |
+
self.device_number = device_number
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def from_numba(context=None):
|
| 66 |
+
"""
|
| 67 |
+
Create a Context instance from a Numba CUDA context.
|
| 68 |
+
|
| 69 |
+
Parameters
|
| 70 |
+
----------
|
| 71 |
+
context : {numba.cuda.cudadrv.driver.Context, None}
|
| 72 |
+
A Numba CUDA context instance.
|
| 73 |
+
If None, the current Numba context is used.
|
| 74 |
+
|
| 75 |
+
Returns
|
| 76 |
+
-------
|
| 77 |
+
shared_context : pyarrow.cuda.Context
|
| 78 |
+
Context instance.
|
| 79 |
+
"""
|
| 80 |
+
if context is None:
|
| 81 |
+
import numba.cuda
|
| 82 |
+
context = numba.cuda.current_context()
|
| 83 |
+
return Context(device_number=context.device.id,
|
| 84 |
+
handle=context.handle.value)
|
| 85 |
+
|
| 86 |
+
def to_numba(self):
|
| 87 |
+
"""
|
| 88 |
+
Convert Context to a Numba CUDA context.
|
| 89 |
+
|
| 90 |
+
Returns
|
| 91 |
+
-------
|
| 92 |
+
context : numba.cuda.cudadrv.driver.Context
|
| 93 |
+
Numba CUDA context instance.
|
| 94 |
+
"""
|
| 95 |
+
import ctypes
|
| 96 |
+
import numba.cuda
|
| 97 |
+
device = numba.cuda.gpus[self.device_number]
|
| 98 |
+
handle = ctypes.c_void_p(self.handle)
|
| 99 |
+
context = numba.cuda.cudadrv.driver.Context(device, handle)
|
| 100 |
+
|
| 101 |
+
class DummyPendingDeallocs(object):
|
| 102 |
+
# Context is managed by pyarrow
|
| 103 |
+
def add_item(self, *args, **kwargs):
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
+
context.deallocations = DummyPendingDeallocs()
|
| 107 |
+
return context
|
| 108 |
+
|
| 109 |
+
@staticmethod
|
| 110 |
+
def get_num_devices():
|
| 111 |
+
""" Return the number of GPU devices.
|
| 112 |
+
"""
|
| 113 |
+
cdef CCudaDeviceManager* manager
|
| 114 |
+
manager = GetResultValue(CCudaDeviceManager.Instance())
|
| 115 |
+
return manager.num_devices()
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def device_number(self):
|
| 119 |
+
""" Return context device number.
|
| 120 |
+
"""
|
| 121 |
+
return self.device_number
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def handle(self):
|
| 125 |
+
""" Return pointer to context handle.
|
| 126 |
+
"""
|
| 127 |
+
return <uintptr_t>self.context.get().handle()
|
| 128 |
+
|
| 129 |
+
cdef void init(self, const shared_ptr[CCudaContext]& ctx):
|
| 130 |
+
self.context = ctx
|
| 131 |
+
|
| 132 |
+
def synchronize(self):
|
| 133 |
+
"""Blocks until the device has completed all preceding requested
|
| 134 |
+
tasks.
|
| 135 |
+
"""
|
| 136 |
+
check_status(self.context.get().Synchronize())
|
| 137 |
+
|
| 138 |
+
@property
|
| 139 |
+
def bytes_allocated(self):
|
| 140 |
+
"""Return the number of allocated bytes.
|
| 141 |
+
"""
|
| 142 |
+
return self.context.get().bytes_allocated()
|
| 143 |
+
|
| 144 |
+
def get_device_address(self, uintptr_t address):
|
| 145 |
+
"""Return the device address that is reachable from kernels running in
|
| 146 |
+
the context
|
| 147 |
+
|
| 148 |
+
Parameters
|
| 149 |
+
----------
|
| 150 |
+
address : int
|
| 151 |
+
Specify memory address value
|
| 152 |
+
|
| 153 |
+
Returns
|
| 154 |
+
-------
|
| 155 |
+
device_address : int
|
| 156 |
+
Device address accessible from device context
|
| 157 |
+
|
| 158 |
+
Notes
|
| 159 |
+
-----
|
| 160 |
+
The device address is defined as a memory address accessible
|
| 161 |
+
by device. While it is often a device memory address but it
|
| 162 |
+
can be also a host memory address, for instance, when the
|
| 163 |
+
memory is allocated as host memory (using cudaMallocHost or
|
| 164 |
+
cudaHostAlloc) or as managed memory (using cudaMallocManaged)
|
| 165 |
+
or the host memory is page-locked (using cudaHostRegister).
|
| 166 |
+
"""
|
| 167 |
+
return GetResultValue(self.context.get().GetDeviceAddress(address))
|
| 168 |
+
|
| 169 |
+
def new_buffer(self, int64_t nbytes):
|
| 170 |
+
"""Return new device buffer.
|
| 171 |
+
|
| 172 |
+
Parameters
|
| 173 |
+
----------
|
| 174 |
+
nbytes : int
|
| 175 |
+
Specify the number of bytes to be allocated.
|
| 176 |
+
|
| 177 |
+
Returns
|
| 178 |
+
-------
|
| 179 |
+
buf : CudaBuffer
|
| 180 |
+
Allocated buffer.
|
| 181 |
+
"""
|
| 182 |
+
cdef:
|
| 183 |
+
shared_ptr[CCudaBuffer] cudabuf
|
| 184 |
+
with nogil:
|
| 185 |
+
cudabuf = GetResultValue(self.context.get().Allocate(nbytes))
|
| 186 |
+
return pyarrow_wrap_cudabuffer(cudabuf)
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def memory_manager(self):
|
| 190 |
+
"""
|
| 191 |
+
The default memory manager tied to this context's device.
|
| 192 |
+
|
| 193 |
+
Returns
|
| 194 |
+
-------
|
| 195 |
+
MemoryManager
|
| 196 |
+
"""
|
| 197 |
+
return MemoryManager.wrap(self.context.get().memory_manager())
|
| 198 |
+
|
| 199 |
+
@property
|
| 200 |
+
def device(self):
|
| 201 |
+
"""
|
| 202 |
+
The device instance associated with this context.
|
| 203 |
+
|
| 204 |
+
Returns
|
| 205 |
+
-------
|
| 206 |
+
Device
|
| 207 |
+
"""
|
| 208 |
+
return Device.wrap(self.context.get().device())
|
| 209 |
+
|
| 210 |
+
def foreign_buffer(self, address, size, base=None):
|
| 211 |
+
"""
|
| 212 |
+
Create device buffer from address and size as a view.
|
| 213 |
+
|
| 214 |
+
The caller is responsible for allocating and freeing the
|
| 215 |
+
memory. When `address==size==0` then a new zero-sized buffer
|
| 216 |
+
is returned.
|
| 217 |
+
|
| 218 |
+
Parameters
|
| 219 |
+
----------
|
| 220 |
+
address : int
|
| 221 |
+
Specify the starting address of the buffer. The address can
|
| 222 |
+
refer to both device or host memory but it must be
|
| 223 |
+
accessible from device after mapping it with
|
| 224 |
+
`get_device_address` method.
|
| 225 |
+
size : int
|
| 226 |
+
Specify the size of device buffer in bytes.
|
| 227 |
+
base : {None, object}
|
| 228 |
+
Specify object that owns the referenced memory.
|
| 229 |
+
|
| 230 |
+
Returns
|
| 231 |
+
-------
|
| 232 |
+
cbuf : CudaBuffer
|
| 233 |
+
Device buffer as a view of device reachable memory.
|
| 234 |
+
|
| 235 |
+
"""
|
| 236 |
+
if not address and size == 0:
|
| 237 |
+
return self.new_buffer(0)
|
| 238 |
+
cdef:
|
| 239 |
+
uintptr_t c_addr = self.get_device_address(address)
|
| 240 |
+
int64_t c_size = size
|
| 241 |
+
shared_ptr[CCudaBuffer] cudabuf
|
| 242 |
+
|
| 243 |
+
cudabuf = GetResultValue(self.context.get().View(
|
| 244 |
+
<uint8_t*>c_addr, c_size))
|
| 245 |
+
return pyarrow_wrap_cudabuffer_base(cudabuf, base)
|
| 246 |
+
|
| 247 |
+
def open_ipc_buffer(self, ipc_handle):
|
| 248 |
+
""" Open existing CUDA IPC memory handle
|
| 249 |
+
|
| 250 |
+
Parameters
|
| 251 |
+
----------
|
| 252 |
+
ipc_handle : IpcMemHandle
|
| 253 |
+
Specify opaque pointer to CUipcMemHandle (driver API).
|
| 254 |
+
|
| 255 |
+
Returns
|
| 256 |
+
-------
|
| 257 |
+
buf : CudaBuffer
|
| 258 |
+
referencing device buffer
|
| 259 |
+
"""
|
| 260 |
+
handle = pyarrow_unwrap_cudaipcmemhandle(ipc_handle)
|
| 261 |
+
cdef shared_ptr[CCudaBuffer] cudabuf
|
| 262 |
+
with nogil:
|
| 263 |
+
cudabuf = GetResultValue(
|
| 264 |
+
self.context.get().OpenIpcBuffer(handle.get()[0]))
|
| 265 |
+
return pyarrow_wrap_cudabuffer(cudabuf)
|
| 266 |
+
|
| 267 |
+
def buffer_from_data(self, object data, int64_t offset=0, int64_t size=-1):
|
| 268 |
+
"""Create device buffer and initialize with data.
|
| 269 |
+
|
| 270 |
+
Parameters
|
| 271 |
+
----------
|
| 272 |
+
data : {CudaBuffer, HostBuffer, Buffer, array-like}
|
| 273 |
+
Specify data to be copied to device buffer.
|
| 274 |
+
offset : int
|
| 275 |
+
Specify the offset of input buffer for device data
|
| 276 |
+
buffering. Default: 0.
|
| 277 |
+
size : int
|
| 278 |
+
Specify the size of device buffer in bytes. Default: all
|
| 279 |
+
(starting from input offset)
|
| 280 |
+
|
| 281 |
+
Returns
|
| 282 |
+
-------
|
| 283 |
+
cbuf : CudaBuffer
|
| 284 |
+
Device buffer with copied data.
|
| 285 |
+
"""
|
| 286 |
+
is_host_data = not pyarrow_is_cudabuffer(data)
|
| 287 |
+
buf = as_buffer(data) if is_host_data else data
|
| 288 |
+
|
| 289 |
+
bsize = buf.size
|
| 290 |
+
if offset < 0 or (bsize and offset >= bsize):
|
| 291 |
+
raise ValueError('offset argument is out-of-range')
|
| 292 |
+
if size < 0:
|
| 293 |
+
size = bsize - offset
|
| 294 |
+
elif offset + size > bsize:
|
| 295 |
+
raise ValueError(
|
| 296 |
+
'requested larger slice than available in device buffer')
|
| 297 |
+
|
| 298 |
+
if offset != 0 or size != bsize:
|
| 299 |
+
buf = buf.slice(offset, size)
|
| 300 |
+
|
| 301 |
+
result = self.new_buffer(size)
|
| 302 |
+
if is_host_data:
|
| 303 |
+
result.copy_from_host(buf, position=0, nbytes=size)
|
| 304 |
+
else:
|
| 305 |
+
result.copy_from_device(buf, position=0, nbytes=size)
|
| 306 |
+
return result
|
| 307 |
+
|
| 308 |
+
def buffer_from_object(self, obj):
|
| 309 |
+
"""Create device buffer view of arbitrary object that references
|
| 310 |
+
device accessible memory.
|
| 311 |
+
|
| 312 |
+
When the object contains a non-contiguous view of device
|
| 313 |
+
accessible memory then the returned device buffer will contain
|
| 314 |
+
contiguous view of the memory, that is, including the
|
| 315 |
+
intermediate data that is otherwise invisible to the input
|
| 316 |
+
object.
|
| 317 |
+
|
| 318 |
+
Parameters
|
| 319 |
+
----------
|
| 320 |
+
obj : {object, Buffer, HostBuffer, CudaBuffer, ...}
|
| 321 |
+
Specify an object that holds (device or host) address that
|
| 322 |
+
can be accessed from device. This includes objects with
|
| 323 |
+
types defined in pyarrow.cuda as well as arbitrary objects
|
| 324 |
+
that implement the CUDA array interface as defined by numba.
|
| 325 |
+
|
| 326 |
+
Returns
|
| 327 |
+
-------
|
| 328 |
+
cbuf : CudaBuffer
|
| 329 |
+
Device buffer as a view of device accessible memory.
|
| 330 |
+
|
| 331 |
+
"""
|
| 332 |
+
if isinstance(obj, HostBuffer):
|
| 333 |
+
return self.foreign_buffer(obj.address, obj.size, base=obj)
|
| 334 |
+
elif isinstance(obj, Buffer):
|
| 335 |
+
return CudaBuffer.from_buffer(obj)
|
| 336 |
+
elif isinstance(obj, CudaBuffer):
|
| 337 |
+
return obj
|
| 338 |
+
elif hasattr(obj, '__cuda_array_interface__'):
|
| 339 |
+
desc = obj.__cuda_array_interface__
|
| 340 |
+
addr = desc['data'][0]
|
| 341 |
+
if addr is None:
|
| 342 |
+
return self.new_buffer(0)
|
| 343 |
+
import numpy as np
|
| 344 |
+
start, end = get_contiguous_span(
|
| 345 |
+
desc['shape'], desc.get('strides'),
|
| 346 |
+
np.dtype(desc['typestr']).itemsize)
|
| 347 |
+
return self.foreign_buffer(addr + start, end - start, base=obj)
|
| 348 |
+
raise ArrowTypeError('cannot create device buffer view from'
|
| 349 |
+
' `%s` object' % (type(obj)))
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
cdef class IpcMemHandle(_Weakrefable):
|
| 353 |
+
"""A serializable container for a CUDA IPC handle.
|
| 354 |
+
"""
|
| 355 |
+
cdef void init(self, shared_ptr[CCudaIpcMemHandle]& h):
|
| 356 |
+
self.handle = h
|
| 357 |
+
|
| 358 |
+
@staticmethod
|
| 359 |
+
def from_buffer(Buffer opaque_handle):
|
| 360 |
+
"""Create IpcMemHandle from opaque buffer (e.g. from another
|
| 361 |
+
process)
|
| 362 |
+
|
| 363 |
+
Parameters
|
| 364 |
+
----------
|
| 365 |
+
opaque_handle :
|
| 366 |
+
a CUipcMemHandle as a const void*
|
| 367 |
+
|
| 368 |
+
Returns
|
| 369 |
+
-------
|
| 370 |
+
ipc_handle : IpcMemHandle
|
| 371 |
+
"""
|
| 372 |
+
c_buf = pyarrow_unwrap_buffer(opaque_handle)
|
| 373 |
+
cdef:
|
| 374 |
+
shared_ptr[CCudaIpcMemHandle] handle
|
| 375 |
+
|
| 376 |
+
handle = GetResultValue(
|
| 377 |
+
CCudaIpcMemHandle.FromBuffer(c_buf.get().data()))
|
| 378 |
+
return pyarrow_wrap_cudaipcmemhandle(handle)
|
| 379 |
+
|
| 380 |
+
def serialize(self, pool=None):
|
| 381 |
+
"""Write IpcMemHandle to a Buffer
|
| 382 |
+
|
| 383 |
+
Parameters
|
| 384 |
+
----------
|
| 385 |
+
pool : {MemoryPool, None}
|
| 386 |
+
Specify a pool to allocate memory from
|
| 387 |
+
|
| 388 |
+
Returns
|
| 389 |
+
-------
|
| 390 |
+
buf : Buffer
|
| 391 |
+
The serialized buffer.
|
| 392 |
+
"""
|
| 393 |
+
cdef CMemoryPool* pool_ = maybe_unbox_memory_pool(pool)
|
| 394 |
+
cdef shared_ptr[CBuffer] buf
|
| 395 |
+
cdef CCudaIpcMemHandle* h = self.handle.get()
|
| 396 |
+
with nogil:
|
| 397 |
+
buf = GetResultValue(h.Serialize(pool_))
|
| 398 |
+
return pyarrow_wrap_buffer(buf)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
cdef class CudaBuffer(Buffer):
|
| 402 |
+
"""An Arrow buffer with data located in a GPU device.
|
| 403 |
+
|
| 404 |
+
To create a CudaBuffer instance, use Context.device_buffer().
|
| 405 |
+
|
| 406 |
+
The memory allocated in a CudaBuffer is freed when the buffer object
|
| 407 |
+
is deleted.
|
| 408 |
+
"""
|
| 409 |
+
|
| 410 |
+
def __init__(self):
|
| 411 |
+
raise TypeError("Do not call CudaBuffer's constructor directly, use "
|
| 412 |
+
"`<pyarrow.Context instance>.device_buffer`"
|
| 413 |
+
" method instead.")
|
| 414 |
+
|
| 415 |
+
cdef void init_cuda(self,
|
| 416 |
+
const shared_ptr[CCudaBuffer]& buffer,
|
| 417 |
+
object base):
|
| 418 |
+
self.cuda_buffer = buffer
|
| 419 |
+
self.init(<shared_ptr[CBuffer]> buffer)
|
| 420 |
+
self.base = base
|
| 421 |
+
|
| 422 |
+
@staticmethod
|
| 423 |
+
def from_buffer(buf):
|
| 424 |
+
""" Convert back generic buffer into CudaBuffer
|
| 425 |
+
|
| 426 |
+
Parameters
|
| 427 |
+
----------
|
| 428 |
+
buf : Buffer
|
| 429 |
+
Specify buffer containing CudaBuffer
|
| 430 |
+
|
| 431 |
+
Returns
|
| 432 |
+
-------
|
| 433 |
+
dbuf : CudaBuffer
|
| 434 |
+
Resulting device buffer.
|
| 435 |
+
"""
|
| 436 |
+
c_buf = pyarrow_unwrap_buffer(buf)
|
| 437 |
+
cuda_buffer = GetResultValue(CCudaBuffer.FromBuffer(c_buf))
|
| 438 |
+
return pyarrow_wrap_cudabuffer(cuda_buffer)
|
| 439 |
+
|
| 440 |
+
@staticmethod
|
| 441 |
+
def from_numba(mem):
|
| 442 |
+
"""Create a CudaBuffer view from numba MemoryPointer instance.
|
| 443 |
+
|
| 444 |
+
Parameters
|
| 445 |
+
----------
|
| 446 |
+
mem : numba.cuda.cudadrv.driver.MemoryPointer
|
| 447 |
+
|
| 448 |
+
Returns
|
| 449 |
+
-------
|
| 450 |
+
cbuf : CudaBuffer
|
| 451 |
+
Device buffer as a view of numba MemoryPointer.
|
| 452 |
+
"""
|
| 453 |
+
ctx = Context.from_numba(mem.context)
|
| 454 |
+
if mem.device_pointer.value is None and mem.size==0:
|
| 455 |
+
return ctx.new_buffer(0)
|
| 456 |
+
return ctx.foreign_buffer(mem.device_pointer.value, mem.size, base=mem)
|
| 457 |
+
|
| 458 |
+
def to_numba(self):
|
| 459 |
+
"""Return numba memory pointer of CudaBuffer instance.
|
| 460 |
+
"""
|
| 461 |
+
import ctypes
|
| 462 |
+
from numba.cuda.cudadrv.driver import MemoryPointer
|
| 463 |
+
return MemoryPointer(self.context.to_numba(),
|
| 464 |
+
pointer=ctypes.c_void_p(self.address),
|
| 465 |
+
size=self.size)
|
| 466 |
+
|
| 467 |
+
cdef getitem(self, int64_t i):
|
| 468 |
+
return self.copy_to_host(position=i, nbytes=1)[0]
|
| 469 |
+
|
| 470 |
+
def copy_to_host(self, int64_t position=0, int64_t nbytes=-1,
|
| 471 |
+
Buffer buf=None,
|
| 472 |
+
MemoryPool memory_pool=None, c_bool resizable=False):
|
| 473 |
+
"""Copy memory from GPU device to CPU host
|
| 474 |
+
|
| 475 |
+
Caller is responsible for ensuring that all tasks affecting
|
| 476 |
+
the memory are finished. Use
|
| 477 |
+
|
| 478 |
+
`<CudaBuffer instance>.context.synchronize()`
|
| 479 |
+
|
| 480 |
+
when needed.
|
| 481 |
+
|
| 482 |
+
Parameters
|
| 483 |
+
----------
|
| 484 |
+
position : int
|
| 485 |
+
Specify the starting position of the source data in GPU
|
| 486 |
+
device buffer. Default: 0.
|
| 487 |
+
nbytes : int
|
| 488 |
+
Specify the number of bytes to copy. Default: -1 (all from
|
| 489 |
+
the position until host buffer is full).
|
| 490 |
+
buf : Buffer
|
| 491 |
+
Specify a pre-allocated output buffer in host. Default: None
|
| 492 |
+
(allocate new output buffer).
|
| 493 |
+
memory_pool : MemoryPool
|
| 494 |
+
resizable : bool
|
| 495 |
+
Specify extra arguments to allocate_buffer. Used only when
|
| 496 |
+
buf is None.
|
| 497 |
+
|
| 498 |
+
Returns
|
| 499 |
+
-------
|
| 500 |
+
buf : Buffer
|
| 501 |
+
Output buffer in host.
|
| 502 |
+
|
| 503 |
+
"""
|
| 504 |
+
if position < 0 or (self.size and position > self.size) \
|
| 505 |
+
or (self.size == 0 and position != 0):
|
| 506 |
+
raise ValueError('position argument is out-of-range')
|
| 507 |
+
cdef:
|
| 508 |
+
int64_t c_nbytes
|
| 509 |
+
if buf is None:
|
| 510 |
+
if nbytes < 0:
|
| 511 |
+
# copy all starting from position to new host buffer
|
| 512 |
+
c_nbytes = self.size - position
|
| 513 |
+
else:
|
| 514 |
+
if nbytes > self.size - position:
|
| 515 |
+
raise ValueError(
|
| 516 |
+
'requested more to copy than available from '
|
| 517 |
+
'device buffer')
|
| 518 |
+
# copy nbytes starting from position to new host buffer
|
| 519 |
+
c_nbytes = nbytes
|
| 520 |
+
buf = allocate_buffer(c_nbytes, memory_pool=memory_pool,
|
| 521 |
+
resizable=resizable)
|
| 522 |
+
else:
|
| 523 |
+
if nbytes < 0:
|
| 524 |
+
# copy all from position until given host buffer is full
|
| 525 |
+
c_nbytes = min(self.size - position, buf.size)
|
| 526 |
+
else:
|
| 527 |
+
if nbytes > buf.size:
|
| 528 |
+
raise ValueError(
|
| 529 |
+
'requested copy does not fit into host buffer')
|
| 530 |
+
# copy nbytes from position to given host buffer
|
| 531 |
+
c_nbytes = nbytes
|
| 532 |
+
|
| 533 |
+
cdef:
|
| 534 |
+
shared_ptr[CBuffer] c_buf = pyarrow_unwrap_buffer(buf)
|
| 535 |
+
int64_t c_position = position
|
| 536 |
+
with nogil:
|
| 537 |
+
check_status(self.cuda_buffer.get()
|
| 538 |
+
.CopyToHost(c_position, c_nbytes,
|
| 539 |
+
c_buf.get().mutable_data()))
|
| 540 |
+
return buf
|
| 541 |
+
|
| 542 |
+
def copy_from_host(self, data, int64_t position=0, int64_t nbytes=-1):
|
| 543 |
+
"""Copy data from host to device.
|
| 544 |
+
|
| 545 |
+
The device buffer must be pre-allocated.
|
| 546 |
+
|
| 547 |
+
Parameters
|
| 548 |
+
----------
|
| 549 |
+
data : {Buffer, array-like}
|
| 550 |
+
Specify data in host. It can be array-like that is valid
|
| 551 |
+
argument to py_buffer
|
| 552 |
+
position : int
|
| 553 |
+
Specify the starting position of the copy in device buffer.
|
| 554 |
+
Default: 0.
|
| 555 |
+
nbytes : int
|
| 556 |
+
Specify the number of bytes to copy. Default: -1 (all from
|
| 557 |
+
source until device buffer, starting from position, is full)
|
| 558 |
+
|
| 559 |
+
Returns
|
| 560 |
+
-------
|
| 561 |
+
nbytes : int
|
| 562 |
+
Number of bytes copied.
|
| 563 |
+
"""
|
| 564 |
+
if position < 0 or position > self.size:
|
| 565 |
+
raise ValueError('position argument is out-of-range')
|
| 566 |
+
cdef:
|
| 567 |
+
int64_t c_nbytes
|
| 568 |
+
buf = as_buffer(data)
|
| 569 |
+
|
| 570 |
+
if nbytes < 0:
|
| 571 |
+
# copy from host buffer to device buffer starting from
|
| 572 |
+
# position until device buffer is full
|
| 573 |
+
c_nbytes = min(self.size - position, buf.size)
|
| 574 |
+
else:
|
| 575 |
+
if nbytes > buf.size:
|
| 576 |
+
raise ValueError(
|
| 577 |
+
'requested more to copy than available from host buffer')
|
| 578 |
+
if nbytes > self.size - position:
|
| 579 |
+
raise ValueError(
|
| 580 |
+
'requested more to copy than available in device buffer')
|
| 581 |
+
# copy nbytes from host buffer to device buffer starting
|
| 582 |
+
# from position
|
| 583 |
+
c_nbytes = nbytes
|
| 584 |
+
|
| 585 |
+
cdef:
|
| 586 |
+
shared_ptr[CBuffer] c_buf = pyarrow_unwrap_buffer(buf)
|
| 587 |
+
int64_t c_position = position
|
| 588 |
+
with nogil:
|
| 589 |
+
check_status(self.cuda_buffer.get().
|
| 590 |
+
CopyFromHost(c_position, c_buf.get().data(),
|
| 591 |
+
c_nbytes))
|
| 592 |
+
return c_nbytes
|
| 593 |
+
|
| 594 |
+
def copy_from_device(self, buf, int64_t position=0, int64_t nbytes=-1):
|
| 595 |
+
"""Copy data from device to device.
|
| 596 |
+
|
| 597 |
+
Parameters
|
| 598 |
+
----------
|
| 599 |
+
buf : CudaBuffer
|
| 600 |
+
Specify source device buffer.
|
| 601 |
+
position : int
|
| 602 |
+
Specify the starting position of the copy in device buffer.
|
| 603 |
+
Default: 0.
|
| 604 |
+
nbytes : int
|
| 605 |
+
Specify the number of bytes to copy. Default: -1 (all from
|
| 606 |
+
source until device buffer, starting from position, is full)
|
| 607 |
+
|
| 608 |
+
Returns
|
| 609 |
+
-------
|
| 610 |
+
nbytes : int
|
| 611 |
+
Number of bytes copied.
|
| 612 |
+
|
| 613 |
+
"""
|
| 614 |
+
if position < 0 or position > self.size:
|
| 615 |
+
raise ValueError('position argument is out-of-range')
|
| 616 |
+
cdef:
|
| 617 |
+
int64_t c_nbytes
|
| 618 |
+
|
| 619 |
+
if nbytes < 0:
|
| 620 |
+
# copy from source device buffer to device buffer starting
|
| 621 |
+
# from position until device buffer is full
|
| 622 |
+
c_nbytes = min(self.size - position, buf.size)
|
| 623 |
+
else:
|
| 624 |
+
if nbytes > buf.size:
|
| 625 |
+
raise ValueError(
|
| 626 |
+
'requested more to copy than available from device buffer')
|
| 627 |
+
if nbytes > self.size - position:
|
| 628 |
+
raise ValueError(
|
| 629 |
+
'requested more to copy than available in device buffer')
|
| 630 |
+
# copy nbytes from source device buffer to device buffer
|
| 631 |
+
# starting from position
|
| 632 |
+
c_nbytes = nbytes
|
| 633 |
+
|
| 634 |
+
cdef:
|
| 635 |
+
shared_ptr[CCudaBuffer] c_buf = pyarrow_unwrap_cudabuffer(buf)
|
| 636 |
+
int64_t c_position = position
|
| 637 |
+
shared_ptr[CCudaContext] c_src_ctx = pyarrow_unwrap_cudacontext(
|
| 638 |
+
buf.context)
|
| 639 |
+
void* c_source_data = <void*>(c_buf.get().address())
|
| 640 |
+
|
| 641 |
+
if self.context.handle != buf.context.handle:
|
| 642 |
+
with nogil:
|
| 643 |
+
check_status(self.cuda_buffer.get().
|
| 644 |
+
CopyFromAnotherDevice(c_src_ctx, c_position,
|
| 645 |
+
c_source_data, c_nbytes))
|
| 646 |
+
else:
|
| 647 |
+
with nogil:
|
| 648 |
+
check_status(self.cuda_buffer.get().
|
| 649 |
+
CopyFromDevice(c_position, c_source_data,
|
| 650 |
+
c_nbytes))
|
| 651 |
+
return c_nbytes
|
| 652 |
+
|
| 653 |
+
def export_for_ipc(self):
|
| 654 |
+
"""
|
| 655 |
+
Expose this device buffer as IPC memory which can be used in other
|
| 656 |
+
processes.
|
| 657 |
+
|
| 658 |
+
After calling this function, this device memory will not be
|
| 659 |
+
freed when the CudaBuffer is destructed.
|
| 660 |
+
|
| 661 |
+
Returns
|
| 662 |
+
-------
|
| 663 |
+
ipc_handle : IpcMemHandle
|
| 664 |
+
The exported IPC handle
|
| 665 |
+
|
| 666 |
+
"""
|
| 667 |
+
cdef shared_ptr[CCudaIpcMemHandle] handle
|
| 668 |
+
with nogil:
|
| 669 |
+
handle = GetResultValue(self.cuda_buffer.get().ExportForIpc())
|
| 670 |
+
return pyarrow_wrap_cudaipcmemhandle(handle)
|
| 671 |
+
|
| 672 |
+
@property
|
| 673 |
+
def context(self):
|
| 674 |
+
"""Returns the CUDA driver context of this buffer.
|
| 675 |
+
"""
|
| 676 |
+
return pyarrow_wrap_cudacontext(self.cuda_buffer.get().context())
|
| 677 |
+
|
| 678 |
+
def slice(self, offset=0, length=None):
|
| 679 |
+
"""Return slice of device buffer
|
| 680 |
+
|
| 681 |
+
Parameters
|
| 682 |
+
----------
|
| 683 |
+
offset : int, default 0
|
| 684 |
+
Specify offset from the start of device buffer to slice
|
| 685 |
+
length : int, default None
|
| 686 |
+
Specify the length of slice (default is until end of device
|
| 687 |
+
buffer starting from offset). If the length is larger than
|
| 688 |
+
the data available, the returned slice will have a size of
|
| 689 |
+
the available data starting from the offset.
|
| 690 |
+
|
| 691 |
+
Returns
|
| 692 |
+
-------
|
| 693 |
+
sliced : CudaBuffer
|
| 694 |
+
Zero-copy slice of device buffer.
|
| 695 |
+
|
| 696 |
+
"""
|
| 697 |
+
if offset < 0 or (self.size and offset >= self.size):
|
| 698 |
+
raise ValueError('offset argument is out-of-range')
|
| 699 |
+
cdef int64_t offset_ = offset
|
| 700 |
+
cdef int64_t size
|
| 701 |
+
if length is None:
|
| 702 |
+
size = self.size - offset_
|
| 703 |
+
elif offset + length <= self.size:
|
| 704 |
+
size = length
|
| 705 |
+
else:
|
| 706 |
+
size = self.size - offset
|
| 707 |
+
parent = pyarrow_unwrap_cudabuffer(self)
|
| 708 |
+
return pyarrow_wrap_cudabuffer(make_shared[CCudaBuffer](parent,
|
| 709 |
+
offset_, size))
|
| 710 |
+
|
| 711 |
+
def to_pybytes(self):
|
| 712 |
+
"""Return device buffer content as Python bytes.
|
| 713 |
+
"""
|
| 714 |
+
return self.copy_to_host().to_pybytes()
|
| 715 |
+
|
| 716 |
+
def __getbuffer__(self, cp.Py_buffer* buffer, int flags):
|
| 717 |
+
# Device buffer contains data pointers on the device. Hence,
|
| 718 |
+
# cannot support buffer protocol PEP-3118 for CudaBuffer.
|
| 719 |
+
raise BufferError('buffer protocol for device buffer not supported')
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
cdef class HostBuffer(Buffer):
|
| 723 |
+
"""Device-accessible CPU memory created using cudaHostAlloc.
|
| 724 |
+
|
| 725 |
+
To create a HostBuffer instance, use
|
| 726 |
+
|
| 727 |
+
cuda.new_host_buffer(<nbytes>)
|
| 728 |
+
"""
|
| 729 |
+
|
| 730 |
+
def __init__(self):
|
| 731 |
+
raise TypeError("Do not call HostBuffer's constructor directly,"
|
| 732 |
+
" use `cuda.new_host_buffer` function instead.")
|
| 733 |
+
|
| 734 |
+
cdef void init_host(self, const shared_ptr[CCudaHostBuffer]& buffer):
|
| 735 |
+
self.host_buffer = buffer
|
| 736 |
+
self.init(<shared_ptr[CBuffer]> buffer)
|
| 737 |
+
|
| 738 |
+
@property
|
| 739 |
+
def size(self):
|
| 740 |
+
return self.host_buffer.get().size()
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
cdef class BufferReader(NativeFile):
|
| 744 |
+
"""File interface for zero-copy read from CUDA buffers.
|
| 745 |
+
|
| 746 |
+
Note: Read methods return pointers to device memory. This means
|
| 747 |
+
you must be careful using this interface with any Arrow code which
|
| 748 |
+
may expect to be able to do anything other than pointer arithmetic
|
| 749 |
+
on the returned buffers.
|
| 750 |
+
"""
|
| 751 |
+
|
| 752 |
+
def __cinit__(self, CudaBuffer obj):
|
| 753 |
+
self.buffer = obj
|
| 754 |
+
self.reader = new CCudaBufferReader(self.buffer.buffer)
|
| 755 |
+
self.set_random_access_file(
|
| 756 |
+
shared_ptr[CRandomAccessFile](self.reader))
|
| 757 |
+
self.is_readable = True
|
| 758 |
+
|
| 759 |
+
def read_buffer(self, nbytes=None):
|
| 760 |
+
"""Return a slice view of the underlying device buffer.
|
| 761 |
+
|
| 762 |
+
The slice will start at the current reader position and will
|
| 763 |
+
have specified size in bytes.
|
| 764 |
+
|
| 765 |
+
Parameters
|
| 766 |
+
----------
|
| 767 |
+
nbytes : int, default None
|
| 768 |
+
Specify the number of bytes to read. Default: None (read all
|
| 769 |
+
remaining bytes).
|
| 770 |
+
|
| 771 |
+
Returns
|
| 772 |
+
-------
|
| 773 |
+
cbuf : CudaBuffer
|
| 774 |
+
New device buffer.
|
| 775 |
+
|
| 776 |
+
"""
|
| 777 |
+
cdef:
|
| 778 |
+
int64_t c_nbytes
|
| 779 |
+
shared_ptr[CCudaBuffer] output
|
| 780 |
+
|
| 781 |
+
if nbytes is None:
|
| 782 |
+
c_nbytes = self.size() - self.tell()
|
| 783 |
+
else:
|
| 784 |
+
c_nbytes = nbytes
|
| 785 |
+
|
| 786 |
+
with nogil:
|
| 787 |
+
output = static_pointer_cast[CCudaBuffer, CBuffer](
|
| 788 |
+
GetResultValue(self.reader.Read(c_nbytes)))
|
| 789 |
+
|
| 790 |
+
return pyarrow_wrap_cudabuffer(output)
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
cdef class BufferWriter(NativeFile):
|
| 794 |
+
"""File interface for writing to CUDA buffers.
|
| 795 |
+
|
| 796 |
+
By default writes are unbuffered. Use set_buffer_size to enable
|
| 797 |
+
buffering.
|
| 798 |
+
"""
|
| 799 |
+
|
| 800 |
+
def __cinit__(self, CudaBuffer buffer):
|
| 801 |
+
self.buffer = buffer
|
| 802 |
+
self.writer = new CCudaBufferWriter(self.buffer.cuda_buffer)
|
| 803 |
+
self.set_output_stream(shared_ptr[COutputStream](self.writer))
|
| 804 |
+
self.is_writable = True
|
| 805 |
+
|
| 806 |
+
def writeat(self, int64_t position, object data):
|
| 807 |
+
"""Write data to buffer starting from position.
|
| 808 |
+
|
| 809 |
+
Parameters
|
| 810 |
+
----------
|
| 811 |
+
position : int
|
| 812 |
+
Specify device buffer position where the data will be
|
| 813 |
+
written.
|
| 814 |
+
data : array-like
|
| 815 |
+
Specify data, the data instance must implement buffer
|
| 816 |
+
protocol.
|
| 817 |
+
"""
|
| 818 |
+
cdef:
|
| 819 |
+
Buffer buf = as_buffer(data)
|
| 820 |
+
const uint8_t* c_data = buf.buffer.get().data()
|
| 821 |
+
int64_t c_size = buf.buffer.get().size()
|
| 822 |
+
|
| 823 |
+
with nogil:
|
| 824 |
+
check_status(self.writer.WriteAt(position, c_data, c_size))
|
| 825 |
+
|
| 826 |
+
def flush(self):
|
| 827 |
+
""" Flush the buffer stream """
|
| 828 |
+
with nogil:
|
| 829 |
+
check_status(self.writer.Flush())
|
| 830 |
+
|
| 831 |
+
def seek(self, int64_t position, int whence=0):
|
| 832 |
+
# TODO: remove this method after NativeFile.seek supports
|
| 833 |
+
# writable files.
|
| 834 |
+
cdef int64_t offset
|
| 835 |
+
|
| 836 |
+
with nogil:
|
| 837 |
+
if whence == 0:
|
| 838 |
+
offset = position
|
| 839 |
+
elif whence == 1:
|
| 840 |
+
offset = GetResultValue(self.writer.Tell())
|
| 841 |
+
offset = offset + position
|
| 842 |
+
else:
|
| 843 |
+
with gil:
|
| 844 |
+
raise ValueError("Invalid value of whence: {0}"
|
| 845 |
+
.format(whence))
|
| 846 |
+
check_status(self.writer.Seek(offset))
|
| 847 |
+
return self.tell()
|
| 848 |
+
|
| 849 |
+
@property
|
| 850 |
+
def buffer_size(self):
|
| 851 |
+
"""Returns size of host (CPU) buffer, 0 for unbuffered
|
| 852 |
+
"""
|
| 853 |
+
return self.writer.buffer_size()
|
| 854 |
+
|
| 855 |
+
@buffer_size.setter
|
| 856 |
+
def buffer_size(self, int64_t buffer_size):
|
| 857 |
+
"""Set CPU buffer size to limit calls to cudaMemcpy
|
| 858 |
+
|
| 859 |
+
Parameters
|
| 860 |
+
----------
|
| 861 |
+
buffer_size : int
|
| 862 |
+
Specify the size of CPU buffer to allocate in bytes.
|
| 863 |
+
"""
|
| 864 |
+
with nogil:
|
| 865 |
+
check_status(self.writer.SetBufferSize(buffer_size))
|
| 866 |
+
|
| 867 |
+
@property
|
| 868 |
+
def num_bytes_buffered(self):
|
| 869 |
+
"""Returns number of bytes buffered on host
|
| 870 |
+
"""
|
| 871 |
+
return self.writer.num_bytes_buffered()
|
| 872 |
+
|
| 873 |
+
# Functions
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
def new_host_buffer(const int64_t size, int device=0):
|
| 877 |
+
"""Return buffer with CUDA-accessible memory on CPU host
|
| 878 |
+
|
| 879 |
+
Parameters
|
| 880 |
+
----------
|
| 881 |
+
size : int
|
| 882 |
+
Specify the number of bytes to be allocated.
|
| 883 |
+
device : int
|
| 884 |
+
Specify GPU device number.
|
| 885 |
+
|
| 886 |
+
Returns
|
| 887 |
+
-------
|
| 888 |
+
dbuf : HostBuffer
|
| 889 |
+
Allocated host buffer
|
| 890 |
+
"""
|
| 891 |
+
cdef shared_ptr[CCudaHostBuffer] buffer
|
| 892 |
+
with nogil:
|
| 893 |
+
buffer = GetResultValue(AllocateCudaHostBuffer(device, size))
|
| 894 |
+
return pyarrow_wrap_cudahostbuffer(buffer)
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
def serialize_record_batch(object batch, object ctx):
|
| 898 |
+
""" Write record batch message to GPU device memory
|
| 899 |
+
|
| 900 |
+
Parameters
|
| 901 |
+
----------
|
| 902 |
+
batch : RecordBatch
|
| 903 |
+
Record batch to write
|
| 904 |
+
ctx : Context
|
| 905 |
+
CUDA Context to allocate device memory from
|
| 906 |
+
|
| 907 |
+
Returns
|
| 908 |
+
-------
|
| 909 |
+
dbuf : CudaBuffer
|
| 910 |
+
device buffer which contains the record batch message
|
| 911 |
+
"""
|
| 912 |
+
cdef shared_ptr[CCudaBuffer] buffer
|
| 913 |
+
cdef CRecordBatch* batch_ = pyarrow_unwrap_batch(batch).get()
|
| 914 |
+
cdef CCudaContext* ctx_ = pyarrow_unwrap_cudacontext(ctx).get()
|
| 915 |
+
with nogil:
|
| 916 |
+
buffer = GetResultValue(CudaSerializeRecordBatch(batch_[0], ctx_))
|
| 917 |
+
return pyarrow_wrap_cudabuffer(buffer)
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def read_message(object source, pool=None):
|
| 921 |
+
""" Read Arrow IPC message located on GPU device
|
| 922 |
+
|
| 923 |
+
Parameters
|
| 924 |
+
----------
|
| 925 |
+
source : {CudaBuffer, cuda.BufferReader}
|
| 926 |
+
Device buffer or reader of device buffer.
|
| 927 |
+
pool : MemoryPool (optional)
|
| 928 |
+
Pool to allocate CPU memory for the metadata
|
| 929 |
+
|
| 930 |
+
Returns
|
| 931 |
+
-------
|
| 932 |
+
message : Message
|
| 933 |
+
The deserialized message, body still on device
|
| 934 |
+
"""
|
| 935 |
+
cdef:
|
| 936 |
+
Message result = Message.__new__(Message)
|
| 937 |
+
cdef CMemoryPool* pool_ = maybe_unbox_memory_pool(pool)
|
| 938 |
+
if not isinstance(source, BufferReader):
|
| 939 |
+
reader = BufferReader(source)
|
| 940 |
+
with nogil:
|
| 941 |
+
result.message = move(
|
| 942 |
+
GetResultValue(ReadMessage(reader.reader, pool_)))
|
| 943 |
+
return result
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
def read_record_batch(object buffer, object schema, *,
|
| 947 |
+
DictionaryMemo dictionary_memo=None, pool=None):
|
| 948 |
+
"""Construct RecordBatch referencing IPC message located on CUDA device.
|
| 949 |
+
|
| 950 |
+
While the metadata is copied to host memory for deserialization,
|
| 951 |
+
the record batch data remains on the device.
|
| 952 |
+
|
| 953 |
+
Parameters
|
| 954 |
+
----------
|
| 955 |
+
buffer :
|
| 956 |
+
Device buffer containing the complete IPC message
|
| 957 |
+
schema : Schema
|
| 958 |
+
The schema for the record batch
|
| 959 |
+
dictionary_memo : DictionaryMemo, optional
|
| 960 |
+
If message contains dictionaries, must pass a populated
|
| 961 |
+
DictionaryMemo
|
| 962 |
+
pool : MemoryPool (optional)
|
| 963 |
+
Pool to allocate metadata from
|
| 964 |
+
|
| 965 |
+
Returns
|
| 966 |
+
-------
|
| 967 |
+
batch : RecordBatch
|
| 968 |
+
Reconstructed record batch, with device pointers
|
| 969 |
+
|
| 970 |
+
"""
|
| 971 |
+
cdef:
|
| 972 |
+
shared_ptr[CSchema] schema_ = pyarrow_unwrap_schema(schema)
|
| 973 |
+
shared_ptr[CCudaBuffer] buffer_ = pyarrow_unwrap_cudabuffer(buffer)
|
| 974 |
+
CDictionaryMemo temp_memo
|
| 975 |
+
CDictionaryMemo* arg_dict_memo
|
| 976 |
+
CMemoryPool* pool_ = maybe_unbox_memory_pool(pool)
|
| 977 |
+
shared_ptr[CRecordBatch] batch
|
| 978 |
+
|
| 979 |
+
if dictionary_memo is not None:
|
| 980 |
+
arg_dict_memo = dictionary_memo.memo
|
| 981 |
+
else:
|
| 982 |
+
arg_dict_memo = &temp_memo
|
| 983 |
+
|
| 984 |
+
with nogil:
|
| 985 |
+
batch = GetResultValue(CudaReadRecordBatch(
|
| 986 |
+
schema_, arg_dict_memo, buffer_, pool_))
|
| 987 |
+
return pyarrow_wrap_batch(batch)
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
# Public API
|
| 991 |
+
|
| 992 |
+
|
| 993 |
+
cdef public api bint pyarrow_is_buffer(object buffer):
|
| 994 |
+
return isinstance(buffer, Buffer)
|
| 995 |
+
|
| 996 |
+
# cudabuffer
|
| 997 |
+
|
| 998 |
+
cdef public api bint pyarrow_is_cudabuffer(object buffer):
|
| 999 |
+
return isinstance(buffer, CudaBuffer)
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
cdef public api object \
|
| 1003 |
+
pyarrow_wrap_cudabuffer_base(const shared_ptr[CCudaBuffer]& buf, base):
|
| 1004 |
+
cdef CudaBuffer result = CudaBuffer.__new__(CudaBuffer)
|
| 1005 |
+
result.init_cuda(buf, base)
|
| 1006 |
+
return result
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
cdef public api object \
|
| 1010 |
+
pyarrow_wrap_cudabuffer(const shared_ptr[CCudaBuffer]& buf):
|
| 1011 |
+
cdef CudaBuffer result = CudaBuffer.__new__(CudaBuffer)
|
| 1012 |
+
result.init_cuda(buf, None)
|
| 1013 |
+
return result
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
cdef public api shared_ptr[CCudaBuffer] pyarrow_unwrap_cudabuffer(object obj):
|
| 1017 |
+
if pyarrow_is_cudabuffer(obj):
|
| 1018 |
+
return (<CudaBuffer>obj).cuda_buffer
|
| 1019 |
+
raise TypeError('expected CudaBuffer instance, got %s'
|
| 1020 |
+
% (type(obj).__name__))
|
| 1021 |
+
|
| 1022 |
+
# cudahostbuffer
|
| 1023 |
+
|
| 1024 |
+
cdef public api bint pyarrow_is_cudahostbuffer(object buffer):
|
| 1025 |
+
return isinstance(buffer, HostBuffer)
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
cdef public api object \
|
| 1029 |
+
pyarrow_wrap_cudahostbuffer(const shared_ptr[CCudaHostBuffer]& buf):
|
| 1030 |
+
cdef HostBuffer result = HostBuffer.__new__(HostBuffer)
|
| 1031 |
+
result.init_host(buf)
|
| 1032 |
+
return result
|
| 1033 |
+
|
| 1034 |
+
|
| 1035 |
+
cdef public api shared_ptr[CCudaHostBuffer] \
|
| 1036 |
+
pyarrow_unwrap_cudahostbuffer(object obj):
|
| 1037 |
+
if pyarrow_is_cudahostbuffer(obj):
|
| 1038 |
+
return (<HostBuffer>obj).host_buffer
|
| 1039 |
+
raise TypeError('expected HostBuffer instance, got %s'
|
| 1040 |
+
% (type(obj).__name__))
|
| 1041 |
+
|
| 1042 |
+
# cudacontext
|
| 1043 |
+
|
| 1044 |
+
cdef public api bint pyarrow_is_cudacontext(object ctx):
|
| 1045 |
+
return isinstance(ctx, Context)
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
cdef public api object \
|
| 1049 |
+
pyarrow_wrap_cudacontext(const shared_ptr[CCudaContext]& ctx):
|
| 1050 |
+
cdef Context result = Context.__new__(Context)
|
| 1051 |
+
result.init(ctx)
|
| 1052 |
+
return result
|
| 1053 |
+
|
| 1054 |
+
|
| 1055 |
+
cdef public api shared_ptr[CCudaContext] \
|
| 1056 |
+
pyarrow_unwrap_cudacontext(object obj):
|
| 1057 |
+
if pyarrow_is_cudacontext(obj):
|
| 1058 |
+
return (<Context>obj).context
|
| 1059 |
+
raise TypeError('expected Context instance, got %s'
|
| 1060 |
+
% (type(obj).__name__))
|
| 1061 |
+
|
| 1062 |
+
# cudaipcmemhandle
|
| 1063 |
+
|
| 1064 |
+
cdef public api bint pyarrow_is_cudaipcmemhandle(object handle):
|
| 1065 |
+
return isinstance(handle, IpcMemHandle)
|
| 1066 |
+
|
| 1067 |
+
|
| 1068 |
+
cdef public api object \
|
| 1069 |
+
pyarrow_wrap_cudaipcmemhandle(shared_ptr[CCudaIpcMemHandle]& h):
|
| 1070 |
+
cdef IpcMemHandle result = IpcMemHandle.__new__(IpcMemHandle)
|
| 1071 |
+
result.init(h)
|
| 1072 |
+
return result
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
cdef public api shared_ptr[CCudaIpcMemHandle] \
|
| 1076 |
+
pyarrow_unwrap_cudaipcmemhandle(object obj):
|
| 1077 |
+
if pyarrow_is_cudaipcmemhandle(obj):
|
| 1078 |
+
return (<IpcMemHandle>obj).handle
|
| 1079 |
+
raise TypeError('expected IpcMemHandle instance, got %s'
|
| 1080 |
+
% (type(obj).__name__))
|
vllm/lib/python3.10/site-packages/pyarrow/_dataset.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# cython: language_level = 3
|
| 19 |
+
|
| 20 |
+
"""Dataset is currently unstable. APIs subject to change without notice."""
|
| 21 |
+
|
| 22 |
+
from pyarrow.includes.common cimport *
|
| 23 |
+
from pyarrow.includes.libarrow_dataset cimport *
|
| 24 |
+
from pyarrow.lib cimport *
|
| 25 |
+
from pyarrow._fs cimport FileSystem, FileInfo
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
cdef CFileSource _make_file_source(object file, FileSystem filesystem=*, object file_size=*)
|
| 29 |
+
|
| 30 |
+
cdef class DatasetFactory(_Weakrefable):
|
| 31 |
+
|
| 32 |
+
cdef:
|
| 33 |
+
SharedPtrNoGIL[CDatasetFactory] wrapped
|
| 34 |
+
CDatasetFactory* factory
|
| 35 |
+
|
| 36 |
+
cdef init(self, const shared_ptr[CDatasetFactory]& sp)
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
cdef wrap(const shared_ptr[CDatasetFactory]& sp)
|
| 40 |
+
|
| 41 |
+
cdef inline shared_ptr[CDatasetFactory] unwrap(self) nogil
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
cdef class Dataset(_Weakrefable):
|
| 45 |
+
|
| 46 |
+
cdef:
|
| 47 |
+
SharedPtrNoGIL[CDataset] wrapped
|
| 48 |
+
CDataset* dataset
|
| 49 |
+
public dict _scan_options
|
| 50 |
+
|
| 51 |
+
cdef void init(self, const shared_ptr[CDataset]& sp)
|
| 52 |
+
|
| 53 |
+
@staticmethod
|
| 54 |
+
cdef wrap(const shared_ptr[CDataset]& sp)
|
| 55 |
+
|
| 56 |
+
cdef shared_ptr[CDataset] unwrap(self) nogil
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
cdef class Scanner(_Weakrefable):
|
| 60 |
+
cdef:
|
| 61 |
+
SharedPtrNoGIL[CScanner] wrapped
|
| 62 |
+
CScanner* scanner
|
| 63 |
+
|
| 64 |
+
cdef void init(self, const shared_ptr[CScanner]& sp)
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
cdef wrap(const shared_ptr[CScanner]& sp)
|
| 68 |
+
|
| 69 |
+
cdef shared_ptr[CScanner] unwrap(self)
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
cdef shared_ptr[CScanOptions] _make_scan_options(Dataset dataset, dict py_scanoptions) except *
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
cdef class FragmentScanOptions(_Weakrefable):
|
| 76 |
+
|
| 77 |
+
cdef:
|
| 78 |
+
shared_ptr[CFragmentScanOptions] wrapped
|
| 79 |
+
|
| 80 |
+
cdef void init(self, const shared_ptr[CFragmentScanOptions]& sp)
|
| 81 |
+
|
| 82 |
+
@staticmethod
|
| 83 |
+
cdef wrap(const shared_ptr[CFragmentScanOptions]& sp)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
cdef class FileFormat(_Weakrefable):
|
| 87 |
+
|
| 88 |
+
cdef:
|
| 89 |
+
shared_ptr[CFileFormat] wrapped
|
| 90 |
+
CFileFormat* format
|
| 91 |
+
|
| 92 |
+
cdef void init(self, const shared_ptr[CFileFormat]& sp)
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
cdef wrap(const shared_ptr[CFileFormat]& sp)
|
| 96 |
+
|
| 97 |
+
cdef inline shared_ptr[CFileFormat] unwrap(self)
|
| 98 |
+
|
| 99 |
+
cdef _set_default_fragment_scan_options(self, FragmentScanOptions options)
|
| 100 |
+
|
| 101 |
+
# Return a WrittenFile after a file was written.
|
| 102 |
+
# May be overridden by subclasses, e.g. to add metadata.
|
| 103 |
+
cdef WrittenFile _finish_write(self, path, base_dir,
|
| 104 |
+
CFileWriter* file_writer)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
cdef class FileWriteOptions(_Weakrefable):
|
| 108 |
+
|
| 109 |
+
cdef:
|
| 110 |
+
shared_ptr[CFileWriteOptions] wrapped
|
| 111 |
+
CFileWriteOptions* c_options
|
| 112 |
+
|
| 113 |
+
cdef void init(self, const shared_ptr[CFileWriteOptions]& sp)
|
| 114 |
+
|
| 115 |
+
@staticmethod
|
| 116 |
+
cdef wrap(const shared_ptr[CFileWriteOptions]& sp)
|
| 117 |
+
|
| 118 |
+
cdef inline shared_ptr[CFileWriteOptions] unwrap(self)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
cdef class Fragment(_Weakrefable):
|
| 122 |
+
|
| 123 |
+
cdef:
|
| 124 |
+
SharedPtrNoGIL[CFragment] wrapped
|
| 125 |
+
CFragment* fragment
|
| 126 |
+
|
| 127 |
+
cdef void init(self, const shared_ptr[CFragment]& sp)
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
cdef wrap(const shared_ptr[CFragment]& sp)
|
| 131 |
+
|
| 132 |
+
cdef inline shared_ptr[CFragment] unwrap(self)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
cdef class FileFragment(Fragment):
|
| 136 |
+
|
| 137 |
+
cdef:
|
| 138 |
+
CFileFragment* file_fragment
|
| 139 |
+
|
| 140 |
+
cdef void init(self, const shared_ptr[CFragment]& sp)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
cdef class Partitioning(_Weakrefable):
|
| 144 |
+
|
| 145 |
+
cdef:
|
| 146 |
+
shared_ptr[CPartitioning] wrapped
|
| 147 |
+
CPartitioning* partitioning
|
| 148 |
+
|
| 149 |
+
cdef init(self, const shared_ptr[CPartitioning]& sp)
|
| 150 |
+
|
| 151 |
+
@staticmethod
|
| 152 |
+
cdef wrap(const shared_ptr[CPartitioning]& sp)
|
| 153 |
+
|
| 154 |
+
cdef inline shared_ptr[CPartitioning] unwrap(self)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
cdef class PartitioningFactory(_Weakrefable):
|
| 158 |
+
|
| 159 |
+
cdef:
|
| 160 |
+
shared_ptr[CPartitioningFactory] wrapped
|
| 161 |
+
CPartitioningFactory* factory
|
| 162 |
+
object constructor
|
| 163 |
+
object options
|
| 164 |
+
|
| 165 |
+
cdef init(self, const shared_ptr[CPartitioningFactory]& sp)
|
| 166 |
+
|
| 167 |
+
@staticmethod
|
| 168 |
+
cdef wrap(const shared_ptr[CPartitioningFactory]& sp,
|
| 169 |
+
object constructor, object options)
|
| 170 |
+
|
| 171 |
+
cdef inline shared_ptr[CPartitioningFactory] unwrap(self)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
cdef class WrittenFile(_Weakrefable):
|
| 175 |
+
|
| 176 |
+
# The full path to the created file
|
| 177 |
+
cdef public str path
|
| 178 |
+
# Optional Parquet metadata
|
| 179 |
+
# This metadata will have the file path attribute set to the path of
|
| 180 |
+
# the written file.
|
| 181 |
+
cdef public object metadata
|
| 182 |
+
# The size of the file in bytes
|
| 183 |
+
cdef public int64_t size
|
vllm/lib/python3.10/site-packages/pyarrow/_dataset.pyx
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vllm/lib/python3.10/site-packages/pyarrow/_orc.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:40543ecaa01cf96a0dbb6ab25f343e2576033484d686fafd182886a3f23c45c7
|
| 3 |
+
size 209752
|
vllm/lib/python3.10/site-packages/pyarrow/_parquet_encryption.pxd
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
# cython: language_level = 3
|
| 20 |
+
|
| 21 |
+
from pyarrow.includes.common cimport *
|
| 22 |
+
from pyarrow.includes.libparquet_encryption cimport *
|
| 23 |
+
from pyarrow._parquet cimport (ParquetCipher,
|
| 24 |
+
CFileEncryptionProperties,
|
| 25 |
+
CFileDecryptionProperties,
|
| 26 |
+
FileEncryptionProperties,
|
| 27 |
+
FileDecryptionProperties,
|
| 28 |
+
ParquetCipher_AES_GCM_V1,
|
| 29 |
+
ParquetCipher_AES_GCM_CTR_V1)
|
| 30 |
+
from pyarrow.lib cimport _Weakrefable
|
| 31 |
+
|
| 32 |
+
cdef class CryptoFactory(_Weakrefable):
|
| 33 |
+
cdef shared_ptr[CPyCryptoFactory] factory
|
| 34 |
+
cdef init(self, callable_client_factory)
|
| 35 |
+
cdef inline shared_ptr[CPyCryptoFactory] unwrap(self)
|
| 36 |
+
|
| 37 |
+
cdef class EncryptionConfiguration(_Weakrefable):
|
| 38 |
+
cdef shared_ptr[CEncryptionConfiguration] configuration
|
| 39 |
+
cdef inline shared_ptr[CEncryptionConfiguration] unwrap(self) nogil
|
| 40 |
+
|
| 41 |
+
cdef class DecryptionConfiguration(_Weakrefable):
|
| 42 |
+
cdef shared_ptr[CDecryptionConfiguration] configuration
|
| 43 |
+
cdef inline shared_ptr[CDecryptionConfiguration] unwrap(self) nogil
|
| 44 |
+
|
| 45 |
+
cdef class KmsConnectionConfig(_Weakrefable):
|
| 46 |
+
cdef shared_ptr[CKmsConnectionConfig] configuration
|
| 47 |
+
cdef inline shared_ptr[CKmsConnectionConfig] unwrap(self) nogil
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
cdef wrap(const CKmsConnectionConfig& config)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
cdef shared_ptr[CCryptoFactory] pyarrow_unwrap_cryptofactory(object crypto_factory) except *
|
| 54 |
+
cdef shared_ptr[CKmsConnectionConfig] pyarrow_unwrap_kmsconnectionconfig(object kmsconnectionconfig) except *
|
| 55 |
+
cdef shared_ptr[CEncryptionConfiguration] pyarrow_unwrap_encryptionconfig(object encryptionconfig) except *
|
| 56 |
+
cdef shared_ptr[CDecryptionConfiguration] pyarrow_unwrap_decryptionconfig(object decryptionconfig) except *
|
vllm/lib/python3.10/site-packages/pyarrow/_s3fs.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:15d8576641e4d8934199313026498bdec65fd0d3350400c7d4128a071d0f6463
|
| 3 |
+
size 232056
|
vllm/lib/python3.10/site-packages/pyarrow/benchmark.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# flake8: noqa
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
from pyarrow.lib import benchmark_PandasObjectIsNull
|
vllm/lib/python3.10/site-packages/pyarrow/builder.pxi
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
cdef class StringBuilder(_Weakrefable):
|
| 22 |
+
"""
|
| 23 |
+
Builder class for UTF8 strings.
|
| 24 |
+
|
| 25 |
+
This class exposes facilities for incrementally adding string values and
|
| 26 |
+
building the null bitmap for a pyarrow.Array (type='string').
|
| 27 |
+
"""
|
| 28 |
+
cdef:
|
| 29 |
+
unique_ptr[CStringBuilder] builder
|
| 30 |
+
|
| 31 |
+
def __cinit__(self, MemoryPool memory_pool=None):
|
| 32 |
+
cdef CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
|
| 33 |
+
self.builder.reset(new CStringBuilder(pool))
|
| 34 |
+
|
| 35 |
+
def append(self, value):
|
| 36 |
+
"""
|
| 37 |
+
Append a single value to the builder.
|
| 38 |
+
|
| 39 |
+
The value can either be a string/bytes object or a null value
|
| 40 |
+
(np.nan or None).
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
value : string/bytes or np.nan/None
|
| 45 |
+
The value to append to the string array builder.
|
| 46 |
+
"""
|
| 47 |
+
if isinstance(value, (bytes, str)):
|
| 48 |
+
self.builder.get().Append(tobytes(value))
|
| 49 |
+
elif value is None or math.isnan(value):
|
| 50 |
+
self.builder.get().AppendNull()
|
| 51 |
+
else:
|
| 52 |
+
raise TypeError('StringBuilder only accepts string objects')
|
| 53 |
+
|
| 54 |
+
def append_values(self, values):
|
| 55 |
+
"""
|
| 56 |
+
Append all the values from an iterable.
|
| 57 |
+
|
| 58 |
+
Parameters
|
| 59 |
+
----------
|
| 60 |
+
values : iterable of string/bytes or np.nan/None values
|
| 61 |
+
The values to append to the string array builder.
|
| 62 |
+
"""
|
| 63 |
+
for value in values:
|
| 64 |
+
self.append(value)
|
| 65 |
+
|
| 66 |
+
def finish(self):
|
| 67 |
+
"""
|
| 68 |
+
Return result of builder as an Array object; also resets the builder.
|
| 69 |
+
|
| 70 |
+
Returns
|
| 71 |
+
-------
|
| 72 |
+
array : pyarrow.Array
|
| 73 |
+
"""
|
| 74 |
+
cdef shared_ptr[CArray] out
|
| 75 |
+
with nogil:
|
| 76 |
+
self.builder.get().Finish(&out)
|
| 77 |
+
return pyarrow_wrap_array(out)
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def null_count(self):
|
| 81 |
+
return self.builder.get().null_count()
|
| 82 |
+
|
| 83 |
+
def __len__(self):
|
| 84 |
+
return self.builder.get().length()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
cdef class StringViewBuilder(_Weakrefable):
|
| 88 |
+
"""
|
| 89 |
+
Builder class for UTF8 string views.
|
| 90 |
+
|
| 91 |
+
This class exposes facilities for incrementally adding string values and
|
| 92 |
+
building the null bitmap for a pyarrow.Array (type='string_view').
|
| 93 |
+
"""
|
| 94 |
+
cdef:
|
| 95 |
+
unique_ptr[CStringViewBuilder] builder
|
| 96 |
+
|
| 97 |
+
def __cinit__(self, MemoryPool memory_pool=None):
|
| 98 |
+
cdef CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
|
| 99 |
+
self.builder.reset(new CStringViewBuilder(pool))
|
| 100 |
+
|
| 101 |
+
def append(self, value):
|
| 102 |
+
"""
|
| 103 |
+
Append a single value to the builder.
|
| 104 |
+
|
| 105 |
+
The value can either be a string/bytes object or a null value
|
| 106 |
+
(np.nan or None).
|
| 107 |
+
|
| 108 |
+
Parameters
|
| 109 |
+
----------
|
| 110 |
+
value : string/bytes or np.nan/None
|
| 111 |
+
The value to append to the string array builder.
|
| 112 |
+
"""
|
| 113 |
+
if isinstance(value, (bytes, str)):
|
| 114 |
+
self.builder.get().Append(tobytes(value))
|
| 115 |
+
elif value is None or math.isnan(value):
|
| 116 |
+
self.builder.get().AppendNull()
|
| 117 |
+
else:
|
| 118 |
+
raise TypeError('StringViewBuilder only accepts string objects')
|
| 119 |
+
|
| 120 |
+
def append_values(self, values):
|
| 121 |
+
"""
|
| 122 |
+
Append all the values from an iterable.
|
| 123 |
+
|
| 124 |
+
Parameters
|
| 125 |
+
----------
|
| 126 |
+
values : iterable of string/bytes or np.nan/None values
|
| 127 |
+
The values to append to the string array builder.
|
| 128 |
+
"""
|
| 129 |
+
for value in values:
|
| 130 |
+
self.append(value)
|
| 131 |
+
|
| 132 |
+
def finish(self):
|
| 133 |
+
"""
|
| 134 |
+
Return result of builder as an Array object; also resets the builder.
|
| 135 |
+
|
| 136 |
+
Returns
|
| 137 |
+
-------
|
| 138 |
+
array : pyarrow.Array
|
| 139 |
+
"""
|
| 140 |
+
cdef shared_ptr[CArray] out
|
| 141 |
+
with nogil:
|
| 142 |
+
self.builder.get().Finish(&out)
|
| 143 |
+
return pyarrow_wrap_array(out)
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def null_count(self):
|
| 147 |
+
return self.builder.get().null_count()
|
| 148 |
+
|
| 149 |
+
def __len__(self):
|
| 150 |
+
return self.builder.get().length()
|
vllm/lib/python3.10/site-packages/pyarrow/csv.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
from pyarrow._csv import ( # noqa
|
| 20 |
+
ReadOptions, ParseOptions, ConvertOptions, ISO8601,
|
| 21 |
+
open_csv, read_csv, CSVStreamingReader, write_csv,
|
| 22 |
+
WriteOptions, CSVWriter, InvalidRow)
|
vllm/lib/python3.10/site-packages/pyarrow/gandiva.pyx
ADDED
|
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# cython: profile=False
|
| 19 |
+
# distutils: language = c++
|
| 20 |
+
# cython: language_level = 3
|
| 21 |
+
|
| 22 |
+
from libcpp.memory cimport shared_ptr
|
| 23 |
+
from libcpp.string cimport string as c_string
|
| 24 |
+
from libcpp.vector cimport vector as c_vector
|
| 25 |
+
from libcpp.unordered_set cimport unordered_set as c_unordered_set
|
| 26 |
+
from libc.stdint cimport int64_t, int32_t
|
| 27 |
+
|
| 28 |
+
from pyarrow.includes.libarrow cimport *
|
| 29 |
+
from pyarrow.lib cimport (DataType, Field, MemoryPool, RecordBatch,
|
| 30 |
+
Schema, check_status, pyarrow_wrap_array,
|
| 31 |
+
pyarrow_wrap_data_type, ensure_type, _Weakrefable,
|
| 32 |
+
pyarrow_wrap_field)
|
| 33 |
+
|
| 34 |
+
from pyarrow.includes.libgandiva cimport (
|
| 35 |
+
CCondition, CGandivaExpression,
|
| 36 |
+
CNode, CProjector, CFilter,
|
| 37 |
+
CSelectionVector,
|
| 38 |
+
_ensure_selection_mode,
|
| 39 |
+
CConfiguration,
|
| 40 |
+
CConfigurationBuilder,
|
| 41 |
+
TreeExprBuilder_MakeExpression,
|
| 42 |
+
TreeExprBuilder_MakeFunction,
|
| 43 |
+
TreeExprBuilder_MakeBoolLiteral,
|
| 44 |
+
TreeExprBuilder_MakeUInt8Literal,
|
| 45 |
+
TreeExprBuilder_MakeUInt16Literal,
|
| 46 |
+
TreeExprBuilder_MakeUInt32Literal,
|
| 47 |
+
TreeExprBuilder_MakeUInt64Literal,
|
| 48 |
+
TreeExprBuilder_MakeInt8Literal,
|
| 49 |
+
TreeExprBuilder_MakeInt16Literal,
|
| 50 |
+
TreeExprBuilder_MakeInt32Literal,
|
| 51 |
+
TreeExprBuilder_MakeInt64Literal,
|
| 52 |
+
TreeExprBuilder_MakeFloatLiteral,
|
| 53 |
+
TreeExprBuilder_MakeDoubleLiteral,
|
| 54 |
+
TreeExprBuilder_MakeStringLiteral,
|
| 55 |
+
TreeExprBuilder_MakeBinaryLiteral,
|
| 56 |
+
TreeExprBuilder_MakeField,
|
| 57 |
+
TreeExprBuilder_MakeIf,
|
| 58 |
+
TreeExprBuilder_MakeAnd,
|
| 59 |
+
TreeExprBuilder_MakeOr,
|
| 60 |
+
TreeExprBuilder_MakeCondition,
|
| 61 |
+
TreeExprBuilder_MakeInExpressionInt32,
|
| 62 |
+
TreeExprBuilder_MakeInExpressionInt64,
|
| 63 |
+
TreeExprBuilder_MakeInExpressionTime32,
|
| 64 |
+
TreeExprBuilder_MakeInExpressionTime64,
|
| 65 |
+
TreeExprBuilder_MakeInExpressionDate32,
|
| 66 |
+
TreeExprBuilder_MakeInExpressionDate64,
|
| 67 |
+
TreeExprBuilder_MakeInExpressionTimeStamp,
|
| 68 |
+
TreeExprBuilder_MakeInExpressionString,
|
| 69 |
+
SelectionVector_MakeInt16,
|
| 70 |
+
SelectionVector_MakeInt32,
|
| 71 |
+
SelectionVector_MakeInt64,
|
| 72 |
+
Projector_Make,
|
| 73 |
+
Filter_Make,
|
| 74 |
+
CFunctionSignature,
|
| 75 |
+
GetRegisteredFunctionSignatures)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
cdef class Node(_Weakrefable):
|
| 79 |
+
cdef:
|
| 80 |
+
shared_ptr[CNode] node
|
| 81 |
+
|
| 82 |
+
def __init__(self):
|
| 83 |
+
raise TypeError("Do not call {}'s constructor directly, use the "
|
| 84 |
+
"TreeExprBuilder API directly"
|
| 85 |
+
.format(self.__class__.__name__))
|
| 86 |
+
|
| 87 |
+
@staticmethod
|
| 88 |
+
cdef create(shared_ptr[CNode] node):
|
| 89 |
+
cdef Node self = Node.__new__(Node)
|
| 90 |
+
self.node = node
|
| 91 |
+
return self
|
| 92 |
+
|
| 93 |
+
def __str__(self):
|
| 94 |
+
return self.node.get().ToString().decode()
|
| 95 |
+
|
| 96 |
+
def __repr__(self):
|
| 97 |
+
type_format = object.__repr__(self)
|
| 98 |
+
return '{0}\n{1}'.format(type_format, str(self))
|
| 99 |
+
|
| 100 |
+
def return_type(self):
|
| 101 |
+
return pyarrow_wrap_data_type(self.node.get().return_type())
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
cdef class Expression(_Weakrefable):
|
| 105 |
+
cdef:
|
| 106 |
+
shared_ptr[CGandivaExpression] expression
|
| 107 |
+
|
| 108 |
+
cdef void init(self, shared_ptr[CGandivaExpression] expression):
|
| 109 |
+
self.expression = expression
|
| 110 |
+
|
| 111 |
+
def __str__(self):
|
| 112 |
+
return self.expression.get().ToString().decode()
|
| 113 |
+
|
| 114 |
+
def __repr__(self):
|
| 115 |
+
type_format = object.__repr__(self)
|
| 116 |
+
return '{0}\n{1}'.format(type_format, str(self))
|
| 117 |
+
|
| 118 |
+
def root(self):
|
| 119 |
+
return Node.create(self.expression.get().root())
|
| 120 |
+
|
| 121 |
+
def result(self):
|
| 122 |
+
return pyarrow_wrap_field(self.expression.get().result())
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
cdef class Condition(_Weakrefable):
|
| 126 |
+
cdef:
|
| 127 |
+
shared_ptr[CCondition] condition
|
| 128 |
+
|
| 129 |
+
def __init__(self):
|
| 130 |
+
raise TypeError("Do not call {}'s constructor directly, use the "
|
| 131 |
+
"TreeExprBuilder API instead"
|
| 132 |
+
.format(self.__class__.__name__))
|
| 133 |
+
|
| 134 |
+
@staticmethod
|
| 135 |
+
cdef create(shared_ptr[CCondition] condition):
|
| 136 |
+
cdef Condition self = Condition.__new__(Condition)
|
| 137 |
+
self.condition = condition
|
| 138 |
+
return self
|
| 139 |
+
|
| 140 |
+
def __str__(self):
|
| 141 |
+
return self.condition.get().ToString().decode()
|
| 142 |
+
|
| 143 |
+
def __repr__(self):
|
| 144 |
+
type_format = object.__repr__(self)
|
| 145 |
+
return '{0}\n{1}'.format(type_format, str(self))
|
| 146 |
+
|
| 147 |
+
def root(self):
|
| 148 |
+
return Node.create(self.condition.get().root())
|
| 149 |
+
|
| 150 |
+
def result(self):
|
| 151 |
+
return pyarrow_wrap_field(self.condition.get().result())
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
cdef class SelectionVector(_Weakrefable):
|
| 155 |
+
cdef:
|
| 156 |
+
shared_ptr[CSelectionVector] selection_vector
|
| 157 |
+
|
| 158 |
+
def __init__(self):
|
| 159 |
+
raise TypeError("Do not call {}'s constructor directly."
|
| 160 |
+
.format(self.__class__.__name__))
|
| 161 |
+
|
| 162 |
+
@staticmethod
|
| 163 |
+
cdef create(shared_ptr[CSelectionVector] selection_vector):
|
| 164 |
+
cdef SelectionVector self = SelectionVector.__new__(SelectionVector)
|
| 165 |
+
self.selection_vector = selection_vector
|
| 166 |
+
return self
|
| 167 |
+
|
| 168 |
+
def to_array(self):
|
| 169 |
+
cdef shared_ptr[CArray] result = self.selection_vector.get().ToArray()
|
| 170 |
+
return pyarrow_wrap_array(result)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
cdef class Projector(_Weakrefable):
|
| 174 |
+
cdef:
|
| 175 |
+
shared_ptr[CProjector] projector
|
| 176 |
+
MemoryPool pool
|
| 177 |
+
|
| 178 |
+
def __init__(self):
|
| 179 |
+
raise TypeError("Do not call {}'s constructor directly, use "
|
| 180 |
+
"make_projector instead"
|
| 181 |
+
.format(self.__class__.__name__))
|
| 182 |
+
|
| 183 |
+
@staticmethod
|
| 184 |
+
cdef create(shared_ptr[CProjector] projector, MemoryPool pool):
|
| 185 |
+
cdef Projector self = Projector.__new__(Projector)
|
| 186 |
+
self.projector = projector
|
| 187 |
+
self.pool = pool
|
| 188 |
+
return self
|
| 189 |
+
|
| 190 |
+
@property
|
| 191 |
+
def llvm_ir(self):
|
| 192 |
+
return self.projector.get().DumpIR().decode()
|
| 193 |
+
|
| 194 |
+
def evaluate(self, RecordBatch batch, SelectionVector selection=None):
|
| 195 |
+
"""
|
| 196 |
+
Evaluate the specified record batch and return the arrays at the
|
| 197 |
+
filtered positions.
|
| 198 |
+
|
| 199 |
+
Parameters
|
| 200 |
+
----------
|
| 201 |
+
batch : pyarrow.RecordBatch
|
| 202 |
+
selection : pyarrow.gandiva.SelectionVector
|
| 203 |
+
|
| 204 |
+
Returns
|
| 205 |
+
-------
|
| 206 |
+
list[pyarrow.Array]
|
| 207 |
+
"""
|
| 208 |
+
cdef vector[shared_ptr[CArray]] results
|
| 209 |
+
if selection is None:
|
| 210 |
+
check_status(self.projector.get().Evaluate(
|
| 211 |
+
batch.sp_batch.get()[0], self.pool.pool, &results))
|
| 212 |
+
else:
|
| 213 |
+
check_status(
|
| 214 |
+
self.projector.get().Evaluate(
|
| 215 |
+
batch.sp_batch.get()[0], selection.selection_vector.get(),
|
| 216 |
+
self.pool.pool, &results))
|
| 217 |
+
cdef shared_ptr[CArray] result
|
| 218 |
+
arrays = []
|
| 219 |
+
for result in results:
|
| 220 |
+
arrays.append(pyarrow_wrap_array(result))
|
| 221 |
+
return arrays
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
cdef class Filter(_Weakrefable):
|
| 225 |
+
cdef:
|
| 226 |
+
shared_ptr[CFilter] filter
|
| 227 |
+
|
| 228 |
+
def __init__(self):
|
| 229 |
+
raise TypeError("Do not call {}'s constructor directly, use "
|
| 230 |
+
"make_filter instead"
|
| 231 |
+
.format(self.__class__.__name__))
|
| 232 |
+
|
| 233 |
+
@staticmethod
|
| 234 |
+
cdef create(shared_ptr[CFilter] filter):
|
| 235 |
+
cdef Filter self = Filter.__new__(Filter)
|
| 236 |
+
self.filter = filter
|
| 237 |
+
return self
|
| 238 |
+
|
| 239 |
+
@property
|
| 240 |
+
def llvm_ir(self):
|
| 241 |
+
return self.filter.get().DumpIR().decode()
|
| 242 |
+
|
| 243 |
+
def evaluate(self, RecordBatch batch, MemoryPool pool, dtype='int32'):
|
| 244 |
+
"""
|
| 245 |
+
Evaluate the specified record batch and return a selection vector.
|
| 246 |
+
|
| 247 |
+
Parameters
|
| 248 |
+
----------
|
| 249 |
+
batch : pyarrow.RecordBatch
|
| 250 |
+
pool : MemoryPool
|
| 251 |
+
dtype : DataType or str, default int32
|
| 252 |
+
|
| 253 |
+
Returns
|
| 254 |
+
-------
|
| 255 |
+
pyarrow.gandiva.SelectionVector
|
| 256 |
+
"""
|
| 257 |
+
cdef:
|
| 258 |
+
DataType type = ensure_type(dtype)
|
| 259 |
+
shared_ptr[CSelectionVector] selection
|
| 260 |
+
|
| 261 |
+
if type.id == _Type_INT16:
|
| 262 |
+
check_status(SelectionVector_MakeInt16(
|
| 263 |
+
batch.num_rows, pool.pool, &selection))
|
| 264 |
+
elif type.id == _Type_INT32:
|
| 265 |
+
check_status(SelectionVector_MakeInt32(
|
| 266 |
+
batch.num_rows, pool.pool, &selection))
|
| 267 |
+
elif type.id == _Type_INT64:
|
| 268 |
+
check_status(SelectionVector_MakeInt64(
|
| 269 |
+
batch.num_rows, pool.pool, &selection))
|
| 270 |
+
else:
|
| 271 |
+
raise ValueError("'dtype' of the selection vector should be "
|
| 272 |
+
"one of 'int16', 'int32' and 'int64'.")
|
| 273 |
+
|
| 274 |
+
check_status(self.filter.get().Evaluate(
|
| 275 |
+
batch.sp_batch.get()[0], selection))
|
| 276 |
+
return SelectionVector.create(selection)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
cdef class TreeExprBuilder(_Weakrefable):
|
| 280 |
+
|
| 281 |
+
def make_literal(self, value, dtype):
|
| 282 |
+
"""
|
| 283 |
+
Create a node on a literal.
|
| 284 |
+
|
| 285 |
+
Parameters
|
| 286 |
+
----------
|
| 287 |
+
value : a literal value
|
| 288 |
+
dtype : DataType
|
| 289 |
+
|
| 290 |
+
Returns
|
| 291 |
+
-------
|
| 292 |
+
pyarrow.gandiva.Node
|
| 293 |
+
"""
|
| 294 |
+
cdef:
|
| 295 |
+
DataType type = ensure_type(dtype)
|
| 296 |
+
shared_ptr[CNode] r
|
| 297 |
+
|
| 298 |
+
if type.id == _Type_BOOL:
|
| 299 |
+
r = TreeExprBuilder_MakeBoolLiteral(value)
|
| 300 |
+
elif type.id == _Type_UINT8:
|
| 301 |
+
r = TreeExprBuilder_MakeUInt8Literal(value)
|
| 302 |
+
elif type.id == _Type_UINT16:
|
| 303 |
+
r = TreeExprBuilder_MakeUInt16Literal(value)
|
| 304 |
+
elif type.id == _Type_UINT32:
|
| 305 |
+
r = TreeExprBuilder_MakeUInt32Literal(value)
|
| 306 |
+
elif type.id == _Type_UINT64:
|
| 307 |
+
r = TreeExprBuilder_MakeUInt64Literal(value)
|
| 308 |
+
elif type.id == _Type_INT8:
|
| 309 |
+
r = TreeExprBuilder_MakeInt8Literal(value)
|
| 310 |
+
elif type.id == _Type_INT16:
|
| 311 |
+
r = TreeExprBuilder_MakeInt16Literal(value)
|
| 312 |
+
elif type.id == _Type_INT32:
|
| 313 |
+
r = TreeExprBuilder_MakeInt32Literal(value)
|
| 314 |
+
elif type.id == _Type_INT64:
|
| 315 |
+
r = TreeExprBuilder_MakeInt64Literal(value)
|
| 316 |
+
elif type.id == _Type_FLOAT:
|
| 317 |
+
r = TreeExprBuilder_MakeFloatLiteral(value)
|
| 318 |
+
elif type.id == _Type_DOUBLE:
|
| 319 |
+
r = TreeExprBuilder_MakeDoubleLiteral(value)
|
| 320 |
+
elif type.id == _Type_STRING:
|
| 321 |
+
r = TreeExprBuilder_MakeStringLiteral(value.encode('UTF-8'))
|
| 322 |
+
elif type.id == _Type_BINARY:
|
| 323 |
+
r = TreeExprBuilder_MakeBinaryLiteral(value)
|
| 324 |
+
else:
|
| 325 |
+
raise TypeError("Didn't recognize dtype " + str(dtype))
|
| 326 |
+
|
| 327 |
+
return Node.create(r)
|
| 328 |
+
|
| 329 |
+
def make_expression(self, Node root_node not None,
|
| 330 |
+
Field return_field not None):
|
| 331 |
+
"""
|
| 332 |
+
Create an expression with the specified root_node,
|
| 333 |
+
and the result written to result_field.
|
| 334 |
+
|
| 335 |
+
Parameters
|
| 336 |
+
----------
|
| 337 |
+
root_node : pyarrow.gandiva.Node
|
| 338 |
+
return_field : pyarrow.Field
|
| 339 |
+
|
| 340 |
+
Returns
|
| 341 |
+
-------
|
| 342 |
+
pyarrow.gandiva.Expression
|
| 343 |
+
"""
|
| 344 |
+
cdef shared_ptr[CGandivaExpression] r = TreeExprBuilder_MakeExpression(
|
| 345 |
+
root_node.node, return_field.sp_field)
|
| 346 |
+
cdef Expression expression = Expression()
|
| 347 |
+
expression.init(r)
|
| 348 |
+
return expression
|
| 349 |
+
|
| 350 |
+
def make_function(self, name, children, DataType return_type):
|
| 351 |
+
"""
|
| 352 |
+
Create a node with a function.
|
| 353 |
+
|
| 354 |
+
Parameters
|
| 355 |
+
----------
|
| 356 |
+
name : str
|
| 357 |
+
children : pyarrow.gandiva.NodeVector
|
| 358 |
+
return_type : DataType
|
| 359 |
+
|
| 360 |
+
Returns
|
| 361 |
+
-------
|
| 362 |
+
pyarrow.gandiva.Node
|
| 363 |
+
"""
|
| 364 |
+
cdef c_vector[shared_ptr[CNode]] c_children
|
| 365 |
+
cdef Node child
|
| 366 |
+
for child in children:
|
| 367 |
+
if child is None:
|
| 368 |
+
raise TypeError("Child nodes must not be None")
|
| 369 |
+
c_children.push_back(child.node)
|
| 370 |
+
cdef shared_ptr[CNode] r = TreeExprBuilder_MakeFunction(
|
| 371 |
+
name.encode(), c_children, return_type.sp_type)
|
| 372 |
+
return Node.create(r)
|
| 373 |
+
|
| 374 |
+
def make_field(self, Field field not None):
|
| 375 |
+
"""
|
| 376 |
+
Create a node with an Arrow field.
|
| 377 |
+
|
| 378 |
+
Parameters
|
| 379 |
+
----------
|
| 380 |
+
field : pyarrow.Field
|
| 381 |
+
|
| 382 |
+
Returns
|
| 383 |
+
-------
|
| 384 |
+
pyarrow.gandiva.Node
|
| 385 |
+
"""
|
| 386 |
+
cdef shared_ptr[CNode] r = TreeExprBuilder_MakeField(field.sp_field)
|
| 387 |
+
return Node.create(r)
|
| 388 |
+
|
| 389 |
+
def make_if(self, Node condition not None, Node this_node not None,
|
| 390 |
+
Node else_node not None, DataType return_type not None):
|
| 391 |
+
"""
|
| 392 |
+
Create a node with an if-else expression.
|
| 393 |
+
|
| 394 |
+
Parameters
|
| 395 |
+
----------
|
| 396 |
+
condition : pyarrow.gandiva.Node
|
| 397 |
+
this_node : pyarrow.gandiva.Node
|
| 398 |
+
else_node : pyarrow.gandiva.Node
|
| 399 |
+
return_type : DataType
|
| 400 |
+
|
| 401 |
+
Returns
|
| 402 |
+
-------
|
| 403 |
+
pyarrow.gandiva.Node
|
| 404 |
+
"""
|
| 405 |
+
cdef shared_ptr[CNode] r = TreeExprBuilder_MakeIf(
|
| 406 |
+
condition.node, this_node.node, else_node.node,
|
| 407 |
+
return_type.sp_type)
|
| 408 |
+
return Node.create(r)
|
| 409 |
+
|
| 410 |
+
def make_and(self, children):
|
| 411 |
+
"""
|
| 412 |
+
Create a Node with a boolean AND expression.
|
| 413 |
+
|
| 414 |
+
Parameters
|
| 415 |
+
----------
|
| 416 |
+
children : list[pyarrow.gandiva.Node]
|
| 417 |
+
|
| 418 |
+
Returns
|
| 419 |
+
-------
|
| 420 |
+
pyarrow.gandiva.Node
|
| 421 |
+
"""
|
| 422 |
+
cdef c_vector[shared_ptr[CNode]] c_children
|
| 423 |
+
cdef Node child
|
| 424 |
+
for child in children:
|
| 425 |
+
if child is None:
|
| 426 |
+
raise TypeError("Child nodes must not be None")
|
| 427 |
+
c_children.push_back(child.node)
|
| 428 |
+
cdef shared_ptr[CNode] r = TreeExprBuilder_MakeAnd(c_children)
|
| 429 |
+
return Node.create(r)
|
| 430 |
+
|
| 431 |
+
def make_or(self, children):
|
| 432 |
+
"""
|
| 433 |
+
Create a Node with a boolean OR expression.
|
| 434 |
+
|
| 435 |
+
Parameters
|
| 436 |
+
----------
|
| 437 |
+
children : list[pyarrow.gandiva.Node]
|
| 438 |
+
|
| 439 |
+
Returns
|
| 440 |
+
-------
|
| 441 |
+
pyarrow.gandiva.Node
|
| 442 |
+
"""
|
| 443 |
+
cdef c_vector[shared_ptr[CNode]] c_children
|
| 444 |
+
cdef Node child
|
| 445 |
+
for child in children:
|
| 446 |
+
if child is None:
|
| 447 |
+
raise TypeError("Child nodes must not be None")
|
| 448 |
+
c_children.push_back(child.node)
|
| 449 |
+
cdef shared_ptr[CNode] r = TreeExprBuilder_MakeOr(c_children)
|
| 450 |
+
return Node.create(r)
|
| 451 |
+
|
| 452 |
+
def _make_in_expression_int32(self, Node node not None, values):
|
| 453 |
+
cdef shared_ptr[CNode] r
|
| 454 |
+
cdef c_unordered_set[int32_t] c_values
|
| 455 |
+
cdef int32_t v
|
| 456 |
+
for v in values:
|
| 457 |
+
c_values.insert(v)
|
| 458 |
+
r = TreeExprBuilder_MakeInExpressionInt32(node.node, c_values)
|
| 459 |
+
return Node.create(r)
|
| 460 |
+
|
| 461 |
+
def _make_in_expression_int64(self, Node node not None, values):
|
| 462 |
+
cdef shared_ptr[CNode] r
|
| 463 |
+
cdef c_unordered_set[int64_t] c_values
|
| 464 |
+
cdef int64_t v
|
| 465 |
+
for v in values:
|
| 466 |
+
c_values.insert(v)
|
| 467 |
+
r = TreeExprBuilder_MakeInExpressionInt64(node.node, c_values)
|
| 468 |
+
return Node.create(r)
|
| 469 |
+
|
| 470 |
+
def _make_in_expression_time32(self, Node node not None, values):
|
| 471 |
+
cdef shared_ptr[CNode] r
|
| 472 |
+
cdef c_unordered_set[int32_t] c_values
|
| 473 |
+
cdef int32_t v
|
| 474 |
+
for v in values:
|
| 475 |
+
c_values.insert(v)
|
| 476 |
+
r = TreeExprBuilder_MakeInExpressionTime32(node.node, c_values)
|
| 477 |
+
return Node.create(r)
|
| 478 |
+
|
| 479 |
+
def _make_in_expression_time64(self, Node node not None, values):
|
| 480 |
+
cdef shared_ptr[CNode] r
|
| 481 |
+
cdef c_unordered_set[int64_t] c_values
|
| 482 |
+
cdef int64_t v
|
| 483 |
+
for v in values:
|
| 484 |
+
c_values.insert(v)
|
| 485 |
+
r = TreeExprBuilder_MakeInExpressionTime64(node.node, c_values)
|
| 486 |
+
return Node.create(r)
|
| 487 |
+
|
| 488 |
+
def _make_in_expression_date32(self, Node node not None, values):
|
| 489 |
+
cdef shared_ptr[CNode] r
|
| 490 |
+
cdef c_unordered_set[int32_t] c_values
|
| 491 |
+
cdef int32_t v
|
| 492 |
+
for v in values:
|
| 493 |
+
c_values.insert(v)
|
| 494 |
+
r = TreeExprBuilder_MakeInExpressionDate32(node.node, c_values)
|
| 495 |
+
return Node.create(r)
|
| 496 |
+
|
| 497 |
+
def _make_in_expression_date64(self, Node node not None, values):
|
| 498 |
+
cdef shared_ptr[CNode] r
|
| 499 |
+
cdef c_unordered_set[int64_t] c_values
|
| 500 |
+
cdef int64_t v
|
| 501 |
+
for v in values:
|
| 502 |
+
c_values.insert(v)
|
| 503 |
+
r = TreeExprBuilder_MakeInExpressionDate64(node.node, c_values)
|
| 504 |
+
return Node.create(r)
|
| 505 |
+
|
| 506 |
+
def _make_in_expression_timestamp(self, Node node not None, values):
|
| 507 |
+
cdef shared_ptr[CNode] r
|
| 508 |
+
cdef c_unordered_set[int64_t] c_values
|
| 509 |
+
cdef int64_t v
|
| 510 |
+
for v in values:
|
| 511 |
+
c_values.insert(v)
|
| 512 |
+
r = TreeExprBuilder_MakeInExpressionTimeStamp(node.node, c_values)
|
| 513 |
+
return Node.create(r)
|
| 514 |
+
|
| 515 |
+
def _make_in_expression_binary(self, Node node not None, values):
|
| 516 |
+
cdef shared_ptr[CNode] r
|
| 517 |
+
cdef c_unordered_set[c_string] c_values
|
| 518 |
+
cdef c_string v
|
| 519 |
+
for v in values:
|
| 520 |
+
c_values.insert(v)
|
| 521 |
+
r = TreeExprBuilder_MakeInExpressionString(node.node, c_values)
|
| 522 |
+
return Node.create(r)
|
| 523 |
+
|
| 524 |
+
def _make_in_expression_string(self, Node node not None, values):
|
| 525 |
+
cdef shared_ptr[CNode] r
|
| 526 |
+
cdef c_unordered_set[c_string] c_values
|
| 527 |
+
cdef c_string _v
|
| 528 |
+
for v in values:
|
| 529 |
+
_v = v.encode('UTF-8')
|
| 530 |
+
c_values.insert(_v)
|
| 531 |
+
r = TreeExprBuilder_MakeInExpressionString(node.node, c_values)
|
| 532 |
+
return Node.create(r)
|
| 533 |
+
|
| 534 |
+
def make_in_expression(self, Node node not None, values, dtype):
|
| 535 |
+
"""
|
| 536 |
+
Create a Node with an IN expression.
|
| 537 |
+
|
| 538 |
+
Parameters
|
| 539 |
+
----------
|
| 540 |
+
node : pyarrow.gandiva.Node
|
| 541 |
+
values : iterable
|
| 542 |
+
dtype : DataType
|
| 543 |
+
|
| 544 |
+
Returns
|
| 545 |
+
-------
|
| 546 |
+
pyarrow.gandiva.Node
|
| 547 |
+
"""
|
| 548 |
+
cdef DataType type = ensure_type(dtype)
|
| 549 |
+
|
| 550 |
+
if type.id == _Type_INT32:
|
| 551 |
+
return self._make_in_expression_int32(node, values)
|
| 552 |
+
elif type.id == _Type_INT64:
|
| 553 |
+
return self._make_in_expression_int64(node, values)
|
| 554 |
+
elif type.id == _Type_TIME32:
|
| 555 |
+
return self._make_in_expression_time32(node, values)
|
| 556 |
+
elif type.id == _Type_TIME64:
|
| 557 |
+
return self._make_in_expression_time64(node, values)
|
| 558 |
+
elif type.id == _Type_TIMESTAMP:
|
| 559 |
+
return self._make_in_expression_timestamp(node, values)
|
| 560 |
+
elif type.id == _Type_DATE32:
|
| 561 |
+
return self._make_in_expression_date32(node, values)
|
| 562 |
+
elif type.id == _Type_DATE64:
|
| 563 |
+
return self._make_in_expression_date64(node, values)
|
| 564 |
+
elif type.id == _Type_BINARY:
|
| 565 |
+
return self._make_in_expression_binary(node, values)
|
| 566 |
+
elif type.id == _Type_STRING:
|
| 567 |
+
return self._make_in_expression_string(node, values)
|
| 568 |
+
else:
|
| 569 |
+
raise TypeError("Data type " + str(dtype) + " not supported.")
|
| 570 |
+
|
| 571 |
+
def make_condition(self, Node condition not None):
|
| 572 |
+
"""
|
| 573 |
+
Create a condition with the specified node.
|
| 574 |
+
|
| 575 |
+
Parameters
|
| 576 |
+
----------
|
| 577 |
+
condition : pyarrow.gandiva.Node
|
| 578 |
+
|
| 579 |
+
Returns
|
| 580 |
+
-------
|
| 581 |
+
pyarrow.gandiva.Condition
|
| 582 |
+
"""
|
| 583 |
+
cdef shared_ptr[CCondition] r = TreeExprBuilder_MakeCondition(
|
| 584 |
+
condition.node)
|
| 585 |
+
return Condition.create(r)
|
| 586 |
+
|
| 587 |
+
cdef class Configuration(_Weakrefable):
|
| 588 |
+
cdef:
|
| 589 |
+
shared_ptr[CConfiguration] configuration
|
| 590 |
+
|
| 591 |
+
def __cinit__(self, bint optimize=True, bint dump_ir=False):
|
| 592 |
+
"""
|
| 593 |
+
Initialize the configuration with specified options.
|
| 594 |
+
|
| 595 |
+
Parameters
|
| 596 |
+
----------
|
| 597 |
+
optimize : bool, default True
|
| 598 |
+
Whether to enable optimizations.
|
| 599 |
+
dump_ir : bool, default False
|
| 600 |
+
Whether to dump LLVM IR.
|
| 601 |
+
"""
|
| 602 |
+
self.configuration = CConfigurationBuilder().build()
|
| 603 |
+
self.configuration.get().set_optimize(optimize)
|
| 604 |
+
self.configuration.get().set_dump_ir(dump_ir)
|
| 605 |
+
|
| 606 |
+
@staticmethod
|
| 607 |
+
cdef create(shared_ptr[CConfiguration] configuration):
|
| 608 |
+
"""
|
| 609 |
+
Create a Configuration instance from an existing CConfiguration pointer.
|
| 610 |
+
|
| 611 |
+
Parameters
|
| 612 |
+
----------
|
| 613 |
+
configuration : shared_ptr[CConfiguration]
|
| 614 |
+
Existing CConfiguration pointer.
|
| 615 |
+
|
| 616 |
+
Returns
|
| 617 |
+
-------
|
| 618 |
+
Configuration instance
|
| 619 |
+
"""
|
| 620 |
+
cdef Configuration self = Configuration.__new__(Configuration)
|
| 621 |
+
self.configuration = configuration
|
| 622 |
+
return self
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
cpdef make_projector(Schema schema, children, MemoryPool pool,
|
| 626 |
+
str selection_mode="NONE",
|
| 627 |
+
Configuration configuration=None):
|
| 628 |
+
"""
|
| 629 |
+
Construct a projection using expressions.
|
| 630 |
+
|
| 631 |
+
A projector is built for a specific schema and vector of expressions.
|
| 632 |
+
Once the projector is built, it can be used to evaluate many row batches.
|
| 633 |
+
|
| 634 |
+
Parameters
|
| 635 |
+
----------
|
| 636 |
+
schema : pyarrow.Schema
|
| 637 |
+
Schema for the record batches, and the expressions.
|
| 638 |
+
children : list[pyarrow.gandiva.Expression]
|
| 639 |
+
List of projectable expression objects.
|
| 640 |
+
pool : pyarrow.MemoryPool
|
| 641 |
+
Memory pool used to allocate output arrays.
|
| 642 |
+
selection_mode : str, default "NONE"
|
| 643 |
+
Possible values are NONE, UINT16, UINT32, UINT64.
|
| 644 |
+
configuration : pyarrow.gandiva.Configuration, default None
|
| 645 |
+
Configuration for the projector.
|
| 646 |
+
|
| 647 |
+
Returns
|
| 648 |
+
-------
|
| 649 |
+
Projector instance
|
| 650 |
+
"""
|
| 651 |
+
cdef:
|
| 652 |
+
Expression child
|
| 653 |
+
c_vector[shared_ptr[CGandivaExpression]] c_children
|
| 654 |
+
shared_ptr[CProjector] result
|
| 655 |
+
|
| 656 |
+
if configuration is None:
|
| 657 |
+
configuration = Configuration()
|
| 658 |
+
|
| 659 |
+
for child in children:
|
| 660 |
+
if child is None:
|
| 661 |
+
raise TypeError("Expressions must not be None")
|
| 662 |
+
c_children.push_back(child.expression)
|
| 663 |
+
|
| 664 |
+
check_status(
|
| 665 |
+
Projector_Make(schema.sp_schema, c_children,
|
| 666 |
+
_ensure_selection_mode(selection_mode),
|
| 667 |
+
configuration.configuration,
|
| 668 |
+
&result))
|
| 669 |
+
return Projector.create(result, pool)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
cpdef make_filter(Schema schema, Condition condition,
|
| 673 |
+
Configuration configuration=None):
|
| 674 |
+
"""
|
| 675 |
+
Construct a filter based on a condition.
|
| 676 |
+
|
| 677 |
+
A filter is built for a specific schema and condition. Once the filter is
|
| 678 |
+
built, it can be used to evaluate many row batches.
|
| 679 |
+
|
| 680 |
+
Parameters
|
| 681 |
+
----------
|
| 682 |
+
schema : pyarrow.Schema
|
| 683 |
+
Schema for the record batches, and the condition.
|
| 684 |
+
condition : pyarrow.gandiva.Condition
|
| 685 |
+
Filter condition.
|
| 686 |
+
configuration : pyarrow.gandiva.Configuration, default None
|
| 687 |
+
Configuration for the filter.
|
| 688 |
+
|
| 689 |
+
Returns
|
| 690 |
+
-------
|
| 691 |
+
Filter instance
|
| 692 |
+
"""
|
| 693 |
+
cdef shared_ptr[CFilter] result
|
| 694 |
+
if condition is None:
|
| 695 |
+
raise TypeError("Condition must not be None")
|
| 696 |
+
|
| 697 |
+
if configuration is None:
|
| 698 |
+
configuration = Configuration()
|
| 699 |
+
|
| 700 |
+
check_status(
|
| 701 |
+
Filter_Make(schema.sp_schema, condition.condition, configuration.configuration, &result))
|
| 702 |
+
return Filter.create(result)
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
cdef class FunctionSignature(_Weakrefable):
|
| 706 |
+
"""
|
| 707 |
+
Signature of a Gandiva function including name, parameter types
|
| 708 |
+
and return type.
|
| 709 |
+
"""
|
| 710 |
+
|
| 711 |
+
cdef:
|
| 712 |
+
shared_ptr[CFunctionSignature] signature
|
| 713 |
+
|
| 714 |
+
def __init__(self):
|
| 715 |
+
raise TypeError("Do not call {}'s constructor directly."
|
| 716 |
+
.format(self.__class__.__name__))
|
| 717 |
+
|
| 718 |
+
@staticmethod
|
| 719 |
+
cdef create(shared_ptr[CFunctionSignature] signature):
|
| 720 |
+
cdef FunctionSignature self = FunctionSignature.__new__(
|
| 721 |
+
FunctionSignature)
|
| 722 |
+
self.signature = signature
|
| 723 |
+
return self
|
| 724 |
+
|
| 725 |
+
def return_type(self):
|
| 726 |
+
return pyarrow_wrap_data_type(self.signature.get().ret_type())
|
| 727 |
+
|
| 728 |
+
def param_types(self):
|
| 729 |
+
result = []
|
| 730 |
+
cdef vector[shared_ptr[CDataType]] types = \
|
| 731 |
+
self.signature.get().param_types()
|
| 732 |
+
for t in types:
|
| 733 |
+
result.append(pyarrow_wrap_data_type(t))
|
| 734 |
+
return result
|
| 735 |
+
|
| 736 |
+
def name(self):
|
| 737 |
+
return self.signature.get().base_name().decode()
|
| 738 |
+
|
| 739 |
+
def __repr__(self):
|
| 740 |
+
signature = self.signature.get().ToString().decode()
|
| 741 |
+
return "FunctionSignature(" + signature + ")"
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def get_registered_function_signatures():
|
| 745 |
+
"""
|
| 746 |
+
Return the function in Gandiva's ExpressionRegistry.
|
| 747 |
+
|
| 748 |
+
Returns
|
| 749 |
+
-------
|
| 750 |
+
registry: a list of registered function signatures
|
| 751 |
+
"""
|
| 752 |
+
results = []
|
| 753 |
+
|
| 754 |
+
cdef vector[shared_ptr[CFunctionSignature]] signatures = \
|
| 755 |
+
GetRegisteredFunctionSignatures()
|
| 756 |
+
|
| 757 |
+
for signature in signatures:
|
| 758 |
+
results.append(FunctionSignature.create(signature))
|
| 759 |
+
|
| 760 |
+
return results
|
vllm/lib/python3.10/site-packages/pyarrow/includes/__init__.pxd
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/pyarrow/includes/common.pxd
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
|
| 20 |
+
from libc.stdint cimport *
|
| 21 |
+
from libcpp cimport bool as c_bool, nullptr
|
| 22 |
+
from libcpp.functional cimport function
|
| 23 |
+
from libcpp.memory cimport shared_ptr, unique_ptr, make_shared
|
| 24 |
+
from libcpp.string cimport string as c_string
|
| 25 |
+
from libcpp.utility cimport pair
|
| 26 |
+
from libcpp.vector cimport vector
|
| 27 |
+
from libcpp.unordered_map cimport unordered_map
|
| 28 |
+
from libcpp.unordered_set cimport unordered_set
|
| 29 |
+
|
| 30 |
+
from cpython cimport PyObject
|
| 31 |
+
from cpython.datetime cimport PyDateTime_DateTime
|
| 32 |
+
cimport cpython
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
cdef extern from * namespace "std" nogil:
|
| 36 |
+
cdef shared_ptr[T] static_pointer_cast[T, U](shared_ptr[U])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
cdef extern from "<optional>" namespace "std" nogil:
|
| 40 |
+
cdef cppclass optional[T]:
|
| 41 |
+
ctypedef T value_type
|
| 42 |
+
optional()
|
| 43 |
+
optional(nullopt_t)
|
| 44 |
+
optional(optional&) except +
|
| 45 |
+
optional(T&) except +
|
| 46 |
+
c_bool has_value()
|
| 47 |
+
T& value()
|
| 48 |
+
T& value_or[U](U& default_value)
|
| 49 |
+
void swap(optional&)
|
| 50 |
+
void reset()
|
| 51 |
+
T& emplace(...)
|
| 52 |
+
T& operator*()
|
| 53 |
+
# T* operator->() # Not Supported
|
| 54 |
+
optional& operator=(optional&)
|
| 55 |
+
optional& operator=[U](U&)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# vendored from the cymove project https://github.com/ozars/cymove
|
| 59 |
+
cdef extern from * namespace "cymove" nogil:
|
| 60 |
+
"""
|
| 61 |
+
#include <type_traits>
|
| 62 |
+
#include <utility>
|
| 63 |
+
namespace cymove {
|
| 64 |
+
template <typename T>
|
| 65 |
+
inline typename std::remove_reference<T>::type&& cymove(T& t) {
|
| 66 |
+
return std::move(t);
|
| 67 |
+
}
|
| 68 |
+
template <typename T>
|
| 69 |
+
inline typename std::remove_reference<T>::type&& cymove(T&& t) {
|
| 70 |
+
return std::move(t);
|
| 71 |
+
}
|
| 72 |
+
} // namespace cymove
|
| 73 |
+
"""
|
| 74 |
+
cdef T move" cymove::cymove"[T](T)
|
| 75 |
+
|
| 76 |
+
cdef extern from * namespace "arrow::py" nogil:
|
| 77 |
+
"""
|
| 78 |
+
#include <memory>
|
| 79 |
+
#include <utility>
|
| 80 |
+
|
| 81 |
+
namespace arrow {
|
| 82 |
+
namespace py {
|
| 83 |
+
template <typename T>
|
| 84 |
+
std::shared_ptr<T> to_shared(std::unique_ptr<T>& t) {
|
| 85 |
+
return std::move(t);
|
| 86 |
+
}
|
| 87 |
+
template <typename T>
|
| 88 |
+
std::shared_ptr<T> to_shared(std::unique_ptr<T>&& t) {
|
| 89 |
+
return std::move(t);
|
| 90 |
+
}
|
| 91 |
+
} // namespace py
|
| 92 |
+
} // namespace arrow
|
| 93 |
+
"""
|
| 94 |
+
cdef shared_ptr[T] to_shared" arrow::py::to_shared"[T](unique_ptr[T])
|
| 95 |
+
|
| 96 |
+
cdef extern from "arrow/python/platform.h":
|
| 97 |
+
pass
|
| 98 |
+
|
| 99 |
+
cdef extern from "<Python.h>":
|
| 100 |
+
void Py_XDECREF(PyObject* o)
|
| 101 |
+
Py_ssize_t Py_REFCNT(PyObject* o)
|
| 102 |
+
|
| 103 |
+
cdef extern from "numpy/halffloat.h":
|
| 104 |
+
ctypedef uint16_t npy_half
|
| 105 |
+
|
| 106 |
+
cdef extern from "arrow/api.h" namespace "arrow" nogil:
|
| 107 |
+
# We can later add more of the common status factory methods as needed
|
| 108 |
+
cdef CStatus CStatus_OK "arrow::Status::OK"()
|
| 109 |
+
|
| 110 |
+
cdef CStatus CStatus_Invalid "arrow::Status::Invalid"()
|
| 111 |
+
cdef CStatus CStatus_NotImplemented \
|
| 112 |
+
"arrow::Status::NotImplemented"(const c_string& msg)
|
| 113 |
+
cdef CStatus CStatus_UnknownError \
|
| 114 |
+
"arrow::Status::UnknownError"(const c_string& msg)
|
| 115 |
+
|
| 116 |
+
cdef cppclass CStatus "arrow::Status":
|
| 117 |
+
CStatus()
|
| 118 |
+
|
| 119 |
+
c_string ToString()
|
| 120 |
+
c_string message()
|
| 121 |
+
shared_ptr[CStatusDetail] detail()
|
| 122 |
+
|
| 123 |
+
c_bool ok()
|
| 124 |
+
c_bool IsIOError()
|
| 125 |
+
c_bool IsOutOfMemory()
|
| 126 |
+
c_bool IsInvalid()
|
| 127 |
+
c_bool IsKeyError()
|
| 128 |
+
c_bool IsNotImplemented()
|
| 129 |
+
c_bool IsTypeError()
|
| 130 |
+
c_bool IsCapacityError()
|
| 131 |
+
c_bool IsIndexError()
|
| 132 |
+
c_bool IsSerializationError()
|
| 133 |
+
c_bool IsCancelled()
|
| 134 |
+
|
| 135 |
+
void Warn()
|
| 136 |
+
|
| 137 |
+
cdef cppclass CStatusDetail "arrow::StatusDetail":
|
| 138 |
+
c_string ToString()
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
cdef extern from "arrow/result.h" namespace "arrow" nogil:
|
| 142 |
+
cdef cppclass CResult "arrow::Result"[T]:
|
| 143 |
+
CResult()
|
| 144 |
+
CResult(CStatus)
|
| 145 |
+
CResult(T)
|
| 146 |
+
c_bool ok()
|
| 147 |
+
CStatus status()
|
| 148 |
+
CStatus Value(T*)
|
| 149 |
+
T operator*()
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
cdef extern from "arrow/util/future.h" namespace "arrow" nogil:
|
| 153 |
+
cdef cppclass CFuture "arrow::Future"[T]:
|
| 154 |
+
CFuture()
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
cdef extern from "arrow/python/async.h" namespace "arrow::py" nogil:
|
| 158 |
+
# BindFuture's third argument is really a C++ callable with
|
| 159 |
+
# the signature `object(T*)`, but Cython does not allow declaring that.
|
| 160 |
+
# We use an ellipsis as a workaround.
|
| 161 |
+
# Another possibility is to type-erase the argument by making it
|
| 162 |
+
# `object(void*)`, but it would lose compile-time C++ type safety.
|
| 163 |
+
void BindFuture[T](CFuture[T], object cb, ...)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
cdef extern from "arrow/python/common.h" namespace "arrow::py" nogil:
|
| 167 |
+
T GetResultValue[T](CResult[T]) except *
|
| 168 |
+
cdef function[F] BindFunction[F](void* unbound, object bound, ...)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
cdef inline object PyObject_to_object(PyObject* o):
|
| 172 |
+
# Cast to "object" increments reference count
|
| 173 |
+
cdef object result = <object> o
|
| 174 |
+
cpython.Py_DECREF(result)
|
| 175 |
+
return result
|
vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow.pxd
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_cuda.pxd
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
|
| 20 |
+
from pyarrow.includes.libarrow cimport *
|
| 21 |
+
|
| 22 |
+
cdef extern from "arrow/gpu/cuda_api.h" namespace "arrow::cuda" nogil:
|
| 23 |
+
|
| 24 |
+
cdef cppclass CCudaDeviceManager" arrow::cuda::CudaDeviceManager":
|
| 25 |
+
@staticmethod
|
| 26 |
+
CResult[CCudaDeviceManager*] Instance()
|
| 27 |
+
CResult[shared_ptr[CCudaContext]] GetContext(int gpu_number)
|
| 28 |
+
CResult[shared_ptr[CCudaContext]] GetSharedContext(int gpu_number,
|
| 29 |
+
void* handle)
|
| 30 |
+
CStatus AllocateHost(int device_number, int64_t nbytes,
|
| 31 |
+
shared_ptr[CCudaHostBuffer]* buffer)
|
| 32 |
+
int num_devices() const
|
| 33 |
+
|
| 34 |
+
cdef cppclass CCudaContext" arrow::cuda::CudaContext":
|
| 35 |
+
CResult[shared_ptr[CCudaBuffer]] Allocate(int64_t nbytes)
|
| 36 |
+
CResult[shared_ptr[CCudaBuffer]] View(uint8_t* data, int64_t nbytes)
|
| 37 |
+
CResult[shared_ptr[CCudaBuffer]] OpenIpcBuffer(
|
| 38 |
+
const CCudaIpcMemHandle& ipc_handle)
|
| 39 |
+
CStatus Synchronize()
|
| 40 |
+
int64_t bytes_allocated() const
|
| 41 |
+
const void* handle() const
|
| 42 |
+
int device_number() const
|
| 43 |
+
CResult[uintptr_t] GetDeviceAddress(uintptr_t addr)
|
| 44 |
+
shared_ptr[CDevice] device() const
|
| 45 |
+
shared_ptr[CMemoryManager] memory_manager() const
|
| 46 |
+
|
| 47 |
+
cdef cppclass CCudaIpcMemHandle" arrow::cuda::CudaIpcMemHandle":
|
| 48 |
+
@staticmethod
|
| 49 |
+
CResult[shared_ptr[CCudaIpcMemHandle]] FromBuffer(
|
| 50 |
+
const void* opaque_handle)
|
| 51 |
+
CResult[shared_ptr[CBuffer]] Serialize(CMemoryPool* pool) const
|
| 52 |
+
|
| 53 |
+
cdef cppclass CCudaBuffer" arrow::cuda::CudaBuffer"(CBuffer):
|
| 54 |
+
CCudaBuffer(uint8_t* data, int64_t size,
|
| 55 |
+
const shared_ptr[CCudaContext]& context,
|
| 56 |
+
c_bool own_data=false, c_bool is_ipc=false)
|
| 57 |
+
CCudaBuffer(const shared_ptr[CCudaBuffer]& parent,
|
| 58 |
+
const int64_t offset, const int64_t size)
|
| 59 |
+
|
| 60 |
+
@staticmethod
|
| 61 |
+
CResult[shared_ptr[CCudaBuffer]] FromBuffer(shared_ptr[CBuffer] buf)
|
| 62 |
+
|
| 63 |
+
CStatus CopyToHost(const int64_t position, const int64_t nbytes,
|
| 64 |
+
void* out) const
|
| 65 |
+
CStatus CopyFromHost(const int64_t position, const void* data,
|
| 66 |
+
int64_t nbytes)
|
| 67 |
+
CStatus CopyFromDevice(const int64_t position, const void* data,
|
| 68 |
+
int64_t nbytes)
|
| 69 |
+
CStatus CopyFromAnotherDevice(const shared_ptr[CCudaContext]& src_ctx,
|
| 70 |
+
const int64_t position, const void* data,
|
| 71 |
+
int64_t nbytes)
|
| 72 |
+
CResult[shared_ptr[CCudaIpcMemHandle]] ExportForIpc()
|
| 73 |
+
shared_ptr[CCudaContext] context() const
|
| 74 |
+
|
| 75 |
+
cdef cppclass \
|
| 76 |
+
CCudaHostBuffer" arrow::cuda::CudaHostBuffer"(CMutableBuffer):
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
cdef cppclass \
|
| 80 |
+
CCudaBufferReader" arrow::cuda::CudaBufferReader"(CBufferReader):
|
| 81 |
+
CCudaBufferReader(const shared_ptr[CBuffer]& buffer)
|
| 82 |
+
CResult[int64_t] Read(int64_t nbytes, void* buffer)
|
| 83 |
+
CResult[shared_ptr[CBuffer]] Read(int64_t nbytes)
|
| 84 |
+
|
| 85 |
+
cdef cppclass \
|
| 86 |
+
CCudaBufferWriter" arrow::cuda::CudaBufferWriter"(WritableFile):
|
| 87 |
+
CCudaBufferWriter(const shared_ptr[CCudaBuffer]& buffer)
|
| 88 |
+
CStatus Close()
|
| 89 |
+
CStatus Write(const void* data, int64_t nbytes)
|
| 90 |
+
CStatus WriteAt(int64_t position, const void* data, int64_t nbytes)
|
| 91 |
+
CStatus SetBufferSize(const int64_t buffer_size)
|
| 92 |
+
int64_t buffer_size()
|
| 93 |
+
int64_t num_bytes_buffered() const
|
| 94 |
+
|
| 95 |
+
CResult[shared_ptr[CCudaHostBuffer]] AllocateCudaHostBuffer(
|
| 96 |
+
int device_number, const int64_t size)
|
| 97 |
+
|
| 98 |
+
# Cuda prefix is added to avoid picking up arrow::cuda functions
|
| 99 |
+
# from arrow namespace.
|
| 100 |
+
CResult[shared_ptr[CCudaBuffer]] \
|
| 101 |
+
CudaSerializeRecordBatch" arrow::cuda::SerializeRecordBatch"\
|
| 102 |
+
(const CRecordBatch& batch,
|
| 103 |
+
CCudaContext* ctx)
|
| 104 |
+
CResult[shared_ptr[CRecordBatch]] \
|
| 105 |
+
CudaReadRecordBatch" arrow::cuda::ReadRecordBatch"\
|
| 106 |
+
(const shared_ptr[CSchema]& schema,
|
| 107 |
+
CDictionaryMemo* dictionary_memo,
|
| 108 |
+
const shared_ptr[CCudaBuffer]& buffer,
|
| 109 |
+
CMemoryPool* pool)
|
vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_dataset.pxd
ADDED
|
@@ -0,0 +1,418 @@
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
|
| 20 |
+
from libcpp.unordered_map cimport unordered_map
|
| 21 |
+
from libcpp cimport bool as c_bool
|
| 22 |
+
|
| 23 |
+
from pyarrow.includes.common cimport *
|
| 24 |
+
from pyarrow.includes.libarrow cimport *
|
| 25 |
+
from pyarrow.includes.libarrow_acero cimport *
|
| 26 |
+
from pyarrow.includes.libarrow_fs cimport *
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
cdef extern from "arrow/dataset/plan.h" namespace "arrow::dataset::internal" nogil:
|
| 30 |
+
|
| 31 |
+
cdef void Initialize()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
ctypedef CStatus cb_writer_finish_internal(CFileWriter*)
|
| 35 |
+
ctypedef void cb_writer_finish(dict, CFileWriter*)
|
| 36 |
+
|
| 37 |
+
cdef extern from "arrow/dataset/api.h" namespace "arrow::dataset" nogil:
|
| 38 |
+
|
| 39 |
+
cdef enum ExistingDataBehavior" arrow::dataset::ExistingDataBehavior":
|
| 40 |
+
ExistingDataBehavior_DELETE_MATCHING" \
|
| 41 |
+
arrow::dataset::ExistingDataBehavior::kDeleteMatchingPartitions"
|
| 42 |
+
ExistingDataBehavior_OVERWRITE_OR_IGNORE" \
|
| 43 |
+
arrow::dataset::ExistingDataBehavior::kOverwriteOrIgnore"
|
| 44 |
+
ExistingDataBehavior_ERROR" \
|
| 45 |
+
arrow::dataset::ExistingDataBehavior::kError"
|
| 46 |
+
|
| 47 |
+
cdef cppclass CScanOptions "arrow::dataset::ScanOptions":
|
| 48 |
+
shared_ptr[CSchema] dataset_schema
|
| 49 |
+
shared_ptr[CSchema] projected_schema
|
| 50 |
+
c_bool use_threads
|
| 51 |
+
CExpression filter
|
| 52 |
+
|
| 53 |
+
cdef cppclass CScanNodeOptions "arrow::dataset::ScanNodeOptions"(CExecNodeOptions):
|
| 54 |
+
CScanNodeOptions(shared_ptr[CDataset] dataset, shared_ptr[CScanOptions] scan_options)
|
| 55 |
+
|
| 56 |
+
shared_ptr[CScanOptions] scan_options
|
| 57 |
+
|
| 58 |
+
cdef cppclass CFragmentScanOptions "arrow::dataset::FragmentScanOptions":
|
| 59 |
+
c_string type_name() const
|
| 60 |
+
|
| 61 |
+
ctypedef CIterator[shared_ptr[CScanTask]] CScanTaskIterator \
|
| 62 |
+
"arrow::dataset::ScanTaskIterator"
|
| 63 |
+
|
| 64 |
+
cdef cppclass CScanTask" arrow::dataset::ScanTask":
|
| 65 |
+
CResult[CRecordBatchIterator] Execute()
|
| 66 |
+
|
| 67 |
+
cdef cppclass CFragment "arrow::dataset::Fragment":
|
| 68 |
+
CResult[shared_ptr[CSchema]] ReadPhysicalSchema()
|
| 69 |
+
CResult[CScanTaskIterator] Scan(shared_ptr[CScanOptions] options)
|
| 70 |
+
c_bool splittable() const
|
| 71 |
+
c_string type_name() const
|
| 72 |
+
const CExpression& partition_expression() const
|
| 73 |
+
|
| 74 |
+
ctypedef vector[shared_ptr[CFragment]] CFragmentVector \
|
| 75 |
+
"arrow::dataset::FragmentVector"
|
| 76 |
+
|
| 77 |
+
ctypedef CIterator[shared_ptr[CFragment]] CFragmentIterator \
|
| 78 |
+
"arrow::dataset::FragmentIterator"
|
| 79 |
+
|
| 80 |
+
cdef cppclass CInMemoryFragment "arrow::dataset::InMemoryFragment"(
|
| 81 |
+
CFragment):
|
| 82 |
+
CInMemoryFragment(vector[shared_ptr[CRecordBatch]] record_batches,
|
| 83 |
+
CExpression partition_expression)
|
| 84 |
+
|
| 85 |
+
cdef cppclass CTaggedRecordBatch "arrow::dataset::TaggedRecordBatch":
|
| 86 |
+
shared_ptr[CRecordBatch] record_batch
|
| 87 |
+
shared_ptr[CFragment] fragment
|
| 88 |
+
|
| 89 |
+
ctypedef CIterator[CTaggedRecordBatch] CTaggedRecordBatchIterator \
|
| 90 |
+
"arrow::dataset::TaggedRecordBatchIterator"
|
| 91 |
+
|
| 92 |
+
cdef cppclass CScanner "arrow::dataset::Scanner":
|
| 93 |
+
CScanner(shared_ptr[CDataset], shared_ptr[CScanOptions])
|
| 94 |
+
CScanner(shared_ptr[CFragment], shared_ptr[CScanOptions])
|
| 95 |
+
CResult[CScanTaskIterator] Scan()
|
| 96 |
+
CResult[CTaggedRecordBatchIterator] ScanBatches()
|
| 97 |
+
CResult[shared_ptr[CTable]] ToTable()
|
| 98 |
+
CResult[shared_ptr[CTable]] TakeRows(const CArray& indices)
|
| 99 |
+
CResult[shared_ptr[CTable]] Head(int64_t num_rows)
|
| 100 |
+
CResult[int64_t] CountRows()
|
| 101 |
+
CResult[CFragmentIterator] GetFragments()
|
| 102 |
+
CResult[shared_ptr[CRecordBatchReader]] ToRecordBatchReader()
|
| 103 |
+
const shared_ptr[CScanOptions]& options()
|
| 104 |
+
|
| 105 |
+
cdef cppclass CScannerBuilder "arrow::dataset::ScannerBuilder":
|
| 106 |
+
CScannerBuilder(shared_ptr[CDataset],
|
| 107 |
+
shared_ptr[CScanOptions] scan_options)
|
| 108 |
+
CScannerBuilder(shared_ptr[CSchema], shared_ptr[CFragment],
|
| 109 |
+
shared_ptr[CScanOptions] scan_options)
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
shared_ptr[CScannerBuilder] FromRecordBatchReader(
|
| 113 |
+
shared_ptr[CRecordBatchReader] reader)
|
| 114 |
+
CStatus ProjectColumns "Project"(const vector[c_string]& columns)
|
| 115 |
+
CStatus Project(vector[CExpression]& exprs, vector[c_string]& columns)
|
| 116 |
+
CStatus Filter(CExpression filter)
|
| 117 |
+
CStatus UseThreads(c_bool use_threads)
|
| 118 |
+
CStatus Pool(CMemoryPool* pool)
|
| 119 |
+
CStatus BatchSize(int64_t batch_size)
|
| 120 |
+
CStatus BatchReadahead(int32_t batch_readahead)
|
| 121 |
+
CStatus FragmentReadahead(int32_t fragment_readahead)
|
| 122 |
+
CStatus FragmentScanOptions(
|
| 123 |
+
shared_ptr[CFragmentScanOptions] fragment_scan_options)
|
| 124 |
+
CResult[shared_ptr[CScanOptions]] GetScanOptions()
|
| 125 |
+
CResult[shared_ptr[CScanner]] Finish()
|
| 126 |
+
shared_ptr[CSchema] schema() const
|
| 127 |
+
|
| 128 |
+
ctypedef vector[shared_ptr[CDataset]] CDatasetVector \
|
| 129 |
+
"arrow::dataset::DatasetVector"
|
| 130 |
+
|
| 131 |
+
cdef cppclass CDataset "arrow::dataset::Dataset":
|
| 132 |
+
const shared_ptr[CSchema] & schema()
|
| 133 |
+
CResult[CFragmentIterator] GetFragments()
|
| 134 |
+
CResult[CFragmentIterator] GetFragments(CExpression predicate)
|
| 135 |
+
const CExpression & partition_expression()
|
| 136 |
+
c_string type_name()
|
| 137 |
+
|
| 138 |
+
CResult[shared_ptr[CDataset]] ReplaceSchema(shared_ptr[CSchema])
|
| 139 |
+
|
| 140 |
+
CResult[shared_ptr[CScannerBuilder]] NewScan()
|
| 141 |
+
|
| 142 |
+
cdef cppclass CInMemoryDataset "arrow::dataset::InMemoryDataset"(
|
| 143 |
+
CDataset):
|
| 144 |
+
CInMemoryDataset(shared_ptr[CRecordBatchReader])
|
| 145 |
+
CInMemoryDataset(shared_ptr[CTable])
|
| 146 |
+
|
| 147 |
+
cdef cppclass CUnionDataset "arrow::dataset::UnionDataset"(
|
| 148 |
+
CDataset):
|
| 149 |
+
@staticmethod
|
| 150 |
+
CResult[shared_ptr[CUnionDataset]] Make(shared_ptr[CSchema] schema,
|
| 151 |
+
CDatasetVector children)
|
| 152 |
+
|
| 153 |
+
const CDatasetVector& children() const
|
| 154 |
+
|
| 155 |
+
cdef cppclass CInspectOptions "arrow::dataset::InspectOptions":
|
| 156 |
+
int fragments
|
| 157 |
+
|
| 158 |
+
cdef cppclass CFinishOptions "arrow::dataset::FinishOptions":
|
| 159 |
+
shared_ptr[CSchema] schema
|
| 160 |
+
CInspectOptions inspect_options
|
| 161 |
+
c_bool validate_fragments
|
| 162 |
+
|
| 163 |
+
cdef cppclass CDatasetFactory "arrow::dataset::DatasetFactory":
|
| 164 |
+
CResult[vector[shared_ptr[CSchema]]] InspectSchemas(CInspectOptions)
|
| 165 |
+
CResult[shared_ptr[CSchema]] Inspect(CInspectOptions)
|
| 166 |
+
CResult[shared_ptr[CDataset]] FinishWithSchema "Finish"(
|
| 167 |
+
const shared_ptr[CSchema]& schema)
|
| 168 |
+
CResult[shared_ptr[CDataset]] Finish()
|
| 169 |
+
const CExpression& root_partition()
|
| 170 |
+
CStatus SetRootPartition(CExpression partition)
|
| 171 |
+
|
| 172 |
+
cdef cppclass CUnionDatasetFactory "arrow::dataset::UnionDatasetFactory":
|
| 173 |
+
@staticmethod
|
| 174 |
+
CResult[shared_ptr[CDatasetFactory]] Make(
|
| 175 |
+
vector[shared_ptr[CDatasetFactory]] factories)
|
| 176 |
+
|
| 177 |
+
cdef cppclass CFileSource "arrow::dataset::FileSource":
|
| 178 |
+
const c_string& path() const
|
| 179 |
+
const shared_ptr[CFileSystem]& filesystem() const
|
| 180 |
+
const shared_ptr[CBuffer]& buffer() const
|
| 181 |
+
const int64_t size() const
|
| 182 |
+
# HACK: Cython can't handle all the overloads so don't declare them.
|
| 183 |
+
# This means invalid construction of CFileSource won't be caught in
|
| 184 |
+
# the C++ generation phase (though it will still be caught when
|
| 185 |
+
# the generated C++ is compiled).
|
| 186 |
+
CFileSource(...)
|
| 187 |
+
|
| 188 |
+
cdef cppclass CFileWriteOptions \
|
| 189 |
+
"arrow::dataset::FileWriteOptions":
|
| 190 |
+
const shared_ptr[CFileFormat]& format() const
|
| 191 |
+
c_string type_name() const
|
| 192 |
+
|
| 193 |
+
cdef cppclass CFileWriter \
|
| 194 |
+
"arrow::dataset::FileWriter":
|
| 195 |
+
const shared_ptr[CFileFormat]& format() const
|
| 196 |
+
const shared_ptr[CSchema]& schema() const
|
| 197 |
+
const shared_ptr[CFileWriteOptions]& options() const
|
| 198 |
+
const CFileLocator& destination() const
|
| 199 |
+
CResult[int64_t] GetBytesWritten()
|
| 200 |
+
|
| 201 |
+
cdef cppclass CFileFormat "arrow::dataset::FileFormat":
|
| 202 |
+
shared_ptr[CFragmentScanOptions] default_fragment_scan_options
|
| 203 |
+
c_string type_name() const
|
| 204 |
+
CResult[shared_ptr[CSchema]] Inspect(const CFileSource&) const
|
| 205 |
+
CResult[shared_ptr[CFileFragment]] MakeFragment(
|
| 206 |
+
CFileSource source,
|
| 207 |
+
CExpression partition_expression,
|
| 208 |
+
shared_ptr[CSchema] physical_schema)
|
| 209 |
+
shared_ptr[CFileWriteOptions] DefaultWriteOptions()
|
| 210 |
+
|
| 211 |
+
cdef cppclass CFileFragment "arrow::dataset::FileFragment"(
|
| 212 |
+
CFragment):
|
| 213 |
+
const CFileSource& source() const
|
| 214 |
+
const shared_ptr[CFileFormat]& format() const
|
| 215 |
+
|
| 216 |
+
cdef cppclass CFileSystemDatasetWriteOptions \
|
| 217 |
+
"arrow::dataset::FileSystemDatasetWriteOptions":
|
| 218 |
+
shared_ptr[CFileWriteOptions] file_write_options
|
| 219 |
+
shared_ptr[CFileSystem] filesystem
|
| 220 |
+
c_string base_dir
|
| 221 |
+
shared_ptr[CPartitioning] partitioning
|
| 222 |
+
int max_partitions
|
| 223 |
+
c_string basename_template
|
| 224 |
+
function[cb_writer_finish_internal] writer_pre_finish
|
| 225 |
+
function[cb_writer_finish_internal] writer_post_finish
|
| 226 |
+
ExistingDataBehavior existing_data_behavior
|
| 227 |
+
c_bool create_dir
|
| 228 |
+
uint32_t max_open_files
|
| 229 |
+
uint64_t max_rows_per_file
|
| 230 |
+
uint64_t min_rows_per_group
|
| 231 |
+
uint64_t max_rows_per_group
|
| 232 |
+
|
| 233 |
+
cdef cppclass CFileSystemDataset \
|
| 234 |
+
"arrow::dataset::FileSystemDataset"(CDataset):
|
| 235 |
+
@staticmethod
|
| 236 |
+
CResult[shared_ptr[CDataset]] Make(
|
| 237 |
+
shared_ptr[CSchema] schema,
|
| 238 |
+
CExpression source_partition,
|
| 239 |
+
shared_ptr[CFileFormat] format,
|
| 240 |
+
shared_ptr[CFileSystem] filesystem,
|
| 241 |
+
vector[shared_ptr[CFileFragment]] fragments)
|
| 242 |
+
|
| 243 |
+
@staticmethod
|
| 244 |
+
CStatus Write(
|
| 245 |
+
const CFileSystemDatasetWriteOptions& write_options,
|
| 246 |
+
shared_ptr[CScanner] scanner)
|
| 247 |
+
|
| 248 |
+
c_string type()
|
| 249 |
+
vector[c_string] files()
|
| 250 |
+
const shared_ptr[CFileFormat]& format() const
|
| 251 |
+
const shared_ptr[CFileSystem]& filesystem() const
|
| 252 |
+
const shared_ptr[CPartitioning]& partitioning() const
|
| 253 |
+
|
| 254 |
+
cdef cppclass CIpcFileWriteOptions \
|
| 255 |
+
"arrow::dataset::IpcFileWriteOptions"(CFileWriteOptions):
|
| 256 |
+
shared_ptr[CIpcWriteOptions] options
|
| 257 |
+
|
| 258 |
+
cdef cppclass CIpcFileFormat "arrow::dataset::IpcFileFormat"(
|
| 259 |
+
CFileFormat):
|
| 260 |
+
pass
|
| 261 |
+
|
| 262 |
+
cdef cppclass COrcFileFormat "arrow::dataset::OrcFileFormat"(
|
| 263 |
+
CFileFormat):
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
cdef cppclass CCsvFileWriteOptions \
|
| 267 |
+
"arrow::dataset::CsvFileWriteOptions"(CFileWriteOptions):
|
| 268 |
+
shared_ptr[CCSVWriteOptions] write_options
|
| 269 |
+
CMemoryPool* pool
|
| 270 |
+
|
| 271 |
+
cdef cppclass CCsvFileFormat "arrow::dataset::CsvFileFormat"(
|
| 272 |
+
CFileFormat):
|
| 273 |
+
CCSVParseOptions parse_options
|
| 274 |
+
|
| 275 |
+
cdef cppclass CCsvFragmentScanOptions \
|
| 276 |
+
"arrow::dataset::CsvFragmentScanOptions"(CFragmentScanOptions):
|
| 277 |
+
CCSVConvertOptions convert_options
|
| 278 |
+
CCSVReadOptions read_options
|
| 279 |
+
function[StreamWrapFunc] stream_transform_func
|
| 280 |
+
|
| 281 |
+
cdef cppclass CJsonFileFormat "arrow::dataset::JsonFileFormat"(CFileFormat):
|
| 282 |
+
pass
|
| 283 |
+
|
| 284 |
+
cdef cppclass CJsonFragmentScanOptions "arrow::dataset::JsonFragmentScanOptions"(CFragmentScanOptions):
|
| 285 |
+
CJSONParseOptions parse_options
|
| 286 |
+
CJSONReadOptions read_options
|
| 287 |
+
|
| 288 |
+
cdef struct CPartitionPathFormat "arrow::dataset::PartitionPathFormat":
|
| 289 |
+
c_string directory
|
| 290 |
+
c_string filename
|
| 291 |
+
|
| 292 |
+
cdef cppclass CPartitioning "arrow::dataset::Partitioning":
|
| 293 |
+
c_string type_name() const
|
| 294 |
+
CResult[CExpression] Parse(const c_string & path) const
|
| 295 |
+
CResult[CPartitionPathFormat] Format(const CExpression & expr) const
|
| 296 |
+
const shared_ptr[CSchema] & schema()
|
| 297 |
+
c_bool Equals(const CPartitioning& other) const
|
| 298 |
+
|
| 299 |
+
cdef cppclass CSegmentEncoding" arrow::dataset::SegmentEncoding":
|
| 300 |
+
bint operator==(CSegmentEncoding)
|
| 301 |
+
|
| 302 |
+
CSegmentEncoding CSegmentEncoding_None\
|
| 303 |
+
" arrow::dataset::SegmentEncoding::None"
|
| 304 |
+
CSegmentEncoding CSegmentEncoding_Uri\
|
| 305 |
+
" arrow::dataset::SegmentEncoding::Uri"
|
| 306 |
+
|
| 307 |
+
cdef cppclass CKeyValuePartitioningOptions \
|
| 308 |
+
"arrow::dataset::KeyValuePartitioningOptions":
|
| 309 |
+
CSegmentEncoding segment_encoding
|
| 310 |
+
|
| 311 |
+
cdef cppclass CHivePartitioningOptions \
|
| 312 |
+
"arrow::dataset::HivePartitioningOptions":
|
| 313 |
+
CSegmentEncoding segment_encoding
|
| 314 |
+
c_string null_fallback
|
| 315 |
+
|
| 316 |
+
cdef cppclass CPartitioningFactoryOptions \
|
| 317 |
+
"arrow::dataset::PartitioningFactoryOptions":
|
| 318 |
+
c_bool infer_dictionary
|
| 319 |
+
shared_ptr[CSchema] schema
|
| 320 |
+
CSegmentEncoding segment_encoding
|
| 321 |
+
|
| 322 |
+
cdef cppclass CHivePartitioningFactoryOptions \
|
| 323 |
+
"arrow::dataset::HivePartitioningFactoryOptions":
|
| 324 |
+
c_bool infer_dictionary
|
| 325 |
+
c_string null_fallback
|
| 326 |
+
shared_ptr[CSchema] schema
|
| 327 |
+
CSegmentEncoding segment_encoding
|
| 328 |
+
|
| 329 |
+
cdef cppclass CPartitioningFactory "arrow::dataset::PartitioningFactory":
|
| 330 |
+
c_string type_name() const
|
| 331 |
+
|
| 332 |
+
cdef cppclass CKeyValuePartitioning \
|
| 333 |
+
"arrow::dataset::KeyValuePartitioning"(CPartitioning):
|
| 334 |
+
CKeyValuePartitioning(shared_ptr[CSchema] schema,
|
| 335 |
+
vector[shared_ptr[CArray]] dictionaries,
|
| 336 |
+
CKeyValuePartitioningOptions options)
|
| 337 |
+
|
| 338 |
+
vector[shared_ptr[CArray]] dictionaries() const
|
| 339 |
+
CSegmentEncoding segment_encoding()
|
| 340 |
+
|
| 341 |
+
cdef cppclass CDirectoryPartitioning \
|
| 342 |
+
"arrow::dataset::DirectoryPartitioning"(CPartitioning):
|
| 343 |
+
CDirectoryPartitioning(shared_ptr[CSchema] schema,
|
| 344 |
+
vector[shared_ptr[CArray]] dictionaries)
|
| 345 |
+
|
| 346 |
+
@staticmethod
|
| 347 |
+
shared_ptr[CPartitioningFactory] MakeFactory(
|
| 348 |
+
vector[c_string] field_names, CPartitioningFactoryOptions)
|
| 349 |
+
|
| 350 |
+
vector[shared_ptr[CArray]] dictionaries() const
|
| 351 |
+
|
| 352 |
+
cdef cppclass CHivePartitioning \
|
| 353 |
+
"arrow::dataset::HivePartitioning"(CPartitioning):
|
| 354 |
+
CHivePartitioning(shared_ptr[CSchema] schema,
|
| 355 |
+
vector[shared_ptr[CArray]] dictionaries,
|
| 356 |
+
CHivePartitioningOptions options)
|
| 357 |
+
|
| 358 |
+
@staticmethod
|
| 359 |
+
shared_ptr[CPartitioningFactory] MakeFactory(
|
| 360 |
+
CHivePartitioningFactoryOptions)
|
| 361 |
+
|
| 362 |
+
vector[shared_ptr[CArray]] dictionaries() const
|
| 363 |
+
c_string null_fallback() const
|
| 364 |
+
|
| 365 |
+
cdef cppclass CFilenamePartitioning \
|
| 366 |
+
"arrow::dataset::FilenamePartitioning"(CPartitioning):
|
| 367 |
+
CFilenamePartitioning(shared_ptr[CSchema] schema,
|
| 368 |
+
vector[shared_ptr[CArray]] dictionaries)
|
| 369 |
+
|
| 370 |
+
@staticmethod
|
| 371 |
+
shared_ptr[CPartitioningFactory] MakeFactory(
|
| 372 |
+
vector[c_string] field_names, CPartitioningFactoryOptions)
|
| 373 |
+
|
| 374 |
+
vector[shared_ptr[CArray]] dictionaries() const
|
| 375 |
+
|
| 376 |
+
cdef cppclass CPartitioningOrFactory \
|
| 377 |
+
"arrow::dataset::PartitioningOrFactory":
|
| 378 |
+
CPartitioningOrFactory(shared_ptr[CPartitioning])
|
| 379 |
+
CPartitioningOrFactory(shared_ptr[CPartitioningFactory])
|
| 380 |
+
CPartitioningOrFactory & operator = (shared_ptr[CPartitioning])
|
| 381 |
+
CPartitioningOrFactory & operator = (
|
| 382 |
+
shared_ptr[CPartitioningFactory])
|
| 383 |
+
shared_ptr[CPartitioning] partitioning() const
|
| 384 |
+
shared_ptr[CPartitioningFactory] factory() const
|
| 385 |
+
|
| 386 |
+
cdef cppclass CFileSystemFactoryOptions \
|
| 387 |
+
"arrow::dataset::FileSystemFactoryOptions":
|
| 388 |
+
CPartitioningOrFactory partitioning
|
| 389 |
+
c_string partition_base_dir
|
| 390 |
+
c_bool exclude_invalid_files
|
| 391 |
+
vector[c_string] selector_ignore_prefixes
|
| 392 |
+
|
| 393 |
+
cdef cppclass CFileSystemDatasetFactory \
|
| 394 |
+
"arrow::dataset::FileSystemDatasetFactory"(
|
| 395 |
+
CDatasetFactory):
|
| 396 |
+
@staticmethod
|
| 397 |
+
CResult[shared_ptr[CDatasetFactory]] MakeFromPaths "Make"(
|
| 398 |
+
shared_ptr[CFileSystem] filesystem,
|
| 399 |
+
vector[c_string] paths,
|
| 400 |
+
shared_ptr[CFileFormat] format,
|
| 401 |
+
CFileSystemFactoryOptions options
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
@staticmethod
|
| 405 |
+
CResult[shared_ptr[CDatasetFactory]] MakeFromSelector "Make"(
|
| 406 |
+
shared_ptr[CFileSystem] filesystem,
|
| 407 |
+
CFileSelector,
|
| 408 |
+
shared_ptr[CFileFormat] format,
|
| 409 |
+
CFileSystemFactoryOptions options
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
@staticmethod
|
| 413 |
+
CResult[shared_ptr[CDatasetFactory]] MakeFromFileInfos "Make"(
|
| 414 |
+
shared_ptr[CFileSystem] filesystem,
|
| 415 |
+
vector[CFileInfo] files,
|
| 416 |
+
shared_ptr[CFileFormat] format,
|
| 417 |
+
CFileSystemFactoryOptions options
|
| 418 |
+
)
|
vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_dataset_parquet.pxd
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
|
| 20 |
+
from pyarrow.includes.libarrow_dataset cimport *
|
| 21 |
+
from pyarrow.includes.libparquet_encryption cimport *
|
| 22 |
+
|
| 23 |
+
from pyarrow._parquet cimport *
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
cdef extern from "arrow/dataset/parquet_encryption_config.h" namespace "arrow::dataset" nogil:
|
| 27 |
+
cdef cppclass CParquetEncryptionConfig "arrow::dataset::ParquetEncryptionConfig":
|
| 28 |
+
shared_ptr[CCryptoFactory] crypto_factory
|
| 29 |
+
shared_ptr[CKmsConnectionConfig] kms_connection_config
|
| 30 |
+
shared_ptr[CEncryptionConfiguration] encryption_config
|
| 31 |
+
|
| 32 |
+
cdef cppclass CParquetDecryptionConfig "arrow::dataset::ParquetDecryptionConfig":
|
| 33 |
+
shared_ptr[CCryptoFactory] crypto_factory
|
| 34 |
+
shared_ptr[CKmsConnectionConfig] kms_connection_config
|
| 35 |
+
shared_ptr[CDecryptionConfiguration] decryption_config
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
cdef extern from "arrow/dataset/api.h" namespace "arrow::dataset" nogil:
|
| 39 |
+
|
| 40 |
+
cdef cppclass CParquetFileWriter \
|
| 41 |
+
"arrow::dataset::ParquetFileWriter"(CFileWriter):
|
| 42 |
+
const shared_ptr[FileWriter]& parquet_writer() const
|
| 43 |
+
|
| 44 |
+
cdef cppclass CParquetFileWriteOptions \
|
| 45 |
+
"arrow::dataset::ParquetFileWriteOptions"(CFileWriteOptions):
|
| 46 |
+
shared_ptr[WriterProperties] writer_properties
|
| 47 |
+
shared_ptr[ArrowWriterProperties] arrow_writer_properties
|
| 48 |
+
shared_ptr[CParquetEncryptionConfig] parquet_encryption_config
|
| 49 |
+
|
| 50 |
+
cdef cppclass CParquetFileFragment "arrow::dataset::ParquetFileFragment"(
|
| 51 |
+
CFileFragment):
|
| 52 |
+
const vector[int]& row_groups() const
|
| 53 |
+
shared_ptr[CFileMetaData] metadata() const
|
| 54 |
+
CResult[vector[shared_ptr[CFragment]]] SplitByRowGroup(
|
| 55 |
+
CExpression predicate)
|
| 56 |
+
CResult[shared_ptr[CFragment]] SubsetWithFilter "Subset"(
|
| 57 |
+
CExpression predicate)
|
| 58 |
+
CResult[shared_ptr[CFragment]] SubsetWithIds "Subset"(
|
| 59 |
+
vector[int] row_group_ids)
|
| 60 |
+
CStatus EnsureCompleteMetadata()
|
| 61 |
+
|
| 62 |
+
cdef cppclass CParquetFileFormatReaderOptions \
|
| 63 |
+
"arrow::dataset::ParquetFileFormat::ReaderOptions":
|
| 64 |
+
unordered_set[c_string] dict_columns
|
| 65 |
+
TimeUnit coerce_int96_timestamp_unit
|
| 66 |
+
|
| 67 |
+
cdef cppclass CParquetFileFormat "arrow::dataset::ParquetFileFormat"(
|
| 68 |
+
CFileFormat):
|
| 69 |
+
CParquetFileFormatReaderOptions reader_options
|
| 70 |
+
CResult[shared_ptr[CFileFragment]] MakeFragment(
|
| 71 |
+
CFileSource source,
|
| 72 |
+
CExpression partition_expression,
|
| 73 |
+
shared_ptr[CSchema] physical_schema,
|
| 74 |
+
vector[int] row_groups)
|
| 75 |
+
|
| 76 |
+
cdef cppclass CParquetFragmentScanOptions \
|
| 77 |
+
"arrow::dataset::ParquetFragmentScanOptions"(CFragmentScanOptions):
|
| 78 |
+
shared_ptr[CReaderProperties] reader_properties
|
| 79 |
+
shared_ptr[ArrowReaderProperties] arrow_reader_properties
|
| 80 |
+
shared_ptr[CParquetDecryptionConfig] parquet_decryption_config
|
| 81 |
+
|
| 82 |
+
cdef cppclass CParquetFactoryOptions \
|
| 83 |
+
"arrow::dataset::ParquetFactoryOptions":
|
| 84 |
+
CPartitioningOrFactory partitioning
|
| 85 |
+
c_string partition_base_dir
|
| 86 |
+
c_bool validate_column_chunk_paths
|
| 87 |
+
|
| 88 |
+
cdef cppclass CParquetDatasetFactory \
|
| 89 |
+
"arrow::dataset::ParquetDatasetFactory"(CDatasetFactory):
|
| 90 |
+
@staticmethod
|
| 91 |
+
CResult[shared_ptr[CDatasetFactory]] MakeFromMetaDataPath "Make"(
|
| 92 |
+
const c_string& metadata_path,
|
| 93 |
+
shared_ptr[CFileSystem] filesystem,
|
| 94 |
+
shared_ptr[CParquetFileFormat] format,
|
| 95 |
+
CParquetFactoryOptions options
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
CResult[shared_ptr[CDatasetFactory]] MakeFromMetaDataSource "Make"(
|
| 100 |
+
const CFileSource& metadata_path,
|
| 101 |
+
const c_string& base_path,
|
| 102 |
+
shared_ptr[CFileSystem] filesystem,
|
| 103 |
+
shared_ptr[CParquetFileFormat] format,
|
| 104 |
+
CParquetFactoryOptions options
|
| 105 |
+
)
|
vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_feather.pxd
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
|
| 20 |
+
from pyarrow.includes.libarrow cimport (CCompressionType, CStatus, CTable,
|
| 21 |
+
COutputStream, CResult, shared_ptr,
|
| 22 |
+
vector, CRandomAccessFile, CSchema,
|
| 23 |
+
c_string, CIpcReadOptions)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
cdef extern from "arrow/ipc/api.h" namespace "arrow::ipc" nogil:
|
| 27 |
+
int kFeatherV1Version" arrow::ipc::feather::kFeatherV1Version"
|
| 28 |
+
int kFeatherV2Version" arrow::ipc::feather::kFeatherV2Version"
|
| 29 |
+
|
| 30 |
+
cdef cppclass CFeatherProperties" arrow::ipc::feather::WriteProperties":
|
| 31 |
+
int version
|
| 32 |
+
int chunksize
|
| 33 |
+
CCompressionType compression
|
| 34 |
+
int compression_level
|
| 35 |
+
|
| 36 |
+
CStatus WriteFeather" arrow::ipc::feather::WriteTable" \
|
| 37 |
+
(const CTable& table, COutputStream* out,
|
| 38 |
+
CFeatherProperties properties)
|
| 39 |
+
|
| 40 |
+
cdef cppclass CFeatherReader" arrow::ipc::feather::Reader":
|
| 41 |
+
@staticmethod
|
| 42 |
+
CResult[shared_ptr[CFeatherReader]] Open(
|
| 43 |
+
const shared_ptr[CRandomAccessFile]& file,
|
| 44 |
+
const CIpcReadOptions& options)
|
| 45 |
+
int version()
|
| 46 |
+
shared_ptr[CSchema] schema()
|
| 47 |
+
|
| 48 |
+
CStatus Read(shared_ptr[CTable]* out)
|
| 49 |
+
CStatus Read(const vector[int] indices, shared_ptr[CTable]* out)
|
| 50 |
+
CStatus Read(const vector[c_string] names, shared_ptr[CTable]* out)
|
vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_flight.pxd
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
|
| 20 |
+
from pyarrow.includes.common cimport *
|
| 21 |
+
from pyarrow.includes.libarrow cimport *
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
cdef extern from "arrow/flight/api.h" namespace "arrow" nogil:
|
| 25 |
+
cdef char* CTracingServerMiddlewareName\
|
| 26 |
+
" arrow::flight::TracingServerMiddleware::kMiddlewareName"
|
| 27 |
+
|
| 28 |
+
cdef cppclass CActionType" arrow::flight::ActionType":
|
| 29 |
+
c_string type
|
| 30 |
+
c_string description
|
| 31 |
+
bint operator==(CActionType)
|
| 32 |
+
CResult[c_string] SerializeToString()
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
CResult[CActionType] Deserialize(const c_string& serialized)
|
| 36 |
+
|
| 37 |
+
cdef cppclass CAction" arrow::flight::Action":
|
| 38 |
+
c_string type
|
| 39 |
+
shared_ptr[CBuffer] body
|
| 40 |
+
bint operator==(CAction)
|
| 41 |
+
CResult[c_string] SerializeToString()
|
| 42 |
+
c_string ToString()
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
CResult[CAction] Deserialize(const c_string& serialized)
|
| 46 |
+
|
| 47 |
+
cdef cppclass CFlightResult" arrow::flight::Result":
|
| 48 |
+
CFlightResult()
|
| 49 |
+
CFlightResult(CFlightResult)
|
| 50 |
+
shared_ptr[CBuffer] body
|
| 51 |
+
bint operator==(CFlightResult)
|
| 52 |
+
CResult[c_string] SerializeToString()
|
| 53 |
+
c_string ToString()
|
| 54 |
+
|
| 55 |
+
@staticmethod
|
| 56 |
+
CResult[CFlightResult] Deserialize(const c_string& serialized)
|
| 57 |
+
|
| 58 |
+
cdef cppclass CBasicAuth" arrow::flight::BasicAuth":
|
| 59 |
+
CBasicAuth()
|
| 60 |
+
CBasicAuth(CBuffer)
|
| 61 |
+
CBasicAuth(CBasicAuth)
|
| 62 |
+
c_string username
|
| 63 |
+
c_string password
|
| 64 |
+
bint operator==(CBasicAuth)
|
| 65 |
+
CResult[c_string] SerializeToString()
|
| 66 |
+
c_string ToString()
|
| 67 |
+
|
| 68 |
+
@staticmethod
|
| 69 |
+
CResult[CBasicAuth] Deserialize(const c_string& serialized)
|
| 70 |
+
|
| 71 |
+
cdef cppclass CResultStream" arrow::flight::ResultStream":
|
| 72 |
+
CResult[unique_ptr[CFlightResult]] Next()
|
| 73 |
+
|
| 74 |
+
cdef cppclass CDescriptorType \
|
| 75 |
+
" arrow::flight::FlightDescriptor::DescriptorType":
|
| 76 |
+
bint operator==(CDescriptorType)
|
| 77 |
+
|
| 78 |
+
CDescriptorType CDescriptorTypeUnknown\
|
| 79 |
+
" arrow::flight::FlightDescriptor::UNKNOWN"
|
| 80 |
+
CDescriptorType CDescriptorTypePath\
|
| 81 |
+
" arrow::flight::FlightDescriptor::PATH"
|
| 82 |
+
CDescriptorType CDescriptorTypeCmd\
|
| 83 |
+
" arrow::flight::FlightDescriptor::CMD"
|
| 84 |
+
|
| 85 |
+
cdef cppclass CFlightDescriptor" arrow::flight::FlightDescriptor":
|
| 86 |
+
CDescriptorType type
|
| 87 |
+
c_string cmd
|
| 88 |
+
vector[c_string] path
|
| 89 |
+
bint operator==(CFlightDescriptor)
|
| 90 |
+
CResult[c_string] SerializeToString()
|
| 91 |
+
c_string ToString()
|
| 92 |
+
|
| 93 |
+
@staticmethod
|
| 94 |
+
CResult[CFlightDescriptor] Deserialize(const c_string& serialized)
|
| 95 |
+
|
| 96 |
+
cdef cppclass CTicket" arrow::flight::Ticket":
|
| 97 |
+
CTicket()
|
| 98 |
+
c_string ticket
|
| 99 |
+
bint operator==(CTicket)
|
| 100 |
+
CResult[c_string] SerializeToString()
|
| 101 |
+
c_string ToString()
|
| 102 |
+
|
| 103 |
+
@staticmethod
|
| 104 |
+
CResult[CTicket] Deserialize(const c_string& serialized)
|
| 105 |
+
|
| 106 |
+
cdef cppclass CCriteria" arrow::flight::Criteria":
|
| 107 |
+
CCriteria()
|
| 108 |
+
c_string expression
|
| 109 |
+
bint operator==(CCriteria)
|
| 110 |
+
CResult[c_string] SerializeToString()
|
| 111 |
+
|
| 112 |
+
@staticmethod
|
| 113 |
+
CResult[CCriteria] Deserialize(const c_string& serialized)
|
| 114 |
+
|
| 115 |
+
cdef cppclass CLocation" arrow::flight::Location":
|
| 116 |
+
CLocation()
|
| 117 |
+
c_string ToString()
|
| 118 |
+
c_bool Equals(const CLocation& other)
|
| 119 |
+
|
| 120 |
+
@staticmethod
|
| 121 |
+
CResult[CLocation] Parse(const c_string& uri_string)
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
CResult[CLocation] ForGrpcTcp(const c_string& host, int port)
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
CResult[CLocation] ForGrpcTls(const c_string& host, int port)
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
CResult[CLocation] ForGrpcUnix(const c_string& path)
|
| 131 |
+
|
| 132 |
+
cdef cppclass CFlightEndpoint" arrow::flight::FlightEndpoint":
|
| 133 |
+
CFlightEndpoint()
|
| 134 |
+
|
| 135 |
+
CTicket ticket
|
| 136 |
+
vector[CLocation] locations
|
| 137 |
+
|
| 138 |
+
bint operator==(CFlightEndpoint)
|
| 139 |
+
CResult[c_string] SerializeToString()
|
| 140 |
+
c_string ToString()
|
| 141 |
+
|
| 142 |
+
@staticmethod
|
| 143 |
+
CResult[CFlightEndpoint] Deserialize(const c_string& serialized)
|
| 144 |
+
|
| 145 |
+
cdef cppclass CFlightInfo" arrow::flight::FlightInfo":
|
| 146 |
+
CFlightInfo(CFlightInfo info)
|
| 147 |
+
int64_t total_records()
|
| 148 |
+
int64_t total_bytes()
|
| 149 |
+
CResult[shared_ptr[CSchema]] GetSchema(CDictionaryMemo* memo)
|
| 150 |
+
CFlightDescriptor& descriptor()
|
| 151 |
+
const vector[CFlightEndpoint]& endpoints()
|
| 152 |
+
CResult[c_string] SerializeToString()
|
| 153 |
+
c_string ToString()
|
| 154 |
+
bint operator==(CFlightInfo)
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
CResult[unique_ptr[CFlightInfo]] Deserialize(
|
| 158 |
+
const c_string& serialized)
|
| 159 |
+
|
| 160 |
+
cdef cppclass CSchemaResult" arrow::flight::SchemaResult":
|
| 161 |
+
CSchemaResult()
|
| 162 |
+
CSchemaResult(CSchemaResult result)
|
| 163 |
+
CResult[shared_ptr[CSchema]] GetSchema(CDictionaryMemo* memo)
|
| 164 |
+
bint operator==(CSchemaResult)
|
| 165 |
+
CResult[c_string] SerializeToString()
|
| 166 |
+
c_string ToString()
|
| 167 |
+
|
| 168 |
+
@staticmethod
|
| 169 |
+
CResult[CSchemaResult] Deserialize(const c_string& serialized)
|
| 170 |
+
|
| 171 |
+
cdef cppclass CFlightListing" arrow::flight::FlightListing":
|
| 172 |
+
CResult[unique_ptr[CFlightInfo]] Next()
|
| 173 |
+
|
| 174 |
+
cdef cppclass CSimpleFlightListing" arrow::flight::SimpleFlightListing":
|
| 175 |
+
# This doesn't work with Cython >= 3
|
| 176 |
+
# CSimpleFlightListing(vector[CFlightInfo]&& info)
|
| 177 |
+
CSimpleFlightListing(const vector[CFlightInfo]& info)
|
| 178 |
+
|
| 179 |
+
cdef cppclass CFlightPayload" arrow::flight::FlightPayload":
|
| 180 |
+
shared_ptr[CBuffer] descriptor
|
| 181 |
+
shared_ptr[CBuffer] app_metadata
|
| 182 |
+
CIpcPayload ipc_message
|
| 183 |
+
|
| 184 |
+
cdef cppclass CFlightDataStream" arrow::flight::FlightDataStream":
|
| 185 |
+
shared_ptr[CSchema] schema()
|
| 186 |
+
CResult[CFlightPayload] Next()
|
| 187 |
+
|
| 188 |
+
cdef cppclass CFlightStreamChunk" arrow::flight::FlightStreamChunk":
|
| 189 |
+
CFlightStreamChunk()
|
| 190 |
+
shared_ptr[CRecordBatch] data
|
| 191 |
+
shared_ptr[CBuffer] app_metadata
|
| 192 |
+
|
| 193 |
+
cdef cppclass CMetadataRecordBatchReader \
|
| 194 |
+
" arrow::flight::MetadataRecordBatchReader":
|
| 195 |
+
CResult[shared_ptr[CSchema]] GetSchema()
|
| 196 |
+
CResult[CFlightStreamChunk] Next()
|
| 197 |
+
CResult[shared_ptr[CTable]] ToTable()
|
| 198 |
+
|
| 199 |
+
CResult[shared_ptr[CRecordBatchReader]] MakeRecordBatchReader\
|
| 200 |
+
" arrow::flight::MakeRecordBatchReader"(
|
| 201 |
+
shared_ptr[CMetadataRecordBatchReader])
|
| 202 |
+
|
| 203 |
+
cdef cppclass CMetadataRecordBatchWriter \
|
| 204 |
+
" arrow::flight::MetadataRecordBatchWriter"(CRecordBatchWriter):
|
| 205 |
+
CStatus Begin(shared_ptr[CSchema] schema,
|
| 206 |
+
const CIpcWriteOptions& options)
|
| 207 |
+
CStatus WriteMetadata(shared_ptr[CBuffer] app_metadata)
|
| 208 |
+
CStatus WriteWithMetadata(const CRecordBatch& batch,
|
| 209 |
+
shared_ptr[CBuffer] app_metadata)
|
| 210 |
+
|
| 211 |
+
cdef cppclass CFlightStreamReader \
|
| 212 |
+
" arrow::flight::FlightStreamReader"(CMetadataRecordBatchReader):
|
| 213 |
+
void Cancel()
|
| 214 |
+
CResult[shared_ptr[CTable]] ToTableWithStopToken" ToTable"\
|
| 215 |
+
(const CStopToken& stop_token)
|
| 216 |
+
|
| 217 |
+
cdef cppclass CFlightMessageReader \
|
| 218 |
+
" arrow::flight::FlightMessageReader"(CMetadataRecordBatchReader):
|
| 219 |
+
CFlightDescriptor& descriptor()
|
| 220 |
+
|
| 221 |
+
cdef cppclass CFlightMessageWriter \
|
| 222 |
+
" arrow::flight::FlightMessageWriter"(CMetadataRecordBatchWriter):
|
| 223 |
+
pass
|
| 224 |
+
|
| 225 |
+
cdef cppclass CFlightStreamWriter \
|
| 226 |
+
" arrow::flight::FlightStreamWriter"(CMetadataRecordBatchWriter):
|
| 227 |
+
CStatus DoneWriting()
|
| 228 |
+
|
| 229 |
+
cdef cppclass CRecordBatchStream \
|
| 230 |
+
" arrow::flight::RecordBatchStream"(CFlightDataStream):
|
| 231 |
+
CRecordBatchStream(shared_ptr[CRecordBatchReader]& reader,
|
| 232 |
+
const CIpcWriteOptions& options)
|
| 233 |
+
|
| 234 |
+
cdef cppclass CFlightMetadataReader" arrow::flight::FlightMetadataReader":
|
| 235 |
+
CStatus ReadMetadata(shared_ptr[CBuffer]* out)
|
| 236 |
+
|
| 237 |
+
cdef cppclass CFlightMetadataWriter" arrow::flight::FlightMetadataWriter":
|
| 238 |
+
CStatus WriteMetadata(const CBuffer& message)
|
| 239 |
+
|
| 240 |
+
cdef cppclass CServerAuthReader" arrow::flight::ServerAuthReader":
|
| 241 |
+
CStatus Read(c_string* token)
|
| 242 |
+
|
| 243 |
+
cdef cppclass CServerAuthSender" arrow::flight::ServerAuthSender":
|
| 244 |
+
CStatus Write(c_string& token)
|
| 245 |
+
|
| 246 |
+
cdef cppclass CClientAuthReader" arrow::flight::ClientAuthReader":
|
| 247 |
+
CStatus Read(c_string* token)
|
| 248 |
+
|
| 249 |
+
cdef cppclass CClientAuthSender" arrow::flight::ClientAuthSender":
|
| 250 |
+
CStatus Write(c_string& token)
|
| 251 |
+
|
| 252 |
+
cdef cppclass CServerAuthHandler" arrow::flight::ServerAuthHandler":
|
| 253 |
+
pass
|
| 254 |
+
|
| 255 |
+
cdef cppclass CClientAuthHandler" arrow::flight::ClientAuthHandler":
|
| 256 |
+
pass
|
| 257 |
+
|
| 258 |
+
cdef cppclass CServerCallContext" arrow::flight::ServerCallContext":
|
| 259 |
+
c_string& peer_identity()
|
| 260 |
+
c_string& peer()
|
| 261 |
+
c_bool is_cancelled()
|
| 262 |
+
void AddHeader(const c_string& key, const c_string& value)
|
| 263 |
+
void AddTrailer(const c_string& key, const c_string& value)
|
| 264 |
+
CServerMiddleware* GetMiddleware(const c_string& key)
|
| 265 |
+
|
| 266 |
+
cdef cppclass CTimeoutDuration" arrow::flight::TimeoutDuration":
|
| 267 |
+
CTimeoutDuration(double)
|
| 268 |
+
|
| 269 |
+
cdef cppclass CFlightCallOptions" arrow::flight::FlightCallOptions":
|
| 270 |
+
CFlightCallOptions()
|
| 271 |
+
CTimeoutDuration timeout
|
| 272 |
+
CIpcWriteOptions write_options
|
| 273 |
+
CIpcReadOptions read_options
|
| 274 |
+
vector[pair[c_string, c_string]] headers
|
| 275 |
+
CStopToken stop_token
|
| 276 |
+
|
| 277 |
+
cdef cppclass CCertKeyPair" arrow::flight::CertKeyPair":
|
| 278 |
+
CCertKeyPair()
|
| 279 |
+
c_string pem_cert
|
| 280 |
+
c_string pem_key
|
| 281 |
+
|
| 282 |
+
cdef cppclass CFlightMethod" arrow::flight::FlightMethod":
|
| 283 |
+
bint operator==(CFlightMethod)
|
| 284 |
+
|
| 285 |
+
CFlightMethod CFlightMethodInvalid\
|
| 286 |
+
" arrow::flight::FlightMethod::Invalid"
|
| 287 |
+
CFlightMethod CFlightMethodHandshake\
|
| 288 |
+
" arrow::flight::FlightMethod::Handshake"
|
| 289 |
+
CFlightMethod CFlightMethodListFlights\
|
| 290 |
+
" arrow::flight::FlightMethod::ListFlights"
|
| 291 |
+
CFlightMethod CFlightMethodGetFlightInfo\
|
| 292 |
+
" arrow::flight::FlightMethod::GetFlightInfo"
|
| 293 |
+
CFlightMethod CFlightMethodGetSchema\
|
| 294 |
+
" arrow::flight::FlightMethod::GetSchema"
|
| 295 |
+
CFlightMethod CFlightMethodDoGet\
|
| 296 |
+
" arrow::flight::FlightMethod::DoGet"
|
| 297 |
+
CFlightMethod CFlightMethodDoPut\
|
| 298 |
+
" arrow::flight::FlightMethod::DoPut"
|
| 299 |
+
CFlightMethod CFlightMethodDoAction\
|
| 300 |
+
" arrow::flight::FlightMethod::DoAction"
|
| 301 |
+
CFlightMethod CFlightMethodListActions\
|
| 302 |
+
" arrow::flight::FlightMethod::ListActions"
|
| 303 |
+
CFlightMethod CFlightMethodDoExchange\
|
| 304 |
+
" arrow::flight::FlightMethod::DoExchange"
|
| 305 |
+
|
| 306 |
+
cdef cppclass CCallInfo" arrow::flight::CallInfo":
|
| 307 |
+
CFlightMethod method
|
| 308 |
+
|
| 309 |
+
# This is really std::unordered_multimap, but Cython has no
|
| 310 |
+
# bindings for it, so treat it as an opaque class and bind the
|
| 311 |
+
# methods we need
|
| 312 |
+
cdef cppclass CCallHeaders" arrow::flight::CallHeaders":
|
| 313 |
+
cppclass const_iterator:
|
| 314 |
+
pair[c_string, c_string] operator*()
|
| 315 |
+
# For Cython < 3
|
| 316 |
+
const_iterator operator++()
|
| 317 |
+
# For Cython >= 3
|
| 318 |
+
const_iterator operator++(int)
|
| 319 |
+
bint operator==(const_iterator)
|
| 320 |
+
bint operator!=(const_iterator)
|
| 321 |
+
const_iterator cbegin()
|
| 322 |
+
const_iterator cend()
|
| 323 |
+
|
| 324 |
+
cdef cppclass CAddCallHeaders" arrow::flight::AddCallHeaders":
|
| 325 |
+
void AddHeader(const c_string& key, const c_string& value)
|
| 326 |
+
|
| 327 |
+
cdef cppclass CServerMiddleware" arrow::flight::ServerMiddleware":
|
| 328 |
+
c_string name()
|
| 329 |
+
|
| 330 |
+
cdef cppclass CServerMiddlewareFactory\
|
| 331 |
+
" arrow::flight::ServerMiddlewareFactory":
|
| 332 |
+
pass
|
| 333 |
+
|
| 334 |
+
cdef cppclass CClientMiddleware" arrow::flight::ClientMiddleware":
|
| 335 |
+
pass
|
| 336 |
+
|
| 337 |
+
cdef cppclass CClientMiddlewareFactory\
|
| 338 |
+
" arrow::flight::ClientMiddlewareFactory":
|
| 339 |
+
pass
|
| 340 |
+
|
| 341 |
+
cpdef cppclass CTracingServerMiddlewareTraceKey\
|
| 342 |
+
" arrow::flight::TracingServerMiddleware::TraceKey":
|
| 343 |
+
CTracingServerMiddlewareTraceKey()
|
| 344 |
+
c_string key
|
| 345 |
+
c_string value
|
| 346 |
+
|
| 347 |
+
cdef cppclass CTracingServerMiddleware\
|
| 348 |
+
" arrow::flight::TracingServerMiddleware"(CServerMiddleware):
|
| 349 |
+
vector[CTracingServerMiddlewareTraceKey] GetTraceContext()
|
| 350 |
+
|
| 351 |
+
cdef shared_ptr[CServerMiddlewareFactory] \
|
| 352 |
+
MakeTracingServerMiddlewareFactory\
|
| 353 |
+
" arrow::flight::MakeTracingServerMiddlewareFactory"()
|
| 354 |
+
|
| 355 |
+
cdef cppclass CFlightServerOptions" arrow::flight::FlightServerOptions":
|
| 356 |
+
CFlightServerOptions(const CLocation& location)
|
| 357 |
+
CLocation location
|
| 358 |
+
unique_ptr[CServerAuthHandler] auth_handler
|
| 359 |
+
vector[CCertKeyPair] tls_certificates
|
| 360 |
+
c_bool verify_client
|
| 361 |
+
c_string root_certificates
|
| 362 |
+
vector[pair[c_string, shared_ptr[CServerMiddlewareFactory]]] middleware
|
| 363 |
+
|
| 364 |
+
cdef cppclass CFlightClientOptions" arrow::flight::FlightClientOptions":
|
| 365 |
+
c_string tls_root_certs
|
| 366 |
+
c_string cert_chain
|
| 367 |
+
c_string private_key
|
| 368 |
+
c_string override_hostname
|
| 369 |
+
vector[shared_ptr[CClientMiddlewareFactory]] middleware
|
| 370 |
+
int64_t write_size_limit_bytes
|
| 371 |
+
vector[pair[c_string, CIntStringVariant]] generic_options
|
| 372 |
+
c_bool disable_server_verification
|
| 373 |
+
|
| 374 |
+
@staticmethod
|
| 375 |
+
CFlightClientOptions Defaults()
|
| 376 |
+
|
| 377 |
+
cdef cppclass CDoPutResult" arrow::flight::FlightClient::DoPutResult":
|
| 378 |
+
unique_ptr[CFlightStreamWriter] writer
|
| 379 |
+
unique_ptr[CFlightMetadataReader] reader
|
| 380 |
+
|
| 381 |
+
cdef cppclass CDoExchangeResult" arrow::flight::FlightClient::DoExchangeResult":
|
| 382 |
+
unique_ptr[CFlightStreamWriter] writer
|
| 383 |
+
unique_ptr[CFlightStreamReader] reader
|
| 384 |
+
|
| 385 |
+
cdef cppclass CFlightClient" arrow::flight::FlightClient":
|
| 386 |
+
@staticmethod
|
| 387 |
+
CResult[unique_ptr[CFlightClient]] Connect(const CLocation& location,
|
| 388 |
+
const CFlightClientOptions& options)
|
| 389 |
+
|
| 390 |
+
c_bool supports_async()
|
| 391 |
+
CStatus CheckAsyncSupport()
|
| 392 |
+
|
| 393 |
+
CStatus Authenticate(CFlightCallOptions& options,
|
| 394 |
+
unique_ptr[CClientAuthHandler] auth_handler)
|
| 395 |
+
|
| 396 |
+
CResult[pair[c_string, c_string]] AuthenticateBasicToken(
|
| 397 |
+
CFlightCallOptions& options,
|
| 398 |
+
const c_string& username,
|
| 399 |
+
const c_string& password)
|
| 400 |
+
|
| 401 |
+
CResult[unique_ptr[CResultStream]] DoAction(CFlightCallOptions& options, CAction& action)
|
| 402 |
+
CResult[vector[CActionType]] ListActions(CFlightCallOptions& options)
|
| 403 |
+
|
| 404 |
+
CResult[unique_ptr[CFlightListing]] ListFlights(CFlightCallOptions& options, CCriteria criteria)
|
| 405 |
+
CResult[unique_ptr[CFlightInfo]] GetFlightInfo(CFlightCallOptions& options,
|
| 406 |
+
CFlightDescriptor& descriptor)
|
| 407 |
+
CFuture[CFlightInfo] GetFlightInfoAsync(CFlightCallOptions& options,
|
| 408 |
+
CFlightDescriptor& descriptor)
|
| 409 |
+
CResult[unique_ptr[CSchemaResult]] GetSchema(CFlightCallOptions& options,
|
| 410 |
+
CFlightDescriptor& descriptor)
|
| 411 |
+
CResult[unique_ptr[CFlightStreamReader]] DoGet(CFlightCallOptions& options, CTicket& ticket)
|
| 412 |
+
CResult[CDoPutResult] DoPut(CFlightCallOptions& options,
|
| 413 |
+
CFlightDescriptor& descriptor,
|
| 414 |
+
shared_ptr[CSchema]& schema)
|
| 415 |
+
CResult[CDoExchangeResult] DoExchange(CFlightCallOptions& options,
|
| 416 |
+
CFlightDescriptor& descriptor)
|
| 417 |
+
CStatus Close()
|
| 418 |
+
|
| 419 |
+
cdef cppclass CFlightStatusCode" arrow::flight::FlightStatusCode":
|
| 420 |
+
bint operator==(CFlightStatusCode)
|
| 421 |
+
|
| 422 |
+
CFlightStatusCode CFlightStatusInternal \
|
| 423 |
+
" arrow::flight::FlightStatusCode::Internal"
|
| 424 |
+
CFlightStatusCode CFlightStatusTimedOut \
|
| 425 |
+
" arrow::flight::FlightStatusCode::TimedOut"
|
| 426 |
+
CFlightStatusCode CFlightStatusCancelled \
|
| 427 |
+
" arrow::flight::FlightStatusCode::Cancelled"
|
| 428 |
+
CFlightStatusCode CFlightStatusUnauthenticated \
|
| 429 |
+
" arrow::flight::FlightStatusCode::Unauthenticated"
|
| 430 |
+
CFlightStatusCode CFlightStatusUnauthorized \
|
| 431 |
+
" arrow::flight::FlightStatusCode::Unauthorized"
|
| 432 |
+
CFlightStatusCode CFlightStatusUnavailable \
|
| 433 |
+
" arrow::flight::FlightStatusCode::Unavailable"
|
| 434 |
+
CFlightStatusCode CFlightStatusFailed \
|
| 435 |
+
" arrow::flight::FlightStatusCode::Failed"
|
| 436 |
+
|
| 437 |
+
cdef cppclass FlightStatusDetail" arrow::flight::FlightStatusDetail":
|
| 438 |
+
CFlightStatusCode code()
|
| 439 |
+
c_string extra_info()
|
| 440 |
+
|
| 441 |
+
@staticmethod
|
| 442 |
+
shared_ptr[FlightStatusDetail] UnwrapStatus(const CStatus& status)
|
| 443 |
+
|
| 444 |
+
cdef cppclass FlightWriteSizeStatusDetail\
|
| 445 |
+
" arrow::flight::FlightWriteSizeStatusDetail":
|
| 446 |
+
int64_t limit()
|
| 447 |
+
int64_t actual()
|
| 448 |
+
|
| 449 |
+
@staticmethod
|
| 450 |
+
shared_ptr[FlightWriteSizeStatusDetail] UnwrapStatus(
|
| 451 |
+
const CStatus& status)
|
| 452 |
+
|
| 453 |
+
cdef CStatus MakeFlightError" arrow::flight::MakeFlightError" \
|
| 454 |
+
(CFlightStatusCode code, const c_string& message)
|
| 455 |
+
|
| 456 |
+
cdef CStatus MakeFlightError" arrow::flight::MakeFlightError" \
|
| 457 |
+
(CFlightStatusCode code,
|
| 458 |
+
const c_string& message,
|
| 459 |
+
const c_string& extra_info)
|
| 460 |
+
|
| 461 |
+
# Callbacks for implementing Flight servers
|
| 462 |
+
# Use typedef to emulate syntax for std::function<void(..)>
|
| 463 |
+
ctypedef CStatus cb_list_flights(object, const CServerCallContext&,
|
| 464 |
+
const CCriteria*,
|
| 465 |
+
unique_ptr[CFlightListing]*)
|
| 466 |
+
ctypedef CStatus cb_get_flight_info(object, const CServerCallContext&,
|
| 467 |
+
const CFlightDescriptor&,
|
| 468 |
+
unique_ptr[CFlightInfo]*)
|
| 469 |
+
ctypedef CStatus cb_get_schema(object, const CServerCallContext&,
|
| 470 |
+
const CFlightDescriptor&,
|
| 471 |
+
unique_ptr[CSchemaResult]*)
|
| 472 |
+
ctypedef CStatus cb_do_put(object, const CServerCallContext&,
|
| 473 |
+
unique_ptr[CFlightMessageReader],
|
| 474 |
+
unique_ptr[CFlightMetadataWriter])
|
| 475 |
+
ctypedef CStatus cb_do_get(object, const CServerCallContext&,
|
| 476 |
+
const CTicket&,
|
| 477 |
+
unique_ptr[CFlightDataStream]*)
|
| 478 |
+
ctypedef CStatus cb_do_exchange(object, const CServerCallContext&,
|
| 479 |
+
unique_ptr[CFlightMessageReader],
|
| 480 |
+
unique_ptr[CFlightMessageWriter])
|
| 481 |
+
ctypedef CStatus cb_do_action(object, const CServerCallContext&,
|
| 482 |
+
const CAction&,
|
| 483 |
+
unique_ptr[CResultStream]*)
|
| 484 |
+
ctypedef CStatus cb_list_actions(object, const CServerCallContext&,
|
| 485 |
+
vector[CActionType]*)
|
| 486 |
+
ctypedef CStatus cb_result_next(object, unique_ptr[CFlightResult]*)
|
| 487 |
+
ctypedef CStatus cb_data_stream_next(object, CFlightPayload*)
|
| 488 |
+
ctypedef CStatus cb_server_authenticate(object, CServerAuthSender*,
|
| 489 |
+
CServerAuthReader*)
|
| 490 |
+
ctypedef CStatus cb_is_valid(object, const c_string&, c_string*)
|
| 491 |
+
ctypedef CStatus cb_client_authenticate(object, CClientAuthSender*,
|
| 492 |
+
CClientAuthReader*)
|
| 493 |
+
ctypedef CStatus cb_get_token(object, c_string*)
|
| 494 |
+
|
| 495 |
+
ctypedef CStatus cb_middleware_sending_headers(object, CAddCallHeaders*)
|
| 496 |
+
ctypedef CStatus cb_middleware_call_completed(object, const CStatus&)
|
| 497 |
+
ctypedef CStatus cb_client_middleware_received_headers(
|
| 498 |
+
object, const CCallHeaders&)
|
| 499 |
+
ctypedef CStatus cb_server_middleware_start_call(
|
| 500 |
+
object,
|
| 501 |
+
const CCallInfo&,
|
| 502 |
+
const CCallHeaders&,
|
| 503 |
+
shared_ptr[CServerMiddleware]*)
|
| 504 |
+
ctypedef CStatus cb_client_middleware_start_call(
|
| 505 |
+
object,
|
| 506 |
+
const CCallInfo&,
|
| 507 |
+
unique_ptr[CClientMiddleware]*)
|
| 508 |
+
|
| 509 |
+
cdef extern from "arrow/python/flight.h" namespace "arrow::py::flight" nogil:
|
| 510 |
+
cdef char* CPyServerMiddlewareName\
|
| 511 |
+
" arrow::py::flight::kPyServerMiddlewareName"
|
| 512 |
+
|
| 513 |
+
cdef cppclass PyFlightServerVtable:
|
| 514 |
+
PyFlightServerVtable()
|
| 515 |
+
function[cb_list_flights] list_flights
|
| 516 |
+
function[cb_get_flight_info] get_flight_info
|
| 517 |
+
function[cb_get_schema] get_schema
|
| 518 |
+
function[cb_do_put] do_put
|
| 519 |
+
function[cb_do_get] do_get
|
| 520 |
+
function[cb_do_exchange] do_exchange
|
| 521 |
+
function[cb_do_action] do_action
|
| 522 |
+
function[cb_list_actions] list_actions
|
| 523 |
+
|
| 524 |
+
cdef cppclass PyServerAuthHandlerVtable:
|
| 525 |
+
PyServerAuthHandlerVtable()
|
| 526 |
+
function[cb_server_authenticate] authenticate
|
| 527 |
+
function[cb_is_valid] is_valid
|
| 528 |
+
|
| 529 |
+
cdef cppclass PyClientAuthHandlerVtable:
|
| 530 |
+
PyClientAuthHandlerVtable()
|
| 531 |
+
function[cb_client_authenticate] authenticate
|
| 532 |
+
function[cb_get_token] get_token
|
| 533 |
+
|
| 534 |
+
cdef cppclass PyFlightServer:
|
| 535 |
+
PyFlightServer(object server, PyFlightServerVtable vtable)
|
| 536 |
+
|
| 537 |
+
CStatus Init(CFlightServerOptions& options)
|
| 538 |
+
int port()
|
| 539 |
+
CStatus ServeWithSignals() except *
|
| 540 |
+
CStatus Shutdown()
|
| 541 |
+
CStatus Wait()
|
| 542 |
+
|
| 543 |
+
cdef cppclass PyServerAuthHandler\
|
| 544 |
+
" arrow::py::flight::PyServerAuthHandler"(CServerAuthHandler):
|
| 545 |
+
PyServerAuthHandler(object handler, PyServerAuthHandlerVtable vtable)
|
| 546 |
+
|
| 547 |
+
cdef cppclass PyClientAuthHandler\
|
| 548 |
+
" arrow::py::flight::PyClientAuthHandler"(CClientAuthHandler):
|
| 549 |
+
PyClientAuthHandler(object handler, PyClientAuthHandlerVtable vtable)
|
| 550 |
+
|
| 551 |
+
cdef cppclass CPyFlightResultStream\
|
| 552 |
+
" arrow::py::flight::PyFlightResultStream"(CResultStream):
|
| 553 |
+
CPyFlightResultStream(object generator,
|
| 554 |
+
function[cb_result_next] callback)
|
| 555 |
+
|
| 556 |
+
cdef cppclass CPyFlightDataStream\
|
| 557 |
+
" arrow::py::flight::PyFlightDataStream"(CFlightDataStream):
|
| 558 |
+
CPyFlightDataStream(object data_source,
|
| 559 |
+
unique_ptr[CFlightDataStream] stream)
|
| 560 |
+
|
| 561 |
+
cdef cppclass CPyGeneratorFlightDataStream\
|
| 562 |
+
" arrow::py::flight::PyGeneratorFlightDataStream"\
|
| 563 |
+
(CFlightDataStream):
|
| 564 |
+
CPyGeneratorFlightDataStream(object generator,
|
| 565 |
+
shared_ptr[CSchema] schema,
|
| 566 |
+
function[cb_data_stream_next] callback,
|
| 567 |
+
const CIpcWriteOptions& options)
|
| 568 |
+
|
| 569 |
+
cdef cppclass PyServerMiddlewareVtable\
|
| 570 |
+
" arrow::py::flight::PyServerMiddleware::Vtable":
|
| 571 |
+
PyServerMiddlewareVtable()
|
| 572 |
+
function[cb_middleware_sending_headers] sending_headers
|
| 573 |
+
function[cb_middleware_call_completed] call_completed
|
| 574 |
+
|
| 575 |
+
cdef cppclass PyClientMiddlewareVtable\
|
| 576 |
+
" arrow::py::flight::PyClientMiddleware::Vtable":
|
| 577 |
+
PyClientMiddlewareVtable()
|
| 578 |
+
function[cb_middleware_sending_headers] sending_headers
|
| 579 |
+
function[cb_client_middleware_received_headers] received_headers
|
| 580 |
+
function[cb_middleware_call_completed] call_completed
|
| 581 |
+
|
| 582 |
+
cdef cppclass CPyServerMiddleware\
|
| 583 |
+
" arrow::py::flight::PyServerMiddleware"(CServerMiddleware):
|
| 584 |
+
CPyServerMiddleware(object middleware, PyServerMiddlewareVtable vtable)
|
| 585 |
+
void* py_object()
|
| 586 |
+
|
| 587 |
+
cdef cppclass CPyServerMiddlewareFactory\
|
| 588 |
+
" arrow::py::flight::PyServerMiddlewareFactory"\
|
| 589 |
+
(CServerMiddlewareFactory):
|
| 590 |
+
CPyServerMiddlewareFactory(
|
| 591 |
+
object factory,
|
| 592 |
+
function[cb_server_middleware_start_call] start_call)
|
| 593 |
+
|
| 594 |
+
cdef cppclass CPyClientMiddleware\
|
| 595 |
+
" arrow::py::flight::PyClientMiddleware"(CClientMiddleware):
|
| 596 |
+
CPyClientMiddleware(object middleware, PyClientMiddlewareVtable vtable)
|
| 597 |
+
|
| 598 |
+
cdef cppclass CPyClientMiddlewareFactory\
|
| 599 |
+
" arrow::py::flight::PyClientMiddlewareFactory"\
|
| 600 |
+
(CClientMiddlewareFactory):
|
| 601 |
+
CPyClientMiddlewareFactory(
|
| 602 |
+
object factory,
|
| 603 |
+
function[cb_client_middleware_start_call] start_call)
|
| 604 |
+
|
| 605 |
+
cdef CStatus CreateFlightInfo" arrow::py::flight::CreateFlightInfo"(
|
| 606 |
+
shared_ptr[CSchema] schema,
|
| 607 |
+
CFlightDescriptor& descriptor,
|
| 608 |
+
vector[CFlightEndpoint] endpoints,
|
| 609 |
+
int64_t total_records,
|
| 610 |
+
int64_t total_bytes,
|
| 611 |
+
unique_ptr[CFlightInfo]* out)
|
| 612 |
+
|
| 613 |
+
cdef CStatus CreateSchemaResult" arrow::py::flight::CreateSchemaResult"(
|
| 614 |
+
shared_ptr[CSchema] schema,
|
| 615 |
+
unique_ptr[CSchemaResult]* out)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
cdef extern from "<variant>" namespace "std" nogil:
|
| 619 |
+
cdef cppclass CIntStringVariant" std::variant<int, std::string>":
|
| 620 |
+
CIntStringVariant()
|
| 621 |
+
CIntStringVariant(int)
|
| 622 |
+
CIntStringVariant(c_string)
|
vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_fs.pxd
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
|
| 20 |
+
from pyarrow.includes.common cimport *
|
| 21 |
+
from pyarrow.includes.libarrow cimport *
|
| 22 |
+
from pyarrow.includes.libarrow_python cimport CTimePoint
|
| 23 |
+
|
| 24 |
+
cdef extern from "arrow/filesystem/api.h" namespace "arrow::fs" nogil:
|
| 25 |
+
|
| 26 |
+
ctypedef enum CFileType "arrow::fs::FileType":
|
| 27 |
+
CFileType_NotFound "arrow::fs::FileType::NotFound"
|
| 28 |
+
CFileType_Unknown "arrow::fs::FileType::Unknown"
|
| 29 |
+
CFileType_File "arrow::fs::FileType::File"
|
| 30 |
+
CFileType_Directory "arrow::fs::FileType::Directory"
|
| 31 |
+
|
| 32 |
+
cdef cppclass CFileInfo "arrow::fs::FileInfo":
|
| 33 |
+
CFileInfo()
|
| 34 |
+
CFileInfo(CFileInfo)
|
| 35 |
+
CFileInfo& operator=(CFileInfo)
|
| 36 |
+
CFileInfo(const CFileInfo&)
|
| 37 |
+
CFileInfo& operator=(const CFileInfo&)
|
| 38 |
+
|
| 39 |
+
CFileType type()
|
| 40 |
+
void set_type(CFileType type)
|
| 41 |
+
c_string path()
|
| 42 |
+
void set_path(const c_string& path)
|
| 43 |
+
c_string base_name()
|
| 44 |
+
int64_t size()
|
| 45 |
+
void set_size(int64_t size)
|
| 46 |
+
c_string extension()
|
| 47 |
+
CTimePoint mtime()
|
| 48 |
+
void set_mtime(CTimePoint mtime)
|
| 49 |
+
|
| 50 |
+
cdef cppclass CFileSelector "arrow::fs::FileSelector":
|
| 51 |
+
CFileSelector()
|
| 52 |
+
c_string base_dir
|
| 53 |
+
c_bool allow_not_found
|
| 54 |
+
c_bool recursive
|
| 55 |
+
|
| 56 |
+
cdef cppclass CFileLocator "arrow::fs::FileLocator":
|
| 57 |
+
shared_ptr[CFileSystem] filesystem
|
| 58 |
+
c_string path
|
| 59 |
+
|
| 60 |
+
cdef cppclass CFileSystem "arrow::fs::FileSystem":
|
| 61 |
+
shared_ptr[CFileSystem] shared_from_this()
|
| 62 |
+
c_string type_name() const
|
| 63 |
+
CResult[c_string] NormalizePath(c_string path)
|
| 64 |
+
CResult[c_string] MakeUri(c_string path)
|
| 65 |
+
CResult[CFileInfo] GetFileInfo(const c_string& path)
|
| 66 |
+
CResult[vector[CFileInfo]] GetFileInfo(
|
| 67 |
+
const vector[c_string]& paths)
|
| 68 |
+
CResult[vector[CFileInfo]] GetFileInfo(const CFileSelector& select)
|
| 69 |
+
CStatus CreateDir(const c_string& path, c_bool recursive)
|
| 70 |
+
CStatus DeleteDir(const c_string& path)
|
| 71 |
+
CStatus DeleteDirContents(const c_string& path, c_bool missing_dir_ok)
|
| 72 |
+
CStatus DeleteRootDirContents()
|
| 73 |
+
CStatus DeleteFile(const c_string& path)
|
| 74 |
+
CStatus DeleteFiles(const vector[c_string]& paths)
|
| 75 |
+
CStatus Move(const c_string& src, const c_string& dest)
|
| 76 |
+
CStatus CopyFile(const c_string& src, const c_string& dest)
|
| 77 |
+
CResult[shared_ptr[CInputStream]] OpenInputStream(
|
| 78 |
+
const c_string& path)
|
| 79 |
+
CResult[shared_ptr[CRandomAccessFile]] OpenInputFile(
|
| 80 |
+
const c_string& path)
|
| 81 |
+
CResult[shared_ptr[COutputStream]] OpenOutputStream(
|
| 82 |
+
const c_string& path, const shared_ptr[const CKeyValueMetadata]&)
|
| 83 |
+
CResult[shared_ptr[COutputStream]] OpenAppendStream(
|
| 84 |
+
const c_string& path, const shared_ptr[const CKeyValueMetadata]&)
|
| 85 |
+
c_bool Equals(const CFileSystem& other)
|
| 86 |
+
c_bool Equals(shared_ptr[CFileSystem] other)
|
| 87 |
+
|
| 88 |
+
CResult[shared_ptr[CFileSystem]] CFileSystemFromUri \
|
| 89 |
+
"arrow::fs::FileSystemFromUri"(const c_string& uri)
|
| 90 |
+
CResult[shared_ptr[CFileSystem]] CFileSystemFromUri \
|
| 91 |
+
"arrow::fs::FileSystemFromUri"(const c_string& uri, c_string* out_path)
|
| 92 |
+
CResult[shared_ptr[CFileSystem]] CFileSystemFromUriOrPath \
|
| 93 |
+
"arrow::fs::FileSystemFromUriOrPath"(const c_string& uri,
|
| 94 |
+
c_string* out_path)
|
| 95 |
+
|
| 96 |
+
cdef cppclass CFileSystemGlobalOptions \
|
| 97 |
+
"arrow::fs::FileSystemGlobalOptions":
|
| 98 |
+
c_string tls_ca_file_path
|
| 99 |
+
c_string tls_ca_dir_path
|
| 100 |
+
|
| 101 |
+
CStatus CFileSystemsInitialize "arrow::fs::Initialize" \
|
| 102 |
+
(const CFileSystemGlobalOptions& options)
|
| 103 |
+
|
| 104 |
+
cdef cppclass CSubTreeFileSystem \
|
| 105 |
+
"arrow::fs::SubTreeFileSystem"(CFileSystem):
|
| 106 |
+
CSubTreeFileSystem(const c_string& base_path,
|
| 107 |
+
shared_ptr[CFileSystem] base_fs)
|
| 108 |
+
c_string base_path()
|
| 109 |
+
shared_ptr[CFileSystem] base_fs()
|
| 110 |
+
|
| 111 |
+
ctypedef enum CS3LogLevel "arrow::fs::S3LogLevel":
|
| 112 |
+
CS3LogLevel_Off "arrow::fs::S3LogLevel::Off"
|
| 113 |
+
CS3LogLevel_Fatal "arrow::fs::S3LogLevel::Fatal"
|
| 114 |
+
CS3LogLevel_Error "arrow::fs::S3LogLevel::Error"
|
| 115 |
+
CS3LogLevel_Warn "arrow::fs::S3LogLevel::Warn"
|
| 116 |
+
CS3LogLevel_Info "arrow::fs::S3LogLevel::Info"
|
| 117 |
+
CS3LogLevel_Debug "arrow::fs::S3LogLevel::Debug"
|
| 118 |
+
CS3LogLevel_Trace "arrow::fs::S3LogLevel::Trace"
|
| 119 |
+
|
| 120 |
+
cdef struct CS3GlobalOptions "arrow::fs::S3GlobalOptions":
|
| 121 |
+
CS3LogLevel log_level
|
| 122 |
+
int num_event_loop_threads
|
| 123 |
+
|
| 124 |
+
cdef cppclass CS3ProxyOptions "arrow::fs::S3ProxyOptions":
|
| 125 |
+
c_string scheme
|
| 126 |
+
c_string host
|
| 127 |
+
int port
|
| 128 |
+
c_string username
|
| 129 |
+
c_string password
|
| 130 |
+
c_bool Equals(const CS3ProxyOptions& other)
|
| 131 |
+
|
| 132 |
+
@staticmethod
|
| 133 |
+
CResult[CS3ProxyOptions] FromUriString "FromUri"(
|
| 134 |
+
const c_string& uri_string)
|
| 135 |
+
|
| 136 |
+
ctypedef enum CS3CredentialsKind "arrow::fs::S3CredentialsKind":
|
| 137 |
+
CS3CredentialsKind_Anonymous "arrow::fs::S3CredentialsKind::Anonymous"
|
| 138 |
+
CS3CredentialsKind_Default "arrow::fs::S3CredentialsKind::Default"
|
| 139 |
+
CS3CredentialsKind_Explicit "arrow::fs::S3CredentialsKind::Explicit"
|
| 140 |
+
CS3CredentialsKind_Role "arrow::fs::S3CredentialsKind::Role"
|
| 141 |
+
CS3CredentialsKind_WebIdentity \
|
| 142 |
+
"arrow::fs::S3CredentialsKind::WebIdentity"
|
| 143 |
+
|
| 144 |
+
cdef cppclass CS3RetryStrategy "arrow::fs::S3RetryStrategy":
|
| 145 |
+
@staticmethod
|
| 146 |
+
shared_ptr[CS3RetryStrategy] GetAwsDefaultRetryStrategy(int64_t max_attempts)
|
| 147 |
+
|
| 148 |
+
@staticmethod
|
| 149 |
+
shared_ptr[CS3RetryStrategy] GetAwsStandardRetryStrategy(int64_t max_attempts)
|
| 150 |
+
|
| 151 |
+
cdef cppclass CS3Options "arrow::fs::S3Options":
|
| 152 |
+
c_string region
|
| 153 |
+
double connect_timeout
|
| 154 |
+
double request_timeout
|
| 155 |
+
c_string endpoint_override
|
| 156 |
+
c_string scheme
|
| 157 |
+
c_bool background_writes
|
| 158 |
+
c_bool allow_bucket_creation
|
| 159 |
+
c_bool allow_bucket_deletion
|
| 160 |
+
c_bool check_directory_existence_before_creation
|
| 161 |
+
c_bool force_virtual_addressing
|
| 162 |
+
shared_ptr[const CKeyValueMetadata] default_metadata
|
| 163 |
+
c_string role_arn
|
| 164 |
+
c_string session_name
|
| 165 |
+
c_string external_id
|
| 166 |
+
int load_frequency
|
| 167 |
+
CS3ProxyOptions proxy_options
|
| 168 |
+
CS3CredentialsKind credentials_kind
|
| 169 |
+
shared_ptr[CS3RetryStrategy] retry_strategy
|
| 170 |
+
void ConfigureDefaultCredentials()
|
| 171 |
+
void ConfigureAccessKey(const c_string& access_key,
|
| 172 |
+
const c_string& secret_key,
|
| 173 |
+
const c_string& session_token)
|
| 174 |
+
c_string GetAccessKey()
|
| 175 |
+
c_string GetSecretKey()
|
| 176 |
+
c_string GetSessionToken()
|
| 177 |
+
c_bool Equals(const CS3Options& other)
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
CS3Options Defaults()
|
| 181 |
+
|
| 182 |
+
@staticmethod
|
| 183 |
+
CS3Options Anonymous()
|
| 184 |
+
|
| 185 |
+
@staticmethod
|
| 186 |
+
CS3Options FromAccessKey(const c_string& access_key,
|
| 187 |
+
const c_string& secret_key,
|
| 188 |
+
const c_string& session_token)
|
| 189 |
+
|
| 190 |
+
@staticmethod
|
| 191 |
+
CS3Options FromAssumeRole(const c_string& role_arn,
|
| 192 |
+
const c_string& session_name,
|
| 193 |
+
const c_string& external_id,
|
| 194 |
+
const int load_frequency)
|
| 195 |
+
|
| 196 |
+
cdef cppclass CS3FileSystem "arrow::fs::S3FileSystem"(CFileSystem):
|
| 197 |
+
@staticmethod
|
| 198 |
+
CResult[shared_ptr[CS3FileSystem]] Make(const CS3Options& options)
|
| 199 |
+
CS3Options options()
|
| 200 |
+
c_string region()
|
| 201 |
+
|
| 202 |
+
cdef CStatus CInitializeS3 "arrow::fs::InitializeS3"(
|
| 203 |
+
const CS3GlobalOptions& options)
|
| 204 |
+
cdef CStatus CEnsureS3Initialized "arrow::fs::EnsureS3Initialized"()
|
| 205 |
+
cdef CStatus CFinalizeS3 "arrow::fs::FinalizeS3"()
|
| 206 |
+
cdef CStatus CEnsureS3Finalized "arrow::fs::EnsureS3Finalized"()
|
| 207 |
+
|
| 208 |
+
cdef CResult[c_string] ResolveS3BucketRegion(const c_string& bucket)
|
| 209 |
+
|
| 210 |
+
cdef cppclass CGcsCredentials "arrow::fs::GcsCredentials":
|
| 211 |
+
c_bool anonymous()
|
| 212 |
+
CTimePoint expiration()
|
| 213 |
+
c_string access_token()
|
| 214 |
+
c_string target_service_account()
|
| 215 |
+
|
| 216 |
+
cdef cppclass CGcsOptions "arrow::fs::GcsOptions":
|
| 217 |
+
CGcsCredentials credentials
|
| 218 |
+
c_string endpoint_override
|
| 219 |
+
c_string scheme
|
| 220 |
+
c_string default_bucket_location
|
| 221 |
+
optional[c_string] project_id
|
| 222 |
+
optional[double] retry_limit_seconds
|
| 223 |
+
shared_ptr[const CKeyValueMetadata] default_metadata
|
| 224 |
+
c_bool Equals(const CS3Options& other)
|
| 225 |
+
|
| 226 |
+
@staticmethod
|
| 227 |
+
CGcsOptions Defaults()
|
| 228 |
+
|
| 229 |
+
@staticmethod
|
| 230 |
+
CGcsOptions Anonymous()
|
| 231 |
+
|
| 232 |
+
@staticmethod
|
| 233 |
+
CGcsOptions FromAccessToken(const c_string& access_token,
|
| 234 |
+
CTimePoint expiration)
|
| 235 |
+
|
| 236 |
+
@staticmethod
|
| 237 |
+
CGcsOptions FromImpersonatedServiceAccount(const CGcsCredentials& base_credentials,
|
| 238 |
+
c_string& target_service_account)
|
| 239 |
+
|
| 240 |
+
cdef cppclass CGcsFileSystem "arrow::fs::GcsFileSystem":
|
| 241 |
+
@staticmethod
|
| 242 |
+
CResult[shared_ptr[CGcsFileSystem]] Make(const CGcsOptions& options)
|
| 243 |
+
CGcsOptions options()
|
| 244 |
+
|
| 245 |
+
cdef cppclass CAzureOptions "arrow::fs::AzureOptions":
|
| 246 |
+
c_string account_name
|
| 247 |
+
c_string blob_storage_authority
|
| 248 |
+
c_string dfs_storage_authority
|
| 249 |
+
c_string blob_storage_scheme
|
| 250 |
+
c_string dfs_storage_scheme
|
| 251 |
+
|
| 252 |
+
c_bool Equals(const CAzureOptions& other)
|
| 253 |
+
CStatus ConfigureDefaultCredential()
|
| 254 |
+
CStatus ConfigureAccountKeyCredential(c_string account_key)
|
| 255 |
+
|
| 256 |
+
cdef cppclass CAzureFileSystem "arrow::fs::AzureFileSystem":
|
| 257 |
+
@staticmethod
|
| 258 |
+
CResult[shared_ptr[CAzureFileSystem]] Make(const CAzureOptions& options)
|
| 259 |
+
CAzureOptions options()
|
| 260 |
+
|
| 261 |
+
cdef cppclass CHdfsOptions "arrow::fs::HdfsOptions":
|
| 262 |
+
HdfsConnectionConfig connection_config
|
| 263 |
+
int32_t buffer_size
|
| 264 |
+
int16_t replication
|
| 265 |
+
int64_t default_block_size
|
| 266 |
+
|
| 267 |
+
@staticmethod
|
| 268 |
+
CResult[CHdfsOptions] FromUriString "FromUri"(
|
| 269 |
+
const c_string& uri_string)
|
| 270 |
+
void ConfigureEndPoint(c_string host, int port)
|
| 271 |
+
void ConfigureDriver(c_bool use_hdfs3)
|
| 272 |
+
void ConfigureReplication(int16_t replication)
|
| 273 |
+
void ConfigureUser(c_string user_name)
|
| 274 |
+
void ConfigureBufferSize(int32_t buffer_size)
|
| 275 |
+
void ConfigureBlockSize(int64_t default_block_size)
|
| 276 |
+
void ConfigureKerberosTicketCachePath(c_string path)
|
| 277 |
+
void ConfigureExtraConf(c_string key, c_string value)
|
| 278 |
+
|
| 279 |
+
cdef cppclass CHadoopFileSystem "arrow::fs::HadoopFileSystem"(CFileSystem):
|
| 280 |
+
@staticmethod
|
| 281 |
+
CResult[shared_ptr[CHadoopFileSystem]] Make(
|
| 282 |
+
const CHdfsOptions& options)
|
| 283 |
+
CHdfsOptions options()
|
| 284 |
+
|
| 285 |
+
cdef cppclass CMockFileSystem "arrow::fs::internal::MockFileSystem"(
|
| 286 |
+
CFileSystem):
|
| 287 |
+
CMockFileSystem(CTimePoint current_time)
|
| 288 |
+
|
| 289 |
+
CStatus CCopyFiles "arrow::fs::CopyFiles"(
|
| 290 |
+
const vector[CFileLocator]& sources,
|
| 291 |
+
const vector[CFileLocator]& destinations,
|
| 292 |
+
const CIOContext& io_context,
|
| 293 |
+
int64_t chunk_size, c_bool use_threads)
|
| 294 |
+
CStatus CCopyFilesWithSelector "arrow::fs::CopyFiles"(
|
| 295 |
+
const shared_ptr[CFileSystem]& source_fs,
|
| 296 |
+
const CFileSelector& source_sel,
|
| 297 |
+
const shared_ptr[CFileSystem]& destination_fs,
|
| 298 |
+
const c_string& destination_base_dir,
|
| 299 |
+
const CIOContext& io_context,
|
| 300 |
+
int64_t chunk_size, c_bool use_threads)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
# Callbacks for implementing Python filesystems
|
| 304 |
+
# Use typedef to emulate syntax for std::function<void(..)>
|
| 305 |
+
ctypedef void CallbackGetTypeName(object, c_string*)
|
| 306 |
+
ctypedef c_bool CallbackEquals(object, const CFileSystem&)
|
| 307 |
+
|
| 308 |
+
ctypedef void CallbackGetFileInfo(object, const c_string&, CFileInfo*)
|
| 309 |
+
ctypedef void CallbackGetFileInfoVector(object, const vector[c_string]&,
|
| 310 |
+
vector[CFileInfo]*)
|
| 311 |
+
ctypedef void CallbackGetFileInfoSelector(object, const CFileSelector&,
|
| 312 |
+
vector[CFileInfo]*)
|
| 313 |
+
ctypedef void CallbackCreateDir(object, const c_string&, c_bool)
|
| 314 |
+
ctypedef void CallbackDeleteDir(object, const c_string&)
|
| 315 |
+
ctypedef void CallbackDeleteDirContents(object, const c_string&, c_bool)
|
| 316 |
+
ctypedef void CallbackDeleteRootDirContents(object)
|
| 317 |
+
ctypedef void CallbackDeleteFile(object, const c_string&)
|
| 318 |
+
ctypedef void CallbackMove(object, const c_string&, const c_string&)
|
| 319 |
+
ctypedef void CallbackCopyFile(object, const c_string&, const c_string&)
|
| 320 |
+
|
| 321 |
+
ctypedef void CallbackOpenInputStream(object, const c_string&,
|
| 322 |
+
shared_ptr[CInputStream]*)
|
| 323 |
+
ctypedef void CallbackOpenInputFile(object, const c_string&,
|
| 324 |
+
shared_ptr[CRandomAccessFile]*)
|
| 325 |
+
ctypedef void CallbackOpenOutputStream(
|
| 326 |
+
object, const c_string&, const shared_ptr[const CKeyValueMetadata]&,
|
| 327 |
+
shared_ptr[COutputStream]*)
|
| 328 |
+
ctypedef void CallbackNormalizePath(object, const c_string&, c_string*)
|
| 329 |
+
|
| 330 |
+
cdef extern from "arrow/python/filesystem.h" namespace "arrow::py::fs" nogil:
|
| 331 |
+
|
| 332 |
+
cdef cppclass CPyFileSystemVtable "arrow::py::fs::PyFileSystemVtable":
|
| 333 |
+
PyFileSystemVtable()
|
| 334 |
+
function[CallbackGetTypeName] get_type_name
|
| 335 |
+
function[CallbackEquals] equals
|
| 336 |
+
function[CallbackGetFileInfo] get_file_info
|
| 337 |
+
function[CallbackGetFileInfoVector] get_file_info_vector
|
| 338 |
+
function[CallbackGetFileInfoSelector] get_file_info_selector
|
| 339 |
+
function[CallbackCreateDir] create_dir
|
| 340 |
+
function[CallbackDeleteDir] delete_dir
|
| 341 |
+
function[CallbackDeleteDirContents] delete_dir_contents
|
| 342 |
+
function[CallbackDeleteRootDirContents] delete_root_dir_contents
|
| 343 |
+
function[CallbackDeleteFile] delete_file
|
| 344 |
+
function[CallbackMove] move
|
| 345 |
+
function[CallbackCopyFile] copy_file
|
| 346 |
+
function[CallbackOpenInputStream] open_input_stream
|
| 347 |
+
function[CallbackOpenInputFile] open_input_file
|
| 348 |
+
function[CallbackOpenOutputStream] open_output_stream
|
| 349 |
+
function[CallbackOpenOutputStream] open_append_stream
|
| 350 |
+
function[CallbackNormalizePath] normalize_path
|
| 351 |
+
|
| 352 |
+
cdef cppclass CPyFileSystem "arrow::py::fs::PyFileSystem":
|
| 353 |
+
@staticmethod
|
| 354 |
+
shared_ptr[CPyFileSystem] Make(object handler,
|
| 355 |
+
CPyFileSystemVtable vtable)
|
| 356 |
+
|
| 357 |
+
PyObject* handler()
|
vllm/lib/python3.10/site-packages/pyarrow/includes/libarrow_substrait.pxd
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
|
| 20 |
+
from libcpp.vector cimport vector as std_vector
|
| 21 |
+
|
| 22 |
+
from pyarrow.includes.common cimport *
|
| 23 |
+
from pyarrow.includes.libarrow cimport *
|
| 24 |
+
from pyarrow.includes.libarrow_acero cimport *
|
| 25 |
+
|
| 26 |
+
ctypedef CResult[CDeclaration] CNamedTableProvider(const std_vector[c_string]&, const CSchema&)
|
| 27 |
+
|
| 28 |
+
cdef extern from "arrow/engine/substrait/options.h" namespace "arrow::engine" nogil:
|
| 29 |
+
cdef enum ConversionStrictness \
|
| 30 |
+
"arrow::engine::ConversionStrictness":
|
| 31 |
+
EXACT_ROUNDTRIP \
|
| 32 |
+
"arrow::engine::ConversionStrictness::EXACT_ROUNDTRIP"
|
| 33 |
+
PRESERVE_STRUCTURE \
|
| 34 |
+
"arrow::engine::ConversionStrictness::PRESERVE_STRUCTURE"
|
| 35 |
+
BEST_EFFORT \
|
| 36 |
+
"arrow::engine::ConversionStrictness::BEST_EFFORT"
|
| 37 |
+
|
| 38 |
+
cdef cppclass CConversionOptions \
|
| 39 |
+
"arrow::engine::ConversionOptions":
|
| 40 |
+
CConversionOptions()
|
| 41 |
+
ConversionStrictness strictness
|
| 42 |
+
function[CNamedTableProvider] named_table_provider
|
| 43 |
+
c_bool allow_arrow_extensions
|
| 44 |
+
|
| 45 |
+
cdef extern from "arrow/engine/substrait/extension_set.h" \
|
| 46 |
+
namespace "arrow::engine" nogil:
|
| 47 |
+
|
| 48 |
+
cdef cppclass ExtensionIdRegistry:
|
| 49 |
+
std_vector[c_string] GetSupportedSubstraitFunctions()
|
| 50 |
+
|
| 51 |
+
ExtensionIdRegistry* default_extension_id_registry()
|
| 52 |
+
|
| 53 |
+
cdef extern from "arrow/engine/substrait/relation.h" namespace "arrow::engine" nogil:
|
| 54 |
+
|
| 55 |
+
cdef cppclass CNamedExpression "arrow::engine::NamedExpression":
|
| 56 |
+
CExpression expression
|
| 57 |
+
c_string name
|
| 58 |
+
|
| 59 |
+
cdef cppclass CBoundExpressions "arrow::engine::BoundExpressions":
|
| 60 |
+
std_vector[CNamedExpression] named_expressions
|
| 61 |
+
shared_ptr[CSchema] schema
|
| 62 |
+
|
| 63 |
+
cdef extern from "arrow/engine/substrait/serde.h" namespace "arrow::engine" nogil:
|
| 64 |
+
|
| 65 |
+
CResult[shared_ptr[CBuffer]] SerializeExpressions(
|
| 66 |
+
const CBoundExpressions& bound_expressions, const CConversionOptions& conversion_options)
|
| 67 |
+
|
| 68 |
+
CResult[CBoundExpressions] DeserializeExpressions(
|
| 69 |
+
const CBuffer& serialized_expressions)
|
| 70 |
+
|
| 71 |
+
cdef extern from "arrow/engine/substrait/util.h" namespace "arrow::engine" nogil:
|
| 72 |
+
CResult[shared_ptr[CRecordBatchReader]] ExecuteSerializedPlan(
|
| 73 |
+
const CBuffer& substrait_buffer, const ExtensionIdRegistry* registry,
|
| 74 |
+
CFunctionRegistry* func_registry, const CConversionOptions& conversion_options,
|
| 75 |
+
c_bool use_threads)
|
| 76 |
+
|
| 77 |
+
CResult[shared_ptr[CBuffer]] SerializeJsonPlan(const c_string& substrait_json)
|
vllm/lib/python3.10/site-packages/pyarrow/includes/libgandiva.pxd
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# distutils: language = c++
|
| 19 |
+
|
| 20 |
+
from libcpp.string cimport string as c_string
|
| 21 |
+
from libcpp.unordered_set cimport unordered_set as c_unordered_set
|
| 22 |
+
from libc.stdint cimport int64_t, int32_t, uint8_t, uintptr_t
|
| 23 |
+
|
| 24 |
+
from pyarrow.includes.common cimport *
|
| 25 |
+
from pyarrow.includes.libarrow cimport *
|
| 26 |
+
|
| 27 |
+
cdef extern from "gandiva/node.h" namespace "gandiva" nogil:
|
| 28 |
+
|
| 29 |
+
cdef cppclass CNode" gandiva::Node":
|
| 30 |
+
c_string ToString()
|
| 31 |
+
shared_ptr[CDataType] return_type()
|
| 32 |
+
|
| 33 |
+
cdef cppclass CGandivaExpression" gandiva::Expression":
|
| 34 |
+
c_string ToString()
|
| 35 |
+
shared_ptr[CNode] root()
|
| 36 |
+
shared_ptr[CField] result()
|
| 37 |
+
|
| 38 |
+
ctypedef vector[shared_ptr[CNode]] CNodeVector" gandiva::NodeVector"
|
| 39 |
+
|
| 40 |
+
ctypedef vector[shared_ptr[CGandivaExpression]] \
|
| 41 |
+
CExpressionVector" gandiva::ExpressionVector"
|
| 42 |
+
|
| 43 |
+
cdef extern from "gandiva/selection_vector.h" namespace "gandiva" nogil:
|
| 44 |
+
|
| 45 |
+
cdef cppclass CSelectionVector" gandiva::SelectionVector":
|
| 46 |
+
|
| 47 |
+
shared_ptr[CArray] ToArray()
|
| 48 |
+
|
| 49 |
+
enum CSelectionVector_Mode" gandiva::SelectionVector::Mode":
|
| 50 |
+
CSelectionVector_Mode_NONE" gandiva::SelectionVector::Mode::MODE_NONE"
|
| 51 |
+
CSelectionVector_Mode_UINT16" \
|
| 52 |
+
gandiva::SelectionVector::Mode::MODE_UINT16"
|
| 53 |
+
CSelectionVector_Mode_UINT32" \
|
| 54 |
+
gandiva::SelectionVector::Mode::MODE_UINT32"
|
| 55 |
+
CSelectionVector_Mode_UINT64" \
|
| 56 |
+
gandiva::SelectionVector::Mode::MODE_UINT64"
|
| 57 |
+
|
| 58 |
+
cdef CStatus SelectionVector_MakeInt16\
|
| 59 |
+
"gandiva::SelectionVector::MakeInt16"(
|
| 60 |
+
int64_t max_slots, CMemoryPool* pool,
|
| 61 |
+
shared_ptr[CSelectionVector]* selection_vector)
|
| 62 |
+
|
| 63 |
+
cdef CStatus SelectionVector_MakeInt32\
|
| 64 |
+
"gandiva::SelectionVector::MakeInt32"(
|
| 65 |
+
int64_t max_slots, CMemoryPool* pool,
|
| 66 |
+
shared_ptr[CSelectionVector]* selection_vector)
|
| 67 |
+
|
| 68 |
+
cdef CStatus SelectionVector_MakeInt64\
|
| 69 |
+
"gandiva::SelectionVector::MakeInt64"(
|
| 70 |
+
int64_t max_slots, CMemoryPool* pool,
|
| 71 |
+
shared_ptr[CSelectionVector]* selection_vector)
|
| 72 |
+
|
| 73 |
+
cdef inline CSelectionVector_Mode _ensure_selection_mode(str name) except *:
|
| 74 |
+
uppercase = name.upper()
|
| 75 |
+
if uppercase == 'NONE':
|
| 76 |
+
return CSelectionVector_Mode_NONE
|
| 77 |
+
elif uppercase == 'UINT16':
|
| 78 |
+
return CSelectionVector_Mode_UINT16
|
| 79 |
+
elif uppercase == 'UINT32':
|
| 80 |
+
return CSelectionVector_Mode_UINT32
|
| 81 |
+
elif uppercase == 'UINT64':
|
| 82 |
+
return CSelectionVector_Mode_UINT64
|
| 83 |
+
else:
|
| 84 |
+
raise ValueError('Invalid value for Selection Mode: {!r}'.format(name))
|
| 85 |
+
|
| 86 |
+
cdef inline str _selection_mode_name(CSelectionVector_Mode ctype):
|
| 87 |
+
if ctype == CSelectionVector_Mode_NONE:
|
| 88 |
+
return 'NONE'
|
| 89 |
+
elif ctype == CSelectionVector_Mode_UINT16:
|
| 90 |
+
return 'UINT16'
|
| 91 |
+
elif ctype == CSelectionVector_Mode_UINT32:
|
| 92 |
+
return 'UINT32'
|
| 93 |
+
elif ctype == CSelectionVector_Mode_UINT64:
|
| 94 |
+
return 'UINT64'
|
| 95 |
+
else:
|
| 96 |
+
raise RuntimeError('Unexpected CSelectionVector_Mode value')
|
| 97 |
+
|
| 98 |
+
cdef extern from "gandiva/condition.h" namespace "gandiva" nogil:
|
| 99 |
+
|
| 100 |
+
cdef cppclass CCondition" gandiva::Condition":
|
| 101 |
+
c_string ToString()
|
| 102 |
+
shared_ptr[CNode] root()
|
| 103 |
+
shared_ptr[CField] result()
|
| 104 |
+
|
| 105 |
+
cdef extern from "gandiva/arrow.h" namespace "gandiva" nogil:
|
| 106 |
+
|
| 107 |
+
ctypedef vector[shared_ptr[CArray]] CArrayVector" gandiva::ArrayVector"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
cdef extern from "gandiva/tree_expr_builder.h" namespace "gandiva" nogil:
|
| 111 |
+
|
| 112 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeBoolLiteral \
|
| 113 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(c_bool value)
|
| 114 |
+
|
| 115 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeUInt8Literal \
|
| 116 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(uint8_t value)
|
| 117 |
+
|
| 118 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeUInt16Literal \
|
| 119 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(uint16_t value)
|
| 120 |
+
|
| 121 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeUInt32Literal \
|
| 122 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(uint32_t value)
|
| 123 |
+
|
| 124 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeUInt64Literal \
|
| 125 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(uint64_t value)
|
| 126 |
+
|
| 127 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInt8Literal \
|
| 128 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(int8_t value)
|
| 129 |
+
|
| 130 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInt16Literal \
|
| 131 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(int16_t value)
|
| 132 |
+
|
| 133 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInt32Literal \
|
| 134 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(int32_t value)
|
| 135 |
+
|
| 136 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInt64Literal \
|
| 137 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(int64_t value)
|
| 138 |
+
|
| 139 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeFloatLiteral \
|
| 140 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(float value)
|
| 141 |
+
|
| 142 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeDoubleLiteral \
|
| 143 |
+
"gandiva::TreeExprBuilder::MakeLiteral"(double value)
|
| 144 |
+
|
| 145 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeStringLiteral \
|
| 146 |
+
"gandiva::TreeExprBuilder::MakeStringLiteral"(const c_string& value)
|
| 147 |
+
|
| 148 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeBinaryLiteral \
|
| 149 |
+
"gandiva::TreeExprBuilder::MakeBinaryLiteral"(const c_string& value)
|
| 150 |
+
|
| 151 |
+
cdef shared_ptr[CGandivaExpression] TreeExprBuilder_MakeExpression\
|
| 152 |
+
"gandiva::TreeExprBuilder::MakeExpression"(
|
| 153 |
+
shared_ptr[CNode] root_node, shared_ptr[CField] result_field)
|
| 154 |
+
|
| 155 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeFunction \
|
| 156 |
+
"gandiva::TreeExprBuilder::MakeFunction"(
|
| 157 |
+
const c_string& name, const CNodeVector& children,
|
| 158 |
+
shared_ptr[CDataType] return_type)
|
| 159 |
+
|
| 160 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeField \
|
| 161 |
+
"gandiva::TreeExprBuilder::MakeField"(shared_ptr[CField] field)
|
| 162 |
+
|
| 163 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeIf \
|
| 164 |
+
"gandiva::TreeExprBuilder::MakeIf"(
|
| 165 |
+
shared_ptr[CNode] condition, shared_ptr[CNode] this_node,
|
| 166 |
+
shared_ptr[CNode] else_node, shared_ptr[CDataType] return_type)
|
| 167 |
+
|
| 168 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeAnd \
|
| 169 |
+
"gandiva::TreeExprBuilder::MakeAnd"(const CNodeVector& children)
|
| 170 |
+
|
| 171 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeOr \
|
| 172 |
+
"gandiva::TreeExprBuilder::MakeOr"(const CNodeVector& children)
|
| 173 |
+
|
| 174 |
+
cdef shared_ptr[CCondition] TreeExprBuilder_MakeCondition \
|
| 175 |
+
"gandiva::TreeExprBuilder::MakeCondition"(
|
| 176 |
+
shared_ptr[CNode] condition)
|
| 177 |
+
|
| 178 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInExpressionInt32 \
|
| 179 |
+
"gandiva::TreeExprBuilder::MakeInExpressionInt32"(
|
| 180 |
+
shared_ptr[CNode] node, const c_unordered_set[int32_t]& values)
|
| 181 |
+
|
| 182 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInExpressionInt64 \
|
| 183 |
+
"gandiva::TreeExprBuilder::MakeInExpressionInt64"(
|
| 184 |
+
shared_ptr[CNode] node, const c_unordered_set[int64_t]& values)
|
| 185 |
+
|
| 186 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInExpressionTime32 \
|
| 187 |
+
"gandiva::TreeExprBuilder::MakeInExpressionTime32"(
|
| 188 |
+
shared_ptr[CNode] node, const c_unordered_set[int32_t]& values)
|
| 189 |
+
|
| 190 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInExpressionTime64 \
|
| 191 |
+
"gandiva::TreeExprBuilder::MakeInExpressionTime64"(
|
| 192 |
+
shared_ptr[CNode] node, const c_unordered_set[int64_t]& values)
|
| 193 |
+
|
| 194 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInExpressionDate32 \
|
| 195 |
+
"gandiva::TreeExprBuilder::MakeInExpressionDate32"(
|
| 196 |
+
shared_ptr[CNode] node, const c_unordered_set[int32_t]& values)
|
| 197 |
+
|
| 198 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInExpressionDate64 \
|
| 199 |
+
"gandiva::TreeExprBuilder::MakeInExpressionDate64"(
|
| 200 |
+
shared_ptr[CNode] node, const c_unordered_set[int64_t]& values)
|
| 201 |
+
|
| 202 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInExpressionTimeStamp \
|
| 203 |
+
"gandiva::TreeExprBuilder::MakeInExpressionTimeStamp"(
|
| 204 |
+
shared_ptr[CNode] node, const c_unordered_set[int64_t]& values)
|
| 205 |
+
|
| 206 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInExpressionString \
|
| 207 |
+
"gandiva::TreeExprBuilder::MakeInExpressionString"(
|
| 208 |
+
shared_ptr[CNode] node, const c_unordered_set[c_string]& values)
|
| 209 |
+
|
| 210 |
+
cdef shared_ptr[CNode] TreeExprBuilder_MakeInExpressionBinary \
|
| 211 |
+
"gandiva::TreeExprBuilder::MakeInExpressionBinary"(
|
| 212 |
+
shared_ptr[CNode] node, const c_unordered_set[c_string]& values)
|
| 213 |
+
|
| 214 |
+
cdef extern from "gandiva/projector.h" namespace "gandiva" nogil:
|
| 215 |
+
|
| 216 |
+
cdef cppclass CProjector" gandiva::Projector":
|
| 217 |
+
|
| 218 |
+
CStatus Evaluate(
|
| 219 |
+
const CRecordBatch& batch, CMemoryPool* pool,
|
| 220 |
+
const CArrayVector* output)
|
| 221 |
+
|
| 222 |
+
CStatus Evaluate(
|
| 223 |
+
const CRecordBatch& batch,
|
| 224 |
+
const CSelectionVector* selection,
|
| 225 |
+
CMemoryPool* pool,
|
| 226 |
+
const CArrayVector* output)
|
| 227 |
+
|
| 228 |
+
c_string DumpIR()
|
| 229 |
+
|
| 230 |
+
cdef CStatus Projector_Make \
|
| 231 |
+
"gandiva::Projector::Make"(
|
| 232 |
+
shared_ptr[CSchema] schema, const CExpressionVector& children,
|
| 233 |
+
shared_ptr[CProjector]* projector)
|
| 234 |
+
|
| 235 |
+
cdef CStatus Projector_Make \
|
| 236 |
+
"gandiva::Projector::Make"(
|
| 237 |
+
shared_ptr[CSchema] schema, const CExpressionVector& children,
|
| 238 |
+
CSelectionVector_Mode mode,
|
| 239 |
+
shared_ptr[CConfiguration] configuration,
|
| 240 |
+
shared_ptr[CProjector]* projector)
|
| 241 |
+
|
| 242 |
+
cdef extern from "gandiva/filter.h" namespace "gandiva" nogil:
|
| 243 |
+
|
| 244 |
+
cdef cppclass CFilter" gandiva::Filter":
|
| 245 |
+
|
| 246 |
+
CStatus Evaluate(
|
| 247 |
+
const CRecordBatch& batch,
|
| 248 |
+
shared_ptr[CSelectionVector] out_selection)
|
| 249 |
+
|
| 250 |
+
c_string DumpIR()
|
| 251 |
+
|
| 252 |
+
cdef CStatus Filter_Make \
|
| 253 |
+
"gandiva::Filter::Make"(
|
| 254 |
+
shared_ptr[CSchema] schema, shared_ptr[CCondition] condition,
|
| 255 |
+
shared_ptr[CConfiguration] configuration,
|
| 256 |
+
shared_ptr[CFilter]* filter)
|
| 257 |
+
|
| 258 |
+
cdef extern from "gandiva/function_signature.h" namespace "gandiva" nogil:
|
| 259 |
+
|
| 260 |
+
cdef cppclass CFunctionSignature" gandiva::FunctionSignature":
|
| 261 |
+
|
| 262 |
+
CFunctionSignature(const c_string& base_name,
|
| 263 |
+
vector[shared_ptr[CDataType]] param_types,
|
| 264 |
+
shared_ptr[CDataType] ret_type)
|
| 265 |
+
|
| 266 |
+
shared_ptr[CDataType] ret_type() const
|
| 267 |
+
|
| 268 |
+
const c_string& base_name() const
|
| 269 |
+
|
| 270 |
+
vector[shared_ptr[CDataType]] param_types() const
|
| 271 |
+
|
| 272 |
+
c_string ToString() const
|
| 273 |
+
|
| 274 |
+
cdef extern from "gandiva/expression_registry.h" namespace "gandiva" nogil:
|
| 275 |
+
|
| 276 |
+
cdef vector[shared_ptr[CFunctionSignature]] \
|
| 277 |
+
GetRegisteredFunctionSignatures()
|
| 278 |
+
|
| 279 |
+
cdef extern from "gandiva/configuration.h" namespace "gandiva" nogil:
|
| 280 |
+
|
| 281 |
+
cdef cppclass CConfiguration" gandiva::Configuration":
|
| 282 |
+
|
| 283 |
+
CConfiguration()
|
| 284 |
+
|
| 285 |
+
CConfiguration(bint optimize, bint dump_ir)
|
| 286 |
+
|
| 287 |
+
void set_optimize(bint optimize)
|
| 288 |
+
|
| 289 |
+
void set_dump_ir(bint dump_ir)
|
| 290 |
+
|
| 291 |
+
cdef cppclass CConfigurationBuilder \
|
| 292 |
+
" gandiva::ConfigurationBuilder":
|
| 293 |
+
@staticmethod
|
| 294 |
+
shared_ptr[CConfiguration] DefaultConfiguration()
|
| 295 |
+
|
| 296 |
+
CConfigurationBuilder()
|
| 297 |
+
|
| 298 |
+
shared_ptr[CConfiguration] build()
|