solverforge-solver 0.17.1

Solver engine 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
use std::fmt;
use std::marker::PhantomData;

use solverforge_core::domain::{
    DynamicListVariableSlot, DynamicScalarVariableSlot, SolutionDescriptor,
};

use super::{ConflictRepair, ListVariableSlot, ScalarGroupBinding, ScalarVariableSlot};

pub enum VariableSlot<S, V, DM, IDM> {
    Scalar(ScalarVariableSlot<S>),
    List(ListVariableSlot<S, V, DM, IDM>),
    DynamicScalar(DynamicScalarVariableSlot<S>),
    DynamicList(DynamicListVariableSlot<S>),
}

impl<S, V, DM: Clone, IDM: Clone> Clone for VariableSlot<S, V, DM, IDM> {
    fn clone(&self) -> Self {
        match self {
            Self::Scalar(variable) => Self::Scalar(*variable),
            Self::List(variable) => Self::List(variable.clone()),
            Self::DynamicScalar(variable) => Self::DynamicScalar(variable.clone()),
            Self::DynamicList(variable) => Self::DynamicList(variable.clone()),
        }
    }
}

impl<S, V, DM: fmt::Debug, IDM: fmt::Debug> fmt::Debug for VariableSlot<S, V, DM, IDM> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Scalar(variable) => variable.fmt(f),
            Self::List(variable) => variable.fmt(f),
            Self::DynamicScalar(variable) => variable.fmt(f),
            Self::DynamicList(variable) => variable.fmt(f),
        }
    }
}

pub struct RuntimeModel<S, V, DM, IDM> {
    variables: Vec<VariableSlot<S, V, DM, IDM>>,
    scalar_groups: Vec<ScalarGroupBinding<S>>,
    conflict_repairs: Vec<ConflictRepair<S>>,
    _phantom: PhantomData<(fn() -> S, fn() -> V)>,
}

impl<S, V, DM: Clone, IDM: Clone> Clone for RuntimeModel<S, V, DM, IDM> {
    fn clone(&self) -> Self {
        Self {
            variables: self.variables.clone(),
            scalar_groups: self.scalar_groups.clone(),
            conflict_repairs: self.conflict_repairs.clone(),
            _phantom: PhantomData,
        }
    }
}

impl<S, V, DM, IDM> RuntimeModel<S, V, DM, IDM> {
    pub fn new(variables: Vec<VariableSlot<S, V, DM, IDM>>) -> Self {
        Self {
            variables,
            scalar_groups: Vec::new(),
            conflict_repairs: Vec::new(),
            _phantom: PhantomData,
        }
    }

    pub fn with_scalar_groups(mut self, groups: Vec<ScalarGroupBinding<S>>) -> Self {
        self.scalar_groups = groups;
        self
    }

    pub fn with_conflict_repairs(mut self, repairs: Vec<ConflictRepair<S>>) -> Self {
        self.conflict_repairs = repairs;
        self
    }

    pub fn resolve_dynamic_descriptor_indexes(
        mut self,
        descriptor: &SolutionDescriptor,
    ) -> Result<Self, String> {
        for variable in &mut self.variables {
            match variable {
                VariableSlot::DynamicScalar(slot) => slot.resolve_descriptor_index(descriptor)?,
                VariableSlot::DynamicList(slot) => slot.resolve_descriptor_index(descriptor)?,
                VariableSlot::Scalar(_) | VariableSlot::List(_) => {}
            }
        }
        Ok(self)
    }

    pub fn assert_dynamic_descriptor_indexes_resolved(&self) {
        for variable in &self.variables {
            match variable {
                VariableSlot::DynamicScalar(slot) => {
                    let _ = slot.descriptor_index();
                }
                VariableSlot::DynamicList(slot) => {
                    let _ = slot.descriptor_index();
                }
                VariableSlot::Scalar(_) | VariableSlot::List(_) => {}
            }
        }
    }

    pub fn variables(&self) -> &[VariableSlot<S, V, DM, IDM>] {
        &self.variables
    }

    pub fn scalar_groups(&self) -> &[ScalarGroupBinding<S>] {
        &self.scalar_groups
    }

    pub fn conflict_repairs(&self) -> &[ConflictRepair<S>] {
        &self.conflict_repairs
    }

    pub fn is_empty(&self) -> bool {
        self.variables.is_empty()
    }

    pub fn has_list_variables(&self) -> bool {
        self.variables.iter().any(|variable| {
            matches!(
                variable,
                VariableSlot::List(_) | VariableSlot::DynamicList(_)
            )
        })
    }

    pub fn has_scalar_variables(&self) -> bool {
        self.variables.iter().any(|variable| {
            matches!(
                variable,
                VariableSlot::Scalar(_) | VariableSlot::DynamicScalar(_)
            )
        })
    }

