Skip to main content

solverforge_scoring/stream/
tri_stream.rs

1//! Zero-erasure tri-constraint stream for three-entity constraint patterns.
2//!
3//! A `TriConstraintStream` operates on triples of entities and supports
4//! filtering, weighting, and constraint finalization. All type information
5//! 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 three 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//!     .join(equal(|t: &Task| t.team))
39//!     .penalize(SoftScore::of(1))
40//!     .named("Team clustering");
41//!
42//! let solution = Solution {
43//!     tasks: vec![
44//!         Task { team: 1 },
45//!         Task { team: 1 },
46//!         Task { team: 1 },
47//!         Task { team: 2 },
48//!     ],
49//! };
50//!
51//! // One triple on team 1: (0, 1, 2) = -1 penalty
52//! assert_eq!(constraint.evaluate(&solution), SoftScore::of(-1));
53//! ```
54
55use std::hash::Hash;
56
57use solverforge_core::score::Score;
58
59use super::collection_extract::CollectionExtract;
60use super::filter::{FnQuadFilter, QuadFilter, TriFilter};
61use super::joiner::Joiner;
62use super::quad_stream::QuadConstraintStream;
63
64super::arity_stream_macros::impl_arity_stream!(tri, TriConstraintStream, TriConstraintBuilder);
65
66/// join method - transitions to QuadConstraintStream
67impl<S, A, K, E, KE, F, Sc> TriConstraintStream<S, A, K, E, KE, F, Sc>
68where
69    S: Send + Sync + 'static,
70    A: Clone + Hash + PartialEq + Send + Sync + 'static,
71    K: Eq + Hash + Clone + Send + Sync,
72    E: CollectionExtract<S, Item = A>,
73    KE: super::key_extract::KeyExtract<S, A, K>,
74    F: TriFilter<S, A, A, A>,
75    Sc: Score + 'static,
76{
77    /// Joins this stream with a fourth element to create quadruples.
78    ///
79    /// # Example
80    ///
81    /// ```
82    /// use solverforge_core::score::SoftScore;
83    /// use solverforge_scoring::api::constraint_set::IncrementalConstraint;
84    /// use solverforge_scoring::stream::joiner::equal;
85    /// use solverforge_scoring::stream::ConstraintFactory;
86    ///
87    /// #[derive(Clone, Debug, Hash, PartialEq, Eq)]
88    /// struct Task {
89    ///     team: u32,
90    /// }
91    ///
92    /// #[derive(Clone)]
93    /// struct Solution {
94    ///     tasks: Vec<Task>,
95    /// }
96    /// # use solverforge_scoring::stream::{source, ChangeSource, CollectionExtract};
97    /// # impl Solution {
98    /// #     fn tasks() -> impl CollectionExtract<Solution, Item = Task> {
99    /// #         fn tasks(s: &Solution) -> &[Task] {
100    /// #             s.tasks.as_slice()
101    /// #         }
102    /// #         source(tasks as fn(&Solution) -> &[Task], ChangeSource::Descriptor(0))
103    /// #     }
104    /// # }
105    ///
106    /// // Penalize when four tasks are on the same team
107    /// let constraint = ConstraintFactory::<Solution, SoftScore>::new()
108    ///     .for_each(Solution::tasks())
109    ///     .join(equal(|t: &Task| t.team))
110    ///     .join(equal(|t: &Task| t.team))
111    ///     .join(equal(|t: &Task| t.team))
112    ///     .penalize(SoftScore::of(1))
113    ///     .named("Team clustering");
114    ///
115    /// let solution = Solution {
116    ///     tasks: vec![
117    ///         Task { team: 1 },
118    ///         Task { team: 1 },
119    ///         Task { team: 1 },
120    ///         Task { team: 1 },
121    ///         Task { team: 2 },
122    ///     ],
123    /// };
124    ///
125    /// // One quadruple on team 1: (0, 1, 2, 3) = -1 penalty
126    /// assert_eq!(constraint.evaluate(&solution), SoftScore::of(-1));
127    /// ```
128    pub fn join<J>(
129        self,
130        joiner: J,
131    ) -> QuadConstraintStream<S, A, K, E, KE, impl QuadFilter<S, A, A, A, A>, Sc>
132    where
133        J: Joiner<A, A> + 'static,
134        F: 'static,
135    {
136        let filter = self.filter;
137        let combined_filter = move |s: &S,
138                                    a: &A,
139                                    b: &A,
140                                    c: &A,
141                                    d: &A,
142                                    a_idx: usize,
143                                    b_idx: usize,
144                                    c_idx: usize,
145                                    _d_idx: usize| {
146            filter.test(s, a, b, c, a_idx, b_idx, c_idx) && joiner.matches(a, d)
147        };
148
149        QuadConstraintStream::new_self_join_with_filter(
150            self.extractor,
151            self.key_extractor,
152            FnQuadFilter::new(combined_filter),
153        )
154    }
155}
156
157// Additional doctests for individual methods
158
159#[cfg(doctest)]
160mod doctests {
161    /* # Filter method
162
163    ```
164    use solverforge_scoring::stream::ConstraintFactory;
165    use solverforge_scoring::stream::joiner::equal;
166    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
167    use solverforge_core::score::SoftScore;
168
169    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
170    struct Item { group: u32, value: i32 }
171
172    #[derive(Clone)]
173    struct Solution { items: Vec<Item> }
174
175    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
176    .for_each(Solution::items())
177    .join(equal(|i: &Item| i.group))
178    .join(equal(|i: &Item| i.group))
179    .filter(|a: &Item, b: &Item, c: &Item| a.value + b.value + c.value > 10)
180    .penalize(SoftScore::of(1))
181    .named("High sum triples");
182
183    let solution = Solution {
184    items: vec![
185    Item { group: 1, value: 3 },
186    Item { group: 1, value: 4 },
187    Item { group: 1, value: 5 },
188    ],
189    };
190
191    // 3+4+5=12 > 10, matches
192    assert_eq!(constraint.evaluate(&solution), SoftScore::of(-1));
193    ```
194
195    # Penalize method
196
197    ```
198    use solverforge_scoring::stream::ConstraintFactory;
199    use solverforge_scoring::stream::joiner::equal;
200    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
201    use solverforge_core::score::SoftScore;
202
203    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
204    struct Task { priority: u32 }
205
206    #[derive(Clone)]
207    struct Solution { tasks: Vec<Task> }
208
209    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
210    .for_each(Solution::tasks())
211    .join(equal(|t: &Task| t.priority))
212    .join(equal(|t: &Task| t.priority))
213    .penalize(SoftScore::of(5))
214    .named("Triple priority conflict");
215
216    let solution = Solution {
217    tasks: vec![
218    Task { priority: 1 },
219    Task { priority: 1 },
220    Task { priority: 1 },
221    ],
222    };
223
224    // One triple = -5
225    assert_eq!(constraint.evaluate(&solution), SoftScore::of(-5));
226    ```
227
228    # Penalize with dynamic weight
229
230    ```
231    use solverforge_scoring::stream::ConstraintFactory;
232    use solverforge_scoring::stream::joiner::equal;
233    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
234    use solverforge_core::score::SoftScore;
235
236    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
237    struct Task { team: u32, cost: i64 }
238
239    #[derive(Clone)]
240    struct Solution { tasks: Vec<Task> }
241
242    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
243    .for_each(Solution::tasks())
244    .join(equal(|t: &Task| t.team))
245    .join(equal(|t: &Task| t.team))
246    .penalize(|a: &Task, b: &Task, c: &Task| {
247    SoftScore::of(a.cost + b.cost + c.cost)
248    })
249    .named("Team cost");
250
251    let solution = Solution {
252    tasks: vec![
253    Task { team: 1, cost: 2 },
254    Task { team: 1, cost: 3 },
255    Task { team: 1, cost: 5 },
256    ],
257    };
258
259    // Penalty: 2+3+5 = -10
260    assert_eq!(constraint.evaluate(&solution), SoftScore::of(-10));
261    ```
262
263    # Reward method
264
265    ```
266    use solverforge_scoring::stream::ConstraintFactory;
267    use solverforge_scoring::stream::joiner::equal;
268    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
269    use solverforge_core::score::SoftScore;
270
271    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
272    struct Person { team: u32 }
273
274    #[derive(Clone)]
275    struct Solution { people: Vec<Person> }
276
277    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
278    .for_each(Solution::people())
279    .join(equal(|p: &Person| p.team))
280    .join(equal(|p: &Person| p.team))
281    .reward(SoftScore::of(10))
282    .named("Team synergy");
283
284    let solution = Solution {
285    people: vec![
286    Person { team: 1 },
287    Person { team: 1 },
288    Person { team: 1 },
289    ],
290    };
291
292    // One triple = +10
293    assert_eq!(constraint.evaluate(&solution), SoftScore::of(10));
294    ```
295
296    # named method
297
298    ```
299    use solverforge_scoring::stream::ConstraintFactory;
300    use solverforge_scoring::stream::joiner::equal;
301    use solverforge_scoring::api::constraint_set::IncrementalConstraint;
302    use solverforge_core::score::SoftScore;
303
304    #[derive(Clone, Debug, Hash, PartialEq, Eq)]
305    struct Item { id: usize }
306
307    #[derive(Clone)]
308    struct Solution { items: Vec<Item> }
309
310    let constraint = ConstraintFactory::<Solution, SoftScore>::new()
311    .for_each(Solution::items())
312    .join(equal(|i: &Item| i.id))
313    .join(equal(|i: &Item| i.id))
314    .penalize(SoftScore::of(1))
315    .named("Triple items");
316
317    assert_eq!(constraint.name(), "Triple items");
318    ```
319    */
320}