Struct Mcts

Source
pub struct Mcts<T: Game<N>, const N: usize> { /* private fields */ }
Expand description

The Monte Carlo Tree Search algorithm implementation.

This struct manages the MCTS tree for a single game instance, allowing for iterative search, game progression, and result retrieval.

§Type Parameters

  • T: The game type that implements the Game trait.
  • N: The number of possible actions in the game, a constant generic.

Implementations§

Source§

impl<T: Game<N>, const N: usize> Mcts<T, N>

Source

pub const VICTORY_SCORE: f64 = 1f64

Standard score representing a victory in the game (e.g., for the current player).

Source

pub const DEFEAT_SCORE: f64 = -1f64

Standard score representing a defeat in the game (e.g., for the current player).

Source

pub const EQUALITY_SCORE: f64 = 0f64

Standard score representing a draw or tie in the game.

Source

pub fn new() -> Self

Creates a new MCTS instance with the default configuration.

The default configuration uses MctsConfig::DEFAULT, which includes a standard exploration_coef and the default_selection_score selection function.

§Returns

A new MCTS instance ready to start searching from a new game.

Source

pub fn from_config(config: &MctsConfig<N>) -> Self

Creates a new MCTS instance from a specified configuration.

This allows users to customize the exploration coefficient and the selection function used during the MCTS process.

§Parameters
  • config: The MctsConfig to use for this instance.
§Returns

A new MCTS instance initialized with the given configuration, ready to start searching from a new game.

Source

pub fn from_game(game: T) -> Self

Creates a new MCTS instance starting from an existing game state with the default configuration.

This is useful when you want to continue a search from a specific point in a game without custom MCTS parameters.

§Parameters
  • game: The initial game instance.
§Returns

A new MCTS instance rooted at the given game state, using MctsConfig::DEFAULT.

Source

pub fn from_game_with_config(game: T, config: &MctsConfig<N>) -> Self

Creates a new MCTS instance starting from an existing game state with a custom configuration.

This allows resuming a search from a specific game point with fine-tuned MCTS parameters.

§Parameters
  • game: The initial game instance.
  • config: The MctsConfig to use for this instance.
§Returns

A new MCTS instance rooted at the given game state, initialized with the provided configuration.

Source

pub fn get_game(&self) -> &T

Gets an immutable reference to the underlying game instance.

This allows inspection of the game state without modifying the MCTS tree.

§Returns

A reference to the internal Game instance.

Source

pub fn get_state(&self) -> u8

Returns the current operational state of the MCTS instance.

This indicates whether the MCTS is ready for a new iteration, awaiting simulation results, or temporarily locked.

§Returns

A clone of the current MctsState.

Source

pub fn iterate( &mut self, evaluator: &dyn GameEvaluator<T, N>, ) -> Result<(), MctsError>

Performs one full iteration of MCTS (selection, expansion, simulation, backpropagation).

This method requires the MCTS instance to be in a Usable state.

§Parameters
  • evaluator: The policy/value evaluator to use.
§Returns

Ok(()) if the iteration completes successfully. Err(MctsError::InvalidState(_)) if the MCTS instance is not in the Usable state.

Source

pub fn start_iteration(&mut self) -> Result<T::State, MctsError>

Performs the first partial iteration of MCTS (selection and expansion), returning the game state for external simulation.

This method transitions the MCTS instance from Usable to AwaitingSimulation state.

§Returns

Ok(game_state) containing the game state requiring evaluation. Err(MctsError::InvalidState(_)) if the MCTS instance is not in the Usable state. Err(MctsError::SearchAlreadyOver) if the root node already represents a finished game.

Source

pub fn apply_simulation( &mut self, evaluation: (f64, [f64; N]), ) -> Result<(), MctsError>

Completes a partial MCTS iteration by applying an external simulation’s evaluation and performing backpropagation.

This method transitions the MCTS instance from AwaitingSimulation back to Usable state.

§Parameters
  • evaluation: A tuple containing the estimated value (f64) and action probabilities ([f64; N]) from the external simulation.
§Returns

Ok(()) if the simulation is successfully applied and backpropagation completes. Err(MctsError::InvalidState(_)) if the MCTS instance is not in the AwaitingSimulation state.

Source

pub fn is_finish(&self) -> bool

Determines if the MCTS search has concluded, either because the game is finished or due to other stopping criteria (though currently only checks for game finish).

§Returns

true if the MCTS search is considered finished (e.g., game over at root), false otherwise.

Source

pub fn get_score(&self) -> f64

Gets the current value estimate for the root node

Source

pub fn get_statistics(&self) -> [f64; N]

Gets the current action probabilities from the root node

Source

pub fn get_result(&self) -> (f64, [f64; N])

Returns the final result of the MCTS search (best score and policy).

This method is typically called when the search is considered complete or when a decision needs to be made based on the current tree.

§Returns

A tuple containing:

  • The average value of the root node (f64).
  • An array of action probabilities ([f64; N]), which is usually the policy from the root node adjusted by visit counts for robust decision making.
Source

pub fn count_visit(&self) -> usize

Calculates the total number of visits across all nodes in the MCTS tree.

This can be used as a metric for the extent of the search performed.

§Returns

The sum of visit counts (n) of all nodes in the tree.

Source

pub fn play(&mut self, action: usize) -> Result<(), MctsError>

Moves the MCTS root to the specified child, effectively playing an action.

This method prunes the tree, discarding all branches not descending from the chosen child. The MCTS instance must be in a Usable state.

§Parameters
  • action: The index of the child (action) to play.
§Returns

Ok(()) if the root is successfully moved to the child corresponding to the action. Err(MctsError::InvalidState(_)) if the MCTS instance is not in the Usable state. Err(MctsError::ActionOutOfRange(action, N)) if the action index is out of bounds (>= N). Err(MctsError::InvalidAction(_)) if the action is invalid according to the game mask. Err(MctsError::UnexploredAction) if the action cannot be check because root is null.

Auto Trait Implementations§

§

impl<T, const N: usize> !Freeze for Mcts<T, N>

§

impl<T, const N: usize> RefUnwindSafe for Mcts<T, N>
where T: RefUnwindSafe,

§

impl<T, const N: usize> Send for Mcts<T, N>
where T: Send,

§

impl<T, const N: usize> Sync for Mcts<T, N>
where T: Sync,

§

impl<T, const N: usize> Unpin for Mcts<T, N>
where T: Unpin,

§

impl<T, const N: usize> UnwindSafe for Mcts<T, N>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V