|
| 1 | +"""Plotly backend interface for visualization.""" |
| 2 | +from ansys.tools.visualization_interface.backends._base import BaseBackend |
| 3 | +from ansys.tools.visualization_interface.types.mesh_object_plot import MeshObjectPlot |
| 4 | +import plotly.graph_objects as go |
| 5 | +from pyvista import PolyData |
| 6 | +from typing import Union, Iterable, Any |
| 7 | + |
| 8 | + |
| 9 | +class PlotlyInterface(BaseBackend): |
| 10 | + """Plotly interface for visualization.""" |
| 11 | + |
| 12 | + def __init__(self, **kwargs): |
| 13 | + self._fig = go.Figure() |
| 14 | + |
| 15 | + def _pv_to_mesh3d(self, pv_mesh: PolyData) -> go.Mesh3d: |
| 16 | + """Convert a PyVista PolyData mesh to Plotly Mesh3d format.""" |
| 17 | + points = pv_mesh.points |
| 18 | + x, y, z = points[:, 0], points[:, 1], points[:, 2] |
| 19 | + |
| 20 | + faces = pv_mesh.faces.reshape((-1, 4)) # First number in each row is the number of points in the face (3 for triangles) |
| 21 | + i, j, k = faces[:, 1], faces[:, 2], faces[:, 3] |
| 22 | + |
| 23 | + return go.Mesh3d(x=x, y=y, z=z, i=i, j=j, k=k) |
| 24 | + @property |
| 25 | + def layout(self) -> Any: |
| 26 | + """Get the current layout of the Plotly figure.""" |
| 27 | + return self._fig.layout |
| 28 | + |
| 29 | + @setters.layout |
| 30 | + def layout(self, new_layout: Any): |
| 31 | + """Set a new layout for the Plotly figure.""" |
| 32 | + self._fig.update_layout(new_layout) |
| 33 | + |
| 34 | + def plot_iter(self, plotting_list): |
| 35 | + """Plot multiple objects using Plotly.""" |
| 36 | + for item in plotting_list: |
| 37 | + self.plot(item) |
| 38 | + |
| 39 | + |
| 40 | + def plot(self, plottable_object: Union[PolyData, MeshObjectPlot, go.Mesh3d], **plotting_options): |
| 41 | + """Plot a single object using Plotly.""" |
| 42 | + if isinstance(plottable_object, PolyData): |
| 43 | + mesh = self._pv_to_mesh3d(plottable_object) |
| 44 | + self._fig.add_trace(mesh) |
| 45 | + elif isinstance(plottable_object, MeshObjectPlot): |
| 46 | + pv_mesh = plottable_object.mesh |
| 47 | + mesh = self._pv_to_mesh3d(pv_mesh) |
| 48 | + self._fig.add_trace(mesh) |
| 49 | + elif isinstance(plottable_object, go.Mesh3d): |
| 50 | + self._fig.add_trace(plottable_object) |
| 51 | + else: |
| 52 | + try: |
| 53 | + self._fig.add_trace(plottable_object) |
| 54 | + except Exception: |
| 55 | + raise TypeError("Unsupported plottable_object type for PlotlyInterface.") |
| 56 | + |
| 57 | + def show(self): |
| 58 | + """Render the Plotly scene.""" |
| 59 | + self._fig.show() |
0 commit comments