use std::collections::HashMap;
use std::hash::Hash;
use std::marker::PhantomData;
use solverforge_core::score::Score;
use solverforge_core::{ConstraintRef, ImpactType};
use crate::api::constraint_set::IncrementalConstraint;
use crate::stream::collector::{Accumulator, UniCollector};
use crate::stream::filter::UniFilter;
pub struct GroupedUniConstraint<S, A, K, E, Fi, KF, C, W, Sc>
where
C: UniCollector<A>,
Sc: Score,
{
constraint_ref: ConstraintRef,
impact_type: ImpactType,
extractor: E,
filter: Fi,
key_fn: KF,
collector: C,
weight_fn: W,
is_hard: bool,
expected_descriptor: Option<usize>,
groups: HashMap<K, C::Accumulator>,
group_counts: HashMap<K, usize>,
entity_groups: HashMap<usize, K>,
entity_values: HashMap<usize, C::Value>,
_phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> Sc)>,
}
impl<S, A, K, E, Fi, KF, C, W, Sc> GroupedUniConstraint<S, A, K, E, Fi, KF, C, W, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
K: Clone + Eq + Hash + Send + Sync + 'static,
E: crate::stream::collection_extract::CollectionExtract<S, Item = A>,
Fi: UniFilter<S, A>,
KF: Fn(&A) -> K + Send + Sync,
C: UniCollector<A> + Send + Sync + 'static,
C::Accumulator: Send + Sync,
C::Result: Send + Sync,
W: Fn(&C::Result) -> Sc + Send + Sync,
Sc: Score + 'static,
{
#[allow(clippy::too_many_arguments)]
pub fn new(
constraint_ref: ConstraintRef,
impact_type: ImpactType,
extractor: E,
filter: Fi,
key_fn: KF,
collector: C,
weight_fn: W,
is_hard: bool,
) -> Self {
Self {
constraint_ref,
impact_type,
extractor,
filter,
key_fn,
collector,
weight_fn,
is_hard,
expected_descriptor: None,
groups: HashMap::new(),
group_counts: HashMap::new(),
entity_groups: HashMap::new(),
entity_values: HashMap::new(),
_phantom: PhantomData,
}
}
pub fn with_descriptor(mut self, descriptor_index: usize) -> Self {
self.expected_descriptor = Some(descriptor_index);
self
}
fn compute_score(&self, result: &C::Result) -> Sc {
let base = (self.weight_fn)(result);
match self.impact_type {
ImpactType::Penalty => -base,
ImpactType::Reward => base,
}
}
}
impl<S, A, K, E, Fi, KF, C, W, Sc> IncrementalConstraint<S, Sc>
for GroupedUniConstraint<S, A, K, E, Fi, KF, C, W, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
K: Clone + Eq + Hash + Send + Sync + 'static,
E: crate::stream::collection_extract::CollectionExtract<S, Item = A>,
Fi: UniFilter<S, A>,
KF: Fn(&A) -> K + Send + Sync,
C: UniCollector<A> + Send + Sync + 'static,
C::Accumulator: Send + Sync,
C::Result: Send + Sync,
C::Value: Send + Sync,
W: Fn(&C::Result) -> Sc + Send + Sync,
Sc: Score + 'static,
{
fn evaluate(&self, solution: &S) -> Sc {
let entities = self.extractor.extract(solution);
let mut groups: HashMap<K, C::Accumulator> = HashMap::new();
for entity in entities {
if !self.filter.test(solution, entity) {
continue;
}
let key = (self.key_fn)(entity);
let value = self.collector.extract(entity);
let acc = groups
.entry(key)
.or_insert_with(|| self.collector.create_accumulator());
acc.accumulate(&value);
}
let mut total = Sc::zero();
for acc in groups.values() {
let result = acc.finish();
total = total + self.compute_score(&result);
}
total
}
fn match_count(&self, solution: &S) -> usize {
let entities = self.extractor.extract(solution);
let mut groups: HashMap<K, ()> = HashMap::new();
for entity in entities {
if !self.filter.test(solution, entity) {
continue;
}
let key = (self.key_fn)(entity);
groups.insert(key, ());
}
groups.len()
}
fn initialize(&mut self, solution: &S) -> Sc {
self.reset();
let entities = self.extractor.extract(solution);
let mut total = Sc::zero();
for (idx, entity) in entities.iter().enumerate() {
if !self.filter.test(solution, entity) {
continue;
}
total = total + self.insert_entity(entities, idx, entity);
}
total
}
fn on_insert(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
if let Some(expected) = self.expected_descriptor {
if descriptor_index != expected {
return Sc::zero();
}
}
let entities = self.extractor.extract(solution);
if entity_index >= entities.len() {
return Sc::zero();
}
let entity = &entities[entity_index];
if !self.filter.test(solution, entity) {
return Sc::zero();
}
self.insert_entity(entities, entity_index, entity)
}
fn on_retract(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
if let Some(expected) = self.expected_descriptor {
if descriptor_index != expected {
return Sc::zero();
}
}
let entities = self.extractor.extract(solution);
self.retract_entity(entities, entity_index)
}
fn reset(&mut self) {
self.groups.clear();
self.group_counts.clear();
self.entity_groups.clear();
self.entity_values.clear();
}
fn name(&self) -> &str {
&self.constraint_ref.name
}
fn is_hard(&self) -> bool {
self.is_hard
}
fn constraint_ref(&self) -> ConstraintRef {
self.constraint_ref.clone()
}
}
impl<S, A, K, E, Fi, KF, C, W, Sc> GroupedUniConstraint<S, A, K, E, Fi, KF, C, W, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
K: Clone + Eq + Hash + Send + Sync + 'static,
E: crate::stream::collection_extract::CollectionExtract<S, Item = A>,
Fi: UniFilter<S, A>,
KF: Fn(&A) -> K + Send + Sync,
C: UniCollector<A> + Send + Sync + 'static,
C::Accumulator: Send + Sync,
C::Result: Send + Sync,
C::Value: Send + Sync,
W: Fn(&C::Result) -> Sc + Send + Sync,
Sc: Score + 'static,
{
fn insert_entity(&mut self, _entities: &[A], entity_index: usize, entity: &A) -> Sc {
let key = (self.key_fn)(entity);
let value = self.collector.extract(entity);
let impact = self.impact_type;
let is_new = !self.groups.contains_key(&key);
let acc = self
.groups
.entry(key.clone())
.or_insert_with(|| self.collector.create_accumulator());
let old = if is_new {
Sc::zero()
} else {
let old_base = (self.weight_fn)(&acc.finish());
match impact {
ImpactType::Penalty => -old_base,
ImpactType::Reward => old_base,
}
};
acc.accumulate(&value);
let new_base = (self.weight_fn)(&acc.finish());
let new_score = match impact {
ImpactType::Penalty => -new_base,
ImpactType::Reward => new_base,
};
self.entity_groups.insert(entity_index, key.clone());
self.entity_values.insert(entity_index, value);
*self.group_counts.entry(key).or_insert(0) += 1;
new_score - old
}
fn retract_entity(&mut self, _entities: &[A], entity_index: usize) -> Sc {
let Some(key) = self.entity_groups.remove(&entity_index) else {
return Sc::zero();
};
let Some(value) = self.entity_values.remove(&entity_index) else {
return Sc::zero();
};
let impact = self.impact_type;
let Some(acc) = self.groups.get_mut(&key) else {
return Sc::zero();
};
let old_base = (self.weight_fn)(&acc.finish());
let old = match impact {
ImpactType::Penalty => -old_base,
ImpactType::Reward => old_base,
};
let is_empty = {
let cnt = self.group_counts.entry(key.clone()).or_insert(0);
*cnt = cnt.saturating_sub(1);
*cnt == 0
};
if is_empty {
self.group_counts.remove(&key);
}
acc.retract(&value);
let new_score = if is_empty {
self.groups.remove(&key);
Sc::zero()
} else {
let new_base = (self.weight_fn)(&acc.finish());
match impact {
ImpactType::Penalty => -new_base,
ImpactType::Reward => new_base,
}
};
new_score - old
}
}
impl<S, A, K, E, Fi, KF, C, W, Sc> std::fmt::Debug
for GroupedUniConstraint<S, A, K, E, Fi, KF, C, W, Sc>
where
C: UniCollector<A>,
Sc: Score,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GroupedUniConstraint")
.field("name", &self.constraint_ref.name)
.field("impact_type", &self.impact_type)
.field("groups", &self.groups.len())
.finish()
}
}