    pub fn has_dynamic_variables(&self) -> bool {
        self.variables.iter().any(|variable| {
            matches!(
                variable,
                VariableSlot::DynamicScalar(_) | VariableSlot::DynamicList(_)
            )
        })
    }

    pub fn has_dynamic_list_variables(&self) -> bool {
        self.variables
            .iter()
            .any(|variable| matches!(variable, VariableSlot::DynamicList(_)))
    }

    pub fn is_scalar_only(&self) -> bool {
        self.has_scalar_variables() && !self.has_list_variables()
    }

    pub fn has_nearby_scalar_change_variables(&self) -> bool {
        self.scalar_variables()
            .any(ScalarVariableSlot::supports_nearby_change)
    }

    pub fn has_nearby_scalar_swap_variables(&self) -> bool {
        self.scalar_variables()
            .any(ScalarVariableSlot::supports_nearby_swap)
    }

    pub fn assignment_scalar_groups(
        &self,
    ) -> impl Iterator<Item = (usize, &ScalarGroupBinding<S>)> {
        self.scalar_groups
            .iter()
            .enumerate()
            .filter(|(_, group)| group.is_assignment())
    }

    pub fn assignment_group_covers_scalar_variable(
        &self,
        variable: &ScalarVariableSlot<S>,
    ) -> bool {
        self.assignment_scalar_groups().any(|(_, group)| {
            group.members.iter().any(|member| {
                member.descriptor_index == variable.descriptor_index
                    && member.variable_index == variable.variable_index
            })
        })
    }

    pub fn has_scalar_groups(&self) -> bool {
        !self.scalar_groups.is_empty()
    }

    pub fn has_assignment_scalar_groups(&self) -> bool {
        self.assignment_scalar_groups().next().is_some()
    }

    pub fn candidate_scalar_groups(&self) -> impl Iterator<Item = (usize, &ScalarGroupBinding<S>)> {
        self.scalar_groups
            .iter()
            .enumerate()
            .filter(|(_, group)| group.is_candidate_group())
    }

    pub fn has_candidate_scalar_groups(&self) -> bool {
        self.candidate_scalar_groups().next().is_some()
    }

    pub fn has_list_ruin_variables(&self) -> bool {
        self.list_variables().any(ListVariableSlot::supports_ruin)
    }

    pub fn list_precedence_variables(
        &self,
    ) -> impl Iterator<Item = &ListVariableSlot<S, V, DM, IDM>> {
        self.list_variables()
            .filter(|variable| variable.supports_precedence_moves())
    }

    pub fn has_list_precedence_variables(&self) -> bool {
        self.list_precedence_variables().next().is_some()
    }

    pub fn has_k_opt_variables(&self) -> bool {
        self.list_variables().any(ListVariableSlot::supports_k_opt)
    }

    pub fn has_conflict_repairs(&self) -> bool {
        !self.conflict_repairs.is_empty()
    }

    pub fn scalar_variables(&self) -> impl Iterator<Item = &ScalarVariableSlot<S>> {
        self.variables.iter().filter_map(|variable| match variable {
            VariableSlot::Scalar(ctx) => Some(ctx),
            VariableSlot::List(_)
            | VariableSlot::DynamicScalar(_)
            | VariableSlot::DynamicList(_) => None,
        })
    }

    pub fn dynamic_scalar_variables(&self) -> impl Iterator<Item = &DynamicScalarVariableSlot<S>> {
        self.variables.iter().filter_map(|variable| match variable {
            VariableSlot::DynamicScalar(ctx) => Some(ctx),
            VariableSlot::Scalar(_) | VariableSlot::List(_) | VariableSlot::DynamicList(_) => None,
        })
    }

    pub fn scalar_variable_target(
        &self,
        entity_class: Option<&str>,
        variable_name: Option<&str>,
    ) -> Result<ScalarVariableSlot<S>, String> {
        let mut matches = self
            .scalar_variables()
            .filter(|slot| slot.matches_target(entity_class, variable_name));
        let Some(first) = matches.next().copied() else {
            return Err(match (entity_class, variable_name) {
                (Some(entity), Some(variable)) => {
                    format!("no scalar variable `{entity}.{variable}` exists in the runtime model")
                }
                (Some(entity), None) => {
                    format!("no scalar variable for entity `{entity}` exists in the runtime model")
                }
                (None, Some(variable)) => {
                    format!("no scalar variable named `{variable}` exists in the runtime model")
                }
                (None, None) => {
                    "exhaustive search requires exactly one scalar variable or an explicit target"
                        .to_string()
                }
            });
        };
        if matches.next().is_some() {
            return Err(
                "exhaustive search target is ambiguous; specify entity_class and variable_name"
                    .to_string(),
            );
        }
        Ok(first)
    }

