OSCR

The anterior cingulate cortex modulates pupil-linked arousal.

Code ↔ Paper

4 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 4 matches
  1. [1] § MATERIALS AND METHODS › Pupil event and facial movement event classification ↔ 4.ipynb, lines 217–367 · score 0.68 · Pupil trace, pupil dilation events, Event amplitude, lowest, median, facial movement
  2. [2] § MATERIALS AND METHODS › Pupil event and facial movement event classification ↔ 7.ipynb, lines 36–188 · score 0.68 · Pupil trace, pupil dilation events, Event amplitude, lowest, median, facial movement
  3. [3] § RESULTS › Pupil-linked autonomic arousal is associated with facial movements and locomotion ↔ 1.ipynb, lines 528–565 · score 0.57 · pupil face correlation, median filter, smooth, Facial movement, speed, frame
  4. [4] § MATERIALS AND METHODS › Heart rate measurement ↔ S1.ipynb, lines 97–124 · score 0.51 · Heart rate, scalar, mapped, error

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 1,046 lines · 42 KB · CC-BY-4.0 · 1 match

  1. # %%
  2. import numpy as np
  3. from scipy import stats
  4. import seaborn as sns
  5. import matplotlib.pyplot as plt
  6. import pandas as pd
  7. from scipy.signal import find_peaks, peak_widths,resample,correlate, correlation_lags,peak_prominences,resample,butter, lfilter, freqz,medfilt
  8. from matplotlib import rcParams
  9. from scipy.stats import ttest_ind,ttest_rel,zscore
  10. params = {
  11. "font.family" : "Arial",
  12. 'pdf.fonttype' : 42,
  13. 'axes.labelsize': 10,
  14. 'axes.titlesize': 11,
  15. 'axes.linewidth': 0.5,
  16. 'xtick.labelsize':9,
  17. 'xtick.major.width':0.5,
  18. 'ytick.major.width':0.5,
  19. 'ytick.labelsize':9,
  20. 'axes.spines.top':False,
  21. 'axes.spines.right':False
  22. }
  23. rcParams['figure.figsize'] = 21.7,8.27
  24. rcParams.update(params)
  25. def format_ax(ax,xlim,ylim,xspace,yspace):
  26. ax.set_xticks(np.arange(xlim[0],xlim[1]+ xspace,xspace))
  27. ax.set_yticks(np.arange(ylim[0],ylim[1]+ yspace,yspace))
  28. ax.set(ylim=(ylim[0], ylim[1]))
  29. ax.set(xlim=(xlim[0], xlim[1]))
  30. # %%
  31. ### Functions to low pass filter pupil and face data
  32. ###low pass filter pupil
  33. def filter_pupil(pupil,order = 1,cutoff = 1,fs = 20):
  34. def butter_lowpass(cutoff, fs, order=5):
  35. return butter(order, cutoff, fs=fs, btype='low', analog=False)
  36. def butter_lowpass_filter(data, cutoff, fs, order=5):
  37. b, a = butter_lowpass(cutoff, fs, order=order)
  38. y = lfilter(b, a, data)
  39. return y
  40. return butter_lowpass_filter(pupil, cutoff, fs, order)
  41. ###low pass filter face
  42. def filter_face(face,order = 1,cutoff = 0.1,fs = 20):
  43. def butter_lowpass(cutoff, fs, order=5):
  44. return butter(order, cutoff, fs=fs, btype='low', analog=False)
  45. def butter_lowpass_filter(data, cutoff, fs, order=5):
  46. b, a = butter_lowpass(cutoff, fs, order=order)
  47. y = lfilter(b, a, data)
  48. return y
  49. return butter_lowpass_filter(face, cutoff, fs, order)
  50. # %%
  51. ### get face aligned events
  52. def get_face_events(id,date):
  53. id = id
  54. date = date
  55. #face_path = f"/Users/nithik/Library/CloudStorage/Box-Box/HUDA_LAB_DATA/ethanol_data/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  56. #path = f"/Users/nithik/Library/CloudStorage/Box-Box/HUDA_LAB_DATA/ethanol_data/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  57. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  58. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  59. df = pd.read_csv(path)
  60. pupil = np.array(df["Pupil Size"])
  61. time = np.array(df["Time"])
  62. speed = np.array(df["Running Speed"])
  63. speed[0] = 0
  64. dff = np.array(df["dFF"])
  65. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  66. ###Onset detection alogrithm
  67. filter = filter_face(face) ###first apply low pass filter to face trace
  68. def groupSequence(x):
  69. it = iter(x)
  70. prev, res = next(it), []
  71. while prev is not None:
  72. start = next(it, None)
  73. if start and start > prev:
  74. res.append(prev)
  75. elif res:
  76. yield list(res + [prev])
  77. res = []
  78. prev = start
  79. regions = list(groupSequence(filter))
  80. corrected_regions = [region for region in regions if len(region) >=15 ] ###only include regions that are >750ms
  81. corrected_regions = [region for region in corrected_regions if region[0]<np.median(filter) ] ###only include onsets that occur below z = median
  82. region_ix = [[np.where(filter == val)[0][0] for val in region] for region in corrected_regions] ### get indices for each region
  83. ##join regions that are near eachother
  84. new = []
  85. for i,first in enumerate(region_ix):
  86. if i < len(region_ix)-1:
  87. second = region_ix[i + 1]
  88. end = first[-1]
  89. start = second[0]
  90. if first[0] - region_ix[i - 1][-1]>20:
  91. if start-end<= 20:
  92. #print(first[0]/20,second[0]/20)
  93. new.append(first + second)
  94. else:
  95. new.append(first)
  96. region_ix = new
  97. corrected_regions = [filter[region[0]:region[-1]] for region in region_ix]
  98. new = []
  99. for i,first in enumerate(region_ix):
  100. if i < len(region_ix)-1:
  101. second = region_ix[i + 1]
  102. end = first[-1]
  103. start = second[0]
  104. if first[0] - region_ix[i - 1][-1]>10:
  105. if start-end<= 10:
  106. new.append(first + second)
  107. else:
  108. new.append(first)
  109. region_ix = new
  110. corrected_regions = [filter[region[0]:region[-1]] for region in region_ix]
  111. onsets_ix = [region[0] for region in region_ix]
  112. ###get offsets and durations for pupil event
  113. offset_ix = []
  114. durations = []
  115. for i,(region,index) in enumerate(zip(corrected_regions,region_ix)):
  116. if i < len(region_ix)-1:
  117. start = index[-1] ###end of region
  118. end = region_ix[i+1][0] ### start of next region
  119. onset_y = region[0]
  120. offsets = np.where(filter[start:end] <= onset_y) ###find ix of first point that goes below onset
  121. if len(offsets[0]) == 0: ###if it never goes below onset then use lowest value
  122. offset = start + np.argmin(filter[start:end])
  123. else:
  124. offset = start + offsets[0][0]
  125. offset_ix.append(offset)
  126. durations.append((offset-index[0])/20)
  127. ###handle last face event
  128. start = region_ix[-1][-1]
  129. end = 36000
  130. onset_y = corrected_regions[-1][0]
  131. offsets = np.where(filter[start:end] <= onset_y)
  132. if len(offsets[0]) == 0:
  133. offset = end-1
  134. else:
  135. offset = start + np.argmin(filter[start:end])
  136. offset_ix[-1] = offset
  137. durations[-1] = (offset-region_ix[-1][0])/20
  138. ###get face event amplitudes
  139. amplitudes = []
  140. amplitudes_ix = []
  141. ###change to align to raw peak
  142. for on,off in zip(onsets_ix,offset_ix):
  143. #print(on,off)
  144. amplitudes.append(max(filter[on:off])-filter[on])
  145. amplitudes_ix.append(on + np.argmax(face[on:off]))
  146. ###get face event slopes
  147. slopes = []
  148. for region in corrected_regions:
  149. run = len(region)/20
  150. rise = region[-1]-region[0]
  151. slopes.append(rise/run)
  152. ###get dff data
  153. aucs = []
  154. peak_dffs = []
  155. mean_dffs = []
  156. for onset,offset in zip(onsets_ix,offset_ix):
  157. baseline = np.mean(dff[onset-40:onset-10])
  158. peak_dffs.append(max(dff[onset:offset]) - np.mean(dff[onset-30:onset]))
  159. mean_dffs.append(np.mean(dff[onset:offset])- np.mean(dff[onset-20:onset]))
  160. ###create dictionary
  161. events_dict = {"durations" :durations,
  162. "amplitudes": amplitudes,
  163. "slopes" : slopes,
  164. "onsets" : onsets_ix,
  165. "offsets" : offset_ix,
  166. "peak_ix" : amplitudes_ix,
  167. "ID" : [id] * len(durations),
  168. "Date" : [date] * len(durations),
  169. "peak_dff" : peak_dffs,
  170. "mean_dff" : mean_dffs,
  171. }
  172. return pd.DataFrame.from_dict(events_dict)
  173. # %%
  174. ### Function to extract pupil dilation events
  175. def get_pupil_events(id,date):
  176. id = id
  177. date = date
  178. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  179. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  180. df = pd.read_csv(path)
  181. pupil = np.array(df["Pupil Size"])
  182. time = np.array(df["Time"])
  183. speed = np.array(df["Running Speed"])
  184. speed[0] = 0
  185. dff = np.array(df["dFF"])
  186. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  187. ###Onset detection alogrithm
  188. filter = filter_pupil(pupil) ###first apply low pass filter to pupil trace
  189. def groupSequence(x):
  190. it = iter(x)
  191. prev, res = next(it), []
  192. while prev is not None:
  193. start = next(it, None)
  194. if start and start > prev:
  195. res.append(prev)
  196. elif res:
  197. yield list(res + [prev])
  198. res = []
  199. prev = start
  200. regions = list(groupSequence(filter))
  201. corrected_regions = [region for region in regions if len(region) >=15 ] ###only include regions that are >750ms
  202. corrected_regions = [region for region in corrected_regions if region[0]<np.median(filter) ] ###only include onsets that occur below z = median
  203. region_ix = [[np.where(filter == val)[0][0] for val in region] for region in corrected_regions] ### get indices for each region
  204. ##join regions that are near eachother
  205. new = []
  206. for i,first in enumerate(region_ix):
  207. if i < len(region_ix)-1:
  208. second = region_ix[i + 1]
  209. end = first[-1]
  210. start = second[0]
  211. if first[0] - region_ix[i - 1][-1]>20:
  212. if start-end<= 20:
  213. #print(first[0]/20,second[0]/20)
  214. new.append(first + second)
  215. else:
  216. new.append(first)
  217. region_ix = new
  218. corrected_regions = [filter[region[0]:region[-1]] for region in region_ix]
  219. new = []
  220. for i,first in enumerate(region_ix):
  221. if i < len(region_ix)-1:
  222. second = region_ix[i + 1]
  223. end = first[-1]
  224. start = second[0]
  225. if first[0] - region_ix[i - 1][-1]>10:
  226. if start-end<= 10:
  227. #print(first[0]/20,second[0]/20)
  228. new.append(first + second)
  229. else:
  230. new.append(first)
  231. region_ix = new
  232. corrected_regions = [filter[region[0]:region[-1]] for region in region_ix]
  233. onsets_ix = [region[0] for region in region_ix]
  234. ###get offsets and durations for pupil event
  235. offset_ix = []
  236. durations = []
  237. for i,(region,index) in enumerate(zip(corrected_regions,region_ix)):
  238. if i < len(region_ix)-1:
  239. start = index[-1] ###end of region
  240. end = region_ix[i+1][0] ### start of next region
  241. onset_y = region[0]
  242. offsets = np.where(filter[start:end] <= onset_y) ###find ix of first point that goes below onset
  243. if len(offsets[0]) == 0: ###if it never goes below onset then use lowest value
  244. offset = start + np.argmin(filter[start:end])
  245. else:
  246. offset = start + offsets[0][0]
  247. offset_ix.append(offset)
  248. durations.append((offset-index[0])/20)
  249. ###handle last pupil event
  250. start = region_ix[-1][-1]
  251. end = 36000
  252. onset_y = corrected_regions[-1][0]
  253. offsets = np.where(filter[start:end] <= onset_y)
  254. if len(offsets[0]) == 0:
  255. offset = end-1
  256. else:
  257. offset = start + np.argmin(filter[start:end])
  258. offset_ix[-1] = offset
  259. durations[-1] = (offset-region_ix[-1][0])/20
  260. ###get pupil event amplitudes
  261. amplitudes = []
  262. amplitudes_ix = []
  263. for on,off in zip(onsets_ix,offset_ix):
  264. #print(on,off)
  265. amplitudes.append(max(filter[on:off])-filter[on])
  266. amplitudes_ix.append(on + np.argmax(filter[on:off]))
  267. ###get pupil event slopes
  268. slopes = []
  269. for region in corrected_regions:
  270. run = len(region)/20
  271. rise = region[-1]-region[0]
  272. slopes.append(rise/run)
  273. ###get dff data
  274. aucs = []
  275. peak_dffs = []
  276. mean_dffs = []
  277. for onset,offset in zip(onsets_ix,offset_ix):
  278. peak_dffs.append(max(dff[onset:offset]) - np.mean(dff[onset-30:onset]))
  279. aucs.append(np.trapz(dff[onset:offset]))
  280. mean_dffs.append(np.mean(dff[onset:offset])- np.mean(dff[onset-20:onset]))
  281. ###create dictionary
  282. events_dict = {"durations" :durations,
  283. "amplitudes": amplitudes,
  284. "slopes" : slopes,
  285. "onsets" : onsets_ix,
  286. "offsets" : offset_ix,
  287. "peak_ix" : amplitudes_ix,
  288. "ID" : [id] * len(durations),
  289. "Date" : [date] * len(durations),
  290. "peak_dff" : peak_dffs,
  291. "aucs" : aucs,
  292. "mean_dff" : mean_dffs,
  293. }
  294. return pd.DataFrame.from_dict(events_dict)
  295. # %%
  296. ### Function to align trials to event onsets, adapted from https://www.tdt.com/docs/sdk/offline-data-analysis/offline-data-python/examples/LickBouts/#time-filter-around-lick-bout-epocs
  297. def trial_align(event_on,time,values,fps = 20,pre = 2, post = 10):
  298. TRANGE = [-pre*np.floor(fps), post*np.floor(fps)]
  299. trial_snips = []
  300. array_ind = []
  301. pre_stim = []
  302. post_stim = []
  303. for on in event_on:
  304. # If the bout cannot include pre-time seconds before event, make zero
  305. if on < pre:
  306. pass
  307. else:
  308. # find first time index after bout onset
  309. array_ind.append(np.where(time > on)[0][0])
  310. # find index corresponding to pre and post stim durations
  311. pre_stim.append(array_ind[-1] + TRANGE[0])
  312. post_stim.append(array_ind[-1] + TRANGE[1])
  313. trial_snips.append(values[int(pre_stim[-1]):int(post_stim[-1])])
  314. # If some snippets are less than max length, add nans to end of array
  315. max1 = np.max([np.size(x) for x in trial_snips])
  316. for i,x in enumerate(trial_snips):
  317. if np.size(x) < max1:
  318. trial_snips[i] = np.concatenate((trial_snips[i],np.full((max1-np.size(trial_snips[i])), np.nan)))
  319. mean_trial_snips = np.mean(trial_snips, axis=0)
  320. peri_time = np.linspace(1, len(mean_trial_snips), len(mean_trial_snips))/fps - pre
  321. return trial_snips,peri_time
  322. # %%
  323. ### Path to data. RENAME THIS TO YOUR PATH
  324. base_dir = "/Users/nithik/Library/CloudStorage/Box-Box/SAS-DLS-HudaLab/Nithik-SciAdv2026-alldata"
  325. # %%
  326. ### Get data for Fig4A
  327. id = "004116"
  328. date = "20230815"
  329. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  330. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  331. df = pd.read_csv(path)
  332. pupil = np.array(df["Pupil Size"])
  333. time = np.array(df["Time"])
  334. speed = zscore(np.array(df["Running Speed"]))
  335. dff = np.array(df["dFF"])
  336. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  337. df["Facial Movement"] = face
  338. df["Running Speed"] = speed
  339. events = get_pupil_events(id,date)
  340. # %%
  341. ### Plot Fig4A
  342. ax2,(ax1,ax2,ax4) = plt.subplots(3,figsize = (20,10))
  343. onsets = [on/20 for on in events["onsets"]]
  344. sns.lineplot(data = df, x = "Time", y = "Pupil Size", ax = ax1,color = "dodgerblue",linewidth = 1)
  345. sns.lineplot(data = df, x = "Time", y = "Facial Movement", ax = ax2,linewidth = 1,color = "purple")
  346. sns.lineplot(data = df, x = "Time", y = "dFF", ax = ax4,linewidth = 1,color = "green")
  347. x_start = 1510
  348. x_end = 1585
  349. x_space = 5
  350. ylim = [-4,4]
  351. for ax in [ax1,ax2,ax4]:
  352. ax.set_xlim(x_start,x_end)
  353. ax.set_xticks(np.arange(x_start,x_end + x_space,x_space))
  354. ax.set_ylim(ylim)
  355. ax1.set_ylim(-2,2)
  356. ax2.set_ylim(-2,5)
  357. ax1.spines[['bottom']].set_visible(False)
  358. ax1.spines[['left']].set_visible(False)
  359. ax1.get_xaxis().set_visible(False)
  360. ax1.get_yaxis().set_visible(False)
  361. ax2.spines[['bottom']].set_visible(False)
  362. ax2.spines[['left']].set_visible(False)
  363. ax2.get_xaxis().set_visible(False)
  364. ax2.get_yaxis().set_visible(False)
  365. ax4.spines[['bottom']].set_visible(False)
  366. ax4.spines[['left']].set_visible(False)
  367. ax4.get_xaxis().set_visible(False)
  368. ax4.get_yaxis().set_visible(False)
  369. ax1.plot([1540,1545], [1, 1],color = "black",linewidth = 1)
  370. ax1.plot([1512,1512], [0, 1],color = "dodgerblue",linewidth = 1)
  371. ax2.plot([1512,1512], [0, 2],color = "purple",linewidth = 1)
  372. ax4.plot([1512,1512], [0, 2],color = "green",linewidth = 1)
  373. # %%
  374. ### Get data for Fig4B
  375. id_date = {
  376. "004113":["20230808"],
  377. "004114":["20230808","20230815"],
  378. "004115":["20230804","20230808","20230815"],
  379. "004116":["20230804","20230808","20230815"],
  380. "004117":["20230804","20230808","20230815"],
  381. "004118":["20230804","20230808","20230815"]
  382. }
  383. df_list = []
  384. for id,dates in id_date.items():
  385. for date in dates:
  386. events = get_pupil_events(id,date)
  387. onsets = [on/20 for on in events["onsets"]] ###get pupil onsets
  388. onsets_ix = events["onsets"]
  389. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  390. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  391. df = pd.read_csv(path)
  392. pupil = filter_pupil(np.array(df["Pupil Size"]))
  393. time = np.array(df["Time"])
  394. speed = zscore(np.array(df["Running Speed"]))
  395. dff = np.array(df["dFF"])
  396. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  397. onsets = [time[on] for on in events["onsets"]]
  398. dil_matrix,dil_times = trial_align(onsets,time,pupil,fps = 20,pre = 2, post = 10 )
  399. trial_matrix,trial_times = trial_align(onsets,time,dff,fps = 20,pre = 2, post = 10)
  400. face_matrix,face_times = trial_align(onsets,time,face,fps = 20,pre = 2, post = 10)
  401. for j,trial in enumerate(dil_matrix):
  402. baseline = np.mean(pupil[onsets_ix[j] - 40:onsets_ix[j] - 10])
  403. trial = trial - baseline
  404. for i,Time in enumerate(dil_times):
  405. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "Pupil","ID" : id, "Date": date}
  406. df_list.append(new_dict)
  407. for j,trial in enumerate(trial_matrix):
  408. baseline = np.mean(dff[onsets_ix[j] - 40:onsets_ix[j] - 10])
  409. trial = trial - baseline
  410. for i,Time in enumerate(trial_times):
  411. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "dff","ID" : id, "Date": date}
  412. df_list.append(new_dict)
  413. for j,trial in enumerate(face_matrix):
  414. baseline = np.mean(face[onsets_ix[j] - 40:onsets_ix[j] - 10])
  415. trial = trial - baseline
  416. for i,Time in enumerate(face_times):
  417. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "Face","ID" : id, "Date": date}
  418. df_list.append(new_dict)
  419. pupil_align_df = pd.DataFrame.from_dict(df_list)
  420. # %%
  421. ### Plot Fig4B
  422. plt.figure(figsize = (1.5,1.2))
  423. ax = sns.lineplot(data = pupil_align_df.groupby(["ID","Time from Onset (s)","type"]).mean().reset_index(), x = "Time from Onset (s)", y = "value", hue = "type",errorbar = "se",palette= ["purple","dodgerblue","green"],legend= None,linewidth = 1)
  424. format_ax(ax,(-1,2),(-0.5,1.5),1,0.5)
  425. ax.set_xlabel("Time from dilation onset (s)")
  426. ax.set_ylabel('Z-Score')
  427. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  428. # %%
  429. ### Get data for Fig4C
  430. id_date = {
  431. "004113":["20230808"],
  432. "004114":["20230808","20230815"],
  433. "004115":["20230804","20230808","20230815"],
  434. "004116":["20230804","20230808","20230815"],
  435. "004117":["20230804","20230808","20230815"],
  436. "004118":["20230804","20230808","20230815"]
  437. }
  438. df_list = []
  439. for id,dates in id_date.items():
  440. for date in dates:
  441. events = get_face_events(id,date)
  442. onsets = [on/20 for on in events["onsets"]] ###get face onsets
  443. onsets_ix = events["onsets"]
  444. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  445. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  446. df = pd.read_csv(path)
  447. pupil = filter_pupil(np.array(df["Pupil Size"]))
  448. time = np.array(df["Time"])
  449. speed = zscore(np.array(df["Running Speed"]))
  450. dff = np.array(df["dFF"])
  451. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  452. dil_matrix,dil_times = trial_align(onsets,time,pupil,fps = 20,pre = 2, post = 10 )
  453. trial_matrix,trial_times = trial_align(onsets,time,dff,fps = 20,pre = 2, post = 10)
  454. face_matrix,face_times = trial_align(onsets,time,face,fps = 20,pre = 2, post = 10)
  455. for j,trial in enumerate(dil_matrix):
  456. baseline = np.mean(pupil[onsets_ix[j] - 40:onsets_ix[j] - 10])
  457. trial = trial - baseline
  458. for i,Time in enumerate(dil_times):
  459. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "Pupil","ID" : id, "Date": date}
  460. df_list.append(new_dict)
  461. for j,trial in enumerate(trial_matrix):
  462. baseline = np.mean(dff[onsets_ix[j] - 40:onsets_ix[j] - 10])
  463. trial = trial - baseline
  464. for i,Time in enumerate(trial_times):
  465. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "dff","ID" : id, "Date": date}
  466. df_list.append(new_dict)
  467. for j,trial in enumerate(face_matrix):
  468. baseline = np.mean(face[onsets_ix[j] - 40:onsets_ix[j] - 10])
  469. trial = trial - baseline
  470. for i,Time in enumerate(face_times):
  471. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "Face","ID" : id, "Date": date}
  472. df_list.append(new_dict)
  473. face_align_df = pd.DataFrame.from_dict(df_list)
  474. # %%
  475. ### Plot Fig4C
  476. plt.figure(figsize = (1.5,1.2))
  477. ax = sns.lineplot(data = face_align_df.groupby(["ID","Time from Onset (s)","type"]).mean().reset_index(), x = "Time from Onset (s)", y = "value", hue = "type",errorbar = "se",palette= ["purple","dodgerblue","green"],legend= None,linewidth = 1)
  478. format_ax(ax,(-1,2),(-0.5,1.5),1,0.5)
  479. ax.set_xlabel("Time from facial movement onset (s)")
  480. ax.set_ylabel('Z-Score')
  481. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  482. # %%
  483. ### Get data for Fig4D (Left)
  484. id_date = {
  485. "004113":["20230808"],
  486. "004114":["20230808","20230815"],
  487. "004115":["20230804","20230808","20230815"],
  488. "004116":["20230804","20230808","20230815"],
  489. "004117":["20230804","20230808","20230815"],
  490. "004118":["20230804","20230808","20230815"]
  491. }
  492. df_list = []
  493. for id,dates in id_date.items():
  494. for date in dates:
  495. events = get_pupil_events(id,date)
  496. onsets_ix = events["onsets"]
  497. amplitudes = events["amplitudes"]
  498. binned_amps = np.array(pd.qcut(amplitudes,q = 4,labels = [1,2,3,4]))
  499. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  500. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  501. df = pd.read_csv(path)
  502. pupil = filter_pupil(np.array(df["Pupil Size"]))
  503. time = np.array(df["Time"])
  504. speed = zscore((np.array(df["Running Speed"])))
  505. dff = np.array(df["dFF"])
  506. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  507. onsets = [time[on]for on in events["onsets"]] ###get pupil onsets
  508. dil_matrix,dil_times = trial_align(onsets,time,pupil,fps = 20,pre = 10, post = 10 )
  509. for j,trial in enumerate(dil_matrix):
  510. baseline = np.mean(pupil[onsets_ix[j] - 40:onsets_ix[j] - 10])
  511. trial = trial - baseline
  512. for i,Time in enumerate(dil_times):
  513. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "Pupil","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  514. df_list.append(new_dict)
  515. trial_matrix,trial_times = trial_align(onsets,time,dff,fps = 20,pre = 10, post = 10)
  516. for j,trial in enumerate(trial_matrix):
  517. baseline = np.mean(dff[onsets_ix[j] - 40:onsets_ix[j] - 10])
  518. trial = trial - baseline
  519. for i,Time in enumerate(trial_times):
  520. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "dff","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  521. df_list.append(new_dict)
  522. face_matrix,face_times = trial_align(onsets,time,face,fps = 20,pre = 10, post = 10)
  523. for j,trial in enumerate(face_matrix):
  524. baseline = np.mean(face[onsets_ix[j] - 40:onsets_ix[j] - 10])
  525. trial = trial - baseline
  526. for i,Time in enumerate(face_times):
  527. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "face","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  528. df_list.append(new_dict)
  529. pupil_onset_df = pd.DataFrame.from_dict(df_list)
  530. # %%
  531. ### Get data for Fig4D (Right)
  532. id_date = {
  533. "004113":["20230808"],
  534. "004114":["20230808","20230815"],
  535. "004115":["20230804","20230808","20230815"],
  536. "004116":["20230804","20230808","20230815"],
  537. "004117":["20230804","20230808","20230815"],
  538. "004118":["20230804","20230808","20230815"]
  539. }
  540. df_list = []
  541. for id,dates in id_date.items():
  542. for date in dates:
  543. events = get_pupil_events(id,date)
  544. onsets_ix = events["onsets"]
  545. amplitudes = events["amplitudes"]
  546. binned_amps = np.array(pd.qcut(amplitudes,q = 4,labels = [1,2,3,4]))
  547. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  548. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  549. df = pd.read_csv(path)
  550. pupil = filter_pupil(np.array(df["Pupil Size"]))
  551. time = np.array(df["Time"])
  552. speed = zscore((np.array(df["Running Speed"])))
  553. dff = np.array(df["dFF"])
  554. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  555. peaks = [time[ix] for ix in events["peak_ix"]] ### get pupil peaks
  556. dil_matrix,dil_times = trial_align(peaks,time,pupil,fps = 20,pre = 10, post = 10 )
  557. for j,trial in enumerate(dil_matrix):
  558. baseline = np.mean(pupil[onsets_ix[j] - 40:onsets_ix[j] - 10])
  559. trial = trial - baseline
  560. for i,Time in enumerate(dil_times):
  561. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "Pupil","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  562. df_list.append(new_dict)
  563. trial_matrix,trial_times = trial_align(peaks,time,dff,fps = 20,pre = 10, post = 10)
  564. for j,trial in enumerate(trial_matrix):
  565. baseline = np.mean(dff[onsets_ix[j] - 40:onsets_ix[j] - 10])
  566. trial = trial - baseline
  567. for i,Time in enumerate(trial_times):
  568. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "dff","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  569. df_list.append(new_dict)
  570. face_matrix,face_times = trial_align(peaks,time,face,fps = 20,pre = 10, post = 10)
  571. for j,trial in enumerate(face_matrix):
  572. baseline = np.mean(face[onsets_ix[j] - 40:onsets_ix[j] - 10])
  573. trial = trial - baseline
  574. for i,Time in enumerate(face_times):
  575. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "face","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  576. df_list.append(new_dict)
  577. pupil_peak_df = pd.DataFrame.from_dict(df_list)
  578. # %%
  579. ### Plot Fig4D (Top Left)
  580. plt.figure(figsize = (1.25,1))
  581. ax = sns.lineplot(data = pupil_onset_df.groupby(["ID","Time from Onset (s)","type","animal_amp_bin"]).mean().reset_index().query("type == 'Pupil'").query("animal_amp_bin == [1,4]"), x = "Time from Onset (s)", y = "value",errorbar = "se",hue = "animal_amp_bin",palette= ["cornflowerblue","darkblue"],legend = None,linewidth = 1)
  582. ax.xaxis.label.set_visible(False)
  583. ax.set_ylabel("Pupil size \n(z-scr)")
  584. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  585. format_ax(ax,(-0.5,0.5),(-0.5,3),0.5,0.5)
  586. # %%
  587. ### Plot Fig4D (Bottom Left)
  588. plt.figure(figsize = (1.25,1.25))
  589. ax = sns.lineplot(data = pupil_onset_df.groupby(["ID","Time from Onset (s)","type","animal_amp_bin"]).mean().reset_index().query("type == 'dff'").query("animal_amp_bin == [1,4]"), x = "Time from Onset (s)", y = "value",errorbar = "se",hue = "animal_amp_bin",palette= ["palegreen","darkgreen"],legend = None,linewidth = 1)
  590. ax.set_xlabel("Time from \nDilation Onset (s)")
  591. ax.set_ylabel("∆ F/F (z-scr)")
  592. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  593. format_ax(ax,(-0.5,0.5),(-0.5,2),0.5,0.5)
  594. # %%
  595. ### Plot Fig4D (Top Right)
  596. plt.figure(figsize = (1.25,1))
  597. ax = sns.lineplot(data = pupil_peak_df.groupby(["ID","Time from Onset (s)","type","animal_amp_bin"]).mean().reset_index().query("type == 'Pupil'").query("animal_amp_bin == [1,4]"), x = "Time from Onset (s)", y = "value",errorbar = "se",hue = "animal_amp_bin",palette= ["cornflowerblue","darkblue"],legend = None,linewidth = 1)
  598. ax.xaxis.label.set_visible(False)
  599. ax.set_ylabel("Pupil Size \n(z-scr)")
  600. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  601. format_ax(ax,(-0.5,1),(-0.5,3),0.5,0.5)
  602. ax.spines[['left']].set_visible(False)
  603. ax.get_yaxis().set_visible(False)
  604. # %%
  605. ### Plot Fig4D (Bottom Right)
  606. plt.figure(figsize = (1.25,1.25))
  607. ax = sns.lineplot(data = pupil_peak_df.groupby(["ID","Time from Onset (s)","type","animal_amp_bin"]).mean().reset_index().query("type == 'dff'").query("animal_amp_bin == [1,4]"), x = "Time from Onset (s)", y = "value",errorbar = "se",hue = "animal_amp_bin",palette= ["palegreen","darkgreen"],legend = None,linewidth = 1)
  608. ax.set_xlabel("Time from \nDilation Peak (s)")
  609. ax.set_ylabel("∆ F/F (z-scr)")
  610. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  611. format_ax(ax,(-0.5,1),(-0.5,2),0.5,0.5)
  612. ax.spines[['left']].set_visible(False)
  613. ax.get_yaxis().set_visible(False)
  614. # %%
  615. ### Get data for Fig4E
  616. id_date = {
  617. "004113":["20230808"],
  618. "004114":["20230808","20230815"],
  619. "004115":["20230804","20230808","20230815"],
  620. "004116":["20230804","20230808","20230815"],
  621. "004117":["20230804","20230808","20230815"],
  622. "004118":["20230804","20230808","20230815"]
  623. }
  624. labels = ["1","2","3","4"]
  625. df_list = []
  626. for id,dates in id_date.items():
  627. for date in dates:
  628. events = get_pupil_events(id,date)
  629. peak_ix = events["peak_ix"]
  630. onsets = [on for on in events["onsets"]] ###get pupil onsets ix
  631. onsets_ix = events["onsets"]
  632. offsets = [off for off in events["offsets"]] ###get pupil offsets ix
  633. amplitudes = events["amplitudes"]
  634. binned_amps = np.array(pd.qcut(amplitudes,q = 4,labels = labels))
  635. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  636. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  637. df = pd.read_csv(path)
  638. pupil = np.array(df["Pupil Size"])
  639. time = np.array(df["Time"])
  640. speed = zscore((np.array(df["Running Speed"])))
  641. dff = np.array(df["dFF"])
  642. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  643. for i,(on,off) in enumerate(zip(onsets,offsets)):
  644. baseline = np.mean(dff[on - 40:on - 10])
  645. pre_dff =np.mean(dff[on-5:on]) - baseline
  646. during_dff = np.mean(dff[on:off]) - baseline
  647. new_dict = { "trial" : i,"ID" : id, "Date": date,"amp":amplitudes[i],"animal_amp_bin":binned_amps[i],"Pre Onset ∆ F/F":pre_dff,"∆ F/F": during_dff}
  648. df_list.append(new_dict)
  649. pupil_bar_df = pd.DataFrame.from_dict(df_list)
  650. # %%
  651. ### Plot Fig4E (Left)
  652. plt.figure(figsize = (1,1.25))
  653. g = sns.pointplot(data = pupil_bar_df.groupby(["ID",'animal_amp_bin']).mean().reset_index(), x = "animal_amp_bin", y = "Pre Onset ∆ F/F",errorbar = "se",scale = 0.5, errwidth= 1.2,color ="black")
  654. sns.lineplot(data = pupil_bar_df.groupby(["ID",'animal_amp_bin']).mean().reset_index(), x = "animal_amp_bin", y = "Pre Onset ∆ F/F",units = "ID",estimator = None,color = "black",alpha = 0.3,linewidth = 0.5)
  655. g.set_xlabel("Dilation Amplitude\n Quartile")
  656. g.set_yticks(np.arange(-0.25,1,0.25))
  657. g.set(ylim=(-0.25,0.75))
  658. # %%
  659. ### Plot Fig4E (Right)
  660. plt.figure(figsize = (1,1.25))
  661. g = sns.pointplot(data = pupil_bar_df.groupby(["ID",'animal_amp_bin']).mean().reset_index(), x = "animal_amp_bin", y = "∆ F/F",errorbar = "se",scale = 0.5, errwidth= 1.2,color ="black")
  662. sns.lineplot(data = pupil_bar_df.groupby(["ID",'animal_amp_bin']).mean().reset_index(), x = "animal_amp_bin", y = "∆ F/F",units = "ID",estimator = None,color = "black",alpha = 0.3,linewidth = 0.5)
  663. g.set_xlabel("Dilation Amplitude\n Quartile")
  664. g.set_yticks(np.arange(-0.25,1.5,0.25))
  665. g.set(ylim=(0,1))
  666. # %%
  667. ### Get data for Fig 4F (Left)
  668. id_date = {
  669. "004113":["20230808"],
  670. "004114":["20230808","20230815"],
  671. "004115":["20230804","20230808","20230815"],
  672. "004116":["20230804","20230808","20230815"],
  673. "004117":["20230804","20230808","20230815"],
  674. "004118":["20230804","20230808","20230815"]
  675. }
  676. df_list = []
  677. for id,dates in id_date.items():
  678. for date in dates:
  679. events = get_face_events(id,date)
  680. onsets_ix = events["onsets"]
  681. amplitudes = events["amplitudes"]
  682. binned_amps = np.array(pd.qcut(amplitudes,q = 4,labels = [1,2,3,4]))
  683. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  684. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  685. df = pd.read_csv(path)
  686. pupil = np.array(df["Pupil Size"])
  687. time = np.array(df["Time"])
  688. speed = zscore((np.array(df["Running Speed"])))
  689. dff = np.array(df["dFF"])
  690. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  691. onsets = [time[on] for on in events["onsets"]]
  692. dil_matrix,dil_times = trial_align(onsets,time,pupil,fps = 20,pre = 10, post = 10 )
  693. for j,trial in enumerate(dil_matrix):
  694. baseline = np.mean(pupil[onsets_ix[j] - 40:onsets_ix[j] - 10])
  695. trial = trial - baseline
  696. for i,Time in enumerate(dil_times):
  697. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "Pupil","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  698. df_list.append(new_dict)
  699. trial_matrix,trial_times = trial_align(onsets,time,dff,fps = 20,pre = 10, post = 10)
  700. for j,trial in enumerate(trial_matrix):
  701. baseline = np.mean(dff[onsets_ix[j] - 40:onsets_ix[j] - 10])
  702. trial = trial - baseline
  703. for i,Time in enumerate(trial_times):
  704. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "dff","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  705. df_list.append(new_dict)
  706. face_matrix,face_times = trial_align(onsets,time,face,fps = 20,pre = 10, post = 10)
  707. for j,trial in enumerate(face_matrix):
  708. baseline = np.mean(face[onsets_ix[j] - 40:onsets_ix[j] - 10])
  709. trial = trial - baseline
  710. for i,Time in enumerate(face_times):
  711. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "face","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  712. df_list.append(new_dict)
  713. face_onset_df = pd.DataFrame.from_dict(df_list)
  714. # %%
  715. ### Get data for Fig 4F (Right)
  716. id_date = {
  717. "004113":["20230808"],
  718. "004114":["20230808","20230815"],
  719. "004115":["20230804","20230808","20230815"],
  720. "004116":["20230804","20230808","20230815"],
  721. "004117":["20230804","20230808","20230815"],
  722. "004118":["20230804","20230808","20230815"]
  723. }
  724. df_list = []
  725. for id,dates in id_date.items():
  726. for date in dates:
  727. events = get_face_events(id,date)
  728. onsets_ix = events["onsets"]
  729. amplitudes = events["amplitudes"]
  730. binned_amps = np.array(pd.qcut(amplitudes,q = 4,labels = [1,2,3,4]))
  731. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  732. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  733. df = pd.read_csv(path)
  734. pupil = filter_pupil(np.array(df["Pupil Size"]))
  735. time = np.array(df["Time"])
  736. speed = zscore((np.array(df["Running Speed"])))
  737. dff = np.array(df["dFF"])
  738. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  739. peaks = [time[ix] for ix in events["peak_ix"]] ### get pupil peaks
  740. dil_matrix,dil_times = trial_align(peaks,time,pupil,fps = 20,pre = 10, post = 10 )
  741. for j,trial in enumerate(dil_matrix):
  742. baseline = np.mean(pupil[onsets_ix[j] - 40:onsets_ix[j] - 10])
  743. trial = trial - baseline
  744. for i,Time in enumerate(dil_times):
  745. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "Pupil","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  746. df_list.append(new_dict)
  747. trial_matrix,trial_times = trial_align(peaks,time,dff,fps = 20,pre = 10, post = 10)
  748. for j,trial in enumerate(trial_matrix):
  749. baseline = np.mean(dff[onsets_ix[j] - 40:onsets_ix[j] - 10])
  750. trial = trial - baseline
  751. for i,Time in enumerate(trial_times):
  752. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "dff","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  753. df_list.append(new_dict)
  754. face_matrix,face_times = trial_align(peaks,time,face,fps = 20,pre = 10, post = 10)
  755. for j,trial in enumerate(face_matrix):
  756. baseline = np.mean(face[onsets_ix[j] - 40:onsets_ix[j] - 10])
  757. trial = trial - baseline
  758. for i,Time in enumerate(trial_times):
  759. new_dict = {"Time from Onset (s)" : Time, "trial" : j, "value" : trial[i], "type" : "face","ID" : id, "Date": date,"amp":amplitudes[j],"animal_amp_bin":binned_amps[j]}
  760. df_list.append(new_dict)
  761. face_peak_df = pd.DataFrame.from_dict(df_list)
  762. # %%
  763. ### Plot Fig4F (Top Left)
  764. plt.figure(figsize = (1.25,1))
  765. ax = sns.lineplot(data = face_onset_df.groupby(["ID","Time from Onset (s)","type","animal_amp_bin"]).mean().reset_index().query("type == 'face'").query("animal_amp_bin == [1,4]"), x = "Time from Onset (s)", y = "value",errorbar = "se",hue = "animal_amp_bin",palette= ["violet","purple"],legend = None,linewidth = 1)
  766. ax.xaxis.label.set_visible(False)
  767. ax.set_ylabel("Facial\nmovement (z-scr)")
  768. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  769. format_ax(ax,(-0.5,0.5),(-0.5,8),0.5,0.5)
  770. # %%
  771. ### Plot Fig4F (Bottom Left)
  772. plt.figure(figsize = (1.25,1.25))
  773. ax = sns.lineplot(data = face_onset_df.groupby(["ID","Time from Onset (s)","type","animal_amp_bin"]).mean().reset_index().query("type == 'dff'").query("animal_amp_bin == [1,4]"), x = "Time from Onset (s)", y = "value",errorbar = "se",hue = "animal_amp_bin",palette= ["palegreen","darkgreen"],legend = None,linewidth = 1)
  774. ax.set_xlabel("Time from \nfacial movement onset (s)")
  775. ax.set_ylabel("∆ F/F (z-scr)")
  776. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  777. format_ax(ax,(-0.5,0.5),(-0.5,2),0.5,0.5)
  778. # %%
  779. ### Plot Fig4F (Top Right)
  780. plt.figure(figsize = (1.25,1))
  781. ax = sns.lineplot(data = face_peak_df.groupby(["ID","Time from Onset (s)","type","animal_amp_bin"]).mean().reset_index().query("type == 'face'").query("animal_amp_bin == [1,4]"), x = "Time from Onset (s)", y = "value",errorbar = "se",hue = "animal_amp_bin",palette= ["violet","purple"],legend = None,linewidth = 1)
  782. ax.xaxis.label.set_visible(False)
  783. ax.set_ylabel("Facial movement \n(z-scr)")
  784. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  785. format_ax(ax,(-0.5,1),(-0.5,8),0.5,0.5)
  786. ax.spines[['left']].set_visible(False)
  787. ax.get_yaxis().set_visible(False)
  788. # %%
  789. ### Plot Fig4F (Bottom Right)
  790. plt.figure(figsize = (1.25,1.25))
  791. ax = sns.lineplot(data = face_peak_df.groupby(["ID","Time from Onset (s)","type","animal_amp_bin"]).mean().reset_index().query("type == 'dff'").query("animal_amp_bin == [1,4]"), x = "Time from Onset (s)", y = "value",errorbar = "se",hue = "animal_amp_bin",palette= ["palegreen","darkgreen"],legend = None,linewidth = 1)
  792. ax.set_xlabel("Time from \nface movement peak (s)")
  793. ax.set_ylabel("∆ F/F (z-scr)")
  794. ax.axvline(0,linestyle = "dashed", color = "black",linewidth = 0.5)
  795. format_ax(ax,(-0.5,1),(-0.5,2),0.5,0.5)
  796. ax.spines[['left']].set_visible(False)
  797. ax.get_yaxis().set_visible(False)
  798. # %%
  799. ### Get data for Fig4G
  800. id_date = {
  801. "004113":["20230808"],
  802. "004114":["20230808","20230815"],
  803. "004115":["20230804","20230808","20230815"],
  804. "004116":["20230804","20230808","20230815"],
  805. "004117":["20230804","20230808","20230815"],
  806. "004118":["20230804","20230808","20230815"]
  807. }
  808. labels = ["1","2","3","4"]
  809. df_list = []
  810. for id,dates in id_date.items():
  811. for date in dates:
  812. events = get_face_events(id,date)
  813. peak_ix = events["peak_ix"]
  814. onsets = [on for on in events["onsets"]] ###get pupil onsets ix
  815. onsets_ix = events["onsets"]
  816. offsets = [off for off in events["offsets"]] ###get pupil offsets ix
  817. amplitudes = events["amplitudes"]
  818. binned_amps = np.array(pd.qcut(amplitudes,q = 4,labels = labels))
  819. face_path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_FaceProcessed.csv"
  820. path = f"{base_dir}/{id}/{date}/{date}_{id}_sess_1_ProcessedData.csv"
  821. df = pd.read_csv(path)
  822. pupil = np.array(df["Pupil Size"])
  823. time = np.array(df["Time"])
  824. speed = zscore((np.array(df["Running Speed"])))
  825. dff = np.array(df["dFF"])
  826. face = np.array(pd.read_csv(face_path)["Facial Movement"])
  827. for i,(on,off) in enumerate(zip(onsets,offsets)):
  828. baseline = np.mean(dff[on - 40:on - 10])
  829. pre_dff =np.mean(dff[on-5:on]) - baseline
  830. during_dff = np.mean(dff[on:off]) - baseline
  831. new_dict = { "trial" : i,"ID" : id, "Date": date,"amp":amplitudes[i],"animal_amp_bin":binned_amps[i],"Pre Onset ∆ F/F":pre_dff,"∆ F/F": during_dff}
  832. df_list.append(new_dict)
  833. face_bar_df = pd.DataFrame.from_dict(df_list)
  834. # %%
  835. ### Plot Fig4G (Left)
  836. plt.figure(figsize = (1,1.25))
  837. g = sns.pointplot(data = face_bar_df.groupby(["ID",'animal_amp_bin']).mean().reset_index(), x = "animal_amp_bin", y = "Pre Onset ∆ F/F",errorbar = "se",scale = 0.5, errwidth= 1.2,color ="black")
  838. sns.lineplot(data = face_bar_df.groupby(["ID",'animal_amp_bin']).mean().reset_index(), x = "animal_amp_bin", y = "Pre Onset ∆ F/F",units = "ID",estimator = None,color = "black",alpha = 0.3,linewidth = 0.5)
  839. g.set_xlabel("Facial movement amplitude\n quartile")
  840. g.set_yticks(np.arange(-0.25,1,0.25))
  841. g.set(ylim=(-0.25,0.75))
  842. # %%
  843. ### Plot Fig4G (Right)
  844. plt.figure(figsize = (1,1.25))
  845. g = sns.pointplot(data = face_bar_df.groupby(["ID",'animal_amp_bin']).mean().reset_index(), x = "animal_amp_bin", y = "∆ F/F",errorbar = "se", scale = 0.5,errwidth= 1.2,color = "black")
  846. sns.lineplot(data = face_bar_df.groupby(["ID",'animal_amp_bin']).mean().reset_index(), x = "animal_amp_bin", y = "∆ F/F",units = "ID",estimator = None,color = "black",alpha = 0.3,linewidth = 0.5)
  847. g.set_ylabel("Peri-event ∆ F/F")
  848. g.set_xlabel("Facial movement amplitude\n quartile")
  849. g.set_yticks(np.arange(0,2,0.5))
  850. g.set(ylim=(0,1))

