Simulation API and Caching
The simulation API runs batches of episodes and hands back every episode’s record plus a table of statistics. Use it instead of writing your own episode loop: it caches each finished episode on disk, gives every episode a fixed seed, runs episodes in parallel, and logs the run to MLflow so the results site can show it. A loop of your own gets none of that, and nothing warns you.
For a walk-through of a full study, see the Running Simulations guide.
Example
Run four episodes of POMCP on Tiger and read the average return:
import tempfile
from pathlib import Path
import numpy as np
from POMDPPlanners.core.belief import get_initial_belief
from POMDPPlanners.core.simulation import EnvironmentRunParams
from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP
from POMDPPlanners.planners.mcts_planners.pomcp import POMCP
from POMDPPlanners.simulations import LocalSimulationsAPI
np.random.seed(0) # fixes the initial belief, and so the cache key
env = TigerPOMDP(discount_factor=0.95)
planner = POMCP(
environment=env,
discount_factor=0.95,
depth=5,
exploration_constant=1.0,
name="POMCP",
time_out_in_seconds=2.0,
)
run_params = EnvironmentRunParams(
environment=env,
belief=get_initial_belief(env, n_particles=100),
policies=[planner],
num_episodes=4,
num_steps=10,
)
run_dir = Path(tempfile.mkdtemp()) / "tiger-demo"
api = LocalSimulationsAPI(cache_dir_path=run_dir)
histories, stats = api.run_multiple_environments_and_policies(
environment_run_params=[run_params],
alpha=0.05, # CVaR over the worst 5% of returns
confidence_interval_level=0.95,
experiment_name="tiger_demo",
n_jobs=1,
cache_dir_path=run_dir,
)
episodes = histories["TigerPOMDP"]["POMCP"] # one History per episode
print(len(episodes), stats[["policy", "average_return"]])
histories maps environment name, then policy name, to a list of
History. stats is a
pandas DataFrame with one row per environment and policy pair. Each metric
column comes with <metric>_ci_lower and <metric>_ci_upper columns;
Metrics lists the metric names.
What a run leaves on disk
Everything goes under cache_dir_path. It defaults to the current
directory, so always pass one.
cache.dband the short hex-named folders next to it: the episode cache, one entry per episode.mlruns/: the MLflow store, whichpomdp-report servereads.logs/: logs of the simulator, the task manager and the cache.env_policy/logs/: one log per environment and policy pair.
How caching works
Each episode is one cached task. Its key is a hash of:
the environment’s
config_id,the policy’s
config_id,the initial belief’s
config_id,the episode index, the step limit and the discount factor,
the episode’s seed.
The seed comes from the environment name, the policy name and the episode
index, so the same episode always gets the same seed. Every config_id is
a hash of the object’s public attributes, so changing any parameter of the
environment or the planner gives new keys, and those episodes run again.
The initial belief is part of the key. get_initial_belief draws random
particles, so seed NumPy before you build the belief, as in the example
above. Without that, every run builds a different belief and no episode is
ever reused.
How a killed run resumes
An episode is written to the cache as soon as it finishes, not at the end of
the batch. If a run is killed, run the same script again with the same
cache_dir_path. Finished episodes load from the cache and only the
missing ones run. The log line Cache status: N tasks cached, M tasks
uncached says how many of each.
A cached episode recorded before an environment reported per-step measurements would score every metric as zero. The task manager detects such an entry and reruns that one episode, keeping the rest.
clear_cache_on_start=True throws the whole cache away. Do not use it to
explain a surprising result: find which config_id changed first, because
clearing removes the finished episodes you would compare against.
Entry points
LocalSimulationsAPI runs on one machine with joblib. DaskSimulationsAPI
and PBSSimulationsAPI have the same methods and run on a Dask cluster or a
PBS queue. All three implement SimulationsAPIInterface.
- class POMDPPlanners.simulations.simulation_apis.local_simulations_api.LocalSimulationsAPI(cache_dir_path=None, debug=False, notification_config=None)[source]
High-level API for running POMDP simulation experiments locally.
This class provides a simplified interface for running POMDP simulations with local execution using Joblib for single-machine parallelization. It wraps the POMDPSimulator class and provides convenient methods for common simulation workflows without distributed computing requirements.
Key Features: - Local execution using Joblib for single-machine parallelization - Debug mode with reduced episodes for quick testing - Automatic profiling and performance analysis - MLflow experiment tracking and result management - Hyperparameter optimization with Optuna
Example
>>> from pathlib import Path >>> from POMDPPlanners.simulations.simulation_apis.local_simulations_api import LocalSimulationsAPI >>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP >>> from POMDPPlanners.planners.mcts_planners.pomcp import POMCP >>> from POMDPPlanners.core.belief import get_initial_belief >>> from POMDPPlanners.core.simulation import EnvironmentRunParams >>> # Initialize the API >>> api = LocalSimulationsAPI(debug=True) >>> # Create environment >>> tiger = TigerPOMDP(discount_factor=0.95) >>> tiger.name 'TigerPOMDP' >>> # Create policy >>> policy = POMCP( ... environment=tiger, ... discount_factor=0.95, ... depth=5, ... exploration_constant=1.0, ... name="POMCP_Tiger", ... n_simulations=20 ... ) >>> policy.name 'POMCP_Tiger' >>> # Configure simulation parameters >>> env_params = EnvironmentRunParams( ... environment=tiger, ... belief=get_initial_belief(tiger, n_particles=10), ... policies=[policy], ... num_episodes=2, ... num_steps=3 ... ) >>> env_params.num_episodes 2
- Parameters:
- run_all_benchmark_environments_on_planner_generators(generators, n_particles=30, num_episodes=10, num_steps=20, alpha=0.1, confidence_interval_level=0.95, experiment_name='All_Benchmark_Environments_On_Planner_Generators', n_jobs=-1, cache_dir_path=None, clear_cache_on_start=False, enable_profiling=False, profiling_output_limit=50, cache_visualizations=True, is_risk_averse=False)[source]
Run all benchmark environments on planner generators.
This method runs benchmark environments on planner generators.
- Parameters:
generators (
Sequence[PlannerGenerator]) – Sequence of PlannerGenerator objects.n_particles (
int) – Number of particles for belief representation.num_episodes (
int) – Number of episodes for optimization.num_steps (
int) – Maximum steps per episode for optimization.alpha (
float) – Statistical significance level for confidence intervals.confidence_interval_level (
float) – Confidence level for statistical analysis.experiment_name (
str) – Name for the experiment.n_jobs (
int) – Number of parallel jobs for execution.cache_dir_path (
Optional[Path]) – Optional path for storing simulation results.clear_cache_on_start (
bool) – Whether to clear existing cache before starting simulation.enable_profiling (
bool) – Whether to enable performance profiling.profiling_output_limit (
int) – Maximum number of profiling entries to display.cache_visualizations (
bool) – Whether to cache visualizations.is_risk_averse (
bool) – Whether to run risk-averse benchmark.
- Returns:
Dict[str, Dict[str, list]]: Raw simulation results organized by environment name, then policy name, containing lists of History objects for each episode.
pd.DataFrame: Statistical summary with confidence intervals, performance metrics, and policy configuration details for analysis and comparison.
- Return type:
- run_all_hyperparameter_benchmarks(policy_space_info, particles=30, num_episodes=2, num_steps=2, n_trials=2, discount_factor=0.95, time_out_in_seconds=0.01, evaluation_episodes=3, evaluation_steps=2, evaluation_n_jobs=1, optimization_n_jobs=1, is_risk_averse=False, confidence_interval_level=0.95, alpha=0.05, cache_dir_path=None, experiment_name='All_Hyperparameter_Benchmarks', debug=False, cache_visualizations=True)[source]
Run all hyperparameter benchmarks with optimization locally.
This method runs hyperparameter optimization for all compatible environments and planners for a given policy space, followed by evaluation using local Joblib parallelization.
- Parameters:
policy_space_info (
PolicySpaceInfo) – Policy space information specifying action and observation space types for compatibility matching.particles (
int) – Number of particles for belief representation.num_episodes (
int) – Number of episodes for optimization.num_steps (
int) – Maximum steps per episode for optimization.n_trials (
int) – Number of optimization trials.discount_factor (
float) – Discount factor for the MDP.time_out_in_seconds (
float) – Timeout for planner execution.evaluation_episodes (
int) – Number of episodes for evaluation.evaluation_steps (
int) – Maximum steps per episode for evaluation.evaluation_n_jobs (
int) – Number of parallel jobs for evaluation.optimization_n_jobs (
int) – Number of parallel jobs for optimization (-1 uses all cores).is_risk_averse (
bool) – Whether to run risk-averse benchmark.confidence_interval_level (
float) – Confidence level for intervals.alpha (
float) – Significance level for statistical tests.cache_dir_path (
Optional[Path]) – Optional path for storing results.experiment_name (
str) – Name for the experiment.debug (
bool) – Enable debug mode.cache_visualizations (
bool) – Whether to cache visualizations.
- Return type:
- Returns:
Tuple of results dictionary and DataFrame.
- run_hyperparameter_optimization(environment_run_params, experiment_name='POMDP_Hyperparameter_Optimization', n_jobs=-1, cache_dir_path=None, clear_cache_on_start=False, debug=False, confidence_interval_level=0.95, alpha=0.05, use_queue_logger=False, parallelization_level=ParallelizationLevel.OPTUNA_TRIALS)[source]
Run hyperparameter optimization for POMDP policies using Optuna.
This method provides a high-level interface for hyperparameter optimization by wrapping the HyperParameterOptimizer class. It supports optimization of multiple environment-policy configurations with comprehensive MLflow tracking and statistical analysis.
The optimization uses Optuna’s advanced algorithms (TPE, CMA-ES, etc.) to efficiently search the hyperparameter space and find optimal configurations for POMDP policies.
- Parameters:
environment_run_params (
List[HyperParameterRunParams]) – List of HyperParameterRunParams configurations, each specifying an environment, policy class, hyperparameter ranges, and optimization settings. Each configuration must include the required n_trials parameter.experiment_name (
str) – Name for the MLflow experiment tracking. Used to organize optimization runs and enable comparison across different experiments.n_jobs (
int) – Number of parallel jobs for episode execution. Use -1 to use all available CPU cores, or specify a positive integer for a specific number of cores.cache_dir_path (
Optional[Path]) – Optional path for storing optimization results, logs, and MLflow artifacts. If None, results are stored in the current working directory.clear_cache_on_start (
bool) – Whether to clear existing cache before starting optimization. Useful for ensuring clean runs when debugging or testing.debug (
bool) – Whether to enable debug-level logging output. When True, provides detailed information about optimization progress and internal operations.confidence_interval_level (
float) – Confidence level for statistical analysis (between 0.0 and 1.0). Used for computing confidence intervals in performance statistics. Defaults to 0.95 for 95% confidence intervals.alpha (
float) – Significance level for statistical tests (between 0.0 and 1.0). Used for hypothesis testing and confidence interval calculations. Defaults to 0.05 for 5% significance level.use_queue_logger (
bool) – Whether to use queue-based logging for distributed execution scenarios. Defaults to False for local execution.parallelization_level (
ParallelizationLevel) – Controls where parallelization is applied. OPTUNA_TRIALS (default) parallelizes across Optuna trials while running episodes sequentially. EPISODES parallelizes across episodes within each trial while running trials sequentially.
- Returns:
- List of optimization results, each containing
the optimized policy with its best hyperparameters, environment reference, and optimization metadata for each input configuration.
- Return type:
List[OptimizedPolicyResult]- Raises:
ValueError – If any configuration contains invalid parameters or missing required fields like n_trials.
TypeError – If policy classes are not Policy subclasses.
RuntimeError – If optimization fails for any configuration.
Example
Running hyperparameter optimization for POMCP on Tiger POMDP:
>>> from pathlib import Path >>> from POMDPPlanners.simulations.simulation_apis.local_simulations_api import LocalSimulationsAPI >>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP >>> from POMDPPlanners.planners.mcts_planners.pomcp import POMCP >>> from POMDPPlanners.core.belief import get_initial_belief >>> from POMDPPlanners.core.simulation import ( ... NumericalHyperParameter, CategoricalHyperParameter ... ) >>> from POMDPPlanners.core.simulation.hyperparameter_tuning import ( ... HyperParameterRunParams, HyperParameterOptimizationDirection, ... HyperParamPlannerConfig ... ) >>> # Initialize the API >>> api = LocalSimulationsAPI(debug=True) >>> # Create environment and initial belief >>> tiger = TigerPOMDP(discount_factor=0.95) >>> initial_belief = get_initial_belief(tiger, n_particles=10) >>> # Define hyperparameter optimization configurations >>> planner_config = HyperParamPlannerConfig( ... policy_cls=POMCP, ... hyper_parameters=[ ... NumericalHyperParameter(0.1, 2.0, "exploration_constant"), ... NumericalHyperParameter(10, 50, "n_simulations") ... ], ... constant_parameters={ ... "discount_factor": 0.95, ... "name": "OptimizedPOMCP", ... "depth": 5 ... } ... ) >>> optimization_configs = [ ... HyperParameterRunParams( ... environment=tiger, ... belief=initial_belief, ... hyper_param_planner_config=planner_config, ... num_episodes=2, # Small for testing ... num_steps=3, # Small for testing ... n_trials=3, # Small number for testing ... parameters_to_optimize=[ ... ("average_return", HyperParameterOptimizationDirection.MAXIMIZE) ... ] ... ) ... ] >>> # Run hyperparameter optimization >>> results = api.run_hyperparameter_optimization( ... environment_run_params=optimization_configs, ... experiment_name="Tiger_POMCP_Optimization", ... n_jobs=1, ... debug=True ... ) >>> # Check optimization results >>> len(results) >= 1 True
Note
This method requires Optuna and MLflow to be installed. The optimization process can be computationally intensive for complex policies and large parameter spaces. All optimization runs are automatically tracked in MLflow with comprehensive parameter logging, metrics recording, and artifact storage.
Key Implementation Details: - Uses HyperParameterOptimizer internally for optimization logic - All optimization runs are automatically tracked in MLflow - Requires explicit belief initialization (not generated automatically) - n_trials parameter is mandatory in each HyperParameterRunParams - Results include optimized policies with their chosen hyperparameters - Supports both numerical and categorical hyperparameters
- run_hyperparameter_tuning_experiment_with_benchmarks(generators, particles=30, num_episodes=10, num_steps=20, n_trials=100, discount_factor=0.95, time_out_in_seconds=3.0, evaluation_episodes=3, evaluation_steps=6, evaluation_n_jobs=1, optimization_n_jobs=-1, is_risk_averse=False, confidence_interval_level=0.95, alpha=0.05, cache_dir_path=None, experiment_name='Comprehensive_Benchmark', debug=False, cache_visualizations=True)[source]
Run comprehensive benchmark with hyperparameter optimization locally.
This method runs hyperparameter optimization followed by policy evaluation using local Joblib parallelization. It optimizes for average return across all configured environments and benchmark planners.
- Parameters:
generators (
Sequence[HyperParamPlannerConfigGenerator]) – Hyperparameter configuration generators list.particles (
int) – Number of particles for belief representation.num_episodes (
int) – Number of episodes for optimization.num_steps (
int) – Maximum steps per episode for optimization.n_trials (
int) – Number of optimization trials.evaluation_episodes (
int) – Number of episodes for evaluation.evaluation_steps (
int) – Maximum steps per episode for evaluation.evaluation_n_jobs (
int) – Number of parallel jobs for evaluation.optimization_n_jobs (
int) – Number of parallel jobs for optimization (-1 uses all cores).is_risk_averse (
bool) – Whether to run risk-averse benchmark.confidence_interval_level (
float) – Confidence level for intervals.alpha (
float) – Significance level for statistical tests.cache_dir_path (
Optional[Path]) – Optional path for storing results.experiment_name (
str) – Name for the experiment.debug (
bool) – Enable debug mode.cache_visualizations (
bool) – Whether to cache visualizations.discount_factor (float)
time_out_in_seconds (float)
- Return type:
- Returns:
Tuple of results dictionary and DataFrame.
- run_multiple_environments_and_policies(environment_run_params, alpha, confidence_interval_level, experiment_name='POMDP_Planning_Comparison', debug=False, scheduler_address=None, n_jobs=-1, cache_dir_path=None, clear_cache_on_start=False, enable_profiling=False, profiling_output_limit=50)[source]
Run POMDP simulations locally using Joblib for parallel execution.
This method executes POMDP simulations on a single machine using Joblib for parallel processing. It’s ideal for development, testing, and small to medium-scale experiments that can be completed on a single workstation.
- Parameters:
environment_run_params (
List[EnvironmentRunParams]) – List of environment configurations for simulation. Each configuration specifies an environment, belief state, policies, number of episodes, and number of steps per episode.alpha (
float) – Statistical significance level for confidence intervals (e.g., 0.05 for 95% CI). Used for computing risk metrics like Conditional Value at Risk (CVaR).confidence_interval_level (
float) – Confidence level for statistical analysis (e.g., 0.95). Determines the width of confidence intervals for performance metrics.experiment_name (
str) – Name for the experiment and MLflow tracking. Used to organize results and enable comparison across different experimental runs.debug (
bool) – Whether to enable debug-level logging output. When True, provides detailed information about simulation progress and internal operations.scheduler_address (
Optional[str]) – This parameter is ignored by LocalSimulationsAPI. It exists for interface compatibility with DaskSimulationsAPI.n_jobs (
int) – Number of parallel jobs for execution. Use -1 to use all available CPU cores, or specify a positive integer for a specific number of cores.cache_dir_path (
Optional[Path]) – Optional path for storing simulation results, logs, and artifacts. If None, results are stored in the current working directory.clear_cache_on_start (
bool) – Whether to clear existing cache before starting simulation. Useful for ensuring clean runs when debugging or testing.enable_profiling (
bool) – Whether to enable performance profiling using cProfile. Generates detailed timing information for optimization analysis.profiling_output_limit (
int) – Maximum number of profiling entries to display when profiling is enabled. Helps focus on the most time-consuming operations.
- Returns:
Dict[str, Dict[str, list]]: Raw simulation results organized by environment name, then policy name, containing lists of History objects for each episode.
pd.DataFrame: Statistical summary with confidence intervals, performance metrics, and policy configuration details for analysis and comparison.
- Return type:
Example
Running a local simulation with multiple environments and policies:
>>> from pathlib import Path >>> from POMDPPlanners.simulations.simulation_apis.local_simulations_api import LocalSimulationsAPI >>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP >>> from POMDPPlanners.planners.mcts_planners.pomcp import POMCP >>> from POMDPPlanners.core.belief import get_initial_belief >>> from POMDPPlanners.core.simulation import EnvironmentRunParams >>> # Initialize the API >>> api = LocalSimulationsAPI(debug=True) >>> # Create environment and policy >>> tiger = TigerPOMDP(discount_factor=0.95) >>> policy = POMCP( ... environment=tiger, ... discount_factor=0.95, ... depth=5, ... exploration_constant=1.0, ... name="POMCP_Local", ... n_simulations=20 ... ) >>> # Configure simulation parameters >>> environment_run_params = [ ... EnvironmentRunParams( ... environment=tiger, ... belief=get_initial_belief(tiger, n_particles=10), ... policies=[policy], ... num_episodes=2, ... num_steps=3 ... ) ... ] >>> # Run local simulation >>> results, statistics_df = api.run_multiple_environments_and_policies( ... environment_run_params=environment_run_params, ... alpha=0.05, ... confidence_interval_level=0.95, ... experiment_name="Local_Tiger_Study", ... n_jobs=1, ... enable_profiling=False ... ) >>> # Check simulation results >>> len(statistics_df) >= 1 True
- run_multiple_environments_and_policies_with_initial_debug_run(environment_run_params, alpha, confidence_interval_level, experiment_name='POMDP_Planning_Comparison', n_jobs=-1, cache_dir_path=None, clear_cache_on_start=False, enable_profiling=False, profiling_output_limit=50)[source]
Run POMDP simulations with an initial debug run for validation.
This method executes POMDP simulations in two phases: first a quick debug run with reduced episodes and steps to validate the configuration, followed by the full simulation run. This approach helps catch configuration errors early and provides confidence that the full simulation will complete successfully.
The debug run uses the same environment and policy configurations but with significantly reduced computational requirements (2 episodes, 2 steps each). Both runs are tracked separately in MLflow for comparison and analysis.
- Parameters:
environment_run_params (
List[EnvironmentRunParams]) – List of environment configurations for simulation. Each configuration specifies an environment, belief state, policies, number of episodes, and number of steps per episode.alpha (
float) – Statistical significance level for confidence intervals (e.g., 0.05 for 95% CI). Used for computing risk metrics like Conditional Value at Risk (CVaR).confidence_interval_level (
float) – Confidence level for statistical analysis (e.g., 0.95). Determines the width of confidence intervals for performance metrics.experiment_name (
str) – Name for the main experiment and MLflow tracking. The debug run will use “{experiment_name}_debug_run” as its experiment name.n_jobs (
int) – Number of parallel jobs for execution. Use -1 to use all available CPU cores, or specify a positive integer for a specific number of cores.cache_dir_path (
Optional[Path]) – Optional path for storing simulation results, logs, and artifacts. If None, results are stored in the current working directory.clear_cache_on_start (
bool) – Whether to clear existing cache before starting simulation. Useful for ensuring clean runs when debugging or testing.enable_profiling (
bool) – Whether to enable performance profiling using cProfile. Generates detailed timing information for optimization analysis.profiling_output_limit (
int) – Maximum number of profiling entries to display when profiling is enabled. Helps focus on the most time-consuming operations.
- Returns:
Dict[str, Dict[str, list]]: Raw simulation results from the main run, organized by environment name, then policy name, containing lists of History objects for each episode.
pd.DataFrame: Statistical summary with confidence intervals, performance metrics, and policy configuration details for analysis and comparison.
- Return type:
Example
Running a simulation with initial debug validation:
>>> from pathlib import Path >>> from POMDPPlanners.simulations.simulation_apis.local_simulations_api import LocalSimulationsAPI >>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP >>> from POMDPPlanners.planners.mcts_planners.pomcp import POMCP >>> from POMDPPlanners.core.belief import get_initial_belief >>> from POMDPPlanners.core.simulation import EnvironmentRunParams >>> # Initialize the API >>> api = LocalSimulationsAPI(debug=True) >>> # Create environment and policy >>> tiger = TigerPOMDP(discount_factor=0.95) >>> policy = POMCP( ... environment=tiger, ... discount_factor=0.95, ... depth=5, ... exploration_constant=1.0, ... name="POMCP_DebugValidated", ... n_simulations=20 ... ) >>> # Configure simulation parameters >>> environment_run_params = [ ... EnvironmentRunParams( ... environment=tiger, ... belief=get_initial_belief(tiger, n_particles=10), ... policies=[policy], ... num_episodes=3, # Small number for testing ... num_steps=2 # Small number for testing ... ) ... ] >>> # Run simulation with debug validation >>> results, statistics_df = api.run_multiple_environments_and_policies_with_initial_debug_run( ... environment_run_params=environment_run_params, ... alpha=0.05, ... confidence_interval_level=0.95, ... experiment_name="Debug_Validated_Tiger_Study", ... n_jobs=1, ... enable_profiling=False ... ) >>> # Check simulation results >>> len(statistics_df) >= 1 True
- run_optimize_and_evaluate(configs, evaluation_episodes=100, evaluation_steps=100, evaluation_n_jobs=1, optimization_n_jobs=-1, confidence_interval_level=0.95, alpha=0.05, cache_dir_path=None, experiment_name='Optimize_And_Evaluate', debug=False, cache_visualizations=True)[source]
Run hyperparameter optimization and evaluation locally.
This method runs hyperparameter optimization for the provided configurations, then evaluates the optimized policies using local Joblib parallelization.
- Parameters:
configs (
List[HyperParameterRunParams]) – List of hyperparameter run configurations.evaluation_episodes (
int) – Number of episodes for evaluation.evaluation_steps (
int) – Maximum steps per episode for evaluation.evaluation_n_jobs (
int) – Number of parallel jobs for evaluation.optimization_n_jobs (
int) – Number of parallel jobs for optimization (-1 uses all cores).confidence_interval_level (
float) – Confidence level for intervals.alpha (
float) – Significance level for statistical tests.cache_dir_path (
Optional[Path]) – Optional path for storing results.experiment_name (
str) – Name for the experiment.debug (
bool) – Enable debug mode.cache_visualizations (
bool) – Whether to cache visualizations.
- Return type:
- Returns:
Tuple of results dictionary and DataFrame.
Example
>>> from pathlib import Path >>> from POMDPPlanners.simulations.simulation_apis.local_simulations_api import LocalSimulationsAPI >>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP >>> from POMDPPlanners.planners.mcts_planners.pomcp import POMCP >>> from POMDPPlanners.core.belief import get_initial_belief >>> from POMDPPlanners.core.simulation import NumericalHyperParameter >>> from POMDPPlanners.core.simulation.hyperparameter_tuning import ( ... HyperParameterRunParams, ... HyperParameterOptimizationDirection, ... HyperParamPlannerConfig ... ) >>> # Initialize the API >>> api = LocalSimulationsAPI(debug=True) >>> # Create environment and initial belief >>> tiger = TigerPOMDP(discount_factor=0.95) >>> initial_belief = get_initial_belief(tiger, n_particles=10) >>> # Define hyperparameter optimization configurations >>> planner_config = HyperParamPlannerConfig( ... policy_cls=POMCP, ... hyper_parameters=[ ... NumericalHyperParameter(0.1, 2.0, "exploration_constant"), ... NumericalHyperParameter(10, 50, "n_simulations") ... ], ... constant_parameters={ ... "discount_factor": 0.95, ... "name": "OptimizedPOMCP", ... "depth": 5 ... } ... ) >>> optimization_configs = [ ... HyperParameterRunParams( ... environment=tiger, ... belief=initial_belief, ... hyper_param_planner_config=planner_config, ... num_episodes=2, ... num_steps=3, ... n_trials=3, ... parameters_to_optimize=[ ... ("average_return", HyperParameterOptimizationDirection.MAXIMIZE) ... ] ... ) ... ] >>> # Run optimization and evaluation >>> results, stats_df = api.run_optimize_and_evaluate( ... configs=optimization_configs, ... evaluation_episodes=5, ... evaluation_steps=10, ... evaluation_n_jobs=1, ... optimization_n_jobs=1, ... debug=True ... ) >>> len(stats_df) >= 1 True
- class POMDPPlanners.simulations.simulation_apis.dask_simulations_api.DaskSimulationsAPI(cache_dir_path=None, debug=False, scheduler_address=None, cache_size=2000000000, notification_config=None)[source]
High-level API for running POMDP simulation experiments using Dask.
This class provides a simplified interface for running POMDP simulations with distributed execution using Dask for distributed computing. It wraps the POMDPSimulator class and provides convenient methods for remote simulation workflows with Dask cluster support.
Key Features: - Remote execution using Dask for distributed computation - Support for existing Dask clusters or automatic local cluster creation - Debug mode with reduced episodes for quick testing - Automatic profiling and performance analysis - MLflow experiment tracking and result management
Example
>>> from pathlib import Path >>> from POMDPPlanners.simulations.simulation_apis.dask_simulations_api import DaskSimulationsAPI >>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP >>> from POMDPPlanners.planners.mcts_planners.pomcp import POMCP >>> from POMDPPlanners.core.belief import get_initial_belief >>> from POMDPPlanners.core.simulation import EnvironmentRunParams >>> # Initialize the API >>> api = DaskSimulationsAPI(debug=False) >>> # Create environment >>> tiger = TigerPOMDP(discount_factor=0.95) >>> tiger.name 'TigerPOMDP' >>> # Create policy >>> policy = POMCP( ... environment=tiger, ... discount_factor=0.95, ... depth=5, ... exploration_constant=1.0, ... name="POMCP_Distributed", ... n_simulations=20 ... ) >>> policy.name 'POMCP_Distributed' >>> # Configure simulation parameters >>> env_params = EnvironmentRunParams( ... environment=tiger, ... belief=get_initial_belief(tiger, n_particles=10), ... policies=[policy], ... num_episodes=2, ... num_steps=3 ... ) >>> env_params.num_episodes 2
- class POMDPPlanners.simulations.simulation_apis.pbs_simulations_api.PBSSimulationsAPI(queue, n_workers=4, cores=1, memory='4GB', processes=1, walltime='01:00:00', job_extra=None, enable_dashboard=True, dashboard_address='0.0.0.0', dashboard_port=8787, dashboard_prefix=None, cache_dir_path=None, debug=False, notification_config=None)[source]
High-level API for running POMDP simulations on PBS clusters.
This class provides a simplified interface for running POMDP simulations on PBS (Portable Batch System) clusters, commonly used in high-performance computing environments. It automatically manages job submission, scaling, and distributed execution across cluster nodes.
Key Features: - PBS cluster execution for large-scale experiments - Automatic job submission and scaling - Dask dashboard support for monitoring - Configurable resource allocation (cores, memory, walltime) - MLflow experiment tracking and result management
Example
>>> from pathlib import Path >>> from POMDPPlanners.simulations.simulation_apis.pbs_simulations_api import PBSSimulationsAPI >>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP >>> from POMDPPlanners.planners.mcts_planners.pomcp import POMCP >>> from POMDPPlanners.core.belief import get_initial_belief >>> from POMDPPlanners.core.simulation import EnvironmentRunParams >>> # Initialize the PBS API with cluster configuration >>> api = PBSSimulationsAPI( ... queue="batch", ... n_workers=4, ... cores=2, ... memory="8GB", ... walltime="02:00:00", ... debug=False ... ) >>> # Create environment >>> tiger = TigerPOMDP(discount_factor=0.95) >>> # Create policy >>> policy = POMCP( ... environment=tiger, ... discount_factor=0.95, ... depth=5, ... exploration_constant=1.0, ... name="POMCP_Cluster", ... n_simulations=20 ... ) >>> # Configure simulation parameters >>> env_params = EnvironmentRunParams( ... environment=tiger, ... belief=get_initial_belief(tiger, n_particles=10), ... policies=[policy], ... num_episodes=100, ... num_steps=50 ... )
- class POMDPPlanners.simulations.simulation_apis.simulations_api_interface.SimulationsAPIInterface(cache_dir_path=None, debug=False, notification_config=None)[source]
Abstract base class defining the interface for POMDP simulation APIs.
This interface ensures that all simulation API implementations (local, Dask, PBS, etc.) provide a consistent set of methods with standardized signatures. Subclasses must implement all abstract methods to provide specific execution strategies while maintaining API compatibility.
The interface defines methods for: - Running simulations with multiple environments and policies - Hyperparameter optimization - Comprehensive benchmarking with hyperparameter tuning - Optimize and evaluate workflows - All hyperparameter benchmarks
Note
This is an abstract base class and cannot be instantiated directly. Use concrete implementations like LocalSimulationsAPI or DaskSimulationsAPI.
- class POMDPPlanners.simulations.simulator.pomdp_simulator.POMDPSimulator(task_manager_config, cache_dir_path=None, experiment_name='POMDP_Planning_Comparison', debug=False, enable_profiling=False, profiling_output_limit=50, task_console_output=False, use_queue_logger=False, console_output=True, no_logs=False, visualizer=None, notification_config=None)[source]
Concrete implementation of BaseSimulator for POMDP planning algorithm comparisons.
This class provides a complete simulation framework for comparing POMDP planning algorithms across multiple environments. It executes episodes in parallel, collects comprehensive statistics, and generates visualizations for analysis.
The simulator supports: - Episode-based simulation with configurable number of steps and episodes - Parallel execution using Dask, Joblib, or PBS cluster task managers - Comprehensive timing and performance metrics collection - Statistical analysis with confidence intervals and risk measures - Pluggable visualization strategy via
ExperimentVisualizer- MLflow experiment tracking with structured loggingKey Metrics Collected: - Average return and discounted return statistics - Conditional Value at Risk (CVaR) and Value at Risk (VaR) - Timing metrics (action selection, belief updates, state transitions) - Episode completion rates and terminal state statistics - Custom environment-specific metrics
Example
Creating and configuring a POMDP simulator for algorithm comparison:
>>> from pathlib import Path >>> from POMDPPlanners.simulations.simulator import POMDPSimulator >>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP >>> from POMDPPlanners.planners.mcts_planners.pomcp import POMCP >>> from POMDPPlanners.planners.sparse_sampling_planners.sparse_sampling import SparseSamplingDiscreteActionsPlanner >>> from POMDPPlanners.core.belief import get_initial_belief >>> from POMDPPlanners.core.simulation import EnvironmentRunParams >>> from POMDPPlanners.simulations.simulations_deployment.task_manager_configs import JoblibConfig
>>> # Create environment >>> tiger_env = TigerPOMDP(discount_factor=0.95) >>> # Create initial belief for testing >>> initial_belief = get_initial_belief(tiger_env, n_particles=10) # Reduced for testing
>>> # Create policies to compare >>> pomcp = POMCP( ... environment=tiger_env, ... discount_factor=0.95, ... depth=5, # Reduced for testing ... exploration_constant=1.0, ... name="POMCP_Test", ... n_simulations=10 # Reduced for testing ... )
>>> sparse_sampling = SparseSamplingDiscreteActionsPlanner( ... environment=tiger_env, ... branching_factor=2, # Reduced for testing ... depth=3, # Reduced for testing ... name="SparseSampling_Test" ... )
>>> # Configure simulation parameters >>> env_params = [ ... EnvironmentRunParams( ... environment=tiger_env, ... belief=initial_belief, ... policies=[pomcp, sparse_sampling], ... num_episodes=2, # Reduced for testing ... num_steps=5 # Reduced for testing ... ) ... ]
>>> # Configure task manager >>> joblib_config = JoblibConfig(n_jobs=1) # Single job for testing >>> joblib_config.n_jobs 1
>>> # Test simulator configuration >>> simulator = POMDPSimulator( ... task_manager_config=joblib_config, ... experiment_name="Tiger_POMDP_Test", ... debug=False, ... enable_profiling=False ... )
- Parameters:
task_manager_config (TaskManagerConfig)
cache_dir_path (Path | None)
experiment_name (str)
debug (bool)
enable_profiling (bool)
profiling_output_limit (int)
task_console_output (bool)
use_queue_logger (bool)
console_output (bool)
no_logs (bool)
visualizer (ExperimentVisualizer | None)
notification_config (NotificationConfig | None)
Run configuration
- class POMDPPlanners.core.simulation.simulation_configs.EnvironmentRunParams(environment, belief, policies, num_episodes, num_steps)[source]
Configuration parameters for environment evaluation runs.
This frozen dataclass contains all parameters needed to configure and execute an environment evaluation run. Input validation is performed at construction time to ensure all parameters are valid before execution begins.
- environment
POMDP environment instance to evaluate policies in
- belief
Initial belief state for the environment
- policies
Sequence of policy instances to evaluate (must be non-empty)
- num_episodes
Number of episodes to run per policy (must be positive)
- num_steps
Maximum number of steps per episode (must be positive)
- Raises:
ValueError – If any numerical parameter is non-positive or if policies list is empty
TypeError – If environment, belief, or any policy has incorrect type
- Parameters:
- class POMDPPlanners.core.simulation.hyperparameter_tuning.HyperParameterRunParams(environment, belief, hyper_param_planner_config, num_episodes, num_steps, n_trials, parameters_to_optimize, early_stopping=None)[source]
Configuration parameters for hyperparameter optimization runs.
This frozen dataclass contains all parameters needed to configure and execute a hyperparameter optimization run. Input validation is performed at construction time to ensure all parameters are valid before optimization begins.
- environment
POMDP environment instance to optimize policies for
- belief
Initial belief state for the environment
- hyper_param_planner_config
Configuration defining policy class, hyperparameters, and constant parameters for optimization
- num_episodes
Number of episodes to run per trial (must be positive)
- num_steps
Maximum number of steps per episode (must be positive)
- n_trials
Number of optimization trials to execute (must be positive)
- parameters_to_optimize
List of (metric_name, direction) tuples specifying which metrics to optimize and in which direction (maximize/minimize)
- early_stopping
Optional patience settings. When set, n_trials becomes an upper bound and the study ends once its Pareto front stops improving.
- Raises:
ValueError – If any numerical parameter is non-positive, if hyperparameters or parameters_to_optimize are empty, or if metric names are invalid
TypeError – If environment, belief, or policy_cls have incorrect types
- Parameters:
environment (Environment)
belief (Belief)
hyper_param_planner_config (HyperParamPlannerConfig)
num_episodes (int)
num_steps (int)
n_trials (int)
parameters_to_optimize (List[Tuple[str, HyperParameterOptimizationDirection]])
early_stopping (EarlyStoppingConfig | None)
- class POMDPPlanners.core.simulation.hyperparameter_tuning.NumericalHyperParameter(low, high, name)[source]
- class POMDPPlanners.core.simulation.hyperparameter_tuning.CategoricalHyperParameter(choices, name)[source]
- class POMDPPlanners.core.simulation.hyperparameter_tuning.EarlyStoppingConfig(patience=100, min_trials=50, min_relative_improvement=0.001)[source]
When to stop a tuning study before its trial budget is spent.
Pure configuration, so it lives here beside the run params rather than with the Optuna callback that reads it – core must not depend on simulations.
- patience
Stop after this many completed trials with no improvement to the Pareto front. Objective values are means over
num_episodesepisodes and are therefore noisy, so a plateau shorter than a hundred trials is often sampling noise rather than convergence.
- min_trials
Never stop before this many trials have completed. Also the point at which the objective normalization bounds are frozen, so it must be large enough to have seen both good and bad regions.
- min_relative_improvement
Front quality must grow by at least this fraction to count as improvement. A guard against floating-point drift, not a “was this gain meaningful” threshold – raising it to do that job stops studies that are still making progress.
- class POMDPPlanners.core.simulation.hyperparameter_tuning.ParallelizationLevel(*values)[source]
Level at which parallelization is applied during hyperparameter tuning.
- OPTUNA_TRIALS
Parallelize across Optuna trials. Multiple trials run concurrently while episodes within each trial run sequentially.
- EPISODES
Parallelize across episodes within each trial. Optuna trials run sequentially while episodes within each trial run concurrently.
Results
- class POMDPPlanners.core.simulation.history.History(history, discount_factor, average_state_sampling_time, average_action_time, average_observation_time, average_belief_update_time, average_reward_time, actual_num_steps, reach_terminal_state, policy_run_data)[source]
Complete history of a POMDP simulation episode.
This class stores the complete history of a simulation episode, including all step data, timing information, and metadata about the episode.
- Parameters:
- history
List of StepData objects representing each step
- discount_factor
Discount factor used for reward calculation
- average_state_sampling_time
Average time spent sampling states
- average_action_time
Average time spent selecting actions
- average_observation_time
Average time spent processing observations
- average_belief_update_time
Average time spent updating beliefs
- average_reward_time
Average time spent calculating rewards
- actual_num_steps
Actual number of steps taken in the episode
- reach_terminal_state
Whether the episode reached a terminal state
- policy_run_data
Additional data from the policy execution
Examples
>>> from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP >>> from POMDPPlanners.core.belief import WeightedParticleBelief >>> from POMDPPlanners.core.policy import PolicyRunData >>> >>> env = TigerPOMDP(discount_factor=0.95) >>> import numpy as np >>> belief = WeightedParticleBelief(env.states, np.array([0.0, -0.1])) >>> step = StepData("tiger_left", "listen", "tiger_left", "tiger_left", -1.0, belief) >>> policy_data = PolicyRunData(info_variables=[]) >>> >>> history = History( ... history=[step], ... discount_factor=0.95, ... average_state_sampling_time=0.001, ... average_action_time=0.01, ... average_observation_time=0.002, ... average_belief_update_time=0.005, ... average_reward_time=0.001, ... actual_num_steps=1, ... reach_terminal_state=False, ... policy_run_data=policy_data ... ) >>> history.discount_factor 0.95 >>> len(history.history) 1 >>> history.reach_terminal_state False
- class POMDPPlanners.core.simulation.history.StepData(state, action, next_state, observation, reward, belief, info=None)[source]
One recorded interaction of an episode.
- Parameters:
- state
The state the step was taken from.
- action
The action taken.
Noneon the terminal bookkeeping step.
- next_state
The realised successor state.
Noneon the terminal step.
- observation
The raw observation emitted by the world.
Noneon the terminal step.
- reward
The realised reward.
Noneon the terminal step.
- belief
The belief held when the action was selected.
- info
Optional auxiliary per-step measurements supplied by the environment’s
step_info()hook, as a flat mapping of channel name to scalar (e.g.{"success": 1.0, "impact": 12.4}).This is the transport that lets an environment report a quantity it can only measure at step time — a contact impulse, a termination reason — to
compute_metrics, which runs later and in a different process. Values must be plain picklable scalars so they survive every task manager.Nonemeans the environment reported nothing.
- POMDPPlanners.core.simulation.history.history_to_discounted_return_value(history)[source]
Calculate the discounted return value from a simulation history.
This function computes the total discounted reward for an episode, where rewards are discounted by the discount factor raised to the power of the step index.