# 5.3 -- La borne temporelle comme accord (Carse, 1986)
# Memes conventions de gains que la section 2 : prendre au tour t rapporte
# big = t + 1 au preneur et small = max(0, t - 1) a l'autre ; toute fin sans
# prise verse a chacun la valeur du palier atteint (terminal (n, n) de la
# section 2.1 = cas particulier b = n).
import numpy as np
N = 12 # longueur physique du jeu (t = 0..N-1)
W = 0.85 # survie par tour (croyance geometrique ; hasard reel en indefini)
EPS = 0.08 # tremblement : probabilite de jouer l'autre action
SEEDS = [0, 1, 7, 42, 99]
K_MAX = 8 # profondeurs mesurees : L0..L8
N_GAMES = 200 # parties par (regime, profondeur, graine)
def payoffs_at_round(t):
big, small = t + 1, max(0, t - 1)
return (big, small) if t % 2 == 0 else (small, big)
def boundary_payoffs(b):
# fin sans prise au palier b : chacun recoit b
return (b, b)
def level_k_policies(H, w, k_max):
"""Politiques L1..Lk_max sous croyance d'horizon : certain en H (w = 1.0)
ou continuation geometrique de survie w (troncature H = 400 : W**400 ~ 1e-28).
L0 passe toujours ; Lk repond au mieux a L(k-1), par induction arriere
sur l'horizon de croyance. Egalite -> Take (cf. section 2, J2 indifferent)."""
policies = [{t: 'P' for t in range(H)}] # L0 : passe toujours
for k in range(1, k_max + 1):
opp = policies[k - 1] # croyance : l'adversaire est L(k-1)
pol, pass_v = {}, {}
for t in range(H - 1, -1, -1):
mover = t % 2 # 0 = J1, 1 = J2
take_v = payoffs_at_round(t)[mover]
# valeur, pour `mover`, d'atteindre le noeud t + 1
if t + 1 >= H:
reach = boundary_payoffs(H)[mover]
elif opp[t + 1] == 'T':
reach = payoffs_at_round(t + 1)[mover]
elif t + 2 >= H:
reach = w * boundary_payoffs(H)[mover] + (1 - w) * boundary_payoffs(t + 2)[mover]
else:
v_next = payoffs_at_round(t + 2)[mover] if pol[t + 2] == 'T' else pass_v[t + 2]
reach = w * v_next + (1 - w) * boundary_payoffs(t + 2)[mover]
pass_v[t] = w * reach + (1 - w) * boundary_payoffs(t + 1)[mover]
pol[t] = 'T' if take_v >= pass_v[t] else 'P'
policies.append(pol)
return policies
pol_annonce = level_k_policies(N, 1.0, K_MAX) # croyance : horizon certain T = N
pol_geom = level_k_policies(400, W, K_MAX) # croyance : continuation geometrique
REGIMES = [
('annonce', pol_annonce), # fin certaine en N, connue des joueurs
('non_annonce', pol_geom), # fin physique en N, croyance geometrique
('indefini', pol_geom), # fin geometrique reelle, croyance exacte
]
def play_game(pol, regime, rng, max_rounds=4000):
"""Une partie en self-play Lk (les deux joueurs de profondeur k).
Retourne (prise_effectuee, tour_de_prise, decisions, passes)."""
t, decisions, passes = 0, 0, 0
while t < max_rounds:
act = pol.get(t, 'P')
if rng.random() < EPS:
act = 'P' if act == 'T' else 'T'
decisions += 1
if act == 'T':
return (True, t, decisions, passes)
passes += 1
if regime == 'indefini':
if rng.random() >= W: # mort exogene au palier t + 1
return (False, None, decisions, passes)
elif t + 1 >= N: # fin physique au palier N
return (False, None, decisions, passes)
t += 1
return (False, None, decisions, passes)
# Graine fixe : la sortie de Monte-Carlo est citee dans la prose du carnet,
# elle doit etre reproductible d'une execution a l'autre.
results = {}
for name, pols in REGIMES:
for k in range(0, K_MAX + 1):
rows = []
for seed in SEEDS:
rng = np.random.default_rng(seed)
took, tours, dec_tot, pass_tot = 0, [], 0, 0
for _ in range(N_GAMES):
take, tour, dec, pas = play_game(pols[k], name, rng)
dec_tot += dec
pass_tot += pas
if take:
took += 1
tours.append(tour)
rows.append((took / N_GAMES,
float(np.mean(tours)) if tours else float('nan'),
pass_tot / dec_tot))
results[(name, k)] = rows
# Politiques pures (sans tremblement) : ou chaque profondeur prend-elle ?
# Filtre t < 40 = region atteignable : sous croyance geometrique, la hierarchie
# produit bien des prises pres du bord de TRONCATURE (t ~ 391-399 pour H = 400),
# mais ce bord est un artefact de calcul -- P(survivre 40 tours) = W**40 ~ 0.2 %.
T_REACH = 40
print('Premier noeud de prise des politiques pures (sans tremblement, t < %d) :' % T_REACH)
for name, pols in REGIMES:
desc = []
for k in range(0, K_MAX + 1):
ts = [t for t in sorted(pols[k]) if pols[k][t] == 'T' and t < T_REACH]
desc.append('L%d: %s' % (k, str(min(ts)) if ts else 'jamais'))
print(' %-12s %s' % (name, ', '.join(desc)))
print()
# Table : par regime et profondeur, moyenne +/- demi-etendue sur les 5 graines
print('Mesure jouee (epsilon = %.2f, %d parties x %d graines) :' % (EPS, N_GAMES, len(SEEDS)))
hdr = ('%-3s | %-16s %-9s | %-16s %-9s | %-16s %-9s'
% ('k', 'coop annonce', '1er take', 'coop non-an.', '1er take', 'coop indefini', '1er take'))
print(hdr)
print('-' * len(hdr))
for k in range(0, K_MAX + 1):
parts = ['%-3d |' % k]
for name in ('annonce', 'non_annonce', 'indefini'):
coops = [r[2] for r in results[(name, k)]]
takes = [r[1] for r in results[(name, k)] if not np.isnan(r[1])]
c, spread = float(np.mean(coops)), (max(coops) - min(coops)) / 2
tk = ('%4.1f' % float(np.mean(takes))) if takes else ' --'
parts.append(' %5.3f +/- %4.3f %s |' % (c, spread, tk))
print(''.join(parts))
# Figure : tour moyen de premiere prise et taux de cooperation vs profondeur
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
ks = np.arange(0, K_MAX + 1)
styles = {'annonce': ('o', 'tab:red'), 'non_annonce': ('s', 'tab:blue'), 'indefini': ('^', 'tab:green')}
labels = {'annonce': 'fini annonce (T=12)',
'non_annonce': 'fini non annonce (croyance w=0.85)',
'indefini': 'indefini (w=0.85)'}
for name, _ in REGIMES:
m, col = styles[name]
take_mean, coop_mean = [], []
for k in ks:
tk = [r[1] for r in results[(name, k)] if not np.isnan(r[1])]
take_mean.append(float(np.mean(tk)) if tk else np.nan)
coop_mean.append(float(np.mean([r[2] for r in results[(name, k)]])))
ax1.plot(ks, take_mean, m + '-', color=col, label=labels[name])
ax2.plot(ks, coop_mean, m + '-', color=col, label=labels[name])
ax1.set_xlabel('profondeur de raisonnement k')
ax1.set_ylabel('tour moyen de premiere prise')
ax2.set_xlabel('profondeur de raisonnement k')
ax2.set_ylabel('taux de cooperation')
ax2.set_ylim(0, 1)
for ax in (ax1, ax2):
ax.grid(alpha=0.3)
ax.set_xticks(ks)
ax1.legend(fontsize=8)
plt.tight_layout()
plt.show()