Coverage for ase/dft/bz.py: 94.09%
186 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1from itertools import product
2from math import cos, pi, sin
3from typing import Any
5import numpy as np
6from matplotlib.patches import FancyArrowPatch
7from mpl_toolkits.mplot3d import Axes3D, proj3d
8from scipy.spatial.transform import Rotation
10from ase.cell import Cell
13def bz_vertices(icell, dim=3):
14 """Return the vertices and the normal vector of the BZ.
16 See https://xkcd.com/1421 ..."""
17 from scipy.spatial import Voronoi
19 icell = icell.copy()
20 if dim < 3:
21 icell[2, 2] = 1e-3
22 if dim < 2:
23 icell[1, 1] = 1e-3
25 indices = (np.indices((3, 3, 3)) - 1).reshape((3, 27))
26 G = np.dot(icell.T, indices).T
27 vor = Voronoi(G)
28 bz1 = []
29 for vertices, points in zip(vor.ridge_vertices, vor.ridge_points):
30 if -1 not in vertices and 13 in points:
31 normal = G[points].sum(0)
32 normal /= (normal**2).sum() ** 0.5
33 bz1.append((vor.vertices[vertices], normal))
34 return bz1
37class FlatPlot:
38 """Helper class for 1D/2D Brillouin zone plots."""
40 axis_dim = 2 # Dimension of the plotting surface (2 even if it's 1D BZ).
41 point_options = {'zorder': 5}
43 def new_axes(self, fig):
44 return fig.gca()
46 def adjust_view(self, ax, minp, maxp, symmetric: bool = True):
47 """Ajusting view property of the drawn BZ. (1D/2D)
49 Parameters
50 ----------
51 ax: Axes
52 matplotlib Axes object.
53 minp: float
54 minimum value for the plotting region, which detemines the
55 bottom left corner of the figure. if symmetric is set as True,
56 this value is ignored.
57 maxp: float
58 maximum value for the plotting region, which detemines the
59 top right corner of the figure.
60 symmetric: bool
61 if True, set the (0,0) position (Gamma-bar position) at the center
62 of the figure.
64 """
65 ax.autoscale_view(tight=True)
66 s = maxp * 1.05
67 if symmetric:
68 ax.set_xlim(-s, s)
69 ax.set_ylim(-s, s)
70 else:
71 ax.set_xlim(minp * 1.05, s)
72 ax.set_ylim(minp * 1.05, s)
73 ax.set_aspect('equal')
75 def draw_arrow(self, ax, vector, **kwargs):
76 ax.arrow(
77 0,
78 0,
79 vector[0],
80 vector[1],
81 lw=1,
82 length_includes_head=True,
83 head_width=0.03,
84 head_length=0.05,
85 **kwargs,
86 )
88 def label_options(self, point):
89 ha_s = ['right', 'left', 'right']
90 va_s = ['bottom', 'bottom', 'top']
92 x, y = point
93 ha = ha_s[int(np.sign(x))]
94 va = va_s[int(np.sign(y))]
95 return {'ha': ha, 'va': va, 'zorder': 4}
97 def view(self):
98 pass
101class SpacePlot:
102 """Helper class for ordinary (3D) Brillouin zone plots.
104 Attributes
105 ----------
106 azim : float
107 Azimuthal angle in radian for viewing 3D BZ.
108 default value is pi/5
109 elev : float
110 Elevation angle in radian for viewing 3D BZ.
111 default value is pi/6
113 """
115 axis_dim = 3
116 point_options: dict[str, Any] = {}
118 def __init__(self, *, azim: float | None = None, elev: float | None = None):
119 class Arrow3D(FancyArrowPatch):
120 def __init__(self, ax, xs, ys, zs, *args, **kwargs):
121 FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
122 self._verts3d = xs, ys, zs
123 self.ax = ax
125 def draw(self, renderer):
126 xs3d, ys3d, zs3d = self._verts3d
127 xs, ys, _zs = proj3d.proj_transform(
128 xs3d, ys3d, zs3d, self.ax.axes.M
129 )
130 self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
131 FancyArrowPatch.draw(self, renderer)
133 # FIXME: Compatibility fix for matplotlib 3.5.0: Handling of 3D
134 # artists have changed and all 3D artists now need
135 # "do_3d_projection". Since this class is a hack that manually
136 # projects onto the 3D axes we don't need to do anything in this
137 # method. Ideally we shouldn't resort to a hack like this.
138 def do_3d_projection(self, *_, **__):
139 return 0
141 self.arrow3d = Arrow3D
142 self.azim: float = pi / 5 if azim is None else azim
143 self.elev: float = pi / 6 if elev is None else elev
144 self.view = [
145 sin(self.azim) * cos(self.elev),
146 cos(self.azim) * cos(self.elev),
147 sin(self.elev),
148 ]
150 def new_axes(self, fig):
151 return fig.add_subplot(projection='3d')
153 def draw_arrow(self, ax: Axes3D, vector, **kwargs):
154 ax.add_artist(
155 self.arrow3d(
156 ax,
157 [0, vector[0]],
158 [0, vector[1]],
159 [0, vector[2]],
160 mutation_scale=20,
161 arrowstyle='-|>',
162 **kwargs,
163 )
164 )
166 def adjust_view(self, ax, minp, maxp, symmetric=True):
167 """Ajusting view property of the drawn BZ. (3D)
169 Parameters
170 ----------
171 ax: Axes
172 matplotlib Axes object.
173 minp: float
174 minimum value for the plotting region, which detemines the
175 bottom left corner of the figure. if symmetric is set as True,
176 this value is ignored.
177 maxp: float
178 maximum value for the plotting region, which detemines the
179 top right corner of the figure.
180 symmetric: bool
181 Currently, this is not used, just for keeping consistency with 2D
182 version.
184 """
185 import matplotlib.pyplot as plt
187 # ax.set_aspect('equal') <-- won't work anymore in 3.1.0
188 ax.view_init(azim=np.rad2deg(self.azim), elev=np.rad2deg(self.elev))
189 # We want aspect 'equal', but apparently there was a bug in
190 # matplotlib causing wrong behaviour. Matplotlib raises
191 # NotImplementedError as of v3.1.0. This is a bit unfortunate
192 # because the workarounds known to StackOverflow and elsewhere
193 # all involve using set_aspect('equal') and then doing
194 # something more.
195 #
196 # We try to get square axes here by setting a square figure,
197 # but this is probably rather inexact.
198 fig = ax.get_figure()
199 xx = plt.figaspect(1.0)
200 fig.set_figheight(xx[1])
201 fig.set_figwidth(xx[0])
203 ax.set_proj_type('ortho')
205 minp0 = 0.9 * minp # Here we cheat a bit to trim spacings
206 maxp0 = 0.9 * maxp
207 ax.set_xlim3d(minp0, maxp0)
208 ax.set_ylim3d(minp0, maxp0)
209 ax.set_zlim3d(minp0, maxp0)
211 ax.set_box_aspect([1, 1, 1])
213 def label_options(self, point):
214 return dict(ha='center', va='bottom')
217def normalize_name(name):
218 if name == 'G':
219 return '\\Gamma'
221 if len(name) > 1:
222 import re
224 m = re.match(r'^(\D+?)(\d*)$', name)
225 if m is None:
226 raise ValueError(f'Bad label: {name}')
227 name, num = m.group(1, 2)
228 if num:
229 name = f'{name}_{{{num}}}'
230 return name
233def bz_plot(
234 cell: Cell,
235 vectors: bool = False,
236 paths=None,
237 points=None,
238 azim: float | None = None,
239 elev: float | None = None,
240 scale=1,
241 interactive: bool = False,
242 transforms: list | None = None,
243 repeat: tuple[int, int] | tuple[int, int, int] = (1, 1, 1),
244 pointstyle: dict | None = None,
245 ax=None,
246 show=False,
247 **kwargs,
248):
249 """Plot the Brillouin zone of the Cell
251 Parameters
252 ----------
253 cell: Cell
254 Cell object for BZ drawing.
255 vectors : bool
256 if True, show the vector.
257 paths : list[tuple[str, np.ndarray]] | None
258 Special point name and its coordinate position
259 points : np.ndarray
260 Coordinate points along the paths.
261 azim : float | None
262 Azimuthal angle in radian for viewing 3D BZ.
263 elev : float | None
264 Elevation angle in radian for viewing 3D BZ.
265 scale : float
266 Not used. To be removed?
267 interactive : bool
268 Not effectively works. To be removed?
269 transforms: List
270 List of linear transformation (scipy.spatial.transform.Rotation)
271 repeat: Tuple[int, int] | Tuple[int, int, int]
272 Set the repeating draw of BZ. default is (1, 1, 1), no repeat.
273 pointstyle : Dict
274 Style of the special point
275 ax : Axes | Axes3D
276 matplolib Axes (Axes3D in 3D) object
277 show : bool
278 If true, show the figure.
279 **kwargs
280 Additional keyword arguments to pass to ax.plot
282 Returns
283 -------
284 ax
285 A matplotlib axis object.
286 """
287 import matplotlib.pyplot as plt
289 if pointstyle is None:
290 pointstyle = {}
292 if transforms is None:
293 transforms = [Rotation.from_rotvec((0, 0, 0))]
295 cell = cell.copy()
297 dimensions = cell.rank
298 if dimensions == 3:
299 plotter: SpacePlot | FlatPlot = SpacePlot(azim=azim, elev=elev)
300 else:
301 plotter = FlatPlot()
302 assert dimensions > 0, 'No BZ for 0D!'
304 if ax is None:
305 ax = plotter.new_axes(plt.gcf())
307 assert not np.array(cell)[dimensions:, :].any()
308 assert not np.array(cell)[:, dimensions:].any()
310 icell = cell.reciprocal()
311 kpoints = points
312 bz1 = bz_vertices(icell, dim=dimensions)
313 if len(repeat) == 2:
314 repeat = (repeat[0], repeat[1], 1)
316 maxp = 0.0
317 minp = 0.0
318 for bz_i in bz_index(repeat):
319 for points, normal in bz1:
320 shift = np.dot(np.array(icell).T, np.array(bz_i))
321 for transform in transforms:
322 shift = transform.apply(shift)
323 ls = '-'
324 xyz = np.concatenate([points, points[:1]])
325 for transform in transforms:
326 xyz = transform.apply(xyz)
327 x, y, z = xyz.T
328 x, y, z = x + shift[0], y + shift[1], z + shift[2]
329 if dimensions == 3:
330 if normal @ plotter.view < 0 and not interactive:
331 ls = ':'
332 if plotter.axis_dim == 2:
333 ax.plot(x, y, c='k', ls=ls, **kwargs)
334 else:
335 ax.plot(x, y, z, c='k', ls=ls, **kwargs)
336 maxp = max(maxp, x.max(), y.max(), z.max())
337 minp = min(minp, x.min(), y.min(), z.min())
339 if vectors:
340 for transform in transforms:
341 icell = transform.apply(icell)
342 assert isinstance(icell, np.ndarray)
343 for i in range(dimensions):
344 plotter.draw_arrow(ax, icell[i], color='k')
346 # XXX Can this be removed?
347 if dimensions == 3:
348 maxp = max(maxp, 0.6 * icell.max())
349 else:
350 maxp = max(maxp, icell.max())
352 if paths is not None:
353 for names, points in paths:
354 for transform in transforms:
355 points = transform.apply(points)
356 coords = np.array(points).T[: plotter.axis_dim, :]
357 ax.plot(*coords, c='r', ls='-')
359 for name, point in zip(names, points):
360 name = normalize_name(name)
361 point = point[: plotter.axis_dim]
362 ax.text(
363 *point,
364 rf'$\mathrm{{{name}}}$',
365 color='g',
366 **plotter.label_options(point),
367 )
369 if kpoints is not None:
370 kw = {'c': 'b', **plotter.point_options, **pointstyle}
371 for transform in transforms:
372 kpoints = transform.apply(kpoints)
373 ax.scatter(*kpoints[:, : plotter.axis_dim].T, **kw)
375 ax.set_axis_off()
377 if repeat == (1, 1, 1):
378 plotter.adjust_view(ax, minp, maxp)
379 else:
380 plotter.adjust_view(ax, minp, maxp, symmetric=False)
381 if show:
382 plt.show()
384 return ax
387def bz_index(repeat):
388 """BZ index from the repeat
390 A helper function to iterating drawing BZ.
392 Parameters
393 ----------
394 repeat: Tuple[int, int] | Tuple[int, int, int]
395 repeating for drawing BZ
397 Returns
398 -------
399 Iterator[Tuple[int, int, int]]
401 >>> list(bz_index((1, 2, -2)))
402 [(0, 0, 0), (0, 0, -1), (0, 1, 0), (0, 1, -1)]
404 """
405 if len(repeat) == 2:
406 repeat = (repeat[0], repeat[1], 1)
407 assert len(repeat) == 3
408 assert repeat[0] != 0
409 assert repeat[1] != 0
410 assert repeat[2] != 0
411 repeat_along_a = (
412 range(0, repeat[0]) if repeat[0] > 0 else range(0, repeat[0], -1)
413 )
414 repeat_along_b = (
415 range(0, repeat[1]) if repeat[1] > 0 else range(0, repeat[1], -1)
416 )
417 repeat_along_c = (
418 range(0, repeat[2]) if repeat[2] > 0 else range(0, repeat[2], -1)
419 )
420 return product(repeat_along_a, repeat_along_b, repeat_along_c)