Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/changelog.d/237.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Update_variables no longer rebuilds the frontend and add sim example notebook
345 changes: 345 additions & 0 deletions examples/notebooks/warp_fluid_update_variables.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,345 @@
{
"cells": [
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": [
"########################################################################\n",
"# Fluid Simulation Example - Update Variables\n",
"#\n",
"# Use Visor to visualize a fluid simulation, and update the\n",
"# variables in Visor as the simulation progresses.\n",
"#\n",
"# Dependency: This example requires the Warp library, which is not\n",
"# included in the Visor package.\n",
"# > pip install warp-lang[examples]\n",
"#\n",
"# We use the warp fluid simulation example:\n",
"# https://github.com/NVIDIA/warp/blob/main/warp/examples/core/example_fluid.py\n",
"#########################################################################\n",
"import asyncio\n",
"\n",
"import numpy as np\n",
"import warp as wp\n",
"from IPython.display import IFrame\n",
"from vtk import vtkHDFWriter, vtkPlaneSource, vtkPolyData\n",
"from vtk.util.numpy_support import numpy_to_vtk\n",
"from warp.examples.core import example_fluid\n",
"from warp.examples.core.example_fluid import Example\n",
"\n",
"from ansys.visor.viewer import Metadata, Visor\n",
"\n",
"wp.ScopedTimer.enabled = False\n",
"\n",
"w = example_fluid.grid_width\n",
"h = example_fluid.grid_height\n",
"VTKHDF_FILE_PATH = \"warp_fluid_sim.vtkhdf\""
],
"id": "b355a718167c2bf0"
},
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": [
"########################################################################\n",
"# Sim data + VTK dataset configuration\n",
"########################################################################\n",
"\n",
"def point_arrays(sim):\n",
" \"\"\" Return a dict of the fluid fields from the warp simulation, ordered for VTK point arrays.\"\"\"\n",
" density = sim.rho0.numpy().T.ravel()\n",
" pressure = sim.p0.numpy().T.ravel()\n",
" velocity = sim.u0.numpy().transpose(1, 0, 2).reshape(-1, 2)\n",
" velocity3 = np.column_stack([velocity, np.zeros(len(velocity), np.float32)])\n",
" return {\"density\": density, \"pressure\": pressure, \"velocity\": velocity3}\n",
"\n",
"def create_grid():\n",
" \"\"\"Create a quad mesh, of size w x h with one point per fluid cell.\"\"\"\n",
" plane = vtkPlaneSource()\n",
" plane.SetOrigin(0, 0, 0)\n",
" plane.SetPoint1(w-1, 0, 0)\n",
" plane.SetPoint2(0, h-1, 0)\n",
" plane.SetResolution(w-1, h-1)\n",
" plane.Update()\n",
" polydata = vtkPolyData()\n",
" polydata.DeepCopy(plane.GetOutput())\n",
" # Remove the default arrays so we only have the simulation's variables\n",
" for name in (\"Normals\", \"TextureCoordinates\"):\n",
" polydata.GetPointData().RemoveArray(name)\n",
" return polydata\n",
"\n",
"def add_arrays_to_dataset(dataset, arrays):\n",
" \"\"\"Add point arrays on a VTK dataset\"\"\"\n",
" for name, values in arrays.items():\n",
" # Create a vtkDataArray from the numpy array\n",
" array = numpy_to_vtk(np.ascontiguousarray(values, dtype=np.float32), deep=True)\n",
" array.SetName(name)\n",
" dataset.GetPointData().AddArray(array)\n",
"\n",
"def write_vtkhdf(dataset, file_path):\n",
" \"\"\"Writes a VTK dataset to disk as VTKHDF.\"\"\"\n",
" writer = vtkHDFWriter()\n",
" writer.SetInputData(dataset)\n",
" writer.SetFileName(file_path)\n",
" if not writer.Write():\n",
" raise RuntimeError(f\"vtkHDFWriter failed for {file_path}\")\n",
"\n",
"def create_dataset_and_write_to_disk(sim):\n",
" \"\"\"Creates a VTK dataset, adds arrays from the sim, and writes the dataset to disk.\"\"\"\n",
" polydata = create_grid()\n",
" arrays = point_arrays(sim)\n",
" add_arrays_to_dataset(polydata, arrays)\n",
" write_vtkhdf(polydata, VTKHDF_FILE_PATH)\n",
"\n",
"########################################################################\n",
"# Visor configuration\n",
"########################################################################\n",
"\n",
"def set_up_metadata(variable_id=\"POINT::velocity::3\"):\n",
" \"\"\"Set up metadata for the dataset in Visor.\n",
" \n",
" This is optional; here, it automatically colors by the specified variable\n",
" instead of having to set it manually in the browser.\n",
"\n",
" Variables available here:\n",
" POINT::density::1\n",
" POINT::pressure::1\n",
" POINT::velocity::3\n",
" \"\"\"\n",
" metadata = Metadata(\n",
" name=\"fluid_simulation\",\n",
" unit=\"\",\n",
" state={\n",
" \"parts\": {\n",
" \"fluid_simulation\": {\n",
" \"selected\": \"true\", # selecting the part displays the legend by default\n",
" \"color_by\": variable_id, # POINT/CELL :: name :: num_components\n",
" \"color_by_component\": -1, # -1 is magnitude\n",
" }\n",
" }\n",
" }\n",
" )\n",
" return metadata\n",
"\n",
"def configure_visor(port, variable_to_display, mode=\"CLIENT\"):\n",
" \"\"\"Instantiate VISOR, start with the VTK dataset file path, and get the dataset's part variables.\"\"\"\n",
" visor = Visor(rendering_mode=mode, url=f\"http://localhost:{port}\")\n",
" metadata = set_up_metadata(variable_to_display)\n",
" dataset_id = visor.start(input=VTKHDF_FILE_PATH, metadata=metadata)\n",
" part_variables = visor.list_variables(dataset_id)[0]\n",
" return visor, dataset_id, part_variables\n",
"\n",
"def get_update_dict(dataset_id, variable, new_data):\n",
" \"\"\"Create a dictionary to pass to Visor's update_variables API.\"\"\"\n",
" update_dict = {\n",
" \"type\": variable.type,\n",
" \"name\": variable.name,\n",
" \"num_components\": variable.num_components,\n",
" \"data\": new_data\n",
" }\n",
" return update_dict\n",
"\n",
"def update_variables(visor, dataset_id, part_variables, arrays):\n",
" \"\"\"Update the Visor dataset to display the new variable data.\"\"\"\n",
" update_dicts = []\n",
" for variable in part_variables.variables:\n",
" update_dicts.append(get_update_dict(dataset_id, variable, arrays.get(variable.name)))\n",
" visor.update_variables(dataset_id, update_dicts)\n"
],
"id": "7a9aa1fe1b996ae0"
},
{
"cell_type": "code",
"execution_count": 3,
"id": "fe1f8e393ff128e5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Warp 1.19.0 initialized:\n",
" CUDA Toolkit 13.4, Driver 13.0\n",
" Devices:\n",
" \"cpu\" : \"Intel64 Family 6 Model 183 Stepping 1, GenuineIntel\"\n",
" \"cuda:0\" : \"NVIDIA RTX 5000 Ada Generation Laptop GPU\" (16 GiB, sm_89, mempool enabled)\n",
" Kernel cache:\n",
" \\\\?\\C:\\Users\\lkasian\\AppData\\Local\\NVIDIA\\warp\\Cache\\1.19.0\n"
]
}
],
"source": [
"# Initialize the simulation, and run 60 steps, from which\n",
"# to create the VTK dataset and write to disk as VTKHDF.\n",
"sim = Example()\n",
"for _ in range(100):\n",
" sim.step()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "83f244d00271089f",
"metadata": {},
"outputs": [],
"source": [
"# Create a plane, add the data from the initial sim pass as data arrays, and save to disk as vtkhdf.\n",
"create_dataset_and_write_to_disk(sim)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "3bbbf65dea57f293",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Server starting...\n",
"Server started and ready on http://localhost:8081\n",
"Server starting...\n",
"Server started and ready on http://localhost:8082\n"
]
}
],
"source": [
"# Instantiate VISOR, start it with the dataset, and get its variable info\n",
"# \n",
"# Optional: update more than one VISOR instance e.g. to view more than one variable at once.\n",
"# In this example: Visor instance 1 by default displays the density\n",
"# Visor instance 2 by default displays the pressure.\n",
"visor1, dataset_id1, variables1 = configure_visor(port=8081, variable_to_display=\"POINT::density::1\")\n",
"visor2, dataset_id2, variables2 = configure_visor(port=8082, variable_to_display=\"POINT::pressure::1\")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "d331c5d1ed65e2aa",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
" <iframe\n",
" width=\"800\"\n",
" height=\"400\"\n",
" src=\"http://localhost:8081\"\n",
" frameborder=\"0\"\n",
" allowfullscreen\n",
" \n",
" ></iframe>\n",
" "
],
"text/plain": [
"<IPython.lib.display.IFrame at 0x277b5b9b860>"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"IFrame(src=\"http://localhost:8081\", width=800, height=400)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "ff7ba5d2ee222f0",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
" <iframe\n",
" width=\"800\"\n",
" height=\"400\"\n",
" src=\"http://localhost:8082\"\n",
" frameborder=\"0\"\n",
" allowfullscreen\n",
" \n",
" ></iframe>\n",
" "
],
"text/plain": [
"<IPython.lib.display.IFrame at 0x2779b1ea780>"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"IFrame(src=\"http://localhost:8082\", width=800, height=400)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "965612190dd9a1f4",
"metadata": {},
"outputs": [
{
"ename": "CancelledError",
"evalue": "",
"output_type": "error",
"traceback": [
"\u001B[31m---------------------------------------------------------------------------\u001B[39m",
"\u001B[31mCancelledError\u001B[39m Traceback (most recent call last)",
"\u001B[36mCell\u001B[39m\u001B[36m \u001B[39m\u001B[32mIn[8]\u001B[39m\u001B[32m, line 6\u001B[39m\n\u001B[32m 2\u001B[39m sim.step()\n\u001B[32m 3\u001B[39m arrays = point_arrays(sim)\n\u001B[32m 4\u001B[39m update_variables(visor1, dataset_id1, variables1, arrays)\n\u001B[32m 5\u001B[39m update_variables(visor2, dataset_id2, variables2, arrays)\n\u001B[32m----> \u001B[39m\u001B[32m6\u001B[39m \u001B[38;5;28;01mawait\u001B[39;00m asyncio.sleep(\u001B[32m0.4\u001B[39m)\n",
"\u001B[36mFile \u001B[39m\u001B[32m~\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\asyncio\\tasks.py:665\u001B[39m, in \u001B[36msleep\u001B[39m\u001B[34m(delay, result)\u001B[39m\n\u001B[32m 661\u001B[39m h = loop.call_later(delay,\n\u001B[32m 662\u001B[39m futures._set_result_unless_cancelled,\n\u001B[32m 663\u001B[39m future, result)\n\u001B[32m 664\u001B[39m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[32m--> \u001B[39m\u001B[32m665\u001B[39m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;01mawait\u001B[39;00m future\n\u001B[32m 666\u001B[39m \u001B[38;5;28;01mfinally\u001B[39;00m:\n\u001B[32m 667\u001B[39m h.cancel()\n",
"\u001B[31mCancelledError\u001B[39m: "
]
}
],
"source": [
"for _ in range(200):\n",
" sim.step()\n",
" arrays = point_arrays(sim)\n",
" update_variables(visor1, dataset_id1, variables1, arrays)\n",
" update_variables(visor2, dataset_id2, variables2, arrays)\n",
" await asyncio.sleep(0.4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9a0592bead7305e4",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
5 changes: 5 additions & 0 deletions src/ansys/visor/viewer/app/paraview/visor_vtk_paraview.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,17 @@ def _initialize_rendering(self, standalone: bool, trame_log_dir: str | None) ->
set_dark_mode=self._scene.set_dark_mode,
rca_window=self._scene.rca_window,
bridge=bridge,
get_variable_records_json=self._scene.get_variable_records_json,
)

def _post_scene_change_hook(self) -> None:
"""Bump scene_version so connected clients rebuild; requests no frame, the operation already did."""
self._state_publisher.bump_scene_version()

def _post_data_change_hook(self) -> None:
"""Bump data_version so connected clients refresh in place; requests no frame, the operation already did."""
self._state_publisher.bump_data_version()

def update_variables(self, dataset_id: int, variables: list[dict[str, Any]]) -> None:
"""Raise UnsupportedInModeError: pvserver holds its own copy of the arrays."""
raise UnsupportedInModeError("update_variables is not supported in PARAVIEW mode")
2 changes: 2 additions & 0 deletions src/ansys/visor/viewer/app/trame/local_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ def __init__(
trame_logger: Logger | None = None,
scene_mutation_api: LocalSceneMutationApi | None = None,
*,
get_variable_records_json: Callable[[], str],
pick_geometry_in_view: Callable[[PickView, int, int, str], GeometryPick],
pick_part_in_view: Callable[[PickView, int, int], int | None],
):
Expand All @@ -70,6 +71,7 @@ def __init__(
standalone=standalone,
trame_logger=trame_logger,
scene_mutation_api=scene_mutation_api,
get_variable_records_json=get_variable_records_json,
)

@property
Expand Down
Loading
Loading