use crate::error::Result;
use crate::game::ExplicitGame;
use crate::{nucleolus, values};
#[derive(Clone, Debug, PartialEq)]
pub struct CostGame {
costs: ExplicitGame,
}
impl CostGame {
pub fn new(costs: ExplicitGame) -> CostGame {
CostGame { costs }
}
pub fn costs(&self) -> &ExplicitGame {
&self.costs
}
pub fn players(&self) -> usize {
self.costs.players()
}
pub fn standalone(&self) -> Vec<f64> {
self.costs.singleton_values()
}
pub fn savings_game(&self) -> Result<ExplicitGame> {
let standalone = self.standalone();
self.costs.map_values(|coalition, cost| {
coalition.members().map(|i| standalone[i]).sum::<f64>() - cost
})
}
pub fn to_costs(&self, savings: &[f64]) -> Vec<f64> {
shares_from_savings(&self.standalone(), savings)
}
pub fn to_savings(&self, costs: &[f64]) -> Vec<f64> {
self.to_costs(costs)
}
pub fn nucleolus(&self) -> Result<Vec<f64>> {
let savings = self.savings_game()?;
Ok(self.to_costs(&nucleolus::nucleolus(&savings)?.allocation))
}
pub fn shapley(&self) -> Vec<f64> {
values::shapley(&self.costs)
}
}
pub(crate) fn shares_from_savings(standalone: &[f64], savings: &[f64]) -> Vec<f64> {
standalone.iter().zip(savings).map(|(c, x)| c - x).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn savings_round_trip_and_young_example() {
let costs = ExplicitGame::from_lex(&[15.0, 20.0, 55.0, 35.0, 61.0, 65.0, 78.0]).unwrap();
let game = CostGame::new(costs);
let savings = game.savings_game().unwrap();
let expected = ExplicitGame::from_lex(&[0.0, 0.0, 0.0, 0.0, 9.0, 10.0, 12.0]).unwrap();
assert_eq!(savings, expected);
let shares = game.nucleolus().unwrap();
assert!((shares.iter().sum::<f64>() - 78.0).abs() < 1e-9);
let back = game.to_savings(&shares);
let nucleolus = nucleolus::nucleolus(&savings).unwrap().allocation;
for (a, b) in back.iter().zip(&nucleolus) {
assert!((a - b).abs() < 1e-9);
}
let direct = game.shapley();
let via_savings = game.to_costs(&values::shapley(&savings));
for (a, b) in direct.iter().zip(&via_savings) {
assert!((a - b).abs() < 1e-9);
}
}
}