.. Track Analyzer - Quantification and visualization of tracking data
    Authors: Arthur Michaut                                                
    Copyright 2016-2019 Harvard Medical School and Brigham and             
                             Women's Hospital                              
    Copyright 2019-2022 Institut Pasteur and CNRS–UMR3738                  
    See the COPYRIGHT file for details                                     
                                                                           
    This file is part of Track Analyzer package.                           
                                                                           
    Track Analyzer is free software: you can redistribute it and/or modify 
    it under the terms of the GNU General Public License as published by   
    the Free Software Foundation, either version 3 of the License, or      
    (at your option) any later version.                                    
                                                                           
    Track Analyzer is distributed in the hope that it will be useful,      
    but WITHOUT ANY WARRANTY; without even the implied warranty of         
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the           
    GNU General Public License for more details .                          
                                                                           
    You should have received a copy of the GNU General Public License      
    along with Track Analyzer (COPYING).                                   
    If not, see <https://www.gnu.org/licenses/>.     

===============
Developer Guide
===============

This guide is a starting point for contributors working on the Python analysis
engine and the napari plugin. For analysis concepts and interface workflows,
start with :doc:`../user_guide/quickstart` and :doc:`../user_guide/napari`.

Development setup
-----------------

Use Python 3.11 or newer. From a source checkout, create and activate a
dedicated environment, then install the project in editable mode:

.. code-block:: sh

    python -m pip install -e ".[napari]"

The napari extra installs the plugin dependencies but not a Qt backend. Install
napari with a Qt 6 backend in the same environment, as shown in the
:doc:`installation guide <../user_guide/installation>`. Start the plugin with
``python -m napari`` and select **Plugins > Track Analyzer**. Editable
installation makes Python source changes available without reinstalling;
restart napari to reload them.

Tests and documentation
-----------------------

The test suite uses Python's ``unittest`` runner. From the checkout root:

.. code-block:: sh

    python -m unittest discover -s tests

To run one module, for example the topology tests:

.. code-block:: sh

    python -m unittest discover -s tests -p test_neighbor_exchange.py

The napari tests require the plugin dependencies and a Qt backend. For a
headless run on macOS or Linux, set ``QT_QPA_PLATFORM=offscreen`` before the
test command. Some tests start subprocesses and render images, so the full
suite takes longer than a focused test.

Build the Sphinx documentation from the checkout root:

.. code-block:: sh

    python -m pip install -r doc/requirements.txt
    python -m sphinx -W -b html doc/source doc/build/html

Open ``doc/build/html/index.html`` to inspect the result. The ``-W`` option
treats documentation warnings as errors.

Code layout
-----------

Paths below are relative to the checkout root.

* ``track_analyzer/prepare.py`` loads and preprocesses tracks, applies
  notebook-style filters, and constructs analysis configuration dictionaries.
* ``track_analyzer/calculate.py`` contains calculations such as velocity, MSD,
  Voronoi tessellation and grid interpolation. ``neighbor_exchange.py``
  detects topology-based T1/T2 candidates.
* ``track_analyzer/plotting.py`` creates figures and exports; ``rendering.py``
  supports TIFF stack rendering.
* ``track_analyzer/scripts/`` contains the trajectory, map, comparison,
  configuration and synthetic-data entry points. The command-line entry points
  are declared in ``setup.py``.
* ``track_analyzer/napari.yaml`` registers the two napari widgets.
  ``napari_plugin/widget.py`` owns dataset, metadata and filter controls;
  ``trajectory.py``, ``maps.py``, ``comparator.py`` and ``synthetic.py``
  implement the analysis tabs and synthetic-data widget.
* ``tests/`` contains calculation, layer conversion, widget and rendering
  tests. ``doc/source/`` contains the Sphinx sources.

Data and analysis flow
----------------------

1. The main napari widget imports and maps a tracking table or loads an
   existing database. Saving a database calls ``prepare.get_data`` to
   regularize trajectories, scale coordinates and compute motion quantities.
   The processed dictionary includes the dataframe, dimensions, scales and
   custom variables; it is saved as ``data_base.p``.
2. The filtering controls produce a filter dictionary. Napari previews use
   ``napari_plugin/filtering.py``; the analysis scripts apply filters through
   ``prepare.select_sub_data``. Keep preview and exported analysis behavior
   consistent when changing filtering.
3. ``TrajectoryAnalysisWidget.get_config`` translates controls into the
   configuration used by ``scripts/analyze_tracks.py``. Map analysis follows
   the equivalent path through ``MapAnalysisWidget`` and
   ``scripts/analyze_maps.py``.
4. The widgets validate inputs and start napari thread workers. The adapters in
   ``napari_plugin/analysis.py`` pass a serialized request to a separate Python
   process with Matplotlib's non-Qt ``Agg`` backend. Output is streamed to the
   widget; a failed process raises an error rather than returning a result.
   The trajectory and map scripts call the calculation and plotting modules
   and write numbered analysis directories.

Coordinates need particular care: processed ``x`` and ``y`` columns are
pixel coordinates, while ``x_scaled`` and ``y_scaled`` use the configured
length scale and may have a custom origin or inverted axes. Napari track
layers use ``(track, frame, [z,] y, x)`` ordering; see
``napari_plugin/layers.py``. Keep these conventions and units explicit when
adding viewer interactions or calculations.

Making a change
---------------

For a new analysis option, a typical path is:

1. Add or update the calculation independently of the UI, with tests for its
   behavior and edge cases.
2. Add the option to the appropriate default configuration in ``prepare.py``
   and consume it in the analysis script. Existing configurations may omit new
   keys: the scripts merge defaults before running.
3. Add napari controls and translate their values in the relevant widget's
   ``get_config``. Validate inputs before launching work, and report errors
   through the existing status and worker error paths.
4. Test the configuration, preview or layer behavior, and an actual analysis
   export when applicable. Update the relevant user guide and build the docs.

For map changes, also check whether cached grid values must be invalidated
when the inputs change. ``MapAnalysisWidget`` tracks the inputs used for its
grid preview and can reuse current values for export.
