ihmm#

pymovements.events.detection.ihmm(velocities: list[list[float]] | list[tuple[float, float]] | ndarray | Series, timesteps: list[int] | ndarray | Series | None = None, minimum_duration: int = 100, mu: list[float] | ndarray | None = None, sigma: list[float] | ndarray | None = None, init_state: list[float] | ndarray | None = None, transition_probabilities: list[list[float]] | ndarray | None = None, reestimation_max_iters: int = 1000, reestimation: bool = False, verbose: bool = False, hmm_parameters_dict: dict | None = None, name: str = 'fixation') → Events[source]#

Detect fixation events from velocity data using a Hidden Markov Model (I-HMM).

The implementation follows the algorithm from Salvucci and Goldberg [Salvucci et al., 2000].

This function implements a 2-state HMM specifically designed for eye-tracking data to distinguish between fixations (state 0) and saccades (state 1). It processes velocity time series, estimates optimal parameters via Baum-Welch (optional), decodes the most likely state sequence using Viterbi, and collapses contiguous fixation periods into events.

Parameters:
  • velocities (list[list[float]] | list[tuple[float, float]] | numpy.ndarray | polars.Series) – Velocity data. Can be: - 2D array of shape (T, 2) containing x and y velocity components - List of (vx, vy) tuples or lists - polars Series of 2-element lists Must have shape (T, 2). Will be converted to velocity magnitudes via Euclidean norm.

  • timesteps (list[int] | numpy.ndarray | polars.Series | None) – Timestamp for each velocity sample. May be integer or float valued. If None, uses sequential indices (0, 1, 2, …, T-1). (default: None)

  • minimum_duration (int) – Minimum fixation duration. The duration should be the same unit as the timesteps array. Must be an integer, so with float-valued timesteps (e.g. seconds) only whole-unit thresholds can be expressed. (default: 100)

  • mu (list[float] | numpy.ndarray | None) – Mean velocity for each state (Gaussian emissions). Shape: (2,), typically [fixation_mean, saccade_mean]. The state order is normalized internally by ascending mean, so the lowest-mean state is always treated as the fixation state (state 0) regardless of the order in which the two values are supplied. If None, uses data-driven defaults or hmm_parameters_dict. (default: None)

  • sigma (list[float] | numpy.ndarray | None) – Standard deviation of velocity for each state. Shape: (2,), typically [fixation_std, saccade_std]. If None, uses data-driven defaults or hmm_parameters_dict. (default: None)

  • init_state (list[float] | numpy.ndarray | None) – Initial state probability distribution (linear scale). Shape: (2,), e.g., [0.5, 0.5]. Must sum to 1. If None, uses defaults or hmm_parameters_dict. (default: None)

  • transition_probabilities (list[list[float]] | numpy.ndarray | None) – State transition probability matrix (linear scale). Shape: (2, 2). Each row must sum to 1. If None, uses default matrix [[0.95, 0.05], [0.05, 0.95]]. (default: None)

  • reestimation_max_iters (int) – Maximum number of Baum-Welch EM iterations if reestimation=True. (default: 1000)

  • reestimation (bool) – If True, performs Baum-Welch reestimation to optimize HMM parameters before state decoding. Recommended for robust parameter estimation. (default: False)

  • verbose (bool) – If True, prints parameter values and reestimation progress. Only effective when reestimation=True. (default: False)

  • hmm_parameters_dict (dict | None) – Dictionary containing custom HMM parameters with keys: - ‘mu’: list of 2 means - ‘sigma’: list of 2 standard deviations - ‘init’: list of 2 initial probabilities - ‘trans’: 2x2 transition probability matrix Overridden by explicit mu, sigma, init_state, transition_probabilities. (default: None)

  • name (str) – Name for the detected events. Appears in the returned Events object. (default: ‘fixation’)

Returns:

An Events object containing: - name: Event type name (‘fixation’ by default) - onsets: Array of fixation onset times - offsets: Array of fixation offset times Shape: (N,) where N is number of detected fixation events.

Return type:

Events

Notes

The processing pipeline consists of several steps:

  1. Input validation and conversion: - Converts velocities to 1D magnitude array via Euclidean norm - Removes leading/trailing NaN values - Validates parameter shapes and transition probability sums

  2. HMM parameter initialization (priority order): - Explicit parameters (mu, sigma, init_state, transition_probabilities) - Custom dictionary (hmm_parameters_dict) - Data-driven defaults (based on velocity percentiles)

  3. Optional parameter reestimation using Baum-Welch: - Maximizes likelihood of observed velocity data - Updates all HMM parameters - Runs for up to reestimation_max_iters iterations

  4. State decoding using Viterbi algorithm: - Finds most likely fixation/saccade sequence

  5. Event extraction: - Collapses consecutive fixation state periods into events - Returns onset and offset times for each fixation

The default transition probabilities (0.95 for self-transitions, 0.05 for switches) are based on Salvucci’s eye movement model, reflecting typical fixation and saccade durations.

Only leading and trailing samples with missing (NaN) velocity are trimmed before decoding. Interior missing samples are kept, and their emission probability is skipped, so Viterbi assigns them a state based on the transition probabilities alone. As a result a fixation can span short gaps of missing data, and events are not split on interior NaNs. This differs from the include_nan option of ivt(), which can split events on missing values.

