OSCR

Brain regions beyond the visual cortex are relevant to subjective time prediction from fMRI salient events in a visual naturalistic context.

Code ↔ Paper

3 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 3 matches
  1. [1] § Results › Approach 1: prediction of normalized bias from salient events ↔ Robustness.ipynb, lines 301 to 362 · score 0.63 · Cingulo Opercular, Dorsal Attention, Fraction, Frontoparietal, model bias, AUD · Report a mismatch
  2. [2] § Methodology › Approach 2: prediction of normalized bias from bold time-series ↔ SVM_REDES+LSTM.ipynb, lines 1042 to 1095 · score 0.61 · cross validation, PyTorch, sequences, padded, batch, LSTM · Report a mismatch
  3. [3] § Results › Approach 1: prediction of normalized bias from salient events ↔ Robustness.ipynb, lines 301 to 362 · score 0.56 · cingulo opercular, dorsal attention, somatomotor, model bias, auditory, correlations · Report a mismatch

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

Jupyter notebook · 538 lines · 23 KB · no license · 2 matches

  1. # %%
  2. """
  3. Transform accumulated changes from fMRI layers into durations (s) using
  4. multiclass SVM
  5. """
  6. # %% [markdown]
  7. # # IMPORT LIBS AND DATA
  8. # %%
  9. from sklearn.svm import SVR
  10. import pandas as pd
  11. import numpy as np
  12. from sklearn.model_selection import KFold
  13. from sklearn.metrics import mean_squared_error
  14. from math import sqrt
  15. import scipy.io as sio
  16. import scipy.stats as stats
  17. import os.path as op
  18. import os
  19. from sklearn.base import clone
  20. import matplotlib.pyplot as plt
  21. import statsmodels.api as sm
  22. from scipy.stats import chi2
  23. # import pymc3 as pm
  24. outdir = 'D:\\ERICK\\MD\\prediction_data\\'
  25. datadir = 'D:\\ERICK\\MD\\'
  26. load_file = op.join(datadir, 'master_dataset.csv')
  27. data = pd.read_csv(load_file)
  28. # %% [markdown]
  29. # # SVM
  30. # %%
  31. # RESTING-STATE NETWORKS
  32. #create training data from salient events
  33. resdir = 'D:\\ERICK\\MD\\Results\\'
  34. excluded = [41, 45] # corrupted data
  35. regions = ['rNet1', 'rNet2', 'rNet3', 'rNet6', 'rNet7', 'rNet8', 'rNet11']
  36. netKey = {
  37. 'rNet1': 'vis',
  38. 'rNet2': 'smn',
  39. 'rNet3': 'cing',
  40. 'rNet6': 'dmn',
  41. 'rNet7': 'fpn',
  42. 'rNet8': 'aud',
  43. # 'rNet9': 'aud2',
  44. 'rNet11': 'dan',
  45. }
  46. regions = [netKey[reg] for reg in regions]
  47. for i, tmax in enumerate(np.linspace(0, 3, 50)):
  48. if tmax % 1 == 0:
  49. tmax = int(tmax)
  50. for j, tmin in enumerate(np.linspace(-3,0,50)):
  51. print('----------------------------------------------')
  52. print(f'tmax = {tmax} and tmin = {tmin}')
  53. if tmin % 1 == 0:
  54. tmin = int(tmin)
  55. for region in regions:
  56. new_id = 1
  57. df_region = []
  58. save_dir = op.join(outdir, 'Robustness', str(i+1), str(j+1))
  59. save_path = op.join(save_dir, '{}.csv'.format(region))
  60. if not op.isdir(save_dir):
  61. os.makedirs(save_dir)
  62. for subject in range(4, 45):
  63. if subject in excluded:
  64. continue
  65. data_net = {'subj': [], 'duration': [], 'isCity': [], 'report': [], 'humanBias': [], 'estimationError': []}
  66. for rd_max in range(3, 7):
  67. for rd_min in range(3, 7):
  68. text = f'tmax={np.round(tmax, rd_max)}_tmin={np.round(tmin, rd_min)}'
  69. datafile = op.join(resdir, str(subject), 'Robustness', region,
  70. f'accum_changes_{region}_{text}.mat')
  71. if op.isfile(datafile):
  72. df = sio.loadmat(datafile)
  73. df = df['d'][0][0]
  74. h = len(df[0])
  75. hb = data.loc[data['rawSubjID']==subject, 'humanBias']
  76. error = data.loc[data['rawSubjID']==subject, 'estimationError']
  77. data_net['subj'].extend([new_id] * h)
  78. data_net['duration'].extend(df[4].reshape(h))
  79. data_net['isCity'].extend(df[2].reshape(h))
  80. data_net['report'].extend(df[1].reshape(h))
  81. data_net['humanBias'].extend(hb)
  82. data_net['estimationError'].extend(error)
  83. data_net['acc_se'] = df[0].reshape(h)
  84. new_df = pd.DataFrame(data_net)
  85. df_region.append(new_df)
  86. break
  87. if op.isfile(datafile):
  88. break
  89. new_id = new_id + 1
  90. # Salvando
  91. df = pd.concat(df_region, ignore_index=True)
  92. df.to_csv(save_path, sep=',', encoding='utf-8')
  93. # df_visual = pd.concat(df_visual, ignore_index=True)
  94. # df_auditory = pd.concat(df_auditory, ignore_index=True)
  95. # df_somatosensory = pd.concat(df_somatosensory, ignore_index=True)
  96. # %%
  97. # HIERARCHICAL DATA
  98. #create training data from salient events
  99. load_file = op.join(datadir, 'master_dataset.csv')
  100. data = pd.read_csv(load_file)
  101. resdir = 'D:\\ERICK\\MD\\Results\\'
  102. excluded = [41, 45]
  103. regions = {'visual': ['rLOC', 'rV1', 'rVO'], 'auditory': ['rBA1', 'rBA2', 'rBA3'], 'somatosensory': ['rBA22', 'rBA41', 'rBA42']}
  104. layers = [1, 2, 3]
  105. for i, tmax in enumerate(np.linspace(0, 3, 50)):
  106. if tmax % 1 == 0:
  107. tmax = int(tmax)
  108. for j, tmin in enumerate(np.linspace(-3,0,50)):
  109. print('----------------------------------------------')
  110. print(f'tmax = {tmax} and tmin = {tmin}')
  111. if tmin % 1 == 0:
  112. tmin = int(tmin)
  113. for region in regions:
  114. new_id = 1
  115. df_region = []
  116. save_dir = op.join(outdir, 'Robustness', str(i+1), str(j+1))
  117. save_path = op.join(save_dir, '{}.csv'.format(region))
  118. if not op.isdir(save_dir):
  119. os.makedirs(save_dir)
  120. for subject in range(4, 45):
  121. if subject in excluded:
  122. continue
  123. print(subject)
  124. data_layers = {'subj': [], 'duration': [], 'isCity': [], 'report': [], 'humanBias': [], 'estimationError': []}
  125. for layer in layers:
  126. for rd_max in range(3, 7):
  127. for rd_min in range(3, 7):
  128. text = f'tmax={np.round(tmax, rd_max)}_tmin={np.round(tmin, rd_min)}'
  129. datafile = op.join(resdir, str(subject), 'Robustness', regions[region][layer-1],
  130. f'accum_changes_{regions[region][layer-1]}_{text}.mat')
  131. if op.isfile(datafile):
  132. df = sio.loadmat(datafile)
  133. df = df['d'][0][0]
  134. h = len(df[0])
  135. hb = data.loc[data['rawSubjID']==subject, 'humanBias']
  136. error = data.loc[data['rawSubjID']==subject, 'estimationError']
  137. if layer==1:
  138. data_layers['subj'].extend([new_id] * h)
  139. data_layers['duration'].extend(df[4].reshape(h))
  140. data_layers['isCity'].extend(df[2].reshape(h))
  141. data_layers['report'].extend(df[1].reshape(h))
  142. data_layers['humanBias'].extend(hb)
  143. data_layers['estimationError'].extend(error)
  144. data_layers['l{}'.format(layer)] = df[0].reshape(h)
  145. break
  146. if op.isfile(datafile):
  147. break
  148. new_df = pd.DataFrame(data_layers)
  149. df_region.append(new_df)
  150. new_id = new_id + 1
  151. # Salvando
  152. df = pd.concat(df_region, ignore_index=True)
  153. df.to_csv(save_path, sep=',', encoding='utf-8')
  154. # df_visual = pd.concat(df_visual, ignore_index=True)
  155. # df_auditory = pd.concat(df_auditory, ignore_index=True)
  156. # df_somatosensory = pd.concat(df_somatosensory, ignore_index=True)
  157. # %%
  158. data
  159. # %%
  160. data_type = 'hierarchical'
  161. if data_type == 'hierarchical':
  162. files = ["visual", "auditory","somatosensory"]
  163. elif data_type == 'rs_nets':
  164. files = ['vis', 'smn', 'cing', 'dmn', 'fpn', 'aud', 'dan']
  165. for i, tmax in enumerate(np.linspace(0, 3, 50)):
  166. for j, tmin in enumerate(np.linspace(-3, 0, 50)):
  167. print(f'tmax: {i+1} and tmin: {j+1}')
  168. for region in files:
  169. print(region)
  170. load_file = op.join(outdir, 'Robustness', str(i+1), str(j+1), '{}.csv'.format(region))
  171. save_file = op.join(outdir, 'Robustness', str(i+1), str(j+1), 'predicted_{}.csv'.format(region))
  172. if not op.isfile(save_file):
  173. print(save_file)
  174. data = pd.read_csv(load_file, sep=',')
  175. if data_type == 'hierarchical':
  176. accumulated_changes = np.array(pd.concat([data.l1 , data.l2, data.l3],axis=1))
  177. elif data_type == 'rs_nets':
  178. accumulated_changes = np.array(data.acc_se).reshape(-1, 1)
  179. duration=np.ravel(data.duration)
  180. regressor = SVR(kernel='rbf', C=1e3, gamma=0.0001)
  181. regressor.fit(accumulated_changes, duration)
  182. predicted = regressor.predict(accumulated_changes)
  183. if data_type == 'hierarchical':
  184. output = np.array(pd.concat([data.subj,data.duration,data.isCity,data.report, data.humanBias, data.estimationError,
  185. pd.Series(predicted), data.l1,data.l2,data.l3],axis=1))
  186. output = pd.DataFrame(output, columns=['subj', 'duration', 'isCity', 'report', 'humanBias', 'estimationError',
  187. 'predicted','l1', 'l2', 'l3'])
  188. elif data_type == 'rs_nets':
  189. output = np.array(pd.concat([data.subj,data.duration,data.isCity,data.report, data.humanBias,
  190. pd.Series(predicted), data.acc_se],axis=1))
  191. output = pd.DataFrame(output, columns=['subj', 'duration', 'isCity', 'report', 'humanBias', 'predicted', 'acc_se'])
  192. output.to_csv(save_file, sep=',', encoding='utf-8')
  193. # %%
  194. #calculate model bias for each subject
  195. data_type = 'hierarchical'
  196. if data_type == 'hierarchical':
  197. files = ["visual", "auditory","somatosensory"]
  198. elif data_type == 'rs_nets':
  199. files = ['vis', 'smn', 'cing', 'dmn', 'fpn', 'aud', 'dan']
  200. durations = [8, 12, 16, 20, 24]
  201. dur_dic = {8:0, 12:1, 16:2, 20:3, 24:4}
  202. excluded = [36, 40] #considerando novo id
  203. for i, tmax in enumerate(np.linspace(0, 3, 50)):
  204. for j, tmin in enumerate(np.linspace(-3, 0, 50)):
  205. print(f'tmax: {i+1} and tmin: {j+1}')
  206. if data_type == 'hierarchical':
  207. modelBias_off = {'visual':[], 'auditory':[], 'somatosensory':[]}
  208. modelBias_city = {'visual':[], 'auditory':[], 'somatosensory':[]}
  209. avgmb_diff = {'visual':[], 'auditory':[], 'somatosensory':[]}
  210. modelBias_all = {'visual':[], 'auditory':[], 'somatosensory':[]}
  211. avgmb_all = {'visual':[], 'auditory':[], 'somatosensory':[]}
  212. avgmb_c = {'visual':[], 'auditory':[], 'somatosensory':[]}
  213. avgmb_o = {'visual':[], 'auditory':[], 'somatosensory':[]}
  214. elif data_type == 'rs_nets':
  215. modelBias_off = {'vis':[], 'smn':[], 'cing':[], 'dmn':[], 'fpn':[], 'aud':[], 'dan':[]}
  216. modelBias_city = {'vis':[], 'smn':[], 'cing':[], 'dmn':[], 'fpn':[], 'aud':[], 'dan':[]}
  217. avgmb_diff = {'vis':[], 'smn':[], 'cing':[], 'dmn':[], 'fpn':[], 'aud':[], 'dan':[]}
  218. modelBias_all = {'vis':[], 'smn':[], 'cing':[], 'dmn':[], 'fpn':[], 'aud':[], 'dan':[]}
  219. avgmb_all = {'vis':[], 'smn':[], 'cing':[], 'dmn':[], 'fpn':[], 'aud':[], 'dan':[]}
  220. avgmb_c = {'vis':[], 'smn':[], 'cing':[], 'dmn':[], 'fpn':[], 'aud':[], 'dan':[]}
  221. avgmb_o = {'vis':[], 'smn':[], 'cing':[], 'dmn':[], 'fpn':[], 'aud':[], 'dan':[]}
  222. n = 40 # Tamanho da amostra
  223. # outdir = 'D:\\ERICK\\MD\\predictions (ORIGINAL)\\'
  224. for region in files:
  225. print(region)
  226. load_file = op.join(outdir, 'Robustness', str(i+1), str(j+1), 'predicted_{}.csv'.format(region))
  227. data = pd.read_csv(load_file)
  228. for subj in range(1, 41):
  229. subset_c = data.loc[(data['subj'] == subj) & (data['isCity'] == 1)]
  230. subset_o = data.loc[(data['subj'] == subj) & (data['isCity'] == 0)]
  231. subset = data.loc[(data['subj'] == subj)]
  232. mb_subcity = []
  233. mb_suboff = []
  234. mb_suball = []
  235. for dur in durations:
  236. mean_dur = subset.groupby('duration')['predicted'].mean().tolist()
  237. for ind, row in subset.iterrows():
  238. modelrep = row['predicted']
  239. md_idx = dur_dic[row['duration']]
  240. model_bias = 100*(modelrep-mean_dur[md_idx])/mean_dur[md_idx]
  241. mb_suball.append(model_bias)
  242. modelBias_all[region].append(model_bias)
  243. for ind, row in subset_c.iterrows():
  244. modelrep = row['predicted']
  245. md_idx = dur_dic[row['duration']]
  246. model_bias = 100*(modelrep-mean_dur[md_idx])/mean_dur[md_idx]
  247. mb_subcity.append(model_bias)
  248. modelBias_city[region].append(model_bias)
  249. for ind, row in subset_o.iterrows():
  250. modelrep = row['predicted']
  251. md_idx = dur_dic[row['duration']]
  252. model_bias = 100*(modelrep-mean_dur[md_idx])/mean_dur[md_idx]
  253. mb_suboff.append(model_bias)
  254. modelBias_off[region].append(model_bias)
  255. #calculate diff
  256. diff = np.mean(mb_subcity)-np.mean(mb_suboff)
  257. avgmb_diff[region].append(diff)
  258. avgmb_c[region].append(np.mean(mb_subcity))
  259. avgmb_o[region].append(np.mean(mb_suboff))
  260. avgmb_all[region].append(np.mean(mb_suball))
  261. #overwrite file
  262. data['modelBias'] = modelBias_all[region]
  263. data.to_csv(load_file, sep=',', encoding='utf-8')
  264. # %%
  265. import seaborn as sns
  266. import matplotlib.colors as mcolors
  267. # outdir = 'D:\\ERICK\\MD\\predictions (ORIGINAL)\\'
  268. # files = {'vis': 'visual', 'smn': 'somatomotor', 'cing': 'cingulo-opercular', 'dmn': 'default mode',
  269. # 'fpn': 'frontoparietal', 'aud': 'auditory', 'dan': 'dorsal-attention'}
  270. files = {'vis':"visual", 'aud':"auditory", 'smn':"somatosensory"}
  271. excluded = [40]
  272. sig_fraction = {}
  273. corrs = {}
  274. for region in files:
  275. sig_count = 0
  276. total_count = 0
  277. heatmap = {'tmax': [], 'tmin': [], 'p-value': []}
  278. corr_list = []
  279. for i, tmax in enumerate(np.linspace(0, 3, 50)):
  280. for j, tmin in enumerate(np.linspace(-3, 0, 50)):
  281. total_count += 1
  282. heatmap['tmax'].append(tmax)
  283. heatmap['tmin'].append(tmin)
  284. model_file = op.join(outdir, 'Robustness', str(i+1), str(j+1), 'predicted_{}.csv'.format(region))
  285. model_data = pd.read_csv(model_file)
  286. mask = model_data['subj'].isin(excluded)
  287. model_data = model_data[~mask]
  288. #Regressão => bias (human) = B0 + B1 * bias (model)
  289. x = model_data['modelBias']
  290. y = model_data['humanBias']
  291. rho, p = stats.pearsonr(x, y)
  292. modelo = sm.OLS(y, sm.add_constant(x)).fit()
  293. p_value = modelo.f_pvalue/2
  294. beta = modelo.params.iloc[1]
  295. if p_value < 0.001:
  296. p_value = 0.001
  297. if p_value < 0.05 and beta>0 :
  298. sig_count += 1
  299. corr_list.append(rho)
  300. heatmap['p-value'].append(p_value)
  301. hm = pd.DataFrame(heatmap)
  302. fig, ax = plt.subplots(figsize=(5, 3))
  303. tmax_vals = np.linspace(0, 3, 50)
  304. tmin_vals = np.linspace(-3, 0, 50)
  305. pvalue_matrix = np.reshape(hm['p-value'].values, (50, 50))
  306. contourf = ax.contourf(tmin_vals, tmax_vals, pvalue_matrix, cmap='jet_r', levels=np.logspace(-3, 0, 51), norm=mcolors.LogNorm())
  307. cbar = plt.colorbar(contourf)
  308. cbar.set_ticks([0.001, 0.01, 0.1, 1])
  309. ax.set_title(files[region], fontsize=15)
  310. ax.set_ylabel('Upper Bound (SD)', fontsize=15)
  311. ax.set_xlabel('Lower Bound (SD)', fontsize=15)
  312. plt.show()
  313. sig_fraction[files[region]] = sig_count/total_count
  314. corrs[files[region]] = corr_list
  315. # print('Fraction of ssig_count_countificant values:', sig_fraction)
  316. # %%
  317. fig, axs = plt.subplots(1, 2, figsize=(8, 3))
  318. corrs_data = [corrs[files[region]] for region in files]
  319. # Criar uma paleta de cores (ex: viridis com 3 cores)
  320. cmap = plt.cm.get_cmap('cividis', len(files))
  321. colors = [cmap(i) for i in range(len(files))]
  322. for i, region in enumerate(files):
  323. axs[0].bar(region, sig_fraction[files[region]], label=region, color=colors[i])
  324. box = axs[1].boxplot(corrs_data, labels=files, patch_artist=True)
  325. # Adicionar cores diferentes às caixas do boxplot
  326. for patch, color in zip(box['boxes'], colors):
  327. patch.set_facecolor(color)
  328. axs[0].set_ylabel('Significant $\\beta_1$ values (%)')
  329. axs[1].set_ylabel('Pearson-r')
  330. plt.subplots_adjust(wspace=0.4)
  331. # %%
  332. sig_fraction
  333. # %% [markdown]
  334. # # FIG 5
  335. # %%
  336. import warnings
  337. warnings.filterwarnings("ignore")
  338. # outdir = 'D:\\ERICK\\MD\\predictions (ORIGINAL)\\'
  339. files = ["visual","auditory","somatosensory"]
  340. columns = ['Região', 'Viés de duração', '95% IC', 'chi-quadrado', 'valor-p']
  341. df = pd.DataFrame(columns=columns)
  342. for region in files:
  343. print('--------------------------------')
  344. print(region)
  345. model_file = op.join(outdir, 'predicted_{}.csv'.format(region))
  346. model_data = pd.read_csv(model_file)
  347. # #plot model bias hist
  348. # plt.hist(model_data['modelBias'])
  349. # plt.show()
  350. #Regressão => bias (human) = B0 + B1 * bias (model)
  351. x = model_data['modelBias']
  352. y = model_data['humanBias']
  353. #corr
  354. rho,p = stats.spearmanr(x, y)
  355. print('Correlation between human and model bias: r = {:.2f}, p = {:.3f}'
  356. .format(rho, p))
  357. modelo = sm.OLS(y, sm.add_constant(x)).fit()
  358. print('Linear Regression between human and model bias: beta = {:.2f} ± {:.2f}, p = {:.3f}'
  359. .format(modelo.params[1], modelo.bse[1], modelo.f_pvalue))
  360. #EFEITO FIXO = MODEL BIAS
  361. vc = {'subj': '1 + C(subj)'}
  362. # Ajustar o modelo reduzido sem o efeito fixo
  363. model_reduced = sm.MixedLM.from_formula("humanBias ~ 1", vc_formula=vc, data=model_data, groups=model_data['subj'])
  364. result_reduced = model_reduced.fit()
  365. # Ajustar o modelo completo com o efeito fixo
  366. model_full = sm.MixedLM.from_formula("humanBias ~ 1 + modelBias", vc_formula=vc, data=model_data, groups=model_data['subj'])
  367. result_full = model_full.fit()
  368. # Calcular a diferença nas log-verossimilhanças
  369. llf_full = result_full.llf
  370. llf_reduced = result_reduced.llf
  371. lrt = -2 * (llf_reduced - llf_full)
  372. # Calcular o valor p do teste
  373. p_value = chi2.sf(lrt, 1)
  374. print('Using model bias as fixed effect: chi-sqr = {:.2f}, p = {:.3f}'
  375. .format(lrt, p_value))
  376. #EFEITO FIXO = CENA
  377. vc = {'subj': '1 + C(subj)'}
  378. # Ajustar o modelo reduzido sem o efeito fixo
  379. model_reduced = sm.MixedLM.from_formula("modelBias ~ 1", vc_formula=vc, data=model_data, groups=model_data['subj'])
  380. result_reduced = model_reduced.fit()
  381. # Ajustar o modelo completo com o efeito fixo
  382. model_full = sm.MixedLM.from_formula("modelBias ~ 1 + isCity", vc_formula=vc, data=model_data, groups=model_data['subj'])
  383. result_full = model_full.fit()
  384. # Calcular a diferença nas log-verossimilhanças
  385. llf_full = result_full.llf
  386. llf_reduced = result_reduced.llf
  387. lrt = np.round(-2 * (llf_reduced - llf_full), 2)
  388. # Calcular o valor p do teste
  389. p_value = np.round(chi2.sf(lrt, 1), 3)
  390. #calculate and print statistics
  391. mean = np.round(np.mean(avgmb_diff[region]), 2)
  392. SE = np.round(np.std(avgmb_diff[region], ddof=1)/np.sqrt(n), 2)
  393. z = 1.96 # Valor crítico para um intervalo de confiança de 95%
  394. lower_bound = np.round(mean - (z * SE), 2)
  395. upper_bound = np.round(mean + (z * SE), 2)
  396. print('Using scene as fixed effect: M±SEdiff = {:.2f} ± {:.2f} (normalized bias, %), 95% CI [{:.2f}, {:.2f}], chi-sqr = {:.2f}, p = {:.3f}'
  397. .format(mean, SE, lower_bound, upper_bound, lrt, p_value))
  398. linha = [region, '{} ± {}'.format(mean, SE), [lower_bound, upper_bound], lrt, p_value]
  399. df.loc[len(df)] = linha
  400. outFile = op.join(outdir, 'lmm_table_rep.csv')
  401. df.to_csv(outFile, sep=',', encoding='utf-8')
  402. # %%
  403. # import warnings
  404. # warnings.filterwarnings("ignore")
  405. # outdir = 'D:\\ERICK\\MD\\predictions (ORIGINAL)\\'
  406. # files = ["visual","auditory","somatosensory"]
  407. # columns = ['Região', 'Viés de duração', '95% IC', 'chi-quadrado', 'valor-p']
  408. # df = pd.DataFrame(columns=columns)
  409. # for region in files:
  410. # print(region)
  411. # model_file = op.join(outdir, 'predicted_{}.csv'.format(region))
  412. # model_data = pd.read_csv(model_file)
  413. # #plot model bias hist
  414. # plt.hist(model_data['modelBias'])
  415. # plt.show()
  416. # orig_file = op.join(datadir, 'master_dataset.csv')
  417. # orig = pd.read_csv(orig_file)
  418. # model_data['humanBias'] = orig['humanBias']
  419. # #EFEITO FIXO = MODEL BIAS
  420. # vc = {'subj': '1 + C(subj)'}
  421. # # Ajustar o modelo reduzido sem o efeito fixo
  422. # model_reduced = sm.MixedLM.from_formula("humanBias ~ 1", vc_formula=vc, data=model_data, groups=model_data['subj'])
  423. # result_reduced = model_reduced.fit()
  424. # # Ajustar o modelo completo com o efeito fixo
  425. # model_full = sm.MixedLM.from_formula("humanBias ~ 1 + modelBias", vc_formula=vc, data=model_data, groups=model_data['subj'])
  426. # result_full = model_full.fit()
  427. # # Calcular a diferença nas log-verossimilhanças
  428. # llf_full = result_full.llf
  429. # llf_reduced = result_reduced.llf
  430. # lrt = -2 * (llf_reduced - llf_full)
  431. # # Calcular o valor p do teste
  432. # p_value = chi2.sf(lrt, 1)
  433. # #calculate and print statistics
  434. # mean = np.mean(avgmb_all[region])
  435. # SE = np.std(avgmb_all[region], ddof=1)/np.sqrt(n)
  436. # z = 1.96 # Valor crítico para um intervalo de confiança de 95%
  437. # lower_bound = mean - (z * SE)
  438. # upper_bound = mean + (z * SE)
  439. # print('Using model bias as fixed effect: M±SEdiff = {:.2f} ± {:.2f} (normalized bias, %), 95% CI [{:.2f}, {:.2f}], chi-sqr = {:.2f}, p = {:.3f}'
  440. # .format(mean, SE, lower_bound, upper_bound, lrt, p_value))
  441. # #EFEITO FIXO = CENA
  442. # vc = {'subj': '1 + C(subj)'}
  443. # # Ajustar o modelo reduzido sem o efeito fixo
  444. # model_reduced = sm.MixedLM.from_formula("modelBias ~ 1", vc_formula=vc, data=model_data, groups=model_data['subj'])
  445. # result_reduced = model_reduced.fit()
  446. # # Ajustar o modelo completo com o efeito fixo
  447. # model_full = sm.MixedLM.from_formula("modelBias ~ 1 + isCity", vc_formula=vc, data=model_data, groups=model_data['subj'])
  448. # result_full = model_full.fit()
  449. # # Calcular a diferença nas log-verossimilhanças
  450. # llf_full = result_full.llf
  451. # llf_reduced = result_reduced.llf
  452. # lrt = np.round(-2 * (llf_reduced - llf_full), 2)
  453. # # Calcular o valor p do teste
  454. # p_value = np.round(chi2.sf(lrt, 1), 3)
  455. # #calculate and print statistics
  456. # mean = np.round(np.mean(avgmb_diff[region]), 2)
  457. # SE = np.round(np.std(avgmb_diff[region], ddof=1)/np.sqrt(n), 2)
  458. # z = 1.96 # Valor crítico para um intervalo de confiança de 95%
  459. # lower_bound = np.round(mean - (z * SE), 2)
  460. # upper_bound = np.round(mean + (z * SE), 2)
  461. # print('Using scene as fixed effect: M±SEdiff = {:.2f} ± {:.2f} (normalized bias, %), 95% CI [{:.2f}, {:.2f}], chi-sqr = {:.2f}, p = {:.3f}'
  462. # .format(mean, SE, lower_bound, upper_bound, lrt, p_value))
  463. # linha = [region, '{} ± {}'.format(mean, SE), [lower_bound, upper_bound], lrt, p_value]
  464. # df.loc[len(df)] = linha
  465. # outFile = op.join(outdir, 'lmm_table_original.csv')
  466. # df.to_csv(outFile, sep=',', encoding='utf-8')

