solverforge_scoring/stream/unassigned.rs
1use solverforge_core::score::Score;
2
3use super::collection_extract::CollectionExtract;
4use super::filter::{AndUniFilter, FnUniFilter, UniFilter};
5use super::UniConstraintStream;
6
7/// An entity that knows whether its planning variable is unassigned, which
8/// enables [`UniConstraintStream::unassigned`] on streams over it.
9///
10/// `#[planning_entity]` implements it for an entity with exactly one
11/// `Option<_>` planning variable: the entity is unassigned while that field is
12/// `None`. Implement it by hand for an entity whose "unassigned" state is
13/// something else, such as several optional variables or a sentinel value.
14///
15/// # Examples
16///
17/// ```
18/// use solverforge_core::score::SoftScore;
19/// use solverforge_scoring::api::constraint_set::IncrementalConstraint;
20/// use solverforge_scoring::stream::{
21/// source, ChangeSource, ConstraintFactory, UnassignedEntity,
22/// };
23///
24/// /// A shift whose `employee` is `usize::MAX` until it is assigned.
25/// #[derive(Clone, Debug)]
26/// struct Shift {
27/// employee: usize,
28/// }
29///
30/// #[derive(Clone)]
31/// struct Roster {
32/// shifts: Vec<Shift>,
33/// }
34///
35/// impl UnassignedEntity<Roster> for Shift {
36/// fn is_unassigned(_roster: &Roster, shift: &Self) -> bool {
37/// shift.employee == usize::MAX
38/// }
39/// }
40///
41/// fn shifts(roster: &Roster) -> &[Shift] {
42/// roster.shifts.as_slice()
43/// }
44///
45/// let constraint = ConstraintFactory::<Roster, SoftScore>::new()
46/// .for_each(source(shifts as fn(&Roster) -> &[Shift], ChangeSource::Descriptor(0)))
47/// .unassigned()
48/// .penalize(SoftScore::of(1))
49/// .named("unassigned shift");
50///
51/// let roster = Roster {
52/// shifts: vec![Shift { employee: 0 }, Shift { employee: usize::MAX }],
53/// };
54/// assert_eq!(constraint.evaluate(&roster), SoftScore::of(-1));
55/// ```
56pub trait UnassignedEntity<S>: Clone + Send + Sync + 'static {
57 /// Whether `entity` is unassigned in `solution`.
58 fn is_unassigned(solution: &S, entity: &Self) -> bool;
59}
60
61impl<S, A, E, F, Sc> UniConstraintStream<S, A, E, F, Sc>
62where
63 S: Send + Sync + 'static,
64 A: UnassignedEntity<S>,
65 E: CollectionExtract<S, Item = A>,
66 F: UniFilter<S, A>,
67 Sc: Score + 'static,
68{
69 /// Keeps only entities whose planning variable is unassigned, as reported by
70 /// their [`UnassignedEntity`] implementation.
71 pub fn unassigned(
72 self,
73 ) -> UniConstraintStream<S, A, E, AndUniFilter<F, FnUniFilter<fn(&S, &A) -> bool>>, Sc> {
74 let (extractor, filter) = self.into_parts();
75 UniConstraintStream::from_parts(
76 extractor,
77 AndUniFilter::new(
78 filter,
79 FnUniFilter::new(A::is_unassigned as fn(&S, &A) -> bool),
80 ),
81 )
82 }
83}