Skip to content

Decision Making, Agency and Social Cognition

Cognition does not stop at understanding the world. Minds exist to choose actions under uncertainty, balance habit against planning, monitor their own reliability, and coordinate with other agents, which we explore here through Prospect Theory, the Drift-Diffusion Model, exploration strategies, the Successor Representation, metacognition, Theory of Mind, pragmatic language, and cumulative culture.

From Expected Utility to Prospect Theory

  • Imagine someone offers you a simple choice. You can take £500 for certain, or flip a fair coin for £1,000 or nothing. Most people happily pocket the guaranteed £500. Now flip the signs. Would you rather lose £500 for certain, or flip a fair coin to lose £1,000 or lose nothing? Suddenly, the vast majority of people choose to gamble, desperately hoping to escape the loss! Yet in both problems the expected monetary payout is identical.

  • Classical economics modelled rational choice through Expected Utility Theory (John von Neumann and Oskar Morgenstern). Facing a gamble over outcomes \(\{x_i\}\) with probabilities \(\{p_i\}\), a rational decision-maker evaluates total wealth through a utility function \(u(x)\) and picks the option maximising expected utility.

\[\text{EU} = \sum_{i} p_i \, u(x_i)\]
  • A concave utility curve such as \(u(x) = \log(x)\) captures diminishing marginal utility (an extra £100 means far more to a student than to a billionaire) and neatly explains risk aversion for gains. Yet Expected Utility runs into brick walls against real human behaviour. It cannot easily explain why people flip from risk-averse on gains to risk-seeking on losses, why reframing "£10 discount" vs "£10 surcharge" changes choices, or why the very same person buys both lottery tickets (risk-seeking) and home insurance (risk-averse) on the same afternoon.

Kahneman and Tversky's Prospect Theory

  • Daniel Kahneman and Amos Tversky resolved these paradoxes with Prospect Theory, resting on three empirically grounded pillars.

  • Reference dependence reflects the fact that brains are change detectors rather than absolute wealth meters. We evaluate outcomes as gains or losses \(\Delta x\) relative to a neutral reference point (usually our current state or expectation), rather than final total wealth.

  • The S-shaped value function and loss aversion make subjective value \(v(\Delta x)\) concave for gains (producing risk aversion) and convex for losses (producing risk seeking). Crucially, the curve plunges much more steeply on the loss side than it rises on the gain side. As Kahneman and Tversky put it, "losses loom larger than gains", meaning losing £100 stings roughly twice as hard as winning £100 delights us.
\[v(\Delta x) = \begin{cases} (\Delta x)^{\alpha} & \text{if } \Delta x \ge 0 \\[4pt] -\lambda\,(-\Delta x)^{\beta} & \text{if } \Delta x < 0 \end{cases}\]
  • Here \(\alpha, \beta \in (0, 1)\) govern diminishing sensitivity as changes grow larger (empirically \(\alpha \approx \beta \approx 0.88\)), and \(\lambda > 1\) is the loss aversion coefficient (typically \(\lambda \approx 2.25\) in human studies).

  • Nonlinear probability weighting captures the fact that humans do not weight outcomes linearly by objective probability \(p\). Instead, a distorted weighting function \(w(p)\) overweights tiny probabilities (making a 1-in-a-million lottery jackpot feel tantalising and a tiny risk of a house fire feel terrifying) while underweighting moderate-to-high probabilities, especially the steep cliff between \(99\%\) and \(100\%\) certainty (the certainty effect).

\[w(p) = \frac{p^{\gamma}}{\left(p^{\gamma} + (1 - p)^{\gamma}\right)^{1/\gamma}} \qquad (\gamma \approx 0.65)\]
  • Putting both distortions together gives the Prospect Theory subjective value \(V = \sum_i w(p_i)\,v(\Delta x_i)\). In reinforcement learning (Chapter 06), this mirrors risk-sensitive RL and reward shaping, where transforming raw rewards or distorting tail probabilities dramatically changes whether an artificial agent plays cautiously or aggressively.

The Drift-Diffusion Model and Decisions in Time

  • Prospect Theory predicts what people choose, but picture standing in front of a café menu torn between a familiar flat white and an intriguing matcha latte, or watching a cloud of flickering dots and deciding whether they drift left or right. Decisions do not happen instantaneously. Noisy evidence trickles into your brain millisecond by millisecond until your internal tally tips over a commitment threshold.

  • Roger Ratcliff's Drift-Diffusion Model (DDM) captures this continuous evidence accumulation using a classic stochastic differential equation (Brownian motion with drift, extending random walks from Chapter 05).

