solverforge-solver 0.11.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
457
458
459
460
461
462
463
464
465
466
467
468
469
/* K-opt move for tour optimization.

K-opt removes k edges from a tour and reconnects the resulting segments
in a different order, potentially reversing some segments. This is a
fundamental move for TSP and VRP optimization.

# Zero-Erasure Design

- Fixed arrays for cut points (no SmallVec for static data)
- Reconnection pattern stored by value (`KOptReconnection` is `Copy`)
- Typed function pointers for all list operations

# Example

```
use solverforge_solver::heuristic::r#move::{KOptMove, CutPoint};
use solverforge_solver::heuristic::r#move::k_opt_reconnection::THREE_OPT_RECONNECTIONS;
use solverforge_core::domain::PlanningSolution;
use solverforge_core::score::SoftScore;

#[derive(Clone, Debug)]
struct Tour { cities: Vec<i32>, score: Option<SoftScore> }

impl PlanningSolution for Tour {
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: &Tour, _: usize) -> usize { s.cities.len() }
fn sublist_remove(s: &mut Tour, _: usize, start: usize, end: usize) -> Vec<i32> {
s.cities.drain(start..end).collect()
}
fn sublist_insert(s: &mut Tour, _: usize, pos: usize, items: Vec<i32>) {
for (i, item) in items.into_iter().enumerate() {
s.cities.insert(pos + i, item);
}
}

// Create a 3-opt move with cuts at positions 2, 4, 6
// This creates 4 segments: [0..2), [2..4), [4..6), [6..)
let cuts = [
CutPoint::new(0, 2),
CutPoint::new(0, 4),
CutPoint::new(0, 6),
];
let reconnection = &THREE_OPT_RECONNECTIONS[3]; // Swap middle segments

let m = KOptMove::<Tour, i32>::new(
&cuts,
reconnection,
list_len,
sublist_remove,
sublist_insert,
"cities",
0,
);
```
*/

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

use smallvec::{smallvec, SmallVec};
use solverforge_core::domain::PlanningSolution;
use solverforge_scoring::Director;

use super::k_opt_reconnection::KOptReconnection;
use super::metadata::{
    encode_option_debug, encode_usize, hash_str, MoveTabuScope, ScopedValueTabuToken,
};
use super::{Move, MoveTabuSignature};

/* A cut point in a route, defining where an edge is removed.

For k-opt, we have k cut points which divide the route into k+1 segments.

# Example

```
use solverforge_solver::heuristic::r#move::CutPoint;

// Cut at position 5 in entity 0
let cut = CutPoint::new(0, 5);
assert_eq!(cut.entity_index(), 0);
assert_eq!(cut.position(), 5);
```
*/
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CutPoint {
    // Entity (route/vehicle) index.
    entity_index: usize,
    // Position in the route where the cut occurs.
    // The edge between position-1 and position is removed.
    position: usize,
}

impl CutPoint {
    #[inline]
    pub const fn new(entity_index: usize, position: usize) -> Self {
        Self {
            entity_index,
            position,
        }
    }

    #[inline]
    pub const fn entity_index(&self) -> usize {
        self.entity_index
    }

    #[inline]
    pub const fn position(&self) -> usize {
        self.position
    }
}

/// A k-opt move that removes k edges and reconnects segments.
///
/// This is the generalized k-opt move supporting k=2,3,4,5.
/// For k=2, this is equivalent to a 2-opt (segment reversal).
///
/// # Zero-Erasure Design
///
/// - Fixed array `[CutPoint; 5]` for up to 5 cuts (5-opt)
/// - `KOptReconnection` stored by value (`Copy` type, no heap allocation)
/// - Typed function pointers for list operations
///
/// # Type Parameters
///
/// * `S` - The planning solution type
/// * `V` - The list element value type
pub struct KOptMove<S, V> {
    // Cut points (up to 5 for 5-opt).
    cuts: [CutPoint; 5],
    // Number of actual cuts (k value).
    cut_count: u8,
    // Reconnection pattern to apply (stored by value — `KOptReconnection` is `Copy`).
    reconnection: KOptReconnection,
    list_len: fn(&S, usize) -> usize,
    list_get: fn(&S, usize, usize) -> Option<V>,
    // Remove sublist [start, end), returns removed elements.
    sublist_remove: fn(&mut S, usize, usize, usize) -> Vec<V>,
    // Insert elements at position.
    sublist_insert: fn(&mut S, usize, usize, Vec<V>),
    // Variable name.
    variable_name: &'static str,
    // Descriptor index.
    descriptor_index: usize,
    // Entity index (for intra-route moves).
    entity_index: usize,
    _phantom: PhantomData<fn() -> V>,
}

