Source code for pypillometry.sim.steps

"""
Steps of a :class:`~pypillometry.sim.Simulation`.

Each step is a small dataclass with the parameters of one part of the
simulated recording. A simulation runs its steps in a fixed order of
stages, whatever the order in which they were added:

1. ``"events"``: the events of a task (:class:`~pypillometry.sim.Task`)
2. ``"pupil"``: the latent pupil size in log-%, :math:`100 \\log(\\text{size}
   / \\text{median})` (:class:`TimescalePupil`)
3. ``"gaze"``: the gaze position in pixels (:class:`Fixations`)
4. ``"foreshortening"``: the apparent pupil size as seen by the camera
   (:class:`Foreshortening`)
5. ``"units"``: from log-% to the units of the tracker (:class:`Units`)
6. ``"occlusion"``: blinks, the lid covers the pupil (:class:`Blinks`)
7. ``"noise"``: measurement noise (:class:`WhiteNoise`)
8. ``"missing"``: losses of the pupil by the tracker (:class:`TrackerLoss`);
   then the samples without pupil (in blinks and losses) are set missing,
   in the pupil and the gaze; comb artifacts (:class:`Comb`) are also in
   this stage

Each step draws from its own random stream (derived from the seed of the
simulation, its stage and its position in the stage), so that changing one
step leaves the random numbers of the others unchanged.
"""
from dataclasses import dataclass, fields
from typing import TYPE_CHECKING, Any

import numpy as np

from ..units import parse_time

if TYPE_CHECKING:
    from ..signal.gaussmarkov import TimescaleBank

__all__ = ["TimescalePupil", "Fixations", "Foreshortening", "Units", "WhiteNoise", "Blinks",
           "TrackerLoss", "Comb"]

#: order in which the stages are run
STAGES = ("events", "pupil", "gaze", "foreshortening", "units", "occlusion", "noise",
          "missing")
#: key of the random stream of each stage (fixed, so that adding stages does
#: not change the random numbers of the others)
STAGE_KEYS = {"pupil": 0, "gaze": 1, "foreshortening": 2, "units": 3, "noise": 4,
              "events": 5, "occlusion": 6, "missing": 7}


def _eyes(eyes) -> tuple[str, ...] | None:
    """tuple of eyes (None: all eyes of the simulation)"""
    if eyes is None:
        return None
    return (eyes,) if isinstance(eyes, str) else tuple(eyes)


def _plain(value) -> Any:
    """value with tuples as lists and numpy scalars as numbers (for the state)"""
    if isinstance(value, dict):
        return {k: _plain(v) for k, v in value.items()}
    if isinstance(value, (list, tuple)):
        return [_plain(v) for v in value]
    if isinstance(value, np.generic):
        return value.item()
    return value


