Merge pull request #413 from phonopy/refactoring

Refactoring and adding typehints
This commit is contained in:
Atsushi Togo 2025-07-18 15:02:04 +09:00 committed by GitHub
commit 35dd083b3a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 219 additions and 168 deletions

View File

@ -37,6 +37,7 @@
import numpy as np
from phono3py.other.isotope import Isotope
from phono3py.phonon.grid import BZGrid
class Phono3pyIsotope:
@ -81,7 +82,7 @@ class Phono3pyIsotope:
return self._iso.dynamical_matrix
@property
def grid(self):
def grid(self) -> BZGrid:
"""Return BZGrid class instance."""
return self._iso.bz_grid

View File

@ -34,7 +34,10 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
import numpy as np
from phonopy.harmonic.dynamical_matrix import DynamicalMatrix
from phonopy.physical_units import get_physical_units
from phonopy.structure.cells import Primitive, Supercell
from phonopy.structure.symmetry import Symmetry
@ -116,7 +119,7 @@ class Phono3pyJointDos:
self.initialize(mesh)
@property
def grid(self):
def grid(self) -> BZGrid | None:
"""Return BZGrid class instance."""
return self._bz_grid
@ -293,7 +296,7 @@ class Phono3pyJointDos:
print('JDOS is written into "%s".' % filename)
@property
def dynamical_matrix(self):
def dynamical_matrix(self) -> DynamicalMatrix:
"""Return DynamicalMatrix class instance."""
return self._jdos.dynamical_matrix

View File

