-
Notifications
You must be signed in to change notification settings - Fork 2
/
json_generator.py
299 lines (249 loc) · 9.78 KB
/
json_generator.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
from abc import abstractmethod
from dataclasses import dataclass
from enum import Enum, auto
from typing import Any
import numpy as np
from cryoet_data_portal_neuroglancer.shaders.annotation import (
NonOrientedPointShaderBuilder,
OrientedPointShaderBuilder,
)
from cryoet_data_portal_neuroglancer.shaders.image import (
ImageShaderBuilder,
ImageWithVolumeRenderingShaderBuilder,
)
def create_source(
url: str,
input_dimension: tuple[float, float, float],
output_dimension: tuple[float, float, float],
) -> dict[str, Any]:
return {
"url": url,
"transform": {
"outputDimensions": {
"x": [output_dimension[0], "m"],
"y": [output_dimension[1], "m"],
"z": [output_dimension[2], "m"],
},
"inputDimensions": {
"x": [input_dimension[0], "m"],
"y": [input_dimension[1], "m"],
"z": [input_dimension[2], "m"],
},
},
}
class RenderingTypes(Enum):
"""Types of rendering for Neuroglancer."""
SEGMENTATION = auto()
IMAGE = auto()
ANNOTATION = auto()
def __str__(self):
return self.name.lower()
@dataclass
class SegmentPropertyJSONGenerator:
"""Generates a JSON file for segmentation properties.
Supports a subset of the properties that can be set in Neuroglancer.
See https://github.com/google/neuroglancer/blob/3efc90465e702453916d2b03d472c16378848132/src/datasource/precomputed/segment_properties.md
"""
ids: list[int]
labels: list[str]
def generate_json(self) -> dict:
return {
"inline": {
"ids": [str(val) for val in self.ids],
"properties": [
{
"values": self.labels,
"type": "label",
"id": "label",
},
],
},
"@type": "neuroglancer_segment_properties",
}
@dataclass
class RenderingJSONGenerator:
"""Generates a JSON file for Neuroglancer to read."""
source: str
name: str
scale: tuple[float, float, float]
@property
def layer_type(self) -> str:
"""Returns the layer type for Neuroglancer."""
try:
return str(self._type) # type: ignore
except AttributeError:
raise ValueError(f"Unknown rendering type {self._type}") from None # type: ignore
def to_json(self) -> dict:
return self.generate_json()
@abstractmethod
def generate_json(self) -> dict:
"""Generates the JSON for Neuroglancer."""
raise NotImplementedError
@dataclass
class ImageJSONGenerator(RenderingJSONGenerator):
"""Generates JSON Neuroglancer config for Image volume."""
size: dict[str, float]
contrast_limits: tuple[float, float] | None = None
threedee_contrast_limits: tuple[float, float] | None = None
start: dict[str, float] | None = None
mean: float | None = None
rms: float | None = None
is_visible: bool = True
has_volume_rendering_shader: bool = False
volume_rendering_depth_samples: int = 128 # Ideally, this should be a power of 2
volume_rendering_is_visible: bool = False
volume_rendering_gain: float = 0.0
can_hide_high_values_in_neuroglancer: bool = False
def __post_init__(self):
self._type = RenderingTypes.IMAGE
def _compute_contrast_limits(self) -> tuple[float, float]:
if self.mean is None or self.rms is None:
return self.contrast_limits
width = 3 * self.rms
return (self.mean - width, self.mean + width)
def _create_shader_and_controls(self) -> dict[str, Any]:
if self.contrast_limits is None:
self.contrast_limits = self._compute_contrast_limits()
if self.threedee_contrast_limits is None:
self.threedee_contrast_limits = self.contrast_limits
if self.has_volume_rendering_shader:
shader_builder = ImageWithVolumeRenderingShaderBuilder(
contrast_limits=self.contrast_limits,
threedee_contrast_limits=self.threedee_contrast_limits,
can_hide_high_values_in_neuroglancer=self.can_hide_high_values_in_neuroglancer,
)
else:
shader_builder = ImageShaderBuilder(
contrast_limits=self.contrast_limits,
can_hide_high_values_in_neuroglancer=self.can_hide_high_values_in_neuroglancer,
)
return shader_builder.build()
def _get_computed_values(self) -> dict[str, Any]:
nstart = self.start or {k: 0 for k in "xyz"}
avg_cross_section_render_height = 400
largest_dimension = max([self.size.get(d, 0) - nstart.get(d, 0) for d in "xyz"])
return {
"_position": [np.round(np.mean([self.size.get(d, 0), nstart.get(d, 0)])) for d in "xyz"],
"_crossSectionScale": max(largest_dimension / avg_cross_section_render_height, 1),
"_projectionScale": largest_dimension * 1.1,
}
def generate_json(self) -> dict:
config = {
"type": self.layer_type,
"name": self.name,
"source": create_source(f"zarr://{self.source}", self.scale, self.scale),
"opacity": 0.51,
"tab": "rendering",
"visible": self.is_visible,
"volumeRendering": "on" if self.volume_rendering_is_visible else "off",
"volumeRenderingGain": self.volume_rendering_gain,
}
if self.has_volume_rendering_shader:
config["volumeRenderingDepthSamples"] = self.volume_rendering_depth_samples
return {**config, **self._create_shader_and_controls(), **self._get_computed_values()}
@dataclass
class AnnotationJSONGenerator(RenderingJSONGenerator):
"""Generates JSON Neuroglancer config for point annotation."""
color: str
point_size_multiplier: float = 1.0
is_instance_segmentation: bool = False
is_visible: bool = True
def __post_init__(self):
self._type = RenderingTypes.ANNOTATION
def _get_shader(self):
shader_builder = NonOrientedPointShaderBuilder(
point_size_multiplier=self.point_size_multiplier,
is_instance_segmentation=self.is_instance_segmentation,
color=self.color,
)
return shader_builder.build()
def generate_json(self) -> dict:
return {
"type": self.layer_type,
"name": f"{self.name}",
"source": create_source(f"precomputed://{self.source}", self.scale, self.scale),
"tab": "rendering",
"visible": self.is_visible,
**self._get_shader(),
}
@dataclass
class OrientedPointAnnotationJSONGenerator(AnnotationJSONGenerator):
"""Generates JSON Neuroglancer config for oriented point annotation."""
line_width: float = 1.0
def _get_shader(self):
shader_builder = OrientedPointShaderBuilder(
point_size_multiplier=self.point_size_multiplier,
is_instance_segmentation=self.is_instance_segmentation,
color=self.color,
line_width=self.line_width,
)
return shader_builder.build()
@dataclass
class SegmentationJSONGenerator(RenderingJSONGenerator):
"""Generates JSON Neuroglancer config for segmentation mask."""
color: str | None = None
is_visible: bool = True
display_mesh: bool = True
display_bounding_box: bool = False
highlight_on_hover: bool = False
mesh_render_scale: float = 1.0
visible_segments: tuple[int, ...] = (1,)
def __post_init__(self):
self._type = RenderingTypes.SEGMENTATION
def generate_json(self) -> dict:
state = {
"type": self.layer_type,
"name": f"{self.name}",
"source": {
**create_source(f"precomputed://{self.source}", self.scale, self.scale),
"subsources": {
"default": True,
"mesh": self.display_mesh,
},
"enableDefaultSubsources": self.display_bounding_box,
},
"tab": "rendering",
"selectedAlpha": 1,
"hoverHighlight": self.highlight_on_hover,
"segments": sorted((self.visible_segments)),
"visible": self.is_visible,
"meshRenderScale": self.mesh_render_scale,
}
# self.color === None means that the color will be random
# This is useful for multiple segmentations
if self.color is not None:
state["segmentDefaultColor"] = self.color
return state
# Alias for SegmentationJSONGenerator - for future compatibility
MeshJSONGenerator = SegmentationJSONGenerator
@dataclass
class ImageVolumeJSONGenerator(RenderingJSONGenerator):
"""Generates JSON Neuroglancer config for volume rendering."""
color: str
rendering_depth: int
def __post_init__(self):
self._type = RenderingTypes.IMAGE
def _get_shader(self) -> dict[str, Any]:
shader = (
f'#uicontrol vec3 color color(default="{self.color}")\n'
f"#uicontrol invlerp toRaw(range=[0, 1], window=[-1, 2])\n"
f"void main() {{\n"
f" emitRGBA(vec4(color * toRaw(getDataValue()), toRaw(getDataValue())));\n"
f"}}"
)
return {
"shader": shader,
"shaderControls": {"color": self.color},
}
def generate_json(self) -> dict:
return {
"type": self.layer_type,
"name": f"{self.name}",
"source": create_source(f"zarr://{self.source}", self.scale, self.scale),
"tab": "rendering",
"blend": "additive",
"volumeRendering": "on",
"volumeRenderingDepthSamples": self.rendering_depth,
"visible": self.is_visible,
**self._get_shader(),
}