\[dx = v\,dt + \sigma\,dW, \qquad x(0) = z\]
  • Every symbol has a crisp physical and cognitive meaning.
  • The accumulated decision variable \(x(t)\) tracks net log-likelihood evidence favouring Option A over Option B.
  • The drift rate \(v\) sets the average speed of evidence accumulation, proportional to signal clarity in perception or subjective value difference \(V_A - V_B\) in value-based choice.
  • The parameter \(\sigma\) scales the diffusion noise, and \(dW \sim \mathcal{N}(0, dt)\) is a Gaussian Wiener increment representing moment-to-moment sensory or neural randomness.
  • The starting point \(z \in (-a, +a)\) encodes any prior bias before evidence arrives.
  • The upper and lower decision boundaries \(+a\) and \(-a\) act as commitment thresholds. The moment \(x(t)\) hits \(+a\), the agent commits to Option A, and if it hits \(-a\), it commits to Option B. Total reaction time equals the boundary crossing time plus a fixed non-decision time \(T_{\text{er}}\) for sensory encoding and motor execution.

  • The DDM immediately explains the speed-accuracy tradeoff. Widen the boundaries \(\pm a\) and noisy fluctuations average out, delivering high accuracy at the cost of slower decisions. Squeeze \(\pm a\) inward and you react fast, at the price of impulsive noise-driven errors. Remarkably, it reproduces the exact positively skewed reaction-time distributions seen in humans and matches single-neuron firing-rate ramps recorded in primate parietal cortex. Mathematically, it is also the continuous-time limit of Wald's Sequential Probability Ratio Test (SPRT), the Bayes-optimal stopping rule for stationary binary evidence!

Prospect Theory S-shaped value function showing loss aversion on the left, and Drift-Diffusion Model noisy evidence trajectories crossing upper and lower bounds on the right

Exploration vs Exploitation in Minds and Machines

  • Picture moving to a new neighbourhood and deciding where to eat dinner tonight. On your first night you stumbled upon a cosy noodle shop that was genuinely delicious. Tonight, do you return to the sure thing (exploit) or gamble on the unfamiliar bistro across the street that might be terrible, or might become your new favourite (explore)?

  • Cognitive science and reinforcement learning (Chapter 06) both study this dilemma through multi-armed bandits, where an agent faces \(K\) actions with unknown reward distributions. Unlike naive \(\epsilon\)-greedy exploration (which wastes effort on clearly awful options), both optimal algorithms and human brains deploy two smarter mechanisms.

  • Directed (uncertainty-driven) exploration deliberately seeks out options you know least about by adding an optimism bonus proportional to epistemic uncertainty. In the Upper Confidence Bound (UCB) algorithm, the agent picks the arm maximising mean estimate plus uncertainty bonus.

\[a_t = \arg\max_{a} \left[ \hat{\mu}_t(a) + c \sqrt{\frac{\ln t}{N_t(a)}} \right]\]
  • Here \(\hat{\mu}_t(a)\) is the current mean reward estimate for arm \(a\), \(N_t(a)\) is the number of times arm \(a\) has been tried up to step \(t\), and \(c > 0\) controls curiosity. In Bayesian Kalman-filter models of human learning, the bonus takes the form \(\hat{\mu}_t(a) + \beta\,\sigma_t(a)\), where \(\sigma_t(a)\) is posterior standard deviation. Crucially, human experiments (Robert Wilson and Samuel Gershman) show that people dial up this uncertainty bonus when the time horizon is long (plenty of future dinners left to enjoy what you discover!) and turn it down on their very last night in town.

  • Random (stochastic) exploration injects calibrated randomness into action selection. While softmax (Boltzmann) exploration samples with \(P(a) \propto \exp(\beta \, \hat{\mu}_t(a))\), the Bayesian gold standard is Thompson Sampling (probability matching). You maintain a posterior belief \(P(\theta_a \mid \mathcal{D}_t)\) over each arm's true reward (Chapter 05), draw one sample \(\tilde{\theta}_a \sim P(\theta_a \mid \mathcal{D}_t)\) per arm, and pick \(\arg\max_a \tilde{\theta}_a\). Each arm is then chosen with exact probability equal to the chance that it is truly the best! Empirical work reveals that human learners actually blend both directed uncertainty bonuses and Thompson-like random exploration.

