use core::fmt;
use core::hash::Hash;
use alloc::vec::Vec;
use crate::budget::Stats;
use crate::error::Error;
use crate::mo::MoMdp;
use crate::mo::coverage::{NO_ACTION, best_under};
use crate::mo::simplex::{best_weight, margin, uniform};
use crate::mo::space::Space;
use crate::solution::Status;
use crate::space::{Id, Kind};
pub type MoSolveResult<M, const N: usize> = Result<
MoSolution<<M as MoMdp<N>>::State, <M as MoMdp<N>>::Action, N>,
Error<<M as MoMdp<N>>::State>,
>;
#[derive(Debug, Clone)]
struct PolicyData<const N: usize> {
value: [f64; N],
weight: [f64; N],
actions: Vec<(Id, u32)>,
}
pub struct MoSolution<S, A, const N: usize> {
space: Space<S, A, N>,
initial: Id,
status: Status,
stats: Stats,
policies: Vec<PolicyData<N>>,
}
impl<S, A, const N: usize> MoSolution<S, A, N> {
pub(crate) fn new(
space: Space<S, A, N>,
initial: Id,
status: Status,
counters: Stats,
epsilon: f64,
) -> Self {
let status = if status == Status::Converged && space.node(initial).value.points.is_empty() {
Status::Unsolvable
} else {
status
};
let policies = extract_policies(&space, initial, epsilon / 1000.0);
Self {
space,
initial,
status,
stats: counters,
policies,
}
}
#[must_use]
pub fn status(&self) -> Status {
self.status
}
#[must_use]
pub fn is_converged(&self) -> bool {
self.status == Status::Converged
}
#[must_use]
pub fn stats(&self) -> &Stats {
&self.stats
}
#[must_use]
pub fn initial_state(&self) -> &S {
self.space.state(self.initial)
}
pub fn policies(&self) -> impl ExactSizeIterator<Item = MoPolicy<'_, S, A, N>> {
self.policies.iter().map(|data| MoPolicy {
solution: self,
data,
})
}
pub(crate) fn vectors_of(&self, id: Id) -> impl Iterator<Item = &[f64; N]> {
self.space.node(id).value.vectors()
}
pub(crate) fn state_count(&self) -> usize {
self.space.len()
}
pub(crate) fn state_of(&self, id: Id) -> &S {
self.space.state(id)
}
}
impl<S: Hash + Eq, A, const N: usize> MoSolution<S, A, N> {
#[must_use]
pub fn value(&self, state: &S) -> Option<Vec<[f64; N]>> {
self.space
.find(state)
.map(|id| self.vectors_of(id).copied().collect())
}
}
impl<S: fmt::Debug, A, const N: usize> fmt::Debug for MoSolution<S, A, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let front: Vec<&[f64; N]> = self.policies.iter().map(|data| &data.value).collect();
f.debug_struct("MoSolution")
.field("initial_state", self.initial_state())
.field("front", &front)
.field("status", &self.status)
.field("stats", &self.stats)
.finish_non_exhaustive()
}
}
pub struct MoPolicy<'a, S, A, const N: usize> {
solution: &'a MoSolution<S, A, N>,
data: &'a PolicyData<N>,
}
impl<'a, S, A, const N: usize> MoPolicy<'a, S, A, N> {
#[must_use]
pub fn value(&self) -> &'a [f64; N] {
&self.data.value
}
#[must_use]
pub fn weight(&self) -> &'a [f64; N] {
&self.data.weight
}
#[must_use]
pub fn len(&self) -> usize {
self.data.actions.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.data.actions.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (&'a S, &'a A)> {
let space = &self.solution.space;
self.data
.actions
.iter()
.map(move |&(id, action)| (space.state(id), &space.action(action).action))
}
}
impl<'a, S: Hash + Eq, A, const N: usize> MoPolicy<'a, S, A, N> {
#[must_use]
pub fn action(&self, state: &S) -> Option<&'a A> {
let space = &self.solution.space;
let id = space.find(state)?;
let index = self
.data
.actions
.binary_search_by_key(&id, |&(state, _)| state)
.ok()?;
Some(&space.action(self.data.actions[index].1).action)
}
}
fn extract_policies<S, A, const N: usize>(
space: &Space<S, A, N>,
initial: Id,
tolerance: f64,
) -> Vec<PolicyData<N>> {
let points = &space.node(initial).value.points;
let mut tableau = Vec::new();
let mut others = Vec::new();
let mut policies: Vec<PolicyData<N>> = Vec::new();
for (index, point) in points.iter().enumerate() {
others.clear();
others.extend(
points
.iter()
.enumerate()
.filter(|&(other, _)| other != index)
.map(|(_, other)| other.vector),
);
let (weight, gap) = best_weight(&point.vector, &others, &mut tableau);
let weight = nudge_inward(weight, gap, &point.vector, &others);
let actions = follow(space, initial, point.action, &weight);
if space.node(initial).kind != Kind::Open {
policies.push(PolicyData {
value: point.vector,
weight,
actions,
});
continue;
}
let duplicate = policies.iter().any(|policy| policy.actions == actions);
let Some(value) = evaluate(space, initial, &actions, &weight, tolerance) else {
continue;
};
if !duplicate {
policies.push(PolicyData {
value,
weight,
actions,
});
}
}
policies
}
fn evaluate<S, A, const N: usize>(
space: &Space<S, A, N>,
initial: Id,
actions: &[(Id, u32)],
weight: &[f64; N],
tolerance: f64,
) -> Option<[f64; N]> {
let index_of = |state: Id| actions.binary_search_by_key(&state, |&(id, _)| id).ok();
let closed = actions.iter().all(|&(_, action)| {
space.outcomes(action).iter().all(|outcome| {
space.node(outcome.target).kind == Kind::Goal || index_of(outcome.target).is_some()
})
});
if !closed || !reaches_goal(space, actions, &index_of) {
return None;
}
let mut values: Vec<[f64; N]> = actions
.iter()
.map(|&(state, _)| {
let set = &space.node(state).value;
best_under(set, weight).map_or([0.0; N], |best| set.points[best].vector)
})
.collect();
for _ in 0..MAX_EVALUATION_SWEEPS {
if sweep_policy(space, actions, &index_of, &mut values) <= tolerance {
break;
}
}
Some(values[index_of(initial)?])
}
const MAX_EVALUATION_SWEEPS: usize = 1_000_000;
fn sweep_policy<S, A, const N: usize>(
space: &Space<S, A, N>,
actions: &[(Id, u32)],
index_of: &impl Fn(Id) -> Option<usize>,
values: &mut [[f64; N]],
) -> f64 {
let mut largest = 0.0_f64;
for (row, &(_, action)) in actions.iter().enumerate() {
let mut value = space.action(action).cost;
for outcome in space.outcomes(action) {
if let Some(index) = index_of(outcome.target) {
for (component, add) in value.iter_mut().zip(&values[index]) {
*component += outcome.probability * add;
}
}
}
for (new, old) in value.iter().zip(&values[row]) {
largest = largest.max(libm::fabs(new - old));
}
values[row] = value;
}
largest
}
fn reaches_goal<S, A, const N: usize>(
space: &Space<S, A, N>,
actions: &[(Id, u32)],
index_of: &impl Fn(Id) -> Option<usize>,
) -> bool {
let mut good = alloc::vec![false; actions.len()];
loop {
let mut changed = false;
for (row, &(_, action)) in actions.iter().enumerate() {
if good[row] {
continue;
}
let reaches = space
.outcomes(action)
.iter()
.any(|outcome| index_of(outcome.target).is_none_or(|index| good[index]));
if reaches {
good[row] = true;
changed = true;
}
}
if !changed {
return good.iter().all(|&g| g);
}
}
}
fn nudge_inward<const N: usize>(
weight: [f64; N],
gap: f64,
v: &[f64; N],
others: &[[f64; N]],
) -> [f64; N] {
let center = uniform::<N>();
let mut share = 0.5;
for _ in 0..30 {
let mut candidate = weight;
for (w, c) in candidate.iter_mut().zip(¢er) {
*w = (1.0 - share) * *w + share * c;
}
if margin(&candidate, v, others) >= gap / 2.0 {
return candidate;
}
share /= 2.0;
}
weight
}
fn follow<S, A, const N: usize>(
space: &Space<S, A, N>,
initial: Id,
first: u32,
weight: &[f64; N],
) -> Vec<(Id, u32)> {
let mut actions: Vec<(Id, u32)> = Vec::new();
let mut seen = alloc::vec![false; space.len()];
let mut stack = alloc::vec![initial];
seen[initial as usize] = true;
while let Some(state) = stack.pop() {
let Some(action) = chosen_action(space, state, initial, first, weight) else {
continue;
};
actions.push((state, action));
for outcome in space.outcomes(action) {
if !seen[outcome.target as usize] {
seen[outcome.target as usize] = true;
stack.push(outcome.target);
}
}
}
actions.sort_unstable();
actions
}
fn chosen_action<S, A, const N: usize>(
space: &Space<S, A, N>,
state: Id,
initial: Id,
first: u32,
weight: &[f64; N],
) -> Option<u32> {
let node = space.node(state);
if node.kind != Kind::Open || !node.expanded {
return None;
}
let action = if state == initial {
first
} else {
node.value.points[best_under(&node.value, weight)?].action
};
(action != NO_ACTION).then_some(action)
}