    pub fn finite_scalar_candidate_space_estimate(
        &self,
        solution: &S,
        slot: ScalarVariableSlot<S>,
        value_candidate_limit: Option<usize>,
    ) -> Option<usize> {
        let entity_count = (slot.entity_count)(solution);
        let mut total: usize = 1;
        for entity_index in 0..entity_count {
            let candidate_count = slot
                .candidate_values_for_entity(solution, entity_index, value_candidate_limit)
                .len();
            if candidate_count == 0 {
                return Some(0);
            }
            total = total.checked_mul(candidate_count)?;
        }
        Some(total)
    }

    pub fn list_variables(&self) -> impl Iterator<Item = &ListVariableSlot<S, V, DM, IDM>> {
        self.variables.iter().filter_map(|variable| match variable {
            VariableSlot::List(ctx) => Some(ctx),
            VariableSlot::Scalar(_)
            | VariableSlot::DynamicScalar(_)
            | VariableSlot::DynamicList(_) => None,
        })
    }

    pub fn dynamic_list_variables(&self) -> impl Iterator<Item = &DynamicListVariableSlot<S>> {
        self.variables.iter().filter_map(|variable| match variable {
            VariableSlot::DynamicList(ctx) => Some(ctx),
            VariableSlot::Scalar(_) | VariableSlot::List(_) | VariableSlot::DynamicScalar(_) => {
                None
            }
        })
    }
}

impl<S, V, DM: fmt::Debug, IDM: fmt::Debug> fmt::Debug for RuntimeModel<S, V, DM, IDM> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RuntimeModel")
            .field("variables", &self.variables)
            .field("scalar_groups", &self.scalar_groups)
            .field("conflict_repairs", &self.conflict_repairs)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use solverforge_core::domain::{
        DynamicListVariableSlot, DynamicModelBackend, DynamicScalarVariableSlot, EntityClassId,
        VariableId,
    };
    use solverforge_core::score::SoftScore;

    use super::{RuntimeModel, VariableSlot};

    #[derive(Clone)]
    struct DynamicRows;

    impl DynamicModelBackend for DynamicRows {
        type Score = SoftScore;

        fn entity_count(&self, _entity: EntityClassId) -> usize {
            0
        }

        fn get_scalar(
            &self,
            _entity: EntityClassId,
            _row: usize,
            _variable: VariableId,
        ) -> Option<usize> {
            None
        }

        fn set_scalar(
            &mut self,
            _entity: EntityClassId,
            _row: usize,
            _variable: VariableId,
            _value: Option<usize>,
        ) {
        }

        fn list_len(&self, _entity: EntityClassId, _row: usize, _variable: VariableId) -> usize {
            0
        }

        fn list_get(
            &self,
            _entity: EntityClassId,
            _row: usize,
            _variable: VariableId,
            _pos: usize,
        ) -> Option<usize> {
            None
        }

        fn list_insert(
            &mut self,
            _entity: EntityClassId,
            _row: usize,
            _variable: VariableId,
            _pos: usize,
            _value: usize,
        ) {
        }

        fn list_remove(
            &mut self,
            _entity: EntityClassId,
            _row: usize,
            _variable: VariableId,
            _pos: usize,
        ) -> Option<usize> {
            None
        }

        fn candidate_values(
            &self,
            _entity: EntityClassId,
            _row: usize,
            _variable: VariableId,
        ) -> &[usize] {
            &[]
        }
    }

    #[test]
    fn runtime_model_tracks_dynamic_variable_slots() {
        let scalar =
            DynamicScalarVariableSlot::new(EntityClassId(0), VariableId(0), "Task", "worker", true);
        let list =
            DynamicListVariableSlot::new(EntityClassId(1), VariableId(0), "Vehicle", "visits");

        let model: RuntimeModel<DynamicRows, usize, (), ()> = RuntimeModel::new(vec![
            VariableSlot::DynamicScalar(scalar.clone()),
            VariableSlot::DynamicList(list.clone()),
        ]);

        assert!(model.has_scalar_variables());
        assert!(model.has_list_variables());
        assert_eq!(
            model
                .dynamic_scalar_variables()
                .map(|slot| slot.variable_name)
                .collect::<Vec<_>>(),
            vec!["worker"]
        );
        assert_eq!(
            model
                .dynamic_list_variables()
                .map(|slot| slot.variable_name)
                .collect::<Vec<_>>(),
            vec!["visits"]
        );
        assert_eq!(model.scalar_variables().count(), 0);
        assert_eq!(model.list_variables().count(), 0);
    }

    #[test]
    #[should_panic(
        expected = "dynamic scalar variable Task.worker has not been resolved against a SolutionDescriptor"
    )]
    fn runtime_model_rejects_unresolved_dynamic_slots_for_selector_use() {
        let scalar =
            DynamicScalarVariableSlot::new(EntityClassId(0), VariableId(0), "Task", "worker", true);
        let model: RuntimeModel<DynamicRows, usize, (), ()> =
            RuntimeModel::new(vec![VariableSlot::DynamicScalar(scalar)]);

        model.assert_dynamic_descriptor_indexes_resolved();
    }
}