// Z3 Optimize : Chamberlin-Courant et Monroe (contrainte d'equilibre des charges)
#r "nuget: Microsoft.Z3, 4.12.2"
#load "../../SymbolicAI/SMT/Z3-API/Z3NativeLoader.cs"
using Microsoft.Z3;
using System;
using System.Collections.Generic;
using System.Linq;
public static class Sc09Random
{
public static string[] Sample(Random rng, IEnumerable<string> source)
{
var items = source.ToList();
for (int i = items.Count - 1; i > 0; i--)
{
int j = rng.Next(i + 1);
(items[i], items[j]) = (items[j], items[i]);
}
return items.ToArray();
}
}
public static class Sc09Z3
{
private static int LongValue(Model model, IntExpr expression)
=> (int)((IntNum)model.Evaluate(expression, true)).Int64;
// Somme lineaire large : MkMul rend des ArithExpr, les termes purs sont IntExpr
// (variance ok, IEnumerable<out T>). MkAdd rend ArithExpr, cast IntExpr valide
// car tous les termes sont entiers.
private static IntExpr Sum(Context ctx, IEnumerable<ArithExpr> terms)
=> (IntExpr)ctx.MkAdd(terms.ToArray());
// Equivalent lineaire exact des pseudo-Booleens MkPBEq/MkPBLe : chaque variable
// passee ici est deja contrainte a {0, 1} par le corps de CcZ3/MonroeZ3
// (MkGe 0 / MkLe 1), donc somme lineaire == nombre de variables a 1.
// Meme formulation que le source Python (Sum([...]) == k, pas de PbEq natif).
private static BoolExpr PbEq(Context ctx, IEnumerable<IntExpr> variables, int target)
=> ctx.MkEq(Sum(ctx, variables), ctx.MkInt(target));
private static BoolExpr PbLe(Context ctx, IEnumerable<IntExpr> variables, int target)
=> ctx.MkLe(Sum(ctx, variables), ctx.MkInt(target));
/// <summary>
/// Chamberlin-Courant par Z3 Optimize. Variables :
/// - y_c in {0, 1} : candidat c elu
/// - x_jc in {0, 1} : votant j attribue au candidat c
/// Maximise sum_j sum_c borda(R_j, c) * x_jc.
/// </summary>
public static (List<string> W, List<string> sigma, int score) CcZ3(List<string[]> R, int k, int? mOpt = null)
{
int m = mOpt ?? R[0].Length;
int n = R.Count;
var cands = Sc09.AllCands(R);
using var ctx = new Context();
var opt = ctx.MkOptimize();
var y = cands.ToDictionary(c => c, c => ctx.MkIntConst("y_" + c));
var x = new Dictionary<(int j, string c), IntExpr>();
foreach (var c in cands)
{
opt.Add(ctx.MkGe(y[c], ctx.MkInt(0)));
opt.Add(ctx.MkLe(y[c], ctx.MkInt(1)));
}
for (int j = 0; j < n; j++)
{
foreach (var c in cands)
{
var variable = ctx.MkIntConst($"x_{j}_{c}");
x[(j, c)] = variable;
opt.Add(ctx.MkGe(variable, ctx.MkInt(0)));
opt.Add(ctx.MkLe(variable, ctx.MkInt(1)));
}
opt.Add(PbEq(ctx, cands.Select(c => x[(j, c)]), 1));
}
opt.Add(PbEq(ctx, cands.Select(c => y[c]), k));
foreach (var c in cands)
for (int j = 0; j < n; j++)
opt.Add(ctx.MkLe(x[(j, c)], y[c]));
var borda = new Dictionary<(int j, string c), int>();
for (int j = 0; j < n; j++)
foreach (var c in cands)
borda[(j, c)] = Sc09.ScoreBorda(R[j], new[] { c }, m);
IntExpr scoreTotal = Sum(ctx, borda.Select(pair => ctx.MkMul(ctx.MkInt(pair.Value), x[pair.Key])));
opt.MkMaximize(scoreTotal);
if (opt.Check() != Status.SATISFIABLE) return (null, null, -1);
var model = opt.Model;
var W = cands.Where(c => LongValue(model, y[c]) == 1).ToList();
var sigma = new List<string>();
for (int j = 0; j < n; j++)
sigma.Add(cands.First(c => LongValue(model, x[(j, c)]) == 1));
int score = R.Sum(r => Sc09.ScoreBorda(r, W, m));
return (W, sigma, score);
}
/// <summary>
/// Monroe (strict, 1995) par Z3 Optimize : formulation CC + contrainte
/// d'equilibre -- chaque candidat elu doit representer entre floor(n/k) et
/// ceil(n/k) votants. C'est l'unique difference de formulation avec CC
/// (absence de la contrainte => la regle est CC, pas Monroe).
/// </summary>
public static (List<string> W, List<string> sigma, int score) MonroeZ3(List<string[]> R, int k, int? mOpt = null)
{
int m = mOpt ?? R[0].Length;
int n = R.Count;
var cands = Sc09.AllCands(R);
int lo = n / k;
int hi = (n + k - 1) / k;
using var ctx = new Context();
var opt = ctx.MkOptimize();
var y = cands.ToDictionary(c => c, c => ctx.MkIntConst("y_" + c));
var x = new Dictionary<(int j, string c), IntExpr>();
foreach (var c in cands)
{
opt.Add(ctx.MkGe(y[c], ctx.MkInt(0)));
opt.Add(ctx.MkLe(y[c], ctx.MkInt(1)));
}
for (int j = 0; j < n; j++)
{
foreach (var c in cands)
{
var variable = ctx.MkIntConst($"x_{j}_{c}");
x[(j, c)] = variable;
opt.Add(ctx.MkGe(variable, ctx.MkInt(0)));
opt.Add(ctx.MkLe(variable, ctx.MkInt(1)));
}
opt.Add(PbEq(ctx, cands.Select(c => x[(j, c)]), 1));
}
opt.Add(PbEq(ctx, cands.Select(c => y[c]), k));
foreach (var c in cands)
for (int j = 0; j < n; j++)
opt.Add(ctx.MkLe(x[(j, c)], y[c]));
foreach (var c in cands)
{
var charge = Sum(ctx, Enumerable.Range(0, n).Select(j => x[(j, c)]));
opt.Add(ctx.MkImplies(ctx.MkEq(y[c], ctx.MkInt(1)), ctx.MkGe(charge, ctx.MkInt(lo))));
opt.Add(PbLe(ctx, Enumerable.Range(0, n).Select(j => x[(j, c)]), hi));
}
var borda = new Dictionary<(int j, string c), int>();
for (int j = 0; j < n; j++)
foreach (var c in cands)
borda[(j, c)] = Sc09.ScoreBorda(R[j], new[] { c }, m);
IntExpr scoreTotal = Sum(ctx, borda.Select(pair => ctx.MkMul(ctx.MkInt(pair.Value), x[pair.Key])));
opt.MkMaximize(scoreTotal);
if (opt.Check() != Status.SATISFIABLE) return (null, null, -1);
var model = opt.Model;
var W = cands.Where(c => LongValue(model, y[c]) == 1).ToList();
var sigma = new List<string>();
for (int j = 0; j < n; j++)
sigma.Add(cands.First(c => LongValue(model, x[(j, c)]) == 1));
int score = Enumerable.Range(0, n).Sum(j => m - Sc09.Rang(R[j], sigma[j]));
return (W, sigma, score);
}
}
var (Wz3, sigmaZ3, scoreZ3) = Sc09Z3.CcZ3(Sc09.R, Sc09.K, Sc09.M);
var (WccBrute, scoreCcBrute) = Sc09Cc.CcBrute(Sc09.R, Sc09.K, Sc09.M);
Console.WriteLine($"CC Z3 Optimize : W = {Sc09.Fmt(Wz3)}, score = {scoreZ3}");
Console.WriteLine($"CC brute : W = {Sc09.Fmt(WccBrute)}, score = {scoreCcBrute}");
bool verdictCc = Wz3.SequenceEqual(WccBrute) && scoreZ3 == scoreCcBrute;
Console.WriteLine($"Verdict confrontation : {(verdictCc ? "OK memes optima" : "DIVERGENCE")}");
var rngZ3 = new Random(20261005);
Console.WriteLine("\nTest sur 5 profils aleatoires (n in [4,5], m in [3,4], k in [2,3]) :");
int nbConcordancesCc = 0;
for (int t = 0; t < 5; t++)
{
int nt = rngZ3.Next(4, 6);
int mt = rngZ3.Next(3, 5);
int kt = rngZ3.Next(2, Math.Min(3, mt) + 1);
var candsT = Enumerable.Range(0, mt).Select(j => ((char)('a' + j)).ToString()).ToList();
var Rt = Enumerable.Range(0, nt).Select(_ => Sc09Random.Sample(rngZ3, candsT)).ToList();
var (WbruteT, sBruteT) = Sc09Cc.CcBrute(Rt, kt, mt);
var (Wz3T, _, sZ3T) = Sc09Z3.CcZ3(Rt, kt, mt);
// Concordance des deux voies au niveau de l'OPTIMUM : la force brute enumere
// tous les comites, son score est l'optimum exact ; Z3 doit l'atteindre.
// En cas d'ex aequo (plusieurs comites optimaux), Z3 peut rendre un autre
// representant optimal -- variabilite de representant anticipee par le source.
bool okT = sZ3T == sBruteT;
if (okT) nbConcordancesCc++;
Console.WriteLine($" t={t}: n={nt}, m={mt}, k={kt} brute={Sc09.Fmt(WbruteT)} (s={sBruteT}) " +
$"Z3={Sc09.Fmt(Wz3T)} (s={sZ3T}) {(Wz3T.SequenceEqual(WbruteT) ? (okT ? "OK" : "DIVERGENCE") : (okT ? "OK (ex aequo)" : "DIVERGENCE"))}");
}
Console.WriteLine($"Concordance brute/Z3 : {nbConcordancesCc}/5 ({100.0 * nbConcordancesCc / 5:F0} %)");
if (nbConcordancesCc != 5) throw new InvalidOperationException("Z3 doit retrouver l'optimum de CC sur les cinq profils");
var RTemoinM = Enumerable.Repeat(new[] { "a", "b", "c" }, 4).ToList();
var (WMzT, sigMzT, scMzT) = Sc09Z3.MonroeZ3(RTemoinM, 2, 3);
var (quotasOkT, quotasT) = Sc09Monroe.VerifierQuotas(sigMzT, WMzT, 4, 2);
Console.WriteLine($"\nTemoin monroe_z3 sur [('a','b','c')]*4, k=2 : W = {Sc09.Fmt(WMzT)}, " +
$"sigma = {Sc09.Fmt(sigMzT)}, score = {scMzT}");
Console.WriteLine("Quotas par elu : " + string.Join(", ", quotasT.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}: {kv.Value}")) +
" -- equilibre [floor, ceil] = [2, 2] respecte : " + quotasOkT);
if (!quotasOkT) throw new InvalidOperationException("Le temoin Monroe doit respecter les quotas [2,2]");
var RDisc = new List<string[]>
{
new[] { "c", "a", "d", "b" },
new[] { "d", "a", "b", "c" },
new[] { "d", "a", "b", "c" },
new[] { "d", "a", "b", "c" },
new[] { "d", "a", "b", "c" },
new[] { "d", "a", "c", "b" },
};
int kDisc = 2;
int mDisc = 4;
int nDisc = RDisc.Count;
var (WMBrute, sigMBrute) = Sc09Monroe.Monroe(RDisc, kDisc, mDisc);
int scoreMBrute = Enumerable.Range(0, nDisc).Sum(i => mDisc - Sc09.Rang(RDisc[i], sigMBrute[i]));
var (WCCBrute, scoreCCBrute) = Sc09Cc.CcBrute(RDisc, kDisc, mDisc);
var (WMzD, sigMzD, scoreMzD) = Sc09Z3.MonroeZ3(RDisc, kDisc, mDisc);
var (WCCzD, sigCCzD, scoreCCzD) = Sc09Z3.CcZ3(RDisc, kDisc, mDisc);
bool okM = WMzD.SequenceEqual(WMBrute) && scoreMzD == scoreMBrute;
bool okCC = WCCzD.SequenceEqual(WCCBrute) && scoreCCzD == scoreCCBrute;
var (quotasOkD, quotasD) = Sc09Monroe.VerifierQuotas(sigMzD, WMzD, nDisc, kDisc);
var chargesCC = sigCCzD.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());
Console.WriteLine("\nProfil discriminant (n=6, m=4, k=2) : " +
"1 x (c>a>d>b), 4 x (d>a>b>c), 1 x (d>a>c>b)");
Console.WriteLine("Quota Monroe par elu : [floor(6/2), ceil(6/2)] = [3, 3]");
Console.WriteLine();
Console.WriteLine($"{"Regle",-8}{"Comite",-12}{"Score",-7}Detail");
Console.WriteLine(new string('-', 66));
Console.WriteLine($"{"Monroe",-8}{Sc09.Fmt(WMBrute.OrderBy(c => c).ToList()),-12}{scoreMBrute,-7}brute : sigma = {Sc09.Fmt(sigMBrute)}");
Console.WriteLine($"{"Monroe",-8}{Sc09.Fmt(WMzD.OrderBy(c => c).ToList()),-12}{scoreMzD,-7}Z3 : sigma = {Sc09.Fmt(sigMzD)} (quotas {string.Join(", ", quotasD.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}: {kv.Value}"))})");
Console.WriteLine($"{"CC",-8}{Sc09.Fmt(WCCBrute.OrderBy(c => c).ToList()),-12}{scoreCCBrute,-7}brute : best-in-W par votant");
Console.WriteLine($"{"CC",-8}{Sc09.Fmt(WCCzD.OrderBy(c => c).ToList()),-12}{scoreCCzD,-7}Z3 : charges par elu {string.Join(", ", chargesCC.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}: {kv.Value}"))}");
Console.WriteLine();
Console.WriteLine($"Accord Z3 / brute-force : Monroe {(okM ? "OK" : "DIVERGENCE")}, CC {(okCC ? "OK" : "DIVERGENCE")}");
Console.WriteLine($"Les deux regles elisent des comites differents : Monroe {Sc09.Fmt(WMzD.OrderBy(c => c).ToList())} vs CC {Sc09.Fmt(WCCzD.OrderBy(c => c).ToList())}.");
Console.WriteLine($"CC satisfait le votant 1 avec c (charges non equilibrees {string.Join(", ", chargesCC.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}: {kv.Value}"))}) ;");
Console.WriteLine("Monroe, contraint par [3, 3], elue a a la place de c : chaque votant garde");
Console.WriteLine("un representant de rang <= 2, et le comite de CC ne vaudrait que 13 en Monroe.");
if (!okM || !okCC) throw new InvalidOperationException("Z3 doit retrouver l'optimum des deux regles");
if (!quotasOkD) throw new InvalidOperationException("L'affectation de monroe_z3 doit respecter les quotas d'equilibre");
if (WMzD.OrderBy(c => c).SequenceEqual(WCCzD.OrderBy(c => c)))
throw new InvalidOperationException("Le profil doit discriminer Monroe et CC");