Model-Free, Model-Based and the Successor Representation

  • Imagine driving on a Saturday morning to visit a friend, only to realise mid-journey that your hands have steered you halfway toward your workplace on pure autopilot. That reflex is model-free control. Now imagine hearing on the radio that the main bridge is closed and smoothly sketching a back-road detour through side streets in your head. That flexible lookahead is model-based control.

  • Recall the reinforcement learning distinction from Chapter 06.

  • Model-free control caches scalar action values \(Q_{\text{MF}}(s, a)\) directly from past reward prediction errors (TD errors, closely mirrored by midbrain dopamine bursts). At decision time it is lightning fast (\(O(1)\) lookup), yet brittle. If the goal or reward suddenly shifts (outcome devaluation), cached habits blindly repeat outdated actions until painfully retrained through trial and error.
  • Model-based control learns an explicit transition model \(T(s' \mid s, a)\) and reward map \(R(s)\), then plans forward via Bellman backups or tree search. It adapts instantly when goals or roadblocks change, but burns heavy working memory and serial computation at every choice.

Daw's Two-Step Task

  • How do scientists measure whether a human is relying on habit or planning? Nathaniel Daw and colleagues invented the landmark two-step task. In Stage 1, you pick Rocket A or Rocket B. Rocket A flies commonly (\(70\%\)) to the Red Planet and rarely (\(30\%\)) to the Blue Planet, while Rocket B does the reverse. On the destination planet (Stage 2), you choose an alien who yields a slowly drifting reward.

  • Now trace what happens after a rare transition, where you picked Rocket A, unexpectedly landed on the Blue Planet, and won a jackpot.

  • A model-free learner simply notes "Rocket A led to reward!" and becomes more likely to pick Rocket A again.
  • A model-based learner knows the transition structure ("Blue Planet is hot right now, and Rocket B gets me there \(70\%\) of the time!"), so it switches to Rocket B!

  • Humans display a hybrid signature \(Q_{\text{net}} = w\,Q_{\text{MB}} + (1 - w)\,Q_{\text{MF}}\), smoothly arbitrating between the two systems and shifting down toward cheaper model-free habits under acute stress, fatigue, or heavy cognitive load.

The Successor Representation Bridge

  • Must a mind choose between fast-but-rigid habits and flexible-but-slow tree search? Peter Dayan proposed, and Samuel Gershman and Kimberly Stachenfeld later revived in cognitive neuroscience, an extraordinarily elegant third way called the Successor Representation (SR).

  • Picture a city map that does not just record which roads touch which, nor merely store how tasty each street corner was last Tuesday, but instead stores a predictive occupancy table \(M(s, s')\). Starting from location \(s\) under your current habits \(\pi\), \(M(s, s')\) counts how many discounted times you expect to visit every future location \(s'\).

\[M(s, s') = \mathbb{E}_{\pi} \!\left[ \sum_{t=0}^{\infty} \gamma^t \, \mathbb{I}(s_t = s') \;\middle|\; s_0 = s \right]\]
  • Written in matrix form with the one-step policy transition matrix \(\mathbf{T}\) (where \(T_{ij} = P^\pi(s_{t+1} = j \mid s_t = i)\)) and discount factor \(\gamma \in [0, 1)\), the Neumann geometric series (Chapter 02) collapses into one crisp closed-form matrix inverse.
\[\mathbf{M} = \mathbf{I} + \gamma \mathbf{T} + \gamma^2 \mathbf{T}^2 + \cdots = (\mathbf{I} - \gamma \mathbf{T})^{-1}\]
  • Now watch the magic. Because expected return simply sums future visits weighted by each state's reward \(r(s')\), the entire state-value vector \(\mathbf{v}\) is just a single matrix-vector dot product (Chapter 01 and Chapter 02).
\[\mathbf{v} = \mathbf{M}\mathbf{r}\]
  • Look at what this achieves! If rewards change overnight (your favourite café closes and a new one opens across town, known as reward revaluation), you update the vector \(\mathbf{r}\) and recompute \(\mathbf{v} = \mathbf{M}\mathbf{r}\) in one instant linear pass, achieving model-based flexibility at model-free speed. On the other hand, if transitions change (a bridge collapses, known as transition revaluation), \(\mathbf{M}\) cannot be updated instantaneously without re-experiencing paths or replaying trajectories via TD updates. Strikingly, human behavioural experiments show people adapt far faster to reward revaluation than to transition revaluation, and place-cell firing fields in the hippocampus distort around barriers in exact agreement with the Successor Representation!

Model-free habits, Successor Representation predictive map M = (I - gamma T)^-1, and Model-based forward planning

