solverforge-scoring 0.25.1

Incremental constraint scoring for SolverForge
Documentation
//! Zero-erasure complemented constraint stream.
//!
//! A `ComplementedConstraintStream` adds entities from a complement source
//! that are not present in grouped results, with default values.

use std::hash::Hash;
use std::marker::PhantomData;

use solverforge_core::score::Score;
use solverforge_core::ImpactType;

use super::collection_extract::CollectionExtract;
use super::collector::{Accumulator, Collector};
use super::relational::leaf_collector::{leaf_key, LeafCollector, OptionalEntityKey};
use super::relational::operator::{CollectionNode, ComplementNode, GroupNode};
use super::relational::view_plan::{GroupKey, ViewEqualPlan};
use super::relational::Leaf;
use super::weighting_support::ConstraintWeight;
use crate::constraint::relational::{
    OperatorScorer, OptionalComplementAdapter, OptionalComplementWeight, SharedOperatorBuilder,
    SharedOperatorTerminal,
};

/// Zero-erasure constraint stream with complemented groups.
///
/// `ComplementedConstraintStream` results from calling `complement` on a
/// `GroupedConstraintStream`. It ensures all keys from a complement source
/// are represented, using default values for missing keys.
///
/// The key function for A entities returns `Option<K>` to allow skipping
/// entities without valid keys (e.g., unassigned shifts).
///
/// # Type Parameters
///
/// - `S` - Solution type
/// - `A` - Original entity type (e.g., Shift)
/// - `B` - Complement entity type (e.g., Employee)
/// - `K` - Group key type
/// - `EA` - Extractor for A entities
/// - `EB` - Extractor for B entities (complement source)
/// - `KA` - Key function for A (returns `Option<K>` to allow filtering)
/// - `KB` - Key function for B
/// - `C` - Collector type
/// - `D` - Default value function
/// - `Sc` - Score type
///
/// # Example
///
/// ```
/// use solverforge_core::score::SoftScore;
/// use solverforge_scoring::api::constraint_set::IncrementalConstraint;
/// use solverforge_scoring::stream::collector::count;
/// use solverforge_scoring::stream::ConstraintFactory;
///
/// #[derive(Clone, Hash, PartialEq, Eq)]
/// struct Employee {
///     id: usize,
/// }
///
/// #[derive(Clone, Hash, PartialEq, Eq)]
/// struct Shift {
///     employee_id: usize,
/// }
///
/// #[derive(Clone)]
/// struct Schedule {
///     employees: Vec<Employee>,
///     shifts: Vec<Shift>,
/// }
/// # use solverforge_scoring::stream::{source, ChangeSource, CollectionExtract};
/// # impl Schedule {
/// #     fn employees() -> impl CollectionExtract<Schedule, Item = Employee> {
/// #         fn employees(s: &Schedule) -> &[Employee] {
/// #             s.employees.as_slice()
/// #         }
/// #         source(employees as fn(&Schedule) -> &[Employee], ChangeSource::Descriptor(0))
/// #     }
/// # }
/// # impl Schedule {
/// #     fn shifts() -> impl CollectionExtract<Schedule, Item = Shift> {
/// #         fn shifts(s: &Schedule) -> &[Shift] {
/// #             s.shifts.as_slice()
/// #         }
/// #         source(shifts as fn(&Schedule) -> &[Shift], ChangeSource::Descriptor(1))
/// #     }
/// # }
///
/// // Count shifts per employee, including employees with 0 shifts
/// let constraint = ConstraintFactory::<Schedule, SoftScore>::new()
///     .for_each(Schedule::shifts())
///     .group_by(|shift: &Shift| shift.employee_id, count())
///     .complement(
///         Schedule::employees(),
///         |emp: &Employee| emp.id,
///         |_emp: &Employee| 0usize,
///     )
///     .penalize(|_employee_id: &usize, count: &usize| SoftScore::of(*count as i64))
///     .named("Shift count");
///
/// let schedule = Schedule {
///     employees: vec![Employee { id: 0 }, Employee { id: 1 }, Employee { id: 2 }],
///     shifts: vec![
///         Shift { employee_id: 0 },
///         Shift { employee_id: 0 },
///         // Employee 1 has 0 shifts, Employee 2 has 0 shifts
///     ],
/// };
///
/// // Employee 0: 2, Employee 1: 0, Employee 2: 0 → Total: -2
/// assert_eq!(constraint.evaluate(&schedule), SoftScore::of(-2));
/// ```
pub struct ComplementedConstraintStream<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
where
    Sc: Score,
{
    extractor_a: EA,
    extractor_b: EB,
    key_a: KA,
    key_b: KB,
    collector: C,
    default_fn: D,
    _phantom: PhantomData<(
        fn() -> S,
        fn() -> A,
        fn() -> B,
        fn() -> K,
        fn() -> V,
        fn() -> R,
        fn() -> Acc,
        fn() -> Sc,
    )>,
}

impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
    ComplementedConstraintStream<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
where
    S: Send + Sync + 'static,
    A: Clone + Send + Sync + 'static,
    B: Clone + Send + Sync + 'static,
    K: Clone + Eq + Hash + Send + Sync + 'static,
    EA: CollectionExtract<S, Item = A>,
    EB: CollectionExtract<S, Item = B>,
    KA: Fn(&A) -> Option<K> + Send + Sync,
    KB: Fn(&B) -> K + Send + Sync,
    C: for<'i> Collector<&'i A, Value = V, Result = R, Accumulator = Acc> + Send + Sync + 'static,
    V: Send + Sync + 'static,
    R: Send + Sync + 'static,
    Acc: Accumulator<V, R> + Send + Sync + 'static,
    D: Fn(&B) -> R + Send + Sync + 'static,
    Sc: Score + 'static,
{
    fn into_weighted_builder<W>(
        self,
        impact_type: ImpactType,
        weight_fn: W,
        is_hard: bool,
    ) -> ComplementedConstraintBuilder<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
    where
        W: Fn(&K, &R) -> Sc + Send + Sync,
    {
        ComplementedConstraintBuilder {
            extractor_a: self.extractor_a,
            extractor_b: self.extractor_b,
            key_a: self.key_a,
            key_b: self.key_b,
            collector: self.collector,
            default_fn: self.default_fn,
            impact_type,
            weight_fn,
            is_hard,
            _phantom: PhantomData,
        }
    }

    /// Creates a new complemented constraint stream.
    pub(crate) fn new(
        extractor_a: EA,
        extractor_b: EB,
        key_a: KA,
        key_b: KB,
        collector: C,
        default_fn: D,
    ) -> Self {
        Self {
            extractor_a,
            extractor_b,
            key_a,
            key_b,
            collector,
            default_fn,
            _phantom: PhantomData,
        }
    }

    /// Penalizes each key by `weight`.
    ///
    /// `weight` is a fixed score, or a closure over the matched `(&key, &result)` returning one.
    /// A fixed weight with a non-zero hard level marks the constraint hard; closures
    /// are soft unless wrapped in [`hard_weight`](crate::stream::hard_weight).
    pub fn penalize<W>(
        self,
        weight: W,
    ) -> ComplementedConstraintBuilder<
        S,
        A,
        B,
        K,
        EA,
        EB,
        KA,
        KB,
        C,
        V,
        R,
        Acc,
        D,
        impl Fn(&K, &R) -> Sc + Send + Sync,
        Sc,
    >
    where
        W: for<'w> ConstraintWeight<(&'w K, &'w R), Sc> + Send + Sync,
    {
        let is_hard = weight.is_hard();
        self.into_weighted_builder(
            ImpactType::Penalty,
            move |key: &K, result: &R| weight.score((key, result)),
            is_hard,
        )
    }

    /// Rewards each key by `weight`.
    ///
    /// `weight` is a fixed score, or a closure over the matched `(&key, &result)` returning one.
    /// A fixed weight with a non-zero hard level marks the constraint hard; closures
    /// are soft unless wrapped in [`hard_weight`](crate::stream::hard_weight).
    pub fn reward<W>(
        self,
        weight: W,
    ) -> ComplementedConstraintBuilder<
        S,
        A,
        B,
        K,
        EA,
        EB,
        KA,
        KB,
        C,
        V,
        R,
        Acc,
        D,
        impl Fn(&K, &R) -> Sc + Send + Sync,
        Sc,
    >
    where
        W: for<'w> ConstraintWeight<(&'w K, &'w R), Sc> + Send + Sync,
    {
        let is_hard = weight.is_hard();
        self.into_weighted_builder(
            ImpactType::Reward,
            move |key: &K, result: &R| weight.score((key, result)),
            is_hard,
        )
    }
}

impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc: Score> std::fmt::Debug
    for ComplementedConstraintStream<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ComplementedConstraintStream").finish()
    }
}

/// Zero-erasure builder for finalizing a complemented constraint.
pub struct ComplementedConstraintBuilder<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
where
    Sc: Score,
{
    extractor_a: EA,
    extractor_b: EB,
    key_a: KA,
    key_b: KB,
    collector: C,
    default_fn: D,
    impact_type: ImpactType,
    weight_fn: W,
    is_hard: bool,
    _phantom: PhantomData<(
        fn() -> S,
        fn() -> A,
        fn() -> B,
        fn() -> K,
        fn() -> V,
        fn() -> R,
        fn() -> Acc,
        fn() -> Sc,
    )>,
}

impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
    ComplementedConstraintBuilder<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
where
    S: Send + Sync + 'static,
    A: Clone + Send + Sync + 'static,
    B: Clone + Send + Sync + 'static,
    K: Clone + Eq + Hash + Send + Sync + 'static,
    EA: CollectionExtract<S, Item = A> + 'static,
    EB: CollectionExtract<S, Item = B> + 'static,
    KA: Fn(&A) -> Option<K> + Send + Sync + 'static,
    KB: Fn(&B) -> K + Send + Sync + Clone + 'static,
    C: for<'i> Collector<&'i A, Value = V, Result = R, Accumulator = Acc> + Send + Sync + 'static,
    V: Send + Sync + 'static,
    R: Send + Sync + 'static,
    Acc: Accumulator<V, R> + Send + Sync + 'static,
    D: Fn(&B) -> R + Send + Sync + 'static,
    W: Fn(&K, &R) -> Sc + Send + Sync,
    Sc: Score + 'static,
{
    /// Names the constraint and builds it as a
    /// [`SharedOperatorTerminal`](crate::constraint::relational::SharedOperatorTerminal),
    /// to which further terminals over the same grouped node can be appended.
    pub fn named(
        self,
        name: &str,
    ) -> SharedOperatorTerminal<
        S,
        ComplementNode<
            S,
            CollectionNode<S, EB>,
            GroupNode<
                CollectionNode<S, EA>,
                impl for<'l> Fn(&Leaf<'l, A>) -> Option<K> + Send + Sync,
                LeafCollector<C, V, R, Acc>,
                Option<K>,
                Acc,
                V,
                R,
            >,
            ViewEqualPlan<Option<K>, OptionalEntityKey<KB>, GroupKey>,
            impl for<'l> Fn(&S, &Leaf<'l, B>) -> R + Send + Sync,
            R,
        >,
        OptionalComplementAdapter<KB, K, R>,
        OperatorScorer<OptionalComplementWeight<W, KB>, Sc>,
        Sc,
    > {
        let key_a = self.key_a;
        let key_b = self.key_b;
        let default_fn = self.default_fn;
        let group = GroupNode::new(
            CollectionNode::new(self.extractor_a, 0),
            leaf_key(key_a),
            LeafCollector::new(self.collector),
        );
        let targets = CollectionNode::new(self.extractor_b, 1);
        let tree = ComplementNode::new(
            targets,
            group,
            ViewEqualPlan::new(OptionalEntityKey::new(key_b.clone()), GroupKey),
            move |_s: &S, row: &Leaf<'_, B>| default_fn(row.entity),
        );
        SharedOperatorBuilder::first_with_hard(
            tree,
            OptionalComplementAdapter::new(key_b),
            self.impact_type,
            self.weight_fn,
            self.is_hard,
        )
        .first_named(name)
    }

    // Finalizes the builder into a `Grouped`.
}

impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc: Score> std::fmt::Debug
    for ComplementedConstraintBuilder<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ComplementedConstraintBuilder")
            .field("impact_type", &self.impact_type)
            .finish()
    }
}