napari.layers.Tracks

class napari.layers.Tracks(data, *, features=None, properties=None, graph=None, tail_width=2, tail_length=30, head_length=0, name=None, metadata=None, scale=None, translate=None, rotate=None, shear=None, affine=None, opacity=1, blending='additive', visible=True, colormap='turbo', color_by='track_id', colormaps_dict=None, cache=True, experimental_clipping_planes=None)[source]

Bases: napari.layers.base.base.Layer

Tracks layer.

Parameters
  • data (array (N, D+1)) – Coordinates for N points in D+1 dimensions. ID,T,(Z),Y,X. The first axis is the integer ID of the track. D is either 3 or 4 for planar or volumetric timeseries respectively.

  • features (Dataframe-like) – Features table where each row corresponds to a point and each column is a feature.

  • properties (dict {str: array (N,)}, DataFrame) – Properties for each point. Each property should be an array of length N, where N is the number of points.

  • graph (dict {int: list}) – Graph representing associations between tracks. Dictionary defines the mapping between a track ID and the parents of the track. This can be one (the track has one parent, and the parent has >=1 child) in the case of track splitting, or more than one (the track has multiple parents, but only one child) in the case of track merging. See examples/tracks_3d_with_graph.py

  • color_by (str) – Track property (from property keys) by which to color vertices.

  • tail_width (float) – Width of the track tails in pixels.

  • tail_length (float) – Length of the positive (backward in time) tails in units of time.

  • head_length (float) – Length of the positive (forward in time) tails in units of time.

  • colormap (str) – Default colormap to use to set vertex colors. Specialized colormaps, relating to specified properties can be passed to the layer via colormaps_dict.

  • colormaps_dict (dict {str: napari.utils.Colormap}) – Optional dictionary mapping each property to a colormap for that property. This allows each property to be assigned a specific colormap, rather than having a global colormap for everything.

  • name (str) – Name of the layer.

  • metadata (dict) – Layer metadata.

  • scale (tuple of float) – Scale factors for the layer.

  • translate (tuple of float) – Translation values for the layer.

  • rotate (float, 3-tuple of float, or n-D array.) – If a float convert into a 2D rotation matrix using that value as an angle. If 3-tuple convert into a 3D rotation matrix, using a yaw, pitch, roll convention. Otherwise assume an nD rotation. Angles are assumed to be in degrees. They can be converted from radians with np.degrees if needed.

  • shear (1-D array or n-D array) – Either a vector of upper triangular values, or an nD shear matrix with ones along the main diagonal.

  • affine (n-D array or napari.utils.transforms.Affine) – (N+1, N+1) affine transformation matrix in homogeneous coordinates. The first (N, N) entries correspond to a linear transform and the final column is a length N translation vector and a 1 or a napari Affine transform object. Applied as an extra transform on top of the provided scale, rotate, and shear values.

  • opacity (float) – Opacity of the layer visual, between 0.0 and 1.0.

  • blending (str) – One of a list of preset blending modes that determines how RGB and alpha values of the layer visual get mixed. Allowed values are {‘opaque’, ‘translucent’, and ‘additive’}.

  • visible (bool) – Whether the layer visual is currently being displayed.

  • cache (bool) – Whether slices of out-of-core datasets should be cached upon retrieval. Currently, this only applies to dask arrays.

Methods

as_layer_data_tuple()

bind_key(key[, func, overwrite])

Bind a key combination to a keymap.

block_update_properties()

click_plane_from_click_data(click_position, ...)

Calculate a (point, normal) plane parallel to the canvas in data coordinates, centered on the centre of rotation of the camera.

create(data[, meta, layer_type])

Create layer from data of type layer_type.

data_to_world(position)

Convert from data coordinates to world coordinates.

get_ray_intersections(position, ...[, world])

Get the start and end point for the ray extending from a point through the data bounding box.

get_status(position, *[, view_direction, ...])

Status message of the data at a coordinate position.

get_value(position, *[, view_direction, ...])

Value of the data at a position.

projected_distance_from_mouse_drag(...)

Calculate the length of the projection of a line between two mouse clicks onto a vector (or array of vectors) in data coordinates.

refresh([event])

Refresh all layer data based on current view slice.

save(path[, plugin])

Save this layer to path with default (or specified) plugin.

set_view_slice()

world_to_data(position)

Convert from world coordinates to data coordinates.

Attributes

affine

Extra affine transform to go from physical to world coordinates.

blending

Determines how RGB and alpha values get mixed.

