solverforge-solver 0.13.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
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
/* Nearby list change move selector for distance-pruned element relocation.

A distance-biased variant of [`ListChangeMoveSelector`] that dramatically
reduces the move space by only considering destination positions that are
close to the source element. This is critical for VRP scalability: without
nearby selection, the move space is O(n²m²) which becomes impractical for
large instances.

# How It Works

For each source (entity, position), instead of generating moves to every
possible (dest_entity, dest_pos), only the `max_nearby` closest destination
positions are considered. Closeness is measured by a user-supplied
[`CrossEntityDistanceMeter`].

# Complexity

O(nm × k) per step where:
- n = number of entities
- m = average route length
- k = `max_nearby` (typically 10–20)

Compare to O(n²m²) for the full [`ListChangeMoveSelector`].

# Example

```
use solverforge_solver::heuristic::selector::nearby_list_change::{
CrossEntityDistanceMeter, NearbyListChangeMoveSelector,
};
use solverforge_solver::heuristic::selector::entity::FromSolutionEntitySelector;
use solverforge_solver::heuristic::selector::MoveSelector;
use solverforge_core::domain::PlanningSolution;
use solverforge_core::score::SoftScore;

#[derive(Clone, Debug)]
struct Visit { x: f64, y: f64 }

#[derive(Clone, Debug)]
struct Vehicle { visits: Vec<Visit> }

#[derive(Clone, Debug)]
struct Solution { vehicles: Vec<Vehicle>, score: Option<SoftScore> }

impl PlanningSolution for Solution {
type Score = SoftScore;
fn score(&self) -> Option<Self::Score> { self.score }
fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
}

fn list_len(s: &Solution, e: usize) -> usize {
s.vehicles.get(e).map_or(0, |v| v.visits.len())
}
fn list_remove(s: &mut Solution, e: usize, pos: usize) -> Option<Visit> {
s.vehicles.get_mut(e).map(|v| v.visits.remove(pos))
}
fn list_insert(s: &mut Solution, e: usize, pos: usize, val: Visit) {
if let Some(v) = s.vehicles.get_mut(e) { v.visits.insert(pos, val); }
}

// Euclidean distance between visit elements across routes
#[derive(Debug)]
struct EuclideanMeter;

impl CrossEntityDistanceMeter<Solution> for EuclideanMeter {
fn distance(
&self,
solution: &Solution,
src_entity: usize, src_pos: usize,
dst_entity: usize, dst_pos: usize,
) -> f64 {
let src = &solution.vehicles[src_entity].visits[src_pos];
let dst = &solution.vehicles[dst_entity].visits[dst_pos];
let dx = src.x - dst.x;
let dy = src.y - dst.y;
(dx * dx + dy * dy).sqrt()
}
}

let selector = NearbyListChangeMoveSelector::<Solution, Visit, _, _>::new(
FromSolutionEntitySelector::new(0),
EuclideanMeter,
10,   // max_nearby: consider 10 closest destinations
list_len,
list_remove,
list_insert,
"visits",
0,
);
```
*/

use std::fmt::Debug;
use std::marker::PhantomData;

use solverforge_core::domain::PlanningSolution;
use solverforge_scoring::Director;

use crate::heuristic::r#move::ListChangeMove;

use super::entity::EntitySelector;
use super::list_support::{collect_selected_entities, ordered_index};
use super::move_selector::{
    CandidateId, CandidateStore, MoveCandidateRef, MoveCursor, MoveSelector, MoveStreamContext,
};
use super::nearby_list_support::{sort_and_limit_nearby_candidates, NearbyCandidate};

/// Measures distance between two list positions, potentially across different entities.
///
/// Used by [`NearbyListChangeMoveSelector`] to rank candidate destination positions
/// by proximity to the source element being relocated.
///
/// # Notes
///
/// - Implementing this for VRP: use the Euclidean (or road-network) distance between
///   the visit at `(src_entity, src_pos)` and the visit at `(dst_entity, dst_pos)`.
/// - The distance can be asymmetric (e.g., directed graphs).
/// - Returning `f64::INFINITY` for a pair excludes it from nearby candidates.
pub trait CrossEntityDistanceMeter<S>: Send + Sync {
    // Returns the distance from the element at `(src_entity, src_pos)` to the element
    // at `(dst_entity, dst_pos)` in the current solution.
    fn distance(
        &self,
        solution: &S,
        src_entity: usize,
        src_pos: usize,
        dst_entity: usize,
        dst_pos: usize,
    ) -> f64;
}

/* Default distance meter: uses absolute position difference within the same entity,
and returns `f64::INFINITY` for cross-entity distances (no pruning across routes).

Useful for intra-route moves only.
*/
#[derive(Debug, Clone, Copy)]
pub struct DefaultCrossEntityDistanceMeter;

impl Default for DefaultCrossEntityDistanceMeter {
    fn default() -> Self {
        Self
    }
}

