-
Notifications
You must be signed in to change notification settings - Fork 1
/
neuron.py
307 lines (248 loc) · 7.42 KB
/
neuron.py
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
"""
Sample module showcasing uses displaying datasets from neurons.
NOTE: Some thirdparty modules may be required to use some of these methods.
"""
import os
from collections import defaultdict
import hyview
import hyview.log
_logger = hyview.log.get_logger(__name__)
SAMPLE_PATH = os.path.join(
os.path.dirname(__file__),
'_data',
'sample_A_20160501.hdf')
def sample(filters=None, minimum=2000000, nth=8, mesh=True):
"""
Visualize interesting data structures within the neuron dataset.
Parameters
----------
filters : Optional[List[int]]
Provide labels to filter the dataset to manually. If not provided,
then it will use labels that contain more than the `minimum` points.
minimum : int
Filter to labels that have point counts over this number.
nth : int
Skip to every nth sample.
mesh : bool
Mesh the points.
"""
import hyview.hy.impl
_logger.info('Loading data from {!r}...'.format(SAMPLE_PATH))
images, labels = load_data()
_logger.info('Finding labels with more than {!r} entries...'.format(minimum))
if filters is None:
filters = list(iter_unique_by_count(labels, minimum=minimum))
_logger.info('Filtering data...')
for name, geo in geogen(
images, labels,
group='label',
colorize=True,
filters=filters,
size=0, znth=0, nth=nth, zmult=10):
_logger.info('Sending {!r} to Houdini...'.format(name))
hyview.build(geo, name=name)
if mesh:
_logger.info('Meshing all geo...')
hyview.hy.impl.mesh_all(particlesep=8)
def load_data_from_h5py(path, *keys):
"""
Examples
--------
>>> images, lables = load_data_from_h5py(
... '/path/to/file.h5py',
... 'volumes/raw',
... 'volumes/labels/neuron_ids'
... )
Parameters
----------
path : str
keys : *str
Returns
-------
Tuple[Any, ...]
"""
import os
import h5py
data = h5py.File(os.path.expandvars(os.path.expanduser(path)))
return tuple(data[x] for x in keys)
def load_data():
"""
Gets "images" and "labels" test numpy arrays.
Returns
-------
Tuple[numpy.array, numpy.array]
"""
return load_data_from_h5py(
SAMPLE_PATH, 'volumes/raw', 'volumes/labels/neuron_ids')
def iterfilter(images, labels, size=None, znth=None, nth=None, zmult=10):
"""
Helper to iterate and filter over dataset.
Parameters
----------
images : numpy.array
labels : numpy.array
size : Optional[int]
znth : Optional[int]
nth : Optionl[int]
zmult : int
Scale multiplier for z coordinate.
Returns
-------
Iterator[Tuple[int, float, float, float, int]]
"""
import itertools
if size:
images = images[:size]
labels = labels[:size]
def islice(it, n):
if n:
return itertools.islice(it, 0, None, n)
return it
for z, (image, zlabels) in islice(enumerate(zip(images, labels)), znth):
for y, (row, ylabels) in islice(enumerate(zip(image, zlabels)), nth):
for x, (c, label) in islice(enumerate(zip(row, ylabels)), nth):
yield int(label), float(x), float(y), float(z * zmult), int(c)
def iter_unique_by_count(ar, minimum=None, maximum=None, return_counts=False):
"""
Filter an array by unique count.
Parameters
----------
ar : numpy.array
minimum : Optional[int]
maximum : Optional[int]
return_counts : bool
Returns
-------
Union[Iterator[Any], Iterator[Tuple[Any, int]]]
"""
import numpy
for item, count in zip(*numpy.unique(ar, return_counts=True)):
if minimum is not None and count < minimum:
continue
if maximum is not None and count > maximum:
continue
if return_counts:
yield item, count
else:
yield item
def pointgen(images, labels, colorize=False, filters=None, size=None, znth=3,
nth=8, zmult=10):
"""
Parameters
----------
images : numpy.array
labels : numpy.array
colorize : bool
Colorize the data per-label.
filters : Optional[List[int]]
Filters the data to only those that have labels within this list.
size : Optional[int]
Specify the number of z slices.
znth : Optional[int]
Specify how many of each z slice to use.
nth : Optional[int]
Filters the points to every `nth`.
zmult : int
Scale multiplier for z.
Returns
-------
Iterator[hyview.Point]
"""
from hyview_samples.utils import ColorGenerator
colors = ColorGenerator()
it = iterfilter(
images, labels,
size=size,
znth=znth,
nth=nth,
zmult=zmult
)
for label, x, y, z, c in it:
if filters and label not in filters:
continue
cd = float(c) / 255.0
if colorize:
color = colors.get(label)
else:
color = (cd, cd, cd)
yield hyview.Point(
x=x, y=y, z=z, attrs={
'label': label,
'luminance': c,
'Cd': color,
'Alpha': cd,
}
)
def geogen(images, labels, group=None, **kwargs):
"""
Helper to generate abstract data representations of the test neuron data.
Parameters
----------
images : numpy.array
labels : numpy.array
group : Optional[str]
{'label', 'z'}
Whether geo is generated by label, by z slice or other.
kwargs : **Any
See `pointgen`
Returns
-------
Iterator[Tuple[str, hyview.Geometry]]
"""
from hyview.c4 import C4
points = defaultdict(list)
piter = pointgen(images, labels, **kwargs)
if group is None:
points['*'] = piter
else:
for point in piter:
if group == 'label':
points[point.attrs['label']].append(point)
elif group == 'z':
points[point.z].append(point)
else:
raise NotImplementedError('Unknown group {!r}'.format(group))
attributes = [
hyview.AttributeDefinition(
name='Cd', type='Point', default=(0.1, 0.1, 0.1)),
hyview.AttributeDefinition(
name='Alpha', type='Point', default=1.0),
hyview.AttributeDefinition(
name='luminance', type='Point', default=1),
hyview.AttributeDefinition(
name='label', type='Point', default=-1),
]
for k, v in points.items():
geo = hyview.Geometry(attributes=attributes, points=v)
if k == '*':
name = str(C4(kwargs))
else:
name = '{}-{}-{}'.format(group, k, C4(kwargs))
yield name, geo
def build_neuron_sample(images, labels, **kwargs):
"""
Helper to visualize the neuron dataset.
Parameters
----------
images : numpy.array
labels : numpy.array
kwargs : **Any
See `geogen`.
"""
kwargs.setdefault('group', 'z')
for name, geo in geogen(images, labels, **kwargs):
hyview.build(geo, name=name)
def build_slice(nth=3):
"""
Visualize an image "slice".
Parameters
----------
nth : int
Density of the points created. Skips to every `nth` point.
"""
images, labels = load_data()
build_neuron_sample(
images, labels,
group=None,
colorize=False,
size=1, znth=0, nth=nth, zmult=10)