Statistics

These helpers turn a list of episode returns into numbers you can compare: a mean with a confidence interval, a tail risk (CVaR), and a quantile with its own interval. The simulator already uses them to build its statistics table, so call them yourself only when you analyse episodes outside a run, or need a statistic the table does not have.

Example

import numpy as np
from POMDPPlanners.utils.statistics_utils import (
    confidence_interval,
    cvar_estimator,
    quantile_confidence_interval,
)

returns = np.array([12.5, 8.3, 15.7, -2.1, 9.8, 13.2, 6.4, 11.0, -1.5, 14.3])

low, high = confidence_interval(returns, confidence=0.95)
print(f"mean {returns.mean():.2f}, 95% CI [{low:.2f}, {high:.2f}]")
# mean 8.76, 95% CI [4.31, 13.21]

# cvar_estimator averages the *largest* alpha fraction of its input.
# Negate twice to get the mean of the worst 20% of returns.
print(f"CVaR of returns at 20%: {-cvar_estimator(-returns, alpha=0.2):.2f}")
# CVaR of returns at 20%: -1.80

low, high, _, _ = quantile_confidence_interval(returns, alpha=0.1, conf_level=0.95)
print(f"10% quantile in [{low:.2f}, {high:.2f}]")

Notes

  • cvar_estimator(x, alpha) treats large values as bad, as for costs. For returns, where small is bad, pass -returns and negate the result. The simulator does this for return_cvar.

  • confidence_interval uses a Student t-interval. The t-distribution widens the interval to account for estimating the standard deviation from the sample, which matters at the 10 to 100 episodes of a planner comparison.

  • cvar_confidence_interval is a finite-sample bound. It needs bounds on the data; pass the true ones when you know them. Without them it uses the sample minimum and maximum, which can make the interval narrower than it should be.

Comparing planners

To compare several planners, pass the histories from a simulation run to compute_statistics_environments_policies_comparison. It returns the same DataFrame that run_multiple_environments_and_policies returns, one row per environment and planner pair with _ci_lower and _ci_upper columns. If two planners’ intervals do not overlap, the difference holds at that confidence level. If they overlap, the table alone cannot settle it; run more episodes.

POMDPPlanners.simulations.simulation_statistics.compute_statistics_environment_policy_pair(env, histories, alpha, confidence_interval_level=0.95)[source]

Compute comprehensive statistics and metrics for a single environment-policy pair.

This function analyzes simulation histories to compute a wide range of performance metrics including returns, risk measures, timing statistics, and custom environment metrics. All metrics include confidence intervals for statistical significance testing.

Computed Metrics: - Average return: Mean discounted return across episodes - CVaR (Conditional Value at Risk): Expected return in worst α fraction of cases - VaR (Value at Risk): α-quantile of return distribution - Timing metrics: Average times for each simulation component - Episode statistics: Step counts and terminal state rates - Custom environment metrics: Domain-specific performance measures

Parameters:
  • env (Environment) – The POMDP environment used in the simulation

  • histories (List[History]) – List of episode histories from simulation runs

  • alpha (float) – Risk level for CVaR and VaR computation (0 < α < 1)

  • confidence_interval_level (float) – Confidence level for statistical intervals (0 < level < 1)

Returns:

  • name: Metric identifier

  • value: Point estimate of the metric

  • lower_confidence_bound: Lower bound of confidence interval

  • upper_confidence_bound: Upper bound of confidence interval

Return type:

List[MetricValue]

Raises:
  • TypeError – If histories is not a list or contains non-History objects

  • ValueError – If histories is empty

Example

Computing statistics for POMCP on Tiger POMDP:

