VISOR Product Instance Manager#
Feature highlight#
Visual Interactive Simulation Object Renderer (VISOR) is a 3D visualization web component for Ansys solutions and apps.
This example shows how to create a product instance manager for VISOR using SAF. The product instance manager enables management of the VISOR product instance lifecycle, including starting, stopping, and interacting with the instance.
In this example, you learn how to:
Start a product instance from a long-running transaction decorated with
@create_instance.Reuse the running instance in other transaction methods through the
@instancedecorator.Display the VISOR viewer in an isolated iframe using the current instance host and port.
Interact with the viewer to display 3D scenes.
Publish progress on named event streams with
transaction.raise_event.Wire one callback per button and use event listeners to refresh the console logs and the notifications.
Prerequisites#
Note
To work with a VISOR product instance, be sure to install the core-pim
and instance-management-visor extras from the ansys-saf-sdk package.
You can do this by manually editing your pyproject.toml.
The VISOR Dash viewer also requires the ansys-visor-viewer package:
ansys-saf-sdk = {version = "^0.3.0", extras = ["core-pim", "instance-management-visor"]}
ansys-visor-viewer = "^1.0.1"
This will install everything needed to control the VISOR product instance and viewer. This example uses PIM as the product instance management system.
Coding#
To create a product instance manager for VISOR and interact with it, work through the following sequence of sections.
Backend#
Create the solution definition.
Key concept — Product instance manager
A product instance manager wraps a running Ansys product session. The
@create_instance decorator starts the product and binds the session to a name,
while the @instance decorator injects that same session into any other
transaction method.
Key concept — Instance lifecycle
A product instance outlives the transaction method that created it. It stays available to every transaction method of the solution until a transaction explicitly shuts it down.
Key concept — Event streams
A transaction method reports progress with self.transaction.raise_event.
Each event is published on a named stream, so the frontend can react while
the transaction is still running.
Key concept — Termination event
Passing enable_termination_event=True to @transaction makes SAF
automatically raise a structured MethodState event on a stream
named after the transaction once it completes or fails, so the frontend
can track its outcome without parsing log text. The persisted state can
also be read at any time with step.get_long_running_method_state(transaction_name).
Define the step fields
The step stores the VISOR version. visor_started tracks whether an instance is running.
Finally, it stores the host and port reported by the product manager for the running instance.
Note
To understand why the VISOR version is 0, refer to the Supported product instance managers page.
Define the step model
The
start_visorlong-running transaction is decorated with@create_instanceto create an instance of the VISOR product manager. It initializes VISOR, stores the current host and port, marks the instance as started, and emits progress messages.show_piston,show_spheres, andshow_elboware decorated with@instanceto reuse the running instance. Each transaction resolves its geometry asset through BDM and sends the cached path to VISOR with aMetadatavalue.shutdown_visoris decorated with@instanceto reuse and shut down the running instance. It also setsvisor_startedtoFalse.
Add VISOR geometry as method assets
Geometry files used by transaction methods are stored as method assets in
the solution’s method_assets directory. In this example, the assets are
organized as follows:
examples/src/saf/solutions/examples/solution/
└── method_assets/
└── visor_shapes/
├── piston_rod.vtkhdf
├── elbow-2-00005.vtkhdf
├── vtk_scene_sphere_l2_b3_r32_v3_c1_z3.vtm
└── vtk_scene_sphere_l2_b3_r32_v3_c1_z3/
├── vtk_scene_sphere_l2_b3_r32_v3_c1_z3_0.vtp
├── ...
└── vtk_scene_sphere_l2_b3_r32_v3_c1_z3_8.vtp
VISOR accepts as input geometry files .vtu, .vtp, .vtm, and .vtkhdf formats.
You can visualize results of other tools (e.g. Fluent) with VISOR, some might need to be converted to a valid format as they don’t use any of the formats above as their output format.
A transaction method gets an asset handle using the path relative to
method_assets and resolves it to a local path for the product instance:
get_cached makes the asset available at a path that can be
passed to VISOR and preserves any sidecar files required by a multiblock
scene.
Note
The assets used in the example were chosen to demonstrate different capabilities of VISOR. Moreover, different formats were used to show how they are used. You can explore the different shapes in the example solution to understand what is possible.
Frontend#
Expose the solution definition in the UI.
Key concept — Callback
A callback is a Dash-decorated function that fires in response to a UI
event. In a SAF solution, callbacks reach the backend through
project.steps.<step_name>, read or write fields, and invoke transaction methods.
No manual HTTP calls are needed.
Key concept — Event listener
DashClient.create_event_listener subscribes a component to a backend
event stream raised by the backend. Each message received by the listener
triggers a callback, so the console logs, the button states, and the notifications
stay in sync with the running transaction.
Register the VISOR viewer endpoints
The VISOR package provides the JavaScript, CSS, theme, and font endpoints
used by the iframe. Register them on the Dash server before the UI starts.
GLOW_UI_PATH_PREFIX is passed to both endpoint registration and the
iframe so the viewer also works when the UI is mounted below a URL prefix.
import os
from visordash import init_endpoints
VISOR_BASE_PATH = os.getenv("GLOW_UI_PATH_PREFIX", "/").rstrip("/")
init_endpoints(app, base_path=VISOR_BASE_PATH)
These endpoints must remain registered even though the viewer itself is
created in visor_instance_page.py.
Create the isolated viewer
_create_visor_viewer creates an html.Iframe with a complete
srcDoc document. It serializes the current VISOR host, port, and base
path into window.__visorArgs. The document loads the Visordash CSS and
JavaScript assets and creates its own VisorContainer element. The host
and port come from the persisted step fields, so the iframe connects to the
instance currently managed by the backend.
The iframe is kept separate from the rest of the Dash page. Its document owns the viewer DOM and runtime, while the parent page remains responsible for the controls, notifications, and logs.
Warning
Don’t forget to redefine VISOR_BASE_PATH = os.getenv("GLOW_UI_PATH_PREFIX", "/").rstrip("/")
in this file.
def _create_visor_viewer(host: str, port: int) -> Any:
"""Create an isolated viewer document connected to the local Visor instance."""
viewer_args = json.dumps(
{
"host": host,
"port": port,
"basePath": VISOR_BASE_PATH,
}
).replace("<", "\\u003c")
asset_prefix = VISOR_BASE_PATH or ""
src_doc = f"""<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{asset_prefix}/visordash/css.css">
</head>
<body style="margin: 0; width: 100vw; height: 100vh; overflow: hidden;">
<div id="VisorContainer" style="width: 100%; height: 100%;"></div>
<script>window.__visorArgs = {viewer_args};</script>
<script type="module" src="{asset_prefix}/visordash/js.js"></script>
</body>
</html>"""
return html.Iframe(
id="visor-viewer-component",
srcDoc=src_doc,
title="VISOR viewer",
style={
"width": "100%",
"height": "100%",
"border": "0",
"display": "block",
},
)
Define the step layout
The layout is split between 3 main parts:
controls_card: Where the buttons to interact with VISOR are located.logs_card: Where the VISOR output logs are displayed.viewer_card: Where the isolated viewer iframe is mounted.
First, the method calls _create_visor_viewer if the viewer is not already initialized.
Then, we define the 3 parts of the layout:
The controls card contains:
Buttons to start and shutdown the VISOR instance.
Show Piston rod, Show Spheres, and Show Elbow buttons to load example shapes into VISOR.
The logs card displays VISOR output and provides a clear-logs action.
The viewer card is placed below the controls and logs and fills the available width.
After defining these components, we return the html.Div linking them together.
The controls and logs use responsive grid spans: they stack at
smaller widths and use 3/9 columns at the lg breakpoint and above.
Finally, the event listeners are created directly in the layout instead of through
a separate mount_event_listeners callback:
output-listenersubscribes tovisor-output-streamand receives human-readable messages such as initialization, geometry loading, and shutdown progress.start-visor-listenersubscribes tostart-visorand receives the structured termination event for the long-running startup transaction.
The startup listener is used by both the control-state callback and the viewer-display callback.
def layout(project: ExamplesSolution) -> html.Div:
"""Layout for the VISOR Instance Manager page."""
step = project.steps.visor_step
viewer: Any = []
if step.visor_started:
if not step.visor_host or step.visor_port is None:
raise RuntimeError("VISOR is marked as running without a host and port.")
viewer = _create_visor_viewer(step.visor_host, step.visor_port)
controls_card = dmc.Card(
[
dmc.CardSection(
dmc.Group(
children=[
dmc.Text("Controls", fw=500, style={"font-size": "17px"}),
],
justify="space-between",
),
withBorder=True,
inheritPadding=True,
py="xs",
),
dmc.Space(h=20),
dmc.Group(
[
dmc.Tooltip(
dmc.ActionIcon(
DashIconify(icon="streamline:startup-solid", width=30),
id="start-visor-button",
size="xl",
color="#2790F1",
disabled=step.visor_started,
loading=False,
),
label="Start Visor",
position="top",
),
dmc.Tooltip(
dmc.ActionIcon(
DashIconify(icon="mdi:shutdown", width=30),
id="stop-visor-button",
size="xl",
color="#2790F1",
disabled=not step.visor_started,
),
label="Stop Visor",
position="top",
),
],
gap="md",
justify="center",
),
dmc.Space(h=20),
dmc.Divider(variant="solid"),
dmc.Space(h=20),
dmc.Stack(
[
dmc.Button(
"Show Piston rod",
id="show-visor-piston-button",
variant="filled",
color="#2790F1",
leftSection=DashIconify(icon="mdi:eye"),
disabled=not step.visor_started,
style={"width": "70%", "font-size": "15px"},
),
dmc.Button(
"Show Spheres",
id="show-visor-spheres-button",
variant="filled",
color="#2790F1",
leftSection=DashIconify(icon="mdi:eye"),
disabled=not step.visor_started,
style={"width": "70%", "font-size": "15px"},
),
dmc.Button(
"Show Elbow",
id="show-visor-elbow-button",
variant="filled",
color="#2790F1",
leftSection=DashIconify(icon="mdi:eye"),
disabled=not step.visor_started,
style={"width": "70%", "font-size": "15px"},
),
],
align="center",
),
],
withBorder=True,
shadow="sm",
radius="md",
)
logs_container = dmc.Card(
[
dmc.CardSection(
dmc.Group(
children=[
dmc.Text("Logs", fw=500, style={"font-size": "17px"}),
dmc.Tooltip(
dmc.ActionIcon(
DashIconify(icon="mdi:delete-sweep", width=24),
id="clear-logs-button",
color="gray",
variant="transparent",
),
label="Clear Logs",
position="left",
),
],
justify="space-between",
),
withBorder=True,
inheritPadding=True,
py="xs",
),
dmc.Space(h=20),
html.Div(
html.Pre(
id="visor-console-logs",
style={
"whiteSpace": "pre-wrap",
"wordBreak": "break-all",
"fontSize": "14px",
"height": "100%",
"overflowY": "auto",
"margin": "0",
},
),
style={
"height": "220px",
"width": "100%",
},
),
],
withBorder=True,
shadow="sm",
radius="md",
)
visor_viewer_container = dmc.Card(
[
dmc.CardSection(
dmc.Text("Viewer", fw=500, style={"font-size": "17px"}),
withBorder=True,
inheritPadding=True,
py="xs",
),
html.Div(
viewer,
id="visor-viewer-container",
style={
"width": "100%",
"height": "calc(100vh - 240px)",
"minHeight": "0",
"overflow": "hidden",
},
),
],
withBorder=True,
shadow="sm",
radius="md",
)
return html.Div(
[
html.H1(
"VISOR Instance Manager",
className="display-3",
style={"font-size": "40px", "font-weight": "bold"},
),
dmc.Blockquote(
'This example demonstrates how to leverage the instance management API to control VISOR.\
Click the Launch action button to\
start the instance. A transaction method will start VISOR which can be used across all transaction\
methods of the solution. Run VISOR operations with the "Show" buttons. The models used in this\
example are selected to represent different capabilities of VISOR, do not hesitate to play with\
them to test the possibilities. Close VISOR using the Shutdown button.',
icon=DashIconify(icon="material-symbols:info", width=30),
style={"font-size": "18px", "fontStyle": "italic"},
),
dmc.Space(h=20),
dmc.Grid(
[
dmc.GridCol(
controls_card,
span={"base": 12, "lg": 3},
),
dmc.GridCol(
logs_container,
span={"base": 12, "lg": 9},
),
dmc.GridCol(
visor_viewer_container,
span=12,
),
],
grow=True,
gutter="xs",
),
DashClient.create_event_listener( # pyright: ignore[reportUnknownMemberType]
step, id="output-listener", stream_name="visor-output-stream"
),
DashClient.create_event_listener( # pyright: ignore[reportUnknownMemberType]
step, id="start-visor-listener", stream_name="start-visor"
),
],
style={"paddingLeft": "20px"},
)
Start VISOR from the launch action
When the start action is clicked, start_visor calls the backend
transaction and immediately shows a loading notification. The start button
is disabled and its loading spinner replaces the rocket icon while the
long-running transaction executes.
@callback(
Output("notification-container", "sendNotifications", allow_duplicate=True),
Output("start-visor-button", "disabled", allow_duplicate=True),
Output("start-visor-button", "loading", allow_duplicate=True),
Input("start-visor-button", "n_clicks"),
State("url", "pathname"),
prevent_initial_call=True,
)
def start_visor(n_clicks: int, project: ExamplesSolution) -> tuple[list[dict[str, Any]] | str, bool, bool]:
"""Initialize the VISOR instance."""
if not n_clicks:
return no_update, no_update, no_update # No update to notification, start button disabled, start button loading
step = project.steps.visor_step
step.start_visor()
return (
[ # Notification
dict(
title="Info",
id="start-visor-notification",
action="show",
message="Starting VISOR instance... Please wait.",
autoClose=False,
loading=True,
color="blue",
withCloseButton=False,
)
],
True, # disable_launch_button
True, # loading_launch_button
)
Synchronize startup controls and notifications
sync_start_controls_on_backend_event parses the structured
MethodState event from the start-visor listener.
Here is the status of different actions based on the startup state:
Case |
Start VISOR |
Stop VISOR |
Show geometry |
Start loading |
Notification |
|---|---|---|---|---|---|
Startup running |
❌ |
❌ |
❌ |
Yes |
Loading |
Startup success |
❌ |
✅ |
✅ |
No |
Success |
Startup failure |
✅ |
❌ |
❌ |
No |
Failure |
The shared handle_method_event helper replaces the loading notification with a success
or failure notification.
@callback(
Output("notification-container", "sendNotifications", allow_duplicate=True),
Output("start-visor-button", "disabled", allow_duplicate=True),
Output("start-visor-button", "loading", allow_duplicate=True),
Output("stop-visor-button", "disabled", allow_duplicate=True),
Output("show-visor-piston-button", "disabled", allow_duplicate=True),
Output("show-visor-spheres-button", "disabled", allow_duplicate=True),
Output("show-visor-elbow-button", "disabled", allow_duplicate=True),
Input("start-visor-listener", "message"),
prevent_initial_call=True,
)
def sync_start_controls_on_backend_event(
message: dict[str, Any] | None,
) -> tuple[list[dict[str, Any]] | Any, bool, bool, bool, bool, bool, bool]:
"""Update the Visor controls and notification after startup completes."""
if not message:
return no_update, no_update, no_update, no_update, no_update, no_update, no_update
method_state = MethodState.model_validate_json(message["data"])
notification = handle_method_event(
method_state,
"start-visor-notification",
"VISOR instance launched successfully!",
"VISOR initialization failed. Please check the logs.",
)
if method_state.status.value == "completed":
return notification, True, False, False, False, False, False
if method_state.status.value == "failed":
return notification, False, False, True, True, True, True
return notification, True, True, True, True, True, True
def handle_method_event(
method_state: MethodState,
notification_id: str,
success_msg: str,
error_msg: str,
success_auto_close: int | bool = 5000,
error_auto_close: int | bool = False,
) -> list[dict[str, Any]]:
"""Process a backend method event and update controls/notification accordingly.
Parameters
----------
method_state : MethodState
The state of the backend method.
notification_id : str
The ID of the notification to update.
success_msg : str
The message to display if the method completed successfully.
error_msg : str
The message to display if the method failed.
success_auto_close : int | bool, optional
Time in milliseconds after which the success notification should auto-close,
or False to disable auto-close. Default is 5000 (5 seconds).
error_auto_close : int | bool, optional
Time in milliseconds after which the error notification should auto-close,
or False to disable auto-close. Default is False (no auto-close).
"""
notification = no_update
if method_state.status.value == "completed":
notification = [
dict(
title="Success",
id=notification_id,
action="update",
message=success_msg,
color="green",
autoClose=success_auto_close,
withCloseButton=True,
loading=False,
)
]
elif method_state.status.value == "failed":
notification = [
dict(
title="Error",
id=notification_id,
action="update",
message=error_msg,
color="red",
autoClose=error_auto_close,
withCloseButton=True,
loading=False,
)
]
return notification
Display the viewer after startup
display_visor_viewer listens to the completed startup event. It reads
the persisted host and port and creates a new isolated iframe. It does not
create the viewer on a failed startup, and it raises an explicit error if a
completed transaction did not persist connection information.
@callback(
Output("visor-viewer-container", "children"),
Input("start-visor-listener", "message"),
State("url", "pathname"),
prevent_initial_call=True,
)
def display_visor_viewer(
message: dict[str, Any] | None,
project: ExamplesSolution,
) -> Any:
"""Display the Visor viewer after its start transaction completes."""
if not message:
return no_update
method_state = MethodState.model_validate_json(message["data"])
status = method_state.status.value.lower()
if status == "completed":
step = project.steps.visor_step
if not step.visor_host or step.visor_port is None:
raise RuntimeError("Visor completed without reporting its host and port.")
return [_create_visor_viewer(step.visor_host, step.visor_port)]
return no_update
Display VISOR geometry
The three geometry callbacks invoke the synchronous show_piston,
show_spheres, and show_elbow transactions. Each transaction updates
the running VISOR scene with one of the bundled assets, while its callback
displays a success notification.
@callback(
Output("notification-container", "sendNotifications", allow_duplicate=True),
Input("show-visor-piston-button", "n_clicks"),
State("url", "pathname"),
prevent_initial_call=True,
)
def show_visor_piston(n_clicks: int | None, project: ExamplesSolution) -> list[dict[str, Any]] | Any:
"""Display the piston rod in the running VISOR instance."""
if not n_clicks:
return no_update
project.steps.visor_step.show_piston()
return [
dict(
title="Success",
id="show-visor-shape-notification",
action="show",
message="Piston rod displayed in VISOR.",
color="green",
autoClose=5000,
withCloseButton=True,
)
]
@callback(
Output("notification-container", "sendNotifications", allow_duplicate=True),
Input("show-visor-spheres-button", "n_clicks"),
State("url", "pathname"),
prevent_initial_call=True,
)
def show_visor_spheres(n_clicks: int | None, project: ExamplesSolution) -> list[dict[str, Any]] | Any:
"""Display the spheres in the running VISOR instance."""
if not n_clicks:
return no_update
project.steps.visor_step.show_spheres()
return [
dict(
title="Success",
id="show-visor-spheres-notification",
action="show",
message="Spheres displayed in VISOR.",
color="green",
autoClose=5000,
withCloseButton=True,
)
]
@callback(
Output("notification-container", "sendNotifications", allow_duplicate=True),
Input("show-visor-elbow-button", "n_clicks"),
State("url", "pathname"),
prevent_initial_call=True,
)
def show_visor_elbow(n_clicks: int | None, project: ExamplesSolution) -> list[dict[str, Any]] | Any:
"""Display the elbow in the running VISOR instance."""
if not n_clicks:
return no_update
project.steps.visor_step.show_elbow()
return [
dict(
title="Success",
id="show-visor-elbow-notification",
action="show",
message="Elbow displayed in VISOR.",
color="green",
autoClose=5000,
withCloseButton=True,
)
]
Stop VISOR and clear the viewer
The shutdown callback calls shutdown_visor on the step. On success, it
displays a success notification, removes the iframe, enables Start, and
disables Stop and the geometry buttons. On failure, it displays an error
notification and leaves the existing viewer and control state unchanged.
@callback(
Output("notification-container", "sendNotifications", allow_duplicate=True),
Output("visor-viewer-container", "children", allow_duplicate=True),
Output("start-visor-button", "disabled", allow_duplicate=True),
Output("stop-visor-button", "disabled", allow_duplicate=True),
Output("show-visor-piston-button", "disabled", allow_duplicate=True),
Output("show-visor-spheres-button", "disabled", allow_duplicate=True),
Output("show-visor-elbow-button", "disabled", allow_duplicate=True),
Input("stop-visor-button", "n_clicks"),
State("url", "pathname"),
prevent_initial_call=True,
)
def shutdown_visor(
n_clicks: int, project: ExamplesSolution
) -> tuple[list[dict[str, Any]] | str, list[Any], bool, bool, bool, bool, bool]:
"""Shutdown the VISOR instance."""
notification = no_update
visor_viewer_children = no_update
disable_launch_button = no_update
disable_shutdown_button = no_update
disable_show_piston_button = no_update
disable_show_spheres_button = no_update
disable_show_elbow_button = no_update
if n_clicks:
step = project.steps.visor_step
try:
step.shutdown_visor()
notification = [
dict(
title="Success",
id="shutdown-visor-notification",
action="show",
message="Visor instance shutdown successfully.",
autoClose=5000,
color="green",
withCloseButton=True,
)
]
visor_viewer_children = []
disable_launch_button = False
disable_shutdown_button = True
disable_show_piston_button = True
disable_show_spheres_button = True
disable_show_elbow_button = True
except Exception:
notification = [
dict(
title="Error",
id="shutdown-visor-notification",
action="show",
message="Failed to shutdown Visor instance.",
autoClose=5000,
color="red",
withCloseButton=True,
)
]
return (
notification,
visor_viewer_children,
disable_launch_button,
disable_shutdown_button,
disable_show_piston_button,
disable_show_spheres_button,
disable_show_elbow_button,
)
Define the logs system
display_visor_output appends each message received on
visor-output-stream to the console log. The log panel shows messages
received during the current page session, and clear_console_logs resets
the visible log content when the clear button is clicked.
@callback(
Output("visor-console-logs", "children", allow_duplicate=True),
Input("output-listener", "message"),
State("visor-console-logs", "children"),
prevent_initial_call=True,
)
def display_visor_output(message: dict[str, Any], current_logs: str) -> str:
"""Display Visor transaction output."""
if message:
new_content = message["data"].strip('"').replace("\\n", "\n")
combined = (current_logs or "") + "\n" + new_content
return combined
return current_logs
@callback(
Output("visor-console-logs", "children"),
Input("clear-logs-button", "n_clicks"),
prevent_initial_call=True,
)
def clear_console_logs(n_clicks: int) -> str:
"""Clear the console logs."""
return ""
Now that your implementation is complete, continue to the Testing section.
Testing#
Finally, test your implementation to confirm it works as expected.
Run the solution and compare your results with the results shown in the Feature highlight section.