diff --git a/README.md b/README.md index d4f27db..581493b 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,132 @@ This code is distributed under MIT license. * Use `black .` to autoformat. * Use `flake8 .` to lint. * Use `pytest .` to run the tests. +* Use `python update_docs_in_readme.py` to update the readme when needed. On every PR, an app with the same name as your branch is deployed to the Dash playground instance so that you can change whether your changes did not break the package. + + +## Reference + +### The VolumeSlicer class + +**class `VolumeSlicer(app, volume, *, spacing=None, origin=None, axis=0, reverse_y=True, scene_id=None, color=None, thumbnail=True)`** + +A slicer object to show 3D image data in Dash. Upon +instantiation one can provide the following parameters: + +* `app` (`dash.Dash`): the Dash application instance. +* `volume` (`ndarray`): the 3D numpy array to slice through. The dimensions + are assumed to be in zyx order. If this is not the case, you can + use `np.swapaxes` to make it so. +* `spacing` (tuple of `float`): The distance between voxels for each + dimension (zyx).The spacing and origin are applied to make the slice + drawn in "scene space" rather than "voxel space". +* `origin` (tuple of `float`): The offset for each dimension (zyx). +* `axis` (`int`): the dimension to slice in. Default 0. +* `reverse_y` (`bool`): Whether to reverse the y-axis, so that the origin of + the slice is in the top-left, rather than bottom-left. Default True. + Note: setting this to False affects performance, see #12. +* `scene_id` (`str`): the scene that this slicer is part of. Slicers + that have the same scene-id show each-other's positions with + line indicators. By default this is derived from `id(volume)`. +* `color` (`str`): the color for this slicer. By default the color is + red, green, or blue, depending on the axis. Set to empty string + for "no color". +* `thumbnail` (`int` or `bool`): preferred size of low-resolution data to be + uploaded to the client. If `False`, the full-resolution data are + uploaded client-side. If `True` (default), a default value of 32 is + used. + +Note that this is not a Dash component. The components that make +up the slicer (and which must be present in the layout) are: +`slicer.graph`, `slicer.slider`, and `slicer.stores`. + +**method `VolumeSlicer.create_overlay_data(mask, color=None)`** + +Given a 3D mask array and an index, create an object that +can be used as output for `slicer.overlay_data`. The color +can be a hex color or an rgb/rgba tuple. Alternatively, color +can be a list of such colors, defining a colormap. + +**property `VolumeSlicer.axis`** (`int`): The axis at which the slicer is slicing. + +**property `VolumeSlicer.graph`**: The `dcc.Graph` for this slicer. Use `graph.figure` to access the +Plotly Figure object. + +**property `VolumeSlicer.nslices`** (`int`): The number of slices for this slicer. + +**property `VolumeSlicer.overlay_data`**: A `dcc.Store` containing the overlay data. The form of this +data is considered an implementation detail; users are expected to use +`create_overlay_data` to create it. + +**property `VolumeSlicer.scene_id`** (`str`): The id of the "virtual scene" for this slicer. Slicers that have +the same scene_id show each-other's positions. + +**property `VolumeSlicer.slider`**: The `dcc.Slider` to change the index for this slicer. If you +don't want to use the slider, wrap it in a div with style +`display: none`. + +**property `VolumeSlicer.state`**: A `dcc.Store` representing the current state of the slicer (present +in slicer.stores). Its data is a dict with the fields: + +* "index": the integer slice index. +* "index_changed": a bool indicating whether the index changed since last time. +* "xrange": the view range (2 floats) in the x-dimension (2D). +* "yrange": the view range (2 floats) in the y-dimension (2D). +* "zpos": the float position aling the axis, in scene coordinates. +* "axis": the axis (int) for this slicer. +* "color": the color (str) for this slicer. + +The id of the store is a dictionary so it can be used in a +pattern matching Input. Its field are: context, scene, name. +Where scene is the scene_id and name is "state". + +**property `VolumeSlicer.stores`**: A list of `dcc.Store` objects that the slicer needs to work. +These must be added to the app layout. + + + +### Reacting to slicer state + +It is possible to get notified of updates to slicer position and +view ranges. To get this for all slicers with a specific scene_id, create +a [pattern matching input](https://dash.plotly.com/pattern-matching-callbacks) +like this: +```py +Input({"scene": scene_id, "context": ALL, "name": "state"}) +``` + +See the `state` property for details. + + +### Setting slicer positions + +To programatically set the position of the slicer, create a `dcc.Store` with +a dictionary-id that has the following fields: + +* 'context': a unique name for this store. +* 'scene': the scene_id of the slicer objects to set the position for. +* 'name': 'setpos' + +The value in the store must be an 3-element tuple (x, y, z) in scene coordinates. +To apply the position for one dimension only, use e.g `(None, None, x)`. + + +### Performance tips + +There tends to be a lot of interaction in an application that contains +slicer objects. Therefore, performance matters to realize a smooth user +experience. Here are some tips to help with that: + +* Most importantly, when running the server in debug mode, consider setting + `dev_tools_props_check=False`. +* Also consider creating the `Dash` application with `update_title=None`. +* Setting `reverse_y` to False negatively affects performance. This will be + fixed in a future version of Plotly/Dash. +* For a smooth experience, avoid triggering unnecessary figure updates. +* When adding a callback that uses the slicer position, use the (rate limited) + `state` store rather than the slider value. + diff --git a/dash_slicer/docs.py b/dash_slicer/docs.py new file mode 100644 index 0000000..219993e --- /dev/null +++ b/dash_slicer/docs.py @@ -0,0 +1,72 @@ +""" +Utilities to produce simple reference docs (in Markdown) from the source code. +""" + +import inspect +import dash_slicer + + +def dedent(text): + """Dedent a docstring, removing leading whitespace.""" + lines = text.lstrip().splitlines() + min_indent = 9999 + for i in range(1, len(lines)): + line1 = lines[i] + line2 = line1.lstrip() + if line2: + indent = len(lines[i]) - len(lines[i].lstrip()) + min_indent = min(min_indent, indent) + if min_indent > 16: + min_indent = 0 + for i in range(1, len(lines)): + lines[i] = lines[i][min_indent:] + return "\n".join(lines) + + +def get_reference_docs(): + """Create reference documentation from the source code. + A bit like Sphinx autodoc, but using Markdown, and more basic. + Returns a str in Markdown format. + + Note that this function is used to build the Dash Slicer chapter + in the Dash docs. + """ + + methods = [] + props = [] + + sig = str(inspect.signature(dash_slicer.VolumeSlicer.__init__)).replace( + "self, ", "" + ) + doc = f"**class `VolumeSlicer{sig}`**" + doc += "\n\n" + dedent(dash_slicer.VolumeSlicer.__doc__).rstrip() + methods.append(doc) + + for name in dir(dash_slicer.VolumeSlicer): + val = getattr(dash_slicer.VolumeSlicer, name) + + if name.startswith("_") or not hasattr(val, "__doc__"): + pass + elif callable(val): + # Method + sig = str(inspect.signature(val)).replace("self, ", "") + doc = f"**method `VolumeSlicer.{name}{sig}`**" + doc += "\n\n" + dedent(val.__doc__).rstrip() + methods.append(doc) + else: + # Property + doc = f"**property `VolumeSlicer.{name}`**" + try: + typ = val.fget.__annotations__["return"].__name__ + doc += f" (`{typ}`)" + except (AttributeError, KeyError): + pass + doc += ": " + dedent(val.__doc__).rstrip() + props.append(doc) + + parts = [] + parts.append("### The VolumeSlicer class") + parts += methods + parts += props + parts.append(dash_slicer.slicer.__doc__) + return "\n\n".join(parts) diff --git a/dash_slicer/slicer.py b/dash_slicer/slicer.py index de12b03..4355b34 100644 --- a/dash_slicer/slicer.py +++ b/dash_slicer/slicer.py @@ -1,3 +1,51 @@ +# The docstring below is used as part of the reference docs. It describes +# the parts that cannot be described well via the properties and methods. + +""" + +### Reacting to slicer state + +It is possible to get notified of updates to slicer position and +view ranges. To get this for all slicers with a specific scene_id, create +a [pattern matching input](https://dash.plotly.com/pattern-matching-callbacks) +like this: +```py +Input({"scene": scene_id, "context": ALL, "name": "state"}) +``` + +See the `state` property for details. + + +### Setting slicer positions + +To programatically set the position of the slicer, create a `dcc.Store` with +a dictionary-id that has the following fields: + +* 'context': a unique name for this store. +* 'scene': the scene_id of the slicer objects to set the position for. +* 'name': 'setpos' + +The value in the store must be an 3-element tuple (x, y, z) in scene coordinates. +To apply the position for one dimension only, use e.g `(None, None, x)`. + + +### Performance tips + +There tends to be a lot of interaction in an application that contains +slicer objects. Therefore, performance matters to realize a smooth user +experience. Here are some tips to help with that: + +* Most importantly, when running the server in debug mode, consider setting + `dev_tools_props_check=False`. +* Also consider creating the `Dash` application with `update_title=None`. +* Setting `reverse_y` to False negatively affects performance. This will be + fixed in a future version of Plotly/Dash. +* For a smooth experience, avoid triggering unnecessary figure updates. +* When adding a callback that uses the slicer position, use the (rate limited) + `state` store rather than the slider value. + +""" + import numpy as np import plotly.graph_objects import dash @@ -14,60 +62,35 @@ class VolumeSlicer: - """A slicer to show 3D image data in Dash. - - Parameters: - app (dash.Dash): the Dash application instance. - volume (ndarray): the 3D numpy array to slice through. The dimensions - are assumed to be in zyx order. If this is not the case, you can - use ``np.swapaxes`` to make it so. - spacing (tuple of floats): The distance between voxels for each - dimension (zyx).The spacing and origin are applied to make the slice - drawn in "scene space" rather than "voxel space". - origin (tuple of floats): The offset for each dimension (zyx). - axis (int): the dimension to slice in. Default 0. - reverse_y (bool): Whether to reverse the y-axis, so that the origin of - the slice is in the top-left, rather than bottom-left. Default True. - Note: setting this to False affects performance, see #12. - scene_id (str): the scene that this slicer is part of. Slicers - that have the same scene-id show each-other's positions with - line indicators. By default this is derived from ``id(volume)``. - color (str): the color for this slicer. By default the color is - red, green, or blue, depending on the axis. Set to empty string - for "no color". - thumbnail (int or bool): preferred size of low-resolution data to be - uploaded to the client. If ``False``, the full-resolution data are - uploaded client-side. If ``True`` (default), a default value of 32 is - used. - - This is a placeholder object, not a Dash component. The components - that make up the slicer can be accessed as attributes. These must all - be present in the app layout: - - * ``graph``: the dcc.Graph object. Use ``graph.figure`` to access the - Plotly Figure object. - * ``slider``: the dcc.Slider object, its value represents the slice - index. If you don't want to use the slider, wrap it in a div with - style ``display: none``. - * ``stores``: a list of dcc.Store objects. - - To programatically set the position of the slicer, use a store with - a dictionary-id with the following fields: - - * 'context': a unique name for this store. - * 'scene': the scene_id for which to set the position - * 'name': 'setpos' - - The value in the store must be an 3-element tuple (x, y, z) in scene coordinates. - To apply the position for one position only, use e.g ``(None, None, x)``. - - Some notes on performance: for a smooth experience, avoid triggering - unnecessary figure updates. When adding a callback that uses the - slicer position, use the (rate limited) `index` and `pos` stores - rather than the slider value. Further, create the `Dash` application - with `update_title=None`, and when running the server in debug mode, - consider setting `dev_tools_props_check=False`. - + """A slicer object to show 3D image data in Dash. Upon + instantiation one can provide the following parameters: + + * `app` (`dash.Dash`): the Dash application instance. + * `volume` (`ndarray`): the 3D numpy array to slice through. The dimensions + are assumed to be in zyx order. If this is not the case, you can + use `np.swapaxes` to make it so. + * `spacing` (tuple of `float`): The distance between voxels for each + dimension (zyx).The spacing and origin are applied to make the slice + drawn in "scene space" rather than "voxel space". + * `origin` (tuple of `float`): The offset for each dimension (zyx). + * `axis` (`int`): the dimension to slice in. Default 0. + * `reverse_y` (`bool`): Whether to reverse the y-axis, so that the origin of + the slice is in the top-left, rather than bottom-left. Default True. + Note: setting this to False affects performance, see #12. + * `scene_id` (`str`): the scene that this slicer is part of. Slicers + that have the same scene-id show each-other's positions with + line indicators. By default this is derived from `id(volume)`. + * `color` (`str`): the color for this slicer. By default the color is + red, green, or blue, depending on the axis. Set to empty string + for "no color". + * `thumbnail` (`int` or `bool`): preferred size of low-resolution data to be + uploaded to the client. If `False`, the full-resolution data are + uploaded client-side. If `True` (default), a default value of 32 is + used. + + Note that this is not a Dash component. The components that make + up the slicer (and which must be present in the layout) are: + `slicer.graph`, `slicer.slider`, and `slicer.stores`. """ _global_slicer_counter = 0 @@ -158,62 +181,74 @@ def __init__( # Note(AK): we could make some stores public, but let's do this only when actual use-cases arise? @property - def scene_id(self): + def scene_id(self) -> str: """The id of the "virtual scene" for this slicer. Slicers that have the same scene_id show each-other's positions. """ return self._scene_id @property - def axis(self): + def axis(self) -> int: """The axis at which the slicer is slicing.""" return self._axis @property - def nslices(self): + def nslices(self) -> int: """The number of slices for this slicer.""" return self._volume.shape[self._axis] @property def graph(self): - """The dcc.Graph for this slicer.""" + """The `dcc.Graph` for this slicer. Use `graph.figure` to access the + Plotly Figure object. + """ return self._graph @property def slider(self): - """The dcc.Slider to change the index for this slicer.""" + """The `dcc.Slider` to change the index for this slicer. If you + don't want to use the slider, wrap it in a div with style + `display: none`. + """ return self._slider @property def stores(self): - """A list of dcc.Store objects that the slicer needs to work. + """A list of `dcc.Store` objects that the slicer needs to work. These must be added to the app layout. """ return self._stores @property def state(self): - """A dcc.Store representing the current state of the slicer (present - in slicer.stores). Its data is a dict with the fields: index (int), - index_changed (bool), xrange (2 floats), yrange (2 floats), - zpos (float), axis (int), color (str). - - Its id is a dictionary so it can be used in a pattern matching Input. - Fields: context, scene, name. Where scene is the scene_id and name is "state". + """A `dcc.Store` representing the current state of the slicer (present + in slicer.stores). Its data is a dict with the fields: + + * "index": the integer slice index. + * "index_changed": a bool indicating whether the index changed since last time. + * "xrange": the view range (2 floats) in the x-dimension (2D). + * "yrange": the view range (2 floats) in the y-dimension (2D). + * "zpos": the float position aling the axis, in scene coordinates. + * "axis": the axis (int) for this slicer. + * "color": the color (str) for this slicer. + + The id of the store is a dictionary so it can be used in a + pattern matching Input. Its field are: context, scene, name. + Where scene is the scene_id and name is "state". """ return self._state @property def overlay_data(self): - """A dcc.Store containing the overlay data. The form of this + """A `dcc.Store` containing the overlay data. The form of this data is considered an implementation detail; users are expected to use - ``create_overlay_data`` to create it. + `create_overlay_data` to create it. """ return self._overlay_data def create_overlay_data(self, mask, color=None): """Given a 3D mask array and an index, create an object that - can be used as output for ``slicer.overlay_data``. The color + can be used as output for `slicer.overlay_data`. The color can be a hex color or an rgb/rgba tuple. Alternatively, color can be a list of such colors, defining a colormap. """ diff --git a/tests/test_docs.py b/tests/test_docs.py new file mode 100644 index 0000000..44c4eaf --- /dev/null +++ b/tests/test_docs.py @@ -0,0 +1,26 @@ +import os + +from dash_slicer.docs import get_reference_docs + + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def test_that_the_docs_build(): + x = get_reference_docs() + assert "VolumeSlicer(app, vol" in x + assert "create_overlay_data(mask" in x + assert "performance" in x.lower() + + +def test_that_reference_docs_in_readme_are_up_to_date(): + filename = os.path.join(os.path.dirname(HERE), "README.md") + assert os.path.isfile(filename) + with open(filename, "rb") as f: + text = f.read().decode() + _, _, ref = text.partition("## Reference") + ref1 = ref.strip().replace("\r\n", "\n") + ref2 = get_reference_docs().strip() + assert ( + ref1 == ref2 + ), "Reference docs in readme are outdated. Run `python update_docs_in_readme.py`"