-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathneuroglancer
executable file
·230 lines (188 loc) · 6.18 KB
/
neuroglancer
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
#!/usr/bin/env python
from funlib.show.neuroglancer import add_layer
import argparse
import daisy
import glob
import neuroglancer
import os
import webbrowser
import numpy as np
import zarr
parser = argparse.ArgumentParser()
parser.add_argument(
'--file',
'-f',
type=str,
action='append',
help="The path to the container to show")
parser.add_argument(
'--datasets',
'-d',
type=str,
nargs='+',
action='append',
help="The datasets in the container to show")
parser.add_argument(
'--graphs',
'-g',
type=str,
nargs='+',
action='append',
help="The graphs in the container to show")
parser.add_argument(
'--no-browser',
'-n',
type=bool,
nargs='?',
default=False,
const=True,
help="If set, do not open a browser, just print a URL")
parser.add_argument(
'--port',
'-p',
type=int,
default=0,
help="Set port for URL")
parser.add_argument(
'--host',
type=str,
default='0.0.0.0',
help="Set host for URL")
args = parser.parse_args()
neuroglancer.set_server_bind_address(args.host, args.port)
viewer = neuroglancer.Viewer()
# viewer = neuroglancer.UnsynchronizedViewer()
def to_slice(slice_str):
values = [int(x) for x in slice_str.split(':')]
if len(values) == 1:
return values[0]
return slice(*values)
def parse_ds_name(ds):
tokens = ds.split('[')
if len(tokens) == 1:
return ds, None
ds, slices = tokens
slices = list(map(to_slice, slices.rstrip(']').split(',')))
return ds, slices
class Project:
def __init__(self, array, dim, value):
self.array = array
self.dim = dim
self.value = value
self.shape = array.shape[:self.dim] + array.shape[self.dim + 1:]
self.dtype = array.dtype
def __getitem__(self, key):
slices = key[:self.dim] + (self.value,) + key[self.dim:]
ret = self.array[slices]
return ret
def slice_dataset(a, slices):
dims = a.roi.dims
for d, s in list(enumerate(slices))[::-1]:
if isinstance(s, slice):
raise NotImplementedError("Slicing not yet implemented!")
else:
index = (s - a.roi.get_begin()[d])//a.voxel_size[d]
a.data = Project(a.data, d, index)
a.roi = daisy.Roi(
a.roi.get_begin()[:d] + a.roi.get_begin()[d + 1:],
a.roi.get_shape()[:d] + a.roi.get_shape()[d + 1:])
a.voxel_size = a.voxel_size[:d] + a.voxel_size[d + 1:]
return a
def open_dataset(f, ds):
original_ds = ds
ds, slices = parse_ds_name(ds)
slices_str = original_ds[len(ds):]
try:
dataset_as = []
if all(key.startswith("s") for key in zarr.open(f)[ds].keys()):
raise AttributeError("This group is a multiscale array!")
for key in zarr.open(f)[ds].keys():
dataset_as.extend(open_dataset(f, f"{ds}/{key}{slices_str}"))
return dataset_as
except AttributeError as e:
# dataset is an array, not a group
pass
print("ds :", ds)
print("slices:", slices)
try:
zarr.open(f)[ds].keys()
is_multiscale = True
except:
is_multiscale = False
if not is_multiscale:
a = daisy.open_ds(f, ds)
if slices is not None:
a = slice_dataset(a, slices)
if a.roi.dims == 2:
print("ROI is 2D, recruiting next channel to z dimension")
a.roi = daisy.Roi((0,) + a.roi.get_begin(), (a.shape[-3],) + a.roi.get_shape())
a.voxel_size = daisy.Coordinate((1,) + a.voxel_size)
if a.roi.dims == 4:
print("ROI is 4D, stripping first dimension and treat as channels")
a.roi = daisy.Roi(a.roi.get_begin()[1:], a.roi.get_shape()[1:])
a.voxel_size = daisy.Coordinate(a.voxel_size[1:])
if a.data.dtype == np.int64 or a.data.dtype == np.int16:
print("Converting dtype in memory...")
a.data = a.data[:].astype(np.uint64)
return [(a, ds)]
else:
return [([daisy.open_ds(f, f"{ds}/{key}") for key in zarr.open(f)[ds].keys()], ds)]
for f, datasets in zip(args.file, args.datasets):
arrays = []
for ds in datasets:
try:
print("Adding %s, %s" % (f, ds))
dataset_as = open_dataset(f, ds)
except Exception as e:
print(type(e), e)
print("Didn't work, checking if this is multi-res...")
scales = glob.glob(os.path.join(f, ds, 's*'))
if len(scales) == 0:
print(f"Couldn't read {ds}, skipping...")
raise e
print("Found scales %s" % ([
os.path.relpath(s, f)
for s in scales
],))
a = [
open_dataset(f, os.path.relpath(scale_ds, f))
for scale_ds in scales
]
for a in dataset_as:
arrays.append(a)
with viewer.txn() as s:
for array, dataset in arrays:
add_layer(s, array, dataset)
if args.graphs:
for f, graphs in zip(args.file, args.graphs):
for graph in graphs:
graph_annotations = []
try:
ids = daisy.open_ds(f, graph + '-ids').data
loc = daisy.open_ds(f, graph + '-locations').data
except:
loc = daisy.open_ds(f, graph).data
ids = None
dims = loc.shape[-1]
loc = loc[:].reshape((-1, dims))
if ids is None:
ids = range(len(loc))
for i, l in zip(ids, loc):
if dims == 2:
l = np.concatenate([[0], l])
graph_annotations.append(
neuroglancer.EllipsoidAnnotation(
center=l[::-1],
radii=(5, 5, 5),
id=i))
graph_layer = neuroglancer.AnnotationLayer(
annotations=graph_annotations,
voxel_size=(1, 1, 1))
with viewer.txn() as s:
s.layers.append(name='graph', layer=graph_layer)
url = str(viewer)
print(url)
# if os.environ.get("DISPLAY") and not args.no_browser:
# webbrowser.open_new(url)
print("Press ENTER to quit")
input()