Metacognition and Confidence Calibration

  • Think of the difference between immediately knowing the capital of Japan ("Tokyo, 100% sure"), instantly knowing you do not know the 14th-century mayor of York ("no clue, 0% sure"), and pausing on a tricky maths step with a nagging feeling that you dropped a minus sign. That ability to monitor, evaluate, and regulate your own cognitive processes is metacognition, literally thinking about thinking.

  • How do we measure whether a human expert or a deployed AI model truly knows what it knows? We measure confidence calibration. If an agent reports \(80\%\) confidence across a hundred predictions, it should be right roughly \(80\%\) of the time. Plotting empirical accuracy against predicted confidence bins produces a reliability (calibration) curve, where perfect calibration hugs the diagonal line \(y = x\), curves below the diagonal expose overconfidence, and curves above expose underconfidence.

  • To score probabilistic forecasts rigorously, we use strictly proper scoring rules, loss functions minimised only when you report your honest true belief. The classic metric is the Brier Score, the mean squared error between stated probability \(p_i \in [0, 1]\) and binary outcome \(y_i \in \{0, 1\}\) (sitting alongside log-loss and cross-entropy from Chapter 05 and Chapter 06).

\[\text{BS} = \frac{1}{N} \sum_{i=1}^{N} \left(p_i - y_i\right)^2\]
  • A perfectly confident, perfectly accurate oracle scores \(\text{BS} = 0\), always hedging at \(0.5\) scores \(0.25\), and being \(100\%\) confident while wrong earns the brutal penalty of \(1.0\). Alongside Brier score and Expected Calibration Error (ECE), cognitive scientists distinguish calibration (overall alignment of confidence with accuracy) from metacognitive sensitivity (how sharply your confidence separates your own right answers from your own mistakes). For AI safety, metacognition is vital, because modern LLMs post-trained with RLHF (Chapter 06 and Chapter 07) often grow systematically overconfident, hallucinating with authoritative polish instead of abstaining when uncertainty spikes.

Social Cognition, Theory of Mind and Cultural Intelligence

  • Picture watching a colleague stride briskly down the corridor carrying an empty ceramic mug toward the break room. Without ever seeing inside their skull, you instantly infer two hidden mental states. You recognise a desire (they want coffee) and a belief (they think fresh coffee is waiting in the break room). Even more subtly, if you happen to know the coffee machine just broke, you predict they are about to walk in and look disappointed!

  • This capacity to attribute unseen beliefs, desires, intentions, and perspectives to other agents is Theory of Mind (ToM). Its developmental milestone is false-belief reasoning, tested by the classic Sally-Anne task. Sally places her marble in a basket and leaves the room, and while she is gone, Anne moves the marble into a box. Where will Sally look when she returns? Three-year-olds often point to the box (where the marble really is), whereas by age four or five children effortlessly point to the basket, separating Sally's internal belief from objective reality.

Bayesian Theory of Mind and Inverse Planning

  • How can we formalise mind-reading mathematically? Chris Baker, Rebecca Saxe, and Joshua Tenenbaum modelled Bayesian Theory of Mind (BToM) as inverse planning, literally running a rational planning model backwards via Bayes' rule (Chapter 05)!

  • Suppose an agent with hidden goal \(g\) and belief \(b\) chooses actions approximately rationally according to a softmax (Boltzmann-rational) policy over expected action values \(Q(s, a; b, g)\).

\[P(a_t \mid s_t, g, b) = \frac{\exp\!\left(\beta \, Q(s_t, a_t; b, g)\right)}{\sum_{a'} \exp\!\left(\beta \, Q(s_t, a'; b, g)\right)}\]
  • Here \(\beta > 0\) measures how rational (efficient) the agent is expected to be. Observing a trajectory of actions \(a_{1:t}\), a social observer simply inverts this forward model using Bayes' theorem to infer what the other mind wants and believes.
\[P(g, b \mid a_{1:t}) \propto P(g, b) \prod_{\tau=1}^{t} P(a_\tau \mid s_\tau, g, b)\]
  • Look how directly this connects cognitive science to AI alignment. Inverse Reinforcement Learning (IRL) (Chapter 06) is the exact engineering twin of Bayesian inverse planning, inferring a human's latent reward function from their behaviour rather than hand-coding brittle objectives!

Rational Speech Acts and Pragmatic Mind-Reading

  • Now bring Theory of Mind straight back to language and pragmatics (Chapter 07). Imagine a teacher saying "Some of the students passed the exam." Strictly speaking, in formal logic, if all students passed, then "some passed" is still literally true! Yet every human listener immediately infers "not all of them passed" (a scalar implicature). Why?

  • Michael Frank and Noah Goodman's Rational Speech Acts (RSA) framework models human communication as recursive Bayesian reasoning between cooperative minds in three clean levels.

  • A literal listener (\(L_0\)) takes words strictly at face value, restricting the prior \(P(w)\) to world states \(w\) where utterance \(u\) is literally true (\(\llbracket u \rrbracket(w) = 1\)).

