1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/* Zero-erasure uni-constraint stream for single-entity constraint patterns.
A `UniConstraintStream` operates on a single entity type and supports
filtering, weighting, and constraint finalization. All type information
is preserved at compile time - no Arc, no dyn, fully monomorphized.
*/
use std::hash::Hash;
use std::marker::PhantomData;
use solverforge_core::score::Score;
use solverforge_core::{ConstraintRef, ImpactType};
use crate::constraint::incremental::IncrementalUniConstraint;
use crate::constraint::if_exists::ExistenceMode;
use super::balance_stream::BalanceConstraintStream;
use super::collection_extract::CollectionExtract;
use super::collector::UniCollector;
use super::filter::{AndUniFilter, FnUniFilter, TrueFilter, UniFilter};
use super::grouped_stream::GroupedConstraintStream;
use super::if_exists_stream::IfExistsStream;
use super::joiner::EqualJoiner;
/* Zero-erasure constraint stream over a single entity type.
`UniConstraintStream` accumulates filters and can be finalized into
an `IncrementalUniConstraint` via `penalize()` or `reward()`.
All type parameters are concrete - no trait objects, no Arc allocations
in the hot path.
# Type Parameters
- `S` - Solution type
- `A` - Entity type
- `E` - Extractor function type
- `F` - Combined filter type
- `Sc` - Score type
*/
pub struct UniConstraintStream<S, A, E, F, Sc>
where
Sc: Score,
{
extractor: E,
filter: F,
_phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> Sc)>,
}
impl<S, A, E, Sc> UniConstraintStream<S, A, E, TrueFilter, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
E: CollectionExtract<S, Item = A>,
Sc: Score + 'static,
{
// Creates a new uni-constraint stream with the given extractor.
pub fn new(extractor: E) -> Self {
Self {
extractor,
filter: TrueFilter,
_phantom: PhantomData,
}
}
}
impl<S, A, E, F, Sc> UniConstraintStream<S, A, E, F, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
E: CollectionExtract<S, Item = A>,
F: UniFilter<S, A>,
Sc: Score + 'static,
{
/* Adds a filter predicate to the stream.
Multiple filters are combined with AND semantics at compile time.
Each filter adds a new type layer, preserving zero-erasure.
To access related entities, use shadow variables on your entity type
(e.g., `#[inverse_relation_shadow_variable]`) rather than solution traversal.
*/
pub fn filter<P>(
self,
predicate: P,
) -> UniConstraintStream<
S,
A,
E,
AndUniFilter<F, FnUniFilter<impl Fn(&S, &A) -> bool + Send + Sync>>,
Sc,
>
where
P: Fn(&A) -> bool + Send + Sync + 'static,
{
UniConstraintStream {
extractor: self.extractor,
filter: AndUniFilter::new(
self.filter,
FnUniFilter::new(move |_s: &S, a: &A| predicate(a)),
),
_phantom: PhantomData,
}
}
/* Joins this stream using the provided join target.
Dispatch depends on argument type:
- `equal(|a: &A| key_fn(a))` — self-join, returns `BiConstraintStream`
- `(extractor_b, equal_bi(ka, kb))` — keyed cross-join, returns `CrossBiConstraintStream`
- `(other_stream, |a, b| predicate)` — predicate cross-join O(n*m)
*/
pub fn join<J>(self, target: J) -> J::Output
where
J: super::join_target::JoinTarget<S, A, E, F, Sc>,
{
target.apply(self.extractor, self.filter)
}
/* Groups entities by key and aggregates with a collector.
Returns a zero-erasure `GroupedConstraintStream` that can be penalized
or rewarded based on the aggregated result for each group.
*/
pub fn group_by<K, KF, C>(
self,
key_fn: KF,
collector: C,
) -> GroupedConstraintStream<S, A, K, E, F, KF, C, Sc>
where
K: Clone + Eq + Hash + Send + Sync + 'static,
KF: Fn(&A) -> K + Send + Sync,
C: UniCollector<A> + Send + Sync + 'static,
C::Accumulator: Send + Sync,
C::Result: Clone + Send + Sync,
{
GroupedConstraintStream::new(self.extractor, self.filter, key_fn, collector)
}
/* Creates a balance constraint that penalizes uneven distribution across groups.
Unlike `group_by` which scores each group independently, `balance` computes
a GLOBAL standard deviation across all group counts and produces a single score.
The `key_fn` returns `Option<K>` to allow skipping entities (e.g., unassigned shifts).
Any filters accumulated on this stream are also applied.
# Example
```
use solverforge_scoring::stream::ConstraintFactory;
use solverforge_scoring::api::constraint_set::IncrementalConstraint;
use solverforge_core::score::SoftScore;
#[derive(Clone)]
struct Shift { employee_id: Option<usize> }
#[derive(Clone)]
struct Solution { shifts: Vec<Shift> }
let constraint = ConstraintFactory::<Solution, SoftScore>::new()
.for_each(|s: &Solution| &s.shifts)
.balance(|shift: &Shift| shift.employee_id)
.penalize(SoftScore::of(1000))
.named("Balance workload");
let solution = Solution {
shifts: vec![
Shift { employee_id: Some(0) },
Shift { employee_id: Some(0) },
Shift { employee_id: Some(0) },
Shift { employee_id: Some(1) },
],
};
// Employee 0: 3 shifts, Employee 1: 1 shift
// std_dev = 1.0, penalty = -1000
assert_eq!(constraint.evaluate(&solution), SoftScore::of(-1000));
```
*/
pub fn balance<K, KF>(self, key_fn: KF) -> BalanceConstraintStream<S, A, K, E, F, KF, Sc>
where
K: Clone + Eq + Hash + Send + Sync + 'static,
KF: Fn(&A) -> Option<K> + Send + Sync,
{
BalanceConstraintStream::new(self.extractor, self.filter, key_fn)
}
/* Filters A entities based on whether a matching B entity exists.
Use this when the B collection needs filtering (e.g., only vacationing employees).
The `extractor_b` returns a `Vec<B>` to allow for filtering.
Any filters accumulated on this stream are applied to A entities.
# Example
```
use solverforge_scoring::stream::ConstraintFactory;
use solverforge_scoring::stream::joiner::equal_bi;
use solverforge_scoring::api::constraint_set::IncrementalConstraint;
use solverforge_core::score::SoftScore;
#[derive(Clone)]
struct Shift { id: usize, employee_idx: Option<usize> }
#[derive(Clone)]
struct Employee { id: usize, on_vacation: bool }
#[derive(Clone)]
struct Schedule { shifts: Vec<Shift>, employees: Vec<Employee> }
// Penalize shifts assigned to employees who are on vacation
let constraint = ConstraintFactory::<Schedule, SoftScore>::new()
.for_each(|s: &Schedule| s.shifts.as_slice())
.filter(|shift: &Shift| shift.employee_idx.is_some())
.if_exists_filtered(
|s: &Schedule| s.employees.iter().filter(|e| e.on_vacation).cloned().collect(),
equal_bi(
|shift: &Shift| shift.employee_idx,
|emp: &Employee| Some(emp.id),
),
)
.penalize(SoftScore::of(1))
.named("Vacation conflict");
let schedule = Schedule {
shifts: vec![
Shift { id: 0, employee_idx: Some(0) }, // assigned to vacationing emp
Shift { id: 1, employee_idx: Some(1) }, // assigned to working emp
Shift { id: 2, employee_idx: None }, // unassigned (filtered out)
],
employees: vec![
Employee { id: 0, on_vacation: true },
Employee { id: 1, on_vacation: false },
],
};
// Only shift 0 matches (assigned to employee 0 who is on vacation)
assert_eq!(constraint.evaluate(&schedule), SoftScore::of(-1));
```
*/
pub fn if_exists_filtered<B, EB, K, KA, KB>(
self,
extractor_b: EB,
joiner: EqualJoiner<KA, KB, K>,
) -> IfExistsStream<S, A, B, K, E, EB, KA, KB, F, Sc>
where
B: Clone + Send + Sync + 'static,
EB: Fn(&S) -> Vec<B> + Send + Sync,
K: Eq + Hash + Clone + Send + Sync,
KA: Fn(&A) -> K + Send + Sync,
KB: Fn(&B) -> K + Send + Sync,
{
let (key_a, key_b) = joiner.into_keys();
IfExistsStream::new(
ExistenceMode::Exists,
self.extractor,
extractor_b,
key_a,
key_b,
self.filter,
)
}
/* Filters A entities based on whether NO matching B entity exists.
Use this when the B collection needs filtering.
The `extractor_b` returns a `Vec<B>` to allow for filtering.
Any filters accumulated on this stream are applied to A entities.
# Example
```
use solverforge_scoring::stream::ConstraintFactory;
use solverforge_scoring::stream::joiner::equal_bi;
use solverforge_scoring::api::constraint_set::IncrementalConstraint;
use solverforge_core::score::SoftScore;
#[derive(Clone)]
struct Task { id: usize, assignee: Option<usize> }
#[derive(Clone)]
struct Worker { id: usize, available: bool }
#[derive(Clone)]
struct Schedule { tasks: Vec<Task>, workers: Vec<Worker> }
// Penalize tasks assigned to workers who are not available
let constraint = ConstraintFactory::<Schedule, SoftScore>::new()
.for_each(|s: &Schedule| s.tasks.as_slice())
.filter(|task: &Task| task.assignee.is_some())
.if_not_exists_filtered(
|s: &Schedule| s.workers.iter().filter(|w| w.available).cloned().collect(),
equal_bi(
|task: &Task| task.assignee,
|worker: &Worker| Some(worker.id),
),
)
.penalize(SoftScore::of(1))
.named("Unavailable worker");
let schedule = Schedule {
tasks: vec![
Task { id: 0, assignee: Some(0) }, // worker 0 is unavailable
Task { id: 1, assignee: Some(1) }, // worker 1 is available
Task { id: 2, assignee: None }, // unassigned (filtered out)
],
workers: vec![
Worker { id: 0, available: false },
Worker { id: 1, available: true },
],
};
// Task 0's worker (id=0) is NOT in the available workers list
assert_eq!(constraint.evaluate(&schedule), SoftScore::of(-1));
```
*/
pub fn if_not_exists_filtered<B, EB, K, KA, KB>(
self,
extractor_b: EB,
joiner: EqualJoiner<KA, KB, K>,
) -> IfExistsStream<S, A, B, K, E, EB, KA, KB, F, Sc>
where
B: Clone + Send + Sync + 'static,
EB: Fn(&S) -> Vec<B> + Send + Sync,
K: Eq + Hash + Clone + Send + Sync,
KA: Fn(&A) -> K + Send + Sync,
KB: Fn(&B) -> K + Send + Sync,
{
let (key_a, key_b) = joiner.into_keys();
IfExistsStream::new(
ExistenceMode::NotExists,
self.extractor,
extractor_b,
key_a,
key_b,
self.filter,
)
}
// Penalizes each matching entity with a fixed weight.
pub fn penalize(
self,
weight: Sc,
) -> UniConstraintBuilder<S, A, E, F, impl Fn(&A) -> Sc + Send + Sync, Sc>
where
Sc: Copy,
{
// Detect if this is a hard constraint by checking if hard level is non-zero
let is_hard = weight
.to_level_numbers()
.first()
.map(|&h| h != 0)
.unwrap_or(false);
UniConstraintBuilder {
extractor: self.extractor,
filter: self.filter,
impact_type: ImpactType::Penalty,
weight: move |_: &A| weight,
is_hard,
expected_descriptor: None,
_phantom: PhantomData,
}
}
/* Penalizes each matching entity with a dynamic weight.
Note: For dynamic weights, use `penalize_hard_with` to explicitly mark as a hard constraint,
since the weight function cannot be evaluated at build time.
*/
pub fn penalize_with<W>(self, weight_fn: W) -> UniConstraintBuilder<S, A, E, F, W, Sc>
where
W: Fn(&A) -> Sc + Send + Sync,
{
UniConstraintBuilder {
extractor: self.extractor,
filter: self.filter,
impact_type: ImpactType::Penalty,
weight: weight_fn,
is_hard: false, // Can't detect at build time; use penalize_hard_with for hard constraints
expected_descriptor: None,
_phantom: PhantomData,
}
}
// Penalizes each matching entity with a dynamic weight, explicitly marked as a hard constraint.
pub fn penalize_hard_with<W>(self, weight_fn: W) -> UniConstraintBuilder<S, A, E, F, W, Sc>
where
W: Fn(&A) -> Sc + Send + Sync,
{
UniConstraintBuilder {
extractor: self.extractor,
filter: self.filter,
impact_type: ImpactType::Penalty,
weight: weight_fn,
is_hard: true,
expected_descriptor: None,
_phantom: PhantomData,
}
}
// Rewards each matching entity with a fixed weight.
pub fn reward(
self,
weight: Sc,
) -> UniConstraintBuilder<S, A, E, F, impl Fn(&A) -> Sc + Send + Sync, Sc>
where
Sc: Copy,
{
// Detect if this is a hard constraint by checking if hard level is non-zero
let is_hard = weight
.to_level_numbers()
.first()
.map(|&h| h != 0)
.unwrap_or(false);
UniConstraintBuilder {
extractor: self.extractor,
filter: self.filter,
impact_type: ImpactType::Reward,
weight: move |_: &A| weight,
is_hard,
expected_descriptor: None,
_phantom: PhantomData,
}
}
/* Rewards each matching entity with a dynamic weight.
Note: For dynamic weights, use `reward_hard_with` to explicitly mark as a hard constraint,
since the weight function cannot be evaluated at build time.
*/
pub fn reward_with<W>(self, weight_fn: W) -> UniConstraintBuilder<S, A, E, F, W, Sc>
where
W: Fn(&A) -> Sc + Send + Sync,
{
UniConstraintBuilder {
extractor: self.extractor,
filter: self.filter,
impact_type: ImpactType::Reward,
weight: weight_fn,
is_hard: false, // Can't detect at build time; use reward_hard_with for hard constraints
expected_descriptor: None,
_phantom: PhantomData,
}
}
// Rewards each matching entity with a dynamic weight, explicitly marked as a hard constraint.
pub fn reward_hard_with<W>(self, weight_fn: W) -> UniConstraintBuilder<S, A, E, F, W, Sc>
where
W: Fn(&A) -> Sc + Send + Sync,
{
UniConstraintBuilder {
extractor: self.extractor,
filter: self.filter,
impact_type: ImpactType::Reward,
weight: weight_fn,
is_hard: true,
expected_descriptor: None,
_phantom: PhantomData,
}
}
// Penalizes each matching entity with one hard score unit.
pub fn penalize_hard(
self,
) -> UniConstraintBuilder<S, A, E, F, impl Fn(&A) -> Sc + Send + Sync, Sc>
where
Sc: Copy,
{
self.penalize(Sc::one_hard())
}
// Penalizes each matching entity with one soft score unit.
pub fn penalize_soft(
self,
) -> UniConstraintBuilder<S, A, E, F, impl Fn(&A) -> Sc + Send + Sync, Sc>
where
Sc: Copy,
{
self.penalize(Sc::one_soft())
}
// Rewards each matching entity with one hard score unit.
pub fn reward_hard(
self,
) -> UniConstraintBuilder<S, A, E, F, impl Fn(&A) -> Sc + Send + Sync, Sc>
where
Sc: Copy,
{
self.reward(Sc::one_hard())
}
// Rewards each matching entity with one soft score unit.
pub fn reward_soft(
self,
) -> UniConstraintBuilder<S, A, E, F, impl Fn(&A) -> Sc + Send + Sync, Sc>
where
Sc: Copy,
{
self.reward(Sc::one_soft())
}
}
impl<S, A, E, F, Sc: Score> UniConstraintStream<S, A, E, F, Sc> {
#[doc(hidden)]
pub fn extractor(&self) -> &E {
&self.extractor
}
#[doc(hidden)]
pub fn into_parts(self) -> (E, F) {
(self.extractor, self.filter)
}
#[doc(hidden)]
pub fn from_parts(extractor: E, filter: F) -> Self {
Self {
extractor,
filter,
_phantom: PhantomData,
}
}
}
impl<S, A, E, F, Sc: Score> std::fmt::Debug for UniConstraintStream<S, A, E, F, Sc> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UniConstraintStream").finish()
}
}
// Zero-erasure builder for finalizing a uni-constraint.
pub struct UniConstraintBuilder<S, A, E, F, W, Sc>
where
Sc: Score,
{
extractor: E,
filter: F,
impact_type: ImpactType,
weight: W,
is_hard: bool,
expected_descriptor: Option<usize>,
_phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> Sc)>,
}
impl<S, A, E, F, W, Sc> UniConstraintBuilder<S, A, E, F, W, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
E: CollectionExtract<S, Item = A>,
F: UniFilter<S, A>,
W: Fn(&A) -> Sc + Send + Sync,
Sc: Score + 'static,
{
/* Restricts this constraint to only fire for the given descriptor index.
Required when multiple entity classes exist (e.g., FurnaceAssignment at 0,
ShiftAssignment at 1). Without this, on_insert/on_retract fire for all entity
classes using the constraint's entity_index, which indexes into the wrong slice.
*/
pub fn for_descriptor(mut self, descriptor_index: usize) -> Self {
self.expected_descriptor = Some(descriptor_index);
self
}
// Finalizes the builder into a zero-erasure `IncrementalUniConstraint`.
pub fn named(
self,
name: &str,
) -> IncrementalUniConstraint<S, A, E, impl Fn(&S, &A) -> bool + Send + Sync, W, Sc> {
let filter = self.filter;
let combined_filter = move |s: &S, a: &A| filter.test(s, a);
let mut constraint = IncrementalUniConstraint::new(
ConstraintRef::new("", name),
self.impact_type,
self.extractor,
combined_filter,
self.weight,
self.is_hard,
);
if let Some(d) = self.expected_descriptor {
constraint = constraint.with_descriptor(d);
}
constraint
}
}
impl<S, A, E, F, W, Sc: Score> std::fmt::Debug for UniConstraintBuilder<S, A, E, F, W, Sc> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UniConstraintBuilder")
.field("impact_type", &self.impact_type)
.finish()
}
}