solverforge-scoring 0.30.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
470
471
472
473
474
475
476
477
478
479
480
481
use std::collections::VecDeque;

use crate::constraint::score_sum::{checked, ScoreSum};
use solverforge_core::score::Score;
use solverforge_core::ConstraintRef;

use super::incremental::{ConstraintMetadata, ConstraintResult, ConstraintSet};
use crate::api::analysis::ConstraintAnalysis;

/// Two constraint sets scored as one, left first then right.
///
/// Results, metadata entries and weight slots list every `Left` constraint
/// before every `Right` one. `#[solverforge_constraints]` builds these to join
/// member sets without erasing their concrete types.
pub struct ConstraintSetChain<Left, Right> {
    left: Left,
    right: Right,
}

/// Where the next authored constraint of an [`OrderedConstraintSetChain`] comes
/// from.
pub enum ConstraintSetSource {
    /// The next single constraint of the left (shared-node) set.
    Left,
    /// The next member of the right set, which may span several constraints.
    Right {
        /// Number of per-constraint results this member contributes.
        constraint_count: usize,
        /// Number of raw metadata entries this member contributes.
        metadata_entry_count: usize,
    },
}

/// Two constraint sets scored as one while reporting per-constraint output in
/// authored order.
///
/// `order` interleaves the left and right outputs: each [`ConstraintSetSource::Left`]
/// takes one item from the left set, each [`ConstraintSetSource::Right`] takes its
/// spans from the right set. Scores are plain sums; only result, analysis and
/// metadata lists are reordered. Weight slots keep structural order (left set
/// first). The per-constraint methods panic when `order` does not consume every
/// left and right item exactly.
pub struct OrderedConstraintSetChain<Left, Right> {
    left: Left,
    right: Right,
    order: Vec<ConstraintSetSource>,
}

impl<Left, Right> ConstraintSetChain<Left, Right> {
    /// Chains `left` and `right`; the left set's constraints come first.
    pub fn new(left: Left, right: Right) -> Self {
        Self { left, right }
    }
}

impl<Left, Right> OrderedConstraintSetChain<Left, Right> {
    /// Chains `left` and `right`, reporting per-constraint output in the order
    /// given by `order`.
    pub fn new(left: Left, right: Right, order: Vec<ConstraintSetSource>) -> Self {
        Self { left, right, order }
    }

    /// Restores authored order across per-constraint left and right outputs.
    fn interleave<T>(&self, left: Vec<T>, right: Vec<T>, what: &str) -> Vec<T> {
        let mut left = VecDeque::from(left);
        let mut right = VecDeque::from(right);
        let mut values = Vec::with_capacity(left.len() + right.len());
        for source in &self.order {
            match source {
                ConstraintSetSource::Left => {
                    let Some(value) = left.pop_front() else {
                        panic!("ordered constraint set source order does not match {what}");
                    };
                    values.push(value);
                }
                ConstraintSetSource::Right {
                    constraint_count, ..
                } => {
                    for _ in 0..*constraint_count {
                        let Some(value) = right.pop_front() else {
                            panic!("ordered constraint set source order does not match {what}");
                        };
                        values.push(value);
                    }
                }
            }
        }
        assert!(
            left.is_empty() && right.is_empty(),
            "ordered constraint set source order does not consume every one of the {what}"
        );
        values
    }
}

/* Weighted delta methods shared by both chains: the left child owns the first
`left.constraint_count()` weight slots and the right child the rest. */
macro_rules! chain_weighted_deltas {
    () => {
        fn constraint_weight_refs<'a>(&'a self, refs: &mut Vec<&'a ConstraintRef>) {
            self.left.constraint_weight_refs(refs);
            self.right.constraint_weight_refs(refs);
        }

        #[inline]
        fn evaluate_all_weighted(&self, solution: &S, multipliers: &[u32]) -> Sc {
            let (left, right) = multipliers.split_at(self.left.constraint_count());
            self.left.evaluate_all_weighted(solution, left)
                + self.right.evaluate_all_weighted(solution, right)
        }

        #[inline]
        fn initialize_all_weighted(&mut self, solution: &S, multipliers: &[u32]) -> Sc {
            let (left, right) = multipliers.split_at(self.left.constraint_count());
            self.left.initialize_all_weighted(solution, left)
                + self.right.initialize_all_weighted(solution, right)
        }

        #[inline]
        fn on_insert_all_weighted(
            &mut self,
            solution: &S,
            entity_index: usize,
            descriptor_index: usize,
            multipliers: &[u32],
        ) -> Sc {
            checked(self.on_insert_all_weighted_overflowing(
                solution,
                entity_index,
                descriptor_index,
                multipliers,
            ))
        }

        #[inline]
        fn on_retract_all_weighted(
            &mut self,
            solution: &S,
            entity_index: usize,
            descriptor_index: usize,
            multipliers: &[u32],
        ) -> Sc {
            checked(self.on_retract_all_weighted_overflowing(
                solution,
                entity_index,
                descriptor_index,
                multipliers,
            ))
        }

        #[inline]
        fn on_insert_all_weighted_overflowing(
            &mut self,
            solution: &S,
            entity_index: usize,
            descriptor_index: usize,
            multipliers: &[u32],
        ) -> (Sc, bool) {
            let (left, right) = multipliers.split_at(self.left.constraint_count());
            let mut delta = ScoreSum::new();
            delta.add_parts(self.left.on_insert_all_weighted_overflowing(
                solution,
                entity_index,
                descriptor_index,
                left,
            ));
            delta.add_parts(self.right.on_insert_all_weighted_overflowing(
                solution,
                entity_index,
                descriptor_index,
                right,
            ));
            delta.into_parts()
        }

        #[inline]
        fn on_retract_all_weighted_overflowing(
            &mut self,
            solution: &S,
            entity_index: usize,
            descriptor_index: usize,
            multipliers: &[u32],
        ) -> (Sc, bool) {
            let (left, right) = multipliers.split_at(self.left.constraint_count());
            let mut delta = ScoreSum::new();
            delta.add_parts(self.left.on_retract_all_weighted_overflowing(
                solution,
                entity_index,
                descriptor_index,
                left,
            ));
            delta.add_parts(self.right.on_retract_all_weighted_overflowing(
                solution,
                entity_index,
                descriptor_index,
                right,
            ));
            delta.into_parts()
        }
    };
}

