use coopgame::analysis::explain::{self, ExplainOptions};
use coopgame::analysis::plot::{self, PlotOptions, Point};
use coopgame::analysis::search::{self, SearchOptions};
use coopgame::analysis::uncertainty::{self, IntervalGame};
use coopgame::game::binary_to_lex;
use coopgame::{ExplicitGame, generators, nucleolus, properties};
fn svg_path() -> Option<String> {
std::env::args().nth(1)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let game = ExplicitGame::from_lex(&[0.0, 0.0, 0.0, 4.0, 6.0, 8.0, 12.0])?;
explain_allocations(&game)?;
uncertainty_and_influence(&game)?;
draw_figure(&game, svg_path())?;
find_counterexample()?;
Ok(())
}
fn explain_allocations(game: &ExplicitGame) -> coopgame::Result<()> {
println!("== 配分の説明 ==");
let nucleolus = nucleolus::nucleolus(game)?.into_allocation();
assert!(close(&nucleolus, &[2.0, 4.0, 6.0], 1e-6));
let report = explain::report(game, &nucleolus, ExplainOptions::default())?;
println!("-- 仁 --");
print!("{}", explain::render(&report));
assert!(report.in_core);
let proposal = [6.0, 3.0, 3.0];
let report = explain::report(game, &proposal, ExplainOptions::default())?;
println!("\n-- 案 (6, 3, 3) --");
print!("{}", explain::render(&report));
let worst: Vec<usize> = report.levels[0].coalitions[0].members().collect();
assert!(!report.in_core);
assert!((report.max_excess - 2.0).abs() < 1e-9);
assert_eq!(worst, vec![1, 2]);
Ok(())
}
fn uncertainty_and_influence(game: &ExplicitGame) -> coopgame::Result<()> {
let solve = |g: &ExplicitGame| Ok(nucleolus::nucleolus(g)?.into_allocation());
println!("\n== 値が不確かなときの仁 ==");
let interval = IntervalGame::around(game, 0.1)?;
let distribution = uncertainty::interval_monte_carlo(&interval, 50, 1, solve)?;
println!("プレイヤー\t平均\t標準偏差\t5%\t95%");
for i in 0..game.players() {
println!(
"{i}\t{:.4}\t{:.4}\t{:.4}\t{:.4}",
distribution.mean[i],
distribution.std[i],
distribution.quantiles[0].1[i],
distribution.quantiles[2].1[i]
);
}
println!(
"解けた標本 {}、解けなかった標本 {}",
distribution.samples, distribution.failures
);
assert!(close(&distribution.mean, &[2.07, 4.00, 5.90], 0.01));
assert_eq!((distribution.samples, distribution.failures), (50, 0));
println!("\n== 仁の感度 ==");
let x = solve(game)?;
let key = uncertainty::key_coalitions(game, &x, 2)?;
let rows = uncertainty::influence(game, &key, 1e-4, solve)?;
println!("提携\tdx/dv (プレイヤー 0, 1, 2 の順)");
for row in &rows {
let values: Vec<String> = row.sensitivity.iter().map(|v| format!("{v:+.4}")).collect();
println!("{}\t{}", row.coalition, values.join(" "));
let total: f64 = row.sensitivity.iter().sum();
let expected = if row.coalition == game.grand() {
1.0
} else {
0.0
};
assert!((total - expected).abs() < 1e-6);
}
assert!(rows.iter().any(|row| row.coalition == game.grand()));
Ok(())
}
fn draw_figure(
game: &ExplicitGame,
path: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
println!("\n== 配分集合の図 ==");
let mut options = PlotOptions::default();
options.points = vec![vec![6.0, 3.0, 3.0]];
let figure = plot::imputation_figure(game, &options)?;
println!("コアの頂点 {} 個:", figure.core_vertices.len());
for vertex in &figure.core_vertices {
println!(" {vertex:.4?}");
}
println!("カーネルの多面体 {} 個", figure.kernel_pieces.len());
println!("描いた点:");
for (point, x) in &figure.points {
println!(" {point}: {x:.4?}");
}
assert_eq!(
figure
.points
.iter()
.map(|(point, _)| *point)
.collect::<Vec<_>>(),
[Point::Nucleolus, Point::Shapley, Point::Extra(0)]
);
assert!(close(&figure.points[0].1, &[2.0, 4.0, 6.0], 1e-6));
assert!(close(&figure.points[1].1, &[3.0, 4.0, 5.0], 1e-9));
assert!(!figure.core_vertices.is_empty());
match path {
Some(path) => {
std::fs::write(&path, &figure.svg)?;
println!("SVG ({} バイト) を {path} に書いた", figure.svg.len());
}
None => println!(
"SVG は {} バイト (引数にパスを渡すとファイルに書く)",
figure.svg.len()
),
}
Ok(())
}
fn find_counterexample() -> coopgame::Result<()> {
println!("\n== 反例の探索 ==");
let mut options = SearchOptions::default();
options.attempts = 200;
options.seed = 1;
options.shrink_budget = 500;
let found = search::search(
|rng| {
let n = 3 + (rng.next_u64() % 2) as usize;
generators::random_superadditive(n, rng.next_u64())
},
|g| properties::is_superadditive(g) && !properties::is_convex(g),
options,
)?;
let found = found.expect("試行回数 (attempts) の中で見つかる");
let original = binary_to_lex(&found.original.values()[1..])?;
let shrunk = binary_to_lex(&found.game.values()[1..])?;
println!(
"{} 番目の生成で発見 ({} 人)。縮小で {} 回変形し {} 人になった。",
found.attempt + 1,
found.original.players(),
found.shrink_steps,
found.game.players()
);
println!("元の値 (辞書式順): {original:.4?}");
println!("縮小した値 (辞書式順): {shrunk:?}");
assert!(properties::is_superadditive(&found.game));
assert!(!properties::is_convex(&found.game));
assert_eq!(shrunk, vec![0.0, 0.0, 0.0, 2.0, 0.0, 1.0, 2.0]);
Ok(())
}
fn close(a: &[f64], b: &[f64], tolerance: f64) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < tolerance)
}