Skip to main content

solverforge_scoring/stream/
complemented_stream.rs

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