impl<S, V> Clone for KOptMove<S, V> {
    fn clone(&self) -> Self {
        Self {
            cuts: self.cuts,
            cut_count: self.cut_count,
            reconnection: self.reconnection,
            list_len: self.list_len,
            list_get: self.list_get,
            sublist_remove: self.sublist_remove,
            sublist_insert: self.sublist_insert,
            variable_name: self.variable_name,
            descriptor_index: self.descriptor_index,
            entity_index: self.entity_index,
            _phantom: PhantomData,
        }
    }
}

impl<S, V: Debug> Debug for KOptMove<S, V> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let cuts: Vec<_> = self.cuts[..self.cut_count as usize]
            .iter()
            .map(|c| c.position)
            .collect();
        f.debug_struct("KOptMove")
            .field("k", &self.cut_count)
            .field("entity", &self.entity_index)
            .field("cuts", &cuts)
            .field("reconnection", &self.reconnection)
            .field("variable_name", &self.variable_name)
            .finish()
    }
}

impl<S, V> KOptMove<S, V> {
    /* Creates a new k-opt move.

    # Arguments

    * `cuts` - Slice of cut points (must be sorted by position for intra-route)
    * `reconnection` - How to reconnect the segments
    * `list_len` - Function to get list length
    * `sublist_remove` - Function to remove a range
    * `sublist_insert` - Function to insert elements
    * `variable_name` - Name of the list variable
    * `descriptor_index` - Entity descriptor index

    # Panics

    Panics if cuts is empty or has more than 5 elements.
    */
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        cuts: &[CutPoint],
        reconnection: &KOptReconnection,
        list_len: fn(&S, usize) -> usize,
        list_get: fn(&S, usize, usize) -> Option<V>,
        sublist_remove: fn(&mut S, usize, usize, usize) -> Vec<V>,
        sublist_insert: fn(&mut S, usize, usize, Vec<V>),
        variable_name: &'static str,
        descriptor_index: usize,
    ) -> Self {
        assert!(!cuts.is_empty() && cuts.len() <= 5, "k must be 1-5");

        let mut cut_array = [CutPoint::default(); 5];
        for (i, cut) in cuts.iter().enumerate() {
            cut_array[i] = *cut;
        }

        // For now, assume intra-route (all cuts on same entity)
        let entity_index = cuts[0].entity_index;

        Self {
            cuts: cut_array,
            cut_count: cuts.len() as u8,
            reconnection: *reconnection,
            list_len,
            list_get,
            sublist_remove,
            sublist_insert,
            variable_name,
            descriptor_index,
            entity_index,
            _phantom: PhantomData,
        }
    }

    #[inline]
    pub fn k(&self) -> usize {
        self.cut_count as usize
    }

    #[inline]
    pub fn cuts(&self) -> &[CutPoint] {
        &self.cuts[..self.cut_count as usize]
    }

    pub fn is_intra_route(&self) -> bool {
        let first = self.cuts[0].entity_index;
        self.cuts[..self.cut_count as usize]
            .iter()
            .all(|c| c.entity_index == first)
    }
}

