stormvogel.visualization¶
Contains the code responsible for model visualization.
Classes¶
Base class for visualizing a Stormvogel MDP model. |
|
Handles visualization of a Model using a Network from stormvogel.network. |
|
Matplotlib-based visualization for Stormvogel models. |
Module Contents¶
- class stormvogel.visualization.VisualizationBase(model: stormvogel.model.Model, layout: stormvogel.layout.Layout = stormvogel.layout.DEFAULT(), result: stormvogel.result.Result | None = None, scheduler: stormvogel.result.Scheduler | None = None)¶
Base class for visualizing a Stormvogel MDP model.
This class sets up a visual representation of a Stormvogel model, optionally incorporating the result of a model checking operation and a scheduler (i.e., a strategy for selecting actions). It constructs an internal graph of the model and manages visual layout settings, such as active and possible display groups.
If a scheduler is not explicitly provided but is available in the model checking result, it will be used automatically. When a scheduler is set, the “scheduled_actions” group is activated in the layout; otherwise, it is deactivated.
- Attributes:
model (stormvogel.model.Model): The MDP model being visualized. layout (stormvogel.layout.Layout): The layout configuration for the visualization. result (stormvogel.result.Result | None): The result of a model checking operation. scheduler (stormvogel.result.Scheduler | None): A scheduler representing a path
through the model.
G (ModelGraph): The internal graph structure representing the model.
- Args:
model (stormvogel.model.Model): The MDP model to visualize. layout (stormvogel.layout.Layout, optional): Layout settings for the visualization.
Defaults to stormvogel.layout.DEFAULT().
- result (stormvogel.result.Result, optional): The result of a model checking
operation, which may contain a scheduler.
- scheduler (stormvogel.result.Scheduler, optional): An explicit scheduler
defining actions to take in each state.
- model¶
- layout¶
- result = None¶
- scheduler = None¶
- static _und(x: str) str¶
Replace spaces by underscores.
- static _random_word(k: int) str¶
Random word of length k
- static _random_color() str¶
Return a random HEX color.
- static _blend_colors(c1: str, c2: str, factor: float) str¶
Blend two colors in HEX format. #RRGGBB. Args:
color1 (str): Color 1 in HEX format #RRGGBB color2 (str): Color 2 in HEX format #RRGGBB factor (float): The fraction of the resulting color that should come from color1.
- recreate()¶
Recreate the ModelGraph and set the edit groups.
- _format_number(n: stormvogel.model.Value) str¶
Call number_to_string in model.py while accounting for the settings specified in the layout object.
- _format_result(s: stormvogel.model.State) str¶
Create a string that shows the result for this state. Starts with newline. If results are not enabled, then it returns the empty string.
- _format_observations(s: stormvogel.model.State) str¶
Create a String that shows the observation for this state (FOR POMDPs). Starts with newline.
- _group_state(s: stormvogel.model.State, default: str) str¶
The user can edit a number of subsets of the states individually, we call these groups. This function determines the group of this state. That is, the label of s that has the highest priority, as specified by the user under edit_groups.
- _group_action(s_id: int, a: stormvogel.model.Action, default: str) str¶
Return the group of this action. Only relevant for scheduling
- _format_rewards(s: stormvogel.model.State, a: stormvogel.model.Action) str¶
Create a string that contains either the state exit reward (if actions are not supported) or the reward of taking this action from this state. (if actions ARE supported) Starts with newline.
- _create_state_properties(state: stormvogel.model.State) dict¶
Generates visualization properties for a given state in the model.
That is, the visual representation of a state, including its label, group assignment, color (based on model checking results), and other textual annotations like rewards and observations. These properties are used when constructing the ModelGraph for visualization.
If result coloring is enabled and a model checking result is available, the state’s color is interpolated between two configured colors based on the state’s result value relative to the maximum result.
- Args:
state (stormvogel.model.State): The model state for which to generate properties.
- Returns:
- dict: A dictionary containing the state’s visualization properties with keys:
“label”: A string representing the state label, including ID (if enabled), labels, rewards, result, and observations.
“group”: A string identifying the layout group this state belongs to.
“color”: A blended RGB color string or None, based on result values.
- _create_action_properties(state: stormvogel.model.State, action: stormvogel.model.Action) dict¶
Generates visualization properties for a given action in the model.
This method creates a label for the action, optionally including any associated reward, and includes the original Action object for use in the visualization or interaction.
- Args:
state (stormvogel.model.State): The state from which the action originates. action (stormvogel.model.Action): The action being evaluated.
- Returns:
- dict: A dictionary containing the action’s visualization properties:
“label”: A string combining the action’s labels and reward.
“model_action”: The original Action object.
- _create_transition_properties(state, action, next_state) dict¶
Generates visualization properties for a transition between states.
This method finds the transition probability for a specific state-action– next-state triplet and formats it as a label. If the transition exists, the formatted probability is included; otherwise, an empty dictionary is returned.
- Args:
state (stormvogel.model.State): The source state of the transition. action (stormvogel.model.Action): The action taken from the source state. next_state (stormvogel.model.State): The target state of the transition.
- Returns:
- dict: A dictionary containing the transition’s visualization properties:
“label”: The formatted transition probability, if found. Otherwise, the dictionary will be empty.
- class stormvogel.visualization.JSVisualization(model: stormvogel.model.Model, name: str | None = None, result: stormvogel.result.Result | None = None, scheduler: stormvogel.result.Scheduler | None = None, layout: stormvogel.layout.Layout = stormvogel.layout.DEFAULT(), output: ipywidgets.Output | None = None, debug_output: ipywidgets.Output | None = None, use_iframe: bool = False, do_init_server: bool = True, max_states: int = 1000, max_physics_states: int = 500)¶
Bases:
VisualizationBaseHandles visualization of a Model using a Network from stormvogel.network.
- EXTRA_PIXELS: int = 20¶
- name: str = ''¶
- use_iframe: bool = False¶
- max_states: int = 1000¶
- max_physics_states: int = 500¶
- do_init_server: bool = True¶
- network_wrapper: str = ''¶
- _generate_node_js() str¶
Generate the required js script for node definition
- _generate_edge_js() str¶
Generate the required js script for edge definition
- _get_options() str¶
Returns the current layout configuration as a JSON-formatted string.
This method serializes the layout dictionary used for visualization into a readable JSON format with indentation for clarity.
- Returns:
str: A pretty-printed JSON string representing the current layout configuration.
- set_options(options: str) None¶
Sets the layout configuration from a JSON-formatted string.
This method replaces the current layout with a new one defined by the given JSON string. It should be called only before visualization is rendered (i.e., before calling show()), as it reinitializes the layout.
- Args:
options (str): A JSON-formatted string representing the layout configuration.
- generate_html() str¶
Generate an html page representing the current state of the ModelGraph
- generate_iframe() str¶
Generate an iframe for the network, using the html.
- generate_svg(width: int = 800) str¶
Generate an svg rendering for the network.
- enable_exploration_mode(initial_node_id: int)¶
Enables exploration mode starting from a specified initial state.
This method activates interactive exploration mode in the visualization and sets the starting point for exploration to the given state ID. show() needs to be called after this method is executed to have an effect.
- Args:
initial_node_id (int): The ID of the state from which exploration should begin.
- get_positions() dict[int, dict[str, int]]¶
Get the current positions of the nodes on the canvas. Returns empty dict if unsuccessful. Example result: {0: {“x”: 5, “y”: 10}}
- show(hidden: bool = False) None¶
- update() None¶
Updates the visualization with the current layout options.
This method sends updated layout configuration to the frontend visualization by injecting JavaScript code. It is typically used to reflect changes made to layout settings after the initial rendering.
- Note:
This should be called after modifying layout properties if the visualization has already been shown, to apply those changes interactively.
- set_node_color(node_id: int, color: str | None) None¶
Sets the color of a specific node in the visualization.
This method updates the visual appearance of a node by changing its color via JavaScript. It only takes effect once the network has been fully loaded in the frontend.
- Args:
node_id (int): The ID of the node whose color should be changed. color (str | None): The color to apply (e.g., “#ff0000” for red).
If None, the node color is reset or cleared.
- Note:
This function requires that the visualization is already rendered (i.e., show() has been called and completed asynchronously).
- highlight_state(state_id: int, color: str | None = 'red')¶
Highlights a single state in the model by changing its color.
This method changes the color of the specified state node in the visualization. Pass None to reset or clear the highlight.
- Args:
state_id (int): The ID of the state to highlight. color (str | None, optional): The color to use for highlighting (e.g., “red”, “#00ff00”).
Defaults to “red”.
- Raises:
AssertionError: If the state ID does not exist in the model graph.
- highlight_action(state_id: int, action: stormvogel.model.Action, color: str | None = 'red')¶
Highlights a single action in the model by changing its color.
This method changes the color of the node representing a specific action taken from a given state. Pass None to remove the highlight.
- Args:
state_id (int): The ID of the state from which the action originates. action (stormvogel.model.Action): The action to highlight. color (str | None, optional): The color to use for highlighting. Defaults to “red”.
- Warns:
UserWarning: If the specified (state, action) pair is not found in the model graph.
- highlight_state_set(state_ids: set[int], color: str | None = 'blue')¶
Highlights a set of states in the model by changing their color.
Iterates over each state ID in the provided set and applies the given color. Pass None to clear highlighting for all specified states.
- Args:
state_ids (set[int]): A set of state IDs to highlight. color (str | None, optional): The color to apply. Defaults to “blue”.
- highlight_action_set(state_action_set: set[tuple[int, stormvogel.model.Action]], color: str = 'red')¶
Highlights a set of actions in the model by changing their color.
Applies the specified color to all (state, action) pairs in the given set. Pass None as the color to clear the current highlighting.
- Args:
- state_action_set (set[tuple[int, stormvogel.model.Action]]): A set of
(state ID, action) pairs to highlight.
color (str, optional): The color to apply. Defaults to “red”.
- highlight_decomposition(decomp: list[tuple[set[int], set[tuple[int, stormvogel.model.Action]]]], colors: list[str] | None = None)¶
Highlight a set of tuples of (states and actions) in the model by changing their color. Args:
decomp: A list of tuples (states, actions) colors (optional): A list of colors for the decompositions. Random colors are picked by default.
- clear_highlighting()¶
Clear all highlighting that is currently active, returning all states to their original colors.
- highlight_path(path: stormvogel.simulator.Path, color: str, delay: float = 1, clear: bool = True) None¶
Highlight the path that is provided as an argument in the model. Args:
path (simulator.Path): The path to highlight. color (str | None): The color that the highlighted states should get (in HTML color standard).
Set to None, in order to clear existing highlights on this path.
delay (float): If not None, there will be a pause of a specified time before highlighting the next state in the path. clear (bool): Clear the highlighting of a state after it was highlighted. Only works if delay is not None.
This is particularly useful for highlighting paths with loops.
- export(output_format: str, filename: str = 'export') None¶
Export the visualization to your preferred output format. The appropriate file extension will be added automatically.
- Parameters:
output_format (str): Desired export format. filename (str): Base name for the exported file.
Supported output formats (not case-sensitive):
“HTML” → An interactive .html file (e.g., draggable nodes) “IFrame” → Exports as an <iframe> wrapped HTML in a .html file “PDF” → Exports to .pdf (via conversion from SVG) “SVG” → Exports to .svg vector image
- class stormvogel.visualization.MplVisualization(model: stormvogel.model.Model, layout: stormvogel.layout.Layout = stormvogel.layout.DEFAULT(), result: stormvogel.result.Result | None = None, scheduler: stormvogel.result.Scheduler | None = None, title: str | None = None, interactive: bool = False, hover_node: collections.abc.Callable[[matplotlib.collections.PathCollection, matplotlib.collections.PathCollection, matplotlib.backend_bases.MouseEvent, matplotlib.axes.Axes], None] | None = None)¶
Bases:
VisualizationBaseMatplotlib-based visualization for Stormvogel models.
Extends the base visualization class to render the model, results, and scheduler using Matplotlib. Supports interactive features like node highlighting and custom hover behavior.
This class manages figure creation, state and edge highlighting, and optionally allows interaction callbacks when hovering over nodes.
- Args:
model (stormvogel.model.Model): The model to visualize. layout (stormvogel.layout.Layout, optional): Layout configuration for
the visualization. Defaults to stormvogel.layout.DEFAULT().
- result (stormvogel.result.Result | None, optional): The result of a model
checking operation, which may contain a scheduler. Defaults to None.
- scheduler (stormvogel.result.Scheduler | None, optional): Explicit scheduler
defining actions to take in each state. Defaults to None.
title (str | None, optional): Title of the visualization figure. Defaults to None. interactive (bool, optional): Whether to enable interactive features such
as node hover callbacks. Defaults to False.
- hover_node (Callable | None, optional): Callback function invoked when
hovering over nodes. Receives parameters (PathCollection, PathCollection, MouseEvent, Axes). Defaults to None.
- title = ''¶
- interactive = False¶
- hover_node = None¶
- _highlights: dict[int, str]¶
- _edge_highlights: dict[tuple[int, int], str]¶
- _fig = None¶
- highlight_state(state: stormvogel.model.State | int, color: str = 'red') None¶
Highlights a state node in the visualization by setting its color.
- Args:
state (stormvogel.model.State | int): The state object or state ID to highlight. color (str, optional): The color to apply. Defaults to “red”.
- Raises:
AssertionError: If the state node is not present in the model graph.
- highlight_action(state: stormvogel.model.State | int, action: stormvogel.model.Action, color: str = 'red') None¶
Highlights an action node associated with a state by setting its color.
- Args:
state (stormvogel.model.State | int): The state object or state ID from which the action originates. action (stormvogel.model.Action): The action to highlight. color (str, optional): The color to apply. Defaults to “red”.
- Raises:
AssertionError: If the state node is not present in the model graph.
- highlight_edge(from_: int, to_: int, color: str = 'red') None¶
Highlights an edge between two nodes by setting its color.
- clear_highlighting() None¶
Clear all nodes that are marked for highlighting in the visualization
- highlight_scheduler(scheduler: stormvogel.result.Scheduler) None¶
Highlights states, actions, and edges according to the given scheduler.
Applies a specific highlight color defined by the layout to all states and actions specified by the scheduler’s taken actions, as well as the edges connecting them. The color is derived from the layout’s configured group colors for scheduled actions.
- Args:
- scheduler (stormvogel.result.Scheduler): The scheduler containing
state-action mappings to highlight.
- add_to_ax(ax, node_size: int | dict[int, int] = 300, node_kwargs: dict[str, Any] | None = None, edge_kwargs: dict[str, Any] | None = None) tuple[Any, Any]¶
Draws the model graph onto a given Matplotlib Axes.
This method renders nodes and edges of the model graph on the provided Matplotlib ax object. It uses layout positions, colors from the current layout configuration, and any highlights applied to nodes or edges. Node sizes can be specified either as a fixed integer or as a dictionary mapping node IDs to sizes.
- Args:
ax (matplotlib.axes.Axes): The Matplotlib axes to draw the graph on. node_size (int or dict[int, int], optional): Size(s) of nodes. If an
int is given, all nodes are drawn with that size. If a dictionary, it must provide sizes for all nodes. Defaults to 300.
- node_kwargs (dict[str, Any], optional): Additional keyword arguments
passed to nx.draw_networkx_nodes(). Defaults to None.
- edge_kwargs (dict[str, Any], optional): Additional keyword arguments
passed to nx.draw_networkx_edges(). Defaults to None.
- Returns:
- tuple: A tuple (nodes, edges) where nodes is the
matplotlib.collections.PathCollection of drawn nodes and edges is the matplotlib.collections.LineCollection of drawn edges.
- update(node_size: int | dict[int, int] = 300, node_kwargs: dict[str, Any] | None = None, edge_kwargs: dict[str, Any] | None = None)¶
Updates or creates the Matplotlib figure displaying the model graph.
This method sets up the figure size based on layout settings, draws the graph nodes and edges using add_to_ax, and applies highlights and titles. If interactive is enabled, it connects a hover event handler to update the plot title dynamically when the mouse moves over nodes.
- Args:
- node_size (int or Sequence[int], optional): Size(s) for the nodes. Can be
a single integer or a sequence of sizes for each node. Defaults to 300.
- node_kwargs (dict[str, Any], optional): Additional keyword arguments
passed to nx.draw_networkx_nodes(). Defaults to None.
- edge_kwargs (dict[str, Any], optional): Additional keyword arguments
passed to nx.draw_networkx_edges(). Defaults to None.
- Returns:
matplotlib.figure.Figure: The Matplotlib figure object containing the visualization.
- show() None¶