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