Merge pull request #266 from phonopy/spglib-v2_5

Update to follow phonopy update for spglib v2.5
This commit is contained in:
Atsushi Togo 2024-08-23 11:50:59 +09:00 committed by GitHub
commit e0d68109a3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 49 additions and 32 deletions

View File

@ -244,6 +244,9 @@ def start_phono3py(**argparse_control) -> tuple[argparse.Namespace, int]:
print("Python version %d.%d.%d" % sys.version_info[:3]) print("Python version %d.%d.%d" % sys.version_info[:3])
import spglib import spglib
try: # spglib.get_version() is deprecated.
print(f"Spglib version {spglib.spg_get_version()}")
except AttributeError:
print("Spglib version %d.%d.%d" % spglib.get_version()) print("Spglib version %d.%d.%d" % spglib.get_version())
if deprecated: if deprecated:

View File

@ -38,6 +38,13 @@ from __future__ import annotations
import warnings import warnings
from collections.abc import Sequence from collections.abc import Sequence
try:
from spglib import SpglibDataset
except ImportError:
from types import SimpleNamespace as SpglibDataset
from typing import Optional, Union from typing import Optional, Union
import numpy as np import numpy as np
@ -137,7 +144,7 @@ class BZGrid:
mesh: Union[int, float, Sequence, np.ndarray], mesh: Union[int, float, Sequence, np.ndarray],
reciprocal_lattice=None, reciprocal_lattice=None,
lattice=None, lattice=None,
symmetry_dataset: Optional[dict] = None, symmetry_dataset: Optional[Union[SpglibDataset]] = None,
transformation_matrix: Optional[Union[Sequence, np.ndarray]] = None, transformation_matrix: Optional[Union[Sequence, np.ndarray]] = None,
is_shift: Optional[Union[list, np.ndarray]] = None, is_shift: Optional[Union[list, np.ndarray]] = None,
is_time_reversal: bool = True, is_time_reversal: bool = True,
@ -156,9 +163,10 @@ class BZGrid:
lattice : array_like lattice : array_like
Direct primitive basis vectors given as row vectors shape=(3, 3), Direct primitive basis vectors given as row vectors shape=(3, 3),
dtype='double', order='C' dtype='double', order='C'
symmetry_dataset : dict, optional symmetry_dataset : SpglibDataset, optional
Symmetry dataset (Symmetry.dataset) searched for the primitive cell Symmetry dataset (Symmetry.dataset) searched for the primitive cell
corresponding to ``reciprocal_lattice`` or ``lattice``. corresponding to ``reciprocal_lattice`` or ``lattice``. For spglib <
v2.5, SimpleNamespace is used instead of SpglibDataset.
transformation_matrix : array_like, optional transformation_matrix : array_like, optional
Transformation matrix equivalent to ``transformation_matrix`` in Transformation matrix equivalent to ``transformation_matrix`` in
spglib-dataset. This is only used when ``use_grg=True`` and spglib-dataset. This is only used when ``use_grg=True`` and
@ -384,7 +392,7 @@ class BZGrid:
return self._reciprocal_operations return self._reciprocal_operations
@property @property
def symmetry_dataset(self): def symmetry_dataset(self) -> SpglibDataset:
"""Return Symmetry.dataset.""" """Return Symmetry.dataset."""
return self._symmetry_dataset return self._symmetry_dataset
@ -472,7 +480,7 @@ class BZGrid:
direct_rotations = np.eye(3, dtype="int_", order="C").reshape(1, 3, 3) direct_rotations = np.eye(3, dtype="int_", order="C").reshape(1, 3, 3)
else: else:
direct_rotations = np.array( direct_rotations = np.array(
self._symmetry_dataset["rotations"], dtype="int_", order="C" self._symmetry_dataset.rotations, dtype="int_", order="C"
) )
rec_rotations = np.zeros((48, 3, 3), dtype="int_", order="C") rec_rotations = np.zeros((48, 3, 3), dtype="int_", order="C")
num_rec_rot = recgrid.reciprocal_rotations( num_rec_rot = recgrid.reciprocal_rotations(
@ -530,7 +538,7 @@ class GridMatrix:
self, self,
mesh: Union[int, float, Sequence, np.ndarray], mesh: Union[int, float, Sequence, np.ndarray],
lattice: Union[Sequence, np.ndarray], lattice: Union[Sequence, np.ndarray],
symmetry_dataset: Optional[dict] = None, symmetry_dataset: Optional[SpglibDataset] = None,
transformation_matrix: Optional[Union[list, np.ndarray]] = None, transformation_matrix: Optional[Union[list, np.ndarray]] = None,
use_grg: bool = True, use_grg: bool = True,
force_SNF: bool = False, force_SNF: bool = False,
@ -547,9 +555,10 @@ class GridMatrix:
lattice : array_like lattice : array_like
Primitive basis vectors in direct space given as row vectors. Primitive basis vectors in direct space given as row vectors.
shape=(3, 3), dtype='double', order='C' shape=(3, 3), dtype='double', order='C'
symmetry_dataset : dict, optional symmetry_dataset : SpglibDataset, optional
Symmetry dataset of spglib (Symmetry.dataset) of primitive cell that Symmetry dataset of spglib (Symmetry.dataset) of primitive cell that
has `lattice`. Default is None. has `lattice`. Default is None. For spglib <
v2.5, SimpleNamespace is used instead of SpglibDataset.
transformation_matrix : array_like, optional transformation_matrix : array_like, optional
Transformation matrix equivalent to ``transformation_matrix`` in Transformation matrix equivalent to ``transformation_matrix`` in
spglib-dataset. This is only used when ``use_grg=True`` and spglib-dataset. This is only used when ``use_grg=True`` and
@ -627,7 +636,7 @@ class GridMatrix:
self, self,
mesh: Union[int, float, Sequence, np.ndarray], mesh: Union[int, float, Sequence, np.ndarray],
use_grg: bool = False, use_grg: bool = False,
symmetry_dataset: Optional[dict] = None, symmetry_dataset: Optional[SpglibDataset] = None,
transformation_matrix: Optional[Union[list, np.ndarray]] = None, transformation_matrix: Optional[Union[list, np.ndarray]] = None,
force_SNF=False, force_SNF=False,
coordinates="reciprocal", coordinates="reciprocal",
@ -673,7 +682,7 @@ class GridMatrix:
self._D_diag = length2mesh(length, self._lattice) self._D_diag = length2mesh(length, self._lattice)
else: else:
self._D_diag = length2mesh( self._D_diag = length2mesh(
length, self._lattice, rotations=symmetry_dataset["rotations"] length, self._lattice, rotations=symmetry_dataset.rotations
) )
if num_values == 9: if num_values == 9:
self._run_grg( self._run_grg(
@ -703,7 +712,7 @@ class GridMatrix:
sym_dataset = symmetry_dataset sym_dataset = symmetry_dataset
else: # transformation_matrix is not None else: # transformation_matrix is not None
sym_dataset = self._get_mock_symmetry_dataset(transformation_matrix) sym_dataset = self._get_mock_symmetry_dataset(transformation_matrix)
if is_primitive_cell(sym_dataset["rotations"]): if is_primitive_cell(sym_dataset.rotations):
self._set_GRG_mesh( self._set_GRG_mesh(
sym_dataset, sym_dataset,
length=length, length=length,
@ -742,18 +751,23 @@ class GridMatrix:
"be equal to or larger than 1." "be equal to or larger than 1."
) )
raise RuntimeError(msg) raise RuntimeError(msg)
sym_dataset = {
from types import SimpleNamespace
sym_dataset = SimpleNamespace(
**{
"rotations": np.eye(3, dtype="intc", order="C").reshape(1, 3, 3), "rotations": np.eye(3, dtype="intc", order="C").reshape(1, 3, 3),
"transformation_matrix": transformation_matrix, "transformation_matrix": transformation_matrix,
"std_lattice": self._lattice, "std_lattice": self._lattice,
"std_types": np.array([1], dtype="intc"), "std_types": np.array([1], dtype="intc"),
"number": 1, "number": 1,
} }
)
return sym_dataset return sym_dataset
def _set_GRG_mesh( def _set_GRG_mesh(
self, self,
sym_dataset: dict, sym_dataset: SpglibDataset,
length: Optional[float] = None, length: Optional[float] = None,
grid_matrix=None, grid_matrix=None,
force_SNF=False, force_SNF=False,
@ -807,22 +821,22 @@ class GridMatrix:
`reciprocal` (default) or `direct`. `reciprocal` (default) or `direct`.
""" """
tmat = sym_dataset["transformation_matrix"] tmat = sym_dataset.transformation_matrix
conv_lat = np.dot(np.linalg.inv(tmat).T, self._lattice) conv_lat = np.dot(np.linalg.inv(tmat).T, self._lattice)
# GRG is wanted to be generated with respect to std_lattice if possible. # GRG is wanted to be generated with respect to std_lattice if possible.
if _can_use_std_lattice( if _can_use_std_lattice(
conv_lat, conv_lat,
tmat, tmat,
sym_dataset["std_lattice"], sym_dataset.std_lattice,
sym_dataset["rotations"], sym_dataset.rotations,
): ):
conv_lat = sym_dataset["std_lattice"] conv_lat = sym_dataset.std_lattice
tmat = np.dot(self._lattice, np.linalg.inv(conv_lat)).T tmat = np.dot(self._lattice, np.linalg.inv(conv_lat)).T
if coordinates == "direct": if coordinates == "direct":
num_cells = int(np.prod(length2mesh(length, conv_lat))) num_cells = int(np.prod(length2mesh(length, conv_lat)))
max_num_atoms = num_cells * len(sym_dataset["std_types"]) max_num_atoms = num_cells * len(sym_dataset.std_types)
conv_mesh_numbers = estimate_supercell_matrix( conv_mesh_numbers = estimate_supercell_matrix(
sym_dataset, max_num_atoms=max_num_atoms, max_iter=200 sym_dataset, max_num_atoms=max_num_atoms, max_iter=200
) )

View File

@ -772,8 +772,8 @@ class Interaction:
# perms.shape = (len(spg_ops), len(primitive)), dtype='intc' # perms.shape = (len(spg_ops), len(primitive)), dtype='intc'
perms = compute_all_sg_permutations( perms = compute_all_sg_permutations(
self._primitive.scaled_positions, self._primitive.scaled_positions,
self._bz_grid.symmetry_dataset["rotations"], self._bz_grid.symmetry_dataset.rotations,
self._bz_grid.symmetry_dataset["translations"], self._bz_grid.symmetry_dataset.translations,
np.array(self._primitive.cell.T, dtype="double", order="C"), np.array(self._primitive.cell.T, dtype="double", order="C"),
symprec=self._symprec, symprec=self._symprec,
) )
@ -821,13 +821,13 @@ class Interaction:
""" """
d2r_map = [] d2r_map = []
for r in self._bz_grid.symmetry_dataset["rotations"]: for r in self._bz_grid.symmetry_dataset.rotations:
for i, rec_r in enumerate(self._bz_grid.reciprocal_operations): for i, rec_r in enumerate(self._bz_grid.reciprocal_operations):
if (rec_r.T == r).all(): if (rec_r.T == r).all():
d2r_map.append(i) d2r_map.append(i)
break break
assert len(d2r_map) == len(self._bz_grid.symmetry_dataset["rotations"]) assert len(d2r_map) == len(self._bz_grid.symmetry_dataset.rotations)
return d2r_map return d2r_map
@ -838,7 +838,7 @@ class Interaction:
""" """
Rq = np.dot(self._bz_grid.QDinv, self._bz_grid.addresses[bzgp]) Rq = np.dot(self._bz_grid.QDinv, self._bz_grid.addresses[bzgp])
tau = self._bz_grid.symmetry_dataset["translations"][t_i] tau = self._bz_grid.symmetry_dataset.translations[t_i]
phase_factor = np.exp(-2j * np.pi * np.dot(Rq, tau)) phase_factor = np.exp(-2j * np.pi * np.dot(Rq, tau))
self._phonon_done[bzgp] = 1 self._phonon_done[bzgp] = 1
self._frequencies[bzgp, :] = self._frequencies[orig_gp, :] self._frequencies[bzgp, :] = self._frequencies[orig_gp, :]

View File

@ -2425,7 +2425,7 @@ def test_GridMatrix_with_grid_matrix(ph_nacl: Phonopy):
np.testing.assert_array_equal(gm.grid_matrix, mesh) np.testing.assert_array_equal(gm.grid_matrix, mesh)
np.testing.assert_array_equal(gm.D_diag, [9, 18, 18]) np.testing.assert_array_equal(gm.D_diag, [9, 18, 18])
tmat = ph_nacl.primitive_symmetry.dataset["transformation_matrix"] tmat = ph_nacl.primitive_symmetry.dataset.transformation_matrix
gm = GridMatrix(mesh, ph_nacl.primitive.cell, transformation_matrix=tmat) gm = GridMatrix(mesh, ph_nacl.primitive.cell, transformation_matrix=tmat)
np.testing.assert_array_equal(gm.grid_matrix, mesh) np.testing.assert_array_equal(gm.grid_matrix, mesh)
np.testing.assert_array_equal(gm.D_diag, [9, 18, 18]) np.testing.assert_array_equal(gm.D_diag, [9, 18, 18])
@ -2439,7 +2439,7 @@ def test_GridMatrix_with_transformation_matrix(ph_nacl: Phonopy):
""" """
mesh = 50.0 mesh = 50.0
tmat = ph_nacl.primitive_symmetry.dataset["transformation_matrix"] tmat = ph_nacl.primitive_symmetry.dataset.transformation_matrix
gm = GridMatrix( gm = GridMatrix(
mesh, mesh,
ph_nacl.primitive.cell, ph_nacl.primitive.cell,