Skip to main content

MctsBatch

Struct MctsBatch 

Source
pub struct MctsBatch<F: SelectionFunction, S: ScoreTransformer, const N: usize> { /* private fields */ }
Expand description

The Batch Manager for MCTS Engines.

It acts as a memory-efficient Arena Allocator (Slot Map) that can manage thousands of independent MCTS trees simultaneously without reallocating memory.

Implementations§

Source§

impl<F: SelectionFunction, S: ScoreTransformer, const N: usize> MctsBatch<F, S, N>

Source

pub fn from_config(config: MctsConfig<F, S>) -> Self

Initializes a new, empty batch manager from a given configuration.

§Arguments
  • config - The MctsConfig specifying exploration rate and heuristics.
§Returns

A new, empty MctsBatch instance.

§Examples
let config = MctsConfig::new(1.414, |w, n, p_n, p, c| 0.0, |s| -s);
let mut batch = MctsBatch::<_, _, 9>::from_config(config);
Source

pub fn add(&mut self) -> MctsId

Allocates a new MCTS engine in the batch.

Memory slots are recycled using a free-list to guarantee O(1) amortized performance.

§Returns

Returns the uniquely generated MctsId for the new engine.

Source

pub fn populate(&mut self, n: usize) -> IdCollection

Pre-allocates and populates the batch with a specified number of new engines.

§Arguments
  • n - The number of engines to instantiate.
§Returns

A collection (IdCollection) containing all the newly minted MctsIds.

Source

pub fn remove_one(&mut self, id: MctsId)

Safely deallocates a specific engine and marks its memory slot for reuse.

Silently ignores the operation if the provided ID is already deleted or out of bounds.

§Arguments
  • id - The MctsId of the engine to remove.
Source

pub fn remove(&mut self, ids: IdCollection)

Deallocates a collection of engines.

§Arguments
  • ids - The collection of MctsIds to remove from the batch.
Source

pub fn clear(&mut self)

Deallocates all active engines and resets the free-list.

§Note

This completely invalidates any MctsId currently held by the user.

Source

pub fn sessions(&self) -> usize

Returns the number of currently active engines in the batch.

§Returns

An usize representing the active session count.

Source

pub fn selection(&self) -> ResultCollection

Triggers the selection phase across all active engines.

§Returns

A ResultCollection containing the traversal paths and selection outcomes for every active engine.

§Examples
batch.populate(3);
let selections = batch.selection();
assert_eq!(selections.len(), 3);
Source

pub fn update_one_with_transformer( &mut self, evaluation: MctsStateEvaluation<N>, score_transformer: &mut impl ScoreTransformer, ) -> Result<(), MctsError>

Updates a single engine with an evaluation result using a custom, localized score transformer.

This method acts as an “escape hatch” for complex or asymmetric games (e.g., 3-player games, hidden information) where the backpropagation logic depends on the specific context of the ongoing game, rather than the universal rule defined in MctsConfig.

§Arguments
  • evaluation - The evaluated state to be integrated into the specific tree.
  • score_transformer - A mutable reference to a custom closure or struct implementing ScoreTransformer.
§Errors

Returns an MctsError::InvalidMctsId if the ID doesn’t point to an active engine. Returns an MctsError::EngineError if the internal tree expansion or backpropagation fails.

§Examples
let eval = MctsStateEvaluation {
    id,
    selection: sel.selection,
    evaluation: StateEvaluation::Terminal(1.0)
};

// Using a custom transformer capturing a local state/context
let mut local_scores = [1.0, -0.5, -0.5]; // e.g., 3-player score array

batch.update_one_with_transformer(eval, &mut |score| {
    // Custom asymmetric logic using the local context
    score * local_scores[0]
}).unwrap();
Source

pub fn update_one( &mut self, evaluation: MctsStateEvaluation<N>, ) -> Result<(), MctsError>

Updates a single engine with an evaluation result and backpropagates the score.

§Arguments
  • evaluation - The evaluated state to be integrated into the specific tree.
§Errors

Returns an MctsError::InvalidMctsId if the ID doesn’t point to an active engine. Returns an MctsError::EngineError if the internal tree expansion or backpropagation fails.

Source

pub fn update( &mut self, evaluations: &mut StateEvaluationCollection<N>, ) -> Result<(), MctsError>

Transactionally updates multiple engines with their respective evaluations.

This function consumes the provided vector. If an error occurs, the function aborts and pushes the problematic evaluation back into the vector to prevent data loss.

§Arguments
  • evaluations - A mutable reference to a collection of evaluations to process.
§Errors

Returns an MctsError if any single engine update fails or if an ID is invalid.

§Examples
let id = batch.add();
let mut selections = batch.selection();
let sel = selections.pop().unwrap();

let mut evals = vec![MctsStateEvaluation {
    id,
    selection: sel.selection,
    evaluation: StateEvaluation::Terminal(1.0)
}];

batch.update(&mut evals).unwrap();
Source

pub fn scores_one(&self, id: MctsId) -> Result<[i32; N], MctsError>

Retrieves the visit counts of all possible actions for a specific engine.

§Arguments
  • id - The unique identifier of the target engine.
§Returns

Returns an array [i32; N] representing the visit distribution of the root node.

§Errors

Returns MctsError::InvalidMctsId if the specified engine is inactive or deleted.

Source

pub fn scores(&self) -> ScoreCollection<N>

Retrieves the visit counts of all possible actions for all active engines.

§Returns

A ScoreCollection containing the score arrays paired with their respective engine IDs.

Source

pub fn commit_actions( &mut self, actions: &mut ActionCollection, ) -> Result<(), MctsError>

Transactionally commits a list of played actions, updating the internal roots of the corresponding engines.

§Arguments
  • actions - A mutable reference to the collection of actions to commit.
§Errors

Returns MctsError::InvalidMctsId if an action targets a non-existent engine.

§Panics

Panics if an action index is out of bounds (i.e., >= N) or if the internal tree structure of an engine is corrupted.

Source

pub fn commit_action(&mut self, action: MctsAction) -> Result<(), MctsError>

Commits a single played action, moving the root of the specified engine.

§Arguments
  • action - The MctsAction containing the target ID and the action index.
§Errors

Returns MctsError::InvalidMctsId if the target engine does not exist.

§Panics

Panics if the action index is out of bounds (i.e., >= N) or if the internal tree structure is corrupted.

Auto Trait Implementations§

§

impl<F, S, const N: usize> Freeze for MctsBatch<F, S, N>
where F: Freeze, S: Freeze,

§

impl<F, S, const N: usize> RefUnwindSafe for MctsBatch<F, S, N>

§

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

§

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

§

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

§

impl<F, S, const N: usize> UnsafeUnpin for MctsBatch<F, S, N>
where F: UnsafeUnpin, S: UnsafeUnpin,

§

impl<F, S, const N: usize> UnwindSafe for MctsBatch<F, S, N>
where F: UnwindSafe, S: 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.