Debian Codegraph @

examples/01-filter/gradients.py

raw
1 """
2 .. _gradients_example:
3
4 Compute Gradients of a Field
5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6
7 Estimate the gradient of a scalar or vector field in a data set.
8
9 The ordering for the output gradient tuple will be
10 {du/dx, du/dy, du/dz, dv/dx, dv/dy, dv/dz, dw/dx, dw/dy, dw/dz} for
11 an input array {u, v, w}.
12
13 Showing the :func:`pyvista.DataSetFilters.compute_derivative` filter.
14 """
15
16 import numpy as np
17
18 # sphinx_gallery_thumbnail_number = 1
19 import pyvista as pv
20 from pyvista import examples
21
22 # A vtkStructuredGrid - but could be any mesh type
23 mesh = examples.download_carotid()
24 mesh
25 # %%
26 # Now compute the gradients of the ``vectors`` vector field in the point data
27 # of that mesh. This is as simple as calling
28 # :func:`pyvista.DataSetFilters.compute_derivative`.
29 mesh_g = mesh.compute_derivative(scalars='vectors')
30 mesh_g['gradient']
31
32 # %%
33 # .. note:: You can also use :func:`pyvista.DataSetFilters.compute_derivative` for
34 # computing other derivative based quantities, such as divergence, vorticity,
35 # and Q-criterion. See function documentation for options.
36
37 # %%
38 # ``mesh_g["gradient"]`` is an ``N`` by 9 NumPy array of the gradients, so we
39 # could make a dictionary of NumPy arrays of the gradients like:
40
41
42 def gradients_to_dict(arr):
43 """Label the gradients into a dictionary."""
44 keys = np.array(
45 ['du/dx', 'du/dy', 'du/dz', 'dv/dx', 'dv/dy', 'dv/dz', 'dw/dx', 'dw/dy', 'dw/dz'],
46 )
47 keys = keys.reshape((3, 3))[:, : arr.shape[1]].ravel()
48 return dict(zip(keys, mesh_g['gradient'].T, strict=False))
49
50
51 gradients = gradients_to_dict(mesh_g['gradient'])
52 gradients
53
54 # %%
55 # And we can add all of those components as individual arrays back to the mesh
56 # by:
57 mesh_g.point_data.update(gradients)
58 mesh_g
59
60 # %%
61
62 keys = np.array(list(gradients.keys())).reshape(3, 3)
63
64 pl = pv.Plotter(shape=keys.shape)
65 for (i, j), name in np.ndenumerate(keys):
66 pl.subplot(i, j)
67 pl.add_mesh(mesh_g.contour(scalars=name), scalars=name, opacity=0.75)
68 pl.add_mesh(mesh_g.outline(), color='k')
69 pl.link_views()
70 pl.view_isometric()
71 pl.show()
72
73
74 # %%
75 # And there you have it, the gradients for a vector field. We could also do
76 # this for a scalar field like for the ``scalars`` field in the given dataset.
77 mesh_g = mesh.compute_derivative(scalars='scalars')
78
79 gradients = gradients_to_dict(mesh_g['gradient'])
80 gradients
81
82 # %%
83
84 mesh_g.point_data.update(gradients)
85
86 keys = np.array(list(gradients.keys())).reshape(1, 3)
87
88 pl = pv.Plotter(shape=keys.shape)
89
90 for (i, j), name in np.ndenumerate(keys):
91 pl.subplot(i, j)
92 pl.add_mesh(mesh_g.contour(scalars=name), scalars=name, opacity=0.75)
93 pl.add_mesh(mesh_g.outline(), color='k')
94 pl.link_views()
95 pl.view_isometric()
96 pl.show()
97 # %%
98 # .. tags:: filter