impl<S> CrossEntityDistanceMeter<S> for DefaultCrossEntityDistanceMeter {
    fn distance(
        &self,
        _solution: &S,
        src_entity: usize,
        src_pos: usize,
        dst_entity: usize,
        dst_pos: usize,
    ) -> f64 {
        if src_entity == dst_entity {
            (src_pos as f64 - dst_pos as f64).abs()
        } else {
            f64::INFINITY
        }
    }
}

/// A distance-pruned list change move selector.
///
/// For each source (entity, position), generates moves only to the `max_nearby`
/// nearest destination positions (measured by `CrossEntityDistanceMeter`).
/// This reduces move space from O(n²m²) to O(nm × k).
///
/// # Type Parameters
/// * `S` - The solution type
/// * `V` - The list element type
/// * `D` - The distance meter type
/// * `ES` - The entity selector type
pub struct NearbyListChangeMoveSelector<S, V, D, ES> {
    entity_selector: ES,
    distance_meter: D,
    max_nearby: usize,
    list_len: fn(&S, usize) -> usize,
    list_get: fn(&S, usize, usize) -> Option<V>,
    list_remove: fn(&mut S, usize, usize) -> Option<V>,
    list_insert: fn(&mut S, usize, usize, V),
    variable_name: &'static str,
    descriptor_index: usize,
    _phantom: PhantomData<(fn() -> S, fn() -> V)>,
}

struct NearbyListChangeSource {
    src_entity: usize,
    src_pos: usize,
    destinations: Vec<(usize, usize)>,
}

pub struct NearbyListChangeMoveCursor<S, V>
where
    S: PlanningSolution,
    V: Clone + PartialEq + Send + Sync + Debug + 'static,
{
    store: CandidateStore<S, ListChangeMove<S, V>>,
    sources: Vec<NearbyListChangeSource>,
    source_offset: usize,
    destination_offset: usize,
    list_len: fn(&S, usize) -> usize,
    list_get: fn(&S, usize, usize) -> Option<V>,
    list_remove: fn(&mut S, usize, usize) -> Option<V>,
    list_insert: fn(&mut S, usize, usize, V),
    variable_name: &'static str,
    descriptor_index: usize,
}

impl<S, V> NearbyListChangeMoveCursor<S, V>
where
    S: PlanningSolution,
    V: Clone + PartialEq + Send + Sync + Debug + 'static,
{
    #[allow(clippy::too_many_arguments)]
    fn new(
        sources: Vec<NearbyListChangeSource>,
        list_len: fn(&S, usize) -> usize,
        list_get: fn(&S, usize, usize) -> Option<V>,
        list_remove: fn(&mut S, usize, usize) -> Option<V>,
        list_insert: fn(&mut S, usize, usize, V),
        variable_name: &'static str,
        descriptor_index: usize,
    ) -> Self {
        Self {
            store: CandidateStore::new(),
            sources,
            source_offset: 0,
            destination_offset: 0,
            list_len,
            list_get,
            list_remove,
            list_insert,
            variable_name,
            descriptor_index,
        }
    }
}

impl<S, V> MoveCursor<S, ListChangeMove<S, V>> for NearbyListChangeMoveCursor<S, V>
where
    S: PlanningSolution,
    V: Clone + PartialEq + Send + Sync + Debug + 'static,
{
    fn next_candidate(&mut self) -> Option<CandidateId> {
        loop {
            let source = self.sources.get(self.source_offset)?;
            if self.destination_offset >= source.destinations.len() {
                self.source_offset += 1;
                self.destination_offset = 0;
                continue;
            }
            let (dst_entity, dst_pos) = source.destinations[self.destination_offset];
            self.destination_offset += 1;
            return Some(self.store.push(ListChangeMove::new(
                source.src_entity,
                source.src_pos,
                dst_entity,
                dst_pos,
                self.list_len,
                self.list_get,
                self.list_remove,
                self.list_insert,
                self.variable_name,
                self.descriptor_index,
            )));
        }
    }

    fn candidate(&self, id: CandidateId) -> Option<MoveCandidateRef<'_, S, ListChangeMove<S, V>>> {
        self.store.candidate(id)
    }

    fn take_candidate(&mut self, id: CandidateId) -> ListChangeMove<S, V> {
        self.store.take_candidate(id)
    }
}

impl<S, V> Iterator for NearbyListChangeMoveCursor<S, V>
where
    S: PlanningSolution,
    V: Clone + PartialEq + Send + Sync + Debug + 'static,
{
    type Item = ListChangeMove<S, V>;

    fn next(&mut self) -> Option<Self::Item> {
        let id = self.next_candidate()?;
        Some(self.take_candidate(id))
    }
}

impl<S, V: Debug, D, ES: Debug> Debug for NearbyListChangeMoveSelector<S, V, D, ES> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NearbyListChangeMoveSelector")
            .field("entity_selector", &self.entity_selector)
            .field("distance_meter", &"<distance_meter>")
            .field("max_nearby", &self.max_nearby)
            .field("variable_name", &self.variable_name)
            .field("descriptor_index", &self.descriptor_index)
            .finish()
    }
}