>>> from POMDPPlanners.simulations.simulation_statistics import compute_statistics_environment_policy_pair
>>> 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.simulations.episodes import run_episode
>>> from POMDPPlanners.utils.logger import get_logger
>>> # Set up environment and policy (reduced parameters for testing)
>>> env = TigerPOMDP(discount_factor=0.95)
>>> env.name
'TigerPOMDP'
>>> policy = POMCP(
...     environment=env,
...     discount_factor=0.95,
...     depth=5,                   # Reduced for testing
...     exploration_constant=1.0,
...     name="POMCP_Stats_Test",
...     n_simulations=10           # Reduced for testing
... )
>>> policy.name
'POMCP_Stats_Test'
>>> # Run a few episodes for testing
>>> histories = []
>>> initial_belief = get_initial_belief(env, n_particles=10)  # Reduced for testing
>>> logger = get_logger("stats_example", debug=False)
>>> # Run 2 episodes for testing
>>> for episode in range(2):
...     history = run_episode(
...         environment=env,
...         policy=policy,
...         initial_belief=initial_belief,
...         num_steps=3,           # Reduced for testing
...         logger=logger
...     )
...     histories.append(history)
>>> len(histories)
2
>>> # Compute comprehensive statistics
>>> metrics = compute_statistics_environment_policy_pair(
...     env=env,
...     histories=histories,
...     alpha=0.05,  # 5% risk level
...     confidence_interval_level=0.95  # 95% confidence intervals
... )
>>> len(metrics) > 5  # Should have multiple metrics
True
>>> # Test that we can find specific metrics
>>> metric_names = [m.name for m in metrics]
>>> 'average_return' in metric_names
True
>>> 'return_cvar' in metric_names
True
>>> 'average_action_time' in metric_names
True
POMDPPlanners.simulations.simulation_statistics.compute_statistics_environments_policies_comparison(histories, environments, alpha, confidence_interval_level=0.95)[source]

Compute statistics for multiple environments and policies, returning results in a DataFrame.

Parameters:
  • histories (Dict[str, Dict[str, List[History]]]) – Dictionary mapping environment names to dictionaries mapping policy names to lists of histories

  • alpha (float) – Alpha value for statistics computation

  • confidence_interval_level (float) – Confidence level for statistics

  • environments (List[Environment])

Return type:

DataFrame

Returns:

DataFrame where each row represents an environment-policy pair and columns are metrics

POMDPPlanners.simulations.simulation_statistics.metrics_dict_to_dataframe(metrics_dict)[source]

Convert a nested dictionary of metrics into a structured DataFrame for analysis.

This function transforms the hierarchical metrics structure returned by simulation runs into a flat DataFrame format suitable for statistical analysis, visualization, and reporting. Each row represents one environment-policy combination.

The resulting DataFrame includes: - Environment and policy identification columns - Point estimates for all computed metrics - Confidence interval bounds for each metric (lower and upper) - Automatically handles missing metrics with appropriate defaults

Parameters:

metrics_dict (Dict[str, Dict[str, List[MetricValue]]]) – Nested dictionary with structure: {environment_name: {policy_name: [MetricValue, …], …}, …} where MetricValue objects contain name, value, and confidence bounds

Returns:

  • ‘environment’: Environment name identifier

  • ’policy’: Policy name identifier

  • For each metric ‘X’: ‘X’, ‘X_ci_lower’, ‘X_ci_upper’ columns

Return type:

DataFrame

Raises:

Example

Converting simulation results to DataFrame for analysis:

>>> from POMDPPlanners.simulations.simulation_statistics import (
...     compute_statistics_environment_policy_pair, metrics_dict_to_dataframe
... )
>>> from POMDPPlanners.core.simulation import MetricValue
>>> # Create sample metrics for testing
>>> pomcp_metrics = [
...     MetricValue("average_return", 10.5, 9.0, 12.0),
...     MetricValue("return_cvar", 8.2, 7.0, 9.4),
...     MetricValue("average_action_time", 0.05, 0.04, 0.06)
... ]
>>> sparse_metrics = [
...     MetricValue("average_return", 9.8, 8.5, 11.1),
...     MetricValue("return_cvar", 7.9, 6.8, 9.0),
...     MetricValue("average_action_time", 0.02, 0.01, 0.03)
... ]
>>> # Create test metrics dictionary
>>> metrics_dict = {
...     'TigerPOMDP': {
...         'POMCP': pomcp_metrics,
...         'SparseSampling': sparse_metrics
...     }
... }
>>> len(metrics_dict)
1
>>> len(metrics_dict['TigerPOMDP'])
2
>>> # Convert to DataFrame
>>> results_df = metrics_dict_to_dataframe(metrics_dict)

Estimators and intervals

POMDPPlanners.utils.statistics_utils.confidence_interval(data, confidence=0.95)[source]

Calculate confidence interval for the mean using t-distribution.

Computes confidence intervals for algorithm performance means, providing statistical bounds on the true expected performance. This is essential for making statistically sound comparisons between POMDP algorithms.

