PupilNamespace#

class pypillometry.eyedata.pupil.PupilNamespace(data=None)[source]#

Bases: Namespace[EyeData]

Methods for pupil data, accessed as d.pupil (e.g., d.pupil.blinks_detect()).

The methods need pupil data and raise a ValueError if there is none. The transforming methods return the data object (see Namespace).

Methods

blinks_detect

Detect blinks in the pupillary signal.

blinks_detect_partial

Detect partial blinks: a fast fall followed by a fast rise of the pupil without missing samples between them (the lid covers part of the pupil, but the tracker does not lose it).

blinks_extend_adaptive

Extend the blinks to cover slow openings of the lid, with a margin tuned for each part of the recording.

blinks_interpolate

Interpolating blinks in the pupillary signal.

blinks_merge_close

Merge blinks that are close together.

blinks_optimize_parameters

Tune the parameters of blinks_interpolate() for this recording.

correct_foreshortening

Correct pupil data using a simple algorithm to correct for foreshortening effects.

estimate_baseline

Apply one of the baseline-estimation methods.

estimate_response

Estimate pupil-response based on event-onsets, see pupil_response().

fit_foreshortening

Fit foreshortening correction model to estimate camera geometry and true pupil size.

lowpass_filter

Lowpass-filter pupil signal using a Butterworth-filter.

mask_comb

Mask comb artifacts: short drops of the pupil that come back up within a few milliseconds, often many in a row, so that the signal looks like a comb.

mask_transients

Mask transients: fast changes of the pupil that are artifacts.

merge_eyes

Merge pupil data from both eyes into a new eye (default "mean").

smooth_window

Apply smoothing of the signal using a moving window.

spectrum

