solverforge_scoring/stream/bi_stream.rs
1//! Zero-erasure bi-constraint stream for self-join patterns.
2//!
3//! A `BiConstraintStream` operates on pairs of entities from the same
4//! collection (self-join), such as comparing Shifts to each other.
5//! All type information is preserved at compile time - no Arc, no dyn.
6//!
7//! # Example
8//!
9//! ```
10//! use solverforge_core::score::SoftScore;
11//! use solverforge_scoring::api::constraint_set::IncrementalConstraint;
12//! use solverforge_scoring::stream::joiner::equal;
13//! use solverforge_scoring::stream::ConstraintFactory;
14//!
15//! #[derive(Clone, Debug, Hash, PartialEq, Eq)]
16//! struct Task {
17//! team: u32,
18//! }
19//!
20//! #[derive(Clone)]
21//! struct Solution {
22//! tasks: Vec<Task>,
23//! }
24//! # use solverforge_scoring::stream::{source, ChangeSource, CollectionExtract};
25//! # impl Solution {
26//! # fn tasks() -> impl CollectionExtract<Solution, Item = Task> {
27//! # fn tasks(s: &Solution) -> &[Task] {
28//! # s.tasks.as_slice()
29//! # }
30//! # source(tasks as fn(&Solution) -> &[Task], ChangeSource::Descriptor(0))
31//! # }
32//! # }
33//!
34//! // Penalize when two tasks are on the same team
35//! let constraint = ConstraintFactory::<Solution, SoftScore>::new()
36//! .for_each(Solution::tasks())
37//! .join(equal(|t: &Task| t.team))
38//! .penalize(SoftScore::of(1))
39//! .named("Team conflict");
40//!
41//! let solution = Solution {
42//! tasks: vec![Task { team: 1 }, Task { team: 1 }, Task { team: 2 }],
43//! };
44//!
45//! // One pair on team 1: (0, 1) = -1 penalty
46//! assert_eq!(constraint.evaluate(&solution), SoftScore::of(-1));
47//! ```
48
49use std::hash::Hash;
50
51use solverforge_core::score::Score;
52
53use super::filter::{BiFilter, FnTriFilter, TriFilter};
54use super::joiner::Joiner;
55use super::tri_stream::TriConstraintStream;
56
57super::arity_stream_macros::impl_arity_stream!(bi, BiConstraintStream, BiConstraintBuilder);
58
59/// join method - transitions to TriConstraintStream
60impl<S, A, K, E, KE, F, Sc> BiConstraintStream<S, A, K, E, KE, F, Sc>
61where
62 S: Send + Sync + 'static,
63 A: Hash + PartialEq + Send + Sync + 'static,
64 K: Eq + Hash + Clone + Send + Sync,
65 E: super::collection_extract::CollectionExtract<S, Item = A>,
66 KE: super::key_extract::KeyExtract<S, A, K>,
67 F: BiFilter<S, A, A>,
68 Sc: Score + 'static,
69{
70 /// Joins this stream with a third element to create triples.
71 ///
72 /// # Example
73 ///
74 /// ```
75 /// use solverforge_core::score::SoftScore;
76 /// use solverforge_scoring::api::constraint_set::IncrementalConstraint;
77 /// use solverforge_scoring::stream::joiner::equal;
78 /// use solverforge_scoring::stream::ConstraintFactory;
79 ///
80 /// #[derive(Clone, Debug, Hash, PartialEq, Eq)]
81 /// struct Task {
82 /// team: u32,
83 /// }
84 ///
85 /// #[derive(Clone)]
86 /// struct Solution {
87 /// tasks: Vec<Task>,
88 /// }
89 /// # use solverforge_scoring::stream::{source, ChangeSource, CollectionExtract};
90 /// # impl Solution {
91 /// # fn tasks() -> impl CollectionExtract<Solution, Item = Task> {
92 /// # fn tasks(s: &Solution) -> &[Task] {
93 /// # s.tasks.as_slice()
94 /// # }
95 /// # source(tasks as fn(&Solution) -> &[Task], ChangeSource::Descriptor(0))
96 /// # }
97 /// # }
98 ///
99 /// // Penalize when three tasks are on the same team
100 /// let constraint = ConstraintFactory::<Solution, SoftScore>::new()
101 /// .for_each(Solution::tasks())
102 /// .join(equal(|t: &Task| t.team))
103 /// .join(equal(|t: &Task| t.team))
104 /// .penalize(SoftScore::of(1))
105 /// .named("Team clustering");
106 ///
107 /// let solution = Solution {
108 /// tasks: vec![
109 /// Task { team: 1 },
110 /// Task { team: 1 },
111 /// Task { team: 1 },
112 /// Task { team: 2 },
113 /// ],
114 /// };
115 ///
116 /// // One triple on team 1: (0, 1, 2) = -1 penalty
117 /// assert_eq!(constraint.evaluate(&solution), SoftScore::of(-1));
118 /// ```
119 pub fn join<J>(
120 self,
121 joiner: J,
122 ) -> TriConstraintStream<S, A, K, E, KE, impl TriFilter<S, A, A, A>, Sc>
123 where
124 J: Joiner<A, A> + 'static,
125 F: 'static,
126 {
127 let combined_filter =
128 crate::stream::closures::self_join_triple_filter::<S, A, _, _>(self.filter, joiner);
129
130 TriConstraintStream::new_self_join_with_filter(
131 self.extractor,
132 self.key_extractor,
133 FnTriFilter::new(combined_filter),
134 )
135 }
136}
137
138// Additional doctests for individual methods
139
140#[cfg(doctest)]
141mod doctests {
142 /* # Filter method
143
144 ```
145 use solverforge_scoring::stream::ConstraintFactory;
146 use solverforge_scoring::stream::joiner::equal;
147 use solverforge_scoring::api::constraint_set::IncrementalConstraint;
148 use solverforge_core::score::SoftScore;
149
150 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
151 struct Item { group: u32, value: i32 }
152
153 #[derive(Clone)]
154 struct Solution { items: Vec<Item> }
155
156 let constraint = ConstraintFactory::<Solution, SoftScore>::new()
157 .for_each(Solution::items())
158 .join(equal(|i: &Item| i.group))
159 .filter(|a: &Item, b: &Item| a.value + b.value > 10)
160 .penalize(SoftScore::of(1))
161 .named("High sum pairs");
162
163 let solution = Solution {
164 items: vec![
165 Item { group: 1, value: 6 },
166 Item { group: 1, value: 7 },
167 ],
168 };
169
170 // 6+7=13 > 10, matches
171 assert_eq!(constraint.evaluate(&solution), SoftScore::of(-1));
172 ```
173
174 # Penalize method
175
176 ```
177 use solverforge_scoring::stream::ConstraintFactory;
178 use solverforge_scoring::stream::joiner::equal;
179 use solverforge_scoring::api::constraint_set::IncrementalConstraint;
180 use solverforge_core::score::SoftScore;
181
182 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
183 struct Task { priority: u32 }
184
185 #[derive(Clone)]
186 struct Solution { tasks: Vec<Task> }
187
188 let constraint = ConstraintFactory::<Solution, SoftScore>::new()
189 .for_each(Solution::tasks())
190 .join(equal(|t: &Task| t.priority))
191 .penalize(SoftScore::of(5))
192 .named("Pair priority conflict");
193
194 let solution = Solution {
195 tasks: vec![
196 Task { priority: 1 },
197 Task { priority: 1 },
198 ],
199 };
200
201 // One pair = -5
202 assert_eq!(constraint.evaluate(&solution), SoftScore::of(-5));
203 ```
204
205 # Penalize with dynamic weight
206
207 ```
208 use solverforge_scoring::stream::ConstraintFactory;
209 use solverforge_scoring::stream::joiner::equal;
210 use solverforge_scoring::api::constraint_set::IncrementalConstraint;
211 use solverforge_core::score::SoftScore;
212
213 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
214 struct Task { team: u32, cost: i64 }
215
216 #[derive(Clone)]
217 struct Solution { tasks: Vec<Task> }
218
219 let constraint = ConstraintFactory::<Solution, SoftScore>::new()
220 .for_each(Solution::tasks())
221 .join(equal(|t: &Task| t.team))
222 .penalize(|a: &Task, b: &Task| {
223 SoftScore::of(a.cost + b.cost)
224 })
225 .named("Team cost");
226
227 let solution = Solution {
228 tasks: vec![
229 Task { team: 1, cost: 2 },
230 Task { team: 1, cost: 3 },
231 ],
232 };
233
234 // Penalty: 2+3 = -5
235 assert_eq!(constraint.evaluate(&solution), SoftScore::of(-5));
236 ```
237
238 # Reward method
239
240 ```
241 use solverforge_scoring::stream::ConstraintFactory;
242 use solverforge_scoring::stream::joiner::equal;
243 use solverforge_scoring::api::constraint_set::IncrementalConstraint;
244 use solverforge_core::score::SoftScore;
245
246 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
247 struct Person { team: u32 }
248
249 #[derive(Clone)]
250 struct Solution { people: Vec<Person> }
251
252 let constraint = ConstraintFactory::<Solution, SoftScore>::new()
253 .for_each(Solution::people())
254 .join(equal(|p: &Person| p.team))
255 .reward(SoftScore::of(10))
256 .named("Team synergy");
257
258 let solution = Solution {
259 people: vec![
260 Person { team: 1 },
261 Person { team: 1 },
262 ],
263 };
264
265 // One pair = +10
266 assert_eq!(constraint.evaluate(&solution), SoftScore::of(10));
267 ```
268
269 # named method
270
271 ```
272 use solverforge_scoring::stream::ConstraintFactory;
273 use solverforge_scoring::stream::joiner::equal;
274 use solverforge_scoring::api::constraint_set::IncrementalConstraint;
275 use solverforge_core::score::SoftScore;
276
277 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
278 struct Item { id: usize }
279
280 #[derive(Clone)]
281 struct Solution { items: Vec<Item> }
282
283 let constraint = ConstraintFactory::<Solution, SoftScore>::new()
284 .for_each(Solution::items())
285 .join(equal(|i: &Item| i.id))
286 .penalize(SoftScore::of(1))
287 .named("Pair items");
288
289 assert_eq!(constraint.name(), "Pair items");
290 ```
291 */
292}