Debian Codegraph @

examples/02-plot/chemistry_molecule.py

raw
1 """
2 .. _chemistry_molecule_example:
3
4 Build a Ball-and-Stick Molecule
5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6
7 Assemble a simple molecule from :func:`pyvista.Sphere` atoms and
8 :func:`pyvista.Cylinder` bonds.
9 """
10
11 import numpy as np
12 import pyvista as pv
13
14 # %%
15 # Define a benzene ring
16 # ~~~~~~~~~~~~~~~~~~~~~
17 # Place six carbons evenly around a circle with a hydrogen pointing
18 # radially outward from each one.
19
20 angles = np.linspace(0, 2 * np.pi, 6, endpoint=False)
21 carbons = np.column_stack((np.cos(angles), np.sin(angles), np.zeros(6)))
22 hydrogens = 1.6 * carbons
23
24
25 def make_bond(point_a: np.ndarray, point_b: np.ndarray, radius: float) -> pv.PolyData:
26 """Create a cylinder between two atom centers."""
27 direction = point_b - point_a
28 return pv.Cylinder(
29 center=(point_a + point_b) / 2,
30 direction=direction,
31 radius=radius,
32 height=np.linalg.norm(direction),
33 )
34
35
36 carbon_atoms = pv.merge([pv.Sphere(radius=0.22, center=center) for center in carbons])
37 hydrogen_atoms = pv.merge([pv.Sphere(radius=0.14, center=center) for center in hydrogens])
38
39 carbon_bonds = pv.merge(
40 [
41 make_bond(carbons[i], carbons[(i + 1) % len(carbons)], 0.08)
42 for i in range(len(carbons))
43 ],
44 )
45 hydrogen_bonds = pv.merge(
46 [make_bond(carbons[i], hydrogens[i], 0.05) for i in range(len(carbons))],
47 )
48
49
50 # %%
51 # Render the molecule
52 # ~~~~~~~~~~~~~~~~~~~
53 # Atoms are rendered as spheres and bonds as cylinders, each with their
54 # own radius and color.
55
56 pl = pv.Plotter()
57 pl.add_mesh(carbon_bonds, color='slategray')
58 pl.add_mesh(hydrogen_bonds, color='lightgray')
59 pl.add_mesh(carbon_atoms, color='dimgray', smooth_shading=True)
60 pl.add_mesh(hydrogen_atoms, color='white', smooth_shading=True)
61 pl.show()
62 # %%
63 # .. tags:: plot