Skip to content

Commit

Permalink
More f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
gmatteo committed Feb 1, 2025
1 parent b90e291 commit f4d0a33
Show file tree
Hide file tree
Showing 31 changed files with 279 additions and 303 deletions.
60 changes: 27 additions & 33 deletions abipy/abio/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,6 @@
# raise ValueError("Don't know how to reallocate variable %s" % str(name))




class AbstractInput(MutableMapping, metaclass=abc.ABCMeta):
"""
Abstract class defining the methods that must be implemented by Input classes.
Expand Down Expand Up @@ -421,7 +419,8 @@ def __init__(self, structure, pseudos,

if pseudo_dir:
pseudo_dir = os.path.abspath(pseudo_dir)
if not os.path.exists(pseudo_dir): raise self.Error("Directory `%s` does not exist" % pseudo_dir)
if not os.path.exists(pseudo_dir):
raise self.Error(f"Directory `{pseudo_dir}` does not exist")
pseudos = [os.path.join(pseudo_dir, p) for p in list_strings(pseudos)]

try:
Expand Down Expand Up @@ -610,7 +609,7 @@ def _check_varname(self, key: str) -> None:
input.set_spell_check(False)
to disable spell checking. Perhaps the internal database is not in synch
with the Abinit version you are using. Please contact the AbiPy developers.""" % key)
with the Abinit version you are using? Please contact the AbiPy developers.""" % key)

@property
def runlevel(self):
Expand Down Expand Up @@ -850,7 +849,7 @@ def escape(text):
app(str(InputVariable(vname, value)))

else:
raise ValueError("Unsupported value for sortmode %s" % str(sortmode))
raise ValueError(f"Unsupported value for {sortmode=}")

def to_html(string):
string = string.replace("\n", "<br>")
Expand Down Expand Up @@ -1804,8 +1803,8 @@ def make_edos_input(self, ngkpt, shiftk=(0, 0, 0), tolwfr=1e-20, nscf_nband=None
prtwf=-1,
comment="Input file for electron DOS calculation from a GS SCF input (NSCF on kmesh)",
)
edos_input.set_kmesh(ngkpt, shiftk)

edos_input.set_kmesh(ngkpt, shiftk)
edos_input.set_vars(**extra_abivars)

return edos_input
Expand Down Expand Up @@ -1952,7 +1951,8 @@ def make_ph_inputs_qpoint(self, qpt, tolerance=None,

return ph_inputs

def make_ddkpert_input(self, perturbation, kptopt=2, only_vk=False, use_symmetries=False, tolerance=None, manager=None) -> AbinitInput:
def make_ddkpert_input(self, perturbation, kptopt=2, only_vk=False,
use_symmetries=False, tolerance=None, manager=None) -> AbinitInput:
"""
Returns |AbinitInput| for the calculation of an electric field perturbation.
This function should be called with an input that represents a GS run and
Expand Down Expand Up @@ -2657,16 +2657,19 @@ def make_eph_transport_input(self, ddb_ngqpt, sigma_erange, tmesh, eph_ngqpt_fin

# return new

def make_gwr_qprange_input(self, gwr_ntau, nband, ecuteps, gw_qprange=0, gwr_task=GWR_TASK.G0W0,
def make_gwr_qprange_input(self, gwr_ntau: int, nband: int, ecuteps: float,
gw_qprange: int = 0,
gwr_task=GWR_TASK.G0W0,
**kwargs) -> AbinitInput:
"""
Build and return an input file to compute QP corrections with the GWR code.
Args:
gwr_ntau: Number of minimax points.
nband: Number of bands in Green's function
ecuteps: Cutoff energy for chi0
gw_qprange = 0 to compute the QP corrections only for the fundamental and the direct gap.
nband: Number of bands in Green's function.
ecuteps: Cutoff energy for chi0 in Ha.
gw_qprange: 0 to compute the QP corrections only for the fundamental and the direct gap.
For other values see Abinit docs.
gwr_task: String defining the GWR task
"""
new = self.new_with_vars(
Expand Down Expand Up @@ -2725,7 +2728,7 @@ def abiget_dryrun_task(self, workdir, manager, **extra_vars):

def abiget_spacegroup(self, tolsym=None, retdict=False, workdir=None, manager=None, verbose=0):
"""
This function invokes Abinit to get the space group (as detected by Abinit, not by spglib)
This function invokes Abinit to get the space group as detected by Abinit, and not by spglib.
It should be called with an input file that contains all the mandatory variables required by ABINIT.
Args:
Expand Down Expand Up @@ -2765,18 +2768,6 @@ def abiget_dims_spginfo(self, workdir=None, manager=None, verbose=0) -> tuple[di
except Exception as exc:
self._handle_task_exception(task, exc)

#def get_qptopt(self) -> int:
# """Helper function that returns"""
# if "qptopt" in self:
# return self["qptopt"]

# kptopt = self.get("kptopt", 1)
# nspinor = self.get("nspinor", 1)
# nsppol = self.get("nsppol", 1)
# nspden = self.get("nspden", 1)
# qptopt = 1
# return qptopt

def abiget_ibz(self, ngkpt=None, shiftk=None, kptopt=None, workdir=None, manager=None, verbose=0):
"""
This function computes the list of points in the IBZ with the corresponding weights.
Expand Down Expand Up @@ -2860,7 +2851,7 @@ def abiget_scr_ibz(self, ngkpt=None, shiftk=None, kptopt=None, workdir=None, man
if verbose:
print("Computing qptdms with input:\n", str(inp))

# Build a Task to run Abinit in a shell subprocess
# Build a Task to run Abinit in a shell subprocess.
task = AbinitTask.temp_shell_task(inp, workdir=workdir, manager=manager)
task.start_and_wait(autoparal=False)

Expand Down Expand Up @@ -3068,7 +3059,6 @@ def abiget_irred_dteperts(self, ngkpt=None, shiftk=None, kptopt=None, ixc=None,
[{'idir': 1, 'ipert': 4, 'qpt': [0.0, 0.0, 0.0]},
{'idir': 2, 'ipert': 4, 'qpt': [0.0, 0.0, 0.0]}]
"""
dteperts_vars = dict(d3e_pert1_phon=1 if phonon_pert else 0, # phonon-type perturbation
d3e_pert2_phon=0,
Expand Down Expand Up @@ -3142,7 +3132,7 @@ def pop_par_vars(self, all=False) -> dict:
"""
Remove all the variables associated to parallelism from the input file.
Useful in case of a restart when we need to remove the parallel variables
before rerunning autoparal
before rerunning with autoparal.
"""
parvars = ['npkpt', 'npfft', 'npband', 'npspinor', 'npimage']
if all:
Expand Down Expand Up @@ -3465,7 +3455,11 @@ def has_same_structures(self) -> bool:
def __str__(self) -> str:
return self.to_string()

def to_string(self, mode="text", verbose=0, with_pseudos=True, files_file=False) -> str:
def to_string(self,
mode: str = "text",
verbose: int =0,
with_pseudos: bool = True,
files_file: bool = False) -> str:
"""
String representation i.e. the ABINIT input file.
Expand Down Expand Up @@ -3803,7 +3797,7 @@ def modes_at_qpoint(cls, structure, qpoint, asr=2, chneut=1, dipdip=1, dipquad=1
qpoint = qpoint.frac_coords if hasattr(qpoint, "frac_coords") else np.array(qpoint)

if len(qpoint) != 3:
raise ValueError("Wrong q-point %s" % qpoint)
raise ValueError(f"Wrong {qpoint=}")

return cls.modes_at_qpoints(structure=structure, qpoints=[qpoint], asr=asr, chneut=chneut, dipdip=dipdip,
dipquad=dipquad, quadquad=quadquad,
Expand Down Expand Up @@ -3942,7 +3936,7 @@ def phbands_and_dos(cls, structure, ngqpt, nqsmall, qppa=None, ndivsm=20, line_d

dossmear = Energy(float(value), eunit).to("Ha")
else:
raise NotImplementedError("Wrong value for dos_method: %s" % str(dos_method))
raise NotImplementedError(f"Wrong value for {dos_method=}")

new = cls(structure, comment="ANADDB input for phonon bands and DOS generated by AbiPy" if not comment else comment,
anaddb_args=anaddb_args, anaddb_kwargs=anaddb_kwargs, spell_check=spell_check)
Expand Down Expand Up @@ -4240,7 +4234,7 @@ def to_string(self, sortmode=None, mode="text", verbose=0, files_file=False) ->
# alphabetical order.
keys = sorted(self.keys())
else:
raise ValueError("Unsupported value for sortmode %s" % str(sortmode))
raise ValueError(f"Unsupported value for {sortmode=}")

if mode == "html":
var_database = get_anaddb_variables()
Expand Down Expand Up @@ -4448,7 +4442,7 @@ def as_dict(self) -> dict:
value = self.vars.get(name)
if value is None: value = self.get_default(name)
if value is None:
raise self.Error("Variable %s is missing" % name)
raise self.Error(f"Variable {name=} is missing")

var = self._NAME2VAR[name]
grp = var.group
Expand All @@ -4465,7 +4459,7 @@ def to_string(self, verbose: int = 0, files_file: bool = False) -> str:
value = self.vars.get(name)
if value is None: value = self.get_default(name)
if value is None:
raise self.Error("Variable %s is missing" % name)
raise self.Error(f"Variable {name=} is missing")

# One line per variable --> valperline set to None
variable = InputVariable("", value, valperline=None)
Expand Down
12 changes: 7 additions & 5 deletions abipy/abio/robots.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# coding: utf-8
"""
This module defines the Robot BaseClass. Robots operates on multiple files and provide helper
functions to plot the data e.g. convergence studies and to build pandas dataframes from the output files.
This module defines the Robot BaseClass.
Robots operates on multiple files and provide helper
functions to plot the data e.g. convergence studies
and to build pandas dataframes from the output files.
"""
from __future__ import annotations

Expand Down Expand Up @@ -150,7 +152,7 @@ def _open_files_in_dir(cls, top: str, walk: bool) -> list:
Open files in directory tree starting from `top`. Return list of Abinit files.
"""
if not os.path.isdir(top):
raise ValueError("%s: no such directory" % str(top))
raise ValueError(f"{top=}: no such directory")
from abipy.abilab import abiopen
items = []
if walk:
Expand Down Expand Up @@ -431,7 +433,7 @@ def add_file(self, label, abifile, filter_abifile=None) -> None:
self._do_close[abifile.filepath] = True

if label in self._abifiles:
raise ValueError("label %s is already present!" % label)
raise ValueError(f"{label=} is already present!")

self._abifiles[label] = abifile

Expand Down Expand Up @@ -773,7 +775,7 @@ def is_sortable(self, aname: str, raise_exc: bool = False) -> bool:
%s
Note that this list is automatically generated.
Not all entries are sortable (Please select number-like quantities)""" % (self.__class__.__name__, aname, str(attrs)))
Not all entries are sortable (please select number-like quantities)""" % (self.__class__.__name__, aname, str(attrs)))

def _sortby_labelfile_list(self, labelfile_list, func_or_string, reverse=False, unpack=False):
"""
Expand Down
22 changes: 10 additions & 12 deletions abipy/dfpt/gruneisen.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from functools import lru_cache
from collections import OrderedDict
#from typing import List
from monty.string import marquee, list_strings
from monty.termcolor import cprint
from monty.collections import AttrDict
Expand Down Expand Up @@ -77,7 +76,7 @@ def __str__(self):
return self.to_string()

def to_string(self, verbose: int = 0) -> str:
"""String representation."""
"""String representation with verbosite level `verbose`."""
lines = []; app = lines.append

app(marquee("File Info", mark="="))
Expand Down Expand Up @@ -185,7 +184,6 @@ def to_dataframe(self) -> pd.DataFrame:
freq Phonon frequency in eV.
============== ==========================
"""

grun_vals = self.gvals_qibz
nqibz, natom3 = grun_vals.shape
phfreqs = self.reader.rootgrp.variables["gruns_wvols_qibz"][:, self.iv0, :] * abu.Ha_eV
Expand Down Expand Up @@ -323,7 +321,7 @@ def plot_phbands_with_gruns(self, fill_with="gruns", gamma_fact=1, alpha=0.6, wi
max_gamma = np.abs(self.grun_vals_finite_differences(match_eigv=True)).max()
values = self.grun_vals_finite_differences(match_eigv=True)
else:
raise ValueError("Unsupported fill_with: `%s`" % fill_with)
raise ValueError(f"Unsupported {fill_with=}")

# Plot gruneisen markers on top of band structure.
xvals = np.arange(len(phbands.phfreqs))
Expand Down Expand Up @@ -399,7 +397,7 @@ def plot_gruns_scatter(self, values="gruns", ax=None, units="eV", cmap="rainbow"
elif values == "gruns_fd":
y = self.gvals_qibz_finite_differences(match_eigv=True)
else:
raise ValueError("Unsupported values: `%s`" % values)
raise ValueError(f"Unsupported {values=}")

w = self.wvols_qibz[:, self.iv0, :] * abu.phfactor_ev2units(units)

Expand Down Expand Up @@ -481,7 +479,7 @@ def plot_gruns_bs(self, values="gruns", ax=None, branch_range=None, qlabels=None
elif values == "gruns_fd":
y = self.split_gruns_finite_differences(match_eigv=True)
else:
raise ValueError("Unsupported values: `%s`" % values)
raise ValueError(f"Unsupported {values=}")

phbands = self.phbands_qpath_vol[self.iv0]

Expand Down Expand Up @@ -673,9 +671,11 @@ def acoustic_debye_temp(self):
return self.phdos.get_acoustic_debye_temp(len(self.structure))

@classmethod
def from_ddb_list(cls, ddb_list, nqsmall=10, qppa=None, ndivsm=20, line_density=None, asr=2, chneut=1, dipdip=1,
dos_method="tetra", lo_to_splitting="automatic", ngqpt=None, qptbounds=None, anaddb_kwargs=None,
verbose=0, mpi_procs=1, workdir=None, manager=None):
def from_ddb_list(cls, ddb_list, nqsmall=10, qppa=None, ndivsm=20, line_density=None,
asr=2, chneut=1, dipdip=1,
dos_method="tetra", lo_to_splitting="automatic",
ngqpt=None, qptbounds=None, anaddb_kwargs=None,
verbose=0, mpi_procs=1, workdir=None, manager=None):
"""
Execute anaddb to compute generate the object from a list of ddbs.
Expand Down Expand Up @@ -748,9 +748,7 @@ def from_ddb_list(cls, ddb_list, nqsmall=10, qppa=None, ndivsm=20, line_density=
if not report.run_completed:
raise ddb0.AnaddbError(task=task, report=report)

gruns = cls.from_file(os.path.join(task.workdir, "run.abo_GRUNS.nc"))

return gruns
return cls.from_file(os.path.join(task.workdir, "run.abo_GRUNS.nc"))

@lru_cache()
def grun_vals_finite_differences(self, match_eigv=True):
Expand Down
6 changes: 4 additions & 2 deletions abipy/dfpt/phtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,11 @@ def has_direction(self, direction, cartesian=False) -> bool:
return False


def open_file_phononwebsite(filename, port=8000,
def open_file_phononwebsite(filename,
port=8000,
website="http://henriquemiranda.github.io/phononwebsite",
host="localhost", browser=None): # pragma: no cover
host="localhost",
browser=None): # pragma: no cover
"""
Take a file, detect the type and open it on the phonon website
Based on a similar function in <https://github.com/henriquemiranda/phononwebsite/phononweb.py>
Expand Down
11 changes: 3 additions & 8 deletions abipy/dfpt/raman.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ def _get_prefactor(w, temp, laser_freq) -> np.array:
Returns:
An array with shape (n modes) with the coefficient for the Raman intensities.
"""

c = np.zeros_like(w)
ind = np.where(w > 1e-5)

Expand All @@ -165,7 +164,7 @@ def _get_prefactor(w, temp, laser_freq) -> np.array:

return c

def _get_lorentz_freqs_and_factor(self, intensity, non_anal_dir, min_freq, max_freq,
def _get_lorentz_freqs_and_factor(self, intensity, non_anal_dir, min_freq, max_freq,
num, width, units) -> tuple:
"""
Helper method to get the list of frequencies and the main spread factors to
Expand All @@ -187,7 +186,6 @@ def _get_lorentz_freqs_and_factor(self, intensity, non_anal_dir, min_freq, max_f
Tuple with list of "num" frequencies in eV and factors for the Lorentz broadening
with shape (n modes, num).
"""

if non_anal_dir is None:
w = self.phfreqs
else:
Expand Down Expand Up @@ -287,7 +285,7 @@ def get_lorentz_intensity(self, temp, laser_freq, width, non_anal_dir=None, min_

return li_func

def get_powder_intensity(self, temp, laser_freq, non_anal_dir=None,
def get_powder_intensity(self, temp, laser_freq, non_anal_dir=None,
relative=False, units="eV") -> PowderIntensity:
"""
Calculates the Raman intensities in arbitrary units for each mode integrated over all possible
Expand All @@ -309,7 +307,6 @@ def get_powder_intensity(self, temp, laser_freq, non_anal_dir=None,
A PowderIntensity with the parallel, perpendicular and total components of the powder
intensities. Each one is an array with length n modes.
"""

if non_anal_dir is None:
w = self.phfreqs
sus = self.susceptibility
Expand Down Expand Up @@ -369,7 +366,6 @@ def get_powder_lorentz_intensity(self, temp, laser_freq, width, non_anal_dir=Non
A PowderIntensity with the parallel, perpendicular and total components of the powder
intensities. Each one is a Function1D with "num" points.
"""

pi = self.get_powder_intensity(temp=temp, laser_freq=laser_freq, non_anal_dir=non_anal_dir, units=units)

freqs, lorentz = self._get_lorentz_freqs_and_factor(intensity=pi.tot, non_anal_dir=non_anal_dir, min_freq=min_freq,
Expand All @@ -386,7 +382,7 @@ def get_powder_lorentz_intensity(self, temp, laser_freq, width, non_anal_dir=Non

@add_fig_kwargs
def plot_intensity(self, temp, laser_freq, width, value, non_anal_dir=None, min_freq=None, max_freq=None,
num=1000, relative=False, units="eV", ax=None,
num=1000, relative=False, units="eV", ax=None,
plot_phfreqs=False, **kwargs) -> Figure:
"""
Plot one representation of the broadened Raman intensities.
Expand Down Expand Up @@ -420,7 +416,6 @@ def plot_intensity(self, temp, laser_freq, width, value, non_anal_dir=None, min_
Returns: |matplotlib-Figure|
"""

ax, fig, plt = get_ax_fig_plt(ax=ax)

if width:
Expand Down
Loading

0 comments on commit f4d0a33

Please sign in to comment.