class SimStep:
    """
    Base class of the steps.

    A step has a `stage` (see :data:`STAGES`), the eyes it applies to
    (`eyes`; None: all eyes of the simulation) and a method ``apply(run,
    rng)`` that changes the arrays of the running simulation and adds to
    its ground truth.
    """
    stage = None

    def apply(self, run, rng) -> None:
        """change the arrays of the running simulation `run`"""
        raise NotImplementedError

    def generate(self, rng) -> tuple[dict[str, np.ndarray], float]:
        """the events and the duration (ms), for steps of stage ``"events"``"""
        raise NotImplementedError

    def __post_init__(self) -> None:
        # lists (e.g., from a saved state) as tuples, so that steps compare equal
        for f in fields(self):
            v = getattr(self, f.name)
            if isinstance(v, list):
                setattr(self, f.name, tuple(v))
            elif f.name == "eyes" and isinstance(v, str):
                setattr(self, f.name, (v,))

    def eyes_in(self, run) -> tuple[str, ...]:
        """the eyes of the simulation the step applies to"""
        eyes = _eyes(getattr(self, "eyes", None))
        if eyes is None:
            return run.eyes
        unknown = set(eyes) - set(run.eyes)
        if unknown:
            raise ValueError(f"{type(self).__name__}: the simulation has no eyes "
                             f"{sorted(unknown)} (eyes: {list(run.eyes)})")
        return eyes

    def to_dict(self) -> dict[str, Any]:
        """name and parameters of the step (numbers, strings, lists, dicts)"""
        return {"step": type(self).__name__,
                "params": {f.name: _plain(getattr(self, f.name)) for f in fields(self)}}

    @staticmethod
    def from_dict(d) -> "SimStep":
        """the step from :meth:`to_dict`"""
        from .task import Task
        cls = {c.__name__: c for c in (TimescalePupil, Fixations, Foreshortening, Units,
                                       WhiteNoise, Task, Blinks, TrackerLoss,
                                       Comb)}.get(d["step"])
        if cls is None:
            raise ValueError(f"unknown simulation step {d['step']!r}")
        return cls(**d["params"])

    def __repr__(self) -> str:
        def short(v):
            if isinstance(v, float):
                return str(int(v)) if v.is_integer() and abs(v) < 1e12 else f"{v:.4g}"
            if isinstance(v, dict):
                return "{" + ", ".join(f"{k!r}: {short(x)}" for k, x in v.items()) + "}"
            if isinstance(v, tuple):
                return "(" + ", ".join(short(x) for x in v) + ("," if len(v) == 1 else "") + ")"
            return repr(v)
        args = ", ".join(f"{f.name}={short(getattr(self, f.name))}" for f in fields(self)
                         if getattr(self, f.name) != f.default)
        return f"{type(self).__name__}({args})"


