use crate::error::{Error, Result};
use crate::game::{PlayerSet, SetFunction};
use crate::nucleolus::convex;
use crate::properties::{ConvexGame, Proven};
#[derive(Clone, Debug, PartialEq)]
pub struct AirportGame {
costs: Vec<f64>,
}
impl AirportGame {
pub fn new(costs: Vec<f64>) -> Result<AirportGame> {
if costs.is_empty() || costs.iter().any(|c| !(c.is_finite() && *c >= 0.0)) {
return Err(Error::InvalidArgument(
"費用は 1 つ以上の非負の有限値".into(),
));
}
Ok(AirportGame { costs })
}
pub fn costs(&self) -> &[f64] {
&self.costs
}
pub fn cost(&self, coalition: &PlayerSet) -> f64 {
coalition
.members()
.map(|i| self.costs[i])
.fold(0.0, f64::max)
}
pub fn shapley_costs(&self) -> Vec<f64> {
let n = self.costs.len();
let mut order: Vec<usize> = (0..n).collect();
order.sort_by(|&a, &b| self.costs[a].total_cmp(&self.costs[b]));
let mut shares = vec![0.0; n];
let (mut previous, mut accumulated) = (0.0, 0.0);
for (position, &i) in order.iter().enumerate() {
accumulated += (self.costs[i] - previous) / (n - position) as f64;
previous = self.costs[i];
shares[i] = accumulated;
}
shares
}
pub fn nucleolus_costs(&self) -> Result<Vec<f64>> {
let savings = convex::nucleolus(self)?;
Ok(crate::games::cost::shares_from_savings(
&self.costs,
&savings.allocation,
))
}
}
impl SetFunction for AirportGame {
fn players(&self) -> usize {
self.costs.len()
}
fn value(&self, coalition: &PlayerSet) -> f64 {
let total: f64 = coalition.members().map(|i| self.costs[i]).sum();
total - self.cost(coalition)
}
}
impl ConvexGame for AirportGame {
type Proof = Proven;
}