impl<S, V> Move<S> for KOptMove<S, V>
where
    S: PlanningSolution,
    V: Clone + Send + Sync + Debug + 'static,
{
    fn is_doable<D: Director<S>>(&self, score_director: &D) -> bool {
        let solution = score_director.working_solution();
        let k = self.cut_count as usize;

        // Must have at least 2 cuts for meaningful k-opt
        if k < 2 {
            return false;
        }

        // Verify reconnection pattern matches k
        if self.reconnection.k() != k {
            return false;
        }

        // For intra-route, verify cuts are sorted and within bounds
        let len = (self.list_len)(solution, self.entity_index);

        // Check cuts are valid positions
        for cut in &self.cuts[..k] {
            if cut.position > len {
                return false;
            }
        }

        // For intra-route, cuts must be strictly increasing
        if self.is_intra_route() {
            for i in 1..k {
                if self.cuts[i].position <= self.cuts[i - 1].position {
                    return false;
                }
            }
            // Need at least 1 element between cuts for meaningful segments
            // Actually, empty segments are allowed in some cases
        }

        true
    }

    fn do_move<D: Director<S>>(&self, score_director: &mut D) {
        let k = self.cut_count as usize;
        let entity = self.entity_index;

        // Notify before change
        score_director.before_variable_changed(self.descriptor_index, entity);

        /* For intra-route k-opt, we need to:
        1. Extract all segments
        2. Reorder according to reconnection pattern
        3. Reverse segments as needed
        4. Rebuild the list
        */

        /* Calculate segment boundaries (segments are between consecutive cuts)
        For k cuts at positions [p0, p1, ..., pk-1], we have k+1 segments:
        Segment 0: [0, p0)
        Segment 1: [p0, p1)
        ...
        Segment k: [pk-1, len)
        */

        let solution = score_director.working_solution_mut();
        let len = (self.list_len)(solution, entity);

        // Extract all elements
        let all_elements = (self.sublist_remove)(solution, entity, 0, len);

        // Build segment boundaries
        let mut boundaries = Vec::with_capacity(k + 2);
        boundaries.push(0);
        for i in 0..k {
            boundaries.push(self.cuts[i].position);
        }
        boundaries.push(len);

        // Extract segments
        let mut segments: Vec<Vec<V>> = Vec::with_capacity(k + 1);
        for i in 0..=k {
            let start = boundaries[i];
            let end = boundaries[i + 1];
            segments.push(all_elements[start..end].to_vec());
        }

        // Reorder and reverse according to reconnection pattern
        let mut new_elements = Vec::with_capacity(len);
        for pos in 0..self.reconnection.segment_count() {
            let seg_idx = self.reconnection.segment_at(pos);
            let mut seg = std::mem::take(&mut segments[seg_idx]);
            if self.reconnection.should_reverse(seg_idx) {
                seg.reverse();
            }
            new_elements.extend(seg);
        }

        // Insert reordered elements back
        let new_len = new_elements.len();
        (self.sublist_insert)(
            score_director.working_solution_mut(),
            entity,
            0,
            new_elements,
        );

        // Notify after change
        score_director.after_variable_changed(self.descriptor_index, entity);

        // Register undo - need to restore original order
        let sublist_remove = self.sublist_remove;
        let sublist_insert = self.sublist_insert;

        score_director.register_undo(Box::new(move |s: &mut S| {
            // Remove current elements
            let _ = sublist_remove(s, entity, 0, new_len);
            // Insert original elements
            sublist_insert(s, entity, 0, all_elements);
        }));
    }

    fn descriptor_index(&self) -> usize {
        self.descriptor_index
    }

    fn entity_indices(&self) -> &[usize] {
        std::slice::from_ref(&self.entity_index)
    }

    fn variable_name(&self) -> &str {
        self.variable_name
    }

    fn tabu_signature<D: Director<S>>(&self, score_director: &D) -> MoveTabuSignature {
        let mut touched_value_ids: SmallVec<[u64; 2]> = SmallVec::new();
        let len = (self.list_len)(score_director.working_solution(), self.entity_index);
        let k = self.cut_count as usize;
        let first_pos = self.cuts[0].position;
        let last_pos = self.cuts[k - 1].position;
        for pos in first_pos..len.min(last_pos.max(first_pos)) {
            let value = (self.list_get)(score_director.working_solution(), self.entity_index, pos);
            touched_value_ids.push(encode_option_debug(value.as_ref()));
        }

        let entity_id = encode_usize(self.entity_index);
        let variable_id = hash_str(self.variable_name);
        let scope = MoveTabuScope::new(self.descriptor_index, self.variable_name);
        let destination_value_tokens: SmallVec<[ScopedValueTabuToken; 2]> = touched_value_ids
            .iter()
            .copied()
            .map(|value_id| scope.value_token(value_id))
            .collect();
        let mut move_id = smallvec![
            encode_usize(self.descriptor_index),
            variable_id,
            entity_id,
            encode_usize(k)
        ];
        for cut in &self.cuts[..k] {
            move_id.push(encode_usize(cut.position));
        }
        for segment in self.reconnection.segment_order() {
            move_id.push(u64::from(*segment));
        }
        for idx in 0..self.reconnection.segment_count() {
            move_id.push(if self.reconnection.should_reverse(idx) {
                1
            } else {
                0
            });
        }
        move_id.extend(touched_value_ids.iter().copied());

        let mut inverse_order = vec![0u8; self.reconnection.segment_count()];
        for (pos, segment) in self
            .reconnection
            .segment_order()
            .iter()
            .copied()
            .enumerate()
        {
            inverse_order[segment as usize] = pos as u8;
        }
        let mut undo_move_id = smallvec![
            encode_usize(self.descriptor_index),
            variable_id,
            entity_id,
            encode_usize(k)
        ];
        for cut in &self.cuts[..k] {
            undo_move_id.push(encode_usize(cut.position));
        }
        for segment in inverse_order {
            undo_move_id.push(u64::from(segment));
        }
        for idx in 0..self.reconnection.segment_count() {
            undo_move_id.push(if self.reconnection.should_reverse(idx) {
                1
            } else {
                0
            });
        }
        undo_move_id.extend(touched_value_ids.iter().copied());

        MoveTabuSignature::new(scope, move_id, undo_move_id)
            .with_entity_tokens([scope.entity_token(entity_id)])
            .with_destination_value_tokens(destination_value_tokens)
    }
}