API Reference
This section provides detailed API documentation for all classes and functions in ssl_vista.
ssl_vista
SSL Simulator Vista - A PyVista/Matplotlib-based Visualization Tool for the SSL Simulator
GridSpec
dataclass
Specification for a full simulation grid layout.
Parameters
shape:
(rows, cols) dimensions of the plotter grid.
plotters:
Ordered list of :class:PlotterSpec entries describing each cell.
PlotterSpec
dataclass
Specification for a single plotter within a :class:GridSpec.
Exactly one of plotter_cls or plotter_type must be supplied.
Parameters
position:
(row, col) cell in the simulation grid.
plotter_cls:
A concrete plotter class (must be a subclass of _BasePlotter).
Use this to pass a class object directly without going through the
string registry.
plotter_type:
Name of a plotter registered in the global registry
(e.g. "Plotter3DCanvas").
kwargs:
Extra keyword arguments forwarded to the plotter constructor.
__getattr__(name)
Lazily resolve Qt-dependent names to avoid circular imports at package load time.
app
run_app(**kwargs)
Launch the ssl_vista simulation viewer.
This function supports three mutually exclusive call signatures:
File-based path (original behaviour - fully preserved)::
run_app(layout="path/to/layout.json", data_path="path/to/run.csv")
GridSpec programmatic path (build the grid from a spec object)::
run_app(grid_spec=my_spec, sim_data=sim_data, sim_settings=sim_settings)
Pre-built grid programmatic path (pass an already-constructed grid)::
run_app(grid=my_grid, sim_data=sim_data, sim_settings=sim_settings)
Parameters
layout:
(File path) Path to the JSON grid layout file.
data_path:
(File path) Path to the simulation CSV file.
grid_spec:
(GridSpec path) A :class:~ssl_vista.types.GridSpec describing the
grid to build programmatically.
grid:
(Pre-built path) An already-constructed
:class:~ssl_vista.ui.grid.SimulationGrid instance.
sim_data:
(Programmatic paths) Pre-parsed simulation data dict (same structure as
returned by load_sim).
sim_settings:
(Programmatic paths) Scalar simulation parameters dict.
auto_play:
Whether to start playback automatically once the window opens.
backend
Session
detach()
Stop chasing the stream head (the user grabbed the slider).
poll()
Change detection + cursor decision. None means: nothing to do this tick.
The exact logic the live QTimer callback used to hold: revision-based change detection (survives ring wrap, where the frame count saturates but content advances), deferred scene init until the first frame exists, and head-rendering only while following.
reattach()
Follow the head again (the user pressed Play on a live source).
set_source(source)
Bind a new data source; the cursor and scene state start over.
SessionUpdate
dataclass
What changed since the previous poll -- everything a frontend needs to apply.
session
The viewer/GCS backend, Qt-free: one object owning source, cursor, and commander.
Session is what every frontend (the Qt MainWindow, a future QML GCS, a notebook, a headless
recorder) programs against:
- telemetry in: a bound :class:
~ssl_link.sources.DataSource(log, running sim, UDP, Ivy); - cursor: the follow-live / scrub state machine, with the change-detection logic that used to live inside the Qt window's timer callback;
- command out: an optional :class:
~ssl_link.command.Commander, so GCS panels callsession.commander.setting(...)and never touch a transport.
Frontends drive it with a periodic :meth:poll (Qt: a QTimer; scripts: a loop) and apply the
returned :class:SessionUpdate to their widgets. Polling keeps sources and this backend free of
any UI framework and makes threading trivial -- producers push from anywhere, only the frontend
thread renders.
Session
detach()
Stop chasing the stream head (the user grabbed the slider).
poll()
Change detection + cursor decision. None means: nothing to do this tick.
The exact logic the live QTimer callback used to hold: revision-based change detection (survives ring wrap, where the frame count saturates but content advances), deferred scene init until the first frame exists, and head-rendering only while following.
reattach()
Follow the head again (the user pressed Play on a live source).
set_source(source)
Bind a new data source; the cursor and scene state start over.
SessionUpdate
dataclass
What changed since the previous poll -- everything a frontend needs to apply.
cli
run(layout=typer.Option(None, '-l', '--layout', help='Layout type (name from grid_layouts folder) or relative JSON layout file'), list_layouts_flag=typer.Option(False, '-ll', '--list-layouts', help='Show all available layouts from grid_layouts folder and exit'), data=None, list_data_flag=typer.Option(False, '-ld', '--list-data', help='Show all available testing data samples and exit'), auto_play=typer.Option(False, '-ap', '--auto-play', help='Automatically start the simulation upon loading (data file required)'), log_level=typer.Option('INFO', '-log', '--log-level', help='Logging level (DEBUG_VERBOSE, DEBUG, INFO, WARNING, ERROR)'), log_format=typer.Option('compact', '-fmt', '--log-format', help='Logging format (simple, compact, standard, detailed)'))
SSL Simulator Vista - A PyVista/Matplotlib-based Visualization Tool for the SSL Simulator
This CLI launch the Qt application with given layout and data.
Examples:
sslvista -l 2d_canvas -data ./data/my_data.csv sslvista -l ./layouts/custom.json -data ./data/my_data.csv
config
Config
Bases: dict
A plain dict for global runtime flags.
Graphics/style defaults now live in typed models - see
:mod:ssl_vista.plotters.pv_utils.configs (GraphicsConfig, GridConfig, ...).
data
DataManager
A class to manage data files and layouts in the SSL Visualization Tool.
get_asset_path(asset_name)
staticmethod
Return the path to an asset PLY file. Looks in package data under data/assets.
get_grid_layout_path(layout_name)
staticmethod
Return the path to a layout JSON file. Looks in package data under data/grid_layouts.
get_sample_path(sample_name)
staticmethod
Return the path to a sample CSV file. Looks in package data under data/samples.
list_available_assets()
staticmethod
Return a list of asset names available in data/assets (without the .ply extension). Works in both editable mode and installed packages.
list_available_layouts()
staticmethod
Return a list of layout names available in data/grid_layouts (without the .json extension). Works in both editable mode and installed packages.
list_available_samples()
staticmethod
Return a list of sample names available in data/samples (without the .csv extension). Works in both editable mode and installed packages.
data_manager
DataManager
A class to manage data files and layouts in the SSL Visualization Tool.
get_asset_path(asset_name)
staticmethod
Return the path to an asset PLY file. Looks in package data under data/assets.
get_grid_layout_path(layout_name)
staticmethod
Return the path to a layout JSON file. Looks in package data under data/grid_layouts.
get_sample_path(sample_name)
staticmethod
Return the path to a sample CSV file. Looks in package data under data/samples.
list_available_assets()
staticmethod
Return a list of asset names available in data/assets (without the .ply extension). Works in both editable mode and installed packages.
list_available_layouts()
staticmethod
Return a list of layout names available in data/grid_layouts (without the .json extension). Works in both editable mode and installed packages.
list_available_samples()
staticmethod
Return a list of sample names available in data/samples (without the .csv extension). Works in both editable mode and installed packages.
layout
Public, dependency-light schema and builder for ssl-vista grid layouts.
This module is the single source of truth for the on-disk layout format
consumed by :func:ssl_vista.load_grid_from_json. It is deliberately free of Qt
and PyVista imports so that producers - simulators writing artifacts, tests,
tooling - can construct and validate layouts without a display or the rendering
stack::
from ssl_vista.layout import LayoutBuilder
layout = (
LayoutBuilder(shape=(2, 1))
.add_canvas_2d((0, 0), robot={"type": "unicycle", "color": "royalblue"})
.add_mpl((1, 0), module_path="my_plotter.py", class_name="MyPlotter")
.build()
)
layout.write_json("layout.json")
The validated model (:class:GridLayoutConfig) is exactly what the viewer parses
at load time, so a layout that builds here is guaranteed schema-valid there -
there is no parallel schema to drift out of sync.
GridLayoutConfig
Bases: BaseModel
Validated root configuration for a simulation grid layout.
to_dict(*, exclude_none=True)
Return a JSON-native dict (tuples become lists) ready for json.dump.
to_json(*, indent=2, exclude_none=True)
Serialize to a JSON string with a trailing newline.
write_json(path, *, indent=2, exclude_none=True)
Write the layout to path and return it.
LayoutBuilder
Fluent, validated builder for :class:GridLayoutConfig.
Every add_* method returns self for chaining; :meth:build runs the
same pydantic validation the viewer applies at load time (grid bounds, unique
positions, custom-plotter field pairing).
add(plotter_type, position, *, args=None, module_path=None, class_name=None)
Add an arbitrary plotter entry. Prefer the add_* shortcuts below.
add_canvas_2d(position, *, robot=None, grid=None, camera=None, graphics=None)
Add a Plotter2DCanvas with typed config namespaces as args.
add_canvas_3d(position, *, robot=None, grid=None, camera=None, graphics=None)
Add a Plotter3DCanvas with typed config namespaces as args.
add_mpl(position, *, module_path, class_name, args=None)
Add a file-loaded BaseMplPlotter (custom Matplotlib plotter plugin).
build(*, check_robot_types=False)
Return a validated :class:GridLayoutConfig.
With check_robot_types=True the builder additionally validates each
canvas plotter's robot["type"] against
:meth:RobotFactory.pose_fields. This is opt-in because it pulls in the
PyVista rendering stack; the default keeps layout building dependency-light.
(Unknown types are rejected by the viewer at load time regardless.)
LayoutSchemaError
Bases: ValueError
Raised when a grid layout file fails schema validation.
PlotterConfig
Bases: BaseModel
Validated configuration for a single plotter entry in a layout file.
parse_layout_config(raw_layout, source=None)
Parse and validate a raw layout dictionary into GridLayoutConfig.
mpl
Matplotlib visualization utilities (optional).
Small, reusable Matplotlib helpers - publication styling, 2-D robot glyphs, vector/axis drawing, colormaps, and animation updaters - shared across the simulation ecosystem. They are pure Matplotlib (no Qt), so they import without a display.
This is an optional feature: install the mpl extra (pip install ssl_vista[mpl]) to pull
Matplotlib + SciPy. 2-D plotting will eventually move to a GPU-backed stack (e.g. pyqtgraph), so
Matplotlib is deliberately not a hard dependency of ssl_vista.
alpha_cmap(cmap, alpha)
Apply a fixed alpha (transparency) to an existing colormap.
This function modifies a given Matplotlib colormap by blending its colors with a white
background using a specified alpha value. This is particularly useful when using
functions like pcolormesh, which can behave unpredictably with transparent overlays.
Parameters
cmap (matplotlib.colors.Colormap): The base colormap to modify.
alpha (float): The transparency level, ranging from 0 (fully transparent)
to 1 (fully opaque).
Returns
matplotlib.colors.ListedColormap: A new colormap with the alpha applied.
Notes
- The alpha is applied uniformly across all colors in the colormap.
- Blending is done with a white background.
- This method avoids rendering issues that can arise from applying alpha directly
to plots like `pcolormesh`.
Reference
https://stackoverflow.com/questions/37327308/add-alpha-to-an-existing-matplotlib-colormap
config_axis(ax, x_step=None, y_step=None, format_float=False, xlims=None, ylims=None, max_major_ticks=6, n_minor=4, max_major_ticks_x=None, max_major_ticks_y=None)
Configure the visual and tick properties of a Matplotlib Axes object.
This utility function allows fine control over the axis ticks, tick formatting, and limits for a Matplotlib plot. It automatically configures minor ticks and gridlines and adapts to the data being shown.
Parameters
ax (matplotlib.axes.Axes): The axes object to configure.
x_step (float, optional): Fixed spacing between major ticks on the x-axis.
Minor ticks will be placed at one-fourth of this interval. If not set,
spacing is inferred from xlims or current axis content.
y_step (float, optional): Fixed spacing between major ticks on the y-axis.
Minor ticks will be placed at one-fourth of this interval. If not set,
spacing is inferred from ylims or current axis content.
format_float (bool, optional): If True, format y-axis tick labels as floats
with two decimal places.
xlims (tuple[float, float], optional): If provided, sets (xmin, xmax) limits.
ylims (tuple[float, float], optional): If provided, sets (ymin, ymax) limits.
max_major_ticks (int, optional): Max number of major ticks to generate if
step size is not specified. Default is 6.
n_minor (int, optional): Number of minor subdivisions between major ticks.
Default is 4.
Returns
None
Notes
- Automatically sets gridlines to be visible.
- If neither steps nor limits are set, uses current axis limits and data.
- Uses `get_nice_ticks()` to compute evenly spaced "nice" ticks.
fixedwing_patch(XY, yaw, size=1, **patch_kwargs)
Generate a Matplotlib patch representing a fixed-wing aircraft.
The fixed-wing aircraft is visualized as an arrow-shaped patch with a given
position (XY), heading (yaw), and size. Additional keyword arguments are
passed to customize patch properties (e.g., color, edge width).
Parameters
XY (tuple or list): The (X, Y) coordinates of the aircraft's center.
yaw (float): The heading (orientation) in radians.
size (float, optional): Scaling factor for the aircraft. Default is 1.
**patch_kwargs: Additional properties for `PathPatch` (e.g., `fc`, `ec`, `lw`).
Returns
matplotlib.patches.PathPatch: A Matplotlib patch representing the fixed-wing.
Example
ax.add_patch(fixedwing_patch([2, 3], np.pi / 4, size=1.5, fc="blue", lw=0.5))
get_nice_ticks(vmin, vmax, max_major_ticks=6, n_minor=4)
Compute 'nice' evenly spaced major and minor tick locations for a given range.
This helper function uses matplotlib's MaxNLocator to determine a clean and
readable spacing between major ticks and then inserts minor ticks uniformly
between them.
Parameters
vmin (float): Minimum value of the axis range.
vmax (float): Maximum value of the axis range.
max_major_ticks (int, optional): Desired maximum number of major ticks.
n_minor (int, optional): Number of minor ticks between each major tick.
Returns
tuple:
- major_levels (np.ndarray): Array of major tick positions.
- minor_levels (np.ndarray): Array of minor tick positions.
- major_step (float): Distance between major ticks.
initialize_plot(ax=None, figsize=(8, 8), projection='3d', **kwargs)
Initialize a matplotlib figure and axis with optional 3D view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Existing matplotlib axis (optional). |
None
|
|
figsize
|
Tuple specifying figure size (default: (8, 8)). |
(8, 8)
|
|
projection
|
Projection type for the axis, e.g., '3d' (default: '3d'). |
'3d'
|
|
view
|
Tuple specifying the view as (elev, azim) (default: None). |
required | |
**kwargs
|
Additional keyword arguments for |
{}
|
Returns
fig: The created matplotlib figure (or None if ax is provided).
ax: The matplotlib axis (either provided or newly created).
save_paper_figure(img_name, output_dir, fig=None, apply_paper_params=True, fontsize=12, fontfamily='serif', uselatex=True, figure_dpi=100, save_dpi=300, low_quality_dpi=100, bbox='tight', pad_inches=0.1, transparent=False, save_pdf=True, close=False)
Save a Matplotlib figure with publication-friendly defaults for LaTeX papers.
The function can optionally apply paper parameters, set save-related rcParams, create the output directory if needed, and export the figure to: - PDF (vector) - PNG (high quality) - PNG low-quality preview
Parameters
img_name (str): Base filename (without extension).
output_dir (str): Directory where files are saved.
fig (matplotlib.figure.Figure, optional): Figure to save. If None, uses current figure.
apply_paper_params (bool, optional): Whether to call set_paper_parameters().
fontsize (int, optional): Font size for set_paper_parameters().
fontfamily (str, optional): Font family for set_paper_parameters().
uselatex (bool, optional): Use LaTeX text rendering in set_paper_parameters().
figure_dpi (int, optional): rcParams['figure.dpi'] value.
save_dpi (int, optional): DPI for high-quality PNG and rcParams['savefig.dpi'].
low_quality_dpi (int, optional): DPI for low-quality PNG preview.
bbox (str, optional): Bounding box mode for savefig.
pad_inches (float, optional): Padding around saved figure.
transparent (bool, optional): Save with transparent background if True.
save_pdf (bool, optional): Save PDF version if True.
close (bool, optional): Close figure after saving if True.
Returns
dict: Paths of the generated files with keys: 'pdf', 'png', 'png_lq'.
set_paper_parameters(fontsize=12, fontfamily='serif', uselatex=True)
Set Matplotlib parameters for consistent, publication-quality plots.
This function configures font styles, sizes, and LaTeX rendering options for consistent figure appearance across plots.
Parameters
fontsize (int, optional): Global font size. Default is 12.
fontfamily (str, optional): Font family (e.g., "serif", "Arial"). Default is "serif".
uselatex (bool, optional): Whether to use LaTeX rendering. Default is True.
Returns
None
Notes
- Requires LaTeX installed if `uselatex=True`.
- Applies to all future plots in the session.
- Math rendering uses the AMS math package and Computer Modern fonts.
Example
set_paper_parameters(fontsize=14, fontfamily="Arial", uselatex=False)
smooth_interpolation(x, y, method='cubic', num_points=100)
Perform smooth interpolation over 1D data.
This function interpolates data points using a specified method, optionally filling in missing values (NaNs) and returning a smooth curve for plotting.
Parameters
x (array-like): X-coordinates of the input data.
y (array-like): Y-coordinates of the input data. Can contain NaNs.
method (str, optional): Interpolation method: "linear", "quadratic", "cubic",
or "spline". Defaults to "cubic".
num_points (int, optional): Number of interpolated points. Default is 100.
Returns
tuple:
- x_smooth (np.ndarray): Interpolated X values.
- y_smooth (np.ndarray): Interpolated Y values.
Example
x_smooth, y_smooth = smooth_interpolation(x, y, method="cubic") plt.plot(x_smooth, y_smooth) plt.scatter(x, y)
unicycle_patch(XY, yaw, size=1, **patch_kwargs)
Generate a Matplotlib patch representing a unicycle.
The unicycle is visualized as a triangular patch with a given position (XY),
heading (yaw), and size. Additional keyword arguments are passed to customize
patch properties (e.g., color, edge width).
Parameters
XY (tuple or list): The (X, Y) coordinates of the unicycle's center.
yaw (float): The heading (orientation) in radians.
size (float, optional): Scaling factor for the unicycle. Default is 1.
**patch_kwargs: Additional properties for `PathPatch` (e.g., `fc`, `ec`, `lw`).
Returns
matplotlib.patches.PathPatch: A Matplotlib patch representing the unicycle.
Example
ax.add_patch(unicycle_patch([2, 3], np.pi / 4, size=1.5, fc="red", lw=0.5))
vector2d(ax, P0, Pf, c='k', ls='-', s=1, lw=0.7, hw=0.1, hl=0.2, alpha=1, zorder=1)
Draw a 2D vector as an arrow on a Matplotlib Axes.
This function adds a vector (arrow) from point P0 to point Pf on the given axes. The appearance of the vector (color, style, size, etc.) can be customized.
Parameters
ax (matplotlib.axes.Axes): Axes on which the vector is plotted.
P0 (tuple): Starting point (x, y) of the vector.
Pf (tuple): Ending point (x, y) of the vector.
c (str, optional): Arrow color. Default is "k" (black).
ls (str, optional): Line style. Default is "-" (solid line).
s (float, optional): Scale factor for vector magnitude. Default is 1.
lw (float, optional): Line width. Default is 0.7.
hw (float, optional): Arrowhead width. Default is 0.1.
hl (float, optional): Arrowhead length. Default is 0.2.
alpha (float, optional): Transparency (0 to 1). Default is 1.
zorder (int, optional): Z-order for layering. Default is 1.
Returns
matplotlib.patches.FancyArrowPatch: The drawn vector arrow.
Notes
- The arrow length includes the head by default.
- This function is useful for visualizing direction fields or forces.
Example
vector2d(ax, P0=(0, 0), Pf=(1, 2), c="red", s=1.5)
zoom_range(begin, end, center, scale_factor)
Calculate a zoomed-in 1D range centered at a given point.
This function returns a new range that zooms in or out relative to a center point by scaling the distance from the center to the range boundaries.
Parameters
begin (float): Starting value of the original range.
end (float): Ending value of the original range.
center (float): The center point around which to zoom.
scale_factor (float): The factor by which to scale the range.
Values < 1 zoom in; values > 1 zoom out.
Returns
tuple (float, float): The new (min, max) bounds of the zoomed range.
Reference
Adapted from: https://gist.github.com/dukelec/e8d4171ef4d12f9998295cfcbe3027ce # nosemgrep: long-hex-secret
basics
This Python module contains a collection of utility functions designed to facilitate data visualization and Matplotlib customization. The functions in this file simplify common tasks such as plotting 2D vectors, configuring Matplotlib axes, and applying alpha blending to colormaps. These utilities are intended to enhance the visual quality and flexibility of plots, particularly for scientific and engineering applications.
alpha_cmap(cmap, alpha)
Apply a fixed alpha (transparency) to an existing colormap.
This function modifies a given Matplotlib colormap by blending its colors with a white
background using a specified alpha value. This is particularly useful when using
functions like pcolormesh, which can behave unpredictably with transparent overlays.
Parameters
cmap (matplotlib.colors.Colormap): The base colormap to modify.
alpha (float): The transparency level, ranging from 0 (fully transparent)
to 1 (fully opaque).
Returns
matplotlib.colors.ListedColormap: A new colormap with the alpha applied.
Notes
- The alpha is applied uniformly across all colors in the colormap.
- Blending is done with a white background.
- This method avoids rendering issues that can arise from applying alpha directly
to plots like `pcolormesh`.
Reference
https://stackoverflow.com/questions/37327308/add-alpha-to-an-existing-matplotlib-colormap
config_axis(ax, x_step=None, y_step=None, format_float=False, xlims=None, ylims=None, max_major_ticks=6, n_minor=4, max_major_ticks_x=None, max_major_ticks_y=None)
Configure the visual and tick properties of a Matplotlib Axes object.
This utility function allows fine control over the axis ticks, tick formatting, and limits for a Matplotlib plot. It automatically configures minor ticks and gridlines and adapts to the data being shown.
Parameters
ax (matplotlib.axes.Axes): The axes object to configure.
x_step (float, optional): Fixed spacing between major ticks on the x-axis.
Minor ticks will be placed at one-fourth of this interval. If not set,
spacing is inferred from xlims or current axis content.
y_step (float, optional): Fixed spacing between major ticks on the y-axis.
Minor ticks will be placed at one-fourth of this interval. If not set,
spacing is inferred from ylims or current axis content.
format_float (bool, optional): If True, format y-axis tick labels as floats
with two decimal places.
xlims (tuple[float, float], optional): If provided, sets (xmin, xmax) limits.
ylims (tuple[float, float], optional): If provided, sets (ymin, ymax) limits.
max_major_ticks (int, optional): Max number of major ticks to generate if
step size is not specified. Default is 6.
n_minor (int, optional): Number of minor subdivisions between major ticks.
Default is 4.
Returns
None
Notes
- Automatically sets gridlines to be visible.
- If neither steps nor limits are set, uses current axis limits and data.
- Uses `get_nice_ticks()` to compute evenly spaced "nice" ticks.
get_nice_ticks(vmin, vmax, max_major_ticks=6, n_minor=4)
Compute 'nice' evenly spaced major and minor tick locations for a given range.
This helper function uses matplotlib's MaxNLocator to determine a clean and
readable spacing between major ticks and then inserts minor ticks uniformly
between them.
Parameters
vmin (float): Minimum value of the axis range.
vmax (float): Maximum value of the axis range.
max_major_ticks (int, optional): Desired maximum number of major ticks.
n_minor (int, optional): Number of minor ticks between each major tick.
Returns
tuple:
- major_levels (np.ndarray): Array of major tick positions.
- minor_levels (np.ndarray): Array of minor tick positions.
- major_step (float): Distance between major ticks.
smooth_interpolation(x, y, method='cubic', num_points=100)
Perform smooth interpolation over 1D data.
This function interpolates data points using a specified method, optionally filling in missing values (NaNs) and returning a smooth curve for plotting.
Parameters
x (array-like): X-coordinates of the input data.
y (array-like): Y-coordinates of the input data. Can contain NaNs.
method (str, optional): Interpolation method: "linear", "quadratic", "cubic",
or "spline". Defaults to "cubic".
num_points (int, optional): Number of interpolated points. Default is 100.
Returns
tuple:
- x_smooth (np.ndarray): Interpolated X values.
- y_smooth (np.ndarray): Interpolated Y values.
Example
x_smooth, y_smooth = smooth_interpolation(x, y, method="cubic") plt.plot(x_smooth, y_smooth) plt.scatter(x, y)
vector2d(ax, P0, Pf, c='k', ls='-', s=1, lw=0.7, hw=0.1, hl=0.2, alpha=1, zorder=1)
Draw a 2D vector as an arrow on a Matplotlib Axes.
This function adds a vector (arrow) from point P0 to point Pf on the given axes. The appearance of the vector (color, style, size, etc.) can be customized.
Parameters
ax (matplotlib.axes.Axes): Axes on which the vector is plotted.
P0 (tuple): Starting point (x, y) of the vector.
Pf (tuple): Ending point (x, y) of the vector.
c (str, optional): Arrow color. Default is "k" (black).
ls (str, optional): Line style. Default is "-" (solid line).
s (float, optional): Scale factor for vector magnitude. Default is 1.
lw (float, optional): Line width. Default is 0.7.
hw (float, optional): Arrowhead width. Default is 0.1.
hl (float, optional): Arrowhead length. Default is 0.2.
alpha (float, optional): Transparency (0 to 1). Default is 1.
zorder (int, optional): Z-order for layering. Default is 1.
Returns
matplotlib.patches.FancyArrowPatch: The drawn vector arrow.
Notes
- The arrow length includes the head by default.
- This function is useful for visualizing direction fields or forces.
Example
vector2d(ax, P0=(0, 0), Pf=(1, 2), c="red", s=1.5)
zoom_range(begin, end, center, scale_factor)
Calculate a zoomed-in 1D range centered at a given point.
This function returns a new range that zooms in or out relative to a center point by scaling the distance from the center to the range boundaries.
Parameters
begin (float): Starting value of the original range.
end (float): Ending value of the original range.
center (float): The center point around which to zoom.
scale_factor (float): The factor by which to scale the range.
Values < 1 zoom in; values > 1 zoom out.
Returns
tuple (float, float): The new (min, max) bounds of the zoomed range.
Reference
Adapted from: https://gist.github.com/dukelec/e8d4171ef4d12f9998295cfcbe3027ce # nosemgrep: long-hex-secret
figure_tools
Matplotlib Figure and Axis Initialization Utilities.
initialize_plot(ax=None, figsize=(8, 8), projection='3d', **kwargs)
Initialize a matplotlib figure and axis with optional 3D view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Existing matplotlib axis (optional). |
None
|
|
figsize
|
Tuple specifying figure size (default: (8, 8)). |
(8, 8)
|
|
projection
|
Projection type for the axis, e.g., '3d' (default: '3d'). |
'3d'
|
|
view
|
Tuple specifying the view as (elev, azim) (default: None). |
required | |
**kwargs
|
Additional keyword arguments for |
{}
|
Returns
fig: The created matplotlib figure (or None if ax is provided).
ax: The matplotlib axis (either provided or newly created).
save_paper_figure(img_name, output_dir, fig=None, apply_paper_params=True, fontsize=12, fontfamily='serif', uselatex=True, figure_dpi=100, save_dpi=300, low_quality_dpi=100, bbox='tight', pad_inches=0.1, transparent=False, save_pdf=True, close=False)
Save a Matplotlib figure with publication-friendly defaults for LaTeX papers.
The function can optionally apply paper parameters, set save-related rcParams, create the output directory if needed, and export the figure to: - PDF (vector) - PNG (high quality) - PNG low-quality preview
Parameters
img_name (str): Base filename (without extension).
output_dir (str): Directory where files are saved.
fig (matplotlib.figure.Figure, optional): Figure to save. If None, uses current figure.
apply_paper_params (bool, optional): Whether to call set_paper_parameters().
fontsize (int, optional): Font size for set_paper_parameters().
fontfamily (str, optional): Font family for set_paper_parameters().
uselatex (bool, optional): Use LaTeX text rendering in set_paper_parameters().
figure_dpi (int, optional): rcParams['figure.dpi'] value.
save_dpi (int, optional): DPI for high-quality PNG and rcParams['savefig.dpi'].
low_quality_dpi (int, optional): DPI for low-quality PNG preview.
bbox (str, optional): Bounding box mode for savefig.
pad_inches (float, optional): Padding around saved figure.
transparent (bool, optional): Save with transparent background if True.
save_pdf (bool, optional): Save PDF version if True.
close (bool, optional): Close figure after saving if True.
Returns
dict: Paths of the generated files with keys: 'pdf', 'png', 'png_lq'.
set_paper_parameters(fontsize=12, fontfamily='serif', uselatex=True)
Set Matplotlib parameters for consistent, publication-quality plots.
This function configures font styles, sizes, and LaTeX rendering options for consistent figure appearance across plots.
Parameters
fontsize (int, optional): Global font size. Default is 12.
fontfamily (str, optional): Font family (e.g., "serif", "Arial"). Default is "serif".
uselatex (bool, optional): Whether to use LaTeX rendering. Default is True.
Returns
None
Notes
- Requires LaTeX installed if `uselatex=True`.
- Applies to all future plots in the session.
- Math rendering uses the AMS math package and Computer Modern fonts.
Example
set_paper_parameters(fontsize=14, fontfamily="Arial", uselatex=False)
patches
fixedwing_patch(XY, yaw, size=1, **patch_kwargs)
Generate a Matplotlib patch representing a fixed-wing aircraft.
The fixed-wing aircraft is visualized as an arrow-shaped patch with a given
position (XY), heading (yaw), and size. Additional keyword arguments are
passed to customize patch properties (e.g., color, edge width).
Parameters
XY (tuple or list): The (X, Y) coordinates of the aircraft's center.
yaw (float): The heading (orientation) in radians.
size (float, optional): Scaling factor for the aircraft. Default is 1.
**patch_kwargs: Additional properties for `PathPatch` (e.g., `fc`, `ec`, `lw`).
Returns
matplotlib.patches.PathPatch: A Matplotlib patch representing the fixed-wing.
Example
ax.add_patch(fixedwing_patch([2, 3], np.pi / 4, size=1.5, fc="blue", lw=0.5))
unicycle_patch(XY, yaw, size=1, **patch_kwargs)
Generate a Matplotlib patch representing a unicycle.
The unicycle is visualized as a triangular patch with a given position (XY),
heading (yaw), and size. Additional keyword arguments are passed to customize
patch properties (e.g., color, edge width).
Parameters
XY (tuple or list): The (X, Y) coordinates of the unicycle's center.
yaw (float): The heading (orientation) in radians.
size (float, optional): Scaling factor for the unicycle. Default is 1.
**patch_kwargs: Additional properties for `PathPatch` (e.g., `fc`, `ec`, `lw`).
Returns
matplotlib.patches.PathPatch: A Matplotlib patch representing the unicycle.
Example
ax.add_patch(unicycle_patch([2, 3], np.pi / 4, size=1.5, fc="red", lw=0.5))
plotters
base_canvas
BaseCanvasPlotter
Bases: _BaseVisualPlotter
Generalized PyVista canvas for spatial visualization.
Configuration is grouped into namespaces - grid (:class:GridConfig),
camera (:class:CameraConfig), robot (:class:RobotConfig) and
graphics (:class:GraphicsConfig) - each accepting a model or a plain dict
(e.g. from a layout file's args). Each namespace is forwarded whole to its
sub-component, so options never need re-declaring on this class.
The robot type dictates which simulation fields are required (see
:meth:RobotFactory.pose_fields): every type needs positions, and directional
types additionally need an orientation - a planar heading in 2D or a rotation
matrix (rotation) in 3D. Symmetric types (e.g. single_integrator) are drawn
from position alone. This policy and the shared init_artists / update_artists
lifecycle live here; concrete subclasses only supply the small dimension-specific
hooks below (_pose_kwargs, _check_orientation_shape, _robot_build_kwargs).
reads
property
Positions, plus the orientation when this robot type is directional.
add_scene_object(name, obj)
Add any :class:Drawable to the scene.
The drawable creates its own actor(s) via obj._attach(pvqt, name) and
returns its leaf objects. A single :class:SceneObject registers under
name; a :class:SceneObjectGroup registers each leaf as
"{name}.{child_name}". Any object implementing the _attach protocol
(including user-defined ones) integrates without special-casing.
Returns the same object for chaining.
Example
sphere = Mesh(pv.Sphere(), color="orange") self.add_scene_object("sphere", sphere) sphere.set_pose(position=[1, 0, 0])
clear_scene_objects()
Remove every scene object's actor and reset the registries.
collect_scene_objects(verbose=False)
Return a structured snapshot of this plotter's scene objects.
Pure data - no logging side effects. The caller decides whether and how to log it.
get_scene_object(obj_name)
Retrieve a scene object by name.
get_widget()
Return the Qt widget for layouts.
in_scene(names)
Check if one or more scene objects exist.
init_artists(sim_data, sim_settings)
Build robot icons + trajectory placeholders and pose them at frame 0.
keyPressEvent(event)
Shadow all key presses to avoid default widget behavior.
keyReleaseEvent(event)
Shadow all key releases to avoid default widget behavior.
missing_components(source)
Which of :attr:reads the given source cannot provide.
refresh_data(sim_data, sim_settings)
The data source grew (live stream): refresh anything derived from the full run.
Called by the grid between reset_scene (new run) and per-frame update_artists
whenever a live source reports new frames. Plotters whose update_artists only index
sim_data[...][idx] need nothing here (arrays growing at the end is transparent);
override to refit axis limits or rebuild caches computed over the whole run.
remove_scene_object(name)
Remove a scene object (single leaf or a whole group added under name).
reset_scene(sim_data=None, sim_settings=None)
Reset the scene by clearing and reinitializing artists.
reset_view()
Restore initial camera orientation, grid position, and fit the scene.
set_grid_centroid(centroid)
Set the canvas grid centroid.
set_widget(widget)
Set the Qt widget for layouts.
setup_scene(sim_data=None, sim_settings=None)
Set up the scene by initializing the grid and artists.
update_all_scene_objects(sim_data, idx)
Update artists for frame idx via update_artists(), then render.
update_artists(sim_data, idx)
Update robot poses and trajectory tails for frame idx.
when_change_robot_focus(idx_new_focus, idx_prv_focus)
Handle changes in robot focus from the context.
apply_camera(pvqt, cam)
Apply a resolved :class:CameraConfig (see CameraConfig.resolved) to a plotter.
base_mpl
BaseMplPlotter
Bases: ProtectedAttrsMixin, _BasePlotter
Base class for Matplotlib-based plotters.
Subclasses should
- define self.axes_config: dict specifying axes e.g., {"main": {"position":[x0,y0,dx,dy], "projection":"3d"}}
- implement init_artists(self)
- implement update_artists(self, frame_data)
reads
property
Derived from the registered lines - register_lines already names each component.
__setattr__(name, value)
Intercept attribute assignments to protect managed attributes. Issues a warning when child classes try to directly reassign protected attributes.
collect_scene_objects(verbose=False)
Return a structured snapshot of this plotter's matplotlib artists.
Pure data - no logging side effects.
get_widget()
Return the Qt widget for layouts.
init_artists(sim_data, sim_settings)
Initialize all plot elements. Must be implemented by subclass.
keyReleaseEvent(event)
Shadow all key releases to avoid default widget behavior.
missing_components(source)
Which of :attr:reads the given source cannot provide.
refresh_data(sim_data, sim_settings)
Live source grew: refit axis limits. Line artists follow per-frame in _update_lines.
register_lines(axis, var, name=None, shape=None, units='', extract=None, **kw_style)
Register a group of lines to be plotted and updated. Parameters: name: str, key for this group of lines axis: str, axis key in self.axes var: str, variable name in sim_data shape: int, number of lines (e.g. 3 for x/y/z) units: str, units for axis label extract: function or None, how to extract data from sim_data[var]
reset_scene(sim_data, sim_settings)
Reset the scene to its initial state.
reset_view()
Restore the initial camera / view state. No-op by default.
set_widget(widget)
Set the Qt widget for layouts.
setup_scene()
Create axes and initialize artists.
update_all_scene_objects(sim_data, idx)
Update all artists in the scene.
update_artists(sim_data, idx)
Update plot elements for a new frame. Must be implemented by subclass.
plotter_2d_canvas
Plotter2DCanvas
Bases: BaseCanvasPlotter
2D PyVista canvas for visualizing robots, trajectories, and vectors.
Directional types (unicycle, car, fixed_wing) are oriented by a planar
heading read from label_heading with shape (T, N); symmetric types
(single_integrator) are drawn from position alone. The shared lifecycle and the
"which fields are required" policy live in :class:BaseCanvasPlotter.
reads
property
Positions, plus the orientation when this robot type is directional.
add_scene_object(name, obj)
Add any :class:Drawable to the scene.
The drawable creates its own actor(s) via obj._attach(pvqt, name) and
returns its leaf objects. A single :class:SceneObject registers under
name; a :class:SceneObjectGroup registers each leaf as
"{name}.{child_name}". Any object implementing the _attach protocol
(including user-defined ones) integrates without special-casing.
Returns the same object for chaining.
Example
sphere = Mesh(pv.Sphere(), color="orange") self.add_scene_object("sphere", sphere) sphere.set_pose(position=[1, 0, 0])
clear_scene_objects()
Remove every scene object's actor and reset the registries.
collect_scene_objects(verbose=False)
Return a structured snapshot of this plotter's scene objects.
Pure data - no logging side effects. The caller decides whether and how to log it.
get_scene_object(obj_name)
Retrieve a scene object by name.
get_widget()
Return the Qt widget for layouts.
in_scene(names)
Check if one or more scene objects exist.
init_artists(sim_data, sim_settings)
Build robot icons + trajectory placeholders and pose them at frame 0.
keyPressEvent(event)
Shadow all key presses to avoid default widget behavior.
keyReleaseEvent(event)
Shadow all key releases to avoid default widget behavior.
missing_components(source)
Which of :attr:reads the given source cannot provide.
refresh_data(sim_data, sim_settings)
The data source grew (live stream): refresh anything derived from the full run.
Called by the grid between reset_scene (new run) and per-frame update_artists
whenever a live source reports new frames. Plotters whose update_artists only index
sim_data[...][idx] need nothing here (arrays growing at the end is transparent);
override to refit axis limits or rebuild caches computed over the whole run.
remove_scene_object(name)
Remove a scene object (single leaf or a whole group added under name).
reset_scene(sim_data=None, sim_settings=None)
Reset the scene by clearing and reinitializing artists.
reset_view()
Restore initial camera orientation, grid position, and fit the scene.
set_grid_centroid(centroid)
Set the canvas grid centroid.
set_widget(widget)
Set the Qt widget for layouts.
setup_scene(sim_data=None, sim_settings=None)
Set up the scene by initializing the grid and artists.
update_all_scene_objects(sim_data, idx)
Update artists for frame idx via update_artists(), then render.
update_artists(sim_data, idx)
Update robot poses and trajectory tails for frame idx.
when_change_robot_focus(idx_new_focus, idx_prv_focus)
Handle changes in robot focus from the context.
plotter_3d_attitude
Plotter3DAttitude
Bases: _BaseVisualPlotter
3D Attitude visualizer for a single robot's orientation matrix.
reads
property
Only the rotation matrix; this plotter draws one robot's attitude.
add_scene_object(name, obj)
Add any :class:Drawable to the scene.
The drawable creates its own actor(s) via obj._attach(pvqt, name) and
returns its leaf objects. A single :class:SceneObject registers under
name; a :class:SceneObjectGroup registers each leaf as
"{name}.{child_name}". Any object implementing the _attach protocol
(including user-defined ones) integrates without special-casing.
Returns the same object for chaining.
Example
sphere = Mesh(pv.Sphere(), color="orange") self.add_scene_object("sphere", sphere) sphere.set_pose(position=[1, 0, 0])
clear_scene_objects()
Remove every scene object's actor and reset the registries.
collect_scene_objects(verbose=False)
Return a structured snapshot of this plotter's scene objects.
Pure data - no logging side effects. The caller decides whether and how to log it.
get_widget()
Return the Qt widget for layouts.
init_artists(sim_data, sim_settings)
Create the sphere grid and the x/y/z attitude axes.
keyPressEvent(event)
Use PageUp/PageDown to switch between robots.
keyReleaseEvent(event)
Shadow all key releases to avoid default widget behavior.
missing_components(source)
Which of :attr:reads the given source cannot provide.
refresh_data(sim_data, sim_settings)
The data source grew (live stream): refresh anything derived from the full run.
Called by the grid between reset_scene (new run) and per-frame update_artists
whenever a live source reports new frames. Plotters whose update_artists only index
sim_data[...][idx] need nothing here (arrays growing at the end is transparent);
override to refit axis limits or rebuild caches computed over the whole run.
remove_scene_object(name)
Remove a scene object (single leaf or a whole group added under name).
reset_scene(sim_data, sim_settings)
Clear existing artists and (re)build them from data via init_artists().
reset_view()
Restore the initial camera / view state. No-op by default.
set_widget(widget)
Set the Qt widget for layouts.
setup_scene()
Set up the camera and lighting (the spherical grid is built in init_artists).
update_all_scene_objects(sim_data, idx)
Update artists for frame idx via update_artists(), then render.
update_artists(sim_data, idx)
Update attitude visualization from simulation data.
sim_data[self.label_rot] should have shape (T, N, 3, 3), where T = time steps, N = number of robots.
when_change_robot_focus(idx_new_focus, idx_prv_focus)
Handle robot focus change. Can be overridden by subclasses.
plotter_3d_canvas
Plotter3DCanvas
Bases: BaseCanvasPlotter
3D PyVista canvas for visualizing robots, trajectories, and vectors.
Directional types (unicycle, car, quadrotor, miniplank) are oriented
by a rotation matrix read from label_rot with shape (T, N, 3, 3); symmetric
types (single_integrator) are drawn from position alone. The shared lifecycle and
the "which fields are required" policy live in :class:BaseCanvasPlotter.
reads
property
Positions, plus the orientation when this robot type is directional.
add_scene_object(name, obj)
Add any :class:Drawable to the scene.
The drawable creates its own actor(s) via obj._attach(pvqt, name) and
returns its leaf objects. A single :class:SceneObject registers under
name; a :class:SceneObjectGroup registers each leaf as
"{name}.{child_name}". Any object implementing the _attach protocol
(including user-defined ones) integrates without special-casing.
Returns the same object for chaining.
Example
sphere = Mesh(pv.Sphere(), color="orange") self.add_scene_object("sphere", sphere) sphere.set_pose(position=[1, 0, 0])
clear_scene_objects()
Remove every scene object's actor and reset the registries.
collect_scene_objects(verbose=False)
Return a structured snapshot of this plotter's scene objects.
Pure data - no logging side effects. The caller decides whether and how to log it.
get_scene_object(obj_name)
Retrieve a scene object by name.
get_widget()
Return the Qt widget for layouts.
in_scene(names)
Check if one or more scene objects exist.
init_artists(sim_data, sim_settings)
Build robot icons + trajectory placeholders and pose them at frame 0.
keyPressEvent(event)
Shadow all key presses to avoid default widget behavior.
keyReleaseEvent(event)
Shadow all key releases to avoid default widget behavior.
missing_components(source)
Which of :attr:reads the given source cannot provide.
refresh_data(sim_data, sim_settings)
The data source grew (live stream): refresh anything derived from the full run.
Called by the grid between reset_scene (new run) and per-frame update_artists
whenever a live source reports new frames. Plotters whose update_artists only index
sim_data[...][idx] need nothing here (arrays growing at the end is transparent);
override to refit axis limits or rebuild caches computed over the whole run.
remove_scene_object(name)
Remove a scene object (single leaf or a whole group added under name).
reset_scene(sim_data=None, sim_settings=None)
Reset the scene by clearing and reinitializing artists.
reset_view()
Restore initial camera orientation, grid position, and fit the scene.
set_grid_centroid(centroid)
Set the canvas grid centroid.
set_widget(widget)
Set the Qt widget for layouts.
setup_scene(sim_data=None, sim_settings=None)
Set up the scene by initializing the grid and artists.
update_all_scene_objects(sim_data, idx)
Update artists for frame idx via update_artists(), then render.
update_artists(sim_data, idx)
Update robot poses and trajectory tails for frame idx.
when_change_robot_focus(idx_new_focus, idx_prv_focus)
Handle changes in robot focus from the context.
registry
create_plotter_instance(plotter_type, *, context=None, module_path=None, class_name=None, base_dir=None, **kwargs)
Create a plotter instance from a class object, registry name, or file plugin.
Parameters
plotter_type:
Either a class object that is a subclass of _BasePlotter (programmatic
path), or a string registry name / 'BaseMplPlotter' sentinel for the
file-based path.
context:
Shared :class:~ssl_vista.ui.grid.SimulationGridContext instance.
module_path:
(File-based path only) Path to a Python module containing a custom plotter.
class_name:
(File-based path only) Name of the class inside module_path.
base_dir:
Base directory used to resolve relative module_path values.
**kwargs:
Additional keyword arguments forwarded to the plotter constructor.
get_plotter_class(name)
Get a registered plotter class by name.
list_registered_plotters()
Return all registered plotter names.
register_plotter(name, plotter_cls, overwrite=False)
Register a plotter class by name.
sources
Compatibility shim: the source contract lives in the ground data plane now.
DataSource/LoggedSource/StreamSource moved to ssl_link so headless ground apps
(bridges, GCS tools, analysis) can consume data without installing the viewer stack. Import
from ssl_link.sources in new code; this module keeps existing ssl_vista.sources
imports working.
types
Programmatic API types for ssl_vista.
These types allow consumers to configure and launch the simulation viewer entirely from Python objects, without touching the filesystem.
Example
from ssl_vista import GridSpec, PlotterSpec, run_app from ssl_simulator.utils.processing import load_sim from ssl_vista.plotters import Plotter3DCanvas
sim_data, sim_settings = load_sim("run.csv") spec = GridSpec( ... shape=(1, 2), ... plotters=[ ... PlotterSpec(position=(0, 0), plotter_cls=Plotter3DCanvas, kwargs={"robot_type": "unicycle"}), ... PlotterSpec(position=(0, 1), plotter_type="Plotter3DAttitude"), ... ], ... ) run_app(grid_spec=spec, sim_data=sim_data, sim_settings=sim_settings, auto_play=True)
GridSpec
dataclass
Specification for a full simulation grid layout.
Parameters
shape:
(rows, cols) dimensions of the plotter grid.
plotters:
Ordered list of :class:PlotterSpec entries describing each cell.
PlotterSpec
dataclass
Specification for a single plotter within a :class:GridSpec.
Exactly one of plotter_cls or plotter_type must be supplied.
Parameters
position:
(row, col) cell in the simulation grid.
plotter_cls:
A concrete plotter class (must be a subclass of _BasePlotter).
Use this to pass a class object directly without going through the
string registry.
plotter_type:
Name of a plotter registered in the global registry
(e.g. "Plotter3DCanvas").
kwargs:
Extra keyword arguments forwarded to the plotter constructor.
ui
custom_widgets
CustomSlider
Bases: QSlider
Custom slider to shadow key events.
keyPressEvent(event)
Override key press events to prevent default slider behavior.
export
Screenshot and video recording export for ssl_vista.
ExportManager
Screenshot and recording facade owned by MainWindow.
Parameters
window: The parent QMainWindow (used as parent for dialogs). get_widget: Callable returning the QWidget to capture. Called lazily at capture time so the grid can be set after ExportManager is constructed.
capture_frame()
Append the current widget state as the next recording frame.
Call this once per rendered frame (e.g. inside update_simulation). No-op when not recording or when the capture widget is unavailable.
start_recording(default_fps)
Show config dialog and open the streaming writer.
Returns True if recording was successfully started, False if the user cancelled or a dependency is missing.
stop_recording()
Flush and close the writer, then show a confirmation dialog.
take_screenshot()
Show the screenshot config dialog, then capture the current widget state.
Mirrors the recording flow: a config dialog with a format choice and a timestamped default path, followed by a save confirmation.
RecordingConfigDialog
Bases: QDialog
Shown before recording starts: choose format, fps, and output path.
ScreenshotConfigDialog
Bases: QDialog
Shown before a screenshot is taken: choose image format, quality, and output path.
capture_grid(grid)
Composite all plotter panels into a single (H, W, 3) uint8 RGB image.
QWidget.grab() misses OpenGL content rendered by PyVista's VTK backend. This function uses the native capture path for each plotter type: - _BaseVisualPlotter -> pvqt.screenshot(return_img=True) via VTK - BaseMplPlotter -> canvas.buffer_rgba() via matplotlib then composites them onto a canvas sized to the full grid widget.
grid
SimulationGrid
Bases: QWidget
A customizable grid layout for plotters.
check_source(sim_data)
Raise if any plotter needs a component the source does not have.
missing_components(sim_data)
Components each plotter declares via reads but the source cannot provide.
Checking up front turns a mid-animation KeyError into one clear message naming the
layout position, the plotter and the absent components.
refresh_scenes(sim_data, sim_settings)
Live source grew: let every plotter refresh run-derived state (see refresh_data).
reset_scenes(sim_data, sim_settings)
Reset all subplots and emit a single structured log record.
reset_views()
Restore the initial camera/view state for all subplots.
restore_splitter_state(state)
Restore layout from saved splitter state.
save_splitter_state()
Return byte array for restoring layout later.
setup_scenes()
Initialize scenes for all subplots.
timer_set(callback, step=50)
Set the timer callback and interval.
timer_start()
Start the simulation update timer.
timer_stop()
Stop the simulation update timer.
update_scenes(sim_data, idx)
Update each subplot with simulation data at timestep 'idx'.
SimulationGridContext
Bases: QObject
A context class for SimulationGrid to share variables and signals.
load_grid_from_json(file_path, parent=None)
Load and configure a SimulationGrid instance from a JSON layout file.
Parameters
file_path : str | Path Path to the JSON configuration file. parent : QWidget, optional Parent widget for the grid.
Returns
SimulationGrid A fully configured SimulationGrid instance.
load_grid_from_spec(spec, parent=None)
Build a :class:SimulationGrid from a programmatic :class:~ssl_vista.types.GridSpec.
This is the programmatic counterpart to :func:load_grid_from_json - it
accepts a :class:~ssl_vista.types.GridSpec Python object rather than a
JSON file path, so no filesystem access is required.
Parameters
spec:
A :class:~ssl_vista.types.GridSpec describing the grid shape and each
plotter cell (by class object or registry name).
parent:
Optional parent widget.
Returns
SimulationGrid
A fully configured :class:SimulationGrid instance ready to be used
as a central widget.
icons
Programmatically-generated SVG icons for ssl_vista toolbar actions.
make_icon(name, size=20)
Render a named SVG string into a QIcon.
Parameters
name:
One of "record", "stop_rec", "screenshot", "play", "stop", "reset".
size:
Icon pixel size (square). Default 20 px.
main_window
MainWindow
Bases: QMainWindow
Base simulation application with a toolbar and customizable grid layout.
clear_current_grid()
Safely remove and delete the existing grid widget.
closeEvent(event)
Handle the close event to stop all timers and clean up.
get_slider_num_steps()
Return the current slider number of steps.
handle_key_press(event)
Handle key press events.
load_data(file_path)
Load simulation data from a data file.
load_grid_layout(file_path)
Load a new grid layout from file, then reload any active data file into it.
next_simulation_step(*args)
Advance the simulation by one time step.
play_simulation()
Start playing the simulation (for a live source: re-attach to the stream head).
process_data()
Process the loaded data file, rolling back on incompatibility.
reload_data()
Reload the currently loaded data file.
reset_simulation()
Reset the simulation to the beginning.
stop_simulation()
Stop the simulation.
update_simulation()
Update the simulation visualization.
update_time(value)
Update the simulation to the specified time index.
toolbars
SimulationToolbar
Bases: QToolBar
Toolbar for simulation controls.