Visualization and Reporting
There are three ways to look at results, and each answers a different question:
An episode replay shows what one planner did in one episode, which is how you catch a planner that scores well for the wrong reason.
The results site shows a whole run in the browser: metric tables, return histograms, and every episode’s replay.
The tuning plots show whether a hyperparameter study converged and what it traded away.
Episode replays
Each environment shows its episodes in exactly one way, returned by
Environment.episode_visualizer():
Environments written in this package return a
TraceVisualizer. It saves each episode astrace_<i>.json, and a three.js scene replays the trace in the browser.Environments that wrap an external simulator (CARLA, Isaac Lab) return a
VideoVisualizer, which saves the simulator’s own camera footage asagent_path_<i>.mp4.
A simulation run writes these files for you. To produce replays without a
full run, use visualize_planner_episode:
import tempfile
from pathlib import Path
from POMDPPlanners.core.belief import get_initial_belief
from POMDPPlanners.core.simulation import EpisodeTrace
from POMDPPlanners.environments.tiger_pomdp import TigerPOMDP
from POMDPPlanners.planners.mcts_planners.pomcp import POMCP
from POMDPPlanners.utils.planner_episode_visualization import visualize_planner_episode
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)
out = Path(tempfile.mkdtemp())
visualize_planner_episode(planner, env, get_initial_belief(env, n_particles=100),
n_episodes=2, cache_dir=out, num_steps=10)
# A trace is a JSON file, so it can be read back and checked.
trace = EpisodeTrace.read(out / "POMCP" / "trace_0.json")
print(trace.payload_kind, trace.num_steps, trace.discounted_return)
A trace has two parts. The envelope (actions, rewards, step_info values)
has the same shape for every environment. The payload holds the states,
observations and beliefs in whatever shape the environment’s scene expects,
and payload_kind (for example "tiger.v1") names that shape.
- POMDPPlanners.utils.planner_episode_visualization.visualize_planner_episode(planner, environment, belief, n_episodes, cache_dir, num_steps=20, n_jobs=1)[source]
Visualize episodes of a planner by running episodes and caching visualizations.
- Parameters:
planner (
Policy) – The planner policy (used for naming cache files)environment (
Environment) – The POMDP environment to run episodes inbelief (
Belief) – The initial belief to use for episodesn_episodes (
int) – Number of episodes to run and visualizecache_dir (
Path) – Directory to cache visualization filesnum_steps (
int) – Maximum number of steps per episode (default: 20)n_jobs (
int) – Number of parallel jobs for episode execution (default: 1, sequential)
- class POMDPPlanners.core.simulation.episode_visualizers.EpisodeVisualizer(environment)[source]
Writes the one file that shows an episode.
- Parameters:
environment (Environment)
- kind
What the written file is. The results site chooses its player from this and nothing else.
- environment
The environment the episodes were run on.
- abstractmethod write(history, output_dir, episode_index, policy_name=None)[source]
Write one episode’s visualization file into
output_dir.The visualizer owns the file name, so callers pass only the directory and the episode index. The index must end the file name, because the results site reads it from there.
- Parameters:
- Return type:
- Returns:
The path written, or
Nonewhen there was nothing to write.
- class POMDPPlanners.core.simulation.episode_visualizers.TraceVisualizer(environment)[source]
Writes an episode as a trace that a three.js scene replays.
Subclasses set
payload_kindand implementbuild_payload(). The envelope — actions, rewards, outcome — is the same for every environment and is filled in here.- Parameters:
environment (Environment)
- payload_kind
The versioned name of the payload’s shape, such as
"battleship.v1". It also names the scene script.
- build_trace(history, episode_index, policy_name=None)[source]
Build the full trace of one episode.
- Parameters:
- Return type:
- Returns:
The episode’s
EpisodeTrace.- Raises:
ValueError – If
historyis empty; there is no episode to write.
- class POMDPPlanners.core.simulation.episode_visualizers.VideoVisualizer(environment)[source]
Writes an external simulator’s camera footage of an episode.
- Parameters:
environment (Environment)
- class POMDPPlanners.core.simulation.traces.EpisodeTrace(environment, payload_kind, episode_index, discount_factor, steps=<factory>, payload=<factory>, policy=None, reach_terminal_state=False, metadata=<factory>, schema_version='1.0')[source]
One episode, written so a program can replay it.
- Parameters:
- environment
The environment’s
name, as the run directory and MLflow record use it.
- payload_kind
An identifier for the shape of
payload, versioned independently of the envelope (e.g."light_dark.v1"). A reader that does not recognise it must not try to draw the payload.
- episode_index
Zero-based index of the episode within its run.
- discount_factor
The discount the episode was run with, so a reader can recompute the discounted return without guessing.
- steps
The envelope’s per-step records, in order.
- payload
Environment-specific episode data. Must be JSON-compatible.
- policy
Name of the policy that produced the episode, when known.
- reach_terminal_state
Whether the episode ended in a terminal state.
- metadata
Free-form envelope-level extras (seed, wall-clock, run id).
- schema_version
Version of the envelope itself.
- classmethod read(path)[source]
Read a trace written by
write().- Parameters:
- Return type:
- Returns:
The reconstructed
EpisodeTrace.
- class POMDPPlanners.core.simulation.traces.TraceStep(index, action=None, reward=None, info=<factory>)[source]
One step of an episode, in the environment-agnostic envelope.
Only what every environment has: which step it was, what was done, what it paid, and whatever scalars the environment reported through
step_info. The state, the observation and the belief live in the payload, because their shape is the environment’s business.- index
Zero-based step index within the episode.
- action
The action taken, as JSON data.
Noneon the terminal bookkeeping step, which carries a state but no decision.
- reward
The realised reward, or
Noneon the terminal step.
- info
The environment’s per-step channels for this step, as a flat mapping of name to scalar. Empty when the environment reported nothing.
- class POMDPPlanners.core.simulation.traces.ArtifactKind(*values)[source]
What an episode artifact is, independent of how it was produced.
The reporting site picks a player from this and nothing else, so an environment that can only emit an MP4 (CARLA, Isaac Lab) is a first-class episode without the site knowing anything about it.
- PLOT = 'plot'
- TRACE = 'trace'
- VIDEO = 'video'
The results site
pomdp-report serve starts a local website over one or more run
directories. It reads the MLflow store that every run writes under
cache_dir_path/mlruns; nothing needs exporting first. It is a server, not
a folder of HTML files, because a browser will not let a page opened from
disk load the trace files next to it.
pomdp-report serve results/my-study
# Serving on http://127.0.0.1:8765/
Tuning diagnostics
A tuning study writes trial_records.json and a set of PNG plots for each
tuned planner, by default under <cache_dir>/tuning_diagnostics/<config_id>/
and also as MLflow artifacts under tuning/. The plots are built from
TrialRecord objects
rather than from the Optuna study, because the study holds episode histories
that no Optuna storage can save. So you can redraw every plot later from the
JSON file without rerunning anything:
import tempfile
from pathlib import Path
from POMDPPlanners.utils.visualization import (
TrialRecord,
load_trial_records,
plot_tuning_diagnostics,
save_trial_records,
)
# Normally a study writes this file; here three trials are made up by hand.
records = [
TrialRecord(number=i, state="COMPLETE",
params={"exploration_constant": c},
objective_values={"average_return": r},
metric_statistics={"average_return": (r, r - 2.0, r + 2.0)},
duration_seconds=10.0)
for i, (c, r) in enumerate([(1.0, -20.0), (10.0, -5.0), (50.0, 3.0)])
]
study_dir = Path(tempfile.mkdtemp())
save_trial_records(records, study_dir / "trial_records.json")
# Later, with no study in memory, redraw the plots from the file.
records = load_trial_records(study_dir / "trial_records.json")
written = plot_tuning_diagnostics(
records,
parameters_to_optimize=[("average_return", "maximize")],
output_dir=study_dir / "plots",
)
print([p.name for p in written]) # only the plots that had data behind them
The front-quality curve answers “did the search converge, or did it run out of budget”. The secondary-metrics plot shows what the study gave up on metrics it did not optimize, such as collision rate. See Hyperparameter Tuning for a full study.
- class POMDPPlanners.utils.visualization.tuning_plots.TrialRecord(number, state, params=<factory>, objective_values=<factory>, metric_statistics=<factory>, duration_seconds=None, is_pareto=False, confidence_interval_level=None)[source]
One trial, reduced to what the diagnostic plots need.
- Parameters:
- number
Optuna trial number.
- state
Optuna trial state name, e.g.
"COMPLETE".
- params
The hyperparameter values the sampler suggested.
- objective_values
Optimized metric name to its value for this trial.
- metric_statistics
Every recorded metric, optimized or not, mapped to
(value, lower_confidence_bound, upper_confidence_bound). The bounds are what tell you whether one trial really beat another or just got a luckier draw of episodes.
- duration_seconds
Wall-clock time of the trial, or None if unknown.
- is_pareto
Whether the trial is on the study’s final Pareto front.
- confidence_interval_level
The level the bounds in
metric_statisticswere computed at, carried alongside them so a plot can label its intervals without the caller having to remember the setting.
- POMDPPlanners.utils.visualization.tuning_plots.extract_trial_records(study, parameters_to_optimize, confidence_interval_level=None)[source]
Reduce an Optuna study to plain records.
- Parameters:
- Return type:
- Returns:
One record per trial, in trial order.
- POMDPPlanners.utils.visualization.tuning_plots.save_trial_records(records, path)[source]
Write records as JSON so the plots can be rebuilt without re-running the study.
- Return type:
- Parameters:
records (Sequence[TrialRecord])
path (Path)
- POMDPPlanners.utils.visualization.tuning_plots.load_trial_records(path)[source]
Read records written by
save_trial_records().- Return type:
- Parameters:
path (Path)
- POMDPPlanners.utils.visualization.tuning_plots.plot_tuning_diagnostics(records, parameters_to_optimize, output_dir, front_quality_history=None, stopped_at_trial=None, study=None)[source]
Write the full diagnostic set for a tuning study.
- Parameters:
records (
Sequence[TrialRecord]) – Trial records, fromextract_trial_records()orload_trial_records().parameters_to_optimize – The optimized
(metric_name, direction)pairs.output_dir (
Path) – Directory to write the PNGs into.front_quality_history (
Optional[Sequence[Tuple[int,float]]]) – Convergence curve from the early-stopping callback. Omitted when early stopping was disabled.stopped_at_trial (
Optional[int]) – Where early stopping fired, if it did.study – The live Optuna study, needed only for parameter importance.
- Return type:
- Returns:
Paths actually written, skipping plots with no data behind them.
- POMDPPlanners.utils.visualization.tuning_plots.plot_parameter_history(records, output_path)[source]
Plot each searched hyperparameter against trial number.
This is convergence of the parameters rather than the objective: as the sampler homes in, the cloud should collapse toward a region. A cloud that stays uniform to the last trial means the parameter never mattered, or the budget was too small to tell.
- Return type:
- Parameters:
records (Sequence[TrialRecord])
output_path (Path)
- POMDPPlanners.utils.visualization.tuning_plots.plot_parameter_slices(records, parameters_to_optimize, output_path)[source]
Plot each searched hyperparameter against each optimized metric.
The companion to
plot_parameter_history(): that one shows where the search settled, this one shows whether it settled somewhere good. Points are shaded by trial number, so a good region that only late trials reach reads as the search working rather than as luck.- Return type:
- Parameters:
records (Sequence[TrialRecord])
output_path (Path)
- POMDPPlanners.utils.visualization.tuning_plots.plot_parameter_importances(study, parameters_to_optimize, output_path)[source]
Plot fANOVA parameter importance, one bar group per optimized metric.
Needs the live study because Optuna computes importance from its internal search space. A near-zero importance usually means the search range was too narrow to matter, not that the parameter is unimportant in general.
Result plots
These draw static matplotlib figures from a run’s statistics or histories, for a paper or a report.
- POMDPPlanners.utils.visualization.metrics_plots.plot_metrics_comparison(statistics, environments, policies, cache_dir_path)[source]
Plot bar plots comparing statistics across environments and policies.
- Parameters:
statistics (
List[List[MetricValue]]) – List of lists of MetricValue objects for each environment-policy combinationenvironments (
List[Environment]) – List of environmentscache_dir_path (
Path) – Path to save the plots
- Return type:
- POMDPPlanners.utils.visualization.metrics_plots.plot_policies_comparison_on_environment(metrics_dict, cache_dir_path)[source]
Plot bar plots comparing policies across environments for each metric type, using academic publication style.
- POMDPPlanners.utils.visualization.returns_plots.plot_discounted_returns_histogram(histories, policy, environment, cache_path)[source]
Create a histogram plot of discounted returns from a list of histories using seaborn.
- Parameters:
histories (
List[History]) – List of History objects containing episode datapolicy (
Policy) – Policy object used to generate the historiesenvironment (
Environment) – Environment object where the histories were generatedcache_path (
Path) – Path where the histogram plot will be saved
- Return type:
- POMDPPlanners.utils.visualization.returns_plots.plot_discounted_returns_histogram_multiple_policies(histories, policies, environment, cache_path)[source]
Create overlapping histogram plots of discounted returns for multiple policies using seaborn.
- POMDPPlanners.utils.visualization.returns_plots.plot_environment_policy_pair_comparison(histories, policy, environment, cache_path)[source]
Create a histogram plot for a single environment-policy pair.
- Parameters:
histories (
List[History]) – List of History objects containing episode datapolicy (
Policy) – Policy object used to generate the historiesenvironment (
Environment) – Environment object where the histories were generatedcache_path (
Path) – Path where the histogram plot will be saved
- Return type:
- POMDPPlanners.utils.visualization.tree_plots.plot_tree_graphs(root_node)[source]
Create two interactive visualizations of the belief tree: 1. Node visit counts 2. Node values (v_value for belief nodes, q_value for action nodes)
- Parameters:
root_node (
BeliefNode) – Root node of the belief tree
- class POMDPPlanners.core.simulation.visualizers.ExperimentVisualizer[source]
Strategy for rendering aggregated per-environment experiment artifacts.
An
ExperimentVisualizeris invoked once per environment after the simulation phase completes. It receives the per-policy episode results and is responsible for writing visualization artifacts (plots, animations, summary files) into a caller-provided output directory.Implementations are dispatched to worker processes via the simulator’s task manager, so they MUST be picklable and MUST NOT capture live execution state (live clients, open sockets, asyncio tasks, file handles, threading primitives).
Note
This is an abstract base class and cannot be instantiated directly.
- abstractmethod render(env_name, environment, policy_results, policies, output_dir, cache_visualizations)[source]
Render aggregated artifacts for one environment.
- Parameters:
env_name (
str) – Name of the environment being visualized.environment (
Environment) – Environment instance whose results are being rendered.policy_results (
Dict[str,List[History]]) – Mapping from policy name to a list of histories produced by that policy on this environment.policies (
Sequence[Policy]) – Sequence of policy instances corresponding topolicy_resultskeys.output_dir (
Path) – Directory under which artifacts are written. The caller guarantees the directory exists.cache_visualizations (
bool) – When True, implementations should also produce per-episode environment-specific caches (e.g. agent trajectory animations) underoutput_dir.
- Return type:
- Returns:
Path to the directory containing the rendered artifacts (typically
output_diritself).