A rollout algorithm plans at decision time: from the current state it estimates for every action by averaging the returns of simulated trajectories that start with that action and then follow a fixed rollout policy , then acts greedily on those estimates. By the policy improvement theorem the result is at least as good as .
Write rollout_q(P, R, terminal, state, pi, n_rollouts, gamma, horizon, seed=0, V=None) that returns (best_action, q) for a tabular model:
P has shape (n_states, n_actions, n_states), R shape (n_states, n_actions) (the reward for taking in ), terminal is a boolean array, and pi has shape (n_states, n_actions) with the rollout policy's probabilities.rng = np.random.default_rng(seed) once. For each action in increasing order, run n_rollouts trajectories from state. A trajectory takes action first; at each step it receives R[s, act] (discounted by ), then samples the next state, then stops if that state is terminal or if horizon steps have been taken, and otherwise samples the next action from pi.p: draw u = rng.random() and take the first index whose np.cumsum(p) value is greater than u (the last index if none is). Each step draws the next state first, then (if the trajectory continues) the next action.V is given, add for the state reached (a truncated rollout).q is the array of average returns per action and best_action its argmax (lowest index on ties).