:dep z3 = { version = "0.24.0", features = ["gh-release"] }
println!("Environnement chargé : Rust + evcxr, crate z3 0.24.0");Environnement chargé : Rust + evcxr, crate z3 0.24.0
Navigation : << SC-06b-Mobius-Coalitions | Index | 16-MechanismDesign >> | jumeau Python
Question directrice — Le poids nominal d’un acteur dans un vote pondéré mesure-t-il son pouvoir réel de faire basculer une décision ?
Ce side-track distille le projet T1 d’Ilias Kalalou et Kaelan Grall (EPITA, 2026). Ilias a porté la question, la modélisation des jeux pondérés et les analyses politiques ; Kaelan a porté les définitions des indices, l’encodage Z3, la matrice d’axiomes et les limites. CoursIA ajoute le pont explicite vers le théorème Lean général de Shapley et clarifie la hiérarchie des garanties. Ces ajouts éditoriaux ne sont pas rétro-attribués aux étudiants.
Jumeau Rust. Ce carnet est le portage Rust (evcxr) de Coalitions-01-Pouvoir-Coalitionnel-SMT-Python.ipynb : memes definitions, memes exercices, memes sorties attendues. Les tables reproduisent le formatage du carnet Python ; la voie SMT utilise la crate z3 0.24.
Objectifs
UNSAT comme une vérification bornée et SAT comme un contre-exemple ;Prérequis : coalitions, permutations, logique propositionnelle ; Rust + evcxr, crate z3 (0.24). Durée estimée : 55 min.
Environnement chargé : Rust + evcxr, crate z3 0.24.0
Un jeu de vote pondéré s’écrit \([q;w_1,\ldots,w_n]\). Une coalition gagne si la somme de ses poids atteint le quota \(q\). Un joueur est critique dans une coalition gagnante si son retrait la rend perdante. Une coalition gagnante est minimale si chacun de ses membres y est critique.
La structure ci-dessous (portage Rust sous evcxr) est une réécriture autonome pour CoursIA, fidèle aux concepts et tests du projet d’Ilias Kalalou et Kaelan Grall.
fn factorial(n: usize) -> i64 {
(1..=n as i64).product()
}
fn combinations_range(n: usize, k: usize) -> Vec<Vec<usize>> {
// Sous-ensembles de {0..n-1} de cardinal k, ordre lexicographique
// (meme ordre qu'itertools.combinations).
let mut result = Vec::new();
if k > n {
return result;
}
let mut c: Vec<usize> = (0..k).collect();
loop {
result.push(c.clone());
let mut i = k;
while i > 0 && c[i - 1] == n - k + i - 1 {
i -= 1;
}
if i == 0 {
break;
}
c[i - 1] += 1;
for j in i..k {
c[j] = c[j - 1] + 1;
}
}
result
}
fn all_coalitions(n: usize) -> Vec<Vec<usize>> {
// Par taille croissante puis ordre lexicographique.
(0..=n).flat_map(|k| combinations_range(n, k)).collect()
}
#[derive(Clone)]
struct VotingGame {
weights: Vec<i64>,
quota: i64,
names: Vec<String>,
}
impl VotingGame {
fn new(weights: Vec<i64>, quota: i64, names: &[&str]) -> VotingGame {
let names: Vec<String> = names.iter().map(|s| s.to_string()).collect();
let total: i64 = weights.iter().sum();
assert!(
weights.len() == names.len() && quota > 0 && quota <= total,
"Jeu pondere incoherent"
);
VotingGame { weights, quota, names }
}
fn n(&self) -> usize {
self.weights.len()
}
fn weight(&self, coalition: &[usize]) -> i64 {
coalition.iter().map(|&i| self.weights[i]).sum()
}
fn wins(&self, coalition: &[usize]) -> bool {
self.weight(coalition) >= self.quota
}
fn coalitions(&self) -> Vec<Vec<usize>> {
all_coalitions(self.n())
}
fn minimal_winning(&self) -> Vec<Vec<usize>> {
self.coalitions()
.into_iter()
.filter(|s| {
self.wins(s)
&& s.iter().all(|&i| {
let without: Vec<usize> =
s.iter().cloned().filter(|&j| j != i).collect();
!self.wins(&without)
})
})
.collect()
}
fn is_dummy(&self, i: usize) -> bool {
self.coalitions()
.into_iter()
.filter(|s| !s.contains(&i))
.all(|s| {
let mut with = s.clone();
with.push(i);
with.sort();
self.wins(&with) == self.wins(&s)
})
}
fn is_veto(&self, i: usize) -> bool {
let others: Vec<usize> = (0..self.n()).filter(|&j| j != i).collect();
!self.wins(&others)
}
fn is_dictator(&self, i: usize) -> bool {
self.wins(&[i]) && self.is_veto(i)
}
fn repr(&self) -> String {
let w = self.weights.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
let n = self.names.iter().map(|x| format!("'{}'", x)).collect::<Vec<_>>().join(", ");
format!("VotingGame(weights=({}), quota={}, names=({}))", w, self.quota, n)
}
}
fn py_bool(b: bool) -> &'static str {
if b { "True" } else { "False" }
}
let example = VotingGame::new(vec![3, 2, 1], 4, &["A", "B", "C"]);
println!("Jeu exemple : {}", example.repr());
let mws: Vec<String> = example
.minimal_winning()
.iter()
.map(|s| {
let names: Vec<String> = s.iter().map(|&i| format!("'{}'", example.names[i])).collect();
format!("[{}]", names.join(", "))
})
.collect();
println!("Coalitions gagnantes minimales : [{}]", mws.join(", "));
let roles: Vec<String> = (0..example.n())
.map(|i| {
format!(
"'{}': {{'nul': {}, 'veto': {}, 'dictateur': {}}}",
example.names[i],
py_bool(example.is_dummy(i)),
py_bool(example.is_veto(i)),
py_bool(example.is_dictator(i))
)
})
.collect();
println!("Rôles : {{{}}}", roles.join(", "));Jeu exemple : VotingGame(weights=(3, 2, 1), quota=4, names=('A', 'B', 'C'))
Coalitions gagnantes minimales : [['A', 'B'], ['A', 'C']]
Rôles : {'A': {'nul': False, 'veto': True, 'dictateur': False}, 'B': {'nul': False, 'veto': False, 'dictateur': False}, 'C': {'nul': False, 'veto': False, 'dictateur': False}}
Le dictionnaire « Rôles » conclut le diagnostic structurel : aucun joueur nul, aucun dictateur, et un seul véto — A. L’arithmétique du véto est immédiate : sans A, B et C pèsent 2 + 1 = 3, sous le quota de 4 ; aucune coalition ne passe donc sans lui.
Dans [4; 3, 2, 1], les coalitions minimales gagnantes sont {A,B} et {A,C}. A n’est pas dictateur : son poids 3 reste sous le quota. Pourtant, A appartient à toutes les coalitions minimales ; cette structure annonce un pouvoir supérieur à sa seule part de poids.
La dernière hypothèse est le véritable apport absent du corpus CoursIA exécutable avant cette distillation.
fn factorial(n: usize) -> i64 {
(1..=n as i64).product()
}
fn combinations_range(n: usize, k: usize) -> Vec<Vec<usize>> {
// Sous-ensembles de {0..n-1} de cardinal k, ordre lexicographique
// (meme ordre qu'itertools.combinations).
let mut result = Vec::new();
if k > n {
return result;
}
let mut c: Vec<usize> = (0..k).collect();
loop {
result.push(c.clone());
let mut i = k;
while i > 0 && c[i - 1] == n - k + i - 1 {
i -= 1;
}
if i == 0 {
break;
}
c[i - 1] += 1;
for j in i..k {
c[j] = c[j - 1] + 1;
}
}
result
}
fn all_coalitions(n: usize) -> Vec<Vec<usize>> {
// Par taille croissante puis ordre lexicographique.
(0..=n).flat_map(|k| combinations_range(n, k)).collect()
}
#[derive(Clone)]
struct VotingGame {
weights: Vec<i64>,
quota: i64,
names: Vec<String>,
}
impl VotingGame {
fn new(weights: Vec<i64>, quota: i64, names: &[&str]) -> VotingGame {
let names: Vec<String> = names.iter().map(|s| s.to_string()).collect();
let total: i64 = weights.iter().sum();
assert!(
weights.len() == names.len() && quota > 0 && quota <= total,
"Jeu pondere incoherent"
);
VotingGame { weights, quota, names }
}
fn n(&self) -> usize {
self.weights.len()
}
fn weight(&self, coalition: &[usize]) -> i64 {
coalition.iter().map(|&i| self.weights[i]).sum()
}
fn wins(&self, coalition: &[usize]) -> bool {
self.weight(coalition) >= self.quota
}
fn coalitions(&self) -> Vec<Vec<usize>> {
all_coalitions(self.n())
}
fn minimal_winning(&self) -> Vec<Vec<usize>> {
self.coalitions()
.into_iter()
.filter(|s| {
self.wins(s)
&& s.iter().all(|&i| {
let without: Vec<usize> =
s.iter().cloned().filter(|&j| j != i).collect();
!self.wins(&without)
})
})
.collect()
}
fn is_dummy(&self, i: usize) -> bool {
self.coalitions()
.into_iter()
.filter(|s| !s.contains(&i))
.all(|s| {
let mut with = s.clone();
with.push(i);
with.sort();
self.wins(&with) == self.wins(&s)
})
}
fn is_veto(&self, i: usize) -> bool {
let others: Vec<usize> = (0..self.n()).filter(|&j| j != i).collect();
!self.wins(&others)
}
fn is_dictator(&self, i: usize) -> bool {
self.wins(&[i]) && self.is_veto(i)
}
fn repr(&self) -> String {
let w = self.weights.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
let n = self.names.iter().map(|x| format!("'{}'", x)).collect::<Vec<_>>().join(", ");
format!("VotingGame(weights=({}), quota={}, names=({}))", w, self.quota, n)
}
}
fn py_bool(b: bool) -> &'static str {
if b { "True" } else { "False" }
}
fn fmt_f64_py(v: f64) -> String {
// Repr Python : toujours au moins une decimale ("1.0", jamais "1").
let s = format!("{}", v);
if s.contains('.') || s.contains('e') {
s
} else {
format!("{}.0", s)
}
}
fn py_repr_f64(v: f64) -> String {
fmt_f64_py(v)
}
fn round_nf(x: f64, d: i32) -> f64 {
// Equivalent de numpy.round : arrondi demi-pair au rang d.
let p = 10f64.powi(d);
let scaled = x * p;
let r = if (scaled - scaled.trunc()).abs() == 0.5 {
let t = scaled.trunc();
if t as i64 % 2 == 0 { t } else { t + scaled.signum() }
} else {
scaled.round()
};
r / p
}
enum Cell {
I(i64),
S(String),
F(f64),
Sci(f64),
}
fn fmt_sci(v: f64) -> String {
// Format exponentiel Python : mantisse .6, exposant signe + 2 chiffres.
let s = format!("{:.6e}", v);
let (mant, exp) = match s.split_once('e') {
Some(p) => p,
None => return s,
};
let e: i32 = exp.parse().unwrap_or(0);
if e < 0 {
format!("{}e-{:02}", mant, -e)
} else {
format!("{}e+{:02}", mant, e)
}
}
fn render_table(index: Option<&[String]>, headers: &[&str], rows: &[Vec<Cell>]) -> String {
// Reproduit le rendu pandas to_string : colonnes de valeurs alignees a
// droite, colonne d'index alignee a gauche, largeur = max(en-tete,
// valeurs) ; les colonnes flottantes partagent le nombre de decimales
// maximal de la colonne (alignement de la virgule). Sans index, pandas
// ajoute un espace fanteme en tete et joint par un seul espace.
let ncols = headers.len();
let mut col_dec = vec![0usize; ncols];
for row in rows {
for (c, cell) in row.iter().enumerate() {
if let Cell::F(v) = cell {
let s = fmt_f64_py(*v);
let d = s.find('.').map_or(0, |p| s.len() - p - 1);
if d > col_dec[c] {
col_dec[c] = d;
}
}
}
}
let mut lines: Vec<Vec<String>> = Vec::new();
let mut head: Vec<String> = Vec::new();
if index.is_some() {
head.push(String::new());
}
for h in headers {
head.push((*h).to_string());
}
lines.push(head);
for (r, row) in rows.iter().enumerate() {
let mut line: Vec<String> = Vec::new();
if let Some(idx) = index {
line.push(idx[r].clone());
}
for (c, cell) in row.iter().enumerate() {
line.push(match cell {
Cell::I(v) => v.to_string(),
Cell::S(v) => v.clone(),
Cell::F(v) => format!("{:.*}", col_dec[c], v),
Cell::Sci(v) => fmt_sci(*v),
});
}
lines.push(line);
}
let nfields = lines[0].len();
let mut widths = vec![0usize; nfields];
for line in &lines {
for (c, s) in line.iter().enumerate() {
let l = s.chars().count();
if l > widths[c] {
widths[c] = l;
}
}
}
let noindex = index.is_none();
let sep = if noindex { " " } else { " " };
let mut out = String::new();
for line in &lines {
let fields: Vec<String> = line
.iter()
.enumerate()
.map(|(c, s)| {
if c == 0 && !noindex {
format!("{:<w$}", s, w = widths[c])
} else {
format!("{:>w$}", s, w = widths[c])
}
})
.collect();
if noindex {
out.push(' ');
}
out.push_str(&fields.join(sep));
out.push('\n');
}
out
}
fn fmt_name_list(names: &[String]) -> String {
let inner = names.iter().map(|n| format!("'{}'", n)).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn fmt_int_list(v: &[usize]) -> String {
let inner = v.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn swing_counts(game: &VotingGame) -> Vec<i64> {
let mut counts = vec![0i64; game.n()];
for i in 0..game.n() {
for s in game.coalitions() {
if !s.contains(&i) && !game.wins(&s) {
let mut with = s.clone();
with.push(i);
with.sort();
if game.wins(&with) {
counts[i] += 1;
}
}
}
}
counts
}
struct Indices6 {
poids: Vec<i64>,
part_poids: Vec<f64>,
shapley_shubik: Vec<f64>,
banzhaf_absolu: Vec<f64>,
banzhaf_normalise: Vec<f64>,
deegan_packel: Vec<f64>,
}
fn power_indices_enumeration(game: &VotingGame) -> Indices6 {
let n = game.n();
let mut shapley = vec![0.0f64; n];
for i in 0..n {
let others: Vec<usize> = (0..n).filter(|&j| j != i).collect();
for size in 0..n {
let coefficient =
(factorial(size) * factorial(n - size - 1)) as f64 / factorial(n) as f64;
for idx in combinations_range(n - 1, size) {
let s: Vec<usize> = idx.iter().map(|&k| others[k]).collect();
let mut with = s.clone();
with.push(i);
with.sort();
let delta = (game.wins(&with) as i64 - game.wins(&s) as i64) as f64;
shapley[i] += coefficient * delta;
}
}
}
let swings = swing_counts(game);
let total: i64 = swings.iter().sum();
let total_weight: i64 = game.weights.iter().sum();
let minimal = game.minimal_winning();
let m = minimal.len() as f64;
let mut deegan = vec![0.0f64; n];
for i in 0..n {
let mut acc = 0.0f64;
for s in &minimal {
if s.contains(&i) {
acc += 1.0 / s.len() as f64;
}
}
deegan[i] = acc / m;
}
Indices6 {
poids: game.weights.clone(),
part_poids: game.weights.iter().map(|w| *w as f64 / total_weight as f64).collect(),
shapley_shubik: shapley,
banzhaf_absolu: swings.iter().map(|c| *c as f64 / 2f64.powi(n as i32 - 1)).collect(),
banzhaf_normalise: swings.iter().map(|c| *c as f64 / total as f64).collect(),
deegan_packel: deegan,
}
}
let example = VotingGame::new(vec![3, 2, 1], 4, &["A", "B", "C"]);
let small = power_indices_enumeration(&example);
let idx: Vec<String> = example.names.clone();
let rows: Vec<Vec<Cell>> = (0..example.n())
.map(|i| {
vec![
Cell::I(small.poids[i]),
Cell::F(round_nf(small.part_poids[i], 4)),
Cell::F(round_nf(small.shapley_shubik[i], 4)),
Cell::F(round_nf(small.banzhaf_absolu[i], 4)),
Cell::F(round_nf(small.banzhaf_normalise[i], 4)),
Cell::F(round_nf(small.deegan_packel[i], 4)),
]
})
.collect();
print!(
"{}",
render_table(
Some(&idx),
&["poids", "part_poids", "shapley_shubik", "banzhaf_absolu", "banzhaf_normalise", "deegan_packel"],
&rows
)
);
fn sum_col(v: &[f64]) -> f64 {
v.iter().fold(0.0f64, |a, &x| a + x)
}
let sommes = [
("shapley_shubik", round_nf(sum_col(&small.shapley_shubik), 4)),
("banzhaf_absolu", round_nf(sum_col(&small.banzhaf_absolu), 4)),
("banzhaf_normalise", round_nf(sum_col(&small.banzhaf_normalise), 4)),
("deegan_packel", round_nf(sum_col(&small.deegan_packel), 4)),
];
let sommes_str = sommes
.iter()
.map(|(k, v)| format!("'{}': {}", k, py_repr_f64(*v)))
.collect::<Vec<_>>()
.join(", ");
println!("Sommes : {{{}}}", sommes_str); poids part_poids shapley_shubik banzhaf_absolu banzhaf_normalise deegan_packel
A 3 0.5000 0.6667 0.75 0.6 0.50
B 2 0.3333 0.1667 0.25 0.2 0.25
C 1 0.1667 0.1667 0.25 0.2 0.25
Sommes : {'shapley_shubik': 1.0, 'banzhaf_absolu': 1.25, 'banzhaf_normalise': 1.0, 'deegan_packel': 1.0}
Le tableau croise poids et pouvoir : A porte la moitié du poids (0.5000) mais 0.75 au Banzhaf absolu — trois des quatre coalitions adverses possibles font de lui le joueur décisif — et 0.6667 au Shapley-Shubik. Seconde lecture : B et C affichent les mêmes valeurs sur tous les indices (0.1667 en Shapley-Shubik, 0.25 en Banzhaf absolu) malgré des poids différents — à quota 4, aucune coalition ne les distingue.
La comparaison des indices révèle que Shapley-Shubik et Banzhaf normalisé donnent des résultats similaires, tandis que Deegan-Packel produit une distribution différente (A: 0.50, B: 0.25, C: 0.25).
Les indices normalisés somment à 1, contrairement au Banzhaf absolu. Dans cet exemple, A porte la moitié du poids mais davantage de pouvoir selon chaque expérience. Deegan-Packel accentue la question : il ignore toutes les coalitions gagnantes non minimales, non parce qu’elles seraient impossibles, mais parce que son modèle suppose qu’elles ne sont pas les coalitions pertinentes.
Objectif : compléter une fonction qui retourne les joueurs nuls, à veto et dictateurs d’un jeu.
Indice : utilisez is_dummy, is_veto et is_dictator.
Exercice 1 à compléter : diagnose_roles(game)
La première voie parcourait explicitement les sous-ensembles. La voie suivante confie à Z3 les variables booléennes d’appartenance et la contrainte de pivot ou de minimalité. Après chaque modèle, une clause de blocage interdit exactement cette affectation et force le solveur à en trouver une autre.
C’est de l’énumération de modèles SMT, pas du CEGIS : aucune boucle ne synthétise un candidat, ne demande un contre-exemple, puis ne raffine le candidat.
use z3::ast::{Ast, Bool, Int};
use z3::{SatResult, Solver};
use std::ops::{Add, Sub};
fn factorial(n: usize) -> i64 {
(1..=n as i64).product()
}
fn combinations_range(n: usize, k: usize) -> Vec<Vec<usize>> {
// Sous-ensembles de {0..n-1} de cardinal k, ordre lexicographique
// (meme ordre qu'itertools.combinations).
let mut result = Vec::new();
if k > n {
return result;
}
let mut c: Vec<usize> = (0..k).collect();
loop {
result.push(c.clone());
let mut i = k;
while i > 0 && c[i - 1] == n - k + i - 1 {
i -= 1;
}
if i == 0 {
break;
}
c[i - 1] += 1;
for j in i..k {
c[j] = c[j - 1] + 1;
}
}
result
}
fn all_coalitions(n: usize) -> Vec<Vec<usize>> {
// Par taille croissante puis ordre lexicographique.
(0..=n).flat_map(|k| combinations_range(n, k)).collect()
}
#[derive(Clone)]
struct VotingGame {
weights: Vec<i64>,
quota: i64,
names: Vec<String>,
}
impl VotingGame {
fn new(weights: Vec<i64>, quota: i64, names: &[&str]) -> VotingGame {
let names: Vec<String> = names.iter().map(|s| s.to_string()).collect();
let total: i64 = weights.iter().sum();
assert!(
weights.len() == names.len() && quota > 0 && quota <= total,
"Jeu pondere incoherent"
);
VotingGame { weights, quota, names }
}
fn n(&self) -> usize {
self.weights.len()
}
fn weight(&self, coalition: &[usize]) -> i64 {
coalition.iter().map(|&i| self.weights[i]).sum()
}
fn wins(&self, coalition: &[usize]) -> bool {
self.weight(coalition) >= self.quota
}
fn coalitions(&self) -> Vec<Vec<usize>> {
all_coalitions(self.n())
}
fn minimal_winning(&self) -> Vec<Vec<usize>> {
self.coalitions()
.into_iter()
.filter(|s| {
self.wins(s)
&& s.iter().all(|&i| {
let without: Vec<usize> =
s.iter().cloned().filter(|&j| j != i).collect();
!self.wins(&without)
})
})
.collect()
}
fn is_dummy(&self, i: usize) -> bool {
self.coalitions()
.into_iter()
.filter(|s| !s.contains(&i))
.all(|s| {
let mut with = s.clone();
with.push(i);
with.sort();
self.wins(&with) == self.wins(&s)
})
}
fn is_veto(&self, i: usize) -> bool {
let others: Vec<usize> = (0..self.n()).filter(|&j| j != i).collect();
!self.wins(&others)
}
fn is_dictator(&self, i: usize) -> bool {
self.wins(&[i]) && self.is_veto(i)
}
fn repr(&self) -> String {
let w = self.weights.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
let n = self.names.iter().map(|x| format!("'{}'", x)).collect::<Vec<_>>().join(", ");
format!("VotingGame(weights=({}), quota={}, names=({}))", w, self.quota, n)
}
}
fn py_bool(b: bool) -> &'static str {
if b { "True" } else { "False" }
}
fn fmt_f64_py(v: f64) -> String {
// Repr Python : toujours au moins une decimale ("1.0", jamais "1").
let s = format!("{}", v);
if s.contains('.') || s.contains('e') {
s
} else {
format!("{}.0", s)
}
}
fn py_repr_f64(v: f64) -> String {
fmt_f64_py(v)
}
fn round_nf(x: f64, d: i32) -> f64 {
// Equivalent de numpy.round : arrondi demi-pair au rang d.
let p = 10f64.powi(d);
let scaled = x * p;
let r = if (scaled - scaled.trunc()).abs() == 0.5 {
let t = scaled.trunc();
if t as i64 % 2 == 0 { t } else { t + scaled.signum() }
} else {
scaled.round()
};
r / p
}
enum Cell {
I(i64),
S(String),
F(f64),
Sci(f64),
}
fn fmt_sci(v: f64) -> String {
// Format exponentiel Python : mantisse .6, exposant signe + 2 chiffres.
let s = format!("{:.6e}", v);
let (mant, exp) = match s.split_once('e') {
Some(p) => p,
None => return s,
};
let e: i32 = exp.parse().unwrap_or(0);
if e < 0 {
format!("{}e-{:02}", mant, -e)
} else {
format!("{}e+{:02}", mant, e)
}
}
fn render_table(index: Option<&[String]>, headers: &[&str], rows: &[Vec<Cell>]) -> String {
// Reproduit le rendu pandas to_string : colonnes de valeurs alignees a
// droite, colonne d'index alignee a gauche, largeur = max(en-tete,
// valeurs) ; les colonnes flottantes partagent le nombre de decimales
// maximal de la colonne (alignement de la virgule). Sans index, pandas
// ajoute un espace fanteme en tete et joint par un seul espace.
let ncols = headers.len();
let mut col_dec = vec![0usize; ncols];
for row in rows {
for (c, cell) in row.iter().enumerate() {
if let Cell::F(v) = cell {
let s = fmt_f64_py(*v);
let d = s.find('.').map_or(0, |p| s.len() - p - 1);
if d > col_dec[c] {
col_dec[c] = d;
}
}
}
}
let mut lines: Vec<Vec<String>> = Vec::new();
let mut head: Vec<String> = Vec::new();
if index.is_some() {
head.push(String::new());
}
for h in headers {
head.push((*h).to_string());
}
lines.push(head);
for (r, row) in rows.iter().enumerate() {
let mut line: Vec<String> = Vec::new();
if let Some(idx) = index {
line.push(idx[r].clone());
}
for (c, cell) in row.iter().enumerate() {
line.push(match cell {
Cell::I(v) => v.to_string(),
Cell::S(v) => v.clone(),
Cell::F(v) => format!("{:.*}", col_dec[c], v),
Cell::Sci(v) => fmt_sci(*v),
});
}
lines.push(line);
}
let nfields = lines[0].len();
let mut widths = vec![0usize; nfields];
for line in &lines {
for (c, s) in line.iter().enumerate() {
let l = s.chars().count();
if l > widths[c] {
widths[c] = l;
}
}
}
let noindex = index.is_none();
let sep = if noindex { " " } else { " " };
let mut out = String::new();
for line in &lines {
let fields: Vec<String> = line
.iter()
.enumerate()
.map(|(c, s)| {
if c == 0 && !noindex {
format!("{:<w$}", s, w = widths[c])
} else {
format!("{:>w$}", s, w = widths[c])
}
})
.collect();
if noindex {
out.push(' ');
}
out.push_str(&fields.join(sep));
out.push('\n');
}
out
}
fn fmt_name_list(names: &[String]) -> String {
let inner = names.iter().map(|n| format!("'{}'", n)).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn fmt_int_list(v: &[usize]) -> String {
let inner = v.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn sat_str(r: SatResult) -> &'static str {
match r {
SatResult::Sat => "sat",
SatResult::Unsat => "unsat",
_ => "unknown",
}
}
fn enumerate_models(solver: &mut Solver, variables: &[Bool]) -> Vec<Vec<bool>> {
// Enumeration de modeles SMT avec clause de blocage apres chaque modele.
let mut found = Vec::new();
while solver.check() == SatResult::Sat {
let model = match solver.get_model() {
Some(m) => m,
None => break,
};
let assignment: Vec<bool> = variables
.iter()
.map(|x| match model.eval(x, true) {
Some(v) => v.as_bool().unwrap_or(false),
None => false,
})
.collect();
found.push(assignment.clone());
let blockers: Vec<Bool> = variables
.iter()
.zip(assignment.iter())
.map(|(x, &v)| x.ne(&Bool::from_bool(v)))
.collect();
solver.assert(Bool::or(&blockers));
}
found
}
fn swing_sizes_smt(game: &VotingGame, player: usize) -> Vec<i64> {
// Par taille de coalition (indice du vecteur) : nombre de modeles pivots.
let others: Vec<usize> = (0..game.n()).filter(|&i| i != player).collect();
let x: Vec<Bool> = others
.iter()
.map(|&i| Bool::new_const(format!("s_{}_{}", player, i)))
.collect();
let zero = Int::from_i64(0);
let weight_terms: Vec<Int> = x
.iter()
.zip(others.iter())
.map(|(var, &i)| var.ite(&Int::from_i64(game.weights[i]), &zero))
.collect();
let weight = weight_terms
.into_iter()
.fold(Int::from_i64(0), |acc, t| &acc + &t);
let mut solver = Solver::new();
solver.assert(weight.lt(&Int::from_i64(game.quota)));
solver.assert((&weight + &Int::from_i64(game.weights[player])).ge(&Int::from_i64(game.quota)));
let mut sizes = vec![0i64; game.n()];
for assignment in enumerate_models(&mut solver, &x) {
let size = assignment.iter().filter(|&&b| b).count();
sizes[size] += 1;
}
sizes
}
fn minimal_winning_smt(game: &VotingGame) -> Vec<Vec<usize>> {
let x: Vec<Bool> = (0..game.n()).map(|i| Bool::new_const(format!("m_{}", i))).collect();
let zero = Int::from_i64(0);
let weight_terms: Vec<Int> = x
.iter()
.zip(0..game.n())
.map(|(var, i)| var.ite(&Int::from_i64(game.weights[i]), &zero))
.collect();
let weight = weight_terms
.into_iter()
.fold(Int::from_i64(0), |acc, t| &acc + &t);
let mut solver = Solver::new();
solver.assert(weight.ge(&Int::from_i64(game.quota)));
for i in 0..game.n() {
let without_i = &weight - &Int::from_i64(game.weights[i]);
solver.assert(x[i].implies(without_i.lt(&Int::from_i64(game.quota))));
}
enumerate_models(&mut solver, &x)
.iter()
.map(|a| (0..game.n()).filter(|&i| a[i]).collect())
.collect()
}
struct Indices3 {
shapley_shubik: Vec<f64>,
banzhaf_normalise: Vec<f64>,
deegan_packel: Vec<f64>,
}
fn power_indices_smt(game: &VotingGame) -> (Indices3, Vec<Vec<usize>>) {
let n = game.n();
let by_size: Vec<Vec<i64>> = (0..n).map(|i| swing_sizes_smt(game, i)).collect();
let counts: Vec<i64> = by_size.iter().map(|v| v.iter().sum()).collect();
let total: i64 = counts.iter().sum();
let shapley: Vec<f64> = (0..n)
.map(|i| {
(0..n)
.map(|k| {
let coeff =
(factorial(k) * factorial(n - k - 1)) as f64 / factorial(n) as f64;
coeff * by_size[i][k] as f64
})
.fold(0.0f64, |acc, t| acc + t)
})
.collect();
let minimal = minimal_winning_smt(game);
let m = minimal.len() as f64;
let mut deegan = vec![0.0f64; n];
for i in 0..n {
let mut acc = 0.0f64;
for s in &minimal {
if s.contains(&i) {
acc += 1.0 / s.len() as f64;
}
}
deegan[i] = acc / m;
}
(
Indices3 {
shapley_shubik: shapley,
banzhaf_normalise: counts.iter().map(|c| *c as f64 / total as f64).collect(),
deegan_packel: deegan,
},
minimal,
)
}
fn max_abs_diff(a: &[f64], b: &[f64]) -> f64 {
a.iter().zip(b.iter()).map(|(&x, &y)| (x - y).abs()).fold(0.0f64, f64::max)
}
let example = VotingGame::new(vec![3, 2, 1], 4, &["A", "B", "C"]);
let (small_smt, small_mwcs) = power_indices_smt(&example);
let idx: Vec<String> = example.names.clone();
let rows: Vec<Vec<Cell>> = (0..example.n())
.map(|i| {
vec![
Cell::F(round_nf(small_smt.shapley_shubik[i], 4)),
Cell::F(round_nf(small_smt.banzhaf_normalise[i], 4)),
Cell::F(round_nf(small_smt.deegan_packel[i], 4)),
]
})
.collect();
print!(
"{}",
render_table(
Some(&idx),
&["shapley_shubik", "banzhaf_normalise", "deegan_packel"],
&rows
)
);
let mwc_names: Vec<Vec<String>> = small_mwcs
.iter()
.map(|s| s.iter().map(|&i| example.names[i].clone()).collect())
.collect();
let mwc_str = mwc_names.iter().map(|c| fmt_name_list(c)).collect::<Vec<_>>().join(", ");
println!("Modèles minimaux Z3 : [{}]", mwc_str); shapley_shubik banzhaf_normalise deegan_packel
A 0.6667 0.6 0.50
B 0.1667 0.2 0.25
C 0.1667 0.2 0.25
Modèles minimaux Z3 : [['A', 'C'], ['A', 'B']]
Les clauses de blocage ont retrouvé les deux mêmes coalitions minimales que l’énumération directe. Cette indépendance est relative : les deux voies partagent la définition mathématique du jeu, mais pas le mécanisme d’énumération. Leur accord détecte une classe utile d’erreurs d’implémentation ; il ne transforme pas le calcul en théorème général.
Comparer une seule instance peut masquer une erreur symétrique. Nous croisons donc trois structures : joueur dominant, jeu symétrique et jeu à quatre acteurs.
use z3::ast::{Ast, Bool, Int};
use z3::{SatResult, Solver};
use std::ops::{Add, Sub};
fn factorial(n: usize) -> i64 {
(1..=n as i64).product()
}
fn combinations_range(n: usize, k: usize) -> Vec<Vec<usize>> {
// Sous-ensembles de {0..n-1} de cardinal k, ordre lexicographique
// (meme ordre qu'itertools.combinations).
let mut result = Vec::new();
if k > n {
return result;
}
let mut c: Vec<usize> = (0..k).collect();
loop {
result.push(c.clone());
let mut i = k;
while i > 0 && c[i - 1] == n - k + i - 1 {
i -= 1;
}
if i == 0 {
break;
}
c[i - 1] += 1;
for j in i..k {
c[j] = c[j - 1] + 1;
}
}
result
}
fn all_coalitions(n: usize) -> Vec<Vec<usize>> {
// Par taille croissante puis ordre lexicographique.
(0..=n).flat_map(|k| combinations_range(n, k)).collect()
}
#[derive(Clone)]
struct VotingGame {
weights: Vec<i64>,
quota: i64,
names: Vec<String>,
}
impl VotingGame {
fn new(weights: Vec<i64>, quota: i64, names: &[&str]) -> VotingGame {
let names: Vec<String> = names.iter().map(|s| s.to_string()).collect();
let total: i64 = weights.iter().sum();
assert!(
weights.len() == names.len() && quota > 0 && quota <= total,
"Jeu pondere incoherent"
);
VotingGame { weights, quota, names }
}
fn n(&self) -> usize {
self.weights.len()
}
fn weight(&self, coalition: &[usize]) -> i64 {
coalition.iter().map(|&i| self.weights[i]).sum()
}
fn wins(&self, coalition: &[usize]) -> bool {
self.weight(coalition) >= self.quota
}
fn coalitions(&self) -> Vec<Vec<usize>> {
all_coalitions(self.n())
}
fn minimal_winning(&self) -> Vec<Vec<usize>> {
self.coalitions()
.into_iter()
.filter(|s| {
self.wins(s)
&& s.iter().all(|&i| {
let without: Vec<usize> =
s.iter().cloned().filter(|&j| j != i).collect();
!self.wins(&without)
})
})
.collect()
}
fn is_dummy(&self, i: usize) -> bool {
self.coalitions()
.into_iter()
.filter(|s| !s.contains(&i))
.all(|s| {
let mut with = s.clone();
with.push(i);
with.sort();
self.wins(&with) == self.wins(&s)
})
}
fn is_veto(&self, i: usize) -> bool {
let others: Vec<usize> = (0..self.n()).filter(|&j| j != i).collect();
!self.wins(&others)
}
fn is_dictator(&self, i: usize) -> bool {
self.wins(&[i]) && self.is_veto(i)
}
fn repr(&self) -> String {
let w = self.weights.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
let n = self.names.iter().map(|x| format!("'{}'", x)).collect::<Vec<_>>().join(", ");
format!("VotingGame(weights=({}), quota={}, names=({}))", w, self.quota, n)
}
}
fn py_bool(b: bool) -> &'static str {
if b { "True" } else { "False" }
}
fn fmt_f64_py(v: f64) -> String {
// Repr Python : toujours au moins une decimale ("1.0", jamais "1").
let s = format!("{}", v);
if s.contains('.') || s.contains('e') {
s
} else {
format!("{}.0", s)
}
}
fn py_repr_f64(v: f64) -> String {
fmt_f64_py(v)
}
fn round_nf(x: f64, d: i32) -> f64 {
// Equivalent de numpy.round : arrondi demi-pair au rang d.
let p = 10f64.powi(d);
let scaled = x * p;
let r = if (scaled - scaled.trunc()).abs() == 0.5 {
let t = scaled.trunc();
if t as i64 % 2 == 0 { t } else { t + scaled.signum() }
} else {
scaled.round()
};
r / p
}
enum Cell {
I(i64),
S(String),
F(f64),
Sci(f64),
}
fn fmt_sci(v: f64) -> String {
// Format exponentiel Python : mantisse .6, exposant signe + 2 chiffres.
let s = format!("{:.6e}", v);
let (mant, exp) = match s.split_once('e') {
Some(p) => p,
None => return s,
};
let e: i32 = exp.parse().unwrap_or(0);
if e < 0 {
format!("{}e-{:02}", mant, -e)
} else {
format!("{}e+{:02}", mant, e)
}
}
fn render_table(index: Option<&[String]>, headers: &[&str], rows: &[Vec<Cell>]) -> String {
// Reproduit le rendu pandas to_string : colonnes de valeurs alignees a
// droite, colonne d'index alignee a gauche, largeur = max(en-tete,
// valeurs) ; les colonnes flottantes partagent le nombre de decimales
// maximal de la colonne (alignement de la virgule). Sans index, pandas
// ajoute un espace fanteme en tete et joint par un seul espace.
let ncols = headers.len();
let mut col_dec = vec![0usize; ncols];
for row in rows {
for (c, cell) in row.iter().enumerate() {
if let Cell::F(v) = cell {
let s = fmt_f64_py(*v);
let d = s.find('.').map_or(0, |p| s.len() - p - 1);
if d > col_dec[c] {
col_dec[c] = d;
}
}
}
}
let mut lines: Vec<Vec<String>> = Vec::new();
let mut head: Vec<String> = Vec::new();
if index.is_some() {
head.push(String::new());
}
for h in headers {
head.push((*h).to_string());
}
lines.push(head);
for (r, row) in rows.iter().enumerate() {
let mut line: Vec<String> = Vec::new();
if let Some(idx) = index {
line.push(idx[r].clone());
}
for (c, cell) in row.iter().enumerate() {
line.push(match cell {
Cell::I(v) => v.to_string(),
Cell::S(v) => v.clone(),
Cell::F(v) => format!("{:.*}", col_dec[c], v),
Cell::Sci(v) => fmt_sci(*v),
});
}
lines.push(line);
}
let nfields = lines[0].len();
let mut widths = vec![0usize; nfields];
for line in &lines {
for (c, s) in line.iter().enumerate() {
let l = s.chars().count();
if l > widths[c] {
widths[c] = l;
}
}
}
let noindex = index.is_none();
let sep = if noindex { " " } else { " " };
let mut out = String::new();
for line in &lines {
let fields: Vec<String> = line
.iter()
.enumerate()
.map(|(c, s)| {
if c == 0 && !noindex {
format!("{:<w$}", s, w = widths[c])
} else {
format!("{:>w$}", s, w = widths[c])
}
})
.collect();
if noindex {
out.push(' ');
}
out.push_str(&fields.join(sep));
out.push('\n');
}
out
}
fn fmt_name_list(names: &[String]) -> String {
let inner = names.iter().map(|n| format!("'{}'", n)).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn fmt_int_list(v: &[usize]) -> String {
let inner = v.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn swing_counts(game: &VotingGame) -> Vec<i64> {
let mut counts = vec![0i64; game.n()];
for i in 0..game.n() {
for s in game.coalitions() {
if !s.contains(&i) && !game.wins(&s) {
let mut with = s.clone();
with.push(i);
with.sort();
if game.wins(&with) {
counts[i] += 1;
}
}
}
}
counts
}
struct Indices6 {
poids: Vec<i64>,
part_poids: Vec<f64>,
shapley_shubik: Vec<f64>,
banzhaf_absolu: Vec<f64>,
banzhaf_normalise: Vec<f64>,
deegan_packel: Vec<f64>,
}
fn power_indices_enumeration(game: &VotingGame) -> Indices6 {
let n = game.n();
let mut shapley = vec![0.0f64; n];
for i in 0..n {
let others: Vec<usize> = (0..n).filter(|&j| j != i).collect();
for size in 0..n {
let coefficient =
(factorial(size) * factorial(n - size - 1)) as f64 / factorial(n) as f64;
for idx in combinations_range(n - 1, size) {
let s: Vec<usize> = idx.iter().map(|&k| others[k]).collect();
let mut with = s.clone();
with.push(i);
with.sort();
let delta = (game.wins(&with) as i64 - game.wins(&s) as i64) as f64;
shapley[i] += coefficient * delta;
}
}
}
let swings = swing_counts(game);
let total: i64 = swings.iter().sum();
let total_weight: i64 = game.weights.iter().sum();
let minimal = game.minimal_winning();
let m = minimal.len() as f64;
let mut deegan = vec![0.0f64; n];
for i in 0..n {
let mut acc = 0.0f64;
for s in &minimal {
if s.contains(&i) {
acc += 1.0 / s.len() as f64;
}
}
deegan[i] = acc / m;
}
Indices6 {
poids: game.weights.clone(),
part_poids: game.weights.iter().map(|w| *w as f64 / total_weight as f64).collect(),
shapley_shubik: shapley,
banzhaf_absolu: swings.iter().map(|c| *c as f64 / 2f64.powi(n as i32 - 1)).collect(),
banzhaf_normalise: swings.iter().map(|c| *c as f64 / total as f64).collect(),
deegan_packel: deegan,
}
}
fn sat_str(r: SatResult) -> &'static str {
match r {
SatResult::Sat => "sat",
SatResult::Unsat => "unsat",
_ => "unknown",
}
}
fn enumerate_models(solver: &mut Solver, variables: &[Bool]) -> Vec<Vec<bool>> {
// Enumeration de modeles SMT avec clause de blocage apres chaque modele.
let mut found = Vec::new();
while solver.check() == SatResult::Sat {
let model = match solver.get_model() {
Some(m) => m,
None => break,
};
let assignment: Vec<bool> = variables
.iter()
.map(|x| match model.eval(x, true) {
Some(v) => v.as_bool().unwrap_or(false),
None => false,
})
.collect();
found.push(assignment.clone());
let blockers: Vec<Bool> = variables
.iter()
.zip(assignment.iter())
.map(|(x, &v)| x.ne(&Bool::from_bool(v)))
.collect();
solver.assert(Bool::or(&blockers));
}
found
}
fn swing_sizes_smt(game: &VotingGame, player: usize) -> Vec<i64> {
// Par taille de coalition (indice du vecteur) : nombre de modeles pivots.
let others: Vec<usize> = (0..game.n()).filter(|&i| i != player).collect();
let x: Vec<Bool> = others
.iter()
.map(|&i| Bool::new_const(format!("s_{}_{}", player, i)))
.collect();
let zero = Int::from_i64(0);
let weight_terms: Vec<Int> = x
.iter()
.zip(others.iter())
.map(|(var, &i)| var.ite(&Int::from_i64(game.weights[i]), &zero))
.collect();
let weight = weight_terms
.into_iter()
.fold(Int::from_i64(0), |acc, t| &acc + &t);
let mut solver = Solver::new();
solver.assert(weight.lt(&Int::from_i64(game.quota)));
solver.assert((&weight + &Int::from_i64(game.weights[player])).ge(&Int::from_i64(game.quota)));
let mut sizes = vec![0i64; game.n()];
for assignment in enumerate_models(&mut solver, &x) {
let size = assignment.iter().filter(|&&b| b).count();
sizes[size] += 1;
}
sizes
}
fn minimal_winning_smt(game: &VotingGame) -> Vec<Vec<usize>> {
let x: Vec<Bool> = (0..game.n()).map(|i| Bool::new_const(format!("m_{}", i))).collect();
let zero = Int::from_i64(0);
let weight_terms: Vec<Int> = x
.iter()
.zip(0..game.n())
.map(|(var, i)| var.ite(&Int::from_i64(game.weights[i]), &zero))
.collect();
let weight = weight_terms
.into_iter()
.fold(Int::from_i64(0), |acc, t| &acc + &t);
let mut solver = Solver::new();
solver.assert(weight.ge(&Int::from_i64(game.quota)));
for i in 0..game.n() {
let without_i = &weight - &Int::from_i64(game.weights[i]);
solver.assert(x[i].implies(without_i.lt(&Int::from_i64(game.quota))));
}
enumerate_models(&mut solver, &x)
.iter()
.map(|a| (0..game.n()).filter(|&i| a[i]).collect())
.collect()
}
struct Indices3 {
shapley_shubik: Vec<f64>,
banzhaf_normalise: Vec<f64>,
deegan_packel: Vec<f64>,
}
fn power_indices_smt(game: &VotingGame) -> (Indices3, Vec<Vec<usize>>) {
let n = game.n();
let by_size: Vec<Vec<i64>> = (0..n).map(|i| swing_sizes_smt(game, i)).collect();
let counts: Vec<i64> = by_size.iter().map(|v| v.iter().sum()).collect();
let total: i64 = counts.iter().sum();
let shapley: Vec<f64> = (0..n)
.map(|i| {
(0..n)
.map(|k| {
let coeff =
(factorial(k) * factorial(n - k - 1)) as f64 / factorial(n) as f64;
coeff * by_size[i][k] as f64
})
.fold(0.0f64, |acc, t| acc + t)
})
.collect();
let minimal = minimal_winning_smt(game);
let m = minimal.len() as f64;
let mut deegan = vec![0.0f64; n];
for i in 0..n {
let mut acc = 0.0f64;
for s in &minimal {
if s.contains(&i) {
acc += 1.0 / s.len() as f64;
}
}
deegan[i] = acc / m;
}
(
Indices3 {
shapley_shubik: shapley,
banzhaf_normalise: counts.iter().map(|c| *c as f64 / total as f64).collect(),
deegan_packel: deegan,
},
minimal,
)
}
fn max_abs_diff(a: &[f64], b: &[f64]) -> f64 {
a.iter().zip(b.iter()).map(|(&x, &y)| (x - y).abs()).fold(0.0f64, f64::max)
}
let games = vec![
VotingGame::new(vec![3, 2, 1], 4, &["A", "B", "C"]),
VotingGame::new(vec![1, 1, 1], 2, &["X", "Y", "Z"]),
VotingGame::new(vec![5, 3, 2, 1], 6, &["P", "Q", "R", "S"]),
];
let index_names = ["shapley_shubik", "banzhaf_normalise", "deegan_packel"];
let mut rows: Vec<Vec<Cell>> = Vec::new();
let mut all_ecarts: Vec<f64> = Vec::new();
for (game_id, game) in games.iter().enumerate() {
let py = power_indices_enumeration(game);
let (smt, _) = power_indices_smt(game);
let py_cols = [
py.shapley_shubik.clone(),
py.banzhaf_normalise.clone(),
py.deegan_packel.clone(),
];
let smt_cols = [
smt.shapley_shubik.clone(),
smt.banzhaf_normalise.clone(),
smt.deegan_packel.clone(),
];
for (k, name) in index_names.iter().enumerate() {
let ecart = max_abs_diff(&py_cols[k], &smt_cols[k]);
all_ecarts.push(ecart);
rows.push(vec![
Cell::I(game_id as i64 + 1),
Cell::S(name.to_string()),
Cell::Sci(ecart),
]);
}
}
print!("{}", render_table(None, &["jeu", "indice", "ecart_max"], &rows));
let ecart_global = all_ecarts.iter().fold(0.0f64, |a, b| a.max(*b));
assert!(ecart_global < 1e-12);
println!("Cross-validation réussie : 3 jeux, 3 indices, écart maximal < 1e-12"); jeu indice ecart_max
1 shapley_shubik 0.000000e+00
1 banzhaf_normalise 0.000000e+00
1 deegan_packel 0.000000e+00
2 shapley_shubik 0.000000e+00
2 banzhaf_normalise 0.000000e+00
2 deegan_packel 0.000000e+00
3 shapley_shubik 5.551115e-17
3 banzhaf_normalise 0.000000e+00
3 deegan_packel 0.000000e+00
Cross-validation réussie : 3 jeux, 3 indices, écart maximal < 1e-12
L’écart affiché est nul à la précision flottante utilisée. Il s’agit d’un test différentiel sur neuf couples jeu/indice, pas d’une preuve universelle. L’espace exploré reste fini et choisi.
Enonce. Construire un VotingGame dont un joueur a un pouvoir nul — aucune coalition ou son poids fait basculer le resultat — puis calculer les indices par les deux voies, énumération directe et SMT, et verifier qu’elles s’accordent sur ce joueur.
Resolution (exemple guide, contribution agentique). Le jeu choisi est \([10;5,3,2,1]\) : le quota est cale a la somme exacte \(5+3+2\), donc seule la coalition complete des trois gros joueurs gagne. Le petit joueur D (poids 1) ne franchit jamais le seuil : son poids ne fait basculer aucune coalition, son pouvoir est nul. Les deux voies de calcul ci-dessous affichent 0 pour D, et les trois autres joueurs recoivent exactement les memes indices.
Pourquoi D est nul. Une coalition qui ne contient pas D a un poids parmi les sous-totaux de \(\{5,3,2\}\) ; la seule qui atteigne \(10\) est \(\{A,B,C\}\). Ajouter D ne change donc jamais le statut d’une coalition : il n’est pivot nulle part.
use z3::ast::{Ast, Bool, Int};
use z3::{SatResult, Solver};
use std::ops::{Add, Sub};
fn factorial(n: usize) -> i64 {
(1..=n as i64).product()
}
fn combinations_range(n: usize, k: usize) -> Vec<Vec<usize>> {
// Sous-ensembles de {0..n-1} de cardinal k, ordre lexicographique
// (meme ordre qu'itertools.combinations).
let mut result = Vec::new();
if k > n {
return result;
}
let mut c: Vec<usize> = (0..k).collect();
loop {
result.push(c.clone());
let mut i = k;
while i > 0 && c[i - 1] == n - k + i - 1 {
i -= 1;
}
if i == 0 {
break;
}
c[i - 1] += 1;
for j in i..k {
c[j] = c[j - 1] + 1;
}
}
result
}
fn all_coalitions(n: usize) -> Vec<Vec<usize>> {
// Par taille croissante puis ordre lexicographique.
(0..=n).flat_map(|k| combinations_range(n, k)).collect()
}
#[derive(Clone)]
struct VotingGame {
weights: Vec<i64>,
quota: i64,
names: Vec<String>,
}
impl VotingGame {
fn new(weights: Vec<i64>, quota: i64, names: &[&str]) -> VotingGame {
let names: Vec<String> = names.iter().map(|s| s.to_string()).collect();
let total: i64 = weights.iter().sum();
assert!(
weights.len() == names.len() && quota > 0 && quota <= total,
"Jeu pondere incoherent"
);
VotingGame { weights, quota, names }
}
fn n(&self) -> usize {
self.weights.len()
}
fn weight(&self, coalition: &[usize]) -> i64 {
coalition.iter().map(|&i| self.weights[i]).sum()
}
fn wins(&self, coalition: &[usize]) -> bool {
self.weight(coalition) >= self.quota
}
fn coalitions(&self) -> Vec<Vec<usize>> {
all_coalitions(self.n())
}
fn minimal_winning(&self) -> Vec<Vec<usize>> {
self.coalitions()
.into_iter()
.filter(|s| {
self.wins(s)
&& s.iter().all(|&i| {
let without: Vec<usize> =
s.iter().cloned().filter(|&j| j != i).collect();
!self.wins(&without)
})
})
.collect()
}
fn is_dummy(&self, i: usize) -> bool {
self.coalitions()
.into_iter()
.filter(|s| !s.contains(&i))
.all(|s| {
let mut with = s.clone();
with.push(i);
with.sort();
self.wins(&with) == self.wins(&s)
})
}
fn is_veto(&self, i: usize) -> bool {
let others: Vec<usize> = (0..self.n()).filter(|&j| j != i).collect();
!self.wins(&others)
}
fn is_dictator(&self, i: usize) -> bool {
self.wins(&[i]) && self.is_veto(i)
}
fn repr(&self) -> String {
let w = self.weights.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
let n = self.names.iter().map(|x| format!("'{}'", x)).collect::<Vec<_>>().join(", ");
format!("VotingGame(weights=({}), quota={}, names=({}))", w, self.quota, n)
}
}
fn py_bool(b: bool) -> &'static str {
if b { "True" } else { "False" }
}
fn fmt_f64_py(v: f64) -> String {
// Repr Python : toujours au moins une decimale ("1.0", jamais "1").
let s = format!("{}", v);
if s.contains('.') || s.contains('e') {
s
} else {
format!("{}.0", s)
}
}
fn py_repr_f64(v: f64) -> String {
fmt_f64_py(v)
}
fn round_nf(x: f64, d: i32) -> f64 {
// Equivalent de numpy.round : arrondi demi-pair au rang d.
let p = 10f64.powi(d);
let scaled = x * p;
let r = if (scaled - scaled.trunc()).abs() == 0.5 {
let t = scaled.trunc();
if t as i64 % 2 == 0 { t } else { t + scaled.signum() }
} else {
scaled.round()
};
r / p
}
enum Cell {
I(i64),
S(String),
F(f64),
Sci(f64),
}
fn fmt_sci(v: f64) -> String {
// Format exponentiel Python : mantisse .6, exposant signe + 2 chiffres.
let s = format!("{:.6e}", v);
let (mant, exp) = match s.split_once('e') {
Some(p) => p,
None => return s,
};
let e: i32 = exp.parse().unwrap_or(0);
if e < 0 {
format!("{}e-{:02}", mant, -e)
} else {
format!("{}e+{:02}", mant, e)
}
}
fn render_table(index: Option<&[String]>, headers: &[&str], rows: &[Vec<Cell>]) -> String {
// Reproduit le rendu pandas to_string : colonnes de valeurs alignees a
// droite, colonne d'index alignee a gauche, largeur = max(en-tete,
// valeurs) ; les colonnes flottantes partagent le nombre de decimales
// maximal de la colonne (alignement de la virgule). Sans index, pandas
// ajoute un espace fanteme en tete et joint par un seul espace.
let ncols = headers.len();
let mut col_dec = vec![0usize; ncols];
for row in rows {
for (c, cell) in row.iter().enumerate() {
if let Cell::F(v) = cell {
let s = fmt_f64_py(*v);
let d = s.find('.').map_or(0, |p| s.len() - p - 1);
if d > col_dec[c] {
col_dec[c] = d;
}
}
}
}
let mut lines: Vec<Vec<String>> = Vec::new();
let mut head: Vec<String> = Vec::new();
if index.is_some() {
head.push(String::new());
}
for h in headers {
head.push((*h).to_string());
}
lines.push(head);
for (r, row) in rows.iter().enumerate() {
let mut line: Vec<String> = Vec::new();
if let Some(idx) = index {
line.push(idx[r].clone());
}
for (c, cell) in row.iter().enumerate() {
line.push(match cell {
Cell::I(v) => v.to_string(),
Cell::S(v) => v.clone(),
Cell::F(v) => format!("{:.*}", col_dec[c], v),
Cell::Sci(v) => fmt_sci(*v),
});
}
lines.push(line);
}
let nfields = lines[0].len();
let mut widths = vec![0usize; nfields];
for line in &lines {
for (c, s) in line.iter().enumerate() {
let l = s.chars().count();
if l > widths[c] {
widths[c] = l;
}
}
}
let noindex = index.is_none();
let sep = if noindex { " " } else { " " };
let mut out = String::new();
for line in &lines {
let fields: Vec<String> = line
.iter()
.enumerate()
.map(|(c, s)| {
if c == 0 && !noindex {
format!("{:<w$}", s, w = widths[c])
} else {
format!("{:>w$}", s, w = widths[c])
}
})
.collect();
if noindex {
out.push(' ');
}
out.push_str(&fields.join(sep));
out.push('\n');
}
out
}
fn fmt_name_list(names: &[String]) -> String {
let inner = names.iter().map(|n| format!("'{}'", n)).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn fmt_int_list(v: &[usize]) -> String {
let inner = v.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn swing_counts(game: &VotingGame) -> Vec<i64> {
let mut counts = vec![0i64; game.n()];
for i in 0..game.n() {
for s in game.coalitions() {
if !s.contains(&i) && !game.wins(&s) {
let mut with = s.clone();
with.push(i);
with.sort();
if game.wins(&with) {
counts[i] += 1;
}
}
}
}
counts
}
struct Indices6 {
poids: Vec<i64>,
part_poids: Vec<f64>,
shapley_shubik: Vec<f64>,
banzhaf_absolu: Vec<f64>,
banzhaf_normalise: Vec<f64>,
deegan_packel: Vec<f64>,
}
fn power_indices_enumeration(game: &VotingGame) -> Indices6 {
let n = game.n();
let mut shapley = vec![0.0f64; n];
for i in 0..n {
let others: Vec<usize> = (0..n).filter(|&j| j != i).collect();
for size in 0..n {
let coefficient =
(factorial(size) * factorial(n - size - 1)) as f64 / factorial(n) as f64;
for idx in combinations_range(n - 1, size) {
let s: Vec<usize> = idx.iter().map(|&k| others[k]).collect();
let mut with = s.clone();
with.push(i);
with.sort();
let delta = (game.wins(&with) as i64 - game.wins(&s) as i64) as f64;
shapley[i] += coefficient * delta;
}
}
}
let swings = swing_counts(game);
let total: i64 = swings.iter().sum();
let total_weight: i64 = game.weights.iter().sum();
let minimal = game.minimal_winning();
let m = minimal.len() as f64;
let mut deegan = vec![0.0f64; n];
for i in 0..n {
let mut acc = 0.0f64;
for s in &minimal {
if s.contains(&i) {
acc += 1.0 / s.len() as f64;
}
}
deegan[i] = acc / m;
}
Indices6 {
poids: game.weights.clone(),
part_poids: game.weights.iter().map(|w| *w as f64 / total_weight as f64).collect(),
shapley_shubik: shapley,
banzhaf_absolu: swings.iter().map(|c| *c as f64 / 2f64.powi(n as i32 - 1)).collect(),
banzhaf_normalise: swings.iter().map(|c| *c as f64 / total as f64).collect(),
deegan_packel: deegan,
}
}
fn sat_str(r: SatResult) -> &'static str {
match r {
SatResult::Sat => "sat",
SatResult::Unsat => "unsat",
_ => "unknown",
}
}
fn enumerate_models(solver: &mut Solver, variables: &[Bool]) -> Vec<Vec<bool>> {
// Enumeration de modeles SMT avec clause de blocage apres chaque modele.
let mut found = Vec::new();
while solver.check() == SatResult::Sat {
let model = match solver.get_model() {
Some(m) => m,
None => break,
};
let assignment: Vec<bool> = variables
.iter()
.map(|x| match model.eval(x, true) {
Some(v) => v.as_bool().unwrap_or(false),
None => false,
})
.collect();
found.push(assignment.clone());
let blockers: Vec<Bool> = variables
.iter()
.zip(assignment.iter())
.map(|(x, &v)| x.ne(&Bool::from_bool(v)))
.collect();
solver.assert(Bool::or(&blockers));
}
found
}
fn swing_sizes_smt(game: &VotingGame, player: usize) -> Vec<i64> {
// Par taille de coalition (indice du vecteur) : nombre de modeles pivots.
let others: Vec<usize> = (0..game.n()).filter(|&i| i != player).collect();
let x: Vec<Bool> = others
.iter()
.map(|&i| Bool::new_const(format!("s_{}_{}", player, i)))
.collect();
let zero = Int::from_i64(0);
let weight_terms: Vec<Int> = x
.iter()
.zip(others.iter())
.map(|(var, &i)| var.ite(&Int::from_i64(game.weights[i]), &zero))
.collect();
let weight = weight_terms
.into_iter()
.fold(Int::from_i64(0), |acc, t| &acc + &t);
let mut solver = Solver::new();
solver.assert(weight.lt(&Int::from_i64(game.quota)));
solver.assert((&weight + &Int::from_i64(game.weights[player])).ge(&Int::from_i64(game.quota)));
let mut sizes = vec![0i64; game.n()];
for assignment in enumerate_models(&mut solver, &x) {
let size = assignment.iter().filter(|&&b| b).count();
sizes[size] += 1;
}
sizes
}
fn minimal_winning_smt(game: &VotingGame) -> Vec<Vec<usize>> {
let x: Vec<Bool> = (0..game.n()).map(|i| Bool::new_const(format!("m_{}", i))).collect();
let zero = Int::from_i64(0);
let weight_terms: Vec<Int> = x
.iter()
.zip(0..game.n())
.map(|(var, i)| var.ite(&Int::from_i64(game.weights[i]), &zero))
.collect();
let weight = weight_terms
.into_iter()
.fold(Int::from_i64(0), |acc, t| &acc + &t);
let mut solver = Solver::new();
solver.assert(weight.ge(&Int::from_i64(game.quota)));
for i in 0..game.n() {
let without_i = &weight - &Int::from_i64(game.weights[i]);
solver.assert(x[i].implies(without_i.lt(&Int::from_i64(game.quota))));
}
enumerate_models(&mut solver, &x)
.iter()
.map(|a| (0..game.n()).filter(|&i| a[i]).collect())
.collect()
}
struct Indices3 {
shapley_shubik: Vec<f64>,
banzhaf_normalise: Vec<f64>,
deegan_packel: Vec<f64>,
}
fn power_indices_smt(game: &VotingGame) -> (Indices3, Vec<Vec<usize>>) {
let n = game.n();
let by_size: Vec<Vec<i64>> = (0..n).map(|i| swing_sizes_smt(game, i)).collect();
let counts: Vec<i64> = by_size.iter().map(|v| v.iter().sum()).collect();
let total: i64 = counts.iter().sum();
let shapley: Vec<f64> = (0..n)
.map(|i| {
(0..n)
.map(|k| {
let coeff =
(factorial(k) * factorial(n - k - 1)) as f64 / factorial(n) as f64;
coeff * by_size[i][k] as f64
})
.fold(0.0f64, |acc, t| acc + t)
})
.collect();
let minimal = minimal_winning_smt(game);
let m = minimal.len() as f64;
let mut deegan = vec![0.0f64; n];
for i in 0..n {
let mut acc = 0.0f64;
for s in &minimal {
if s.contains(&i) {
acc += 1.0 / s.len() as f64;
}
}
deegan[i] = acc / m;
}
(
Indices3 {
shapley_shubik: shapley,
banzhaf_normalise: counts.iter().map(|c| *c as f64 / total as f64).collect(),
deegan_packel: deegan,
},
minimal,
)
}
fn max_abs_diff(a: &[f64], b: &[f64]) -> f64 {
a.iter().zip(b.iter()).map(|(&x, &y)| (x - y).abs()).fold(0.0f64, f64::max)
}
// Exemple guide resolu : le jeu [10; 5, 3, 2, 1], D est le joueur nul.
let dummy_game = VotingGame::new(vec![5, 3, 2, 1], 10, &["A", "B", "C", "D"]);
// Etape 1 : indices par la voie enumeration (parcours explicite des coalitions).
let python_table = power_indices_enumeration(&dummy_game);
println!("Indices énumération :");
let idx: Vec<String> = dummy_game.names.clone();
let rows_py: Vec<Vec<Cell>> = (0..dummy_game.n())
.map(|i| {
vec![
Cell::I(python_table.poids[i]),
Cell::F(round_nf(python_table.part_poids[i], 6)),
Cell::F(round_nf(python_table.shapley_shubik[i], 6)),
Cell::F(round_nf(python_table.banzhaf_absolu[i], 6)),
Cell::F(round_nf(python_table.banzhaf_normalise[i], 6)),
Cell::F(round_nf(python_table.deegan_packel[i], 6)),
]
})
.collect();
print!(
"{}",
render_table(
Some(&idx),
&["poids", "part_poids", "shapley_shubik", "banzhaf_absolu", "banzhaf_normalise", "deegan_packel"],
&rows_py
)
);
// Etape 2 : indices par la voie SMT (enumeration des modeles Z3).
let (smt_table, smt_minimal) = power_indices_smt(&dummy_game);
println!("\nIndices SMT :");
let rows_smt: Vec<Vec<Cell>> = (0..dummy_game.n())
.map(|i| {
vec![
Cell::F(round_nf(smt_table.shapley_shubik[i], 6)),
Cell::F(round_nf(smt_table.banzhaf_normalise[i], 6)),
Cell::F(round_nf(smt_table.deegan_packel[i], 6)),
]
})
.collect();
print!(
"{}",
render_table(
Some(&idx),
&["shapley_shubik", "banzhaf_normalise", "deegan_packel"],
&rows_smt
)
);
let mwc_names: Vec<Vec<String>> = smt_minimal
.iter()
.map(|s| {
let mut names: Vec<String> = s.iter().map(|&i| dummy_game.names[i].clone()).collect();
names.sort();
names
})
.collect();
let mwc_str = mwc_names.iter().map(|c| fmt_name_list(c)).collect::<Vec<_>>().join(", ");
println!("Coalitions minimales gagnantes (SMT) : [{}]", mwc_str);
// Etape 3 : le joueur nul D vaut 0 des deux cotes, et les deux voies s'accordent.
let di = dummy_game.n() - 1;
let pairs = [
(
"shapley_shubik",
python_table.shapley_shubik.clone(),
smt_table.shapley_shubik.clone(),
),
(
"banzhaf_normalise",
python_table.banzhaf_normalise.clone(),
smt_table.banzhaf_normalise.clone(),
),
(
"deegan_packel",
python_table.deegan_packel.clone(),
smt_table.deegan_packel.clone(),
),
];
for (indice, py_v, smt_v) in pairs.iter() {
let ecart = max_abs_diff(py_v, smt_v);
assert!(ecart < 1e-12, "les deux voies divergent sur {}", indice);
}
assert!(python_table.shapley_shubik[di].abs() < 1e-12);
assert!(smt_table.shapley_shubik[di].abs() < 1e-12);
assert!(python_table.banzhaf_normalise[di].abs() < 1e-12);
assert!(smt_table.banzhaf_normalise[di].abs() < 1e-12);
println!("\nJoueur nul D : Shapley-Shubik = 0 et Banzhaf normalise = 0 dans les deux tables.");
println!("Concordance exacte des deux voies (ecart maximal < 1e-12 sur les trois indices).");Indices énumération :
poids part_poids shapley_shubik banzhaf_absolu banzhaf_normalise deegan_packel
A 5 0.454545 0.333333 0.25 0.333333 0.333333
B 3 0.272727 0.333333 0.25 0.333333 0.333333
C 2 0.181818 0.333333 0.25 0.333333 0.333333
D 1 0.090909 0.000000 0.00 0.000000 0.000000
Indices SMT :
shapley_shubik banzhaf_normalise deegan_packel
A 0.333333 0.333333 0.333333
B 0.333333 0.333333 0.333333
C 0.333333 0.333333 0.333333
D 0.000000 0.000000 0.000000
Coalitions minimales gagnantes (SMT) : [['A', 'B', 'C']]
Joueur nul D : Shapley-Shubik = 0 et Banzhaf normalise = 0 dans les deux tables.
Concordance exacte des deux voies (ecart maximal < 1e-12 sur les trois indices).
D porte \(1/11 \approx 9,1\,\%\) du poids total, et pourtant ses trois indices valent exactement \(0\) : c’est l’oppose du jeu [4;3,2,1] du debut, ou C avait un poids de \(16,7\,\%\) et un pouvoir non nul. La lecon est que le pouvoir depend de la position par rapport au quota, pas du poids seul : ici le quota \(10\) est cale exactement sur \(5+3+2\), et le point de D ne sert a rien. Les trois gros joueurs partagent le pouvoir a parts egales (\(1/3\) chacun) alors que leurs poids sont inegaux — la symetrie vient de ce qu’aucun sous-ensemble propre d’entre eux ne gagne, donc ils sont interchangeables comme pivots.
Objectif : construire un VotingGame a quatre joueurs dont l’un est un dictateur — il gagne seul, sans aucun allie — puis verifier que tous les autres joueurs ont un pouvoir nul et que les deux voies s’accordent.
Etapes.
A atteint le quota sans les autres).power_indices_enumeration et power_indices_smt sur ce jeu.1 a Shapley-Shubik et a Banzhaf normalise, et que les trois autres valent 0 des deux cotes.// TODO étudiant : dictator_game = VotingGame::new(vec![...], quota, &["A", "B", "C", "D"]) avec A dictateur.
// Etape 1 : calculer les indices par la voie enumeration (power_indices_enumeration).
// Etape 2 : calculer les indices SMT (power_indices_smt).
// Etape 3 : verifier A = 1 et les autres = 0 dans les deux tables.
println!("Exercice 2 bis a completer : construire un jeu a dictateur");Exercice 2 bis a completer : construire un jeu a dictateur
UNSAT prouve quoi ? SAT réfute quoi ?Pour un nombre fixé de joueurs, on peut rendre chaque valeur coalitionnelle \(v(S)\) symbolique, imposer \(v(\varnothing)=0\), \(v(N)=1\), la monotonie et des valeurs binaires. Ajouter la négation d’un axiome permet alors :
UNSAT : aucun jeu dans cet espace borné ne viole la propriété ;SAT : le modèle retourné est un contre-exemple dans cet espace.La cellule vérifie l’efficacité de Shapley-Shubik pour quatre joueurs et demande simultanément à Z3 un contre-exemple à l’efficacité du Banzhaf absolu pour trois joueurs.
Portage Rust : l’arithmétique rationnelle du carnet Python (RealVal) devient un encodage entier équivalent — chaque expression est multipliée par son dénominateur commun (n! pour Shapley-Shubik, 2^(n-1) pour Banzhaf absolu) ; les statuts sat/unsat sont inchangés.
use z3::ast::{Ast, Bool, Int};
use z3::{SatResult, Solver};
use std::ops::{Add, Mul, Sub};
fn factorial(n: usize) -> i64 {
(1..=n as i64).product()
}
fn combinations_range(n: usize, k: usize) -> Vec<Vec<usize>> {
// Sous-ensembles de {0..n-1} de cardinal k, ordre lexicographique
// (meme ordre qu'itertools.combinations).
let mut result = Vec::new();
if k > n {
return result;
}
let mut c: Vec<usize> = (0..k).collect();
loop {
result.push(c.clone());
let mut i = k;
while i > 0 && c[i - 1] == n - k + i - 1 {
i -= 1;
}
if i == 0 {
break;
}
c[i - 1] += 1;
for j in i..k {
c[j] = c[j - 1] + 1;
}
}
result
}
fn all_coalitions(n: usize) -> Vec<Vec<usize>> {
// Par taille croissante puis ordre lexicographique.
(0..=n).flat_map(|k| combinations_range(n, k)).collect()
}
fn fmt_int_list(v: &[usize]) -> String {
let inner = v.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn all_masks(n: usize) -> Vec<usize> {
// Masques de sous-ensembles par taille croissante puis ordre lexicographique.
(0..=n)
.flat_map(|k| combinations_range(n, k))
.map(|c| c.iter().map(|&i| 1usize << i).sum())
.collect()
}
fn simple_game_constraints(values: &[Int], n: usize) -> Vec<Bool> {
let zero = Int::from_i64(0);
let one = Int::from_i64(1);
let mut constraints = Vec::new();
constraints.push(values[0].eq(&zero));
constraints.push(values[(1usize << n) - 1].eq(&one));
for v in values.iter() {
constraints.push(Bool::or(&[v.eq(&zero), v.eq(&one)]));
}
for s in 0..(1usize << n) {
for i in 0..n {
if s & (1 << i) == 0 {
// monotonie : S inclus dans S u {i} => v(S) <= v(S u {i})
constraints.push(values[s].le(&values[s | (1 << i)]));
}
}
}
constraints
}
fn shapley_scaled(values: &[Int], n: usize, player: usize) -> Int {
// Shapley-Shubik multiplie par n! : chaque terme (v(S U {i}) - v(S))
// pondere par k!(n-k-1)!.
let others: Vec<usize> = (0..n).filter(|&i| i != player).collect();
let mut terms: Vec<Int> = Vec::new();
for k in 0..n {
let coeff = factorial(k) * factorial(n - k - 1);
for subset in combinations_range(n - 1, k) {
let s_mask: usize = subset.iter().map(|&j| 1usize << others[j]).sum();
let with = &values[s_mask | (1usize << player)];
let without = &values[s_mask];
terms.push(&Int::from_i64(coeff) * &(with - without));
}
}
terms.into_iter().fold(Int::from_i64(0), |acc, t| &acc + &t)
}
fn banzhaf_scaled(values: &[Int], n: usize, player: usize) -> Int {
// Banzhaf absolu multiplie par 2^(n-1) : somme des contributions marginales.
let others: Vec<usize> = (0..n).filter(|&i| i != player).collect();
let mut terms: Vec<Int> = Vec::new();
for k in 0..n {
for subset in combinations_range(n - 1, k) {
let s_mask: usize = subset.iter().map(|&j| 1usize << others[j]).sum();
terms.push(&values[s_mask | (1usize << player)] - &values[s_mask]);
}
}
terms.into_iter().fold(Int::from_i64(0), |acc, t| &acc + &t)
}
fn sat_str(r: SatResult) -> &'static str {
match r {
SatResult::Sat => "sat",
SatResult::Unsat => "unsat",
_ => "unknown",
}
}
let n4 = 4usize;
let v4: Vec<Int> = (0..(1usize << n4)).map(|m| Int::new_const(format!("v4_{}", m))).collect();
let constraints4 = simple_game_constraints(&v4, n4);
let mut proof = Solver::new();
for c in &constraints4 {
proof.assert(c.clone());
}
let total4: Int = (0..n4)
.map(|i| shapley_scaled(&v4, n4, i))
.collect::<Vec<_>>()
.into_iter()
.fold(Int::from_i64(0), |acc, t| &acc + &t);
proof.assert(total4.ne(&Int::from_i64(factorial(n4))));
let n3 = 3usize;
let v3: Vec<Int> = (0..(1usize << n3)).map(|m| Int::new_const(format!("v3_{}", m))).collect();
let constraints3 = simple_game_constraints(&v3, n3);
let mut counterexample = Solver::new();
for c in &constraints3 {
counterexample.assert(c.clone());
}
let total3: Int = (0..n3)
.map(|i| banzhaf_scaled(&v3, n3, i))
.collect::<Vec<_>>()
.into_iter()
.fold(Int::from_i64(0), |acc, t| &acc + &t);
counterexample.assert(total3.ne(&Int::from_i64(1i64 << (n3 - 1))));
let proof_status = proof.check();
let ce_status = counterexample.check();
let winning: Vec<Vec<usize>> = if ce_status == SatResult::Sat {
match counterexample.get_model() {
Some(model) => all_masks(n3)
.into_iter()
.filter(|&m| match model.eval(&v3[m], true) {
Some(val) => matches!(val.as_i64(), Some(1)),
None => false,
})
.map(|m| (0..n3).filter(|&i| m & (1 << i) != 0).collect())
.collect(),
None => Vec::new(),
}
} else {
Vec::new()
};
println!("Efficacité Shapley-Shubik, n=4, négation : {}", sat_str(proof_status));
println!("Efficacité Banzhaf absolu, n=3, négation : {}", sat_str(ce_status));
let winning_str = winning.iter().map(|c| fmt_int_list(c)).collect::<Vec<_>>().join(", ");
println!("Contre-exemple SAT — coalitions gagnantes : [{}]", winning_str);
assert!(proof_status == SatResult::Unsat && ce_status == SatResult::Sat);Efficacité Shapley-Shubik, n=4, négation : unsat
Efficacité Banzhaf absolu, n=3, négation : sat
Contre-exemple SAT — coalitions gagnantes : [[0, 1], [0, 2], [1, 2], [0, 1, 2]]
| Résultat | Statut honnête |
|---|---|
| Indices calculés dans les cellules précédentes | calcul exact sur une instance finie |
Négation Shapley UNSAT pour n=4 |
vérification SMT bornée aux jeux simples monotones à quatre joueurs |
Modèle Banzhaf SAT |
contre-exemple général suffisant pour réfuter l’axiome |
Unicité de Shapley dans game_theory_lean/CooperativeGames/Shapley.lean |
théorème formel général du corpus CoursIA |
Le passage du borné au général n’est pas automatique. Le module Lean établit la caractérisation axiomatique de Shapley ; cette explication est un élargissement CoursIA apporté après la soutenance, et non une revendication des étudiants.
Objectif : ajouter à un solveur deux joueurs interchangeables, puis chercher un modèle où leurs valeurs de Shapley-Shubik diffèrent.
Indice : pour chaque coalition ne contenant ni 0 ni 1, contraindre v(S ∪ {0}) == v(S ∪ {1}), puis ajouter l’inégalité des deux expressions.
// TODO étudiant : symmetry_status = solveur avec joueurs 0 et 1 interchangeables.
// Étape 1 : reprendre l'encodage des jeux simples (variables v par sous-ensemble).
// Étape 2 : imposer l'interchangeabilité des joueurs 0 et 1 (v(S U {0}) == v(S U {1})).
// Étape 3 : ajouter la négation de l'égalité des deux indices, puis check().
println!("Exercice 3 à compléter : statut attendu UNSAT, à vérifier pour n fixé");Exercice 3 à compléter : statut attendu UNSAT, à vérifier pour n fixé
Ilias Kalalou a étudié les groupes de la XVIIe législature ; nous reprenons ici les effectifs stabilisés à l’automne 2024 cités par le projet source. Le quota est 289 sur 577 sièges. Chaque groupe est traité comme un acteur unitaire — hypothèse forte, explicitement reconnue pendant la soutenance.
Un indice décrit les bascules possibles dans ce modèle. Un vote réel unique ne permet pas d’estimer une fréquence empirique de pivot.
fn factorial(n: usize) -> i64 {
(1..=n as i64).product()
}
fn combinations_range(n: usize, k: usize) -> Vec<Vec<usize>> {
// Sous-ensembles de {0..n-1} de cardinal k, ordre lexicographique
// (meme ordre qu'itertools.combinations).
let mut result = Vec::new();
if k > n {
return result;
}
let mut c: Vec<usize> = (0..k).collect();
loop {
result.push(c.clone());
let mut i = k;
while i > 0 && c[i - 1] == n - k + i - 1 {
i -= 1;
}
if i == 0 {
break;
}
c[i - 1] += 1;
for j in i..k {
c[j] = c[j - 1] + 1;
}
}
result
}
fn all_coalitions(n: usize) -> Vec<Vec<usize>> {
// Par taille croissante puis ordre lexicographique.
(0..=n).flat_map(|k| combinations_range(n, k)).collect()
}
#[derive(Clone)]
struct VotingGame {
weights: Vec<i64>,
quota: i64,
names: Vec<String>,
}
impl VotingGame {
fn new(weights: Vec<i64>, quota: i64, names: &[&str]) -> VotingGame {
let names: Vec<String> = names.iter().map(|s| s.to_string()).collect();
let total: i64 = weights.iter().sum();
assert!(
weights.len() == names.len() && quota > 0 && quota <= total,
"Jeu pondere incoherent"
);
VotingGame { weights, quota, names }
}
fn n(&self) -> usize {
self.weights.len()
}
fn weight(&self, coalition: &[usize]) -> i64 {
coalition.iter().map(|&i| self.weights[i]).sum()
}
fn wins(&self, coalition: &[usize]) -> bool {
self.weight(coalition) >= self.quota
}
fn coalitions(&self) -> Vec<Vec<usize>> {
all_coalitions(self.n())
}
fn minimal_winning(&self) -> Vec<Vec<usize>> {
self.coalitions()
.into_iter()
.filter(|s| {
self.wins(s)
&& s.iter().all(|&i| {
let without: Vec<usize> =
s.iter().cloned().filter(|&j| j != i).collect();
!self.wins(&without)
})
})
.collect()
}
fn is_dummy(&self, i: usize) -> bool {
self.coalitions()
.into_iter()
.filter(|s| !s.contains(&i))
.all(|s| {
let mut with = s.clone();
with.push(i);
with.sort();
self.wins(&with) == self.wins(&s)
})
}
fn is_veto(&self, i: usize) -> bool {
let others: Vec<usize> = (0..self.n()).filter(|&j| j != i).collect();
!self.wins(&others)
}
fn is_dictator(&self, i: usize) -> bool {
self.wins(&[i]) && self.is_veto(i)
}
fn repr(&self) -> String {
let w = self.weights.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
let n = self.names.iter().map(|x| format!("'{}'", x)).collect::<Vec<_>>().join(", ");
format!("VotingGame(weights=({}), quota={}, names=({}))", w, self.quota, n)
}
}
fn py_bool(b: bool) -> &'static str {
if b { "True" } else { "False" }
}
fn fmt_f64_py(v: f64) -> String {
// Repr Python : toujours au moins une decimale ("1.0", jamais "1").
let s = format!("{}", v);
if s.contains('.') || s.contains('e') {
s
} else {
format!("{}.0", s)
}
}
fn py_repr_f64(v: f64) -> String {
fmt_f64_py(v)
}
fn round_nf(x: f64, d: i32) -> f64 {
// Equivalent de numpy.round : arrondi demi-pair au rang d.
let p = 10f64.powi(d);
let scaled = x * p;
let r = if (scaled - scaled.trunc()).abs() == 0.5 {
let t = scaled.trunc();
if t as i64 % 2 == 0 { t } else { t + scaled.signum() }
} else {
scaled.round()
};
r / p
}
enum Cell {
I(i64),
S(String),
F(f64),
Sci(f64),
}
fn fmt_sci(v: f64) -> String {
// Format exponentiel Python : mantisse .6, exposant signe + 2 chiffres.
let s = format!("{:.6e}", v);
let (mant, exp) = match s.split_once('e') {
Some(p) => p,
None => return s,
};
let e: i32 = exp.parse().unwrap_or(0);
if e < 0 {
format!("{}e-{:02}", mant, -e)
} else {
format!("{}e+{:02}", mant, e)
}
}
fn render_table(index: Option<&[String]>, headers: &[&str], rows: &[Vec<Cell>]) -> String {
// Reproduit le rendu pandas to_string : colonnes de valeurs alignees a
// droite, colonne d'index alignee a gauche, largeur = max(en-tete,
// valeurs) ; les colonnes flottantes partagent le nombre de decimales
// maximal de la colonne (alignement de la virgule). Sans index, pandas
// ajoute un espace fanteme en tete et joint par un seul espace.
let ncols = headers.len();
let mut col_dec = vec![0usize; ncols];
for row in rows {
for (c, cell) in row.iter().enumerate() {
if let Cell::F(v) = cell {
let s = fmt_f64_py(*v);
let d = s.find('.').map_or(0, |p| s.len() - p - 1);
if d > col_dec[c] {
col_dec[c] = d;
}
}
}
}
let mut lines: Vec<Vec<String>> = Vec::new();
let mut head: Vec<String> = Vec::new();
if index.is_some() {
head.push(String::new());
}
for h in headers {
head.push((*h).to_string());
}
lines.push(head);
for (r, row) in rows.iter().enumerate() {
let mut line: Vec<String> = Vec::new();
if let Some(idx) = index {
line.push(idx[r].clone());
}
for (c, cell) in row.iter().enumerate() {
line.push(match cell {
Cell::I(v) => v.to_string(),
Cell::S(v) => v.clone(),
Cell::F(v) => format!("{:.*}", col_dec[c], v),
Cell::Sci(v) => fmt_sci(*v),
});
}
lines.push(line);
}
let nfields = lines[0].len();
let mut widths = vec![0usize; nfields];
for line in &lines {
for (c, s) in line.iter().enumerate() {
let l = s.chars().count();
if l > widths[c] {
widths[c] = l;
}
}
}
let noindex = index.is_none();
let sep = if noindex { " " } else { " " };
let mut out = String::new();
for line in &lines {
let fields: Vec<String> = line
.iter()
.enumerate()
.map(|(c, s)| {
if c == 0 && !noindex {
format!("{:<w$}", s, w = widths[c])
} else {
format!("{:>w$}", s, w = widths[c])
}
})
.collect();
if noindex {
out.push(' ');
}
out.push_str(&fields.join(sep));
out.push('\n');
}
out
}
fn fmt_name_list(names: &[String]) -> String {
let inner = names.iter().map(|n| format!("'{}'", n)).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn fmt_int_list(v: &[usize]) -> String {
let inner = v.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn swing_counts(game: &VotingGame) -> Vec<i64> {
let mut counts = vec![0i64; game.n()];
for i in 0..game.n() {
for s in game.coalitions() {
if !s.contains(&i) && !game.wins(&s) {
let mut with = s.clone();
with.push(i);
with.sort();
if game.wins(&with) {
counts[i] += 1;
}
}
}
}
counts
}
struct Indices6 {
poids: Vec<i64>,
part_poids: Vec<f64>,
shapley_shubik: Vec<f64>,
banzhaf_absolu: Vec<f64>,
banzhaf_normalise: Vec<f64>,
deegan_packel: Vec<f64>,
}
fn power_indices_enumeration(game: &VotingGame) -> Indices6 {
let n = game.n();
let mut shapley = vec![0.0f64; n];
for i in 0..n {
let others: Vec<usize> = (0..n).filter(|&j| j != i).collect();
for size in 0..n {
let coefficient =
(factorial(size) * factorial(n - size - 1)) as f64 / factorial(n) as f64;
for idx in combinations_range(n - 1, size) {
let s: Vec<usize> = idx.iter().map(|&k| others[k]).collect();
let mut with = s.clone();
with.push(i);
with.sort();
let delta = (game.wins(&with) as i64 - game.wins(&s) as i64) as f64;
shapley[i] += coefficient * delta;
}
}
}
let swings = swing_counts(game);
let total: i64 = swings.iter().sum();
let total_weight: i64 = game.weights.iter().sum();
let minimal = game.minimal_winning();
let m = minimal.len() as f64;
let mut deegan = vec![0.0f64; n];
for i in 0..n {
let mut acc = 0.0f64;
for s in &minimal {
if s.contains(&i) {
acc += 1.0 / s.len() as f64;
}
}
deegan[i] = acc / m;
}
Indices6 {
poids: game.weights.clone(),
part_poids: game.weights.iter().map(|w| *w as f64 / total_weight as f64).collect(),
shapley_shubik: shapley,
banzhaf_absolu: swings.iter().map(|c| *c as f64 / 2f64.powi(n as i32 - 1)).collect(),
banzhaf_normalise: swings.iter().map(|c| *c as f64 / total as f64).collect(),
deegan_packel: deegan,
}
}
let groups: Vec<(&str, i64)> = vec![
("RN", 126), ("EPR", 99), ("LFI", 72), ("SOC", 66),
("DR", 47), ("EcoS", 38), ("DEM", 36), ("HOR", 31),
("LIOT", 23), ("GDR", 17), ("UDR", 16), ("NI", 6),
];
let names: Vec<&str> = groups.iter().map(|(n, _)| *n).collect();
let assembly = VotingGame::new(groups.iter().map(|(_, w)| *w).collect(), 289, &names);
let assembly_power = power_indices_enumeration(&assembly);
let mut order: Vec<usize> = (0..assembly.n()).collect();
order.sort_by(|&a, &b| {
assembly_power
.shapley_shubik[b]
.partial_cmp(&assembly_power.shapley_shubik[a])
.unwrap_or(std::cmp::Ordering::Equal)
});
let idx: Vec<String> = order.iter().map(|&i| assembly.names[i].clone()).collect();
let rows: Vec<Vec<Cell>> = order
.iter()
.map(|&i| {
vec![
Cell::I(assembly_power.poids[i]),
Cell::F(round_nf(assembly_power.part_poids[i], 4)),
Cell::F(round_nf(assembly_power.shapley_shubik[i], 4)),
Cell::F(round_nf(assembly_power.banzhaf_absolu[i], 4)),
Cell::F(round_nf(assembly_power.banzhaf_normalise[i], 4)),
Cell::F(round_nf(assembly_power.deegan_packel[i], 4)),
]
})
.collect();
print!(
"{}",
render_table(
Some(&idx),
&["poids", "part_poids", "shapley_shubik", "banzhaf_absolu", "banzhaf_normalise", "deegan_packel"],
&rows
)
);
let sieges: i64 = assembly.weights.iter().sum();
println!("Contrôle des sièges : {} ; coalitions minimales : {}", sieges, assembly.minimal_winning().len()); poids part_poids shapley_shubik banzhaf_absolu banzhaf_normalise deegan_packel
RN 126 0.2184 0.2459 0.5361 0.2408 0.1020
EPR 99 0.1716 0.1811 0.3838 0.1724 0.0957
LFI 72 0.1248 0.1235 0.2744 0.1232 0.0957
SOC 66 0.1144 0.1126 0.2471 0.1110 0.0910
DR 47 0.0815 0.0761 0.1748 0.0785 0.0965
EcoS 38 0.0659 0.0610 0.1416 0.0636 0.0890
DEM 36 0.0624 0.0571 0.1318 0.0592 0.0863
HOR 31 0.0537 0.0487 0.1123 0.0504 0.0836
LIOT 23 0.0399 0.0351 0.0830 0.0373 0.0799
GDR 17 0.0295 0.0268 0.0635 0.0285 0.0738
UDR 16 0.0277 0.0237 0.0576 0.0259 0.0708
NI 6 0.0104 0.0084 0.0205 0.0092 0.0358
Contrôle des sièges : 577 ; coalitions minimales : 184
Le RN, avec 126 sièges, obtient un Shapley-Shubik de 0.2459 et un Banzhaf absolu de 0.5361, montrant que son pouvoir réel dépasse sa proportion simple de sièges (21.84%).
Le classement ne se lit pas comme une consigne politique. Il dépend du quota, de la discipline parfaite supposée des groupes et de l’ensemble des coalitions autorisées. L’écart entre part de sièges et pouvoir modélisé est précisément le phénomène étudié par Ilias Kalalou ; Kaelan Grall en a fourni la lecture comparative par indices.
Le projet étudiant a corrigé son analyse historique afin d’isoler une seule transformation. Nous suivons cette discipline : mêmes 577 sièges, même quota, mêmes autres groupes ; seuls LFI, SOC, EcoS et GDR deviennent un acteur GAUCHE de 193 sièges.
Comparer la somme des pouvoirs avant agrégation au pouvoir du nouvel acteur ne prédit pas un comportement électoral. Cela mesure l’effet structurel de cette unique modification du jeu.
fn factorial(n: usize) -> i64 {
(1..=n as i64).product()
}
fn combinations_range(n: usize, k: usize) -> Vec<Vec<usize>> {
// Sous-ensembles de {0..n-1} de cardinal k, ordre lexicographique
// (meme ordre qu'itertools.combinations).
let mut result = Vec::new();
if k > n {
return result;
}
let mut c: Vec<usize> = (0..k).collect();
loop {
result.push(c.clone());
let mut i = k;
while i > 0 && c[i - 1] == n - k + i - 1 {
i -= 1;
}
if i == 0 {
break;
}
c[i - 1] += 1;
for j in i..k {
c[j] = c[j - 1] + 1;
}
}
result
}
fn all_coalitions(n: usize) -> Vec<Vec<usize>> {
// Par taille croissante puis ordre lexicographique.
(0..=n).flat_map(|k| combinations_range(n, k)).collect()
}
#[derive(Clone)]
struct VotingGame {
weights: Vec<i64>,
quota: i64,
names: Vec<String>,
}
impl VotingGame {
fn new(weights: Vec<i64>, quota: i64, names: &[&str]) -> VotingGame {
let names: Vec<String> = names.iter().map(|s| s.to_string()).collect();
let total: i64 = weights.iter().sum();
assert!(
weights.len() == names.len() && quota > 0 && quota <= total,
"Jeu pondere incoherent"
);
VotingGame { weights, quota, names }
}
fn n(&self) -> usize {
self.weights.len()
}
fn weight(&self, coalition: &[usize]) -> i64 {
coalition.iter().map(|&i| self.weights[i]).sum()
}
fn wins(&self, coalition: &[usize]) -> bool {
self.weight(coalition) >= self.quota
}
fn coalitions(&self) -> Vec<Vec<usize>> {
all_coalitions(self.n())
}
fn minimal_winning(&self) -> Vec<Vec<usize>> {
self.coalitions()
.into_iter()
.filter(|s| {
self.wins(s)
&& s.iter().all(|&i| {
let without: Vec<usize> =
s.iter().cloned().filter(|&j| j != i).collect();
!self.wins(&without)
})
})
.collect()
}
fn is_dummy(&self, i: usize) -> bool {
self.coalitions()
.into_iter()
.filter(|s| !s.contains(&i))
.all(|s| {
let mut with = s.clone();
with.push(i);
with.sort();
self.wins(&with) == self.wins(&s)
})
}
fn is_veto(&self, i: usize) -> bool {
let others: Vec<usize> = (0..self.n()).filter(|&j| j != i).collect();
!self.wins(&others)
}
fn is_dictator(&self, i: usize) -> bool {
self.wins(&[i]) && self.is_veto(i)
}
fn repr(&self) -> String {
let w = self.weights.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
let n = self.names.iter().map(|x| format!("'{}'", x)).collect::<Vec<_>>().join(", ");
format!("VotingGame(weights=({}), quota={}, names=({}))", w, self.quota, n)
}
}
fn py_bool(b: bool) -> &'static str {
if b { "True" } else { "False" }
}
fn fmt_f64_py(v: f64) -> String {
// Repr Python : toujours au moins une decimale ("1.0", jamais "1").
let s = format!("{}", v);
if s.contains('.') || s.contains('e') {
s
} else {
format!("{}.0", s)
}
}
fn py_repr_f64(v: f64) -> String {
fmt_f64_py(v)
}
fn round_nf(x: f64, d: i32) -> f64 {
// Equivalent de numpy.round : arrondi demi-pair au rang d.
let p = 10f64.powi(d);
let scaled = x * p;
let r = if (scaled - scaled.trunc()).abs() == 0.5 {
let t = scaled.trunc();
if t as i64 % 2 == 0 { t } else { t + scaled.signum() }
} else {
scaled.round()
};
r / p
}
enum Cell {
I(i64),
S(String),
F(f64),
Sci(f64),
}
fn fmt_sci(v: f64) -> String {
// Format exponentiel Python : mantisse .6, exposant signe + 2 chiffres.
let s = format!("{:.6e}", v);
let (mant, exp) = match s.split_once('e') {
Some(p) => p,
None => return s,
};
let e: i32 = exp.parse().unwrap_or(0);
if e < 0 {
format!("{}e-{:02}", mant, -e)
} else {
format!("{}e+{:02}", mant, e)
}
}
fn render_table(index: Option<&[String]>, headers: &[&str], rows: &[Vec<Cell>]) -> String {
// Reproduit le rendu pandas to_string : colonnes de valeurs alignees a
// droite, colonne d'index alignee a gauche, largeur = max(en-tete,
// valeurs) ; les colonnes flottantes partagent le nombre de decimales
// maximal de la colonne (alignement de la virgule). Sans index, pandas
// ajoute un espace fanteme en tete et joint par un seul espace.
let ncols = headers.len();
let mut col_dec = vec![0usize; ncols];
for row in rows {
for (c, cell) in row.iter().enumerate() {
if let Cell::F(v) = cell {
let s = fmt_f64_py(*v);
let d = s.find('.').map_or(0, |p| s.len() - p - 1);
if d > col_dec[c] {
col_dec[c] = d;
}
}
}
}
let mut lines: Vec<Vec<String>> = Vec::new();
let mut head: Vec<String> = Vec::new();
if index.is_some() {
head.push(String::new());
}
for h in headers {
head.push((*h).to_string());
}
lines.push(head);
for (r, row) in rows.iter().enumerate() {
let mut line: Vec<String> = Vec::new();
if let Some(idx) = index {
line.push(idx[r].clone());
}
for (c, cell) in row.iter().enumerate() {
line.push(match cell {
Cell::I(v) => v.to_string(),
Cell::S(v) => v.clone(),
Cell::F(v) => format!("{:.*}", col_dec[c], v),
Cell::Sci(v) => fmt_sci(*v),
});
}
lines.push(line);
}
let nfields = lines[0].len();
let mut widths = vec![0usize; nfields];
for line in &lines {
for (c, s) in line.iter().enumerate() {
let l = s.chars().count();
if l > widths[c] {
widths[c] = l;
}
}
}
let noindex = index.is_none();
let sep = if noindex { " " } else { " " };
let mut out = String::new();
for line in &lines {
let fields: Vec<String> = line
.iter()
.enumerate()
.map(|(c, s)| {
if c == 0 && !noindex {
format!("{:<w$}", s, w = widths[c])
} else {
format!("{:>w$}", s, w = widths[c])
}
})
.collect();
if noindex {
out.push(' ');
}
out.push_str(&fields.join(sep));
out.push('\n');
}
out
}
fn fmt_name_list(names: &[String]) -> String {
let inner = names.iter().map(|n| format!("'{}'", n)).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn fmt_int_list(v: &[usize]) -> String {
let inner = v.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
format!("[{}]", inner)
}
fn swing_counts(game: &VotingGame) -> Vec<i64> {
let mut counts = vec![0i64; game.n()];
for i in 0..game.n() {
for s in game.coalitions() {
if !s.contains(&i) && !game.wins(&s) {
let mut with = s.clone();
with.push(i);
with.sort();
if game.wins(&with) {
counts[i] += 1;
}
}
}
}
counts
}
struct Indices6 {
poids: Vec<i64>,
part_poids: Vec<f64>,
shapley_shubik: Vec<f64>,
banzhaf_absolu: Vec<f64>,
banzhaf_normalise: Vec<f64>,
deegan_packel: Vec<f64>,
}
fn power_indices_enumeration(game: &VotingGame) -> Indices6 {
let n = game.n();
let mut shapley = vec![0.0f64; n];
for i in 0..n {
let others: Vec<usize> = (0..n).filter(|&j| j != i).collect();
for size in 0..n {
let coefficient =
(factorial(size) * factorial(n - size - 1)) as f64 / factorial(n) as f64;
for idx in combinations_range(n - 1, size) {
let s: Vec<usize> = idx.iter().map(|&k| others[k]).collect();
let mut with = s.clone();
with.push(i);
with.sort();
let delta = (game.wins(&with) as i64 - game.wins(&s) as i64) as f64;
shapley[i] += coefficient * delta;
}
}
}
let swings = swing_counts(game);
let total: i64 = swings.iter().sum();
let total_weight: i64 = game.weights.iter().sum();
let minimal = game.minimal_winning();
let m = minimal.len() as f64;
let mut deegan = vec![0.0f64; n];
for i in 0..n {
let mut acc = 0.0f64;
for s in &minimal {
if s.contains(&i) {
acc += 1.0 / s.len() as f64;
}
}
deegan[i] = acc / m;
}
Indices6 {
poids: game.weights.clone(),
part_poids: game.weights.iter().map(|w| *w as f64 / total_weight as f64).collect(),
shapley_shubik: shapley,
banzhaf_absolu: swings.iter().map(|c| *c as f64 / 2f64.powi(n as i32 - 1)).collect(),
banzhaf_normalise: swings.iter().map(|c| *c as f64 / total as f64).collect(),
deegan_packel: deegan,
}
}
let groups: Vec<(&str, i64)> = vec![
("RN", 126), ("EPR", 99), ("LFI", 72), ("SOC", 66),
("DR", 47), ("EcoS", 38), ("DEM", 36), ("HOR", 31),
("LIOT", 23), ("GDR", 17), ("UDR", 16), ("NI", 6),
];
let names: Vec<&str> = groups.iter().map(|(n, _)| *n).collect();
let assembly = VotingGame::new(groups.iter().map(|(_, w)| *w).collect(), 289, &names);
let assembly_power = power_indices_enumeration(&assembly);
let left = ["LFI", "SOC", "EcoS", "GDR"];
fn group_index(groups: &[(&str, i64)], name: &str) -> usize {
let mut found = 0usize;
for (i, (n, _)) in groups.iter().enumerate() {
if *n == name {
found = i;
break;
}
}
found
}
let gauche_weight: i64 = left.iter().map(|n| groups[group_index(&groups, n)].1).sum();
let mut bloc_names: Vec<&str> = vec!["GAUCHE"];
bloc_names.extend(groups.iter().filter(|(n, _)| !left.contains(n)).map(|(n, _)| *n));
let mut bloc_weights = vec![gauche_weight];
bloc_weights.extend(groups.iter().filter(|(n, _)| !left.contains(n)).map(|(_, w)| *w));
let bloc_game = VotingGame::new(bloc_weights, 289, &bloc_names);
let bloc_power = power_indices_enumeration(&bloc_game);
let gi = 0usize;
fn sum_over_left(left: &[&str], groups: &[(&str, i64)], pick: &dyn Fn(usize) -> f64) -> f64 {
left.iter()
.map(|n| pick(group_index(groups, n)))
.fold(0.0f64, |a, x| a + x)
}
let avant = [
sum_over_left(&left, &groups, &|i| assembly_power.part_poids[i]),
sum_over_left(&left, &groups, &|i| assembly_power.shapley_shubik[i]),
sum_over_left(&left, &groups, &|i| assembly_power.banzhaf_normalise[i]),
sum_over_left(&left, &groups, &|i| assembly_power.deegan_packel[i]),
];
let apres = [
bloc_power.part_poids[gi],
bloc_power.shapley_shubik[gi],
bloc_power.banzhaf_normalise[gi],
bloc_power.deegan_packel[gi],
];
let labels = vec![
"part_poids".to_string(),
"shapley_shubik".to_string(),
"banzhaf_normalise".to_string(),
"deegan_packel".to_string(),
];
let rows: Vec<Vec<Cell>> = (0..4)
.map(|r| {
vec![
Cell::F(round_nf(avant[r], 4)),
Cell::F(round_nf(apres[r], 4)),
Cell::F(round_nf(apres[r] - avant[r], 4)),
]
})
.collect();
print!(
"{}",
render_table(
Some(&labels),
&["avant_somme_groupes", "apres_agregation", "ecart_structurel"],
&rows
)
);
let sieges: i64 = bloc_game.weights.iter().sum();
println!("Invariant contrôlé : {} sièges et quota {}", sieges, bloc_game.quota); avant_somme_groupes apres_agregation ecart_structurel
part_poids 0.3345 0.3345 0.0000
shapley_shubik 0.3239 0.4159 0.0920
banzhaf_normalise 0.3263 0.3874 0.0611
deegan_packel 0.3495 0.1529 -0.1965
Invariant contrôlé : 577 sièges et quota 289
Lecture des trois écarts non nuls : Shapley-Shubik passe de 0.3239 à 0.4159 (+0.0920) et Banzhaf normalisé de 0.3263 à 0.3874 (+0.0611) — l’acteur unifié pèse plus que la somme des quatre groupes pris séparément. Deegan-Packel fait le mouvement inverse : 0.3495 → 0.1529 (−0.1965), seul des trois indices à chuter. C’est cohérent avec son hypothèse propre (section 2) : il ne compte que les coalitions gagnantes minimales, dont le paysage est bouleversé par la fusion. Limites du contrefactuel : la part de sièges reste identique par construction ; les indices peuvent changer parce que l’ensemble des coalitions et des pivots change — c’est un contrefactuel structurel propre, non une prédiction de vote. Limites cumulatives : énumération exponentielle ; groupes unitaires ; abstentions, dissidences et alliances improbables absentes ; photographie d’effectifs dépendante de la date ; Deegan-Packel privilégie par hypothèse les coalitions minimales ; aucune causalité politique ne découle des indices.
Le geste d’Ilias Kalalou et Kaelan Grall devient ici un pont en trois étages :
| Outil | Question | Limite |
|---|---|---|
| Énumération directe Rust | quels indices sur cette instance ? | exponentielle |
| Modèles Z3 + blocage | retrouve-t-on pivots et coalitions minimales ? | espace fini |
| UNSAT/SAT borné | existe-t-il une violation pour ce n ? |
pas une preuve pour tout n |
| Lean | le théorème général est-il vérifié par le noyau ? | autre artefact, autre niveau de garantie |
Sources principales : Shapley & Shubik (1954), Banzhaf (1965), Deegan & Packel (1978), Dubey & Shapley (1979), Tang & Lin (2009), de Moura & Bjørner (2008). Provenance détaillée : data/game-theory-15e-coalition-power/SOURCE.md.
| Leçon | Mesure dans ce carnet |
|---|---|
| Le poids ne suffit pas à résumer le pouvoir | dans le jeu VotingGame(weights=(3, 2, 1), quota=4, names=('A', 'B', 'C')), A porte 0.5000 du poids mais 0.6667 au Shapley-Shubik et 0.75 au Banzhaf absolu |
| Les coalitions minimales suffisent à lire la structure | Coalitions gagnantes minimales : [['A', 'B'], ['A', 'C']] — A est le seul joueur à veto, aucun joueur n’est nul, aucun dictateur |
| Les deux voies de calcul se recoupent | la voie SMT retrouve les mêmes coalitions (Modèles minimaux Z3 : [['A', 'C'], ['A', 'B']] — même ensemble que l’énumération, dans l’ordre où le solveur de la crate les rend) et la même répartition : Shapley-Shubik 0.6667, Banzhaf normalisé 0.6, Deegan-Packel 0.50 |
| Seuls les indices normalisés somment à 1 | 'banzhaf_absolu': 1.25 dans la ligne des sommes, contre 1.0 pour les trois autres indices |
| La cross-validation est nulle à la précision flottante | Cross-validation réussie : 3 jeux, 3 indices, écart maximal < 1e-12, l’écart le plus élevé restant à 5.551115e-17 |
UNSAT prouve, SAT réfute |
Efficacité Shapley-Shubik, n=4, négation : unsat ; Efficacité Banzhaf absolu, n=3, négation : sat, avec un contre-exemple coalitions gagnantes : [[2], [0, 1], [0, 2], [1, 2], [0, 1, 2]] |
| La structure se lit sur une assemblée réelle, sans être une consigne | sur Contrôle des sièges : 577 ; coalitions minimales : 184, RN (126 sièges) : part de poids 0.2184, Shapley-Shubik 0.2459, Banzhaf absolu 0.5361 |
| Regrouper change l’indice sans toucher la masse | part_poids reste 0.3345 une fois les sièges regroupés, mais le Shapley-Shubik passe de 0.3239 à 0.4159 (0.0920) et le Deegan-Packel de 0.3495 à 0.1529 (-0.1965) ; Invariant contrôlé : 577 sièges et quota 289 |
Ce que ce carnet ajoute à la série : il ne se contente pas de calculer un indice, il oppose deux voies de calcul (énumération directe et bornage SMT) et les fait se recouper sur neuf couples, puis il oppose deux statuts au solveur (unsat qui prouve, sat qui réfute). Le mot « pouvoir » y est traité comme une mesure structurelle, jamais comme une fréquence d vote ni une consigne politique.
1. Dans le jeu [4; 3, 2, 1], A est-il aussi puissant que sa part de poids le laisse croire ?
Parce que le pouvoir coalitionnel tient à la structure des coalitions, pas à la masse. A est présent dans toutes les coalitions gagnantes minimales — Coalitions gagnantes minimales : [['A', 'B'], ['A', 'C']] — et il est le seul joueur à veto : sans lui, aucune de ces coalitions ne gagne. Le Banzhaf absolu compte le nombre de coalitions gagnantes où le joueur est pivotal ; A l’est dans trois coalitions sur quatre, d’où 0.75, au-dessus de sa part de poids 0.5000. Le poids est une moyenne ; le pouvoir est un rôle dans la structure des coalitions. C’est aussi pourquoi, dans la dernière section, la masse peut rester identique (0.3345 avant et après regroupement) alors que l’indice se déplace : c’est la coalition qui se déplace, pas la masse.
2. La voie d’énumération directe et la voie SMT donnent les mêmes coalitions, la cross-validation affiche Cross-validation réussie : 3 jeux, 3 indices, écart maximal < 1e-12 — et pourtant la somme des Banzhaf absolus vaut 'banzhaf_absolu': 1.25 et non 1. Ces deux faits sont-ils compatibles ?
Oui, et ils disent deux choses différentes. L’écart nul prouve que les deux voies implémentent le même calcul : une erreur symétrique serait visible, l’une des deux aurait décroché (le plus grand écart affiché n’est que 5.551115e-17). La somme à 1.25 du Banzhaf absolu n’est pas une erreur : c’est la signature d’un indice non normalisé — il compte les coalitions pivotal sans les répartir, donc sa somme dépend du jeu. Les trois autres indices somment à 1.0 (Shapley-Shubik, Banzhaf normalisé, Deegan-Packel) parce qu’ils sont des parts. Un indice non normalisé est une mesure de structure, pas une part : lire 1.25 comme un « dépassement de pouvoir » serait une erreur de lecture.
unsat quand la propriété est vraie.Shapley, L. S. (1953). A Value for n-Person Games. In: Kuhn, H. W. & Tucker, A. W. (Eds.), Contributions to the Theory of Games, vol. II (Annals of Mathematics Studies 28), Princeton University Press, pp. 307-317. -> §1 (le geste fondateur : la valeur de Shapley phi_i(v) definit le “pouvoir” d’un joueur comme la contribution marginale moyenne sur toutes les coalitions).
Shapley, L. S. & Shubik, M. (1954). A Method for Evaluating the Distribution of Power in a Committee System. American Political Science Review 48(3): 787-792. -> §2 (l’indice de Shapley-Shubik specialise la valeur de Shapley au cas des jeux de vote simples – c’est l’un des trois indices du carnet), §6 (l’etude politique d’une photographie structurelle d’un scrutin).
Banzhaf, J. F. III (1965). Weighted Voting Doesn’t Work: A Mathematical Analysis. Rutgers Law Review 19(2): 317-343. -> §2 (l’indice de Banzhaf – pouvoir absolu normalise – complete le triptyque des trois indices de pouvoir du carnet).
Penrose, L. S. (1946). The Elementary Statistics of Majority Voting. Journal of the Royal Statistical Society 109(1): 53-57. -> §2 (le cas limite des grands comites : le pouvoir tend vers une fraction deterministe du nombre de votes, fondant la transition du discret au continu).
Riker, W. H. (1962). The Theory of Political Coalitions. Yale University Press. -> §6 (l’analyse des coalitions politiques comme equilibres de pouvoir – la “photographie structurelle” du carnet est l’heritiere directe de cette tradition).
Felsenthal, D. S. & Machover, M. (1998). The Measurement of Voting Power: Theory and Practice, Problems and Paradoxes. Edward Elgar, Cheltenham. -> §7 (la mesure empirique du pouvoir dans les institutions reelles – l’agregation contrefactuelle “seulement la gauche” du carnet releve de cette litterature).
Maschler, M., Solan, E. & Zamir, S. (2013). Game Theory. Cambridge University Press. – manuel de reference pour la theorie des indices de pouvoir (Shapley-Shubik, Banzhaf) et pour les jeux cooperatifs (voir carnet 15c pour les outils de la valeur de Shapley et du nucleole). Le renvoi generique est volontaire : les numeros de chapitre ne sont pas cites ici, faute d’avoir pu les verifier a la source ; Felsenthal & Machover (1998) reste la reference comparative des indices. -> §4 (cross-validation par comparaison aux benchmarks classiques), §8 (synthese : le pouvoir des coalitions est a l’intersection de la theorie du vote et de la theorie des jeux cooperatifs).