[docs] @dataclass(repr=False) class TimescalePupil(SimStep): """ Latent pupil size from the timescale model (see :class:`~pypillometry.TimescaleModel`): a fast component (Matérn-3/2) and slow components ("atoms") at fixed time scales, in log-%. Parameters ---------- params : dict, optional parameters on their natural scale, as for one unit in :attr:`TimescaleModel.params <pypillometry.TimescaleModel.params>`: ``fast_sd`` (log-%), ``fast_ell`` (ms) and the standard deviation of each atom (``sd_3s``, ``sd_10s``, ...; log-%); for two eyes with `binocular` also ``diff_sd``, ``diff_ell`` (the difference between the eyes) and ``gain`` (of the common components in the second eye relative to the first). Missing parameters are the centre of the general prior (see :func:`~pypillometry.signal.gaussmarkov.general_prior`); the noise (``noise_sd``) is ignored (see :class:`WhiteNoise`). timescales : sequence of float, str or Quantity time scales of the atoms (plain numbers are ms); default 3, 10, 30, 100 and 300 s nu : float smoothness of the atoms (default 1.5) binocular : bool if True, the eyes share the fast component and the atoms and differ by a difference component (needs two eyes); if False (default), each eye is drawn independently with the same parameters cutoff : float, str or Quantity time scale from which on the atoms count as slow, for the ground truth ``log_slow`` (plain numbers are ms; default 10 s) eyes : str or list, optional eyes the step applies to (default: all eyes of the simulation) Notes ----- Ground truth per eye (log-%): ``log_size`` (the latent signal), ``log_fast``, one entry per atom (``log_3s``, ...), ``log_slow`` (the atoms from `cutoff`) and, if `binocular`, ``log_diff``; ``log_size`` is the sum of the components. Examples -------- The components of five minutes of the latent pupil size: .. plot:: >>> import pypillometry as pp >>> d = pp.sim.Simulation("5 min", fs=20, seed=1, name="TimescalePupil").pupil().run() >>> fig = d.plot.plot_components() """ params: dict | None = None timescales: tuple = ("3 s", "10 s", "30 s", "100 s", "300 s") nu: float = 1.5 binocular: bool = False cutoff: str = "10 s" eyes: tuple | None = None stage = "pupil" def bank(self, eyes) -> "TimescaleBank": from ..signal.gaussmarkov import TimescaleBank ts = [float(parse_time(t, to="ms")) for t in self.timescales] return TimescaleBank(ts, nu=self.nu, channels=tuple(eyes) if self.binocular else 1)
[docs] def theta(self, bank) -> np.ndarray: """parameter vector of `bank` (the noise is negligible)""" from ..signal.gaussmarkov import general_prior p = bank.params(general_prior(bank).mean) given = dict(self.params or {}) unknown = set(given) - set(p) if unknown: raise ValueError(f"TimescalePupil: unknown parameters {sorted(unknown)}; " f"use {sorted(k for k in p if not k.startswith('noise'))}") p.update(given) for k in p: if k.startswith("noise_sd"): p[k] = 1e-9 for k in ("fast_sd", "diff_sd"): if k in p: p[k] = max(float(p[k]), 1e-9) return bank.theta(**p)
[docs] def apply(self, run, rng) -> None: eyes = self.eyes_in(run) if self.binocular and len(eyes) != 2: raise ValueError(f"TimescalePupil(binocular=True) needs two eyes, got {list(eyes)}") cutoff = float(parse_time(self.cutoff, to="ms")) groups = [eyes] if self.binocular else [(e,) for e in eyes] rngs = rng.spawn(len(groups)) for group, r in zip(groups, rngs): bank = self.bank(group) theta = self.theta(bank) _, X = bank.simulate(theta, run.n, run.fs, rng=r, return_states=True) names = ["fast"] + (["diff"] if self.binocular else []) + bank.atom_names for ch, eye in enumerate(group): parts = {n: X @ bank.select(n, cutoff, channel=ch, theta=theta) for n in names + ["slow", "signal"]} run.set_pupil(eye, parts.pop("signal")) for n, v in parts.items(): run.truth[eye, f"log_{n}"] = v
[docs] @dataclass(repr=False) class Fixations(SimStep): """ Gaze as a sequence of fixations at random places on the screen (the same for all eyes). Parameters ---------- mean, sd : float, str or Quantity mean and standard deviation of the duration of the fixations (plain numbers are ms; at least 50 ms); default 300 and 100 ms screen : tuple of int, optional width and height of the screen in pixels; default: the screen of the experimental setup of the simulation, or (1920, 1080) Examples -------- The gaze position during three seconds: .. plot:: >>> import pypillometry as pp >>> import matplotlib.pyplot as plt >>> d = pp.sim.Simulation("3 s", fs=200, seed=1).pupil().gaze().run() >>> fig, ax = plt.subplots(figsize=(8, 3), layout="constrained") >>> _ = ax.plot(d.tx / 1000, d["left_x"], label="x") >>> _ = ax.plot(d.tx / 1000, d["left_y"], label="y") >>> _ = ax.set(xlabel="time (sec)", ylabel="gaze (px)") >>> _ = ax.legend() """ mean: str = "300 ms" sd: str = "100 ms" screen: tuple | None = None stage = "gaze"
[docs] def apply(self, run, rng) -> None: if self.screen is not None: width, height = self.screen elif run.setup is not None and run.setup.screen_resolution is not None: width, height = run.setup.screen_resolution else: width, height = 1920, 1080 mean = float(parse_time(self.mean, to="ms")) sd = float(parse_time(self.sd, to="ms")) total = run.n * 1000.0 / run.fs n_fix = int(total / mean) + 1 durations = np.clip(rng.normal(mean, sd, n_fix), 50, None) durations *= total / durations.sum() # fill the whole recording starts = np.r_[0, np.cumsum(durations)[:-1]] idx = np.searchsorted(starts, np.arange(run.n) * 1000.0 / run.fs, side="right") - 1 x = rng.uniform(0, width, n_fix)[idx] y = rng.uniform(0, height, n_fix)[idx] for eye in run.eyes: run.x[eye], run.y[eye] = x.copy(), y.copy()
[docs] @dataclass(repr=False) class Foreshortening(SimStep): """ Pupil foreshortening: the camera sees the pupil at the angle :math:`\\alpha` between the directions from the eye to the camera and to the gaze position, so that the measured size is :math:`A_0 \\cos\\alpha`. Needs the gaze (e.g., :class:`Fixations`) and an experimental setup with screen, eye distance and camera position. Parameters ---------- eye_offset : float horizontal offset of the eye from the screen centre (mm) Notes ----- Ground truth per eye: ``cosalpha``. Examples -------- The measured pupil is smaller than the true size, and jumps with the gaze: .. plot:: >>> import pypillometry as pp >>> import matplotlib.pyplot as plt >>> setup = pp.ExperimentalSetup(screen_resolution=(1920, 1080), ... physical_screen_size=("52 cm", "29 cm"), ... eye_to_screen_center="60 cm", ... camera_spherical=("20 deg", "-90 deg", "70 cm")) >>> d = (pp.sim.Simulation("10 s", fs=100, seed=1, setup=setup, name="Foreshortening") ... .pupil().gaze().foreshortening().units(800).run()) >>> fig, ax = plt.subplots(figsize=(8, 3), layout="constrained") >>> ax = d.plot.plot_truth(ax=ax) """ eye_offset: float = 0.0 stage = "foreshortening"
[docs] def apply(self, run, rng) -> None: from ..eyedata.foreshortening_calibration import _compute_cos_alpha_vectorized setup = run.setup if setup is None or not (setup.has_screen_info() and setup.has_eye_distance() and setup.has_camera_position()): raise ValueError("Foreshortening needs an experimental setup with screen, " "eye distance and camera position (Simulation(setup=...))") for eye in run.eyes: if eye not in run.x: raise ValueError("Foreshortening needs the gaze (e.g., Fixations)") x_mm, y_mm = setup.pixels_to_mm(run.x[eye], run.y[eye]) cos_alpha = _compute_cos_alpha_vectorized( x_mm, y_mm, setup.theta, setup.phi, setup.r, setup.d, eye_offset=self.eye_offset) run.truth[eye, "cosalpha"] = cos_alpha run.log_pupil[eye] = run.log_pupil[eye] + 100.0 * np.log(cos_alpha)
[docs] @dataclass(repr=False) class Units(SimStep): """ Units of the tracker: the pupil is :math:`\\text{median} \\cdot e^{y / 100}` for the signal :math:`y` in log-%. Parameters ---------- median : float or dict median pupil size in the units of the tracker (per eye with a dict); default 1000 Notes ----- Ground truth per eye: ``size`` (the true pupil size) and ``pupil`` (the pupil as measured without noise, i.e. with the foreshortening). """ median: float = 1000.0 stage = "units"
[docs] def apply(self, run, rng) -> None: for eye in run.eyes: m = self.median[eye] if isinstance(self.median, dict) else self.median run.truth[eye, "size"] = m * np.exp(run.log_size[eye] / 100.0) run.pupil[eye] = m * np.exp(run.log_pupil[eye] / 100.0) run.truth[eye, "pupil"] = run.pupil[eye].copy()
[docs] @dataclass(repr=False) class WhiteNoise(SimStep): """ White measurement noise on the pupil. Parameters ---------- sd : float standard deviation of the noise scale : {"log%", "data"} ``"log%"`` (default): `sd` in log-% (multiplicative noise, like the noise of the timescale model); ``"data"``: `sd` in the units of the data (additive) eyes : str or list, optional eyes the step applies to (default: all eyes of the simulation) Examples -------- Two seconds with noise of 0.5 log-%: .. plot:: >>> import pypillometry as pp >>> import matplotlib.pyplot as plt >>> d = pp.sim.Simulation("2 s", fs=500, seed=1, name="WhiteNoise").pupil().units(800).noise(0.5).run() >>> fig, ax = plt.subplots(figsize=(8, 3), layout="constrained") >>> ax = d.plot.plot_truth(ax=ax) """ sd: float = 0.2 scale: str = "log%" eyes: tuple | None = None stage = "noise" def __post_init__(self) -> None: super().__post_init__() if self.scale not in ("log%", "data"): raise ValueError(f"scale must be 'log%' or 'data', got {self.scale!r}") if self.sd < 0: raise ValueError("sd must not be negative")
[docs] def apply(self, run, rng) -> None: for eye in self.eyes_in(run): e = rng.normal(0.0, self.sd, run.n) if self.scale == "log%": run.pupil[eye] = run.pupil[eye] * np.exp(e / 100.0) else: run.pupil[eye] = run.pupil[eye] + e
def _event_times(rate, min_interval, total, rng) -> np.ndarray: """onsets (ms) of events at `rate` (per ms) with a minimal interval""" if rate <= 0: return np.zeros(0) mean = 1.0 / rate extra = max(mean - min_interval, 1e-9) out, t = [], rng.exponential(mean) while t < total: out.append(t) t += min_interval + rng.exponential(extra) return np.array(out)
[docs] @dataclass(repr=False) class TrackerLoss(SimStep): """ Losses of the pupil by the tracker: stretches of missing samples at random times, without a transient. Parameters ---------- rate : str or float mean rate (``"0.5/min"``; plain numbers per minute) duration : float, str or distribution duration of a loss binocular : bool if True, the losses are the same in all eyes; if False (default), each eye has its own eyes : str or list, optional eyes (default: all eyes of the simulation) Notes ----- Ground truth: one true event ``"loss"`` per loss and eye in ``d.truth_events`` (with the metadata ``eye`` and ``duration``). Examples -------- Ten seconds with losses (shaded): .. plot:: >>> import pypillometry as pp >>> import matplotlib.pyplot as plt >>> d = (pp.sim.Simulation("10 s", fs=500, seed=1) ... .pupil().units(800).loss(rate="20/min", duration="300 ms").noise(0.1).run()) >>> t = d.tx / 1000 >>> fig, ax = plt.subplots(figsize=(8, 3), layout="constrained") >>> _ = ax.plot(t, d.truth["left", "pupil"], color="0.7", label="true") >>> _ = ax.plot(t, d["left_pupil"], label="data") >>> for onset, dur in zip(d.truth_events.onsets, d.truth_events.meta["duration"]): ... _ = ax.axvspan(onset / 1000, (onset + dur) / 1000, alpha=0.2) >>> _ = ax.set(xlabel="time (sec)", ylabel="pupil") >>> _ = ax.legend() """ rate: str = "0.5/min" duration: str = "lognormal(150 ms, 200 ms)" binocular: bool = False eyes: tuple | None = None stage = "missing" def __post_init__(self) -> None: super().__post_init__() from .dist import parse_dist, parse_rate parse_rate(self.rate) parse_dist(self.duration)
[docs] def apply(self, run, rng) -> None: from .dist import parse_dist, parse_rate eyes = self.eyes_in(run) dt = 1000.0 / run.fs groups = [eyes] if self.binocular else [(e,) for e in eyes] dur = parse_dist(self.duration) for group in groups: for t0 in _event_times(parse_rate(self.rate), 0.0, run.n * dt, rng): length = max(float(dur.sample(rng)), dt) a = int(np.ceil(t0 / dt)) b = min(int(np.ceil((t0 + length) / dt)), run.n) if b <= a: continue for e in group: mask = np.zeros(run.n, dtype=bool) mask[a:b] = True run.lost(e, mask) run.truth_events.append(dict(onset=a * dt, label="loss", eye=e, duration=(b - a) * dt))
[docs] @dataclass(repr=False) class Comb(SimStep): """ Comb artifacts: bursts of teeth, short dropouts of the pupil with a too-small value on each side, or short drops without missing samples, so that the signal looks like a comb. The bursts come at random times (`rate`); in a burst, a tooth starts every `interval` until the end of the burst (`duration`). With probability `missing`, the tracker loses the pupil for `gap`, and the sample before and the one after the dropout are lowered by `depth` (a fraction of the pupil); otherwise, the samples of the `gap` are lowered by `depth` and are not missing. :meth:`d.pupil.mask_comb() <pypillometry.eyedata.pupil.PupilNamespace.mask_comb>` finds the lowered samples. The defaults are close to the comb of an EyeLink recording (1000 Hz). Parameters ---------- rate : str or float mean rate of the bursts (``"15/min"``; plain numbers per minute) duration : float, str or distribution duration of a burst (from the start of its first tooth to the start of its last one) interval : float, str or distribution time from the start of one tooth to the start of the next (at least one sample) gap : float, str or distribution duration of the dropout of a tooth (or of the drop, without missing samples; at least one sample) depth : float or distribution how much a lowered sample is lowered, as a fraction of the pupil (drawn for each lowered sample) missing : float share of the teeth with a dropout (default 1); 0: all teeth are drops without missing samples binocular : bool if True, the bursts and teeth are the same in all eyes (the depths are drawn for each eye); if False (default), each eye has its own eyes : str or list, optional eyes (default: all eyes of the simulation) Notes ----- Ground truth: ``comb`` per eye (the fraction by which each sample was lowered, 0 elsewhere), and one true event ``"comb"`` per burst and eye in ``d.truth_events`` (with the metadata ``eye``, ``duration`` and ``teeth``, the number of teeth). Examples -------- A burst of teeth with dropouts (default) and one without (``missing=0``): .. plot:: >>> import numpy as np >>> import pypillometry as pp >>> import matplotlib.pyplot as plt >>> fig, axes = plt.subplots(2, 1, figsize=(8, 4.5), layout="constrained") >>> for ax, missing in zip(axes, (1, 0)): ... d = (pp.sim.Simulation("1 min", fs=1000, seed=3).pupil().units(800).noise(0.1) ... .comb(missing=missing).run()) ... te = d.truth_events ... t0 = te.onsets[np.argmax(te.meta["teeth"])] # the longest burst ... win = (d.tx > t0 - 30) & (d.tx < t0 + 200) ... _ = ax.plot(d.tx[win], d.truth["left", "pupil"][win], color="0.7", label="true") ... _ = ax.plot(d.tx[win], d["left_pupil"][win], ".-", ms=3, label="data") ... _ = ax.set(title=f"missing={missing}", xlabel="time (ms)", ylabel="pupil") >>> _ = axes[0].legend() """ rate: str = "15/min" duration: str = "lognormal(70 ms, 80 ms)" interval: str = "lognormal(12 ms, 6 ms)" gap: str = "lognormal(7 ms, 6 ms)" depth: str = "normal(0.045, 0.01)" missing: float = 1.0 binocular: bool = False eyes: tuple | None = None stage = "missing" def __post_init__(self) -> None: super().__post_init__() from .dist import parse_dist, parse_rate parse_rate(self.rate) for spec in (self.duration, self.interval, self.gap, self.depth): parse_dist(spec) if not 0 <= self.missing <= 1: raise ValueError("missing must be between 0 and 1")
[docs] def apply(self, run, rng) -> None: from .dist import parse_dist, parse_rate eyes = self.eyes_in(run) n, dt = run.n, 1000.0 / run.fs D = {k: parse_dist(getattr(self, k)) for k in ("duration", "interval", "gap", "depth")} drop = {e: np.zeros(n) for e in eyes} lost = {e: np.zeros(n, dtype=bool) for e in eyes} def lower(e, ix): d = min(max(float(D["depth"].sample(rng)), 0.0), 1.0) drop[e][ix] = np.maximum(drop[e][ix], d) groups = [eyes] if self.binocular else [(e,) for e in eyes] for group in groups: for t0 in _event_times(parse_rate(self.rate), 0.0, n * dt, rng): end = t0 + max(float(D["duration"].sample(rng)), 0.0) teeth, t = 0, t0 while t <= end: a = int(np.ceil(t / dt)) b = min(int(np.ceil((t + max(float(D["gap"].sample(rng)), dt)) / dt)), n) t += max(float(D["interval"].sample(rng)), dt) if a >= n: break if b <= a: continue teeth += 1 if rng.random() < self.missing: for e in group: lost[e][a:b] = True for ix in (a - 1, b): if 0 <= ix < n: lower(e, ix) else: for e in group: for ix in range(a, b): lower(e, ix) for e in group: run.truth_events.append(dict(onset=t0, label="comb", eye=e, duration=end - t0, teeth=teeth)) for e in eyes: drop[e][lost[e]] = 0.0 # missing: not lowered run.pupil[e] = run.pupil[e] * (1 - drop[e]) run.truth[e, "comb"] = drop[e] run.lost(e, lost[e])