solverforge-solver 0.15.0

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
use std::fmt;

use crate::planning::{
    ScalarAssignmentDeclaration, ScalarAssignmentRule, ScalarCandidateProvider, ScalarEdit,
    ScalarGroup, ScalarGroupKind, ScalarGroupLimits,
};

use super::value_source::ValueSource;
use super::variable::{ScalarGetter, ScalarSetter, ScalarVariableSlot};

pub struct ScalarGroupMemberBinding<S> {
    pub descriptor_index: usize,
    pub variable_index: usize,
    pub entity_type_name: &'static str,
    pub variable_name: &'static str,
    pub getter: ScalarGetter<S>,
    pub setter: ScalarSetter<S>,
    pub value_source: ValueSource<S>,
    pub entity_count: fn(&S) -> usize,
    pub candidate_values: Option<super::variable::ScalarCandidateValues<S>>,
    pub allows_unassigned: bool,
}

impl<S> Clone for ScalarGroupMemberBinding<S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S> Copy for ScalarGroupMemberBinding<S> {}

impl<S> ScalarGroupMemberBinding<S> {
    pub fn from_scalar_slot(slot: ScalarVariableSlot<S>) -> Self {
        Self {
            descriptor_index: slot.descriptor_index,
            variable_index: slot.variable_index,
            entity_type_name: slot.entity_type_name,
            variable_name: slot.variable_name,
            getter: slot.getter,
            setter: slot.setter,
            value_source: slot.value_source,
            entity_count: slot.entity_count,
            candidate_values: slot.candidate_values,
            allows_unassigned: slot.allows_unassigned,
        }
    }

    pub fn current_value(&self, solution: &S, entity_index: usize) -> Option<usize> {
        (self.getter)(solution, entity_index, self.variable_index)
    }

    pub fn value_is_legal(
        &self,
        solution: &S,
        entity_index: usize,
        candidate: Option<usize>,
    ) -> bool {
        let Some(value) = candidate else {
            return self.allows_unassigned;
        };
        match self.value_source {
            ValueSource::Empty => false,
            ValueSource::CountableRange { from, to } => from <= value && value < to,
            ValueSource::SolutionCount {
                count_fn,
                provider_index,
            } => value < count_fn(solution, provider_index),
            ValueSource::EntitySlice { values_for_entity } => {
                values_for_entity(solution, entity_index, self.variable_index).contains(&value)
            }
        }
    }

    pub fn entity_count(&self, solution: &S) -> usize {
        (self.entity_count)(solution)
    }

    pub fn candidate_values(
        &self,
        solution: &S,
        entity_index: usize,
        value_candidate_limit: Option<usize>,
    ) -> Vec<usize> {
        if let Some(candidate_values) = self.candidate_values {
            let values = candidate_values(solution, entity_index, self.variable_index);
            return match value_candidate_limit {
                Some(limit) => values.iter().copied().take(limit).collect(),
                None => values.to_vec(),
            };
        }
        match self.value_source {
            ValueSource::Empty => Vec::new(),
            ValueSource::CountableRange { from, to } => {
                let end = value_candidate_limit
                    .map(|limit| from.saturating_add(limit).min(to))
                    .unwrap_or(to);
                (from..end).collect()
            }
            ValueSource::SolutionCount {
                count_fn,
                provider_index,
            } => {
                let count = count_fn(solution, provider_index);
                let end = value_candidate_limit
                    .map(|limit| limit.min(count))
                    .unwrap_or(count);
                (0..end).collect()
            }
            ValueSource::EntitySlice { values_for_entity } => {
                let values = values_for_entity(solution, entity_index, self.variable_index);
                match value_candidate_limit {
                    Some(limit) => values.iter().copied().take(limit).collect(),
                    None => values.to_vec(),
                }
            }
        }
    }
}

impl<S> fmt::Debug for ScalarGroupMemberBinding<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScalarGroupMemberBinding")
            .field("descriptor_index", &self.descriptor_index)
            .field("variable_index", &self.variable_index)
            .field("entity_type_name", &self.entity_type_name)
            .field("variable_name", &self.variable_name)
            .field("value_source", &self.value_source)
            .field("allows_unassigned", &self.allows_unassigned)
            .finish()
    }
}

pub struct ScalarGroupBinding<S> {
    pub group_name: &'static str,
    pub members: Vec<ScalarGroupMemberBinding<S>>,
    pub kind: ScalarGroupBindingKind<S>,
    pub limits: ScalarGroupLimits,
}

