use crate::game::oracle::Separation;
use crate::game::{ExplicitGame, PlayerSet, SetFunction};
pub(crate) fn positive_scale(magnitude: f64) -> f64 {
if magnitude > 0.0 && magnitude.is_finite() {
magnitude
} else {
1.0
}
}
pub(crate) fn normalizer(magnitude: f64) -> f64 {
let magnitude = positive_scale(magnitude);
if magnitude < f64::MIN_POSITIVE {
return f64::MIN_POSITIVE;
}
f64::from_bits(magnitude.to_bits() & (0x7ff << 52))
}
impl ExplicitGame {
pub(crate) fn divided_by(&self, divisor: f64) -> ExplicitGame {
ExplicitGame {
players: self.players(),
values: self.values().iter().map(|v| v / divisor).collect(),
}
}
pub(crate) fn normalized(&self) -> (ExplicitGame, f64) {
let divisor = normalizer(self.max_abs_value());
(self.divided_by(divisor), divisor)
}
}
pub(crate) struct Scaled<'a, G: ?Sized> {
game: &'a G,
divisor: f64,
}
impl<'a, G: ?Sized> Scaled<'a, G> {
pub fn new(game: &'a G, divisor: f64) -> Scaled<'a, G> {
Scaled { game, divisor }
}
}
impl<G: SetFunction + ?Sized> SetFunction for Scaled<'_, G> {
fn players(&self) -> usize {
self.game.players()
}
fn value(&self, coalition: &PlayerSet) -> f64 {
self.game.value(coalition) / self.divisor
}
}
impl<G: Separation + ?Sized> Separation for Scaled<'_, G> {
fn violated(
&self,
x: &[f64],
bound: f64,
skip: &dyn Fn(&PlayerSet) -> bool,
limit: usize,
) -> Vec<(PlayerSet, f64)> {
let original: Vec<f64> = x.iter().map(|v| v * self.divisor).collect();
self.game
.violated(&original, bound * self.divisor, skip, limit)
.into_iter()
.map(|(coalition, excess)| (coalition, excess / self.divisor))
.collect()
}
fn value_scale(&self) -> f64 {
self.game.value_scale() / self.divisor
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalizer_is_largest_power_of_two_below() {
assert_eq!(normalizer(0.0), 1.0);
assert_eq!(normalizer(1.0), 1.0);
assert_eq!(normalizer(1.99), 1.0);
assert_eq!(normalizer(2.0), 2.0);
assert_eq!(normalizer(920000.0), 524288.0);
assert_eq!(normalizer(3e-7), 2f64.powi(-22));
assert_eq!(normalizer(1e-310), f64::MIN_POSITIVE);
for magnitude in [1e-300, 3e-7, 0.7, 5.0, 1e7, 1e300] {
let scaled = magnitude / normalizer(magnitude);
assert!((1.0..2.0).contains(&scaled), "{magnitude}");
}
}
#[test]
fn normalized_game_keeps_values_exactly() {
let game = crate::generators::bnf(1, 4, 0).unwrap();
let big = game.map_values(|_, v| v * 1e6).unwrap();
let (normalized, divisor) = big.normalized();
assert!((1.0..2.0).contains(&normalized.max_abs_value()));
for (a, b) in normalized.values().iter().zip(big.values()) {
assert_eq!(a * divisor, *b);
}
}
}