MctsBatch

Struct MctsBatch 

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

Manages a collection of MCTS simulations that can be processed in parallel.

MctsBatch tracks the complete history of each simulation, which is valuable for training machine learning models or analyzing game outcomes.

§Type Parameters

  • T: The type of game being simulated.
  • N: The number of possible actions in the game.

Implementations§

Source§

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

Source

pub fn new() -> Self

Creates a new empty MCTS batch processor with the default configuration.

The random number generator will be seeded based on the current system time.

Source

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

Creates a new empty MCTS batch processor from a specified configuration.

This allows customizing the MCTS parameters for all instances in the batch, including the random number generator’s seed for reproducibility.

§Parameters
  • config: The MctsBatchConfig to use for this batch manager.
Source

pub fn get_count(&self) -> usize

Returns the number of active MCTS instances currently managed by the batch processor.

This count represents the simulations that are still ongoing and have not yet reached a terminal state or been otherwise removed from the batch.

§Returns

The usize representing the total number of active MCTS instances.

§Examples
use simple_mcts::{MctsBatch, test_utils::GameTest, MctsError, Game};

fn main() -> Result<(), MctsError> {
    let mut manager = MctsBatch::<GameTest, 4>::new();
    manager.populate_from_game(vec![GameTest::new(), GameTest::new()])?;
     
    // Initially, the count should reflect the number of populated instances.
    assert_eq!(manager.get_count(), 2);

    // After some iterations, if games finish or are processed, the count might change.
    // (Assuming `next` or other operations might reduce the count)
    // manager.iterate(&evaluator)?; // If an iteration causes a game to finish
    // manager.next()?; // If retrieving results removes finished games
     
    // Example: If one game finishes and is removed
    // assert_eq!(manager.get_count(), 1); 
    Ok(())
}
Source

pub fn get_state(&self) -> u8

Returns the current operational state of the MctsBatch processor.

This indicates whether the batch is Usable (ready for operations), AwaitingSimulation (waiting for external evaluation results), or Locked (temporarily busy with internal processing).

§Returns

A clone of the current MctsState of the batch processor.

§Examples
use simple_mcts::{MctsBatch, test_utils::GameTest, MctsError, MctsState, Game};

fn main() -> Result<(), MctsError> {
    let manager = MctsBatch::<GameTest, 4>::new();
    // A newly created MctsBatch is typically in the Usable state.
    assert_eq!(manager.get_state(), MctsState::USABLE);
     
    // The state would change, for example, after calling `start_iteration`
    // (if MctsBatch had such a method that changed its state to AwaitingSimulation)
    // or during internal processing.
    Ok(())
}
Source

pub fn populate(&mut self, n: usize) -> Result<(), MctsError>

Populates the batch with new MCTS instances.

This method requires the batch processor to be in a Usable state.

§Parameters
  • n: The number of new instances to add.
§Returns

Ok(()) if the batch is successfully populated. Err(MctsError::InvalidState(_)) if the batch processor is not in the Usable state.

Source

pub fn populate_from_game(&mut self, games: Vec<T>) -> Result<(), MctsError>

Populates the batch with new MCTS instances, each initialized with an existing game state.

This method requires the batch processor to be in a Usable state.

§Parameters
  • games: A vector of game states to initialize the new instances.
§Returns
  • Ok(()) if the batch is successfully populated.
  • Err(MctsError::InvalidState(_)) if the batch is not in the Usable state.
Source

pub fn clear(&mut self) -> Result<(), MctsError>

Clears all instances from the batch, resetting it to an empty state.

This method requires the batch processor to be in a Usable state.

§Returns
  • Ok(()) if the batch is successfully cleared.
  • Err(MctsError::InvalidState(_)) if the batch is not in the Usable state.
Source

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

Performs one full MCTS iteration on all active instances in the batch.

This method requires the batch processor to be in a Usable state.

§Parameters
  • evaluator: The policy/value evaluator used for simulations.
§Returns
  • Ok(()) if all active instances complete an iteration successfully.
  • Err(MctsError::InvalidState(_)): If the batch is not in the Usable state.
  • Propagated errors from MCTS instances, such as:
    • MctsError::SearchAlreadyOver
    • MctsError::InvalidEvaluationCount
    • MctsError::ActionOutOfRange
    • MctsError::InvalidAction
    • MctsError::UnexploredAction
Source

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

Initiates the selection and expansion phases for all active MCTS instances in the batch.

This method requires the batch processor to be in a Usable state and transitions it to AwaitingSimulation.

§Returns

Ok(Vec<T::State>) containing the game states from each instance that require external evaluation. Err(MctsError::InvalidState(_)) if the batch processor is not in the Usable state. Err(MctsError::SearchAlreadyOver) if an MCTS instance’s root node indicates the game is already finished.

Source

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

Applies the results of external simulations and performs backpropagation for all active MCTS instances.

This method requires the batch processor to be in the AwaitingSimulation state and transitions it back to Usable.

§Parameters
  • evaluations: A vector of tuples, where each tuple contains the estimated value (f64) and action probabilities ([f64; N]) for an MCTS instance. The order of evaluations should correspond to the order of game states returned by start_iteration.
§Returns

Ok(()) if all simulations are successfully applied and backpropagation completes. Err(MctsError::InvalidState(_)) if the batch processor is not in the AwaitingSimulation state. Err(MctsError::InvalidEvaluationCount(expected, received)) if the number of provided evaluations does not match the number of active instances that were awaiting simulation.

Source

pub fn next(&mut self) -> Result<Vec<Vec<(T, f64, [f64; N])>>, MctsError>

Retrieves the final results (score and policy) for any MCTS instances that have completed their search (game is finished at the root).

Completed instances are removed from the batch. This method can only be called when the batch is in a Usable state.

§Returns

Ok(Vec<(f64, [f64; N])>) containing tuples of final score and action probabilities for completed games. Returns an empty Vec if no instances have finished. Err(MctsError::InvalidState(_)) if the batch processor is not in the Usable state.

Auto Trait Implementations§

§

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

§

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

§

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

§

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

§

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

§

impl<T, const N: usize> UnwindSafe for MctsBatch<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