solverforge_scoring/stream/balance_stream.rs
1//! Zero-erasure balance constraint stream for load distribution patterns.
2//!
3//! A `BalanceConstraintStream` is created from `UniConstraintStream::balance()`
4//! and provides fluent finalization into a `BalanceConstraint`.
5
6use std::hash::Hash;
7use std::marker::PhantomData;
8
9use solverforge_core::score::Score;
10use solverforge_core::{ConstraintRef, ImpactType};
11
12use super::collection_extract::CollectionExtract;
13use super::filter::UniFilter;
14use super::weighting_support::fixed_weight_is_hard;
15use crate::constraint::balance::BalanceConstraint;
16
17/// Zero-erasure stream for building balance constraints.
18///
19/// Created by `UniConstraintStream::balance()`. Provides `penalize()` and
20/// `reward()` methods to finalize the constraint.
21///
22/// # Type Parameters
23///
24/// - `S` - Solution type
25/// - `A` - Entity type
26/// - `K` - Group key type
27/// - `E` - Extractor function for entities
28/// - `F` - Filter type
29/// - `KF` - Key function (returns `Option<K>` to skip unassigned entities)
30/// - `Sc` - Score type
31///
32/// # Example
33///
34/// ```
35/// use solverforge_core::score::SoftScore;
36/// use solverforge_scoring::api::constraint_set::IncrementalConstraint;
37/// use solverforge_scoring::stream::ConstraintFactory;
38///
39/// #[derive(Clone)]
40/// struct Shift {
41/// employee_id: Option<usize>,
42/// }
43///
44/// #[derive(Clone)]
45/// struct Solution {
46/// shifts: Vec<Shift>,
47/// }
48/// # use solverforge_scoring::stream::{source, ChangeSource, CollectionExtract};
49/// # impl Solution {
50/// # fn shifts() -> impl CollectionExtract<Solution, Item = Shift> {
51/// # fn shifts(s: &Solution) -> &[Shift] {
52/// # s.shifts.as_slice()
53/// # }
54/// # source(shifts as fn(&Solution) -> &[Shift], ChangeSource::Descriptor(0))
55/// # }
56/// # }
57///
58/// let constraint = ConstraintFactory::<Solution, SoftScore>::new()
59/// .for_each(Solution::shifts())
60/// .balance(|shift: &Shift| shift.employee_id)
61/// .penalize(SoftScore::of(1000))
62/// .named("Balance workload");
63///
64/// let solution = Solution {
65/// shifts: vec![
66/// Shift {
67/// employee_id: Some(0),
68/// },
69/// Shift {
70/// employee_id: Some(0),
71/// },
72/// Shift {
73/// employee_id: Some(0),
74/// },
75/// Shift {
76/// employee_id: Some(1),
77/// },
78/// ],
79/// };
80///
81/// // std_dev = 1.0, penalty = -1000
82/// assert_eq!(constraint.evaluate(&solution), SoftScore::of(-1000));
83/// ```
84pub struct BalanceConstraintStream<S, A, K, E, F, KF, Sc>
85where
86 Sc: Score,
87{
88 extractor: E,
89 filter: F,
90 key_fn: KF,
91 _phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> K, fn() -> Sc)>,
92}
93
94impl<S, A, K, E, F, KF, Sc> BalanceConstraintStream<S, A, K, E, F, KF, Sc>
95where
96 S: Send + Sync + 'static,
97 A: Send + Sync + 'static,
98 K: Clone + Eq + Hash + Send + Sync + 'static,
99 E: CollectionExtract<S, Item = A>,
100 F: UniFilter<S, A>,
101 KF: Fn(&A) -> Option<K> + Send + Sync,
102 Sc: Score + 'static,
103{
104 fn into_builder(
105 self,
106 impact_type: ImpactType,
107 base_score: Sc,
108 ) -> BalanceConstraintBuilder<S, A, K, E, F, KF, Sc> {
109 BalanceConstraintBuilder {
110 extractor: self.extractor,
111 filter: self.filter,
112 key_fn: self.key_fn,
113 impact_type,
114 base_score,
115 is_hard: fixed_weight_is_hard(base_score),
116 _phantom: PhantomData,
117 }
118 }
119
120 /// Creates a new balance constraint stream.
121 pub(crate) fn new(extractor: E, filter: F, key_fn: KF) -> Self {
122 Self {
123 extractor,
124 filter,
125 key_fn,
126 _phantom: PhantomData,
127 }
128 }
129
130 /// Penalizes imbalanced distribution with the given base score per unit std_dev.
131 ///
132 /// The final score is `base_score.multiply(std_dev)`, negated for penalty.
133 pub fn penalize(self, base_score: Sc) -> BalanceConstraintBuilder<S, A, K, E, F, KF, Sc> {
134 self.into_builder(ImpactType::Penalty, base_score)
135 }
136
137 /// Rewards imbalanced distribution with the given base score per unit std_dev.
138 ///
139 /// The final score is `base_score.multiply(std_dev)`.
140 pub fn reward(self, base_score: Sc) -> BalanceConstraintBuilder<S, A, K, E, F, KF, Sc> {
141 self.into_builder(ImpactType::Reward, base_score)
142 }
143}
144
145impl<S, A, K, E, F, KF, Sc: Score> std::fmt::Debug
146 for BalanceConstraintStream<S, A, K, E, F, KF, Sc>
147{
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 f.debug_struct("BalanceConstraintStream").finish()
150 }
151}
152
153/// Zero-erasure builder for finalizing a balance constraint.
154pub struct BalanceConstraintBuilder<S, A, K, E, F, KF, Sc>
155where
156 Sc: Score,
157{
158 extractor: E,
159 filter: F,
160 key_fn: KF,
161 impact_type: ImpactType,
162 base_score: Sc,
163 is_hard: bool,
164 _phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> K)>,
165}
166
167impl<S, A, K, E, F, KF, Sc> BalanceConstraintBuilder<S, A, K, E, F, KF, Sc>
168where
169 S: Send + Sync + 'static,
170 A: Send + Sync + 'static,
171 K: Clone + Eq + Hash + Send + Sync + 'static,
172 E: CollectionExtract<S, Item = A>,
173 F: UniFilter<S, A>,
174 KF: Fn(&A) -> Option<K> + Send + Sync,
175 Sc: Score + 'static,
176{
177 /// Finalizes the builder into a zero-erasure [`BalanceConstraint`] named `name`.
178 pub fn named(self, name: &str) -> BalanceConstraint<S, A, K, E, F, KF, Sc> {
179 BalanceConstraint::new(
180 ConstraintRef::new("", name),
181 self.impact_type,
182 self.extractor,
183 self.filter,
184 self.key_fn,
185 self.base_score,
186 self.is_hard,
187 )
188 }
189}
190
191impl<S, A, K, E, F, KF, Sc: Score> std::fmt::Debug
192 for BalanceConstraintBuilder<S, A, K, E, F, KF, Sc>
193{
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 f.debug_struct("BalanceConstraintBuilder")
196 .field("impact_type", &self.impact_type)
197 .finish()
198 }
199}