\[P_{L_0}(w \mid u) \propto \mathbb{I}\!\left(\llbracket u \rrbracket(w) = 1\right) P(w)\]
  1. A pragmatic speaker (\(S_1\)) wants a literal listener to infer the true world \(w\), trading off informativeness (\(\log P_{L_0}(w \mid u)\)) against utterance effort cost \(C(u)\).
\[P_{S_1}(u \mid w) \propto \exp\!\Big(\alpha \big[\log P_{L_0}(w \mid u) - C(u)\big]\Big)\]
  1. A pragmatic listener (\(L_1\)) applies Bayes' rule over the speaker's choice to recover the intended world.
\[P_{L_1}(w \mid u) \propto P_{S_1}(u \mid w)\,P(w)\]
  • Trace the chain of thought! If all students had passed, a helpful speaker \(S_1\) would strongly prefer saying "all", since "all" pinpoints the exact state with maximum \(\log P_{L_0}\). Because the speaker chose "some" instead, the pragmatic listener \(L_1\) immediately down-weights the "all passed" world, deriving Gricean pragmatics (Chapter 07) from pure Bayesian Theory of Mind!

Cumulative Cultural Learning and Social Intelligence

  • Ask yourself one final question to zoom out across all of Chapter 11. If you were dropped alone on a deserted island with zero tools, how long would it take you to invent a telescope, refine silicon wafers, or derive backpropagation? Even the sharpest human brain alive could never do it in a single lifetime.

  • Anthropologists and cognitive scientists (Michael Tomasello and Joseph Henrich) call the real secret of human intelligence the cultural ratchet, or cumulative cultural evolution. Through high-fidelity imitation, shared attention, pedagogy, and compositional language, each generation preserves hard-won discoveries (the "ratchet" prevents slippage backward) and adds incremental innovations on top. No lone genius built calculus, medicine, or deep learning. Human intelligence is fundamentally social, distributed, and cumulative, a profound lesson as AI moves from solitary models toward multi-agent systems and human-AI collaboration.

Take-Home

  • Subjective value is reference-dependent and asymmetric. Prospect Theory replaces linear Expected Utility with an S-shaped value curve (with loss aversion \(\lambda \approx 2.25\)) and nonlinear probability weights that overweight rare events.
  • Decisions unfold in time as noisy evidence accumulation. The Drift-Diffusion Model (\(dx = v\,dt + \sigma\,dW\)) unifies accuracy, skewed reaction times, and the speed-accuracy tradeoff through adjustable decision thresholds \(\pm a\).
  • Smart exploration balances curiosity and probability matching. Both human brains and optimal bandit algorithms look beyond blind randomness by combining directed uncertainty bonuses (UCB) with posterior sampling (Thompson sampling).
  • The Successor Representation bridges fast habits and flexible planning. Caching discounted future occupancy \(\mathbf{M} = (\mathbf{I} - \gamma \mathbf{T})^{-1}\) lets an agent revalue states instantaneously via \(\mathbf{v} = \mathbf{M}\mathbf{r}\) without running expensive tree search.
  • Metacognition and Theory of Mind turn solitary learners into social partners. Proper scoring rules like the Brier score enforce honest uncertainty, while Bayesian inverse planning and Rational Speech Acts explain how minds read intentions, decode pragmatic language, and build cumulative culture.

