OSCR

Neural and computational correlates of strategic aborting and long-run policy optimization in the dorsolateral prefrontal cortex.

Code ↔ Paper

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

Paper

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

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 1,789 lines · 75 KB · Apache-2.0

  1. # %%
  2. import numpy as np
  3. from numpy.random import default_rng
  4. import torch
  5. import torch.nn.functional as F
  6. import pandas as pd
  7. import matplotlib.pyplot as plt
  8. from matplotlib.ticker import FuncFormatter
  9. from scipy.stats import sem, mannwhitneyu, kstest, pearsonr, bootstrap
  10. from sklearn.linear_model import LinearRegression, RidgeCV
  11. from my_utils import *
  12. import pickle
  13. from pathlib import Path
  14. import sys
  15. import warnings
  16. # %%
  17. import config.config as config
  18. arg = config.ConfigGain()
  19. arg.device = 'cpu'
  20. # %%
  21. def config_colors():
  22. colors = {'abort_c': '#ed2024', 'attempt_c': '#9E9F9F',
  23. 'withvalue_c': 'lightseagreen', 'withoutvalue_c': 'salmon', 'holistic_c': 'blue',
  24. 'RNN_c': '#faaf3b'}
  25. return colors
  26. # %%
  27. plt.rcParams['pdf.fonttype'] = '42'
  28. plt.rcParams["font.family"] = 'sans-serif'
  29. plt.rcParams['font.sans-serif'] = 'Arial'
  30. plt.rcParams['mathtext.default'] = 'it'
  31. plt.rcParams['mathtext.fontset'] = 'custom'
  32. # %%
  33. locals().update(config_colors())
  34. major_formatter = FuncFormatter(my_tickformatter)
  35. fontsize = 7
  36. lw = 1
  37. # %%
  38. # agents checkpoints path
  39. actorvalue_agents_path = Path('../data/agents_no_curriculum/ActorCritic')
  40. actornovalue_agents_path = Path('../data/agents_no_curriculum/Actor_novalueCritic')
  41. actorholistic_agents_path = Path('../data/agents_no_curriculum/Actor_holisticCritic')
  42. # data path
  43. analysis_data_path = Path('../data/analysis_data')
  44. # %%
  45. from Actor_novalue import Actor as Actor_novalue
  46. from Actor import Actor
  47. from Actor_holistic import Actor as Actor_holistic
  48. from Critic import Critic
  49. # %% [markdown]
  50. # ## 2F
  51. # %%
  52. seeds_actorvalue = seeds_actornovalue = seeds_actorholistic = np.arange(50)
  53. # %%
  54. actorvalue_agents_training_progress = []
  55. actornovalue_agents_training_progress = []
  56. actorholistic_agents_training_progress = []
  57. for seed in seeds_actorvalue:
  58. actorvalue_agents_training_progress.append(pd.read_csv(list((
  59. actorvalue_agents_path / f'seed{seed}').glob('*.csv'))[0]))
  60. for seed in seeds_actornovalue:
  61. actornovalue_agents_training_progress.append(pd.read_csv(list((
  62. actornovalue_agents_path / f'seed{seed}').glob('*.csv'))[0]))
  63. for seed in seeds_actorholistic:
  64. actorholistic_agents_training_progress.append(pd.read_csv(list((
  65. actorholistic_agents_path / f'seed{seed}').glob('*.csv'))[0]))
  66. actorvalue_agents_reward_rate = np.array([v.reward_rate.values for v in actorvalue_agents_training_progress])
  67. actornovalue_agents_reward_rate = np.array([v.reward_rate.values for v in actornovalue_agents_training_progress])
  68. actorholistic_agents_reward_rate = np.array([v.reward_rate.values for v in actorholistic_agents_training_progress])
  69. actorvalue_agents_skip_frac = np.array([v['skipped_fraction'].values for v in actorvalue_agents_training_progress])
  70. actornovalue_agents_skip_frac = np.array([v['skipped_fraction'].values for v in actornovalue_agents_training_progress])
  71. actorholistic_agents_skip_frac = np.array([v['skipped_fraction'].values for v in actorholistic_agents_training_progress])
  72. actorvalue_agents_trial_dur = np.array([v['mean_steps'].values for v in actorvalue_agents_training_progress])
  73. actornovalue_agents_trial_dur = np.array([v['mean_steps'].values for v in actornovalue_agents_training_progress])
  74. actorholistic_agents_trial_dur = np.array([v['mean_steps'].values for v in actorholistic_agents_training_progress])
  75. actorvalue_agents_travel_dist = np.array([v['traveled_distance'].values for v in actorvalue_agents_training_progress])
  76. actornovalue_agents_travel_dist = np.array([v['traveled_distance'].values for v in actornovalue_agents_training_progress])
  77. actorholistic_agents_travel_dist = np.array([v['traveled_distance'].values for v in actorholistic_agents_training_progress])
  78. # %%
  79. mean_reward_rate = [actorholistic_agents_reward_rate.mean(axis=0), actornovalue_agents_reward_rate.mean(axis=0),
  80. actorvalue_agents_reward_rate.mean(axis=0)]
  81. sem_reward_rate = [sem(actorholistic_agents_reward_rate, axis=0), sem(actornovalue_agents_reward_rate, axis=0),
  82. sem(actorvalue_agents_reward_rate, axis=0)]
  83. mean_skip_frac = [np.nanmean(actorholistic_agents_skip_frac, axis=0), np.nanmean(actornovalue_agents_skip_frac, axis=0),
  84. np.nanmean(actorvalue_agents_skip_frac, axis=0)]
  85. sem_skip_frac = [sem(actorholistic_agents_skip_frac, axis=0, nan_policy='omit'),
  86. sem(actornovalue_agents_skip_frac, axis=0, nan_policy='omit'),
  87. sem(actorvalue_agents_skip_frac, axis=0, nan_policy='omit')]
  88. mean_trial_dur = [actorholistic_agents_trial_dur.mean(axis=0), actornovalue_agents_trial_dur.mean(axis=0),
  89. actorvalue_agents_trial_dur.mean(axis=0)]
  90. sem_trial_dur = [sem(actorholistic_agents_trial_dur, axis=0), sem(actornovalue_agents_trial_dur, axis=0),
  91. sem(actorvalue_agents_trial_dur, axis=0)]
  92. mean_travel_dist = [actorholistic_agents_travel_dist.mean(axis=0), actornovalue_agents_travel_dist.mean(axis=0),
  93. actorvalue_agents_travel_dist.mean(axis=0)]
  94. sem_travel_dist = [sem(actorholistic_agents_travel_dist, axis=0), sem(actornovalue_agents_travel_dist, axis=0),
  95. sem(actorvalue_agents_travel_dist, axis=0)]
  96. # %%
  97. width = 1.5; height = 1.3
  98. MAX_TRAINING_T = 10000
  99. xaxis_scale = int(1e4)
  100. yticks = np.around(np.linspace(0, 0.6, 3), 2)
  101. xticks = np.linspace(0, MAX_TRAINING_T, 5)
  102. xticklabels = [my_tickformatter(i, None) for i in xticks / xaxis_scale]
  103. fig = plt.figure(figsize=(width, height), dpi=300)
  104. ax = fig.add_subplot(1, 1, 1)
  105. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  106. plt.xticks(xticks, xticklabels, fontsize=fontsize)
  107. plt.yticks(yticks, fontsize=fontsize)
  108. ax.set_xlabel(r'Training episode ($\times$10$^4$)', fontsize=fontsize + 1)
  109. ax.set_ylabel('Reward rate (trial/s)', fontsize=fontsize + 1)
  110. ax.set_xlim(xticks[0], xticks[-1])
  111. ax.set_ylim(yticks[0], yticks[-1])
  112. ax.xaxis.set_label_coords(0.5, -0.15)
  113. ax.yaxis.set_label_coords(-0.15, 0.5)
  114. ax.yaxis.set_major_formatter(major_formatter)
  115. ax.tick_params(axis='both', which='major', pad=2)
  116. for ymean, ysem, color, label, xdata in zip(mean_reward_rate, sem_reward_rate,
  117. [holistic_c, withoutvalue_c, withvalue_c],
  118. ['Agent 1', 'Agent 2', 'Agent 3'],
  119. [actorholistic_agents_training_progress[0].episode.values,
  120. actornovalue_agents_training_progress[0].episode.values,
  121. actorvalue_agents_training_progress[0].episode.values]):
  122. ax.plot(xdata, ymean, lw=lw, clip_on=True, c=color, label=label)
  123. ax.fill_between(xdata, ymean - ysem, ymean + ysem,
  124. edgecolor='None', facecolor=color, alpha=0.4)
  125. fig.tight_layout(pad=0.3, w_pad=0.5, rect=(0, 0, 1, 1))
  126. # %% [markdown]
  127. # ## S3C
  128. # %%
  129. width = 2.7; height = 1.3
  130. yticks = np.around(np.linspace(0, 0.6, 7), 1)
  131. xticks = [0, 0.2, 0.4, 0.6, 0.8]
  132. fig = plt.figure(figsize=(width, height), dpi=300)
  133. ax = fig.add_subplot(131)
  134. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  135. plt.xticks(xticks, fontsize=fontsize)
  136. plt.yticks(yticks, fontsize=fontsize)
  137. ax.set_xlabel('Reward rate (trial/s)', fontsize=fontsize + 1)
  138. ax.set_ylabel('Fraction of seeds', fontsize=fontsize + 1)
  139. ax.set_xlim(xticks[0], xticks[-1])
  140. ax.set_ylim(yticks[0], yticks[-1])
  141. ax.xaxis.set_label_coords(0.5, -0.18)
  142. ax.yaxis.set_label_coords(-0.25, 0.5)
  143. ax.yaxis.set_major_formatter(major_formatter)
  144. ax.xaxis.set_major_formatter(major_formatter)
  145. ax.tick_params(axis='both', which='major', pad=2)
  146. bins = np.linspace(0, 0.8, 9)
  147. data = actorholistic_agents_reward_rate[:, 99]
  148. weights = np.ones_like(data) / len(data)
  149. ax.hist(data, weights=weights, bins=bins, alpha=1, histtype='bar', color=holistic_c, edgecolor='k', lw=lw)
  150. ax.plot([data.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  151. ax = fig.add_subplot(132)
  152. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  153. plt.xticks(xticks, fontsize=fontsize)
  154. plt.yticks(yticks, fontsize=fontsize)
  155. ax.set_xlabel('', fontsize=fontsize)
  156. ax.set_ylabel('', fontsize=fontsize)
  157. ax.set_xlim(xticks[0], xticks[-1])
  158. ax.set_ylim(yticks[0], yticks[-1])
  159. ax.yaxis.set_major_formatter(major_formatter)
  160. ax.xaxis.set_major_formatter(major_formatter)
  161. ax.tick_params(axis='both', which='major', pad=2)
  162. data = actornovalue_agents_reward_rate[:, -1]
  163. weights = np.ones_like(data) / len(data)
  164. ax.hist(data, weights=weights, bins=bins, alpha=1, histtype='bar', color=withoutvalue_c, edgecolor='k', clip_on=False, lw=lw)
  165. ax.plot([data.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  166. ax = fig.add_subplot(133)
  167. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  168. plt.xticks(xticks, fontsize=fontsize)
  169. plt.yticks(yticks, fontsize=fontsize)
  170. ax.set_xlabel('', fontsize=fontsize)
  171. ax.set_ylabel('', fontsize=fontsize)
  172. ax.set_xlim(xticks[0], xticks[-1])
  173. ax.set_ylim(yticks[0], yticks[-1])
  174. ax.yaxis.set_major_formatter(major_formatter)
  175. ax.xaxis.set_major_formatter(major_formatter)
  176. ax.tick_params(axis='both', which='major', pad=2)
  177. data = actorvalue_agents_reward_rate[:, -1]
  178. weights = np.ones_like(data) / len(data)
  179. ax.hist(data, weights=weights, bins=bins, alpha=1, histtype='bar', color=withvalue_c, edgecolor='k', clip_on=False, lw=lw)
  180. ax.plot([data.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  181. fig.tight_layout(pad=0.1, w_pad=0, rect=(0, 0, 1, 1))
  182. # %% [markdown]
  183. # ## S3D
  184. # %%
  185. width = 2.7; height = 1.3
  186. yticks = np.around(np.linspace(0, 0.5, 6), 1)
  187. xticks = np.around(np.linspace(0, 0.6, 7), 1)
  188. fig = plt.figure(figsize=(width, height), dpi=300)
  189. ax = fig.add_subplot(131)
  190. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  191. plt.xticks(xticks, fontsize=fontsize)
  192. plt.yticks(yticks, fontsize=fontsize)
  193. ax.set_xlabel('Abort frac.', fontsize=fontsize + 1)
  194. ax.set_ylabel('Fraction of good seeds', fontsize=fontsize + 1)
  195. ax.set_xlim(xticks[0], xticks[-1])
  196. ax.set_ylim(yticks[0], yticks[-1])
  197. ax.xaxis.set_label_coords(0.5, -0.18)
  198. ax.yaxis.set_label_coords(-0.25, 0.45)
  199. ax.yaxis.set_major_formatter(major_formatter)
  200. ax.xaxis.set_major_formatter(major_formatter)
  201. ax.tick_params(axis='both', which='major', pad=2)
  202. bins = np.linspace(0, 0.6, 7)
  203. mask = actorholistic_agents_reward_rate[:, 99] > 0.6
  204. data1 = actorholistic_agents_skip_frac[mask, 99]
  205. weights = np.ones_like(data1) / len(data1)
  206. ax.hist(data1, weights=weights, bins=bins, alpha=1, histtype='bar', color=holistic_c, edgecolor='k', lw=lw)
  207. ax.plot([data1.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  208. ax = fig.add_subplot(132)
  209. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  210. plt.xticks(xticks, fontsize=fontsize)
  211. plt.yticks(yticks, fontsize=fontsize)
  212. ax.set_xlabel('', fontsize=fontsize)
  213. ax.set_ylabel('', fontsize=fontsize)
  214. ax.set_xlim(xticks[0], xticks[-1])
  215. ax.set_ylim(yticks[0], yticks[-1])
  216. ax.yaxis.set_major_formatter(major_formatter)
  217. ax.xaxis.set_major_formatter(major_formatter)
  218. ax.tick_params(axis='both', which='major', pad=2)
  219. mask = actornovalue_agents_reward_rate[:, -1] > 0.6
  220. data2 = actornovalue_agents_skip_frac[mask, -1]
  221. weights = np.ones_like(data2) / len(data2)
  222. ax.hist(data2, weights=weights, bins=bins, alpha=1, histtype='bar', color=withoutvalue_c, edgecolor='k', clip_on=False, lw=lw)
  223. ax.plot([data2.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  224. ax = fig.add_subplot(133)
  225. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  226. plt.xticks(xticks, fontsize=fontsize)
  227. plt.yticks(yticks, fontsize=fontsize)
  228. ax.set_xlabel('', fontsize=fontsize)
  229. ax.set_ylabel('', fontsize=fontsize)
  230. ax.set_xlim(xticks[0], xticks[-1])
  231. ax.set_ylim(yticks[0], yticks[-1])
  232. ax.yaxis.set_major_formatter(major_formatter)
  233. ax.xaxis.set_major_formatter(major_formatter)
  234. ax.tick_params(axis='both', which='major', pad=2)
  235. mask = actorvalue_agents_reward_rate[:, -1] > 0.6
  236. data3 = actorvalue_agents_skip_frac[mask, -1]
  237. weights = np.ones_like(data3) / len(data3)
  238. ax.hist(data3, weights=weights, bins=bins, alpha=1, histtype='bar', color=withvalue_c, edgecolor='k', clip_on=False, lw=lw)
  239. ax.plot([data3.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  240. fig.tight_layout(pad=0.1, w_pad=0, rect=(0, 0, 1, 1))
  241. # %% [markdown]
  242. # ## S3B
  243. # %%
  244. width = 1.35; height = 1.1
  245. yticks = np.linspace(0, 1, 3)
  246. fig = plt.figure(figsize=(width, height), dpi=300)
  247. ax = fig.add_subplot(1, 1, 1)
  248. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  249. plt.yticks(yticks, fontsize=fontsize)
  250. ax.set_ylabel('Fraction of seeds', fontsize=fontsize + 1)
  251. ax.set_ylim(yticks[0], yticks[-1])
  252. ax.yaxis.set_label_coords(-0.18, 0.5)
  253. ax.yaxis.set_major_formatter(major_formatter)
  254. ax.tick_params(axis='both', which='major', pad=2)
  255. denominator = np.array([len(actorholistic_agents_reward_rate), len(actornovalue_agents_reward_rate),
  256. len(actorvalue_agents_reward_rate)])
  257. species = ("Agent 1", "Agent 2", "Agent 3")
  258. weight_counts = {
  259. "bad seeds": np.array([(actorholistic_agents_reward_rate[:, 99] <= 0.6).sum(),
  260. (actornovalue_agents_reward_rate[:, -1] <= 0.6).sum(),
  261. (actorvalue_agents_reward_rate[:, -1] <= 0.6).sum()]) / denominator,
  262. "abort frac.$<=0.3$": np.array([((actorholistic_agents_reward_rate[:, 99] > 0.6)
  263. & (actorholistic_agents_skip_frac[:, 99] <= 0.3)).sum(),
  264. ((actornovalue_agents_reward_rate[:, -1] > 0.6)
  265. & (actornovalue_agents_skip_frac[:, -1] <= 0.3)).sum(),
  266. ((actorvalue_agents_reward_rate[:, -1] > 0.6)
  267. & (actorvalue_agents_skip_frac[:, -1] <= 0.3)).sum()]) / denominator,
  268. "abort frac.$>0.3$": np.array([((actorholistic_agents_reward_rate[:, 99] > 0.6)
  269. & (actorholistic_agents_skip_frac[:, 99] > 0.3)).sum(),
  270. ((actornovalue_agents_reward_rate[:, -1] > 0.6)
  271. & (actornovalue_agents_skip_frac[:, -1] > 0.3)).sum(),
  272. ((actorvalue_agents_reward_rate[:, -1] > 0.6)
  273. & (actorvalue_agents_skip_frac[:, -1] > 0.3)).sum()]) / denominator
  274. }
  275. barwidth = 0.5
  276. bottom = np.zeros(3)
  277. for (boolean, weight_count), c in zip(weight_counts.items(), ['C4', 'C1', 'C2']):
  278. p = ax.bar(species, weight_count, barwidth, label=boolean, bottom=bottom, color=c)
  279. bottom += weight_count
  280. plt.xticks(fontsize=fontsize-0.5)
  281. fig.tight_layout(pad=0.3, w_pad=0.5, rect=(0, 0, 1, 1))
  282. # %% [markdown]
  283. # ## S3A
  284. # %%
  285. okseed_mask_value = actorvalue_agents_reward_rate[:, -1] > 0.2
  286. okseed_mask_novalue = actornovalue_agents_reward_rate[:, -1] > 0.2
  287. okseed_mask_holistic = actorholistic_agents_reward_rate[:, 99] > 0.2
  288. okseeds_actorvalue = seeds_actorvalue[okseed_mask_value]
  289. okseeds_actornovalue = seeds_actornovalue[okseed_mask_novalue]
  290. okseeds_actorholistic = seeds_actorholistic[okseed_mask_holistic]
  291. mean_reward_rate_ok = [actorholistic_agents_reward_rate[okseed_mask_holistic, :].mean(axis=0),
  292. actornovalue_agents_reward_rate[okseed_mask_novalue, :].mean(axis=0),
  293. actorvalue_agents_reward_rate[okseed_mask_value, :].mean(axis=0)]
  294. sem_reward_rate_ok = [sem(actorholistic_agents_reward_rate[okseed_mask_holistic, :], axis=0),
  295. sem(actornovalue_agents_reward_rate[okseed_mask_novalue, :], axis=0),
  296. sem(actorvalue_agents_reward_rate[okseed_mask_value, :], axis=0)]
  297. mean_trial_dur_ok = [actorholistic_agents_trial_dur[okseed_mask_holistic, :].mean(axis=0),
  298. actornovalue_agents_trial_dur[okseed_mask_novalue, :].mean(axis=0),
  299. actorvalue_agents_trial_dur[okseed_mask_value, :].mean(axis=0)]
  300. sem_trial_dur_ok = [sem(actorholistic_agents_trial_dur[okseed_mask_holistic, :], axis=0),
  301. sem(actornovalue_agents_trial_dur[okseed_mask_novalue, :], axis=0),
  302. sem(actorvalue_agents_trial_dur[okseed_mask_value, :], axis=0)]
  303. width = 1.5; height = 1.3
  304. MAX_TRAINING_T = 10000
  305. xaxis_scale = int(1e4)
  306. yticks = np.around(np.linspace(0, 0.8, 3), 2)
  307. xticks = np.linspace(0, MAX_TRAINING_T, 5)
  308. xticklabels = [my_tickformatter(i, None) for i in xticks / xaxis_scale]
  309. fig = plt.figure(figsize=(width, height), dpi=300)
  310. ax = fig.add_subplot(1, 1, 1)
  311. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  312. plt.xticks(xticks, xticklabels, fontsize=fontsize)
  313. plt.yticks(yticks, fontsize=fontsize)
  314. ax.set_xlabel(r'Training episode ($\times$10$^4$)', fontsize=fontsize + 1)
  315. ax.set_ylabel('Reward rate (trial/s)', fontsize=fontsize + 1)
  316. ax.set_xlim(xticks[0], xticks[-1])
  317. ax.set_ylim(yticks[0], yticks[-1])
  318. ax.xaxis.set_label_coords(0.5, -0.15)
  319. ax.yaxis.set_label_coords(-0.15, 0.5)
  320. ax.yaxis.set_major_formatter(major_formatter)
  321. ax.tick_params(axis='both', which='major', pad=2)
  322. for ymean, ysem, color, label, xdata in zip(mean_reward_rate_ok, sem_reward_rate_ok,
  323. [holistic_c, withoutvalue_c, withvalue_c],
  324. ['Agent 1', 'Agent 2', 'Agent 3'],
  325. [actorholistic_agents_training_progress[0].episode.values,
  326. actornovalue_agents_training_progress[0].episode.values,
  327. actorvalue_agents_training_progress[0].episode.values]):
  328. ax.plot(xdata, ymean, lw=lw, clip_on=True, c=color, label=label)
  329. ax.fill_between(xdata, ymean - ysem, ymean + ysem,
  330. edgecolor='None', facecolor=color, alpha=0.4)
  331. fig.tight_layout(pad=0.3, w_pad=0.5, rect=(0, 0, 1, 1))
  332. # %% [markdown]
  333. # ## S3F
  334. # %%
  335. width = 1.5; height = 1.3
  336. MAX_TRAINING_T = 20000
  337. xaxis_scale = int(1e4)
  338. yticks = np.around(np.linspace(0, 0.6, 3), 2)
  339. xticks = np.linspace(0, MAX_TRAINING_T, 5)
  340. xticklabels = [my_tickformatter(i, None) for i in xticks / xaxis_scale]
  341. fig = plt.figure(figsize=(width, height), dpi=300)
  342. ax = fig.add_subplot(1, 1, 1)
  343. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  344. plt.xticks(xticks, xticklabels, fontsize=fontsize)
  345. plt.yticks(yticks, fontsize=fontsize)
  346. ax.set_xlabel(r'Training episode ($\times$10$^4$)', fontsize=fontsize + 1)
  347. ax.set_ylabel('Reward rate (trial/s)', fontsize=fontsize + 1)
  348. ax.set_xlim(xticks[0], xticks[-1])
  349. ax.set_ylim(yticks[0], yticks[-1])
  350. ax.xaxis.set_label_coords(0.5, -0.15)
  351. ax.yaxis.set_label_coords(-0.15, 0.5)
  352. ax.yaxis.set_major_formatter(major_formatter)
  353. ax.tick_params(axis='both', which='major', pad=2)
  354. for ymean, ysem, color, label, xdata in zip(mean_reward_rate, sem_reward_rate,
  355. [holistic_c, withoutvalue_c, withvalue_c],
  356. ['Agent 1', 'Agent 2', 'Agent 3'],
  357. [actorholistic_agents_training_progress[0].episode.values,
  358. actornovalue_agents_training_progress[0].episode.values,
  359. actorvalue_agents_training_progress[0].episode.values]):
  360. ax.plot(xdata, ymean, lw=lw, clip_on=True, c=color, label=label)
  361. ax.plot(ax.get_xlim(), [ymean[-1]] * 2, c=color, lw=lw, ls='--')
  362. ax.fill_between(xdata, ymean - ysem, ymean + ysem,
  363. edgecolor='None', facecolor=color, alpha=0.4)
  364. fig.tight_layout(pad=0.3, w_pad=0.5, rect=(0, 0, 1, 1))
  365. # %% [markdown]
  366. # ## S3H
  367. # %%
  368. width = 2.7; height = 1.3
  369. yticks = np.around(np.linspace(0, 0.7, 8), 1)
  370. xticks = [0, 0.2, 0.4, 0.6, 0.8]
  371. fig = plt.figure(figsize=(width, height), dpi=300)
  372. ax = fig.add_subplot(131)
  373. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  374. plt.xticks(xticks, fontsize=fontsize)
  375. plt.yticks(yticks, fontsize=fontsize)
  376. ax.set_xlabel('Reward rate (trial/s)', fontsize=fontsize + 1)
  377. ax.set_ylabel('Fraction of seeds', fontsize=fontsize + 1)
  378. ax.set_xlim(xticks[0], xticks[-1])
  379. ax.set_ylim(yticks[0], yticks[-1])
  380. ax.xaxis.set_label_coords(0.5, -0.18)
  381. ax.yaxis.set_label_coords(-0.25, 0.5)
  382. ax.yaxis.set_major_formatter(major_formatter)
  383. ax.xaxis.set_major_formatter(major_formatter)
  384. ax.tick_params(axis='both', which='major', pad=2)
  385. bins = np.linspace(0, 0.8, 9)
  386. data = actorholistic_agents_reward_rate[:, -1]
  387. weights = np.ones_like(data) / len(data)
  388. ax.hist(data, weights=weights, bins=bins, alpha=1, histtype='bar', color=holistic_c, edgecolor='k', clip_on=False, lw=lw)
  389. ax.plot([data.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  390. ax = fig.add_subplot(132)
  391. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  392. plt.xticks(xticks, fontsize=fontsize)
  393. plt.yticks(yticks, fontsize=fontsize)
  394. ax.set_xlabel('', fontsize=fontsize)
  395. ax.set_ylabel('', fontsize=fontsize)
  396. ax.set_xlim(xticks[0], xticks[-1])
  397. ax.set_ylim(yticks[0], yticks[-1])
  398. ax.yaxis.set_major_formatter(major_formatter)
  399. ax.xaxis.set_major_formatter(major_formatter)
  400. ax.tick_params(axis='both', which='major', pad=2)
  401. data = actornovalue_agents_reward_rate[:, -1]
  402. weights = np.ones_like(data) / len(data)
  403. ax.hist(data, weights=weights, bins=bins, alpha=1, histtype='bar', color=withoutvalue_c, edgecolor='k', clip_on=False, lw=lw)
  404. ax.plot([data.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  405. ax = fig.add_subplot(133)
  406. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  407. plt.xticks(xticks, fontsize=fontsize)
  408. plt.yticks(yticks, fontsize=fontsize)
  409. ax.set_xlabel('', fontsize=fontsize)
  410. ax.set_ylabel('', fontsize=fontsize)
  411. ax.set_xlim(xticks[0], xticks[-1])
  412. ax.set_ylim(yticks[0], yticks[-1])
  413. ax.yaxis.set_major_formatter(major_formatter)
  414. ax.xaxis.set_major_formatter(major_formatter)
  415. ax.tick_params(axis='both', which='major', pad=2)
  416. data = actorvalue_agents_reward_rate[:, -1]
  417. weights = np.ones_like(data) / len(data)
  418. ax.hist(data, weights=weights, bins=bins, alpha=1, histtype='bar', color=withvalue_c, edgecolor='k', clip_on=False, lw=lw)
  419. ax.plot([data.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  420. fig.tight_layout(pad=0.1, w_pad=0, rect=(0, 0, 1, 1))
  421. # %% [markdown]
  422. # ## S3I
  423. # %%
  424. width = 2.7; height = 1.3
  425. yticks = np.around(np.linspace(0, 0.5, 6), 1)
  426. xticks = np.around(np.linspace(0, 0.6, 7), 1)
  427. fig = plt.figure(figsize=(width, height), dpi=300)
  428. ax = fig.add_subplot(131)
  429. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  430. plt.xticks(xticks, fontsize=fontsize)
  431. plt.yticks(yticks, fontsize=fontsize)
  432. ax.set_xlabel('Abort frac.', fontsize=fontsize + 1)
  433. ax.set_ylabel('Fraction of good seeds', fontsize=fontsize + 1)
  434. ax.set_xlim(xticks[0], xticks[-1])
  435. ax.set_ylim(yticks[0], yticks[-1])
  436. ax.xaxis.set_label_coords(0.5, -0.18)
  437. ax.yaxis.set_label_coords(-0.25, 0.45)
  438. ax.yaxis.set_major_formatter(major_formatter)
  439. ax.xaxis.set_major_formatter(major_formatter)
  440. ax.tick_params(axis='both', which='major', pad=2)
  441. bins = np.linspace(0, 0.6, 7)
  442. mask = actorholistic_agents_reward_rate[:, -1] > 0.6
  443. data = actorholistic_agents_skip_frac[mask, -1]
  444. weights = np.ones_like(data) / len(data)
  445. ax.hist(data, weights=weights, bins=bins, alpha=1,
  446. histtype='bar', color=holistic_c, edgecolor='k', clip_on=False, lw=lw)
  447. ax.plot([data.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  448. ax = fig.add_subplot(132)
  449. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  450. plt.xticks(xticks, fontsize=fontsize)
  451. plt.yticks(yticks, fontsize=fontsize)
  452. ax.set_xlabel('', fontsize=fontsize)
  453. ax.set_ylabel('', fontsize=fontsize)
  454. ax.set_xlim(xticks[0], xticks[-1])
  455. ax.set_ylim(yticks[0], yticks[-1])
  456. ax.yaxis.set_major_formatter(major_formatter)
  457. ax.xaxis.set_major_formatter(major_formatter)
  458. ax.tick_params(axis='both', which='major', pad=2)
  459. mask = actornovalue_agents_reward_rate[:, -1] > 0.6
  460. data = actornovalue_agents_skip_frac[mask, -1]
  461. weights = np.ones_like(data) / len(data)
  462. ax.hist(data, weights=weights, bins=bins, alpha=1,
  463. histtype='bar', color=withoutvalue_c, edgecolor='k', clip_on=False, lw=lw)
  464. ax.plot([data.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  465. ax = fig.add_subplot(133)
  466. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  467. plt.xticks(xticks, fontsize=fontsize)
  468. plt.yticks(yticks, fontsize=fontsize)
  469. ax.set_xlabel('', fontsize=fontsize)
  470. ax.set_ylabel('', fontsize=fontsize)
  471. ax.set_xlim(xticks[0], xticks[-1])
  472. ax.set_ylim(yticks[0], yticks[-1])
  473. ax.yaxis.set_major_formatter(major_formatter)
  474. ax.xaxis.set_major_formatter(major_formatter)
  475. ax.tick_params(axis='both', which='major', pad=2)
  476. mask = actorvalue_agents_reward_rate[:, -1] > 0.6
  477. data = actorvalue_agents_skip_frac[mask, -1]
  478. weights = np.ones_like(data) / len(data)
  479. ax.hist(data, weights=weights, bins=bins, alpha=1,
  480. histtype='bar', color=withvalue_c, edgecolor='k', clip_on=False, lw=lw)
  481. ax.plot([data.mean()] * 2, ax.get_ylim(), c='gray', lw=lw, ls='--')
  482. fig.tight_layout(pad=0.1, w_pad=0, rect=(0, 0, 1, 1))
  483. # %% [markdown]
  484. # ## S3G
  485. # %%
  486. width = 1.35; height = 1.1
  487. yticks = np.linspace(0, 1, 3)
  488. fig = plt.figure(figsize=(width, height), dpi=300)
  489. ax = fig.add_subplot(1, 1, 1)
  490. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  491. plt.yticks(yticks, fontsize=fontsize)
  492. ax.set_ylabel('Fraction of seeds', fontsize=fontsize + 1)
  493. ax.set_ylim(yticks[0], yticks[-1])
  494. ax.yaxis.set_label_coords(-0.18, 0.5)
  495. ax.yaxis.set_major_formatter(major_formatter)
  496. ax.tick_params(axis='both', which='major', pad=2)
  497. denominator = np.array([len(actorholistic_agents_reward_rate), len(actornovalue_agents_reward_rate),
  498. len(actorvalue_agents_reward_rate)])
  499. species = ("Agent 1", "Agent 2", "Agent 3")
  500. weight_counts = {
  501. "bad seeds": np.array([(actorholistic_agents_reward_rate[:, -1] <= 0.6).sum(),
  502. (actornovalue_agents_reward_rate[:, -1] <= 0.6).sum(),
  503. (actorvalue_agents_reward_rate[:, -1] <= 0.6).sum()]) / denominator,
  504. "abort frac.$<=0.3$": np.array([((actorholistic_agents_reward_rate[:, -1] > 0.6)
  505. & (actorholistic_agents_skip_frac[:, -1] <= 0.3)).sum(),
  506. ((actornovalue_agents_reward_rate[:, -1] > 0.6)
  507. & (actornovalue_agents_skip_frac[:, -1] <= 0.3)).sum(),
  508. ((actorvalue_agents_reward_rate[:, -1] > 0.6)
  509. & (actorvalue_agents_skip_frac[:, -1] <= 0.3)).sum()]) / denominator,
  510. "abort frac.$>0.3$": np.array([((actorholistic_agents_reward_rate[:, -1] > 0.6)
  511. & (actorholistic_agents_skip_frac[:, -1] > 0.3)).sum(),
  512. ((actornovalue_agents_reward_rate[:, -1] > 0.6)
  513. & (actornovalue_agents_skip_frac[:, -1] > 0.3)).sum(),
  514. ((actorvalue_agents_reward_rate[:, -1] > 0.6)
  515. & (actorvalue_agents_skip_frac[:, -1] > 0.3)).sum()]) / denominator
  516. }
  517. barwidth = 0.5
  518. bottom = np.zeros(3)
  519. for (boolean, weight_count), c in zip(weight_counts.items(), ['C4', 'C1', 'C2']):
  520. p = ax.bar(species, weight_count, barwidth, label=boolean, bottom=bottom, color=c)
  521. bottom += weight_count
  522. plt.xticks(fontsize=fontsize-0.5)
  523. fig.tight_layout(pad=0.3, w_pad=0.5, rect=(0, 0, 1, 1))
  524. # %% [markdown]
  525. # # Run agent
  526. # %%
  527. from Agent_LSTM import *
  528. from Environment import Env
  529. # %%
  530. reset_seeds(0)
  531. env = Env(arg)
  532. target_positions = []
  533. for _ in range(2000):
  534. __ = env.reset()
  535. target_positions.append(env.target_position)
  536. # %%
  537. def LSTM_agent_simulation(agent):
  538. reset_seeds(0)
  539. env = Env(arg)
  540. pos_x = []; pos_x_end = []; pos_y = []; pos_y_end = []
  541. head_dir = []; head_dir_end = []; pos_r = []
  542. pos_theta = []; pos_r_end = []; pos_theta_end = []; pos_v = []; pos_w = []
  543. target_x = []; target_y = []; target_r = []; target_theta = []
  544. rewarded = []; relative_radius = []; relative_angle = []
  545. action_v = []; action_w = []
  546. relative_radius_end = []; relative_angle_end = []
  547. steps = []; state_ = []; action_ = []
  548. skipped = []
  549. for target_position in target_positions:
  550. cross_start_threshold = False
  551. x = env.reset(target_position=target_position)
  552. agent.bstep.reset(env.pro_gains)
  553. last_action = torch.zeros([1, 1, arg.ACTION_DIM])
  554. last_action_raw = last_action.clone()
  555. state = torch.cat([x[-arg.OBS_DIM:].view(1, 1, -1), last_action,
  556. env.target_position_obs.view(1, 1, -1),
  557. torch.zeros(1, 1, 1)], dim=2).to(arg.device)
  558. hidden_in = None
  559. true_states = []
  560. actions = []
  561. states = []
  562. for t in range(arg.EPISODE_LEN):
  563. if not cross_start_threshold and (last_action_raw.abs() > arg.TERMINAL_ACTION).any():
  564. cross_start_threshold = True
  565. action, action_raw, hidden_out = agent.select_action(state, hidden_in, action_noise=None)
  566. next_x, reached_target, _ = env(x, action, t)
  567. next_ox = agent.bstep(next_x)
  568. next_state = torch.cat([next_ox.view(1, 1, -1), action,
  569. env.target_position_obs.view(1, 1, -1),
  570. torch.ones(1, 1, 1) * (t + 1)
  571. ], dim=2).to(arg.device)
  572. is_stop = env.is_stop(x, action)
  573. true_states.append(x)
  574. states.append(state)
  575. actions.append(action)
  576. if is_stop and cross_start_threshold:
  577. break
  578. last_action_raw = action_raw
  579. state = next_state
  580. x = next_x
  581. hidden_in = hidden_out
  582. # Trial end
  583. pos_x_temp, pos_y_temp, head_dir_temp, pos_v_temp, pos_w_temp \
  584. = torch.chunk(torch.cat(true_states, dim=1), x.shape[0], dim=0)
  585. pos_x.append(pos_x_temp.view(-1).numpy() * arg.LINEAR_SCALE)
  586. pos_y.append(pos_y_temp.view(-1).numpy() * arg.LINEAR_SCALE)
  587. pos_x_end.append(pos_x[-1][-1])
  588. pos_y_end.append(pos_y[-1][-1])
  589. head_dir.append(np.rad2deg(head_dir_temp.view(-1).numpy()))
  590. pos_v.append(pos_v_temp.view(-1).numpy() * arg.LINEAR_SCALE)
  591. pos_w.append(np.rad2deg(pos_w_temp.view(-1).numpy()))
  592. head_dir_end.append(head_dir[-1][-1])
  593. rho, phi = cart2pol(pos_x[-1], pos_y[-1])
  594. pos_r.append(rho)
  595. pos_theta.append(np.rad2deg(phi))
  596. pos_r_end.append(rho[-1])
  597. pos_theta_end.append(np.rad2deg(phi[-1]))
  598. target_x.append(target_position[0].item() * arg.LINEAR_SCALE)
  599. target_y.append(target_position[1].item() * arg.LINEAR_SCALE)
  600. tar_rho, tar_phi = cart2pol(target_x[-1], target_y[-1])
  601. target_r.append(tar_rho)
  602. target_theta.append(np.rad2deg(tar_phi))
  603. state_.append(torch.cat(states))
  604. action_.append(torch.cat(actions))
  605. action_v_temp, action_w_temp = torch.chunk(torch.cat(actions).squeeze(1),
  606. action.shape[-1], dim=1)
  607. action_v.append(action_v_temp.view(-1).numpy())
  608. action_w.append(action_w_temp.view(-1).numpy())
  609. relative_r, relative_ang = get_relative_r_ang(pos_x[-1], pos_y[-1], head_dir[-1],
  610. target_x[-1], target_y[-1])
  611. relative_radius.append(relative_r)
  612. relative_angle.append(np.rad2deg(relative_ang))
  613. relative_radius_end.append(relative_r[-1])
  614. relative_angle_end.append(np.rad2deg(relative_ang[-1]))
  615. rewarded.append((reached_target & is_stop).item())
  616. skipped.append(pos_r_end[-1] < target_r[-1] * 0.3)
  617. steps.append(np.arange(relative_r.size))
  618. return(pd.DataFrame().assign(pos_x=pos_x, pos_y=pos_y, pos_x_end=pos_x_end, pos_y_end=pos_y_end,
  619. head_dir=head_dir, head_dir_end=head_dir_end,
  620. pos_r=pos_r, pos_theta=pos_theta,
  621. pos_r_end=pos_r_end, pos_theta_end=pos_theta_end, pos_v=pos_v,
  622. pos_w=pos_w, target_x=target_x, target_y=target_y,
  623. target_r=target_r,
  624. target_theta=target_theta, rewarded=rewarded,
  625. relative_radius=relative_radius, relative_angle=relative_angle,
  626. action_v=action_v, action_w=action_w,
  627. relative_radius_end=relative_radius_end,
  628. relative_angle_end=relative_angle_end,
  629. steps=steps, state=state_, action=action_,
  630. skipped=skipped))
  631. # %%
  632. okseed_mask_value = actorvalue_agents_reward_rate[:, -1] > 0.2
  633. okseed_mask_novalue = actornovalue_agents_reward_rate[:, -1] > 0.2
  634. okseed_mask_holistic = actorholistic_agents_reward_rate[:, 99] > 0.2
  635. okseed_mask_holisticLong = actorholistic_agents_reward_rate[:, -1] > 0.2
  636. okseeds_actorvalue = seeds_actorvalue[okseed_mask_value]
  637. okseeds_actornovalue = seeds_actornovalue[okseed_mask_novalue]
  638. okseeds_actorholistic = seeds_actorholistic[okseed_mask_holistic]
  639. okseeds_actorholisticLong = seeds_actorholistic[okseed_mask_holisticLong]
  640. goodseed_mask_value = actorvalue_agents_reward_rate[:, -1] > 0.6
  641. goodseed_mask_novalue = actornovalue_agents_reward_rate[:, -1] > 0.6
  642. goodseed_mask_holistic = actorholistic_agents_reward_rate[:, 99] > 0.6
  643. goodseed_mask_holisticLong = actorholistic_agents_reward_rate[:, -1] > 0.6
  644. goodmask_fromok_value = np.isin(np.where(okseed_mask_value)[0], np.where(goodseed_mask_value)[0])
  645. goodmask_fromok_novalue = np.isin(np.where(okseed_mask_novalue)[0], np.where(goodseed_mask_novalue)[0])
  646. goodmask_fromok_holistic = np.isin(np.where(okseed_mask_holistic)[0], np.where(goodseed_mask_holistic)[0])
  647. goodmask_fromok_holisticLong = np.isin(np.where(okseed_mask_holisticLong)[0], np.where(goodseed_mask_holisticLong)[0])
  648. # %%
  649. #run agents here, it takes hours.
  650. '''
  651. epi = 9999
  652. actorvalue_data = []; actornovalue_data = []; actorholistic_data = []; actorholisticLong_data = []
  653. actorvalue_agents = []; actornovalue_agents = []; actorholistic_agents = []; actorholisticLong_agents = []
  654. for seed in okseeds_actorvalue:
  655. actorvalue_agent = Agent(arg, Actor, Critic)
  656. actorvalue_agent.data_path = actorvalue_agents_path / f'seed{seed}'
  657. actorvalue_agent.load(list((actorvalue_agents_path / f'seed{seed}').glob('*.csv'))[0].stem + f'-{epi}',
  658. load_memory=False, load_optimzer=False)
  659. df = LSTM_agent_simulation(actorvalue_agent)
  660. actorvalue_data.append(df)
  661. actorvalue_agents.append(actorvalue_agent)
  662. for seed in okseeds_actornovalue:
  663. actornovalue_agent = Agent(arg, Actor_novalue, Critic)
  664. actornovalue_agent.data_path = actornovalue_agents_path / f'seed{seed}'
  665. actornovalue_agent.load(list((actornovalue_agents_path / f'seed{seed}').glob('*.csv'))[0].stem + f'-{epi}',
  666. load_memory=False, load_optimzer=False)
  667. df = LSTM_agent_simulation(actornovalue_agent)
  668. actornovalue_data.append(df)
  669. actornovalue_agents.append(actornovalue_agent)
  670. for seed in okseeds_actorholistic:
  671. actorholistic_agent = Agent(arg, Actor_holistic, Critic)
  672. actorholistic_agent.data_path = actorholistic_agents_path / f'seed{seed}'
  673. actorholistic_agent.load(list((actorholistic_agents_path / f'seed{seed}').glob('*.csv'))[0].stem + f'-{epi}',
  674. load_memory=False, load_optimzer=False)
  675. df = LSTM_agent_simulation(actorholistic_agent)
  676. actorholistic_data.append(df)
  677. actorholistic_agents.append(actorholistic_agent)
  678. for seed in okseeds_actorholisticLong:
  679. actorholistic_agent = Agent(arg, Actor_holistic, Critic)
  680. actorholistic_agent.data_path = actorholistic_agents_path / f'seed{seed}'
  681. actorholistic_agent.load(list((actorholistic_agents_path / f'seed{seed}').glob('*.csv'))[0].stem + f'-{epi+10000}',
  682. load_memory=False, load_optimzer=False)
  683. df = LSTM_agent_simulation(actorholistic_agent)
  684. actorholisticLong_data.append(df)
  685. actorholisticLong_agents.append(actorholistic_agent)
  686. '''
  687. # %%
  688. #store data
  689. '''
  690. with open(analysis_data_path / 'actorvalue_data.pkl', 'wb') as file:
  691. pickle.dump(actorvalue_data, file)
  692. with open(analysis_data_path / 'actornovalue_data.pkl', 'wb') as file:
  693. pickle.dump(actornovalue_data, file)
  694. with open(analysis_data_path / 'actorholistic_data.pkl', 'wb') as file:
  695. pickle.dump(actorholistic_data, file)
  696. with open(analysis_data_path / 'actorholisticLong_data.pkl', 'wb') as file:
  697. pickle.dump(actorholisticLong_data, file)
  698. with open(analysis_data_path / 'actorvalue_agents.pkl', 'wb') as file:
  699. pickle.dump(actorvalue_agents, file)
  700. with open(analysis_data_path / 'actornovalue_agents.pkl', 'wb') as file:
  701. pickle.dump(actornovalue_agents, file)
  702. with open(analysis_data_path / 'actorholistic_agents.pkl', 'wb') as file:
  703. pickle.dump(actorholistic_agents, file)
  704. with open(analysis_data_path / 'actorholisticLong_agents.pkl', 'wb') as file:
  705. pickle.dump(actorholisticLong_agents, file)
  706. '''
  707. # %%
  708. #load data
  709. with open(analysis_data_path / 'actorvalue_data.pkl', 'rb') as file:
  710. actorvalue_data = pickle.load(file)
  711. with open(analysis_data_path / 'actornovalue_data.pkl', 'rb') as file:
  712. actornovalue_data = pickle.load(file)
  713. with open(analysis_data_path / 'actorholistic_data.pkl', 'rb') as file:
  714. actorholistic_data = pickle.load(file)
  715. with open(analysis_data_path / 'actorholisticLong_data.pkl', 'rb') as file:
  716. actorholisticLong_data = pickle.load(file)
  717. with open(analysis_data_path / 'actorvalue_agents.pkl', 'rb') as file:
  718. actorvalue_agents = pickle.load(file)
  719. with open(analysis_data_path / 'actornovalue_agents.pkl', 'rb') as file:
  720. actornovalue_agents = pickle.load(file)
  721. with open(analysis_data_path / 'actorholistic_agents.pkl', 'rb') as file:
  722. actorholistic_agents = pickle.load(file)
  723. with open(analysis_data_path / 'actorholisticLong_agents.pkl', 'rb') as file:
  724. actorholisticLong_agents = pickle.load(file)
  725. # %% [markdown]
  726. # ## 2G
  727. # %%
  728. # agent 3
  729. dfs = pd.concat([df for idx, df in enumerate(actorvalue_data) if goodmask_fromok_value[idx]], ignore_index=True)
  730. df = dfs.sample(800, random_state=37)
  731. fig = plt.figure(figsize=(1., 1.), dpi=300)
  732. ax = fig.add_subplot(111)
  733. ax.set_aspect('equal')
  734. ax.spines['top'].set_visible(False)
  735. ax.spines['right'].set_visible(False)
  736. ax.spines['bottom'].set_visible(False)
  737. ax.spines['left'].set_visible(False)
  738. ax.axes.xaxis.set_ticks([]); ax.axes.yaxis.set_ticks([])
  739. ax.set_xlim([-235, 235]); ax.set_ylim([-2, 430])
  740. for _, trial in df.iterrows():
  741. ax.plot(trial.pos_x, trial.pos_y, c='k', lw=0.3, ls='-', alpha=0.2)
  742. skipped_idexes = df.skipped.values
  743. skipped_idexes = skipped_idexes
  744. for label, mask, c in zip(['Attempted', 'Aborted'], [~skipped_idexes, skipped_idexes],
  745. [attempt_c, abort_c]):
  746. ax.scatter(*df.loc[mask, ['target_x', 'target_y']].values.T,
  747. c=c, marker='o', s=1, lw=0.5)
  748. fig.tight_layout(pad=0)
  749. # %%
  750. # agent 2
  751. dfs = pd.concat([df for idx, df in enumerate(actornovalue_data) if goodmask_fromok_novalue[idx]], ignore_index=True)
  752. df = dfs.sample(800, random_state=1)
  753. fig = plt.figure(figsize=(1., 1.), dpi=300)
  754. ax = fig.add_subplot(111)
  755. ax.set_aspect('equal')
  756. ax.spines['top'].set_visible(False)
  757. ax.spines['right'].set_visible(False)
  758. ax.spines['bottom'].set_visible(False)
  759. ax.spines['left'].set_visible(False)
  760. ax.axes.xaxis.set_ticks([]); ax.axes.yaxis.set_ticks([])
  761. ax.set_xlim([-235, 235]); ax.set_ylim([-2, 430])
  762. for _, trial in df.iterrows():
  763. ax.plot(trial.pos_x, trial.pos_y, c='k', lw=0.3, ls='-', alpha=0.2)
  764. skipped_idexes = df.skipped.values
  765. skipped_idexes = skipped_idexes
  766. for label, mask, c in zip(['Attempted', 'Aborted'], [~skipped_idexes, skipped_idexes],
  767. [attempt_c, abort_c]):
  768. ax.scatter(*df.loc[mask, ['target_x', 'target_y']].values.T,
  769. c=c, marker='o', s=1, lw=0.5)
  770. fig.tight_layout(pad=0)
  771. # %%
  772. # agent 1
  773. dfs = pd.concat([df for idx, df in enumerate(actorholistic_data) if goodmask_fromok_holistic[idx]], ignore_index=True)
  774. df = dfs.sample(800, random_state=1)
  775. fig = plt.figure(figsize=(1., 1.), dpi=300)
  776. ax = fig.add_subplot(111)
  777. ax.set_aspect('equal')
  778. ax.spines['top'].set_visible(False)
  779. ax.spines['right'].set_visible(False)
  780. ax.spines['bottom'].set_visible(False)
  781. ax.spines['left'].set_visible(False)
  782. ax.axes.xaxis.set_ticks([]); ax.axes.yaxis.set_ticks([])
  783. ax.set_xlim([-235, 235]); ax.set_ylim([-2, 430])
  784. for _, trial in df.iterrows():
  785. ax.plot(trial.pos_x, trial.pos_y, c='k', lw=0.3, ls='-', alpha=0.2)
  786. skipped_idexes = df.skipped.values
  787. skipped_idexes = skipped_idexes
  788. for label, mask, c in zip(['Attempted', 'Aborted'], [~skipped_idexes, skipped_idexes],
  789. [attempt_c, abort_c]):
  790. ax.scatter(*df.loc[mask, ['target_x', 'target_y']].values.T,
  791. c=c, marker='o', s=1, lw=0.5)
  792. fig.tight_layout(pad=0)
  793. # %% [markdown]
  794. # ## 2H
  795. # %%
  796. bin_edges = np.arange(100, 401, 10)
  797. skipped_frac_bybin_value = []
  798. for df in actorvalue_data:
  799. skipped_frac_bybin = []
  800. for edge_idx in range(bin_edges.size - 1):
  801. left_edge = bin_edges[edge_idx]
  802. right_edge = bin_edges[edge_idx + 1]
  803. trials_inbin = df.skipped[(df.target_r >= left_edge) & (df.target_r < right_edge)]
  804. skipped_frac_bybin.append(trials_inbin.sum() / len(trials_inbin))
  805. skipped_frac_bybin_value.append(skipped_frac_bybin)
  806. # %%
  807. skipped_frac_bybin_novalue = []
  808. for df in actornovalue_data:
  809. skipped_frac_bybin = []
  810. for edge_idx in range(bin_edges.size - 1):
  811. left_edge = bin_edges[edge_idx]
  812. right_edge = bin_edges[edge_idx + 1]
  813. trials_inbin = df.skipped[(df.target_r >= left_edge) & (df.target_r < right_edge)]
  814. skipped_frac_bybin.append(trials_inbin.sum() / len(trials_inbin))
  815. skipped_frac_bybin_novalue.append(skipped_frac_bybin)
  816. # %%
  817. skipped_frac_bybin_holisticLong = []
  818. for df in actorholisticLong_data:
  819. skipped_frac_bybin = []
  820. for edge_idx in range(bin_edges.size - 1):
  821. left_edge = bin_edges[edge_idx]
  822. right_edge = bin_edges[edge_idx + 1]
  823. trials_inbin = df.skipped[(df.target_r >= left_edge) & (df.target_r < right_edge)]
  824. skipped_frac_bybin.append(trials_inbin.sum() / len(trials_inbin))
  825. skipped_frac_bybin_holisticLong.append(skipped_frac_bybin)
  826. # %%
  827. ymean_value = np.mean(skipped_frac_bybin_value, axis=0)
  828. ysem_value = sem(np.array(skipped_frac_bybin_value), axis=0)
  829. ymean_novalue = np.mean(skipped_frac_bybin_novalue, axis=0)
  830. ysem_novalue = sem(np.array(skipped_frac_bybin_novalue), axis=0)
  831. ymean_holisticLong = np.mean(skipped_frac_bybin_holisticLong, axis=0)
  832. ysem_holisticLong = sem(np.array(skipped_frac_bybin_holisticLong), axis=0)
  833. # %%
  834. width = 1.5; height = 1.3
  835. yticks = np.around(np.linspace(0, 0.8, 5), 1)
  836. xticks = np.arange(100, 401, 100)
  837. fig = plt.figure(figsize=(width, height), dpi=300)
  838. ax = fig.add_subplot(1, 1, 1)
  839. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  840. plt.xticks(xticks, fontsize=fontsize)
  841. plt.yticks(yticks, fontsize=fontsize)
  842. ax.set_xlabel(r'Initial target distance (cm)', fontsize=fontsize + 1)
  843. ax.set_ylabel('Aborted fraction', fontsize=fontsize + 1)
  844. ax.set_xlim(xticks[0], xticks[-1])
  845. ax.set_ylim(yticks[0] - 0.03, yticks[-1])
  846. ax.xaxis.set_label_coords(0.5, -0.2)
  847. ax.yaxis.set_label_coords(-0.15, 0.5)
  848. ax.yaxis.set_major_formatter(major_formatter)
  849. ax.tick_params(axis='both', which='major', pad=2)
  850. xdata = (bin_edges[:-1] + bin_edges[1:]) / 2
  851. ax.plot(xdata, ymean_value, lw=lw*1.5, clip_on=False, c=withvalue_c, alpha=1)
  852. ax.plot(xdata, ymean_novalue, lw=lw*1.5, clip_on=False, c=withoutvalue_c, alpha=1)
  853. ax.plot(xdata, ymean_holisticLong, lw=lw*1.5, clip_on=False, c=holistic_c, alpha=0.5)
  854. ax.fill_between(xdata, ymean_value - ysem_value, ymean_value + ysem_value,
  855. edgecolor='None', facecolor=withvalue_c, alpha=0.6, clip_on=False)
  856. ax.fill_between(xdata, ymean_holisticLong - ysem_holisticLong, ymean_holisticLong + ysem_holisticLong,
  857. edgecolor='None', facecolor=holistic_c, alpha=0.3, clip_on=False)
  858. ax.fill_between(xdata, ymean_novalue - ysem_novalue, ymean_novalue + ysem_novalue,
  859. edgecolor='None', facecolor=withoutvalue_c, alpha=0.6, clip_on=False)
  860. ax.plot([], [], lw=lw, clip_on=False, c=holistic_c, alpha=1, label='Agent 1')
  861. ax.plot([], [], lw=lw, clip_on=False, c=withoutvalue_c, alpha=1, label='Agent 2')
  862. ax.plot([], [], lw=lw, clip_on=False, c=withvalue_c, alpha=1, label='Agent 3')
  863. ax.plot([200 * np.sqrt(2)] * 2, ax.get_ylim(), lw=lw, c='k', ls='--', clip_on=False)
  864. fig.tight_layout(pad=0.3, w_pad=0.5, rect=(0, 0, 1, 1))
  865. ax.legend(fontsize=fontsize - 0.3, frameon=False, loc=[0, 0.45],
  866. handletextpad=0.5, labelspacing=0.1, ncol=1, columnspacing=1)
  867. # %% [markdown]
  868. # ## S3E
  869. # %%
  870. width = 2.7; height = 1.3
  871. yticks = np.around(np.linspace(0, 1, 6), 1)
  872. xticks = np.arange(100, 401, 100)
  873. fig = plt.figure(figsize=(width, height), dpi=300)
  874. ax = fig.add_subplot(131)
  875. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  876. plt.xticks(xticks, fontsize=fontsize)
  877. plt.yticks(yticks, fontsize=fontsize)
  878. ax.set_xlabel(r'Initial target distance (cm)', fontsize=fontsize + 1)
  879. ax.set_ylabel('Aborted fraction', fontsize=fontsize + 1)
  880. ax.set_xlim(xticks[0], xticks[-1])
  881. ax.set_ylim(yticks[0] - 0.01, yticks[-1])
  882. ax.xaxis.set_label_coords(0.65, -0.2)
  883. ax.yaxis.set_label_coords(-0.27, 0.5)
  884. ax.yaxis.set_major_formatter(major_formatter)
  885. ax.tick_params(axis='both', which='major', pad=2)
  886. xdata = (bin_edges[:-1] + bin_edges[1:]) / 2
  887. for v in skipped_frac_bybin_holisticLong:
  888. ax.plot(xdata, v, lw=lw*0.7, clip_on=False, c=holistic_c, alpha=0.5)
  889. ax.plot([200 * np.sqrt(2)] * 2, [0, 1], lw=lw, c='k', ls='--', clip_on=False)
  890. ax = fig.add_subplot(132)
  891. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  892. plt.xticks(xticks, fontsize=fontsize)
  893. plt.yticks(yticks, fontsize=fontsize)
  894. ax.set_xlabel(r'', fontsize=fontsize + 1)
  895. ax.set_ylabel('', fontsize=fontsize + 1)
  896. ax.set_xlim(xticks[0], xticks[-1])
  897. ax.set_ylim(yticks[0] - 0.01, yticks[-1])
  898. ax.xaxis.set_label_coords(0.5, -0.2)
  899. ax.yaxis.set_label_coords(-0.15, 0.5)
  900. ax.yaxis.set_major_formatter(major_formatter)
  901. ax.tick_params(axis='both', which='major', pad=2)
  902. for v in skipped_frac_bybin_novalue:
  903. ax.plot(xdata, v, lw=lw*0.7, clip_on=False, c=withoutvalue_c, alpha=0.5)
  904. ax.plot([200 * np.sqrt(2)] * 2, [0, 1], lw=lw, c='k', ls='--', clip_on=False)
  905. ax = fig.add_subplot(133)
  906. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  907. plt.xticks(xticks, fontsize=fontsize)
  908. plt.yticks(yticks, fontsize=fontsize)
  909. ax.set_xlabel(r'', fontsize=fontsize + 1)
  910. ax.set_ylabel('', fontsize=fontsize + 1)
  911. ax.set_xlim(xticks[0], xticks[-1])
  912. ax.set_ylim(yticks[0] - 0.01, yticks[-1])
  913. ax.xaxis.set_label_coords(0.5, -0.2)
  914. ax.yaxis.set_label_coords(-0.15, 0.5)
  915. ax.yaxis.set_major_formatter(major_formatter)
  916. ax.tick_params(axis='both', which='major', pad=2)
  917. for v in skipped_frac_bybin_value:
  918. ax.plot(xdata, v, lw=lw*0.7, clip_on=False, c=withvalue_c, alpha=0.5)
  919. ax.plot([200 * np.sqrt(2)] * 2, [0, 1], lw=lw, c='k', ls='--', clip_on=False)
  920. fig.tight_layout(pad=0, w_pad=0, rect=(0, 0, 1, 1))
  921. # %% [markdown]
  922. # ## S4A
  923. # %%
  924. b__ = []; av__ = []; aw__ = []; x__ = []; rewarded_frac = []; skipped_frac = []; reward_rate = []
  925. for df, agent in zip(actorholisticLong_data, actorholisticLong_agents):
  926. actor = agent.actor
  927. b_ = []; av_ = [];aw_ = []; x_ = []
  928. for trial in df.itertuples():
  929. b_.append(trial.relative_radius)
  930. x = trial.state[..., :-1]
  931. with torch.no_grad():
  932. x, _ = actor.rnn(x)
  933. a = actor.l1(x)
  934. x_.append(x.squeeze().numpy())
  935. av_.append(a.squeeze()[:, 0].numpy())
  936. aw_.append(a.squeeze()[:, 1].numpy())
  937. b__.append(np.hstack(b_)); av__.append(np.hstack(av_)); aw__.append(np.hstack(aw_)); x__.append(np.concatenate(x_))
  938. rewarded_frac.append(df.rewarded.sum() / len(df))
  939. reward_rate.append(df.rewarded.sum() / (np.hstack(df.pos_x).size - len(df)) / arg.DT)
  940. skipped_frac.append(df.skipped.sum() / len(df))
  941. rewarded_frac = np.array(rewarded_frac); skipped_frac = np.array(skipped_frac); reward_rate = np.array(reward_rate)
  942. # %%
  943. def get_tuning_corrs(b__, av__, aw__, x__, corr_thre=0.5):
  944. count_b_cav_tune = []; count_b_caw_tune = []
  945. count_av_cb_tune = []; count_aw_cb_tune = []
  946. count_b_av_tune = []; count_b_aw_tune = []
  947. for b, av, aw, x in zip(b__, av__, aw__, x__):
  948. corrxb_av = [];corrxb_aw = []
  949. corrxav_b = []; corrxaw_b = []
  950. # av
  951. rbav = np.corrcoef(av, b)[0, 1]
  952. for neural_idx in range(x.shape[1]):
  953. rxb = np.corrcoef(x[:, neural_idx], b)[0, 1]
  954. rxav = np.corrcoef(x[:, neural_idx], av)[0, 1]
  955. rxb_av = (rxb - rxav * rbav) / np.sqrt((1-rxav**2) * (1-rbav**2))
  956. corrxb_av.append(rxb)
  957. rxav_b = (rxav - rxb * rbav) / np.sqrt((1-rxb**2) * (1-rbav**2))
  958. corrxav_b.append(rxav)
  959. # aw
  960. rbaw = np.corrcoef(aw, b)[0, 1]
  961. for neural_idx in range(x.shape[1]):
  962. rxb = np.corrcoef(x[:, neural_idx], b)[0, 1]
  963. rxaw = np.corrcoef(x[:, neural_idx], aw)[0, 1]
  964. rxb_aw = (rxb - rxaw * rbaw) / np.sqrt((1-rxaw**2) * (1-rbaw**2))
  965. corrxb_aw.append(rxb)
  966. rxaw_b = (rxaw - rxb * rbaw) / np.sqrt((1-rxb**2) * (1-rbaw**2))
  967. corrxaw_b.append(rxaw)
  968. corrxb_av = np.array(corrxb_av); corrxb_aw = np.array(corrxb_aw)
  969. corrxav_b = np.array(corrxav_b); corrxaw_b = np.array(corrxaw_b)
  970. tuneb_av_idx = np.where(abs(corrxb_av) > corr_thre)[0]
  971. tuneb_aw_idx = np.where(abs(corrxb_aw) > corr_thre)[0]
  972. tuneav_b_idx = np.where(abs(corrxav_b) > corr_thre)[0]
  973. tuneaw_b_idx = np.where(abs(corrxaw_b) > corr_thre)[0]
  974. count_b_cav_tune.append(tuneb_av_idx.size); count_b_caw_tune.append(tuneb_aw_idx.size)
  975. count_av_cb_tune.append(tuneav_b_idx.size); count_aw_cb_tune.append(tuneaw_b_idx.size);
  976. count_b_av_tune.append(np.intersect1d(np.intersect1d(tuneav_b_idx, tuneaw_b_idx), tuneb_av_idx).size)
  977. count_b_aw_tune.append(np.intersect1d(tuneb_aw_idx, tuneaw_b_idx).size)
  978. count_b_cav_tune = np.array(count_b_cav_tune); count_b_caw_tune = np.array(count_b_caw_tune)
  979. count_av_cb_tune = np.array(count_av_cb_tune); count_aw_cb_tune = np.array(count_aw_cb_tune)
  980. count_b_av_tune = np.array(count_b_av_tune); count_b_aw_tune = np.array(count_b_aw_tune)
  981. return count_b_cav_tune, count_b_caw_tune, count_av_cb_tune, count_aw_cb_tune, count_b_av_tune, count_b_aw_tune
  982. # %%
  983. count_b_cav_tune = []; count_b_caw_tune = []
  984. count_av_cb_tune = []; count_aw_cb_tune = []
  985. count_b_av_tune = []; count_b_aw_tune = []
  986. corr_countb_cav_reward = []; corr_countb_caw_reward = []
  987. corr_countav_cb_reward = []; corr_countaw_cb_reward = []
  988. corr_countb_av_reward = []; corr_countb_aw_reward = []
  989. p_countb_cav_reward = []; p_countb_caw_reward = []
  990. p_countav_cb_reward = []; p_countaw_cb_reward = []
  991. p_countb_av_reward = []; p_countb_aw_reward = []
  992. thresholds = np.array([0.1, 0.2, 0.3, 0.4, 0.5])
  993. for corr_thre in thresholds:
  994. count_b_cav_tune_, count_b_caw_tune_, count_av_cb_tune_, \
  995. count_aw_cb_tune_, count_b_av_tune_, count_b_aw_tune_ = get_tuning_corrs(b__, av__, aw__, x__, corr_thre=corr_thre)
  996. count_b_cav_tune.append(count_b_cav_tune_)
  997. count_b_caw_tune.append(count_b_caw_tune_)
  998. count_av_cb_tune.append(count_av_cb_tune_)
  999. count_aw_cb_tune.append(count_aw_cb_tune_)
  1000. count_b_av_tune.append(count_b_av_tune_)
  1001. count_b_aw_tune.append(count_b_aw_tune_)
  1002. method = None
  1003. r = pearsonr(count_b_cav_tune_, rewarded_frac)
  1004. corr_countb_cav_reward.append(r.statistic)
  1005. p_countb_cav_reward.append(r.pvalue)
  1006. r = pearsonr(count_b_caw_tune_, rewarded_frac)
  1007. corr_countb_caw_reward.append(r.statistic)
  1008. p_countb_caw_reward.append(r.pvalue)
  1009. r = pearsonr(count_av_cb_tune_, rewarded_frac)
  1010. corr_countav_cb_reward.append(r.statistic)
  1011. p_countav_cb_reward.append(r.pvalue)
  1012. r = pearsonr(count_aw_cb_tune_, rewarded_frac)
  1013. corr_countaw_cb_reward.append(r.statistic)
  1014. p_countaw_cb_reward.append(r.pvalue)
  1015. r = pearsonr(count_b_av_tune_, rewarded_frac)
  1016. corr_countb_av_reward.append(r.statistic)
  1017. p_countb_av_reward.append(r.pvalue)
  1018. r = pearsonr(count_b_aw_tune_, rewarded_frac)
  1019. corr_countb_aw_reward.append(r.statistic)
  1020. p_countb_aw_reward.append(r.pvalue)
  1021. corr_countb_cav_reward, corr_countb_caw_reward, corr_countav_cb_reward,\
  1022. corr_countaw_cb_reward, corr_countb_av_reward, corr_countb_aw_reward = map(np.array, [corr_countb_cav_reward,
  1023. corr_countb_caw_reward, corr_countav_cb_reward, corr_countaw_cb_reward, corr_countb_av_reward, corr_countb_aw_reward])
  1024. p_countb_cav_reward, p_countb_caw_reward, p_countav_cb_reward,\
  1025. p_countaw_cb_reward, p_countb_av_reward, p_countb_aw_reward = map(np.array, [p_countb_cav_reward,
  1026. p_countb_caw_reward, p_countav_cb_reward, p_countaw_cb_reward, p_countb_av_reward, p_countb_aw_reward])
  1027. # %%
  1028. width = 0.8; height = 0.8
  1029. yticks = np.around(np.linspace(0, 1, 6), 1)
  1030. xticks = np.arange(0, 201, 50)
  1031. fig = plt.figure(figsize=(width, height), dpi=300)
  1032. ax = fig.add_subplot(1, 1, 1)
  1033. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  1034. plt.xticks(xticks, fontsize=fontsize - 1)
  1035. plt.yticks(yticks, fontsize=fontsize - 1)
  1036. ax.set_xlabel(r'', fontsize=fontsize + 1)
  1037. ax.set_ylabel('', fontsize=fontsize + 1)
  1038. ax.set_xlim(xticks[0], xticks[-1])
  1039. ax.set_ylim(yticks[0], yticks[-1])
  1040. ax.yaxis.set_major_formatter(major_formatter)
  1041. ax.tick_params(axis='both', which='major', pad=2)
  1042. xdata = count_av_cb_tune[2]; ydata = rewarded_frac
  1043. ax.scatter(xdata, ydata, s=1, c=holistic_c, clip_on=False)
  1044. ax.text(10, 0.02, f'$p={np.around(corr_countav_cb_reward[2], 2)}$', fontsize=fontsize)
  1045. model = LinearRegression()
  1046. model.fit(xdata.reshape(-1, 1), ydata)
  1047. xata = np.linspace(*ax.get_xlim())
  1048. ax.plot(xata, model.predict(xata.reshape(-1, 1)), lw=lw, c='k', zorder=0, ls='-')
  1049. fig.tight_layout(pad=0, w_pad=0, rect=(0, 0, 1, 1))
  1050. # %%
  1051. width = 0.8; height = 0.8
  1052. yticks = np.around(np.linspace(0, 1, 6), 1)
  1053. xticks = np.arange(0, 201, 50)
  1054. fig = plt.figure(figsize=(width, height), dpi=300)
  1055. ax = fig.add_subplot(1, 1, 1)
  1056. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  1057. plt.xticks(xticks, fontsize=fontsize - 1)
  1058. plt.yticks(yticks, fontsize=fontsize - 1)
  1059. ax.set_xlabel(r'', fontsize=fontsize + 1)
  1060. ax.set_ylabel('', fontsize=fontsize + 1)
  1061. ax.set_xlim(xticks[0], xticks[-1])
  1062. ax.set_ylim(yticks[0], yticks[-1])
  1063. ax.yaxis.set_major_formatter(major_formatter)
  1064. ax.tick_params(axis='both', which='major', pad=2)
  1065. xdata = count_aw_cb_tune[2]; ydata = rewarded_frac
  1066. ax.scatter(xdata, ydata, s=1, c=holistic_c, clip_on=False)
  1067. ax.text(70, 0.7, f'$p={np.around(corr_countaw_cb_reward[2], 2)}$', fontsize=fontsize)
  1068. model = LinearRegression()
  1069. model.fit(xdata.reshape(-1, 1), ydata)
  1070. xata = np.linspace(*ax.get_xlim())
  1071. ax.plot(xata, model.predict(xata.reshape(-1, 1)), lw=lw, c='k', zorder=0, ls='-')
  1072. fig.tight_layout(pad=0, w_pad=0, rect=(0, 0, 1, 1))
  1073. # %%
  1074. width = 0.8; height = 0.8
  1075. yticks = np.around(np.linspace(0, 1, 6), 1)
  1076. xticks = np.arange(0, 201, 50)
  1077. fig = plt.figure(figsize=(width, height), dpi=300)
  1078. ax = fig.add_subplot(1, 1, 1)
  1079. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  1080. plt.xticks(xticks, fontsize=fontsize - 1)
  1081. plt.yticks(yticks, fontsize=fontsize - 1)
  1082. ax.set_xlabel(r'', fontsize=fontsize + 1)
  1083. ax.set_ylabel('', fontsize=fontsize + 1)
  1084. ax.set_xlim(xticks[0], xticks[-1])
  1085. ax.set_ylim(yticks[0], yticks[-1])
  1086. ax.yaxis.set_major_formatter(major_formatter)
  1087. ax.tick_params(axis='both', which='major', pad=2)
  1088. xdata = count_b_cav_tune[2]; ydata = rewarded_frac
  1089. ax.scatter(xdata, ydata, s=1, c=holistic_c, clip_on=False)
  1090. ax.text(10, 0.02, f'$p={np.around(corr_countb_cav_reward[2], 2)}$', fontsize=fontsize)
  1091. model = LinearRegression()
  1092. model.fit(xdata.reshape(-1, 1), ydata)
  1093. xata = np.linspace(*ax.get_xlim())
  1094. ax.plot(xata, model.predict(xata.reshape(-1, 1)), lw=lw, c='k', zorder=0, ls='-')
  1095. fig.tight_layout(pad=0, w_pad=0, rect=(0, 0, 1, 1))
  1096. # %%
  1097. width = 0.8; height = 0.8
  1098. yticks = np.around(np.linspace(0, 1, 6), 1)
  1099. xticks = np.arange(0, 201, 50)
  1100. fig = plt.figure(figsize=(width, height), dpi=300)
  1101. ax = fig.add_subplot(1, 1, 1)
  1102. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  1103. plt.xticks(xticks, fontsize=fontsize - 1)
  1104. plt.yticks(yticks, fontsize=fontsize - 1)
  1105. ax.set_xlabel(r'', fontsize=fontsize + 1)
  1106. ax.set_ylabel('', fontsize=fontsize + 1)
  1107. ax.set_xlim(xticks[0], xticks[-1])
  1108. ax.set_ylim(yticks[0], yticks[-1])
  1109. ax.yaxis.set_major_formatter(major_formatter)
  1110. ax.tick_params(axis='both', which='major', pad=2)
  1111. xdata = count_b_av_tune[2]; ydata = rewarded_frac
  1112. ax.scatter(xdata, ydata, s=1, c=holistic_c, clip_on=False)
  1113. ax.text(70, 0.7, f'$p={np.around(corr_countb_av_reward[2], 2)}$', fontsize=fontsize)
  1114. model = LinearRegression()
  1115. model.fit(xdata.reshape(-1, 1), ydata)
  1116. xata = np.linspace(*ax.get_xlim())
  1117. ax.plot(xata, model.predict(xata.reshape(-1, 1)), lw=lw, c='k', zorder=0, ls='-')
  1118. fig.tight_layout(pad=0, w_pad=0, rect=(0, 0, 1, 1))
  1119. # %% [markdown]
  1120. # ## S4B
  1121. # %%
  1122. width = 1.4; height = 1.2
  1123. yticks = np.around(np.linspace(-1, 0, 6), 1)
  1124. xticks = xdata = thresholds
  1125. fig = plt.figure(figsize=(width, height), dpi=300)
  1126. ax = fig.add_subplot(111)
  1127. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  1128. plt.xticks(xticks, fontsize=fontsize)
  1129. plt.yticks(yticks, fontsize=fontsize)
  1130. ax.set_xlabel(r'', fontsize=fontsize + 1)
  1131. ax.set_ylabel('', fontsize=fontsize + 1)
  1132. ax.set_xlim(xticks[0] - 0.05, xticks[-1] + 0.05)
  1133. ax.set_ylim(yticks[0], yticks[-1])
  1134. ax.yaxis.set_major_formatter(major_formatter)
  1135. ax.xaxis.set_major_formatter(major_formatter)
  1136. ax.tick_params(axis='both', which='major', pad=2)
  1137. mask = p_countav_cb_reward < 0.05
  1138. ax.scatter(xdata[mask], corr_countav_cb_reward[mask], c='C5', s=8, lw=0)
  1139. ax.plot(xdata[mask], corr_countav_cb_reward[mask], lw=lw, c='C5')
  1140. mask = p_countav_cb_reward >= 0.05
  1141. ax.scatter(xdata[mask], corr_countav_cb_reward[mask], c='C5', alpha=0.3, s=8, lw=0)
  1142. mask = p_countaw_cb_reward < 0.05
  1143. ax.scatter(xdata[mask], corr_countaw_cb_reward[mask], c='C6', s=8, lw=0)
  1144. ax.plot(xdata[mask], corr_countaw_cb_reward[mask], lw=lw, c='C6')
  1145. mask = p_countaw_cb_reward >= 0.05
  1146. ax.scatter(xdata[mask], corr_countaw_cb_reward[mask], c='C6', alpha=0.3, s=8, lw=0)
  1147. mask = p_countb_cav_reward < 0.05
  1148. ax.scatter(xdata[mask], corr_countb_cav_reward[mask], c='C4', s=8, lw=0)
  1149. ax.plot(xdata[mask], corr_countb_cav_reward[mask], lw=lw, c='C4')
  1150. mask = p_countb_cav_reward >= 0.05
  1151. ax.scatter(xdata[mask], corr_countb_cav_reward[mask], c='C4', alpha=0.3, s=8, lw=0)
  1152. mask = p_countb_av_reward < 0.05
  1153. ax.scatter(xdata[mask], corr_countb_av_reward[mask], c='C8', s=8, lw=0)
  1154. ax.plot(xdata[mask], corr_countb_av_reward[mask], lw=lw, c='C8')
  1155. mask = p_countb_av_reward >= 0.05
  1156. ax.scatter(xdata[mask], corr_countb_av_reward[mask], c='C8', alpha=0.3, s=8, lw=0)
  1157. fig.tight_layout(pad=0, w_pad=0, rect=(0, 0, 1, 1))
  1158. # %% [markdown]
  1159. # ## 3A
  1160. # %%
  1161. def get_valuediff(b, critic):
  1162. with torch.no_grad():
  1163. u1 = torch.zeros(b.shape[0], b.shape[1], 2, device=b.device)
  1164. u2 = torch.zeros(b.shape[0], b.shape[1], 2, device=b.device); u2[..., 0] = 1
  1165. v_ = []
  1166. for u in [u1, u2]:
  1167. v = F.relu(critic.l1(torch.cat([b, u], dim=2)))
  1168. v = F.relu(critic.l2(v))
  1169. v = critic.l3(v)
  1170. v_.append(v)
  1171. v = v_[0] - v_[1]
  1172. return v / 5
  1173. # %%
  1174. actorvalue_agent_values = []
  1175. for agent, states_ in zip(actorvalue_agents, actorvalue_data):
  1176. actor = agent.actor; critic = agent.critic
  1177. states = states_.state
  1178. vs = []
  1179. for state in states:
  1180. x = state[..., :-1]
  1181. with torch.no_grad():
  1182. b, _ = critic.rnn1(x)
  1183. v = get_valuediff(b, critic)
  1184. v = v.squeeze(1).numpy()
  1185. vs.append(v)
  1186. actorvalue_agent_values.append(vs)
  1187. # %%
  1188. actornovalue_agent_values = []
  1189. for agent, states_ in zip(actornovalue_agents, actornovalue_data):
  1190. actor = agent.actor; critic = agent.critic
  1191. states = states_.state
  1192. vs = []
  1193. for state in states:
  1194. x = state[..., :-1]
  1195. with torch.no_grad():
  1196. b, _ = critic.rnn1(x)
  1197. v = get_valuediff(b, critic)
  1198. v = v.squeeze(1).numpy()
  1199. vs.append(v)
  1200. actornovalue_agent_values.append(vs)
  1201. # %%
  1202. target_idexes = np.arange(0, 800)
  1203. i = -17
  1204. df = actornovalue_data[i]
  1205. value_diffs = actornovalue_agent_values[i]
  1206. fig = plt.figure(figsize=(1.7, 0.8), dpi=300)
  1207. ax = fig.add_subplot(121)
  1208. ax.set_aspect('equal')
  1209. ax.spines['top'].set_visible(False)
  1210. ax.spines['right'].set_visible(False)
  1211. ax.spines['bottom'].set_visible(False)
  1212. ax.spines['left'].set_visible(False)
  1213. ax.axes.xaxis.set_ticks([]); ax.axes.yaxis.set_ticks([])
  1214. ax.set_xlim([-235, 235]); ax.set_ylim([-2, 430])
  1215. skipped_idexes = np.hstack([v[1] for v in value_diffs]) > 0
  1216. skipped_idexes = skipped_idexes[:target_idexes.size]
  1217. for label, mask, c in zip(['Aborted', 'Attempted'], [skipped_idexes, ~skipped_idexes],
  1218. [abort_c, attempt_c]):
  1219. ax.scatter(*df.iloc[target_idexes].loc[mask, ['target_x', 'target_y']].values.T,
  1220. c=c, marker='o', s=1, lw=0, label=label)
  1221. x = np.linspace(-165, 165)
  1222. y = np.sqrt((200 * np.sqrt(2))**2 - x**2)
  1223. ax.plot(x, y, lw=lw*0.8, c='k', ls='--')
  1224. ax = fig.add_subplot(122)
  1225. ax.set_aspect('equal')
  1226. ax.spines['top'].set_visible(False)
  1227. ax.spines['right'].set_visible(False)
  1228. ax.spines['bottom'].set_visible(False)
  1229. ax.spines['left'].set_visible(False)
  1230. ax.axes.xaxis.set_ticks([]); ax.axes.yaxis.set_ticks([])
  1231. ax.set_xlim([-235, 235]); ax.set_ylim([-2, 430])
  1232. skipped_idexes = df.skipped.iloc[target_idexes].values
  1233. skipped_idexes = skipped_idexes[:target_idexes.size]
  1234. for label, mask, c in zip(['Aborted', 'Attempted'], [skipped_idexes, ~skipped_idexes],
  1235. [abort_c, attempt_c]):
  1236. ax.scatter(*df.iloc[target_idexes].loc[mask, ['target_x', 'target_y']].values.T,
  1237. c=c, marker='o', s=1, lw=0, label=label)
  1238. x = np.linspace(-165, 165)
  1239. y = np.sqrt((200 * np.sqrt(2))**2 - x**2)
  1240. ax.plot(x, y, lw=lw*0.8, c='k', ls='--')
  1241. fig.tight_layout(pad=0)
  1242. # %%
  1243. target_idexes = np.arange(0, 800)
  1244. i = 25
  1245. df = actorvalue_data[i]
  1246. value_diffs = actorvalue_agent_values[i]
  1247. fig = plt.figure(figsize=(1.7, 0.8), dpi=300)
  1248. ax = fig.add_subplot(121)
  1249. ax.set_aspect('equal')
  1250. ax.spines['top'].set_visible(False)
  1251. ax.spines['right'].set_visible(False)
  1252. ax.spines['bottom'].set_visible(False)
  1253. ax.spines['left'].set_visible(False)
  1254. ax.axes.xaxis.set_ticks([]); ax.axes.yaxis.set_ticks([])
  1255. ax.set_xlim([-235, 235]); ax.set_ylim([-2, 430])
  1256. skipped_idexes = np.hstack([v[1] for v in value_diffs]) > 0
  1257. skipped_idexes = skipped_idexes[:target_idexes.size]
  1258. for label, mask, c in zip(['Aborted', 'Attempted'], [skipped_idexes, ~skipped_idexes],
  1259. [abort_c, attempt_c]):
  1260. ax.scatter(*df.iloc[target_idexes].loc[mask, ['target_x', 'target_y']].values.T,
  1261. c=c, marker='o', s=1, lw=0, label=label)
  1262. x = np.linspace(-165, 165)
  1263. y = np.sqrt((200 * np.sqrt(2))**2 - x**2)
  1264. ax.plot(x, y, lw=lw*0.8, c='k', ls='--')
  1265. ax = fig.add_subplot(122)
  1266. ax.set_aspect('equal')
  1267. ax.spines['top'].set_visible(False)
  1268. ax.spines['right'].set_visible(False)
  1269. ax.spines['bottom'].set_visible(False)
  1270. ax.spines['left'].set_visible(False)
  1271. ax.axes.xaxis.set_ticks([]); ax.axes.yaxis.set_ticks([])
  1272. ax.set_xlim([-235, 235]); ax.set_ylim([-2, 430])
  1273. skipped_idexes = df.skipped.iloc[target_idexes].values
  1274. skipped_idexes = skipped_idexes[:target_idexes.size]
  1275. for label, mask, c in zip(['Aborted', 'Attempted'], [skipped_idexes, ~skipped_idexes],
  1276. [abort_c, attempt_c]):
  1277. ax.scatter(*df.iloc[target_idexes].loc[mask, ['target_x', 'target_y']].values.T,
  1278. c=c, marker='o', s=1, lw=0, label=label)
  1279. x = np.linspace(-165, 165)
  1280. y = np.sqrt((200 * np.sqrt(2))**2 - x**2)
  1281. ax.plot(x, y, lw=lw*0.8, c='k', ls='--')
  1282. fig.tight_layout(pad=0)
  1283. # %% [markdown]
  1284. # ## 3B
  1285. # %%
  1286. actorvalue_isfartar = np.hstack([df.target_r > 200 * np.sqrt(2) for df in actorvalue_data])
  1287. actorvalue_isvalueskip = np.hstack([np.hstack([v2[1] for v2 in v1]) for v1 in actorvalue_agent_values]) > 0
  1288. actorvalue_isskipped = np.hstack([(df.skipped) for df in actorvalue_data])
  1289. df = pd.DataFrame({'dist': actorvalue_isfartar, 'value': actorvalue_isvalueskip, 'behv': actorvalue_isskipped})
  1290. actorvalue_distvalue_crosstab = pd.crosstab(df.value, df.dist)
  1291. actorvalue_distvalue_crosstab /= actorvalue_distvalue_crosstab.values.sum()
  1292. actorvalue_valuebehv_crosstab = pd.crosstab(df.behv, df.value)
  1293. actorvalue_valuebehv_crosstab /= actorvalue_valuebehv_crosstab.values.sum()
  1294. # %%
  1295. actornovalue_isfartar = np.hstack([df.target_r > 200 * np.sqrt(2) for df in actornovalue_data])
  1296. actornovalue_isvalueskip = np.hstack([np.hstack([v2[1] for v2 in v1]) for v1 in actornovalue_agent_values]) > 0
  1297. actornovalue_isskipped = np.hstack([(df.skipped) for df in actornovalue_data])
  1298. df = pd.DataFrame({'dist': actornovalue_isfartar, 'value': actornovalue_isvalueskip, 'behv': actornovalue_isskipped})
  1299. actornovalue_distvalue_crosstab = pd.crosstab(df.value, df.dist)
  1300. actornovalue_distvalue_crosstab /= actornovalue_distvalue_crosstab.values.sum()
  1301. actornovalue_valuebehv_crosstab = pd.crosstab(df.behv, df.value)
  1302. actornovalue_valuebehv_crosstab /= actornovalue_valuebehv_crosstab.values.sum()
  1303. # %%
  1304. ticks = [0, 1]
  1305. fig = plt.figure(figsize=(1.7, 0.9), dpi=300)
  1306. ax = fig.add_subplot(121)
  1307. ax.set_title('Agent 2', fontsize=fontsize, c=withoutvalue_c, pad=4)
  1308. plt.xticks(ticks, ['close', 'far'], fontsize=fontsize - 1)
  1309. plt.yticks(ticks, ['attempt', 'abort'], fontsize=fontsize - 1)
  1310. ax.set_xlabel(r'', fontsize=fontsize)
  1311. ax.set_ylabel('', fontsize=fontsize)
  1312. ax.xaxis.set_label_coords(0.5, -0.25)
  1313. ax.yaxis.set_label_coords(-0.57, 0.5)
  1314. ax.tick_params(axis='both', which='major', pad=1, length=2.5)
  1315. ax.imshow(actornovalue_distvalue_crosstab * 0, cmap='hot_r')
  1316. ax.plot([0.5, 0.5], [-0.5, 1.5], c='k', lw=lw)
  1317. ax.plot([-0.5, 1.5], [0.5, 0.5], c='k', lw=lw)
  1318. ax.text(0, 0, np.around(actornovalue_distvalue_crosstab.values[0, 0], 3), fontsize=fontsize - 1, ha='center', va='center')
  1319. ax.text(1, 0, np.around(actornovalue_distvalue_crosstab.values[0, 1], 3), fontsize=fontsize - 1, ha='center', va='center')
  1320. ax.text(0, 1, np.around(actornovalue_distvalue_crosstab.values[1, 0], 3), fontsize=fontsize - 1, ha='center', va='center')
  1321. ax.text(1, 1, np.around(actornovalue_distvalue_crosstab.values[1, 1], 3), fontsize=fontsize - 1, ha='center', va='center')
  1322. ax = fig.add_subplot(122)
  1323. ax.set_title('Agent 3', fontsize=fontsize, c=withvalue_c, pad=4)
  1324. plt.xticks(ticks, ['', ''], fontsize=fontsize - 1)
  1325. plt.yticks(ticks, ['', ''], fontsize=fontsize - 1)
  1326. ax.set_xlabel(r'', fontsize=fontsize)
  1327. ax.set_ylabel('', fontsize=fontsize)
  1328. ax.tick_params(axis='both', which='major', pad=1, length=2.5)
  1329. ax.imshow(actorvalue_distvalue_crosstab * 0, cmap='hot_r')
  1330. ax.plot([0.5, 0.5], [-0.5, 1.5], c='k', lw=lw)
  1331. ax.plot([-0.5, 1.5], [0.5, 0.5], c='k', lw=lw)
  1332. ax.text(0, 0, np.around(actorvalue_distvalue_crosstab.values[0, 0], 3), fontsize=fontsize - 1, ha='center', va='center')
  1333. ax.text(1, 0, np.around(actorvalue_distvalue_crosstab.values[0, 1], 3), fontsize=fontsize - 1, ha='center', va='center')
  1334. ax.text(0, 1, np.around(actorvalue_distvalue_crosstab.values[1, 0], 3), fontsize=fontsize - 1, ha='center', va='center')
  1335. ax.text(1, 1, np.around(actorvalue_distvalue_crosstab.values[1, 1], 3), fontsize=fontsize - 1, ha='center', va='center')
  1336. fig.tight_layout(pad=0.5, w_pad=0.7, rect=(0, -0.01, 1, 0.99))
  1337. # %%
  1338. ticks = [0, 1]
  1339. fig = plt.figure(figsize=(1.7, 0.9), dpi=300)
  1340. ax = fig.add_subplot(121)
  1341. ax.set_title('Agent 2', fontsize=fontsize, c=withoutvalue_c, pad=4)
  1342. plt.yticks(ticks, ['attempt', 'abort'], fontsize=fontsize - 1)
  1343. plt.xticks(ticks, ['attempt', 'abort'], fontsize=fontsize - 1)
  1344. ax.set_ylabel(r'', fontsize=fontsize)
  1345. ax.set_xlabel('', fontsize=fontsize)
  1346. ax.xaxis.set_label_coords(0.5, -0.25)
  1347. ax.yaxis.set_label_coords(-0.57, 0.5)
  1348. ax.tick_params(axis='both', which='major', pad=1, length=2.5)
  1349. ax.imshow(actornovalue_valuebehv_crosstab * 0, cmap='hot_r')
  1350. ax.plot([0.5, 0.5], [-0.5, 1.5], c='k', lw=lw)
  1351. ax.plot([-0.5, 1.5], [0.5, 0.5], c='k', lw=lw)
  1352. ax.text(0, 0, np.around(actornovalue_valuebehv_crosstab.values[0, 0], 3), fontsize=fontsize - 1, ha='center', va='center')
  1353. ax.text(1, 0, np.around(actornovalue_valuebehv_crosstab.values[0, 1], 3), fontsize=fontsize - 1, ha='center', va='center',
  1354. c='r')
  1355. ax.text(0, 1, np.around(actornovalue_valuebehv_crosstab.values[1, 0], 3), fontsize=fontsize - 1, ha='center', va='center')
  1356. ax.text(1, 1, np.around(actornovalue_valuebehv_crosstab.values[1, 1], 3), fontsize=fontsize - 1, ha='center', va='center',
  1357. c='r')
  1358. ax = fig.add_subplot(122)
  1359. ax.set_title('Agent 3', fontsize=fontsize, c=withvalue_c, pad=4)
  1360. plt.xticks(ticks, ['', ''], fontsize=fontsize - 1)
  1361. plt.yticks(ticks, ['', ''], fontsize=fontsize - 1)
  1362. ax.set_xlabel(r'', fontsize=fontsize)
  1363. ax.set_ylabel('', fontsize=fontsize)
  1364. ax.tick_params(axis='both', which='major', pad=1, length=2.5)
  1365. ax.imshow(actorvalue_valuebehv_crosstab * 0, cmap='hot_r')
  1366. ax.plot([0.5, 0.5], [-0.5, 1.5], c='k', lw=lw)
  1367. ax.plot([-0.5, 1.5], [0.5, 0.5], c='k', lw=lw)
  1368. ax.text(0, 0, np.around(actorvalue_valuebehv_crosstab.values[0, 0], 3), fontsize=fontsize - 1, ha='center', va='center')
  1369. ax.text(1, 0, np.around(actorvalue_valuebehv_crosstab.values[0, 1], 3), fontsize=fontsize - 1, ha='center', va='center',
  1370. c='r')
  1371. ax.text(0, 1, np.around(actorvalue_valuebehv_crosstab.values[1, 0], 3), fontsize=fontsize - 1, ha='center', va='center')
  1372. ax.text(1, 1, np.around(actorvalue_valuebehv_crosstab.values[1, 1], 3), fontsize=fontsize - 1, ha='center', va='center',
  1373. c='r')
  1374. fig.tight_layout(pad=0.5, w_pad=0.7, rect=(0, -0.01, 1, 0.99))
  1375. # %% [markdown]
  1376. # ## 3C
  1377. # %%
  1378. width = 1; height = 1
  1379. yticks = np.around(np.linspace(0, 0.5, 6), 1)
  1380. fig = plt.figure(figsize=(width, height), dpi=300)
  1381. ax = fig.add_subplot(1, 1, 1)
  1382. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  1383. plt.yticks(yticks, fontsize=fontsize)
  1384. ax.set_ylabel('Attempted fraction', fontsize=fontsize)
  1385. ax.set_ylim(yticks[0], yticks[-1])
  1386. ax.yaxis.set_label_coords(-0.25, 0.5)
  1387. ax.yaxis.set_major_formatter(major_formatter)
  1388. ax.tick_params(axis='both', which='major', pad=2)
  1389. species = ("Agent 2", "Agent 3")
  1390. barwidth = 0.5
  1391. d1 = actornovalue_valuebehv_crosstab.values[:, 1]
  1392. d1 /= d1.sum()
  1393. d2 = actorvalue_valuebehv_crosstab.values[:, 1]
  1394. d2 /= d2.sum()
  1395. p = ax.bar(species, [d1[0], d2[0]], barwidth, color=[withoutvalue_c, withvalue_c])
  1396. plt.xticks(fontsize=fontsize-0.3)
  1397. fig.tight_layout(pad=0.3, w_pad=0.5, rect=(0, 0, 1, 1))
  1398. # %% [markdown]
  1399. # ## 2I
  1400. # %%
  1401. reward_rate_value = np.array([df.rewarded.sum() / ((np.hstack(df.pos_x).size - len(df)) * arg.DT)
  1402. for df in actorvalue_data])
  1403. reward_rate_novalue = np.array([df.rewarded.sum() / ((np.hstack(df.pos_x).size - len(df)) * arg.DT)
  1404. for df in actornovalue_data])
  1405. reward_rate_holistic = np.array([df.rewarded.sum() / ((np.hstack(df.pos_x).size - len(df)) * arg.DT)
  1406. for df in actorholistic_data])
  1407. reward_rate_holisticLong = np.array([df.rewarded.sum() / ((np.hstack(df.pos_x).size - len(df)) * arg.DT)
  1408. for df in actorholisticLong_data])
  1409. skip_diff_value = np.array([df.skipped.sum() / len(df) for df in actorvalue_data])
  1410. skip_diff_novalue = np.array([df.skipped.sum() / len(df) for df in actornovalue_data])
  1411. skip_diff_holistic = np.array([df.skipped.sum() / len(df) for df in actorholistic_data])
  1412. skip_diff_holisticLong = np.array([df.skipped.sum() / len(df) for df in actorholisticLong_data])
  1413. badseedidces_novalue = np.where(okseed_mask_novalue)[0][np.where(reward_rate_novalue < 0.6)[0]]
  1414. badseedidces_holistic = np.where(okseed_mask_holistic)[0][np.where(reward_rate_holistic < 0.6)[0]]
  1415. badseedidces_holisticLong = np.where(okseed_mask_holisticLong)[0][np.where(reward_rate_holisticLong < 0.6)[0]]
  1416. # %%
  1417. width = 1.5; height = 1.3
  1418. xticks = np.around(np.linspace(0, 0.7, 8), 1)
  1419. yticks = np.around(np.linspace(0.2, 0.9, 8), 1)
  1420. fig = plt.figure(figsize=(width, height), dpi=300)
  1421. ax = fig.add_subplot(1, 1, 1)
  1422. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  1423. plt.xticks(xticks, fontsize=fontsize)
  1424. plt.yticks(yticks, fontsize=fontsize)
  1425. ax.set_ylabel(r'Reward rate (trial/s)', fontsize=fontsize + 1)
  1426. ax.set_xlabel('Fraction of aborted trials', fontsize=fontsize + 1)
  1427. ax.set_xlim(xticks[0], xticks[-1])
  1428. ax.set_ylim(yticks[0], yticks[-1])
  1429. ax.xaxis.set_label_coords(0.5, -0.2)
  1430. ax.yaxis.set_label_coords(-0.15, 0.5)
  1431. ax.yaxis.set_major_formatter(major_formatter)
  1432. ax.xaxis.set_major_formatter(major_formatter)
  1433. ax.tick_params(axis='both', which='major', pad=2)
  1434. ax.scatter(skip_diff_value, reward_rate_value, c=withvalue_c, s=1, alpha=0.8, lw=2, clip_on=False)
  1435. model = LinearRegression()
  1436. model.fit(skip_diff_value.reshape(-1, 1), reward_rate_value)
  1437. xdata = np.linspace(0, 1, 100).reshape(-1, 1)
  1438. ydata = model.predict(xdata)
  1439. ax.plot(xdata.reshape(-1), ydata, lw=lw, c=withvalue_c, ls='--')
  1440. ax.scatter(skip_diff_novalue, reward_rate_novalue, c=withoutvalue_c, s=1, alpha=0.8, lw=2, clip_on=False)
  1441. model = LinearRegression()
  1442. model.fit(skip_diff_novalue.reshape(-1, 1), reward_rate_novalue)
  1443. xdata = np.linspace(0, 1, 100).reshape(-1, 1)
  1444. ydata = model.predict(xdata)
  1445. ax.plot(xdata.reshape(-1), ydata, lw=lw, c=withoutvalue_c, ls='--')
  1446. ax.scatter(skip_diff_holistic, reward_rate_holistic, c=holistic_c, s=1, alpha=0.8, lw=2, clip_on=False)
  1447. model = LinearRegression()
  1448. model.fit(skip_diff_holistic.reshape(-1, 1), reward_rate_holistic)
  1449. xdata = np.linspace(0, 1, 100).reshape(-1, 1)
  1450. ydata = model.predict(xdata)
  1451. ax.plot(xdata.reshape(-1), ydata, lw=lw, c=holistic_c, ls='--')
  1452. fig.tight_layout(pad=0.3, w_pad=0.5, rect=(0, 0, 1, 1))
  1453. # %% [markdown]
  1454. # ## S3J
  1455. # %%
  1456. width = 1.5; height = 1.3
  1457. xticks = np.around(np.linspace(0, 0.7, 8), 1)
  1458. yticks = np.around(np.linspace(0.2, 0.9, 8), 1)
  1459. fig = plt.figure(figsize=(width, height), dpi=300)
  1460. ax = fig.add_subplot(1, 1, 1)
  1461. ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  1462. plt.xticks(xticks, fontsize=fontsize)
  1463. plt.yticks(yticks, fontsize=fontsize)
  1464. ax.set_ylabel(r'Reward rate (trial/s)', fontsize=fontsize + 1)
  1465. ax.set_xlabel('Fraction of aborted trials', fontsize=fontsize + 1)
  1466. ax.set_xlim(xticks[0], xticks[-1])
  1467. ax.set_ylim(yticks[0], yticks[-1])
  1468. ax.xaxis.set_label_coords(0.5, -0.2)
  1469. ax.yaxis.set_label_coords(-0.15, 0.5)
  1470. ax.yaxis.set_major_formatter(major_formatter)
  1471. ax.xaxis.set_major_formatter(major_formatter)
  1472. ax.tick_params(axis='both', which='major', pad=2)
  1473. ax.scatter(skip_diff_value, reward_rate_value, c=withvalue_c, s=1, alpha=0.8, lw=2, clip_on=False)
  1474. model = LinearRegression()
  1475. model.fit(skip_diff_value.reshape(-1, 1), reward_rate_value)
  1476. xdata = np.linspace(0, 1, 100).reshape(-1, 1)
  1477. ydata = model.predict(xdata)
  1478. ax.plot(xdata.reshape(-1), ydata, lw=lw, c=withvalue_c, ls='--')
  1479. ax.scatter(skip_diff_novalue, reward_rate_novalue, c=withoutvalue_c, s=1, alpha=0.8, lw=2, clip_on=False)
  1480. model = LinearRegression()
  1481. model.fit(skip_diff_novalue.reshape(-1, 1), reward_rate_novalue)
  1482. xdata = np.linspace(0, 1, 100).reshape(-1, 1)
  1483. ydata = model.predict(xdata)
  1484. ax.plot(xdata.reshape(-1), ydata, lw=lw, c=withoutvalue_c, ls='--')
  1485. ax.scatter(skip_diff_holisticLong, reward_rate_holisticLong, c=holistic_c, s=1, alpha=0.8, lw=2, clip_on=False)
  1486. model = LinearRegression()
  1487. model.fit(skip_diff_holisticLong.reshape(-1, 1), reward_rate_holisticLong)
  1488. xdata = np.linspace(0, 1, 100).reshape(-1, 1)
  1489. ydata = model.predict(xdata)
  1490. ax.plot(xdata.reshape(-1), ydata, lw=lw, c=holistic_c, ls='--')
  1491. fig.tight_layout(pad=0.3, w_pad=0.5, rect=(0, 0, 1, 1))

figs-1.ipynb at commit 4503792, under Apache-2.0 · at the source

Overview

Authors: Jean-Paul Noel1,2, Ruiyi Zhang3,4,5,6, Xaq Pitkow3,4, Dora E Angelaki5,6
  1. Department of Neuroscience, University of Minnesota, Minneapolis, USA
  2. Minnesota Robotics Institute, College of Science and Engineering, University of Minnesota, Minneapolis, USA
  3. Neuroscience Institute, Carnegie Mellon University, Pennsylvania, USA
  4. Machine Learning Department, Carnegie Mellon University, Pennsylvania, USA
  5. Center for Neural Science, New York University, New York, USA
  6. Tandon School of Engineering, New York University, New York, USA
Institutions: University of Minnesota (United States); New York University (United States); Carnegie Mellon University (United States)
Journal: Nature communications, volume 17, issue 1, article 8025
Dates: received 28 November 2024; accepted 8 June 2026; published online 26 June 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41467-026-74783-6 · PMID 42362568 · PMCID PMC13454609 · OpenAlex W7166023829
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: non-human primate (organism), systems (subfield)
Methods: Statistics, Smoothing, state filtering, decompositions, Machine learning, Single-unit activity, calcium imaging
Keywords: Neural circuits, Learning algorithms
MeSH: Choice Behavior*, Dorsolateral Prefrontal Cortex*, Prefrontal Cortex*, Animals, Decision Making, Macaca mulatta, Male, Reinforcement Machine Learning, Reward, Virtual Reality (* major topic)
Topic: Neural and Behavioral Psychology Studies (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: U.S. Department of Health & Human Services | NIH | National Institute of Neurological Disorders and Stroke (NINDS) (R00NS128075); Alfred P. Sloan Foundation (Sloan Research Fellowship); U.S. Department of Health &amp; Human Services | NIH | National Institute of Neurological Disorders and Stroke (R00NS128075); NINDS NIH HHS (R00 NS128075); Simons Foundation (SFI-AN-NC-SCN-00007276)
Citations: not cited yet (Europe PMC); 72 references in the paper

Abstract

The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.

Repository

Its files are read in the Code ↔ Paper reader above.

ryzhang1/dlPFC-strategic-aborting

License: Apache-2.0
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 4503792cfee18f809084aa3466f3c610b5e668e1, 6 February 2026
Languages: Python (9), Jupyter (7)
Size: 20 files, 16 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file, 7 notebooks
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: PyTorch (12 files), NumPy (11 files), pandas (5 files), Matplotlib (4 files), scikit-learn (3 files), SciPy (3 files)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
18 files

Code availability statement

The paper has a code availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s41467-026-74783-6.

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;
  • no match between paragraphs and code yet;
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

Datasets cited

Data availability statement

The paper has a data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s41467-026-74783-6.

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

Recorded: type, language, journal, volume, issue, pages, dates, 4 authors, 2 keywords, 10 MeSH terms, 5 funders, 58 references.

Cite

This paper

Noel, J.-P., Zhang, R., Pitkow, X., & Angelaki, D. E. (2026). Neural and computational correlates of strategic aborting and long-run policy optimization in the dorsolateral prefrontal cortex. Nature communications, 17(1), 8025. https://doi.org/10.1038/s41467-026-74783-6

BibTeX

@article{noel2026neural,
author = {Noel, Jean-Paul and Zhang, Ruiyi and Pitkow, Xaq and Angelaki, Dora E},
title = {{Neural and computational correlates of strategic aborting and long-run policy optimization in the dorsolateral prefrontal cortex}},
journal = {Nature communications},
year = {2026},
month = jun,
volume = {17},
number = {1},
pages = {8025},
publisher = {Nature Publishing Group},
issn = {2041-1723},
doi = {10.1038/s41467-026-74783-6},
url = {https://doi.org/10.1038/s41467-026-74783-6},
pmid = {42362568},
pmcid = {PMC13454609}
}

RIS

TY - JOUR
AU - Noel, Jean-Paul
AU - Zhang, Ruiyi
AU - Pitkow, Xaq
AU - Angelaki, Dora E
TI - Neural and computational correlates of strategic aborting and long-run policy optimization in the dorsolateral prefrontal cortex
T2 - Nature communications
J2 - Nat Commun
PY - 2026
DA - 2026/06/26
VL - 17
IS - 1
SP - 8025
SN - 2041-1723
PB - Nature Publishing Group
DO - 10.1038/s41467-026-74783-6
UR - https://doi.org/10.1038/s41467-026-74783-6
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41467-026-74783-6",
"type": "article-journal",
"title": "Neural and computational correlates of strategic aborting and long-run policy optimization in the dorsolateral prefrontal cortex",
"container-title": "Nature communications",
"author": [
{
"family": "Noel",
"given": "Jean-Paul"
},
{
"family": "Zhang",
"given": "Ruiyi"
},
{
"family": "Pitkow",
"given": "Xaq"
},
{
"family": "Angelaki",
"given": "Dora E"
}
],
"container-title-short": "Nat Commun",
"volume": "17",
"issue": "1",
"page": "8025",
"DOI": "10.1038/s41467-026-74783-6",
"PMID": "42362568",
"PMCID": "PMC13454609",
"ISSN": "2041-1723",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41467-026-74783-6",
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
26
]
]
}
}

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.1016/j.isci.2026.117492 [code]
Neural subspace reorganization reflects value-based decision-making.
Journal: iScience
In common: scikit-learn, pandas, SciPy, 2 other tools, 6 references
[2] doi:10.7554/elife.106032 [code]
Neural signatures of model-based and model-free reinforcement learning across prefrontal cortex and striatum.
Journal: eLife
In common: scikit-learn, pandas, SciPy, 2 other tools, non-human primate, 5 references
[3] doi:10.1038/s41593-026-02333-w [code]
Learning shapes neural geometry in the primate prefrontal cortex.
Journal: Nature neuroscience
In common: scikit-learn, pandas, SciPy, 2 other tools, non-human primate, 3 references
[4] doi:10.1038/s41467-026-72057-9 [code]
Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.
Journal: Nature communications
In common: PyTorch, scikit-learn, pandas, 3 other tools, systems, 2 references
[5] doi:10.1371/journal.pbio.3003824 [code]
Flexible goal learning involves coordinated population activity in dCA1 and medial orbitofrontal cortex.
Journal: PLoS biology
In common: PyTorch, scikit-learn, pandas, 3 other tools, systems, 2 references
[6] doi:10.1038/s41597-026-07129-y [code]
Dataset of cortical and subcortical single neuron activity during value-based tasks in macaque monkey.
Journal: Scientific data
In common: pandas, SciPy, Matplotlib, 1 other tool, non-human primate, 3 references
[7] doi:10.1038/s41467-026-76104-3 [code]
Sensorimotor remapping drives task specialization in prefrontal cortex.
Journal: Nature communications
In common: scikit-learn, pandas, SciPy, 2 other tools, non-human primate, systems, 2 references
[8] doi:10.1038/s41467-026-74347-8 [code]
Compositionality of social gaze in the prefrontal-amygdala circuits.
Journal: Nature communications
In common: scikit-learn, pandas, SciPy, 2 other tools, non-human primate, systems, 2 references
[9] doi:10.1016/j.neuron.2026.04.011 [code]
Precision fMRI reveals densely interdigitated network patches with conserved motifs in the lateral prefrontal cortex.
Journal: Neuron
In common: PyTorch, scikit-learn, SciPy, 2 other tools, systems, 2 references
[10] doi:10.7554/elife.107423 [code]
A context-free model of savings in motor learning.
Journal: eLife
In common: PyTorch, scikit-learn, pandas, 3 other tools, 2 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

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.