| 1 |
|
| 2 |
) |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
try: |
| 11 |
from collections.abc import Sequence, Iterable |
| 12 |
except ImportError: |
| 13 |
from collections import Sequence, Iterable |
| 14 |
from enum import Enum |
| 15 |
from numbers import Number |
| 16 |
import numpy as np |
| 17 |
|
| 18 |
from .datatype import DataType |
| 19 |
from .entity import Entity |
| 20 |
from . import util |
| 21 |
|
| •22 |
def ensure_str(s): |
| 23 |
if isinstance(s, bytes): |
| 24 |
return s.decode() |
| 25 |
else: |
| 26 |
return s |
| 27 |
|
| 28 |
|
| 29 |
class OdmlType(Enum): |
| 30 |
""" |
| 31 |
OdmlType provides all types currently supported by the odML |
| 32 |
data format. It provides additional information about the |
| 33 |
nature of the values of an odML Property. |
| 34 |
""" |
| 35 |
Boolean = 'boolean' |
| 36 |
Int = 'int' |
| 37 |
Float = 'float' |
| 38 |
String = 'string' |
| 39 |
Text = 'text' |
| 40 |
URL = 'url' |
| 41 |
Person = 'person' |
| 42 |
Datetime = 'datetime' |
| 43 |
Date = 'date' |
| 44 |
Time = 'time' |
| 45 |
|
| 46 |
def __str__(self): |
| 47 |
return self.value |
| 48 |
|
| 49 |
def compatible(self, value): |
| 50 |
""" |
| 51 |
compatible returns True or False depending on whether a |
| 52 |
passed value can be mapped to an OdmlType or not. |
| 53 |
|
| 54 |
:param value: Any single value |
| 55 |
:return: Boolean |
| 56 |
""" |
| 57 |
if (self in (self.String, self.Text, self.URL, self.Person) and |
| 58 |
DataType.get_dtype(value) == DataType.String): |
| 59 |
return True |
| 60 |
elif (self == self.Boolean and |
| 61 |
DataType.get_dtype(value) == DataType.Bool): |
| 62 |
return True |
| 63 |
elif (self == self.Float and |
| 64 |
DataType.get_dtype(value) == DataType.Double): |
| 65 |
return True |
| 66 |
elif self == self.Int and DataType.get_dtype(value) == DataType.Int64: |
| 67 |
return True |
| 68 |
elif (self in (self.Time, self.Date, self.Datetime) and |
| 69 |
DataType.get_dtype(value) == DataType.String): |
| 70 |
|
| 71 |
|
| 72 |
return True |
| 73 |
|
| 74 |
return False |
| 75 |
|
| 76 |
@classmethod |
| 77 |
def get_odml_type(cls, dtype): |
| 78 |
""" |
| 79 |
get_odml_type returns the appropriate OdmlType |
| 80 |
for a handed in nix value DataType. |
| 81 |
|
| 82 |
:param dtype: nix DataType |
| 83 |
:return: OdmlType |
| 84 |
""" |
| 85 |
if dtype in DataType.FloatTypes: |
| 86 |
return cls.Float |
| 87 |
elif dtype in DataType.IntTypes: |
| 88 |
return cls.Int |
| 89 |
elif dtype == DataType.String: |
| 90 |
return cls.String |
| 91 |
elif dtype == DataType.Bool: |
| 92 |
return cls.Boolean |
| 93 |
|
| 94 |
raise TypeError("No available OdmlType for type '%s'" % dtype) |
| 95 |
|
| 96 |
|
| 97 |
class Property(Entity): |
| 98 |
"""An odML Property""" |
| 99 |
def __init__(self, nixfile, nixparent, h5dataset): |
| 100 |
super(Property, self).__init__(nixfile, nixparent, h5dataset) |
| 101 |
self._h5dataset = self._h5group |
| 102 |
|
| 103 |
@classmethod |
| 104 |
def create_new(cls, nixfile, nixparent, h5parent, name, |
| 105 |
dtype, shape=None, oid=None): |
| 106 |
if shape is None or shape[0] == 0: |
| 107 |
shape = (8, ) |
| 108 |
util.check_entity_name(name) |
| 109 |
dtype = cls._make_h5_dtype(dtype) |
| 110 |
|
| 111 |
h5dataset = h5parent.create_dataset(name, shape=shape, dtype=dtype) |
| 112 |
h5dataset.set_attr("name", name) |
| 113 |
|
| 114 |
if not util.is_uuid(oid): |
| 115 |
oid = util.create_id() |
| 116 |
|
| 117 |
h5dataset.set_attr("entity_id", oid) |
| 118 |
|
| 119 |
newentity = cls(nixfile, nixparent, h5dataset) |
| 120 |
newentity.force_created_at() |
| 121 |
newentity.force_updated_at() |
| 122 |
|
| 123 |
return newentity |
| 124 |
|
| 125 |
@property |
| 126 |
def name(self): |
| 127 |
return self._h5dataset.get_attr("name") |
| 128 |
|
| 129 |
@property |
| 130 |
def definition(self): |
| 131 |
return self._h5dataset.get_attr("definition") |
| 132 |
|
| 133 |
@definition.setter |
| 134 |
def definition(self, d): |
| 135 |
util.check_attr_type(d, str) |
| 136 |
self._h5dataset.set_attr("definition", d) |
| 137 |
|
| 138 |
@property |
| 139 |
def unit(self): |
| 140 |
return self._h5dataset.get_attr("unit") |
| 141 |
|
| 142 |
@unit.setter |
| 143 |
def unit(self, new): |
| 144 |
if new: |
| 145 |
new = util.units.sanitizer(new) |
| 146 |
|
| 147 |
if new == "": |
| 148 |
new = None |
| 149 |
|
| 150 |
util.check_attr_type(new, str) |
| 151 |
self._h5dataset.set_attr("unit", new) |
| 152 |
|
| 153 |
@property |
| 154 |
def uncertainty(self): |
| 155 |
dataset = self._h5dataset |
| 156 |
filever = tuple(dataset._parent.file.attrs["version"]) |
| 157 |
if filever < (1, 1, 1): |
| 158 |
val = self._h5dataset.dataset[:] |
| 159 |
uncertainty = val[0]["uncertainty"] |
| 160 |
return uncertainty |
| 161 |
return self._h5dataset.get_attr("uncertainty") |
| 162 |
|
| 163 |
@uncertainty.setter |
| 164 |
def uncertainty(self, uncertainty): |
| 165 |
util.check_attr_type(uncertainty, Number) |
| 166 |
uncertainty = float(uncertainty) if uncertainty is not None else None |
| 167 |
self._h5dataset.set_attr("uncertainty", uncertainty) |
| 168 |
|
| 169 |
@property |
| 170 |
def reference(self): |
| 171 |
dataset = self._h5dataset |
| 172 |
filever = tuple(dataset._parent.file.attrs["version"]) |
| 173 |
if filever < (1, 1, 1): |
| 174 |
val = self._h5dataset.dataset[:] |
| 175 |
reference = val[0]["reference"] |
| 176 |
return reference |
| 177 |
return self._h5dataset.get_attr("reference") |
| 178 |
|
| 179 |
@reference.setter |
| 180 |
def reference(self, ref): |
| 181 |
util.check_attr_type(ref, str) |
| 182 |
self._h5dataset.set_attr("reference", ref) |
| 183 |
|
| 184 |
@property |
| 185 |
def dependency(self): |
| 186 |
return self._h5dataset.get_attr("dependency") |
| 187 |
|
| 188 |
@dependency.setter |
| 189 |
def dependency(self, dep): |
| 190 |
util.check_attr_type(dep, str) |
| 191 |
self._h5dataset.set_attr("dependency", dep) |
| 192 |
|
| 193 |
@property |
| 194 |
def dependency_value(self): |
| 195 |
return self._h5dataset.get_attr("dependency_value") |
| 196 |
|
| 197 |
@dependency_value.setter |
| 198 |
def dependency_value(self, depval): |
| 199 |
util.check_attr_type(depval, str) |
| 200 |
self._h5dataset.set_attr("dependency_value", depval) |
| 201 |
|
| 202 |
@property |
| 203 |
def value_origin(self): |
| 204 |
return self._h5dataset.get_attr("value_origin") |
| 205 |
|
| 206 |
@value_origin.setter |
| 207 |
def value_origin(self, origin): |
| 208 |
util.check_attr_type(origin, str) |
| 209 |
self._h5dataset.set_attr("value_origin", origin) |
| 210 |
|
| 211 |
@property |
| 212 |
def odml_type(self): |
| 213 |
otype = self._h5dataset.get_attr("odml_type") |
| 214 |
if not otype: |
| 215 |
return None |
| 216 |
|
| 217 |
return OdmlType(otype) |
| 218 |
|
| 219 |
@odml_type.setter |
| 220 |
def odml_type(self, new_type): |
| 221 |
""" |
| 222 |
odml_type can only be set if the handed in new type is a valid |
| 223 |
OdmlType and if it is compatible with the value data type of |
| 224 |
the property. |
| 225 |
|
| 226 |
:param new_type: OdmlType |
| 227 |
""" |
| 228 |
if not isinstance(new_type, OdmlType): |
| 229 |
raise TypeError("'{}' is not a valid odml_type.".format(new_type)) |
| 230 |
|
| 231 |
if not new_type.compatible(self.values[0]): |
| 232 |
raise TypeError("Type '{}' is incompatible " |
| 233 |
"with property values".format(new_type)) |
| 234 |
|
| 235 |
self._h5dataset.set_attr("odml_type", str(new_type)) |
| 236 |
|
| 237 |
def _read_old_values(self): |
| 238 |
val = self._h5dataset.dataset[:] |
| 239 |
if len(val) > 0 and isinstance(val[0]["value"], bytes): |
| 240 |
return tuple(ensure_str(v["value"]) for v in val) |
| 241 |
return tuple(v["value"] for v in val) |
| 242 |
|
| 243 |
@property |
| 244 |
def values(self): |
| 245 |
dataset = self._h5dataset |
| 246 |
filever = tuple(dataset._parent.file.attrs["version"]) |
| 247 |
if filever < (1, 1, 1): |
| 248 |
values = self._read_old_values() |
| 249 |
return values |
| 250 |
if not sum(dataset.shape): |
| 251 |
return tuple() |
| 252 |
|
| 253 |
data = dataset.read_data() |
| 254 |
|
| 255 |
def data_to_value(dat): |
| 256 |
if isinstance(dat, bytes): |
| •257 |
dat = dat.decode() |
| 258 |
return dat |
| 259 |
|
| 260 |
values = tuple(map(data_to_value, data)) |
| 261 |
|
| 262 |
return values |
| 263 |
|
| 264 |
@values.setter |
| 265 |
def values(self, vals): |
| 266 |
""" |
| 267 |
Set the value of the property discarding any previous information. |
| 268 |
|
| 269 |
:param vals: a single value or list of values. |
| 270 |
""" |
| 271 |
|
| 272 |
if vals is None or (isinstance(vals, (Sequence, Iterable)) and not len(vals)): |
| 273 |
self.delete_values() |
| 274 |
return |
| 275 |
|
| 276 |
if not isinstance(vals, (Sequence, Iterable)) or isinstance(vals, str): |
| 277 |
vals = [vals] |
| 278 |
|
| 279 |
|
| 280 |
vtype = self._check_new_value_types(vals) |
| 281 |
if vtype == DataType.String: |
| •282 |
vals = [str(v) for v in vals] |
| 283 |
self._h5dataset.shape = np.shape(vals) |
| 284 |
data = np.array(vals, dtype=vtype) |
| 285 |
self._h5dataset.write_data(data) |
| 286 |
|
| 287 |
def extend_values(self, data): |
| 288 |
""" |
| 289 |
Extends values to existing data. |
| 290 |
Suitable when new data is nested or original data is long. |
| 291 |
""" |
| 292 |
vtype = self._check_new_value_types(data) |
| 293 |
|
| 294 |
arr = np.array(data, dtype=vtype).flatten('C') |
| 295 |
dataset = self._h5dataset |
| 296 |
src_len = len(self.values) |
| 297 |
dlen = len(arr) |
| 298 |
dataset.shape = (src_len + dlen,) |
| 299 |
dataset.write_data(arr, slc=np.s_[src_len: src_len + dlen]) |
| 300 |
|
| 301 |
def _check_new_value_types(self, data): |
| 302 |
if isinstance(data, (Sequence, Iterable)) and not isinstance(data, str): |
| 303 |
single_val = data[0] |
| 304 |
else: |
| 305 |
single_val = data |
| 306 |
data = [data] |
| 307 |
|
| 308 |
def check_prop_consistent(vtype): |
| 309 |
|
| 310 |
|
| 311 |
if vtype != self.data_type: |
| 312 |
raise TypeError("New data type '{}' is inconsistent with the " |
| 313 |
"Property's data type '{}'".format( |
| 314 |
vtype, self.data_type)) |
| 315 |
|
| 316 |
def check_new_data_consistent(vtype): |
| 317 |
|
| 318 |
for val in data: |
| 319 |
if DataType.get_dtype(val) != vtype: |
| 320 |
raise TypeError("Array contains inconsistent values. " |
| 321 |
"Only values of type '{}' can be " |
| 322 |
"assigned".format(vtype)) |
| 323 |
|
| 324 |
if hasattr(data, "dtype"): |
| 325 |
|
| 326 |
|
| 327 |
vtype = data.dtype |
| 328 |
check_prop_consistent(vtype) |
| 329 |
else: |
| 330 |
|
| 331 |
|
| 332 |
vtype = DataType.get_dtype(single_val) |
| 333 |
check_prop_consistent(vtype) |
| 334 |
check_new_data_consistent(vtype) |
| 335 |
|
| 336 |
return vtype |
| 337 |
|
| 338 |
@property |
| 339 |
def data_type(self): |
| 340 |
return self._h5dataset.dtype |
| 341 |
|
| 342 |
def delete_values(self): |
| 343 |
self._h5dataset.shape = (0,) |
| 344 |
|
| 345 |
@staticmethod |
| 346 |
def _make_h5_dtype(valued_type): |
| 347 |
str_ = util.vlen_str_dtype |
| 348 |
|
| 349 |
if valued_type == DataType.String: |
| 350 |
valued_type = str_ |
| 351 |
|
| 352 |
return valued_type |
| 353 |
|
| 354 |
def __str__(self): |
| 355 |
return "{}: {{name = {}}}".format( |
| 356 |
type(self).__name__, self.name |
| 357 |
) |
| 358 |
|
| 359 |
def __repr__(self): |
| 360 |
return self.__str__() |
| 361 |
|
| 362 |
def pprint(self, indent=2, max_length=80, current_depth=-1): |
| 363 |
""" |
| 364 |
Pretty print method. Method is called in Section.pprint() |
| 365 |
""" |
| 366 |
property_spaces = "" |
| 367 |
prefix = "" |
| 368 |
if current_depth >= 0: |
| 369 |
property_spaces = " " * ((current_depth + 2) * indent) |
| 370 |
prefix = "|-" |
| 371 |
if self.unit is None: |
| 372 |
value_string = str(self.values) |
| 373 |
else: |
| 374 |
value_string = "{}{}".format(self.values, self.unit) |
| 375 |
p_len = len(property_spaces) + len(self.name) + len(value_string) |
| 376 |
if p_len >= max_length - 4: |
| 377 |
split_len = int((max_length - len(property_spaces) + |
| 378 |
len(self.name) - len(prefix)) / 2) |
| 379 |
str1 = value_string[0: split_len] |
| 380 |
str2 = value_string[-split_len:] |
| 381 |
print(("{}{} {}: {} ... {}".format(property_spaces, prefix, |
| 382 |
self.name, str1, str2))) |
| 383 |
else: |
| 384 |
print(("{}{} {}: {}".format(property_spaces, prefix, self.name, |
| 385 |
value_string))) |