class_keymap

colomaps_dict

color_by

colormap

colormaps_dict

current_time

current time according to the first dimension

cursor

String identifying cursor displayed over canvas.

cursor_size

Size of cursor if custom.

data

Coordinates for N points in D+1 dimensions.

display_graph

display the graph edges

display_id

display the track id

display_tail

display the track tail

editable

Whether the current layer data is editable from the viewer.

experimental_clipping_planes

extent

Extent of layer in data and world coordinates.

features

Dataframe-like features table.

graph

Graph representing associations between tracks.

graph_connex

vertex connections for drawing the graph

graph_times

time points associated with each graph vertex

head_length

help

displayed in status bar bottom right.

interactive

Determine if canvas pan/zoom interactivity is enabled.

loaded

Return True if this layer is fully loaded in memory.

metadata

Key/value map for user-stored data.

name

Unique name of the layer.

ndim

Number of dimensions in the data.

opacity

Opacity value between 0.0 and 1.0.

properties

Properties for each track.

properties_to_color_by

track properties that can be used for coloring etc...

rotate

Rotation matrix in world coordinates.

scale

Anisotropy factors to scale data into world coordinates.

shear

Shear matrix in world coordinates.

source

tail_length

Width for all vectors in pixels.

tail_width

Width for all vectors in pixels.

thumbnail

Integer array of thumbnail for the layer

track_colors

return the vertex colors according to the currently selected property

track_connex

vertex connections for drawing track lines

track_labels

return track labels at the current time

track_times

time points associated with each track vertex

translate

Factors to shift the layer by in units of world coordinates.

translate_grid

use_fade

toggle whether we fade the tail of the track, depending on whether the time dimension is displayed

visible

Whether the visual is currently being displayed.

Details

property affine

Extra affine transform to go from physical to world coordinates.

Type

napari.utils.transforms.Affine

bind_key(key, func=<object object>, *, overwrite=False)

Bind a key combination to a keymap.

Parameters
  • keymap (dict of str: callable) – Keymap to modify.

  • key (str or ...) – Key combination. ... acts as a wildcard if no key combinations can be matched in the keymap (this will overwrite all key combinations further down the lookup chain).

  • func (callable, None, or ...) – Callable to bind to the key combination. If None is passed, unbind instead. ... acts as a blocker, effectively unbinding the key combination for all keymaps further down the lookup chain.

  • overwrite (bool, keyword-only, optional) – Whether to overwrite the key combination if it already exists.

Returns

unbound – Callable unbound by this operation, if any.

Return type

callable or None

Notes

Key combinations are represented in the form [modifier-]key, e.g. a, Control-c, or Control-Alt-Delete. Valid modifiers are Control, Alt, Shift, and Meta.

Letters will always be read as upper-case. Due to the native implementation of the key system, Shift pressed in certain key combinations may yield inconsistent or unexpected results. Therefore, it is not recommended to use Shift with non-letter keys. On OSX, Control is swapped with Meta such that pressing Command reads as Control.

Special keys include Shift, Control, Alt, Meta, Up, Down, Left, Right, PageUp, PageDown, Insert, Delete, Home, End, Escape, Backspace, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Space, Enter, and Tab

Functions take in only one argument: the parent that the function was bound to.

By default, all functions are assumed to work on key presses only, but can be denoted to work on release too by separating the function into two statements with the yield keyword:

@viewer.bind_key('h')
def hello_world(viewer):
    # on key press
    viewer.status = 'hello world!'

    yield

    # on key release
    viewer.status = 'goodbye world :('

