OSCR

Pupil Constriction Causes Activity in the Human Retina and Visual System.

Code ↔ Paper

The paper beside its authors' code: matches between them have not been computed for this paper yet.

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

  1. """Constriction-locked ERG analysis.
  2. Analyzes the relationship between pupil constriction and the electroretinogram
  3. (ERG) by locking the ERG signal to the moment of maximum pupil constriction
  4. velocity. A permutation test assesses statistical significance.
  5. """
  6. from pathlib import Path
  7. from matplotlib import pyplot as plt
  8. import seaborn as sns
  9. import time_series_test as tst
  10. from datamatrix import io, operations as ops, series as srs
  11. import numpy as np
  12. from scipy.signal import decimate
  13. from constants import (SAMPLING_FREQ, SAMPLE_DURATION_MS, T0_SAMPLE, SEARCH_WINDOW,
  14. SEARCH_SMOOTH_WINLEN, V_MAX_CONSTRICT_RANGE, SEARCH_MARGIN,
  15. PLOT_WINDOW, DOWNSAMPLE_FACTOR,
  16. HIGHPASS_FREQ_MIN, N_VELOCITY_BINS, FIG_SINGLE, FIG_DOUBLE,
  17. FIG_LARGE, EEG_CHANNELS, TOPOMAP_WINLEN,
  18. PLOT_TIME_MS, CONSTRICT_X0_S, STIMULUS_X0_S, N_EEG_CHANNELS,
  19. COLOR_REAL, COLOR_PERMUTED, COLOR_UPPER, COLOR_LOWER,
  20. LOCKING_EVENT, BRANCH, get_checkpoint_dir, get_output_dir)
  21. from helpers import (single_permutation, run_permutation_test,
  22. plot_effect_size_topomap)
  23. """"
  24. # Ensure output folders exist
  25. """
  26. for output_type in ['png', 'svg']:
  27. Path(get_output_dir(output_type)).mkdir(parents=True, exist_ok=True)
  28. Path(get_output_dir(f"{output_type}/topomaps")).mkdir(parents=True, exist_ok=True)
  29. Path(get_output_dir(f"{output_type}/channels")).mkdir(parents=True, exist_ok=True)
  30. """
  31. # Load data
  32. """
  33. dms = []
  34. checkpoint_dir = get_checkpoint_dir()
  35. for path in checkpoint_dir.glob('*.dm'):
  36. print(f'Loading {path}')
  37. dms.append(io.readbin(path))
  38. # Only keep EEG for datasets that have all 26 channels
  39. for dm in dms:
  40. print(dm.dataset.unique)
  41. if 'erp' in dm:
  42. if dm.erp.shape[1] != N_EEG_CHANNELS:
  43. print('removing incomplete EEG data')
  44. del dm.erp
  45. dm.has_eeg = 0
  46. else:
  47. print('has EEG data')
  48. dm.has_eeg = 1
  49. else:
  50. print('no EEG data')
  51. dm.has_eeg = 0
  52. dm = ops.stack(dms)
  53. del dms
  54. """
  55. # Determine point of maximum constriction velocity
  56. """
  57. for row in dm:
  58. d = np.diff(srs.smooth(
  59. row.pupil[SEARCH_WINDOW[0]:SEARCH_WINDOW[1]],
  60. winlen=SEARCH_SMOOTH_WINLEN))
  61. peak_idx = np.argmin(d)
  62. row.v_max_constrict = d[peak_idx]
  63. if LOCKING_EVENT == 'peak':
  64. lock_idx = peak_idx
  65. elif LOCKING_EVENT == 'start':
  66. # Scan backward from peak: find last non-negative derivative before
  67. # peak, i.e. the onset of constriction
  68. pre = np.where(d[:peak_idx] >= 0)[0]
  69. lock_idx = pre[-1] if len(pre) else 0
  70. elif LOCKING_EVENT == 'end':
  71. # Scan forward from peak: find first non-negative derivative after
  72. # peak, i.e. the end of constriction
  73. post = np.where(d[peak_idx:] >= 0)[0]
  74. lock_idx = peak_idx + post[0] if len(post) else len(d) - 1
  75. row.t_max_constrict = lock_idx + SEARCH_WINDOW[0]
  76. fig, (ax1, ax2) = plt.subplots(1, 2, figsize=FIG_DOUBLE)
  77. plt.sca(ax1)
  78. t_max_constrict_ms = (np.array(dm.t_max_constrict) - T0_SAMPLE) * SAMPLE_DURATION_MS
  79. sns.histplot(t_max_constrict_ms, bins=100)
  80. ax1.axvline((SEARCH_WINDOW[0] + SEARCH_MARGIN - T0_SAMPLE) * SAMPLE_DURATION_MS,
  81. color='black', linestyle='--', label='Filter bounds')
  82. ax1.axvline((SEARCH_WINDOW[1] - SEARCH_MARGIN - T0_SAMPLE) * SAMPLE_DURATION_MS,
  83. color='black', linestyle='--')
  84. ax1.legend(frameon=False)
  85. ax1.set_xlabel('Max. constriction time (ms)')
  86. ax1.set_ylabel('Count')
  87. plt.sca(ax2)
  88. sns.histplot(np.array(dm.v_max_constrict), bins=100, binrange=(-.1, 0))
  89. ax2.axvline(V_MAX_CONSTRICT_RANGE[0], color='black', linestyle='--',
  90. label='Filter bounds')
  91. ax2.axvline(V_MAX_CONSTRICT_RANGE[1], color='black', linestyle='--')
  92. ax2.set_xlabel('Max. constriction velocity (mm/sample)')
  93. ax2.set_ylabel('Count')
  94. ax2.legend(frameon=False)
  95. plt.tight_layout()
  96. plt.savefig(get_output_dir('png') / 'constriction-time-and-velocity.png')
  97. plt.savefig(get_output_dir('svg') / 'constriction-time-and-velocity.svg')
  98. plt.show()
  99. """
  100. # Filter data and descriptive statistics
  101. """
  102. print('=== Filtering ===')
  103. n_total = len(dm)
  104. t_min = SEARCH_WINDOW[0] + SEARCH_MARGIN
  105. t_max = SEARCH_WINDOW[1] - SEARCH_MARGIN
  106. v_min, v_max = V_MAX_CONSTRICT_RANGE
  107. print(f'Before filtering: {n_total} trials')
  108. _n = len(dm)
  109. dm = dm.t_max_constrict > t_min
  110. print(f'After t_max_constrict > {t_min}: {len(dm)} trials '
  111. f'(lost {_n - len(dm)})')
  112. _n = len(dm)
  113. dm = dm.t_max_constrict < t_max
  114. print(f'After t_max_constrict < {t_max}: {len(dm)} trials '
  115. f'(lost {_n - len(dm)})')
  116. _n = len(dm)
  117. dm = dm.v_max_constrict > v_min
  118. print(f'After v_max_constrict > {v_min}: {len(dm)} trials '
  119. f'(lost {_n - len(dm)})')
  120. _n = len(dm)
  121. dm = dm.v_max_constrict < v_max
  122. print(f'After v_max_constrict < {v_max}: {len(dm)} trials '
  123. f'(lost {_n - len(dm)})')
  124. print(f'Total lost: {n_total - len(dm)} trials')
  125. print(f'Remaining: {len(dm)} trials')
  126. print('=== Descriptive statistics ===')
  127. print(f'Total trials: {len(dm)}')
  128. datasets = list(ops.split(dm.dataset))
  129. conditions = list(ops.split(dm.condition))
  130. subjects = list(ops.split(dm.subject_nr))
  131. print(f'Datasets: {len(datasets)} '
  132. f'({", ".join(str(d) for d, _ in datasets)})')
  133. print(f'Conditions: {len(conditions)} '
  134. f'({", ".join(str(c) for c, _ in conditions)})')
  135. print(f'Subjects: {len(subjects)}')
  136. print('Trials per dataset:')
  137. for dataset, ddm in ops.split(dm.dataset):
  138. n_subj = len(list(ops.split(ddm.subject_nr)))
  139. print(f' {dataset}: {len(ddm)} trials, {n_subj} subjects')
  140. print('Trials per condition:')
  141. for condition, cdm in ops.split(dm.condition):
  142. print(f' {condition}: {len(cdm)} trials')
  143. """
  144. # Sanity check: signal recovery simulation
  145. """
  146. if BRANCH == 'recovery':
  147. for *_, sdm in ops.split(dm.dataset, dm.condition, dm.subject_nr):
  148. shuffle_sdm = ops.shuffle(sdm)
  149. dm.t_max_constrict[sdm] = shuffle_sdm.t_max_constrict
  150. dm.v_max_constrict[sdm] = shuffle_sdm.v_max_constrict
  151. fake_signal_len = 60
  152. component = (np.sin(np.linspace(-np.pi, np.pi, fake_signal_len))
  153. * 5e-7)
  154. plt.figure(figsize=FIG_SINGLE)
  155. plt.plot(component)
  156. plt.xlabel('Sample')
  157. plt.ylabel('Amplitude')
  158. plt.title('Simulated recovery component')
  159. plt.tight_layout()
  160. plt.show()
  161. for row in dm:
  162. start = row.t_max_constrict - fake_signal_len // 2
  163. end = row.t_max_constrict + fake_signal_len // 2
  164. row.erg[start:end] += component
  165. """
  166. # Create constriction-locked signals
  167. """
  168. # Eye position is uncalibrated so we z-score for a decent signal
  169. dm.gaze_x = srs.z(dm.gaze_x)
  170. dm.gaze_y = srs.z(dm.gaze_y)
  171. signal_cols = [
  172. ('erg', 'erg_constrict'),
  173. ('erg_upper', 'erg_upper_constrict'),
  174. ('erg_lower', 'erg_lower_constrict'),
  175. ('erp_occipital', 'erp_occipital_constrict'),
  176. ('pupil', 'pupil_constrict'),
  177. ('gaze_x', 'gaze_x_constrict'),
  178. ('gaze_y', 'gaze_y_constrict')
  179. ]
  180. for src_col, dst_col in signal_cols:
  181. locked, zero_point = srs.lock(dm[src_col], lock=dm.t_max_constrict)
  182. dm[dst_col] = locked[
  183. :, zero_point + PLOT_WINDOW[0]:zero_point + PLOT_WINDOW[1]
  184. ]
  185. single_permutation(dm, [dm.dataset, dm.condition, dm.subject_nr])
  186. dm.t_diff = dm.t_max_constrict - dm.t_max_constrict_shuffle
  187. # io.writebin(dm, 'merged-data.dm')
  188. """
  189. # Create velocity bins
  190. """
  191. # Bin real data
  192. dm.bin_max_constrict = 0
  193. for *_, ddm in ops.split(dm.subject_nr, dm.dataset, dm.condition):
  194. if len(ddm) < N_VELOCITY_BINS:
  195. continue
  196. for bin_nr, bdm in enumerate(
  197. ops.bin_split(-1 * ddm.v_max_constrict,
  198. bins=N_VELOCITY_BINS)):
  199. dm.bin_max_constrict[bdm] = bin_nr
  200. # Bin shuffled data
  201. dm.bin_max_constrict_shuffle = 0
  202. for *_, ddm in ops.split(dm.subject_nr, dm.dataset, dm.condition):
  203. if len(ddm) < N_VELOCITY_BINS:
  204. continue
  205. for bin_nr, bdm in enumerate(
  206. ops.bin_split(-1 * ddm.v_max_constrict_shuffle,
  207. bins=N_VELOCITY_BINS)):
  208. dm.bin_max_constrict_shuffle[bdm] = bin_nr
  209. """
  210. # Individual traces sorted by constriction time
  211. """
  212. dm_sorted = ops.sort(dm, by=dm.t_max_constrict)
  213. a = srs.filter_highpass(dm_sorted.erg, freq_min=HIGHPASS_FREQ_MIN,
  214. sampling_freq=SAMPLING_FREQ).array
  215. b = decimate(a, DOWNSAMPLE_FACTOR, axis=0)
  216. a_sorted = np.array(dm_sorted.t_max_constrict)
  217. a_resampled = decimate(a_sorted, DOWNSAMPLE_FACTOR)
  218. n_samples_total = a.shape[1]
  219. tick_interval_ms = 200
  220. tick_interval_samples = tick_interval_ms / SAMPLE_DURATION_MS
  221. tick_positions = np.arange(T0_SAMPLE, n_samples_total, tick_interval_samples)
  222. tick_labels = ((tick_positions - T0_SAMPLE)
  223. * SAMPLE_DURATION_MS).astype(int)
  224. plt.figure(figsize=FIG_LARGE)
  225. plt.scatter(a_resampled, np.arange(a_resampled.size),
  226. c=COLOR_PERMUTED, s=10, linewidths=0,
  227. label='Max. constriction time', zorder=5)
  228. plt.imshow(b[1:], aspect='auto')
  229. plt.xticks(tick_positions, tick_labels)
  230. plt.axvline(T0_SAMPLE, color='black', linestyle=':',
  231. label='Stimulus onset')
  232. plt.xlabel('Time since stimulus onset (ms)')
  233. plt.ylabel('Trial (sorted by constriction time)')
  234. plt.legend(frameon=False, loc='upper left')
  235. plt.tight_layout()
  236. plt.savefig(get_output_dir('png') / 'trial-sort.png')
  237. plt.savefig(get_output_dir('svg') / 'trial-sort.svg')
  238. plt.show()
  239. """
  240. Split by maximum constriction velocity
  241. """
  242. fig, (ax1, ax2) = plt.subplots(1, 2, figsize=FIG_DOUBLE, sharey=True)
  243. fig.subplots_adjust(wspace=0.05)
  244. plt.sca(ax1)
  245. tst.plot(dm, 'erg_constrict', hue_factor='bin_max_constrict', hues='jet',
  246. x0=CONSTRICT_X0_S, sampling_freq=SAMPLING_FREQ)
  247. ax1.axvline(0, color='black', linestyle=':')
  248. ax1.text(0.02, 0.97, 'Real', transform=ax1.transAxes,
  249. va='top', ha='left', fontweight='bold')
  250. ax1.set_xlabel('Time relative to max. constriction (s)')
  251. ax1.set_ylabel('ERG (µV)')
  252. plt.sca(ax2)
  253. tst.plot(dm, 'erg_constrict_shuffle',
  254. hue_factor='bin_max_constrict_shuffle', hues='jet',
  255. legend_kwargs=None,
  256. x0=CONSTRICT_X0_S, sampling_freq=SAMPLING_FREQ)
  257. ax2.axvline(0, color='black', linestyle=':')
  258. ax2.text(0.02, 0.97, 'Shuffled', transform=ax2.transAxes,
  259. va='top', ha='left', fontweight='bold')
  260. ax2.set_xlabel('Time relative to max. constriction (s)')
  261. ax2.set_ylabel('')
  262. plt.tight_layout()
  263. plt.savefig(get_output_dir('png') / 'split-by-constriction-velocity.png')
  264. plt.savefig(get_output_dir('svg') / 'split-by-constriction-velocity.svg')
  265. plt.show()
  266. """
  267. Visualize pupil and eye position locked to stimulus onset and constriction
  268. """
  269. for signal in ('pupil', 'gaze_x', 'gaze_y'):
  270. fig, (ax1, ax2) = plt.subplots(1, 2, figsize=FIG_DOUBLE, sharey=True)
  271. fig.subplots_adjust(wspace=0.05)
  272. plt.sca(ax1)
  273. tst.plot(dm, signal, 'dataset', x0=STIMULUS_X0_S,
  274. sampling_freq=SAMPLING_FREQ,
  275. legend_kwargs={'loc': 'upper right', 'frameon': False})
  276. plt.xlim(0, 1.5)
  277. plt.axvline(
  278. .001 * dm.t_max_constrict.mean * SAMPLE_DURATION_MS + STIMULUS_X0_S,
  279. color='black', linestyle=':')
  280. plt.xlabel('Time since stimulus onset (s)')
  281. if signal == 'pupil':
  282. plt.ylim(2.5, 5.5)
  283. plt.ylabel('Pupil size (mm)')
  284. elif signal == 'gaze_x':
  285. plt.ylabel('Horizontal gaze position (z-score)')
  286. elif signal == 'gaze_y':
  287. plt.ylabel('Vertical gaze position (z-score)')
  288. plt.sca(ax2)
  289. tst.plot(dm, f'{signal}_constrict', 'dataset', x0=CONSTRICT_X0_S,
  290. sampling_freq=SAMPLING_FREQ,
  291. legend_kwargs={'loc': 'upper right', 'frameon': False})
  292. plt.axvline(0, color='black', linestyle=':')
  293. if signal == 'pupil':
  294. plt.ylim(2.5, 5.5)
  295. plt.xlabel('Time relative to max. constriction (s)')
  296. plt.tight_layout()
  297. plt.savefig(get_output_dir('png') / f'{signal}-constriction.png')
  298. plt.savefig(get_output_dir('svg') / f'{signal}-constriction.svg')
  299. plt.show()
  300. """
  301. Visualize ERG locked to stimulus onset
  302. """
  303. fig, ax = plt.subplots(1, 1, figsize=FIG_SINGLE)
  304. tst.plot(dm, 'erg', 'dataset', x0=STIMULUS_X0_S,
  305. sampling_freq=SAMPLING_FREQ,
  306. legend_kwargs={'loc': 'upper right', 'frameon': False})
  307. plt.axvline(0, color='black', linestyle=':')
  308. plt.xlabel('Time since stimulus onset (s)')
  309. plt.axvline(.001 * dm.t_max_constrict.mean * SAMPLE_DURATION_MS, color='black',
  310. linestyle=':')
  311. plt.ylabel('ERG (µV)')
  312. plt.tight_layout()
  313. plt.savefig(get_output_dir('png') / 'erg-stimulus-locked.png')
  314. plt.savefig(get_output_dir('svg') / 'erg-stimulus-locked.svg')
  315. plt.show()
  316. """
  317. Visualize ERG separately for upper and lower electrodes
  318. """
  319. constrict_time_s = PLOT_TIME_MS / 1000
  320. stimulus_time_s = (np.arange(dm.erg_upper.depth) / SAMPLING_FREQ
  321. + STIMULUS_X0_S)
  322. fig, axes = plt.subplots(1, 2, figsize=FIG_DOUBLE)
  323. plt.sca(axes[0])
  324. plt.plot(stimulus_time_s, dm.erg_upper.mean,
  325. color=COLOR_UPPER, label='Upper')
  326. plt.plot(stimulus_time_s, dm.erg_lower.mean,
  327. color=COLOR_LOWER, label='Lower')
  328. plt.axvline(0, color='black', linestyle=':')
  329. plt.xlabel('Time since stimulus onset (s)')
  330. plt.ylabel('ERG (µV)')
  331. plt.legend(frameon=False)
  332. plt.title('Stimulus-locked')
  333. plt.sca(axes[1])
  334. plt.plot(constrict_time_s, dm.erg_upper_constrict.mean,
  335. color=COLOR_UPPER, label='Upper (real)')
  336. plt.plot(constrict_time_s, dm.erg_upper_constrict_shuffle.mean,
  337. color=COLOR_UPPER, linestyle=':', label='Upper (shuffled)')
  338. plt.plot(constrict_time_s, dm.erg_lower_constrict.mean,
  339. color=COLOR_LOWER, label='Lower (real)')
  340. plt.plot(constrict_time_s, dm.erg_lower_constrict_shuffle.mean,
  341. color=COLOR_LOWER, linestyle=':', label='Lower (shuffled)')
  342. plt.axvline(0, color='black', linestyle=':')
  343. plt.xlabel('Time relative to max. constriction (s)')
  344. plt.ylabel('ERG (µV)')
  345. plt.legend(frameon=False, fontsize=8)
  346. plt.title('Constriction-locked')
  347. plt.tight_layout()
  348. plt.savefig(get_output_dir('png') / 'upper-lower-electrodes.png')
  349. plt.savefig(get_output_dir('svg') / 'upper-lower-electrodes.svg')
  350. plt.show()
  351. """
  352. Visualize occipital ERP
  353. """
  354. fig, axes = plt.subplots(1, 2, figsize=FIG_DOUBLE)
  355. plt.sca(axes[0])
  356. plt.plot(stimulus_time_s, dm.erp_occipital.mean, color=COLOR_REAL)
  357. plt.axvline(0, color='black', linestyle=':')
  358. plt.xlabel('Time since stimulus onset (s)')
  359. plt.ylabel('ERP (µV)')
  360. plt.title('Stimulus-locked occipital ERP')
  361. plt.sca(axes[1])
  362. plt.plot(constrict_time_s, dm.erp_occipital_constrict.mean,
  363. color=COLOR_REAL, label='Real')
  364. plt.plot(constrict_time_s, dm.erp_occipital_constrict_shuffle.mean,
  365. color=COLOR_PERMUTED, linestyle=':', label='Shuffled')
  366. plt.axvline(0, color='black', linestyle=':')
  367. plt.xlabel('Time relative to max. constriction (s)')
  368. plt.ylabel('ERP (µV)')
  369. plt.legend(frameon=False)
  370. plt.title('Constriction-locked occipital ERP')
  371. plt.tight_layout()
  372. plt.savefig(get_output_dir('png') / 'occipital-erp.png')
  373. plt.savefig(get_output_dir('svg') / 'occipital-erp.svg')
  374. plt.show()
  375. """
  376. # Figure 2: Main results (four-panel composite)
  377. """
  378. fig = plt.figure(figsize=(6.27, 9))
  379. gs = fig.add_gridspec(3, 2, height_ratios=[0.8, 1, .8], hspace=0.4, wspace=0)
  380. # --- Panel a: Constriction-locked ERG (all datasets) ---------------------
  381. ax_a = fig.add_subplot(gs[0, :])
  382. plt.sca(ax_a)
  383. xdm = dm[dm.subject_nr, dm.dataset, dm.condition, dm.erg,
  384. dm.erg_constrict, dm.t_max_constrict, dm.v_max_constrict]
  385. print('Running main permutation test')
  386. run_permutation_test(
  387. xdm,
  388. shuffle_by=[xdm.subject_nr, xdm.dataset, xdm.condition],
  389. )
  390. ax_a.set_title('a) Retinal activity (ERG) locked to pupil constriction (all datasets)',
  391. loc='left')
  392. # --- Panel b: Split by maximum constriction velocity ---------------------
  393. ax_c = fig.add_subplot(gs[1, 0])
  394. plt.sca(ax_c)
  395. tst.plot(dm, 'erg_constrict', hue_factor='bin_max_constrict', hues='jet',
  396. x0=CONSTRICT_X0_S * 1000, sampling_freq=SAMPLING_FREQ / 1000)
  397. ax_c.axvline(0, color='black', linestyle=':')
  398. ax_c.set_xlabel('Time relative to max. constriction (ms)')
  399. ax_c.set_ylabel('ERG (µV)')
  400. ax_c.set_title('b) Split by maximum constriction velocity', loc='left')
  401. # --- Panel c: 3×3 grid split by dataset ---------------------------------
  402. gs_b = gs[1, 1].subgridspec(3, 3, wspace=0, hspace=0)
  403. xdm = dm[dm.subject_nr, dm.dataset, dm.condition, dm.erg,
  404. dm.erg_constrict, dm.t_max_constrict, dm.v_max_constrict]
  405. axes_b = []
  406. for i, (dataset, ddm) in enumerate(ops.split(xdm.dataset)):
  407. print(f'Running permutation test for {dataset}')
  408. ax = fig.add_subplot(gs_b[i // 3, i % 3])
  409. plt.sca(ax)
  410. run_permutation_test(
  411. ddm,
  412. shuffle_by=[ddm.subject_nr, ddm.condition],
  413. ylabel='',
  414. )
  415. ax.set_xlabel('')
  416. ax.set_ylabel('')
  417. ax.set_xticks([])
  418. ax.set_yticks([])
  419. legend = ax.get_legend()
  420. if legend is not None:
  421. legend.remove()
  422. ax.text(0.05, 0.95, dataset, transform=ax.transAxes,
  423. fontsize=7, va='top', ha='left', fontweight='bold',
  424. bbox=dict(boxstyle='round,pad=0.2', facecolor='white',
  425. edgecolor='none', alpha=0.7))
  426. axes_b.append(ax)
  427. axes_b[0].set_title('c) Split by dataset', loc='left')
  428. # --- Panel d: Constriction-locked occipital ERP (all datasets) ---------------------
  429. ax_d = fig.add_subplot(gs[2, :])
  430. plt.sca(ax_d)
  431. xdm = dm[dm.subject_nr, dm.dataset, dm.condition, dm.erp_occipital,
  432. dm.erp_occipital_constrict, dm.t_max_constrict,
  433. dm.v_max_constrict]
  434. run_permutation_test(
  435. xdm,
  436. shuffle_by=[xdm.subject_nr, xdm.dataset, xdm.condition],
  437. col='erp_occipital_constrict',
  438. ylabel='ERP (µV)',
  439. )
  440. ax_d.set_title('d) Visual-cortex activity (occipital ERP) locked to pupil constriction',
  441. loc='left')
  442. plt.savefig(get_output_dir('png') / 'figure-2.png', dpi=300, bbox_inches='tight')
  443. plt.savefig(get_output_dir('svg') / 'figure-2.svg', bbox_inches='tight')
  444. plt.show()
  445. """
  446. # Figure 3: Stimulus-locked ERG by dataset and by intensity
  447. """
  448. mean_t_max_constrict = dm.t_max_constrict.mean * SAMPLE_DURATION_MS + STIMULUS_X0_S * 1000
  449. fig = plt.figure(figsize=(6.27, 3))
  450. gs = fig.add_gridspec(1, 2, wspace=0)
  451. # Left panel: ERG by dataset
  452. ax1 = fig.add_subplot(gs[0, 0])
  453. plt.sca(ax1)
  454. ax1.axvline(0, color='black', linestyle=':')
  455. ax1.axhline(0, color='black', linestyle=':')
  456. ax1.axvline(mean_t_max_constrict, color='black', linestyle=':')
  457. tst.plot(dm, 'erg', 'dataset', x0=STIMULUS_X0_S * 1000,
  458. sampling_freq=SAMPLING_FREQ / 1000,
  459. legend_kwargs={'loc': 'upper right', 'frameon': False})
  460. ax1.set_xlabel('Time since stimulus onset (ms)')
  461. ax1.set_ylabel('ERG (µV)')
  462. ax1.set_title('a) Retinal activity (ERG) locked to stimulus', loc='left')
  463. ax1.set_ylim(-1.3e-5, 1e-5)
  464. # Right panel: ERG by intensity (original dataset only)
  465. ax2 = fig.add_subplot(gs[0, 1])
  466. plt.sca(ax2)
  467. odm = dm.dataset == 'original'
  468. tst.plot(odm, 'erg', 'intensity_cdm2', x0=STIMULUS_X0_S * 1000,
  469. sampling_freq=SAMPLING_FREQ / 1000, hues='jet',
  470. legend_kwargs={'loc': 'upper right', 'frameon': False})
  471. ax2.set_xlim(0, 250)
  472. ax2.set_ylim(-1.3e-5, 1e-5)
  473. ax2.axhline(0, color='black', linestyle=':')
  474. ax2.set_xlabel('Time since stimulus onset (ms)')
  475. ax2.set_ylabel('')
  476. ax2.set_yticks([])
  477. ax2.set_title('b) ERG as a function of stimulus intensity', loc='left')
  478. plt.tight_layout()
  479. plt.savefig(get_output_dir('png') / 'figure-3.png', dpi=300, bbox_inches='tight')
  480. plt.savefig(get_output_dir('svg') / 'figure-3.svg', bbox_inches='tight')
  481. plt.show()
  482. """
  483. # Figure 4: Pupil size and constriction timing by dataset
  484. """
  485. fig = plt.figure(figsize=(6.27, 3))
  486. gs = fig.add_gridspec(1, 2, wspace=0)
  487. # Left panel: Pupil size by dataset
  488. ax1 = fig.add_subplot(gs[0, 0])
  489. plt.sca(ax1)
  490. ax1.axvline(mean_t_max_constrict, color='black', linestyle=':')
  491. tst.plot(dm, 'pupil', 'dataset', x0=STIMULUS_X0_S * 1000,
  492. sampling_freq=SAMPLING_FREQ / 1000,
  493. legend_kwargs={'loc': 'upper right', 'frameon': False})
  494. ax1.set_xlim(0, 1500)
  495. ax1.set_xlabel('Time since stimulus onset (ms)')
  496. ax1.set_ylabel('Pupil size (mm)')
  497. ax1.set_title('a) Pupil size locked to stimulus', loc='left')
  498. # Right panel: Distribution of constriction timing by dataset
  499. ax2 = fig.add_subplot(gs[0, 1])
  500. plt.sca(ax2)
  501. palette = plt.cm.Dark2.colors # Get Dark2 palette colors
  502. for i, (dataset, ddm) in enumerate(ops.split(dm.dataset)):
  503. vals = (np.array(ddm.t_max_constrict) - T0_SAMPLE) * SAMPLE_DURATION_MS
  504. sns.kdeplot(vals, label=dataset, ax=ax2, color=palette[i % len(palette)])
  505. ax2.axvline(mean_t_max_constrict, color='black', linestyle=':')
  506. ax2.set_xlim(0, 1500)
  507. ax2.set_xlabel('Max. constriction time (ms)')
  508. ax2.set_ylabel('Density')
  509. ax2.set_yticks([])
  510. ax2.yaxis.set_label_position("right") # Move y-label to the right
  511. ax2.legend(frameon=False)
  512. ax2.set_title('b) Timepoints of max. pupil constriction',
  513. loc='left')
  514. plt.tight_layout()
  515. plt.savefig(get_output_dir('png') / 'figure-4.png', dpi=300, bbox_inches='tight')
  516. plt.savefig(get_output_dir('svg') / 'figure-4.svg', bbox_inches='tight')
  517. plt.show()
  518. """
  519. Visualize all EEG channels, and the ERG for the datasets with full EEG data.
  520. """
  521. xdm = dm.has_eeg == 1
  522. xdm = xdm[xdm.subject_nr, xdm.dataset, xdm.condition, xdm.t_max_constrict,
  523. xdm.v_max_constrict, xdm.erp]
  524. effect_sizes = {}
  525. for ch in EEG_CHANNELS:
  526. plt.figure(figsize=FIG_SINGLE)
  527. xdm[f'erp_{ch}'] = xdm.erp[:, ch]
  528. locked, zero_point = srs.lock(xdm[f'erp_{ch}'], lock=xdm.t_max_constrict)
  529. xdm[f'erp_{ch}_constrict'] = locked[
  530. :, zero_point + PLOT_WINDOW[0]:zero_point + PLOT_WINDOW[1]
  531. ]
  532. plt.title(f'Constriction-locked ERP ({ch})')
  533. result = run_permutation_test(
  534. xdm,
  535. shuffle_by=[xdm.subject_nr, xdm.dataset, xdm.condition],
  536. col=f'erp_{ch}_constrict',
  537. ylabel='ERP (µV)'
  538. )
  539. effect_sizes[ch] = result['effect_size']
  540. del xdm[f'erp_{ch}']
  541. del xdm[f'erp_{ch}_constrict']
  542. plt.tight_layout()
  543. plt.savefig(get_output_dir('png/channels') / f'permutation-erp-{ch}.png')
  544. plt.savefig(get_output_dir('svg/channels') / f'permutation-erp-{ch}.svg')
  545. plt.show()
  546. plt.figure(figsize=FIG_SINGLE)
  547. xdm = dm.has_eeg == 1
  548. xdm = xdm[xdm.subject_nr, xdm.dataset, xdm.condition, xdm.t_max_constrict,
  549. xdm.v_max_constrict, xdm.erg, xdm.erg_constrict]
  550. plt.title('Constriction-locked ERG (datasets with EEG)')
  551. result = run_permutation_test(
  552. xdm,
  553. shuffle_by=[xdm.subject_nr, xdm.dataset, xdm.condition]
  554. )
  555. effect_sizes['erg'] = result['effect_size']
  556. plt.tight_layout()
  557. plt.savefig(get_output_dir('png/channels') / 'permutation-erg-with-eeg.png')
  558. plt.savefig(get_output_dir('svg/channels') / 'permutation-erg-with-eeg.svg')
  559. plt.show()
  560. """
  561. Create topomap of effect sizes.
  562. """
  563. for winstart in range(0, len(effect_sizes['erg']), TOPOMAP_WINLEN):
  564. t0 = (winstart + PLOT_WINDOW[0]) * SAMPLE_DURATION_MS
  565. t1 = t0 + TOPOMAP_WINLEN * SAMPLE_DURATION_MS
  566. fig, ax = plot_effect_size_topomap(
  567. effect_sizes,
  568. title=f'Constriction-locked effect sizes ({t0:.0f}–{t1:.0f}ms)',
  569. show=False, window=(winstart, winstart + TOPOMAP_WINLEN),
  570. vmin=0, vmax=14)
  571. plt.savefig(get_output_dir('png/topomaps') / f'topomap-{winstart}.png')
  572. plt.savefig(get_output_dir('svg/topomaps') / f'topomap-{winstart}.svg')
  573. plt.show()

analyze.py, no license · at the source

Overview

  1. Department of Psychology, University of Groningen, Groningen, the Netherlands
  2. Faculty of Science and Engineering, University of Groningen, Groningen, the Netherlands
Institutions: University of Groningen (Netherlands)
Journal: Psychophysiology, volume 63, issue 7, article e70362
Dates: received 6 May 2026; accepted 15 July 2026; published online 22 July 2026; in print July 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1111/psyp.70362 · PMID 42487203 · PMCID PMC13392059 · OpenAlex W7170147802
Open access: hybrid, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: EEG (modality), human (organism)
Methods: Spectral & time-frequency, Connectivity, Preprocessing, Physiology & signal measures
MeSH: Pupil*, Retina*, Visual Cortex*, Visual Perception*, Adult, Electroencephalography, Female, Humans, Male, Photic Stimulation, Reflex, Pupillary, Young Adult (* major topic)
Topic: Retinal Development and Disorders (Ophthalmology, Medicine), according to OpenAlex
Funding: Dutch Research Council (NWO) (VI.Vidi.191.045); The Dutch Organization for Scientific Research (NWO) (VI.Vidi.191.045)
Citations: not cited yet (Europe PMC); 45 references in the paper

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

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Languages: Python (3)
Size: 14 files, 3 scripts
Software Heritage: not checked
Found in: “Data Availability Statement”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Matplotlib (3 files), NumPy (3 files), SciPy (2 files), MNE-Python (1 file), seaborn (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
  • 27 September 2026: the link answers (HTTP 200)
3 files
At the source: osf.io/2u6jv/

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://osf.io/2u6jv/.

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://doi.org/10.1111/psyp.70362

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/psyp.70362},
url = {https://doi.org/10.1111/psyp.70362},
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/07/01
VL - 63
IS - 7
SP - e70362
SN - 0048-5772
PB - Wiley
DO - 10.1111/psyp.70362
UR - https://doi.org/10.1111/psyp.70362
LA - en
ER -

CSL-JSON

{
"id": "10.1111/psyp.70362",
"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": "Psychophysiology",
"volume": "63",
"issue": "7",
"page": "e70362",
"DOI": "10.1111/psyp.70362",
"PMID": "42487203",
"PMCID": "PMC13392059",
"ISSN": "0048-5772",
"publisher": "Wiley",
"URL": "https://doi.org/10.1111/psyp.70362",
"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: Psychophysiology
In 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: Psychophysiology
In 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 physiology
In 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 methods
In 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 biology
In 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 reports
In 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 reports
In 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 methods
In 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: Psychophysiology
In 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.

Add the badge to the code's README

OSCR: the badge of this paper

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 -->
[![OSCR](https://openscicode.org/badge/doi/10.1111/psyp.70362.svg)](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:end
HTML
<!-- 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.