4.ipynb, under CC-BY-4.0 · at the source

Overview

Authors: Nithik Chintalacheruvu1, Anagha Kalelkar1, Hector Alatriste-León1, Joël Boutin2, Vincent Breton-Provencher2, Rafiq Huda1
  1. WM Keck Center for Collaborative Neuroscience, Department of Cell Biology and Neuroscience, Rutgers University–New Brunswick, Piscataway, NJ, USA
  2. Department of Psychiatry and Neuroscience, CERVO Brain Research Center, Université Laval, Québec City, Québec, Canada
Institutions: Rutgers, The State University of New Jersey (United States); Université Laval (Canada)
Journal: Science advances, volume 12, issue 19, article eadv5652
Dates: received 8 January 2025; accepted 8 April 2026; published online 8 May 2026; in print May 2026
Type: Research article · Language: English
License: CC BY-NC
Identifiers: DOI 10.1126/sciadv.adv5652 · PMID 42102204 · PMCID PMC13155339 · OpenAlex W7160701040
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: systems (subfield)
Methods: Spectral & time-frequency, Connectivity, Statistics, Machine learning, Preprocessing, Evoked potentials, fMRI & imaging, Single-unit activity, calcium imaging, Physiology & signal measures
MeSH: Arousal*, Gyrus Cinguli*, Pupil*, Animals, Locus Coeruleus, Neurons, Norepinephrine, Optogenetics (* major topic)
Topic: Memory and Neural Mechanisms (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: National Institute of Mental Health (R00-MH112855); Natural Sciences and Engineering Research Council of Canada (RGPIN-2021-03284); Fondation Brain Canada; National Institute on Alcohol Abuse and Alcoholism (R01-AA030594); Brain and Behavior Research Foundation (NARSAD Young Investigator Award); New Frontiers in Research Fund (NFRFE-2022-00342); Fonds de recherche du Québec
Citations: cited by 4 papers (Europe PMC); 79 references in the paper

Abstract

Subcortical structures like the locus coeruleus (LC) are well known to regulate pupil-linked autonomic arousal, while the role of cortical circuits in this process remains largely unclear. We designed a closed-loop optogenetic system to inactivate the anterior cingulate cortex (ACC) in real time during pupil dilations. ACC inactivation decreased the magnitude of spontaneous pupil events. In parallel, ACC population activity scaled with the magnitude of spontaneously occurring pupil dilations. In addition to modulating spontaneous arousal, ACC responses to salient sensory stimuli scaled with the size of evoked pupil dilations and ACC inactivation suppressed saliency-linked pupil events. Last, we show that LC norepinephrine neurons signal arousal faster than the ACC. However, unlike the ACC, LC responses did not scale with the magnitude of pupil dilations. Collectively, our experiments identify the ACC as a key cortical site for sustaining momentary increases in pupil-linked arousal.

Reproduced under the paper's license (CC BY-NC), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 4 matches between paragraphs and lines of code.

Zenodo 19410291

License: CC-BY-4.0
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: “Data, code, and materials availability:”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Matplotlib (16 files), NumPy (16 files), pandas (16 files), SciPy (16 files), seaborn (16 files), OpenCV (3 files)
Availability: 1 check, the latest on 28 September 2026: the link answers (HTTP 200)
  • 28 September 2026: the link answers (HTTP 200)
16 files

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;
  • 16 scripts, each with its path and the digest of its content;
  • 4 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • 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, code, and materials availability

All data and code needed to evaluate and reproduce the results in the paper are present in the paper and/or the Supplementary Materials. Source data are included. Code can be found at: https://doi.org/10.5281/zenodo.19410291. This study did not generate new materials.

Reproduced under the paper's license (CC BY-NC), 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 1, 28 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 6 authors, 8 MeSH terms, 7 funders, 78 references.

Cite

This paper

Chintalacheruvu, N., Kalelkar, A., Alatriste-León, H., Boutin, J., Breton-Provencher, V., & Huda, R. (2026). The anterior cingulate cortex modulates pupil-linked arousal. Science advances, 12(19), eadv5652. https://doi.org/10.1126/sciadv.adv5652

BibTeX

@article{chintalacheruvu2026anterior,
author = {Chintalacheruvu, Nithik and Kalelkar, Anagha and Alatriste-León, Hector and Boutin, Joël and Breton-Provencher, Vincent and Huda, Rafiq},
title = {{The anterior cingulate cortex modulates pupil-linked arousal}},
journal = {Science advances},
year = {2026},
month = may,
volume = {12},
number = {19},
pages = {eadv5652},
publisher = {American Association for the Advancement of Science},
issn = {2375-2548},
doi = {10.1126/sciadv.adv5652},
url = {https://doi.org/10.1126/sciadv.adv5652},
pmid = {42102204},
pmcid = {PMC13155339}
}

RIS

TY - JOUR
AU - Chintalacheruvu, Nithik
AU - Kalelkar, Anagha
AU - Alatriste-León, Hector
AU - Boutin, Joël
AU - Breton-Provencher, Vincent
AU - Huda, Rafiq
TI - The anterior cingulate cortex modulates pupil-linked arousal
T2 - Science advances
J2 - Sci Adv
PY - 2026
DA - 2026/05/08
VL - 12
IS - 19
SP - eadv5652
SN - 2375-2548
PB - American Association for the Advancement of Science
DO - 10.1126/sciadv.adv5652
UR - https://doi.org/10.1126/sciadv.adv5652
LA - en
ER -

CSL-JSON

{
"id": "10.1126/sciadv.adv5652",
"type": "article-journal",
"title": "The anterior cingulate cortex modulates pupil-linked arousal",
"container-title": "Science advances",
"author": [
{
"family": "Chintalacheruvu",
"given": "Nithik"
},
{
"family": "Kalelkar",
"given": "Anagha"
},
{
"family": "Alatriste-León",
"given": "Hector"
},
{
"family": "Boutin",
"given": "Joël"
},
{
"family": "Breton-Provencher",
"given": "Vincent"
},
{
"family": "Huda",
"given": "Rafiq"
}
],
"container-title-short": "Sci Adv",
"volume": "12",
"issue": "19",
"page": "eadv5652",
"DOI": "10.1126/sciadv.adv5652",
"PMID": "42102204",
"PMCID": "PMC13155339",
"ISSN": "2375-2548",
"publisher": "American Association for the Advancement of Science",
"URL": "https://doi.org/10.1126/sciadv.adv5652",
"language": "en",
"issued": {
"date-parts": [
[
2026,
5,
8
]
]
}
}

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.1126/sciadv.adz6495
Pupil-linked arousal heterogeneously modulates cell-type-specific sensory processing.
Journal: Science advances
In common: systems, 15 references
[2] doi:10.1038/s41467-026-71725-0 [code]
Interactions across hemispheres in prefrontal cortex reflect global cognitive processing.
Journal: Nature communications
In common: pandas, SciPy, Matplotlib, 1 other tool, 9 references
[3] doi:10.1038/s41562-026-02533-1 [code]
Fluctuations in arousal reflect latent state transitions that facilitate behavioural optimization.
Journal: Nature human behaviour
In common: 10 references
[4] doi:10.7554/elife.109717 [code]
Retrosplenial cortex enables context-dependent goal-directed sensorimotor transformation.
Journal: eLife
In common: OpenCV, seaborn, pandas, 3 other tools, systems, 5 references
[5] doi:10.1038/s41467-026-75492-w [code]
Place and behavioral modulation of hippocampal neurons during immobility.
Journal: Nature communications
In common: systems, 8 references
[6] doi:10.1523/eneuro.0417-25.2026 [code]
Learning and Motivation State Fluctuations from Motoric and Neurophysiologic Metrics during a Somatosensory Task in Mice.
Journal: eNeuro
In common: 8 references
[7] doi:10.7554/elife.110294 [code]
Arousal modulates functional connectivity through structured and hemispherically asymmetric community architecture during wakefulness.
Journal: eLife
In common: seaborn, pandas, SciPy, 2 other tools, 5 references
[8] doi:10.1016/j.crmeth.2026.101421 [code]
EthoPy provides an accessible platform for reproducible behavioral neuroscience.
Journal: Cell reports methods
In common: OpenCV, seaborn, pandas, 3 other tools, 4 references
[9] doi:10.7554/elife.99278 [code]
Brain-wide arousal signals are segregated from movement planning in the superior colliculus of the macaque.
Journal: eLife
In common: NumPy, systems, 6 references
[10] doi:10.1126/sciadv.aed3610 [code]
Dexterous single sniffs for ethological active olfaction.
Journal: Science advances
In common: OpenCV, seaborn, pandas, 3 other tools, 3 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.

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: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.