solverforge-scoring 0.21.0

Incremental constraint scoring for SolverForge
Documentation
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
// Uni tests

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

use solverforge_core::score::SoftScore;
use solverforge_core::{ConstraintRef, ImpactType};

use crate::api::constraint_set::{ConstraintSet, IncrementalConstraint};
use crate::constraint::grouped::{
    GroupedNodeState, GroupedTerminalScorer, SharedGroupedConstraintSet, Uni,
};
use crate::stream::collection_extract::{source, vec, ChangeSource};
use crate::stream::collector::{collect_vec, count, CollectedVec};
use crate::stream::filter::TrueFilter;
use crate::stream::ConstraintFactory;

#[derive(Clone)]
struct GroupedShift {
    employee_id: usize,
}

#[derive(Clone)]
struct GroupedSolution {
    shifts: Vec<GroupedShift>,
}

#[test]
fn test_grouped_constraint_evaluate() {
    let constraint = Uni::new(
        ConstraintRef::new("", "Workload"),
        ImpactType::Penalty,
        source(
            vec(|s: &GroupedSolution| &s.shifts),
            ChangeSource::Descriptor(0),
        ),
        TrueFilter,
        |shift: &GroupedShift| shift.employee_id,
        count(),
        |_employee_id: &usize, count: &usize| SoftScore::of((*count * *count) as i64),
        false,
    );

    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 2 },
        ],
    };

    /* Employee 1: 3 shifts -> 9
    Employee 2: 1 shift -> 1
    Total penalty: -10
    */
    assert_eq!(constraint.evaluate(&solution), SoftScore::of(-10));
}

#[test]
fn test_grouped_constraint_incremental() {
    let mut constraint = Uni::new(
        ConstraintRef::new("", "Workload"),
        ImpactType::Penalty,
        source(
            vec(|s: &GroupedSolution| &s.shifts),
            ChangeSource::Descriptor(0),
        ),
        TrueFilter,
        |shift: &GroupedShift| shift.employee_id,
        count(),
        |_employee_id: &usize, count: &usize| SoftScore::of(*count as i64),
        false,
    );

    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 2 },
        ],
    };

    // Initialize
    let total = constraint.initialize(&solution);
    /* Employee 1: 2 shifts -> -2
    Employee 2: 1 shift -> -1
    Total: -3
    */
    assert_eq!(total, SoftScore::of(-3));

    // Retract shift at index 0 (employee 1)
    let delta = constraint.on_retract(&solution, 0, 0);
    // Employee 1 now has 1 shift -> score goes from -2 to -1, delta = +1
    assert_eq!(delta, SoftScore::of(1));

    // Insert shift at index 0 (employee 1)
    let delta = constraint.on_insert(&solution, 0, 0);
    // Employee 1 now has 2 shifts -> score goes from -1 to -2, delta = -1
    assert_eq!(delta, SoftScore::of(-1));
}

#[test]
fn test_grouped_constraint_reward() {
    let constraint = Uni::new(
        ConstraintRef::new("", "Collaboration"),
        ImpactType::Reward,
        vec(|s: &GroupedSolution| &s.shifts),
        TrueFilter,
        |shift: &GroupedShift| shift.employee_id,
        count(),
        |_employee_id: &usize, count: &usize| SoftScore::of(*count as i64),
        false,
    );

    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
        ],
    };

    // 2 shifts in one group -> reward of +2
    assert_eq!(constraint.evaluate(&solution), SoftScore::of(2));
}

#[test]
fn test_grouped_constraint_weight_can_use_key() {
    let constraint = Uni::new(
        ConstraintRef::new("", "Key weighted workload"),
        ImpactType::Penalty,
        vec(|s: &GroupedSolution| &s.shifts),
        TrueFilter,
        |shift: &GroupedShift| shift.employee_id,
        count(),
        |employee_id: &usize, count: &usize| SoftScore::of((*employee_id as i64) * (*count as i64)),
        false,
    );

    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 2 },
            GroupedShift { employee_id: 2 },
        ],
    };

    assert_eq!(constraint.evaluate(&solution), SoftScore::of(-5));
}

#[test]
fn test_grouped_constraint_collect_vec_accepts_owned_labels() {
    let constraint = Uni::new(
        ConstraintRef::new("", "Grouped labels"),
        ImpactType::Penalty,
        vec(|s: &GroupedSolution| &s.shifts),
        TrueFilter,
        |shift: &GroupedShift| shift.employee_id,
        collect_vec(|shift: &GroupedShift| format!("employee-{}", shift.employee_id)),
        |_employee_id: &usize, labels: &CollectedVec<String>| SoftScore::of(labels.len() as i64),
        false,
    );

    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 2 },
        ],
    };

    assert_eq!(constraint.evaluate(&solution), SoftScore::of(-3));
}