Uses the t-distribution to account for sample size uncertainty, which is more appropriate than normal distribution for small to moderate sample sizes common in POMDP experiments.

Parameters:
  • data (array-like) – Sample data (algorithm returns, rewards, or performance metrics)

  • confidence (float) – Confidence level (0 < confidence < 1, typically 0.95)

Returns:

Tuple of (lower_bound, upper_bound) for the confidence interval

Raises:

ValueError – If insufficient data or contains NaN values

Return type:

Tuple[float, float]

Example

Statistical comparison of algorithm performance:

>>> import numpy as np
>>> # Algorithm performance from multiple runs
>>> pomcp_rewards = [12.3, 11.8, 13.1, 12.7, 11.9, 12.5, 13.0, 12.1, 12.8, 12.4]
>>> pft_rewards = [11.5, 13.2, 12.8, 11.9, 12.3, 13.5, 12.1, 12.9, 11.7, 12.6]
>>>
>>> # Calculate 95% confidence intervals
>>> pomcp_ci = confidence_interval(pomcp_rewards, confidence=0.95)
>>> pft_ci = confidence_interval(pft_rewards, confidence=0.95)
>>>
>>> # Verify confidence intervals are tuples with two elements
>>> isinstance(pomcp_ci, tuple) and len(pomcp_ci) == 2
True
>>> isinstance(pft_ci, tuple) and len(pft_ci) == 2
True
>>>
>>> # Verify confidence intervals contain the mean
>>> pomcp_mean = np.mean(pomcp_rewards)
>>> pft_mean = np.mean(pft_rewards)
>>> bool(pomcp_ci[0] <= pomcp_mean <= pomcp_ci[1])
True
>>> bool(pft_ci[0] <= pft_mean <= pft_ci[1])
True
>>>
>>> # Verify lower bound is less than upper bound
>>> pomcp_ci[0] < pomcp_ci[1]
True
>>> pft_ci[0] < pft_ci[1]
True

Calculate the confidence interval for the mean of a dataset using the t-distribution.

Parameters:
  • data (array-like) – Sample data

  • confidence (float) – Confidence level (default 0.95 for 95%)

Returns:

(lower_bound, upper_bound) of the confidence interval

Return type:

Tuple[float, float]

Raises:

ValueError – If data contains NaN values or has insufficient samples

POMDPPlanners.utils.statistics_utils.cvar_estimator(vec, alpha)[source]

Calculate Conditional Value at Risk (CVaR) for risk-sensitive POMDP evaluation.

CVaR measures the expected value of the worst-case outcomes, providing a risk-sensitive performance metric that goes beyond simple mean rewards. This is particularly valuable for safety-critical applications where tail risk matters more than average performance.

Mathematical Definition:

CVaR_α(X) = E[X | X ≥ VaR_α(X)]

Where VaR_α is the Value at Risk at confidence level α.

The implementation uses a vectorized approach for computational efficiency, calculating CVaR by integrating over the tail distribution above the α-quantile.

Parameters:
  • vec (ndarray) – Array of values (typically returns, costs, or performance metrics)

  • alpha (float) – Confidence level (0 < α ≤ 1), where higher values focus on worse outcomes

Return type:

float

Returns:

CVaR value representing expected worst-case performance

Raises:

ValueError – If alpha not in [0,1] or vec is empty

Example

Risk analysis of POMDP algorithm performance:

>>> import numpy as np
>>> from POMDPPlanners.utils.statistics_utils import cvar_estimator
>>> # Simulate algorithm returns from multiple episodes
>>> returns = np.array([12.5, 8.3, 15.7, -2.1, 9.8, 13.2, 6.4, 11.0, -1.5, 14.3])
>>> len(returns)
10
>>> # Calculate risk metrics
>>> mean_return = np.mean(returns)
>>> bool(mean_return > 8.0)  # Check reasonable mean
True
>>> cvar_90 = cvar_estimator(returns, alpha=0.9)  # Worst 10% outcomes
>>> cvar_95 = cvar_estimator(returns, alpha=0.95) # Worst 5% outcomes
>>> isinstance(cvar_90, (float, np.floating))
True
>>> isinstance(cvar_95, (float, np.floating))
True
>>> cvar_95 <= cvar_90  # CVaR should be lower for higher alpha
True

Example

Comparing algorithm risk profiles:

