File size: 10,569 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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | import io
import warnings
from typing import Any, Optional, Sequence, Union
import numpy as np
import tiledb.cc as lt
from .ctx import Ctx, CtxMixin
from .datatypes import DataType
from .filter import Filter, FilterList
class Attr(CtxMixin, lt.Attribute):
"""
Represents a TileDB attribute.
"""
def __init__(
self,
name: str = "",
dtype: np.dtype = np.float64,
fill: Any = None,
var: bool = None,
nullable: bool = False,
filters: Union[FilterList, Sequence[Filter]] = None,
enum_label: str = None,
ctx: Optional[Ctx] = None,
):
"""Class representing a TileDB array attribute.
:param name: Attribute name, empty if anonymous
:param dtype: Attribute value datatype
:param fill: Fill value for unset cells
:param var: Attribute is variable-length (automatic for byte/string types)
:param nullable: Attribute is nullable
:param filters: List of filters to apply
:param ctx: A TileDB Context
:raises TypeError: invalid dtype
:raises tiledb.TileDBError:
"""
dt = DataType.from_numpy(
np.dtype(dtype) if dtype not in ("ascii", "blob", "wkb", "wkt") else dtype
)
# ensure that all strings are var-length
if (var is None and dtype == "ascii") or np.issubdtype(dt.np_dtype, np.str_):
var = True
elif np.issubdtype(dt.np_dtype, np.bytes_):
if dt.np_dtype.itemsize > 0 and var:
warnings.warn(
f"Attr given `var=True` but `dtype` `{dtype}` is fixed; "
"setting `dtype=S0`. Hint: set `var=True` with `dtype=S0`, "
f"or `var=False`with `dtype={dtype}`",
DeprecationWarning,
)
elif dt.np_dtype.itemsize == 0 and dtype != "ascii":
if var is False:
warnings.warn(
"Attr given `var=False` but `dtype` `S0` is var-length; "
"setting `var=True` and `dtype=S0`. Hint: set `var=False` "
"with `dtype=S0`, or `var=False` with a fixed-width "
"string `dtype=S<n>` where is n>1",
DeprecationWarning,
)
var = True
super().__init__(ctx, name, dt.tiledb_type)
if var:
self._ncell = lt.TILEDB_VAR_NUM()
elif dt.ncells != lt.TILEDB_VAR_NUM():
self._ncell = dt.ncells
else:
raise TypeError("dtype is not compatible with var-length attribute")
if filters is not None:
if isinstance(filters, FilterList):
self._filters = filters
else:
self._filters = FilterList(filters)
if fill is not None:
if self._tiledb_dtype == lt.DataType.STRING_UTF8:
self._fill = np.array([fill.encode("utf-8")], dtype="S")
elif self.dtype == np.dtype("complex64") or self.dtype == np.dtype(
"complex128"
):
if hasattr(fill, "dtype") and fill.dtype in {
np.dtype("f4, f4"),
np.dtype("f8, f8"),
}:
_fill = fill["f0"] + fill["f1"] * 1j
elif hasattr(fill, "__len__") and len(fill) == 2:
_fill = fill[0] + fill[1] * 1j
else:
_fill = fill
self._fill = np.array(_fill, dtype=self.dtype)
else:
self._fill = np.array([fill], dtype=self.dtype)
if nullable is not None:
self._nullable = nullable
if enum_label is not None:
self._set_enumeration_name(self._ctx, enum_label)
def __eq__(self, other):
if not isinstance(other, Attr):
return False
if self.isnullable != other.isnullable or self.dtype != other.dtype:
return False
if not self.isnullable:
# Check the fill values are equal.
def equal_or_nan(x, y):
return x == y or (np.isnan(x) and np.isnan(y))
if self.ncells == 1:
if not equal_or_nan(self.fill, other.fill):
return False
elif np.issubdtype(self.dtype, np.bytes_) or np.issubdtype(
self.dtype, np.str_
):
if self.fill != other.fill:
return False
elif self.dtype in {np.dtype("complex64"), np.dtype("complex128")}:
if not (
equal_or_nan(np.real(self.fill), np.real(other.fill))
and equal_or_nan(np.imag(self.fill), np.imag(other.fill))
):
return False
else:
if not all(
equal_or_nan(x, y)
or (
isinstance(x, str)
and x.lower() == "nat"
and isinstance(y, str)
and y.lower() == "nat"
)
for x, y in zip(self.fill[0], other.fill[0])
):
return False
return (
self._internal_name == other._internal_name
and self.isvar == other.isvar
and self.filters == other.filters
)
def dump(self):
"""Dumps a string representation of the Attr object to standard output (stdout)"""
print(self._dump(), "\n")
@property
def dtype(self) -> np.dtype:
"""Return numpy dtype object representing the Attr type
:rtype: numpy.dtype
"""
return DataType.from_tiledb(self._tiledb_dtype, self._ncell).np_dtype
@property
def name(self) -> str:
"""Attribute string name, empty string if the attribute is anonymous
:rtype: str
:raises: :py:exc:`tiledb.TileDBError`
"""
internal_name = self._name
# handle __attr names from arrays written with libtiledb < 2
if internal_name == "__attr":
return ""
return internal_name
@property
def _internal_name(self):
return self._name
@property
def isanon(self) -> bool:
"""True if attribute is an anonymous attribute
:rtype: bool
"""
return self._name == "" or self._name.startswith("__attr")
@property
def filters(self) -> FilterList:
"""FilterList of the TileDB attribute
:rtype: tiledb.FilterList
:raises: :py:exc:`tiledb.TileDBError`
"""
return FilterList.from_pybind11(self._ctx, self._filters)
@property
def fill(self) -> Any:
"""Fill value for unset cells of this attribute
:rtype: depends on dtype
:raises: :py:exc:`tiledb.TileDBERror`
"""
dtype = self.dtype
if np.issubdtype(dtype, np.bytes_):
return self._fill.tobytes()
if np.issubdtype(dtype, np.str_):
return self._fill.tobytes().decode("utf-8")
if np.issubdtype(dtype, np.datetime64):
return self._fill[0].astype(np.timedelta64)
return self._fill
@property
def isnullable(self) -> bool:
"""True if the attribute is nullable
:rtype: bool
:raises: :py:exc:`tiledb.TileDBError`
"""
return self._nullable
@property
def isvar(self) -> bool:
"""True if the attribute is variable length
:rtype: bool
:raises: :py:exc:`tiledb.TileDBError`
"""
return self._var
@property
def ncells(self) -> int:
"""The number of cells (scalar values) for a given attribute value
:rtype: int
:raises: :py:exc:`tiledb.TileDBError`
"""
assert self._ncell != 0
return int(self._ncell)
@property
def isascii(self) -> bool:
"""True if the attribute is TileDB dtype TILEDB_STRING_ASCII
:rtype: bool
:raises: :py:exc:`tiledb.TileDBError`
"""
return self._tiledb_dtype == lt.DataType.STRING_ASCII
@property
def enum_label(self):
return self._get_enumeration_name(self._ctx)
def __repr__(self):
# use safe repr if pybind11 constructor failed
if self._ctx is None:
return object.__repr__(self)
filters_str = ""
if self.filters:
filters_str = ", filters=FilterList(["
for f in self.filters:
filters_str += repr(f) + ", "
filters_str += "])"
if self._tiledb_dtype == lt.DataType.STRING_ASCII:
attr_dtype = "ascii"
elif self._tiledb_dtype == lt.DataType.BLOB:
attr_dtype = "blob"
elif (
hasattr(lt.DataType, "GEOM_WKB")
and self._tiledb_dtype == lt.DataType.GEOM_WKB
):
attr_dtype = "wkb"
elif (
hasattr(lt.DataType, "GEOM_WKT")
and self._tiledb_dtype == lt.DataType.GEOM_WKT
):
attr_dtype = "wkt"
else:
attr_dtype = self.dtype
if self.enum_label is None:
enum_label = None
else:
enum_label = f"'{self.enum_label!s}'"
# filters_str must be last with no spaces
return (
f"""Attr(name={repr(self.name)}, dtype='{attr_dtype!s}', """
f"""var={self.isvar!s}, nullable={self.isnullable!s}, """
f"""enum_label={enum_label}{filters_str})"""
)
def _repr_html_(self):
output = io.StringIO()
output.write("<table>")
output.write("<tr>")
output.write("<th>Name</th>")
output.write("<th>Data Type</th>")
output.write("<th>Is Var-Len</th>")
output.write("<th>Is Nullable</th>")
output.write("<th>Filters</th>")
output.write("</tr>")
output.write(f"{self._repr_html_row_only_()}")
output.write("</table>")
return output.getvalue()
def _repr_html_row_only_(self):
output = io.StringIO()
output.write("<tr>")
output.write(f"<td>{self.name}</td>")
output.write(f"<td>{'ascii' if self.isascii else self.dtype}</td>")
output.write(f"<td>{self.isvar}</td>")
output.write(f"<td>{self.isnullable}</td>")
output.write(f"<td>{self.filters._repr_html_()}</td>")
output.write("</tr>")
return output.getvalue()
|