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