File size: 9,081 Bytes
2c3c408 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | import numpy as np
import tiledb
# Integer types supported by Python / System
_inttypes = (int, np.integer)
def _tiledb_datetime_extent(begin, end):
"""
Returns the integer extent of a datetime range.
:param begin: beginning of datetime range
:type begin: numpy.datetime64
:param end: end of datetime range
:type end: numpy.datetime64
:return: Extent of range, returned as an integer number of time units
:rtype: int
"""
extent = end - begin + 1
date_unit = np.datetime_data(extent.dtype)[0]
one = np.timedelta64(1, date_unit)
# Dividing a timedelta by 1 will convert the timedelta to an integer
return int(extent / one)
def index_as_tuple(idx):
"""Forces scalar index objects to a tuple representation"""
if isinstance(idx, tuple):
return idx
return (idx,)
def replace_ellipsis(ndim: int, idx: tuple):
"""
Replace indexing ellipsis object with slice objects to match the number
of dimensions.
"""
# count number of ellipsis
n_ellip = sum(1 for i in idx if i is Ellipsis)
if n_ellip > 1:
raise IndexError("an index can only have a single ellipsis ('...')")
elif n_ellip == 1:
n = len(idx)
if (n - 1) >= ndim:
# does nothing, strip it out
idx = tuple(i for i in idx if i is not Ellipsis)
else:
# locate where the ellipse is, count the number of items to left and right
# fill in whole dim slices up to th ndim of the array
left = idx.index(Ellipsis)
right = n - (left + 1)
new_idx = idx[:left] + ((slice(None),) * (ndim - (n - 1)))
if right:
new_idx += idx[-right:]
idx = new_idx
idx_ndim = len(idx)
if idx_ndim < ndim:
idx += (slice(None),) * (ndim - idx_ndim)
if len(idx) > ndim:
raise IndexError("too many indices for array")
return idx
def replace_scalars_slice(dom, idx: tuple):
"""Replace scalar indices with slice objects"""
new_idx, drop_axes = [], []
for i in range(dom.ndim):
dim = dom.dim(i)
dim_idx = idx[i]
if np.isscalar(dim_idx):
drop_axes.append(i)
if isinstance(dim_idx, _inttypes):
start = int(dim_idx)
if start < 0:
start += int(dim.domain[1]) + 1
stop = start + 1
else:
start = dim_idx
stop = dim_idx
new_idx.append(slice(start, stop, None))
else:
new_idx.append(dim_idx)
return tuple(new_idx), tuple(drop_axes)
def check_for_floats(selection):
"""
Check if a selection object contains floating point values
:param selection: selection object
:return: True if selection contains floating point values
:rtype: bool
"""
if isinstance(selection, float):
return True
if isinstance(selection, slice):
if isinstance(selection.start, float) or isinstance(selection.stop, float):
return True
elif isinstance(selection, tuple):
for s in selection:
if check_for_floats(s):
return True
return False
def index_domain_subarray(array, dom, idx: tuple):
"""
Return a numpy array representation of the tiledb subarray buffer
for a given domain and tuple of index slices
"""
ndim = dom.ndim
if len(idx) != ndim:
raise IndexError(
"number of indices does not match domain rank: "
"(got {!r}, expected: {!r})".format(len(idx), ndim)
)
subarray = list()
for r in range(ndim):
# extract lower and upper bounds for domain dimension extent
dim = dom.dim(r)
dim_dtype = dim.dtype
if array.mode == "r" and (
np.issubdtype(dim_dtype, np.str_) or np.issubdtype(dim_dtype, np.bytes_)
):
# NED can only be retrieved in read mode
ned = array.nonempty_domain()
(dim_lb, dim_ub) = ned[r] if ned else (None, None)
else:
(dim_lb, dim_ub) = dim.domain
dim_slice = idx[r]
if not isinstance(dim_slice, slice):
raise IndexError("invalid index type: {!r}".format(type(dim_slice)))
start, stop, step = dim_slice.start, dim_slice.stop, dim_slice.step
if np.issubdtype(dim_dtype, np.str_) or np.issubdtype(dim_dtype, np.bytes_):
if start is None or stop is None:
if start is None:
start = dim_lb
if stop is None:
stop = dim_ub
elif not isinstance(start, (str, bytes)) or not isinstance(
stop, (str, bytes)
):
raise tiledb.TileDBError(
f"Non-string range '({start},{stop})' provided for string dimension '{dim.name}'"
)
subarray.append((start, stop))
continue
if step and array.schema.sparse:
raise IndexError("steps are not supported for sparse arrays")
# Datetimes will be treated specially
is_datetime = dim_dtype.kind == "M"
# Promote to a common type
if start is not None and stop is not None:
if type(start) != type(stop):
promoted_dtype = np.promote_types(type(start), type(stop))
start = np.array(start, dtype=promoted_dtype, ndmin=1)[0]
stop = np.array(stop, dtype=promoted_dtype, ndmin=1)[0]
if start is not None:
if is_datetime and not isinstance(start, np.datetime64):
raise IndexError(
"cannot index datetime dimension with non-datetime interval"
)
# don't round / promote fp slices
if np.issubdtype(dim_dtype, np.integer):
if isinstance(start, (np.float32, np.float64)):
raise IndexError(
"cannot index integral domain dimension with floating point slice"
)
elif not isinstance(start, _inttypes):
raise IndexError(
"cannot index integral domain dimension with non-integral slice (dtype: {})".format(
type(start)
)
)
# apply negative indexing (wrap-around semantics)
if not is_datetime and start < 0:
start += int(dim_ub) + 1
if start < dim_lb:
# numpy allows start value < the array dimension shape,
# clamp to lower bound of dimension domain
# start = dim_lb
raise IndexError("index out of bounds <todo>")
else:
start = dim_lb
if stop is not None:
if is_datetime and not isinstance(stop, np.datetime64):
raise IndexError(
"cannot index datetime dimension with non-datetime interval"
)
# don't round / promote fp slices
if np.issubdtype(dim_dtype, np.integer):
if isinstance(start, (np.float32, np.float64)):
raise IndexError(
"cannot index integral domain dimension with floating point slice"
)
elif not isinstance(start, _inttypes):
raise IndexError(
"cannot index integral domain dimension with non-integral slice (dtype: {})".format(
type(start)
)
)
if not is_datetime and stop < 0:
stop = np.int64(stop) + dim_ub
if stop > dim_ub:
# numpy allows stop value > than the array dimension shape,
# clamp to upper bound of dimension domain
if is_datetime:
stop = dim_ub
else:
stop = int(dim_ub) + 1
else:
if np.issubdtype(dim_dtype, np.floating) or is_datetime:
stop = dim_ub
else:
stop = int(dim_ub) + 1
if np.issubdtype(type(stop), np.floating):
# inclusive bounds for floating point / datetime ranges
start = dim_dtype.type(start)
stop = dim_dtype.type(stop)
subarray.append((start, stop))
elif is_datetime:
# need to ensure that datetime ranges are in the units of dim_dtype
# so that add_range and output shapes work correctly
start = start.astype(dim_dtype)
stop = stop.astype(dim_dtype)
subarray.append((start, stop))
elif np.issubdtype(type(stop), np.integer):
# normal python indexing semantics
subarray.append((start, int(stop) - 1))
else:
raise IndexError(
"domain indexing is defined for integral and floating point values"
)
return subarray
|