odatse.algorithm.montecarlo module#
- class odatse.algorithm.montecarlo.AlgorithmBase(info: Info, runner: Runner = None, domain=None, nwalkers: int = 1, run_mode: str = 'initial')[source]#
Bases:
AlgorithmBaseBase class for Monte Carlo algorithms implementing common functionality.
This class provides the foundation for various Monte Carlo methods, handling both continuous and discrete parameter spaces. It supports parallel execution with multiple walkers and temperature-based sampling methods.
Implementation Details#
- The class handles two types of parameter spaces:
Continuous: Uses real-valued parameters within specified bounds
Discrete: Uses node-based parameters with defined neighbor relationships
- For continuous problems:
Parameters are bounded by xmin and xmax
Steps are controlled by xstep for each dimension
- For discrete problems:
Parameters are represented as nodes in a graph
Transitions are only allowed between neighboring nodes
Neighbor relationships must form a connected, bidirectional graph
- The sampling process:
Initializes walkers in valid positions
Proposes moves based on the parameter space type
Evaluates the objective function (“Energy”)
Accepts/rejects moves based on the Monte Carlo criterion
Tracks the best solution found
Key Methods#
- _initialize() :
Sets up initial walker positions and counters
- statespace.propose() :
Generates candidate moves for walkers (lives on the state space)
- local_update() :
Performs one Monte Carlo step
- _evaluate() :
Computes objective function values
Initialize the AlgorithmBase class.
- param info:
Information object containing algorithm parameters.
- type info:
odatse.Info
- param runner:
Runner object for executing the algorithm, by default None.
- type runner:
odatse.Runner, optional
- param domain:
Domain object defining the problem space, by default None.
- type domain:
odatse.domain.Domain, optional
- param nwalkers:
Number of walkers to use in the simulation, by default 1.
- type nwalkers:
int, optional
- param run_mode:
Mode of the run, e.g., “initial”, by default “initial”.
- type run_mode:
str, optional
- raises ValueError:
If an unsupported domain type is provided or required parameters are missing.
Examples
>>> info = odatse.Info(config_file_path) >>> runner = odatse.Runner() >>> algorithm = AlgorithmBase(info, runner, nwalkers=100)
- __init__(info: Info, runner: Runner = None, domain=None, nwalkers: int = 1, run_mode: str = 'initial') None[source]#
Initialize the AlgorithmBase class.
- Parameters:
info (odatse.Info) – Information object containing algorithm parameters.
runner (odatse.Runner, optional) – Runner object for executing the algorithm, by default None.
domain (odatse.domain.Domain, optional) – Domain object defining the problem space, by default None.
nwalkers (int, optional) – Number of walkers to use in the simulation, by default 1.
run_mode (str, optional) – Mode of the run, e.g., “initial”, by default “initial”.
- Raises:
ValueError – If an unsupported domain type is provided or required parameters are missing.
Examples
>>> info = odatse.Info(config_file_path) >>> runner = odatse.Runner() >>> algorithm = AlgorithmBase(info, runner, nwalkers=100)
- _apply_state(data: dict, mode: str = 'resume', restore_rng: bool = True) None[source]#
Restore algorithm state from a checkpoint snapshot.
Delegates MPI validation, timer restore, parameter check, and RNG restore to the base class, then applies every field listed in
montecarlo.AlgorithmBase._checkpoint_attrs. Subclasses that need additional fields should override this method, callsuper()._apply_state(data, mode=mode, restore_rng=restore_rng), then handle their own fields.- Parameters:
data (dict) – Snapshot previously produced by
__getstate__.mode (str) –
"resume"or"continue", forwarded to base class and available to subclass overrides for continue-mode semantics.restore_rng (bool) – When True (default) the RNG state is restored from data; when False a fresh RNG state is kept (
--reset_randmode).
- _evaluate(state, in_range: ndarray = None) ndarray[source]#
Evaluate objective function for current walker positions.
- Optimization Features:
Skips evaluation for out-of-bounds positions
Tracks evaluation timing statistics
Supports parallel evaluation across walkers
- Parameters:
state (ContinuousState or DiscreteState) – Walker state whose positions
state.xare evaluated.in_range (np.ndarray, optional) – Boolean mask indicating valid positions True = position is valid and should be evaluated False = position is invalid, will be assigned inf
- Returns:
Array of objective function values Invalid positions are assigned inf
- Return type:
np.ndarray
- _initialize()[source]#
Initialize the Monte Carlo simulation state.
- For continuous problems:
Uses domain.initialize to generate valid initial positions
Respects any additional limitations from the runner
- For discrete problems:
Randomly assigns walkers to valid nodes
Maps node indices to actual coordinate positions
- Also initializes:
Objective function values (fx) to zero
Best solution tracking variables
Acceptance counters for monitoring convergence
- _prepare() None[source]#
Algorithm-specific preparation (MC layer).
Called by the framework after checkpoint dispatch. The default implementation does nothing; MC subclasses override this to initialise timer entries or other pre-loop state.
- local_update(beta: float | ndarray, extra_info_to_write: list | tuple = None) None[source]#
Perform one step of the Monte Carlo algorithm.
- Algorithm Flow:
Generate proposed moves for all walkers
Check if proposals are within valid bounds
Evaluate objective function for valid proposals
Apply Metropolis acceptance criterion:
P(accept) = min(1, exp(-beta * (f_new - f_old)))For discrete case, adjust acceptance probability by:
P *= (n_neighbors_old / n_neighbors_new)Update positions and energies
Track best solution found
Log results if writers are configured
- Parameters:
beta (Union[float, np.ndarray]) – Inverse temperature(s) controlling acceptance probability Can be single value or array (one per walker)
extra_info_to_write (Union[list, tuple], optional) – Additional data to log with results
Notes
Handles numerical overflow in exponential calculation
Maintains detailed acceptance statistics
Supports both single and multiple temperature values
Preserves best solution across all steps