#!python #cython: embedsignature=True #cython: auto_pickle=False from cpython.pycapsule cimport PyCapsule_GetPointer, PyCapsule_IsValid, PyCapsule_New from cpython.version cimport PY_MAJOR_VERSION from .domain_indexer import DomainIndexer include "common.pxi" include "indexing.pyx" include "libmetadata.pyx" import io import warnings import collections.abc from collections import OrderedDict from json import dumps as json_dumps, loads as json_loads from ._generated_version import version_tuple as tiledbpy_version from .cc import TileDBError from .ctx import Config, Ctx, default_ctx from .vfs import VFS from .sparse_array import SparseArrayImpl from .dense_array import DenseArrayImpl ############################################################################### # Numpy initialization code (critical) # ############################################################################### # https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.import_array np.import_array() ############################################################################### # Utility/setup # ############################################################################### # Use unified numpy printing np.set_printoptions(legacy="1.21" if np.lib.NumpyVersion(np.__version__) >= "1.22.0" else False) cdef tiledb_ctx_t* safe_ctx_ptr(object ctx): if ctx is None: raise TileDBError("internal error: invalid Ctx object") return PyCapsule_GetPointer(ctx.__capsule__(), "ctx") def version(): """Return the version of the linked ``libtiledb`` shared library :rtype: tuple :return: Semver version (major, minor, rev) """ cdef: int major = 0 int minor = 0 int rev = 0 tiledb_version(&major, &minor, &rev) return major, minor, rev # note: this function is cdef, so it must return a python object in order to # properly forward python exceptions raised within the function. See: # https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#error-return-values cdef dict get_query_fragment_info(tiledb_ctx_t* ctx_ptr, tiledb_query_t* query_ptr): cdef int rc = TILEDB_OK cdef uint32_t num_fragments cdef Py_ssize_t fragment_idx cdef const char* fragment_uri_ptr cdef unicode fragment_uri cdef uint64_t fragment_t1, fragment_t2 cdef dict result = dict() rc = tiledb_query_get_fragment_num(ctx_ptr, query_ptr, &num_fragments) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) if (num_fragments < 1): return result for fragment_idx in range(0, num_fragments): rc = tiledb_query_get_fragment_uri(ctx_ptr, query_ptr, fragment_idx, &fragment_uri_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) rc = tiledb_query_get_fragment_timestamp_range( ctx_ptr, query_ptr, fragment_idx, &fragment_t1, &fragment_t2) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) fragment_uri = fragment_uri_ptr.decode('UTF-8') result[fragment_uri] = (fragment_t1, fragment_t2) return result def _write_array_wrapper( object tiledb_array, object subarray, list coordinates, list buffer_names, list values, dict labels, dict nullmaps, bint issparse, ): cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(tiledb_array.ctx) cdef tiledb_array_t* array_ptr = (tiledb_array).ptr cdef dict fragment_info = (tiledb_array).last_fragment_info _write_array(ctx_ptr, array_ptr, tiledb_array, subarray, coordinates, buffer_names, values, labels, nullmaps, fragment_info, issparse) cdef _write_array( tiledb_ctx_t* ctx_ptr, tiledb_array_t* array_ptr, object tiledb_array, object subarray, list coordinates, list buffer_names, list values, dict labels, dict nullmaps, dict fragment_info, bint issparse, ): # used for buffer conversion (local import to avoid circularity) from .main import array_to_buffer cdef bint isfortran = False cdef Py_ssize_t nattr = len(buffer_names) cdef Py_ssize_t nlabel = len(labels) # Create arrays to hold buffer sizes cdef Py_ssize_t nbuffer = nattr + nlabel if issparse: nbuffer += tiledb_array.schema.ndim cdef np.ndarray buffer_sizes = np.zeros((nbuffer,), dtype=np.uint64) cdef np.ndarray buffer_offsets_sizes = np.zeros((nbuffer,), dtype=np.uint64) cdef np.ndarray nullmaps_sizes = np.zeros((nbuffer,), dtype=np.uint64) # Create lists for data and offset buffers output_values = list() output_offsets = list() # Set data and offset buffers for attributes for i in range(nattr): # if dtype is ASCII, ensure all characters are valid if tiledb_array.schema.attr(i).isascii: try: values[i] = np.asarray(values[i], dtype=np.bytes_) except Exception as exc: raise TileDBError(f'dtype of attr {tiledb_array.schema.attr(i).name} is "ascii" but attr_val contains invalid ASCII characters') attr = tiledb_array.schema.attr(i) if attr.isvar: try: if attr.isnullable: if(np.issubdtype(attr.dtype, np.str_) or np.issubdtype(attr.dtype, np.bytes_)): attr_val = np.array(["" if v is None else v for v in values[i]]) else: attr_val = np.nan_to_num(values[i]) else: attr_val = values[i] buffer, offsets = array_to_buffer(attr_val, True, False) except Exception as exc: raise type(exc)(f"Failed to convert buffer for attribute: '{attr.name}'") from exc buffer_offsets_sizes[i] = offsets.nbytes else: buffer, offsets = values[i], None buffer_sizes[i] = buffer.nbytes output_values.append(buffer) output_offsets.append(offsets) # Check value layouts if len(values) and nattr > 1: value = output_values[0] isfortran = value.ndim > 1 and value.flags.f_contiguous for value in values: if value.ndim > 1 and value.flags.f_contiguous and not isfortran: raise ValueError("mixed C and Fortran array layouts") # Set data and offsets buffers for dimensions (sparse arrays only) ibuffer = nattr if issparse: for dim_idx, coords in enumerate(coordinates): if tiledb_array.schema.domain.dim(dim_idx).isvar: buffer, offsets = array_to_buffer(coords, True, False) buffer_sizes[ibuffer] = buffer.nbytes buffer_offsets_sizes[ibuffer] = offsets.nbytes else: buffer, offsets = coords, None buffer_sizes[ibuffer] = buffer.nbytes output_values.append(buffer) output_offsets.append(offsets) name = tiledb_array.schema.domain.dim(dim_idx).name buffer_names.append(name) ibuffer = ibuffer + 1 for label_name, label_values in labels.items(): # Append buffer name buffer_names.append(label_name) # Get label data buffer and offsets buffer for the labels dim_label = tiledb_array.schema.dim_label(label_name) if dim_label.isvar: buffer, offsets = array_to_buffer(label_values, True, False) buffer_sizes[ibuffer] = buffer.nbytes buffer_offsets_sizes[ibuffer] = offsets.nbytes else: buffer, offsets = label_values, None buffer_sizes[ibuffer] = buffer.nbytes # Append the buffers output_values.append(buffer) output_offsets.append(offsets) ibuffer = ibuffer + 1 # Allocate the query cdef int rc = TILEDB_OK cdef tiledb_query_t* query_ptr = NULL rc = tiledb_query_alloc(ctx_ptr, array_ptr, TILEDB_WRITE, &query_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) # Set layout cdef tiledb_layout_t layout = ( TILEDB_UNORDERED if issparse else (TILEDB_COL_MAJOR if isfortran else TILEDB_ROW_MAJOR) ) rc = tiledb_query_set_layout(ctx_ptr, query_ptr, layout) if rc != TILEDB_OK: tiledb_query_free(&query_ptr) _raise_ctx_err(ctx_ptr, rc) # Create and set the subarray for the query (dense arrays only) cdef np.ndarray s_start cdef np.ndarray s_end cdef np.dtype dim_dtype = None cdef void* s_start_ptr = NULL cdef void* s_end_ptr = NULL cdef tiledb_subarray_t* subarray_ptr = NULL if not issparse: subarray_ptr = PyCapsule_GetPointer( subarray.__capsule__(), "subarray") # Set the subarray on the query rc = tiledb_query_set_subarray_t(ctx_ptr, query_ptr, subarray_ptr) if rc != TILEDB_OK: tiledb_query_free(&query_ptr) _raise_ctx_err(ctx_ptr, rc) # Set buffers on the query cdef bytes bname cdef void* buffer_ptr = NULL cdef uint64_t* offsets_buffer_ptr = NULL cdef uint8_t* nulmap_buffer_ptr = NULL cdef uint64_t* buffer_sizes_ptr = np.PyArray_DATA(buffer_sizes) cdef uint64_t* offsets_buffer_sizes_ptr = np.PyArray_DATA(buffer_offsets_sizes) cdef uint64_t* nullmaps_sizes_ptr = np.PyArray_DATA(nullmaps_sizes) try: for i, buffer_name in enumerate(buffer_names): # Get utf-8 version of the name for C-API calls bname = buffer_name.encode('UTF-8') # Set data buffer buffer_ptr = np.PyArray_DATA(output_values[i]) rc = tiledb_query_set_data_buffer( ctx_ptr, query_ptr, bname, buffer_ptr, &(buffer_sizes_ptr[i])) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) # Set offsets buffer if output_offsets[i] is not None: offsets_buffer_ptr = np.PyArray_DATA(output_offsets[i]) rc = tiledb_query_set_offsets_buffer( ctx_ptr, query_ptr, bname, offsets_buffer_ptr, &(offsets_buffer_sizes_ptr[i]) ) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) # Set validity buffer if buffer_name in nullmaps: # NOTE: validity map is owned *by the caller* nulmap = nullmaps[buffer_name] nullmaps_sizes[i] = len(nulmap) nulmap_buffer_ptr = np.PyArray_DATA(nulmap) rc = tiledb_query_set_validity_buffer( ctx_ptr, query_ptr, bname, nulmap_buffer_ptr, &(nullmaps_sizes_ptr[i]) ) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) with nogil: rc = tiledb_query_submit(ctx_ptr, query_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) rc = tiledb_query_finalize(ctx_ptr, query_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) if fragment_info is not False: assert(type(fragment_info) is dict) fragment_info.clear() fragment_info.update(get_query_fragment_info(ctx_ptr, query_ptr)) finally: tiledb_query_free(&query_ptr) return cdef _raise_tiledb_error(tiledb_error_t* err_ptr): cdef const char* err_msg_ptr = NULL ret = tiledb_error_message(err_ptr, &err_msg_ptr) if ret != TILEDB_OK: tiledb_error_free(&err_ptr) if ret == TILEDB_OOM: raise MemoryError() raise TileDBError("error retrieving error message") cdef unicode message_string try: message_string = err_msg_ptr.decode('UTF-8', 'strict') finally: tiledb_error_free(&err_ptr) raise TileDBError(message_string) cdef _raise_ctx_err(tiledb_ctx_t* ctx_ptr, int rc): if rc == TILEDB_OK: return if rc == TILEDB_OOM: raise MemoryError() cdef tiledb_error_t* err_ptr = NULL cdef int ret = tiledb_ctx_get_last_error(ctx_ptr, &err_ptr) if ret != TILEDB_OK: tiledb_error_free(&err_ptr) if ret == TILEDB_OOM: raise MemoryError() raise TileDBError("error retrieving error object from ctx") _raise_tiledb_error(err_ptr) cpdef check_error(object ctx, int rc): cdef tiledb_ctx_t* ctx_ptr = PyCapsule_GetPointer( ctx.__capsule__(), "ctx") _raise_ctx_err(ctx_ptr, rc) cpdef unicode ustring(object s): """Coerce a python object to a unicode string""" if type(s) is unicode: return s elif PY_MAJOR_VERSION < 3 and isinstance(s, bytes): return ( s).decode('ascii') elif isinstance(s, unicode): return unicode(s) raise TypeError( "ustring() must be a string or a bytes-like object" ", not {0!r}".format(type(s))) cdef bytes unicode_path(object path): """Returns a UTF-8 encoded byte representation of a given URI path string""" return ustring(path).encode('UTF-8') ############################################################################### # # # CLASS DEFINITIONS # # # ############################################################################### from .array import _tiledb_datetime_extent, index_as_tuple, replace_ellipsis, replace_scalars_slice, check_for_floats, index_domain_subarray # Wrapper class to allow returning a Python object so that exceptions work correctly # within preload_array cdef class ArrayPtr(object): cdef tiledb_array_t* ptr cdef ArrayPtr preload_array(uri, mode, key, timestamp, ctx=None): """Open array URI without constructing specific type of Array object (internal).""" if not ctx: ctx = default_ctx() # ctx cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(ctx) # uri cdef bytes buri = unicode_path(uri) cdef const char* uri_ptr = PyBytes_AS_STRING(buri) # mode cdef tiledb_query_type_t query_type = TILEDB_READ # key cdef bytes bkey cdef tiledb_encryption_type_t key_type = TILEDB_NO_ENCRYPTION cdef const char* key_ptr = NULL cdef unsigned int key_len = 0 # convert python mode string to a query type mode_to_query_type = { "r": TILEDB_READ, "w": TILEDB_WRITE, "m": TILEDB_MODIFY_EXCLUSIVE, "d": TILEDB_DELETE } if mode not in mode_to_query_type: raise ValueError("TileDB array mode must be 'r', 'w', 'm', or 'd'") query_type = mode_to_query_type[mode] # check the key, and convert the key to bytes if key is not None: if isinstance(key, str): bkey = key.encode('ascii') else: bkey = bytes(key) key_type = TILEDB_AES_256_GCM key_ptr = PyBytes_AS_STRING(bkey) #TODO: unsafe cast here ssize_t -> uint64_t key_len = PyBytes_GET_SIZE(bkey) cdef uint64_t ts_start = 0 cdef uint64_t ts_end = 0 cdef bint set_start = False, set_end = False if timestamp is not None: if isinstance(timestamp, tuple): if len(timestamp) != 2: raise ValueError("'timestamp' argument expects either int or tuple(start: int, end: int)") if timestamp[0] is not None: ts_start = timestamp[0] set_start = True if timestamp[1] is not None: ts_end = timestamp[1] set_end = True elif isinstance(timestamp, int): # handle the existing behavior for unary timestamp # which is equivalent to endpoint of the range ts_end = timestamp set_end = True else: raise TypeError("Unexpected argument type for 'timestamp' keyword argument") # allocate and then open the array cdef tiledb_array_t* array_ptr = NULL cdef int rc = TILEDB_OK rc = tiledb_array_alloc(ctx_ptr, uri_ptr, &array_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) cdef tiledb_config_t* config_ptr = NULL cdef tiledb_error_t* err_ptr = NULL if key is not None: rc = tiledb_config_alloc(&config_ptr, &err_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) rc = tiledb_config_set(config_ptr, "sm.encryption_type", "AES_256_GCM", &err_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) rc = tiledb_config_set(config_ptr, "sm.encryption_key", key_ptr, &err_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) try: # note: tiledb_array_set_config copies the config rc = tiledb_array_set_config(ctx_ptr, array_ptr, config_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) finally: tiledb_config_free(&config_ptr) try: if set_start: check_error(ctx, tiledb_array_set_open_timestamp_start(ctx_ptr, array_ptr, ts_start) ) if set_end: check_error(ctx, tiledb_array_set_open_timestamp_end(ctx_ptr, array_ptr, ts_end) ) except: tiledb_array_free(&array_ptr) raise with nogil: rc = tiledb_array_open(ctx_ptr, array_ptr, query_type) if rc != TILEDB_OK: tiledb_array_free(&array_ptr) _raise_ctx_err(ctx_ptr, rc) cdef ArrayPtr retval = ArrayPtr() retval.ptr = array_ptr return retval cdef class Array(object): """Base class for TileDB array objects. Defines common properties/functionality for the different array types. When an Array instance is initialized, the array is opened with the specified mode. :param str uri: URI of array to open :param str mode: (default 'r') Open the array object in read 'r', write 'w', or delete 'd' mode :param str key: (default None) If not None, encryption key to decrypt the array :param tuple timestamp: (default None) If int, open the array at a given TileDB timestamp. If tuple, open at the given start and end TileDB timestamps. :param str attr: (default None) open one attribute of the array; indexing a dense array will return a Numpy ndarray directly rather than a dictionary. :param Ctx ctx: TileDB context """ def __init__(self, uri, mode='r', key=None, timestamp=None, attr=None, ctx=None): if not ctx: ctx = default_ctx() # ctx cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(ctx) # array cdef ArrayPtr preload_ptr if not self._isopen: preload_ptr = preload_array(uri, mode, key, timestamp, ctx) self.ptr = preload_ptr.ptr assert self.ptr != NULL, "internal error: unexpected null tiledb_array_t pointer in Array.__init__" cdef tiledb_array_t* array_ptr = self.ptr cdef tiledb_array_schema_t* array_schema_ptr = NULL try: rc = TILEDB_OK with nogil: rc = tiledb_array_get_schema(ctx_ptr, array_ptr, &array_schema_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) from .array_schema import ArraySchema schema = ArraySchema.from_capsule(ctx, PyCapsule_New(array_schema_ptr, "schema", NULL)) except: tiledb_array_close(ctx_ptr, array_ptr) tiledb_array_free(&array_ptr) self.ptr = NULL raise # view on a single attribute if attr and not any(attr == schema.attr(i).name for i in range(schema.nattr)): tiledb_array_close(ctx_ptr, array_ptr) tiledb_array_free(&array_ptr) self.ptr = NULL raise KeyError("No attribute matching '{}'".format(attr)) else: self.view_attr = unicode(attr) if (attr is not None) else None self.ctx = ctx self.uri = unicode(uri) self.mode = unicode(mode) self.schema = schema self.key = key self.domain_index = DomainIndexer(self) self.pyquery = None self.last_fragment_info = dict() self.meta = Metadata(self) def __cinit__(self): self.ptr = NULL def __dealloc__(self): if self.ptr != NULL: tiledb_array_free(&self.ptr) def __capsule__(self): if self.ptr == NULL: raise TileDBError("internal error: cannot create capsule for uninitialized Ctx!") cdef const char* name = "ctx" cap = PyCapsule_New((self.ptr), name, NULL) return cap def __repr__(self): if self.isopen: return "Array(type={0}, uri={1!r}, mode={2}, ndim={3})"\ .format("Sparse" if self.schema.sparse else "Dense", self.uri, self.mode, self.schema.ndim) else: return "Array(uri={0!r}, mode=closed)" def _ctx_(self) -> Ctx: """ Get Ctx object associated with the array (internal). This method exists for serialization. :return: Ctx object used to open the array. :rtype: Ctx """ return self.ctx @classmethod def create(cls, uri, schema, key=None, overwrite=False, ctx=None): """Creates a TileDB Array at the given URI :param str uri: URI at which to create the new empty array. :param ArraySchema schema: Schema for the array :param str key: (default None) Encryption key to use for array :param bool overwrite: (default False) Overwrite the array if it already exists :param Ctx ctx: (default None) Optional TileDB Ctx used when creating the array, by default uses the ArraySchema's associated context (*not* necessarily ``tiledb.default_ctx``). """ if issubclass(cls, DenseArrayImpl) and schema.sparse: raise ValueError("Array.create `schema` argument must be a dense schema for DenseArray and subclasses") if issubclass(cls, SparseArrayImpl) and not schema.sparse: raise ValueError("Array.create `schema` argument must be a sparse schema for SparseArray and subclasses") cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(schema.ctx) cdef bytes buri = unicode_path(uri) cdef const char* uri_ptr = PyBytes_AS_STRING(buri) cdef tiledb_array_schema_t* schema_ptr = PyCapsule_GetPointer( schema.__capsule__(), "schema") cdef bytes bkey cdef tiledb_encryption_type_t key_type = TILEDB_NO_ENCRYPTION cdef const char* key_ptr = NULL cdef unsigned int key_len = 0 cdef tiledb_config_t* config_ptr = NULL cdef tiledb_error_t* err_ptr = NULL cdef int rc = TILEDB_OK if key is not None: if isinstance(key, str): bkey = key.encode('ascii') else: bkey = bytes(key) key_type = TILEDB_AES_256_GCM key_ptr = PyBytes_AS_STRING(bkey) #TODO: unsafe cast here ssize_t -> uint64_t key_len = PyBytes_GET_SIZE(bkey) rc = tiledb_config_alloc(&config_ptr, &err_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) rc = tiledb_config_set(config_ptr, "sm.encryption_type", "AES_256_GCM", &err_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) rc = tiledb_config_set(config_ptr, "sm.encryption_key", key_ptr, &err_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) rc = tiledb_ctx_alloc(config_ptr, &ctx_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) if overwrite: from .highlevel import object_type if object_type(uri) == "array": if uri.startswith("file://") or "://" not in uri: if VFS().remove_dir(uri) != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) else: raise TypeError("Cannot overwrite non-local array.") else: warnings.warn("Overwrite set, but array does not exist") if ctx is not None: if not isinstance(ctx, Ctx): raise TypeError("tiledb.Array.create() expected tiledb.Ctx " "object to argument ctx") ctx_ptr = safe_ctx_ptr(ctx) with nogil: rc = tiledb_array_create(ctx_ptr, uri_ptr, schema_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) return @staticmethod def load_typed(uri, mode='r', key=None, timestamp=None, attr=None, ctx=None): """Return a {Dense,Sparse}Array instance from a pre-opened Array (internal)""" if not ctx: ctx = default_ctx() cdef int32_t rc = TILEDB_OK cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(ctx) cdef tiledb_array_schema_t* schema_ptr = NULL cdef tiledb_array_type_t array_type cdef Array new_array cdef object new_array_typed # *** preload_array owns array_ptr until it returns *** # and will free array_ptr upon exception cdef ArrayPtr tmp_array = preload_array(uri, mode, key, timestamp, ctx) assert tmp_array.ptr != NULL, "Internal error, array loading return nullptr" cdef tiledb_array_t* array_ptr = tmp_array.ptr # *** now we own array_ptr -- free in the try..except clause *** try: rc = tiledb_array_get_schema(ctx_ptr, array_ptr, &schema_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) rc = tiledb_array_schema_get_array_type(ctx_ptr, schema_ptr, &array_type) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) tiledb_array_schema_free(&schema_ptr) from . import DenseArray, SparseArray if array_type == TILEDB_DENSE: new_array_typed = DenseArray.__new__(DenseArray) else: new_array_typed = SparseArray.__new__(SparseArray) except: tiledb_array_free(&array_ptr) raise # *** this assignment must happen outside the try block *** # *** because the array destructor will free array_ptr *** # note: must use the immediate form `(x).m()` here # do not assign a temporary Array object (new_array_typed).ptr = array_ptr (new_array_typed)._isopen = True # *** new_array_typed now owns array_ptr *** new_array_typed.__init__(uri, mode=mode, key=key, timestamp=timestamp, attr=attr, ctx=ctx) return new_array_typed def __enter__(self): """ The `__enter__` and `__exit__` methods allow TileDB arrays to be opened (and auto-closed) using `with tiledb.open(uri) as A:` syntax. """ return self def __exit__(self, exc_type, exc_val, exc_tb): """ The `__enter__` and `__exit__` methods allow TileDB arrays to be opened (and auto-closed) using `with tiledb.open(uri) as A:` syntax. """ self.close() def close(self): """Closes this array, flushing all buffered data.""" cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) cdef tiledb_array_t* array_ptr = self.ptr cdef int rc = TILEDB_OK with nogil: rc = tiledb_array_close(ctx_ptr, array_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) self.schema = None return def reopen(self, timestamp=None): """ Reopens this array. This is useful when the array is updated after it was opened. To sync-up with the updates, the user must either close the array and open again, or just use ``reopen()`` without closing. ``reopen`` will be generally faster than a close-then-open. """ cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) cdef tiledb_array_t* array_ptr = self.ptr cdef uint64_t _timestamp = 0 cdef int rc = TILEDB_OK if timestamp is not None: _timestamp = timestamp rc = tiledb_array_set_open_timestamp_start(ctx_ptr, array_ptr, _timestamp) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) with nogil: rc = tiledb_array_reopen(ctx_ptr, array_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) return @property def pyquery(self): return self.pyquery @pyquery.setter def pyquery(self, value): self.pyquery = value @property def meta(self): """ Return array metadata instance :rtype: tiledb.Metadata """ return self.meta @property def schema(self): """The :py:class:`ArraySchema` for this array.""" schema = self.schema if schema is None: raise TileDBError("Cannot access schema, array is closed") return schema @property def mode(self): """The mode this array was opened with.""" return self.mode @property def iswritable(self): """This array is currently opened as writable.""" return self.mode == 'w' @property def isopen(self): """True if this array is currently open.""" cdef int isopen = 0 cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) cdef tiledb_array_t* array_ptr = self.ptr cdef int rc = TILEDB_OK rc = tiledb_array_is_open(ctx_ptr, array_ptr, &isopen) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) return isopen == 1 @property def ndim(self): """The number of dimensions of this array.""" return self.schema.ndim @property def domain(self): """The :py:class:`Domain` of this array.""" return self.schema.domain @property def dtype(self): """The NumPy dtype of the specified attribute""" if self.view_attr is None and self.schema.nattr > 1: raise NotImplementedError("Multi-attribute does not have single dtype!") return self.schema.attr(0).dtype @property def shape(self): """The shape of this array.""" return self.schema.shape @property def nattr(self): """The number of attributes of this array.""" if self.view_attr: return 1 else: return self.schema.nattr @property def view_attr(self): """The view attribute of this array.""" return self.view_attr @property def timestamp_range(self): """Returns the timestamp range the array is opened at :rtype: tuple :returns: tiledb timestamp range at which point the array was opened """ cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) cdef tiledb_array_t* array_ptr = self.ptr cdef uint64_t timestamp_start = 0 cdef uint64_t timestamp_end = 0 cdef int rc = TILEDB_OK rc = tiledb_array_get_open_timestamp_start(ctx_ptr, array_ptr, ×tamp_start) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) rc = tiledb_array_get_open_timestamp_end(ctx_ptr, array_ptr, ×tamp_end) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) return (int(timestamp_start), int(timestamp_end)) @property def uri(self): """Returns the URI of the array""" return self.uri def subarray(self, selection, attrs=None, coords=False, order=None): raise NotImplementedError() def attr(self, key): """Returns an :py:class:`Attr` instance given an int index or string label :param key: attribute index (positional or associative) :type key: int or str :rtype: :py:class:`Attr` :return: The array attribute at index or with the given name (label) :raises TypeError: invalid key type""" return self.schema.attr(key) def dim(self, dim_id): """Returns a :py:class:`Dim` instance given a dim index or name :param key: attribute index (positional or associative) :type key: int or str :rtype: :py:class:`Attr` :return: The array attribute at index or with the given name (label) :raises TypeError: invalid key type""" return self.schema.domain.dim(dim_id) def enum(self, name): """ Return the Enumeration from the attribute name. :param name: attribute name :type key: str :rtype: `Enumeration` """ cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) cdef tiledb_array_t* array_ptr = self.ptr cdef bytes bname = unicode_path(name) cdef const char* name_ptr = PyBytes_AS_STRING(bname) cdef tiledb_enumeration_t* enum_ptr = NULL rc = tiledb_array_get_enumeration(ctx_ptr, array_ptr, name_ptr, &enum_ptr) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) from .enumeration import Enumeration return Enumeration.from_capsule(self.ctx, PyCapsule_New(enum_ptr, "enum", NULL)) def delete_fragments(self_or_uri, timestamp_start, timestamp_end, ctx=None): """ Delete a range of fragments from timestamp_start to timestamp_end. The array needs to be opened in 'm' mode as shown in the example below. :param timestamp_start: the first fragment to delete in the range :type timestamp_start: int :param timestamp_end: the last fragment to delete in the range :type timestamp_end: int **Example:** >>> import tiledb, tempfile, numpy as np >>> path = tempfile.mkdtemp() >>> with tiledb.from_numpy(path, np.zeros(4), timestamp=1) as A: ... pass >>> with tiledb.open(path, 'w', timestamp=2) as A: ... A[:] = np.ones(4, dtype=np.int64) >>> with tiledb.open(path, 'r') as A: ... A[:] array([1., 1., 1., 1.]) >>> tiledb.Array.delete_fragments(path, 2, 2) >>> with tiledb.open(path, 'r') as A: ... A[:] array([0., 0., 0., 0.]) """ cdef tiledb_ctx_t* ctx_ptr cdef tiledb_array_t* array_ptr cdef tiledb_query_t* query_ptr cdef bytes buri cdef int rc = TILEDB_OK if isinstance(self_or_uri, str): uri = self_or_uri if not ctx: ctx = default_ctx() ctx_ptr = safe_ctx_ptr(ctx) buri = uri.encode('UTF-8') rc = tiledb_array_delete_fragments_v2( ctx_ptr, buri, timestamp_start, timestamp_end ) else: # TODO: Make this method static and entirely remove the conditional. raise TypeError( "The `tiledb.Array.delete_fragments` instance method is deprecated and removed. Use the static method with the same name instead.") if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) @staticmethod def delete_array(uri, ctx=None): """ Delete the given array. :param str uri: The URI of the array :param Ctx ctx: TileDB context **Example:** >>> import tiledb, tempfile, numpy as np >>> path = tempfile.mkdtemp() >>> with tiledb.from_numpy(path, np.zeros(4), timestamp=1) as A: ... pass >>> tiledb.array_exists(path) True >>> tiledb.Array.delete_array(path) >>> tiledb.array_exists(path) False """ if not ctx: ctx = default_ctx() cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(ctx) cdef bytes buri = uri.encode('UTF-8') cdef int rc = TILEDB_OK rc = tiledb_array_delete(ctx_ptr, buri) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) def nonempty_domain(self): """Return the minimum bounding domain which encompasses nonempty values. :rtype: tuple(tuple(numpy scalar, numpy scalar), ...) :return: A list of (inclusive) domain extent tuples, that contain all nonempty cells """ cdef list results = list() dom = self.schema.domain cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) cdef tiledb_array_t* array_ptr = self.ptr cdef int rc = TILEDB_OK cdef uint32_t dim_idx cdef uint64_t start_size cdef uint64_t end_size cdef int32_t is_empty cdef np.ndarray start_buf cdef np.ndarray end_buf cdef void* start_buf_ptr cdef void* end_buf_ptr cdef np.dtype dim_dtype for dim_idx in range(dom.ndim): dim_dtype = dom.dim(dim_idx).dtype if np.issubdtype(dim_dtype, np.str_) or np.issubdtype(dim_dtype, np.bytes_): rc = tiledb_array_get_non_empty_domain_var_size_from_index( ctx_ptr, array_ptr, dim_idx, &start_size, &end_size, &is_empty) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) if is_empty: results.append((None, None)) continue buf_dtype = 'S' start_buf = np.empty(start_size, 'S' + str(start_size)) end_buf = np.empty(end_size, 'S' + str(end_size)) start_buf_ptr = np.PyArray_DATA(start_buf) end_buf_ptr = np.PyArray_DATA(end_buf) else: # this one is contiguous start_buf = np.empty(2, dim_dtype) start_buf_ptr = np.PyArray_DATA(start_buf) if np.issubdtype(dim_dtype, np.str_) or np.issubdtype(dim_dtype, np.bytes_): rc = tiledb_array_get_non_empty_domain_var_from_index( ctx_ptr, array_ptr, dim_idx, start_buf_ptr, end_buf_ptr, &is_empty ) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) if is_empty: return None if start_size > 0 and end_size > 0: results.append((start_buf.item(0), end_buf.item(0))) else: results.append((None, None)) else: rc = tiledb_array_get_non_empty_domain_from_index( ctx_ptr, array_ptr, dim_idx, start_buf_ptr, &is_empty ) if rc != TILEDB_OK: _raise_ctx_err(ctx_ptr, rc) if is_empty: return None res_x, res_y = start_buf.item(0), start_buf.item(1) if np.issubdtype(dim_dtype, np.datetime64): # Convert to np.datetime64 date_unit = np.datetime_data(dim_dtype)[0] res_x = np.datetime64(res_x, date_unit) res_y = np.datetime64(res_y, date_unit) results.append((res_x, res_y)) return tuple(results) def consolidate(self, config=None, key=None, fragment_uris=None, timestamp=None): """ Consolidates fragments of an array object for increased read performance. Overview: https://docs.tiledb.com/main/concepts/internal-mechanics/consolidation :param tiledb.Config config: The TileDB Config with consolidation parameters set :param key: (default None) encryption key to decrypt an encrypted array :type key: str or bytes :param fragment_uris: (default None) Consolidate the array using a list of fragment _names_ (note: the `__ts1_ts2_