impl<S, Sc, Left, Right> ConstraintSet<S, Sc> for ConstraintSetChain<Left, Right>
where
    S: Send + Sync,
    Sc: Score,
    Left: ConstraintSet<S, Sc>,
    Right: ConstraintSet<S, Sc>,
{
    #[inline]
    fn evaluate_all(&self, solution: &S) -> Sc {
        self.left.evaluate_all(solution) + self.right.evaluate_all(solution)
    }

    #[inline]
    fn constraint_count(&self) -> usize {
        self.left.constraint_count() + self.right.constraint_count()
    }

    fn constraint_metadata_entries(&self) -> Vec<ConstraintMetadata<'_>> {
        let mut metadata = self.left.constraint_metadata_entries();
        metadata.extend(self.right.constraint_metadata_entries());
        metadata
    }

    fn evaluate_each<'a>(&'a self, solution: &S) -> Vec<ConstraintResult<'a, Sc>> {
        let mut results = self.left.evaluate_each(solution);
        results.extend(self.right.evaluate_each(solution));
        results
    }

    fn evaluate_detailed<'a>(&'a self, solution: &S) -> Vec<ConstraintAnalysis<'a, Sc>> {
        let mut analyses = self.left.evaluate_detailed(solution);
        analyses.extend(self.right.evaluate_detailed(solution));
        analyses
    }

    #[inline]
    fn initialize_all(&mut self, solution: &S) -> Sc {
        self.left.initialize_all(solution) + self.right.initialize_all(solution)
    }

    #[inline]
    fn on_insert_all(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
        checked(self.on_insert_all_overflowing(solution, entity_index, descriptor_index))
    }

    #[inline]
    fn on_insert_all_overflowing(
        &mut self,
        solution: &S,
        entity_index: usize,
        descriptor_index: usize,
    ) -> (Sc, bool) {
        let mut delta = ScoreSum::new();
        delta.add_parts(self.left.on_insert_all_overflowing(
            solution,
            entity_index,
            descriptor_index,
        ));
        delta.add_parts(self.right.on_insert_all_overflowing(
            solution,
            entity_index,
            descriptor_index,
        ));
        delta.into_parts()
    }

    #[inline]
    fn on_retract_all(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
        checked(self.on_retract_all_overflowing(solution, entity_index, descriptor_index))
    }

    #[inline]
    fn on_retract_all_overflowing(
        &mut self,
        solution: &S,
        entity_index: usize,
        descriptor_index: usize,
    ) -> (Sc, bool) {
        let mut delta = ScoreSum::new();
        delta.add_parts(self.left.on_retract_all_overflowing(
            solution,
            entity_index,
            descriptor_index,
        ));
        delta.add_parts(self.right.on_retract_all_overflowing(
            solution,
            entity_index,
            descriptor_index,
        ));
        delta.into_parts()
    }

    #[inline]
    fn reset_all(&mut self) {
        self.left.reset_all();
        self.right.reset_all();
    }

    chain_weighted_deltas!();

    fn evaluate_each_weighted<'a>(
        &'a self,
        solution: &S,
        multipliers: &[u32],
    ) -> Vec<ConstraintResult<'a, Sc>> {
        let (left, right) = multipliers.split_at(self.left.constraint_count());
        let mut results = self.left.evaluate_each_weighted(solution, left);
        results.extend(self.right.evaluate_each_weighted(solution, right));
        results
    }

    fn evaluate_detailed_weighted<'a>(
        &'a self,
        solution: &S,
        multipliers: &[u32],
    ) -> Vec<ConstraintAnalysis<'a, Sc>> {
        let (left, right) = multipliers.split_at(self.left.constraint_count());
        let mut analyses = self.left.evaluate_detailed_weighted(solution, left);
        analyses.extend(self.right.evaluate_detailed_weighted(solution, right));
        analyses
    }
}

