Skip to main content

solverforge_solver/heuristic/selector/k_opt/
selector.rs

1//! Public static adapter for the canonical exhaustive K-opt cursor.
2
3use std::fmt::Debug;
4use std::marker::PhantomData;
5
6use solverforge_core::domain::PlanningSolution;
7use solverforge_scoring::Director;
8
9use crate::heuristic::r#move::k_opt_reconnection::{
10    enumerate_reconnections, KOptReconnection, THREE_OPT_RECONNECTIONS,
11};
12use crate::heuristic::r#move::KOptMove;
13use crate::heuristic::selector::list_kernel::{KOptCursor, NativeKOptEmitter};
14
15use super::super::entity::EntitySelector;
16use super::super::move_selector::{
17    CandidateId, MoveCandidateRef, MoveCursor, MoveSelector, MoveStreamContext,
18};
19use super::config::KOptConfig;
20use super::iterators::count_cut_combinations;
21
22/// Static K-opt selector.  It preserves its public move/cursor types while
23/// common cut and reconnection enumeration is owned by the shared list kernel.
24pub struct KOptMoveSelector<S, V, ES> {
25    entity_selector: ES,
26    config: KOptConfig,
27    owned_patterns: Vec<KOptReconnection>,
28    list_len: fn(&S, usize) -> usize,
29    list_get: fn(&S, usize, usize) -> Option<V>,
30    sublist_remove: fn(&mut S, usize, usize, usize) -> Vec<V>,
31    sublist_insert: fn(&mut S, usize, usize, Vec<V>),
32    variable_name: &'static str,
33    descriptor_index: usize,
34    _phantom: PhantomData<(fn() -> S, fn() -> V)>,
35}
36
37pub struct KOptMoveCursor<'a, S, V>
38where
39    S: PlanningSolution,
40    V: Clone + Send + Sync + Debug + 'static,
41{
42    inner: KOptCursor<'a, S, NativeKOptEmitter<S, V>>,
43}
44
45impl<'a, S, V> KOptMoveCursor<'a, S, V>
46where
47    S: PlanningSolution,
48    V: Clone + Send + Sync + Debug + 'static,
49{
50    fn new(inner: KOptCursor<'a, S, NativeKOptEmitter<S, V>>) -> Self {
51        Self { inner }
52    }
53}
54
55impl<S, V> MoveCursor<S, KOptMove<S, V>> for KOptMoveCursor<'_, S, V>
56where
57    S: PlanningSolution,
58    V: Clone + Send + Sync + Debug + 'static,
59{
60    fn next_candidate(&mut self, solution: &S) -> Option<CandidateId> {
61        self.inner.next_candidate(solution)
62    }
63    fn candidate(&self, id: CandidateId) -> Option<MoveCandidateRef<'_, S, KOptMove<S, V>>> {
64        self.inner.candidate(id)
65    }
66    fn take_candidate(&mut self, id: CandidateId) -> KOptMove<S, V> {
67        self.inner.take_candidate(id)
68    }
69    fn next_owned_candidate(&mut self, solution: &S) -> Option<KOptMove<S, V>> {
70        self.inner.next_owned_candidate(solution)
71    }
72    fn next_owned_candidate_matching(
73        &mut self,
74        solution: &S,
75        predicate: for<'b> fn(MoveCandidateRef<'b, S, KOptMove<S, V>>) -> bool,
76    ) -> Option<KOptMove<S, V>> {
77        self.inner
78            .next_owned_candidate_matching(solution, predicate)
79    }
80    fn release_candidate(&mut self, id: CandidateId) -> bool {
81        self.inner.release_candidate(id)
82    }
83}
84
85impl<S, V: Debug, ES: Debug> Debug for KOptMoveSelector<S, V, ES> {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.debug_struct("KOptMoveSelector")
88            .field("entity_selector", &self.entity_selector)
89            .field("config", &self.config)
90            .field("pattern_count", &self.owned_patterns.len())
91            .field("variable_name", &self.variable_name)
92            .finish()
93    }
94}
95
96impl<S: PlanningSolution, V, ES> KOptMoveSelector<S, V, ES> {
97    #[allow(clippy::too_many_arguments)]
98    pub fn new(
99        entity_selector: ES,
100        config: KOptConfig,
101        list_len: fn(&S, usize) -> usize,
102        list_get: fn(&S, usize, usize) -> Option<V>,
103        sublist_remove: fn(&mut S, usize, usize, usize) -> Vec<V>,
104        sublist_insert: fn(&mut S, usize, usize, Vec<V>),
105        variable_name: &'static str,
106        descriptor_index: usize,
107    ) -> Self {
108        let owned_patterns = if config.k == 3 {
109            THREE_OPT_RECONNECTIONS.to_vec()
110        } else {
111            enumerate_reconnections(config.k)
112        };
113        Self {
114            entity_selector,
115            config,
116            owned_patterns,
117            list_len,
118            list_get,
119            sublist_remove,
120            sublist_insert,
121            variable_name,
122            descriptor_index,
123            _phantom: PhantomData,
124        }
125    }
126}
127
128impl<S, V, ES> MoveSelector<S, KOptMove<S, V>> for KOptMoveSelector<S, V, ES>
129where
130    S: PlanningSolution,
131    ES: EntitySelector<S>,
132    V: Clone + Send + Sync + Debug + 'static,
133{
134    type Cursor<'a>
135        = KOptMoveCursor<'a, S, V>
136    where
137        Self: 'a;
138
139    fn open_cursor<'a, D: Director<S>>(&'a self, score_director: &D) -> Self::Cursor<'a> {
140        self.open_cursor_with_context(score_director, MoveStreamContext::default())
141    }
142
143    fn open_cursor_with_context<'a, D: Director<S>>(
144        &'a self,
145        score_director: &D,
146        context: MoveStreamContext,
147    ) -> Self::Cursor<'a> {
148        let entity_lens = self
149            .entity_selector
150            .iter(score_director)
151            .map(|reference| {
152                let entity = reference.entity_index;
153                (
154                    entity,
155                    (self.list_len)(score_director.working_solution(), entity),
156                )
157            })
158            .collect();
159        KOptMoveCursor::new(KOptCursor::new(
160            NativeKOptEmitter::new(
161                self.list_len,
162                self.list_get,
163                self.sublist_remove,
164                self.sublist_insert,
165                self.variable_name,
166                self.descriptor_index,
167            ),
168            entity_lens,
169            self.config.k,
170            self.config.min_segment_len,
171            &self.owned_patterns,
172            context,
173            self.descriptor_index,
174        ))
175    }
176
177    fn size<D: Director<S>>(&self, score_director: &D) -> usize {
178        self.entity_selector
179            .iter(score_director)
180            .map(|reference| {
181                let len =
182                    (self.list_len)(score_director.working_solution(), reference.entity_index);
183                count_cut_combinations(self.config.k, len, self.config.min_segment_len)
184                    * self.owned_patterns.len()
185            })
186            .sum()
187    }
188}