impl<S, V, D, ES> NearbyListChangeMoveSelector<S, V, D, ES> {
    /* Creates a new nearby list change move selector.

    # Arguments
    * `entity_selector` - Selects entities to consider for moves
    * `distance_meter` - Measures distance between position pairs
    * `max_nearby` - Maximum destination positions to consider per source
    * `list_len` - Function to get list length for an entity
    * `list_remove` - Function to remove element at position
    * `list_insert` - Function to insert element at position
    * `variable_name` - Name of the list variable
    * `descriptor_index` - Entity descriptor index
    */
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        entity_selector: ES,
        distance_meter: D,
        max_nearby: usize,
        list_len: fn(&S, usize) -> usize,
        list_get: fn(&S, usize, usize) -> Option<V>,
        list_remove: fn(&mut S, usize, usize) -> Option<V>,
        list_insert: fn(&mut S, usize, usize, V),
        variable_name: &'static str,
        descriptor_index: usize,
    ) -> Self {
        Self {
            entity_selector,
            distance_meter,
            max_nearby,
            list_len,
            list_get,
            list_remove,
            list_insert,
            variable_name,
            descriptor_index,
            _phantom: PhantomData,
        }
    }
}

impl<S, V, D, ES> MoveSelector<S, ListChangeMove<S, V>>
    for NearbyListChangeMoveSelector<S, V, D, ES>
where
    S: PlanningSolution,
    V: Clone + PartialEq + Send + Sync + Debug + 'static,
    D: CrossEntityDistanceMeter<S>,
    ES: EntitySelector<S>,
{
    type Cursor<'a>
        = NearbyListChangeMoveCursor<S, V>
    where
        Self: 'a;

    fn open_cursor<'a, SD: Director<S>>(&'a self, score_director: &SD) -> Self::Cursor<'a> {
        self.open_cursor_with_context(score_director, MoveStreamContext::default())
    }

    fn open_cursor_with_context<'a, SD: Director<S>>(
        &'a self,
        score_director: &SD,
        context: MoveStreamContext,
    ) -> Self::Cursor<'a> {
        let max_nearby = self.max_nearby;
        let solution = score_director.working_solution();

        let mut selected =
            collect_selected_entities(&self.entity_selector, score_director, self.list_len);
        selected.apply_stream_order(
            context,
            0xA1EA_2B17_C4A4_0001 ^ self.descriptor_index as u64,
        );
        let entities = selected.entities;
        let route_lens = selected.route_lens;

        let mut sources = Vec::new();
        let mut candidates: Vec<NearbyCandidate> = Vec::new();

        for (src_idx, &src_entity) in entities.iter().enumerate() {
            let src_len = route_lens[src_idx];
            if src_len == 0 {
                continue;
            }

            for src_pos_offset in 0..src_len {
                let src_pos = ordered_index(
                    src_pos_offset,
                    src_len,
                    context,
                    0xA1EA_2B17_C4A4_0002 ^ src_entity as u64 ^ self.descriptor_index as u64,
                );
                candidates.clear();

                // Intra-entity candidates
                for dst_pos in 0..src_len {
                    if dst_pos == src_pos || dst_pos == src_pos + 1 {
                        continue; // Skip no-ops
                    }
                    let dist = self
                        .distance_meter
                        .distance(solution, src_entity, src_pos, src_entity, dst_pos);
                    if dist.is_finite() {
                        candidates.push((src_entity, dst_pos, dist));
                    }
                }

                // Inter-entity candidates: insert at any position in other entities
                for (dst_idx, &dst_entity) in entities.iter().enumerate() {
                    if dst_idx == src_idx {
                        continue;
                    }
                    let dst_len = route_lens[dst_idx];
                    // Can insert at positions 0..=dst_len
                    for dst_pos in 0..=dst_len {
                        // For the last position, use the distance to the last element
                        let ref_pos = dst_pos.min(dst_len.saturating_sub(1));
                        let dist = self
                            .distance_meter
                            .distance(solution, src_entity, src_pos, dst_entity, ref_pos);
                        if dist.is_finite() {
                            candidates.push((dst_entity, dst_pos, dist));
                        }
                    }
                }

                sort_and_limit_nearby_candidates(&mut candidates, max_nearby);

                sources.push(NearbyListChangeSource {
                    src_entity,
                    src_pos,
                    destinations: candidates
                        .iter()
                        .map(|&(dst_entity, dst_pos, _)| (dst_entity, dst_pos))
                        .collect(),
                });
            }
        }

        NearbyListChangeMoveCursor::new(
            sources,
            self.list_len,
            self.list_get,
            self.list_remove,
            self.list_insert,
            self.variable_name,
            self.descriptor_index,
        )
    }

    fn size<SD: Director<S>>(&self, score_director: &SD) -> usize {
        let selected =
            collect_selected_entities(&self.entity_selector, score_director, self.list_len);

        // Each element generates at most max_nearby moves
        selected.total_elements() * self.max_nearby
    }
}