Raises:
  • TypeError – If velocities is a polars Series whose dtype is not List. If timesteps is a polars Series with a non-numeric dtype. If minimum_duration is not an integer.

  • ValueError – If velocities does not have shape (T, 2). If velocities is a polars Series whose lists don’t all have length 2. If parameter shapes are incorrect (not (2,) or (2,2)). If minimum_duration is not greater than 0. If transition_probabilities rows don’t sum to 1, or contain values outside [0, 1]. If init_state does not sum to 1, or contains values outside [0, 1]. If hmm_parameters_dict has incorrect keys or shapes, or its init/trans values don’t sum to 1 or lie outside [0, 1].

Examples

Create a synthetic step signal representing gaze segments.

>>> import numpy as np
>>> from pymovements.transforms.numpy import pos2vel
>>> from pymovements.synthetic import step_function
>>> from pymovements.gaze import from_numpy
>>> positions = step_function(
...         length=500,
...         steps=[50, 250, 450, 650, 750],
...         values=[(5., 5.), (10., 10.), (5., 5.), (15., 15.), (5., 5.)],
...         start_value=(0., 0.))
>>> positions.shape
(500, 2)

Transform into velocities

>>> velocities = pos2vel(positions)
>>> velocities.shape
(500, 2)

Apply event detection algorithm on numpy array:

>>> ihmm(velocities)
shape: (2, 4)
┌──────────┬───────┬────────┬──────────┐
│ name     ┆ onset ┆ offset ┆ duration │
│ ---      ┆ ---   ┆ ---    ┆ ---      │
│ str      ┆ i64   ┆ i64    ┆ i64      │
╞══════════╪═══════╪════════╪══════════╡
│ fixation ┆ 52    ┆ 247    ┆ 195      │
│ fixation ┆ 252   ┆ 447    ┆ 195      │
└──────────┴───────┴────────┴──────────┘

Run fixation detection with custom HMM parameters:

>>> hmm_parameters = {'mu': [2.0140785987072225, 69.41529375180251],
...         'sigma': [1.3220152347857494, 87.32409626093246],
...         'init': [1.e+00, 1.e-12],
...         'trans': [[0.97360507, 0.02639493],[0.07593547, 0.92406453]]}
>>> ihmm(velocities, hmm_parameters_dict = hmm_parameters)
shape: (2, 4)
┌──────────┬───────┬────────┬──────────┐
│ name     ┆ onset ┆ offset ┆ duration │
│ ---      ┆ ---   ┆ ---    ┆ ---      │
│ str      ┆ i64   ┆ i64    ┆ i64      │
╞══════════╪═══════╪════════╪══════════╡
│ fixation ┆ 52    ┆ 247    ┆ 195      │
│ fixation ┆ 252   ┆ 447    ┆ 195      │
└──────────┴───────┴────────┴──────────┘

We can also apply the detection on a Gaze object.

>>> from pymovements import Experiment
>>> gaze = from_numpy(
...         velocity=velocities.T,
...         time=np.arange(len(velocities)),)
>>> gaze
shape: (500, 2)
┌──────┬────────────┐
│ time ┆ velocity   │
│ ---  ┆ ---        │
│ i64  ┆ list[f64]  │
╞══════╪════════════╡
│ 0    ┆ [0.0, 0.0] │
│ 1    ┆ [0.0, 0.0] │
│ 2    ┆ [0.0, 0.0] │
│ 3    ┆ [0.0, 0.0] │
│ 4    ┆ [0.0, 0.0] │
│ …    ┆ …          │
│ 495  ┆ [0.0, 0.0] │
│ 496  ┆ [0.0, 0.0] │
│ 497  ┆ [0.0, 0.0] │
│ 498  ┆ [0.0, 0.0] │
│ 499  ┆ [0.0, 0.0] │
└──────┴────────────┘

Run fixation detection by using the detect() method.

>>> gaze.detect('ihmm')
>>> gaze.events
shape: (2, 4)
┌──────────┬───────┬────────┬──────────┐
│ name     ┆ onset ┆ offset ┆ duration │
│ ---      ┆ ---   ┆ ---    ┆ ---      │
│ str      ┆ i64   ┆ i64    ┆ i64      │
╞══════════╪═══════╪════════╪══════════╡
│ fixation ┆ 52    ┆ 247    ┆ 195      │
│ fixation ┆ 252   ┆ 447    ┆ 195      │
└──────────┴───────┴────────┴──────────┘

Passing parameters to detect():

>>> gaze.detect('ihmm', reestimation=True, name='fixation_ihmm')
>>> gaze.events.filter_by_name('fixation_ihmm')
shape: (2, 4)
┌───────────────┬───────┬────────┬──────────┐
│ name          ┆ onset ┆ offset ┆ duration │
│ ---           ┆ ---   ┆ ---    ┆ ---      │
│ str           ┆ i64   ┆ i64    ┆ i64      │
╞═══════════════╪═══════╪════════╪══════════╡
│ fixation_ihmm ┆ 52    ┆ 247    ┆ 195      │
│ fixation_ihmm ┆ 252   ┆ 447    ┆ 195      │
└───────────────┴───────┴────────┴──────────┘