use std::fmt::Debug;
use std::marker::PhantomData;
use solverforge_core::domain::PlanningSolution;
use solverforge_scoring::Director;
use crate::heuristic::r#move::ListChangeMove;
use crate::list_placement::{selected_owner_allows, OwnerRestriction, SelectedOwnerRestrictions};
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::precedence_route::{PrecedenceRouteGraph, PrecedenceRouteHooks};
pub struct ListChangeMoveSelector<S, V, ES> {
entity_selector: ES,
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),
element_owner_fn: Option<fn(&S, &V) -> Option<usize>>,
precedence_route_hooks: Option<PrecedenceRouteHooks<S, V>>,
variable_name: &'static str,
descriptor_index: usize,
_phantom: PhantomData<(fn() -> S, fn() -> V)>,
}
enum ListChangeStage {
Intra,
Inter,
}
pub struct ListChangeMoveCursor<S, V>
where
S: PlanningSolution,
V: Clone + PartialEq + Send + Sync + Debug + 'static,
{
store: CandidateStore<S, ListChangeMove<S, V>>,
entities: Vec<usize>,
route_lens: Vec<usize>,
context: MoveStreamContext,
src_idx: usize,
src_pos_offset: usize,
stage: ListChangeStage,
intra_dst_offset: usize,
dst_idx: usize,
inter_dst_pos_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),
element_owners: Option<Vec<Vec<OwnerRestriction>>>,
fixed_to_current_entity: bool,
precedence_route_graph: Option<PrecedenceRouteGraph>,
variable_name: &'static str,
descriptor_index: usize,
}
impl<S, V> ListChangeMoveCursor<S, V>
where
S: PlanningSolution,
V: Clone + PartialEq + Send + Sync + Debug + 'static,
{
#[allow(clippy::too_many_arguments)]
fn new(
entities: Vec<usize>,
route_lens: Vec<usize>,
context: MoveStreamContext,
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),
element_owners: Option<Vec<Vec<OwnerRestriction>>>,
fixed_to_current_entity: bool,
precedence_route_graph: Option<PrecedenceRouteGraph>,
variable_name: &'static str,
descriptor_index: usize,
) -> Self {
Self {
store: CandidateStore::new(),
entities,
route_lens,
context,
src_idx: 0,
src_pos_offset: 0,
stage: ListChangeStage::Intra,
intra_dst_offset: 0,
dst_idx: 0,
inter_dst_pos_offset: 0,
list_len,
list_get,
list_remove,
list_insert,
element_owners,
fixed_to_current_entity,
precedence_route_graph,
variable_name,
descriptor_index,
}
}
pub(crate) fn with_precedence_route_graph(
mut self,
precedence_route_graph: Option<PrecedenceRouteGraph>,
) -> Self {
self.precedence_route_graph = precedence_route_graph;
self
}
fn owner_allows_destination(&self, src_idx: usize, src_pos: usize, dst_entity: usize) -> bool {
self.element_owners
.as_ref()
.is_none_or(|owners| selected_owner_allows(owners, src_idx, src_pos, dst_entity))
}
fn current_source(&self) -> Option<(usize, usize, usize)> {
let src_entity = *self.entities.get(self.src_idx)?;
let src_len = self.route_lens[self.src_idx];
if src_len == 0 {
return Some((src_entity, src_len, 0));
}
let src_pos = ordered_index(
self.src_pos_offset,
src_len,
self.context,
0x1157_C4A4_6E00_0002 ^ src_entity as u64 ^ self.descriptor_index as u64,
);
Some((src_entity, src_len, src_pos))
}
fn advance_source_position(&mut self) {
self.src_pos_offset += 1;
self.stage = ListChangeStage::Intra;
self.intra_dst_offset = 0;
self.dst_idx = 0;
self.inter_dst_pos_offset = 0;
while self.src_idx < self.route_lens.len()
&& self.src_pos_offset >= self.route_lens[self.src_idx]
{
self.src_idx += 1;
self.src_pos_offset = 0;
}
}
fn push_move(
&mut self,
src_entity: usize,
src_pos: usize,
dst_entity: usize,
dst_pos: usize,
) -> CandidateId {
self.store.push(ListChangeMove::new(
src_entity,
src_pos,
dst_entity,
dst_pos,
self.list_len,
self.list_get,
self.list_remove,
self.list_insert,
self.variable_name,
self.descriptor_index,
))
}
}
impl<S, V> MoveCursor<S, ListChangeMove<S, V>> for ListChangeMoveCursor<S, V>
where
S: PlanningSolution,
V: Clone + PartialEq + Send + Sync + Debug + 'static,
{
fn next_candidate(&mut self) -> Option<CandidateId> {
loop {
let (src_entity, src_len, src_pos) = self.current_source()?;
if src_len == 0 {
self.src_idx += 1;
continue;
}
match self.stage {
ListChangeStage::Intra => {
while self.intra_dst_offset <= src_len {
let dst_pos = ordered_index(
self.intra_dst_offset,
src_len + 1,
self.context,
0x1157_C4A4_6E00_0003 ^ src_entity as u64 ^ src_pos as u64,
);
self.intra_dst_offset += 1;
if src_pos == dst_pos || dst_pos == src_pos + 1 {
continue;
}
if self.element_owners.is_some()
&& !self.owner_allows_destination(self.src_idx, src_pos, src_entity)
{
continue;
}
if self.precedence_route_graph.as_ref().is_some_and(|graph| {
graph.intra_list_change_introduces_cycle(src_entity, src_pos, dst_pos)
}) {
continue;
}
return Some(self.push_move(src_entity, src_pos, src_entity, dst_pos));
}
if self.fixed_to_current_entity {
self.advance_source_position();
continue;
}
self.stage = ListChangeStage::Inter;
self.dst_idx = 0;
self.inter_dst_pos_offset = 0;
}
ListChangeStage::Inter => {
while self.dst_idx < self.entities.len() {
if self.dst_idx == self.src_idx {
self.dst_idx += 1;
self.inter_dst_pos_offset = 0;
continue;
}
let dst_entity = self.entities[self.dst_idx];
let dst_len = self.route_lens[self.dst_idx];
if self.inter_dst_pos_offset <= dst_len {
let dst_pos = ordered_index(
self.inter_dst_pos_offset,
dst_len + 1,
self.context,
0x1157_C4A4_6E00_0004
^ src_entity as u64
^ dst_entity as u64
^ src_pos as u64,
);
self.inter_dst_pos_offset += 1;
if self.element_owners.is_some()
&& !self.owner_allows_destination(self.src_idx, src_pos, dst_entity)
{
continue;
}
return Some(self.push_move(src_entity, src_pos, dst_entity, dst_pos));
}
self.dst_idx += 1;
self.inter_dst_pos_offset = 0;
}
self.advance_source_position();
}
}
}
}
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 ListChangeMoveCursor<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, ES: Debug> Debug for ListChangeMoveSelector<S, V, ES> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ListChangeMoveSelector")
.field("entity_selector", &self.entity_selector)
.field("variable_name", &self.variable_name)
.field("descriptor_index", &self.descriptor_index)
.finish()
}
}
impl<S, V, ES> ListChangeMoveSelector<S, V, ES> {
pub fn new(
entity_selector: ES,
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,
list_len,
list_get,
list_remove,
list_insert,
element_owner_fn: None,
precedence_route_hooks: None,
variable_name,
descriptor_index,
_phantom: PhantomData,
}
}
pub fn with_element_owner_fn(
mut self,
element_owner_fn: Option<fn(&S, &V) -> Option<usize>>,
) -> Self {
self.element_owner_fn = element_owner_fn;
self
}
pub(crate) fn with_precedence_route_hooks(
mut self,
precedence_route_hooks: Option<PrecedenceRouteHooks<S, V>>,
) -> Self {
self.precedence_route_hooks = precedence_route_hooks;
self
}
pub(crate) fn precedence_route_hooks(&self) -> Option<PrecedenceRouteHooks<S, V>> {
self.precedence_route_hooks
}
}
impl<S, V, ES> MoveSelector<S, ListChangeMove<S, V>> for ListChangeMoveSelector<S, V, ES>
where
S: PlanningSolution,
V: Clone + PartialEq + Send + Sync + Debug + 'static,
ES: EntitySelector<S>,
{
type Cursor<'a>
= ListChangeMoveCursor<S, V>
where
Self: 'a;
fn open_cursor<'a, D: Director<S>>(&'a self, score_director: &D) -> Self::Cursor<'a> {
self.open_cursor_with_context(score_director, MoveStreamContext::default())
}
fn open_cursor_with_context<'a, D: Director<S>>(
&'a self,
score_director: &D,
context: MoveStreamContext,
) -> Self::Cursor<'a> {
let mut selected =
collect_selected_entities(&self.entity_selector, score_director, self.list_len);
selected.apply_stream_order(
context,
0x1157_C4A4_6E00_0001 ^ self.descriptor_index as u64,
);
let owner_restrictions = crate::list_placement::selected_owner_restrictions(
self.element_owner_fn,
score_director.working_solution(),
score_director
.entity_count(self.descriptor_index)
.unwrap_or(0),
&selected.entities,
&selected.route_lens,
self.list_get,
);
let fixed_to_current_entity = owner_restrictions
.as_ref()
.is_some_and(SelectedOwnerRestrictions::is_fixed_to_current);
let element_owners = owner_restrictions.and_then(SelectedOwnerRestrictions::into_mixed);
ListChangeMoveCursor::new(
selected.entities,
selected.route_lens,
context,
self.list_len,
self.list_get,
self.list_remove,
self.list_insert,
element_owners,
fixed_to_current_entity,
None,
self.variable_name,
self.descriptor_index,
)
}
fn size<D: Director<S>>(&self, score_director: &D) -> usize {
let selected =
collect_selected_entities(&self.entity_selector, score_director, self.list_len);
let Some(owner_restrictions) = crate::list_placement::selected_owner_restrictions(
self.element_owner_fn,
score_director.working_solution(),
score_director
.entity_count(self.descriptor_index)
.unwrap_or(0),
&selected.entities,
&selected.route_lens,
self.list_get,
) else {
return selected.list_change_move_capacity();
};
if owner_restrictions.is_fixed_to_current() {
return selected
.route_lens
.iter()
.map(|&src_len| src_len * list_change_intra_destination_count(src_len))
.sum();
}
let element_owners = owner_restrictions
.mixed()
.expect("non-fixed owner restrictions must retain mixed owner matrix");
let mut count = 0;
for (src_idx, (&src_entity, &src_len)) in selected
.entities
.iter()
.zip(selected.route_lens.iter())
.enumerate()
{
for src_pos in 0..src_len {
if selected_owner_allows(element_owners, src_idx, src_pos, src_entity) {
count += list_change_intra_destination_count(src_len);
}
for (dst_idx, (&dst_entity, &dst_len)) in selected
.entities
.iter()
.zip(selected.route_lens.iter())
.enumerate()
{
if dst_idx == src_idx {
continue;
}
if selected_owner_allows(element_owners, src_idx, src_pos, dst_entity) {
count += dst_len + 1;
}
}
}
}
count
}
}
#[inline]
fn list_change_intra_destination_count(src_len: usize) -> usize {
src_len.saturating_sub(1)
}