impl<S, Sc, Left, Right> ConstraintSet<S, Sc> for OrderedConstraintSetChain<Left, Right>
where
    S: Send + Sync,
    Sc: Score,
    Left: ConstraintSet<S, Sc>,
    Right: ConstraintSet<S, Sc>,
{
    #[inline]
    fn evaluate_all(&self, solution: &S) -> Sc {
        self.left.evaluate_all(solution) + self.right.evaluate_all(solution)
    }

    #[inline]
    fn constraint_count(&self) -> usize {
        self.left.constraint_count() + self.right.constraint_count()
    }

    fn constraint_metadata_entries(&self) -> Vec<ConstraintMetadata<'_>> {
        let mut left = VecDeque::from(self.left.constraint_metadata_entries());
        let mut right = VecDeque::from(self.right.constraint_metadata_entries());
        let mut metadata = Vec::new();
        for source in &self.order {
            match source {
                ConstraintSetSource::Left => {
                    let Some(candidate) = left.pop_front() else {
                        panic!("ordered constraint set source order does not match metadata");
                    };
                    metadata.push(candidate);
                }
                ConstraintSetSource::Right {
                    metadata_entry_count,
                    ..
                } => {
                    for _ in 0..*metadata_entry_count {
                        let Some(candidate) = right.pop_front() else {
                            panic!("ordered constraint set source order does not match metadata");
                        };
                        metadata.push(candidate);
                    }
                }
            }
        }
        assert!(
            left.is_empty() && right.is_empty(),
            "ordered constraint set source order does not consume every metadata entry"
        );
        metadata
    }

    fn evaluate_each<'a>(&'a self, solution: &S) -> Vec<ConstraintResult<'a, Sc>> {
        self.interleave(
            self.left.evaluate_each(solution),
            self.right.evaluate_each(solution),
            "constraint results",
        )
    }

    fn evaluate_detailed<'a>(&'a self, solution: &S) -> Vec<ConstraintAnalysis<'a, Sc>> {
        self.interleave(
            self.left.evaluate_detailed(solution),
            self.right.evaluate_detailed(solution),
            "constraint analyses",
        )
    }

    #[inline]
    fn initialize_all(&mut self, solution: &S) -> Sc {
        self.left.initialize_all(solution) + self.right.initialize_all(solution)
    }

    #[inline]
    fn on_insert_all(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
        checked(self.on_insert_all_overflowing(solution, entity_index, descriptor_index))
    }

    #[inline]
    fn on_insert_all_overflowing(
        &mut self,
        solution: &S,
        entity_index: usize,
        descriptor_index: usize,
    ) -> (Sc, bool) {
        let mut delta = ScoreSum::new();
        delta.add_parts(self.left.on_insert_all_overflowing(
            solution,
            entity_index,
            descriptor_index,
        ));
        delta.add_parts(self.right.on_insert_all_overflowing(
            solution,
            entity_index,
            descriptor_index,
        ));
        delta.into_parts()
    }

    #[inline]
    fn on_retract_all(&mut self, solution: &S, entity_index: usize, descriptor_index: usize) -> Sc {
        checked(self.on_retract_all_overflowing(solution, entity_index, descriptor_index))
    }

    #[inline]
    fn on_retract_all_overflowing(
        &mut self,
        solution: &S,
        entity_index: usize,
        descriptor_index: usize,
    ) -> (Sc, bool) {
        let mut delta = ScoreSum::new();
        delta.add_parts(self.left.on_retract_all_overflowing(
            solution,
            entity_index,
            descriptor_index,
        ));
        delta.add_parts(self.right.on_retract_all_overflowing(
            solution,
            entity_index,
            descriptor_index,
        ));
        delta.into_parts()
    }

    #[inline]
    fn reset_all(&mut self) {
        self.left.reset_all();
        self.right.reset_all();
    }

    chain_weighted_deltas!();

    fn evaluate_each_weighted<'a>(
        &'a self,
        solution: &S,
        multipliers: &[u32],
    ) -> Vec<ConstraintResult<'a, Sc>> {
        let (left, right) = multipliers.split_at(self.left.constraint_count());
        self.interleave(
            self.left.evaluate_each_weighted(solution, left),
            self.right.evaluate_each_weighted(solution, right),
            "constraint results",
        )
    }

    fn evaluate_detailed_weighted<'a>(
        &'a self,
        solution: &S,
        multipliers: &[u32],
    ) -> Vec<ConstraintAnalysis<'a, Sc>> {
        let (left, right) = multipliers.split_at(self.left.constraint_count());
        self.interleave(
            self.left.evaluate_detailed_weighted(solution, left),
            self.right.evaluate_detailed_weighted(solution, right),
            "constraint analyses",
        )
    }
}