Pupil Constriction Causes Activity in the Human Retina and Visual System.
Paper
Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Python · 624 lines · 23 KB · no license
- """Constriction-locked ERG analysis.
- Analyzes the relationship between pupil constriction and the electroretinogram
- (ERG) by locking the ERG signal to the moment of maximum pupil constriction
- velocity. A permutation test assesses statistical significance.
- """
- from pathlib import Path
- from matplotlib import pyplot as plt
- import seaborn as sns
- import time_series_test as tst
- from datamatrix import io, operations as ops, series as srs
- import numpy as np
- from scipy.signal import decimate
- from constants import (SAMPLING_FREQ, SAMPLE_DURATION_MS, T0_SAMPLE, SEARCH_WINDOW,
- SEARCH_SMOOTH_WINLEN, V_MAX_CONSTRICT_RANGE, SEARCH_MARGIN,
- PLOT_WINDOW, DOWNSAMPLE_FACTOR,
- HIGHPASS_FREQ_MIN, N_VELOCITY_BINS, FIG_SINGLE, FIG_DOUBLE,
- FIG_LARGE, EEG_CHANNELS, TOPOMAP_WINLEN,
- PLOT_TIME_MS, CONSTRICT_X0_S, STIMULUS_X0_S, N_EEG_CHANNELS,
- COLOR_REAL, COLOR_PERMUTED, COLOR_UPPER, COLOR_LOWER,
- LOCKING_EVENT, BRANCH, get_checkpoint_dir, get_output_dir)
- from helpers import (single_permutation, run_permutation_test,
- plot_effect_size_topomap)
- """"
- # Ensure output folders exist
- """
- for output_type in ['png', 'svg']:
- Path(get_output_dir(output_type)).mkdir(parents=True, exist_ok=True)
- Path(get_output_dir(f"{output_type}/topomaps")).mkdir(parents=True, exist_ok=True)
- Path(get_output_dir(f"{output_type}/channels")).mkdir(parents=True, exist_ok=True)
- """
- # Load data
- """
- dms = []
- checkpoint_dir = get_checkpoint_dir()
- for path in checkpoint_dir.glob('*.dm'):
- print(f'Loading {path}')
- dms.append(io.readbin(path))
- # Only keep EEG for datasets that have all 26 channels
- for dm in dms:
- print(dm.dataset.unique)
- if 'erp' in dm:
- if dm.erp.shape[1] != N_EEG_CHANNELS:
- print('removing incomplete EEG data')
- del dm.erp
- dm.has_eeg = 0
- else:
- print('has EEG data')
- dm.has_eeg = 1
- else:
- print('no EEG data')
- dm.has_eeg = 0
- dm = ops.stack(dms)
- del dms
- """
- # Determine point of maximum constriction velocity
- """
- for row in dm:
- d = np.diff(srs.smooth(
- row.pupil[SEARCH_WINDOW[0]:SEARCH_WINDOW[1]],
- winlen=SEARCH_SMOOTH_WINLEN))
- peak_idx = np.argmin(d)
- row.v_max_constrict = d[peak_idx]
- if LOCKING_EVENT == 'peak':
- lock_idx = peak_idx
- elif LOCKING_EVENT == 'start':
- # Scan backward from peak: find last non-negative derivative before
- # peak, i.e. the onset of constriction
- pre = np.where(d[:peak_idx] >= 0)[0]
- lock_idx = pre[-1] if len(pre) else 0
- elif LOCKING_EVENT == 'end':
- # Scan forward from peak: find first non-negative derivative after
- # peak, i.e. the end of constriction
- post = np.where(d[peak_idx:] >= 0)[0]
- lock_idx = peak_idx + post[0] if len(post) else len(d) - 1
- row.t_max_constrict = lock_idx + SEARCH_WINDOW[0]
- fig, (ax1, ax2) = plt.subplots(1, 2, figsize=FIG_DOUBLE)
- plt.sca(ax1)
- t_max_constrict_ms = (np.array(dm.t_max_constrict) - T0_SAMPLE) * SAMPLE_DURATION_MS
- sns.histplot(t_max_constrict_ms, bins=100)
- ax1.axvline((SEARCH_WINDOW[0] + SEARCH_MARGIN - T0_SAMPLE) * SAMPLE_DURATION_MS,
- color='black', linestyle='--', label='Filter bounds')
- ax1.axvline((SEARCH_WINDOW[1] - SEARCH_MARGIN - T0_SAMPLE) * SAMPLE_DURATION_MS,
- color='black', linestyle='--')
- ax1.legend(frameon=False)
- ax1.set_xlabel('Max. constriction time (ms)')
- ax1.set_ylabel('Count')
- plt.sca(ax2)
- sns.histplot(np.array(dm.v_max_constrict), bins=100, binrange=(-.1, 0))
- ax2.axvline(V_MAX_CONSTRICT_RANGE[0], color='black', linestyle='--',
- label='Filter bounds')
- ax2.axvline(V_MAX_CONSTRICT_RANGE[1], color='black', linestyle='--')
- ax2.set_xlabel('Max. constriction velocity (mm/sample)')
- ax2.set_ylabel('Count')
- ax2.legend(frameon=False)
- plt.tight_layout()
- plt.savefig(get_output_dir('png') / 'constriction-time-and-velocity.png')
- plt.savefig(get_output_dir('svg') / 'constriction-time-and-velocity.svg')
- plt.show()
- """
- # Filter data and descriptive statistics
- """
- print('=== Filtering ===')
- n_total = len(dm)
- t_min = SEARCH_WINDOW[0] + SEARCH_MARGIN
- t_max = SEARCH_WINDOW[1] - SEARCH_MARGIN
- v_min, v_max = V_MAX_CONSTRICT_RANGE
- print(f'Before filtering: {n_total} trials')
- _n = len(dm)
- dm = dm.t_max_constrict > t_min
- print(f'After t_max_constrict > {t_min}: {len(dm)} trials '
- f'(lost {_n - len(dm)})')
- _n = len(dm)
- dm = dm.t_max_constrict < t_max
- print(f'After t_max_constrict < {t_max}: {len(dm)} trials '
- f'(lost {_n - len(dm)})')
- _n = len(dm)
- dm = dm.v_max_constrict > v_min
- print(f'After v_max_constrict > {v_min}: {len(dm)} trials '
- f'(lost {_n - len(dm)})')
- _n = len(dm)
- dm = dm.v_max_constrict < v_max
- print(f'After v_max_constrict < {v_max}: {len(dm)} trials '
- f'(lost {_n - len(dm)})')
- print(f'Total lost: {n_total - len(dm)} trials')
- print(f'Remaining: {len(dm)} trials')
- print('=== Descriptive statistics ===')
- print(f'Total trials: {len(dm)}')
- datasets = list(ops.split(dm.dataset))
- conditions = list(ops.split(dm.condition))
- subjects = list(ops.split(dm.subject_nr))
- print(f'Datasets: {len(datasets)} '
- f'({", ".join(str(d) for d, _ in datasets)})')
- print(f'Conditions: {len(conditions)} '
- f'({", ".join(str(c) for c, _ in conditions)})')
- print(f'Subjects: {len(subjects)}')
- print('Trials per dataset:')
- for dataset, ddm in ops.split(dm.dataset):
- n_subj = len(list(ops.split(ddm.subject_nr)))
- print(f' {dataset}: {len(ddm)} trials, {n_subj} subjects')
- print('Trials per condition:')
- for condition, cdm in ops.split(dm.condition):
- print(f' {condition}: {len(cdm)} trials')
- """
- # Sanity check: signal recovery simulation
- """
- if BRANCH == 'recovery':
- for *_, sdm in ops.split(dm.dataset, dm.condition, dm.subject_nr):
- shuffle_sdm = ops.shuffle(sdm)
- dm.t_max_constrict[sdm] = shuffle_sdm.t_max_constrict
- dm.v_max_constrict[sdm] = shuffle_sdm.v_max_constrict
- fake_signal_len = 60
- component = (np.sin(np.linspace(-np.pi, np.pi, fake_signal_len))
- * 5e-7)
- plt.figure(figsize=FIG_SINGLE)
- plt.plot(component)
- plt.xlabel('Sample')
- plt.ylabel('Amplitude')
- plt.title('Simulated recovery component')
- plt.tight_layout()
- plt.show()
- for row in dm:
- start = row.t_max_constrict - fake_signal_len // 2
- end = row.t_max_constrict + fake_signal_len // 2
- row.erg[start:end] += component
- """
- # Create constriction-locked signals
- """
- # Eye position is uncalibrated so we z-score for a decent signal
- dm.gaze_x = srs.z(dm.gaze_x)
- dm.gaze_y = srs.z(dm.gaze_y)
- signal_cols = [
- ('erg', 'erg_constrict'),
- ('erg_upper', 'erg_upper_constrict'),
- ('erg_lower', 'erg_lower_constrict'),
- ('erp_occipital', 'erp_occipital_constrict'),
- ('pupil', 'pupil_constrict'),
- ('gaze_x', 'gaze_x_constrict'),
- ('gaze_y', 'gaze_y_constrict')
- ]
- for src_col, dst_col in signal_cols:
- locked, zero_point = srs.lock(dm[src_col], lock=dm.t_max_constrict)
- dm[dst_col] = locked[
- :, zero_point + PLOT_WINDOW[0]:zero_point + PLOT_WINDOW[1]
- ]
- single_permutation(dm, [dm.dataset, dm.condition, dm.subject_nr])
- dm.t_diff = dm.t_max_constrict - dm.t_max_constrict_shuffle
- # io.writebin(dm, 'merged-data.dm')
- """
- # Create velocity bins
- """
- # Bin real data
- dm.bin_max_constrict = 0
- for *_, ddm in ops.split(dm.subject_nr, dm.dataset, dm.condition):
- if len(ddm) < N_VELOCITY_BINS:
- continue
- for bin_nr, bdm in enumerate(
- ops.bin_split(-1 * ddm.v_max_constrict,
- bins=N_VELOCITY_BINS)):
- dm.bin_max_constrict[bdm] = bin_nr
- # Bin shuffled data
- dm.bin_max_constrict_shuffle = 0
- for *_, ddm in ops.split(dm.subject_nr, dm.dataset, dm.condition):
- if len(ddm) < N_VELOCITY_BINS:
- continue
- for bin_nr, bdm in enumerate(
- ops.bin_split(-1 * ddm.v_max_constrict_shuffle,
- bins=N_VELOCITY_BINS)):
- dm.bin_max_constrict_shuffle[bdm] = bin_nr
- """
- # Individual traces sorted by constriction time
- """
- dm_sorted = ops.sort(dm, by=dm.t_max_constrict)
- a = srs.filter_highpass(dm_sorted.erg, freq_min=HIGHPASS_FREQ_MIN,
- sampling_freq=SAMPLING_FREQ).array
- b = decimate(a, DOWNSAMPLE_FACTOR, axis=0)
- a_sorted = np.array(dm_sorted.t_max_constrict)
- a_resampled = decimate(a_sorted, DOWNSAMPLE_FACTOR)
- n_samples_total = a.shape[1]
- tick_interval_ms = 200
- tick_interval_samples = tick_interval_ms / SAMPLE_DURATION_MS
- tick_positions = np.arange(T0_SAMPLE, n_samples_total, tick_interval_samples)
- tick_labels = ((tick_positions - T0_SAMPLE)
- * SAMPLE_DURATION_MS).astype(int)
- plt.figure(figsize=FIG_LARGE)
- plt.scatter(a_resampled, np.arange(a_resampled.size),
- c=COLOR_PERMUTED, s=10, linewidths=0,
- label='Max. constriction time', zorder=5)
- plt.imshow(b[1:], aspect='auto')
- plt.xticks(tick_positions, tick_labels)
- plt.axvline(T0_SAMPLE, color='black', linestyle=':',
- label='Stimulus onset')
- plt.xlabel('Time since stimulus onset (ms)')
- plt.ylabel('Trial (sorted by constriction time)')
- plt.legend(frameon=False, loc='upper left')
- plt.tight_layout()
- plt.savefig(get_output_dir('png') / 'trial-sort.png')
- plt.savefig(get_output_dir('svg') / 'trial-sort.svg')
- plt.show()
- """
- Split by maximum constriction velocity
- """
- fig, (ax1, ax2) = plt.subplots(1, 2, figsize=FIG_DOUBLE, sharey=True)
- fig.subplots_adjust(wspace=0.05)
- plt.sca(ax1)
- tst.plot(dm, 'erg_constrict', hue_factor='bin_max_constrict', hues='jet',
- x0=CONSTRICT_X0_S, sampling_freq=SAMPLING_FREQ)
- ax1.axvline(0, color='black', linestyle=':')
- ax1.text(0.02, 0.97, 'Real', transform=ax1.transAxes,
- va='top', ha='left', fontweight='bold')
- ax1.set_xlabel('Time relative to max. constriction (s)')
- ax1.set_ylabel('ERG (µV)')
- plt.sca(ax2)
- tst.plot(dm, 'erg_constrict_shuffle',
- hue_factor='bin_max_constrict_shuffle', hues='jet',
- legend_kwargs=None,
- x0=CONSTRICT_X0_S, sampling_freq=SAMPLING_FREQ)
- ax2.axvline(0, color='black', linestyle=':')
- ax2.text(0.02, 0.97, 'Shuffled', transform=ax2.transAxes,
- va='top', ha='left', fontweight='bold')
- ax2.set_xlabel('Time relative to max. constriction (s)')
- ax2.set_ylabel('')
- plt.tight_layout()
- plt.savefig(get_output_dir('png') / 'split-by-constriction-velocity.png')
- plt.savefig(get_output_dir('svg') / 'split-by-constriction-velocity.svg')
- plt.show()
- """
- Visualize pupil and eye position locked to stimulus onset and constriction
- """
- for signal in ('pupil', 'gaze_x', 'gaze_y'):
- fig, (ax1, ax2) = plt.subplots(1, 2, figsize=FIG_DOUBLE, sharey=True)
- fig.subplots_adjust(wspace=0.05)
- plt.sca(ax1)
- tst.plot(dm, signal, 'dataset', x0=STIMULUS_X0_S,
- sampling_freq=SAMPLING_FREQ,
- legend_kwargs={'loc': 'upper right', 'frameon': False})
- plt.xlim(0, 1.5)
- plt.axvline(
- .001 * dm.t_max_constrict.mean * SAMPLE_DURATION_MS + STIMULUS_X0_S,
- color='black', linestyle=':')
- plt.xlabel('Time since stimulus onset (s)')
- if signal == 'pupil':
- plt.ylim(2.5, 5.5)
- plt.ylabel('Pupil size (mm)')
- elif signal == 'gaze_x':
- plt.ylabel('Horizontal gaze position (z-score)')
- elif signal == 'gaze_y':
- plt.ylabel('Vertical gaze position (z-score)')
- plt.sca(ax2)
- tst.plot(dm, f'{signal}_constrict', 'dataset', x0=CONSTRICT_X0_S,
- sampling_freq=SAMPLING_FREQ,
- legend_kwargs={'loc': 'upper right', 'frameon': False})
- plt.axvline(0, color='black', linestyle=':')
- if signal == 'pupil':
- plt.ylim(2.5, 5.5)
- plt.xlabel('Time relative to max. constriction (s)')
- plt.tight_layout()
- plt.savefig(get_output_dir('png') / f'{signal}-constriction.png')
- plt.savefig(get_output_dir('svg') / f'{signal}-constriction.svg')
- plt.show()
- """
- Visualize ERG locked to stimulus onset
- """
- fig, ax = plt.subplots(1, 1, figsize=FIG_SINGLE)
- tst.plot(dm, 'erg', 'dataset', x0=STIMULUS_X0_S,
- sampling_freq=SAMPLING_FREQ,
- legend_kwargs={'loc': 'upper right', 'frameon': False})
- plt.axvline(0, color='black', linestyle=':')
- plt.xlabel('Time since stimulus onset (s)')
- plt.axvline(.001 * dm.t_max_constrict.mean * SAMPLE_DURATION_MS, color='black',
- linestyle=':')
- plt.ylabel('ERG (µV)')
- plt.tight_layout()
- plt.savefig(get_output_dir('png') / 'erg-stimulus-locked.png')
- plt.savefig(get_output_dir('svg') / 'erg-stimulus-locked.svg')
- plt.show()
- """
- Visualize ERG separately for upper and lower electrodes
- """
- constrict_time_s = PLOT_TIME_MS / 1000
- stimulus_time_s = (np.arange(dm.erg_upper.depth) / SAMPLING_FREQ
- + STIMULUS_X0_S)
- fig, axes = plt.subplots(1, 2, figsize=FIG_DOUBLE)
- plt.sca(axes[0])
- plt.plot(stimulus_time_s, dm.erg_upper.mean,
- color=COLOR_UPPER, label='Upper')
- plt.plot(stimulus_time_s, dm.erg_lower.mean,
- color=COLOR_LOWER, label='Lower')
- plt.axvline(0, color='black', linestyle=':')
- plt.xlabel('Time since stimulus onset (s)')
- plt.ylabel('ERG (µV)')
- plt.legend(frameon=False)
- plt.title('Stimulus-locked')
- plt.sca(axes[1])
- plt.plot(constrict_time_s, dm.erg_upper_constrict.mean,
- color=COLOR_UPPER, label='Upper (real)')
- plt.plot(constrict_time_s, dm.erg_upper_constrict_shuffle.mean,
- color=COLOR_UPPER, linestyle=':', label='Upper (shuffled)')
- plt.plot(constrict_time_s, dm.erg_lower_constrict.mean,
- color=COLOR_LOWER, label='Lower (real)')
- plt.plot(constrict_time_s, dm.erg_lower_constrict_shuffle.mean,
- color=COLOR_LOWER, linestyle=':', label='Lower (shuffled)')
- plt.axvline(0, color='black', linestyle=':')
- plt.xlabel('Time relative to max. constriction (s)')
- plt.ylabel('ERG (µV)')
- plt.legend(frameon=False, fontsize=8)
- plt.title('Constriction-locked')
- plt.tight_layout()
- plt.savefig(get_output_dir('png') / 'upper-lower-electrodes.png')
- plt.savefig(get_output_dir('svg') / 'upper-lower-electrodes.svg')
- plt.show()
- """
- Visualize occipital ERP
- """
- fig, axes = plt.subplots(1, 2, figsize=FIG_DOUBLE)
- plt.sca(axes[0])
- plt.plot(stimulus_time_s, dm.erp_occipital.mean, color=COLOR_REAL)
- plt.axvline(0, color='black', linestyle=':')
- plt.xlabel('Time since stimulus onset (s)')
- plt.ylabel('ERP (µV)')
- plt.title('Stimulus-locked occipital ERP')
- plt.sca(axes[1])
- plt.plot(constrict_time_s, dm.erp_occipital_constrict.mean,
- color=COLOR_REAL, label='Real')
- plt.plot(constrict_time_s, dm.erp_occipital_constrict_shuffle.mean,
- color=COLOR_PERMUTED, linestyle=':', label='Shuffled')
- plt.axvline(0, color='black', linestyle=':')
- plt.xlabel('Time relative to max. constriction (s)')
- plt.ylabel('ERP (µV)')
- plt.legend(frameon=False)
- plt.title('Constriction-locked occipital ERP')
- plt.tight_layout()
- plt.savefig(get_output_dir('png') / 'occipital-erp.png')
- plt.savefig(get_output_dir('svg') / 'occipital-erp.svg')
- plt.show()
- """
- # Figure 2: Main results (four-panel composite)
- """
- fig = plt.figure(figsize=(6.27, 9))
- gs = fig.add_gridspec(3, 2, height_ratios=[0.8, 1, .8], hspace=0.4, wspace=0)
- # --- Panel a: Constriction-locked ERG (all datasets) ---------------------
- ax_a = fig.add_subplot(gs[0, :])
- plt.sca(ax_a)
- xdm = dm[dm.subject_nr, dm.dataset, dm.condition, dm.erg,
- dm.erg_constrict, dm.t_max_constrict, dm.v_max_constrict]
- print('Running main permutation test')
- run_permutation_test(
- xdm,
- shuffle_by=[xdm.subject_nr, xdm.dataset, xdm.condition],
- )
- ax_a.set_title('a) Retinal activity (ERG) locked to pupil constriction (all datasets)',
- loc='left')
- # --- Panel b: Split by maximum constriction velocity ---------------------
- ax_c = fig.add_subplot(gs[1, 0])
- plt.sca(ax_c)
- tst.plot(dm, 'erg_constrict', hue_factor='bin_max_constrict', hues='jet',
- x0=CONSTRICT_X0_S * 1000, sampling_freq=SAMPLING_FREQ / 1000)
- ax_c.axvline(0, color='black', linestyle=':')
- ax_c.set_xlabel('Time relative to max. constriction (ms)')
- ax_c.set_ylabel('ERG (µV)')
- ax_c.set_title('b) Split by maximum constriction velocity', loc='left')
- # --- Panel c: 3×3 grid split by dataset ---------------------------------
- gs_b = gs[1, 1].subgridspec(3, 3, wspace=0, hspace=0)
- xdm = dm[dm.subject_nr, dm.dataset, dm.condition, dm.erg,
- dm.erg_constrict, dm.t_max_constrict, dm.v_max_constrict]
- axes_b = []
- for i, (dataset, ddm) in enumerate(ops.split(xdm.dataset)):
- print(f'Running permutation test for {dataset}')
- ax = fig.add_subplot(gs_b[i // 3, i % 3])
- plt.sca(ax)
- run_permutation_test(
- ddm,
- shuffle_by=[ddm.subject_nr, ddm.condition],
- ylabel='',
- )
- ax.set_xlabel('')
- ax.set_ylabel('')
- ax.set_xticks([])
- ax.set_yticks([])
- legend = ax.get_legend()
- if legend is not None:
- legend.remove()
- ax.text(0.05, 0.95, dataset, transform=ax.transAxes,
- fontsize=7, va='top', ha='left', fontweight='bold',
- bbox=dict(boxstyle='round,pad=0.2', facecolor='white',
- edgecolor='none', alpha=0.7))
- axes_b.append(ax)
- axes_b[0].set_title('c) Split by dataset', loc='left')
- # --- Panel d: Constriction-locked occipital ERP (all datasets) ---------------------
- ax_d = fig.add_subplot(gs[2, :])
- plt.sca(ax_d)
- xdm = dm[dm.subject_nr, dm.dataset, dm.condition, dm.erp_occipital,
- dm.erp_occipital_constrict, dm.t_max_constrict,
- dm.v_max_constrict]
- run_permutation_test(
- xdm,
- shuffle_by=[xdm.subject_nr, xdm.dataset, xdm.condition],
- col='erp_occipital_constrict',
- ylabel='ERP (µV)',
- )
- ax_d.set_title('d) Visual-cortex activity (occipital ERP) locked to pupil constriction',
- loc='left')
- plt.savefig(get_output_dir('png') / 'figure-2.png', dpi=300, bbox_inches='tight')
- plt.savefig(get_output_dir('svg') / 'figure-2.svg', bbox_inches='tight')
- plt.show()
- """
- # Figure 3: Stimulus-locked ERG by dataset and by intensity
- """
- mean_t_max_constrict = dm.t_max_constrict.mean * SAMPLE_DURATION_MS + STIMULUS_X0_S * 1000
- fig = plt.figure(figsize=(6.27, 3))
- gs = fig.add_gridspec(1, 2, wspace=0)
- # Left panel: ERG by dataset
- ax1 = fig.add_subplot(gs[0, 0])
- plt.sca(ax1)
- ax1.axvline(0, color='black', linestyle=':')
- ax1.axhline(0, color='black', linestyle=':')
- ax1.axvline(mean_t_max_constrict, color='black', linestyle=':')
- tst.plot(dm, 'erg', 'dataset', x0=STIMULUS_X0_S * 1000,
- sampling_freq=SAMPLING_FREQ / 1000,
- legend_kwargs={'loc': 'upper right', 'frameon': False})
- ax1.set_xlabel('Time since stimulus onset (ms)')
- ax1.set_ylabel('ERG (µV)')
- ax1.set_title('a) Retinal activity (ERG) locked to stimulus', loc='left')
- ax1.set_ylim(-1.3e-5, 1e-5)
- # Right panel: ERG by intensity (original dataset only)
- ax2 = fig.add_subplot(gs[0, 1])
- plt.sca(ax2)
- odm = dm.dataset == 'original'
- tst.plot(odm, 'erg', 'intensity_cdm2', x0=STIMULUS_X0_S * 1000,
- sampling_freq=SAMPLING_FREQ / 1000, hues='jet',
- legend_kwargs={'loc': 'upper right', 'frameon': False})
- ax2.set_xlim(0, 250)
- ax2.set_ylim(-1.3e-5, 1e-5)
- ax2.axhline(0, color='black', linestyle=':')
- ax2.set_xlabel('Time since stimulus onset (ms)')
- ax2.set_ylabel('')
- ax2.set_yticks([])
- ax2.set_title('b) ERG as a function of stimulus intensity', loc='left')
- plt.tight_layout()
- plt.savefig(get_output_dir('png') / 'figure-3.png', dpi=300, bbox_inches='tight')
- plt.savefig(get_output_dir('svg') / 'figure-3.svg', bbox_inches='tight')
- plt.show()
- """
- # Figure 4: Pupil size and constriction timing by dataset
- """
- fig = plt.figure(figsize=(6.27, 3))
- gs = fig.add_gridspec(1, 2, wspace=0)
- # Left panel: Pupil size by dataset
- ax1 = fig.add_subplot(gs[0, 0])
- plt.sca(ax1)
- ax1.axvline(mean_t_max_constrict, color='black', linestyle=':')
- tst.plot(dm, 'pupil', 'dataset', x0=STIMULUS_X0_S * 1000,
- sampling_freq=SAMPLING_FREQ / 1000,
- legend_kwargs={'loc': 'upper right', 'frameon': False})
- ax1.set_xlim(0, 1500)
- ax1.set_xlabel('Time since stimulus onset (ms)')
- ax1.set_ylabel('Pupil size (mm)')
- ax1.set_title('a) Pupil size locked to stimulus', loc='left')
- # Right panel: Distribution of constriction timing by dataset
- ax2 = fig.add_subplot(gs[0, 1])
- plt.sca(ax2)
- palette = plt.cm.Dark2.colors # Get Dark2 palette colors
- for i, (dataset, ddm) in enumerate(ops.split(dm.dataset)):
- vals = (np.array(ddm.t_max_constrict) - T0_SAMPLE) * SAMPLE_DURATION_MS
- sns.kdeplot(vals, label=dataset, ax=ax2, color=palette[i % len(palette)])
- ax2.axvline(mean_t_max_constrict, color='black', linestyle=':')
- ax2.set_xlim(0, 1500)
- ax2.set_xlabel('Max. constriction time (ms)')
- ax2.set_ylabel('Density')
- ax2.set_yticks([])
- ax2.yaxis.set_label_position("right") # Move y-label to the right
- ax2.legend(frameon=False)
- ax2.set_title('b) Timepoints of max. pupil constriction',
- loc='left')
- plt.tight_layout()
- plt.savefig(get_output_dir('png') / 'figure-4.png', dpi=300, bbox_inches='tight')
- plt.savefig(get_output_dir('svg') / 'figure-4.svg', bbox_inches='tight')
- plt.show()
- """
- Visualize all EEG channels, and the ERG for the datasets with full EEG data.
- """
- xdm = dm.has_eeg == 1
- xdm = xdm[xdm.subject_nr, xdm.dataset, xdm.condition, xdm.t_max_constrict,
- xdm.v_max_constrict, xdm.erp]
- effect_sizes = {}
- for ch in EEG_CHANNELS:
- plt.figure(figsize=FIG_SINGLE)
- xdm[f'erp_{ch}'] = xdm.erp[:, ch]
- locked, zero_point = srs.lock(xdm[f'erp_{ch}'], lock=xdm.t_max_constrict)
- xdm[f'erp_{ch}_constrict'] = locked[
- :, zero_point + PLOT_WINDOW[0]:zero_point + PLOT_WINDOW[1]
- ]
- plt.title(f'Constriction-locked ERP ({ch})')
- result = run_permutation_test(
- xdm,
- shuffle_by=[xdm.subject_nr, xdm.dataset, xdm.condition],
- col=f'erp_{ch}_constrict',
- ylabel='ERP (µV)'
- )
- effect_sizes[ch] = result['effect_size']
- del xdm[f'erp_{ch}']
- del xdm[f'erp_{ch}_constrict']
- plt.tight_layout()
- plt.savefig(get_output_dir('png/channels') / f'permutation-erp-{ch}.png')
- plt.savefig(get_output_dir('svg/channels') / f'permutation-erp-{ch}.svg')
- plt.show()
- plt.figure(figsize=FIG_SINGLE)
- xdm = dm.has_eeg == 1
- xdm = xdm[xdm.subject_nr, xdm.dataset, xdm.condition, xdm.t_max_constrict,
- xdm.v_max_constrict, xdm.erg, xdm.erg_constrict]
- plt.title('Constriction-locked ERG (datasets with EEG)')
- result = run_permutation_test(
- xdm,
- shuffle_by=[xdm.subject_nr, xdm.dataset, xdm.condition]
- )
- effect_sizes['erg'] = result['effect_size']
- plt.tight_layout()
- plt.savefig(get_output_dir('png/channels') / 'permutation-erg-with-eeg.png')
- plt.savefig(get_output_dir('svg/channels') / 'permutation-erg-with-eeg.svg')
- plt.show()
- """
- Create topomap of effect sizes.
- """
- for winstart in range(0, len(effect_sizes['erg']), TOPOMAP_WINLEN):
- t0 = (winstart + PLOT_WINDOW[0]) * SAMPLE_DURATION_MS
- t1 = t0 + TOPOMAP_WINLEN * SAMPLE_DURATION_MS
- fig, ax = plot_effect_size_topomap(
- effect_sizes,
- title=f'Constriction-locked effect sizes ({t0:.0f}–{t1:.0f}ms)',
- show=False, window=(winstart, winstart + TOPOMAP_WINLEN),
- vmin=0, vmax=14)
- plt.savefig(get_output_dir('png/topomaps') / f'topomap-{winstart}.png')
- plt.savefig(get_output_dir('svg/topomaps') / f'topomap-{winstart}.svg')
- plt.show()
analyze.py, no license · at the source
Overview
- Department of Psychology, University of Groningen, Groningen, the Netherlands
- Faculty of Science and Engineering, University of Groningen, Groningen, the Netherlands
Abstract
Pupil responses shape the earliest stages of visual perception by regulating the amount of light that enters the eye. How this affects visual processing is still poorly understood. Here we present evidence that pupil constriction causes activity in the human retina and visual system, independently of visual stimulation. Healthy human participants (N = 119) viewed brief visual stimuli (light increments or decrements) while pupil size, retinal activity (electroretinogram), and brain activity (electroencephalogram) were recorded. As expected, visual stimulation triggered an initial burst of retinal activity followed by pupil constriction (the pupil light response). Importantly, we used trial‐to‐trial variability in constriction latency to reveal a previously unknown retinal response that is locked to pupil constriction, rather than to visual stimulation. Presumably, and in line with similar findings in mice, this constriction‐locked retinal activity is a response to the sudden decrease in retinal light exposure that accompanies pupil constriction (although a contribution of iris muscle activity is not conclusively ruled out). A similar constriction‐locked response emerged later over visual cortex. Given these findings, an important open question is how the visual system maintains brightness constancy despite pupil‐induced retinal and cortical activity.
Reproduced under the paper's license (CC BY), from the paper cited above.
Repository
Its files are read in the Code ↔ Paper reader above.
OSF 2u6jv
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
- 27 September 2026: the link answers (HTTP 200)
3 files
- analyze.py, Python, 624 lines
- constants.py, Python, 81 lines
- helpers.py, Python, 209 lines
The paper's code and data availability statement is in the Data section.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 3 scripts, each with its path and the digest of its content;
- no match between paragraphs and code yet;
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
No dataset and no data link were found in the paper.
Data Availability Statement
All data, experimental materials, analysis scripts, and Supporting Information are available from https://
Reproduced under the paper's license (CC BY), from the paper cited above.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 2, 28 September 2026
- Publisher: n/a → Wiley
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 6 authors, 12 MeSH terms, 2 funders, 45 references.
Cite
This paper
Mathôt, S., Dimigen, O., Karsilar, H., Ruuskanen, V., Weiden, D., & Vilotijević, A. (2026). Pupil Constriction Causes Activity in the Human Retina and Visual System. Psychophysiology, 63(7), e70362. https://
BibTeX
@article{mathot2026pupil
author = {Mathôt, Sebastiaan and Dimigen, Olaf and Karsilar, Hakan and Ruuskanen, Veera and Weiden, Daria and Vilotijević, Ana},
title = {{Pupil Constriction Causes Activity in the Human Retina and Visual System}},
journal = {Psychophysiology},
year = {2026},
month = jul,
volume = {63},
number = {7},
pages = {e70362},
publisher = {Wiley},
issn = {0048-5772},
doi = {10.1111/
url = {https://
pmid = {42487203},
pmcid = {PMC13392059}
}
RIS
TY - JOUR
AU - Mathôt, Sebastiaan
AU - Dimigen, Olaf
AU - Karsilar, Hakan
AU - Ruuskanen, Veera
AU - Weiden, Daria
AU - Vilotijević, Ana
TI - Pupil Constriction Causes Activity in the Human Retina and Visual System
T2 - Psychophysiology
J2 - Psychophysiology
PY - 2026
DA - 2026/
VL - 63
IS - 7
SP - e70362
SN - 0048-5772
PB - Wiley
DO - 10.1111/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1111/
"type": "article-journal",
"title": "Pupil Constriction Causes Activity in the Human Retina and Visual System",
"container-title": "Psychophysiology",
"author": [
{
"family": "Mathôt",
"given": "Sebastiaan"
},
{
"family": "Dimigen",
"given": "Olaf"
},
{
"family": "Karsilar",
"given": "Hakan"
},
{
"family": "Ruuskanen",
"given": "Veera"
},
{
"family": "Weiden",
"given": "Daria"
},
{
"family": "Vilotijević",
"given": "Ana"
}
],
"container-title-short":
"volume": "63",
"issue": "7",
"page": "e70362",
"DOI": "10.1111/
"PMID": "42487203",
"PMCID": "PMC13392059",
"ISSN": "0048-5772",
"publisher": "Wiley",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
1
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1111/psyp.70035 [code]
- The Interplay of Spontaneous Pupil-Size Fluctuations and EEG Power in Near-Threshold Detection.Journal: PsychophysiologyIn common: EEG, 15 references, 2 authors
- [2] doi:10.1111/psyp.14155 [code]
- Concealed identity information detection with pupillometry in rapid serial visual presentation.Journal: PsychophysiologyIn common: MNE-Python, seaborn, SciPy, 2 other tools, EEG, 3 references, author Sebastiaan Mathôt
- [3] doi:10.1113/jp287205 [code]
- The pupillary respiratory-phase response: pupil size is smallest around inhalation onset and largest during exhalation.Journal: The Journal of physiologyIn common: 3 references, author Sebastiaan Mathôt
- [4] doi:10.3758/s13428-023-02098-1 [code]
- From pre-processing to advanced dynamic modeling of pupil data.Journal: Behavior research methodsIn common: seaborn, SciPy, Matplotlib, 1 other tool, 4 references
- [5] doi:10.1162/imag.a.1321 [code]
- Phase similarity between similar objects indicates representational merging across retrieval training but not sleep.Journal: Imaging neuroscience (Cambridge, Mass.)In common: MNE-Python, seaborn, SciPy, 2 other tools, EEG, 3 references
- [6] doi:10.1038/s42003-025-08464-3 [code]
- How EEG preprocessing shapes decoding performance.Journal: Communications biologyIn common: MNE-Python, seaborn, SciPy, 2 other tools, EEG, 3 references
- [7] doi:10.1038/s41598-023-41613-4 [code]
- Single-trial visually evoked potentials predict both individual choice and market outcomes.Journal: Scientific reportsIn common: MNE-Python, seaborn, SciPy, 2 other tools, EEG, 3 references
- [8] doi:10.1038/s41598-022-17304-x [code]
- Altered EEG variability on different time scales in participants with autism spectrum disorder: an exploratory study.Journal: Scientific reportsIn common: MNE-Python, seaborn, SciPy, 2 other tools, EEG, 3 references
- [9] doi:10.3758/s13428-026-02997-z [code]
- PyLossless: A non-destructive EEG processing pipeline.Journal: Behavior research methodsIn common: MNE-Python, SciPy, NumPy, EEG, 4 references
- [10] doi:10.1111/psyp.70047 [code]
- Presaccadic Attention Shifts Up- and Downwards: Evidence From the Pupil Light Response.Journal: PsychophysiologyIn common: MNE-Python, seaborn, SciPy, 2 other tools, 2 references
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 3 scripts, and 0 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:41074934ce4b50cb…
Add the badge to the code's README
If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.
Markdown
<!-- oscr-badge:start -->
[](https://openscicode.org/badge/doi/10.1111/psyp.70362)
<!-- oscr-badge:end -->reStructuredText
.. oscr-badge:start
.. image:: https://openscicode.org/badge/doi/10.1111/psyp.70362.svg
:target: https://openscicode.org/badge/doi/10.1111/psyp.70362
:alt: OSCR
.. oscr-badge:endHTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1111/psyp.70362"><img src="https://openscicode.org/badge/doi/10.1111/psyp.70362.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.
Report a mismatch between the code and the paper · Report a code error (signed in)
Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.
Report a reproduction failure (signed in)
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
