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 ") 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