Skip to main content

solverforge_scoring/stream/
complemented_stream.rs

1//! Zero-erasure complemented constraint stream.
2//!
3//! A `ComplementedConstraintStream` adds entities from a complement source
4//! that are not present in grouped results, with default values.
5
6use std::hash::Hash;
7use std::marker::PhantomData;
8
9use solverforge_core::score::Score;
10use solverforge_core::ImpactType;
11
12use super::collection_extract::CollectionExtract;
13use super::collector::{Accumulator, Collector};
14use super::relational::leaf_collector::{leaf_key, LeafCollector, OptionalEntityKey};
15use super::relational::operator::{CollectionNode, ComplementNode, GroupNode};
16use super::relational::view_plan::{GroupKey, ViewEqualPlan};
17use super::relational::Leaf;
18use super::weighting_support::ConstraintWeight;
19use crate::constraint::relational::{
20    OperatorScorer, OptionalComplementAdapter, OptionalComplementWeight, SharedOperatorBuilder,
21    SharedOperatorTerminal,
22};
23
24/// Zero-erasure constraint stream with complemented groups.
25///
26/// `ComplementedConstraintStream` results from calling `complement` on a
27/// `GroupedConstraintStream`. It ensures all keys from a complement source
28/// are represented, using default values for missing keys.
29///
30/// The key function for A entities returns `Option<K>` to allow skipping
31/// entities without valid keys (e.g., unassigned shifts).
32///
33/// # Type Parameters
34///
35/// - `S` - Solution type
36/// - `A` - Original entity type (e.g., Shift)
37/// - `B` - Complement entity type (e.g., Employee)
38/// - `K` - Group key type
39/// - `EA` - Extractor for A entities
40/// - `EB` - Extractor for B entities (complement source)
41/// - `KA` - Key function for A (returns `Option<K>` to allow filtering)
42/// - `KB` - Key function for B
43/// - `C` - Collector type
44/// - `D` - Default value function
45/// - `Sc` - Score type
46///
47/// # Example
48///
49/// ```
50/// use solverforge_core::score::SoftScore;
51/// use solverforge_scoring::api::constraint_set::IncrementalConstraint;
52/// use solverforge_scoring::stream::collector::count;
53/// use solverforge_scoring::stream::ConstraintFactory;
54///
55/// #[derive(Clone, Hash, PartialEq, Eq)]
56/// struct Employee {
57///     id: usize,
58/// }
59///
60/// #[derive(Clone, Hash, PartialEq, Eq)]
61/// struct Shift {
62///     employee_id: usize,
63/// }
64///
65/// #[derive(Clone)]
66/// struct Schedule {
67///     employees: Vec<Employee>,
68///     shifts: Vec<Shift>,
69/// }
70/// # use solverforge_scoring::stream::{source, ChangeSource, CollectionExtract};
71/// # impl Schedule {
72/// #     fn employees() -> impl CollectionExtract<Schedule, Item = Employee> {
73/// #         fn employees(s: &Schedule) -> &[Employee] {
74/// #             s.employees.as_slice()
75/// #         }
76/// #         source(employees as fn(&Schedule) -> &[Employee], ChangeSource::Descriptor(0))
77/// #     }
78/// # }
79/// # impl Schedule {
80/// #     fn shifts() -> impl CollectionExtract<Schedule, Item = Shift> {
81/// #         fn shifts(s: &Schedule) -> &[Shift] {
82/// #             s.shifts.as_slice()
83/// #         }
84/// #         source(shifts as fn(&Schedule) -> &[Shift], ChangeSource::Descriptor(1))
85/// #     }
86/// # }
87///
88/// // Count shifts per employee, including employees with 0 shifts
89/// let constraint = ConstraintFactory::<Schedule, SoftScore>::new()
90///     .for_each(Schedule::shifts())
91///     .group_by(|shift: &Shift| shift.employee_id, count())
92///     .complement(
93///         Schedule::employees(),
94///         |emp: &Employee| emp.id,
95///         |_emp: &Employee| 0usize,
96///     )
97///     .penalize(|_employee_id: &usize, count: &usize| SoftScore::of(*count as i64))
98///     .named("Shift count");
99///
100/// let schedule = Schedule {
101///     employees: vec![Employee { id: 0 }, Employee { id: 1 }, Employee { id: 2 }],
102///     shifts: vec![
103///         Shift { employee_id: 0 },
104///         Shift { employee_id: 0 },
105///         // Employee 1 has 0 shifts, Employee 2 has 0 shifts
106///     ],
107/// };
108///
109/// // Employee 0: 2, Employee 1: 0, Employee 2: 0 → Total: -2
110/// assert_eq!(constraint.evaluate(&schedule), SoftScore::of(-2));
111/// ```
112pub struct ComplementedConstraintStream<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
113where
114    Sc: Score,
115{
116    extractor_a: EA,
117    extractor_b: EB,
118    key_a: KA,
119    key_b: KB,
120    collector: C,
121    default_fn: D,
122    _phantom: PhantomData<(
123        fn() -> S,
124        fn() -> A,
125        fn() -> B,
126        fn() -> K,
127        fn() -> V,
128        fn() -> R,
129        fn() -> Acc,
130        fn() -> Sc,
131    )>,
132}
133
134impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
135    ComplementedConstraintStream<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
136where
137    S: Send + Sync + 'static,
138    A: Clone + Send + Sync + 'static,
139    B: Clone + Send + Sync + 'static,
140    K: Clone + Eq + Hash + Send + Sync + 'static,
141    EA: CollectionExtract<S, Item = A>,
142    EB: CollectionExtract<S, Item = B>,
143    KA: Fn(&A) -> Option<K> + Send + Sync,
144    KB: Fn(&B) -> K + Send + Sync,
145    C: for<'i> Collector<&'i A, Value = V, Result = R, Accumulator = Acc> + Send + Sync + 'static,
146    V: Send + Sync + 'static,
147    R: Send + Sync + 'static,
148    Acc: Accumulator<V, R> + Send + Sync + 'static,
149    D: Fn(&B) -> R + Send + Sync + 'static,
150    Sc: Score + 'static,
151{
152    fn into_weighted_builder<W>(
153        self,
154        impact_type: ImpactType,
155        weight_fn: W,
156        is_hard: bool,
157    ) -> ComplementedConstraintBuilder<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
158    where
159        W: Fn(&K, &R) -> Sc + Send + Sync,
160    {
161        ComplementedConstraintBuilder {
162            extractor_a: self.extractor_a,
163            extractor_b: self.extractor_b,
164            key_a: self.key_a,
165            key_b: self.key_b,
166            collector: self.collector,
167            default_fn: self.default_fn,
168            impact_type,
169            weight_fn,
170            is_hard,
171            _phantom: PhantomData,
172        }
173    }
174
175    /// Creates a new complemented constraint stream.
176    pub(crate) fn new(
177        extractor_a: EA,
178        extractor_b: EB,
179        key_a: KA,
180        key_b: KB,
181        collector: C,
182        default_fn: D,
183    ) -> Self {
184        Self {
185            extractor_a,
186            extractor_b,
187            key_a,
188            key_b,
189            collector,
190            default_fn,
191            _phantom: PhantomData,
192        }
193    }
194
195    /// Penalizes each key by `weight`.
196    ///
197    /// `weight` is a fixed score, or a closure over the matched `(&key, &result)` returning one.
198    /// A fixed weight with a non-zero hard level marks the constraint hard; closures
199    /// are soft unless wrapped in [`hard_weight`](crate::stream::hard_weight).
200    pub fn penalize<W>(
201        self,
202        weight: W,
203    ) -> ComplementedConstraintBuilder<
204        S,
205        A,
206        B,
207        K,
208        EA,
209        EB,
210        KA,
211        KB,
212        C,
213        V,
214        R,
215        Acc,
216        D,
217        impl Fn(&K, &R) -> Sc + Send + Sync,
218        Sc,
219    >
220    where
221        W: for<'w> ConstraintWeight<(&'w K, &'w R), Sc> + Send + Sync,
222    {
223        let is_hard = weight.is_hard();
224        self.into_weighted_builder(
225            ImpactType::Penalty,
226            crate::stream::closures::weight2::<K, R, Sc, _>(weight),
227            is_hard,
228        )
229    }
230
231    /// Rewards each key by `weight`.
232    ///
233    /// `weight` is a fixed score, or a closure over the matched `(&key, &result)` returning one.
234    /// A fixed weight with a non-zero hard level marks the constraint hard; closures
235    /// are soft unless wrapped in [`hard_weight`](crate::stream::hard_weight).
236    pub fn reward<W>(
237        self,
238        weight: W,
239    ) -> ComplementedConstraintBuilder<
240        S,
241        A,
242        B,
243        K,
244        EA,
245        EB,
246        KA,
247        KB,
248        C,
249        V,
250        R,
251        Acc,
252        D,
253        impl Fn(&K, &R) -> Sc + Send + Sync,
254        Sc,
255    >
256    where
257        W: for<'w> ConstraintWeight<(&'w K, &'w R), Sc> + Send + Sync,
258    {
259        let is_hard = weight.is_hard();
260        self.into_weighted_builder(
261            ImpactType::Reward,
262            crate::stream::closures::weight2::<K, R, Sc, _>(weight),
263            is_hard,
264        )
265    }
266}
267
268impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc: Score> std::fmt::Debug
269    for ComplementedConstraintStream<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
270{
271    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
272        f.debug_struct("ComplementedConstraintStream").finish()
273    }
274}
275
276/// Zero-erasure builder for finalizing a complemented constraint.
277pub struct ComplementedConstraintBuilder<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
278where
279    Sc: Score,
280{
281    extractor_a: EA,
282    extractor_b: EB,
283    key_a: KA,
284    key_b: KB,
285    collector: C,
286    default_fn: D,
287    impact_type: ImpactType,
288    weight_fn: W,
289    is_hard: bool,
290    _phantom: PhantomData<(
291        fn() -> S,
292        fn() -> A,
293        fn() -> B,
294        fn() -> K,
295        fn() -> V,
296        fn() -> R,
297        fn() -> Acc,
298        fn() -> Sc,
299    )>,
300}
301
302impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
303    ComplementedConstraintBuilder<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
304where
305    S: Send + Sync + 'static,
306    A: Clone + Send + Sync + 'static,
307    B: Clone + Send + Sync + 'static,
308    K: Clone + Eq + Hash + Send + Sync + 'static,
309    EA: CollectionExtract<S, Item = A> + 'static,
310    EB: CollectionExtract<S, Item = B> + 'static,
311    KA: Fn(&A) -> Option<K> + Send + Sync + 'static,
312    KB: Fn(&B) -> K + Send + Sync + Clone + 'static,
313    C: for<'i> Collector<&'i A, Value = V, Result = R, Accumulator = Acc> + Send + Sync + 'static,
314    V: Send + Sync + 'static,
315    R: Send + Sync + 'static,
316    Acc: Accumulator<V, R> + Send + Sync + 'static,
317    D: Fn(&B) -> R + Send + Sync + 'static,
318    W: Fn(&K, &R) -> Sc + Send + Sync,
319    Sc: Score + 'static,
320{
321    /// Names the constraint and builds it as a
322    /// [`SharedOperatorTerminal`](crate::constraint::relational::SharedOperatorTerminal),
323    /// to which further terminals over the same grouped node can be appended.
324    pub fn named(
325        self,
326        name: &str,
327    ) -> SharedOperatorTerminal<
328        S,
329        ComplementNode<
330            S,
331            CollectionNode<S, EB>,
332            GroupNode<
333                CollectionNode<S, EA>,
334                impl for<'l> Fn(&Leaf<'l, A>) -> Option<K> + Send + Sync,
335                LeafCollector<C, V, R, Acc>,
336                Option<K>,
337                Acc,
338                V,
339                R,
340            >,
341            ViewEqualPlan<Option<K>, OptionalEntityKey<KB>, GroupKey>,
342            impl for<'l> Fn(&S, &Leaf<'l, B>) -> R + Send + Sync,
343            R,
344        >,
345        OptionalComplementAdapter<KB, K, R>,
346        OperatorScorer<OptionalComplementWeight<W, KB>, Sc>,
347        Sc,
348    > {
349        let key_a = self.key_a;
350        let key_b = self.key_b;
351        let default_fn = self.default_fn;
352        let group = GroupNode::new(
353            CollectionNode::new(self.extractor_a, 0),
354            leaf_key(key_a),
355            LeafCollector::new(self.collector),
356        );
357        let targets = CollectionNode::new(self.extractor_b, 1);
358        let tree = ComplementNode::new(
359            targets,
360            group,
361            ViewEqualPlan::new(OptionalEntityKey::new(key_b.clone()), GroupKey),
362            crate::stream::closures::leaf_default::<S, B, R, _>(default_fn),
363        );
364        SharedOperatorBuilder::first_with_hard(
365            tree,
366            OptionalComplementAdapter::new(key_b),
367            self.impact_type,
368            self.weight_fn,
369            self.is_hard,
370        )
371        .first_named(name)
372    }
373
374    // Finalizes the builder into a `Grouped`.
375}
376
377impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc: Score> std::fmt::Debug
378    for ComplementedConstraintBuilder<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
379{
380    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
381        f.debug_struct("ComplementedConstraintBuilder")
382            .field("impact_type", &self.impact_type)
383            .finish()
384    }
385}