View#
Visualization methods for meshes, mesh and field containers as well as solid bodies. The
scenes are drawn by a plotting backend, by default by PyVista
("pyvista"). The plotting backend "webgl" draws the scenes by a WebGL viewer in
the web browser (in a self-contained HTML page), without PyVista. The plotting backend
"matplotlib" draws the scenes on the axes of a figure of matplotlib, without PyVista,
e.g. for off-screen screenshots in vector formats (PDF or SVG).
Base class for plotting a static scene. |
|
|
Provide Visualization methods for |
|
Provide Visualization methods for |
|
Provide Visualization methods for |
|
Provide Visualization methods for a XDMF file generated by |
|
Interactively select (and exclude) smooth surface patches and return their point ids. |
|
Interactively select (and exclude) smooth edge patches and return their point ids. |
Plotting Backends
|
Set the current plotting backend by its name. |
Return the name of the current plotting backend. |
|
Return the name of the plotting backend which is selected automatically by the installed optional dependencies: |
|
|
Register a plotting backend by a name. |
Base class of a plotting backend, which draws the scenes of the plot-methods, e.g. of |
|
The plotter of the plotting backend |
|
|
The plotter of the plotting backend |
Detailed API Reference
- class felupe.view.Scene[source]#
Base class for plotting a static scene.
- mesh#
A generalized Dataset with the mesh as well as point- and cell-data. This is not an instance of
felupe.Mesh.- Type:
Examples
>>> import numpy as np >>> import felupe as fem >>> >>> scene = fem.view.Scene() >>> scene.mesh = fem.Cube(n=3).as_unstructured_grid() >>> scene.mesh.point_data["Displacement"] = np.arange(81).reshape(27, 3) / 300 >>> _ = scene.mesh.set_active_scalars(None) >>> >>> scene.plot("Displacement", component=None).show()
See also
felupe.ViewMeshProvide Visualization methods for a mesh with optional given dicts of point- and cell-data items.
felupe.ViewFieldProvide Visualization methods for a field container.
felupe.ViewSolidProvide Visualization methods for a field container or a solid body.
- class felupe.ViewMesh(mesh, point_data=None, cell_data=None, cell_type=None)[source]#
Provide Visualization methods for
felupe.Meshwith optional given dicts of point- and cell-data items.- Parameters:
mesh (felupe.Mesh) – The mesh object.
point_data (dict or None, optional) – Additional point-data dict (default is None).
cell_data (dict or None, optional) – Additional cell-data dict (default is None).
cell_type (pyvista.CellType or None, optional) – Cell-type of PyVista (default is None).
- points#
Point coordinates of the mesh.
- Type:
ndarray
- cells#
Point-connectivity of the cells of the mesh.
- Type:
ndarray
- mesh#
A generalized Dataset with the mesh as well as point- and cell-data. This is not an instance of
felupe.Mesh. It is created on first access, i.e. PyVista is only required for this attribute and for plotting.- Type:
Examples
See also
felupe.view.SceneBase class for plotting a static scene.
felupe.ViewFieldProvide Visualization methods for a field container.
felupe.ViewSolidProvide Visualization methods for a field container or a solid body.
- clip(normal='x', origin=None, invert=True, value=0.0, crinkle=True)[source]#
Clip the scene by a plane and return the clipped scene.
The arguments are those of
pyvista.DataSetFilters.clip(). By default, the clip is crinkled, i.e. the cells are kept as a whole and not cut by the plane. All cells with at least one point on the kept side of the plane are kept, together with their point- and cell-data. Unused points are removed. The crinkled clip is evaluated by NumPy and it is supported by all plotting backends.- Parameters:
normal (str or array_like, optional) – The normal vector of the plane, e.g.
"x","-y"or(1, 1, 0)(default is"x"). A given vector is normalized.origin (array_like or None, optional) – A point on the plane (default is None). If None, the center of the bounds of the points is used.
invert (bool, optional) – A flag to keep the part of the scene behind the plane, i.e. on the opposite side of the normal vector (default is True). If False, the part in front of the plane is kept.
value (float, optional) – The plane is shifted by this value along the (normalized) normal vector (default is 0.0).
crinkle (bool, optional) – A flag to keep the clipped cells as a whole (default is True). If False, the cells are cut by the plane by
pyvista.DataSetFilters.clip(). This requires PyVista and the clipped scene is only supported by the plotting backend"pyvista".
- Returns:
The clipped scene. A crinkled clip returns a scene of the same class, e.g. a
ViewField, otherwise aScenewith the clipped mesh aspyvista.UnstructuredGrid.- Return type:
Notes
The scene is clipped in the undeformed configuration, i.e. the points of the mesh are not displaced by the point-data
"Displacement".Examples
- felupe.ViewField(field, point_data=None, cell_data=None, cell_type=None, project=None)[source]#
Provide Visualization methods for
felupe.FieldContainer. The warped (deformed) mesh is created from the values of the first field (displacements). By default, the “Deformation Gradient” tensor, the “Logarithmic Strain” tensor and the “Principal Values of Logarithmic Strain” are evaluated as field-related items of the cell-data dict. Optional items of given point- and cell-data overwrite these default field-related cell-data items.- Parameters:
field (felupe.FieldContainer) – The field-container.
point_data (dict or None, optional) – Additional point-data dict (default is None).
cell_data (dict or None, optional) – Additional cell-data dict (default is None).
cell_type (pyvista.CellType or None, optional) – Cell-type of PyVista (default is None).
project (callable or None, optional) – Callable to project internal cell-data at quadrature-points to mesh-points (default is None). Valid callables are
projectorextrapolate.
- felupe.points#
Point coordinates of the mesh.
- Type:
ndarray
- felupe.cells#
Point-connectivity of the cells of the mesh.
- Type:
ndarray
- felupe.cell_type#
A string in VTK-convention that specifies the cell type of the mesh.
- Type:
str or None
- felupe.mesh#
A generalized Dataset with the mesh as well as point- and cell-data. This is not an instance of
felupe.Mesh. It is created on first access, i.e. PyVista is only required for this attribute and for plotting.- Type:
Examples
>>> import numpy as np >>> import felupe as fem >>> >>> mesh = fem.Cube(n=3) >>> region = fem.RegionHexahedron(mesh) >>> u = np.sqrt(1 + np.arange(81)).reshape(27, 3) / 100 >>> field = fem.FieldContainer([fem.Field(region, dim=3, values=u)]) >>> >>> view = fem.ViewField(field, project=fem.project) >>> view.plot("Principal Values of Logarithmic Strain").show()
See also
felupe.view.SceneBase class for plotting a static scene.
felupe.ViewMeshProvide Visualization methods for a mesh with optional given dicts of point- and cell-data items.
felupe.ViewSolidProvide Visualization methods for a field container or a solid body.
felupe.projectProject given values at quadrature-points to mesh-points.
- felupe.ViewSolid(field, solid=None, stress_type='Cauchy', point_data=None, cell_data=None, cell_type=None, project=None, **kwargs)[source]#
Provide Visualization methods for
felupe.FieldContainerand felupe.SolidBody. The warped (deformed) mesh is created from the values of the first field (displacements). By default, the “Deformation Gradient” tensor, the “Logarithmic Strain” tensor and the “Principal Values of Logarithmic Strain” are evaluated as field-related items of the cell-data dict. Optional items of given point- and cell-data overwrite these default field-related cell-data items.- Parameters:
field (felupe.FieldContainer) – The field-container.
solid (felupe.SolidBody or felupe.SolidBodyIncompressible or None, optional) – A solid body to evaluate the (Cauchy) stress (default is None).
stress_type (str or None, optional) – The type of stress which is exported, either “Cauchy”, “Kirchhoff” or None. If None, the first Piola-Kirchhoff stress (engineering stress in linear elasticity) is used. Default is “Cauchy”.
point_data (dict or None, optional) – Additional point-data dict (default is None).
cell_data (dict or None, optional) – Additional cell-data dict (default is None).
cell_type (pyvista.CellType or None, optional) – Cell-type of PyVista (default is None).
project (callable or None, optional) – Callable to project stress at quadrature-points to mesh-points (default is None). Valid callables are
projectorextrapolate.
- felupe.points#
Point coordinates of the mesh.
- Type:
ndarray
- felupe.cells#
Point-connectivity of the cells of the mesh.
- Type:
ndarray
- felupe.cell_type#
A string in VTK-convention that specifies the cell type of the mesh.
- Type:
str or None
- felupe.mesh#
A generalized Dataset with the mesh as well as point- and cell-data. This is not an instance of
felupe.Mesh. It is created on first access, i.e. PyVista is only required for this attribute and for plotting.- Type:
Examples
>>> import numpy as np >>> import felupe as fem >>> >>> mesh = fem.Cube(n=3) >>> region = fem.RegionHexahedron(mesh) >>> u = np.sqrt(1 + np.arange(81)).reshape(27, 3) / 100 >>> field = fem.FieldContainer([fem.Field(region, dim=3, values=u)]) >>> solid = fem.SolidBody(umat=fem.NeoHooke(mu=1, bulk=2), field=field) >>> >>> view = fem.ViewSolid(field, solid, project=fem.project) >>> view.plot("Principal Values of Cauchy Stress").show()
See also
felupe.view.SceneBase class for plotting a static scene.
felupe.ViewMeshProvide Visualization methods for a mesh with optional given dicts of point- and cell-data items.
felupe.ViewFieldProvide Visualization methods for a field container.
felupe.projectProject given values at quadrature-points to mesh-points.
- felupe.ViewXdmf(filename, time=0)[source]#
Provide Visualization methods for a XDMF file generated by
Job.evaluate(filename="result.xdmf")(). The warped (deformed) mesh is created from the values of the point-data “Displacement”.- Parameters:
- felupe.mesh#
A generalized Dataset with the mesh as well as point- and cell-data. This is not an instance of
felupe.Mesh.- Type:
- felupe.view.select_surface_points(mesh, angle=30.0, slider=True, selected=None, excluded=None, color='lightgrey', selected_color=None, excluded_color='darkred', show_edges=False, nonlinear_subdivision=1, **kwargs)[source]#
Interactively select (and exclude) smooth surface patches and return their point ids.
- Parameters:
mesh (Mesh) – The mesh from which to select surface points.
angle (float, optional) – Max. angle in degrees between the normals of two neighbouring faces to be treated as one connected patch (default is 30).
slider (bool, optional) – Show a slider to change the angle interactively (default is True).
selected (array_like or None, optional) – Coordinates of points to initially select the surface patches of their closest faces, e.g.
[(1.0, 0.5, 0.5)], same as a left click on these patches. Default is None.excluded (array_like or None, optional) – Coordinates of points to initially exclude the surface patches of their closest faces, same as two left clicks on these patches. Default is None.
color (str, optional) – Color of unselected surface patches (default is “lightgrey”).
selected_color (str or None, optional) – Color of selected surface patches. Default is None, which lets PyVista choose the default color based on the global theme.
excluded_color (str, optional) – Color of excluded surface patches (default is “darkred”).
show_edges (bool, optional) – Whether to show the edges of the mesh (default is False). The patches are separated by their borders anyway.
nonlinear_subdivision (int, optional) – Number of subdivisions to generate a smooth surface based on the mid-edge points of quadratic (or Lagrange) cells, same as in
plot()(default is 1, no subdivision). If greater than 1, the surface is plotted with smooth shading and the shown edges are the (curved) edges of the faces. The patches are evaluated on the subdivided surface.**kwargs (optional) – Additional keyword arguments to pass to the PyVista plotter.
- Returns:
Sorted point ids (of
mesh) of all faces on the selected patches, without the points of all faces on the excluded patches. A face is on a patch if one of its triangles (on the subdivided surface) is on the patch.- Return type:
Notes
The selection is controlled by the mouse and the keyboard.
Left click: cycle the patch under the cursor from unselected to selected, from selected to excluded and from excluded back to unselected (a drag rotates as usual).
Right click: finish (a drag zooms as usual), same as
qor closing the window.Button or
c: clear the selection, i.e. all patches are unselected.
Excluded patches have priority over selected patches: the points shared by a selected and an excluded patch, e.g. the points on their common border, are not selected. If both a selected and an excluded patch are merged into one patch by an increased angle, the merged patch is excluded.
The subdivision of nonlinear faces creates new points, which are only used for the visualization. The returned point ids are always the point ids of the faces of the mesh, e.g. all eight points of a face of a quadratic hexahedron (including the mid-edge points), independent of
nonlinear_subdivision.Examples
The surface patch at \(x=1\) of a cube is selected and the surface patch at \(z=1\) is excluded. Here, the patches are given by points next to them, which is the same as a left click on the patch at \(x=1\) and two left clicks on the patch at \(z=1\). The selection is finished by a right click (not required for the static images of the documentation). The selected points are plotted on the mesh, the points on the common edge of both patches are not selected.
>>> import felupe as fem >>> import pyvista as pv >>> >>> mesh = fem.Cube(n=6) >>> point_ids = mesh.select_surface_points( ... selected=[(1.0, 0.5, 0.5)], excluded=[(0.5, 0.5, 1.0)] ... ) >>> >>> plotter = pv.Plotter() >>> points = mesh.points[point_ids] >>> actor = plotter.add_points(points, color="red", point_size=10) >>> mesh.plot(plotter=plotter).show()
See also
felupe.view.select_edge_pointsInteractively select smooth edge patches and return their point ids.
- felupe.view.select_edge_points(mesh, angle=30.0, slider=True, selected=None, excluded=None, color='black', selected_color=None, excluded_color='red', show_edges=False, **kwargs)[source]#
Interactively select (and exclude) smooth edge patches and return their point ids.
The edges are the borders of the surface patches (see
select_surface_points()), i.e. the edges between neighbouring faces with a kink angle aboveangleand the boundary edges of open surfaces, e.g. of 2d-meshes. An edge patch is a chain of connected edges. The chains are split at points with a kink angle aboveangleand at points with more than two edges.- Parameters:
mesh (Mesh) – The mesh from which to select edge points.
angle (float, optional) – Max. angle in degrees between the normals of two neighbouring faces or between two neighbouring edges to be treated as one connected patch (default is 30).
slider (bool, optional) – Show a slider to change the angle interactively (default is True).
selected (array_like or None, optional) – Coordinates of points to initially select the edge patches of their closest edges, e.g.
[(1.0, 1.0, 0.5)], same as a left click on these patches. Default is None.excluded (array_like or None, optional) – Coordinates of points to initially exclude the edge patches of their closest edges, same as two left clicks on these patches. Default is None.
color (str, optional) – Color of unselected edge patches (default is “black”).
selected_color (str or None, optional) – Color of selected edge patches. Default is None, which lets PyVista choose the default color based on the global theme.
excluded_color (str, optional) – Color of excluded edge patches (default is “red”).
show_edges (bool, optional) – Whether to show the edges of the mesh on the surface (default is False). The edges which may be selected are shown anyway.
**kwargs (optional) – Additional keyword arguments to pass to the PyVista plotter.
- Returns:
Sorted point ids (of
mesh) of all edges on the selected patches, without the points of all edges on the excluded patches.- Return type:
Notes
The selection is controlled by the mouse and the keyboard.
Left click: cycle the patch next to the cursor from unselected to selected, from selected to excluded and from excluded back to unselected (a drag rotates as usual). Edges which are hidden behind the surface are ignored.
Right click: finish (a drag zooms as usual), same as
qor closing the window.Button or
c: clear the selection, i.e. all patches are unselected.
Excluded patches have priority over selected patches: the points shared by a selected and an excluded patch, e.g. a corner point between two edge patches, are not selected. If both a selected and an excluded patch are merged into one patch by an increased angle, the merged patch is excluded.
Examples
The edge patch at \(x=z=1\) of a cube is selected and the edge patch at \(x=1, y=0\) is excluded. Here, the patches are given by points next to them, which is the same as a left click on the edge at \(x=z=1\) and two left clicks on the edge at \(x=1, y=0\). The selection is finished by a right click (not required for the static images of the documentation). The selected points are plotted on the mesh, the common corner point of both patches is not selected.
>>> import felupe as fem >>> import pyvista as pv >>> >>> mesh = fem.Cube(n=6) >>> point_ids = mesh.select_edge_points( ... selected=[(1.0, 0.5, 1.0)], excluded=[(1.0, 0.0, 0.5)] ... ) >>> >>> plotter = pv.Plotter() >>> points = mesh.points[point_ids] >>> actor = plotter.add_points(points, color="red", point_size=10) >>> mesh.plot(plotter=plotter).show()
See also
felupe.view.select_surface_pointsInteractively select smooth surface patches and return their point ids.
- felupe.set_plotting_backend(name)[source]#
Set the current plotting backend by its name. It draws the plots without a given plotter, e.g.
mesh.plot(). A plot with a given plotter, e.g.mesh.plot(plotter=plotter), is drawn by the plotting backend of the given plotter.- Parameters:
name (str or None) – The name of a registered plotting backend. Available are
"pyvista","webgl"and"matplotlib". If None, the plotting backend is selected automatically:"pyvista"if PyVista is installed, otherwise"webgl"(which requires no optional dependency). The plotting backend"matplotlib"is only selected by its name. The selected name is returned byget_plotting_backend(). The default plotting backend, i.e. on import of FElupe, is selected automatically.- Raises:
ValueError – If no plotting backend is registered with the given name.
Notes
The plotting backend
"pyvista"draws the plots bypyvista.Plotter(with screenshots, e.g. forMesh.screenshot()).The plotting backend
"webgl"draws the plots by a WebGL viewer in the web browser, without PyVista. Its plotter has the methodsshow(filename=None),export_html(filename)andwidget(height="480px"). Like with PyVista, the plotter is shown byshow(): in a notebook, the self-contained HTML page of the viewer is shown in the output of the cell (in aniframe), otherwise it is written to a file, which is opened in the web browser.widget()returns a Jupyter widget of the viewer with binary buffers, e.g. for a layout of widgets (this requires anywidget,pip install felupe[web]). The outer surface of the meshes is curved for quadratic and Lagrange cells withnonlinear_subdivision > 1. Screenshots, the plots of finite elements and regions and the options which are specific to PyVista (which raise a warning once) are not supported. Drag to rotate, shift-drag to pan, scroll to zoom and double-click to reset the view.The plotting backend
"matplotlib"draws the plots on the axes of a figure of matplotlib, without PyVista. Its plotter, aMatplotlibPlotter, has the methodsshow(),screenshot(filename=None, transparent_background=None, scale=None)andsavefig()and the attributesfigureandax. The screenshots, e.g. ofMesh.screenshot(), are taken off-screen, i.e. without a display. The format of the file of a screenshot is given by the suffix of its filename, e.g. a raster format (PNG) or a vector format (PDF, SVG or EPS). Given (two-dimensional) axes of matplotlib are accepted as plotter, e.g.mesh.plot(plotter=ax), e.g. for figures with several subplots. The faces of the outer surface of the meshes are drawn as polygons with a flat color each, in the order of their depths (painter’s algorithm). The faces on the back of the closed surfaces of opaque solid bodies are not drawn. Withnonlinear_subdivision=k, the edges of the faces are subdivided intoorder * 2 ** (k - 1)segments, also of linear cells (e.g. for smoother colors of point-data). The plots of finite elements and regions and the options which are specific to PyVista (which raise a warning once) are not supported.Examples
>>> import felupe as fem >>> >>> fem.set_plotting_backend("webgl") >>> mesh = fem.Cube(n=3) >>> plotter = mesh.plot() >>> path = plotter.export_html("cube.html") >>> >>> fem.set_plotting_backend("matplotlib") >>> image = mesh.screenshot(filename="cube.pdf") >>> >>> fem.set_plotting_backend("pyvista") >>> fem.get_plotting_backend() 'pyvista'
The plotting backend is selected automatically by the installed optional dependencies, e.g.
"pyvista"if PyVista is installed.>>> fem.set_plotting_backend(None)
See also
felupe.get_plotting_backendReturn the name of the current plotting backend.
felupe.view.register_plotting_backendRegister a plotting backend by a name.
- felupe.get_plotting_backend()[source]#
Return the name of the current plotting backend.
- Returns:
The name of the current plotting backend, e.g.
"pyvista".- Return type:
See also
felupe.set_plotting_backendSet the current plotting backend by its name.
- felupe.view.auto_plotting_backend()[source]#
Return the name of the plotting backend which is selected automatically by the installed optional dependencies:
"pyvista"if PyVista is installed, otherwise"webgl", which requires no optional dependency. PyVista is not imported. The plotting backend"matplotlib"is never selected automatically.- Returns:
The name of the plotting backend.
- Return type:
See also
felupe.set_plotting_backendSet the current plotting backend by its name.
- felupe.view.register_plotting_backend(name, backend)[source]#
Register a plotting backend by a name. An already registered plotting backend with the same name is replaced.
- Parameters:
name (str) – The name of the plotting backend, e.g.
"pyvista".backend (felupe.view.PlottingBackend) – An instance of a plotting backend. Its attribute
nameis set to the given name.
- Raises:
TypeError – If the backend is not an instance of
PlottingBackend.
See also
felupe.view.PlottingBackendBase class of a plotting backend.
felupe.set_plotting_backendSet the current plotting backend by its name.
- class felupe.view.PlottingBackend[source]#
Base class of a plotting backend, which draws the scenes of the plot-methods, e.g. of
Mesh.plot(),FieldContainer.plot()orSolidBody.plot().A plotting backend draws on its own type of plotter. A subclass implements
is_plotter(),prepare_plotter()andadd_view(). The other methods are optional and raise aNotImplementedErrorby default: the primitivesadd_points(),add_lines(),add_arrows(),add_shape()andadd_legend(), which draw the decorations of a model, e.g. of boundary conditions, point loads, constraints and rigid contact surfaces, andscreenshot().- name#
The name of the plotting backend, which is set by
register_plotting_backend().- Type:
str or None
Notes
A plot-method draws its scene on a given plotter or on a new plotter. The argument
plottercombines several plots in one plotter, e.g.mesh.plot(plotter=other_mesh.plot()). A given plotter is drawn by the plotting backend which recognizes it (byis_plotter()), independent of the current plotting backend. Without a given plotter, the current plotting backend creates a new plotter, seeset_plotting_backend().Examples
A minimal plotting backend, which collects the scenes in a list.
>>> import felupe as fem >>> >>> class ListPlotter(list): ... def show(self): ... print(f"Plotter with {len(self)} scene(s)") >>> >>> class ListBackend(fem.view.PlottingBackend): ... def is_plotter(self, plotter): ... return isinstance(plotter, ListPlotter) ... ... def prepare_plotter(self, plotter=None, **kwargs): ... if plotter is None: ... plotter = ListPlotter() ... return plotter ... ... def add_view(self, plotter, scene, **kwargs): ... plotter.append(scene) ... return plotter >>> >>> fem.view.register_plotting_backend("list", ListBackend()) >>> fem.set_plotting_backend("list") >>> >>> mesh = fem.Cube(n=3) >>> mesh.plot(plotter=mesh.plot()).show() Plotter with 2 scene(s)
>>> fem.set_plotting_backend("pyvista")
See also
felupe.set_plotting_backendSet the current plotting backend by its name.
felupe.get_plotting_backendReturn the name of the current plotting backend.
felupe.view.register_plotting_backendRegister a plotting backend by a name.
- add_arrows(plotter, points, directions, scale=1.0, color=None, **kwargs)[source]#
Add arrows to a plotter and return the plotter. Not supported by default.
- Parameters:
plotter (object) – A plotter of this plotting backend.
points (ndarray) – The start points of the arrows of shape
(narrows, dim)withdim <= 3.directions (ndarray) – The vectors of the arrows of shape
(narrows, dim).scale (float, optional) – A factor of the vectors of the arrows (default is 1.0).
color (str or None, optional) – The color of the arrows (default is None).
**kwargs (dict, optional) – Optional keyword-arguments of the arrows.
- Returns:
The plotter.
- Return type:
- add_legend(plotter, entries=None, size=None, background_color=None, **kwargs)[source]#
Add a legend to a plotter and return the plotter. Not supported by default.
- Parameters:
plotter (object) – A plotter of this plotting backend.
entries (list of tuple or None, optional) – The entries
(label, color)of the legend (default is None). If None, the entries are taken from the labels of the primitives, e.g. given byadd_points(..., label=label).size (tuple of float or None, optional) – The relative size of the legend (default is None).
background_color (str or None, optional) – The background color of the legend (default is None).
**kwargs (dict, optional) – Optional keyword-arguments of the legend.
- Returns:
The plotter.
- Return type:
- add_lines(plotter, lines, color=None, line_width=None, **kwargs)[source]#
Add straight line segments to a plotter and return the plotter. Not supported by default.
- Parameters:
plotter (object) – A plotter of this plotting backend.
lines (ndarray) – The start and end points of the line segments of shape
(nlines, 2, dim)withdim <= 3.color (str or None, optional) – The color of the lines (default is None).
line_width (float or None, optional) – The width of the lines (default is None).
**kwargs (dict, optional) – Optional keyword-arguments of the lines.
- Returns:
The plotter.
- Return type:
- add_points(plotter, points, color=None, point_size=None, **kwargs)[source]#
Add points to a plotter and return the plotter. Not supported by default.
- Parameters:
plotter (object) – A plotter of this plotting backend.
points (ndarray) – The point coordinates of shape
(npoints, dim)withdim <= 3.color (str or None, optional) – The color of the points (default is None).
point_size (float or None, optional) – The size of the points (default is None).
**kwargs (dict, optional) – Optional keyword-arguments of the points, e.g. a
labelfor the legend.
- Returns:
The plotter.
- Return type:
- add_shape(plotter, shape, color=None, opacity=None, show_edges=None, **kwargs)[source]#
Add a shape, e.g. a plane, a cylinder or a cone, to a plotter and return the plotter. Not supported by default.
- Parameters:
plotter (object) – A plotter of this plotting backend.
shape (object) – A shape with a method
shape.triangulate(), which returns the points of shape(npoints, 3)and the triangles of shape(ntriangles, 3)of its (clipped) surface.color (str or None, optional) – The color of the shape (default is None).
opacity (float or None, optional) – The opacity of the shape (default is None).
show_edges (bool or None, optional) – A flag to show the edges of the surface of the shape (default is None).
**kwargs (dict, optional) – Optional keyword-arguments of the shape.
- Returns:
The plotter.
- Return type:
- abstractmethod add_view(plotter, scene, **kwargs)[source]#
Add a scene to a plotter and return the plotter.
- Parameters:
plotter (object) – A plotter of this plotting backend.
scene (felupe.view.Scene) – The scene to add, e.g. a
ViewMeshwith the attributespoints,cells,cell_type,point_dataandcell_data.**kwargs (dict, optional) – The other arguments of
felupe.view.Scene.plot(), e.g.name,componentandfactor.
- Returns:
The plotter.
- Return type:
- default_color()[source]#
Return the default color of the meshes, e.g. of the current theme, or None if there is no default color (default is None).
- abstractmethod is_plotter(plotter)[source]#
Return True if the given object is a plotter of this plotting backend.
- abstractmethod prepare_plotter(plotter=None, **kwargs)[source]#
Return the given plotter or a new plotter.
- Parameters:
- Returns:
The given or a new plotter.
- Return type:
- screenshot(plot, *args, filename=None, transparent_background=None, scale=None, **kwargs)[source]#
Take a screenshot of the plotter, which is returned by
plot(*args, **kwargs). Not supported by default.- Parameters:
plot (callable) – A function which returns a plotter, e.g. the plot-method of a mesh.
*args (tuple, optional) – Optional positional arguments of the plot-function.
filename (str or None, optional) – The filename of the screenshot (default is None).
transparent_background (bool or None, optional) – A flag for a transparent background (default is None).
scale (int or None, optional) – A factor of the resolution of the screenshot (default is None).
**kwargs (dict, optional) – Optional keyword-arguments of the plot-function.
- Returns:
The image data of the screenshot.
- Return type:
ndarray
- Raises:
NotImplementedError – If the plotting backend does not support screenshots.
- class felupe.view.WebGLPlotter[source]#
The plotter of the plotting backend
"webgl", a scene which is shown in the web browser by a WebGL viewer.- view#
The view of the camera, e.g.
"xy". If"default", planar models are viewed from the top ("xy") and other models from an oblique view.- Type:
str or None
Notes
The page of the viewer is a self-contained HTML page (without a server and without other files). Like a plotter of PyVista, the plotter is shown by
show(). In a notebook, the page is shown in the output of the cell (in aniframe, without a Jupyter widget, e.g. also in the interactive window of VS Code). Otherwise, the page is written to a file, which is opened in the web browser. A Jupyter widget of the viewer, e.g. for a layout of widgets, is returned bywidget().With the plotting backend
"webgl", i.e. afterfem.set_plotting_backend("webgl"), the plot-methods return a new plotter of this class, e.g.Mesh.plot()orSolidBody.plot(). A given plotter is always drawn by the WebGL viewer, independent of the current plotting backend.Examples
A new plotter is given to a plot-method. The viewer is shown by
plotter.show().>>> import felupe as fem >>> >>> mesh = fem.Cube(n=3) >>> plotter = mesh.plot(plotter=fem.view.WebGLPlotter())
The self-contained HTML page of the viewer is written to a file, e.g. to share the model. It works offline, without a server and without other files.
>>> path = plotter.export_html("mesh.html")
See also
felupe.set_plotting_backendSet the current plotting backend by its name.
felupe.view.MatplotlibPlotterThe plotter of the plotting backend
"matplotlib".
- export_html(filename)[source]#
Write the self-contained HTML page of the viewer to a file.
- Parameters:
filename (str or pathlib.Path) – The filename of the HTML file, e.g.
"plot.html".- Returns:
The path of the HTML file.
- Return type:
- property html#
The self-contained HTML page of the viewer.
- show(filename=None)[source]#
Show the viewer. In a notebook (without a given filename), the page of the viewer is shown in the output of the cell (in an
iframe). Otherwise, the page is written to a file, which is opened in the web browser.- Parameters:
filename (str, pathlib.Path or None, optional) – The filename of the HTML file (default is None). If None, a temporary file is written (outside of a notebook) in the private folder
felupe-<uid>of the temporary directory with the id of the user (felupeon Windows), where the pages older than a day are removed.- Returns:
The path of the HTML file (or None in a notebook).
- Return type:
pathlib.Path or None
- widget(height='480px')[source]#
Return a Jupyter widget of the viewer, e.g. to show it in a layout of widgets. The arrays of the scene are transferred as binary buffers. This requires the optional dependency anywidget (
pip install felupe[web]).- Parameters:
height (str, optional) – The height of the widget as CSS length (default is
"480px").- Returns:
The widget of the viewer.
- Return type:
anywidget.AnyWidget
- class felupe.view.MatplotlibPlotter(ax=None, off_screen=False)[source]#
The plotter of the plotting backend
"matplotlib", a scene which is drawn on the axes of a figure of matplotlib.- Parameters:
ax (matplotlib.axes.Axes or None, optional) – The (two-dimensional) axes of matplotlib to draw on (default is None). If None, a new figure with axes is created. A scene on given axes is drawn whenever an object is added, i.e. the figure of the axes may be saved by
fig.savefig(), e.g. a figure with several subplots in a vector format.off_screen (bool, optional) – A flag to create the new figure without pyplot (default is False), i.e. it is not shown in a window, e.g. for screenshots. In a notebook, the figure is always created without pyplot and it is shown by
show().
- view#
The view of the camera, e.g.
"xy","xz"or"iso". If"default", planar models are viewed from the top ("xy") and other models from an oblique view (the default view of FElupe).- Type:
str or None
- parallel_projection#
A flag for a parallel projection (default is None). If None, planar models are drawn by a parallel projection and other models by a perspective projection.
- Type:
bool or None
- rasterized#
A flag to rasterize the model in vector formats (default is False), e.g. for large models. The scalar bars, the legend and the axes are not rasterized.
- Type:
Notes
The model is drawn by projected polygons (with a flat color each), which are drawn in the order of their depths (painter’s algorithm), i.e. far polygons first. The faces on the back of the closed surfaces of opaque solid bodies are not drawn (back-face culling). Hence, a screenshot in a vector format, e.g. PDF or SVG, contains a polygon for each visible face (with its edges), see
screenshot(). Overlapping faces, which intersect each other, e.g. at a contact, may be drawn in a wrong order.Examples
>>> import felupe as fem >>> import matplotlib.pyplot as plt >>> >>> fig, ax = plt.subplots(1, 2) >>> plotter = fem.view.MatplotlibPlotter(ax=ax[0]) >>> plotter = fem.Cube(n=3).plot(plotter=plotter) >>> plotter = fem.Rectangle(n=3).plot(plotter=ax[1]) >>> fig.savefig("meshes.pdf")
- enable_parallel_projection()[source]#
Enable the parallel projection of the camera and return the plotter.
- render()[source]#
Draw the scene on the axes, i.e. the model as a collection of paths, the scalar bars, the legend and the axes. A previously drawn scene is removed. The scene is drawn by
show(),screenshot()andsavefig(), e.g. with changed attributes like the view.- Returns:
The plotter.
- Return type:
- savefig(*args, **kwargs)[source]#
Save the figure, see
matplotlib.figure.Figure.savefig(), e.g.plotter.savefig("model.pdf").
- screenshot(filename=None, transparent_background=None, scale=None)[source]#
Take a screenshot of the figure and return the image data. Optionally, the screenshot is saved to a file. The format of the file is given by the suffix of the filename, e.g.
"model.png"(raster) or"model.pdf","model.svg"and"model.eps"(vector formats).- Parameters:
filename (str, pathlib.Path or None, optional) – The filename of the screenshot (default is None). If None, no file is written.
transparent_background (bool or None, optional) – A flag for a transparent background (default is None). If True, the image data has an alpha channel.
scale (float or None, optional) – A factor of the resolution (the dots per inch) of the figure (default is None).
- Returns:
The image data of the screenshot of shape
(height, width, 3), or(height, width, 4)with a transparent background, as unsigned integers (uint8).- Return type:
ndarray
- show()[source]#
Show the figure. A figure of pyplot is shown by
pyplot.show(). In a notebook, the image of the figure is shown in the output of the cell. An off-screen figure (outside of a notebook) is not shown.- Return type:
None