To create a keymap that will block others, bind_key(..., ...)`.

property blending

Determines how RGB and alpha values get mixed.

Blending.OPAQUE

Allows for only the top layer to be visible and corresponds to depth_test=True, cull_face=False, blend=False.

Blending.TRANSLUCENT

Allows for multiple layers to be blended with different opacity and corresponds to depth_test=True, cull_face=False, blend=True, blend_func=(‘src_alpha’, ‘one_minus_src_alpha’).

Blending.ADDITIVE

Allows for multiple layers to be blended together with different colors and opacity. Useful for creating overlays. It corresponds to depth_test=False, cull_face=False, blend=True, blend_func=(‘src_alpha’, ‘one’).

Type

Blending mode

click_plane_from_click_data(click_position: numpy.ndarray, view_direction: numpy.ndarray, dims_displayed: List) Tuple[numpy.ndarray, numpy.ndarray]

Calculate a (point, normal) plane parallel to the canvas in data coordinates, centered on the centre of rotation of the camera.

Parameters
  • click_position (np.ndarray) – click position in world coordinates from mouse event.

  • view_direction (np.ndarray) – view direction in world coordinates from mouse event.

  • dims_displayed (List) – dimensions of the data array currently in view.

Returns

click_plane – tuple of (plane_position, plane_normal) in data coordinates.

Return type

Tuple[np.ndarray, np.ndarray]

classmethod create(data, meta: Optional[dict] = None, layer_type: Optional[str] = None) napari.layers.base.base.Layer

Create layer from data of type layer_type.

Primarily intended for usage by reader plugin hooks and creating a layer from an unwrapped layer data tuple.

Parameters
  • data (Any) – Data in a format that is valid for the corresponding layer_type.

  • meta (dict, optional) – Dict of keyword arguments that will be passed to the corresponding layer constructor. If any keys in meta are not valid for the corresponding layer type, an exception will be raised.

  • layer_type (str) – Type of layer to add. Must be the (case insensitive) name of a Layer subclass. If not provided, the layer is assumed to be “image”, unless data.dtype is one of (np.int32, np.uint32, np.int64, np.uint64), in which case it is assumed to be “labels”.

Raises
  • ValueError – If layer_type is not one of the recognized layer types.

  • TypeError – If any keyword arguments in meta are unexpected for the corresponding add_* method for this layer_type.

Examples

A typical use case might be to upack a tuple of layer data with a specified layer_type.

>>> data = (
...     np.random.random((10, 2)) * 20,
...     {'face_color': 'blue'},
...     'points',
... )
>>> Layer.create(*data)
property current_time

current time according to the first dimension

property cursor

String identifying cursor displayed over canvas.

Type

str

property cursor_size

Size of cursor if custom. None yields default size.

Type

int | None

property data: numpy.ndarray

Coordinates for N points in D+1 dimensions.

Type

array (N, D+1)

data_to_world(position)

Convert from data coordinates to world coordinates.

Parameters

position (tuple, list, 1D array) – Position in data coordinates. If longer then the number of dimensions of the layer, the later dimensions will be used.

Returns

Position in world coordinates.

Return type

tuple

property display_graph: bool

display the graph edges

property display_id: bool

display the track id

property display_tail: bool

display the track tail

property editable

Whether the current layer data is editable from the viewer.

Type

bool

property extent: napari.layers.base.base.Extent

Extent of layer in data and world coordinates.

property features

Dataframe-like features table.

It is an implementation detail that this is a pandas.DataFrame. In the future, we will target the currently-in-development Data API dataframe protocol [1]. This will enable us to use alternate libraries such as xarray or cuDF for additional features without breaking existing usage of this.

If you need to specifically rely on the pandas API, please coerce this to a pandas.DataFrame using features_to_pandas_dataframe.

References

get_ray_intersections(position: List[float], view_direction: numpy.ndarray, dims_displayed: List[int], world: bool = True) Union[Tuple[numpy.ndarray, numpy.ndarray], Tuple[None, None]]

Get the start and end point for the ray extending from a point through the data bounding box.

Parameters
  • position – the position of the point in nD coordinates. World vs. data is set by the world keyword argument.

  • view_direction (np.ndarray) – a unit vector giving the direction of the ray in nD coordinates. World vs. data is set by the world keyword argument.

  • dims_displayed – a list of the dimensions currently being displayed in the viewer.

  • world (bool) – True if the provided coordinates are in world coordinates. Default value is True.

Returns

  • start_point (np.ndarray) – The point on the axis-aligned data bounding box that the cursor click intersects with. This is the point closest to the camera. The point is the full nD coordinates of the layer data. If the click does not intersect the axis-aligned data bounding box, None is returned.

  • end_point (np.ndarray) – The point on the axis-aligned data bounding box that the cursor click intersects with. This is the point farthest from the camera. The point is the full nD coordinates of the layer data. If the click does not intersect the axis-aligned data bounding box, None is returned.

get_status(position: numpy.ndarray, *, view_direction: Optional[numpy.ndarray] = None, dims_displayed: Optional[List[int]] = None, world=False)

Status message of the data at a coordinate position.

Parameters
  • position (tuple) – Position in either data or world coordinates.

  • view_direction (Optional[np.ndarray]) – A unit vector giving the direction of the ray in nD world coordinates. The default value is None.

  • dims_displayed (Optional[List[int]]) – A list of the dimensions currently being displayed in the viewer. The default value is None.

  • world (bool) – If True the position is taken to be in world coordinates and converted into data coordinates. False by default.

Returns

msg – String containing a message that can be used as a status update.

Return type

string

get_value(position, *, view_direction: Optional[numpy.ndarray] = None, dims_displayed: Optional[List[int]] = None, world=False)

Value of the data at a position.

If the layer is not visible, return None.

Parameters
  • position (tuple) – Position in either data or world coordinates.

  • view_direction (Optional[np.ndarray]) – A unit vector giving the direction of the ray in nD world coordinates. The default value is None.

  • dims_displayed (Optional[List[int]]) – A list of the dimensions currently being displayed in the viewer. The default value is None.

  • world (bool) – If True the position is taken to be in world coordinates and converted into data coordinates. False by default.

Returns

value – Value of the data. If the layer is not visible return None.

Return type

tuple, None

property graph: Dict[int, Union[int, List[int]]]

Graph representing associations between tracks.

Type

dict {int

Type

list}

property graph_connex: numpy.ndarray

vertex connections for drawing the graph

property graph_times: numpy.ndarray

time points associated with each graph vertex

property help

displayed in status bar bottom right.

Type

str

property interactive

Determine if canvas pan/zoom interactivity is enabled.

Type

bool

property loaded: bool

Return True if this layer is fully loaded in memory.

This base class says that layers are permanently in the loaded state. Derived classes that do asynchronous loading can override this.

property metadata: dict

Key/value map for user-stored data.

property name

Unique name of the layer.

Type

str

property ndim

Number of dimensions in the data.

Type

int

property opacity

Opacity value between 0.0 and 1.0.

Type

float

projected_distance_from_mouse_drag(start_position: numpy.ndarray, end_position: numpy.ndarray, view_direction: numpy.ndarray, vector: numpy.ndarray, dims_displayed: Union[List, numpy.ndarray])

Calculate the length of the projection of a line between two mouse clicks onto a vector (or array of vectors) in data coordinates.

Parameters
  • start_position (np.ndarray) – Starting point of the drag vector in data coordinates

  • end_position (np.ndarray) – End point of the drag vector in data coordinates

  • view_direction (np.ndarray) – Vector defining the plane normal of the plane onto which the drag vector is projected.

  • vector (np.ndarray) – (3,) unit vector or (n, 3) array thereof on which to project the drag vector from start_event to end_event. This argument is defined in data coordinates.

  • dims_displayed (Union[List, np.ndarray]) – (3,) list of currently displayed dimensions

Returns

projected_distance

Return type

(1, ) or (n, ) np.ndarray of float

property properties: Dict[str, numpy.ndarray]

Properties for each track.

Type

dict {str

Type

np.ndarray (N,)}

property properties_to_color_by: List[str]

track properties that can be used for coloring etc…

refresh(event=None)

Refresh all layer data based on current view slice.

property rotate

Rotation matrix in world coordinates.

Type

array

save(path: str, plugin: Optional[str] = None) List[str]

Save this layer to path with default (or specified) plugin.

Parameters
  • path (str) – A filepath, directory, or URL to open. Extensions may be used to specify output format (provided a plugin is available for the requested format).

  • plugin (str, optional) – Name of the plugin to use for saving. If None then all plugins corresponding to appropriate hook specification will be looped through to find the first one that can save the data.

Returns

File paths of any files that were written.

Return type

list of str

property scale

Anisotropy factors to scale data into world coordinates.

Type

list

property shear

Shear matrix in world coordinates.

Type

array

property tail_length: Union[int, float]

Width for all vectors in pixels.

Type

float

property tail_width: Union[int, float]

Width for all vectors in pixels.

Type

float

property thumbnail

Integer array of thumbnail for the layer

Type

array

property track_colors: numpy.ndarray

return the vertex colors according to the currently selected property

property track_connex: numpy.ndarray

vertex connections for drawing track lines

property track_labels: tuple

return track labels at the current time

property track_times: numpy.ndarray

time points associated with each track vertex

property translate

Factors to shift the layer by in units of world coordinates.

Type

list

property use_fade: bool

toggle whether we fade the tail of the track, depending on whether the time dimension is displayed

property visible

Whether the visual is currently being displayed.

Type

bool

world_to_data(position)

Convert from world coordinates to data coordinates.

Parameters

position (tuple, list, 1D array) – Position in world coordinates. If longer then the number of dimensions of the layer, the later dimensions will be used.

Returns

Position in data coordinates.

Return type

tuple