"""The relation between a primitive cell and a supercell, and the q-points it implies.
:class:`Lattice` bundles the integer repetition matrix `P` with the
commensurate q-points it defines. :func:`get_P_matrix` and
:func:`get_supercell_qpoints_along_path` are the standalone entry points.
"""
import warnings
from fractions import Fraction
from functools import cached_property
import numpy as np
from numpy.typing import NDArray
from dynasor.qpoints.tools import exact_inverse, _find_on_line, _get_commensurate_points
[docs]
class Lattice:
r"""Relates a primitive cell to a supercell and provides the commensurate q-points.
The class serves two purposes: it holds the integer repetition matrix `P`
connecting the two cells, and it hands out the q-points that a simulation in
that supercell can actually resolve, via :attr:`q_reduced`, :attr:`q_cartesian`
and :meth:`make_path`.
The supercell `S` is given by the primitive cell `p` and a repetition
matrix `P` such that:
dot(P, p) = S
In this convention the cell vectors are row vectors of `p` and `S` as in
ASE. An inverse cell is defined as:
c_inv = inv(c).T
and the reciprocal cell is defined as:
c_rec = 2*pi*inv(c).T
Notice that the inverse cell here is defined with the transpose so that
the lattice vectors of the inverse/reciprocal lattice are also row
vectors. The above also implies:
dot(P.T, S_inv) = p_inv
The inverse supercell S_inv defines a new lattice in reciprocal space.
Those inverse lattice points which reside inside the inverse primitive
cell p_inv are called commensurate lattice points. These are typically
the only points of interest in MD simulations from a crystallographic
and lattice dynamics point of view.
The convention taken here is that the reciprocal cell carries the 2pi
factor onto the cartesian q-points. This is consistent with e.g.
Kittel. The reduced coordinates are always with respect to the
reciprocal primitive cell.
Parameters
----------
primitive_cell
Cell metric of the primitive cell with lattice vectors as rows.
supercell_cell
Cell metric of the supercell with lattice vectors as rows.
Example
-------
>>> from ase.build import bulk
>>> from dynasor.qpoints import Lattice
>>> prim = bulk('Al', 'fcc', a=4.0)
>>> lattice = Lattice(prim.cell, prim.repeat(2).cell)
>>> len(lattice.q_cartesian)
8
"""
def __init__(self, primitive_cell: NDArray[float], supercell_cell: NDArray[float]):
self._primitive_cell = np.array(primitive_cell)
self._supercell_cell = np.array(supercell_cell)
self._P = get_P_matrix(self._primitive_cell, self._supercell_cell)
# The q-points are computed on first use, since callers that only want a path
# through the Brillouin zone need nothing but P.
@cached_property
def _q_reduced(self) -> NDArray[Fraction]:
# As stated in the doc the P matrix relating the inverse cells are just P.T
return _get_commensurate_points(self._P.T)
@cached_property
def _q_minus(self) -> NDArray[int]:
# exact fractions, so the -q partner is found by an exact tuple match
index = {tuple(q): i for i, q in enumerate(self._q_reduced)}
return np.array([index[tuple((-q) % 1)] for q in self._q_reduced])
@property
def primitive_cell(self) -> NDArray[float]:
"""Returns the primitive cell with lattice vectors as rows"""
return self._primitive_cell.copy()
@property
def supercell_cell(self) -> NDArray[float]:
"""Returns the supercell with lattice vectors as rows"""
return self._supercell_cell.copy()
@property
def reciprocal_primitive_cell(self) -> NDArray[float]:
"""Returns 2*pi*inv(primitive_cell).T so that the rows are the inverse lattice vectors"""
return 2*np.pi * np.linalg.inv(self._primitive_cell.T)
@property
def reciprocal_supercell_cell(self) -> NDArray[float]:
"""Returns 2*pi*inv(supercell_cell).T so that the rows are the inverse lattice vectors"""
return 2*np.pi * np.linalg.inv(self._supercell_cell.T)
@property
def P(self) -> NDArray[int]:
"""The P-matrix for this system, P @ primitive_cell = supercell_cell"""
return self._P.copy()
@property
def P_inv(self) -> NDArray[Fraction]:
"""Inverse of :attr:`P` as exact :class:`fractions.Fraction` values."""
return exact_inverse(self._P)
@property
def q_reduced(self) -> NDArray[Fraction]:
"""The commensurate q-points in reduced coordinates, as exact fractions.
This is an object array, so it is not a drop-in numerical array;
``np.allclose``, ``np.isfinite`` and ``np.round`` raise :class:`TypeError`
on it, while ``.astype(float)``, arithmetic and ``np.sort`` work.
"""
return self._q_reduced.copy()
@property
def q_cartesian(self) -> NDArray[float]:
"""The commensurate q-points in Cartesian coordinates with unit of rad/Å."""
return self.reduced_to_cartesian(self._q_reduced)
@property
def q_minus(self) -> NDArray[int]:
"""For each q-point, the index of the q-point corresponding to :math:`-q`."""
return self._q_minus.copy()
def __repr__(self) -> str:
rep = (f'{self.__class__.__name__}('
f'primitive_cell={self._primitive_cell.tolist()}, '
f'supercell_cell={self._supercell_cell.tolist()})')
return rep
[docs]
def reduced_to_cartesian(self, qpoints: NDArray[float]) -> NDArray[float]:
"""Convert from reduced to cartesian coordinates.
Accepts the exact fractions returned by :attr:`q_reduced` as well as floats.
"""
return np.asarray(qpoints, dtype=float) @ self.reciprocal_primitive_cell
[docs]
def cartesian_to_reduced(self, qpoints: NDArray[float]) -> NDArray[float]:
"""Convert from Cartesian to reduced coordinates."""
qpoints = np.asarray(qpoints, dtype=float)
return np.linalg.solve(self.reciprocal_primitive_cell.T, qpoints.T).T
[docs]
def make_path(
self,
start: NDArray[float],
stop: NDArray[float],
) -> tuple[NDArray[float], NDArray[float]]:
"""Takes qpoints in reduced coordinates and returns all points in between
Parameters
----------
start
Coordinate of starting point in reduced inverse coordinates.
For example, a zone mode is given as (0.5, 0, 0), (0,0,0) == (1,0,0) etc.
stop
Stop position.
Returns
-------
Tuple of the coordinates of commensurate points along path in Cartesian
reciprocals and the fractional distances along the path.
"""
# float, since integer input gives Fractions with unhashable numpy numerators
start = np.asarray(start, dtype=float)
stop = np.asarray(stop, dtype=float)
fracs = _find_on_line(start, stop, self._P.T)
if not len(fracs):
warnings.warn('No q-points along path!')
return np.zeros(shape=(0, 3)), np.zeros(shape=(0,))
points = np.array([start + float(f) * (stop - start) for f in fracs])
qpoints = self.reduced_to_cartesian(points)
dists = np.array([float(f) for f in fracs])
return qpoints, dists
[docs]
def get_P_matrix(
c: NDArray[float],
S: NDArray[float],
) -> NDArray[int]:
"""Returns the P matrix, i.e., the `3x3` integer matrix :math:`P` that satisfies
.. math::
P c = S
Here, :math:`c` is the primitive cell metric and :math:`S` is the
supercell metric as row vectors. Note that the above condition is
equivalent to:
.. math::
c^T P^T = S^T
Parameters
----------
c
Cell metric of the primitive structure.
S
Cell metric of the supercell.
"""
PT = np.linalg.solve(np.asarray(c).T, np.asarray(S).T)
P_float = PT.T
P = np.round(P_float).astype(int)
if not np.allclose(P_float, P) or not np.allclose(P @ c, S):
raise ValueError(
f'Please check that the supercell metric ({S}) is related to the'
f' primitive cell {c} by an integer transformation matrix.')
return P
[docs]
def get_supercell_qpoints_along_path(
path: list[tuple[str, str]],
coordinates: dict[str, NDArray[float]],
primitive_cell: NDArray[float],
supercell_cell: NDArray[float]) -> list[NDArray[float]]:
r"""
Returns the q-points commensurate with the given supercell along the specific path.
Parameters
----------
path
List of pairs of q-point labels.
coordinates
Dict with q-point labels and coordinates as keys and values, respectively;
there must be one entry for each q-point label used in :attr:`path`.
primitive_cell
Cell metric of the primitive cell with lattice vectors as rows.
supercell_cell
Cell metric of the supercell with lattice vectors as rows.
Returns
-------
A list of the accessible q-point coordinates along the specified segment.
Example
-------
The following example illustrates how to retrieve the q-points that
can be sampled using a supercell comprising :math:`6 \times 6 \times 6`
conventional (4-atom) unit cells of FCC Al along the path X-:math:`\Gamma`-L.
>>> import numpy as np
>>> from ase.build import bulk
>>> from dynasor.qpoints import get_supercell_qpoints_along_path
>>> prim = bulk('Al', 'fcc', a=4.0)
>>> supercell = bulk('Al', 'fcc', a=4.0, cubic=True).repeat(6)
>>> path = [('X', 'G'), ('G', 'L'), ('L', 'W')]
>>> coordinates = dict(X=[0.5, 0.5, 0], G=[0, 0, 0],
... L=[0.5, 0.5, 0.5], W=[0.5, 0.25, 0.75])
>>> qpoints = get_supercell_qpoints_along_path(
... path, coordinates, prim.cell, supercell.cell)
"""
for lbl in np.array(path).flatten():
if lbl not in coordinates:
raise ValueError(f'Unknown point in path: {lbl}')
lattice = Lattice(primitive_cell, supercell_cell)
# build the segments
supercell_paths = []
for l1, l2 in path:
q1 = np.array(coordinates[l1], dtype=float)
q2 = np.array(coordinates[l2], dtype=float)
dynasor_path, _ = lattice.make_path(q1, q2)
supercell_paths.append(dynasor_path)
return supercell_paths
[docs]
def is_qpoint_commensurate(
q_point: NDArray[float],
cell: NDArray[float],
atol: float = 1e-5,
) -> bool:
r"""Return whether a single q-point is commensurate with a periodic cell.
A q-point is commensurate with the cell when it is a reciprocal-lattice
vector of that cell, i.e. when its reduced coordinates
:math:`m_i = \mathbf{q}\cdot\mathbf{a}_i / 2\pi` are all integers, where the
:math:`\mathbf{a}_i` are the cell vectors (rows of :attr:`cell`). Only then
is :math:`\rho(\mathbf{q}) = \sum_j e^{i\mathbf{q}\cdot\mathbf{r}_j}`
independent of which periodic image is chosen for each atom; at other
q-points the correlation functions can contain artifacts.
The reduced coordinates are formed with the full cell matrix, so the test is
correct for non-orthogonal cells (a per-axis check would not be).
Parameters
----------
q_point
A single q-point ``(3,)`` in Cartesian coordinates (rad/Å).
cell
Cell metric with lattice vectors as rows (Å).
atol
Absolute tolerance on the reduced coordinates when testing for integers.
"""
q_point = np.asarray(q_point, dtype=float)
cell = np.asarray(cell, dtype=float)
reduced = q_point @ cell.T / (2 * np.pi) # m_i = q . a_i / 2pi
return bool(np.all(np.abs(reduced - np.rint(reduced)) < atol))