solverforge-scoring 0.29.0

Incremental constraint scoring for SolverForge
Documentation
//! Zero-erasure incremental uni-constraint.
//!
//! All closure types are concrete generics - no Arc, no dyn, fully monomorphized.

use crate::constraint::score_sum::checked;
use std::fmt::Debug;
use std::marker::PhantomData;

use solverforge_core::score::Score;
use solverforge_core::{ConstraintRef, ImpactType};

use crate::api::analysis::{ConstraintJustification, DetailedConstraintMatch, EntityRef};
use crate::api::constraint_set::IncrementalConstraint;

/// Zero-erasure incremental uni-constraint.
///
/// All closure types are concrete generics - no Arc, no dyn, fully monomorphized.
pub struct IncrementalUniConstraint<S, A, E, F, W, Sc>
where
    Sc: Score,
{
    constraint_ref: ConstraintRef,
    impact_type: ImpactType,
    extractor: E,
    filter: F,
    weight: W,
    is_hard: bool,
    change_source: crate::stream::collection_extract::ChangeSource,
    _phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> Sc)>,
}

impl<S, A, E, F, W, Sc> IncrementalUniConstraint<S, A, E, F, W, Sc>
where
    S: Send + Sync + 'static,
    A: Send + Sync + 'static,
    E: crate::stream::collection_extract::CollectionExtract<S, Item = A>,
    F: Fn(&S, &A) -> bool + Send + Sync,
    W: Fn(&A) -> Sc + Send + Sync,
    Sc: Score,
{
    /// Creates a new zero-erasure incremental uni-constraint.
    pub fn new(
        constraint_ref: ConstraintRef,
        impact_type: ImpactType,
        extractor: E,
        filter: F,
        weight: W,
        is_hard: bool,
    ) -> Self {
        let change_source = extractor.change_source();
        Self {
            constraint_ref,
            impact_type,
            extractor,
            filter,
            weight,
            is_hard,
            change_source,
            _phantom: PhantomData,
        }
    }

    #[inline]
    fn matches(&self, solution: &S, entity: &A) -> bool {
        (self.filter)(solution, entity)
    }

    #[inline]
    fn compute_delta(&self, entity: &A) -> Sc {
        let base = (self.weight)(entity);
        match self.impact_type {
            ImpactType::Penalty => -base,
            ImpactType::Reward => base,
        }
    }

    #[inline]
    fn compute_delta_overflowing(&self, entity: &A) -> (Sc, bool) {
        let base = (self.weight)(entity);
        match self.impact_type {
            ImpactType::Penalty => base.overflowing_neg(),
            ImpactType::Reward => (base, false),
        }
    }

    #[inline]
    fn reverse_delta_overflowing(&self, entity: &A) -> (Sc, bool) {
        let base = (self.weight)(entity);
        match self.impact_type {
            ImpactType::Penalty => (base, false),
            ImpactType::Reward => base.overflowing_neg(),
        }
    }
}

impl<S, A, E, F, W, Sc> IncrementalConstraint<S, Sc> for IncrementalUniConstraint<S, A, E, F, W, Sc>
where
    S: Send + Sync + 'static,
    A: Debug + Send + Sync + 'static,
    E: crate::stream::collection_extract::CollectionExtract<S, Item = A>,
    F: Fn(&S, &A) -> bool + Send + Sync,
    W: Fn(&A) -> Sc + Send + Sync,
    Sc: Score,
{
    fn evaluate(&self, solution: &S) -> Sc {
        let entities = self.extractor.extract(solution);
        let mut total = Sc::zero();
        for entity in entities {
            if self.matches(solution, entity) {
                total = total + self.compute_delta(entity);
            }
        }
        total
    }

    fn match_count(&self, solution: &S) -> usize {
        let entities = self.extractor.extract(solution);
        entities
            .iter()
            .filter(|e| self.matches(solution, e))
            .count()
    }

    fn initialize(&mut self, solution: &S) -> Sc {
        self.evaluate(solution)
    }

    fn on_insert(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
        checked(self.on_insert_overflowing(solution, entity_index, descriptor_index))
    }

    fn on_insert_overflowing(
        &mut self,
        solution: &S,
        entity_index: usize,
        descriptor_index: usize,
    ) -> (Sc, bool) {
        if !self.change_source.owns_descriptor(descriptor_index) {
            return (Sc::zero(), false);
        }
        let entities = self.extractor.extract(solution);
        if entity_index >= entities.len() {
            return (Sc::zero(), false);
        }
        let entity = &entities[entity_index];
        if self.matches(solution, entity) {
            self.compute_delta_overflowing(entity)
        } else {
            (Sc::zero(), false)
        }
    }

    fn on_retract(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
        checked(self.on_retract_overflowing(solution, entity_index, descriptor_index))
    }

    fn on_retract_overflowing(
        &mut self,
        solution: &S,
        entity_index: usize,
        descriptor_index: usize,
    ) -> (Sc, bool) {
        if !self.change_source.owns_descriptor(descriptor_index) {
            return (Sc::zero(), false);
        }
        let entities = self.extractor.extract(solution);
        if entity_index >= entities.len() {
            return (Sc::zero(), false);
        }
        let entity = &entities[entity_index];
        if self.matches(solution, entity) {
            self.reverse_delta_overflowing(entity)
        } else {
            (Sc::zero(), false)
        }
    }

    fn reset(&mut self) {
        // Stateless
    }

    fn name(&self) -> &str {
        &self.constraint_ref.name
    }

    fn is_hard(&self) -> bool {
        self.is_hard
    }

    fn constraint_ref(&self) -> &ConstraintRef {
        &self.constraint_ref
    }

    fn get_matches<'a>(&'a self, solution: &S) -> Vec<DetailedConstraintMatch<'a, Sc>> {
        let entities = self.extractor.extract(solution);
        let cref = self.constraint_ref();
        entities
            .iter()
            .filter(|e| self.matches(solution, e))
            .map(|entity| {
                let entity_ref =
                    EntityRef::new(entity).with_planning_id(self.extractor.planning_id(entity));
                let justification = ConstraintJustification::new(vec![entity_ref]);
                DetailedConstraintMatch::new(cref, self.compute_delta(entity), justification)
            })
            .collect()
    }
}

impl<S, A, E, F, W, Sc: Score> std::fmt::Debug for IncrementalUniConstraint<S, A, E, F, W, Sc> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IncrementalUniConstraint")
            .field("name", &self.constraint_ref.name)
            .field("impact_type", &self.impact_type)
            .finish()
    }
}