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) -> Option<CandidateId> {
70 self.inner.next_candidate()
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) -> Option<ListChangeMove<S, V>> {
82 self.inner.next_owned_candidate()
83 }
84
85 fn next_owned_candidate_matching(
86 &mut self,
87 predicate: for<'a> fn(MoveCandidateRef<'a, S, ListChangeMove<S, V>>) -> bool,
88 ) -> Option<ListChangeMove<S, V>> {
89 self.inner.next_owned_candidate_matching(predicate)
90 }
91
92 fn release_candidate(&mut self, id: CandidateId) -> bool {
93 self.inner.release_candidate(id)
94 }
95}
96
97impl<S, V> Iterator for ListChangeMoveCursor<S, V>
98where
99 S: PlanningSolution,
100 V: Clone + PartialEq + Send + Sync + Debug + 'static,
101{
102 type Item = ListChangeMove<S, V>;
103
104 fn next(&mut self) -> Option<Self::Item> {
105 self.next_owned_candidate()
106 }
107}
108
109impl<S, V: Debug, ES: Debug> Debug for ListChangeMoveSelector<S, V, ES> {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 f.debug_struct("ListChangeMoveSelector")
112 .field("entity_selector", &self.entity_selector)
113 .field("variable_name", &self.variable_name)
114 .field("descriptor_index", &self.descriptor_index)
115 .finish()
116 }
117}
118
119impl<S, V, ES> ListChangeMoveSelector<S, V, ES> {
120 #[allow(clippy::too_many_arguments)]
121 pub fn new(
122 entity_selector: ES,
123 list_len: fn(&S, usize) -> usize,
124 list_get: fn(&S, usize, usize) -> Option<V>,
125 list_remove: fn(&mut S, usize, usize) -> Option<V>,
126 list_insert: fn(&mut S, usize, usize, V),
127 variable_name: &'static str,
128 descriptor_index: usize,
129 ) -> Self {
130 Self {
131 entity_selector,
132 list_len,
133 list_get,
134 list_remove,
135 list_insert,
136 element_owner_fn: None,
137 variable_name,
138 descriptor_index,
139 _phantom: PhantomData,
140 }
141 }
142
143 pub fn with_element_owner_fn(
144 mut self,
145 element_owner_fn: Option<fn(&S, &V) -> Option<usize>>,
146 ) -> Self {
147 self.element_owner_fn = element_owner_fn;
148 self
149 }
150}
151
152impl<S, V, ES> MoveSelector<S, ListChangeMove<S, V>> for ListChangeMoveSelector<S, V, ES>
153where
154 S: PlanningSolution,
155 V: Clone + PartialEq + Send + Sync + Debug + 'static,
156 ES: EntitySelector<S>,
157{
158 type Cursor<'a>
159 = ListChangeMoveCursor<S, V>
160 where
161 Self: 'a;
162
163 fn open_cursor<'a, D: Director<S>>(&'a self, score_director: &D) -> Self::Cursor<'a> {
164 self.open_cursor_with_context(score_director, MoveStreamContext::default())
165 }
166
167 fn open_cursor_with_context<'a, D: Director<S>>(
168 &'a self,
169 score_director: &D,
170 context: MoveStreamContext,
171 ) -> Self::Cursor<'a> {
172 let mut selected =
173 collect_selected_entities(&self.entity_selector, score_director, self.list_len);
174 selected.apply_stream_order(
175 context,
176 STATIC_CHANGE_SALTS.entity ^ self.descriptor_index as u64,
177 );
178 let owner_restrictions = crate::list_placement::selected_owner_restrictions(
179 self.element_owner_fn,
180 score_director.working_solution(),
181 score_director
182 .entity_count(self.descriptor_index)
183 .unwrap_or(0),
184 &selected.entities,
185 &selected.route_lens,
186 self.list_get,
187 );
188 let owners = SelectedListOwners::from_selected_restrictions(owner_restrictions);
189 ListChangeMoveCursor::new(ChangeCursor::new(
190 NativeChangeEmitter::new(
191 self.list_len,
192 self.list_get,
193 self.list_remove,
194 self.list_insert,
195 self.variable_name,
196 self.descriptor_index,
197 ),
198 selected.entities,
199 selected.route_lens,
200 context,
201 STATIC_CHANGE_SALTS,
202 owners,
203 self.descriptor_index,
204 ))
205 }
206
207 fn size<D: Director<S>>(&self, score_director: &D) -> usize {
208 let selected =
209 collect_selected_entities(&self.entity_selector, score_director, self.list_len);
210 let Some(owner_restrictions) = crate::list_placement::selected_owner_restrictions(
211 self.element_owner_fn,
212 score_director.working_solution(),
213 score_director
214 .entity_count(self.descriptor_index)
215 .unwrap_or(0),
216 &selected.entities,
217 &selected.route_lens,
218 self.list_get,
219 ) else {
220 return selected.list_change_move_capacity();
221 };
222
223 if owner_restrictions.is_fixed_to_current() {
224 return selected
225 .route_lens
226 .iter()
227 .map(|&source_len| source_len * list_change_intra_destination_count(source_len))
228 .sum();
229 }
230 let element_owners = owner_restrictions
231 .mixed()
232 .expect("non-fixed owner restrictions retain their matrix");
233
234 let mut count = 0;
235 for (source_idx, (&source_entity, &source_len)) in selected
236 .entities
237 .iter()
238 .zip(selected.route_lens.iter())
239 .enumerate()
240 {
241 for source_position in 0..source_len {
242 if selected_owner_allows(element_owners, source_idx, source_position, source_entity)
243 {
244 count += list_change_intra_destination_count(source_len);
245 }
246 for (destination_idx, (&destination_entity, &destination_len)) in selected
247 .entities
248 .iter()
249 .zip(selected.route_lens.iter())
250 .enumerate()
251 {
252 if destination_idx == source_idx {
253 continue;
254 }
255 if selected_owner_allows(
256 element_owners,
257 source_idx,
258 source_position,
259 destination_entity,
260 ) {
261 count += destination_len + 1;
262 }
263 }
264 }
265 }
266 count
267 }
268}
269
270#[inline]
271fn list_change_intra_destination_count(source_len: usize) -> usize {
272 source_len.saturating_sub(1)
273}