@ -38,10 +38,10 @@ from __future__ import annotations
import copy
import warnings
from collections.abc import Sequence
from typing import Literal, Optional, Union, cast
from typing import Literal, cast
import numpy as np
from numpy.typing import NDArray
from numpy.typing import ArrayLike, NDArray
from phonopy.harmonic.displacement import (
directions_to_displacement_dataset,
get_least_displacements,
@ -151,19 +151,19 @@ class Phono3py:
def __init__(
self,
unitcell: PhonopyAtoms,
supercell_matrix=None,
primitive_matrix=None,
phonon_supercell_matrix=None,
cutoff_frequency=1e-4,
frequency_factor_to_THz=None,
is_symmetry=True,
is_mesh_symmetry=True,
use_grg=False,
SNF_coordinates="reciprocal",
supercell_matrix: ArrayLike | None = None,
primitive_matrix: ArrayLike | None = None,
phonon_supercell_matrix: ArrayLike | None = None,
cutoff_frequency: float = 1e-4,
frequency_factor_to_THz: float | None = None,
is_symmetry: bool = True,
is_mesh_symmetry: bool = True,
use_grg: bool = False,
SNF_coordinates: str = "reciprocal",
make_r0_average: bool = True,
symprec=1e-5,
calculator: Optional[str] = None,
log_level=0,
symprec: float = 1e-5,
calculator: str | None = None,
log_level: int = 0,
):
"""Init method.
@ -236,7 +236,7 @@ class Phono3py:
self._make_r0_average = make_r0_average
self._cutoff_frequency = cutoff_frequency
self._calculator: Optional[str] = calculator
self._calculator = calculator
self._log_level = log_level
# Create supercell and primitive cell
@ -264,9 +264,7 @@ class Phono3py:
self._build_phonon_supercell()
self._build_phonon_primitive_cell()
self._sigmas = [
None,
]
self._sigmas = [None]
self._sigma_cutoff = None
# Grid
@ -330,7 +328,7 @@ class Phono3py:
return __version__
@property
def calculator(self) -> Optional[str]:
def calculator(self) -> str | None:
"""Return calculator interface name.
str
@ -428,7 +426,7 @@ class Phono3py:
self._sigmas.append(None)
@property
def sigma_cutoff(self) -> Optional[float]:
def sigma_cutoff(self) -> float | None:
"""Setter and getter of Smearing cutoff width.
This is given as a multiple of the standard deviation.
@ -445,7 +443,7 @@ class Phono3py:
self._sigma_cutoff = sigma_cutoff
@property
def nac_params(self) -> Optional[dict]:
def nac_params(self) -> dict | None:
"""Setter and getter of parameters for non-analytical term correction.
dict
@ -469,7 +467,7 @@ class Phono3py:
self._init_dynamical_matrix()
@property
def dynamical_matrix(self) -> Optional[DynamicalMatrix]:
def dynamical_matrix(self) -> DynamicalMatrix | None:
"""Return DynamicalMatrix instance.
This is not dynamical matrices but the instance of DynamicalMatrix
@ -609,7 +607,7 @@ class Phono3py:
return self._frequency_factor_to_THz
@property
def dataset(self) -> Optional[dict]:
def dataset(self) -> dict | None:
"""Setter and getter of displacement-force dataset.
dict
@ -671,7 +669,7 @@ class Phono3py:
self._phonon_supercells_with_displacements = None
@property
def phonon_dataset(self) -> Optional[dict]:
def phonon_dataset(self) -> dict | None:
"""Setter and getter of displacement-force dataset for fc2.
dict
@ -716,7 +714,7 @@ class Phono3py:
self._phonon_supercells_with_displacements = None
@property
def mlp_dataset(self) -> Optional[dict]:
def mlp_dataset(self) -> dict | None:
"""Return displacement-force dataset.
The supercell matrix is equal to that of usual displacement-force
@ -732,7 +730,7 @@ class Phono3py:
self._mlp_dataset = mlp_dataset
@property
def phonon_mlp_dataset(self) -> Optional[dict]:
def phonon_mlp_dataset(self) -> dict | None:
"""Return phonon displacement-force dataset.
The phonon supercell matrix is equal to that of usual displacement-force
@ -846,7 +844,7 @@ class Phono3py:
return self._bz_grid.D_diag
@mesh_numbers.setter
def mesh_numbers(self, mesh_numbers: Union[int, float, Sequence, NDArray]):
def mesh_numbers(self, mesh_numbers: float | ArrayLike):
self._set_mesh_numbers(mesh_numbers)
@property
@ -1399,12 +1397,12 @@ class Phono3py:
def generate_fc2_displacements(
self,
distance: Optional[float] = None,
distance: float | None = None,
is_plusminus: str = "auto",
is_diagonal: bool = False,
number_of_snapshots: Optional[Union[int, Literal["auto"]]] = None,
random_seed: Optional[int] = None,
max_distance: Optional[float] = None,
number_of_snapshots: int | Literal["auto"] | None = None,
random_seed: int | None = None,
max_distance: float | None = None,
):
"""Generate displacement dataset in phonon supercell for fc2.
@ -2099,16 +2097,16 @@ class Phono3py:
def run_thermal_conductivity(
self,
is_LBTE: bool = False,
temperatures: Optional[Sequence] = None,
temperatures: Sequence | None = None,
is_isotope: bool = False,
mass_variances: Optional[Sequence] = None,
grid_points: Optional[Sequence[int]] = None,
boundary_mfp: Optional[float] = None, # in micrometer
mass_variances: Sequence | None = None,
grid_points: ArrayLike | None = None,
boundary_mfp: float | None = None, # in micrometer
solve_collective_phonon: bool = False,
use_ave_pp: bool = False,
is_reducible_collision_matrix: bool = False,
is_kappa_star: bool = True,
gv_delta_q: Optional[float] = None, # for group velocity
gv_delta_q: float | None = None, # for group velocity
is_full_pp: bool = False,
pinv_cutoff: float = 1.0e-8, # for pseudo-inversion of collision matrix
pinv_method: int = 0, # for pseudo-inversion of collision matrix
@ -2116,18 +2114,18 @@ class Phono3py:
write_gamma: bool = False,
read_gamma: bool = False,
is_N_U: bool = False,
conductivity_type: Optional[str] = None,
conductivity_type: str | None = None,
write_kappa: bool = False,
write_gamma_detail: bool = False,
write_collision: bool = False,
read_collision: bool = False,
read_collision: str | Sequence | None = None,
write_pp: bool = False,
read_pp: bool = False,
write_LBTE_solution: bool = False,
compression: str = "gzip",
input_filename: Optional[str] = None,
output_filename: Optional[str] = None,
log_level: Optional[int] = None,
input_filename: str | None = None,
output_filename: str | None = None,
log_level: int | None = None,
):
"""Run thermal conductivity calculation.
@ -2234,9 +2232,9 @@ class Phono3py:
is written into a file. With multiple `sigmas` specified,
respective files are created. Be careful that this file can be
huge.
read_collision : bool, optional, default is False
Direct solution only (`is_LBTE=True`). With True, collision matrix
is read from a file.
read_collision : str | Sequence, optional, default is None.
Direct solution only (`is_LBTE=True`). With specified, collision
matrix is read from a file.
write_pp : bool, optional, default is False
With True, phonon-phonon interaction strength is written into
files at each grid point. This option assumes single value is in
@ -2408,14 +2406,14 @@ class Phono3py:
test_size=test_size,
)
def save_mlp(self, filename: Optional[str] = None):
def save_mlp(self, filename: str | None = None):
"""Save machine learning potential."""
if self._mlp is None:
raise RuntimeError("MLP is not developed yet.")
self._mlp.save(filename=filename)
def load_mlp(self, filename: Optional[str] = None):
def load_mlp(self, filename: str | None = None):
"""Load machine learning potential."""
self._mlp = PhonopyMLP(log_level=self._log_level)
self._mlp.load(filename=filename)
@ -2445,7 +2443,7 @@ class Phono3py:
def develop_phonon_mlp(
self,
params: Optional[Union[PypolymlpParams, dict, str]] = None,
params: PypolymlpParams | dict | str | None = None,
test_size: float = 0.1,
):
"""Develop MLP for fc2.
@ -2472,14 +2470,14 @@ class Phono3py:
test_size=test_size,
)
def save_phonon_mlp(self, filename: Optional[str] = None):
def save_phonon_mlp(self, filename: str | None = None):
"""Save machine learning potential."""
if self._mlp is None:
raise RuntimeError("MLP is not developed yet.")
self._phonon_mlp.save(filename=filename)
def load_phonon_mlp(self, filename: Optional[str] = None):
def load_phonon_mlp(self, filename: str | None = None):
"""Load machine learning potential."""
self._phonon_mlp = PhonopyMLP(log_level=self._log_level)
self._phonon_mlp.load(filename=filename)
@ -2690,7 +2688,7 @@ class Phono3py:
def _set_mesh_numbers(
self,
mesh: Union[int, float, Sequence, NDArray],
mesh: float | ArrayLike,
):
# initialization related to mesh
self._interaction = None

