|
| 1 | +import numpy as np |
| 2 | +from plotly.graph_objects import Figure |
| 3 | +from dash import Dash |
| 4 | +from dash.dependencies import Input, Output, State |
| 5 | +from dash_core_components import Graph, Slider, Store |
| 6 | + |
| 7 | +from .utils import gen_random_id, img_array_to_uri |
| 8 | + |
| 9 | + |
| 10 | +class DashVolumeSlicer: |
| 11 | + """A slicer to show 3D image data in Dash.""" |
| 12 | + |
| 13 | + def __init__(self, app, volume, axis=0, id=None): |
| 14 | + if not isinstance(app, Dash): |
| 15 | + raise TypeError("Expect first arg to be a Dash app.") |
| 16 | + # Check and store volume |
| 17 | + if not (isinstance(volume, np.ndarray) and volume.ndim == 3): |
| 18 | + raise TypeError("Expected volume to be a 3D numpy array") |
| 19 | + self._volume = volume |
| 20 | + # Check and store axis |
| 21 | + if not (isinstance(axis, int) and 0 <= axis <= 2): |
| 22 | + raise ValueError("The given axis must be 0, 1, or 2.") |
| 23 | + self._axis = int(axis) |
| 24 | + # Check and store id |
| 25 | + if id is None: |
| 26 | + id = gen_random_id() |
| 27 | + elif not isinstance(id, str): |
| 28 | + raise TypeError("Id must be a string") |
| 29 | + self._id = id |
| 30 | + |
| 31 | + # Get the slice size (width, height), and max index |
| 32 | + arr_shape = list(volume.shape) |
| 33 | + arr_shape.pop(self._axis) |
| 34 | + slice_size = list(reversed(arr_shape)) |
| 35 | + self._max_index = self._volume.shape[self._axis] - 1 |
| 36 | + |
| 37 | + # Create the figure object |
| 38 | + fig = Figure() |
| 39 | + fig.update_layout( |
| 40 | + template=None, |
| 41 | + margin=dict(l=0, r=0, b=0, t=0, pad=4), |
| 42 | + ) |
| 43 | + fig.update_xaxes( |
| 44 | + showgrid=False, |
| 45 | + range=(0, slice_size[0]), |
| 46 | + showticklabels=False, |
| 47 | + zeroline=False, |
| 48 | + ) |
| 49 | + fig.update_yaxes( |
| 50 | + showgrid=False, |
| 51 | + scaleanchor="x", |
| 52 | + range=(slice_size[1], 0), # todo: allow flipping x or y |
| 53 | + showticklabels=False, |
| 54 | + zeroline=False, |
| 55 | + ) |
| 56 | + # Add an empty layout image that we can populate from JS. |
| 57 | + fig.add_layout_image( |
| 58 | + dict( |
| 59 | + source="", |
| 60 | + xref="x", |
| 61 | + yref="y", |
| 62 | + x=0, |
| 63 | + y=0, |
| 64 | + sizex=slice_size[0], |
| 65 | + sizey=slice_size[1], |
| 66 | + sizing="contain", |
| 67 | + layer="below", |
| 68 | + ) |
| 69 | + ) |
| 70 | + # Wrap the figure in a graph |
| 71 | + # todo: or should the user provide this? |
| 72 | + self.graph = Graph( |
| 73 | + id=self._subid("graph"), |
| 74 | + figure=fig, |
| 75 | + config={"scrollZoom": True}, |
| 76 | + ) |
| 77 | + # Create a slider object that the user can put in the layout (or not) |
| 78 | + self.slider = Slider( |
| 79 | + id=self._subid("slider"), |
| 80 | + min=0, |
| 81 | + max=self._max_index, |
| 82 | + step=1, |
| 83 | + value=self._max_index // 2, |
| 84 | + updatemode="drag", |
| 85 | + ) |
| 86 | + # Create the stores that we need (these must be present in the layout) |
| 87 | + self.stores = [ |
| 88 | + Store(id=self._subid("slice-index"), data=volume.shape[self._axis] // 2), |
| 89 | + Store(id=self._subid("_requested-slice-index"), data=0), |
| 90 | + Store(id=self._subid("_slice-data"), data=""), |
| 91 | + ] |
| 92 | + |
| 93 | + self._create_server_callbacks(app) |
| 94 | + self._create_client_callbacks(app) |
| 95 | + |
| 96 | + def _subid(self, subid): |
| 97 | + """Given a subid, get the full id including the slicer's prefix.""" |
| 98 | + return self._id + "-" + subid |
| 99 | + |
| 100 | + def _slice(self, index): |
| 101 | + """Sample a slice from the volume.""" |
| 102 | + indices = [slice(None), slice(None), slice(None)] |
| 103 | + indices[self._axis] = index |
| 104 | + return self._volume[tuple(indices)] |
| 105 | + |
| 106 | + def _create_server_callbacks(self, app): |
| 107 | + """Create the callbacks that run server-side.""" |
| 108 | + |
| 109 | + @app.callback( |
| 110 | + Output(self._subid("_slice-data"), "data"), |
| 111 | + [Input(self._subid("_requested-slice-index"), "data")], |
| 112 | + ) |
| 113 | + def upload_requested_slice(slice_index): |
| 114 | + slice = self._slice(slice_index) |
| 115 | + slice = (slice.astype(np.float32) * (255 / slice.max())).astype(np.uint8) |
| 116 | + return [slice_index, img_array_to_uri(slice)] |
| 117 | + |
| 118 | + def _create_client_callbacks(self, app): |
| 119 | + """Create the callbacks that run client-side.""" |
| 120 | + |
| 121 | + app.clientside_callback( |
| 122 | + """ |
| 123 | + function handle_slider_move(index) { |
| 124 | + return index; |
| 125 | + } |
| 126 | + """, |
| 127 | + Output(self._subid("slice-index"), "data"), |
| 128 | + [Input(self._subid("slider"), "value")], |
| 129 | + ) |
| 130 | + |
| 131 | + app.clientside_callback( |
| 132 | + """ |
| 133 | + function handle_slice_index(index) { |
| 134 | + if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; } |
| 135 | + let slice_cache = window.slicecache_for_{{ID}}; |
| 136 | + if (slice_cache[index]) { |
| 137 | + return window.dash_clientside.no_update; |
| 138 | + } else { |
| 139 | + console.log('requesting slice ' + index) |
| 140 | + return index; |
| 141 | + } |
| 142 | + } |
| 143 | + """.replace( |
| 144 | + "{{ID}}", self._id |
| 145 | + ), |
| 146 | + Output(self._subid("_requested-slice-index"), "data"), |
| 147 | + [Input(self._subid("slice-index"), "data")], |
| 148 | + ) |
| 149 | + |
| 150 | + # app.clientside_callback(""" |
| 151 | + # function update_slider_pos(index) { |
| 152 | + # return index; |
| 153 | + # } |
| 154 | + # """, |
| 155 | + # [Output("slice-index", "data")], |
| 156 | + # [State("slider", "value")], |
| 157 | + # ) |
| 158 | + |
| 159 | + app.clientside_callback( |
| 160 | + """ |
| 161 | + function handle_incoming_slice(index, index_and_data, ori_figure) { |
| 162 | + let new_index = index_and_data[0]; |
| 163 | + let new_data = index_and_data[1]; |
| 164 | + // Store data in cache |
| 165 | + if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; } |
| 166 | + let slice_cache = window.slicecache_for_{{ID}}; |
| 167 | + slice_cache[new_index] = new_data; |
| 168 | + // Get the data we need *now* |
| 169 | + let data = slice_cache[index]; |
| 170 | + // Maybe we do not need an update |
| 171 | + if (!data) { |
| 172 | + return window.dash_clientside.no_update; |
| 173 | + } |
| 174 | + if (data == ori_figure.layout.images[0].source) { |
| 175 | + return window.dash_clientside.no_update; |
| 176 | + } |
| 177 | + // Otherwise, perform update |
| 178 | + console.log("updating figure"); |
| 179 | + let figure = {...ori_figure}; |
| 180 | + figure.layout.images[0].source = data; |
| 181 | + return figure; |
| 182 | + } |
| 183 | + """.replace( |
| 184 | + "{{ID}}", self._id |
| 185 | + ), |
| 186 | + Output(self._subid("graph"), "figure"), |
| 187 | + [ |
| 188 | + Input(self._subid("slice-index"), "data"), |
| 189 | + Input(self._subid("_slice-data"), "data"), |
| 190 | + ], |
| 191 | + [State(self._subid("graph"), "figure")], |
| 192 | + ) |
0 commit comments