Power spectrum of the pupil size (Welch's method for data with gaps).

Details

Detect blinks in the pupillary signal.

A blink is a run of missing samples (NaN or 0) with the marks of the lid next to it: the lid covering the pupil makes the signal fall fast before the dropout (the closing), and the reopening makes it rise after it. The length of these flanks comes from the data (it differs between people, between closing and reopening, and with tiredness). They are found with one of two tests (method, as in mask_transients()):

  • "excess" (default; see excess_flank()): the change from the edge of the dropout over many intervals (scales, 10 to 300 ms) is compared with the largest change the pupil can manage in that interval (flank_rate times its length). It also finds a slow reopening, which is too slow to stand out in a short window. A flank counts if the excess is larger than z times the noise of a difference; it ends where the excess is largest, where the change has slowed to a pace the pupil could manage.

  • "velocity": the velocity (window winsize), with hysteresis: a flank is the run of samples next to the dropout where the signal changes faster than flank_rate_min, and it counts if it reaches flank_rate for at least flank_min_duration.

Runs of missing samples without these marks (e.g., loss of tracking, looking away) are not blinks: they stay missing, but are not interpolated by blinks_interpolate(). A fast fall followed by a fast rise without missing samples (a partial blink) is found by blinks_detect_partial(). Samples masked under policy right next to the missing ones (e.g., the margin of another mask) belong to the dropout: the flanks are looked for beyond them, and on a side without a flank the blink ends with the missing samples. A masked stretch without missing samples is not a blink.

Detected blinks are stored in the object, as the "blink" layer of the pupil (retrieve them with get_blinks()), and are masked under the mask policies (see mask()). They replace the blinks detected before (and their mask), and the blinks detected before are not treated as masked during detection, so re-running the detection with other parameters gives the same result as running it once (clear_layer("blink") removes them). Eyes whose pupil has interpolated samples (after blinks_interpolate()) are skipped with a warning and keep their blinks: the values there are reconstructed, so detect blinks before interpolating them.

Blinks have to be at least min_duration and at most max_duration long; longer runs of missing samples (e.g., loss of the pupil or breaks) stay missing, but are not blinks. They can be extended by a margin on each side, e.g. to include the slow parts of the transient around the blink.

Parameters:
  • eyes (list) – list of eyes to process; if empty, all available eyes are processed

  • min_duration (float) – minimum duration (in ms, or with units) for a sequence of missing numbers to be treated as blink (rounded to the nearest number of samples, at least 2 samples)

  • max_duration (float) – maximum duration (in ms, or with units) of a blink (default 2 s, generous: the flanks decide what is a blink, and blinks that are close are merged later, see blinks_merge_close()). None means no limit.

  • require (str) –

    which flanks a dropout needs to be a blink:

    • "either" (default): a closing before or a reopening after it

    • "both": a closing before and a reopening after it

    • "none": none; every dropout between min_duration and max_duration is a blink (e.g., for data where the tracker does not show the transients, or for synthetic data)

  • flank_rate (float, str or None) – the rate of the flanks (falling before, rising after the dropout): with method="excess", the largest plausible rate of the pupil (default "0.1%/ms"); with method="velocity", how fast a flank has to be (default "5sd"). "<p>%/ms": p percent of the local pupil size per millisecond (also on data scaled with scale()); "<k>sd": k times the robust standard deviation of the velocity of the recording, which adapts to the units and the noise of the data; a number: units of the data per millisecond

  • method (str) – test of the flanks: "excess" (default) or "velocity" (see above)

  • z (float) – excess test: threshold of the excess change, in standard deviations of the noise of a difference of two samples (default 4)

  • scales (tuple) – excess test: shortest and longest interval of the test (in ms, or with units; default 10 and 300 ms); the longest also bounds the length of a flank

  • smooth (float) – excess test: width of the running median of the signal and of the start value at the edge (in ms, or with units; default 5 ms)

  • flank_rate_min (float or str) – velocity: rate down to which a flank extends (hysteresis; default "2sd", same forms); "0sd" extends it up to where the signal turns (which can include slow trends of the pupil). The first 10 ms next to the dropout may be slower.

  • flank_min_duration (float) – velocity: how long (in ms, or with units) a flank has to be beyond flank_rate (default 10 ms; against noise)

  • max_gap (float) – a flank goes on across missing or masked samples up to this long (in ms, or with units; default 5 ms), e.g. a short dropout during the reopening or a sample removed by another criterion

  • winsize (float) – velocity: size of the Savitzky-Golay window of the velocity (in ms, or with units; default 45 ms), rounded to the nearest odd number of samples, at least 5 samples

  • margin (float, str, Quantity or tuple) – time (in ms, or with units) by which each detected blink is extended to the left and right, after the min_duration filter; a tuple (before, after) gives different margins on each side. Blinks that overlap after extending are merged. Default 0 (no extension). This is independent of the margin of blinks_interpolate(), which is applied on top of it.

  • level (dict, optional) – settings of the local pupil size that rates in "%/ms" refer to (scales, min_coverage, max_dev; see local_level() and plot_local_level()); default: its defaults

  • policy (str or MaskPolicy) – which masked samples the detection leaves out (default "strict"; see mask()): they are no dropouts by themselves (only next to missing samples, see above), no flank is found in them, and they do not count for the thresholds relative to the velocity. "raw" uses all samples. Masks of other criteria often cover the flanks of blinks (e.g., the gaze dives at the closing of the lid, so mask_offscreen() with the pupil masks the closing; mask_transients() masks the flanks themselves); detect blinks before them, or leave their layers out, e.g. MaskPolicy("*", exclude=["offscreen", "transient"]).

  • inplace (bool or None) – if True, make change in-place and return the object if False, make and return copy before making changes if None, use the object-level setting

Return type:

EyeData

Returns:

the object with the blinks (self or a copy, depending on inplace)

Examples

>>> d = d.pupil.blinks_detect()
>>> d.get_blinks(variables="pupil", units="ms")

Detect partial blinks: a fast fall followed by a fast rise of the pupil without missing samples between them (the lid covers part of the pupil, but the tracker does not lose it).

The fall and the rise are found with one of two tests (method, as in blinks_detect()):

  • "excess" (default; see excess_flank()): the tip of the dip takes the place of the dropout of a blink. From each minimum of the signal, the change over many intervals (scales) is compared with the largest change the pupil can manage in that interval (rate times its length); the signal has to grow faster on both sides, by more than z times the noise of a difference. Each side ends where the excess is largest.

  • "velocity": the velocity (window winsize) of the fall and of the rise has to reach rate for at least min_duration; each partial blink extends from them with hysteresis down to rate_min. Without a dropout as evidence, the threshold is much stricter than for the flanks of blinks.

Dips with missing samples, or whose flanks run up to missing or masked samples, are not partial blinks (see blinks_detect()). A partial blink is V-shaped (the lid goes down and straight back up): a dip with a bottom longer than max_bottom is not one (e.g., a step down and a later step up from two saccades).

The partial blinks are stored as the "partial_blink" layer of the pupil (it masks them, like any layer; read them with get_layer_intervals("partial_blink"), remove them with clear_layer("partial_blink")). They replace the ones detected before, and they are kept apart from the blinks (get_blinks(), blink statistics); blinks_interpolate() interpolates them with partial=True. Eyes whose pupil has interpolated samples are skipped with a warning.

Parameters:
  • eyes (str or list) – eyes to process; if empty, all eyes with pupil data

  • rate (float, str or None) – with method="excess", the largest plausible rate of the pupil (default "0.1%/ms"); with method="velocity", how fast the fall and the rise have to be (default "25sd"). "<k>sd": k times the robust standard deviation of the velocity of the recording; "<p>%/ms": p percent of the local pupil size per millisecond; a number: units of the data per millisecond (see blinks_detect())

  • method (str) – test of the fall and the rise: "excess" (default) or "velocity" (see above)

  • z (float) – excess test: threshold of the excess change, in standard deviations of the noise of a difference of two samples (default 4)

  • scales (tuple) – excess test: shortest and longest interval of the test (in ms, or with units; default 10 and 300 ms); the longest also bounds the length of each side of a partial blink

  • smooth (float) – excess test: width of the running median of the signal and of the start value at the tip (in ms, or with units; default 5 ms)

  • rate_min (float or str) – velocity: rate down to which a partial blink extends (hysteresis; default "2sd", same forms; "0sd": up to where the signal turns)

  • min_duration (float) – velocity: how long (in ms, or with units) the fall and the rise have to be beyond rate (default 10 ms)

  • max_duration (float) – maximum duration of a partial blink (default 1 s); None: no limit

  • max_bottom (float) – maximum duration of the bottom of a partial blink (default 20 ms), measured on the signal: the stretch within 20% of the depth of the dip above its minimum (the depth from the lower of its two edges), less the 20% of the width of the dip that a V of straight lines has there (0 for a sharp V, about the length of the flat part for a dip with a flat bottom); None: no limit

  • winsize (float) – velocity: size of the Savitzky-Golay window of the velocity (in ms, or with units; default 45 ms; also for rates in "sd")

  • level (dict, optional) – settings of the local pupil size that rates in "%/ms" refer to (scales, min_coverage, max_dev; see local_level() and plot_local_level()); default: its defaults

  • policy (str or MaskPolicy) – masked samples under this policy (default "strict", so also the blinks) are not part of a partial blink; see blinks_detect()

  • inplace (bool or None) – if True, make change in-place and return the object; if False, make and return copy before making changes; if None, use the object-level setting

Return type:

EyeData

Returns:

the object with the partial blinks (self or a copy, depending on inplace)

Examples

>>> d = d.pupil.blinks_detect().pupil.blinks_detect_partial()
>>> d.get_layer_intervals("partial_blink", variables="pupil")
>>> d = d.pupil.blinks_interpolate(partial=True)

Extend the blinks to cover slow openings of the lid, with a margin tuned for each part of the recording.

After some blinks the lid opens slowly: the first few hundred ms of valid samples after the dropout are too low and climb back to the pupil. These samples change at a pace the pupil could manage, so the blink detection (blinks_detect()) does not find them, and the interpolation follows them. How slowly the lid opens differs between people and changes over a session, so a fixed margin does not fit.

This method extends the end of each detected blink by a margin tuned on transplanted blinks (see tune_post_margins()): the artifacts of the blinks around each point of the recording (weighted with a Gaussian kernel over time) are pooled into their median, which keeps the slow opening (the same after all of them) and removes the fluctuations of the pupil after each single blink. Only the part where the pooled artifact lowers the signal counts. It is put into clean stretches of the recording and interpolated (Kalman smoother, see blinks_interpolate()) with each margin from 0 to max_margin (in steps of grid_step), and the shortest margin that is about as good as the best one (within se standard errors) is used. Between these points, the margins of the blinks are interpolated.

The extended blinks replace the "blink" layer of the pupil; blinks that overlap after extending are merged. Run it right after blinks_detect() (and before masks that cover the samples after the blinks, e.g. mask_transients()), then interpolate the stored blinks as they are (e.g., blinks_interpolate(method="kalman", margin=None)). Running it again extends the blinks only a little more (their ends are then after the slow openings). Eyes whose pupil has interpolated samples are skipped with a warning.

Parameters:
  • eyes (str or list) – eyes to process; if empty, all eyes with pupil data

  • max_margin (float) – longest margin after a blink (in ms, or with units; default 500 ms). Longer margins could mask the response of the pupil to the blink.

  • grid_step (float) – step of the margins that are tried (in ms, or with units; default 25 ms)

  • kernel (float, str, Quantity or None) – standard deviation of the Gaussian weights of the blinks over time (in ms, or with units; default "3min"); narrower follows faster changes, but with fewer blinks. None: one margin for the whole recording.

  • window (tuple, optional) – time (before, after) the blinks that is transplanted (in ms, or with units); after the blink, it must be longer than max_margin. Default: (200, max_margin + 300).

  • sites (int) – number of places in clean signal the pooled artifact is put into (more: more reliable, but slower)

  • pad (float) – clean signal on each side of a transplanted window that counts for the error (in ms, or with units)

  • clearance (float) – minimum distance of the transplanted blinks from blinks and missing samples of the recording (in ms, or with units)

  • kalman_window (float) – signal before and after each interpolated stretch that the Kalman smoother uses (in ms, or with units)

  • mode (str) – "multiplicative" (default): the artifacts are ratios to the baseline (the lid covers a share of the pupil), for raw data (area or diameter), which must be positive; "additive": differences, e.g. for log-transformed data

  • max_core (float) – blinks longer than this (in ms, or with units) are not used for the artifacts (they still get a margin)

  • se (float) – number of standard errors a margin may be worse than the best one; 0 uses the best one

  • min_eff (float) – a warning is given where fewer blinks (effective number, with the weights of the kernel) are around

  • seed (int, optional) – seed of the random numbers (places of the transplanted blinks)

  • inplace (bool or None) – if True, make change in-place and return the object if False, make and return copy before making changes if None, use the object-level setting

Return type:

EyeData

Returns:

the object with the extended blinks

Examples

>>> d = d.pupil.blinks_detect().pupil.blinks_extend_adaptive()
>>> d = d.pupil.blinks_interpolate(method="kalman", margin=None)

Interpolating blinks in the pupillary signal.

The blinks to interpolate are taken from the blinks stored in the object, so blinks have to be detected first (e.g., using blinks_detect()). The interpolated samples get the "interpolated" layer (on the variable they are stored in, see store_as): they are used under the default mask policy and masked under the "strict" one (see mask()); the interpolated blinks can be retrieved with get_interpolated().

Methods:

  • "mahot" (default): the method by Mahot (2013). The on- and offsets of each blink are refined using the velocity profile, and the blink is replaced by a cubic curve through four anchor points around it. Blinks that are so close that the anchor points of one fall into the other are merged and interpolated together. Blinks with an anchor point that is masked for another reason (e.g., by mask_intervals(), an excluded period or interpolated before) are skipped with a warning. This procedure relies heavily on eye-balling (reconstructing visually convincing signal), so it can help to inspect the result visually (e.g., using d.plot.plot_blinks()) to set good parameter values for winsize, rate_onset, rate_offset and margin (see paper linked below).

  • "kalman": the blink samples are replaced by their expected value given the signal around them (Kalman smoother). Around each blink, blinkwindow before and after it is used, after removing a linear trend; the signal is modelled as a smooth Gauss-Markov process (a fast and a slow Matérn process, smoothness 3/2) plus measurement noise. The time scales of the components are fixed and the noise level is estimated from the data (with optimize=True, all parameters are fitted, which is much slower). Each blink is replaced from its core (its first to its last missing sample; the whole blink if it has none) with margin before and after it, which should cover the transients around the blink (see blinks_optimize_parameters()); with margin=None, exactly the stored blinks are replaced.

Each method has its own parameters (see below), passed as keyword arguments. Parameters of another method are ignored with a warning, so that the method can be switched quickly.

Parameters:
  • eyes (str | list) – str or list of eyes to process; if empty, all available eyes are processed

  • store_as (str) – how to store the interpolated data; either “pupil” (default) which replaces the original pupil data or a string that will be used as the new variable name in the data (e.g., “pupilinterp”)

  • method (str) – method to use: "mahot" (default) or "kalman"

  • blinkwindow (float) – how much time before and after each blink to use (in ms, or with units); for "mahot", the window in which the on- and offsets are searched; for "kalman", the signal the blink is predicted from

  • partial (bool) – also interpolate the partial blinks (see blinks_detect_partial(); default False)

  • inplace (bool or None) – if True, make change in-place and return the object if False, make and return copy before making changes if None, use the object-level setting

  • **kwargs – parameters of the method (see below)

Return type:

EyeData

Returns:

the object with the interpolated pupil data

Other Parameters:
  • winsize (float, str or Quantity) – "mahot": size of the Savitzky-Golay window (in ms, or with units; rounded to the nearest odd number of samples, at least 5); default 30

  • rate_onset (float or str) – "mahot": how fast the pupil has to fall to find the start of the closing around each blink; default "2sd"

    • "<k>sd": k robust standard deviations of the velocity of the recording (see blinks_detect()), which works in any units

    • "<p>%/ms": p percent of the local pupil size per millisecond

    • a number: rate in pupil units per millisecond (e.g., 5.0)

  • rate_offset (float or str) – "mahot": how fast the pupil has to rise to find the end of the reopening; default "2sd" (same forms)

  • level (dict, optional) – "mahot": settings of the local pupil size that rates in "%/ms" refer to (scales, min_coverage, max_dev; see local_level()); default: its defaults

  • margin (Tuple[float,float] or Quantity) – "mahot": margin that is subtracted/added to onset and offset (in ms, or with units, e.g. (10, 30) * u.ms); default (10, 30). "kalman": time before and after the core of each blink that is replaced too (the transients); default (50, 150); None: exactly the stored blinks

  • interp_type (str) – "mahot": type of interpolation accepted by scipy.interpolate.interp1d(); default "cubic". A blink whose anchor points are close on one side (because of a neighbouring blink) gets a monotone curve (scipy.interpolate.PchipInterpolator) instead of the cubic, which would overshoot.

  • max_duration (float, str, Quantity or None) – "mahot": maximum duration (in ms, or with units) of a stretch that is interpolated; blinks that are longer (with their margins, or after merging with neighbouring blinks whose anchor points overlap) are skipped with a warning; default 2000, None: no limit

  • optimize (bool) – "kalman": fit all parameters of the model to the data instead of using the defaults; much slower, and usually changes the result little; default False

Raises:
  • ValueError – if method is unknown

  • TypeError – if a keyword argument is not a parameter of any method

References

Mahot, 2013: https://figshare.com/articles/A_simple_way_to_reconstruct_pupil_size_during_eye_blinks/688001.

Merge blinks that are close together.

The merged blinks replace the "blink" layer of the pupil (see set_blinks()); read them with get_blinks().

Parameters:
  • eyes (list) – eye(s) to process; if empty, all eyes with pupil data

  • distance (float) – Merge blinks closer than this distance, e.g. 100 * u.ms or "0.1 sec"; plain numbers are in units given by units. Default 100.

  • units (str) – Units for distance if it is a plain number. Can be “ms”, “sec”, “min”, or “h”. Default “ms”.

  • inplace (bool | None) – if True, make change in-place and return the object; if False, make and return copy before making changes; if None, use the object-level setting (specified in the constructor).

Return type:

EyeData

Returns:

the object with the merged blinks (self or a copy, depending on inplace)

Tune the parameters of blinks_interpolate() for this recording.

The parameters of the "mahot" method (winsize, rate_onset, rate_offset, margin and blinkwindow) decide how much of the signal around the missing samples of a blink is replaced. Instead of setting them by eye, they are tuned on transplanted blinks: the obvious blinks of the recording are cut out with a window around their missing samples, a slow baseline is removed, and what remains (the artifact) is added to clean stretches of the recording, where the signal without the blink is known (see transplant_blinks()). The parameters that reconstruct it best are searched (see tune_blinks_mahot()). The error is the difference between the reconstructed and the clean signal in the window around the transplanted blinks (with pad): the root mean squared error of each blink, averaged over the blinks.

The blinks have to be detected first (blinks_detect()), so the workflow is blinks_detect(), this method, and blinks_interpolate() with the tuned parameters. Of the detected blinks, only the obvious ones are transplanted: their missing samples (from the first to the last, as in the interpolation) last at most max_core, have no other blink or missing samples in the window around them, and the drop of the pupil before and the rise after them are larger than the quantile of the changes over the same distance in the clean signal. Other blinks (e.g., loss of the pupil by the eye tracker without transients, eye movements that make the pupil drop and rise in steps, blinks without missing samples) are not used, but no blinks are put on them.

Not all blinks are needed: the search runs on n_tune random blinks, each transplanted repeats times. All sets of blinks are spread over the recording (one random blink from each of equal parts), as the blinks can change over time. As the result depends on which blinks these are, it runs n_starts times, on different blinks. Of the other blinks, n_refine are used to choose the best result (or the starting parameters) and refine it (one more round of the search on them and its n_tune blinks), and n_test only to test it; the rest are not used. If there are fewer blinks, there are fewer searches, and the others are split in the same proportion. The tuned parameters are only returned if they are better for the test blinks than the starting parameters (otherwise those are returned, with a warning). With at most n_tune blinks, there is no refinement, and up to half of them (at most n_test) are used for testing.

The blinks of all eyes are used together; call the method for one eye at a time to get parameters for each. The object is not changed. The result depends on the random choice of the blinks and their places (see seed).

Parameters:
  • eyes (str or list) – eyes to use; if empty, all eyes with pupil data

  • method (str) – method of blinks_interpolate() to tune: "mahot" (default) or "kalman". For "kalman", only the margin before and after the core of the blinks is tuned (on a grid, see tune_blinks_kalman(); start and bounds take "margin" and "margin_before"/ "margin_after", fixed the "blinkwindow" it uses), and the arguments for the searches (n_starts, …) only decide which blinks are used.

  • window (float, str, Quantity or tuple) – time (before, after) the missing samples of a blink (in ms, or with units) that is transplanted with it. It should include the whole artifact, but not much more: everything in it that differs from a straight line (e.g., slower changes of the pupil) is transplanted as part of the artifact. It also limits the search ranges (see bounds).

  • n_tune (int) – number of different blinks for the search

  • repeats (int) – number of times each of the n_tune blinks is transplanted (at most as many as fit)

  • n_starts (int) – number of searches, each on n_tune other blinks

  • n_refine (int) – number of further blinks for refining the result (0: no refinement)

  • n_test (int) – number of further blinks that are only used for testing the tuned parameters (0: no test)

  • start (dict, optional) – starting parameters, as the arguments of blinks_interpolate() (e.g., dict(rate_onset=10)); default: its defaults. max_duration is not tuned, but used as in blinks_interpolate() (stretches that are longer are skipped there and count with their whole error here); level is not tuned either, but used for rates in "%/ms" in start and fixed.

  • bounds (dict, optional) – search range (lower, upper) for "winsize", "rate_onset", "rate_offset", "margin_before", "margin_after" or "blinkwindow" (units as in blinks_interpolate()); default: from the data (see tune_blinks_mahot())

  • fixed (dict, optional) – parameters that are not tuned, with their values, as the arguments of blinks_interpolate() (e.g., dict(blinkwindow=500))

  • quantile (float) – quantile of the changes in the clean signal that the drop and rise around an obvious blink must exceed (higher: fewer, more obvious blinks)

  • max_core (float) – maximum duration (in ms, or with units) of the missing samples of an obvious blink (longer ones are, e.g., loss of the pupil); None: no limit

  • pad (float) – clean signal (in ms, or with units) that is kept free on each side of the window of a transplanted blink; it counts for the error

  • clearance (float) – minimum distance (in ms, or with units) of the transplanted blinks (with pad) from the blinks and missing samples of the recording, so that their interpolation does not depend on neighbouring blinks

  • mode (str) – "additive" (default): the difference to the baseline is transplanted; "multiplicative": the ratio to the baseline

  • shrink (bool) – remove the fluctuations of the signal around the blinks from their artifacts (default; see shrink_blink_artifacts())

  • seed (int, optional) – seed of the random numbers (choice of the blinks, their places, search)

  • **kwargs – further arguments of tune_blinks_mahot() (n_init, n_grid, sweeps)

Return type:

BlinkTuneResult

Returns:

result.params are the parameters to use, as arguments of blinks_interpolate() (including the method, e.g. d.pupil.blinks_interpolate(**result.params)); the result also has the errors of the tuned and the starting parameters and all evaluated parameters (see BlinkTuneResult)

Raises:

ValueError – if there are no detected blinks, none of them is obvious, no blinks can be transplanted, or the pupil has interpolated samples (tune before interpolating)

Examples

>>> import pypillometry as pp
>>> d = pp.get_example_data("rlmw_002_short").pupil.blinks_detect()
>>> res = d.pupil.blinks_optimize_parameters(seed=1)
>>> d = d.pupil.blinks_interpolate(**res.params)
correct_foreshortening(eyes=[], midpoint=None, store_as='pupil', inplace=None)[source]#

Correct pupil data using a simple algorithm to correct for foreshortening effects.

Correct the pupil data for foreshortening effects caused by saccades/eye movements. This method is based on a simple algorithm that assumes the pupil appears perfectly circular when fixating midpoint: for each sample, the distance \(\Delta\) (in mm) of the gaze position from midpoint is computed and the pupil signal is multiplied by the correction factor \(\sqrt{1+\Delta^2/d^2}\), where \(d\) is the eye-to-screen distance from the experimental setup. For a more complete model that also estimates the camera position, see fit_foreshortening().

Relevant publication (not the description of the algorithm used here): https://link.springer.com/article/10.3758/s13428-015-0588-x

  • [ ] TODO: when using interpolated pupil data, x/y data may still be missing. Make sure that the pupil data is not touched where x/y is missing

Parameters:
  • eyes (list) – Which eyes to correct. If empty, correct all available eyes that have pupil and gaze (x, y) data.

  • midpoint (tuple or None) – The center of the screen (x,y) in pixels where it is assumed that the pupil is completely circular. If None, the midpoint is taken to be the center of the screen as registered in the experimental_setup.

  • store_as (str) – name of the variable in which to store the corrected pupil data (as data[eye, store_as]); the default “pupil” replaces the original pupil data

  • inplace (bool or None) – Whether to modify the object in place or return a new object. true: modify in place false: return a new object None: use the object’s default setting (initialized in __init__)

Return type:

EyeData

Returns:

An EyeData object with the corrected pupil

Raises:

ValueError – if no experimental setup is set (see set_experimental_setup())

estimate_baseline(eyes=[], variable='pupil', method='envelope_iter_bspline_2', policy='default', inplace=None, **kwargs)[source]#

Apply one of the baseline-estimation methods.

The baseline is estimated from the usable samples under the mask policy (by default, interpolated samples are used, see mask()). The unusable samples (masked or NaN, e.g., blinks that were not interpolated or the excluded periods) are bridged linearly between their neighbours. Interpolate blinks first (see blinks_interpolate()) to use a better reconstruction than a straight line.

Parameters:
  • eyes (list or str) – str or list of eyes to process; if empty, all available eyes are processed

  • variable (str) – default is to use the “pupil” but it could be used to process, e.g., interpolated pupil data stored in a different variables, e.g., “pupilinterp”

  • method (str) –

  • policy (str, MaskPolicy or list of str) – mask policy that decides which samples are usable (see mask()); default "default"

  • inplace (bool or None) – if True, make change in-place and return the object if False, make and return copy before making changes if None, use the object-level setting

  • **kwargs (dict) – named arguments passed to the low-level function in pypillometry.signal.baseline.

Return type:

EyeData

Returns:

object with baseline estimated (stored in data[eye, "baseline"])

Raises:

ValueError – if method is unknown or no sample is usable

References

Mittner, M., & Groot, J. M. (2025). A novel method for modeling tonic and phasic pupil dynamics in humans. Behavior Research Methods, 57(9), 233. https://doi.org/10.3758/s13428-025-02755-7

estimate_response(eyes=[], npar='free', tmax='free', verbose=50, bounds={'npar': (1, 20), 'tmax': (100, 2000)}, min_valid=0.5, policy='default', inplace=None)[source]#

Estimate pupil-response based on event-onsets, see pupil_response().

The model has one response per event in d.events: all events are used, whatever their label. To use only some of them, set the events first, e.g. d.set_events(d.events.filter("stim")) on a copy of the data.

If a baseline has been estimated (see estimate_baseline()), it is subtracted from the pupil signal before estimating the response; otherwise, a baseline of zero is used.

Only the usable samples under the mask policy are used for the fit: by default, NaN, masked samples (e.g., blinks applied as mask) and the excluded periods (see exclude_intervals(), e.g., breaks) are not used, interpolated samples (e.g., blinks) are. For each event, the share of its response that falls on usable samples (valid) and the share that falls on real data (observed: usable under the "strict" policy, i.e., not interpolated either) are stored with the parameters (weighted by the response, see pupil_response_coverage()). Events with a valid share below min_valid are left out of the fit; their coefficient is NaN.

Parameters:
  • eyes (list or str) – str or list of eyes to process; if empty, all available eyes are processed

  • npar (str | float) – npar-parameter for the canonical response-function or “free”; in case of “free”, the function optimizes for this parameter

  • tmax (str | float) – tmax-parameter for the canonical response-function or “free”; in case of “free”, the function optimizes for this parameter

  • verbose (int) – verbosity level, passed on to pupil_response()

  • bounds (dict) – in case that one or both parameters are estimated, give the lower and upper bounds for the parameters

  • min_valid (float) – events whose share valid is below this are left out of the fit (coefficient NaN), as their amplitude cannot be estimated reliably; default 0.5; 0 uses all events

  • policy (str, MaskPolicy or list of str) – mask policy that decides which samples are usable (see mask()); default "default"

  • inplace (bool or None) – if True, make change in-place and return the object if False, make and return copy before making changes if None, use the object-level setting

Return type:

EyeData

Returns:

the object with the estimated response

Raises:

ValueError – if the object has no events

Notes

The predicted response is stored in data[eye, "response"]; the estimated parameters (npar, tmax, the coefficients coef and the bounds) are stored in params["response"]["<eye>_pupil"] (e.g., params["response"]["left_pupil"]), together with the shares valid and observed (0-1, one per event; NaN for events without response in the data, e.g., at the very end).

References

Mittner, M., & Groot, J. M. (2025). A novel method for modeling tonic and phasic pupil dynamics in humans. Behavior Research Methods, 57(9), 233. https://doi.org/10.3758/s13428-025-02755-7

fit_foreshortening(eye, r=None, d=None, intervals=None, target_fs=50.0, lowpass_freq=4.0, lambda_smooth=1.0, knots_per_second=1.0, initial_theta=None, initial_phi=None, verbose=True)[source]#

Fit foreshortening correction model to estimate camera geometry and true pupil size.

This method implements Stage 1 of the foreshortening correction algorithm, which jointly estimates the camera position (theta, phi) and the temporal dynamics of true pupil size A0(t) using B-splines. The data is automatically preprocessed (filtered and downsampled) before fitting.

Parameters:
  • eye (str) – Which eye to fit (‘left’ or ‘right’)

  • r (Union[float, str, None]) –

    Eye-to-camera distance. If not provided, uses the r from experimental_setup.

    • Plain number: assumed to be mm (with warning)

    • String: e.g., “600 mm”, “60 cm”

    • Quantity: e.g., 600 * u.mm

  • d (Union[float, str, None]) –

    Eye-to-screen distance. If not provided, uses the d from experimental_setup.

    • Plain number: assumed to be mm (with warning)

    • String: e.g., “700 mm”, “70 cm”

    • Quantity: e.g., 700 * u.mm

  • intervals (Optional[Intervals]) – Time intervals to use for fitting. If None, uses all available data. Useful for fitting only on calibration periods. Intervals in any time units or in sample indices (units="samples") are accepted; a plain list of (start, end) tuples is taken as ms. Intervals are end-exclusive.

  • target_fs (float) – Target sampling rate in Hz after downsampling for efficiency. Pupil dynamics are typically well-preserved at 50 Hz.

  • lowpass_freq (float) – Lowpass filter cutoff frequency in Hz. Removes high-frequency noise before downsampling. Should be below target_fs/2 (Nyquist).

  • lambda_smooth (float) – Smoothness regularization weight. Higher values produce smoother A0(t) estimates. Tune via cross-validation if needed.

  • knots_per_second (float) – Number of B-spline knots per second. Controls temporal resolution of A0(t) model. Typical values: 0.5-2.0.

  • initial_theta (Union[float, str, None]) –

    Initial guess for camera polar angle. If None, uses pi/2 (horizontal) as starting point.

    • Plain number: assumed to be radians (with warning)

    • String: e.g., “20 degrees”, “0.349 radians”

    • Quantity: e.g., 20 * u.deg

  • initial_phi (Union[float, str, None]) –

    Initial guess for camera azimuthal angle. If None, uses 0 (camera on x-axis) as starting point.

    • Plain number: assumed to be radians (with warning)

    • String: e.g., “-90 degrees”, “-1.57 radians”

    • Quantity: e.g., -90 * u.deg

  • verbose (bool) – Print optimization progress and fit statistics.

Return type:

ForeshorteningCalibration

Returns:

calibration (ForeshorteningCalibration) – Fitted calibration object containing camera geometry (theta, phi), spline coefficients for A0(t), and fit quality metrics.

Raises:

ValueError – If specified eye doesn’t exist or lacks gaze/pupil data, if the experimental setup is not set or lacks required information, if lowpass_freq is not below the Nyquist frequency or if fewer than 100 valid samples are available.

See also

ForeshorteningCalibration

Container for fitted parameters

correct_foreshortening

Simple foreshortening correction method

Notes

The model is:

A_measured(x,y,t) = A0(t) * cos(alpha(x,y; theta, phi))

where:

  • A0(t) = sum_k a_k * B_k(t) is modeled with B-splines

  • cos(alpha) is the foreshortening factor depending on viewing angle

  • theta, phi parameterize camera position in spherical coordinates

The optimization minimizes:

sum_i (A_i - A_pred_i)^2 + lambda_smooth * sum_k (a_{k+1} - a_k)^2

Examples

>>> import pypillometry as pp
>>> data = pp.EyeData.from_eyelink('recording.edf')
>>> 
>>> # Set experimental setup
>>> data.set_experimental_setup(
...     screen_resolution=(1920, 1080),
...     physical_screen_size=("52 cm", "29 cm"),
...     eye_to_screen_center="65 cm",
...     camera_offset=("0 cm", "-30 cm", "0 cm"),
... )
>>> 
>>> # Fit on calibration period (first 2 minutes)
>>> cal_intervals = pp.Intervals([(0, 120000)], units="ms")
>>> calib = data.pupil.fit_foreshortening(
...     eye='left',
...     intervals=cal_intervals
... )
>>> 
>>> # Or provide r and d explicitly
>>> calib = data.pupil.fit_foreshortening(
...     eye='left',
...     r="60 cm",
...     d="70 cm",
...     intervals=cal_intervals
... )
>>> 
>>> # Inspect fit quality
>>> print(calib)
>>> print(f"R² = {calib.fit_metrics['r2']:.3f}")
>>> 
>>> # Compute correction for all data
>>> correction_factor = calib.get_correction_factor(
...     data['left', 'x'], 
...     data['left', 'y']
... )
>>> corrected_pupil = data['left', 'pupil'] * correction_factor
lowpass_filter(cutoff, order=2, eyes=[], policy='default', inplace=None)[source]#

Lowpass-filter pupil signal using a Butterworth-filter.

Only the usable samples under the mask policy are filtered (by default, interpolated samples are used; see mask()). The unusable samples (masked or NaN) are bridged linearly for the filter (see lowpass_filter_iterative()), so their stored values (e.g., zeros in blinks) do not enter the filter; they keep their values. The filtered samples replace the pupil data; the mask layers are kept.

Parameters:
  • cutoff (float) – lowpass-filter cutoff frequency in Hz

  • order (int) – filter order

  • eyes (list) – list of eyes to filter; if empty, all available eyes are filtered

  • policy (str, MaskPolicy or list of str) – mask policy that decides which samples are usable (see mask()); default "default"

  • inplace (bool or None) – if True, make change in-place and return the object if False, make and return copy before making changes if None, use the object-level setting

Return type:

EyeData

Returns:

the object with the filtered pupil data

mask_comb(eyes=[], width=15, depth='3%', margin=2, policy='default', inplace=None)[source]#

Mask comb artifacts: short drops of the pupil that come back up within a few milliseconds, often many in a row, so that the signal looks like a comb.

The upper envelope of the pupil is its grey closing over width (a running maximum followed by a running minimum), which fills in the teeth of the comb; samples more than depth below it are masked (see detect_comb()), with margin before and after each tooth.

The teeth are stored as the "comb" layer of the pupil (read them with get_layer_intervals("comb"), remove them with clear_layer("comb")); they replace the ones masked before. Eyes whose pupil has interpolated samples are skipped with a warning.

Parameters:
  • eyes (str or list) – eyes to process; if empty, all eyes with pupil data

  • width (float) – size of the closing (in ms, or with units; default 15 ms); teeth narrower than this are found

  • depth (float or str) – how far below the envelope a sample has to lie: "<p>%" of the median pupil size (default "3%"; of the unscaled pupil if the data were scaled with scale()), or a number in units of the data

  • margin (float, str, Quantity or tuple) – time masked before and after each tooth (plain numbers in ms; a tuple (before, after) for different margins); default 2 ms

  • policy (str or MaskPolicy) – samples unusable under this policy (default "default"; the "comb" layer itself does not count) are not used, neither for the envelope nor for the median pupil size

  • inplace (bool or None) – if True, make change in-place and return the object; if False, make and return copy before making changes; if None, use the object-level setting

Return type:

EyeData

Returns:

the object with the teeth masked (self or a copy, depending on inplace)

Examples

>>> import pypillometry as pp
>>> d = pp.get_example_data("rlmw_002_short")
>>> d = d.pupil.mask_comb()
>>> iv = d.get_layer_intervals("comb", "left", "pupil")["left_pupil"]
mask_transients(eyes=[], rate=None, free_rate='0.6%/ms', method='excess', z=4, scales=(10, 300), smooth=5, rate_min='2sd', max_gap=5, winsize=10, max_flank=1000, level=None, policy='strict', inplace=None)[source]#

Mask transients: fast changes of the pupil that are artifacts.

Two kinds:

  • the flanks of all dropouts (runs of missing samples, blinks or not, and of samples masked under policy): the change next to a dropout that is faster than the pupil can manage (in either direction: an artifact can also make the signal jump up)

  • free transients: changes faster than free_rate anywhere else (e.g., partial blinks, jumps, spikes); without a dropout as evidence, free_rate is stricter

The rates are speeds of the pupil, by default in percent of the pupil size per millisecond (the pupil changes by at most about 0.1 %/ms in diameter; in area, the percentages are about twice those in diameter).

The flanks of dropouts are found with one of two tests (method):

  • "excess" (default; see excess_flank()): the change from the edge of the dropout over many intervals (scales, 10 to 300 ms) is compared with the largest change the pupil can manage in that interval (rate times its length). An artifact that is too slow to stand out in a short window (e.g., a slow reopening of the lid) clearly exceeds it at some scale. A flank counts if the excess is larger than z times the noise of a difference; it ends where the excess is largest, where the change has slowed to a pace the pupil could manage.

  • "velocity" (see detect_transients()): the velocity in a short window (winsize, 10 ms), so that steps stay sharp and in place, also in narrow artifacts. A flank counts if it is faster than rate for at least 2 samples and changes the signal by more than 5 times the noise; it extends with hysteresis down to rate_min.

Free transients are always found from the velocity, with hysteresis down to rate_min (it can go on across 10 ms of noise below it). The noise is the standard deviation of a sample, from the differences of successive samples.

It does not need a detection of blinks: it is meant for analyses that reconstruct all masked samples (e.g., with a Kalman smoother), where it does not matter whether a dropout was a blink, only which samples next to it are artifacts.

The transients are stored as the "transient" layer of the pupil (it masks them; read them with get_layer_intervals("transient"), remove them with clear_layer("transient")); they replace the ones masked before. Eyes whose pupil has interpolated samples are skipped with a warning.

Parameters:
  • eyes (str or list) – eyes to process; if empty, all eyes with pupil data

  • rate (float, str or None) – the rate of the flanks of dropouts: with method="excess", the largest plausible rate of the pupil (default "0.1%/ms"); with method="velocity", how fast a flank has to be (default "0.3%/ms"). "<p>%/ms": p percent of the local pupil size per millisecond (of the unscaled pupil if the data were scaled with scale()); "<k>sd": k times the robust standard deviation of the velocity of the recording; a number: units of the data per millisecond

  • free_rate (float, str or None) – how fast a free transient has to be (default "0.6%/ms", same forms); None: only the flanks of dropouts

  • method (str) – test of the flanks of dropouts: "excess" (default) or "velocity" (see above)

  • z (float) – excess test: threshold of the excess change, in standard deviations of the noise of a difference of two samples (default 4)

  • scales (tuple) – excess test: shortest and longest interval of the test (in ms, or with units; default 10 and 300 ms); the longest also bounds the length of a flank

  • smooth (float) – excess test: width of the running median of the signal and of the start value at the edge (in ms, or with units; default 5 ms)

  • rate_min (float or str) – velocity (the flanks with method="velocity", and the free transients): rate down to which a transient extends (default "2sd", same forms as rate; "0sd": up to where the signal turns, which can include slow trends of the pupil)

  • max_gap (float) – a transient goes on across missing or masked samples up to this long (in ms, or with units; default 5 ms), e.g. a short dropout during the reopening or a sample removed by another criterion

  • winsize (float) – velocity: size of the Savitzky-Golay window of the velocity (in ms, or with units; default 10 ms)

  • max_flank (float) – velocity: maximum length of one side of a transient (in ms, default 1 s; a safety bound)

  • level (dict, optional) – settings of the local pupil size that rates in "%/ms" refer to (scales, min_coverage, max_dev; see local_level() and plot_local_level()); default: its defaults

  • policy (str or MaskPolicy) – samples masked under this policy (default "strict"; the "transient" layer itself does not count) are not part of a transient, and a transient stops at them (unless they are shorter than max_gap); they are dropouts like missing samples, so the fast change next to them is a transient; see blinks_detect()

  • inplace (bool or None) – if True, make change in-place and return the object; if False, make and return copy before making changes; if None, use the object-level setting

Return type:

EyeData

Returns:

the object with the transients masked (self or a copy, depending on inplace)

Examples

>>> import pypillometry as pp
>>> d = pp.get_example_data("rlmw_002_short")
>>> d = d.pupil.mask_transients()
>>> iv = d.get_layer_intervals("transient", "left", "pupil")["left_pupil"]
merge_eyes(method='local_offset', lowpass_cutoff=0.2, max_iter=10, keep_eyes=True, policy='default', name='mean', inplace=None)[source]#

Merge pupil data from both eyes into a new eye (default "mean").

This method combines left and right pupil signals, handling missing data (masked values) intelligently. Where both eyes are valid, the signals are averaged to reduce noise. Where only one eye is valid, that eye’s data is used (with offset correction if applicable). Valid samples are the usable samples under the mask policy (see mask()), where recorded samples come first: an interpolated sample of one eye is used only if the other eye has no recorded sample there. The merged pupil gets the layers that are set in all eyes that went into a sample (e.g., "interpolated" where both were interpolated, "blink" where both eyes are masked by a blink); masked samples without such a common layer get the "user" layer.

Parameters:
  • method (str) –

    Method for merging the two eyes. Options:

    • ”local_offset” (default): Compute a slowly-varying offset between eyes using lowpass filtering. This handles drift over the session. The right eye is shifted to match the left eye’s level before merging.

    • ”offset”: Use a single global offset (mean difference) computed over the entire signal where both eyes are valid.

    • ”both_available”: Only use data where both eyes are valid (take mean). Timepoints where only one eye is valid remain masked.

    # TODO: Implement “signal_quality” method that weights eyes by their # local signal quality (SNR), giving more weight to the cleaner eye.

  • lowpass_cutoff (float) – Cutoff frequency (Hz) for the lowpass filter used in “local_offset” method. Lower values produce a more stable offset that only tracks very slow drift. Default is 0.2 Hz (~5 second time constant).

  • max_iter (int) – Maximum iterations for iterative lowpass filtering in “local_offset” method. Default is 10.

  • keep_eyes (bool) – If True (default), keep the original left/right pupil data. If False, remove the original left/right pupil data after merging (gaze data are kept).

  • policy (str, MaskPolicy or list of str) – mask policy that decides which samples are valid (see mask()); default "default"

  • name (str) – name of the new eye (default "mean", as in merge_eyes()); the merged pupil is stored as "<name>_pupil"

  • inplace (bool | None) – If True, modify in-place. If False, return a copy. If None, use the object’s default setting.

Return type:

EyeData

Returns:

The object with merged pupil data stored as “mean_pupil”.

Raises:

ValueError – If only one eye is available (nothing to merge). If an unknown method is specified.

See also

merge_eyes

Generic merge method in EyeData (masks if all eyes invalid)

pypillometry.signal.pupil.pupil_eye_offset

Compute local offset between eyes

Notes

The merged signal is stored as “mean_pupil” (with the default name) and can be accessed via data[“mean”, “pupil”] or data[“mean_pupil”].

The mask for the merged signal reflects which timepoints have valid data: - For “local_offset” and “offset”: masked only where BOTH eyes are masked - For “both_available”: masked where EITHER eye is masked Masked samples still hold the merged stored values (e.g., interpolated blinks), computed as for valid samples (NaN only if both eyes are NaN).

The “local_offset” method is recommended for most use cases as it: 1. Uses all available data (doesn’t discard single-eye timepoints) 2. Handles session-long drift in the inter-ocular difference 3. Produces smooth transitions at boundaries between single/both-eye regions

Examples

>>> import pypillometry as pp
>>> d = pp.get_example_data("rlmw_002_short")
>>> # Default: local offset correction
>>> d1 = d.pupil.merge_eyes(inplace=False)
>>> merged = d1["mean", "pupil"]
>>> # Use global offset (simpler, assumes no drift)
>>> d2 = d.pupil.merge_eyes(method="offset", inplace=False)
>>> # Only use timepoints where both eyes are valid
>>> d3 = d.pupil.merge_eyes(method="both_available", inplace=False)
>>> # Remove the original pupil data after merging (gaze is kept)
>>> d4 = d.pupil.merge_eyes(keep_eyes=False, inplace=False)
>>> list(d4.data.keys())
['left_x', 'left_y', 'right_x', 'right_y', 'mean_pupil']
smooth_window(eyes=[], window='hanning', winsize=11, policy='default', inplace=None)[source]#

Apply smoothing of the signal using a moving window. See smooth_window().

Only the usable samples under the mask policy are smoothed; the unusable samples (masked or NaN) are bridged linearly for the smoothing and keep their stored values (as in lowpass_filter()). The mask layers are kept.

Parameters:
  • eyes (list) – list of eyes to smooth; if empty, all available eyes are smoothed

  • window (str) – (the type of window from ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’); flat window will produce a moving average smoothing.

  • winsize (float) – the length of the window in ms (or with units, e.g. "20 ms")

  • policy (str, MaskPolicy or list of str) – mask policy that decides which samples are usable (see mask()); default "default"

  • inplace (bool or None) – if True, make change in-place and return the object if False, make and return copy before making changes if None, use the object-level setting

Return type:

EyeData

Returns:

the object with the smoothed pupil data

spectrum(eyes=[], variable='pupil', window='200 s', overlap=0.5, max_missing=0.3, scale='original', policy='default')[source]#

Power spectrum of the pupil size (Welch’s method for data with gaps).

The signal is cut into overlapping windows within the periods that are not excluded (see exclude_intervals()). Windows with too many unusable samples are skipped; the gaps in the other windows are bridged linearly, and the periodograms of the windows are averaged (see spectrum()). Nothing has to be interpolated before, but blinks should be detected, so that they are treated as gaps.

Parameters:
  • eyes (str or list) – eyes to process; if empty, all eyes with the variable

  • variable (str) – variable to use (default "pupil")

  • window (float, str or Quantity) – length of the windows (plain numbers are ms; default 200 s); the lowest frequency is one cycle per window

  • overlap (float) – overlap of neighbouring windows as a fraction of their length (default 0.5)

  • max_missing (float) – windows with a larger fraction of unusable samples are skipped (default 0.3)

  • scale (str) – "original" (default): spectrum of the signal in its units; "log%": of \(100 \log(x / \mathrm{median})\), the change relative to the median in percent, which makes recordings with different pupil units comparable

  • policy (str, MaskPolicy or list of str) – mask policy that decides which samples are usable (see mask()); default "default"

Return type:

dict[str, Spectrum]

Returns:

Spectrum (frequencies in Hz, power spectral density in units squared per Hz) for each eye, with keys like "left_pupil"

Examples

>>> d = d.pupil.blinks_detect()
>>> sp = d.pupil.spectrum(window="100 s")["left_pupil"]
>>> sp.freqs, sp.power