Skip to main content

solverforge_scoring/stream/
existence_stream.rs

1//! Semi/anti existence streams over the count-backed membership engine.
2//!
3//! An existence constraint is a semi/anti join: it retains only left rows whose
4//! matching-right key is alive (or dead, for `NotExists`). There is no third
5//! retention engine — the relationship is a named pair of key adapters over the
6//! two operators' views, the left is a collection over the left stream (whose
7//! membership is the stream's own filter), the right is a collection over the
8//! right stream (children expanded in place by the key adapter), and scoring is
9//! the generic `OperatorTerminal`.
10
11use std::marker::PhantomData;
12
13use solverforge_core::score::Score;
14use solverforge_core::{ConstraintRef, ImpactType};
15
16use super::relational::operator::ExistenceNode;
17use super::relational::Leaf;
18use super::weighting_support::ConstraintWeight;
19use crate::constraint::relational::OperatorTerminal;
20
21/// Whether an existence constraint keeps entities with or without a match.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ExistenceMode {
24    /// Keep left entities with at least one matching right entity.
25    Exists,
26    /// Keep left entities with no matching right entity.
27    NotExists,
28}
29
30/// Zero-erasure existence stream: a left operator, a right operator, and the
31/// named key adapters between them. `named()` builds the count-backed
32/// `ExistenceNode` and its generic terminal.
33pub struct ExistsConstraintStream<S, A, K, L, R, LK, RK, Sc>
34where
35    Sc: Score,
36{
37    pub(super) mode: ExistenceMode,
38    pub(super) left: L,
39    pub(super) right: R,
40    pub(super) left_key: LK,
41    pub(super) right_keys: RK,
42    pub(super) _phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> K, fn() -> Sc)>,
43}
44
45impl<S, A, K, L, R, LK, RK, Sc> ExistsConstraintStream<S, A, K, L, R, LK, RK, Sc>
46where
47    Sc: Score,
48{
49    pub(super) fn new(
50        mode: ExistenceMode,
51        left: L,
52        right: R,
53        left_key: LK,
54        right_keys: RK,
55    ) -> Self {
56        Self {
57            mode,
58            left,
59            right,
60            left_key,
61            right_keys,
62            _phantom: PhantomData,
63        }
64    }
65}
66
67impl<S, A, K, L, R, LK, RK, Sc> ExistsConstraintStream<S, A, K, L, R, LK, RK, Sc>
68where
69    S: Send + Sync + 'static,
70    A: Send + Sync + 'static,
71    K: Eq + std::hash::Hash + Clone + Send + Sync + 'static,
72    L: super::relational::operator::Operator<S>,
73    for<'a> LK: super::relational::view_plan::ViewKey<L::View<'a>, Key = K>,
74    R: super::relational::operator::Operator<S>,
75    for<'a> RK: crate::stream::relational::operator::RightKeySet<R::View<'a>, Key = K>,
76    Sc: Score + 'static,
77{
78    fn into_weighted_builder<W>(
79        self,
80        impact_type: ImpactType,
81        weight: W,
82        is_hard: bool,
83    ) -> ExistsConstraintBuilder<S, A, K, L, R, LK, RK, W, Sc>
84    where
85        W: for<'a> Fn(&S, &Leaf<'a, A>) -> Sc,
86    {
87        ExistsConstraintBuilder {
88            mode: self.mode,
89            left: self.left,
90            right: self.right,
91            left_key: self.left_key,
92            right_keys: self.right_keys,
93            impact_type,
94            weight,
95            is_hard,
96            _phantom: PhantomData,
97        }
98    }
99
100    /// Penalizes each match by `weight`.
101    ///
102    /// `weight` is a fixed score, or a closure over the matched entity returning one.
103    /// A fixed weight with a non-zero hard level marks the constraint hard; closures
104    /// are soft unless wrapped in [`hard_weight`](crate::stream::hard_weight).
105    pub fn penalize<W>(
106        self,
107        weight: W,
108    ) -> ExistsConstraintBuilder<
109        S,
110        A,
111        K,
112        L,
113        R,
114        LK,
115        RK,
116        impl for<'a> Fn(&S, &Leaf<'a, A>) -> Sc + Send + Sync,
117        Sc,
118    >
119    where
120        W: for<'w> ConstraintWeight<(&'w A,), Sc> + Send + Sync,
121    {
122        let is_hard = weight.is_hard();
123        self.into_weighted_builder(
124            ImpactType::Penalty,
125            crate::stream::closures::leaf_weight::<S, A, Sc, _>(weight),
126            is_hard,
127        )
128    }
129
130    /// Rewards each match by `weight`.
131    ///
132    /// `weight` is a fixed score, or a closure over the matched entity returning one.
133    /// A fixed weight with a non-zero hard level marks the constraint hard; closures
134    /// are soft unless wrapped in [`hard_weight`](crate::stream::hard_weight).
135    pub fn reward<W>(
136        self,
137        weight: W,
138    ) -> ExistsConstraintBuilder<
139        S,
140        A,
141        K,
142        L,
143        R,
144        LK,
145        RK,
146        impl for<'a> Fn(&S, &Leaf<'a, A>) -> Sc + Send + Sync,
147        Sc,
148    >
149    where
150        W: for<'w> ConstraintWeight<(&'w A,), Sc> + Send + Sync,
151    {
152        let is_hard = weight.is_hard();
153        self.into_weighted_builder(
154            ImpactType::Reward,
155            crate::stream::closures::leaf_weight::<S, A, Sc, _>(weight),
156            is_hard,
157        )
158    }
159}
160
161/// Builder holding a weighted existence constraint until [`named`](Self::named) finalizes it.
162pub struct ExistsConstraintBuilder<S, A, K, L, R, LK, RK, W, Sc>
163where
164    Sc: Score,
165{
166    mode: ExistenceMode,
167    left: L,
168    right: R,
169    left_key: LK,
170    right_keys: RK,
171    impact_type: ImpactType,
172    weight: W,
173    is_hard: bool,
174    _phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> K, fn() -> Sc)>,
175}
176
177impl<S, A, K, L, R, LK, RK, W, Sc> ExistsConstraintBuilder<S, A, K, L, R, LK, RK, W, Sc>
178where
179    S: Send + Sync + 'static,
180    A: 'static,
181    K: Eq + std::hash::Hash + Clone + Send + Sync + 'static,
182    L: super::relational::operator::Operator<S>,
183    for<'a> LK: super::relational::view_plan::ViewKey<L::View<'a>, Key = K>,
184    R: super::relational::operator::Operator<S>,
185    for<'a> RK: crate::stream::relational::operator::RightKeySet<R::View<'a>, Key = K>,
186    W: for<'a> Fn(&S, &Leaf<'a, A>) -> Sc + Send + Sync,
187    Sc: Score + 'static,
188{
189    /// Names the constraint and builds it as an `OperatorTerminal` over the
190    /// count-backed `ExistenceNode`.
191    pub fn named(
192        self,
193        name: &str,
194    ) -> OperatorTerminal<S, ExistenceNode<S, L, R, K, LK, RK>, W, Sc> {
195        let exists = matches!(self.mode, ExistenceMode::Exists);
196        let node = ExistenceNode::new(
197            self.left,
198            self.right,
199            self.left_key,
200            self.right_keys,
201            exists,
202        );
203        OperatorTerminal::new(
204            ConstraintRef::new("", name),
205            self.impact_type,
206            node,
207            self.weight,
208            self.is_hard,
209        )
210    }
211}
212
213impl<S, A, K, L, R, LK, RK, Sc: Score> std::fmt::Debug
214    for ExistsConstraintStream<S, A, K, L, R, LK, RK, Sc>
215{
216    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217        f.debug_struct("ExistsConstraintStream")
218            .field("mode", &self.mode)
219            .finish()
220    }
221}
222
223impl<S, A, K, L, R, LK, RK, W, Sc: Score> std::fmt::Debug
224    for ExistsConstraintBuilder<S, A, K, L, R, LK, RK, W, Sc>
225{
226    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227        f.debug_struct("ExistsConstraintBuilder")
228            .field("mode", &self.mode)
229            .field("impact_type", &self.impact_type)
230            .finish()
231    }
232}