code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def view_direction(self) -> tuple[float, float, float]:
"""3D view direction vector of the camera.
View direction is calculated from the Euler angles and returned as a
3-tuple. This direction is in 3D scene coordinates, the world coordinate
system for three currently displayed dimension... | 3D view direction vector of the camera.
View direction is calculated from the Euler angles and returned as a
3-tuple. This direction is in 3D scene coordinates, the world coordinate
system for three currently displayed dimensions.
| view_direction | python | napari/napari | src/napari/components/camera.py | https://github.com/napari/napari/blob/master/src/napari/components/camera.py | BSD-3-Clause |
def up_direction(self) -> tuple[float, float, float]:
"""3D direction vector pointing up on the canvas.
Up direction is calculated from the Euler angles and returned as a
3-tuple. This direction is in 3D scene coordinates, the world coordinate
system for three currently displayed dimens... | 3D direction vector pointing up on the canvas.
Up direction is calculated from the Euler angles and returned as a
3-tuple. This direction is in 3D scene coordinates, the world coordinate
system for three currently displayed dimensions.
| up_direction | python | napari/napari | src/napari/components/camera.py | https://github.com/napari/napari/blob/master/src/napari/components/camera.py | BSD-3-Clause |
def set_view_direction(
self,
view_direction: tuple[float, float, float],
up_direction: tuple[float, float, float] = (0, -1, 0),
):
"""Set camera angles from direction vectors.
Both the view direction and the up direction are specified in 3D scene
coordinates, the wo... | Set camera angles from direction vectors.
Both the view direction and the up direction are specified in 3D scene
coordinates, the world coordinate system for three currently displayed
dimensions.
The provided up direction must not be parallel to the provided
view direction. The... | set_view_direction | python | napari/napari | src/napari/components/camera.py | https://github.com/napari/napari/blob/master/src/napari/components/camera.py | BSD-3-Clause |
def calculate_nd_view_direction(
self, ndim: int, dims_displayed: tuple[int, ...]
) -> Optional['npt.NDArray[np.float64]']:
"""Calculate the nD view direction vector of the camera.
Parameters
----------
ndim : int
Number of dimensions in which to embed the 3D vie... | Calculate the nD view direction vector of the camera.
Parameters
----------
ndim : int
Number of dimensions in which to embed the 3D view vector.
dims_displayed : Tuple[int]
Dimensions in which to embed the 3D view vector.
Returns
-------
... | calculate_nd_view_direction | python | napari/napari | src/napari/components/camera.py | https://github.com/napari/napari/blob/master/src/napari/components/camera.py | BSD-3-Clause |
def calculate_nd_up_direction(
self, ndim: int, dims_displayed: tuple[int, ...]
) -> np.ndarray | None:
"""Calculate the nD up direction vector of the camera.
Parameters
----------
ndim : int
Number of dimensions in which to embed the 3D view vector.
dims... | Calculate the nD up direction vector of the camera.
Parameters
----------
ndim : int
Number of dimensions in which to embed the 3D view vector.
dims_displayed : Tuple[int]
Dimensions in which to embed the 3D view vector.
Returns
-------
u... | calculate_nd_up_direction | python | napari/napari | src/napari/components/camera.py | https://github.com/napari/napari/blob/master/src/napari/components/camera.py | BSD-3-Clause |
def handedness(self) -> Handedness:
"""Right or left-handedness of the current orientation."""
# we know default orientation is right-handed, so an odd number of
# differences from default means left-handed.
diffs = [
self.orientation[i] != DEFAULT_ORIENTATION_TYPED[i]
... | Right or left-handedness of the current orientation. | handedness | python | napari/napari | src/napari/components/camera.py | https://github.com/napari/napari/blob/master/src/napari/components/camera.py | BSD-3-Clause |
def _check_ranges(ranges):
"""
Ensure the range values are sane.
- start < stop
- step > 0
"""
for axis, (start, stop, step) in enumerate(ranges):
if start > stop:
raise ValueError(
trans._(
'start a... |
Ensure the range values are sane.
- start < stop
- step > 0
| _check_ranges | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def _check_dims(cls, values):
"""Check the consistency of dimensionality for all attributes.
Parameters
----------
values : dict
Values dictionary to update dims model with.
"""
updated = {}
ndim = values['ndim']
range_ = ensure_len(values['... | Check the consistency of dimensionality for all attributes.
Parameters
----------
values : dict
Values dictionary to update dims model with.
| _check_dims | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def set_range(
self,
axis: int | Sequence[int],
_range: Sequence[int | float] | Sequence[Sequence[int | float]],
):
"""Sets ranges (min, max, step) for the given dimensions.
Parameters
----------
axis : int or sequence of int
Dimension index or a ... | Sets ranges (min, max, step) for the given dimensions.
Parameters
----------
axis : int or sequence of int
Dimension index or a sequence of axes whos range will be set.
_range : tuple or sequence of tuple
Range specified as (min, max, step) or a sequence of these... | set_range | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def set_point(
self,
axis: int | Sequence[int],
value: float | Sequence[float],
):
"""Sets point to slice dimension in world coordinates.
Parameters
----------
axis : int or sequence of int
Dimension index or a sequence of axes whos point will be ... | Sets point to slice dimension in world coordinates.
Parameters
----------
axis : int or sequence of int
Dimension index or a sequence of axes whos point will be set.
value : scalar or sequence of scalars
Value of the point for each axis.
| set_point | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def set_axis_label(
self,
axis: int | Sequence[int],
label: str | Sequence[str],
):
"""Sets new axis labels for the given axes.
Parameters
----------
axis : int or sequence of int
Dimension index or a sequence of axes whos labels will be set.
... | Sets new axis labels for the given axes.
Parameters
----------
axis : int or sequence of int
Dimension index or a sequence of axes whos labels will be set.
label : str or sequence of str
Given labels for the specified axes.
| set_axis_label | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def reset(self):
"""Reset dims values to initial states."""
# Don't reset axis labels
# TODO: could be optimized with self.update, but need to fix
# event firing in EventedModel first
self.range = ((0, 2, 1),) * self.ndim
self.point = (0,) * self.ndim
self.o... | Reset dims values to initial states. | reset | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def transpose(self):
"""Transpose displayed dimensions.
This swaps the order of the last two displayed dimensions.
The order of the displayed is taken from Dims.order.
"""
order = list(self.order)
order[-2], order[-1] = order[-1], order[-2]
self.order = order | Transpose displayed dimensions.
This swaps the order of the last two displayed dimensions.
The order of the displayed is taken from Dims.order.
| transpose | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def _increment_dims_right(self, axis: int | None = None):
"""Increment dimensions to the right along given axis, or last used axis if None
Parameters
----------
axis : int, optional
Axis along which to increment dims, by default None
"""
if axis is None:
... | Increment dimensions to the right along given axis, or last used axis if None
Parameters
----------
axis : int, optional
Axis along which to increment dims, by default None
| _increment_dims_right | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def _increment_dims_left(self, axis: int | None = None):
"""Increment dimensions to the left along given axis, or last used axis if None
Parameters
----------
axis : int, optional
Axis along which to increment dims, by default None
"""
if axis is None:
... | Increment dimensions to the left along given axis, or last used axis if None
Parameters
----------
axis : int, optional
Axis along which to increment dims, by default None
| _increment_dims_left | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def _focus_up(self):
"""Shift focused dimension slider to be the next slider above."""
sliders = [d for d in self.not_displayed if self.nsteps[d] > 1]
if len(sliders) == 0:
return
index = (sliders.index(self.last_used) + 1) % len(sliders)
self.last_used = sliders[ind... | Shift focused dimension slider to be the next slider above. | _focus_up | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def _focus_down(self):
"""Shift focused dimension slider to be the next slider bellow."""
sliders = [d for d in self.not_displayed if self.nsteps[d] > 1]
if len(sliders) == 0:
return
index = (sliders.index(self.last_used) - 1) % len(sliders)
self.last_used = sliders[... | Shift focused dimension slider to be the next slider bellow. | _focus_down | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def roll(self):
"""Roll order of dimensions for display."""
order = np.array(self.order)
# we combine "rollable" and "nsteps" into a mask for rolling
# this mask has to be aligned to "order" as "rollable" and
# "nsteps" are static but order is dynamic, meaning "rollable"
... | Roll order of dimensions for display. | roll | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def _sanitize_input(
self, axis, value, value_is_sequence=False
) -> tuple[list[int], list]:
"""
Ensure that axis and value are the same length, that axes are not
out of bounds, and coerces to lists for easier processing.
"""
if isinstance(axis, Integral):
... |
Ensure that axis and value are the same length, that axes are not
out of bounds, and coerces to lists for easier processing.
| _sanitize_input | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def ensure_len(value: tuple, length: int, pad_width: Any):
"""
Ensure that the value has the required number of elements.
Right-crop if value is too long; left-pad with default if too short.
Parameters
----------
value : Tuple
A tuple of values to be resized.
ndim : int
Num... |
Ensure that the value has the required number of elements.
Right-crop if value is too long; left-pad with default if too short.
Parameters
----------
value : Tuple
A tuple of values to be resized.
ndim : int
Number of desired values.
default : Tuple
Default element... | ensure_len | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def ensure_axis_in_bounds(axis: int, ndim: int) -> int:
"""Ensure a given value is inside the existing axes of the image.
Returns
-------
axis : int
The axis which was checked for validity.
ndim : int
The dimensionality of the layer.
Raises
------
ValueError
The... | Ensure a given value is inside the existing axes of the image.
Returns
-------
axis : int
The axis which was checked for validity.
ndim : int
The dimensionality of the layer.
Raises
------
ValueError
The given axis index is out of bounds.
| ensure_axis_in_bounds | python | napari/napari | src/napari/components/dims.py | https://github.com/napari/napari/blob/master/src/napari/components/dims.py | BSD-3-Clause |
def actual_shape(self, nlayers: int = 1) -> tuple[int, int]:
"""Return the actual shape of the grid.
This will return the shape parameter, unless one of the row
or column numbers is -1 in which case it will compute the
optimal shape of the grid given the number of layers and
cur... | Return the actual shape of the grid.
This will return the shape parameter, unless one of the row
or column numbers is -1 in which case it will compute the
optimal shape of the grid given the number of layers and
current stride.
If the grid is not enabled, this will return (1, 1... | actual_shape | python | napari/napari | src/napari/components/grid.py | https://github.com/napari/napari/blob/master/src/napari/components/grid.py | BSD-3-Clause |
def position(self, index: int, nlayers: int) -> tuple[int, int]:
"""Return the position of a given linear index in grid.
If the grid is not enabled, this will return (0, 0).
Parameters
----------
index : int
Position of current layer in layer list.
nlayers :... | Return the position of a given linear index in grid.
If the grid is not enabled, this will return (0, 0).
Parameters
----------
index : int
Position of current layer in layer list.
nlayers : int
Number of layers that need to be placed in the grid.
... | position | python | napari/napari | src/napari/components/grid.py | https://github.com/napari/napari/blob/master/src/napari/components/grid.py | BSD-3-Clause |
def _create_contexts(self):
"""Create contexts to manage enabled/visible action/menu states.
Connects LayerList and Selection[Layer] to their context keys to allow
actions and menu items (in the GUI) to be dynamically enabled/disabled
and visible/hidden based on the state of layers in t... | Create contexts to manage enabled/visible action/menu states.
Connects LayerList and Selection[Layer] to their context keys to allow
actions and menu items (in the GUI) to be dynamically enabled/disabled
and visible/hidden based on the state of layers in the list.
| _create_contexts | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def _coerce_name(self, name, layer=None):
"""Coerce a name into a unique equivalent.
Parameters
----------
name : str
Original name.
layer : napari.layers.Layer, optional
Layer for which name is generated.
Returns
-------
new_name... | Coerce a name into a unique equivalent.
Parameters
----------
name : str
Original name.
layer : napari.layers.Layer, optional
Layer for which name is generated.
Returns
-------
new_name : str
Coerced, unique name.
| _coerce_name | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def _update_name(self, event):
"""Coerce name of the layer in `event.layer`."""
layer = event.source
layer.name = self._coerce_name(layer.name, layer) | Coerce name of the layer in `event.layer`. | _update_name | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def remove_selected(self):
"""Remove selected layers from LayerList, but first unlink them."""
if not self.selection:
return
self.unlink_layers(self.selection)
super().remove_selected() | Remove selected layers from LayerList, but first unlink them. | remove_selected | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def _extent_world_augmented(self) -> np.ndarray:
"""Extent of layers in world coordinates.
Default to 2D with (-0.5, 511.5) min/ max values if no data is present.
Corresponds to pixels centered at [0, ..., 511].
Returns
-------
extent_world : array, shape (2, D)
... | Extent of layers in world coordinates.
Default to 2D with (-0.5, 511.5) min/ max values if no data is present.
Corresponds to pixels centered at [0, ..., 511].
Returns
-------
extent_world : array, shape (2, D)
| _extent_world_augmented | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def _get_extent_world(self, layer_extent_list, augmented=False):
"""Extent of layers in world coordinates.
Default to 2D image-like with (0, 511) min/ max values if no data is present.
Corresponds to image with 512 pixels in each dimension.
Returns
-------
extent_world ... | Extent of layers in world coordinates.
Default to 2D image-like with (0, 511) min/ max values if no data is present.
Corresponds to image with 512 pixels in each dimension.
Returns
-------
extent_world : array, shape (2, D)
| _get_extent_world | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def get_extent(self, layers: Iterable[Layer]) -> Extent:
"""
Return extent for a given layer list.
Extent bounds are inclusive. This function is useful for calculating the extent
of a subset of layers when preparing and updating some supplementary layers.
For example see the cro... |
Return extent for a given layer list.
Extent bounds are inclusive. This function is useful for calculating the extent
of a subset of layers when preparing and updating some supplementary layers.
For example see the cross Vectors layer in the `multiple_viewer_widget` example.
P... | get_extent | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def _ranges(self) -> tuple[RangeTuple, ...]:
"""Get ranges for Dims.range in world coordinates."""
ext = self.extent
return tuple(
RangeTuple(*x)
for x in zip(ext.world[0], ext.world[1], ext.step, strict=False)
) | Get ranges for Dims.range in world coordinates. | _ranges | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def link_layers(
self,
layers: Iterable[str | Layer] | None = None,
attributes: Iterable[str] = (),
):
"""
Links the selected layers.
Once layers are linked, any action performed on one layer will be
performed on all linked layers at the same time.
""... |
Links the selected layers.
Once layers are linked, any action performed on one layer will be
performed on all linked layers at the same time.
| link_layers | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def unlink_layers(
self,
layers: Iterable[str | Layer] | None = None,
attributes: Iterable[str] = (),
):
"""Unlinks previously linked layers.
Changes to one of the layer's properties no longer result in the same
changes to the previously linked layers.
"""
... | Unlinks previously linked layers.
Changes to one of the layer's properties no longer result in the same
changes to the previously linked layers.
| unlink_layers | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def save(
self,
path: str,
*,
selected: bool = False,
plugin: str | None = None,
_writer: WriterContribution | None = None,
) -> list[str]:
"""Save all or only selected layers to a path using writer plugins.
If ``plugin`` is not provided and only one ... | Save all or only selected layers to a path using writer plugins.
If ``plugin`` is not provided and only one layer is targeted, then we
directly call the corresponding``napari_write_<layer_type>`` hook (see
:ref:`single layer writer hookspecs <write-single-layer-hookspecs>`)
which will l... | save | python | napari/napari | src/napari/components/layerlist.py | https://github.com/napari/napari/blob/master/src/napari/components/layerlist.py | BSD-3-Clause |
def _update_camera_orientation(self):
"""Update camera orientation based on settings."""
settings = get_settings()
self.camera.orientation = (
settings.application.depth_axis_orientation,
settings.application.vertical_axis_orientation,
settings.application.ho... | Update camera orientation based on settings. | _update_camera_orientation | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _update_viewer_grid(self):
"""Keep viewer grid settings up to date with settings values."""
settings = get_settings()
self.grid.stride = settings.application.grid_stride
self.grid.shape = (
settings.application.grid_height,
settings.application.grid_width,
... | Keep viewer grid settings up to date with settings values. | _update_viewer_grid | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _sliced_extent_world_augmented(self) -> np.ndarray:
"""Extent of layers in world coordinates after slicing.
D is either 2 or 3 depending on if the displayed data is 2D or 3D.
Returns
-------
sliced_extent_world : array, shape (2, D)
"""
# if not layers are p... | Extent of layers in world coordinates after slicing.
D is either 2 or 3 depending on if the displayed data is 2D or 3D.
Returns
-------
sliced_extent_world : array, shape (2, D)
| _sliced_extent_world_augmented | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def reset_view(
self, *, margin: float = 0.05, reset_camera_angle: bool = True
) -> None:
"""Reset the camera and fit the current layers to the canvas.
Resets the angles of the camera, adjust the camera zoom,
and centers the view so that all layers are visible,
accounting fo... | Reset the camera and fit the current layers to the canvas.
Resets the angles of the camera, adjust the camera zoom,
and centers the view so that all layers are visible,
accounting for the current grid mode and margin.
Parameters
----------
margin : float in [0, 1)
... | reset_view | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def fit_to_view(self, *, margin: float = 0.05) -> None:
"""Fit the current data view to the canvas.
Adjusts the camera zoom and centers the view so that all visible layers
are within the canvas, accounting for the current grid mode and margin.
Parameters
----------
marg... | Fit the current data view to the canvas.
Adjusts the camera zoom and centers the view so that all visible layers
are within the canvas, accounting for the current grid mode and margin.
Parameters
----------
margin : float in [0, 1)
Margin as fraction of the canvas, ... | fit_to_view | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _get_scene_parameters(self):
"""Get the scene parameters for the current grid mode.
Returns
-------
extent : array, shape (2, D)
An array with the min/max coordinate values of the layers
First row is min values, second row is max values.
scene_size : ... | Get the scene parameters for the current grid mode.
Returns
-------
extent : array, shape (2, D)
An array with the min/max coordinate values of the layers
First row is min values, second row is max values.
scene_size : array, shape (D,)
Size of the bo... | _get_scene_parameters | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _calculate_view_center(self, corner, total_size):
"""Calculate the center of the view based on the total size."""
center_array = np.add(corner, np.divide(total_size, 2))[
-self.dims.ndisplay :
]
center = cast(
tuple[float, float, float] | tuple[float, float],... | Calculate the center of the view based on the total size. | _calculate_view_center | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _get_scale_factor(self, margin: float) -> float:
"""Get the scale factor for camera zoom with a valid margin."""
if 0 <= margin < 1:
return 1 - margin
raise ValueError(
trans._(
'margin must be between 0 and 1; got {margin} instead.',
d... | Get the scale factor for camera zoom with a valid margin. | _get_scale_factor | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _get_2d_camera_zoom(
self, total_size: np.ndarray, scale_factor: float
) -> float:
"""Get the camera zoom for 2D view."""
scale = np.array(total_size[-2:])
scale[np.isclose(scale, 0)] = 1
return scale_factor * np.min(np.array(self._canvas_size) / scale) | Get the camera zoom for 2D view. | _get_2d_camera_zoom | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _get_3d_camera_zoom(
self, extent: np.ndarray, total_size: np.ndarray, scale_factor: float
) -> float:
"""Calculate the zoom such that the minimum of the bounding box fits the canvas."""
grid_extent = extent.copy()
# calculate max coords with grid spacing included
grid_ex... | Calculate the zoom such that the minimum of the bounding box fits the canvas. | _get_3d_camera_zoom | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _new_labels(self):
"""Create new labels layer filling full world coordinates space."""
layers_extent = self.layers.extent
extent = layers_extent.world
scale = layers_extent.step
scene_size = extent[1] - extent[0]
corner = extent[0]
shape = [
np.rou... | Create new labels layer filling full world coordinates space. | _new_labels | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _on_active_layer(self, event):
"""Update viewer state for a new active layer."""
active_layer = event.value
if active_layer is None:
for layer in self.layers:
layer.update_transform_box_visibility(False)
layer.update_highlight_visibility(False)
... | Update viewer state for a new active layer. | _on_active_layer | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _update_mouse_pan(self, event):
"""Set the viewer interactive mouse panning"""
if event.source is self.layers.selection.active:
self.camera.mouse_pan = event.mouse_pan | Set the viewer interactive mouse panning | _update_mouse_pan | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _update_mouse_zoom(self, event):
"""Set the viewer interactive mouse zoom"""
if event.source is self.layers.selection.active:
self.camera.mouse_zoom = event.mouse_zoom | Set the viewer interactive mouse zoom | _update_mouse_zoom | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def update_status_from_cursor(self):
"""Update the status and tooltip from the cursor position."""
status = self._calc_status_from_cursor()
if status is not None:
self.status, self.tooltip.text = status
if (active := self.layers.selection.active) is not None:
self... | Update the status and tooltip from the cursor position. | update_status_from_cursor | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _on_grid_change(self):
"""Arrange the current layers is a 2D grid."""
extent = self._sliced_extent_world_augmented
n_layers = len(self.layers)
for i, layer in enumerate(self.layers):
i_row, i_column = self.grid.position(n_layers - 1 - i, n_layers)
self._subplo... | Arrange the current layers is a 2D grid. | _on_grid_change | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _subplot(
self,
layer: Layer,
position: tuple[int, int],
extent: np.ndarray,
spacing: float,
):
"""Shift a layer to a specified position in a 2D grid.
Parameters
----------
layer : napari.layers.Layer
Layer that is to be moved.... | Shift a layer to a specified position in a 2D grid.
Parameters
----------
layer : napari.layers.Layer
Layer that is to be moved.
position : 2-tuple of int
New position of layer in grid.
extent : array, shape (2, D)
Extent of the world.
... | _subplot | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def experimental(self):
"""Experimental commands for IPython console.
For example run "viewer.experimental.cmds.loader.help".
"""
from napari.components.experimental.commands import (
ExperimentalNamespace,
)
return ExperimentalNamespace(self.layers) | Experimental commands for IPython console.
For example run "viewer.experimental.cmds.loader.help".
| experimental | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _on_add_layer(self, event):
"""Connect new layer events.
Parameters
----------
event : :class:`napari.layers.Layer`
Layer to add.
"""
layer = event.value
# Connect individual layer events to viewer events
# TODO: in a future PR, we should... | Connect new layer events.
Parameters
----------
event : :class:`napari.layers.Layer`
Layer to add.
| _on_add_layer | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _layer_help_from_mode(layer: Layer):
"""
Update layer help text base on layer mode.
"""
layer_to_func_and_mode: dict[type[Layer], list] = {
Points: points_fun_to_mode,
Labels: labels_fun_to_mode,
Shapes: shapes_fun_to_mode,
Vectors: vec... |
Update layer help text base on layer mode.
| _layer_help_from_mode | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _on_remove_layer(self, event):
"""Disconnect old layer events.
Parameters
----------
event : napari.utils.event.Event
Event which will remove a layer.
Returns
-------
layer : :class:`napari.layers.Layer` or list
The layer that was add... | Disconnect old layer events.
Parameters
----------
event : napari.utils.event.Event
Event which will remove a layer.
Returns
-------
layer : :class:`napari.layers.Layer` or list
The layer that was added (same as input).
| _on_remove_layer | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def add_layer(self, layer: Layer) -> Layer:
"""Add a layer to the viewer.
Parameters
----------
layer : :class:`napari.layers.Layer`
Layer to add.
Returns
-------
layer : :class:`napari.layers.Layer` or list
The layer that was added (same... | Add a layer to the viewer.
Parameters
----------
layer : :class:`napari.layers.Layer`
Layer to add.
Returns
-------
layer : :class:`napari.layers.Layer` or list
The layer that was added (same as input).
| add_layer | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def open_sample(
self,
plugin: str,
sample: str,
reader_plugin: str | None = None,
**kwargs,
) -> list[Layer]:
"""Open `sample` from `plugin` and add it to the viewer.
To see all available samples registered by plugins, use
:func:`napari.plugins.avail... | Open `sample` from `plugin` and add it to the viewer.
To see all available samples registered by plugins, use
:func:`napari.plugins.available_samples`
Parameters
----------
plugin : str
name of a plugin providing a sample
sample : str
name of the... | open_sample | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def open(
self,
path: PathOrPaths,
*,
stack: bool | list[list[PathLike]] = False,
plugin: str | None = 'napari',
layer_type: LayerTypeName | None = None,
**kwargs,
) -> list[Layer]:
"""Open a path or list of paths with plugins, and add layers to viewer... | Open a path or list of paths with plugins, and add layers to viewer.
A list of paths will be handed one-by-one to the napari_get_reader hook
if stack is False, otherwise the full list is passed to each plugin
hook.
Parameters
----------
path : str or list of str
... | open | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _open_or_raise_error(
self,
paths: list[Path | str],
kwargs: Dict[str, Any] | None = None,
layer_type: LayerTypeName | None = None,
stack: bool = False,
):
"""Open paths if plugin choice is unambiguous, raising any errors.
This function will open paths if... | Open paths if plugin choice is unambiguous, raising any errors.
This function will open paths if there is no plugin choice to be made
i.e. there is a preferred reader associated with this file extension,
or there is only one plugin available. Any errors that occur during
the opening pro... | _open_or_raise_error | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _add_layers_with_plugins(
self,
paths: list[PathLike],
*,
stack: bool,
kwargs: Dict | None = None,
plugin: str | None = None,
layer_type: LayerTypeName | None = None,
) -> list[Layer]:
"""Load a path or a list of paths into the viewer using plugins... | Load a path or a list of paths into the viewer using plugins.
This function is mostly called from self.open_path, where the ``stack``
argument determines whether a list of strings is handed to plugins one
at a time, or en-masse.
Parameters
----------
paths : list of str... | _add_layers_with_plugins | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _add_layer_from_data(
self,
data,
meta: Mapping[str, Any] | None = None,
layer_type: str | None = None,
) -> list[Layer]:
"""Add arbitrary layer data to the viewer.
Primarily intended for usage by reader plugin hooks.
Parameters
----------
... | Add arbitrary layer data to the viewer.
Primarily intended for usage by reader plugin hooks.
Parameters
----------
data : Any
Data in a format that is valid for the corresponding `add_*` method
of the specified ``layer_type``.
meta : dict, optional
... | _add_layer_from_data | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _normalize_layer_data(data: LayerData) -> FullLayerData:
"""Accepts any layerdata tuple, and returns a fully qualified tuple.
Parameters
----------
data : LayerData
1-, 2-, or 3-tuple with (data, meta, layer_type).
Returns
-------
FullLayerData
3-tuple with (data, meta,... | Accepts any layerdata tuple, and returns a fully qualified tuple.
Parameters
----------
data : LayerData
1-, 2-, or 3-tuple with (data, meta, layer_type).
Returns
-------
FullLayerData
3-tuple with (data, meta, layer_type)
Raises
------
ValueError
If data h... | _normalize_layer_data | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _unify_data_and_user_kwargs(
data: LayerData,
kwargs: dict | None = None,
layer_type: LayerTypeName | None = None,
fallback_name: str | None = None,
) -> FullLayerData:
"""Merge data returned from plugins with options specified by user.
If ``data == (data_, meta_, type_)``. Then:
- ``... | Merge data returned from plugins with options specified by user.
If ``data == (data_, meta_, type_)``. Then:
- ``kwargs`` will be used to update ``meta_``
- ``layer_type`` will replace ``type_`` and, if provided, ``meta_`` keys
will be pruned to layer_type-appropriate kwargs
- ``fallback_name... | _unify_data_and_user_kwargs | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def prune_kwargs(kwargs: Mapping[str, Any], layer_type: str) -> dict[str, Any]:
"""Return copy of ``kwargs`` with only keys valid for ``add_<layer_type>``
Parameters
----------
kwargs : dict
A key: value mapping where some or all of the keys are parameter names
for the corresponding ``V... | Return copy of ``kwargs`` with only keys valid for ``add_<layer_type>``
Parameters
----------
kwargs : dict
A key: value mapping where some or all of the keys are parameter names
for the corresponding ``Viewer.add_<layer_type>`` method.
layer_type : str
The type of layer that is... | prune_kwargs | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def valid_add_kwargs() -> dict[str, set[str]]:
"""Return a dict where keys are layer types & values are valid kwargs."""
valid = {}
for meth in dir(ViewerModel):
if not meth.startswith('add_') or meth[4:] == 'layer':
continue
params = inspect.signature(getattr(ViewerModel, meth))... | Return a dict where keys are layer types & values are valid kwargs. | valid_add_kwargs | python | napari/napari | src/napari/components/viewer_model.py | https://github.com/napari/napari/blob/master/src/napari/components/viewer_model.py | BSD-3-Clause |
def _make_slice_request(self, dims: Dims) -> _SliceRequest:
"""Makes a callable slice request that returns a response.
This method should run quickly, as it is expected to run on the main thread.
Slower parts of slicing should be moved into the callable request, which can
be run off the... | Makes a callable slice request that returns a response.
This method should run quickly, as it is expected to run on the main thread.
Slower parts of slicing should be moved into the callable request, which can
be run off the main thread.
The request should capture any state it needs fro... | _make_slice_request | python | napari/napari | src/napari/components/_layer_slicer.py | https://github.com/napari/napari/blob/master/src/napari/components/_layer_slicer.py | BSD-3-Clause |
def _update_slice_response(self, response: Any) -> None:
"""Passes through a completed slice response.
This method should run on the main thread and is mostly needed to update
slice state on layers.
""" | Passes through a completed slice response.
This method should run on the main thread and is mostly needed to update
slice state on layers.
| _update_slice_response | python | napari/napari | src/napari/components/_layer_slicer.py | https://github.com/napari/napari/blob/master/src/napari/components/_layer_slicer.py | BSD-3-Clause |
def _set_unloaded_slice_id(self, slice_id: int) -> None:
"""Sets the ID associated with the latest slice request.
This is needed to support ``Layer.loaded`` in async slicing.
This could be done at the end of ``_make_slice_request``, but was separated
to avoid mutations in that method an... | Sets the ID associated with the latest slice request.
This is needed to support ``Layer.loaded`` in async slicing.
This could be done at the end of ``_make_slice_request``, but was separated
to avoid mutations in that method and to clarify responsibilities.
| _set_unloaded_slice_id | python | napari/napari | src/napari/components/_layer_slicer.py | https://github.com/napari/napari/blob/master/src/napari/components/_layer_slicer.py | BSD-3-Clause |
def __init__(self) -> None:
"""
Attributes
----------
_executor : concurrent.futures.ThreadPoolExecutor
manager for the slicing threading
_force_sync: bool
if true, forces slicing to execute synchronously
_layers_to_task : dict of tuples of layer w... |
Attributes
----------
_executor : concurrent.futures.ThreadPoolExecutor
manager for the slicing threading
_force_sync: bool
if true, forces slicing to execute synchronously
_layers_to_task : dict of tuples of layer weakrefs to futures
task sto... | __init__ | python | napari/napari | src/napari/components/_layer_slicer.py | https://github.com/napari/napari/blob/master/src/napari/components/_layer_slicer.py | BSD-3-Clause |
def _slice_layers(self, requests: dict) -> dict:
"""
Iterates through a dictionary of request objects and call the slice
on each individual layer. Can be called from the main or slicing thread.
Attributes
----------
requests: dict[Layer, SliceRequest]
Diction... |
Iterates through a dictionary of request objects and call the slice
on each individual layer. Can be called from the main or slicing thread.
Attributes
----------
requests: dict[Layer, SliceRequest]
Dictionary of request objects to be used for constructing the slice... | _slice_layers | python | napari/napari | src/napari/components/_layer_slicer.py | https://github.com/napari/napari/blob/master/src/napari/components/_layer_slicer.py | BSD-3-Clause |
def _on_slice_done(self, task: Future[dict]) -> None:
"""
This is the "done_callback" which is added to each task.
Can be called from the main or slicing thread.
"""
logger.debug('_LayerSlicer._on_slice_done: %s', id(task))
if not self._try_to_remove_task(task):
... |
This is the "done_callback" which is added to each task.
Can be called from the main or slicing thread.
| _on_slice_done | python | napari/napari | src/napari/components/_layer_slicer.py | https://github.com/napari/napari/blob/master/src/napari/components/_layer_slicer.py | BSD-3-Clause |
def _try_to_remove_task(self, task: Future[dict]) -> bool:
"""
Attempt to remove task, return false if task not found, return true
if task is found and removed from layers_to_task dict.
This function provides a lock to ensure that the layers_to_task dict
is unmodified during thi... |
Attempt to remove task, return false if task not found, return true
if task is found and removed from layers_to_task dict.
This function provides a lock to ensure that the layers_to_task dict
is unmodified during this process.
| _try_to_remove_task | python | napari/napari | src/napari/components/_layer_slicer.py | https://github.com/napari/napari/blob/master/src/napari/components/_layer_slicer.py | BSD-3-Clause |
def _find_existing_task(
self, layers: Iterable[Layer]
) -> Future[dict] | None:
"""Find the task associated with a list of layers. Returns the first
task found for which the layers of the task are a subset of the input
layers.
This function provides a lock to ensure that th... | Find the task associated with a list of layers. Returns the first
task found for which the layers of the task are a subset of the input
layers.
This function provides a lock to ensure that the layers_to_task dict
is unmodified during this process.
| _find_existing_task | python | napari/napari | src/napari/components/_layer_slicer.py | https://github.com/napari/napari/blob/master/src/napari/components/_layer_slicer.py | BSD-3-Clause |
def register_viewer_action(description, repeatable=False):
"""
Convenient decorator to register an action with the current ViewerModel
It will use the function name as the action name. We force the description
to be given instead of function docstring for translation purpose.
"""
def _inner(fu... |
Convenient decorator to register an action with the current ViewerModel
It will use the function name as the action name. We force the description
to be given instead of function docstring for translation purpose.
| register_viewer_action | python | napari/napari | src/napari/components/_viewer_key_bindings.py | https://github.com/napari/napari/blob/master/src/napari/components/_viewer_key_bindings.py | BSD-3-Clause |
def _show_only_selected_layer(viewer):
"""Helper function to show only selected layer"""
for layer in viewer.layers:
if layer not in viewer.layers.selection:
layer.visible = False
else:
layer.visible = True | Helper function to show only selected layer | _show_only_selected_layer | python | napari/napari | src/napari/components/_viewer_key_bindings.py | https://github.com/napari/napari/blob/master/src/napari/components/_viewer_key_bindings.py | BSD-3-Clause |
def double_click_to_zoom(viewer, event):
"""Zoom in on double click by zoom_factor; zoom out with Alt."""
if (
viewer.layers.selection.active
and viewer.layers.selection.active.mode != 'pan_zoom'
):
return
# if Alt held down, zoom out instead
zoom_factor = 0.5 if 'Alt' in eve... | Zoom in on double click by zoom_factor; zoom out with Alt. | double_click_to_zoom | python | napari/napari | src/napari/components/_viewer_mouse_bindings.py | https://github.com/napari/napari/blob/master/src/napari/components/_viewer_mouse_bindings.py | BSD-3-Clause |
def _process_client_messages(self) -> None:
"""Process every new message in the queue."""
client_messages = self._remote.client_messages
while True:
try:
message = client_messages.get_nowait()
if not isinstance(message, dict):
LOG... | Process every new message in the queue. | _process_client_messages | python | napari/napari | src/napari/components/experimental/monitor/_api.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_api.py | BSD-3-Clause |
def _load_config(path: str) -> dict:
"""Load the JSON formatted config file.
Parameters
----------
path : str
The path of the JSON file we should load.
Returns
-------
dict
The parsed data from the JSON file.
"""
path = Path(path).expanduser()
if not path.exists... | Load the JSON formatted config file.
Parameters
----------
path : str
The path of the JSON file we should load.
Returns
-------
dict
The parsed data from the JSON file.
| _load_config | python | napari/napari | src/napari/components/experimental/monitor/_monitor.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_monitor.py | BSD-3-Clause |
def _load_monitor_config() -> dict | None:
"""Return the MonitorService config file data, or None.
Returns
-------
Optional[dict]
The parsed config file data or None if no config.
"""
# We shouldn't even call into this file unless NAPARI_MON is defined
# but check to be sure.
va... | Return the MonitorService config file data, or None.
Returns
-------
Optional[dict]
The parsed config file data or None if no config.
| _load_monitor_config | python | napari/napari | src/napari/components/experimental/monitor/_monitor.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_monitor.py | BSD-3-Clause |
def _setup_logging(config: dict) -> None:
"""Log "napari.monitor" messages to the configured file.
Parameters
----------
config : dict
Monitor configuration
"""
try:
log_path = config['log_path']
except KeyError:
return # No log file.
# Nuke/reset log for now.
... | Log "napari.monitor" messages to the configured file.
Parameters
----------
config : dict
Monitor configuration
| _setup_logging | python | napari/napari | src/napari/components/experimental/monitor/_monitor.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_monitor.py | BSD-3-Clause |
def _get_monitor_config() -> dict | None:
"""Create and return the configuration for the MonitorService.
The routine might return None for one serveral reasons:
1) We're not running under Python 3.9 or now.
2) The monitor is explicitly disable, ENABLED_MONITOR is False.
3) The NAPARI_MON environmen... | Create and return the configuration for the MonitorService.
The routine might return None for one serveral reasons:
1) We're not running under Python 3.9 or now.
2) The monitor is explicitly disable, ENABLED_MONITOR is False.
3) The NAPARI_MON environment variable is not defined.
4) The NAPARI_MON ... | _get_monitor_config | python | napari/napari | src/napari/components/experimental/monitor/_monitor.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_monitor.py | BSD-3-Clause |
def start(self) -> bool:
"""Start the monitor service, if it hasn't been started already.
Returns
-------
bool
True if we started the service or it was already started.
"""
if self._running:
return True # It was already started.
config =... | Start the monitor service, if it hasn't been started already.
Returns
-------
bool
True if we started the service or it was already started.
| start | python | napari/napari | src/napari/components/experimental/monitor/_monitor.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_monitor.py | BSD-3-Clause |
def on_poll(self, event) -> None:
"""The QtPoll object polls us.
Probably we could get rid of polling by creating a thread that
blocks waiting for client messages. Then it posts those messages as
Qt Events. So the GUI doesn't block, but gracefully handles
incoming messages as Qt... | The QtPoll object polls us.
Probably we could get rid of polling by creating a thread that
blocks waiting for client messages. Then it posts those messages as
Qt Events. So the GUI doesn't block, but gracefully handles
incoming messages as Qt events.
| on_poll | python | napari/napari | src/napari/components/experimental/monitor/_monitor.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_monitor.py | BSD-3-Clause |
def _create_client_env(server_port: int) -> dict:
"""Create and return the environment for the client.
Parameters
----------
server_port : int
The port the client should connect to.
"""
# Every client gets the same config. Copy template and then stuff
# in the correct values.
cl... | Create and return the environment for the client.
Parameters
----------
server_port : int
The port the client should connect to.
| _create_client_env | python | napari/napari | src/napari/components/experimental/monitor/_service.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_service.py | BSD-3-Clause |
def _start_clients(self) -> None:
"""Start every client in our config."""
# We asked for port 0 which means the OS will pick a port, we
# save it off so we can send it the clients are starting up.
server_port = self._manager.address[1]
LOGGER.info('Listening on port %s', server_p... | Start every client in our config. | _start_clients | python | napari/napari | src/napari/components/experimental/monitor/_service.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_service.py | BSD-3-Clause |
def base64_encoded_json(data: dict) -> str:
"""Return base64 encoded version of this data as JSON.
Parameters
----------
data : dict
The data to write as JSON then base64 encode.
Returns
-------
str
The base64 encoded JSON string.
"""
json_str = numpy_dumps(data)
... | Return base64 encoded version of this data as JSON.
Parameters
----------
data : dict
The data to write as JSON then base64 encode.
Returns
-------
str
The base64 encoded JSON string.
| base64_encoded_json | python | napari/napari | src/napari/components/experimental/monitor/_utils.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/monitor/_utils.py | BSD-3-Clause |
def process_command(self, event) -> None:
"""Process this one command from the remote client.
Parameters
----------
event : dict
The remote command.
"""
command = event.command
LOGGER.info('RemoveCommands._process_command: %s', json.dumps(command))
... | Process this one command from the remote client.
Parameters
----------
event : dict
The remote command.
| process_command | python | napari/napari | src/napari/components/experimental/remote/_commands.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/remote/_commands.py | BSD-3-Clause |
def on_poll(self) -> None:
"""Send messages to clients.
These message go out once per frame. So it might not make sense to
include static information that rarely changes. Although if it's
small, maybe it's okay.
The message looks like:
{
"poll": {
... | Send messages to clients.
These message go out once per frame. So it might not make sense to
include static information that rarely changes. Although if it's
small, maybe it's okay.
The message looks like:
{
"poll": {
"layers": {
... | on_poll | python | napari/napari | src/napari/components/experimental/remote/_messages.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/remote/_messages.py | BSD-3-Clause |
def _send_frame_time(self) -> None:
"""Send the frame time since last poll."""
now = time.time()
last = self._last_time
delta = now - last if last is not None else 0
delta_ms = delta * 1000
monitor.send_message(
{'frame_time': {'time': now, 'delta_ms': delta_... | Send the frame time since last poll. | _send_frame_time | python | napari/napari | src/napari/components/experimental/remote/_messages.py | https://github.com/napari/napari/blob/master/src/napari/components/experimental/remote/_messages.py | BSD-3-Clause |
def test_add_layers_with_plugins(layer_datum):
"""Test that add_layers_with_plugins adds the expected layer types."""
with patch(
'napari.plugins.io.read_data_with_plugins',
MagicMock(return_value=([layer_datum], _testimpl)),
):
v = ViewerModel()
v._add_layers_with_plugins(['... | Test that add_layers_with_plugins adds the expected layer types. | test_add_layers_with_plugins | python | napari/napari | src/napari/components/_tests/test_add_layers.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_add_layers.py | BSD-3-Clause |
def test_add_layers_with_plugins_full_layers(layer):
"""Test that add_layers_with_plugins works for full Layer objects."""
with patch(
'napari.plugins.io.read_data_with_plugins',
MagicMock(return_value=([layer], _testimpl)),
):
v = ViewerModel()
v._add_layers_with_plugins(['m... | Test that add_layers_with_plugins works for full Layer objects. | test_add_layers_with_plugins_full_layers | python | napari/napari | src/napari/components/_tests/test_add_layers.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_add_layers.py | BSD-3-Clause |
def test_add_layers_with_plugins_layer_mix(layer):
"""Test add_layers_with_plugins handles mixed Layer and LayerDataTuple."""
layer_tuple = layer.as_layer_data_tuple()
with patch(
'napari.plugins.io.read_data_with_plugins',
# return one instantiated layer and one layer tuple
MagicMoc... | Test add_layers_with_plugins handles mixed Layer and LayerDataTuple. | test_add_layers_with_plugins_layer_mix | python | napari/napari | src/napari/components/_tests/test_add_layers.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_add_layers.py | BSD-3-Clause |
def test_plugin_returns_nothing():
"""Test that a plugin returning nothing adds nothing to the Viewer."""
v = ViewerModel()
v._add_layers_with_plugins(['mock_path'], stack=False)
assert not v.layers | Test that a plugin returning nothing adds nothing to the Viewer. | test_plugin_returns_nothing | python | napari/napari | src/napari/components/_tests/test_add_layers.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_add_layers.py | BSD-3-Clause |
def test_viewer_open():
"""Test that a plugin to returning an image adds stuff to the viewer."""
viewer = ViewerModel()
assert len(viewer.layers) == 0
viewer.open('mock_path.tif')
assert len(viewer.layers) == 1
# The name should be taken from the path name, stripped of extension
assert viewe... | Test that a plugin to returning an image adds stuff to the viewer. | test_viewer_open | python | napari/napari | src/napari/components/_tests/test_add_layers.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_add_layers.py | BSD-3-Clause |
def test_add_layers_with_plugins_and_kwargs(layer_data, kwargs):
"""Test that _add_layers_with_plugins kwargs override plugin kwargs.
see also: napari.components._test.test_prune_kwargs
"""
with patch(
'napari.plugins.io.read_data_with_plugins',
MagicMock(return_value=(layer_data, _test... | Test that _add_layers_with_plugins kwargs override plugin kwargs.
see also: napari.components._test.test_prune_kwargs
| test_add_layers_with_plugins_and_kwargs | python | napari/napari | src/napari/components/_tests/test_add_layers.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_add_layers.py | BSD-3-Clause |
def test_add_points_layer_with_different_range_updates_all_slices():
"""See https://github.com/napari/napari/pull/4819"""
viewer = ViewerModel()
# Adding the first point should show the point
initial_point = viewer.add_points([[10, 5, 5]])
np.testing.assert_array_equal(initial_point._indices_view, ... | See https://github.com/napari/napari/pull/4819 | test_add_points_layer_with_different_range_updates_all_slices | python | napari/napari | src/napari/components/_tests/test_add_layers.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_add_layers.py | BSD-3-Clause |
def test_calculate_view_direction_3d():
"""Check that view direction is calculated properly from camera angles."""
# simple case
camera = Camera(center=(0, 0, 0), angles=(90, 0, 0), zoom=1)
assert np.allclose(camera.view_direction, (0, 1, 0))
# shouldn't change with zoom
camera = Camera(center=... | Check that view direction is calculated properly from camera angles. | test_calculate_view_direction_3d | python | napari/napari | src/napari/components/_tests/test_camera.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_camera.py | BSD-3-Clause |
def test_calculate_up_direction_3d():
"""Check that up direction is calculated properly from camera angles."""
# simple case
camera = Camera(center=(0, 0, 0), angles=(0, 0, 90), zoom=1)
assert np.allclose(camera.up_direction, (0, -1, 0))
# shouldn't change with zoom
camera = Camera(center=(0, 0... | Check that up direction is calculated properly from camera angles. | test_calculate_up_direction_3d | python | napari/napari | src/napari/components/_tests/test_camera.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_camera.py | BSD-3-Clause |
def test_set_view_direction_3d():
"""Check that view direction can be set properly."""
# simple case
camera = Camera(center=(0, 0, 0), angles=(0, 0, 0), zoom=1)
camera.set_view_direction(view_direction=(1, 0, 0))
assert np.allclose(camera.view_direction, (1, 0, 0))
assert np.allclose(_normalize_... | Check that view direction can be set properly. | test_set_view_direction_3d | python | napari/napari | src/napari/components/_tests/test_camera.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_camera.py | BSD-3-Clause |
def test_calculate_view_direction_nd():
"""Check that nD view direction is calculated properly."""
camera = Camera(center=(0, 0, 0), angles=(90, 0, 0), zoom=1)
# should return none if ndim == 2
view_direction = camera.calculate_nd_view_direction(
ndim=2, dims_displayed=[0, 1]
)
assert v... | Check that nD view direction is calculated properly. | test_calculate_view_direction_nd | python | napari/napari | src/napari/components/_tests/test_camera.py | https://github.com/napari/napari/blob/master/src/napari/components/_tests/test_camera.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.