Skip to main content

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: Clone + 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 filter = self.filter;
128        let combined_filter =
129            move |s: &S, a: &A, b: &A, c: &A, a_idx: usize, b_idx: usize, _c_idx: usize| {
130                filter.test(s, a, b, a_idx, b_idx) && joiner.matches(a, c)
131            };
132
133        TriConstraintStream::new_self_join_with_filter(
134            self.extractor,
135            self.key_extractor,
136            FnTriFilter::new(combined_filter),
137        )
138    }
139}
140
141// Additional doctests for individual methods
142
143#[cfg(doctest)]
144mod doctests {
145    /* # Filter method
146
147    ```
148    use solverforge_scoring::stream::ConstraintFactory;
149    use solverforge_scoring::stream::joiner::equal;
150    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
151    use solverforge_core::score::SoftScore;
152
153    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
154    struct Item { group: u32, value: i32 }
155
156    #[derive(Clone)]
157    struct Solution { items: Vec<Item> }
158
159    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
160    .for_each(Solution::items())
161    .join(equal(|i: &Item| i.group))
162    .filter(|a: &Item, b: &Item| a.value + b.value > 10)
163    .penalize(SoftScore::of(1))
164    .named("High sum pairs");
165
166    let solution = Solution {
167    items: vec![
168    Item { group: 1, value: 6 },
169    Item { group: 1, value: 7 },
170    ],
171    };
172
173    // 6+7=13 > 10, matches
174    assert_eq!(constraint.evaluate(&solution), SoftScore::of(-1));
175    ```
176
177    # Penalize method
178
179    ```
180    use solverforge_scoring::stream::ConstraintFactory;
181    use solverforge_scoring::stream::joiner::equal;
182    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
183    use solverforge_core::score::SoftScore;
184
185    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
186    struct Task { priority: u32 }
187
188    #[derive(Clone)]
189    struct Solution { tasks: Vec<Task> }
190
191    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
192    .for_each(Solution::tasks())
193    .join(equal(|t: &Task| t.priority))
194    .penalize(SoftScore::of(5))
195    .named("Pair priority conflict");
196
197    let solution = Solution {
198    tasks: vec![
199    Task { priority: 1 },
200    Task { priority: 1 },
201    ],
202    };
203
204    // One pair = -5
205    assert_eq!(constraint.evaluate(&solution), SoftScore::of(-5));
206    ```
207
208    # Penalize with dynamic weight
209
210    ```
211    use solverforge_scoring::stream::ConstraintFactory;
212    use solverforge_scoring::stream::joiner::equal;
213    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
214    use solverforge_core::score::SoftScore;
215
216    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
217    struct Task { team: u32, cost: i64 }
218
219    #[derive(Clone)]
220    struct Solution { tasks: Vec<Task> }
221
222    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
223    .for_each(Solution::tasks())
224    .join(equal(|t: &Task| t.team))
225    .penalize(|a: &Task, b: &Task| {
226    SoftScore::of(a.cost + b.cost)
227    })
228    .named("Team cost");
229
230    let solution = Solution {
231    tasks: vec![
232    Task { team: 1, cost: 2 },
233    Task { team: 1, cost: 3 },
234    ],
235    };
236
237    // Penalty: 2+3 = -5
238    assert_eq!(constraint.evaluate(&solution), SoftScore::of(-5));
239    ```
240
241    # Reward method
242
243    ```
244    use solverforge_scoring::stream::ConstraintFactory;
245    use solverforge_scoring::stream::joiner::equal;
246    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
247    use solverforge_core::score::SoftScore;
248
249    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
250    struct Person { team: u32 }
251
252    #[derive(Clone)]
253    struct Solution { people: Vec<Person> }
254
255    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
256    .for_each(Solution::people())
257    .join(equal(|p: &Person| p.team))
258    .reward(SoftScore::of(10))
259    .named("Team synergy");
260
261    let solution = Solution {
262    people: vec![
263    Person { team: 1 },
264    Person { team: 1 },
265    ],
266    };
267
268    // One pair = +10
269    assert_eq!(constraint.evaluate(&solution), SoftScore::of(10));
270    ```
271
272    # named method
273
274    ```
275    use solverforge_scoring::stream::ConstraintFactory;
276    use solverforge_scoring::stream::joiner::equal;
277    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
278    use solverforge_core::score::SoftScore;
279
280    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
281    struct Item { id: usize }
282
283    #[derive(Clone)]
284    struct Solution { items: Vec<Item> }
285
286    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
287    .for_each(Solution::items())
288    .join(equal(|i: &Item| i.id))
289    .penalize(SoftScore::of(1))
290    .named("Pair items");
291
292    assert_eq!(constraint.name(), "Pair items");
293    ```
294    */
295}