solverforge_scoring/constraint/projected/
uni.rs1use std::marker::PhantomData;
2
3use solverforge_core::score::Score;
4use solverforge_core::{ConstraintRef, ImpactType};
5
6use crate::api::constraint_set::IncrementalConstraint;
7use crate::stream::filter::UniFilter;
8use crate::stream::projected::{RowCoordinate, RowOwner, Source};
9use crate::stream::relational::hash::{FastMap, FastSet};
10
11pub struct Uni<S, Out, Src, F, W, Sc>
17where
18 Src: Source<S, Out>,
19 Sc: Score,
20{
21 constraint_ref: ConstraintRef,
22 impact_type: ImpactType,
23 source: Src,
24 filter: F,
25 weight: W,
26 is_hard: bool,
27 source_state: Option<Src::State>,
28 row_contributions: FastMap<RowCoordinate, Sc>,
29 rows_by_owner: FastMap<RowOwner, Vec<RowCoordinate>>,
30 _phantom: PhantomData<(fn() -> S, fn() -> Out)>,
31}
32
33impl<S, Out, Src, F, W, Sc> Uni<S, Out, Src, F, W, Sc>
34where
35 S: Send + Sync + 'static,
36 Out: Send + Sync + 'static,
37 Src: Source<S, Out>,
38 F: UniFilter<S, Out>,
39 W: Fn(&Out) -> Sc + Send + Sync,
40 Sc: Score + 'static,
41{
42 pub fn new(
45 constraint_ref: ConstraintRef,
46 impact_type: ImpactType,
47 source: Src,
48 filter: F,
49 weight: W,
50 is_hard: bool,
51 ) -> Self {
52 Self {
53 constraint_ref,
54 impact_type,
55 source,
56 filter,
57 weight,
58 is_hard,
59 source_state: None,
60 row_contributions: FastMap::default(),
61 rows_by_owner: FastMap::default(),
62 _phantom: PhantomData,
63 }
64 }
65
66 fn compute_score(&self, output: &Out) -> Sc {
67 let base = (self.weight)(output);
68 match self.impact_type {
69 ImpactType::Penalty => -base,
70 ImpactType::Reward => base,
71 }
72 }
73
74 fn ensure_source_state(&mut self, solution: &S) {
75 if self.source_state.is_none() {
76 self.source_state = Some(self.source.build_state(solution));
77 }
78 }
79
80 fn index_coordinate(&mut self, coordinate: RowCoordinate) {
81 coordinate.for_each_owner(|owner| {
82 self.rows_by_owner
83 .entry(owner)
84 .or_default()
85 .push(coordinate);
86 });
87 }
88
89 fn unindex_coordinate(&mut self, coordinate: RowCoordinate) {
90 coordinate.for_each_owner(|owner| {
91 let mut remove_bucket = false;
92 if let Some(rows) = self.rows_by_owner.get_mut(&owner) {
93 rows.retain(|candidate| *candidate != coordinate);
94 remove_bucket = rows.is_empty();
95 }
96 if remove_bucket {
97 self.rows_by_owner.remove(&owner);
98 }
99 });
100 }
101
102 fn insert_row(&mut self, solution: &S, coordinate: RowCoordinate, output: Out) -> Sc {
103 if self.row_contributions.contains_key(&coordinate) || !self.filter.test(solution, &output)
104 {
105 return Sc::zero();
106 }
107 let contribution = self.compute_score(&output);
108 self.row_contributions.insert(coordinate, contribution);
109 self.index_coordinate(coordinate);
110 contribution
111 }
112
113 fn retract_row(&mut self, coordinate: RowCoordinate) -> Sc {
114 let Some(contribution) = self.row_contributions.remove(&coordinate) else {
115 return Sc::zero();
116 };
117 self.unindex_coordinate(coordinate);
118 -contribution
119 }
120
121 fn localized_owners(&self, descriptor_index: usize, entity_index: usize) -> Vec<RowOwner> {
122 let mut owners = Vec::new();
123 for slot in 0..self.source.source_count() {
124 if self
125 .source
126 .change_source(slot)
127 .owns_descriptor(descriptor_index)
128 {
129 owners.push(RowOwner {
130 source_slot: slot,
131 entity_index,
132 });
133 }
134 }
135 owners
136 }
137
138 fn coordinates_for_owners(&self, owners: &[RowOwner]) -> Vec<RowCoordinate> {
139 let mut seen = FastSet::default();
140 let mut coordinates = Vec::new();
141 for owner in owners {
142 let Some(rows) = self.rows_by_owner.get(owner) else {
143 continue;
144 };
145 for &coordinate in rows {
146 if seen.insert(coordinate) {
147 coordinates.push(coordinate);
148 }
149 }
150 }
151 coordinates
152 }
153}
154
155impl<S, Out, Src, F, W, Sc> IncrementalConstraint<S, Sc> for Uni<S, Out, Src, F, W, Sc>
156where
157 S: Send + Sync + 'static,
158 Out: Send + Sync + 'static,
159 Src: Source<S, Out>,
160 F: UniFilter<S, Out>,
161 W: Fn(&Out) -> Sc + Send + Sync,
162 Sc: Score + 'static,
163{
164 fn evaluate(&self, solution: &S) -> Sc {
165 let state = self.source.build_state(solution);
166 let mut total = Sc::zero();
167 self.source.collect_all(solution, &state, |_, output| {
168 if self.filter.test(solution, &output) {
169 total = total + self.compute_score(&output);
170 }
171 });
172 total
173 }
174
175 fn match_count(&self, solution: &S) -> usize {
176 let state = self.source.build_state(solution);
177 let mut count = 0;
178 self.source.collect_all(solution, &state, |_, output| {
179 if self.filter.test(solution, &output) {
180 count += 1;
181 }
182 });
183 count
184 }
185
186 fn initialize(&mut self, solution: &S) -> Sc {
187 self.reset();
188 let state = self.source.build_state(solution);
189 let mut total = Sc::zero();
190 let mut rows = Vec::new();
191 self.source
192 .collect_all(solution, &state, |coordinate, output| {
193 rows.push((coordinate, output));
194 });
195 self.source_state = Some(state);
196 for (coordinate, output) in rows {
197 total = total + self.insert_row(solution, coordinate, output);
198 }
199 total
200 }
201
202 fn on_insert(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
203 let owners = self.localized_owners(descriptor_index, entity_index);
204 self.ensure_source_state(solution);
205 {
206 let state = self.source_state.as_mut().expect("projected source state");
207 for owner in &owners {
208 self.source.insert_entity_state(
209 solution,
210 state,
211 owner.source_slot,
212 owner.entity_index,
213 );
214 }
215 }
216 let mut rows = Vec::new();
217 let state = self.source_state.as_ref().expect("projected source state");
218 for owner in &owners {
219 self.source.collect_entity(
220 solution,
221 state,
222 owner.source_slot,
223 owner.entity_index,
224 |coordinate, output| rows.push((coordinate, output)),
225 );
226 }
227 let mut total = Sc::zero();
228 for (coordinate, output) in rows {
229 total = total + self.insert_row(solution, coordinate, output);
230 }
231 total
232 }
233
234 fn on_retract(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
235 let owners = self.localized_owners(descriptor_index, entity_index);
236 let mut total = Sc::zero();
237 for coordinate in self.coordinates_for_owners(&owners) {
238 total = total + self.retract_row(coordinate);
239 }
240 if let Some(state) = self.source_state.as_mut() {
241 for owner in &owners {
242 self.source.retract_entity_state(
243 solution,
244 state,
245 owner.source_slot,
246 owner.entity_index,
247 );
248 }
249 }
250 total
251 }
252
253 fn reset(&mut self) {
254 self.source_state = None;
255 self.row_contributions.clear();
256 self.rows_by_owner.clear();
257 }
258
259 fn name(&self) -> &str {
260 &self.constraint_ref.name
261 }
262
263 fn constraint_ref(&self) -> &ConstraintRef {
264 &self.constraint_ref
265 }
266
267 fn is_hard(&self) -> bool {
268 self.is_hard
269 }
270}