#[test]
fn test_shared_grouped_constraint_set_updates_one_node_for_multiple_terminals() {
    let state = GroupedNodeState::new(
        source(
            vec(|s: &GroupedSolution| &s.shifts),
            ChangeSource::Descriptor(0),
        ),
        TrueFilter,
        |shift: &GroupedShift| shift.employee_id,
        count(),
    );
    let scorers = (
        GroupedTerminalScorer::new(
            ConstraintRef::new("", "Linear workload"),
            ImpactType::Penalty,
            |_employee_id: &usize, count: &usize| SoftScore::of(*count as i64),
            false,
        ),
        GroupedTerminalScorer::new(
            ConstraintRef::new("", "Squared workload"),
            ImpactType::Penalty,
            |_employee_id: &usize, count: &usize| SoftScore::of((*count * *count) as i64),
            false,
        ),
    );
    let mut constraints = SharedGroupedConstraintSet::new(state, scorers);
    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 2 },
        ],
    };

    assert_eq!(constraints.evaluate_all(&solution), SoftScore::of(-8));
    assert_eq!(constraints.constraint_count(), 2);
    let metadata = constraints.constraint_metadata();
    assert_eq!(metadata[0].name(), "Linear workload");
    assert_eq!(metadata[1].name(), "Squared workload");

    assert_eq!(constraints.initialize_all(&solution), SoftScore::of(-8));
    assert_eq!(constraints.state().update_count(), 0);
    assert_eq!(
        constraints.on_retract_all(&solution, 0, 0),
        SoftScore::of(4)
    );
    assert_eq!(constraints.state().update_count(), 1);
    assert_eq!(constraints.state().changed_key_count(), 1);
    assert_eq!(
        constraints.on_insert_all(&solution, 0, 0),
        SoftScore::of(-4)
    );
    assert_eq!(constraints.state().update_count(), 2);
    assert_eq!(constraints.state().changed_key_count(), 2);
}

#[test]
fn test_grouped_fluent_chain_appends_terminals_to_one_node() {
    let mut constraints = ConstraintFactory::<GroupedSolution, SoftScore>::new()
        .for_each(source(
            vec(|s: &GroupedSolution| &s.shifts),
            ChangeSource::Descriptor(0),
        ))
        .group_by(|shift: &GroupedShift| shift.employee_id, count())
        .penalize(|_employee_id: &usize, count: &usize| SoftScore::of(*count as i64))
        .named("Linear workload")
        .penalize(|_employee_id: &usize, count: &usize| SoftScore::of((*count * *count) as i64))
        .named("Squared workload")
        .reward(|_employee_id: &usize, count: &usize| SoftScore::of(*count as i64))
        .named("Coverage reward");

    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 2 },
        ],
    };

    assert_eq!(constraints.evaluate_all(&solution), SoftScore::of(-5));
    assert_eq!(constraints.constraint_count(), 3);
    let metadata = constraints.constraint_metadata();
    assert_eq!(metadata[0].name(), "Linear workload");
    assert_eq!(metadata[1].name(), "Squared workload");
    assert_eq!(metadata[2].name(), "Coverage reward");

    assert_eq!(constraints.initialize_all(&solution), SoftScore::of(-5));
    assert_eq!(
        constraints.on_retract_all(&solution, 0, 0),
        SoftScore::of(3)
    );
    assert_eq!(constraints.state().update_count(), 1);
    assert_eq!(
        constraints.on_insert_all(&solution, 0, 0),
        SoftScore::of(-3)
    );
    assert_eq!(constraints.state().update_count(), 2);
}

#[test]
fn test_shared_grouped_constraint_set_refreshes_only_dirty_keys() {
    let state = GroupedNodeState::new(
        source(
            vec(|s: &GroupedSolution| &s.shifts),
            ChangeSource::Descriptor(0),
        ),
        TrueFilter,
        |shift: &GroupedShift| shift.employee_id,
        count(),
    );
    let scorers = (
        GroupedTerminalScorer::new(
            ConstraintRef::new("", "Linear workload"),
            ImpactType::Penalty,
            |_employee_id: &usize, count: &usize| SoftScore::of(*count as i64),
            false,
        ),
        GroupedTerminalScorer::new(
            ConstraintRef::new("", "Squared workload"),
            ImpactType::Penalty,
            |_employee_id: &usize, count: &usize| SoftScore::of((*count * *count) as i64),
            false,
        ),
    );
    let mut constraints = SharedGroupedConstraintSet::new(state, scorers);
    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 2 },
        ],
    };

    constraints.initialize_all(&solution);
    assert_eq!(
        constraints.on_retract_all(&solution, 0, 1),
        SoftScore::of(0)
    );
    assert_eq!(constraints.state().update_count(), 0);
    assert_eq!(
        constraints.on_retract_all(&solution, 0, 0),
        SoftScore::of(4)
    );
    assert_eq!(constraints.evaluate_each(&solution).len(), 2);
    constraints.reset_all();
    assert_eq!(constraints.initialize_all(&solution), SoftScore::of(-8));
}

