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 track_labels(self) -> tuple:
"""return track labels at the current time"""
assert self.current_time is not None
labels, positions = self._manager.track_labels(self.current_time)
# if there are no labels, return empty for vispy
if not labels:
return None, (None, N... | return track labels at the current time | track_labels | python | napari/napari | src/napari/layers/tracks/tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/tracks.py | BSD-3-Clause |
def _fast_points_lookup(sorted_time: np.ndarray) -> dict[int, slice]:
"""Computes a fast lookup table from time to their respective points slicing."""
# finds where t transitions to t + 1
transitions = np.nonzero(sorted_time[:-1] - sorted_time[1:])[0] + 1
start = np.insert(transitions, ... | Computes a fast lookup table from time to their respective points slicing. | _fast_points_lookup | python | napari/napari | src/napari/layers/tracks/_track_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_track_utils.py | BSD-3-Clause |
def data(self, data: list | np.ndarray) -> None:
"""set the vertex data and build the vispy arrays for display"""
# convert data to a numpy array if it is not already one
data = np.asarray(data)
# check check the formatting of the incoming track data
data = self._validate_track... | set the vertex data and build the vispy arrays for display | data | python | napari/napari | src/napari/layers/tracks/_track_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_track_utils.py | BSD-3-Clause |
def vertex_properties(self, color_by: str) -> np.ndarray:
"""return the properties of tracks by vertex"""
if color_by not in self.properties:
raise ValueError(
trans._(
'Property {color_by} not found',
deferred=True,
... | return the properties of tracks by vertex | vertex_properties | python | napari/napari | src/napari/layers/tracks/_track_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_track_utils.py | BSD-3-Clause |
def get_value(self, coords: npt.NDArray) -> npt.NDArray | None:
"""use a kd-tree to lookup the ID of the nearest tree"""
if self._kdtree is None:
return None
# query can return indices to points that do not exist, trim that here
# then prune to only those in the current fram... | use a kd-tree to lookup the ID of the nearest tree | get_value | python | napari/napari | src/napari/layers/tracks/_track_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_track_utils.py | BSD-3-Clause |
def max_time(self) -> int | None:
"""Determine the maximum timestamp of the dataset"""
if self.track_times is not None:
return int(np.max(self.track_times))
return None | Determine the maximum timestamp of the dataset | max_time | python | napari/napari | src/napari/layers/tracks/_track_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_track_utils.py | BSD-3-Clause |
def track_times(self) -> np.ndarray | None:
"""time points associated with each track vertex"""
if self.track_vertices is not None:
return self.track_vertices[:, 0]
return None | time points associated with each track vertex | track_times | python | napari/napari | src/napari/layers/tracks/_track_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_track_utils.py | BSD-3-Clause |
def graph_times(self) -> np.ndarray | None:
"""time points associated with each graph vertex"""
if self.graph_vertices is not None:
return self.graph_vertices[:, 0]
return None | time points associated with each graph vertex | graph_times | python | napari/napari | src/napari/layers/tracks/_track_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_track_utils.py | BSD-3-Clause |
def test_tracks_layer_2dt_ndim(data):
"""Test instantiating Tracks layer, check 2D+t dimensionality."""
layer = Tracks(data)
assert layer.ndim == 3 | Test instantiating Tracks layer, check 2D+t dimensionality. | test_tracks_layer_2dt_ndim | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_tracks_layer_3dt_ndim(data):
"""Test instantiating Tracks layer, check 3D+t dimensionality."""
layer = Tracks(data)
assert layer.ndim == 4 | Test instantiating Tracks layer, check 3D+t dimensionality. | test_tracks_layer_3dt_ndim | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_track_layer_data_nonzero_starting_time(timestamps):
"""Test data with sparse timestamps or not starting at zero."""
data = np.zeros((100, 4))
data[:, 1] = timestamps
layer = Tracks(data)
np.testing.assert_array_equal(layer.data, data) | Test data with sparse timestamps or not starting at zero. | test_track_layer_data_nonzero_starting_time | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_track_layer_colorby_nonexistent():
"""Test error handling for non-existent properties with color_by"""
data = np.zeros((100, 4))
data[:, 1] = np.arange(100)
non_existant_property = 'not_a_valid_key'
assert non_existant_property not in properties_dict
with pytest.raises(ValueError, match... | Test error handling for non-existent properties with color_by | test_track_layer_colorby_nonexistent | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_track_layer_properties_changed_colorby():
"""Test behaviour when changes to properties invalidate current color_by"""
properties_dict_1 = {'time': np.arange(100), 'prop1': np.arange(100)}
properties_dict_2 = {'time': np.arange(100), 'prop2': np.arange(100)}
data = np.zeros((100, 4))
data[:,... | Test behaviour when changes to properties invalidate current color_by | test_track_layer_properties_changed_colorby | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_track_layer_reset_data():
"""Test changing data once layer is instantiated."""
data = np.zeros((100, 4))
data[:, 1] = np.arange(100)
data[50:, 0] = 1
properties = {'time': data[:, 1]}
graph = {1: [0]}
layer = Tracks(data, graph=graph, properties=properties)
cropped_data = data[:... | Test changing data once layer is instantiated. | test_track_layer_reset_data | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_tracks_float_time_index():
"""Test Tracks layer instantiation with floating point time values"""
coords = np.random.normal(loc=50, size=(100, 2))
time = np.random.normal(loc=50, size=(100, 1))
track_id = np.zeros((100, 1))
track_id[50:] = 1
data = np.concatenate((track_id, time, coords)... | Test Tracks layer instantiation with floating point time values | test_tracks_float_time_index | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_tracks_length_change():
"""Test changing length properties of tracks"""
track_length = 1000
data = np.zeros((track_length, 4))
layer = Tracks(data)
layer.tail_length = track_length
assert layer.tail_length == track_length
assert layer._max_length == track_length
layer = Tracks(... | Test changing length properties of tracks | test_tracks_length_change | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_single_time_tracks() -> None:
"""Edge case where all tracks belong to a single time"""
# track_id, t, y, x
tracks = [[0, 5, 2, 3], [1, 5, 3, 4], [2, 5, 4, 5]]
layer = Tracks(tracks)
np.testing.assert_array_equal(layer.data, tracks) | Edge case where all tracks belong to a single time | test_single_time_tracks | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_track_ids_ordering() -> None:
"""Check if tracks ids are correctly set to features when given not-sorted tracks."""
# track_id, t, y, x
unsorted_data = np.asarray(
[[1, 1, 0, 0], [0, 1, 0, 0], [2, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0]]
)
sorted_track_ids = [0, 0, 1, 1, 2] # track_id... | Check if tracks ids are correctly set to features when given not-sorted tracks. | test_track_ids_ordering | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_changing_data_inplace() -> None:
"""Test if layer can be refreshed after changing data in place."""
data = np.ones((100, 4))
data[:, 1] = np.arange(100)
layer = Tracks(data)
# Change data in place
# coordinates
layer.data[50:, -1] = 2
layer.refresh()
# time
layer.dat... | Test if layer can be refreshed after changing data in place. | test_changing_data_inplace | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_track_connex_validity() -> None:
"""Test if track_connex is valid (i.e if the value False appears as many
times as there are tracks."""
data = np.zeros((11, 4))
# Track ids
data[:-1, 0] = np.repeat(np.arange(1, 6), 2)
# create edge case where a track has length one
data[-1, 0] = 6... | Test if track_connex is valid (i.e if the value False appears as many
times as there are tracks. | test_track_connex_validity | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def test_track_coloring() -> None:
"""Test if the track colors are correctly set."""
data = np.zeros((100, 4))
data[:, 1] = np.arange(100)
layer = Tracks(data)
colors = np.random.random(size=(100, 4))
layer.track_colors = colors
assert np.array_equal(layer._track_colors, colors) | Test if the track colors are correctly set. | test_track_coloring | python | napari/napari | src/napari/layers/tracks/_tests/test_tracks.py | https://github.com/napari/napari/blob/master/src/napari/layers/tracks/_tests/test_tracks.py | BSD-3-Clause |
def validate(
cls, value: Union['ColorEncoding', dict, str, ColorType]
) -> 'ColorEncoding':
"""Validates and coerces a value to a ColorEncoding.
Parameters
----------
value : ColorEncodingArgument
The value to validate and coerce.
If this is already ... | Validates and coerces a value to a ColorEncoding.
Parameters
----------
value : ColorEncodingArgument
The value to validate and coerce.
If this is already a ColorEncoding, it is returned as is.
If this is a dict, then it should represent one of the built-in c... | validate | python | napari/napari | src/napari/layers/utils/color_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_encoding.py | BSD-3-Clause |
def _set_color(
self,
color: ColorType,
n_colors: int,
properties: dict[str, np.ndarray],
current_properties: dict[str, np.ndarray],
):
"""Set a color property. This is convenience function
Parameters
----------
color : (N, 4) array or str
... | Set a color property. This is convenience function
Parameters
----------
color : (N, 4) array or str
The value for setting edge or face_color
n_colors : int
The number of colors that needs to be set. Typically len(data).
properties : Dict[str, np.ndarray]... | _set_color | python | napari/napari | src/napari/layers/utils/color_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager.py | BSD-3-Clause |
def _refresh_colors(
self,
properties: dict[str, np.ndarray],
update_color_mapping: bool = False,
):
"""Calculate and update colors if using a cycle or color map
Parameters
----------
properties : Dict[str, np.ndarray]
The layer properties to use to... | Calculate and update colors if using a cycle or color map
Parameters
----------
properties : Dict[str, np.ndarray]
The layer properties to use to update the colors.
update_color_mapping : bool
If set to True, the function will recalculate the color cycle map
... | _refresh_colors | python | napari/napari | src/napari/layers/utils/color_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager.py | BSD-3-Clause |
def _remove(self, indices_to_remove: set | list | np.ndarray):
"""Remove the indicated color elements
Parameters
----------
indices_to_remove : set, list, np.ndarray
The indices of the text elements to remove.
"""
selected_indices = list(indices_to_remove)
... | Remove the indicated color elements
Parameters
----------
indices_to_remove : set, list, np.ndarray
The indices of the text elements to remove.
| _remove | python | napari/napari | src/napari/layers/utils/color_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager.py | BSD-3-Clause |
def _paste(self, colors: np.ndarray, properties: dict[str, np.ndarray]):
"""Append colors to the ColorManager. Uses the color values if
in direct mode and the properties in colormap or cycle mode.
This method is for compatibility with the paste functionality
in the layers.
Para... | Append colors to the ColorManager. Uses the color values if
in direct mode and the properties in colormap or cycle mode.
This method is for compatibility with the paste functionality
in the layers.
Parameters
----------
colors : np.ndarray
The (Nx4) color ar... | _paste | python | napari/napari | src/napari/layers/utils/color_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager.py | BSD-3-Clause |
def _update_current_properties(
self, current_properties: dict[str, np.ndarray]
):
"""This is updates the current_value of the color_properties when the
layer current_properties is updated.
This is a convenience method that is generally only called by the layer.
Parameters
... | This is updates the current_value of the color_properties when the
layer current_properties is updated.
This is a convenience method that is generally only called by the layer.
Parameters
----------
current_properties : Dict[str, np.ndarray]
The new current property... | _update_current_properties | python | napari/napari | src/napari/layers/utils/color_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager.py | BSD-3-Clause |
def _update_current_color(
self, current_color: np.ndarray, update_indices: list | None = None
):
"""Update the current color and update the colors if requested.
This is a convenience method and is generally called by the layer.
Parameters
----------
current_color :... | Update the current color and update the colors if requested.
This is a convenience method and is generally called by the layer.
Parameters
----------
current_color : np.ndarray
The new current color value.
update_indices : list
The indices of the color e... | _update_current_color | python | napari/napari | src/napari/layers/utils/color_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager.py | BSD-3-Clause |
def _from_layer_kwargs(
cls,
colors: dict | str | np.ndarray,
properties: dict[str, np.ndarray],
n_colors: int | None = None,
continuous_colormap: str | Colormap | None = None,
contrast_limits: tuple[float, float] | None = None,
categorical_colormap: CategoricalCo... | Initialize a ColorManager object from layer kwargs. This is a convenience
function to coerce possible inputs into ColorManager kwargs
| _from_layer_kwargs | python | napari/napari | src/napari/layers/utils/color_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager.py | BSD-3-Clause |
def guess_continuous(color_map: np.ndarray) -> bool:
"""Guess if the property is continuous (return True) or categorical (return False)
The property is guessed as continuous if it is a float or contains over 16 elements.
Parameters
----------
color_map : np.ndarray
The property values to g... | Guess if the property is continuous (return True) or categorical (return False)
The property is guessed as continuous if it is a float or contains over 16 elements.
Parameters
----------
color_map : np.ndarray
The property values to guess if they are continuous
Returns
-------
con... | guess_continuous | python | napari/napari | src/napari/layers/utils/color_manager_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager_utils.py | BSD-3-Clause |
def _validate_colormap_mode(
values: dict[str, Any],
) -> tuple[np.ndarray, dict[str, Any]]:
"""Validate the ColorManager field values specific for colormap mode
This is called by the root_validator in ColorManager
Parameters
----------
values : dict
The field values that are passed to ... | Validate the ColorManager field values specific for colormap mode
This is called by the root_validator in ColorManager
Parameters
----------
values : dict
The field values that are passed to the ColorManager root validator
Returns
-------
colors : np.ndarray
The (Nx4) color... | _validate_colormap_mode | python | napari/napari | src/napari/layers/utils/color_manager_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager_utils.py | BSD-3-Clause |
def _validate_cycle_mode(
values: dict[str, Any],
) -> tuple[np.ndarray, dict[str, Any]]:
"""Validate the ColorManager field values specific for color cycle mode
This is called by the root_validator in ColorManager
Parameters
----------
values : dict
The field values that are passed to ... | Validate the ColorManager field values specific for color cycle mode
This is called by the root_validator in ColorManager
Parameters
----------
values : dict
The field values that are passed to the ColorManager root validator
Returns
-------
colors : np.ndarray
The (Nx4) co... | _validate_cycle_mode | python | napari/napari | src/napari/layers/utils/color_manager_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_manager_utils.py | BSD-3-Clause |
def transform_color_with_defaults(
num_entries: int, colors: ColorType, elem_name: str, default: str
) -> np.ndarray:
"""Helper method to return an Nx4 np.array from an arbitrary user input.
Parameters
----------
num_entries : int
The number of data elements in the layer
colors : ColorT... | Helper method to return an Nx4 np.array from an arbitrary user input.
Parameters
----------
num_entries : int
The number of data elements in the layer
colors : ColorType
The wanted colors for each of the data points
elem_name : str
Element we're trying to set the color, for ... | transform_color_with_defaults | python | napari/napari | src/napari/layers/utils/color_transformations.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_transformations.py | BSD-3-Clause |
def transform_color_cycle(
color_cycle: ColorType, elem_name: str, default: str
) -> tuple['cycle[np.ndarray]', np.ndarray]:
"""Helper method to return an Nx4 np.array from an arbitrary user input.
Parameters
----------
color_cycle : ColorType
The desired colors for each of the data points
... | Helper method to return an Nx4 np.array from an arbitrary user input.
Parameters
----------
color_cycle : ColorType
The desired colors for each of the data points
elem_name : str
Whether we're trying to set the face color or edge color of the layer
default : str
The default ... | transform_color_cycle | python | napari/napari | src/napari/layers/utils/color_transformations.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_transformations.py | BSD-3-Clause |
def normalize_and_broadcast_colors(
num_entries: int, colors: np.ndarray
) -> np.ndarray:
"""Takes an input color array and forces into being the length of ``data``.
Used when a single color is supplied for many input objects, but we need
Layer.current_face_color or Layer.current_edge_color to have the... | Takes an input color array and forces into being the length of ``data``.
Used when a single color is supplied for many input objects, but we need
Layer.current_face_color or Layer.current_edge_color to have the shape of
the actual data.
Note: This function can't robustly parse user input, and thus sho... | normalize_and_broadcast_colors | python | napari/napari | src/napari/layers/utils/color_transformations.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/color_transformations.py | BSD-3-Clause |
def generate_interaction_box_vertices(
top_left: tuple[float, float],
bot_right: tuple[float, float],
handles: bool = True,
rotation: bool = True,
) -> np.ndarray:
"""
Generate coordinates for all the handles in InteractionBoxHandle.
Coordinates are assumed to follow vispy "y down" conventi... |
Generate coordinates for all the handles in InteractionBoxHandle.
Coordinates are assumed to follow vispy "y down" convention.
Parameters
----------
top_left : Tuple[float, float]
Top-left corner of the box
bot_right : Tuple[float, float]
Bottom-right corner of the box
han... | generate_interaction_box_vertices | python | napari/napari | src/napari/layers/utils/interaction_box.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/interaction_box.py | BSD-3-Clause |
def generate_transform_box_from_layer(
layer: Layer, dims_displayed: tuple[int, int]
) -> np.ndarray:
"""
Generate coordinates for the handles of a layer's transform box.
Parameters
----------
layer : Layer
Layer whose transform box to generate.
dims_displayed : Tuple[int, ...]
... |
Generate coordinates for the handles of a layer's transform box.
Parameters
----------
layer : Layer
Layer whose transform box to generate.
dims_displayed : Tuple[int, ...]
Dimensions currently displayed (must be 2).
Returns
-------
np.ndarray
Vertices and handl... | generate_transform_box_from_layer | python | napari/napari | src/napari/layers/utils/interaction_box.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/interaction_box.py | BSD-3-Clause |
def calculate_bounds_from_contained_points(
points: np.ndarray,
) -> tuple[tuple[float, float], tuple[float, float]]:
"""
Calculate the top-left and bottom-right corners of an axis-aligned bounding box.
Parameters
----------
points : np.ndarray
Array of point coordinates.
Returns
... |
Calculate the top-left and bottom-right corners of an axis-aligned bounding box.
Parameters
----------
points : np.ndarray
Array of point coordinates.
Returns
-------
Tuple[Tuple[float, float], Tuple[float, float]]
Top-left and bottom-right corners of the bounding box.
... | calculate_bounds_from_contained_points | python | napari/napari | src/napari/layers/utils/interaction_box.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/interaction_box.py | BSD-3-Clause |
def get_nearby_handle(
position: np.ndarray, handle_coordinates: np.ndarray
) -> InteractionBoxHandle | None:
"""
Get the InteractionBoxHandle close to the given position, within tolerance.
Parameters
----------
position : np.ndarray
Position to query for.
handle_coordinates : np.nd... |
Get the InteractionBoxHandle close to the given position, within tolerance.
Parameters
----------
position : np.ndarray
Position to query for.
handle_coordinates : np.ndarray
Coordinates of all the handles (except INSIDE).
Returns
-------
Optional[InteractionBoxHandle]... | get_nearby_handle | python | napari/napari | src/napari/layers/utils/interaction_box.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/interaction_box.py | BSD-3-Clause |
def displayed_plane_from_nd_line_segment(
start_point: npt.NDArray,
end_point: npt.NDArray,
dims_displayed: list[int] | npt.NDArray,
) -> tuple[npt.NDArray, npt.NDArray]:
"""Get the plane defined by start_point and the normal vector that goes
from start_point to end_point.
Note the start_point ... | Get the plane defined by start_point and the normal vector that goes
from start_point to end_point.
Note the start_point and end_point are nD and
the returned plane is in the displayed dimensions (i.e., 3D).
Parameters
----------
start_point : np.ndarray
The start point of the line seg... | displayed_plane_from_nd_line_segment | python | napari/napari | src/napari/layers/utils/interactivity_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/interactivity_utils.py | BSD-3-Clause |
def drag_data_to_projected_distance(
start_position: npt.NDArray,
end_position: npt.NDArray,
view_direction: npt.NDArray,
vector: npt.NDArray,
) -> npt.NDArray:
"""Calculate the projected distance between two mouse events.
Project the drag vector between two mouse events onto a 3D vector
sp... | Calculate the projected distance between two mouse events.
Project the drag vector between two mouse events onto a 3D vector
specified in data coordinates.
The general strategy is to
1) find mouse drag start and end positions, project them onto a
pseudo-canvas (a plane aligned with the canvas) ... | drag_data_to_projected_distance | python | napari/napari | src/napari/layers/utils/interactivity_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/interactivity_utils.py | BSD-3-Clause |
def orient_plane_normal_around_cursor(
layer: Image, plane_normal: tuple
) -> None:
"""Orient a rendering plane by rotating it around the cursor.
If the cursor ray does not intersect the plane, the position will remain
unchanged.
Parameters
----------
layer : Image
The layer on whi... | Orient a rendering plane by rotating it around the cursor.
If the cursor ray does not intersect the plane, the position will remain
unchanged.
Parameters
----------
layer : Image
The layer on which the rendering plane is to be rotated
plane_normal : 3-tuple
The target plane nor... | orient_plane_normal_around_cursor | python | napari/napari | src/napari/layers/utils/interactivity_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/interactivity_utils.py | BSD-3-Clause |
def nd_line_segment_to_displayed_data_ray(
start_point: np.ndarray,
end_point: np.ndarray,
dims_displayed: list[int] | np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""Convert the start and end point of the line segment of a mouse click ray
intersecting a data cube to a ray (i.e., start position a... | Convert the start and end point of the line segment of a mouse click ray
intersecting a data cube to a ray (i.e., start position and direction) in
displayed data coordinates
Note: the ray starts 0.1 data units outside of the data volume.
Parameters
----------
start_point : np.ndarray
T... | nd_line_segment_to_displayed_data_ray | python | napari/napari | src/napari/layers/utils/interactivity_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/interactivity_utils.py | BSD-3-Clause |
def register_layer_action(
keymapprovider,
description: str,
repeatable: bool = False,
shortcuts: str | list[str] | None = None,
) -> Callable[[Callable], Callable]:
"""
Convenient decorator to register an action with the current Layers
It will use the function name as the action name. We f... |
Convenient decorator to register an action with the current Layers
It will use the function name as the action name. We force the description
to be given instead of function docstring for translation purpose.
Parameters
----------
keymapprovider : KeymapProvider
class on which to reg... | register_layer_action | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def register_layer_attr_action(
keymapprovider,
description: str,
attribute_name: str,
shortcuts=None,
) -> Callable[[Callable], Callable]:
"""
Convenient decorator to register an action with the current Layers.
This will get and restore attribute from function first argument.
It will u... |
Convenient decorator to register an action with the current Layers.
This will get and restore attribute from function first argument.
It will use the function name as the action name. We force the description
to be given instead of function docstring for translation purpose.
Parameters
------... | register_layer_attr_action | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def _nanmin(array):
"""
call np.min but fall back to avoid nan and inf if necessary
"""
min_value = np.min(array)
if not np.isfinite(min_value):
masked = array[np.isfinite(array)]
if masked.size == 0:
return 0
min_value = np.min(masked)
return min_value |
call np.min but fall back to avoid nan and inf if necessary
| _nanmin | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def _nanmax(array):
"""
call np.max but fall back to avoid nan and inf if necessary
"""
max_value = np.max(array)
if not np.isfinite(max_value):
masked = array[np.isfinite(array)]
if masked.size == 0:
return 1
max_value = np.max(masked)
return max_value |
call np.max but fall back to avoid nan and inf if necessary
| _nanmax | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def calc_data_range(
data: LayerDataProtocol, rgb: bool = False
) -> tuple[float, float]:
"""Calculate range of data values. If all values are equal return [0, 1].
Parameters
----------
data : array
Data to calculate range of values over.
rgb : bool
Flag if data is rgb.
Ret... | Calculate range of data values. If all values are equal return [0, 1].
Parameters
----------
data : array
Data to calculate range of values over.
rgb : bool
Flag if data is rgb.
Returns
-------
values : pair of floats
Minimum and maximum values in that order.
N... | calc_data_range | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def segment_normal(a, b, p=(0, 0, 1)) -> np.ndarray:
"""Determines the unit normal of the vector from a to b.
Parameters
----------
a : np.ndarray
Length 2 array of first point or Nx2 array of points
b : np.ndarray
Length 2 array of second point or Nx2 array of points
p : 3-tupl... | Determines the unit normal of the vector from a to b.
Parameters
----------
a : np.ndarray
Length 2 array of first point or Nx2 array of points
b : np.ndarray
Length 2 array of second point or Nx2 array of points
p : 3-tuple, optional
orthogonal vector for segment calculatio... | segment_normal | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def get_current_properties(
properties: dict[str, np.ndarray],
choices: dict[str, np.ndarray],
num_data: int = 0,
) -> dict[str, Any]:
"""Get the current property values from the properties or choices.
Parameters
----------
properties : dict[str, np.ndarray]
The property values.
... | Get the current property values from the properties or choices.
Parameters
----------
properties : dict[str, np.ndarray]
The property values.
choices : dict[str, np.ndarray]
The property value choices.
num_data : int
The length of data that the properties represent (e.g. num... | get_current_properties | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def dataframe_to_properties(
dataframe: pd.DataFrame,
) -> dict[str, np.ndarray]:
"""Convert a dataframe to a properties dictionary.
Parameters
----------
dataframe : DataFrame
The dataframe object to be converted to a properties dictionary
Returns
-------
dict[str, np.ndarray]
... | Convert a dataframe to a properties dictionary.
Parameters
----------
dataframe : DataFrame
The dataframe object to be converted to a properties dictionary
Returns
-------
dict[str, np.ndarray]
A properties dictionary where the key is the property name and the value
is an... | dataframe_to_properties | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def validate_properties(
properties: dict[str, Array] | pd.DataFrame | None,
expected_len: int | None = None,
) -> dict[str, np.ndarray]:
"""Validate the type and size of properties and coerce values to numpy arrays.
Parameters
----------
properties : dict[str, Array] or DataFrame
The pr... | Validate the type and size of properties and coerce values to numpy arrays.
Parameters
----------
properties : dict[str, Array] or DataFrame
The property values.
expected_len : int
The expected length of each property value array.
Returns
-------
Dict[str, np.ndarray]
... | validate_properties | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def _coerce_current_properties_value(
value: float | str | bool | list | tuple | np.ndarray,
) -> np.ndarray:
"""Coerce a value in a current_properties dictionary into the correct type.
Parameters
----------
value : Union[float, str, int, bool, list, tuple, np.ndarray]
The value to be coerc... | Coerce a value in a current_properties dictionary into the correct type.
Parameters
----------
value : Union[float, str, int, bool, list, tuple, np.ndarray]
The value to be coerced.
Returns
-------
coerced_value : np.ndarray
The value in a 1D numpy array with length 1.
| _coerce_current_properties_value | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def coerce_current_properties(
current_properties: Mapping[
str, float | str | int | bool | list | tuple | npt.NDArray
],
) -> dict[str, np.ndarray]:
"""Coerce a current_properties dictionary into the correct type.
Parameters
----------
current_properties : Dict[str, Union[float, str, ... | Coerce a current_properties dictionary into the correct type.
Parameters
----------
current_properties : Dict[str, Union[float, str, int, bool, list, tuple, np.ndarray]]
The current_properties dictionary to be coerced.
Returns
-------
coerced_current_properties : Dict[str, np.ndarray]... | coerce_current_properties | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def compute_multiscale_level(
requested_shape, shape_threshold, downsample_factors
):
"""Computed desired level of the multiscale given requested field of view.
The level of the multiscale should be the lowest resolution such that
the requested shape is above the shape threshold. By passing a shape
... | Computed desired level of the multiscale given requested field of view.
The level of the multiscale should be the lowest resolution such that
the requested shape is above the shape threshold. By passing a shape
threshold corresponding to the shape of the canvas on the screen this
ensures that we have a... | compute_multiscale_level | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def compute_multiscale_level_and_corners(
corner_pixels, shape_threshold, downsample_factors
):
"""Computed desired level and corners of a multiscale view.
The level of the multiscale should be the lowest resolution such that
the requested shape is above the shape threshold. By passing a shape
thre... | Computed desired level and corners of a multiscale view.
The level of the multiscale should be the lowest resolution such that
the requested shape is above the shape threshold. By passing a shape
threshold corresponding to the shape of the canvas on the screen this
ensures that we have at least one dat... | compute_multiscale_level_and_corners | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def coerce_affine(
affine: npt.ArrayLike | Affine,
*,
ndim: int,
name: str | None = None,
) -> Affine:
"""Coerce a user input into an affine transform object.
If the input is already an affine transform object, that same object is returned
with a name change if the given name is not None. I... | Coerce a user input into an affine transform object.
If the input is already an affine transform object, that same object is returned
with a name change if the given name is not None. If the input is None, an identity
affine transform object of the given dimensionality is returned.
Parameters
----... | coerce_affine | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def dims_displayed_world_to_layer(
dims_displayed_world: list[int],
ndim_world: int,
ndim_layer: int,
) -> list[int]:
"""Convert the dims_displayed from world dims to the layer dims.
This accounts differences in the number of dimensions in the world
dims versus the layer and for transpose and r... | Convert the dims_displayed from world dims to the layer dims.
This accounts differences in the number of dimensions in the world
dims versus the layer and for transpose and rolls.
Parameters
----------
dims_displayed_world : List[int]
The dims_displayed in world coordinates (i.e., from vie... | dims_displayed_world_to_layer | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def get_extent_world(
data_extent: npt.NDArray,
data_to_world: Affine,
centered: Any | None = None,
) -> npt.NDArray:
"""Range of layer in world coordinates base on provided data_extent
Parameters
----------
data_extent : array, shape (2, D)
Extent of layer in data coordinates.
... | Range of layer in world coordinates base on provided data_extent
Parameters
----------
data_extent : array, shape (2, D)
Extent of layer in data coordinates.
data_to_world : napari.utils.transforms.Affine
The transform from data to world coordinates.
Returns
-------
extent_... | get_extent_world | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def choices(self) -> dict[str, np.ndarray]:
"""Converts this to a deprecated property choices dictionary.
Only categorical features will have corresponding entries in the dictionary.
Returns
-------
Dict[str, np.ndarray]
The property choices dictionary equivalent to... | Converts this to a deprecated property choices dictionary.
Only categorical features will have corresponding entries in the dictionary.
Returns
-------
Dict[str, np.ndarray]
The property choices dictionary equivalent to this.
| choices | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def set_currents(
self,
currents: dict[str, npt.NDArray],
*,
update_indices: list[int] | None = None,
) -> None:
"""Sets the default values using the deprecated current properties dictionary.
May also update some of the feature values to be equal to the new default v... | Sets the default values using the deprecated current properties dictionary.
May also update some of the feature values to be equal to the new default values.
Parameters
----------
currents : Dict[str, np.ndarray]
The new current property values.
update_indices : Opt... | set_currents | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def resize(
self,
size: int,
) -> None:
"""Resize this padding with default values if required.
Parameters
----------
size : int
The new size (number of rows) of the features table.
"""
current_size = self._values.shape[0]
if size ... | Resize this padding with default values if required.
Parameters
----------
size : int
The new size (number of rows) of the features table.
| resize | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def from_layer(
cls,
*,
features: dict[str, np.ndarray] | pd.DataFrame | None = None,
feature_defaults: dict[str, Any] | pd.DataFrame | None = None,
properties: dict[str, np.ndarray] | pd.DataFrame | None = None,
property_choices: dict[str, np.ndarray] | None = None,
... | Coerces a layer's keyword arguments to a feature manager.
Parameters
----------
features : Optional[Union[Dict[str, np.ndarray], pd.DataFrame]]
The features input to a layer.
properties : Optional[Union[Dict[str, np.ndarray], pd.DataFrame]]
The properties input t... | from_layer | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def _get_default_column(column: pd.Series) -> pd.Series:
"""Get the default column of length 1 from a data column."""
value = None
if column.size > 0:
value = column.iloc[-1]
elif isinstance(column.dtype, pd.CategoricalDtype):
choices = column.dtype.categories
if choices.size > 0... | Get the default column of length 1 from a data column. | _get_default_column | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def _validate_features(
features: dict[str, np.ndarray] | pd.DataFrame | None,
*,
num_data: int | None = None,
) -> pd.DataFrame:
"""Validates and coerces feature values into a pandas DataFrame.
See Also
--------
:class:`_FeatureTable` : See initialization for parameter descriptions.
""... | Validates and coerces feature values into a pandas DataFrame.
See Also
--------
:class:`_FeatureTable` : See initialization for parameter descriptions.
| _validate_features | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def _validate_feature_defaults(
defaults: dict[str, Any] | pd.DataFrame | None,
values: pd.DataFrame,
) -> pd.DataFrame:
"""Validates and coerces feature default values into a pandas DataFrame.
See Also
--------
:class:`_FeatureTable` : See initialization for parameter descriptions.
"""
... | Validates and coerces feature default values into a pandas DataFrame.
See Also
--------
:class:`_FeatureTable` : See initialization for parameter descriptions.
| _validate_feature_defaults | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def _features_from_properties(
*,
properties: dict[str, np.ndarray] | pd.DataFrame | None = None,
property_choices: dict[str, np.ndarray] | None = None,
num_data: int | None = None,
) -> pd.DataFrame:
"""Validates and coerces deprecated properties input into a features DataFrame.
See Also
-... | Validates and coerces deprecated properties input into a features DataFrame.
See Also
--------
:meth:`_FeatureTable.from_layer`
| _features_from_properties | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def _unique_element(array: Array) -> Any | None:
"""
Returns the unique element along the 0th axis, if it exists; otherwise, returns None.
This is faster than np.unique, does not require extra tricks for nD arrays, and
does not fail for non-sortable elements.
"""
if len(array) == 0:
ret... |
Returns the unique element along the 0th axis, if it exists; otherwise, returns None.
This is faster than np.unique, does not require extra tricks for nD arrays, and
does not fail for non-sortable elements.
| _unique_element | python | napari/napari | src/napari/layers/utils/layer_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/layer_utils.py | BSD-3-Clause |
def shift_along_normal_vector(self, distance: float) -> None:
"""Shift the plane along its normal vector by a given distance."""
assert len(self.position) == len(self.normal) == 3
self.position = cast(
Point3D,
tuple(
p + (distance * n)
for... | Shift the plane along its normal vector by a given distance. | shift_along_normal_vector | python | napari/napari | src/napari/layers/utils/plane.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/plane.py | BSD-3-Clause |
def from_points(
cls,
a: npt.NDArray,
b: npt.NDArray,
c: npt.NDArray,
enabled: bool = True,
) -> 'Plane':
"""Derive a Plane from three points.
Parameters
----------
a : ArrayLike
(3,) array containing coordinates of a point
... | Derive a Plane from three points.
Parameters
----------
a : ArrayLike
(3,) array containing coordinates of a point
b : ArrayLike
(3,) array containing coordinates of a point
c : ArrayLike
(3,) array containing coordinates of a point
R... | from_points | python | napari/napari | src/napari/layers/utils/plane.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/plane.py | BSD-3-Clause |
def as_array(self) -> npt.NDArray:
"""Return a (N, 2, 3) array of clipping planes.
[i, 0, :] : ith plane position
[i, 1, :] : ith plane normal
"""
arrays = []
for plane in self:
if plane.enabled:
arrays.append(plane.as_array())
if not ... | Return a (N, 2, 3) array of clipping planes.
[i, 0, :] : ith plane position
[i, 1, :] : ith plane normal
| as_array | python | napari/napari | src/napari/layers/utils/plane.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/plane.py | BSD-3-Clause |
def from_array(
cls, array: npt.NDArray, enabled: bool = True
) -> 'ClippingPlaneList':
"""Construct the PlaneList from an (N, 2, 3) array.
[i, 0, :] : ith plane position
[i, 1, :] : ith plane normal
"""
if array.ndim != 3 or array.shape[1:] != (2, 3):
ra... | Construct the PlaneList from an (N, 2, 3) array.
[i, 0, :] : ith plane position
[i, 1, :] : ith plane normal
| from_array | python | napari/napari | src/napari/layers/utils/plane.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/plane.py | BSD-3-Clause |
def slice_from_axis(array, *, axis, element):
"""Take a single index slice from array using slicing.
Equivalent to :func:`np.take`, but using slicing, which ensures that the
output is a view of the original array.
Parameters
----------
array : NumPy or other array
Input array to be sli... | Take a single index slice from array using slicing.
Equivalent to :func:`np.take`, but using slicing, which ensures that the
output is a view of the original array.
Parameters
----------
array : NumPy or other array
Input array to be sliced.
axis : int
The axis along which to s... | slice_from_axis | python | napari/napari | src/napari/layers/utils/stack_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/stack_utils.py | BSD-3-Clause |
def split_channels(
data: np.ndarray,
channel_axis: int,
**kwargs,
) -> list[FullLayerData]:
"""Split the data array into separate arrays along an axis.
Keyword arguments will override any parameters altered or set in this
function. Colormap, blending, or multiscale are set as follows if not
... | Split the data array into separate arrays along an axis.
Keyword arguments will override any parameters altered or set in this
function. Colormap, blending, or multiscale are set as follows if not
overridden by a keyword:
- colormap : (magenta, green) for 2 channels, (CYMRGB) for more than 2
- blen... | split_channels | python | napari/napari | src/napari/layers/utils/stack_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/stack_utils.py | BSD-3-Clause |
def split_rgb(stack: Image, with_alpha=False) -> list[Image]:
"""Variant of stack_to_images that splits an RGB with predefined cmap."""
if not stack.rgb:
raise ValueError(
trans._('Image must be RGB to use split_rgb', deferred=True)
)
images = stack_to_images(stack, -1, colormap... | Variant of stack_to_images that splits an RGB with predefined cmap. | split_rgb | python | napari/napari | src/napari/layers/utils/stack_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/stack_utils.py | BSD-3-Clause |
def images_to_stack(images: list[Image], axis: int = 0, **kwargs) -> Image:
"""Combines a list of Image layers into one layer stacked along axis
The new image layer will get the meta properties of the first
image layer in the input list unless specified in kwargs
Parameters
----------
images :... | Combines a list of Image layers into one layer stacked along axis
The new image layer will get the meta properties of the first
image layer in the input list unless specified in kwargs
Parameters
----------
images : List
List of Image Layers
axis : int
Index to to insert the ne... | images_to_stack | python | napari/napari | src/napari/layers/utils/stack_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/stack_utils.py | BSD-3-Clause |
def merge_rgb(images: list[Image]) -> Image:
"""Variant of images_to_stack that makes an RGB from 3 images."""
if not (len(images) == 3 and all(isinstance(x, Image) for x in images)):
raise ValueError(
trans._(
'Merging to RGB requires exactly 3 Image layers', deferred=True
... | Variant of images_to_stack that makes an RGB from 3 images. | merge_rgb | python | napari/napari | src/napari/layers/utils/stack_utils.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/stack_utils.py | BSD-3-Clause |
def validate(
cls, value: Union['StringEncoding', dict, str, Sequence[str]]
) -> 'StringEncoding':
"""Validates and coerces a value to a StringEncoding.
Parameters
----------
value : StringEncodingArgument
The value to validate and coerce.
If this is ... | Validates and coerces a value to a StringEncoding.
Parameters
----------
value : StringEncodingArgument
The value to validate and coerce.
If this is already a StringEncoding, it is returned as is.
If this is a dict, then it should represent one of the built-i... | validate | python | napari/napari | src/napari/layers/utils/string_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/string_encoding.py | BSD-3-Clause |
def _is_format_string(string: str) -> bool:
"""Returns True if a string is a valid format string with at least one field, False otherwise."""
try:
fields = tuple(
field
for _, field, _, _ in Formatter().parse(string)
if field is not None
)
except ValueErro... | Returns True if a string is a valid format string with at least one field, False otherwise. | _is_format_string | python | napari/napari | src/napari/layers/utils/string_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/string_encoding.py | BSD-3-Clause |
def __call__(self, features: Any) -> StyleValue | StyleArray:
"""Apply this encoding with the given features to generate style values.
Parameters
----------
features : Dataframe-like
The layer features table from which to derive the output values.
Returns
--... | Apply this encoding with the given features to generate style values.
Parameters
----------
features : Dataframe-like
The layer features table from which to derive the output values.
Returns
-------
Union[StyleValue, StyleArray]
Either a single s... | __call__ | python | napari/napari | src/napari/layers/utils/style_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/style_encoding.py | BSD-3-Clause |
def _apply(self, features: Any) -> None:
"""Applies this to the tail of the given features and updates cached values.
If the cached values are longer than the given features, this will remove
the extra cached values. If they are the same length, this may do nothing.
Parameters
... | Applies this to the tail of the given features and updates cached values.
If the cached values are longer than the given features, this will remove
the extra cached values. If they are the same length, this may do nothing.
Parameters
----------
features : Dataframe-like
... | _apply | python | napari/napari | src/napari/layers/utils/style_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/style_encoding.py | BSD-3-Clause |
def _append(self, array: StyleArray) -> None:
"""Appends raw style values to cached values.
This is useful for supporting the paste operation in layers.
Parameters
----------
array : StyleArray
The values to append. The dimensionality of these should match that of t... | Appends raw style values to cached values.
This is useful for supporting the paste operation in layers.
Parameters
----------
array : StyleArray
The values to append. The dimensionality of these should match that of the existing style values.
| _append | python | napari/napari | src/napari/layers/utils/style_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/style_encoding.py | BSD-3-Clause |
def _delete(self, indices: IndicesType) -> None:
"""Deletes cached style values by index.
Parameters
----------
indices
The indices of the style values to remove.
""" | Deletes cached style values by index.
Parameters
----------
indices
The indices of the style values to remove.
| _delete | python | napari/napari | src/napari/layers/utils/style_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/style_encoding.py | BSD-3-Clause |
def _json_encode(self) -> dict:
"""Convert this to a dictionary that can be passed to json.dumps.
Returns
-------
dict
The dictionary representation of this with JSON compatible keys and values.
""" | Convert this to a dictionary that can be passed to json.dumps.
Returns
-------
dict
The dictionary representation of this with JSON compatible keys and values.
| _json_encode | python | napari/napari | src/napari/layers/utils/style_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/style_encoding.py | BSD-3-Clause |
def _call_safely(self, features: Any) -> StyleArray:
"""Calls this without raising encoding errors, warning instead."""
try:
array = self(features)
except (KeyError, ValueError):
warnings.warn(
trans._(
'Applying the encoding failed. Us... | Calls this without raising encoding errors, warning instead. | _call_safely | python | napari/napari | src/napari/layers/utils/style_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/style_encoding.py | BSD-3-Clause |
def _get_style_values(
encoding: StyleEncoding[StyleValue, StyleArray],
indices: IndicesType,
value_ndim: int = 0,
):
"""Returns a scalar style value or indexes non-scalar style values."""
values = encoding._values
return values if values.ndim == value_ndim else values[indices] | Returns a scalar style value or indexes non-scalar style values. | _get_style_values | python | napari/napari | src/napari/layers/utils/style_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/style_encoding.py | BSD-3-Clause |
def _empty_array_like(value: StyleValue) -> StyleArray:
"""Returns an empty array with the same type and remaining shape of the given value."""
shape = (0, *value.shape)
return np.empty_like(value, shape=shape) | Returns an empty array with the same type and remaining shape of the given value. | _empty_array_like | python | napari/napari | src/napari/layers/utils/style_encoding.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/style_encoding.py | BSD-3-Clause |
def _get_scaled_size(self, scale_factor: float | None = None) -> float:
"""Calculate the scaled text size based on zoom level."""
if not self.scaling or scale_factor is None:
return self.size
return self.size / scale_factor | Calculate the scaled text size based on zoom level. | _get_scaled_size | python | napari/napari | src/napari/layers/utils/text_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/text_manager.py | BSD-3-Clause |
def refresh(self, features: Any) -> None:
"""Refresh all encoded values using new layer features.
Parameters
----------
features : Any
The features table of a layer.
"""
self.string._clear()
self.color._clear()
self.string._apply(features)
... | Refresh all encoded values using new layer features.
Parameters
----------
features : Any
The features table of a layer.
| refresh | python | napari/napari | src/napari/layers/utils/text_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/text_manager.py | BSD-3-Clause |
def refresh_text(self, properties: dict[str, np.ndarray]):
"""Refresh all of the current text elements using updated properties values
Parameters
----------
properties : Dict[str, np.ndarray]
The new properties from the layer
"""
warnings.warn(
tr... | Refresh all of the current text elements using updated properties values
Parameters
----------
properties : Dict[str, np.ndarray]
The new properties from the layer
| refresh_text | python | napari/napari | src/napari/layers/utils/text_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/text_manager.py | BSD-3-Clause |
def add(self, properties: dict, n_text: int):
"""Adds a number of a new text elements.
Parameters
----------
properties : dict
The properties to draw the text from
n_text : int
The number of text elements to add
"""
warnings.warn(
... | Adds a number of a new text elements.
Parameters
----------
properties : dict
The properties to draw the text from
n_text : int
The number of text elements to add
| add | python | napari/napari | src/napari/layers/utils/text_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/text_manager.py | BSD-3-Clause |
def remove(self, indices_to_remove: range | set | list | np.ndarray):
"""Remove the indicated text elements
Parameters
----------
indices_to_remove : set, list, np.ndarray
The indices of the text elements to remove.
"""
if isinstance(indices_to_remove, set):
... | Remove the indicated text elements
Parameters
----------
indices_to_remove : set, list, np.ndarray
The indices of the text elements to remove.
| remove | python | napari/napari | src/napari/layers/utils/text_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/text_manager.py | BSD-3-Clause |
def _copy(self, indices: list[int]) -> dict:
"""Copies all encoded values at the given indices."""
return {
'string': _get_style_values(self.string, indices),
'color': _get_style_values(self.color, indices, value_ndim=1),
} | Copies all encoded values at the given indices. | _copy | python | napari/napari | src/napari/layers/utils/text_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/text_manager.py | BSD-3-Clause |
def compute_text_coords(
self,
view_data: np.ndarray,
ndisplay: int,
order: tuple[int, ...] | None = None,
) -> tuple[np.ndarray, str, str]:
"""Calculate the coordinates for each text element in view
Parameters
----------
view_data : np.ndarray
... | Calculate the coordinates for each text element in view
Parameters
----------
view_data : np.ndarray
The in view data from the layer
ndisplay : int
The number of dimensions being displayed in the viewer
order : tuple of ints, optional
The disp... | compute_text_coords | python | napari/napari | src/napari/layers/utils/text_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/text_manager.py | BSD-3-Clause |
def view_text(self, indices_view: np.ndarray) -> np.ndarray:
"""Get the values of the text elements in view
Parameters
----------
indices_view : (N x 1) np.ndarray
Indices of the text elements in view
Returns
-------
text : (N x 1) np.ndarray
... | Get the values of the text elements in view
Parameters
----------
indices_view : (N x 1) np.ndarray
Indices of the text elements in view
Returns
-------
text : (N x 1) np.ndarray
Array of text strings for the N text elements in view
| view_text | python | napari/napari | src/napari/layers/utils/text_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/text_manager.py | BSD-3-Clause |
def _from_layer(
cls,
*,
text: Union['TextManager', dict, str, Sequence[str], None],
features: Any,
) -> 'TextManager':
"""Create a TextManager from a layer.
Parameters
----------
text : Union[TextManager, dict, str, Sequence[str], None]
A... | Create a TextManager from a layer.
Parameters
----------
text : Union[TextManager, dict, str, Sequence[str], None]
An instance of TextManager, a dict that contains some of its state,
a string that may be a format string or a feature name, or a
sequence of str... | _from_layer | python | napari/napari | src/napari/layers/utils/text_manager.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/text_manager.py | BSD-3-Clause |
def get_linked_layers(*layers: Layer) -> set[Layer]:
"""Return layers that are linked to any layer in `*layers`.
Note, if multiple layers are provided, the returned set will represent any
layer that is linked to any one of the input layers. They may not all be
directly linked to each other. This is u... | Return layers that are linked to any layer in `*layers`.
Note, if multiple layers are provided, the returned set will represent any
layer that is linked to any one of the input layers. They may not all be
directly linked to each other. This is useful for context menu generation.
| get_linked_layers | python | napari/napari | src/napari/layers/utils/_link_layers.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/_link_layers.py | BSD-3-Clause |
def unlink_layers(
layers: Iterable[Layer], attributes: Iterable[str] = ()
) -> None:
"""Unlink previously linked ``attributes`` between all layers in ``layers``.
Parameters
----------
layers : Iterable[napari.layers.Layer]
The list of layers to unlink. All combinations of layers provided ... | Unlink previously linked ``attributes`` between all layers in ``layers``.
Parameters
----------
layers : Iterable[napari.layers.Layer]
The list of layers to unlink. All combinations of layers provided will
be unlinked. If a single layer is provided, it will be unlinked from
all ot... | unlink_layers | python | napari/napari | src/napari/layers/utils/_link_layers.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/_link_layers.py | BSD-3-Clause |
def layers_linked(
layers: Iterable[Layer], attributes: Iterable[str] = ()
) -> Generator[None, None, None]:
"""Context manager that temporarily links ``attributes`` on ``layers``."""
links = link_layers(layers, attributes)
try:
yield
finally:
_unlink_keys(links) | Context manager that temporarily links ``attributes`` on ``layers``. | layers_linked | python | napari/napari | src/napari/layers/utils/_link_layers.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/_link_layers.py | BSD-3-Clause |
def _get_common_evented_attributes(
layers: Iterable[Layer],
exclude: abc.Set[str] = frozenset(
(
'thumbnail',
'status',
'name',
'mode',
'data',
'features',
'properties',
'size',
'symbol',
... | Get the set of common, non-private evented attributes in ``layers``.
Not all layer events are attributes, and not all attributes have
corresponding events. Here we get the set of valid, non-private attributes
that are both events and attributes for the provided layer set.
Parameters
----------
... | _get_common_evented_attributes | python | napari/napari | src/napari/layers/utils/_link_layers.py | https://github.com/napari/napari/blob/master/src/napari/layers/utils/_link_layers.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.