1use std::fmt::Debug;
9use std::marker::PhantomData;
10
11use solverforge_core::domain::PlanningSolution;
12use solverforge_scoring::Director;
13
14use crate::heuristic::r#move::ListChangeMove;
15use crate::heuristic::selector::list_kernel::{
16 ChangeCursor, NativeChangeEmitter, SelectedListOwners, STATIC_CHANGE_SALTS,
17};
18use crate::list_placement::selected_owner_allows;
19
20use super::entity::EntitySelector;
21use super::list_support::collect_selected_entities;
22use super::move_selector::{
23 CandidateId, MoveCandidateRef, MoveCursor, MoveSelector, MoveStreamContext,
24};
25
26pub struct ListChangeMoveSelector<S, V, ES> {
33 entity_selector: ES,
34 list_len: fn(&S, usize) -> usize,
35 list_get: fn(&S, usize, usize) -> Option<V>,
36 list_remove: fn(&mut S, usize, usize) -> Option<V>,
37 list_insert: fn(&mut S, usize, usize, V),
38 element_owner_fn: Option<fn(&S, &V) -> Option<usize>>,
39 variable_name: &'static str,
40 descriptor_index: usize,
41 _phantom: PhantomData<(fn() -> S, fn() -> V)>,
42}
43
44pub struct ListChangeMoveCursor<S, V>
47where
48 S: PlanningSolution,
49 V: Clone + PartialEq + Send + Sync + Debug + 'static,
50{
51 inner: ChangeCursor<S, NativeChangeEmitter<S, V>>,
52}
53
54impl<S, V> ListChangeMoveCursor<S, V>
55where
56 S: PlanningSolution,
57 V: Clone + PartialEq + Send + Sync + Debug + 'static,
58{
59 fn new(inner: ChangeCursor<S, NativeChangeEmitter<S, V>>) -> Self {
60 Self { inner }
61 }
62}
63
64impl<S, V> MoveCursor<S, ListChangeMove<S, V>> for ListChangeMoveCursor<S, V>
65where
66 S: PlanningSolution,
67 V: Clone + PartialEq + Send + Sync + Debug + 'static,
68{
69 fn next_candidate(&mut self, solution: &S) -> Option<CandidateId> {
70 self.inner.next_candidate(solution)
71 }
72
73 fn candidate(&self, id: CandidateId) -> Option<MoveCandidateRef<'_, S, ListChangeMove<S, V>>> {
74 self.inner.candidate(id)
75 }
76
77 fn take_candidate(&mut self, id: CandidateId) -> ListChangeMove<S, V> {
78 self.inner.take_candidate(id)
79 }
80
81 fn next_owned_candidate(&mut self, solution: &S) -> Option<ListChangeMove<S, V>> {
82 self.inner.next_owned_candidate(solution)
83 }
84
85 fn next_owned_candidate_matching(
86 &mut self,
87 solution: &S,
88 predicate: for<'a> fn(MoveCandidateRef<'a, S, ListChangeMove<S, V>>) -> bool,
89 ) -> Option<ListChangeMove<S, V>> {
90 self.inner
91 .next_owned_candidate_matching(solution, predicate)
92 }
93
94 fn release_candidate(&mut self, id: CandidateId) -> bool {
95 self.inner.release_candidate(id)
96 }
97}
98
99impl<S, V: Debug, ES: Debug> Debug for ListChangeMoveSelector<S, V, ES> {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 f.debug_struct("ListChangeMoveSelector")
102 .field("entity_selector", &self.entity_selector)
103 .field("variable_name", &self.variable_name)
104 .field("descriptor_index", &self.descriptor_index)
105 .finish()
106 }
107}
108
109impl<S, V, ES> ListChangeMoveSelector<S, V, ES> {
110 #[allow(clippy::too_many_arguments)]
111 pub fn new(
112 entity_selector: ES,
113 list_len: fn(&S, usize) -> usize,
114 list_get: fn(&S, usize, usize) -> Option<V>,
115 list_remove: fn(&mut S, usize, usize) -> Option<V>,
116 list_insert: fn(&mut S, usize, usize, V),
117 variable_name: &'static str,
118 descriptor_index: usize,
119 ) -> Self {
120 Self {
121 entity_selector,
122 list_len,
123 list_get,
124 list_remove,
125 list_insert,
126 element_owner_fn: None,
127 variable_name,
128 descriptor_index,
129 _phantom: PhantomData,
130 }
131 }
132
133 pub fn with_element_owner_fn(
134 mut self,
135 element_owner_fn: Option<fn(&S, &V) -> Option<usize>>,
136 ) -> Self {
137 self.element_owner_fn = element_owner_fn;
138 self
139 }
140}
141
142impl<S, V, ES> MoveSelector<S, ListChangeMove<S, V>> for ListChangeMoveSelector<S, V, ES>
143where
144 S: PlanningSolution,
145 V: Clone + PartialEq + Send + Sync + Debug + 'static,
146 ES: EntitySelector<S>,
147{
148 type Cursor<'a>
149 = ListChangeMoveCursor<S, V>
150 where
151 Self: 'a;
152
153 fn open_cursor<'a, D: Director<S>>(&'a self, score_director: &D) -> Self::Cursor<'a> {
154 self.open_cursor_with_context(score_director, MoveStreamContext::default())
155 }
156
157 fn open_cursor_with_context<'a, D: Director<S>>(
158 &'a self,
159 score_director: &D,
160 context: MoveStreamContext,
161 ) -> Self::Cursor<'a> {
162 let mut selected =
163 collect_selected_entities(&self.entity_selector, score_director, self.list_len);
164 selected.apply_stream_order(
165 context,
166 STATIC_CHANGE_SALTS.entity ^ self.descriptor_index as u64,
167 );
168 let owner_restrictions = crate::list_placement::selected_owner_restrictions(
169 self.element_owner_fn,
170 score_director.working_solution(),
171 score_director
172 .entity_count(self.descriptor_index)
173 .unwrap_or(0),
174 &selected.entities,
175 &selected.route_lens,
176 self.list_get,
177 );
178 let owners = SelectedListOwners::from_selected_restrictions(owner_restrictions);
179 ListChangeMoveCursor::new(ChangeCursor::new(
180 NativeChangeEmitter::new(
181 self.list_len,
182 self.list_get,
183 self.list_remove,
184 self.list_insert,
185 self.variable_name,
186 self.descriptor_index,
187 ),
188 selected.entities,
189 selected.route_lens,
190 context,
191 STATIC_CHANGE_SALTS,
192 owners,
193 self.descriptor_index,
194 ))
195 }
196
197 fn size<D: Director<S>>(&self, score_director: &D) -> usize {
198 let selected =
199 collect_selected_entities(&self.entity_selector, score_director, self.list_len);
200 let Some(owner_restrictions) = crate::list_placement::selected_owner_restrictions(
201 self.element_owner_fn,
202 score_director.working_solution(),
203 score_director
204 .entity_count(self.descriptor_index)
205 .unwrap_or(0),
206 &selected.entities,
207 &selected.route_lens,
208 self.list_get,
209 ) else {
210 return selected.list_change_move_capacity();
211 };
212
213 if owner_restrictions.is_fixed_to_current() {
214 return selected
215 .route_lens
216 .iter()
217 .map(|&source_len| source_len * list_change_intra_destination_count(source_len))
218 .sum();
219 }
220 let element_owners = owner_restrictions
221 .mixed()
222 .expect("non-fixed owner restrictions retain their matrix");
223
224 let mut count = 0;
225 for (source_idx, (&source_entity, &source_len)) in selected
226 .entities
227 .iter()
228 .zip(selected.route_lens.iter())
229 .enumerate()
230 {
231 for source_position in 0..source_len {
232 if selected_owner_allows(element_owners, source_idx, source_position, source_entity)
233 {
234 count += list_change_intra_destination_count(source_len);
235 }
236 for (destination_idx, (&destination_entity, &destination_len)) in selected
237 .entities
238 .iter()
239 .zip(selected.route_lens.iter())
240 .enumerate()
241 {
242 if destination_idx == source_idx {
243 continue;
244 }
245 if selected_owner_allows(
246 element_owners,
247 source_idx,
248 source_position,
249 destination_entity,
250 ) {
251 count += destination_len + 1;
252 }
253 }
254 }
255 }
256 count
257 }
258}
259
260#[inline]
261fn list_change_intra_destination_count(source_len: usize) -> usize {
262 source_len.saturating_sub(1)
263}