Coverage for tbkit/lattice.py: 100%
230 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-21 11:05 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-21 11:05 +0000
1from __future__ import annotations
3from typing import Sequence
5import numpy as np
6from numpy.typing import NDArray
7import matplotlib.pyplot as plt
8from matplotlib.figure import Figure
9from scipy.spatial import cKDTree
10import tbkit.error_handling as error_handling
13PI = np.pi
14#: Longest sublattice tag, in characters.
15TAG_LEN = error_handling.TAG_LEN
16COOR_DTYPE = [('x', 'f8'), ('y', 'f8'), ('tag', 'U{}'.format(TAG_LEN))]
17#: Site dtype of a lattice in 3D space (*unit_cell* and *prim_vec* given as 3-tuples).
18COOR_DTYPE_3D = [('x', 'f8'), ('y', 'f8'), ('z', 'f8'), ('tag', 'U{}'.format(TAG_LEN))]
21def _tag_pair(tag: str | Sequence[str]) -> tuple[str, str]:
22 '''
23 Private function. The sublattice tags (tag_i, tag_j) of a bond selector
24 'tag': a string of two one-character tags (``'ab'``) or a pair of tags
25 (``('Mo', 'S')``).
26 '''
27 return str(tag[0]), str(tag[1])
30#################################
31# CLASS LATTICE
32#################################
35class Lattice():
36 r'''
37 Build up 1D, 2D or 3D lattice.
38 Lattice is defined by the discrete operation:
40 .. math::
42 \mathbf{R} = n_1\mathbf{a}_1 + n_2\mathbf{a}_2 + n_3\mathbf{a}_3
44 where :math:`\mathbf{a}_1`, :math:`\mathbf{a}_2`, :math:`\mathbf{a}_3` are the
45 primitive vectors and :math:`n_1`, :math:`n_2`, :math:`n_3` are the number of
46 unit cells along them.
48 Parameters
49 ----------
50 unit_cell : List of dictionaries
51 One dictionary per site within the unit cell. Each dictionary has two keys:
53 * 'tag', string of 1 to 8 characters (``'a'``, ``'Mo'``,
54 ``'Se1'``). Label of the associated sublattice.
55 * 'r0', Tuple. Position: :math:`(x, y)`, or :math:`(x, y, z)` for a
56 lattice in 3D space.
57 prim_vec : List of tuples
58 Define the primitive vectors. List of one/two/three tuples for 1D/2D/3D
59 lattices, each the cartesian coordinates of a primitive vector: 2-tuples
60 in the plane, or 3-tuples in 3D space (then *r0* must be 3-tuples too,
61 and *coor* gains a 'z' field, see :data:`COOR_DTYPE_3D`).
63 Notes
64 -----
65 In 3D space, the geometry methods acting in the plane (*rotation*,
66 *ellipse_in*, *boundary_line*, ...) act on :math:`(x, y)` only (rotation
67 about the z axis, cylinders, vertical planes), and *plot* draws the
68 projection on the :math:`(x, y)` plane.
70 Examples
71 --------
72 Example usage::
74 # Line-Centered Square lattice
75 unit_cell = [{'tag': 'a', 'r0': (0., 0.)}, {'tag': 'a', 'r0': (0., 1.)}]
76 prim_vec = [(0, 2), (2, 0)]
77 lat = lattice(unit_cell=unit_cell, prim_vec=prim_vec)
78 '''
80 def __init__(self, unit_cell: list[dict], prim_vec: Sequence[tuple[float, ...]]) -> None:
81 error_handling.unit_cell(unit_cell)
82 error_handling.prim_vec(prim_vec)
83 error_handling.space_dim(unit_cell, prim_vec)
84 self.unit_cell = unit_cell
85 self.prim_vec = prim_vec
86 self.tags = np.unique(np.array([dic['tag'] for dic in self.unit_cell]))
87 self.space_dim = len(prim_vec[0]) # 2, or 3 for a lattice in 3D space
88 self.dtype = COOR_DTYPE if self.space_dim == 2 else COOR_DTYPE_3D
89 self.n1, self.n2, self.n3 = 0, 0, 0
90 self.coor = np.array([], dtype=self.dtype)
91 self.sites = 0
93 def get_lattice(self, n1: int, n2: int = 1, n3: int = 1) -> None:
94 r'''
95 Get the lattice positions, sorted by (y, x) -- by (z, y, x) in 3D space.
97 Parameters
98 ----------
99 n1 : Positive Integer
100 Number of unit cells along :math:`\mathbf{a}_1`.
101 n2 : Positive Integer, default 1
102 Number of unit cells along :math:`\mathbf{a}_2`.
103 n3 : Positive Integer, default 1
104 Number of unit cells along :math:`\mathbf{a}_3` (3D lattices only).
106 Examples
107 --------
108 Example usage::
110 # Line-Centered Square lattice
111 unit_cell = [{'tag': 'a', 'r0': (0., 0.)}, {'tag': 'a', 'r0': (0., 1.)}]
112 prim_vec = [(0, 2), (2, 0)]
113 lat = lattice(unit_cell=unit_cell, prim_vec=prim_vec)
114 lat.get_lattice(n1=4, n2=5)
115 '''
116 error_handling.get_lattice(self.prim_vec, n1, n2, n3)
117 sites_uc = len(self.unit_cell)
118 sites_tag = n1*n2*n3
119 self.sites = sites_uc * sites_tag
120 self.coor = np.empty(self.sites, dtype=self.dtype)
121 self.n1, self.n2, self.n3 = n1, n2, n3
122 # translations R = i1 a1 + i2 a2 (+ i3 a3), i1 running fastest
123 axes = [f for f in ('x', 'y', 'z')[:self.space_dim]]
124 trans = np.zeros((sites_tag, self.space_dim))
125 counts = (n1, n2, n3)
126 index = np.indices(counts[:max(len(self.prim_vec), 1)][::-1]).reshape(
127 max(len(self.prim_vec), 1), -1)[::-1]
128 for n, a in zip(index, self.prim_vec):
129 trans += n[:, None] * np.array(a, dtype='f8')[None, :]
130 for i, dic in enumerate(self.unit_cell):
131 for c, f in enumerate(axes):
132 self.coor[f][i*sites_tag: (i+1)*sites_tag] = trans[:, c] + dic['r0'][c]
133 self.coor['tag'][i*sites_tag: (i+1)*sites_tag] = dic['tag']
134 self.coor = np.sort(self.coor, order=self.sort_order())
136 def sort_order(self) -> tuple[str, ...]:
137 '''
138 Private method. Fields the sites are sorted by: ('y', 'x'), or
139 ('z', 'y', 'x') in 3D space.
140 '''
141 return ('y', 'x') if self.space_dim == 2 else ('z', 'y', 'x')
143 def distances(self) -> tuple[NDArray, ...]:
144 '''
145 Private method. Pairwise coordinate differences, *d[i, j]* from site
146 *i* to site *j*: (dx, dy), or (dx, dy, dz) in 3D space.
147 '''
148 return tuple(self.coor[f] - self.coor[f].reshape(self.sites, 1)
149 for f in ('x', 'y', 'z')[:self.space_dim])
151 def add_sites(self, coor: NDArray) -> None:
152 '''
153 Add sites.
155 Parameters
156 ----------
157 coor
158 Structured array with keys: {'x', 'y', 'tag'}
159 ({'x', 'y', 'z', 'tag'} for a lattice in 3D space), with a tag
160 field from 'U1' to 'U8'.
162 Examples
163 --------
164 Example usage::
166 # Square lattice
167 unit_cell = [{'tag': 'a', 'r0': (0., 0.)}]
168 prim_vec = [(0, 1), (1, 0)]
169 lat = lattice(unit_cell=unit_cell, prim_vec=prim_vec)
170 lat.get_lattice(n1=2, n2=2)
171 coor = np.array([(-1., -1, 'b'), (-2., -2, 'c')],
172 dtype=[('x', 'f8'), ('y', 'f8'), ('tag', 'U1')])
173 lat.add_sites(coor)
174 '''
175 error_handling.coor(coor, self.dtype)
176 self.coor = np.concatenate([self.coor, coor.astype(self.dtype)])
177 self.sites += len(coor)
178 self.tags = np.unique(np.concatenate([self.tags, coor['tag']]))
179 self.coor = np.sort(self.coor, order=self.sort_order())
181 def remove_sites(self, index: list[int]) -> None:
182 '''
183 Remove sites defined by their indices
184 (use method lattice.plot(plt_index=True)
185 to get access to the site indices).
187 Parameters
188 ----------
189 index : List
190 Site indices to be removed.
192 Examples
193 --------
194 Example usage::
196 # Square lattice
197 unit_cell = [{'tag': 'a', 'r0': (0., 0.)}]
198 prim_vec = [(0, 1), (1, 0)]
199 lat = lattice(unit_cell=unit_cell, prim_vec=prim_vec)
200 lat.get_lattice(n1=2, n2=2)
201 lat.remove_sites([0, 2])
202 '''
203 error_handling.empty_coor(self.coor)
204 error_handling.remove_sites(index, self.sites)
205 mask = np.ones(self.sites, bool)
206 mask[index] = False
207 self.coor = self.coor[mask]
208 self.sites = self.coor.size
210 def remove_dangling(self) -> None:
211 '''
212 Remove dangling sites
213 (sites connected with just another site).
214 '''
215 error_handling.empty_coor(self.coor)
216 while True:
217 coords = np.stack([self.coor[f] for f in ('x', 'y', 'z')[:self.space_dim]], axis=1)
218 tree = cKDTree(coords)
219 near = tree.query(coords, k=min(self.sites, 8))[0][:, 1:]
220 len_hop = np.min(near[near > 0]) # the shortest distance between sites
221 pairs = tree.query_pairs(len_hop * (1. + 1e-5) + 1e-8, output_type='ndarray')
222 dis = np.linalg.norm(coords[pairs[:, 1]] - coords[pairs[:, 0]], axis=1)
223 pairs = pairs[np.isclose(dis, len_hop)]
224 degree = np.bincount(pairs.ravel(), minlength=self.sites)
225 dang = list(np.flatnonzero(degree == 1))
226 self.coor = np.delete(self.coor, dang, axis=0)
227 self.sites -= len(dang)
228 if dang == []:
229 break
231 def shift_x(self, shift: float) -> None:
232 '''
233 Shift the x coordinates.
235 Parameters
236 ----------
237 shift : Real number
238 Shift value.
239 '''
240 error_handling.empty_coor(self.coor)
241 error_handling.real_number(shift, 'shift')
242 self.coor['x'] += shift
244 def shift_y(self, shift: float) -> None:
245 '''
246 Shift the y coordinates.
248 Parameters
249 ----------
250 shift : Real number
251 Shift value.
252 '''
253 error_handling.empty_coor(self.coor)
254 error_handling.real_number(shift, 'shift')
255 self.coor['y'] += shift
257 def change_sign_x(self) -> None:
258 '''
259 Change x coordinates sign.
260 '''
261 error_handling.empty_coor(self.coor)
262 self.coor['x'] *= -1
264 def change_sign_y(self) -> None:
265 '''
266 Change y coordinates sign.
267 '''
268 error_handling.empty_coor(self.coor)
269 self.coor['y'] *= -1
271 def shift_z(self, shift: float) -> None:
272 '''
273 Shift the z coordinates (3D lattices only).
275 Parameters
276 ----------
277 shift : Real number
278 Shift value.
279 '''
280 error_handling.empty_coor(self.coor)
281 error_handling.space_3d(self.space_dim)
282 error_handling.real_number(shift, 'shift')
283 self.coor['z'] += shift
285 def change_sign_z(self) -> None:
286 '''
287 Change z coordinates sign (3D lattices only).
288 '''
289 error_handling.empty_coor(self.coor)
290 error_handling.space_3d(self.space_dim)
291 self.coor['z'] *= -1
293 def slab(self, z_min: float, z_max: float) -> None:
294 r'''
295 Keep only the sites with :math:`z_{min} < z < z_{max}` (3D lattices only).
297 Parameters
298 ----------
299 z_min : Real number
300 z_max : Real number, larger than *z_min*
301 '''
302 error_handling.empty_coor(self.coor)
303 error_handling.space_3d(self.space_dim)
304 error_handling.real_number(z_min, 'z_min')
305 error_handling.real_number(z_max, 'z_max')
306 error_handling.smaller(z_min, 'z_min', z_max, 'z_max')
307 self.coor = self.coor[(self.coor['z'] > z_min) & (self.coor['z'] < z_max)]
308 self.sites = len(self.coor)
310 def boundary_line(self, cx: float, cy: float, co: float) -> None:
311 r'''
312 Keep only the sites with :math:`c_yy+c_xx > c_0`.
314 Parameters
315 ----------
316 cx : Real number
317 :math:`c_x` value.
318 cy : Real number
319 :math:`c_y` value.
320 co : Real number
321 :math:`c_0` value.
322 '''
323 error_handling.empty_coor(self.coor)
324 error_handling.real_number(cx, 'cx')
325 error_handling.real_number(cy, 'cy')
326 error_handling.real_number(co, 'co')
327 self.coor = self.coor[cy * self.coor['y'] + cx * self.coor['x'] > co]
328 self.sites = len(self.coor)
330 def ellipse_in(self, rx: float, ry: float, x0: float, y0: float) -> None:
331 r'''
332 Select sites according to
334 .. math::
336 (x-x_0)^2/r_x^2+(y-y_0)^2/r_y^2 < 1\, .
338 Parameters
339 ----------
340 rx : Positive Real number
341 Radius along :math:`x`.
342 ry : Positive Real number
343 Radius along :math:`y`.
344 x0 : Real number
345 :math:`x` center.
346 y0 : Real number
347 :math:`y` center.
348 '''
349 error_handling.empty_coor(self.coor)
350 error_handling.positive_real(rx, 'rx')
351 error_handling.positive_real(ry, 'ry')
352 error_handling.real_number(x0, 'x0')
353 error_handling.real_number(y0, 'y0')
354 self.coor = self.coor[(self.coor['x'] -x0) ** 2 / rx ** 2 + \
355 (self.coor['y'] -y0) ** 2 / ry ** 2 < 1.]
356 self.sites = len(self.coor)
358 def ellipse_out(self, rx: float, ry: float, x0: float, y0: float) -> None:
359 r'''
360 Select sites according to
362 .. math::
364 (x-x_0)^2/r_x^2+(y-y_0)^2/r_y^2 > 1\, .
366 Parameters
367 ----------
368 rx : Positive Real number
369 Radius along :math:`x`.
370 ry : Positive Real number
371 Radius along :math:`y`.
372 x0 : Real number
373 :math:`x` center.
374 y0 : Real number
375 :math:`y` center.
376 '''
377 error_handling.empty_coor(self.coor)
378 error_handling.positive_real(rx, 'rx')
379 error_handling.positive_real(ry, 'ry')
380 error_handling.real_number(x0, 'x0')
381 error_handling.real_number(y0, 'y0')
382 self.coor = self.coor[(self.coor['x'] -x0) ** 2 / rx ** 2 + \
383 (self.coor['y'] -y0) ** 2 / ry ** 2 > 1.]
384 self.sites = len(self.coor)
386 def center(self) -> None:
387 '''
388 Fix the center of mass of the lattice at (0, 0) -- (0, 0, 0) in 3D space.
389 '''
390 error_handling.empty_coor(self.coor)
391 for f in ('x', 'y', 'z')[:self.space_dim]:
392 self.coor[f] -= np.mean(self.coor[f])
394 def rotation(self, theta: float) -> None:
395 r'''
396 Rotate the lattice structure about the origin (about the z axis, in
397 3D space) by the angle :math:`\theta`.
399 Parameters
400 ----------
401 theta
402 Rotation angle in degrees.
403 '''
404 error_handling.empty_coor(self.coor)
405 error_handling.real_number(theta, 'theta')
406 theta *= PI / 180
407 x = self.coor['x'].copy()
408 y = self.coor['y'].copy()
409 self.coor['x'] = x * np.cos(theta) - y * np.sin(theta)
410 self.coor['y'] = y * np.cos(theta) + x * np.sin(theta)
412 def clean_coor(self) -> None:
413 '''
414 Keep only the sites with different coordinates.
415 '''
416 error_handling.empty_coor(self.coor)
417 fields = list(('x', 'y', 'z')[:self.space_dim])
418 coor = self.coor[fields].copy()
419 for f in fields:
420 coor[f] = self.coor[f].round(4)
421 _, idx = np.unique(coor, return_index=True)
422 self.coor = self.coor[idx]
423 self.sites = len(self.coor)
425 def __add__(self, other: 'Lattice') -> 'Lattice':
426 '''
427 Overloading operator +.
428 '''
429 error_handling.lat(other)
430 error_handling.empty_coor(self.coor)
431 error_handling.empty_coor(other.coor)
432 coor = np.concatenate([self.coor, other.coor])
433 tags = np.concatenate([self.tags, other.tags])
434 lat = lattice(unit_cell=self.unit_cell, prim_vec=self.prim_vec)
435 lat.add_sites(coor)
436 lat.sites = self.sites + other.sites
437 lat.tags = np.unique(tags)
438 return lat
440 def __iadd__(self, other: 'Lattice') -> 'Lattice':
441 '''
442 Overloading operator +=.
443 '''
444 error_handling.lat(other)
445 error_handling.empty_coor(self.coor)
446 error_handling.empty_coor(other.coor)
447 self.coor = np.concatenate([self.coor, other.coor])
448 self.sites += other.sites
449 self.tags = np.unique(np.concatenate([self.tags, other.tags]))
450 return self
452 def __sub__(self, other: 'Lattice') -> 'Lattice':
453 '''
454 Overloading operator -.
456 .. note::
458 The tags are not considered in the lattice subtraction.
459 '''
460 error_handling.lat(other)
461 error_handling.empty_coor(self.coor)
462 error_handling.empty_coor(other.coor)
463 boo = self.overlaps(other)
464 coor = self.coor[np.logical_not(boo)]
465 lat = lattice(unit_cell=self.unit_cell, prim_vec=self.prim_vec)
466 lat.add_sites(coor)
467 lat.sites = len(lat.coor)
468 lat.tags = self.tags
469 return lat
471 def __isub__(self, other: 'Lattice') -> 'Lattice':
472 '''
473 Overloading operator -=.
475 .. note::
477 The tags are not considered in the lattice subtraction.
478 '''
479 error_handling.lat(other)
480 error_handling.empty_coor(self.coor)
481 error_handling.empty_coor(other.coor)
482 boo = self.overlaps(other)
483 self.coor = self.coor[np.logical_not(boo)]
484 self.sites = int(np.sum(np.logical_not(boo)))
485 return self
487 def overlaps(self, other: 'Lattice') -> NDArray[np.bool_]:
488 '''
489 Private method. Mask of the sites of *self* that coincide with a site
490 of *other*.
491 '''
492 names = self.coor.dtype.names or ()
493 fields = [f for f in ('x', 'y', 'z') if f in names]
494 boo = np.zeros(self.sites, bool)
495 for c in other.coor:
496 match = np.ones(self.sites, bool)
497 for f in fields:
498 match &= np.isclose(c[f] if f in (other.coor.dtype.names or ()) else 0., self.coor[f])
499 boo += match
500 return boo
502 def plot(
503 self,
504 ms: float = 20,
505 fs: float = 20,
506 plt_index: bool = False,
507 axis: bool = False,
508 figsize: tuple[float, float] | None = None,
509 ) -> Figure:
510 '''
511 Plot the lattice in real space (its projection on the (x, y) plane,
512 in 3D space).
514 Parameters
515 ----------
516 ms : Positive number, default 20
517 Markersize.
518 fs : Positive number, default 20
519 Fontsize.
520 plt_index : Boolean, default False
521 Plot site labels.
522 axis : Boolean, default False
523 Plot axis.
524 figsize : Tuple, default None
525 Figsize.
527 Returns
528 -------
529 fig : Figure
530 '''
531 error_handling.empty_coor(self.coor)
532 error_handling.positive_real(ms, 'ms')
533 error_handling.positive_real(fs, 'fs')
534 error_handling.boolean(plt_index, 'plt_index')
535 error_handling.boolean(axis, 'axis')
536 if figsize is None:
537 figsize = (5, 5)
538 error_handling.list_tuple_2elem(figsize, 'figsize')
539 error_handling.positive_real(figsize[0], 'figsize[0]')
540 error_handling.positive_real(figsize[1], 'figsize[1]')
541 fig, ax = plt.subplots(figsize=figsize)
542 # plot sites
543 colors = ['b', 'r', 'g', 'y', 'm', 'k']
544 for color, tag in zip(colors, self.tags):
545 plt.plot(self.coor['x'][self.coor['tag'] == tag],
546 self.coor['y'][self.coor['tag'] == tag],
547 'o', color=color, ms=ms, markeredgecolor='none')
548 ax.set_aspect('equal')
549 ax.set_xlim(np.min(self.coor['x'])-1., np.max(self.coor['x'])+1.)
550 ax.set_ylim(np.min(self.coor['y'])-1., np.max(self.coor['y'])+1.)
551 if not axis:
552 ax.axis('off')
553 # plot indices
554 if plt_index:
555 indices = ['{}'.format(i) for i in range(self.sites)]
556 for l, x, y in zip(indices, self.coor['x'], self.coor['y']):
557 plt.annotate(l, xy=(x, y), xytext=(0, 0),
558 textcoords='offset points',
559 ha='right', va='bottom', size=fs)
560 plt.draw()
561 return fig
563 def show(self) -> None:
564 """
565 Emulate Matplotlib method plt.show().
566 """
567 plt.show()
570# Backward-compatible lowercase alias (pre-0.2 API).
571lattice = Lattice