.. _napari-plugin:

=============
napari plugin
=============

The Track Analyzer dock widget loads and filters tracks, runs analyses, and
displays previews alongside images in napari. Install it as described in
:doc:`installation`, start napari, and select **Plugins > Track Analyzer**.
The widget has five tabs: **Load data**, **Filtering**, **Trajectory
analysis**, **Map analysis**, and **Comparator**.

Inputs
======

Use a CSV or TXT table containing track IDs, frame numbers, X and Y coordinates,
and optionally Z coordinates and custom variables. Coordinates may be in
pixels or scaled units. The plugin maps source columns to Track Analyzer's
column names. For TrackMate data, export the spots table.

An image is optional. Open it in napari before using image-based previews or
backgrounds; there is no separate image loader in the plugin. For exported
backgrounds, the open grayscale image must have a saved source file, or the
layer name must match a file in the dataset directory.

Load data and metadata
======================

In **Load data**, choose one of the following:

* **Load table**: first set the column separator, header-row option, and
  **TrackMate CSV** option. Select a new table, then expand **Inspect dataframe
  and link columns**. Assign ``x``, ``y``, ``frame``, and ``track``; assign
  ``z`` and named custom variables if needed. Choose how to resolve trajectory
  gaps and click **Apply mapping**. TrackMate column assignments are proposed
  automatically when the TrackMate option is enabled.
* **Load database**: select an existing ``data_base.p``. Its processed table
  is loaded directly, so column mapping is not needed.

Loading a table or database sets **Dataset directory** to its parent folder.
In **Input metadata**, enter or load the pixel size, frame interval, units,
image dimensions, and optional Z step. Use **Save info.txt** to save metadata
in the dataset directory; replacing an existing file requires confirmation.

Before saving a new database, optionally set preprocessing coordinates in
**Custom origin and axis orientation**. Use **Pick origin in viewer** to
choose an origin on an open image. These settings affect preprocessing;
displayed tracks retain their source coordinates. Then click **Save database**
to preprocess trajectories and write ``data_base.p``. Saving over an existing
database requires confirmation. Trajectory and map analyses require a
processed database and saved ``info.txt``.

**Plotting configuration** controls figure size, resolution, format, stack
export, data-point export, and custom colors.

Filtering
=========

In **Filtering**, set the number of named subsets and choose whether to
analyze them **separately** or **together**. Expand **Define analysis
subsets** to set each subset's color, position ranges, frame window, and
track-length limits. **Draw ROI** sets the X/Y ranges using a rectangle drawn
over an open image.

Optionally add track-selection sets under **Select tracks within each
subset**. Each set can select track IDs, tracks entering a position ROI within
a frame window, or both, and is applied within every analysis subset. Use
**Draw ROI** to define a selection ROI on an open image. Set the two
frame-window endpoints to the same value to select at a single frame.

Click **Apply filters** to apply the selections; a successfully applied ROI
drawing layer is hidden, but its coordinate ranges are retained. **Display
tracks** shows the filtered tracks using the selected colors. **Save filters**
writes ``config/filters.csv``; **Remove all subsets** clears subset and
track-selection controls.

Trajectory analysis
===================

The trajectory tab offers **Trajectories on movie**, **Total trajectories**,
**Parameter plots**, **Mean squared displacement (MSD)**, and **Voronoi
analysis**. Each foldout has an independent On/Off switch: opening or closing
it does not change whether that analysis runs. Add histogram, boxplot, or
scatter-plot rows for instantaneous or whole-track parameters as needed.

The track color code and colormap at the top are shared by **Preview colored
tracks** and the trajectory exports. The ``group`` color code uses the
filtering subset colors, or the track-selection set colors when those sets
are present.

In **Voronoi analysis**, **Preview Voronoi** displays a 2D tessellation for
the current filters and frame. The outline color is editable; enabling **Show
cell area** adds a separate area-colored layer. The area threshold, length
scale, colormap, and color limits determine the fill. Unbounded and excluded
cells are not filled. The preview supports 2D images and 2D time-lapse images;
it follows the current frame and is computed per subset in separate mode.
Area and color settings update an existing preview automatically; run it
again after changing data or filters.

Click **Run trajectory analysis** to save results in numbered folders under
``<dataset>/traj_analysis/``. Subsets must have unique names and contain data.
The progress bar indicates work is ongoing rather than a percentage; the log
shows analysis messages.

Map analysis
============

Maps average quantities on a regular 2D grid. In **Define grid**, select the
number of X cells and grid origin, then click **Preview grid**. Changing these
settings updates a visible grid preview. The grid uses the open image
dimensions, or filtered track extents if no image is open.

Set temporal averaging, relative arrow size, frame increment, and export
options under **Map parameters**. In **Fields to plot**, add scalar fields,
vector fields, or vector means and remove any unwanted rows. Vector fields
can have a scalar background.

**Compute grid values** calculates all available fields and displays finite
ranges for the selected fields across frames and subsets. Edit the color
limits if needed. Changing the data, filters, grid, image geometry, or
temporal average invalidates the computed values. Run the computation again
after such changes. A subsequent map analysis reuses current computed values;
if none are available, analysis computes them as usual.

**Show selected maps in viewer** creates scalar image layers and vector arrow
layers. Missing scalar values are transparent. Scalar colors and limits are
set in the widget; click the display button again after changing them.
**Relative arrow size** updates existing preview arrows immediately.
**Run map analysis** saves plots and optional field exports under
``<dataset>/map_analysis/``.

Comparator
==========

The comparator pools or compares previously saved trajectory analyses, even
when they come from different dataset roots. All selected datasets must use
the same length and time units: unit conversion is not supported.

1. Expand **Datasets** and choose a dataset root. Select an individual folder
   under **Trajectory analysis** and click **Add selected analysis**. Repeat
   for other analyses or roots. Use **Refresh analyses** after generating
   new analyses, or browse directly to an analysis folder.
2. Give the selected datasets unique names and choose ``compare`` (separate
   colors) or ``pool`` (one group).
3. Add instantaneous or whole-trajectory histograms, boxplots, or scatter
   plots. Parameter choices are numerical fields shared by all datasets
   and supported by the plotting engine.
4. Optionally turn on the **Mean squared displacement (MSD)** foldout switch;
   it is off by default. MSD comparison requires a nonempty ``all_MSD.csv``
   for each selected analysis. Parameter plots use ``all_data.csv`` and
   ``mean_track_data.csv``.
5. Click **Run comparison**. Results are saved under
   ``<first dataset>/pooled_datasets/<mode>_<dataset names>/``. If the output
   folder exists, choose **Overwrite**, **Create new folder**, or **Cancel**.
   Overwrite replaces matching files but retains unrelated files in the folder.

The comparator runs in a separate process and displays progress and output
messages in the widget.

Troubleshooting
===============

* If the plugin is missing from napari, check that napari and Track Analyzer
  are installed in the same environment, as described in :doc:`installation`.
* If analysis cannot start, check the status and log, confirm ``info.txt``
  and ``data_base.p`` are available, and remove or adjust empty subsets.
* If an exported background cannot be found, save the image to a file or hide
  the background in the analysis settings.
* If map colors are unavailable, compute grid values and select a field with
  finite values. After changing grid inputs, recompute them.
* If comparator fields are unavailable, check that the corresponding analysis
  tables exist and contain the selected numerical parameter in every dataset.
