solverforge-core 0.31.1

Core types and traits for SolverForge constraint solver
Documentation
//! Core domain traits

use std::any::Any;
use std::hash::Hash;

use crate::constraint_weights::ConstraintWeights;
use crate::score::Score;

/// Marker trait for planning solutions.
///
/// A planning solution represents both the problem definition and the
/// (potentially partial) solution. It contains:
/// - Problem facts: Immutable input data
/// - Planning entities: Things to be optimized
/// - Score: The quality of the current solution
///
/// # Example
///
/// ```
/// use solverforge_core::{PlanningSolution, score::SoftScore};
///
/// #[derive(Clone)]
/// struct NQueens {
///     n: usize,
///     rows: Vec<Option<usize>>,
///     score: Option<SoftScore>,
/// }
///
/// impl PlanningSolution for NQueens {
///     type Score = SoftScore;
///
///     fn score(&self) -> Option<Self::Score> {
///         self.score
///     }
///
///     fn set_score(&mut self, score: Option<Self::Score>) {
///         self.score = score;
///     }
/// }
/// ```
///
/// For complex solutions, use the `#[derive(PlanningSolution)]` macro from `solverforge-macros`.
///
/// # Thread Safety
///
/// Planning solutions must be `Send + Sync` to support multi-threaded solving.
pub trait PlanningSolution: Clone + Send + Sync + 'static {
    /// The score type used to evaluate this solution.
    type Score: Score;

    /// Returns the current score of this solution, if calculated.
    ///
    /// Returns `None` if the solution has not been scored yet.
    fn score(&self) -> Option<Self::Score>;

    /// Stores the score; `None` marks the solution as unscored.
    fn set_score(&mut self, score: Option<Self::Score>);

    /// Updates shadow variables for the descriptor/entity pair.
    ///
    /// Default implementation is a no-op. Solutions with derived state can override
    /// this to keep cached values synchronized during solving.
    fn update_entity_shadows(&mut self, _descriptor_index: usize, _entity_index: usize) {}

    /// Updates all shadow variables for the full solution.
    ///
    /// Default implementation is a no-op. Solutions with derived state can override
    /// this to refresh all cached values before initialization.
    fn update_all_shadows(&mut self) {}

    /// Whether this solution type carries runtime constraint weights.
    ///
    /// Whether a value's weights apply is decided by the score director's weight
    /// mode, a type chosen when the director is built; solves pick the weighted
    /// mode only when this constant is `true` and some multiplier differs from
    /// `1`. `#[planning_solution]` sets it to `true` exactly when a field is
    /// marked `#[constraint_weights]`, and then also routes the solve through the
    /// weighted entrypoint. A manual implementation that overrides
    /// `constraint_weights` must set it to `true` as well, or the weights are
    /// never applied.
    const HAS_CONSTRAINT_WEIGHTS: bool = false;

    /// Returns the runtime constraint weight multipliers carried by this solution.
    ///
    /// Default implementation returns `None`: every constraint keeps its coded
    /// weight. `#[planning_solution]` generates this accessor for the field marked
    /// `#[constraint_weights]`. Weighted-mode score directors bind these
    /// multipliers on construction and on every (re)initialization, so a running
    /// solve must reset its director after changing them.
    fn constraint_weights(&self) -> Option<&ConstraintWeights> {
        None
    }

    /// Returns the elements whose list shadows
    /// `update_entity_shadows(descriptor_index, entity_index)` writes, with the
    /// change source their stream rows are reported under.
    ///
    /// A score director retracts these rows before the shadow write and inserts
    /// them after it, so streams that read element shadows stay incremental.
    /// Default implementation reports no list shadows.
    fn list_shadow_elements(
        &self,
        _descriptor_index: usize,
        _entity_index: usize,
    ) -> Option<(usize, &[usize])> {
        None
    }

    /// Clears the list shadows of an element that no list holds any more.
    ///
    /// Default implementation is a no-op.
    fn clear_list_shadows(&mut self, _element: usize) {}

    /// Returns the change source under which rows of `collection` are reported
    /// when they carry list shadows, or `None` when the collection holds none.
    fn list_shadow_source(_collection: &str) -> Option<usize> {
        None
    }

    /// Whether the list shadows include a cascading shadow: an element value
    /// computed from the element's previous element in its list and from the
    /// elements it declares it depends on, which may sit in other owners'
    /// lists.
    ///
    /// `#[shadow_variable_updates(cascading_field = ...)]` sets it to `true`
    /// and generates the `cascading_*` hooks below. When it is `false`
    /// (the default) a score director compiles no cascading code into its
    /// variable-change path.
    const HAS_CASCADING_SHADOWS: bool = false;

    /// Number of elements in the collection that carries the cascading
    /// shadow.
    fn cascading_element_count(&self) -> usize {
        0
    }

    /// Whether `element` is held by a list.
    fn cascading_assigned(&self, _element: usize) -> bool {
        false
    }

    /// The element after `element` in its list, if any.
    fn cascading_next(&self, _element: usize) -> Option<usize> {
        None
    }

    /// Appends the elements `element`'s cascading value depends on, besides
    /// its previous element in its list, to `dependencies`. Dependencies are
    /// problem facts: moves never change them.
    fn cascading_dependencies(&self, _element: usize, _dependencies: &mut Vec<usize>) {}

    /// Appends the peers of `element` to `peers`: elements computed together
    /// with it, joined transitively into a joint group. A member's value is
    /// computed after the previous elements and dependencies of every member
    /// hold their final values, so it may read them; it must not read
    /// another member's cascading value. Peers are problem facts: moves
    /// never change them.
    fn cascading_peers(&self, _element: usize, _peers: &mut Vec<usize>) {}

    /// Whether `element`'s list structure shadows already describe the place
    /// `owner_descriptor`/`owner_index`, position `index`, between `previous`
    /// and `next`: its owner, previous and next shadows (and index shadow,
    /// when declared) hold those values.
    ///
    /// A score director with a cascading shadow asks this before rewriting an
    /// owner's structure and keeps the stream row of an element that answers
    /// `true` and whose cascading value does not change. `false` (the default)
    /// rescores the element. `#[shadow_variable_updates(cascading_field =
    /// ...)]` generates it from the configured structure fields.
    fn list_structure_unchanged(
        &self,
        _element: usize,
        _owner_descriptor: usize,
        _owner_index: usize,
        _index: usize,
        _previous: Option<usize>,
        _next: Option<usize>,
    ) -> bool {
        false
    }

    /// Whether `element`'s cascading value is unset.
    fn cascading_unset(&self, _element: usize) -> bool {
        true
    }

    /// Recomputes `element`'s cascading value, or unsets it when
    /// `computable` is `false` (the element is in no list, or on a
    /// dependency cycle). When the value changes, calls `before_write` with
    /// the solution still holding the old value, then writes the new one and
    /// returns `true`.
    fn update_cascading_shadow<W: FnOnce(&Self)>(
        &mut self,
        _element: usize,
        _computable: bool,
        _before_write: W,
    ) -> bool {
        false
    }

    /// Updates the list shadows of one owner that describe list structure
    /// (inverse, index, previous, next) without the cascading shadow, which
    /// the caller propagates afterwards. Defaults to `update_entity_shadows`.
    fn update_list_structure_shadows(&mut self, descriptor_index: usize, entity_index: usize) {
        self.update_entity_shadows(descriptor_index, entity_index);
    }

    /// Returns true if this solution is fully initialized.
    ///
    /// A solution is initialized when all planning variables have been assigned.
    fn is_initialized(&self) -> bool {
        // Default implementation - can be overridden by derived code
        true
    }
}

