OSCR

BitterBuster: A virtual world for understanding naturalistic patch foraging.

Code ↔ Paper

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

The 1 match
  1. [1] § Results › Experiment 1: Solo foraging ↔ Scripts/AnalysisScripts/AnalysisControl.ipynb, lines 1833 to 1957 · score 0.58 · confidence interval, marginal reward rate, patch visits, histogram, exit · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 2,002 lines · 71 KB · no license · 1 match

  1. # %%
  2. import numpy as np
  3. import sys
  4. from scipy.stats import norm
  5. sys.path.append('../ProcessingScripts/')
  6. #from logs_to_dfs import logs_to_dfs
  7. import os
  8. import pandas as pd
  9. import matplotlib.pyplot as plt
  10. from matplotlib.collections import LineCollection, PolyCollection
  11. import matplotlib.colors as mcolors
  12. from matplotlib.lines import Line2D
  13. import seaborn as sns
  14. import math
  15. from statsmodels.stats.anova import AnovaRM
  16. import statsmodels.formula.api as smf
  17. from scipy.stats import spearmanr
  18. from scipy.stats import t as t_dist
  19. import matplotlib.gridspec as gridspec
  20. cwd = os.getcwd()
  21. tier_path = os.path.dirname(os.path.dirname(cwd))
  22. analysis_dir = os.path.join(tier_path,'Data','analysisData')
  23. getting_codes = os.listdir(analysis_dir)
  24. subject_pair_codes = [f for f in getting_codes if not f.startswith('.')] ## no hidden dirs
  25. # %% [markdown]
  26. # # Functions
  27. # %%
  28. nameSpaces = {
  29. 'PatchEfficiency': 'nb',
  30. 'EffectiveReward': '$R_e$',
  31. 'TimeOnPatchAvg': 'Time-On-Patch Average',
  32. 'VisitedNeighborhoodDepletion': 'First Visit Depletion',
  33. 'DPrime': 'd\'',
  34. 'HarvestEfficiency': 'hb'
  35. }
  36. # %%
  37. def makeRoundAverageGraphV2(allData, measureName, ylimit = None):
  38. rounds = [0, 1, 2]
  39. averages = []
  40. for r in allData['Round'].unique():
  41. tempDF = allData.loc[allData['Round'] == r]
  42. averages.append(math.fsum(tempDF[measureName]) / len(tempDF[measureName]))
  43. for id in allData['PairCode'].unique():
  44. temp = allData.loc[allData['PairCode'] == id]
  45. yvals = []
  46. rvals = []
  47. for r in range(len(temp)):
  48. yvals.append(temp.iloc[r][measureName])
  49. rvals.append(int(temp.iloc[r]['Round']) - 1)
  50. # print(type(temp['Round']))
  51. # print(type(temp[measureName]))
  52. sns.lineplot(
  53. x = rvals,
  54. y = yvals,
  55. color='k',
  56. linewidth=.2
  57. )
  58. print(rounds)
  59. print(averages)
  60. sns.barplot(
  61. x = rounds,
  62. y = averages,
  63. palette='Blues',
  64. alpha = .75
  65. )
  66. sns.stripplot(
  67. data= allData,
  68. x= 'Round',
  69. y= measureName,
  70. palette='Blues',
  71. linewidth=.4
  72. )
  73. if ylimit:
  74. plt.ylim(ylimit)
  75. plt.xlabel('Round', fontsize=22)
  76. if measureName in nameSpaces:
  77. plt.ylabel(nameSpaces[measureName], fontsize=22)
  78. else:
  79. plt.ylabel(measureName, fontsize=22)
  80. plt.xticks(rounds, ['1 (20min)', '2 (10min)', '3 (10min)'], fontsize=14)
  81. plt.yticks(fontsize=14)
  82. sns.despine()
  83. #plt.show()
  84. plt.savefig(os.path.join(tier_path, 'Output', f'F2_{measureName}_RoundDistributions.png'))
  85. print(averages)
  86. # %%
  87. def makeMeasureAvgsAgainstLockout(allData, measureName, ylimit = None):
  88. rounds = [0, 1, 2]
  89. averages = {}
  90. for r in allData['LockoutDuration'].unique():
  91. tempDF = allData.loc[allData['LockoutDuration'] == r]
  92. averages[r] = math.fsum(tempDF[measureName]) / len(tempDF[measureName])
  93. # for id in allData['PairCode'].unique():
  94. # temp = allData.loc[allData['PairCode'] == id]
  95. # yvals = []
  96. # rvals = []
  97. # for r in range(len(temp)):
  98. # yvals.append(temp.iloc[r][measureName])
  99. # rvals.append(int(temp.iloc[r]['Round']) - 1)
  100. # # print(type(temp['Round']))
  101. # # print(type(temp[measureName]))
  102. # sns.lineplot(
  103. # x = rvals,
  104. # y = yvals,
  105. # color='k',
  106. # linewidth=.2
  107. # )
  108. allData['Round'] = allData['Round'].astype(str)
  109. allData['LockoutDuration'] = allData['LockoutDuration'].astype(str)
  110. print(rounds)
  111. print(averages)
  112. sns.barplot(
  113. data=allData,
  114. errorbar='se',
  115. x = 'LockoutDuration',
  116. y = measureName,
  117. order=['0', '5', '15'],
  118. palette='Blues',
  119. alpha = .75
  120. )
  121. # sns.stripplot(
  122. # data= allData,
  123. # x= 'LockoutDuration',
  124. # y= measureName,
  125. # order=['0', '5', '15'],
  126. # palette='Blues',
  127. # linewidth=.4
  128. # )
  129. if ylimit:
  130. plt.ylim(ylimit)
  131. plt.xlabel('Lockout Duration', fontsize=22)
  132. plt.ylabel(measureName, fontsize=16)
  133. #plt.xticks(['0', '5', '15'], fontsize=14)
  134. plt.yticks(fontsize=14)
  135. sns.despine()
  136. #plt.show()
  137. plt.savefig(os.path.join(tier_path, 'Output', f'F2_{measureName}_RoundDistributions.png'))
  138. print(averages)
  139. # %%
  140. def makeRoundAverageGraphV3(allData, measureName, ylimit = None):
  141. rounds = [0, 1, 2]
  142. averages = []
  143. for r in allData['Round'].unique():
  144. tempDF = allData.loc[allData['Round'] == r]
  145. averages.append(math.fsum(tempDF[measureName]) / len(tempDF[measureName]))
  146. # for id in allData['PairCode'].unique():
  147. # temp = allData.loc[allData['PairCode'] == id]
  148. # yvals = []
  149. # rvals = []
  150. # for r in range(len(temp)):
  151. # yvals.append(temp.iloc[r][measureName])
  152. # rvals.append(temp.iloc[r]['Round'] - 1)
  153. # # print(type(temp['Round']))
  154. # # print(type(temp[measureName]))
  155. # sns.lineplot(
  156. # x = rvals,
  157. # y = yvals,
  158. # color='k',
  159. # linewidth=.2
  160. # )
  161. print(rounds)
  162. print(averages)
  163. allData['Round'] = allData['Round'].astype(str)
  164. allData['LockoutDuration'] = allData['LockoutDuration'].astype(str)
  165. sns.barplot(
  166. data=allData,
  167. errorbar='se',
  168. x = 'Round',
  169. y = measureName,
  170. hue='LockoutDuration',
  171. hue_order=['0', '5', '15'],
  172. palette='Blues',
  173. alpha = .75
  174. )
  175. sns.stripplot(
  176. data= allData,
  177. x= 'Round',
  178. y= measureName,
  179. hue='LockoutDuration',
  180. hue_order=['0', '5', '15'],
  181. dodge=True,
  182. palette='Blues',
  183. linewidth=.4
  184. )
  185. if ylimit:
  186. plt.ylim(ylimit)
  187. plt.xlabel('Round', fontsize=22)
  188. plt.ylabel(measureName, fontsize=22)
  189. plt.xticks(rounds, ['1 (20min)', '2 (10min)', '3 (10min)'], fontsize=14)
  190. plt.yticks(fontsize=14)
  191. sns.despine()
  192. #plt.show()
  193. plt.legend(title='Lockout Duration', loc=(-.5, .6))
  194. plt.savefig(os.path.join(tier_path, 'Output', f'F2_{measureName}_RoundDistributions.png'))
  195. print(averages)
  196. # %%
  197. def makeRoundAverageGraphV4(allData, measureName, ylimit = None):
  198. '''
  199. Just lockout subjects
  200. '''
  201. rounds = [0, 1, 2]
  202. averages = []
  203. for r in allData['Round'].unique():
  204. tempDF = allData.loc[allData['Round'] == r]
  205. averages.append(math.fsum(tempDF[measureName]) / len(tempDF[measureName]))
  206. print(rounds)
  207. print(averages)
  208. allData['Round'] = allData['Round'].astype(str)
  209. #allData['LockoutDuration'] = allData['LockoutDuration'].astype(str)
  210. new = allData[allData['LockoutDuration'] != '0']
  211. new['LockoutDuration'] = new['LockoutDuration'].astype('category').cat.remove_unused_categories()
  212. sns.barplot(
  213. data=new,
  214. errorbar='se',
  215. x = 'Round',
  216. y = measureName,
  217. hue='LockoutDuration',
  218. hue_order=['5', '15'],
  219. palette='Blues',
  220. alpha = .75
  221. )
  222. if ylimit:
  223. plt.ylim(ylimit)
  224. plt.xlabel('Round', fontsize=22)
  225. if measureName in nameSpaces:
  226. plt.ylabel(nameSpaces[measureName], fontsize=16)
  227. else:
  228. plt.ylabel(measureName, fontsize=16)
  229. plt.xticks(rounds, ['1 (20min)', '2 (10min)', '3 (10min)'], fontsize=14)
  230. plt.yticks(fontsize=14)
  231. sns.despine()
  232. #plt.show()
  233. plt.legend(title='Lockout Duration')#, loc=(-.5, .6))
  234. plt.savefig(os.path.join(tier_path, 'Output', f'F2_{measureName}_RoundDistributions.png'))
  235. print(averages)
  236. # %% [markdown]
  237. # def makeRankAndExpectedOrderList(houseEventList, x=100):
  238. # output = {
  239. # 'visitOrder': [],
  240. # 'rankOrder': []
  241. # }
  242. # nextExpected = {
  243. # 'blue': 1, 'green': 1, 'pink': 1, 'brown': 1
  244. # }
  245. # currEntry = houseEventList[0]
  246. # currN = houseEventList[0]['Neighborhood']
  247. # count=0
  248. # for p in range(len(houseEventList)):
  249. # if houseEventList[p]['Neighborhood'] != currN:
  250. # currN = houseEventList[p]['Neighborhood']
  251. # count=0
  252. # output['rankOrder'] = houseEventList[p]['Rank']
  253. # output['visitOrder'] = nextExpected[currN]
  254. # nextExpected[currN] += 1
  255. # elif count >= x:
  256. # continue
  257. # else:
  258. # output['rankOrder'] = houseEventList[p]['Rank']
  259. # output['visitOrder'] = nextExpected[currN]
  260. # nextExpected[currN] += 1
  261. # count += 1
  262. # return output
  263. # %%
  264. # TODO: ADD call to add new data to this dataframe
  265. PerformanceDF = pd.read_csv(os.path.join(tier_path, 'Output', 'Table4Performance.csv'))
  266. #DemographicsDF = pd.read_csv(os.path.join(tier_path, 'Output', 'Table5Demographics.csv'))
  267. VisitsDF = pd.read_csv(os.path.join(tier_path, 'Output', 'Table3AllVisitEvents.csv'))
  268. RealExitsDF = pd.read_csv(os.path.join(tier_path, 'Output', 'Table5RealExits.csv'))
  269. # %%
  270. test = VisitsDF[VisitsDF['Round'] == 1]
  271. aaDepletesRound1 = test['ParticipantID'].value_counts()
  272. aaDepletesRound1 = aaDepletesRound1 % 43
  273. test = VisitsDF[VisitsDF['Round'] == 2]
  274. aaDepletesRound2 = test['ParticipantID'].value_counts()
  275. aaDepletesRound2 = aaDepletesRound2 % 43
  276. test = VisitsDF[VisitsDF['Round'] == 3]
  277. aaDepletesRound3 = test['ParticipantID'].value_counts()
  278. aaDepletesRound3 = aaDepletesRound3 % 43
  279. # %% [markdown]
  280. # # Outputs
  281. # %%
  282. makeRoundAverageGraphV2(PerformanceDF, 'PatchEfficiency', [0,1])
  283. # %% [markdown]
  284. # makeMeasureAvgsAgainstLockout(PerformanceDF, 'VisitedNeighborhoodDepletion', [.8, 1.0])
  285. # %%
  286. makeRoundAverageGraphV2(PerformanceDF, 'EffectiveReward')
  287. # %% [markdown]
  288. # makeRoundAverageGraphV4(PerformanceDF, 'VisitedNeighborhoodDepletion', [.8, 1.0])
  289. # %%
  290. makeRoundAverageGraphV2(PerformanceDF, 'DPrime')
  291. # %%
  292. makeRoundAverageGraphV2(PerformanceDF, 'HarvestEfficiency')
  293. # %%
  294. makeRoundAverageGraphV3(PerformanceDF, 'HitsPerMinute')
  295. # %%
  296. makeMeasureAvgsAgainstLockout(PerformanceDF, 'TimeOnPatchAvg')
  297. # %%
  298. makeRoundAverageGraphV3(PerformanceDF, 'EffectiveReward')
  299. # %%
  300. makeRoundAverageGraphV3(PerformanceDF, 'RewardRate')
  301. # %% [markdown]
  302. # ## Stats
  303. # %%
  304. outMixedLM = smf.mixedlm('EffectiveReward ~ Round + DPrime * PatchEfficiency', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  305. FittedOut = outMixedLM.fit()
  306. x = FittedOut.summary()
  307. #print(x.as_latex())
  308. # %%
  309. outMixedLM = smf.mixedlm('HitsPerMinute ~ Round + DPrime * PatchEfficiency', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  310. FittedOut = outMixedLM.fit()
  311. x = FittedOut.summary()
  312. #print(x)
  313. #print(x.as_latex())
  314. # %%
  315. outMixedLM = smf.mixedlm('HitsPerMinute ~ Round + EffectiveRewardBeforeAbandon * DPrime + PatchEfficiency', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  316. FittedOut = outMixedLM.fit()
  317. x = FittedOut.summary()
  318. #print(x)
  319. #print(x.as_latex())
  320. # %%
  321. outMixedLM = smf.mixedlm('EffectiveReward ~ Round + HarvestEfficiency', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  322. FittedOut = outMixedLM.fit()
  323. x = FittedOut.summary()
  324. #print(x.as_latex())
  325. # %%
  326. outMixedLM = smf.mixedlm('EffectiveReward ~ PatchEfficiency', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  327. FittedOut = outMixedLM.fit()
  328. x = FittedOut.summary()
  329. #print(x.as_latex())
  330. # %%
  331. outMixedLM = smf.mixedlm('RewardRate ~ Round + DPrime * PatchEfficiency', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  332. FittedOut = outMixedLM.fit()
  333. #print(FittedOut.summary())
  334. # %%
  335. outMixedLM = smf.mixedlm('EffectiveReward ~ Round', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  336. FittedOut = outMixedLM.fit()
  337. x = FittedOut.summary()
  338. #print(x.as_latex())
  339. # %%
  340. outMixedLM = smf.mixedlm('HarvestEfficiency ~ Round', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  341. FittedOut = outMixedLM.fit()
  342. x = FittedOut.summary()
  343. #print(x.as_latex())
  344. # %%
  345. outMixedLM = smf.mixedlm('PatchEfficiency ~ Round', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  346. FittedOut = outMixedLM.fit()
  347. x = FittedOut.summary()
  348. #print(x.as_latex())
  349. # %%
  350. outMixedLM = smf.mixedlm('DPrime ~ Round', data= PerformanceDF, groups=PerformanceDF['PairCode'])
  351. FittedOut = outMixedLM.fit()
  352. x = FittedOut.summary()
  353. #print(x.as_latex())
  354. # %% [markdown]
  355. # # To Be Redone
  356. # %%
  357. GraphingToHitsPerMin, subplots = plt.subplots(2,3, figsize=(15,10))
  358. rounds = ['Round1', 'Round2', 'Round3']
  359. GraphingToHitsPerMin.suptitle('')
  360. for s in range(len(rounds)):
  361. print(s)
  362. tempForSpear = PerformanceDF.loc[PerformanceDF['Round'] == str(s+1)]
  363. dSpear, dP = spearmanr(tempForSpear['DPrime'], tempForSpear['HitsPerMinute'])
  364. print(f'ROUND{s+1} Spearman R for hits-per-minute and d\' is:\n {dSpear}, p-value: {dP}\n\n')
  365. peSpear, peP = spearmanr(tempForSpear['PatchEfficiency'], tempForSpear['HitsPerMinute'])
  366. print(f'ROUND{s+1} Spearman R for hits-per-minute and PE is:\n {peSpear}, p-value: {peP}\n\n')
  367. sns.scatterplot(
  368. ax= subplots[0, s],
  369. data= tempForSpear,
  370. y= f'PatchEfficiency',
  371. x= f'HitsPerMinute',
  372. hue= f'DPrime',
  373. hue_norm=(0, 5),
  374. palette='Purples',
  375. linewidth=.5,
  376. edgecolor='k'
  377. )
  378. sns.scatterplot(
  379. ax= subplots[1, s],
  380. data= tempForSpear,
  381. y= f'DPrime',
  382. x= f'HitsPerMinute',
  383. hue= f'PatchEfficiency',
  384. hue_norm=(0.0, 1.0),
  385. palette='Purples',
  386. linewidth=.5,
  387. edgecolor='k'
  388. )
  389. subplots[0,s].set_xlim([0, 18])
  390. subplots[0,s].set_ylim([0, 1])
  391. subplots[0,s].set_xlabel('')
  392. subplots[0,s].set_ylabel('', fontsize=12)
  393. subplots[0,s].set_title(f'Round {s+1}', fontsize=22)
  394. #subplots[0,s].text(0, .85, s=f' r: {peSpear}\n p: {peP}')
  395. subplots[1,s].set_xlim([0, 18])
  396. subplots[1,s].set_ylim([-1, 5])
  397. subplots[1,s].set_xlabel('Hits Per Minute', fontsize=16)
  398. subplots[1,s].set_ylabel('', fontsize=12)
  399. #subplots[1,s].set_title(f'\nRound {s+1}', fontsize=16)
  400. #subplots[1,s].text(0, 5, s=f' r: {dSpear}\n p: {dP}')
  401. if s != 1:
  402. subplots[0,s].get_legend().set_visible(False)
  403. subplots[1,s].get_legend().set_visible(False)
  404. else:
  405. subplots[0,s].legend(title='d\'', loc=(-.5, .6))
  406. subplots[1,s].legend(title='nb', loc=(-.5, .6))
  407. subplots[0,0].set_ylabel('Neighborhood Bias', fontsize=16)
  408. subplots[1,0].set_ylabel('d\'', fontsize=16)
  409. sns.despine()
  410. #fontsize 18
  411. # %%
  412. GraphingToHitsPerMin, subplots = plt.subplots(2,3, figsize=(15,10))
  413. rounds = ['Round1', 'Round2', 'Round3']
  414. GraphingToHitsPerMin.suptitle('')
  415. for s in range(len(rounds)):
  416. tempForSpear = PerformanceDF.loc[PerformanceDF['Round'] == str(s+1)]
  417. dSpear, dP = spearmanr(tempForSpear['DPrime'], tempForSpear['EffectiveReward'])
  418. print(f'ROUND{s+1} Spearman R for effective reward and d\' is:\n {dSpear}, p-value: {dP}\n\n')
  419. peSpear, peP = spearmanr(tempForSpear['PatchEfficiency'], tempForSpear['EffectiveReward'])
  420. print(f'ROUND{s+1} Spearman R for effective reward and PE is:\n {peSpear}, p-value: {peP}\n\n')
  421. sns.scatterplot(
  422. ax= subplots[0, s],
  423. data= tempForSpear,
  424. x= f'PatchEfficiency',
  425. y= f'EffectiveReward',
  426. hue= f'DPrime',
  427. hue_norm=(0, 5),
  428. palette='Purples',
  429. linewidth=.5,
  430. edgecolor='k'
  431. )
  432. sns.scatterplot(
  433. ax= subplots[1, s],
  434. data= tempForSpear,
  435. x= f'DPrime',
  436. y= f'EffectiveReward',
  437. hue= f'PatchEfficiency',
  438. hue_norm=(0.0, 1.0),
  439. palette='Purples',
  440. linewidth=.5,
  441. edgecolor='k'
  442. )
  443. subplots[0,s].set_ylim([0, 0.25])
  444. subplots[0,s].set_xlim([0, 1])
  445. subplots[0,s].set_ylabel('')
  446. subplots[0,s].set_xlabel('nb', fontsize=16)
  447. subplots[0,s].set_title(f'Round {s+1}', fontsize=22)
  448. #subplots[0,s].text(0, .85, s=f' r: {peSpear}\n p: {peP}')
  449. subplots[1,s].set_ylim([0, 0.25])
  450. subplots[1,s].set_xlim([-1, 5])
  451. subplots[1,s].set_xlabel('d\'', fontsize=16)
  452. subplots[1,s].set_ylabel('', fontsize=12)
  453. #subplots[1,s].set_title(f'\nRound {s+1}', fontsize=16)
  454. #subplots[1,s].text(0, 5, s=f' r: {dSpear}\n p: {dP}')
  455. if s != 1:
  456. subplots[0,s].get_legend().set_visible(False)
  457. subplots[1,s].get_legend().set_visible(False)
  458. else:
  459. subplots[0,s].legend(title='d\'', loc=(-.5, .6))
  460. subplots[1,s].legend(title='nb', loc=(-.5, .6))
  461. subplots[0,0].set_ylabel('$R_e$', fontsize=16)
  462. subplots[1,0].set_ylabel('$R_e$', fontsize=16)
  463. sns.despine()
  464. #fontsize 18
  465. plt.savefig(os.path.join(tier_path, 'Output', 'F3_EffectiveReward_by_Performance.png'))
  466. # %%
  467. stepSize = 2.0
  468. endTimes = {1: 1200, 2: 600, 3: 600}
  469. # sort chronologically
  470. VisitsDF = VisitsDF.sort_values(['Round', 'ParticipantID', 'TimeIn'])
  471. processed_dfs = []
  472. for roundN in [1, 2, 3]:
  473. visitsForRound = VisitsDF[VisitsDF['Round'] == roundN]
  474. for pID in visitsForRound['ParticipantID'].unique():
  475. df_p = visitsForRound[visitsForRound['ParticipantID'] == pID].copy()
  476. if df_p.empty:
  477. continue
  478. # Build Timers & Neighborhood Visit Segments
  479. df_p['NbhChange'] = (df_p['NeighborhoodID'] != df_p['NeighborhoodID'].shift(1))
  480. df_p['NbhSegmentID'] = df_p['NbhChange'].cumsum().astype(int)
  481. # if df_p['TimeIn'].iloc[0] != np.nan:
  482. # df_p['firstIn'] = 0
  483. # else:
  484. # df_p['firstIn'] = np.nan
  485. df_p['firstIn'] = df_p['TimeIn'].iloc[0]
  486. df_p['nbhIn'] = df_p.groupby('NbhSegmentID')['TimeIn'].transform('first')
  487. # Build Cumulative Rewards based on TimeOut
  488. df_p_out = df_p.sort_values('TimeOut').copy()
  489. df_p_out['CumTotalReward'] = df_p_out['RewardCollected'].cumsum()
  490. df_p_out['CumNbhReward'] = df_p_out.groupby('NbhSegmentID')['RewardCollected'].cumsum()
  491. # 2 second interval
  492. grid_df = pd.DataFrame({
  493. 'RegularTimestamp': np.arange(0, endTimes[roundN] + stepSize, stepSize)
  494. })
  495. # 1. Merge active timers & active NbhSegmentID based on TimeIn <= t
  496. resampled = pd.merge_asof(
  497. grid_df,
  498. df_p[['TimeIn', 'firstIn', 'nbhIn', 'NbhSegmentID']],
  499. left_on='RegularTimestamp',
  500. right_on='TimeIn',
  501. direction='backward'
  502. )
  503. # 2. Merge Total Cumulative Reward achieved by TimeOut <= t
  504. resampled = pd.merge_asof(
  505. resampled,
  506. df_p_out[['TimeOut', 'CumTotalReward']],
  507. left_on='RegularTimestamp',
  508. right_on='TimeOut',
  509. direction='backward'
  510. )
  511. # 3. Merge Current Neighborhood Cumulative Reward achieved by TimeOut <= t
  512. resampled['NbhSegmentID_tmp'] = resampled['NbhSegmentID'].fillna(-1).astype(int)
  513. df_p_out['NbhSegmentID_tmp'] = df_p_out['NbhSegmentID'].astype(int)
  514. resampled = pd.merge_asof(
  515. resampled,
  516. df_p_out[['TimeOut', 'NbhSegmentID_tmp', 'CumNbhReward']],
  517. left_on='RegularTimestamp',
  518. right_on='TimeOut',
  519. by='NbhSegmentID_tmp',
  520. direction='backward'
  521. )
  522. resampled.drop(columns=['NbhSegmentID_tmp'], inplace=True)
  523. resampled['CumTotalReward'] = resampled['CumTotalReward'].fillna(0)
  524. resampled['CumNbhReward'] = resampled['CumNbhReward'].fillna(0)
  525. t = resampled['RegularTimestamp']
  526. dt_total = t# - resampled['firstIn']
  527. dt_nbh = t - resampled['nbhIn']
  528. # Calculate rates only when elapsed time > 0
  529. resampled['RewardRateTotal'] = np.where(dt_total > 0, resampled['CumTotalReward'] / dt_total, np.nan)
  530. resampled['RewardRateCurrent'] = np.where(dt_nbh > 0, resampled['CumNbhReward'] / dt_nbh, np.nan)
  531. resampled['VisitNumber'] = resampled['NbhSegmentID'] # visit tracking columns for multi-panel plotting
  532. resampled['TimeInNbh'] = np.where(dt_nbh >= 0, dt_nbh, np.nan)
  533. resampled['ID'] = pID
  534. resampled['Round'] = roundN
  535. processed_dfs.append(resampled[[
  536. 'ID', 'Round', 'RegularTimestamp',
  537. 'RewardRateTotal', 'RewardRateCurrent',
  538. 'VisitNumber', 'TimeInNbh', 'nbhIn', 'firstIn'
  539. ]])
  540. resampledDF = pd.concat(processed_dfs, ignore_index=True)
  541. # %%
  542. '''
  543. Bypass this if not using cumulative expected reward rate
  544. '''
  545. stepSize = 2.0
  546. endTimes = {1: 1200, 2: 600, 3: 600}
  547. # Global offsets to map local round time to continuous experiment time
  548. round_offsets = {1: 0, 2: 1200, 3: 1800}
  549. # Sort chronologically by Participant and Round
  550. VisitsDF = VisitsDF.sort_values(['ParticipantID', 'Round', 'TimeIn']).copy()
  551. # Add global timestamps for experiment-wide matching
  552. VisitsDF['GlobalTimeIn'] = VisitsDF['TimeIn'] + VisitsDF['Round'].map(round_offsets)
  553. VisitsDF['GlobalTimeOut'] = VisitsDF['TimeOut'] + VisitsDF['Round'].map(round_offsets)
  554. processed_dfs = []
  555. # Process per participant across all rounds
  556. for pID in VisitsDF['ParticipantID'].unique():
  557. df_p = VisitsDF[VisitsDF['ParticipantID'] == pID].copy()
  558. if df_p.empty:
  559. continue
  560. # 1. Global cumulative reward tracking (across all 3 rounds)
  561. df_p_out = df_p.sort_values('GlobalTimeOut').copy()
  562. df_p_out['CumTotalReward'] = df_p_out['RewardCollected'].cumsum()
  563. # 2. Process each round with reset round-level timers
  564. for roundN in [1, 2, 3]:
  565. df_p_round = df_p[df_p['Round'] == roundN].copy()
  566. if df_p_round.empty:
  567. continue
  568. # Local Neighborhood Tracking (resets/tracks for current round)
  569. df_p_round['NbhChange'] = (df_p_round['NeighborhoodID'] != df_p_round['NeighborhoodID'].shift(1))
  570. df_p_round['NbhSegmentID'] = df_p_round['NbhChange'].cumsum().astype(int)
  571. #df_p_round['firstIn'] = 0 if pd.notna(df_p_round['TimeIn'].iloc[0]) else np.nan
  572. df_p_round['firstIn'] = df_p_round['TimeIn'].iloc[0]
  573. df_p_round['nbhIn'] = df_p_round.groupby('NbhSegmentID')['TimeIn'].transform('first')
  574. # Local Cumulative Neighborhood Reward
  575. df_p_round_out = df_p_round.sort_values('TimeOut').copy()
  576. df_p_round_out['CumNbhReward'] = df_p_round_out.groupby('NbhSegmentID')['RewardCollected'].cumsum()
  577. # Regular local grid starting at 0 for plotting
  578. grid_df = pd.DataFrame({
  579. 'RegularTimestamp': np.arange(0, endTimes[roundN] + stepSize, stepSize)
  580. })
  581. # Global lookup timestamp for cross-round reward lookup
  582. grid_df['GlobalTimestamp'] = grid_df['RegularTimestamp'] + round_offsets[roundN]
  583. # Merge active local timers & NbhSegmentID
  584. resampled = pd.merge_asof(
  585. grid_df,
  586. df_p_round[['TimeIn', 'firstIn', 'nbhIn', 'NbhSegmentID']],
  587. left_on='RegularTimestamp',
  588. right_on='TimeIn',
  589. direction='backward'
  590. )
  591. # Merge ALL-TIME Cumulative Reward up to global time point
  592. resampled = pd.merge_asof(
  593. resampled,
  594. df_p_out[['GlobalTimeOut', 'CumTotalReward']],
  595. left_on='GlobalTimestamp',
  596. right_on='GlobalTimeOut',
  597. direction='backward'
  598. )
  599. # Merge CURRENT Neighborhood Cumulative Reward up to local time point
  600. resampled['NbhSegmentID_tmp'] = resampled['NbhSegmentID'].fillna(-1).astype(int)
  601. df_p_round_out['NbhSegmentID_tmp'] = df_p_round_out['NbhSegmentID'].astype(int)
  602. resampled = pd.merge_asof(
  603. resampled,
  604. df_p_round_out[['TimeOut', 'NbhSegmentID_tmp', 'CumNbhReward']],
  605. left_on='RegularTimestamp',
  606. right_on='TimeOut',
  607. by='NbhSegmentID_tmp',
  608. direction='backward'
  609. )
  610. resampled.drop(columns=['NbhSegmentID_tmp'], inplace=True)
  611. resampled['CumTotalReward'] = resampled['CumTotalReward'].fillna(0)
  612. resampled['CumNbhReward'] = resampled['CumNbhReward'].fillna(0)
  613. # Local elapsed time for round and neighborhood
  614. t_local = resampled['RegularTimestamp']
  615. dt_total_local = t_local - resampled['firstIn']
  616. dt_nbh_local = t_local - resampled['nbhIn']
  617. # Global elapsed time for cross-round total reward rate
  618. t_global = resampled['GlobalTimestamp']
  619. # Rates:
  620. # Total rate uses cumulative rewards over global elapsed time
  621. # Current rate uses local neighborhood rewards over local neighborhood time
  622. resampled['RewardRateTotal'] = np.where(t_global > 0, resampled['CumTotalReward'] / t_global, np.nan)
  623. resampled['RewardRateCurrent'] = np.where(dt_nbh_local > 0, resampled['CumNbhReward'] / dt_nbh_local, np.nan)
  624. resampled['VisitNumber'] = resampled['NbhSegmentID']
  625. resampled['TimeInNbh'] = np.where(dt_nbh_local >= 0, dt_nbh_local, np.nan)
  626. resampled['ID'] = pID
  627. resampled['Round'] = roundN
  628. processed_dfs.append(resampled[[
  629. 'ID', 'Round', 'RegularTimestamp',
  630. 'RewardRateTotal', 'RewardRateCurrent',
  631. 'VisitNumber', 'TimeInNbh', 'nbhIn', 'firstIn'
  632. ]])
  633. resampledDF = pd.concat(processed_dfs, ignore_index=True)
  634. # %%
  635. sns.set_theme(style="ticks")
  636. palette = {"tRR": "#1f77b4", "cRR": "#ff7f0e"}
  637. fig, axes = plt.subplots(3, 1, figsize=(10, 11), sharex=True, sharey=True)
  638. for i, roundN in enumerate([1, 2, 3]):
  639. ax = axes[i]
  640. round_data = resampledDF[resampledDF['Round'] == roundN]
  641. '''
  642. Plot individual participant traces
  643. '''
  644. for pID, p_data in round_data.groupby('ID'):
  645. ax.plot(
  646. p_data['RegularTimestamp'], p_data['RewardRateTotal'],
  647. color=palette['tRR'], alpha=0.12, linewidth=0.8, zorder=1
  648. )
  649. ax.plot(
  650. p_data['RegularTimestamp'], p_data['RewardRateCurrent'],
  651. color=palette['cRR'], alpha=0.12, linewidth=0.8, zorder=1
  652. )
  653. '''
  654. Calculate and plot group mean
  655. '''
  656. mean_df = round_data.groupby('RegularTimestamp')[['RewardRateTotal', 'RewardRateCurrent']].mean().reset_index()
  657. ax.plot(
  658. mean_df['RegularTimestamp'], mean_df['RewardRateTotal'],
  659. color=palette['tRR'], linewidth=2.5, label='Total Reward Rate (tRR)', zorder=2
  660. )
  661. ax.plot(
  662. mean_df['RegularTimestamp'], mean_df['RewardRateCurrent'],
  663. color=palette['cRR'], linewidth=2.5, label='Current Nbh Reward Rate (cRR)', zorder=2
  664. )
  665. ax.set_title(f'Round {roundN}', fontsize=12, fontweight='semibold', loc='left', pad=8)
  666. ax.set_ylabel('Reward Rate (pts/sec)', fontsize=10, labelpad=8)
  667. ax.grid(True, linestyle='--', alpha=0.3, zorder=0)
  668. sns.despine(ax=ax, top=True, right=True)
  669. if i == 0:
  670. ax.legend(
  671. loc='upper right', frameon=True, facecolor='white',
  672. edgecolor='none', framealpha=0.9, fontsize=10
  673. )
  674. axes[-1].set_xlabel('Time (seconds)', fontsize=11, labelpad=8)
  675. plt.tight_layout()
  676. plt.show()
  677. # %%
  678. sns.set_theme(style="ticks")
  679. palette = {"tRR": "#1f77b4", "cRR": "#ff7f0e"}
  680. plot_df = resampledDF.copy()
  681. def mask_before_first_payload(df_p):
  682. valid_payloads = df_p[df_p['RewardRateTotal'].notna() & (df_p['RewardRateTotal'] > 0)]
  683. if not valid_payloads.empty:
  684. first_payload_t = valid_payloads['RegularTimestamp'].iloc[0]
  685. df_p.loc[df_p['RegularTimestamp'] < first_payload_t, ['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  686. else:
  687. df_p[['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  688. return df_p
  689. plot_df = plot_df.groupby(['Round', 'ID'], group_keys=False).apply(mask_before_first_payload)
  690. fig, axes = plt.subplots(3, 1, figsize=(10, 11), sharex=True, sharey=True)
  691. for i, roundN in enumerate([1, 2, 3]):
  692. ax = axes[i]
  693. round_data = plot_df[plot_df['Round'] == roundN]
  694. # individual traces starting at personal first payload
  695. for pID, p_data in round_data.groupby('ID'):
  696. p_valid = p_data.dropna(subset=['RewardRateTotal', 'RewardRateCurrent'], how='all')
  697. if p_valid.empty:
  698. continue
  699. ax.plot(
  700. p_valid['RegularTimestamp'], p_valid['RewardRateTotal'],
  701. color=palette['tRR'], alpha=0.12, linewidth=0.8, zorder=1
  702. )
  703. ax.plot(
  704. p_valid['RegularTimestamp'], p_valid['RewardRateCurrent'],
  705. color=palette['cRR'], alpha=0.12, linewidth=0.8, zorder=1
  706. )
  707. # population mean
  708. mean_df = round_data.groupby('RegularTimestamp')[['RewardRateTotal', 'RewardRateCurrent']].mean().reset_index()
  709. mean_df = mean_df.dropna(subset=['RewardRateTotal', 'RewardRateCurrent'], how='all')
  710. ax.plot(
  711. mean_df['RegularTimestamp'], mean_df['RewardRateTotal'],
  712. color=palette['tRR'], linewidth=2.5, label='Total Reward Rate (tRR)', zorder=2
  713. )
  714. ax.plot(
  715. mean_df['RegularTimestamp'], mean_df['RewardRateCurrent'],
  716. color=palette['cRR'], linewidth=2.5, label='Current Nbh Reward Rate (cRR)', zorder=2
  717. )
  718. ax.set_title(f'Round {roundN}', fontsize=12, fontweight='semibold', loc='left', pad=8)
  719. ax.set_ylabel('Reward Rate (pts/sec)', fontsize=10, labelpad=8)
  720. ax.grid(True, linestyle='--', alpha=0.3, zorder=0)
  721. sns.despine(ax=ax, top=True, right=True)
  722. if i == 0:
  723. ax.legend(
  724. loc='upper right', frameon=True, facecolor='white',
  725. edgecolor='none', framealpha=0.9, fontsize=10
  726. )
  727. axes[-1].set_xlabel('Time (seconds)', fontsize=11, labelpad=8)
  728. plt.tight_layout()
  729. plt.show()
  730. # %%
  731. sns.set_theme(style="ticks")
  732. blue_col = "#1f77b4"
  733. orange_col = "#ff7f0e"
  734. MAX_VISITS_TO_SHOW = 5
  735. fig = plt.figure(figsize=(16, 10))
  736. outer_gs = gridspec.GridSpec(3, 1, figure=fig, hspace=0.55)
  737. for i, roundN in enumerate([1, 2, 3]):
  738. # subgrid: 1 main tRR panel + MAX_VISITS_TO_SHOW small cRR panels
  739. inner_gs = gridspec.GridSpecFromSubplotSpec(
  740. 1, 1 + MAX_VISITS_TO_SHOW,
  741. subplot_spec=outer_gs[i],
  742. width_ratios=[2.5] + [1.0] * MAX_VISITS_TO_SHOW,
  743. wspace=0.35
  744. )
  745. round_data = resampledDF[resampledDF['Round'] == roundN]
  746. '''
  747. MAIN PANEL (Left): Total Reward Rate (tRR) over Round Time
  748. '''
  749. ax_trr = fig.add_subplot(inner_gs[0, 0])
  750. # Participant background lines
  751. for pID, p_data in round_data.groupby('ID'):
  752. ax_trr.plot(p_data['RegularTimestamp'], p_data['RewardRateTotal'],
  753. color=blue_col, alpha=0.12, linewidth=0.8, zorder=1)
  754. # mean line
  755. mean_trr = round_data.groupby('RegularTimestamp')['RewardRateTotal'].mean().reset_index()
  756. ax_trr.plot(mean_trr['RegularTimestamp'], mean_trr['RewardRateTotal'],
  757. color=blue_col, linewidth=2.2, label='tRR (Total Rate)', zorder=2)
  758. ax_trr.set_title(f'Round {roundN}: Total Rate', fontsize=11, fontweight='semibold', loc='left')
  759. ax_trr.set_xlabel('Round Time (s)', fontsize=9)
  760. ax_trr.set_ylabel('Rate (reward/s)', fontsize=9)
  761. ax_trr.grid(True, linestyle='--', alpha=0.3)
  762. sns.despine(ax=ax_trr)
  763. if i == 0:
  764. ax_trr.legend(loc='upper right', frameon=True, facecolor='white', framealpha=0.9, fontsize=9)
  765. '''
  766. SUB-PANELS (Right): cRR for Visit 1, Visit 2, ..., Visit N
  767. '''
  768. for visit_idx in range(1, MAX_VISITS_TO_SHOW + 1):
  769. ax_crr = fig.add_subplot(inner_gs[0, visit_idx])
  770. visit_data = round_data[round_data['VisitNumber'] == visit_idx]
  771. valid_visit_data = visit_data.dropna(subset=['RewardRateCurrent'])
  772. n_subjects = valid_visit_data['ID'].nunique()
  773. if not valid_visit_data.empty:
  774. for pID, p_data in valid_visit_data.groupby('ID'):
  775. ax_crr.plot(p_data['TimeInNbh'], p_data['RewardRateCurrent'],
  776. color=orange_col, alpha=0.15, linewidth=0.8, zorder=1)
  777. mean_crr = valid_visit_data.groupby('TimeInNbh')['RewardRateCurrent'].mean().reset_index()
  778. ax_crr.plot(mean_crr['TimeInNbh'], mean_crr['RewardRateCurrent'],
  779. color=orange_col, linewidth=2.0, zorder=2)
  780. ax_crr.set_title(f'Visit #{visit_idx}\n(N={n_subjects})', fontsize=9, fontweight='medium')
  781. ax_crr.set_xlabel('In-Nbh Time (s)', fontsize=8)
  782. ax_crr.grid(True, linestyle='--', alpha=0.3)
  783. sns.despine(ax=ax_crr)
  784. if visit_idx > 1:
  785. ax_crr.set_yticklabels([])
  786. # global y-axis scaling
  787. global_ymax = max(ax.get_ylim()[1] for ax in fig.axes)
  788. target_ymax = max(0.5, global_ymax)
  789. for ax in fig.axes:
  790. ax.set_ylim(bottom=0, top=target_ymax)
  791. plt.tight_layout()
  792. plt.show()
  793. # %%
  794. sns.set_theme(style="ticks")
  795. palette = {"tRR": "#1f77b4", "cRR": "#ff7f0e"}
  796. plot_df = resampledDF.copy()
  797. # 1. Mask timestamps prior to the first completed payload in EACH neighborhood visit
  798. def mask_before_first_nbh_payload(df_visit):
  799. valid_payloads = df_visit[df_visit['RewardRateCurrent'].notna() & (df_visit['RewardRateCurrent'] > 0)]
  800. if not valid_payloads.empty:
  801. first_payload_t = valid_payloads['TimeInNbh'].iloc[0]
  802. df_visit.loc[df_visit['TimeInNbh'] < first_payload_t, ['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  803. else:
  804. df_visit[['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  805. return df_visit
  806. plot_df = plot_df.groupby(['Round', 'ID', 'VisitNumber'], group_keys=False).apply(mask_before_first_nbh_payload)
  807. # 2. Bin TimeInNbh to integer seconds and truncate at t = 300s
  808. plot_df['TimeInNbh_bin'] = plot_df['TimeInNbh'].round(0)
  809. plot_df = plot_df[plot_df['TimeInNbh_bin'] <= 300]
  810. # Helper function to plot a line with dynamic opacity mapped to N
  811. def plot_fading_line(ax, x, y, counts, color, linewidth, zorder):
  812. x = np.asarray(x)
  813. y = np.asarray(y)
  814. counts = np.asarray(counts)
  815. n_max = counts.max()
  816. n_min = counts.min()
  817. # Scale alpha linearly between 0.20 (at N_min) and 1.00 (at N_max)
  818. if n_max > n_min:
  819. alphas = 0.20 + 0.80 * (counts - n_min) / (n_max - n_min)
  820. else:
  821. alphas = np.ones_like(counts, dtype=float)
  822. # Build 2D line segments between consecutive (x, y) points
  823. points = np.array([x, y]).T.reshape(-1, 1, 2)
  824. segments = np.concatenate([points[:-1], points[1:]], axis=1)
  825. # Calculate average RGBA color per segment
  826. base_rgb = mcolors.to_rgb(color)
  827. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  828. colors = [(*base_rgb, a) for a in seg_alphas]
  829. lc = LineCollection(segments, colors=colors, linewidths=linewidth, zorder=zorder)
  830. ax.add_collection(lc)
  831. fig, axes = plt.subplots(3, 1, figsize=(10, 11), sharex=True, sharey=True)
  832. for i, roundN in enumerate([1, 2, 3]):
  833. ax = axes[i]
  834. round_data = plot_df[plot_df['Round'] == roundN]
  835. # 3. Aggregate mean and sample size N per time bin (up to t=300)
  836. agg_df = (
  837. round_data.groupby('TimeInNbh_bin')
  838. .agg(
  839. trr_mean=('RewardRateTotal', 'mean'),
  840. trr_count=('RewardRateTotal', 'count'),
  841. crr_mean=('RewardRateCurrent', 'mean'),
  842. crr_count=('RewardRateCurrent', 'count')
  843. )
  844. .reset_index()
  845. .sort_values('TimeInNbh_bin')
  846. .dropna(subset=['trr_mean', 'crr_mean'], how='all')
  847. )
  848. time_vals = agg_df['TimeInNbh_bin'].values
  849. # 4. Plot cRR (Orange) with fading opacity
  850. plot_fading_line(
  851. ax, time_vals, agg_df['crr_mean'], agg_df['crr_count'],
  852. color=palette['cRR'], linewidth=2.5, zorder=2
  853. )
  854. # 5. Plot tRR (Blue) on top with fading opacity
  855. plot_fading_line(
  856. ax, time_vals, agg_df['trr_mean'], agg_df['trr_count'],
  857. color=palette['tRR'], linewidth=2.5, zorder=3
  858. )
  859. ax.set_title(f'Round {roundN}', fontsize=12, fontweight='semibold', loc='left', pad=8)
  860. ax.set_ylabel('Reward Rate (reward/sec)', fontsize=10, labelpad=8)
  861. ax.grid(True, linestyle='--', alpha=0.3, zorder=0)
  862. sns.despine(ax=ax, top=True, right=True)
  863. if i == 0:
  864. # Custom legend elements for metrics + opacity gradient indicators
  865. legend_elements = [
  866. Line2D([0], [0], color=palette['cRR'], lw=2.5, label='Patch Reward Rate (pRR)'),
  867. Line2D([0], [0], color=palette['tRR'], lw=2.5, label='Expected Reward Rate (eRR)'),
  868. Line2D([0], [0], color='gray', lw=2.5, alpha=1.0, label=r'100% Opacity ($N = N_{\mathrm{max}}$)'),
  869. Line2D([0], [0], color='gray', lw=2.5, alpha=0.2, label=r'20% Opacity ($N = N_{\mathrm{min}}$)'),
  870. ]
  871. ax.legend(
  872. handles=legend_elements,
  873. loc='upper right', frameon=True, facecolor='white',
  874. edgecolor='none', framealpha=0.9, fontsize=9.5
  875. )
  876. # Fix x-axis range to [0, 300] seconds
  877. for ax in axes:
  878. ax.set_xlim(left=0, right=300)
  879. # Axis formatting
  880. axes[-1].set_xlabel('Time Since Neighborhood Entry (seconds)', fontsize=11, labelpad=8)
  881. # Enforce uniform bottom=0 and a minimum y-axis ceiling across subplots
  882. global_ymax = max(ax.get_ylim()[1] for ax in fig.axes)
  883. target_ymax = max(0.5, global_ymax)
  884. for ax in fig.axes:
  885. ax.set_ylim(bottom=0, top=target_ymax)
  886. plt.tight_layout()
  887. plt.show()
  888. # %%
  889. sns.set_theme(style="ticks")
  890. palette = {"tRR": "#1f77b4", "cRR": "#ff7f0e"}
  891. plot_df = resampledDF.copy()
  892. # 1. Mask timestamps prior to the first completed payload in EACH neighborhood visit
  893. def mask_before_first_nbh_payload(df_visit):
  894. valid_payloads = df_visit[df_visit['RewardRateCurrent'].notna() & (df_visit['RewardRateCurrent'] > 0)]
  895. if not valid_payloads.empty:
  896. first_payload_t = valid_payloads['TimeInNbh'].iloc[0]
  897. df_visit.loc[df_visit['TimeInNbh'] < first_payload_t, ['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  898. else:
  899. df_visit[['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  900. return df_visit
  901. plot_df = plot_df.groupby(['Round', 'ID', 'VisitNumber'], group_keys=False).apply(mask_before_first_nbh_payload)
  902. # 2. Bin TimeInNbh to integer seconds and truncate at t = 300s
  903. plot_df['TimeInNbh_bin'] = plot_df['TimeInNbh'].round(0)
  904. plot_df = plot_df[plot_df['TimeInNbh_bin'] <= 300]
  905. # Helper function to plot line segments with dynamic opacity mapped to N
  906. def plot_fading_line(ax, x, y, counts, color, linewidth, zorder):
  907. x = np.asarray(x)
  908. y = np.asarray(y)
  909. counts = np.asarray(counts)
  910. n_max = counts.max()
  911. n_min = counts.min()
  912. if n_max > n_min:
  913. alphas = 0.20 + 0.80 * (counts - n_min) / (n_max - n_min)
  914. else:
  915. alphas = np.ones_like(counts, dtype=float)
  916. points = np.array([x, y]).T.reshape(-1, 1, 2)
  917. segments = np.concatenate([points[:-1], points[1:]], axis=1)
  918. base_rgb = mcolors.to_rgb(color)
  919. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  920. colors = [(*base_rgb, a) for a in seg_alphas]
  921. lc = LineCollection(segments, colors=colors, linewidths=linewidth, zorder=zorder)
  922. ax.add_collection(lc)
  923. # Helper function to plot SEM shaded ribbon with dynamic opacity mapped to N
  924. def plot_fading_ribbon(ax, x, y_lower, y_upper, counts, color, zorder):
  925. x = np.asarray(x)
  926. y_lower = np.asarray(y_lower)
  927. y_upper = np.asarray(y_upper)
  928. counts = np.asarray(counts)
  929. n_max = counts.max()
  930. n_min = counts.min()
  931. # Scale ribbon fill opacity from 0.05 (at N_min) to 0.25 (at N_max)
  932. if n_max > n_min:
  933. alphas = 0.05 + 0.20 * (counts - n_min) / (n_max - n_min)
  934. else:
  935. alphas = np.full_like(counts, 0.25, dtype=float)
  936. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  937. base_rgb = mcolors.to_rgb(color)
  938. facecolors = [(*base_rgb, a) for a in seg_alphas]
  939. verts = []
  940. for i in range(len(x) - 1):
  941. verts.append([
  942. [x[i], y_lower[i]],
  943. [x[i+1], y_lower[i+1]],
  944. [x[i+1], y_upper[i+1]],
  945. [x[i], y_upper[i]]
  946. ])
  947. pc = PolyCollection(verts, facecolors=facecolors, edgecolors='none', zorder=zorder)
  948. ax.add_collection(pc)
  949. fig, axes = plt.subplots(3, 1, figsize=(10, 11), sharex=True, sharey=True)
  950. for i, roundN in enumerate([1, 2, 3]):
  951. ax = axes[i]
  952. round_data = plot_df[plot_df['Round'] == roundN]
  953. # 3. Aggregate mean, SEM, and sample size N per time bin (up to t=300)
  954. agg_df = (
  955. round_data.groupby('TimeInNbh_bin')
  956. .agg(
  957. trr_mean=('RewardRateTotal', 'mean'),
  958. trr_sem=('RewardRateTotal', 'sem'),
  959. trr_count=('RewardRateTotal', 'count'),
  960. crr_mean=('RewardRateCurrent', 'mean'),
  961. crr_sem=('RewardRateCurrent', 'sem'),
  962. crr_count=('RewardRateCurrent', 'count')
  963. )
  964. .reset_index()
  965. .sort_values('TimeInNbh_bin')
  966. .dropna(subset=['trr_mean', 'crr_mean'], how='all')
  967. )
  968. # Handle bins with single observation (SEM=NaN)
  969. agg_df['trr_sem'] = agg_df['trr_sem'].fillna(0)
  970. agg_df['crr_sem'] = agg_df['crr_sem'].fillna(0)
  971. time_vals = agg_df['TimeInNbh_bin'].values
  972. # 4. Plot cRR (Orange) SEM Ribbon + Mean Line (Underneath)
  973. plot_fading_ribbon(
  974. ax, time_vals,
  975. agg_df['crr_mean'] - agg_df['crr_sem'],
  976. agg_df['crr_mean'] + agg_df['crr_sem'],
  977. agg_df['crr_count'], color=palette['cRR'], zorder=1
  978. )
  979. plot_fading_line(
  980. ax, time_vals, agg_df['crr_mean'], agg_df['crr_count'],
  981. color=palette['cRR'], linewidth=2.5, zorder=2
  982. )
  983. # 5. Plot tRR (Blue) SEM Ribbon + Mean Line (On Top)
  984. plot_fading_ribbon(
  985. ax, time_vals,
  986. agg_df['trr_mean'] - agg_df['trr_sem'],
  987. agg_df['trr_mean'] + agg_df['trr_sem'],
  988. agg_df['trr_count'], color=palette['tRR'], zorder=3
  989. )
  990. plot_fading_line(
  991. ax, time_vals, agg_df['trr_mean'], agg_df['trr_count'],
  992. color=palette['tRR'], linewidth=2.5, zorder=4
  993. )
  994. ax.set_title(f'Round {roundN}', fontsize=12, fontweight='semibold', loc='left', pad=8)
  995. ax.set_ylabel('Reward Rate (reward/sec)', fontsize=10, labelpad=8)
  996. ax.grid(True, linestyle='--', alpha=0.3, zorder=0)
  997. sns.despine(ax=ax, top=True, right=True)
  998. if i == 0:
  999. legend_elements = [
  1000. Line2D([0], [0], color=palette['cRR'], lw=2.5, label='Patch Reward Rate (pRR) ± SEM'),
  1001. Line2D([0], [0], color=palette['tRR'], lw=2.5, label='Expected Reward Rate (eRR) ± SEM'),
  1002. Line2D([0], [0], color='gray', lw=2.5, alpha=1.0, label=r'100% Opacity ($N = N_{\mathrm{max}}$)'),
  1003. Line2D([0], [0], color='gray', lw=2.5, alpha=0.2, label=r'20% Opacity ($N = N_{\mathrm{min}}$)'),
  1004. ]
  1005. ax.legend(
  1006. handles=legend_elements,
  1007. loc='upper right', frameon=True, facecolor='white',
  1008. edgecolor='none', framealpha=0.9, fontsize=9.5
  1009. )
  1010. # Fix x-axis range to [0, 300] seconds
  1011. for ax in axes:
  1012. ax.set_xlim(left=0, right=300)
  1013. # Axis formatting
  1014. axes[-1].set_xlabel('Time Since Neighborhood Entry (seconds)', fontsize=11, labelpad=8)
  1015. # Enforce uniform bottom=0 and a minimum y-axis ceiling across subplots
  1016. global_ymax = max(ax.get_ylim()[1] for ax in fig.axes)
  1017. target_ymax = max(0.5, global_ymax)
  1018. for ax in fig.axes:
  1019. ax.set_ylim(bottom=0, top=target_ymax)
  1020. plt.tight_layout()
  1021. plt.show()
  1022. # %%
  1023. sns.set_theme(style="ticks")
  1024. palette = {"tRR": "#1f77b4", "cRR": "#ff7f0e"}
  1025. plot_df = resampledDF.copy()
  1026. # 1. Mask timestamps prior to the first completed payload in EACH neighborhood visit
  1027. def mask_before_first_nbh_payload(df_visit):
  1028. valid_payloads = df_visit[df_visit['RewardRateCurrent'].notna() & (df_visit['RewardRateCurrent'] > 0)]
  1029. if not valid_payloads.empty:
  1030. first_payload_t = valid_payloads['TimeInNbh'].iloc[0]
  1031. df_visit.loc[df_visit['TimeInNbh'] < first_payload_t, ['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  1032. else:
  1033. df_visit[['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  1034. return df_visit
  1035. plot_df = plot_df.groupby(['Round', 'ID', 'VisitNumber'], group_keys=False).apply(mask_before_first_nbh_payload)
  1036. # 2. Bin TimeInNbh to integer seconds and truncate at t = 300s
  1037. plot_df['TimeInNbh_bin'] = plot_df['TimeInNbh'].round(0)
  1038. plot_df = plot_df[plot_df['TimeInNbh_bin'] <= 300]
  1039. # Helper function to plot a line with dynamic opacity mapped to N
  1040. def plot_fading_line(ax, x, y, counts, color, linewidth, zorder):
  1041. x = np.asarray(x)
  1042. y = np.asarray(y)
  1043. counts = np.asarray(counts)
  1044. n_max = counts.max()
  1045. n_min = counts.min()
  1046. # Scale alpha linearly between 0.20 (at N_min) and 1.00 (at N_max)
  1047. if n_max > n_min:
  1048. alphas = 0.20 + 0.80 * (counts - n_min) / (n_max - n_min)
  1049. else:
  1050. alphas = np.ones_like(counts, dtype=float)
  1051. # Build 2D line segments between consecutive (x, y) points
  1052. points = np.array([x, y]).T.reshape(-1, 1, 2)
  1053. segments = np.concatenate([points[:-1], points[1:]], axis=1)
  1054. # Calculate average RGBA color per segment
  1055. base_rgb = mcolors.to_rgb(color)
  1056. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  1057. colors = [(*base_rgb, a) for a in seg_alphas]
  1058. lc = LineCollection(segments, colors=colors, linewidths=linewidth, zorder=zorder)
  1059. ax.add_collection(lc)
  1060. fig, axes = plt.subplots(3, 1, figsize=(10, 11), sharex=True, sharey=True)
  1061. for i, roundN in enumerate([1, 2, 3]):
  1062. ax = axes[i]
  1063. round_data = plot_df[plot_df['Round'] == roundN]
  1064. # 3. Individual visit traces underneath (linewidth=0.4, alpha=0.12, zorder=1)
  1065. for (pID, vNum), visit_data in round_data.groupby(['ID', 'VisitNumber']):
  1066. v_valid = visit_data.dropna(subset=['RewardRateTotal', 'RewardRateCurrent'], how='all')
  1067. if v_valid.empty:
  1068. continue
  1069. # Orange (cRR) individual visit trace
  1070. ax.plot(
  1071. v_valid['TimeInNbh_bin'], v_valid['RewardRateCurrent'],
  1072. color=palette['cRR'], alpha=0.12, linewidth=0.4, zorder=1
  1073. )
  1074. # Blue (tRR) individual visit trace
  1075. ax.plot(
  1076. v_valid['TimeInNbh_bin'], v_valid['RewardRateTotal'],
  1077. color=palette['tRR'], alpha=0.12, linewidth=0.4, zorder=1
  1078. )
  1079. # 4. Aggregate mean and sample size N per time bin (up to t=300)
  1080. agg_df = (
  1081. round_data.groupby('TimeInNbh_bin')
  1082. .agg(
  1083. trr_mean=('RewardRateTotal', 'mean'),
  1084. trr_count=('RewardRateTotal', 'count'),
  1085. crr_mean=('RewardRateCurrent', 'mean'),
  1086. crr_count=('RewardRateCurrent', 'count')
  1087. )
  1088. .reset_index()
  1089. .sort_values('TimeInNbh_bin')
  1090. .dropna(subset=['trr_mean', 'crr_mean'], how='all')
  1091. )
  1092. time_vals = agg_df['TimeInNbh_bin'].values
  1093. # 5. Plot cRR (Orange) mean with fading opacity
  1094. plot_fading_line(
  1095. ax, time_vals, agg_df['crr_mean'], agg_df['crr_count'],
  1096. color=palette['cRR'], linewidth=2.5, zorder=2
  1097. )
  1098. # 6. Plot tRR (Blue) mean on top with fading opacity
  1099. plot_fading_line(
  1100. ax, time_vals, agg_df['trr_mean'], agg_df['trr_count'],
  1101. color=palette['tRR'], linewidth=2.5, zorder=3
  1102. )
  1103. ax.set_title(f'Round {roundN}', fontsize=12, fontweight='semibold', loc='left', pad=8)
  1104. ax.set_ylabel('Reward Rate (reward/sec)', fontsize=10, labelpad=8)
  1105. ax.grid(True, linestyle='--', alpha=0.3, zorder=0)
  1106. sns.despine(ax=ax, top=True, right=True)
  1107. if i == 0:
  1108. # Custom legend elements
  1109. legend_elements = [
  1110. Line2D([0], [0], color=palette['cRR'], lw=2.5, label='Patch Reward Rate (pRR)'),
  1111. Line2D([0], [0], color=palette['tRR'], lw=2.5, label='Expected Reward Rate (eRR)'),
  1112. Line2D([0], [0], color='gray', lw=0.8, alpha=0.5, label='Individual Visit Traces'),
  1113. Line2D([0], [0], color='gray', lw=2.5, alpha=1.0, label=r'100% Opacity ($N = N_{\mathrm{max}}$)'),
  1114. Line2D([0], [0], color='gray', lw=2.5, alpha=0.2, label=r'20% Opacity ($N = N_{\mathrm{min}}$)'),
  1115. ]
  1116. ax.legend(
  1117. handles=legend_elements,
  1118. loc='upper right', frameon=True, facecolor='white',
  1119. edgecolor='none', framealpha=0.9, fontsize=9.5
  1120. )
  1121. # Fix x-axis range to [0, 300] seconds
  1122. for ax in axes:
  1123. ax.set_xlim(left=0, right=300)
  1124. # Axis formatting
  1125. axes[-1].set_xlabel('Time Since Neighborhood Entry (seconds)', fontsize=11, labelpad=8)
  1126. # Enforce uniform bottom=0 and a minimum y-axis ceiling across subplots
  1127. global_ymax = max(ax.get_ylim()[1] for ax in fig.axes)
  1128. target_ymax = max(0.5, global_ymax)
  1129. for ax in fig.axes:
  1130. ax.set_ylim(bottom=0, top=target_ymax)
  1131. plt.tight_layout()
  1132. plt.show()
  1133. # %%
  1134. sns.set_theme(style="ticks")
  1135. # --- 1. Blue Color Gradient across Rounds ---
  1136. blues = sns.color_palette("Blues", n_colors=6)
  1137. round_colors = [blues[2], blues[4], blues[5]] # Round 1: Light, Round 2: Medium, Round 3: Dark
  1138. # --- 2. Vectorized Data Processing ---
  1139. plot_df = resampledDF.copy()
  1140. # Find time of first valid payload per visit group
  1141. valid_mask = plot_df['RewardRateCurrent'] > 0
  1142. plot_df['first_payload_t'] = plot_df.where(valid_mask).groupby(['Round', 'ID', 'VisitNumber'])['TimeInNbh'].transform('min')
  1143. # Mask timestamps prior to first payload (or visits with no payload)
  1144. invalid_mask = (plot_df['TimeInNbh'] < plot_df['first_payload_t']) | plot_df['first_payload_t'].isna()
  1145. plot_df.loc[invalid_mask, ['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  1146. # Calculate Marginal Reward Rate (Patch RR - Expected RR) and filter binned time (<= 200s)
  1147. plot_df['RR_Diff'] = plot_df['RewardRateCurrent'] - plot_df['RewardRateTotal']
  1148. plot_df['TimeInNbh_bin'] = plot_df['TimeInNbh'].round(0)
  1149. plot_df = plot_df[plot_df['TimeInNbh_bin'] <= 400]
  1150. # --- 3. Compact Visual Helpers ---
  1151. def get_alphas(counts, min_val, max_val):
  1152. """Rescale counts to alpha range [min_val, max_val]."""
  1153. n_min, n_max = counts.min(), counts.max()
  1154. if n_max > n_min:
  1155. return min_val + (max_val - min_val) * (counts - n_min) / (n_max - n_min)
  1156. return np.full_like(counts, max_val, dtype=float)
  1157. def plot_fading_line(ax, x, y, counts, color, linewidth=2.5, zorder=2):
  1158. alphas = get_alphas(counts, 0.20, 1.00)
  1159. pts = np.array([x, y]).T.reshape(-1, 1, 2)
  1160. segments = np.concatenate([pts[:-1], pts[1:]], axis=1)
  1161. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  1162. colors = [(*mcolors.to_rgb(color), a) for a in seg_alphas]
  1163. ax.add_collection(LineCollection(segments, colors=colors, linewidths=linewidth, zorder=zorder))
  1164. def plot_fading_ribbon(ax, x, y_lower, y_upper, counts, color, zorder=1):
  1165. alphas = get_alphas(counts, 0.05, 0.25)
  1166. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  1167. base_rgb = mcolors.to_rgb(color)
  1168. verts = [
  1169. [[x[i], y_lower[i]], [x[i+1], y_lower[i+1]],
  1170. [x[i+1], y_upper[i+1]], [x[i], y_upper[i]]]
  1171. for i in range(len(x) - 1)
  1172. ]
  1173. ax.add_collection(PolyCollection(verts, facecolors=[(*base_rgb, a) for a in seg_alphas], edgecolors='none', zorder=zorder))
  1174. # --- 4. Figure Plotting Loop ---
  1175. fig, axes = plt.subplots(3, 1, figsize=(10, 11), sharex=True, sharey=True)
  1176. for i, roundN in enumerate([1, 2, 3]):
  1177. ax = axes[i]
  1178. current_color = round_colors[i] # Progressive blue per round
  1179. # Aggregate mean, sample size N, and compute 95% CI
  1180. agg_df = (
  1181. plot_df[plot_df['Round'] == roundN]
  1182. .groupby('TimeInNbh_bin')['RR_Diff']
  1183. .agg(mean='mean', sem='sem', count='count')
  1184. .dropna(subset=['mean'])
  1185. .reset_index()
  1186. )
  1187. # Calculate 95% Confidence Interval bound using scipy.stats.t
  1188. t_crit = t_dist.ppf(0.975, df=np.maximum(agg_df['count'] - 1, 1))
  1189. agg_df['ci95'] = (t_crit * agg_df['sem']).fillna(0)
  1190. x = agg_df['TimeInNbh_bin'].values
  1191. y_mean = agg_df['mean'].values
  1192. ci = agg_df['ci95'].values
  1193. counts = agg_df['count'].values
  1194. # Plot elements
  1195. ax.axhline(0, color='gray', linestyle='--', linewidth=1.2, alpha=0.7, zorder=0)
  1196. plot_fading_ribbon(ax, x, y_mean - ci, y_mean + ci, counts, color=current_color, zorder=1)
  1197. plot_fading_line(ax, x, y_mean, counts, color=current_color, linewidth=2.5, zorder=2)
  1198. # Subplot Formatting
  1199. ax.set_ylim(-0.2, 0.2)
  1200. ax.set_xlim(0, 400)
  1201. ax.set_title(f'Round {roundN}', fontsize=12, fontweight='semibold', loc='left', pad=8)
  1202. ax.set_ylabel('Marginal Reward Rate (reward/sec)\n[Patch RR - Expected RR]', fontsize=10, labelpad=8)
  1203. ax.grid(True, linestyle='--', alpha=0.3, zorder=0)
  1204. sns.despine(ax=ax, top=True, right=True)
  1205. axes[-1].set_xlabel('Time Since Neighborhood Entry (seconds)', fontsize=11, labelpad=8)
  1206. plt.tight_layout()
  1207. plt.show()
  1208. # %%
  1209. sns.set_theme(style="ticks")
  1210. # --- 1. Calculate Marginal RR ---
  1211. resampled_df = resampledDF.copy()
  1212. resampled_df['Marginal_RR'] = resampled_df['RewardRateCurrent'] - resampled_df['RewardRateTotal']
  1213. exits_df = RealExitsDF.copy().rename(columns={'ParticipantID': 'ID'})
  1214. # --- 2. Align Key Data Types Across DataFrames ---
  1215. merge_by = ['Round', 'ID']
  1216. if 'VisitNumber' in exits_df.columns and 'VisitNumber' in resampled_df.columns:
  1217. merge_by.append('VisitNumber')
  1218. for col in merge_by:
  1219. exits_df[col] = exits_df[col].astype(int)
  1220. resampled_df[col] = resampled_df[col].astype(int)
  1221. # --- 3. Sort & Merge on Time Keys ---
  1222. resampled_sorted = resampled_df.dropna(subset=['Marginal_RR']).sort_values('RegularTimestamp')
  1223. exits_sorted = exits_df.sort_values('TimeStamp')
  1224. exit_data = pd.merge_asof(
  1225. exits_sorted,
  1226. resampled_sorted[merge_by + ['RegularTimestamp', 'Marginal_RR']],
  1227. left_on='TimeStamp', # Time column in RealExitsDF
  1228. right_on='RegularTimestamp', # Time column in resampledDF
  1229. by=merge_by,
  1230. direction='nearest' # Matches to nearest floating timestamp
  1231. )
  1232. # Diagnostic verification
  1233. print(f"Total Exit Events in RealExitsDF: {len(RealExitsDF)}")
  1234. print(f"Matched Exit Events in exit_data: {len(exit_data)}")
  1235. print(f"Missing/NaN RR Exits: {exit_data['Marginal_RR'].isna().sum()}")
  1236. # --- 4. Plotting Histograms per Round ---
  1237. fig, axes = plt.subplots(3, 1, figsize=(10, 10), sharex=True, sharey=True)
  1238. bins = np.linspace(-0.4, 0.4, 81)
  1239. # Extract 3 shades of blue (Round 1: light blue, Round 2: medium blue, Round 3: dark blue)
  1240. blues = sns.color_palette("Blues", n_colors=6)
  1241. round_colors = [blues[2], blues[4], blues[5]]
  1242. for i, roundN in enumerate([1, 2, 3]):
  1243. ax = axes[i]
  1244. round_exits = exit_data[exit_data['Round'] == roundN]['Marginal_RR'].dropna()
  1245. if len(round_exits) > 0:
  1246. mean_val = round_exits.mean()
  1247. median_val = round_exits.median()
  1248. sdDuration = round_exits.std()
  1249. print(f'Round {roundN}:\nmean = {mean_val}\nmedian = {median_val}\nsd = {sdDuration}')
  1250. sns.histplot(
  1251. round_exits, bins=bins, kde=False, ax=ax,
  1252. color=round_colors[i], alpha=0.85, stat="density",
  1253. edgecolor="white", linewidth=0.8
  1254. )
  1255. sns.kdeplot(
  1256. round_exits, fill=True,
  1257. ax = ax, color=round_colors[i], alpha=0.45
  1258. )
  1259. # # Uncomment these if you want reference lines on the plot:
  1260. # ax.axvline(0, color='gray', linestyle='--', linewidth=1.2, alpha=0.8, label='Equilibrium (0)')
  1261. # ax.axvline(mean_val, color='#d62728', linestyle='-', linewidth=1.8, label=f'Mean ({mean_val:.3f})')
  1262. # ax.axvline(median_val, color='#1f77b4', linestyle=':', linewidth=2.0, label=f'Median ({median_val:.3f})')
  1263. ax.set_xlim(-0.4, 0.4)
  1264. ax.set_title(f'Round {roundN} (N = {len(round_exits)} exits)', fontsize=12, fontweight='semibold', loc='left', pad=8)
  1265. ax.set_ylabel('Density', fontsize=10, labelpad=8)
  1266. ax.grid(True, linestyle='--', alpha=0.3)
  1267. sns.despine(ax=ax, top=True, right=True)
  1268. axes[-1].set_xlabel('Marginal Reward Rate at Exit (reward/sec)', fontsize=11, labelpad=8)
  1269. plt.tight_layout()
  1270. plt.show()
  1271. # %%
  1272. sns.set_theme(style="ticks")
  1273. # --- 1. Calculate Marginal RR ---
  1274. resampled_df = resampledDF.copy()
  1275. resampled_df['Marginal_RR'] = resampled_df['RewardRateCurrent'] - resampled_df['RewardRateTotal']
  1276. exits_df = RealExitsDF.copy().rename(columns={'ParticipantID': 'ID'})
  1277. # --- 2. Filter Out the First Exit of Each Round Per Participant ---
  1278. # Sort to ensure chronological order per participant and round
  1279. exits_df = exits_df.sort_values(['Round', 'ID', 'TimeStamp'])
  1280. # Option A: If VisitNumber exists, keep visits greater than the minimum visit number
  1281. if 'VisitNumber' in exits_df.columns:
  1282. min_visits = exits_df.groupby(['Round', 'ID'])['VisitNumber'].transform('min')
  1283. exits_df = exits_df[exits_df['VisitNumber'] > min_visits]
  1284. # Option B: Fallback using row rank based on exit time
  1285. else:
  1286. exits_df['exit_rank'] = exits_df.groupby(['Round', 'ID'])['TimeStamp'].rank(method='first')
  1287. exits_df = exits_df[exits_df['exit_rank'] > 1].drop(columns=['exit_rank'])
  1288. # --- 3. Align Key Data Types Across DataFrames ---
  1289. merge_by = ['Round', 'ID']
  1290. if 'VisitNumber' in exits_df.columns and 'VisitNumber' in resampled_df.columns:
  1291. merge_by.append('VisitNumber')
  1292. for col in merge_by:
  1293. exits_df[col] = exits_df[col].astype(int)
  1294. resampled_df[col] = resampled_df[col].astype(int)
  1295. # --- 4. Sort & Merge on Time Keys ---
  1296. resampled_sorted = resampled_df.dropna(subset=['Marginal_RR']).sort_values('RegularTimestamp')
  1297. exits_sorted = exits_df.sort_values('TimeStamp')
  1298. exit_data = pd.merge_asof(
  1299. exits_sorted,
  1300. resampled_sorted[merge_by + ['RegularTimestamp', 'Marginal_RR']],
  1301. left_on='TimeStamp', # Time column in RealExitsDF
  1302. right_on='RegularTimestamp', # Time column in resampledDF
  1303. by=merge_by,
  1304. direction='nearest' # Matches to nearest floating timestamp
  1305. )
  1306. # Diagnostic verification
  1307. print(f"Total Exit Events Filtered: {len(exits_df)}")
  1308. print(f"Matched Exit Events in exit_data: {len(exit_data)}")
  1309. print(f"Missing/NaN RR Exits: {exit_data['Marginal_RR'].isna().sum()}")
  1310. # --- 5. Plotting Histograms per Round ---
  1311. fig, axes = plt.subplots(3, 1, figsize=(10, 10), sharex=True, sharey=True)
  1312. bins = np.linspace(-0.4, 0.4, 81)
  1313. # Extract 3 shades of blue (Round 1: light blue, Round 2: medium blue, Round 3: dark blue)
  1314. blues = sns.color_palette("Blues", n_colors=6)
  1315. round_colors = [blues[2], blues[4], blues[5]]
  1316. for i, roundN in enumerate([1, 2, 3]):
  1317. ax = axes[i]
  1318. round_exits = exit_data[exit_data['Round'] == roundN]['Marginal_RR'].dropna()
  1319. if len(round_exits) > 0:
  1320. mean_val = round_exits.mean()
  1321. median_val = round_exits.median()
  1322. sdDuration = round_exits.std()
  1323. print(f'Round {roundN} (Excluding First Exits):\nmean = {mean_val}\nmedian = {median_val}\nsd = {sdDuration}\n')
  1324. sns.histplot(
  1325. round_exits, bins=bins, kde=False, ax=ax,
  1326. color=round_colors[i], alpha=0.85, stat="density",
  1327. edgecolor="white", linewidth=0.8
  1328. )
  1329. sns.kdeplot(
  1330. round_exits, fill=True,
  1331. ax=ax, color=round_colors[i], alpha=0.45
  1332. )
  1333. ax.set_xlim(-0.4, 0.4)
  1334. ax.set_title(f'Round {roundN} (N = {len(round_exits)} exits - excluding first exit)', fontsize=12, fontweight='semibold', loc='left', pad=8)
  1335. ax.set_ylabel('Density', fontsize=10, labelpad=8)
  1336. ax.grid(True, linestyle='--', alpha=0.3)
  1337. sns.despine(ax=ax, top=True, right=True)
  1338. axes[-1].set_xlabel('Marginal Reward Rate at Exit (reward/sec)', fontsize=11, labelpad=8)
  1339. plt.tight_layout()
  1340. plt.show()
  1341. # %%
  1342. # Filter resampledDF for nbhIn rows (where time in neighborhood starts)
  1343. nbh_in_events = resampledDF[resampledDF['TimeInNbh'] < 2.0].sort_values('RegularTimestamp')
  1344. exits_sorted = exit_data.sort_values('RegularTimestamp')
  1345. # %%
  1346. # --- 1. Standardize and Sort DataFrames ---
  1347. nbh_df = nbh_in_events.copy()
  1348. exits_df = RealExitsDF.copy().rename(columns={'ParticipantID': 'ID'})
  1349. # Align data types
  1350. for col in ['ID', 'Round']:
  1351. nbh_df[col] = nbh_df[col].astype(int)
  1352. exits_df[col] = exits_df[col].astype(int)
  1353. # Sort chronologically within each participant & round
  1354. nbh_sorted = nbh_df.sort_values(['ID', 'Round', 'RegularTimestamp']).reset_index(drop=True)
  1355. exits_sorted = exits_df.sort_values(['ID', 'Round', 'TimeStamp']).reset_index(drop=True)
  1356. # --- 2. Create Sequence Number per (ID, Round) Group ---
  1357. nbh_sorted['visit_seq'] = nbh_sorted.groupby(['ID', 'Round']).cumcount()
  1358. exits_sorted['visit_seq'] = exits_sorted.groupby(['ID', 'Round']).cumcount()
  1359. # --- 3. Positional Inner Merge ---
  1360. visit_durations_df = pd.merge(
  1361. nbh_sorted,
  1362. exits_sorted[['ID', 'Round', 'visit_seq', 'TimeStamp']].rename(columns={'TimeStamp': 'Exit_Timestamp'}),
  1363. on=['ID', 'Round', 'visit_seq'],
  1364. how='inner' # Drops trailing entries with no matching exit index
  1365. )
  1366. # --- 4. Calculate Duration & Ensure Exit > Entry ---
  1367. visit_durations_df['VisitDuration'] = visit_durations_df['Exit_Timestamp'] - visit_durations_df['RegularTimestamp']
  1368. # Filter out any non-positive duration edge cases
  1369. visit_durations_df = visit_durations_df[visit_durations_df['VisitDuration'] > 0]
  1370. # --- Verification Summary ---
  1371. print(f"Total Entries: {len(nbh_in_events)}")
  1372. print(f"Total Exits Available: {len(RealExitsDF)}")
  1373. print(f"Successfully Matched Visits: {len(visit_durations_df)}")
  1374. print(f"Dropped Uncompleted/Trailing Visits: {len(nbh_in_events) - len(visit_durations_df)}")
  1375. # %%
  1376. sns.set_theme(style="ticks")
  1377. fig, axes = plt.subplots(3, 1, figsize=(10, 10), sharex=True, sharey=True)
  1378. #bins = np.linspace(0, 200, 41)
  1379. blues = sns.color_palette("Blues", n_colors=6)
  1380. round_colors = [blues[2], blues[4], blues[5]] # [R1: Light, R2: Medium, R3: Dark]
  1381. for i, roundN in enumerate([1, 2, 3]):
  1382. ax = axes[i]
  1383. round_durations = visit_durations_df[visit_durations_df['Round'] == roundN]['VisitDuration'].dropna()
  1384. n_count = len(round_durations)
  1385. meanDuration = np.mean(round_durations)
  1386. medDuration = np.median(round_durations)
  1387. sdDuration = np.std(round_durations)
  1388. print(f'Round {roundN}:\nmean = {meanDuration}\nmedian = {medDuration}\nsd = {sdDuration}')
  1389. sns.histplot(
  1390. round_durations, kde=False, ax=ax, #bins=bins,
  1391. color=round_colors[i], alpha=0.85, stat="density",
  1392. edgecolor="white", linewidth=0.8
  1393. )
  1394. ax.set_title(f'Round {roundN} (N = {n_count} completed visits)', fontsize=12, fontweight='semibold', loc='left', pad=8)
  1395. ax.set_ylabel('Density', fontsize=10, labelpad=8)
  1396. ax.grid(True, linestyle='--', alpha=0.3)
  1397. sns.despine(ax=ax, top=True, right=True)
  1398. axes[-1].set_xlabel(r'Neighborhood Visit Duration (seconds) [$t_{\mathrm{exit}} - t_{\mathrm{entry}}$]', fontsize=11, labelpad=8)
  1399. plt.tight_layout()
  1400. plt.show()
  1401. # %%
  1402. sns.set_theme(style="ticks")
  1403. TIME_MAX = 400
  1404. bins = np.linspace(0, TIME_MAX, 20)
  1405. # --- 1. Blue Color Gradient across Rounds ---
  1406. blues = sns.color_palette("Blues", n_colors=6)
  1407. round_colors = [blues[2], blues[4], blues[5]]
  1408. purps = sns.color_palette('Greys', n_colors=20)
  1409. hist_colors = [purps[9], purps[14], purps[19]]
  1410. # --- 2. Vectorized Data Processing ---
  1411. plot_df = resampledDF.copy()
  1412. # Find time of first valid payload per visit group
  1413. valid_mask = plot_df['RewardRateCurrent'] > 0
  1414. plot_df['first_payload_t'] = plot_df.where(valid_mask).groupby(['Round', 'ID', 'VisitNumber'])['TimeInNbh'].transform('min')
  1415. # Mask timestamps prior to first payload (or visits with no payload)
  1416. invalid_mask = (plot_df['TimeInNbh'] < plot_df['first_payload_t']) | plot_df['first_payload_t'].isna()
  1417. plot_df.loc[invalid_mask, ['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  1418. # Calculate Marginal Reward Rate (Patch RR - Expected RR) and filter binned time (<= 200s)
  1419. plot_df['RR_Diff'] = plot_df['RewardRateCurrent'] - plot_df['RewardRateTotal']
  1420. plot_df['TimeInNbh_bin'] = plot_df['TimeInNbh'].round(0)
  1421. plot_df = plot_df[plot_df['TimeInNbh_bin'] <= TIME_MAX]
  1422. # --- 3. Compact Visual Helpers ---
  1423. def get_alphas(counts, min_val, max_val):
  1424. """Rescale counts to alpha range [min_val, max_val]."""
  1425. n_min, n_max = counts.min(), counts.max()
  1426. if n_max > n_min:
  1427. return min_val + (max_val - min_val) * (counts - n_min) / (n_max - n_min)
  1428. return np.full_like(counts, max_val, dtype=float)
  1429. def plot_fading_line(ax, x, y, counts, color, linewidth=2.5, zorder=2):
  1430. alphas = get_alphas(counts, 0.20, 1.00)
  1431. pts = np.array([x, y]).T.reshape(-1, 1, 2)
  1432. segments = np.concatenate([pts[:-1], pts[1:]], axis=1)
  1433. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  1434. colors = [(*mcolors.to_rgb(color), a) for a in seg_alphas]
  1435. ax.add_collection(LineCollection(segments, colors=colors, linewidths=linewidth, zorder=zorder))
  1436. def plot_fading_ribbon(ax, x, y_lower, y_upper, counts, color, zorder=1):
  1437. alphas = get_alphas(counts, 0.05, 0.25)
  1438. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  1439. base_rgb = mcolors.to_rgb(color)
  1440. verts = [
  1441. [[x[i], y_lower[i]], [x[i+1], y_lower[i+1]],
  1442. [x[i+1], y_upper[i+1]], [x[i], y_upper[i]]]
  1443. for i in range(len(x) - 1)
  1444. ]
  1445. ax.add_collection(PolyCollection(verts, facecolors=[(*base_rgb, a) for a in seg_alphas], edgecolors='none', zorder=zorder))
  1446. # --- 4. Figure Plotting Loop ---
  1447. fig, axes = plt.subplots(3, 1, figsize=(12, 20), sharex=True, sharey=True)
  1448. for i, roundN in enumerate([1, 2, 3]):
  1449. ax = axes[i]
  1450. current_color = round_colors[i] # Progressive blue per round
  1451. # Aggregate mean, sample size N, and compute 95% CI
  1452. agg_df = (
  1453. plot_df[plot_df['Round'] == roundN]
  1454. .groupby('TimeInNbh_bin')['RR_Diff']
  1455. .agg(mean='mean', sem='sem', count='count')
  1456. .dropna(subset=['mean'])
  1457. .reset_index()
  1458. )
  1459. # Calculate 95% Confidence Interval bound using scipy.stats.t
  1460. t_crit = t_dist.ppf(0.975, df=np.maximum(agg_df['count'] - 1, 1))
  1461. agg_df['ci95'] = (t_crit * agg_df['sem']).fillna(0)
  1462. x = agg_df['TimeInNbh_bin'].values
  1463. y_mean = agg_df['mean'].values
  1464. ci = agg_df['ci95'].values
  1465. counts = agg_df['count'].values
  1466. # Plot elements
  1467. ax.axhline(0, color='gray', linestyle='--', linewidth=1.2, alpha=0.7, zorder=0)
  1468. plot_fading_ribbon(ax, x, y_mean - ci, y_mean + ci, counts, color=current_color, zorder=1)
  1469. plot_fading_line(ax, x, y_mean, counts, color=current_color, linewidth=2.5, zorder=2)
  1470. # Subplot Formatting
  1471. ax.set_ylim(-0.05, 0.3)
  1472. ax.set_xlim(0, TIME_MAX)
  1473. ax.set_title(f'Round {roundN}', fontsize=24, fontweight='semibold', loc='left', pad=8)
  1474. ax.set_ylabel('Marginal Reward Rate (reward/sec)', fontsize=20, labelpad=8)
  1475. ax.grid(True, linestyle='--', alpha=0.3, zorder=0)
  1476. sns.despine(ax=ax, top=True, right=True)
  1477. axRight = ax.twinx()
  1478. round_durations = visit_durations_df[visit_durations_df['Round'] == roundN]['VisitDuration'].dropna()
  1479. n_count = len(round_durations)
  1480. sns.histplot(
  1481. round_durations, kde=False, ax=axRight, bins=bins,
  1482. color=hist_colors[i], alpha=0.66, stat="density",
  1483. edgecolor=None, linewidth=0.1
  1484. )
  1485. axRight.set_ylim(-.003, .018)
  1486. axRight.set_ylabel('Density', fontsize=20, labelpad=8)
  1487. axes[-1].set_xlabel('Time Since Neighborhood Entry (seconds)', fontsize=22, labelpad=8)
  1488. plt.tight_layout()
  1489. plt.show()
  1490. # %%
  1491. sns.set_theme(style="ticks")
  1492. TIME_MAX = 400
  1493. bins = np.linspace(0, TIME_MAX, 20)
  1494. # --- 1. Blue Color Gradient across Rounds ---
  1495. blues = sns.color_palette("Blues", n_colors=6)
  1496. round_colors = [blues[2], blues[4], blues[5]]
  1497. purps = sns.color_palette('Greys', n_colors=20)
  1498. hist_colors = [purps[9], purps[14], purps[19]]
  1499. # --- 2. Vectorized Data Processing ---
  1500. plot_df = resampledDF.copy()
  1501. # EXCLUDE FIRST PATCH VISIT (where current neighborhood entry == round's first entry)
  1502. # plot_df = plot_df[plot_df['nbhIn'] != plot_df['firstIn']].copy()
  1503. # Find time of first valid payload per visit group
  1504. valid_mask = plot_df['RewardRateCurrent'] > 0
  1505. plot_df['first_payload_t'] = plot_df.where(valid_mask).groupby(['Round', 'ID', 'VisitNumber'])['TimeInNbh'].transform('min')
  1506. # Mask timestamps prior to first payload (or visits with no payload)
  1507. invalid_mask = (plot_df['TimeInNbh'] < plot_df['first_payload_t']) | plot_df['first_payload_t'].isna()
  1508. plot_df.loc[invalid_mask, ['RewardRateTotal', 'RewardRateCurrent']] = np.nan
  1509. # Calculate Marginal Reward Rate (Patch RR - Expected RR) and filter binned time (<= 400s)
  1510. plot_df['RR_Diff'] = plot_df['RewardRateCurrent'] - plot_df['RewardRateTotal']
  1511. plot_df['TimeInNbh_bin'] = plot_df['TimeInNbh'].round(0)
  1512. plot_df = plot_df[plot_df['TimeInNbh_bin'] <= TIME_MAX]
  1513. plot_df = plot_df[plot_df['nbhIn'] != plot_df['firstIn']].copy()
  1514. # --- 3. Compact Visual Helpers ---
  1515. def get_alphas(counts, min_val, max_val):
  1516. """Rescale counts to alpha range [min_val, max_val]."""
  1517. n_min, n_max = counts.min(), counts.max()
  1518. if n_max > n_min:
  1519. return min_val + (max_val - min_val) * (counts - n_min) / (n_max - n_min)
  1520. return np.full_like(counts, max_val, dtype=float)
  1521. def plot_fading_line(ax, x, y, counts, color, linewidth=2.5, zorder=2):
  1522. alphas = get_alphas(counts, 0.20, 1.00)
  1523. pts = np.array([x, y]).T.reshape(-1, 1, 2)
  1524. segments = np.concatenate([pts[:-1], pts[1:]], axis=1)
  1525. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  1526. colors = [(*mcolors.to_rgb(color), a) for a in seg_alphas]
  1527. ax.add_collection(LineCollection(segments, colors=colors, linewidths=linewidth, zorder=zorder))
  1528. def plot_fading_ribbon(ax, x, y_lower, y_upper, counts, color, zorder=1):
  1529. alphas = get_alphas(counts, 0.05, 0.25)
  1530. seg_alphas = 0.5 * (alphas[:-1] + alphas[1:])
  1531. base_rgb = mcolors.to_rgb(color)
  1532. verts = [
  1533. [[x[i], y_lower[i]], [x[i+1], y_lower[i+1]],
  1534. [x[i+1], y_upper[i+1]], [x[i], y_upper[i]]]
  1535. for i in range(len(x) - 1)
  1536. ]
  1537. ax.add_collection(PolyCollection(verts, facecolors=[(*base_rgb, a) for a in seg_alphas], edgecolors='none', zorder=zorder))
  1538. # --- 4. Figure Plotting Loop ---
  1539. fig, axes = plt.subplots(3, 1, figsize=(12, 20), sharex=True, sharey=True)
  1540. # Also exclude the first patch visit duration from the exits histogram dataset
  1541. if 'firstIn' in visit_durations_df.columns and 'nbhIn' in visit_durations_df.columns:
  1542. durations_filtered = visit_durations_df[visit_durations_df['nbhIn'] != visit_durations_df['firstIn']]
  1543. elif 'VisitNumber' in visit_durations_df.columns:
  1544. durations_filtered = visit_durations_df[visit_durations_df['VisitNumber'] > 1]
  1545. else:
  1546. durations_filtered = visit_durations_df.copy()
  1547. for i, roundN in enumerate([1, 2, 3]):
  1548. ax = axes[i]
  1549. current_color = round_colors[i] # Progressive blue per round
  1550. # Aggregate mean, sample size N, and compute 95% CI
  1551. agg_df = (
  1552. plot_df[plot_df['Round'] == roundN]
  1553. .groupby('TimeInNbh_bin')['RR_Diff']
  1554. .agg(mean='mean', sem='sem', count='count')
  1555. .dropna(subset=['mean'])
  1556. .reset_index()
  1557. )
  1558. # Calculate 95% Confidence Interval bound using scipy.stats.t
  1559. t_crit = t_dist.ppf(0.975, df=np.maximum(agg_df['count'] - 1, 1))
  1560. agg_df['ci95'] = (t_crit * agg_df['sem']).fillna(0)
  1561. x = agg_df['TimeInNbh_bin'].values
  1562. y_mean = agg_df['mean'].values
  1563. ci = agg_df['ci95'].values
  1564. counts = agg_df['count'].values
  1565. # Plot elements
  1566. ax.axhline(0, color='gray', linestyle='--', linewidth=1.2, alpha=0.7, zorder=0)
  1567. plot_fading_ribbon(ax, x, y_mean - ci, y_mean + ci, counts, color=current_color, zorder=1)
  1568. plot_fading_line(ax, x, y_mean, counts, color=current_color, linewidth=2.5, zorder=2)
  1569. # Subplot Formatting
  1570. ax.set_ylim(-0.05, 0.3)
  1571. ax.set_xlim(0, TIME_MAX)
  1572. ax.set_title(f'Round {roundN}', fontsize=24, fontweight='semibold', loc='left', pad=8)
  1573. ax.set_ylabel('Marginal Reward Rate (reward/sec)', fontsize=20, labelpad=8)
  1574. ax.grid(True, linestyle='--', alpha=0.3, zorder=0)
  1575. sns.despine(ax=ax, top=True, right=True)
  1576. axRight = ax.twinx()
  1577. round_durations = durations_filtered[durations_filtered['Round'] == roundN]['VisitDuration'].dropna()
  1578. sns.histplot(
  1579. round_durations, kde=False, ax=axRight, bins=bins,
  1580. color=hist_colors[i], alpha=0.66, stat="density",
  1581. edgecolor=None, linewidth=0.1
  1582. )
  1583. axRight.set_ylim(-.003, .018)
  1584. axRight.set_ylabel('Density', fontsize=20, labelpad=8)
  1585. axes[-1].set_xlabel('Time Since Neighborhood Entry (seconds)', fontsize=22, labelpad=8)
  1586. plt.tight_layout()
  1587. plt.show()
  1588. # %%
  1589. AbandonHouseDF = VisitsDF[VisitsDF['AbandonedPatch'] == True]
  1590. abandonIDs = AbandonHouseDF['ParticipantID'].unique()
  1591. 1/30
  1592. # %%
  1593. AbandonParticipantsDF = VisitsDF[VisitsDF['ParticipantID'].isin(abandonIDs)]
  1594. # %%
  1595. R1PerfDF = PerformanceDF[PerformanceDF['Round'] == 1]
  1596. R2PerfDF = PerformanceDF[PerformanceDF['Round'] == 2]
  1597. R3PerfDF = PerformanceDF[PerformanceDF['Round'] == 3]
  1598. # %%
  1599. for df in [R1PerfDF, R2PerfDF, R3PerfDF]:
  1600. print(df['PatchEfficiency'].mean())
  1601. # %%
  1602. def dobStringToAge(s):
  1603. ## analysis date = 01/01/2025.
  1604. ## returns approx. age as of this date.
  1605. year = int(s[:4])
  1606. month = int(s[4:6])
  1607. day = int(s[6:])
  1608. age = 2025 - (1 + year)
  1609. extraDays = 360 - (30 * month) - day
  1610. return age + extraDays / 360
  1611. # %% [markdown]
  1612. # ages = []
  1613. # for dob in DemographicsDF['Date of Birth']:
  1614. # dobTokens = dob.split('/')
  1615. # dobString = ''
  1616. # for t in dobTokens:
  1617. # if len(t) == 1:
  1618. # t = f'0{t}'
  1619. # dobString = f'{t}{dobString}'
  1620. # ages.append(dobStringToAge(dobString))
  1621. #
  1622. # #ages.append(dobStringToAge('20050424'))
  1623. # #ages.append(dobStringToAge('20050803'))
  1624. # print(sum(ages) / len(ages))

AnalysisControl.ipynb at commit 37e189e, no license · at the source

Overview

Authors: John P. Kasarda1, Jyotika Bahuguna2, Angela Zhang3, Hua Tong3, Yuan Tan3, Ruizi Wang3, Michael J. Tarr1,4, Timothy Verstynen1,4
ORCID iDs: John P. Kasarda
  1. Department of Psychology, Carnegie Mellon University, Pittsburgh, Pennsylvania, United States of America
  2. Laboratoire de Neurosciences Cognitives et Adaptatives (LNCA), Faculté de Psychologie, Université de Strasbourg, Strasbourg, France
  3. Entertainment Technology Center, Carnegie Mellon University, Pittsburgh, Pennsylvania, United States of America
  4. Neuroscience Institute, Carnegie Mellon University, Pittsburgh, Pennsylvania, United States of America
Institutions: Carnegie Mellon University (United States); Université de Strasbourg (France)
Journal: PloS one, volume 21, issue 10, article e0361502
Dates: received 19 May 2026; accepted 12 October 2026; published online 30 October 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1371/journal.pone.0361502 · PMID 42961977 · PMCID PMC13722190 · OpenAlex W7224843773
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: human (organism), cognitive (subfield)
Methods: Preprocessing, Connectivity, Statistics
MeSH: Feeding Behavior*, User-Computer Interface*, Virtual Reality*, Humans, Learning (* major topic)
Journal subjects: Biology and Life Sciences, Psychology, Behavior, Animal Behavior, Foraging, Social Sciences, Zoology, Neuroscience, Cognitive Science, Cognitive Psychology, Learning, Learning and Memory, Perceptual Learning, Perception, Sensory Perception, Organisms, Eukaryota, Plants, Fruits, Decision Making, Cognition, Human Learning, Physical Sciences, Mathematics, Probability Theory, Probability Distribution
Topic: Neural and Behavioral Psychology Studies (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: Air Force Research Laboratory (FA9550-18-1-0251)
Citations: not cited yet (Europe PMC); 23 references in the paper

Abstract

The past decade has seen a resurgence of interest in the naturalistic behavior of patch foraging in both the neural and cognitive sciences. Patch foraging is observed throughout the animal kingdom and requires the integration of multiple cognitive processes, including value and perceptual learning, spatial estimation, the evaluation of instantaneous return rates, and anticipating future effort. Here, we present a novel virtual environment, BitterBuster, for studying patch foraging in humans. In the BitterBuster game, players navigate a virtual world with four neighborhoods (patches) populated with houses (harvest points) containing inhabitants known as “Oomplets”. The goal is to search for “bitter” Oomplets, characterized by the union of specific body colors and textures. Each neighborhood has a different overall probability of containing bitter Oomplets and, within each, specific house locations predict the relative rate of bitter Oomplets. BitterBuster can be used for solo or team based foraging, where the tasks of exploring and perceptual learning are implemented by two separate players working together. Our results show how both the solo and team version of BitterBuster can accurately measure multiple aspects of naturalistic patch foraging, with participants learning to identify optimal patches, classify harvestable resources, and make rational decisions about when to leave a patch before overharvesting. BitterBuster is well-suited for researchers interested in the contextual, neural, and cooperative dynamics of foraging.

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

Repositories

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

CoAxLab/BitterBusterTIER

License: none: the authors keep all their rights
State: the link answers, verified on 1 November 2026
Evidence: files inventoried
Commit: 37e189eddd719a3325713e82b5e5fb87134e3c28, 26 August 2026
Languages: Jupyter (9), Python (7)
Size: 24 files, 16 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README, 8 notebooks
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: pandas (15 files), NumPy (9 files), SciPy (7 files), Matplotlib (6 files), seaborn (5 files), statsmodels (2 files), NetworkX (1 file), Pillow (1 file), scikit-learn (1 file), statannotations (1 file)
Availability: 1 check, the latest on 1 November 2026: the link answers
  • 1 November 2026: the link answers
17 files

CoAxLab/BitterBusterForagingPaperRelease

License: CC-BY-NC-SA-4.0
State: the link answers, verified on 1 November 2026
Evidence: files inventoried
Commit: e95090abb8147060239c9ac5ad53b2237f790206, 20 June 2024
Size: 2,496 files, 0 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README, license file, documentation
Not found: CITATION.cff, environment file, tests, continuous integration
Availability: 1 check, the latest on 1 November 2026: the link answers
  • 1 November 2026: the link answers
2 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories 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;
  • 1 match between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

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

Data

No dataset and no data link were found in the paper.

Data Availability

The data set and accompanying code is available at GitHub via https://github.com/CoAxLab/BitterBusterTIER. The Unity game code and all assets required to build the BitterBuster game is available on GitHub via https://github.com/CoAxLab/BitterBusterForagingPaperRelease.

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

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 1 November 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 8 authors, 5 MeSH terms, 1 funder, 19 references.

Cite

This paper

Kasarda, J. P., Bahuguna, J., Zhang, A., Tong, H., Tan, Y., Wang, R., Tarr, M. J., & Verstynen, T. (2026). BitterBuster: A virtual world for understanding naturalistic patch foraging. PloS one, 21(10), e0361502. https://doi.org/10.1371/journal.pone.0361502

BibTeX

@article{kasarda2026bitterbuster,
author = {Kasarda, John P. and Bahuguna, Jyotika and Zhang, Angela and Tong, Hua and Tan, Yuan and Wang, Ruizi and Tarr, Michael J. and Verstynen, Timothy},
title = {{BitterBuster: A virtual world for understanding naturalistic patch foraging}},
journal = {PloS one},
year = {2026},
month = oct,
volume = {21},
number = {10},
pages = {e0361502},
publisher = {PLOS},
issn = {1932-6203},
doi = {10.1371/journal.pone.0361502},
url = {https://doi.org/10.1371/journal.pone.0361502},
pmid = {42961977},
pmcid = {PMC13722190}
}

RIS

TY - JOUR
AU - Kasarda, John P.
AU - Bahuguna, Jyotika
AU - Zhang, Angela
AU - Tong, Hua
AU - Tan, Yuan
AU - Wang, Ruizi
AU - Tarr, Michael J.
AU - Verstynen, Timothy
TI - BitterBuster: A virtual world for understanding naturalistic patch foraging
T2 - PloS one
J2 - PLoS One
PY - 2026
DA - 2026/10/30
VL - 21
IS - 10
SP - e0361502
SN - 1932-6203
PB - PLOS
DO - 10.1371/journal.pone.0361502
UR - https://doi.org/10.1371/journal.pone.0361502
LA - en
ER -

CSL-JSON

{
"id": "10.1371/journal.pone.0361502",
"type": "article-journal",
"title": "BitterBuster: A virtual world for understanding naturalistic patch foraging",
"container-title": "PloS one",
"author": [
{
"family": "Kasarda",
"given": "John P."
},
{
"family": "Bahuguna",
"given": "Jyotika"
},
{
"family": "Zhang",
"given": "Angela"
},
{
"family": "Tong",
"given": "Hua"
},
{
"family": "Tan",
"given": "Yuan"
},
{
"family": "Wang",
"given": "Ruizi"
},
{
"family": "Tarr",
"given": "Michael J."
},
{
"family": "Verstynen",
"given": "Timothy"
}
],
"container-title-short": "PLoS One",
"volume": "21",
"issue": "10",
"page": "e0361502",
"DOI": "10.1371/journal.pone.0361502",
"PMID": "42961977",
"PMCID": "PMC13722190",
"ISSN": "1932-6203",
"publisher": "PLOS",
"URL": "https://doi.org/10.1371/journal.pone.0361502",
"language": "en",
"issued": {
"date-parts": [
[
2026,
10,
30
]
]
}
}

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.1038/s41467-026-68711-x [code]
Neural and computational mechanisms underlying one-shot perceptual learning in humans.
Journal: Nature communications
In common: statannotations, NetworkX, Pillow, 7 other tools, cognitive
[2] doi:10.1016/j.isci.2026.115488 [code]
An integrated &lt;i&gt;i&lt;/i&gt; &lt;i&gt;n vitro&lt;/i&gt; platform and biophysical modeling approach for studying synaptic transmission in isolated neuronal pairs.
Journal: iScience
In common: statannotations, NetworkX, Pillow, 7 other tools
[3] doi:10.1038/s41586-025-09520-y [code]
ABCA7 variants impact phosphatidylcholine and mitochondria in neurons.
Journal: Nature
In common: statannotations, NetworkX, Pillow, 7 other tools
[4] doi:10.1093/schizbullopen/sgae010 [code]
Cortical Network Disruption Is Minimal in Early Stages of Psychosis.
Journal: Schizophrenia bulletin open
In common: statannotations, NetworkX, Pillow, 7 other tools
[5] doi:10.1038/s41598-023-40683-8 [code]
Cross-species comparative analysis of single presynapses.
Journal: Scientific reports
In common: statannotations, NetworkX, Pillow, 7 other tools
[6] doi:10.1371/journal.pcbi.1012629 [code]
Image-based force inference by biomechanical simulation.
Journal: PLoS computational biology
In common: statannotations, NetworkX, Pillow, 7 other tools
[7] doi:10.1371/journal.pcbi.1012989 [code]
Foraging animals use dynamic Bayesian updating to model meta-uncertainty in environment representations.
Journal: PLoS computational biology
In common: NetworkX, seaborn, pandas, 3 other tools, 3 references
[8] doi:10.1038/s42003-024-06858-3 [code]
Dynamical structure-function correlations provide robust and generalizable signatures of consciousness in humans.
Journal: Communications biology
In common: statannotations, NetworkX, statsmodels, 6 other tools, cognitive
[9] doi:10.7554/elife.101688 [code]
Transcranial direct current stimulation modulates primate brain dynamics across states of consciousness.
Journal: eLife
In common: statannotations, NetworkX, statsmodels, 6 other tools, cognitive
[10] doi:10.3389/fnagi.2025.1550673 [code]
Disrupted calcium dynamics and electrophysiological activity in the stratum pyramidale and hippocampal alveus during fear conditioning in the 5xFAD model of Alzheimer's disease.
Journal: Frontiers in aging neuroscience
In common: statannotations, NetworkX, statsmodels, 6 other tools, cognitive

Contribute

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

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

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1371/journal.pone.0361502.svg)](https://openscicode.org/badge/doi/10.1371/journal.pone.0361502)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1371/journal.pone.0361502.svg
   :target: https://openscicode.org/badge/doi/10.1371/journal.pone.0361502
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1371/journal.pone.0361502"><img src="https://openscicode.org/badge/doi/10.1371/journal.pone.0361502.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

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

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

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

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