From 7a83fdfb327a6a1c474fa606aab9c82de707ca3e Mon Sep 17 00:00:00 2001 From: Atsushi Togo Date: Fri, 21 Jun 2024 13:49:24 +0900 Subject: [PATCH] Migrate to ruff --- .pre-commit-config.yaml | 29 ++--------- phono3py/api_jointdos.py | 2 +- phono3py/api_phono3py.py | 6 +-- phono3py/conductivity/base.py | 22 +++++++- phono3py/conductivity/direct_solution.py | 12 +++-- phono3py/conductivity/rta.py | 10 ++-- phono3py/conductivity/utils.py | 13 +++-- phono3py/cui/phono3py_argparse.py | 2 +- phono3py/cui/phono3py_script.py | 2 +- phono3py/cui/settings.py | 2 +- phono3py/cui/show_log.py | 3 +- phono3py/cui/triplets_info.py | 2 +- phono3py/file_IO.py | 28 +++++++---- phono3py/interface/phono3py_yaml.py | 10 ++-- phono3py/phonon/grid.py | 1 + phono3py/phonon3/displacement_fc3.py | 14 +++--- phono3py/phonon3/fc3.py | 58 +++++++++++----------- phono3py/phonon3/gruneisen.py | 6 +-- phono3py/phonon3/imag_self_energy.py | 7 ++- phono3py/phonon3/interaction.py | 21 ++++++-- phono3py/phonon3/joint_dos.py | 31 +++++++----- phono3py/phonon3/real_self_energy.py | 14 +++--- phono3py/phonon3/spectral_function.py | 4 +- phono3py/phonon3/triplets.py | 7 +-- pyproject.toml | 23 +++++---- scripts/phono3py-coleigplot | 10 +++- scripts/phono3py-kdeplot | 13 +++-- setup.py | 4 +- test/conductivity/test_kappa_RTA.py | 1 - test/conductivity/test_kappa_RTA_Wigner.py | 1 - test/cui/test_phono3py_load_script.py | 1 + test/other/test_kaccum.py | 1 + test/phonon3/test_joint_dos.py | 2 +- test/phonon3/test_triplets.py | 2 +- test/sscha/test_sscha.py | 5 -- 35 files changed, 207 insertions(+), 162 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index eab202d5..c54535af 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,31 +10,12 @@ repos: exclude: ^conda/ - id: check-added-large-files -- repo: https://github.com/pycqa/flake8 - rev: 7.1.0 +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.1.13 hooks: - - id: flake8 - args: - - "--max-line-length=88" - - "--ignore=E203,W503" - -- repo: https://github.com/psf/black - rev: 24.4.2 - hooks: - - id: black - args: - - --line-length=88 - -- repo: https://github.com/pycqa/pydocstyle - rev: 6.3.0 - hooks: - - id: pydocstyle - -- repo: https://github.com/pycqa/isort - rev: 5.13.2 - hooks: - - id: isort - name: isort (python) + - id: ruff + args: [ "--fix", "--show-fixes" ] + - id: ruff-format - repo: https://github.com/Takishima/cmake-pre-commit-hooks rev: v1.9.6 diff --git a/phono3py/api_jointdos.py b/phono3py/api_jointdos.py index 6b4841eb..a69146a9 100644 --- a/phono3py/api_jointdos.py +++ b/phono3py/api_jointdos.py @@ -40,12 +40,12 @@ from phonopy.units import VaspToTHz from phono3py.file_IO import write_joint_dos +from phono3py.phonon.grid import BZGrid from phono3py.phonon3.imag_self_energy import ( get_freq_points_batches, get_frequency_points, ) from phono3py.phonon3.joint_dos import JointDos -from phono3py.phonon.grid import BZGrid class Phono3pyJointDos: diff --git a/phono3py/api_phono3py.py b/phono3py/api_phono3py.py index d65f883c..24dba4af 100644 --- a/phono3py/api_phono3py.py +++ b/phono3py/api_phono3py.py @@ -72,19 +72,20 @@ from phono3py.conductivity.rta import get_thermal_conductivity_RTA from phono3py.interface.fc_calculator import get_fc3 from phono3py.interface.phono3py_yaml import Phono3pyYaml +from phono3py.phonon.grid import BZGrid from phono3py.phonon3.dataset import get_displacements_and_forces_fc3 from phono3py.phonon3.displacement_fc3 import ( direction_to_displacement, get_third_order_displacements, ) -from phono3py.phonon3.fc3 import cutoff_fc3_by_zero -from phono3py.phonon3.fc3 import get_fc3 as get_phono3py_fc3 from phono3py.phonon3.fc3 import ( + cutoff_fc3_by_zero, set_permutation_symmetry_compact_fc3, set_permutation_symmetry_fc3, set_translational_invariance_compact_fc3, set_translational_invariance_fc3, ) +from phono3py.phonon3.fc3 import get_fc3 as get_phono3py_fc3 from phono3py.phonon3.imag_self_energy import ( get_imag_self_energy, write_imag_self_energy, @@ -95,7 +96,6 @@ write_real_self_energy, ) from phono3py.phonon3.spectral_function import run_spectral_function -from phono3py.phonon.grid import BZGrid from phono3py.version import __version__ diff --git a/phono3py/conductivity/base.py b/phono3py/conductivity/base.py index 05c14912..24478392 100644 --- a/phono3py/conductivity/base.py +++ b/phono3py/conductivity/base.py @@ -45,10 +45,10 @@ from phonopy.units import EV, Angstrom, Kb, THz, THzToEv from phono3py.other.isotope import Isotope +from phono3py.phonon.grid import get_grid_points_by_rotations, get_ir_grid_points from phono3py.phonon3.collision_matrix import CollisionMatrix from phono3py.phonon3.imag_self_energy import ImagSelfEnergy from phono3py.phonon3.interaction import Interaction -from phono3py.phonon.grid import get_grid_points_by_rotations, get_ir_grid_points unit_to_WmK = ( (THz * Angstrom) ** 2 / (Angstrom**3) * EV / THz / (2 * np.pi) @@ -81,6 +81,7 @@ def get_mode_heat_capacities(self): "Use attribute, Conductivity.mode_heat_capacities " "instead of Conductivity.get_mode_heat_capacities().", DeprecationWarning, + stacklevel=2, ) return self.mode_heat_capacities @@ -129,6 +130,7 @@ def get_kappa(self): warnings.warn( "Use attribute, Conductivity.kappa " "instead of Conductivity.get_kappa().", DeprecationWarning, + stacklevel=2, ) return self.kappa @@ -143,6 +145,7 @@ def get_mode_kappa(self): "Use attribute, Conductivity.mode_kappa " "instead of Conductivity.get_mode_kappa().", DeprecationWarning, + stacklevel=2, ) return self.mode_kappa @@ -165,6 +168,7 @@ def get_group_velocities(self): "Use attribute, Conductivity.group_velocities " "instead of Conductivity.get_group_velocities().", DeprecationWarning, + stacklevel=2, ) return self.group_velocities @@ -179,6 +183,7 @@ def get_gv_by_gv(self): "Use attribute, Conductivity.gv_by_gv " "instead of Conductivity.get_gv_by_gv().", DeprecationWarning, + stacklevel=2, ) return self.gv_by_gv @@ -413,6 +418,7 @@ def get_mesh_numbers(self): "Use attribute, Conductivity.mesh_numbers " "instead of Conductivity.get_mesh_numbers().", DeprecationWarning, + stacklevel=2, ) return self.mesh_numbers @@ -440,6 +446,7 @@ def get_frequencies(self): "Use attribute, Conductivity.frequencies " "instead of Conductivity.get_frequencies().", DeprecationWarning, + stacklevel=2, ) return self.frequencies @@ -458,6 +465,7 @@ def get_qpoints(self): "Use attribute, Conductivity.qpoints " "instead of Conductivity.get_qpoints().", DeprecationWarning, + stacklevel=2, ) return self.qpoints @@ -480,6 +488,7 @@ def get_grid_points(self): "Use attribute, Conductivity.grid_points " "instead of Conductivity.get_grid_points().", DeprecationWarning, + stacklevel=2, ) return self.grid_points @@ -494,6 +503,7 @@ def get_grid_weights(self): "Use attribute, Conductivity.grid_weights " "instead of Conductivity.get_grid_weights().", DeprecationWarning, + stacklevel=2, ) return self.grid_weights @@ -513,6 +523,7 @@ def get_temperatures(self): "Use attribute, Conductivity.temperatures " "instead of Conductivity.get_temperatures().", DeprecationWarning, + stacklevel=2, ) return self.temperatures @@ -522,6 +533,7 @@ def set_temperatures(self, temperatures): "Use attribute, Conductivity.temperatures " "instead of Conductivity.set_temperatures().", DeprecationWarning, + stacklevel=2, ) self.temperatures = temperatures @@ -540,6 +552,7 @@ def get_gamma(self): warnings.warn( "Use attribute, Conductivity.gamma " "instead of Conductivity.get_gamma().", DeprecationWarning, + stacklevel=2, ) return self.gamma @@ -548,6 +561,7 @@ def set_gamma(self, gamma): warnings.warn( "Use attribute, Conductivity.gamma " "instead of Conductivity.set_gamma().", DeprecationWarning, + stacklevel=2, ) self.gamma = gamma @@ -567,6 +581,7 @@ def get_gamma_isotope(self): "Use attribute, Conductivity.gamma_isotope " "instead of Conductivity.get_gamma_isotope().", DeprecationWarning, + stacklevel=2, ) return self.gamma_isotope @@ -576,6 +591,7 @@ def set_gamma_isotope(self, gamma_iso): "Use attribute, Conductivity.gamma_isotope " "instead of Conductivity.set_gamma_isotope().", DeprecationWarning, + stacklevel=2, ) self.gamma_isotope = gamma_iso @@ -590,6 +606,7 @@ def get_sigmas(self): "Use attribute, Conductivity.sigmas " "instead of Conductivity.get_sigmas().", DeprecationWarning, + stacklevel=2, ) return self.sigmas @@ -604,6 +621,7 @@ def get_sigma_cutoff_width(self): "Use attribute, Conductivity.sigma_cutoff_width " "instead of Conductivity.get_sigma_cutoff_width().", DeprecationWarning, + stacklevel=2, ) return self.sigma_cutoff_width @@ -618,6 +636,7 @@ def get_grid_point_count(self): "Use attribute, Conductivity.grid_point_count " "instead of Conductivity.get_grid_point_count().", DeprecationWarning, + stacklevel=2, ) return self.grid_point_count @@ -632,6 +651,7 @@ def get_averaged_pp_interaction(self): "Use attribute, Conductivity.averaged_pp_interaction " "instead of Conductivity.get_averaged_pp_interaction().", DeprecationWarning, + stacklevel=2, ) return self.averaged_pp_interaction diff --git a/phono3py/conductivity/direct_solution.py b/phono3py/conductivity/direct_solution.py index b8e027cb..89b31ceb 100644 --- a/phono3py/conductivity/direct_solution.py +++ b/phono3py/conductivity/direct_solution.py @@ -56,9 +56,9 @@ get_conversion_factor_WTE, ) from phono3py.file_IO import read_pp_from_hdf5 +from phono3py.phonon.grid import get_grid_points_by_rotations from phono3py.phonon3.collision_matrix import CollisionMatrix from phono3py.phonon3.interaction import Interaction, all_bands_exist -from phono3py.phonon.grid import get_grid_points_by_rotations class ConductivityLBTEBase(ConductivityBase): @@ -163,6 +163,7 @@ def get_collision_matrix(self): "Use attribute, Conductivity_LBTE.collision_matrix " "instead of Conductivity_LBTE.get_collision_matrix().", DeprecationWarning, + stacklevel=2, ) return self.collision_matrix @@ -172,6 +173,7 @@ def set_collision_matrix(self, collision_matrix): "Use attribute, Conductivity_LBTE.collision_matrix " "instead of Conductivity_LBTE.set_collision_matrix().", DeprecationWarning, + stacklevel=2, ) self.collision_matrix = collision_matrix @@ -517,9 +519,9 @@ def _set_collision_matrix_at_sigmas(self, i_gp): else: i_data = 0 self._gamma[j, k, i_data] = self._collision.imag_self_energy - self._collision_matrix[j, k, i_data] = ( - self._collision.get_collision_matrix() - ) + self._collision_matrix[ + j, k, i_data + ] = self._collision.get_collision_matrix() def _prepare_collision_matrix(self): """Collect pieces and construct collision matrix.""" @@ -1271,6 +1273,7 @@ def get_kappa_RTA(self): "Use attribute, Conductivity_LBTE.kappa_RTA " "instead of Conductivity_LBTE.get_kappa_RTA().", DeprecationWarning, + stacklevel=2, ) return self.kappa_RTA @@ -1285,6 +1288,7 @@ def get_mode_kappa_RTA(self): "Use attribute, Conductivity_LBTE.mode_kappa_RTA " "instead of Conductivity_LBTE.get_mode_kappa_RTA().", DeprecationWarning, + stacklevel=2, ) return self.mode_kappa_RTA diff --git a/phono3py/conductivity/rta.py b/phono3py/conductivity/rta.py index 64ac8bbe..f9f9e346 100644 --- a/phono3py/conductivity/rta.py +++ b/phono3py/conductivity/rta.py @@ -54,9 +54,9 @@ ) from phono3py.file_IO import read_pp_from_hdf5 from phono3py.other.tetrahedron_method import get_tetrahedra_relative_grid_address +from phono3py.phonon.grid import get_grid_points_by_rotations from phono3py.phonon3.imag_self_energy import ImagSelfEnergy, average_by_degeneracy from phono3py.phonon3.interaction import Interaction, all_bands_exist -from phono3py.phonon.grid import get_grid_points_by_rotations class ConductivityRTABase(ConductivityBase): @@ -298,9 +298,9 @@ def _set_gamma_at_sigmas(self, i): self._gamma_N[j, k, i] = g_N self._gamma_U[j, k, i] = g_U if self._is_gamma_detail: - self._gamma_detail_at_q[k] = ( - self._collision.get_detailed_imag_self_energy() - ) + self._gamma_detail_at_q[ + k + ] = self._collision.get_detailed_imag_self_energy() def _set_gamma_at_sigmas_lowmem(self, i): """Calculate gamma without storing ph-ph interaction strength. @@ -921,7 +921,7 @@ def _set_kappa_at_sigmas(self, j, k, i_gp, i_band, g_sum, frequencies): return g = g_sum[i_band] + g_sum[j_band] - for i_pair, (a, b) in enumerate( + for i_pair, _ in enumerate( ([0, 0], [1, 1], [2, 2], [1, 2], [0, 2], [0, 1]) ): old_settings = np.seterr(all="raise") diff --git a/phono3py/conductivity/utils.py b/phono3py/conductivity/utils.py index 62b62801..dcc4c63b 100644 --- a/phono3py/conductivity/utils.py +++ b/phono3py/conductivity/utils.py @@ -34,7 +34,6 @@ # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. - import sys from typing import TYPE_CHECKING, Optional, Union @@ -367,7 +366,7 @@ def write_gamma_detail( all_triplets = get_all_triplets(gp, interaction.bz_grid) if all_bands_exist(interaction): - for j, sigma in enumerate(sigmas): + for sigma in sigmas: write_gamma_detail_to_hdf5( temperatures, mesh, @@ -384,7 +383,7 @@ def write_gamma_detail( verbose=verbose, ) else: - for j, sigma in enumerate(sigmas): + for sigma in sigmas: for k, bi in enumerate(interaction.get_band_indices()): write_gamma_detail_to_hdf5( temperatures, @@ -871,7 +870,7 @@ def kappa_RTA(br: "ConductivityRTA", log_level): ("#%6s " + " %-10s" * 6) % ("T(K)", "xx", "yy", "zz", "yz", "xz", "xy") ) - for j, (t, k) in enumerate(zip(temperatures, kappa[i])): + for t, k in zip(temperatures, kappa[i]): print(("%7.1f " + " %10.3f" * 6) % ((t,) + tuple(k))) print("") @@ -936,13 +935,13 @@ def kappa_Wigner_RTA(br: "ConductivityWignerRTA", log_level): % (" \t T(K)", "xx", "yy", "zz", "yz", "xz", "xy") ) if kappa_P_RTA is not None: - for j, (t, k) in enumerate(zip(temperatures, kappa_P_RTA[i])): + for t, k in zip(temperatures, kappa_P_RTA[i]): print("K_P\t" + ("%7.1f " + " %10.3f" * 6) % ((t,) + tuple(k))) print(" ") - for j, (t, k) in enumerate(zip(temperatures, kappa_C[i])): + for t, k in zip(temperatures, kappa_C[i]): print("K_C\t" + ("%7.1f " + " %10.3f" * 6) % ((t,) + tuple(k))) print(" ") - for j, (t, k) in enumerate(zip(temperatures, kappa_TOT_RTA[i])): + for t, k in zip(temperatures, kappa_TOT_RTA[i]): print("K_T\t" + ("%7.1f " + " %10.3f" * 6) % ((t,) + tuple(k))) print("") diff --git a/phono3py/cui/phono3py_argparse.py b/phono3py/cui/phono3py_argparse.py index f004226f..78e734e5 100644 --- a/phono3py/cui/phono3py_argparse.py +++ b/phono3py/cui/phono3py_argparse.py @@ -516,7 +516,7 @@ def get_parser(fc_symmetry=False, is_nac=False, load_phono3py_yaml=False): action="store_true", default=False, help="Deactivate summation of partial kappa at q-stars", - ), + ) parser.add_argument( "--nomeshsym", dest="is_nomeshsym", diff --git a/phono3py/cui/phono3py_script.py b/phono3py/cui/phono3py_script.py index 3fc35cc1..4cbacee1 100644 --- a/phono3py/cui/phono3py_script.py +++ b/phono3py/cui/phono3py_script.py @@ -89,9 +89,9 @@ write_phonon_to_hdf5, ) from phono3py.interface.phono3py_yaml import Phono3pyYaml +from phono3py.phonon.grid import get_grid_point_from_address, get_ir_grid_points from phono3py.phonon3.fc3 import show_drift_fc3 from phono3py.phonon3.gruneisen import run_gruneisen_parameters -from phono3py.phonon.grid import get_grid_point_from_address, get_ir_grid_points from phono3py.version import __version__ # import logging diff --git a/phono3py/cui/settings.py b/phono3py/cui/settings.py index 5f35b37f..815fb9a5 100644 --- a/phono3py/cui/settings.py +++ b/phono3py/cui/settings.py @@ -709,7 +709,7 @@ def _parse_conf(self): # specials if conf_key in ("create_forces_fc2", "create_forces_fc3"): - if type(confs[conf_key]) is str: + if isinstance(confs[conf_key], str): fnames = confs[conf_key].split() else: fnames = confs[conf_key] diff --git a/phono3py/cui/show_log.py b/phono3py/cui/show_log.py index 2283e065..2ef4f1ba 100644 --- a/phono3py/cui/show_log.py +++ b/phono3py/cui/show_log.py @@ -48,7 +48,8 @@ def show_general_settings( ): """Show general setting information.""" is_primitive_axes_auto = ( - type(phono3py.primitive_matrix) is str and phono3py.primitive_matrix == "auto" + isinstance(phono3py.primitive_matrix, str) + and phono3py.primitive_matrix == "auto" ) primitive_matrix = phono3py.primitive_matrix supercell_matrix = phono3py.supercell_matrix diff --git a/phono3py/cui/triplets_info.py b/phono3py/cui/triplets_info.py index 50ced6a5..1e85bbc9 100644 --- a/phono3py/cui/triplets_info.py +++ b/phono3py/cui/triplets_info.py @@ -37,8 +37,8 @@ import numpy as np from phono3py.file_IO import write_grid_address_to_hdf5, write_ir_grid_points -from phono3py.phonon3.triplets import get_triplets_at_q from phono3py.phonon.grid import get_ir_grid_points +from phono3py.phonon3.triplets import get_triplets_at_q def write_grid_points( diff --git a/phono3py/file_IO.py b/phono3py/file_IO.py index c5285848..8875fb35 100644 --- a/phono3py/file_IO.py +++ b/phono3py/file_IO.py @@ -57,7 +57,9 @@ def write_disp_fc3_yaml(dataset, supercell, filename="disp_fc3.yaml"): This function should not be called from phono3py script from version 3. """ - warnings.warn("write_disp_fc3_yaml() is deprecated.", DeprecationWarning) + warnings.warn( + "write_disp_fc3_yaml() is deprecated.", DeprecationWarning, stacklevel=2 + ) w = open(filename, "w") w.write("natom: %d\n" % dataset["natom"]) @@ -155,7 +157,9 @@ def write_disp_fc2_yaml(dataset, supercell, filename="disp_fc2.yaml"): This function should not be called from phono3py script from version 3. """ - warnings.warn("write_disp_fc2_yaml() is deprecated.", DeprecationWarning) + warnings.warn( + "write_disp_fc2_yaml() is deprecated.", DeprecationWarning, stacklevel=2 + ) w = open(filename, "w") w.write("natom: %d\n" % dataset["natom"]) @@ -251,7 +255,7 @@ def write_FORCES_FC3(disp_dataset, forces_fc3=None, fp=None, filename="FORCES_FC else: # for forces in forces_fc3[i]: # w.write("%15.10f %15.10f %15.10f\n" % (tuple(forces))) - for j in range(natom): + for _ in range(natom): w.write("%15.10f %15.10f %15.10f\n" % (0, 0, 0)) count += 1 @@ -339,8 +343,8 @@ def write_force_constants_to_hdf5( ): try: import h5py - except ImportError: - raise ModuleNotFoundError("You need to install python-h5py.") + except ImportError as exc: + raise ModuleNotFoundError("You need to install python-h5py.") from exc with h5py.File(filename, "w") as w: w.create_dataset( @@ -1480,7 +1484,9 @@ def parse_disp_fc2_yaml(filename="disp_fc2.yaml", return_cell=False): This function should not be called from phono3py script from version 3. """ - warnings.warn("parse_disp_fc2_yaml() is deprecated.", DeprecationWarning) + warnings.warn( + "parse_disp_fc2_yaml() is deprecated.", DeprecationWarning, stacklevel=2 + ) dataset = _parse_yaml(filename) natom = dataset["natom"] @@ -1507,7 +1513,9 @@ def parse_disp_fc3_yaml(filename="disp_fc3.yaml", return_cell=False): This function should not be called from phono3py script from version 3. """ - warnings.warn("parse_disp_fc3_yaml() is deprecated.", DeprecationWarning) + warnings.warn( + "parse_disp_fc3_yaml() is deprecated.", DeprecationWarning, stacklevel=2 + ) dataset = _parse_yaml(filename) natom = dataset["natom"] @@ -1547,7 +1555,7 @@ def parse_FORCES_FC2(disp_dataset, filename="FORCES_FC2", unit_conversion_factor num_disp = len(disp_dataset["first_atoms"]) forces_fc2 = [] with open(filename, "r") as f2: - for i in range(num_disp): + for _ in range(num_disp): forces = _parse_force_lines(f2, num_atom) if forces is None: return [] @@ -1681,7 +1689,7 @@ def _parse_yaml(file_yaml): So this is obsolete at v2 and later versions. """ - warnings.warn("_parse_yaml() is deprecated.", DeprecationWarning) + warnings.warn("_parse_yaml() is deprecated.", DeprecationWarning, stacklevel=2) import yaml @@ -1720,7 +1728,7 @@ def _write_cell_yaml(w, supercell): These methods are also deprecated. """ - warnings.warn("write_cell_yaml() is deprecated.", DeprecationWarning) + warnings.warn("write_cell_yaml() is deprecated.", DeprecationWarning, stacklevel=2) w.write("lattice:\n") for axis in supercell.get_cell(): diff --git a/phono3py/interface/phono3py_yaml.py b/phono3py/interface/phono3py_yaml.py index 9369e282..2decda01 100644 --- a/phono3py/interface/phono3py_yaml.py +++ b/phono3py/interface/phono3py_yaml.py @@ -152,9 +152,9 @@ def _parse_fc3_dataset(self): dataset = None if "displacement_pairs" in self._yaml: disp = self._yaml["displacement_pairs"][0] - if type(disp) is dict: # type1 + if isinstance(disp, dict): # type1 dataset = self._parse_fc3_dataset_type1(len(self._data.supercell)) - elif type(disp) is list: # type2 + elif isinstance(disp, list): # type2 if "displacement" in disp[0]: dataset = self._parse_force_sets_type2() if "displacement_pair_info" in self._yaml: @@ -507,7 +507,7 @@ def _displacements_yaml_lines_type1_info(dataset): if "duplicates" in dataset and dataset["duplicates"]: lines.append(" duplicated_supercell_ids: " "# 0 means perfect supercell") # Backward compatibility for dict type - if type(dataset["duplicates"]) is dict: + if isinstance(dataset["duplicates"], dict): for disp1_id, j in dataset["duplicates"].items(): lines.append(" - [ %d, %d ]" % (int(disp1_id), j)) else: @@ -580,7 +580,7 @@ def read_phono3py_yaml( ) -> Phono3pyYamlData: """Read phono3py.yaml like file.""" yaml_data = load_yaml(filename) - if type(yaml_data) is str: + if isinstance(yaml_data, str): msg = f'Could not load "{filename}" properly.' raise TypeError(msg) return load_phono3py_yaml( @@ -597,7 +597,7 @@ def load_phono3py_yaml( """Return Phono3pyYamlData instance loading yaml data. Parameters - ----------- + ---------- yaml_data : dict """ diff --git a/phono3py/phonon/grid.py b/phono3py/phonon/grid.py index ea7bc30f..b42112ea 100644 --- a/phono3py/phonon/grid.py +++ b/phono3py/phonon/grid.py @@ -716,6 +716,7 @@ def _run_grg( warnings.warn( "Non primitive cell input. Unable to use GR-grid.", RuntimeWarning, + stacklevel=2, ) return False diff --git a/phono3py/phonon3/displacement_fc3.py b/phono3py/phonon3/displacement_fc3.py index 4f539977..f769c900 100644 --- a/phono3py/phonon3/displacement_fc3.py +++ b/phono3py/phonon3/displacement_fc3.py @@ -350,13 +350,11 @@ def _find_duplicates(direction_dataset): duplucates = [] done = [] - for i, direction1 in enumerate(direction_dataset): + for direction1 in direction_dataset: n1 = direction1["number"] for directions2 in direction1["second_atoms"]: n2 = directions2["number"] - if ( - n2 > n1 and (n2, n1) not in done and (n2, n1) in direction_sets - ): # noqa E129 + if n2 > n1 and (n2, n1) not in done and (n2, n1) in direction_sets: # noqa E129 done.append((n2, n1)) duplucates += _compare( n1, @@ -368,14 +366,14 @@ def _find_duplicates(direction_dataset): ) done = [] - for i, direction1 in enumerate(direction_dataset): + for direction1 in direction_dataset: n1 = direction1["number"] for directions2 in direction1["second_atoms"]: n2 = directions2["number"] if n1 == n2 and n1 not in done: done.append(n1) duplucates += _compare_opposite( - n1, direction_sets[(n1, n1)], pair_idx[(n1, n1)] + direction_sets[(n1, n1)], pair_idx[(n1, n1)] ) return duplucates @@ -393,10 +391,10 @@ def _compare(n1, n2, dset1, dset2, pidx1, pidx2): return [[i, j] for (i, j) in duplucates if i > j] -def _compare_opposite(n1, dset1, pidx1): +def _compare_opposite(dset1, pidx1): flip_sets = np.array(dset1)[:, [3, 4, 5, 0, 1, 2]] duplucates = [] - for i, d1 in enumerate(dset1): + for d1 in dset1: eq_indices = np.where(np.abs(flip_sets + d1).sum(axis=1) == 0)[0] if len(eq_indices) > 0: duplucates += [[pidx1[j], 0] for j in eq_indices] diff --git a/phono3py/phonon3/fc3.py b/phono3py/phonon3/fc3.py index d7204971..817a06ff 100644 --- a/phono3py/phonon3/fc3.py +++ b/phono3py/phonon3/fc3.py @@ -276,12 +276,12 @@ def set_permutation_symmetry_compact_fc3(fc3, primitive): np.array(p2s_map, dtype="int_"), np.array(nsym_list, dtype="int_"), ) - except ImportError: + except ImportError as exc: text = ( "Import error at phono3c.permutation_symmetry_compact_fc3. " "Corresponding python code is not implemented." ) - raise RuntimeError(text) + raise RuntimeError(text) from exc def _copy_permutation_symmetry_fc3_elem(fc3, fc3_elem, a, b, c): @@ -339,29 +339,29 @@ def set_translational_invariance_compact_fc3(fc3, primitive: Primitive): _set_translational_invariance_fc3_per_index(fc3, index=1) _set_translational_invariance_fc3_per_index(fc3, index=2) - except ImportError: + except ImportError as exc: text = ( "Import error at phono3c.tranpose_compact_fc3. " "Corresponding python code is not implemented." ) - raise RuntimeError(text) + raise RuntimeError(text) from exc def _set_translational_invariance_fc3_per_index(fc3, index=0): for i in range(fc3.shape[(1 + index) % 3]): for j in range(fc3.shape[(2 + index) % 3]): - for k, l, m in list(np.ndindex(3, 3, 3)): + for k, ll, m in list(np.ndindex(3, 3, 3)): if index == 0: - fc3[:, i, j, k, l, m] -= ( - np.sum(fc3[:, i, j, k, l, m]) / fc3.shape[0] + fc3[:, i, j, k, ll, m] -= ( + np.sum(fc3[:, i, j, k, ll, m]) / fc3.shape[0] ) elif index == 1: - fc3[j, :, i, k, l, m] -= ( - np.sum(fc3[j, :, i, k, l, m]) / fc3.shape[1] + fc3[j, :, i, k, ll, m] -= ( + np.sum(fc3[j, :, i, k, ll, m]) / fc3.shape[1] ) elif index == 2: - fc3[i, j, :, k, l, m] -= ( - np.sum(fc3[i, j, :, k, l, m]) / fc3.shape[2] + fc3[i, j, :, k, ll, m] -= ( + np.sum(fc3[i, j, :, k, ll, m]) / fc3.shape[2] ) @@ -465,7 +465,7 @@ def _solve_fc3( print("Displacements (in Angstrom):") else: print("One displacement (in Angstrom):") - for i, v in enumerate(displacements_first): + for v in displacements_first: print(" [%7.4f %7.4f %7.4f]" % tuple(v)) sys.stdout.flush() if verbose > 2: @@ -577,19 +577,19 @@ def show_drift_fc3(fc3, primitive=None, name="fc3"): klm1 = [0, 0, 0] klm2 = [0, 0, 0] klm3 = [0, 0, 0] - for i, j, k, l, m in list(np.ndindex((num_atom, num_atom, 3, 3, 3))): - val1 = fc3[:, i, j, k, l, m].sum() - val2 = fc3[i, :, j, k, l, m].sum() - val3 = fc3[i, j, :, k, l, m].sum() + for i, j, k, ll, m in list(np.ndindex((num_atom, num_atom, 3, 3, 3))): + val1 = fc3[:, i, j, k, ll, m].sum() + val2 = fc3[i, :, j, k, ll, m].sum() + val3 = fc3[i, j, :, k, ll, m].sum() if abs(val1) > abs(maxval1): maxval1 = val1 - klm1 = [k, l, m] + klm1 = [k, ll, m] if abs(val2) > abs(maxval2): maxval2 = val2 - klm2 = [k, l, m] + klm2 = [k, ll, m] if abs(val3) > abs(maxval3): maxval3 = val3 - klm3 = [k, l, m] + klm3 = [k, ll, m] else: try: import phono3py._phono3py as phono3c @@ -614,29 +614,29 @@ def show_drift_fc3(fc3, primitive=None, name="fc3"): phono3c.transpose_compact_fc3( fc3, permutations, s2pp_map, p2s_map, nsym_list, 0 ) # dim[0] <--> dim[1] - for i, j, k, l, m in np.ndindex((num_patom, num_satom, 3, 3, 3)): - val1 = fc3[i, :, j, k, l, m].sum() + for i, j, k, ll, m in np.ndindex((num_patom, num_satom, 3, 3, 3)): + val1 = fc3[i, :, j, k, ll, m].sum() if abs(val1) > abs(maxval1): maxval1 = val1 - klm1 = [k, l, m] + klm1 = [k, ll, m] phono3c.transpose_compact_fc3( fc3, permutations, s2pp_map, p2s_map, nsym_list, 0 ) # dim[0] <--> dim[1] - for i, j, k, l, m in np.ndindex((num_patom, num_satom, 3, 3, 3)): - val2 = fc3[i, :, j, k, l, m].sum() - val3 = fc3[i, j, :, k, l, m].sum() + for i, j, k, ll, m in np.ndindex((num_patom, num_satom, 3, 3, 3)): + val2 = fc3[i, :, j, k, ll, m].sum() + val3 = fc3[i, j, :, k, ll, m].sum() if abs(val2) > abs(maxval2): maxval2 = val2 - klm2 = [k, l, m] + klm2 = [k, ll, m] if abs(val3) > abs(maxval3): maxval3 = val3 - klm3 = [k, l, m] - except ImportError: + klm3 = [k, ll, m] + except ImportError as exc: text = ( "Import error at phono3c.tranpose_compact_fc3. " "Corresponding python code is not implemented." ) - raise RuntimeError(text) + raise RuntimeError(text) from exc text = "Max drift of %s: " % name text += "%f (%s%s%s) " % (maxval1, "xyz"[klm1[0]], "xyz"[klm1[1]], "xyz"[klm1[2]]) diff --git a/phono3py/phonon3/gruneisen.py b/phono3py/phonon3/gruneisen.py index bc47a3f9..e001f998 100644 --- a/phono3py/phonon3/gruneisen.py +++ b/phono3py/phonon3/gruneisen.py @@ -270,9 +270,7 @@ def _write_band_yaml(self, filename): ): f.write("- nqpoint: %d\n" % len(path)) f.write(" phonon:\n") - for i, (q, d, g_at_q, freqs_at_q) in enumerate( - zip(path, distances, gs, fs) - ): # noqa E125 + for q, d, g_at_q, freqs_at_q in zip(path, distances, gs, fs): f.write(" - q-position: [ %10.7f, %10.7f, %10.7f ]\n" % tuple(q)) f.write(" distance: %10.7f\n" % d) f.write(" band:\n") @@ -415,7 +413,7 @@ def _get_dPhidu(self): for j in range(3): for k in range(3): for ll in range(3): - for m in range(3): + for _ in range(3): dPhidu[nu, pi, i, j, k, ll] = ( fc3[p2s[nu], pi, :, i, j, :] * Y[:, :, k, ll] ).sum() diff --git a/phono3py/phonon3/imag_self_energy.py b/phono3py/phonon3/imag_self_energy.py index 563ba6a6..6c06a86b 100644 --- a/phono3py/phonon3/imag_self_energy.py +++ b/phono3py/phonon3/imag_self_energy.py @@ -46,9 +46,9 @@ write_gamma_detail_to_hdf5, write_imag_self_energy_at_grid_point, ) +from phono3py.phonon.func import bose_einstein from phono3py.phonon3.interaction import Interaction from phono3py.phonon3.triplets import get_triplets_integration_weights -from phono3py.phonon.func import bose_einstein class ImagSelfEnergy: @@ -170,6 +170,7 @@ def get_imag_self_energy(self): "Use attribute, ImagSelfEnergy.imag_self_energy " "instead of ImagSelfEnergy.get_imag_self_energy().", DeprecationWarning, + stacklevel=2, ) return self.imag_self_energy @@ -200,6 +201,7 @@ def get_detailed_imag_self_energy(self): "Use attribute, ImagSelfEnergy.detailed_imag_self_energy " "instead of ImagSelfEnergy.get_detailed_imag_self_energy().", DeprecationWarning, + stacklevel=2, ) return self.detailed_imag_self_energy @@ -222,6 +224,7 @@ def get_unit_conversion_factor(self): "Use attribute, ImagSelfEnergy.unit_conversion_factor " "instead of ImagSelfEnergy.get_unit_conversion_factor().", DeprecationWarning, + stacklevel=2, ) return self.unit_conversion_factor @@ -268,6 +271,7 @@ def set_frequency_points(self, frequency_points): "Use attribute, ImagSelfEnergy.frequency_points " "instead of ImagSelfEnergy.set_frequency_points().", DeprecationWarning, + stacklevel=2, ) self.frequency_points = frequency_points @@ -289,6 +293,7 @@ def set_temperature(self, temperature): "Use attribute, ImagSelfEnergy.temperature " "instead of ImagSelfEnergy.set_temperature().", DeprecationWarning, + stacklevel=2, ) self.temperature = temperature diff --git a/phono3py/phonon3/interaction.py b/phono3py/phonon3/interaction.py index 575088e6..6461fc0c 100644 --- a/phono3py/phonon3/interaction.py +++ b/phono3py/phonon3/interaction.py @@ -45,15 +45,15 @@ from phonopy.structure.symmetry import Symmetry from phonopy.units import AMU, EV, Angstrom, Hbar, THz, VaspToTHz -from phono3py.phonon3.real_to_reciprocal import RealToReciprocal -from phono3py.phonon3.reciprocal_to_normal import ReciprocalToNormal -from phono3py.phonon3.triplets import get_nosym_triplets_at_q, get_triplets_at_q from phono3py.phonon.grid import ( BZGrid, get_grid_points_by_rotations, get_ir_grid_points, ) from phono3py.phonon.solver import run_phonon_solver_c, run_phonon_solver_py +from phono3py.phonon3.real_to_reciprocal import RealToReciprocal +from phono3py.phonon3.reciprocal_to_normal import ReciprocalToNormal +from phono3py.phonon3.triplets import get_nosym_triplets_at_q, get_triplets_at_q class Interaction: @@ -222,6 +222,7 @@ def get_interaction_strength(self): "Use attribute, Interaction.interaction_strength " "instead of Interaction.get_interaction_strength().", DeprecationWarning, + stacklevel=2, ) return self.interaction_strength @@ -243,6 +244,7 @@ def get_mesh_numbers(self): "Use attribute, Interaction.mesh_numbers " "instead of Interaction.get_mesh_numbers().", DeprecationWarning, + stacklevel=2, ) return self.mesh_numbers @@ -261,6 +263,7 @@ def get_fc3(self): warnings.warn( "Use attribute, Interaction.fc3 " "instead of Interaction.get_fc3().", DeprecationWarning, + stacklevel=2, ) return self.fc3 @@ -275,6 +278,7 @@ def get_dynamical_matrix(self): "Use attribute, Interaction.dynamical_matrix " "instead of Interaction.get_dynamical_matrix().", DeprecationWarning, + stacklevel=2, ) return self.dynamical_matrix @@ -289,6 +293,7 @@ def get_primitive(self): "Use attribute, Interaction.primitive " "instead of Interaction.get_primitive().", DeprecationWarning, + stacklevel=2, ) return self.primitive @@ -338,6 +343,7 @@ def get_band_indices(self): "Use attribute, Interaction.band_indices " "instead of Interaction.get_band_indices().", DeprecationWarning, + stacklevel=2, ) return self.band_indices @@ -373,6 +379,7 @@ def get_nac_q_direction(self): "Use attribute, Interaction.nac_q_direction " "instead of Interaction.get_nac_q_direction().", DeprecationWarning, + stacklevel=2, ) return self.nac_q_direction @@ -382,6 +389,7 @@ def set_nac_q_direction(self, nac_q_direction=None): "Use attribute, Interaction.nac_q_direction " "instead of Interaction.set_nac_q_direction().", DeprecationWarning, + stacklevel=2, ) self.nac_q_direction = nac_q_direction @@ -402,6 +410,7 @@ def get_zero_value_positions(self): "Use attribute, Interaction.zero_value_positions " "instead of Interaction.get_zero_value_positions().", DeprecationWarning, + stacklevel=2, ) return self.zero_value_positions @@ -436,6 +445,7 @@ def get_frequency_factor_to_THz(self): "Use attribute, Interaction.frequency_factor_to_THz ", "instead of Interaction.get_frequency_factor_to_THz().", DeprecationWarning, + stacklevel=2, ) return self.frequency_factor_to_THz @@ -450,6 +460,7 @@ def get_lapack_zheev_uplo(self): "Use attribute, Interaction.lapack_zheev_uplo " "instead of Interaction.get_lapack_zheev_uplo().", DeprecationWarning, + stacklevel=2, ) return self.lapack_zheev_uplo @@ -464,6 +475,7 @@ def get_cutoff_frequency(self): "Use attribute, Interaction.cutoff_frequency " "instead of Interaction.get_cutoff_frequency().", DeprecationWarning, + stacklevel=2, ) return self.cutoff_frequency @@ -520,6 +532,7 @@ def get_averaged_interaction(self): "Use attribute, Interaction.averaged_interaction " "instead of Interaction.get_averaged_interaction().", DeprecationWarning, + stacklevel=2, ) return self.averaged_interaction @@ -540,6 +553,7 @@ def get_unit_conversion_factor(self): "Use attribute, Interaction.unit_conversion_factor " "instead of Interaction.get_unit_conversion_factor().", DeprecationWarning, + stacklevel=2, ) return self.unit_conversion_factor @@ -554,6 +568,7 @@ def get_constant_averaged_interaction(self): "Use attribute, Interaction.constant_averaged_interaction " "instead of Interaction.get_constant_averaged_interaction().", DeprecationWarning, + stacklevel=2, ) return self.constant_averaged_interaction diff --git a/phono3py/phonon3/joint_dos.py b/phono3py/phonon3/joint_dos.py index 66d2e4da..2bb1add0 100644 --- a/phono3py/phonon3/joint_dos.py +++ b/phono3py/phonon3/joint_dos.py @@ -42,14 +42,14 @@ from phonopy.structure.cells import Primitive, Supercell from phonopy.units import VaspToTHz +from phono3py.phonon.func import bose_einstein +from phono3py.phonon.grid import BZGrid, get_grid_point_from_address +from phono3py.phonon.solver import run_phonon_solver_c from phono3py.phonon3.triplets import ( get_nosym_triplets_at_q, get_triplets_at_q, get_triplets_integration_weights, ) -from phono3py.phonon.func import bose_einstein -from phono3py.phonon.grid import BZGrid, get_grid_point_from_address -from phono3py.phonon.solver import run_phonon_solver_c class JointDos: @@ -129,7 +129,7 @@ def joint_dos(self): def get_joint_dos(self): """Return joint-density-of-states.""" - warnings.warn("Use attribute, joint_dos", DeprecationWarning) + warnings.warn("Use attribute, joint_dos", DeprecationWarning, stacklevel=2) return self.joint_dos @property @@ -143,7 +143,9 @@ def frequency_points(self, frequency_points): def get_frequency_points(self): """Return frequency points.""" - warnings.warn("Use attribute, frequency_points", DeprecationWarning) + warnings.warn( + "Use attribute, frequency_points", DeprecationWarning, stacklevel=2 + ) return self.frequency_points def get_phonons(self): @@ -157,7 +159,7 @@ def primitive(self) -> Primitive: def get_primitive(self): """Return primitive cell.""" - warnings.warn("Use attribute, primitive", DeprecationWarning) + warnings.warn("Use attribute, primitive", DeprecationWarning, stacklevel=2) return self.primitive @property @@ -172,7 +174,7 @@ def mesh_numbers(self): def get_mesh_numbers(self): """Return mesh numbers by three integer values.""" - warnings.warn("Use attribute, mesh_numbers", DeprecationWarning) + warnings.warn("Use attribute, mesh_numbers", DeprecationWarning, stacklevel=2) return self.mesh @property @@ -189,7 +191,9 @@ def nac_q_direction(self, nac_q_direction=None): def set_nac_q_direction(self, nac_q_direction=None): """Set q-direction for NAC.""" - warnings.warn("Use attribute, nac_q_direction", DeprecationWarning) + warnings.warn( + "Use attribute, nac_q_direction", DeprecationWarning, stacklevel=2 + ) self.nac_q_direction = nac_q_direction @property @@ -209,6 +213,7 @@ def set_sigma(self, sigma): warnings.warn( "Use attribute, JointDOS.sigma instead of JointDOS.set_sigma()", DeprecationWarning, + stacklevel=2, ) self.sigma = sigma @@ -401,14 +406,16 @@ def _run_occupation(self): def _run_py_with_g_at_temperature(self, jdos, i): g = self._g n = self._occupations - for k, l in list(np.ndindex(g.shape[3:])): + for k, ll in list(np.ndindex(g.shape[3:])): weights = np.where( - np.logical_or(n[:, 0, k] < 0, n[:, 1, l] < 0), 0, self._weights_at_q + np.logical_or(n[:, 0, k] < 0, n[:, 1, ll] < 0), 0, self._weights_at_q ) jdos[i, 1] += np.dot( - (n[:, 0, k] + n[:, 1, l] + 1) * g[0, :, i, k, l], weights + (n[:, 0, k] + n[:, 1, ll] + 1) * g[0, :, i, k, ll], weights + ) + jdos[i, 0] += np.dot( + (n[:, 0, k] - n[:, 1, ll]) * g[1, :, i, k, ll], weights ) - jdos[i, 0] += np.dot((n[:, 0, k] - n[:, 1, l]) * g[1, :, i, k, l], weights) def _init_dynamical_matrix(self): self._dm = get_dynamical_matrix( diff --git a/phono3py/phonon3/real_self_energy.py b/phono3py/phonon3/real_self_energy.py index a49ee932..b39bc039 100644 --- a/phono3py/phonon3/real_self_energy.py +++ b/phono3py/phonon3/real_self_energy.py @@ -44,9 +44,9 @@ write_real_self_energy_at_grid_point, write_real_self_energy_to_hdf5, ) +from phono3py.phonon.func import bose_einstein from phono3py.phonon3.imag_self_energy import get_frequency_points from phono3py.phonon3.interaction import Interaction -from phono3py.phonon.func import bose_einstein class RealSelfEnergy: @@ -247,8 +247,8 @@ def _run_c_with_band_indices(self): ) def _run_py_with_band_indices(self): - for i, (triplet, w, interaction) in enumerate( - zip(self._triplets_at_q, self._weights_at_q, self._pp_strength) + for triplet, w, interaction in zip( + self._triplets_at_q, self._weights_at_q, self._pp_strength ): freqs = self._frequencies[triplet] for j, bi in enumerate(self._band_indices): @@ -286,11 +286,11 @@ def _run_c_with_frequency_points(self): def _run_py_with_frequency_points(self): for k, fpoint in enumerate(self._frequency_points): - for i, (triplet, w, interaction) in enumerate( - zip(self._triplets_at_q, self._weights_at_q, self._pp_strength) + for triplet, w, interaction in zip( + self._triplets_at_q, self._weights_at_q, self._pp_strength ): freqs = self._frequencies[triplet] - for j, bi in enumerate(self._band_indices): + for j, _ in enumerate(self._band_indices): if self._temperature > 0: self._real_self_energies[ k, j @@ -442,7 +442,7 @@ def _half_shift(self): fpoints = [] coef = self._df / np.pi i_zero = (len(self._im_part) - 1) // 2 - for i, im_part_at_i in enumerate(self._im_part): + for i, _ in enumerate(self._im_part): if i < i_zero: continue fpoint = self._all_frequency_points[i] + self._df / 2 diff --git a/phono3py/phonon3/spectral_function.py b/phono3py/phonon3/spectral_function.py index 4b0b9f99..95f4de33 100644 --- a/phono3py/phonon3/spectral_function.py +++ b/phono3py/phonon3/spectral_function.py @@ -214,7 +214,7 @@ def __init__( def run(self): """Calculate spectral function over grid points.""" - for gp_index in self: + for _ in self: pass def __iter__(self): @@ -354,7 +354,7 @@ def _run_spectral_function(self, i, grid_point, sigma_i): if self._log_level: print("* Spectral function") frequencies = self._pp.get_phonons()[0] - for j, temp in enumerate(self._temperatures): + for j, _ in enumerate(self._temperatures): for k, bi in enumerate(self._pp.band_indices): freq = frequencies[grid_point, bi] gammas = self._gammas[sigma_i, j, i, k] diff --git a/phono3py/phonon3/triplets.py b/phono3py/phonon3/triplets.py index 139240a6..aa75bcad 100644 --- a/phono3py/phonon3/triplets.py +++ b/phono3py/phonon3/triplets.py @@ -109,9 +109,10 @@ def get_triplets_at_q( ) triplets_at_q, weights = _get_BZ_triplets_at_q(grid_point, bz_grid, map_triplets) - assert ( - np.prod(bz_grid.D_diag) == weights.sum() - ), "Num grid points %d, sum of weight %d" % (np.prod(bz_grid.D_diag), weights.sum()) + assert np.prod(bz_grid.D_diag) == weights.sum(), ( + "Num grid points %d, sum of weight %d" + % (np.prod(bz_grid.D_diag), weights.sum()) + ) return triplets_at_q, weights, map_triplets, map_q diff --git a/pyproject.toml b/pyproject.toml index df2609e6..1827bc6e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,14 +1,19 @@ [build-system] requires = ["setuptools", "wheel", "numpy"] -#requires = ["setuptools", "wheel", "numpy", "oldest-supported-numpy"] -#build-backend = "setuptools.build_meta" -[tool.flake8] -max-line-length = 88 -extend-ignore = "E203,W503" - -[tool.black] +[tool.ruff] line-length = 88 +select = [ + "F", # Flake8 + "B", # Black + "I", # isort + "E", # pycodestyle-errors + "D", # pydocstyle +] +extend-ignore = [ + "D417", + "D100", +] -[tool.isort] -profile = "black" +[tool.ruff.lint.pydocstyle] +convention = "numpy" diff --git a/scripts/phono3py-coleigplot b/scripts/phono3py-coleigplot index bb60bcd8..22d1894b 100755 --- a/scripts/phono3py-coleigplot +++ b/scripts/phono3py-coleigplot @@ -11,7 +11,7 @@ epsilon = 1.0e-8 def get_options(): - # Arg-parser + """Parse command line options.""" parser = argparse.ArgumentParser(description="Plot collision matrix eigenvalues") parser.add_argument( "--temperature", @@ -33,6 +33,7 @@ def get_options(): def get_t_index(temperatures, args): + """Return temperature index.""" if len(temperatures) > 29: t_index = 30 else: @@ -45,6 +46,7 @@ def get_t_index(temperatures, args): def plot_one(ax, coleigs, temperatures, args): + """Plot collision matrix eigenvalues at one temperature.""" t_index = get_t_index(temperatures, args) coleigs_p = coleigs[t_index].copy() coleigs_n = coleigs[t_index].copy() @@ -56,6 +58,7 @@ def plot_one(ax, coleigs, temperatures, args): def plot_one_file(ax, args): + """Plot collision matrix eigenvalues at one temperature from file.""" filename = args.filenames[0] if os.path.isfile(filename): with h5py.File(filename, "r") as f: @@ -68,6 +71,7 @@ def plot_one_file(ax, args): def plot_more(ax, coleigs, temperatures, args): + """Update plot by collision matrix eigenvalues from one file.""" t_index = get_t_index(temperatures[0], args) y = [np.abs(v[t_index]) for v in coleigs] ax.semilogy(np.transpose(y), ".", markersize=5) @@ -75,6 +79,7 @@ def plot_more(ax, coleigs, temperatures, args): def plot_more_files(ax, args): + """Plot collision matrix eigenvalues from multiple files.""" temperatures = [] coleigs = [] for filename in args.filenames: @@ -89,6 +94,7 @@ def plot_more_files(ax, args): def plot(args: argparse.Namespace): + """Plot collision matrix eigenvalues.""" import matplotlib.pyplot as plt _, ax = plt.subplots() @@ -108,6 +114,7 @@ def plot(args: argparse.Namespace): def write_dat(args: argparse.Namespace): + """Write collision matrix eigenvalues to a file in gnuplot style.""" with open("coleigs.dat", "w") as w: for filename in args.filenames: with h5py.File(filename) as f: @@ -125,6 +132,7 @@ def write_dat(args: argparse.Namespace): def main(args: argparse.Namespace): + """Run phono3py-coleigplot.""" if args.savetxt: write_dat(args) else: diff --git a/scripts/phono3py-kdeplot b/scripts/phono3py-kdeplot index ca284900..184bbc88 100755 --- a/scripts/phono3py-kdeplot +++ b/scripts/phono3py-kdeplot @@ -12,6 +12,7 @@ epsilon = 1.0e-8 def collect_data(gamma, weights, frequencies, cutoff, max_freq): + """Collect data for making input of Gaussian-KDE.""" freqs = [] mode_prop = [] for w, freq, g in zip(weights, frequencies, gamma): @@ -37,8 +38,7 @@ def collect_data(gamma, weights, frequencies, cutoff, max_freq): def run_KDE(x, y, nbins, x_max=None, y_max=None, density_ratio=0.1): - """Running Gaussian-KDE by scipy""" - + """Run Gaussian-KDE by scipy.""" x_min = 0 if x_max is None: _x_max = np.rint(x.max() * 1.1) @@ -95,6 +95,7 @@ def plot( point_size=5, title=None, ): + """Plot lifetime distribution.""" xmax = np.max(x) ymax = np.max(y) x_cut = [] @@ -159,7 +160,7 @@ def plot( def get_options(): - # Arg-parser + """Parse command-line arguments.""" parser = argparse.ArgumentParser( description="Plot property density with gaussian KDE" ) @@ -206,7 +207,7 @@ def get_options(): "Number of bins in which data are assigned, " "i.e., determining resolution of plot" ), - ), + ) parser.add_argument( "--no-points", dest="no_points", action="store_true", help="Do not show points" ) @@ -246,9 +247,7 @@ def get_options(): def main(args): - # - # Matplotlib setting - # + """Run phono3py-kdeplot.""" import matplotlib matplotlib.use("Agg") diff --git a/setup.py b/setup.py index 04f071d8..d08cc8b5 100644 --- a/setup.py +++ b/setup.py @@ -188,12 +188,12 @@ def _get_extensions(build_dir): found_libs[key] = line.split()[3].split(";") if f"{key} flags" in line and len(line.split()) > 3: found_flags[key] = line.split()[3].split(";") - for key, value in found_libs.items(): + for _, value in found_libs.items(): found_extra_link_args += value for element in value: if "libmkl" in element: use_mkl_lapacke = True - for key, value in found_flags.items(): + for _, value in found_flags.items(): found_extra_compile_args += value if use_mkl_lapacke: params["define_macros"].append(("MKL_LAPACKE", None)) diff --git a/test/conductivity/test_kappa_RTA.py b/test/conductivity/test_kappa_RTA.py index 46643819..ea82c728 100644 --- a/test/conductivity/test_kappa_RTA.py +++ b/test/conductivity/test_kappa_RTA.py @@ -111,7 +111,6 @@ def test_kappa_RTA_si_nosym(si_pbesol: Phono3py, si_pbesol_nosym: Phono3py): def test_kappa_RTA_si_nomeshsym(si_pbesol: Phono3py, si_pbesol_nomeshsym: Phono3py): """Test RTA without considering mesh symmetry by Si.""" - if si_pbesol_nomeshsym._make_r0_average: ref_kappa_RTA_si_nomeshsym = [81.147, 81.147, 81.147, 0.000, 0.000, 0.000] else: diff --git a/test/conductivity/test_kappa_RTA_Wigner.py b/test/conductivity/test_kappa_RTA_Wigner.py index 37426406..b8d88190 100644 --- a/test/conductivity/test_kappa_RTA_Wigner.py +++ b/test/conductivity/test_kappa_RTA_Wigner.py @@ -92,7 +92,6 @@ def test_kappa_RTA_si_with_sigma_iso(si_pbesol: Phono3py): def test_kappa_RTA_si_nosym(si_pbesol: Phono3py, si_pbesol_nosym: Phono3py): """Test RTA without considering symmetry by Si.""" - if si_pbesol_nosym._make_r0_average: ref_kappa_P_RTA_si_nosym = [39.396, 39.222, 39.368, -0.096, -0.022, 0.026] ref_kappa_C_si_nosym = [0.009, 0.009, 0.009, 0.000, 0.000, 0.000] diff --git a/test/cui/test_phono3py_load_script.py b/test/cui/test_phono3py_load_script.py index 92f76597..e6987194 100644 --- a/test/cui/test_phono3py_load_script.py +++ b/test/cui/test_phono3py_load_script.py @@ -45,6 +45,7 @@ def __iter__(self): return (getattr(self, field.name) for field in fields(self)) def __contains__(self, item): + """Implement in operator.""" return item in (field.name for field in fields(self)) diff --git a/test/other/test_kaccum.py b/test/other/test_kaccum.py index 503d78af..becd2b13 100644 --- a/test/other/test_kaccum.py +++ b/test/other/test_kaccum.py @@ -298,6 +298,7 @@ def test_GammaDOSsmearing(nacl_pbe: Phono3py): def test_run_prop_dos(si_pbesol: Phono3py): + """Test of run_prop_dos.""" ph3 = si_pbesol ph3.mesh_numbers = [7, 7, 7] ph3.init_phph_interaction() diff --git a/test/phonon3/test_joint_dos.py b/test/phonon3/test_joint_dos.py index cb48cb31..9167f236 100644 --- a/test/phonon3/test_joint_dos.py +++ b/test/phonon3/test_joint_dos.py @@ -5,8 +5,8 @@ from phono3py import Phono3py from phono3py.api_jointdos import Phono3pyJointDos -from phono3py.phonon3.joint_dos import JointDos from phono3py.phonon.grid import BZGrid +from phono3py.phonon3.joint_dos import JointDos si_freq_points = [ 0.0000000, diff --git a/test/phonon3/test_triplets.py b/test/phonon3/test_triplets.py index dceb62a8..ef5ddf5d 100644 --- a/test/phonon3/test_triplets.py +++ b/test/phonon3/test_triplets.py @@ -7,12 +7,12 @@ from phonopy.structure.symmetry import Symmetry from phono3py import Phono3py +from phono3py.phonon.grid import BZGrid, get_grid_point_from_address from phono3py.phonon3.triplets import ( _get_BZ_triplets_at_q, _get_triplets_reciprocal_mesh_at_q, get_triplets_at_q, ) -from phono3py.phonon.grid import BZGrid, get_grid_point_from_address def test_get_triplets_at_q_type1(si_pbesol_111): diff --git a/test/sscha/test_sscha.py b/test/sscha/test_sscha.py index 0d3276d5..a1d80eaf 100644 --- a/test/sscha/test_sscha.py +++ b/test/sscha/test_sscha.py @@ -13,11 +13,6 @@ get_sscha_matrices, ) -try: - ModuleNotFoundError -except NameError: - ModuleNotFoundError = ImportError - si_pbesol_upsilon0_0 = [[3.849187e02, 0, 0], [0, 3.849187e02, 0], [0, 0, 3.849187e02]] si_pbesol_upsilon1_34 = [ [1.886404, -1.549705, -1.126055],