View File

@ -41,7 +41,7 @@ from abc import ABC, abstractmethod
from typing import Optional
import numpy as np
from numpy.typing import NDArray
from numpy.typing import ArrayLike, NDArray
from phonopy.phonon.group_velocity import GroupVelocity
from phonopy.phonon.thermal_properties import mode_cv
from phonopy.physical_units import get_physical_units
@ -419,12 +419,12 @@ class ConductivityBase(ABC):
def __init__(
self,
interaction: Interaction,
grid_points: np.ndarray | None = None,
temperatures: list | np.ndarray | None = None,
sigmas: list | np.ndarray | None = None,
grid_points: ArrayLike | None = None,
temperatures: ArrayLike | None = None,
sigmas: ArrayLike | None = None,
sigma_cutoff: float | None = None,
is_isotope=False,
mass_variances: list | np.ndarray | None = None,
mass_variances: ArrayLike | None = None,
boundary_mfp: float | None = None,
is_kappa_star: bool = True,
is_full_pp: bool = False,

View File

@ -36,9 +36,10 @@
from __future__ import annotations
from typing import Optional, Union
import os
import numpy as np
from numpy.typing import ArrayLike
from phono3py.conductivity.base import ConductivityComponents
from phono3py.conductivity.direct_solution_base import (
@ -54,20 +55,20 @@ class ConductivityLBTE(ConductivityLBTEBase):
def __init__(
self,
interaction: Interaction,
grid_points: Optional[np.ndarray] = None,
temperatures: Optional[Union[list, np.ndarray]] = None,
sigmas: Optional[Union[list, np.ndarray]] = None,
sigma_cutoff: Optional[float] = None,
grid_points: ArrayLike | None = None,
temperatures: ArrayLike | None = None,
sigmas: ArrayLike | None = None,
sigma_cutoff: float | None = None,
is_isotope: bool = False,
mass_variances: Optional[Union[list, np.ndarray]] = None,
boundary_mfp: Optional[float] = None, # in micrometer
mass_variances: ArrayLike | None = None,
boundary_mfp: float | None = None, # in micrometer
solve_collective_phonon: bool = False,
is_reducible_collision_matrix: bool = False,
is_kappa_star: bool = True,
gv_delta_q: Optional[float] = None,
gv_delta_q: float | None = None,
is_full_pp: bool = False,
read_pp: bool = False,
pp_filename: Optional[float] = None,
pp_filename: str | os.PathLike | None = None,
pinv_cutoff: float = 1.0e-8,
pinv_solver: int = 0,
pinv_method: int = 0,

View File

@ -36,12 +36,14 @@
from __future__ import annotations
import os
import sys
import time
from abc import abstractmethod
from typing import Optional, Union
from typing import Optional
import numpy as np
from numpy.typing import ArrayLike
from phonopy.phonon.degeneracy import degenerate_sets
from phonopy.physical_units import get_physical_units
@ -63,19 +65,19 @@ class ConductivityLBTEBase(ConductivityBase):
def __init__(
self,
interaction: Interaction,
grid_points: Optional[np.ndarray] = None,
temperatures: Optional[Union[list, np.ndarray]] = None,
sigmas: Optional[Union[list, np.ndarray]] = None,
sigma_cutoff: Optional[float] = None,
grid_points: ArrayLike | None = None,
temperatures: ArrayLike | None = None,
sigmas: ArrayLike | None = None,
sigma_cutoff: float | None = None,
is_isotope: bool = False,
mass_variances: Optional[Union[list, np.ndarray]] = None,
boundary_mfp: Optional[float] = None, # in micrometer
mass_variances: ArrayLike | None = None,
boundary_mfp: float | None = None, # in micrometer
solve_collective_phonon: bool = False,
is_reducible_collision_matrix: bool = False,
is_kappa_star: bool = True,
is_full_pp: bool = False,
read_pp: bool = False,
pp_filename: Optional[float] = None,
pp_filename: str | os.PathLike | None = None,
pinv_cutoff: float = 1.0e-8,
pinv_solver: int = 0,
pinv_method: int = 0,

View File

@ -34,8 +34,14 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
import os
import sys
from typing import Optional, Union
from collections.abc import Sequence
from typing import Union
from numpy.typing import ArrayLike
from phono3py.conductivity.base import get_unit_to_WmK
from phono3py.conductivity.direct_solution import ConductivityLBTE
@ -59,32 +65,32 @@ cond_LBTE_type = Union[ConductivityLBTE, ConductivityWignerLBTE]
def get_thermal_conductivity_LBTE(
interaction: Interaction,
temperatures=None,
sigmas=None,
sigma_cutoff=None,
is_isotope=False,
mass_variances=None,
grid_points=None,
boundary_mfp=None, # in micrometer
solve_collective_phonon=False,
is_reducible_collision_matrix=False,
is_kappa_star=True,
gv_delta_q=None,
is_full_pp=False,
conductivity_type=None,
pinv_cutoff=1.0e-8,
pinv_solver=0, # default: dsyev in lapacke
pinv_method=0, # default: abs(eig) < cutoff
write_collision=False,
read_collision=False,
write_kappa=False,
write_pp=False,
read_pp=False,
write_LBTE_solution=False,
compression="gzip",
input_filename=None,
output_filename=None,
log_level=0,
temperatures: Sequence | None = None,
sigmas: Sequence | None = None,
sigma_cutoff: float | None = None,
is_isotope: bool = False,
mass_variances: Sequence | None = None,
grid_points: ArrayLike | None = None,
boundary_mfp: float | None = None, # in micrometer
solve_collective_phonon: bool = False,
is_reducible_collision_matrix: bool = False,
is_kappa_star: bool = True,
gv_delta_q: float | None = None,
is_full_pp: bool = False,
conductivity_type: str | None = None,
pinv_cutoff: float = 1.0e-8,
pinv_solver: int = 0, # default: dsyev in lapacke
pinv_method: int = 0, # default: abs(eig) < cutoff
write_collision: bool = False,
read_collision: str | Sequence | None = None,
write_kappa: bool = False,
write_pp: bool = False,
read_pp: bool = False,
write_LBTE_solution: bool = False,
compression: str = "gzip",
input_filename: str | os.PathLike | None = None,
output_filename: str | os.PathLike | None = None,
log_level: int = 0,
):
"""Calculate lattice thermal conductivity by direct solution."""
if temperatures is None:
@ -292,9 +298,9 @@ class ConductivityLBTEWriter:
volume: float,
is_reducible_collision_matrix: bool = False,
write_LBTE_solution: bool = False,
pinv_solver: Optional[int] = None,
pinv_solver: int | None = None,
compression: str = "gzip",
filename: Optional[str] = None,
filename: str | os.PathLike | None = None,
log_level: int = 0,
):
"""Write kappa related properties into a hdf5 file."""
@ -473,7 +479,7 @@ class ConductivityLBTEWriter:
def _set_collision_from_file(
lbte: ConductivityLBTEBase,
indices="all",
indices: str | Sequence | None = "all",
is_reducible_collision_matrix=False,
filename=None,
log_level=0,

View File

@ -34,6 +34,8 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
import numpy as np
from phonopy.physical_units import get_physical_units

View File

@ -34,6 +34,8 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
import sys
from phonopy.cui.phonopy_argparse import fix_deprecated_option_names

View File

@ -42,10 +42,10 @@ import pathlib
import sys
import warnings
from collections.abc import Sequence
from typing import Optional, cast
from typing import cast
import numpy as np
from numpy.typing import NDArray
from numpy.typing import ArrayLike, NDArray
from phonopy.api_phonopy import Phonopy
from phonopy.cui.phonopy_argparse import show_deprecated_option_warnings
from phonopy.cui.phonopy_script import (
@ -60,6 +60,7 @@ from phonopy.cui.phonopy_script import (
from phonopy.cui.settings import PhonopySettings
from phonopy.exception import CellNotFoundError, ForceCalculatorRequiredError
from phonopy.file_IO import is_file_phonopy_yaml
from phonopy.harmonic.dynamical_matrix import DynamicalMatrixGL
from phonopy.harmonic.force_constants import show_drift_force_constants
from phonopy.interface.calculator import get_calculator_physical_units
from phonopy.interface.symfc import estimate_symfc_cutoff_from_memsize
@ -235,7 +236,7 @@ def _start_phono3py(**argparse_control) -> tuple[argparse.Namespace, int]:
# Title
if log_level:
print_phono3py()
import phono3py._phono3py as phono3c
import phono3py._phono3py as phono3c # type: ignore[import]
max_threads = phono3c.omp_max_threads()
if max_threads > 0:
@ -503,7 +504,9 @@ def _init_phono3py(
return phono3py, updated_settings
def _settings_to_grid_points(settings: Phono3pySettings, bz_grid: BZGrid):
def _settings_to_grid_points(
settings: Phono3pySettings, bz_grid: BZGrid
) -> ArrayLike | None:
"""Read or set grid point indices."""
if settings.grid_addresses is not None:
grid_points = _grid_addresses_to_grid_points(settings.grid_addresses, bz_grid)
@ -514,7 +517,7 @@ def _settings_to_grid_points(settings: Phono3pySettings, bz_grid: BZGrid):
return grid_points
def _grid_addresses_to_grid_points(grid_addresses: NDArray, bz_grid: BZGrid):
def _grid_addresses_to_grid_points(grid_addresses: NDArray, bz_grid: BZGrid) -> NDArray:
"""Return grid point indices from grid addresses."""
grid_points = [
get_grid_point_from_address(ga, bz_grid.D_diag) for ga in grid_addresses
@ -527,7 +530,7 @@ def _create_supercells_with_displacements(
cell_info: Phono3pyCellInfoResult,
confs_dict: dict,
unitcell_filename: str,
interface_mode: Optional[str],
interface_mode: str | None,
symprec: float,
log_level: int,
):
@ -690,7 +693,10 @@ def _produce_force_constants(
def _run_gruneisen_then_exit(
phono3py: Phono3py, settings: Phono3pySettings, output_filename: str, log_level: int
phono3py: Phono3py,
settings: Phono3pySettings,
output_filename: str | os.PathLike | None,
log_level: int,
):
"""Run mode Grueneisen parameter calculation from fc3."""
if (
@ -703,6 +709,8 @@ def _run_gruneisen_then_exit(
print_error()
sys.exit(1)
assert phono3py.fc2 is not None
assert phono3py.fc3 is not None
if len(phono3py.fc2) != len(phono3py.fc3):
print("Supercells used for fc2 and fc3 have to be same.")
if log_level:
@ -775,9 +783,10 @@ def _run_jdos_then_exit(
if log_level > 0:
dm = joint_dos.dynamical_matrix
if dm.is_nac() and dm.nac_method == "gonze":
dm.show_Gonze_nac_message()
if isinstance(dm, DynamicalMatrixGL):
dm.show_nac_message()
assert joint_dos.grid is not None
grid_points = _settings_to_grid_points(settings, joint_dos.grid)
joint_dos.run(grid_points, write_jdos=True)
@ -819,8 +828,8 @@ def _run_isotope_then_exit(
)
if log_level > 0:
dm = iso.dynamical_matrix
if dm.is_nac() and dm.nac_method == "gonze":
dm.show_Gonze_nac_message()
if isinstance(dm, DynamicalMatrixGL):
dm.show_nac_message()
grid_points = _settings_to_grid_points(settings, iso.grid)
iso.run(grid_points)
@ -841,7 +850,8 @@ def _init_phph_interaction(
"""Initialize ph-ph interaction and phonons on grid."""
if log_level:
print("Generating grid system ... ", end="", flush=True)
phono3py.mesh_numbers = settings.mesh_numbers
assert phono3py.grid is not None
assert phono3py.mesh_numbers is not None
bz_grid = phono3py.grid
if log_level:
if bz_grid.grid_matrix is None:
@ -872,7 +882,7 @@ def _init_phph_interaction(
if log_level:
print("-" * 27 + " Phonon calculations " + "-" * 28)
dm = phono3py.dynamical_matrix
if dm.is_nac() and dm.nac_method == "gonze":
if isinstance(dm, DynamicalMatrixGL):
dm.show_nac_message()
print("Running harmonic phonon calculations...")
sys.stdout.flush()
@ -1131,6 +1141,7 @@ def main(**argparse_control):
"show_triplets_info",
)
run_modes_with_gp = ("imag_self_energy", "real_self_energy", "jdos", "isotope")
if settings.mesh_numbers is None and run_mode in run_modes_with_mesh:
print("")
print("Mesh numbers have to be specified.")
@ -1151,11 +1162,19 @@ def main(**argparse_control):
print_error()
sys.exit(1)
####################
# Set mesh numbers #
####################
if run_mode in run_modes_with_mesh:
assert settings.mesh_numbers is not None
if run_mode not in ("jdos", "isotope"):
ph3py.mesh_numbers = settings.mesh_numbers
#########################################################
# Write ir-grid points and grid addresses and then exit #
#########################################################
if run_mode == "write_grid_info":
ph3py.mesh_numbers = settings.mesh_numbers
assert ph3py.grid is not None
write_grid_points(
ph3py.primitive,
ph3py.grid,
@ -1175,7 +1194,7 @@ def main(**argparse_control):
# Show reduced number of triplets at grid points and then exit #
################################################################
if run_mode == "show_triplets_info":
ph3py.mesh_numbers = settings.mesh_numbers
assert ph3py.grid is not None
grid_points = _settings_to_grid_points(settings, ph3py.grid)
show_num_triplets(
ph3py.primitive,
@ -1338,6 +1357,7 @@ def main(**argparse_control):
# Run imaginary part of self energy of bubble diagram #
#######################################################
if run_mode == "imag_self_energy":
assert ph3py.grid is not None
ph3py.run_imag_self_energy(
_settings_to_grid_points(settings, ph3py.grid),
updated_settings["temperature_points"],
@ -1354,6 +1374,7 @@ def main(**argparse_control):
# Run frequency shift calculation of bubble diagram #
#####################################################
elif run_mode == "real_self_energy":
assert ph3py.grid is not None
ph3py.run_real_self_energy(
_settings_to_grid_points(settings, ph3py.grid),
updated_settings["temperature_points"],
@ -1368,6 +1389,7 @@ def main(**argparse_control):
# Run spectral function calculation of bubble diagram #
#######################################################
elif run_mode == "spectral_function":
assert ph3py.grid is not None
ph3py.run_spectral_function(
_settings_to_grid_points(settings, ph3py.grid),
updated_settings["temperature_points"],
@ -1383,6 +1405,7 @@ def main(**argparse_control):
# Run lattice thermal conductivity #
####################################
elif run_mode == "conductivity-RTA" or run_mode == "conductivity-LBTE":
assert ph3py.grid is not None
grid_points = _settings_to_grid_points(settings, ph3py.grid)
ph3py.run_thermal_conductivity(
is_LBTE=settings.is_lbte,

View File

@ -34,10 +34,12 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from collections.abc import Sequence
from typing import Optional, Union
from __future__ import annotations
import os
import numpy as np
from numpy.typing import ArrayLike
from phonopy.structure.atoms import PhonopyAtoms
from phono3py.file_IO import write_grid_address_to_hdf5, write_ir_grid_points
@ -48,13 +50,13 @@ from phono3py.phonon3.triplets import get_triplets_at_q
def write_grid_points(
primitive: PhonopyAtoms,
bz_grid: BZGrid,
band_indices: Optional[Union[Sequence, np.ndarray]] = None,
sigmas: Optional[Union[Sequence, np.ndarray]] = None,
temperatures: Optional[Union[Sequence, np.ndarray]] = None,
band_indices: ArrayLike | None = None,
sigmas: ArrayLike | None = None,
temperatures: ArrayLike | None = None,
is_kappa_star: bool = True,
is_lbte: bool = False,
compression: Union[str, int] = "gzip",
filename: bool = None,
compression: str | int = "gzip",
filename: str | os.PathLike | None = None,
):
"""Write grid points into files."""
ir_grid_points, ir_grid_weights = _get_ir_grid_points(
@ -109,8 +111,8 @@ def write_grid_points(
def show_num_triplets(
primitive: PhonopyAtoms,
bz_grid: BZGrid,
band_indices: Optional[Union[Sequence, np.ndarray]] = None,
grid_points: Optional[Union[Sequence, np.ndarray]] = None,
band_indices: ArrayLike | None = None,
grid_points: ArrayLike | None = None,
is_kappa_star: bool = True,
):
"""Show numbers of triplets at grid points."""

View File

@ -54,6 +54,7 @@ from phonopy.file_IO import (
write_FORCE_SETS,
)
from phono3py.phonon.grid import BZGrid
from phono3py.version import __version__
@ -483,9 +484,9 @@ def write_grid_address_to_hdf5(
grid_address,
mesh,
grid_mapping_table,
bz_grid=None,
compression: Union[str, int] = "gzip",
filename=None,
bz_grid: BZGrid | None = None,
compression: str | int = "gzip",
filename: str | os.PathLike | None = None,
):
"""Write grid addresses to grid_address.hdf5."""
suffix = _get_filename_suffix(mesh, filename=filename)
@ -1155,7 +1156,7 @@ def read_gamma_from_hdf5(
def read_collision_from_hdf5(
mesh,
indices=None,
indices: str | Sequence = "all",
grid_point=None,
band_index=None,
sigma=None,

View File

@ -36,9 +36,8 @@
from __future__ import annotations
from typing import Optional, Union
import numpy as np
from numpy.typing import ArrayLike
from phonopy.harmonic.dynamical_matrix import get_dynamical_matrix
from phonopy.phonon.tetrahedron_mesh import get_tetrahedra_frequencies
from phonopy.physical_units import get_physical_units
@ -58,9 +57,9 @@ from phono3py.phonon.solver import run_phonon_solver_c, run_phonon_solver_py
def get_mass_variances(
primitive: Optional[PhonopyAtoms] = None,
symbols: Optional[Union[list[str], tuple[str]]] = None,
isotope_data: Optional[dict] = None,
primitive: PhonopyAtoms | None = None,
symbols: list[str] | tuple[str] | None = None,
isotope_data: dict | None = None,
):
"""Calculate mass variances."""
if primitive is not None:
@ -93,14 +92,14 @@ class Isotope:
def __init__(
self,
mesh,
primitive,
mesh: float | ArrayLike,
primitive: Primitive,
mass_variances=None, # length of list is num_atom.
isotope_data=None,
band_indices=None,
sigma=None,
bz_grid=None,
frequency_factor_to_THz=None,
bz_grid: BZGrid | None = None,
frequency_factor_to_THz: float | None = None,
use_grg=False,
symprec=1e-5,
cutoff_frequency=None,
@ -116,7 +115,6 @@ class Isotope:
self._mass_variances = np.array(mass_variances, dtype="double")
self._primitive = primitive
self._sigma = sigma
self._bz_grid = bz_grid
self._symprec = symprec
if cutoff_frequency is None:
self._cutoff_frequency = 0
@ -143,7 +141,7 @@ class Isotope:
else:
self._band_indices = np.array(band_indices, dtype="int64")
if self._bz_grid is None:
if bz_grid is None:
primitive_symmetry = Symmetry(self._primitive, self._symprec)
self._bz_grid = BZGrid(
self._mesh,
@ -152,6 +150,8 @@ class Isotope:
use_grg=use_grg,
store_dense_gp_map=True,
)
else:
self._bz_grid = bz_grid
def set_grid_point(self, grid_point):
"""Initialize grid points."""
@ -196,8 +196,9 @@ class Isotope:
return self._gamma
@property
def bz_grid(self):
def bz_grid(self) -> BZGrid:
"""Return BZgrid class instance."""
assert self._bz_grid is not None
return self._bz_grid
@property

View File

@ -144,12 +144,12 @@ class BZGrid:
def __init__(
self,
mesh: Union[int, float, Sequence, np.ndarray],
reciprocal_lattice=None,
lattice=None,
symmetry_dataset: Optional[SpglibDataset] = None,
transformation_matrix: Optional[Union[Sequence, np.ndarray]] = None,
is_shift: Optional[Union[list, np.ndarray]] = None,
mesh: float | ArrayLike,
reciprocal_lattice: ArrayLike | None = None,
lattice: ArrayLike | None = None,
symmetry_dataset: SpglibDataset | None = None,
transformation_matrix: ArrayLike | None = None,
is_shift: ArrayLike | None = None,
is_time_reversal: bool = True,
use_grg: bool = False,
force_SNF: bool = False,

View File

@ -34,7 +34,14 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
import numpy as np
from phonopy.harmonic.dynamical_matrix import (
DynamicalMatrix,
DynamicalMatrixGL,
DynamicalMatrixNAC,
)
from phonopy.physical_units import get_physical_units
from phonopy.structure.cells import sparse_to_dense_svecs
@ -81,8 +88,8 @@ def run_phonon_solver_c(
'U' or 'L' for lapack zheev solver. Default is 'L'.
"""
import phono3py._phono3py as phono3c
import phono3py._phononcalc as phononcalc
import phono3py._phono3py as phono3c # type: ignore[import-untyped]
import phono3py._phononcalc as phononcalc # type: ignore[import-untyped]
if frequency_conversion_factor is None:
_frequency_conversion_factor = get_physical_units().DefaultToTHz
@ -100,7 +107,7 @@ def run_phonon_solver_c(
dielectric,
) = _extract_params(dm)
if dm.is_nac() and dm.nac_method == "gonze":
if isinstance(dm, DynamicalMatrixGL):
gonze_nac_dataset = dm.Gonze_nac_dataset
if gonze_nac_dataset[0] is None:
dm.make_Gonze_nac_dataset()
@ -112,6 +119,7 @@ def run_phonon_solver_c(
G_list, # List of G points where d-d interactions are integrated.
Lambda,
) = gonze_nac_dataset # Convergence parameter
assert Lambda is not None
fc = gonze_fc
use_GL_NAC = True
else:
@ -120,7 +128,7 @@ def run_phonon_solver_c(
dd_q0 = np.zeros(2) # dummy variable
G_list = np.zeros(3) # dummy variable
Lambda = 0 # dummy variable
if not dm.is_nac():
if not isinstance(dm, DynamicalMatrixNAC):
born = np.zeros((3, 3)) # dummy variable
dielectric = np.zeros(3) # dummy variable
fc = dm.force_constants
@ -168,7 +176,7 @@ def run_phonon_solver_c(
dd_q0,
G_list,
float(Lambda),
dm.is_nac() * 1,
isinstance(dm, DynamicalMatrixNAC) * 1,
is_nac_q_zero * 1,
use_GL_NAC * 1,
lapack_zheev_uplo,
@ -207,14 +215,14 @@ def run_phonon_solver_py(
dynamical_matrix.run(q)
dm = dynamical_matrix.dynamical_matrix
eigvals, eigvecs = np.linalg.eigh(dm, UPLO=lapack_zheev_uplo)
eigvals = eigvals.real
eigvals = eigvals.real # type: ignore[no-untyped-call]
frequencies[gp] = (
np.sqrt(np.abs(eigvals)) * np.sign(eigvals) * frequency_conversion_factor
)
eigenvectors[gp] = eigvecs
def _extract_params(dm):
def _extract_params(dm: DynamicalMatrix | DynamicalMatrixNAC):
svecs, multi = dm.primitive.get_smallest_vectors()
if dm.primitive.store_dense_svecs:
_svecs = svecs
@ -225,7 +233,7 @@ def _extract_params(dm):
masses = np.array(dm.primitive.masses, dtype="double")
rec_lattice = np.array(np.linalg.inv(dm.primitive.cell), dtype="double", order="C")
positions = np.array(dm.primitive.positions, dtype="double", order="C")
if dm.is_nac():
if isinstance(dm, DynamicalMatrixNAC):
born = dm.born
nac_factor = dm.nac_factor
dielectric = dm.dielectric_constant

View File

@ -35,6 +35,7 @@
# POSSIBILITY OF SUCH DAMAGE.
import numpy as np
from phonopy.harmonic.dynamical_matrix import DynamicalMatrixGL
from phonopy.phonon.group_velocity import GroupVelocity
from phonopy.physical_units import get_physical_units
@ -210,11 +211,7 @@ class VelocityOperator(GroupVelocity):
if np.linalg.norm(q) < np.linalg.norm(delta_q):
flag_gamma = True
if (
(self._dynmat.is_nac())
and (self._dynmat.nac_method == "gonze")
and flag_gamma
):
if isinstance(dynmat, DynamicalMatrixGL) and flag_gamma:
dynmat.run(
q - delta_q, q_direction=(q - delta_q) / np.linalg.norm(q - delta_q)
)

View File

@ -37,7 +37,11 @@
import sys
import numpy as np
from phonopy.harmonic.dynamical_matrix import get_dynamical_matrix
from phonopy.harmonic.dynamical_matrix import (
DynamicalMatrixGL,
DynamicalMatrixNAC,
get_dynamical_matrix,
)
from phonopy.physical_units import get_physical_units
from phonopy.structure.atoms import PhonopyAtoms
from phonopy.structure.cells import Primitive
@ -96,8 +100,8 @@ def run_gruneisen_parameters(
if log_level > 0:
dm = gruneisen.dynamical_matrix
if dm.is_nac() and dm.nac_method == "gonze":
dm.show_Gonze_nac_message()
if isinstance(dm, DynamicalMatrixGL):
dm.show_nac_message()
if mesh is not None:
gruneisen.set_sampling_mesh(mesh, rotations=rotations, is_gamma_center=True)
@ -310,7 +314,7 @@ class Gruneisen:
gruneisen_parameters = []
frequencies = []
for i, q in enumerate(qpoints):
if self._dm.is_nac():
if isinstance(self._dm, DynamicalMatrixNAC):
if (np.abs(q) < 1e-5).all(): # If q is almost at Gamma
if self._run_mode == "band":
# Direction estimated from neighboring point