/// Marker trait for planning entities.
///
/// A planning entity is something that gets planned/optimized.
/// It contains one or more planning variables that the solver will change.
///
/// # Example
///
/// ```
/// use std::any::Any;
/// use solverforge_core::PlanningEntity;
///
/// #[derive(Clone)]
/// struct Queen {
///     column: i32,
///     row: Option<i32>,
/// }
///
/// impl PlanningEntity for Queen {
///     fn as_any(&self) -> &dyn Any { self }
///     fn as_any_mut(&mut self) -> &mut dyn Any { self }
/// }
/// ```
///
/// For complex entities, use the `#[derive(PlanningEntity)]` macro from `solverforge-macros`.
///
/// # Pinning
///
/// Entities can be "pinned" to preserve their input genuine planning variables
/// during solving. Override `is_pinned()` to return true for pinned entities;
/// manually assembled entity descriptors must also supply a pin predicate.
pub trait PlanningEntity: Clone + Send + Sync + Any + 'static {
    /// Returns true if this entity is pinned (should not be changed).
    ///
    /// Default implementation returns false (entity can be changed).
    fn is_pinned(&self) -> bool {
        false
    }

    /// Cast to Any for dynamic typing support.
    fn as_any(&self) -> &dyn Any;

    /// Cast to mutable Any for dynamic typing support.
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

/// Marker trait for problem facts.
///
/// Problem facts are immutable input data that define the problem.
/// They are used by constraints but not changed during solving.
///
/// # Example
///
/// ```
/// use std::any::Any;
/// use solverforge_core::ProblemFact;
///
/// #[derive(Clone)]
/// struct Room {
///     id: i64,
///     capacity: usize,
/// }
///
/// impl ProblemFact for Room {
///     fn as_any(&self) -> &dyn Any { self }
/// }
/// ```
pub trait ProblemFact: Clone + Send + Sync + Any + 'static {
    /// Cast to Any for dynamic typing support.
    fn as_any(&self) -> &dyn Any;
}

/// Trait for unique identification of entities and facts.
///
/// Used for looking up working copies during solving and rebasing moves.
///
/// # Example
///
/// ```
/// use solverforge_core::PlanningId;
///
/// #[derive(Clone)]
/// struct Task {
///     id: i64,
///     name: String,
/// }
///
/// impl PlanningId for Task {
///     type Id = i64;
///     fn planning_id(&self) -> i64 { self.id }
/// }
/// ```
///
/// The ID type must be `Eq + Hash + Clone`.
pub trait PlanningId {
    /// The type of the unique identifier.
    type Id: Eq + Hash + Clone + Send + Sync + 'static;

    /// Returns the unique identifier for this object.
    ///
    /// This must never return a value that changes during solving.
    fn planning_id(&self) -> Self::Id;
}