Debian Codegraph @

examples/99-advanced/atomic_orbitals.py

raw
1 """
2 .. _atomic_orbitals_example:
3
4 Plot Atomic Orbitals
5 --------------------
6 Visualize the wave functions (orbitals) of the hydrogen atom.
7
8 """
9
10 # %%
11 # Import
12 # ~~~~~~
13 # Import the applicable libraries.
14 #
15 # .. note::
16 # This example is modeled off of `Matplotlib: Hydrogen Wave Function
17 # <http://staff.ustc.edu.cn/~zqj/posts/Hydrogen-Wavefunction/>`_.
18 #
19 # This example requires `sympy <https://www.sympy.org/>`_. Install it with:
20 #
21 # .. code-block:: bash
22 #
23 # pip install sympy
24 import numpy as np
25 import pyvista as pv
26 from pyvista import examples
27
28 # %%
29 # Generate the Dataset
30 # ~~~~~~~~~~~~~~~~~~~~
31 # Generate the dataset by evaluating the analytic hydrogen wave function from
32 # ``sympy``.
33 #
34 # .. math::
35 # \begin{equation}
36 # \psi_{n\ell m}(r,\theta,\phi)
37 # =
38 # \sqrt{
39 # \left(\frac{2}{na_0}\right)^3\, \frac{(n-\ell-1)!}{2n[(n+\ell)!]}
40 # }
41 # e^{-r / na_0}
42 # \left(\frac{2r}{na_0}\right)^\ell
43 # L_{n-\ell-1}^{2\ell+1} \cdot Y_\ell^m(\theta, \phi)
44 # \end{equation}
45 #
46 # See `Hydrogen atom <https://en.wikipedia.org/wiki/Hydrogen_atom>`_ for more
47 # details.
48 #
49 # This dataset evaluates this function for the hydrogen orbital
50 # :math:`3d_{xy}`, with the following quantum numbers:
51 #
52 # * Principal quantum number: ``n=3``
53 # * Azimuthal quantum number: ``l=2``
54 # * Magnetic quantum number: ``m=-2``
55
56 grid = examples.load_hydrogen_orbital(3, 2, -2)
57 grid
58
59
60 # %%
61 # Plot the Orbital
62 # ~~~~~~~~~~~~~~~~
63 # Plot the orbital using :func:`add_volume() <pyvista.Plotter.add_volume>` and
64 # using the default scalars contained in ``grid``, ``real_wf``. This way we
65 # can plot more than just the probability of the electron, but also the phase
66 # of the electron wave function.
67 #
68 # .. note::
69 # Since the real value of evaluated wave function for this orbital varies
70 # between ``[-<value>, <value>]``, we cannot use the default opacity
71 # ``opacity='linear'``. Instead, we use ``[1, 0, 1]`` since we would like
72 # the opacity to be proportional to the absolute value of the scalars.
73
74 # sphinx_gallery_start_ignore
75 # volume rendering does not work in interactive plots currently
76 PYVISTA_GALLERY_FORCE_STATIC = True
77 # sphinx_gallery_end_ignore
78
79 pl = pv.Plotter()
80 vol = pl.add_volume(grid, cmap='magma', opacity=[1, 0, 1])
81 vol.prop.interpolation_type = 'linear'
82 pl.camera.zoom(2)
83 pl.show_axes()
84 pl.show()
85
86
87 # %%
88 # Plot the Orbital Contours as an Isosurface
89 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
90 # Generate the contour plot for the orbital by determining when the orbital
91 # equals 10% the maximum value of the orbital. This effectively captures the
92 # most likely locations of the electron for this orbital.
93 #
94 # Note how we use the absolute value of the scalars when evaluating
95 # :func:`contour() <pyvista.DataSetFilters.contour>` to capture where the
96 # positive and negative phases cross ``eval_at``.
97
98 eval_at = grid['real_wf'].max() * 0.1
99 contours = grid.contour(
100 [eval_at],
101 scalars=np.abs(grid['real_wf']),
102 method='marching_cubes',
103 )
104 contours = contours.interpolate(grid)
105 contours.plot(
106 smooth_shading=True,
107 show_scalar_bar=False,
108 )
109
110
111 # %%
112 # Volumetric Plot: Plot the Orbitals using RGBA
113 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
114 # Let's now combine some of the best parts of the two above plots. The
115 # volumetric plot is great for showing the probability of the "electron cloud"
116 # orbitals, but the colormap doesn't quite match reality as well as the
117 # isosurface plot.
118 #
119 # For this example we're going to use an RGBA colormap to tightly control the
120 # way the orbitals are plotted. For this, the opacity will be mapped to the
121 # probability of the electron being at a location in the grid, which we can do
122 # by taking the absolute value squared of the orbital's wave function. We can
123 # set the color of the orbital based on the phase, which we can get simply
124 # with ``orbital['real_wf'] < 0``.
125 #
126 # Let's start with a simple one, the :math:`3p_z` orbital.
127
128 # sphinx_gallery_start_ignore
129 # volume rendering does not work in interactive plots currently
130 PYVISTA_GALLERY_FORCE_STATIC = True
131 # sphinx_gallery_end_ignore
132
133
134 def plot_orbital(orbital, cpos='iso', clip_plane='x'):
135 """Plot an electron orbital using an RGBA colormap."""
136 neg_mask = orbital['real_wf'] < 0
137 rgba = np.zeros((orbital.n_points, 4), np.uint8)
138 rgba[neg_mask, 0] = 255
139 rgba[~neg_mask, 1] = 255
140
141 # normalize opacity
142 opac = np.abs(orbital['real_wf']) ** 2
143 opac /= opac.max()
144 rgba[:, -1] = opac * 255
145
146 orbital['plot_scalars'] = rgba
147
148 pl = pv.Plotter()
149 vol = pl.add_volume(
150 orbital,
151 scalars='plot_scalars',
152 )
153 vol.prop.interpolation_type = 'linear'
154 if clip_plane:
155 pl.add_volume_clip_plane(
156 vol,
157 normal=clip_plane,
158 normal_rotation=False,
159 )
160 pl.camera_position = cpos
161 pl.camera.zoom(1.5)
162 pl.show_axes()
163 return pl.show()
164
165
166 hydro_orbital = examples.load_hydrogen_orbital(3, 1, 0)
167 plot_orbital(hydro_orbital, clip_plane='-x')
168
169
170 # %%
171 # Volumetric Plot: :math:`4d_{z^2}` orbital
172 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
173
174 # sphinx_gallery_start_ignore
175 # volume rendering does not work in interactive plots currently
176 PYVISTA_GALLERY_FORCE_STATIC = True
177 # sphinx_gallery_end_ignore
178 hydro_orbital = examples.load_hydrogen_orbital(4, 2, 0)
179 plot_orbital(hydro_orbital, clip_plane='-y')
180
181
182 # %%
183 # Volumetric Plot: :math:`4d_{xz}` orbital
184 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
185
186 # sphinx_gallery_start_ignore
187 # volume rendering does not work in interactive plots currently
188 PYVISTA_GALLERY_FORCE_STATIC = True
189 # sphinx_gallery_end_ignore
190 hydro_orbital = examples.load_hydrogen_orbital(4, 2, -1)
191 plot_orbital(hydro_orbital, clip_plane='-y')
192
193
194 # %%
195 # Plot an Orbital Using a Density Plot
196 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
197 # We can also plot atomic orbitals using a 3D density plot. For this, we will
198 # use :func:`numpy.random.choice` to sample all the points of our
199 # :class:`pyvista.ImageData` based on the probability of the electron being
200 # at that coordinate.
201
202 # Seed rng for reproducibility
203 rng = np.random.default_rng(seed=0)
204
205 # Generate the orbital and sample based on the square of the probability of an
206 # electron being within a particular volume of space.
207 hydro_orbital = examples.load_hydrogen_orbital(4, 2, 0, zoom_fac=0.5)
208 prob = np.abs(hydro_orbital['real_wf']) ** 2
209 prob /= prob.sum()
210 indices = rng.choice(hydro_orbital.n_points, 10000, p=prob)
211
212 # add a small amount of noise to these coordinates to remove the "grid like"
213 # structure present in the underlying ImageData
214 points = hydro_orbital.points[indices]
215 points += rng.random(points.shape) - 0.5
216
217 # Create a point cloud and add the phase as the active scalars
218 point_cloud = pv.PolyData(points)
219 point_cloud['phase'] = hydro_orbital['real_wf'][indices] < 0
220
221 # Turn the point cloud into individual spheres. We do this so we can improve
222 # the plot by enabling surface space ambient occlusion (SSAO)
223 dplot = point_cloud.glyph(
224 geom=pv.Sphere(theta_resolution=8, phi_resolution=8),
225 scale=False,
226 orient=False,
227 )
228
229 # be sure to enable SSAO here. This makes the "points" that are deeper within
230 # the density plot darker.
231 pl = pv.Plotter()
232 pl.add_mesh(
233 dplot,
234 smooth_shading=True,
235 show_scalar_bar=False,
236 cmap=['red', 'green'],
237 ambient=0.2,
238 )
239 pl.enable_ssao(radius=10)
240 pl.enable_anti_aliasing()
241 pl.camera.zoom(2)
242 pl.background_color = 'w'
243 pl.show()
244
245
246 # %%
247 # Density Plot - Gaussian Points Representation
248 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
249 # Finally, let's plot the same data using the "Gaussian points" representation.
250
251
252 # sphinx_gallery_start_ignore
253 # volume rendering does not work in interactive plots currently
254 PYVISTA_GALLERY_FORCE_STATIC = True
255 # sphinx_gallery_end_ignore
256
257 point_cloud.plot(
258 style='points_gaussian',
259 render_points_as_spheres=False,
260 point_size=3,
261 emissive=True,
262 background='k',
263 show_scalar_bar=False,
264 cpos='xz',
265 zoom=2,
266 )