// ================== Rationalisabilite : croyance MIXTE ==================
// Une strategie i est rationalisable s'il existe une distribution p sur les
// strategies survivantes de l'adversaire telle que i soit la meilleure reponse
// a p : (u(i) - u(k)) . p >= 0 pour tout k != i, p >= 0, sum(p) = 1.
//
// Deux implementations exactes, comme en Python :
// - MeilleureReponseMelange : enumeration des SOMMETS du polyedre (rapide) ;
// - MeilleureReponseMelangeLp : programme lineaire par SIMPLEX MAISON (reference).
// La contrainte k = i est EXCLUE : elle vaudrait 0 >= 0 et, introduite dans le
// programme lineaire, forcerait eps <= 0 -- le critere deviendrait eps = 0.
const double TOL = 1e-9;
// --- Systeme lineaire carre : elimination gaussienne, pivot partiel.
// Renvoie null si la matrice est singuliere (|pivot| < 1e-12).
public static double[] LinSolve(double[,] M, double[] rhs)
{
int d = rhs.Length;
var U = (double[,])M.Clone();
var b = (double[])rhs.Clone();
for (int c = 0; c < d; c++)
{
int piv = c;
for (int r = c + 1; r < d; r++)
if (Math.Abs(U[r, c]) > Math.Abs(U[piv, c])) piv = r;
if (Math.Abs(U[piv, c]) < 1e-12) return null;
if (piv != c)
{
for (int j = 0; j < d; j++) (U[c, j], U[piv, j]) = (U[piv, j], U[c, j]);
(b[c], b[piv]) = (b[piv], b[c]);
}
for (int r = c + 1; r < d; r++)
{
double f = U[r, c] / U[c, c];
for (int j = c; j < d; j++) U[r, j] -= f * U[c, j];
b[r] -= f * b[c];
}
}
var x = new double[d];
for (int r = d - 1; r >= 0; r--)
{
double s = b[r];
for (int j = r + 1; j < d; j++) s -= U[r, j] * x[j];
x[r] = s / U[r, r];
}
return x;
}
// Contraintes (u(i)-u(k)).p >= 0, exprimees en coordonnees libres x :
// on elimine la derniere composante de p par la normalisation
// p = (x_0, ..., x_{d-1}, 1 - sum(x)) avec d = n - 1.
// Chaque contrainte devient une droite (coef . x = rhs) du polyedre.
public static List<(double[] coef, double rhs)> ContraintesLignes(double[,] gains, int i)
{
int m = gains.GetLength(0), n = gains.GetLength(1);
int d = n - 1;
var lignes = new List<(double[], double)>();
for (int k = 0; k < m; k++)
{
if (k == i) continue;
var a = new double[n];
for (int j = 0; j < n; j++) a[j] = gains[k, j] - gains[i, j];
var coef = new double[d];
for (int j = 0; j < d; j++) coef[j] = a[j] - a[d];
lignes.Add((coef, -a[d]));
}
for (int j = 0; j < d; j++)
{
var e = new double[d]; e[j] = 1.0;
lignes.Add((e, 0.0)); // frontiere x_j = 0
}
lignes.Add((Enumerable.Repeat(1.0, d).ToArray(), 1.0)); // sum(x) = 1 (frontiere)
return lignes;
}
// Combinaisons de k indices parmi [0, n) -- backtracking, ordre lexicographique.
public static IEnumerable<int[]> Combinaisons(int n, int k)
{
var buf = new int[k];
IEnumerable<int[]> Rec(int start, int depth)
{
if (depth == k) { yield return (int[])buf.Clone(); yield break; }
for (int v = start; v <= n - (k - depth); v++)
{
buf[depth] = v;
foreach (var c in Rec(v + 1, depth + 1)) yield return c;
}
}
foreach (var c in Rec(0, 0)) yield return c;
}
// C(n, k) par formule multiplicative (long).
public static long NbCombinaisons(int n, int k)
{
if (k < 0 || k > n) return 0;
long r = 1;
for (int t = 0; t < k; t++) r = r * (n - t) / (t + 1);
return r;
}
// Sommets candidats du polyedre : intersections de d frontieres actives et
// lineairement independantes (le pivot < 1e-12 ecarte les singularites).
// Exact a toute taille de jeu -- croiser deux frontieres ne suffirait qu'a
// d = 2, c'est-a-dire aux jeux a trois colonnes au plus.
public static List<double[]> Sommets(int d, List<(double[] coef, double rhs)> lignes)
{
var candidats = new List<double[]>();
for (int j = 0; j < d; j++) { var e = new double[d]; e[j] = 1.0; candidats.Add(e); }
candidats.Add(new double[d]);
foreach (var combo in Combinaisons(lignes.Count, d))
{
var M = new double[d, d];
var rhs = new double[d];
for (int t = 0; t < d; t++)
{
for (int j = 0; j < d; j++) M[t, j] = lignes[combo[t]].coef[j];
rhs[t] = lignes[combo[t]].rhs;
}
var x = LinSolve(M, rhs);
if (x != null) candidats.Add(x);
}
return candidats;
}
// Au-dela de ce nombre de sommets candidats, l'enumeration devient trop couteuse
// et le programme lineaire (reference exacte) prend le relais.
const int SEUIL_ENUMERATION = 20000;
// ============== Simplex a deux phases, MAISON (remplace scipy.linprog) ==============
// Forme standard : min c.z s.t. M z = b, z >= 0.
// Phase 1 : variables artificielles (somme minimale > tol => infaisable).
// Phase 2 : objectif reel, artificiels verrouilles hors de la base.
// Regle de Bland (premier indice entrant, plus petit indice de base sortant
// en cas d'egalite) : terminaison garantie, pas de cycling.
static void Pivot(double[,] T, int[] basis, int r, int col, int rows, int total)
{
double piv = T[r, col];
for (int j = 0; j <= total; j++) T[r, j] /= piv;
for (int r2 = 0; r2 < rows; r2++)
{
if (r2 == r) continue;
double f = T[r2, col];
if (Math.Abs(f) > 1e-15)
for (int j = 0; j <= total; j++) T[r2, j] -= f * T[r, j];
}
basis[r] = col;
}
// Renvoie 0 (optimal), 2 (infaisable -- phase 1), 3 (non borne).
static int PivotLoop(double[] c, double[,] T, int[] basis, int rows, int total, int lockFrom = int.MaxValue)
{
while (true)
{
var cb = new double[rows];
for (int r = 0; r < rows; r++) cb[r] = c[basis[r]];
int enter = -1;
for (int j = 0; j < total && enter < 0; j++)
{
if (j >= lockFrom) continue;
bool inBasis = false;
for (int r = 0; r < rows; r++) if (basis[r] == j) inBasis = true;
if (inBasis) continue;
double rj = c[j];
for (int r2 = 0; r2 < rows; r2++) rj -= cb[r2] * T[r2, j];
if (rj < -1e-10) enter = j; // Bland : premier indice negatif
}
if (enter < 0) return 0; // optimal
int leave = -1;
double best = double.PositiveInfinity;
for (int r = 0; r < rows; r++)
{
if (T[r, enter] > 1e-10)
{
double ratio = T[r, total] / T[r, enter];
if (ratio < best - 1e-12
|| (Math.Abs(ratio - best) <= 1e-12 && (leave < 0 || basis[r] < basis[leave])))
{
best = ratio; leave = r;
}
}
}
if (leave < 0) return 3; // non borne
Pivot(T, basis, leave, enter, rows, total);
}
}
// min cObj.z sur M z = b (b>=0 par normalisation de signe), z >= 0.
// status : 0 optimal, 2 infaisable, 3 non borne.
public static (int status, double[] z) SimplexStandard(double[] cObj, double[,] M0, double[] b0)
{
int rows = b0.Length, cols0 = M0.GetLength(1);
var M = (double[,])M0.Clone();
var b = (double[])b0.Clone();
for (int r = 0; r < rows; r++)
if (b[r] < 0)
{
for (int j = 0; j < cols0; j++) M[r, j] = -M[r, j];
b[r] = -b[r];
}
int total = cols0 + rows; // colonnes : z puis artificiels
var T = new double[rows, total + 1]; // +1 : membre de droite
var basis = new int[rows];
for (int r = 0; r < rows; r++)
{
for (int j = 0; j < cols0; j++) T[r, j] = M[r, j];
T[r, cols0 + r] = 1.0;
T[r, total] = b[r];
basis[r] = cols0 + r;
}
// ---- phase 1 : minimiser la somme des artificiels ----
var c1 = new double[total];
for (int r = 0; r < rows; r++) c1[cols0 + r] = 1.0;
int st1 = PivotLoop(c1, T, basis, rows, total);
double val1 = 0;
for (int r = 0; r < rows; r++) if (basis[r] >= cols0) val1 += T[r, total];
if (st1 != 0 || val1 > 1e-8) return (2, new double[cols0]);
// chasser les artificiels restants (base degeneree a valeur 0) :
// pivoter sur n'importe quelle colonne reelle non nulle de leur ligne ;
// ligne entierement nulle = contrainte redondante, on la garde a zero.
for (int r = 0; r < rows; r++)
{
if (basis[r] >= cols0)
{
int pivCol = -1;
for (int j = 0; j < cols0; j++)
if (Math.Abs(T[r, j]) > 1e-9) { pivCol = j; break; }
if (pivCol >= 0) Pivot(T, basis, r, pivCol, rows, total);
}
}
// ---- phase 2 : minimiser cObj, artificiels interdits d'entrer ----
var c2 = new double[total];
for (int j = 0; j < cols0; j++) c2[j] = cObj[j];
int st2 = PivotLoop(c2, T, basis, rows, total, lockFrom: cols0);
if (st2 != 0) return (st2, new double[cols0]);
var z = new double[cols0];
for (int r = 0; r < rows; r++) if (basis[r] < cols0) z[basis[r]] = T[r, total];
return (0, z);
}
// Interface facon linprog : MAXIMISER c.x sous A_ub.x <= b_ub, A_eq.x = b_eq,
// x_j >= 0 pour j < n-1 -- la DERNIERE variable (eps) est LIBRE et se scinde
// en e+ - e-. Renvoie (status, x) avec x reconstitue ; status 0 = optimum.
public static (int status, double[] x) LpMax(double[] c, double[,] A_ub, double[] b_ub,
double[,] A_eq, double[] b_eq)
{
int nOrig = c.Length, nFixed = nOrig - 1;
int N = nFixed + 2; // colonnes : x..., e+, e-
int m1 = A_ub != null ? A_ub.GetLength(0) : 0;
int m2 = A_eq != null ? A_eq.GetLength(0) : 0;
int rows = m1 + m2;
int cols0 = N + m1; // + slacks des inegalites
var M = new double[rows, cols0];
var b = new double[rows];
for (int r = 0; r < m1; r++)
{
for (int j = 0; j < nFixed; j++) M[r, j] = A_ub[r, j];
M[r, nFixed] = A_ub[r, nOrig - 1]; // +eps
M[r, nFixed + 1] = -A_ub[r, nOrig - 1]; // -eps
M[r, N + r] = 1.0; // slack
b[r] = b_ub[r];
}
for (int r = 0; r < m2; r++)
{
for (int j = 0; j < nFixed; j++) M[m1 + r, j] = A_eq[r, j];
M[m1 + r, nFixed] = A_eq[r, nOrig - 1];
M[m1 + r, nFixed + 1] = -A_eq[r, nOrig - 1];
b[m1 + r] = b_eq[r];
}
// maximiser c.x <=> minimiser -c.x
var cMin = new double[cols0];
for (int j = 0; j < nFixed; j++) cMin[j] = -c[j];
cMin[nFixed] = -c[nOrig - 1];
cMin[nFixed + 1] = c[nOrig - 1];
var (status, zz) = SimplexStandard(cMin, M, b);
var x = new double[nOrig];
for (int j = 0; j < nFixed; j++) x[j] = zz[j];
x[nOrig - 1] = zz[nFixed] - zz[nFixed + 1];
return (status, x);
}
// Reference LP : i meilleure reponse a une croyance mixte ?
// max eps s.t. (u(k)-u(i)).p + eps <= 0 (k != i), sum(p) = 1, p >= 0.
// La valeur optimale peut etre NEGATIVE : elle l'est quand i n'est la
// meilleure reponse a aucune croyance mixte.
public static bool MeilleureReponseMelangeLp(double[,] gains, int i)
{
int m = gains.GetLength(0), n = gains.GetLength(1);
int nVars = n + 1;
var c = new double[nVars]; c[nVars - 1] = 1.0;
var A_ub = new double[m - 1, nVars];
var b_ub = new double[m - 1];
int t = 0;
for (int k = 0; k < m; k++)
{
if (k == i) continue;
for (int j = 0; j < n; j++) A_ub[t, j] = gains[k, j] - gains[i, j];
A_ub[t, n] = 1.0;
b_ub[t] = 0.0;
t++;
}
var A_eq = new double[1, nVars];
for (int j = 0; j < n; j++) A_eq[0, j] = 1.0;
var (status, x) = LpMax(c, A_ub, b_ub, A_eq, new[] { 1.0 });
return status == 0 && x[nVars - 1] >= -TOL;
}
// i est-elle la meilleure reponse a UNE croyance mixte ? (enumeration, exacte)
public static bool MeilleureReponseMelange(double[,] gains, int i)
{
int m = gains.GetLength(0), n = gains.GetLength(1);
if (n == 1)
{
// Croyance unique : i doit battre (ou egaler) toutes les autres.
for (int k = 0; k < m; k++) if (gains[k, 0] > gains[i, 0] + TOL) return false;
return true;
}
int d = n - 1;
var lignes = ContraintesLignes(gains, i);
if (NbCombinaisons(lignes.Count, d) > SEUIL_ENUMERATION)
return MeilleureReponseMelangeLp(gains, i);
foreach (var x in Sommets(d, lignes))
{
var p = new double[n];
double s = 0;
for (int j = 0; j < d; j++) { p[j] = x[j]; s += x[j]; }
p[d] = 1.0 - s;
if (p.Min() < -TOL) continue;
bool ok = true;
for (int k = 0; k < m && ok; k++)
{
double dp = 0;
for (int j = 0; j < n; j++) dp += (gains[i, j] - gains[k, j]) * p[j];
if (dp < -TOL) ok = false;
}
if (ok) return true;
}
return false;
}
// Sous-matrice et transposee (equivalents de np.ix_ / .T du Python).
public static double[,] SubMatrix(double[,] X, List<int> rows, List<int> cols)
{
var S = new double[rows.Count, cols.Count];
for (int i = 0; i < rows.Count; i++)
for (int j = 0; j < cols.Count; j++) S[i, j] = X[rows[i], cols[j]];
return S;
}
public static double[,] Transpose(double[,] X)
{
int m = X.GetLength(0), n = X.GetLength(1);
var T = new double[n, m];
for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) T[j, i] = X[i, j];
return T;
}
// Elimination iteree des strategies jamais meilleure reponse a une croyance
// MIXTE (Bernheim, Pearce) -- jeu restreint a chaque tour.
public static (List<string> ratL, List<string> ratC)
StrategiesRationalisables(double[,] A, double[,] B, string[] labelsL = null, string[] labelsC = null)
{
int m = A.GetLength(0), n = B.GetLength(1);
var tousL = labelsL ?? Enumerable.Range(0, m).Select(i => "R" + i).ToArray();
var tousC = labelsC ?? Enumerable.Range(0, n).Select(j => "C" + j).ToArray();
var actifsL = Enumerable.Range(0, m).ToList();
var actifsC = Enumerable.Range(0, n).ToList();
while (true)
{
if (actifsL.Count == 0 || actifsC.Count == 0) break;
var Ar = SubMatrix(A, actifsL, actifsC);
var Br = Transpose(SubMatrix(B, actifsL, actifsC)); // lignes = colonnes du jeu
var aRetirerL = Enumerable.Range(0, actifsL.Count)
.Where(p => !MeilleureReponseMelange(Ar, p)).ToList();
var aRetirerC = Enumerable.Range(0, actifsC.Count)
.Where(q => !MeilleureReponseMelange(Br, q)).ToList();
if (aRetirerL.Count == 0 && aRetirerC.Count == 0) break;
foreach (var p in aRetirerL.OrderByDescending(x => x)) actifsL.RemoveAt(p);
foreach (var q in aRetirerC.OrderByDescending(x => x)) actifsC.RemoveAt(q);
}
return (actifsL.Select(i => tousL[i]).ToList(), actifsC.Select(j => tousC[j]).ToList());
}
// Le lemme de Pearce : la meme chose, par la dominance stricte MIXTE.
// i est-elle strictement dominee par un MELANGE des strategies ?
// max eps s.t. sum_k q_k u(k, j) - u(i, j) >= eps pour tout j ; sum(q) = 1.
public static bool StrictementDominanteMixte(double[,] gains, int i)
{
int m = gains.GetLength(0), n = gains.GetLength(1);
int nVars = m + 1;
var c = new double[nVars]; c[nVars - 1] = 1.0;
var A_ub = new double[n, nVars];
var b_ub = new double[n];
for (int j = 0; j < n; j++)
{
for (int k = 0; k < m; k++) A_ub[j, k] = -gains[k, j];
A_ub[j, m] = 1.0;
b_ub[j] = -gains[i, j];
}
var A_eq = new double[1, nVars];
for (int k = 0; k < m; k++) A_eq[0, k] = 1.0;
var (status, x) = LpMax(c, A_ub, b_ub, A_eq, new[] { 1.0 });
return status == 0 && x[nVars - 1] > 1e-9;
}
// Elimination iteree des strategies strictement dominees par un melange.
public static (List<string> domL, List<string> domC)
EliminationDominanceMixte(double[,] A, double[,] B, string[] labelsL = null, string[] labelsC = null)
{
int m = A.GetLength(0), n = B.GetLength(1);
var tousL = labelsL ?? Enumerable.Range(0, m).Select(i => "R" + i).ToArray();
var tousC = labelsC ?? Enumerable.Range(0, n).Select(j => "C" + j).ToArray();
var actifsL = Enumerable.Range(0, m).ToList();
var actifsC = Enumerable.Range(0, n).ToList();
while (true)
{
if (actifsL.Count == 0 || actifsC.Count == 0) break;
var Ar = SubMatrix(A, actifsL, actifsC);
var Br = Transpose(SubMatrix(B, actifsL, actifsC));
var aRetirerL = Enumerable.Range(0, actifsL.Count)
.Where(p => StrictementDominanteMixte(Ar, p)).ToList();
var aRetirerC = Enumerable.Range(0, actifsC.Count)
.Where(q => StrictementDominanteMixte(Br, q)).ToList();
if (aRetirerL.Count == 0 && aRetirerC.Count == 0) break;
foreach (var p in aRetirerL.OrderByDescending(x => x)) actifsL.RemoveAt(p);
foreach (var q in aRetirerC.OrderByDescending(x => x)) actifsC.RemoveAt(q);
}
return (actifsL.Select(i => tousL[i]).ToList(), actifsC.Select(j => tousC[j]).ToList());
}
// --- Le contre-exemple de la section 4 : trois lignes, deux colonnes -----
double[,] A_TMB = { { 3, 0 }, { 0, 3 }, { 2, 2 } };
double[,] B_TMB = { { 1, 1 }, { 1, 1 }, { 0, 0 } };
var jeuTmb = new Game(A_TMB, B_TMB, new[] { "R0", "R1", "R2" }, new[] { "C0", "C1" },
"Trois lignes, deux colonnes");
jeuTmb.Display();
var pureTmb = new bool[3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 2; j++)
{
bool mr = true;
for (int k = 0; k < 3; k++) if (A_TMB[k, j] > A_TMB[i, j] + TOL) mr = false;
if (mr) pureTmb[i] = true;
}
var mixteTmb = Enumerable.Range(0, 3).Select(i => MeilleureReponseMelange(A_TMB, i)).ToArray();
var gainsMilieu = Enumerable.Range(0, 3)
.Select(i => A_TMB[i, 0] * 0.5 + A_TMB[i, 1] * 0.5).ToArray();
static string Bools(bool[] v) => "[" + string.Join(", ", v.Select(b => b ? "True" : "False")) + "]";
Console.WriteLine("Meilleure reponse a une croyance PURE : " + Bools(pureTmb));
Console.WriteLine("Meilleure reponse a une croyance MIXTE : " + Bools(mixteTmb));
Console.WriteLine("Gains de la Ligne sur p = (1/2, 1/2) : ["
+ string.Join(", ", gainsMilieu.Select(v => v.ToString("F1", INV))) + "]");
Console.WriteLine("Reference LP (simplex maison) : "
+ Bools(Enumerable.Range(0, 3).Select(i => MeilleureReponseMelangeLp(A_TMB, i)).ToArray()));
var (poncL, poncC) = StrategiesRationalisablesPures(A_TMB, B_TMB, new[] { "R0", "R1", "R2" }, new[] { "C0", "C1" });
var (ratL, ratC) = StrategiesRationalisables(A_TMB, B_TMB, new[] { "R0", "R1", "R2" }, new[] { "C0", "C1" });
Console.WriteLine("Rationalisables ponctuels (croyance pure) : lignes [" + string.Join(", ", poncL)
+ "] | colonnes [" + string.Join(", ", poncC) + "]");
Console.WriteLine("Rationalisables (croyance mixte) : lignes [" + string.Join(", ", ratL)
+ "] | colonnes [" + string.Join(", ", ratC) + "]");
Console.WriteLine("Equilibres de Nash purs : ["
+ string.Join(", ", FindPureNash(jeuTmb).Select(p => "(" + jeuTmb.RowLabels[p.i] + ", " + jeuTmb.ColLabels[p.j] + ")")) + "]");