>>> # Algorithm performance data from experiments
>>> pomcp_returns = np.array([10.2, 12.8, 9.5, 11.3, 8.7, 12.1, 10.9, 9.8, 11.5, 10.4])
>>> pft_returns = np.array([15.1, 7.2, 14.8, 13.3, 6.9, 15.5, 8.1, 14.2, 12.7, 9.3])
>>> pomcp_cvar = cvar_estimator(pomcp_returns, alpha=0.9)
>>> pft_cvar = cvar_estimator(pft_returns, alpha=0.9)
Risk Assessment Applications:

Portfolio Analysis: Compare multiple algorithms’ risk-return profiles

Safety-Critical Systems: Evaluate worst-case performance guarantees

Robust Planning: Select algorithms with acceptable tail risk

Performance Bounds: Establish confidence intervals for worst-case scenarios

Mathematical Properties:
  • Monotonic: CVaR_α ≥ VaR_α (CVaR is always at least as large as VaR)

  • Coherent: Satisfies subadditivity, monotonicity, positive homogeneity

  • Tail Sensitivity: Lower α values emphasize extreme outcomes more

  • Computational: More stable than VaR, especially for small samples

POMDPPlanners.utils.statistics_utils.cvar_confidence_interval(data, alpha=0.95, delta=0.05, dist_lower_bound=None, dist_upper_bound=None)[source]

Calculate finite-sample CVaR concentration bounds using the Thomas method.

Parameters:
  • data – Array of values

  • alpha – Confidence level (default 0.95 for 95%)

  • delta – Significance level for the probabilistic bounds (default 0.05)

  • dist_lower_bound (Optional[float]) – Known lower bound of the distribution support. If None, uses min(data) as a conservative data-driven fallback.

  • dist_upper_bound (Optional[float]) – Known upper bound of the distribution support. If None, uses max(data) as a conservative data-driven fallback.

Returns:

(lower_bound, upper_bound) of the confidence interval

Return type:

tuple

Raises:

ValueError – If parameters, data, support, or computed bounds are invalid

POMDPPlanners.utils.statistics_utils.quantile_confidence_interval(data, alpha=0.95, conf_level=0.95)[source]

data: 1D array-like of samples alpha: target quantile (e.g. 0.95 for 95% VaR) conf_level: overall coverage (e.g. 0.95 for 95% CI) Returns: (lower_value, upper_value, k1, k2)

POMDPPlanners.utils.statistics_utils.cvar_estimator_from_dist(values, weights, alpha)[source]

Calculate the Conditional Value at Risk (CVaR) from a discrete distribution.

Parameters:
  • values (ndarray) – Array of values

  • weights (ndarray) – Array of corresponding weights/probabilities

  • alpha (float) – Confidence level (between 0 and 1)

Returns:

The CVaR value

Return type:

float

Raises:

ValueError – If alpha is not between 0 and 1, if arrays are empty, or if weights don’t sum to 1

Distances between distributions

POMDPPlanners.utils.statistics_utils.tv_distance(p, q, n_samples=1000, method='grid', **kwargs)[source]

Compute Total Variation distance between two distributions.

Total Variation distance measures how different two probability distributions are, with values ranging from 0 (identical) to 1 (completely different).

Parameters:
  • p (Distribution) – First distribution

  • q (Distribution) – Second distribution

  • n_samples (int) – Number of samples (method-dependent usage)

  • method (str) – Estimation method - “grid”, “monte_carlo”, “averaged”, “mixture”

  • **kwargs – Additional method-specific parameters: For “grid”: x_min, x_max, n_points For “averaged”: n_runs For “mixture”: (uses n_samples directly) For “monte_carlo”: (uses n_samples directly)

Return type:

float

Returns:

TV distance estimate

Example

>>> import numpy as np
>>> from POMDPPlanners.core.distributions import DiscreteDistribution
>>> np.random.seed(42)
>>> # Create two similar discrete distributions
>>> values = [0, 1, 2, 3, 4]
>>> p_probs = np.array([0.2, 0.3, 0.25, 0.15, 0.1])
>>> q_probs = np.array([0.25, 0.25, 0.25, 0.15, 0.1])
>>> p = DiscreteDistribution(values, p_probs)
>>> q = DiscreteDistribution(values, q_probs)
>>> tv = tv_distance(p, q, method="monte_carlo", n_samples=10000)
>>> isinstance(tv, float)
True
>>> 0.0 <= tv <= 1.0
True