Debian Codegraph @

nixio/data_view.py

raw symbols SCIP
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 from numbers import Integral
10 try:
11 from collections.abc import Iterable
12 except ImportError:
13 from collections import Iterable
14 import numpy as np
15 from .data_set import DataSet
16 from .exceptions import OutOfBounds, InvalidSlice
17
18
19 class DataView(DataSet):
20
21 def __init__(self, da, slices):
22 self._valid = slices is not None and all(slices)
23 self._slices = slices
24 self._error_message = ""
25 if not self.valid:
26 self._error_message = (
27 "InvalidSlice error!"
28 "Given slice {} is invalid! At least one slice along one dimension"
29 "does not contain data.".format(slices)
30 )
31
32 if self.valid and len(slices) != len(da.shape):
33 # This is always checked by the calling function, but we repeat
34 # the check here for future bug catching
35 self._valid = False
36 self._error_message = (
37 "IncompatibleDimensions error."
38 "Number of dimensions for DataView does not match underlying "
39 "data object: {} != {}".format(len(slices), len(da.shape)),
40 )
41
42 if self.valid and any(s.stop > e for s, e in zip(slices, da.data_extent)):
43 self._valid = False
44 self._error_message = (
45 "OutOfBounds error!"
46 "Trying to create DataView with slices {} which are out of bounds of the "
47 "underlying DataArray {}".format(self._slices, da.shape)
48 )
49
50 # Simplify all slices
51 if self.valid:
52 slices = tuple(slice(*sl.indices(dimlen))
53 for sl, dimlen in zip(slices, da.shape))
54 self._slices = slices
55
56 self.array = da
57 self._h5group = self.array._h5group
58
59 @property
60 def valid(self):
61 return self._valid
62
63 @property
64 def debug_message(self):
65 return self._error_message
66
67 @property
68 def data_extent(self):
69 if self.valid:
70 return tuple(s.stop - s.start for s in self._slices)
71 else:
72 return None
73
74 @data_extent.setter
75 def data_extent(self, v):
76 raise AttributeError("can't set attribute")
77
78 @property
79 def data_type(self):
80 return self.array.data_type
81
82 def _write_data(self, data, sl=None):
83 if not self.valid:
84 raise InvalidSlice(
85 "Write Data failed due to an invalid slice."
86 "Reason is: {}".format(self._error_message)
87 )
88 tsl = self._slices
89 if sl:
90 tsl = self._transform_coordinates(sl)
91 super(DataView, self)._write_data(data, tsl)
92
93 def _read_data(self, sl=None):
94 if not self.valid:
95 return np.array([])
96 tsl = self._slices
97 if sl is not None:
98 tsl = self._transform_coordinates(sl)
99 return self.array._read_data(tsl)
100
101 def _transform_coordinates(self, user_slices):
102 """
103 Takes a series (tuple) of slices or indices passed to the DataView and
104 transforms them to the equivalent slices or indices for the underlying
105 DataArray. Bounds checking is performed on the results to make sure it
106 is not outside the DataView's range.
107
108 Note: HDF5 hyperslabs don't support negative steps, so we catch it
109 here to throw an error from NIX instead to shorten the stack trace (we
110 use the same message).
111 """
112 oob = OutOfBounds("Trying to access data outside of range of DataView")
113
114 def transform_slice(uslice, dvslice):
115 """
116 Single dimension transform function for slices.
117
118 uslice: User provided slice for dimension
119 dvslice: DataView slice for dimension
120 """
121 # Simplify uslice; DataView step is always 1
122 dimlen = dvslice.stop - dvslice.start
123 ustart, ustop, ustep = uslice.indices(dimlen)
124 if ustop < 0: # special case for None stop
125 ustop = dimlen + ustop
126 tslice = slice(dvslice.start + ustart, dvslice.start + ustop, ustep)
127 if tslice.stop > dvslice.stop:
128 raise oob
129
130 if tslice.step < 0:
131 raise ValueError("Step must be >= 1")
132
133 return tslice
134
135 dvslices = self._slices
136 user_slices = self._expand_user_slices(user_slices)
137 tslices = list()
138 for uslice, dvslice in zip(user_slices, dvslices):
139 if isinstance(uslice, Integral):
140 if uslice < 0:
141 tslice = dvslice.stop + uslice
142 else:
143 tslice = uslice + dvslice.start
144 if tslice < dvslice.start or tslice >= dvslice.stop:
145 raise oob
146 elif isinstance(uslice, slice):
147 tslice = transform_slice(uslice, dvslice)
148 if tslice.start < dvslice.start:
149 raise oob
150 if tslice.stop > dvslice.stop:
151 raise oob
152 else:
153 raise TypeError("Data indices must be integers or slices, "
154 "not {}".format(type(uslice)))
155 tslices.append(tslice)
156
157 return tuple(tslices)
158
159 def _expand_user_slices(self, user_slices):
160 """
161 Given the user-supplied slices or indices, expands Ellipses if
162 necessary and returns the same objects in a tuple padded with
163 slice(None) to match the dimensionality of the DataView.
164 """
165 if not isinstance(user_slices, Iterable):
166 user_slices = (user_slices,)
167
168 if user_slices.count(Ellipsis) > 1:
169 raise IndexError(
170 "an index can only have a single ellipsis ('...')"
171 )
172 elif user_slices.count(Ellipsis) == 1:
173 # expand slices at Ellipsis index
174 expidx = user_slices.index(Ellipsis)
175 npad = len(self.data_extent) - len(user_slices) + 1
176 padding = (slice(None),) * npad
177 return user_slices[:expidx] + padding + user_slices[expidx + 1:]
178
179 # expand slices at the end
180 npad = len(self.data_extent) - len(user_slices)
181 padding = (slice(None),) * npad
182 return user_slices + padding