Coding Tasks (use CoLab or notebook)

  1. Plot Prospect Theory curves and a Drift-Diffusion Model (DDM) side by side, showing Kahneman and Tversky's S-shaped value function alongside simulated DDM evidence trajectories and reaction-time distributions for a low threshold (fast and impulsive) versus a high threshold (slow and accurate).

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # --- Part 1: Prospect Theory Value Function ---
    dx = jnp.linspace(-100.0, 100.0, 400)
    alpha, beta, lam = 0.88, 0.88, 2.25
    v_pt = jnp.where(dx >= 0, jnp.power(jnp.maximum(dx, 0.0), alpha),
                     -lam * jnp.power(jnp.maximum(-dx, 0.0), beta))
    
    # --- Part 2: Drift-Diffusion Model Simulation ---
    def simulate_ddm(key, drift=0.6, sigma=1.0, bound=1.2, dt=0.01, max_steps=600, n_trials=600):
        noise = jax.random.normal(key, (n_trials, max_steps)) * (sigma * jnp.sqrt(dt))
        increments = drift * dt + noise
        paths = jnp.cumsum(increments, axis=1)  # start at z = 0
    
        hit_upper = paths >= bound
        hit_lower = paths <= -bound
        hit_any = hit_upper | hit_lower
    
        # First crossing index (default to max_steps - 1 if uncrossed)
        has_hit = jnp.any(hit_any, axis=1)
        first_idx = jnp.where(has_hit, jnp.argmax(hit_any, axis=1), max_steps - 1)
        rt = (first_idx + 1) * dt
    
        # Value at crossing index via one-hot dot product
        one_hot = (jnp.arange(max_steps)[None, :] == first_idx[:, None]).astype(jnp.float32)
        final_val = jnp.sum(paths * one_hot, axis=1)
        correct = final_val >= 0.0
        return paths, rt, correct, first_idx
    
    key = jax.random.PRNGKey(12)
    k1, k2 = jax.random.split(key)
    paths_fast, rt_fast, acc_fast, idx_fast = simulate_ddm(k1, bound=0.7)
    paths_slow, rt_slow, acc_slow, idx_slow = simulate_ddm(k2, bound=1.6)
    
    print(f"Low bound (a=0.7):  Accuracy={float(jnp.mean(acc_fast)):.1%}, Mean RT={float(jnp.mean(rt_fast)):.2f}s")
    print(f"High bound (a=1.6): Accuracy={float(jnp.mean(acc_slow)):.1%}, Mean RT={float(jnp.mean(rt_slow)):.2f}s")
    
    fig, axes = plt.subplots(1, 3, figsize=(14, 4))
    axes[0].plot(dx, v_pt, color="#3498db", linewidth=2.2)
    axes[0].axhline(0, color="#666", linewidth=0.8); axes[0].axvline(0, color="#666", linewidth=0.8)
    axes[0].set_title("Prospect Theory Value Function")
    axes[0].set_xlabel("Outcome Change (Δx)"); axes[0].set_ylabel("Subjective Value v(Δx)")
    axes[0].grid(alpha=0.3)
    
    t_axis = jnp.arange(1, 601) * 0.01
    for i in range(6):
        end = int(idx_slow[i]) + 1
        col = "#27ae60" if bool(acc_slow[i]) else "#e74c3c"
        axes[1].plot(t_axis[:end], paths_slow[i, :end], color=col, alpha=0.8, linewidth=1.4)
    axes[1].axhline(1.6, color="#27ae60", linestyle="--", label="+a (correct)")
    axes[1].axhline(-1.6, color="#e74c3c", linestyle="--", label="-a (error)")
    axes[1].set_title("Sample DDM Trajectories (a=1.6)")
    axes[1].set_xlabel("Time (s)"); axes[1].set_ylabel("Evidence x(t)")
    axes[1].legend(fontsize=8); axes[1].grid(alpha=0.3)
    
    axes[2].hist(rt_fast, bins=25, alpha=0.6, color="#e74c3c", label=f"Fast (a=0.7, acc={float(jnp.mean(acc_fast)):.0%})")
    axes[2].hist(rt_slow, bins=25, alpha=0.6, color="#3498db", label=f"Accurate (a=1.6, acc={float(jnp.mean(acc_slow)):.0%})")
    axes[2].set_title("Speed-Accuracy Tradeoff (RT Distributions)")
    axes[2].set_xlabel("Reaction Time (s)"); axes[2].set_ylabel("Count")
    axes[2].legend(fontsize=8); axes[2].grid(alpha=0.3)
    
    plt.tight_layout(); plt.show()
    

  2. Compare the Successor Representation against Model-Free TD under sudden reward revaluation on a two-branch corridor MDP (6 states with two parallel tracks \(0 \to 2 \to 4\) and \(1 \to 3 \to 5\)). Initially state 4 gives reward \(+10\) and state 5 gives \(0\), and halfway through the rewards suddenly flip (\(r_4 = 0, r_5 = +10\)). Plot how instantaneously \(\mathbf{v} = \mathbf{M}\mathbf{r}\) revalues states \(0\) and \(1\) compared to a model-free TD(0) learner.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # 6 states: Track A is 0 -> 2 -> 4 (absorbing); Track B is 1 -> 3 -> 5 (absorbing)
    gamma = 0.9
    T = jnp.array([
        [0.0, 0.0, 1.0, 0.0, 0.0, 0.0],  # state 0 -> 2
        [0.0, 0.0, 0.0, 1.0, 0.0, 0.0],  # state 1 -> 3
        [0.0, 0.0, 0.0, 0.0, 1.0, 0.0],  # state 2 -> 4
        [0.0, 0.0, 0.0, 0.0, 0.0, 1.0],  # state 3 -> 5
        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],  # terminal 4
        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],  # terminal 5
    ])
    
    # Closed-form Successor Representation M = (I - gamma T)^(-1)
    M = jnp.linalg.inv(jnp.eye(6) - gamma * T)
    
    r_before = jnp.array([0.0, 0.0, 0.0, 0.0, 10.0, 0.0])
    r_after  = jnp.array([0.0, 0.0, 0.0, 0.0,  0.0, 10.0])
    
    # SR values before and immediately after reward revaluation (only observing terminal states 4 & 5!)
    v_sr_before = jnp.dot(M, r_before)
    v_sr_after  = jnp.dot(M, r_after)
    print(f"SR before swap: V(s0)={float(v_sr_before[0]):.2f}, V(s1)={float(v_sr_before[1]):.2f}")
    print(f"SR AFTER swap:  V(s0)={float(v_sr_after[0]):.2f}, V(s1)={float(v_sr_after[1]):.2f} (instant!)")
    
    # Simulate model-free TD(0) adapting after the swap over 35 episodes of each track
    v_mf = list(float(x) for x in v_sr_before)  # start fully converged to pre-swap values
    alpha_td = 0.25
    mf_s0_hist, mf_s1_hist = [v_mf[0]], [v_mf[1]]
    sr_s0_hist, sr_s1_hist = [float(v_sr_before[0])], [float(v_sr_before[1])]
    
    episodes = 35
    for ep in range(episodes):
        # Track A: 0 -> 2 -> 4 (new reward 0)
        v_mf[0] += alpha_td * (0.0 + gamma * v_mf[2] - v_mf[0])
        v_mf[2] += alpha_td * (0.0 + gamma * v_mf[4] - v_mf[2])
        v_mf[4] += alpha_td * (0.0 - v_mf[4])
        # Track B: 1 -> 3 -> 5 (new reward 10)
        v_mf[1] += alpha_td * (0.0 + gamma * v_mf[3] - v_mf[1])
        v_mf[3] += alpha_td * (0.0 + gamma * v_mf[5] - v_mf[3])
        v_mf[5] += alpha_td * (10.0 - v_mf[5])
    
        mf_s0_hist.append(v_mf[0]); mf_s1_hist.append(v_mf[1])
        sr_s0_hist.append(float(v_sr_after[0])); sr_s1_hist.append(float(v_sr_after[1]))
    
    plt.figure(figsize=(9, 4.5))
    plt.plot(sr_s1_hist, color="#9b59b6", linewidth=2.4, label="SR: V(Start B) (instant revaluation)")
    plt.plot(mf_s1_hist, "--", color="#27ae60", linewidth=2.0, label="Model-Free TD: V(Start B) (slow climb)")
    plt.plot(sr_s0_hist, color="#3498db", linewidth=2.0, alpha=0.8, label="SR: V(Start A) (instant drop)")
    plt.plot(mf_s0_hist, "--", color="#e74c3c", linewidth=2.0, label="Model-Free TD: V(Start A) (slow decay)")
    plt.xlabel("Episodes After Reward Swap")
    plt.ylabel("Estimated Start-State Value")
    plt.title("Reward Revaluation: Successor Representation vs Model-Free TD")
    plt.grid(alpha=0.3); plt.legend(fontsize=8.5); plt.tight_layout(); plt.show()
    

  3. Implement Rational Speech Acts (RSA) and Bayesian Inverse Planning together. First, run the recursive RSA model (\(L_0 \to S_1 \to L_1\)) for scalar implicature ("some" vs "all" when 0, 1, 2, or 3 apples were eaten) and verify that \(L_1\) infers "some but not all". Second, build a 2D Bayesian inverse-planning observer that infers which of two goals a moving agent intends as each step arrives.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # --- Part 1: Rational Speech Acts (Scalar Implicature) ---
    # Worlds: 0, 1, 2, or 3 apples eaten. Utterances: "none", "some" (>=1), "all" (==3)
    prior_w = jnp.array([0.25, 0.25, 0.25, 0.25])
    # Literal truth matrix M[u, w] = 1 if utterance u is literally true in world w
    truth = jnp.array([
        [1.0, 0.0, 0.0, 0.0],  # "none"
        [0.0, 1.0, 1.0, 1.0],  # "some" (literally true even if all 3!)
        [0.0, 0.0, 0.0, 1.0],  # "all"
    ])
    
    # Literal listener L0(w | u)
    L0 = truth * prior_w[None, :]
    L0 = L0 / jnp.sum(L0, axis=1, keepdims=True)
    
    # Pragmatic speaker S1(u | w) proportional to exp(alpha * log L0(w | u))
    alpha_rsa = 3.0
    log_L0 = jnp.where(L0 > 0, jnp.log(jnp.maximum(L0, 1e-12)), -1e9)
    S1_logits = alpha_rsa * log_L0  # shape (U, W)
    S1 = jnp.exp(S1_logits - jnp.max(S1_logits, axis=0, keepdims=True))
    S1 = S1 / jnp.sum(S1, axis=0, keepdims=True)
    
    # Pragmatic listener L1(w | u) proportional to S1(u | w) * P(w)
    L1 = S1 * prior_w[None, :]
    L1 = L1 / jnp.sum(L1, axis=1, keepdims=True)
    
    print("Hearing 'some' -> Literal L0(0,1,2,3):", [round(float(x), 3) for x in L0[1]])
    print("Hearing 'some' -> Pragmatic L1(0,1,2,3):", [round(float(x), 3) for x in L1[1]])
    
    # --- Part 2: Bayesian Inverse Planning (2D Goal Inference) ---
    goal_A = jnp.array([5.0, 4.0])
    goal_B = jnp.array([5.0, -4.0])
    goals = jnp.stack([goal_A, goal_B])  # (2, 2)
    actions = jnp.array([[1.0, 0.0], [0.0, 1.0], [0.0, -1.0], [-1.0, 0.0]])  # E, N, S, W
    
    # Observed trajectory heading East first (ambiguous!), then curving North toward Goal A
    traj_states = [jnp.array([0.0, 0.0]), jnp.array([1.0, 0.0]), jnp.array([2.0, 0.0]),
                   jnp.array([2.0, 1.0]), jnp.array([3.0, 1.0]), jnp.array([3.0, 2.0])]
    traj_actions = [0, 0, 1, 0, 1]  # E, E, N, E, N
    
    beta_inv = 2.0
    log_post_g = jnp.log(jnp.array([0.5, 0.5]))
    prob_A_hist = [0.5]
    
    for s, a_idx in zip(traj_states[:-1], traj_actions):
        # Q(s, a; g) = -distance to goal after taking action a
        next_states = s[None, :] + actions  # (4, 2)
        # Distance from each next state (4, 1, 2) to each goal (1, 2, 2)
        dists = jnp.linalg.norm(next_states[:, None, :] - goals[None, :, :], axis=-1)  # (4, 2)
        q_vals = -dists
        # Softmax policy P(a | s, g) over the 4 actions for each goal
        logits = beta_inv * q_vals
        log_pi = logits - jnp.log(jnp.sum(jnp.exp(logits), axis=0, keepdims=True))
        log_post_g = log_post_g + log_pi[a_idx]
        post_g = jnp.exp(log_post_g - jnp.max(log_post_g))
        post_g = post_g / jnp.sum(post_g)
        prob_A_hist.append(float(post_g[0]))
    
    fig, axes = plt.subplots(1, 2, figsize=(11.5, 4.2))
    w_labels = ["0 apples", "1 apple", "2 apples", "3 (all)"]
    x_pos = jnp.arange(4)
    axes[0].bar(x_pos - 0.18, L0[1], width=0.35, color="#3498db", alpha=0.8, label="Literal Listener L0")
    axes[0].bar(x_pos + 0.18, L1[1], width=0.35, color="#9b59b6", alpha=0.85, label="Pragmatic Listener L1")
    axes[0].set_xticks(x_pos); axes[0].set_xticklabels(w_labels)
    axes[0].set_ylabel("Posterior P(world | 'some')")
    axes[0].set_title("RSA Scalar Implicature: 'Some' Implies 'Not All'")
    axes[0].legend(fontsize=8.5); axes[0].grid(alpha=0.25)
    
    axes[1].plot(range(len(prob_A_hist)), prob_A_hist, "o-", color="#27ae60", linewidth=2.2)
    axes[1].axhline(0.5, color="#666", linestyle="--", alpha=0.5)
    axes[1].set_ylim(0, 1.05)
    axes[1].set_xlabel("Observed Step t (E, E, N, E, N)")
    axes[1].set_ylabel("P(Goal = A | actions)")
    axes[1].set_title("Bayesian Inverse Planning: Inferring Intent Online")
    axes[1].grid(alpha=0.3)
    
    plt.tight_layout(); plt.show()