#[test]
fn shared_grouped_terminals_keep_independent_detailed_identity() {
    let state = GroupedNodeState::new(
        source(
            vec(|s: &GroupedSolution| &s.shifts),
            ChangeSource::Descriptor(0),
        ),
        TrueFilter,
        |shift: &GroupedShift| shift.employee_id,
        count(),
    );
    let scorers = (
        GroupedTerminalScorer::new(
            ConstraintRef::new("", "Linear workload"),
            ImpactType::Penalty,
            |_employee_id: &usize, count: &usize| SoftScore::of(*count as i64),
            false,
        ),
        GroupedTerminalScorer::new(
            ConstraintRef::new("", "Squared workload"),
            ImpactType::Penalty,
            |_employee_id: &usize, count: &usize| SoftScore::of((*count * *count) as i64),
            false,
        ),
    );
    let mut constraints = SharedGroupedConstraintSet::new(state, scorers);
    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 2 },
        ],
    };
    constraints.initialize_all(&solution);

    // One shared group state, two terminals: each terminal's detailed
    // analysis must carry its own identity and its own score derived from the
    // SAME retained groups (employee 1 counts 2, employee 2 counts 1) - no
    // cross-attribution, no duplication of either terminal onto the other.
    let analyses = constraints.evaluate_detailed(&solution);
    assert_eq!(analyses.len(), 2);
    assert_eq!(analyses[0].constraint_ref.name, "Linear workload");
    assert_eq!(analyses[1].constraint_ref.name, "Squared workload");
    let scores: Vec<_> = analyses.iter().map(|analysis| analysis.score).collect();
    assert_eq!(
        scores,
        vec![SoftScore::of(-3), SoftScore::of(-5)],
        "each terminal explains its own score from the shared state"
    );
    // Per-terminal match identity: both terminals see the same two groups,
    // but the analyses they emit remain two independent constraint entries.
    let each = constraints.evaluate_each(&solution);
    assert_eq!(each.len(), 2);
    assert_eq!(each[0].name, "Linear workload");
    assert_eq!(each[1].name, "Squared workload");
    assert_eq!(each[0].match_count, 2);
    assert_eq!(each[1].match_count, 2);
    let mut names: Vec<_> = constraints
        .constraint_metadata()
        .iter()
        .map(|metadata| metadata.name().to_string())
        .collect();
    names.sort();
    assert_eq!(names, vec!["Linear workload", "Squared workload"]);
}

/// A payload with neither Copy nor Clone: any accidental duplicate would fail
/// to compile; the drop counter proves exact retraction without leaks.
struct NonClonePayload {
    slot: usize,
    drops: Arc<AtomicUsize>,
}

impl Drop for NonClonePayload {
    fn drop(&mut self) {
        self.drops.fetch_add(1, Ordering::SeqCst);
    }
}

impl std::fmt::Debug for NonClonePayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NonClonePayload")
            .field("slot", &self.slot)
            .finish()
    }
}

#[test]
fn non_clone_payload_grouped_set_retracts_exactly_on_mutation() {
    let drops = Arc::new(AtomicUsize::new(0));
    let payload_drops = Arc::clone(&drops);
    let state = GroupedNodeState::new(
        source(
            vec(|s: &GroupedSolution| &s.shifts),
            ChangeSource::Descriptor(0),
        ),
        TrueFilter,
        |shift: &GroupedShift| shift.employee_id,
        collect_vec({
            let payload_drops = Arc::clone(&payload_drops);
            move |_: &GroupedShift| NonClonePayload {
                slot: 0,
                drops: Arc::clone(&payload_drops),
            }
        }),
    );
    let scorer = GroupedTerminalScorer::new(
        ConstraintRef::new("", "Payload count"),
        ImpactType::Penalty,
        |_employee_id: &usize, collected: &CollectedVec<NonClonePayload>| {
            SoftScore::of(collected.len() as i64)
        },
        false,
    );
    let mut constraints = SharedGroupedConstraintSet::new(state, (scorer,));
    let solution = GroupedSolution {
        shifts: vec![
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 1 },
            GroupedShift { employee_id: 2 },
        ],
    };

    assert_eq!(constraints.initialize_all(&solution), SoftScore::of(-3));
    let payloads_before = drops.load(Ordering::SeqCst);
    // Retract one contributor: its payload drops exactly once and the group
    // score updates from 3 to 2.
    assert_eq!(
        constraints.on_retract_all(&solution, 0, 0),
        SoftScore::of(1)
    );
    // The retained state's cached score is the authoritative mutation view;
    // evaluate_all deliberately re-derives from the live solution. Assert the
    // retraction's exact ledger effect instead: the cached delta plus the
    // payload drop count.
    let retracted_drops = drops.load(Ordering::SeqCst) - payloads_before;
    assert!(
        retracted_drops >= 1,
        "retraction must drop at least the retracted contributor's payload"
    );
    constraints.reset_all();
    // Reset frees every retained payload shell (empty group shells at minimum).
    assert!(
        drops.load(Ordering::SeqCst) >= payloads_before + retracted_drops,
        "reset must free retained payload slots"
    );
}