pub enum ScalarGroupBindingKind<S> {
    Candidates {
        candidate_provider: ScalarCandidateProvider<S>,
    },
    Assignment(ScalarAssignmentBinding<S>),
}

impl<S> Clone for ScalarGroupBindingKind<S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S> Copy for ScalarGroupBindingKind<S> {}

pub struct ScalarAssignmentBinding<S> {
    pub target: ScalarGroupMemberBinding<S>,
    pub required_entity: Option<fn(&S, usize) -> bool>,
    pub capacity_key: Option<fn(&S, usize, usize) -> Option<usize>>,
    pub position_key: Option<fn(&S, usize) -> i64>,
    pub sequence_key: Option<fn(&S, usize, usize) -> Option<usize>>,
    pub entity_order: Option<fn(&S, usize) -> i64>,
    pub value_order: Option<fn(&S, usize, usize) -> i64>,
    pub assignment_rule: Option<ScalarAssignmentRule<S>>,
}

impl<S> Clone for ScalarAssignmentBinding<S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S> Copy for ScalarAssignmentBinding<S> {}

impl<S> ScalarAssignmentBinding<S> {
    fn bind(
        group_name: &'static str,
        members: &[ScalarGroupMemberBinding<S>],
        declaration: ScalarAssignmentDeclaration<S>,
    ) -> Self {
        assert_eq!(
            members.len(),
            1,
            "assignment scalar group `{group_name}` must target exactly one scalar planning variable",
        );
        let target = members[0];
        assert!(
            target.allows_unassigned,
            "assignment scalar group `{group_name}` target {}.{} must allow unassigned values",
            target.entity_type_name, target.variable_name,
        );
        assert!(
            declaration.assignment_rule.is_none() || declaration.sequence_key.is_some(),
            "assignment scalar group `{group_name}` with an assignment rule must declare a sequence key",
        );
        Self {
            target,
            required_entity: declaration.required_entity,
            capacity_key: declaration.capacity_key,
            position_key: declaration.position_key,
            sequence_key: declaration.sequence_key,
            entity_order: declaration.entity_order,
            value_order: declaration.value_order,
            assignment_rule: declaration.assignment_rule,
        }
    }

    pub fn entity_count(&self, solution: &S) -> usize {
        self.target.entity_count(solution)
    }

    pub fn current_value(&self, solution: &S, entity_index: usize) -> Option<usize> {
        self.target.current_value(solution, entity_index)
    }

    pub fn is_required(&self, solution: &S, entity_index: usize) -> bool {
        self.required_entity
            .map(|required_entity| required_entity(solution, entity_index))
            .unwrap_or(false)
    }

    pub fn capacity_key(&self, solution: &S, entity_index: usize, value: usize) -> Option<usize> {
        self.capacity_key
            .and_then(|capacity_key| capacity_key(solution, entity_index, value))
    }

    pub fn position_key(&self, solution: &S, entity_index: usize) -> Option<i64> {
        self.position_key
            .map(|position_key| position_key(solution, entity_index))
    }

    pub fn sequence_key(&self, solution: &S, entity_index: usize, value: usize) -> Option<usize> {
        self.sequence_key
            .and_then(|sequence_key| sequence_key(solution, entity_index, value))
    }

    pub fn entity_order_key(&self, solution: &S, entity_index: usize) -> Option<i64> {
        self.entity_order
            .map(|entity_order| entity_order(solution, entity_index))
    }

    pub fn value_order_key(&self, solution: &S, entity_index: usize, value: usize) -> Option<i64> {
        self.value_order
            .map(|value_order| value_order(solution, entity_index, value))
    }

    pub fn assignment_edge_allowed(
        &self,
        solution: &S,
        left_entity: usize,
        left_value: usize,
        right_entity: usize,
        right_value: usize,
    ) -> bool {
        self.assignment_rule
            .map(|assignment_rule| {
                assignment_rule(solution, left_entity, left_value, right_entity, right_value)
            })
            .unwrap_or(true)
    }

    pub fn candidate_values(
        &self,
        solution: &S,
        entity_index: usize,
        value_candidate_limit: Option<usize>,
    ) -> Vec<usize> {
        let mut values =
            self.target
                .candidate_values(solution, entity_index, value_candidate_limit);
        values.sort_by_key(|value| (self.value_order_key(solution, entity_index, *value), *value));
        values
    }

