use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use crate::{Builder, Coefficient, Problem, Var};
#[derive(Debug, Clone, PartialEq)]
pub struct Encoding<T> {
problem: Problem<T>,
vars: Vec<Var>,
costs: Vec<T>,
tasks: usize,
agents: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ShapeMismatch {
pub task: usize,
}
impl fmt::Display for ShapeMismatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"the cost row of task {} does not have one entry per agent",
self.task
)
}
}
impl core::error::Error for ShapeMismatch {}
#[derive(Debug, Clone, PartialEq)]
pub struct Decoded<T> {
pub agents: Vec<Option<usize>>,
pub cost: T,
pub violations: Vec<String>,
}
impl<T> Decoded<T> {
#[must_use]
pub fn is_feasible(&self) -> bool {
self.violations.is_empty()
}
}
pub fn encode<T: Coefficient>(
costs: &[impl AsRef<[T]>],
capacities: &[u32],
penalty: T,
) -> Result<Encoding<T>, ShapeMismatch> {
let agents = capacities.len();
if let Some(task) = costs.iter().position(|row| row.as_ref().len() != agents) {
return Err(ShapeMismatch { task });
}
let mut builder = Builder::new();
let (vars, flat_costs) = add_objective(&mut builder, costs);
add_task_constraints(&mut builder, &vars, costs.len(), penalty);
add_capacity_constraints(&mut builder, &vars, costs.len(), capacities, penalty);
Ok(Encoding {
problem: builder.build(),
vars,
costs: flat_costs,
tasks: costs.len(),
agents,
})
}
fn add_objective<T: Coefficient>(
builder: &mut Builder<T>,
costs: &[impl AsRef<[T]>],
) -> (Vec<Var>, Vec<T>) {
let mut vars = Vec::new();
let mut flat = Vec::new();
for (t, row) in costs.iter().enumerate() {
for (a, &cost) in row.as_ref().iter().enumerate() {
let var = builder.variable(&format!("task{t}.agent{a}"));
builder.add_linear(var, cost);
vars.push(var);
flat.push(cost);
}
}
(vars, flat)
}
fn add_task_constraints<T: Coefficient>(
builder: &mut Builder<T>,
vars: &[Var],
tasks: usize,
penalty: T,
) {
let agents = vars.len().checked_div(tasks).unwrap_or(0);
for t in 0..tasks {
let row = &vars[t * agents..(t + 1) * agents];
builder.exactly_one(&format!("task{t}.exactly_one"), row, penalty);
}
}
fn add_capacity_constraints<T: Coefficient>(
builder: &mut Builder<T>,
vars: &[Var],
tasks: usize,
capacities: &[u32],
penalty: T,
) {
let agents = capacities.len();
for (a, &capacity) in capacities.iter().enumerate() {
if usize::try_from(capacity).is_ok_and(|c| c >= tasks) {
continue;
}
let column: Vec<Var> = vars.iter().skip(a).step_by(agents).copied().collect();
add_capacity(
builder,
&format!("agent{a}.capacity"),
&column,
capacity,
penalty,
);
}
}
fn add_capacity<T: Coefficient>(
builder: &mut Builder<T>,
name: &str,
column: &[Var],
capacity: u32,
penalty: T,
) {
if capacity == 1 {
builder.at_most_one(name, column, penalty);
return;
}
let terms: Vec<(Var, T)> = column.iter().map(|&v| (v, T::ONE)).collect();
builder.linear_equality(name, &terms, T::from_u32(capacity), capacity, penalty);
}
impl<T: Coefficient> Encoding<T> {
#[must_use]
pub fn problem(&self) -> &Problem<T> {
&self.problem
}
#[must_use]
pub fn tasks(&self) -> usize {
self.tasks
}
#[must_use]
pub fn agents(&self) -> usize {
self.agents
}
#[must_use]
pub fn variable(&self, task: usize, agent: usize) -> Var {
assert!(agent < self.agents, "agent {agent} is out of range");
self.vars[task * self.agents + agent]
}
#[must_use]
pub fn decode(&self, bits: &[bool]) -> Decoded<T> {
let violations = self
.problem
.violations(bits)
.map(|c| c.name.clone())
.collect();
Decoded {
agents: self.agent_of_each_task(bits),
cost: self.cost(bits),
violations,
}
}
fn agent_of_each_task(&self, bits: &[bool]) -> Vec<Option<usize>> {
(0..self.tasks())
.map(|t| {
let mut chosen = (0..self.agents).filter(|&a| bits[self.variable(t, a).index()]);
let first = chosen.next();
if chosen.next().is_some() { None } else { first }
})
.collect()
}
fn cost(&self, bits: &[bool]) -> T {
self.vars
.iter()
.zip(&self.costs)
.filter(|(v, _)| bits[v.index()])
.fold(T::ZERO, |sum, (_, &c)| sum.plus(c))
}
}