Robustness.ipynb at commit 3d40efc, no license · at the source

Overview

  1. InBrain, Department of Physics, FFCLRP, University of São Paulo, Ribeirão Preto, Brazil
  2. Department of Medical Imaging, Hematology and Clinical Oncology, FMRP, University of São Paulo, Ribeirão Preto, Brazil
Institutions: Universidade de São Paulo (Brazil)
Journal: Brain imaging and behavior, volume 20, issue 2, article 58
Dates: received 10 June 2025; accepted 28 February 2026; published online 21 March 2026; in print 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1007/s11682-026-01128-8 · PMID 41863592 · PMCID PMC13005859 · OpenAlex W7139968686
Open access: hybrid, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: fMRI (modality), human (organism), cognitive (subfield)
Methods: Connectivity, Machine learning, Statistics, Preprocessing, fMRI & imaging
Keywords: Human time perception, fMRI, Machine Learning, Cerebral cortex
MeSH: Brain*, Time Perception*, Visual Perception*, Adult, Attention, Brain Mapping, Female, Humans, Long Short Term Memory, Magnetic Resonance Imaging, Male, Neural Pathways, Photic Stimulation, Visual Cortex, Young Adult (* major topic)
Topic: Neuroscience and Music Perception (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Citations: not cited yet (Europe PMC); 41 references in the paper

Abstract

Time perception is an essential part of human experience and can be distorted by features of daily stimuli, causing variations relative to actual time. This study aimed to test the hypothesis that subjective time results from the accumulation of salient events and investigate the neural bases of this perceptual processing, while using a publicly available dataset obtained and analyzed in a previous study. Three approaches were used with fMRI data from participants who watched and estimated the duration of silent videos in an MRI scanner. In the first approach, using a functional parcellation of 360 cortical regions, we showed that salient events in functional networks beyond the visual one also had a significant association with subjective time (normalized bias): the dorsal attention network, the cingulo-opercular network, and the somatomotor network. In the second approach, using an Long-Short Term Memory (LSTM) deep learning model, it was not possible to predict normalized bias from fMRI trial-by-trial time series within any functional network. In the last approach, functional connectivity between the 360 cortical regions and within the visual network showed no consistent association with subjective time. The results suggest that regions in additional functional networks may be important for duration quantification in the context of visual stimulation, although the approach based on salient events still requires further validation. Furthermore, features such as functional connectivity and fMRI time-series did not show direct association with the normalized bias.

Supplementary Information: The online version contains supplementary material available at 10.1007/s11682-026-01128-8.

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

Repository

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

inbrainlab/time_perception_fMRI

License: none: the authors keep all their rights
State: the link answers, verified on 30 September 2026
Evidence: files inventoried
Commit: 3d40efcd8698f284840cc4142ea88d9e3822ba6c, 6 June 2025
Languages: MATLAB (9), Jupyter (4)
Size: 15 files, 13 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, 4 notebooks
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Statistics and Machine Learning Toolbox (4 files), Matplotlib (4 files), NumPy (4 files), pandas (4 files), scikit-learn (4 files), SciPy (4 files), statsmodels (4 files), SPM (3 files), PyTorch (2 files), seaborn (2 files), NiBabel (1 file), Nilearn (1 file)
Availability: 1 check, the latest on 30 September 2026: the link answers
  • 30 September 2026: the link answers
14 files

Code availability

All analysis scripts are available at https://github.com/inbrainlab/time_perception_fMRI.

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

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;
  • 13 scripts, each with its path and the digest of its content;
  • 3 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

Datasets cited

Data availability

The dataset used in this study was provided by Sherman et al. (2022) and is available for download at the OSF repository https://osf.io/2zqfu.

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 1, 30 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 2 authors, 4 keywords, 15 MeSH terms, 3 funders, 35 references.

Cite

This paper

de Souza, E. A., & Salmon, C. E. G. (2026). Brain regions beyond the visual cortex are relevant to subjective time prediction from fMRI salient events in a visual naturalistic context. Brain imaging and behavior, 20(2), 58. https://doi.org/10.1007/s11682-026-01128-8

BibTeX

@article{desouza2026brain,
author = {de Souza, Erick Almeida and Salmon, Carlos Ernesto Garrido},
title = {{Brain regions beyond the visual cortex are relevant to subjective time prediction from fMRI salient events in a visual naturalistic context}},
journal = {Brain imaging and behavior},
year = {2026},
month = mar,
volume = {20},
number = {2},
pages = {58},
publisher = {Springer Science+Business Media},
issn = {1931-7557},
doi = {10.1007/s11682-026-01128-8},
url = {https://doi.org/10.1007/s11682-026-01128-8},
pmid = {41863592},
pmcid = {PMC13005859}
}

RIS

TY - JOUR
AU - de Souza, Erick Almeida
AU - Salmon, Carlos Ernesto Garrido
TI - Brain regions beyond the visual cortex are relevant to subjective time prediction from fMRI salient events in a visual naturalistic context
T2 - Brain imaging and behavior
J2 - Brain Imaging Behav
PY - 2026
DA - 2026/03/21
VL - 20
IS - 2
SP - 58
SN - 1931-7557
PB - Springer Science+Business Media
DO - 10.1007/s11682-026-01128-8
UR - https://doi.org/10.1007/s11682-026-01128-8
LA - en
ER -

CSL-JSON

{
"id": "10.1007/s11682-026-01128-8",
"type": "article-journal",
"title": "Brain regions beyond the visual cortex are relevant to subjective time prediction from fMRI salient events in a visual naturalistic context",
"container-title": "Brain imaging and behavior",
"author": [
{
"family": "de Souza",
"given": "Erick Almeida"
},
{
"family": "Salmon",
"given": "Carlos Ernesto Garrido"
}
],
"container-title-short": "Brain Imaging Behav",
"volume": "20",
"issue": "2",
"page": "58",
"DOI": "10.1007/s11682-026-01128-8",
"PMID": "41863592",
"PMCID": "PMC13005859",
"ISSN": "1931-7557",
"publisher": "Springer Science+Business Media",
"URL": "https://doi.org/10.1007/s11682-026-01128-8",
"language": "en",
"issued": {
"date-parts": [
[
2026,
3,
21
]
]
}
}

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.21203/rs.3.rs-9326213/v1 [code]
Multi-task fMRI outperforms resting-state fMRI for revealing task-invariant organization of the human brain
Journal: Research Square (preprint)
In common: Nilearn, SPM, NiBabel, 7 other tools, fMRI, cognitive, 3 references
[2] doi:10.64898/2026.03.09.710558 [code]
Multi-task fMRI outperforms resting-state fMRI for revealing task-invariant organization of the human brain
Journal: bioRxiv (preprint)
In common: Nilearn, SPM, NiBabel, 7 other tools, fMRI, cognitive, 3 references
[3] doi:10.1016/j.neuroimage.2023.120044 [code]
Comparison between gradients and parcellations for functional connectivity prediction of behavior.
Journal: NeuroImage
In common: Nilearn, SPM, NiBabel, 6 other tools, fMRI, 3 references
[4] doi:10.1016/j.nicl.2022.103139 [code]
Altered brain network topology in children with auditory processing disorder: A resting-state multi-echo fMRI study.
Journal: NeuroImage. Clinical
In common: Nilearn, SPM, NiBabel, 7 other tools, fMRI, 2 references
[5] doi:10.1016/j.isci.2025.114212 [code]
Alpha power indexes working memory load for durations.
Journal: iScience
In common: Nilearn, statsmodels, NiBabel, 6 other tools, cognitive, 2 references
[6] doi:10.1038/s42003-026-09900-8 [code]
A multidimensional framework for dissociating the neuroplasticity of auditory and early language deprivation.
Journal: Communications biology
In common: Nilearn, statsmodels, NiBabel, 6 other tools, cognitive, 2 references
[7] doi:10.1371/journal.pbio.3003704
Neuronal populations across the cortex underlie discrete, categorical, and subjective representations of visual durations.
Journal: PLoS biology
In common: fMRI, 7 references
[8] doi:10.34133/bmef.0231 [code]
Digital Twin Brain: Generating Multitask Behavior from Connectomes for Personalized Therapy.
Journal: BME frontiers
In common: Nilearn, statsmodels, PyTorch, 6 other tools, fMRI, 2 references
[9] doi:10.1002/hbm.26415 [code]
Accounting for temporal variability in functional magnetic resonance imaging improves prediction of intelligence.
Journal: Human brain mapping
In common: PyTorch, pandas, SciPy, 2 other tools, fMRI, 4 references
[10] doi:10.1371/journal.pbio.3002937 [code]
The thalamus encodes and updates context representations during hierarchical cognitive control.
Journal: PLoS biology
In common: Nilearn, statsmodels, NiBabel, 6 other tools, cognitive, 1 reference

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.1007/s11682-026-01128-8.svg)](https://openscicode.org/badge/doi/10.1007/s11682-026-01128-8)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1007/s11682-026-01128-8.svg
   :target: https://openscicode.org/badge/doi/10.1007/s11682-026-01128-8
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1007/s11682-026-01128-8"><img src="https://openscicode.org/badge/doi/10.1007/s11682-026-01128-8.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

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)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

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