    pub fn value_is_legal(&self, solution: &S, entity_index: usize, value: Option<usize>) -> bool {
        self.target.value_is_legal(solution, entity_index, value)
    }

    pub fn edit(&self, entity_index: usize, value: Option<usize>) -> ScalarEdit<S> {
        ScalarEdit::from_descriptor_index(
            self.target.descriptor_index,
            entity_index,
            self.target.variable_name,
            value,
        )
    }

    pub fn remaining_required_count(&self, solution: &S) -> u64 {
        (0..self.entity_count(solution))
            .filter(|entity_index| {
                self.is_required(solution, *entity_index)
                    && self.current_value(solution, *entity_index).is_none()
            })
            .fold(0_u64, |count, _| count.saturating_add(1))
    }

    pub fn unassigned_count(&self, solution: &S) -> u64 {
        (0..self.entity_count(solution))
            .filter(|entity_index| self.current_value(solution, *entity_index).is_none())
            .fold(0_u64, |count, _| count.saturating_add(1))
    }
}

impl<S> ScalarGroupBinding<S> {
    pub fn bind(group: ScalarGroup<S>, scalar_slots: &[ScalarVariableSlot<S>]) -> Self {
        let members = group
            .targets()
            .iter()
            .map(|target| {
                let descriptor_index = target.descriptor_index();
                let variable_name = target.variable_name();
                let slot = scalar_slots
                    .iter()
                    .copied()
                    .find(|slot| {
                        slot.descriptor_index == descriptor_index
                            && slot.variable_name == variable_name
                    })
                    .unwrap_or_else(|| {
                        panic!(
                            "scalar group `{}` targets unknown scalar variable `{}` on descriptor {}",
                            group.group_name(),
                            variable_name,
                            descriptor_index
                        )
                    });
                ScalarGroupMemberBinding::from_scalar_slot(slot)
            })
            .collect::<Vec<_>>();

        let kind = match group.kind() {
            ScalarGroupKind::Assignment(declaration) => ScalarGroupBindingKind::Assignment(
                ScalarAssignmentBinding::bind(group.group_name(), &members, declaration),
            ),
            ScalarGroupKind::Candidates { candidate_provider } => {
                ScalarGroupBindingKind::Candidates { candidate_provider }
            }
        };

        Self {
            group_name: group.group_name(),
            members,
            kind,
            limits: group.limits(),
        }
    }

    pub fn member_for_edit(&self, edit: &ScalarEdit<S>) -> Option<ScalarGroupMemberBinding<S>> {
        self.members.iter().copied().find(|member| {
            member.descriptor_index == edit.descriptor_index()
                && member.variable_name == edit.variable_name()
        })
    }

    pub fn assignment(&self) -> Option<&ScalarAssignmentBinding<S>> {
        match &self.kind {
            ScalarGroupBindingKind::Assignment(assignment) => Some(assignment),
            ScalarGroupBindingKind::Candidates { .. } => None,
        }
    }

    pub fn is_assignment(&self) -> bool {
        matches!(self.kind, ScalarGroupBindingKind::Assignment(_))
    }

    pub fn is_candidate_group(&self) -> bool {
        matches!(self.kind, ScalarGroupBindingKind::Candidates { .. })
    }

    pub fn has_sequence_metadata(&self) -> bool {
        self.assignment()
            .is_some_and(|assignment| assignment.sequence_key.is_some())
    }

    pub fn has_position_metadata(&self) -> bool {
        self.assignment()
            .is_some_and(|assignment| assignment.position_key.is_some())
    }

    pub fn default_max_moves_per_step(&self) -> Option<usize> {
        self.limits.max_moves_per_step
    }
}

impl<S> Clone for ScalarGroupBinding<S> {
    fn clone(&self) -> Self {
        Self {
            group_name: self.group_name,
            members: self.members.clone(),
            kind: self.kind,
            limits: self.limits,
        }
    }
}

impl<S> fmt::Debug for ScalarGroupBinding<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScalarGroupBinding")
            .field("group_name", &self.group_name)
            .field("members", &self.members)
            .finish_non_exhaustive()
    }
}

pub fn bind_scalar_groups<S>(
    groups: Vec<ScalarGroup<S>>,
    scalar_slots: &[ScalarVariableSlot<S>],
) -> Vec<ScalarGroupBinding<S>> {
    groups
        .into_iter()
        .map(|group| ScalarGroupBinding::bind(group, scalar_slots))
        .collect()
}