Skip to content

Commit

Permalink
Fix remaining pycodestyle issues
Browse files Browse the repository at this point in the history
  • Loading branch information
gmatteo committed Oct 14, 2019
1 parent f3147b5 commit 78ed33e
Show file tree
Hide file tree
Showing 81 changed files with 372 additions and 331 deletions.
6 changes: 3 additions & 3 deletions abipy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
# Release data
__author__ = ''
for author, email in release.authors.values():
__author__ += author + ' <' + email + '>\n'
__author__ += author + ' <' + email + '>\n'
del author, email

__license__ = release.license
__version__ = release.version
__license__ = release.license
__version__ = release.version
1 change: 1 addition & 0 deletions abipy/abilab.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ def _straceback():
import traceback
return traceback.format_exc()


# Abinit text files. Use OrderedDict for nice output in show_abiopen_exc2class.
ext2file = collections.OrderedDict([
(".abi", AbinitInputFile),
Expand Down
22 changes: 12 additions & 10 deletions abipy/abio/abivars.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"AbinitInputParser",
]


def is_anaddb_var(varname):
"""True if varname is a valid Anaddb variable."""
return varname in get_codevars()["anaddb"]
Expand All @@ -44,6 +45,7 @@ def is_abivar(varname):
"T", "Tesla",)
}


def is_abiunit(s):
"""
True if string is one of the units supported by the ABINIT parser
Expand Down Expand Up @@ -218,7 +220,7 @@ def to_string(self, post=None, mode="text", verbose=0):
if mode == "html": vname = var_database[k].html_link(label=vname)
app("%s %s" % (vname, str(self[k])))

return "\n".join(lines) if mode=="text" else "\n".join(lines).replace("\n", "<br>")
return "\n".join(lines) if mode == "text" else "\n".join(lines).replace("\n", "<br>")

def _repr_html_(self):
"""Integration with jupyter_ notebooks."""
Expand Down Expand Up @@ -428,7 +430,7 @@ def parse(self, s):

varpos.append(len(tokens))

# Build dict {varname --> value_string}
# Build dict {varname --> value_string}
dvars = {}
for i, pos in enumerate(varpos[:-1]):
varname = tokens[pos]
Expand All @@ -452,7 +454,7 @@ def parse(self, s):
if udtset is not None:
raise NotImplementedError("udtset is not supported")

# Build list of datasets.
# Build list of datasets.
datasets = [Dataset() for i in range(ndtset)]

# Treat all variables without a dataset index
Expand Down Expand Up @@ -483,7 +485,7 @@ def parse(self, s):
vname = k[:-1]
start = str2array(dvars.pop(k))

# Handle ecut+ or ecut*
# Handle ecut+ or ecut*
incr = dvars.pop(vname + "+", None)
if incr is not None:
incr = str2array(incr)
Expand All @@ -498,12 +500,12 @@ def parse(self, s):
dt[vname] = start.copy()
start *= mult

# Consistency check
# 1) dvars should be empty
# Consistency check
# 1) dvars should be empty
if dvars:
raise ValueError("Don't know how handle variables in:\n%s" % pformat(dvars), indent=4)

# 2) Keys in datasets should be valid Abinit input variables.
# 2) Keys in datasets should be valid Abinit input variables.
wrong = []
for i, dt in enumerate(datasets):
wlist = [k for k in dt if not is_abivar(k)]
Expand All @@ -512,7 +514,7 @@ def parse(self, s):
if wrong:
raise ValueError("Found variables that are not registered in the abipy database:\n%s" % pformat(wrong, indent=4))

# 3) We don't support spg builder: dataset.structure will fail or, even worse,
# 3) We don't support spg builder: dataset.structure will fail or, even worse,
# spglib will segfault so it's better to raise here!
for dt in datasets:
if "spgroup" in dt or "nobj" in dt:
Expand All @@ -531,9 +533,9 @@ def eval_abinit_operators(tokens):
Receive a list of strings, find the occurences of operators supported
in the input file (e.g. sqrt), evalute the expression and return new list of strings.
.. note:
.. note:
This function is not recursive hence expr like sqrt(1/2) are not supported
This function is not recursive hence expr like sqrt(1/2) are not supported
"""
import math
import re
Expand Down
2 changes: 2 additions & 0 deletions abipy/abio/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
kppa=1000,
)


class ShiftMode(Enum):
"""
Class defining the mode to be used for the shifts.
Expand Down Expand Up @@ -1416,6 +1417,7 @@ def dfpt_from_gsinput(gs_inp, ph_ngqpt=None, qpoints=None, do_ddk=True, do_dde=T

return multi


#FIXME if the pseudos are passed as a PseudoTable the whole table will be serialized,
# it would be better to filter on the structure elements
class InputFactory(MSONable):
Expand Down
2 changes: 1 addition & 1 deletion abipy/abio/input_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
NSCF = "nscf"
BANDS = "bands"
DOS = "dos"
MOLECULAR_DYNACMICS="molecular_dynamics"
MOLECULAR_DYNACMICS = "molecular_dynamics"
DFPT = "dfpt"
PHONON = "phonon"
DDK = "ddk"
Expand Down
41 changes: 22 additions & 19 deletions abipy/abio/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,9 +582,11 @@ def to_string(self, sortmode="section", post=None, with_mnemonics=False, mode="t
"""
if mode == "html":
import html

def escape(text):
return html.escape(text, quote=True)
else:

def escape(text):
return text

Expand Down Expand Up @@ -988,7 +990,7 @@ def product(self, *items):
varnames, values = items[:i], items[i:]
if len(varnames) != len(values):
raise self.Error("The number of variables must equal the number of lists\n"
"varnames: %s\nvalues %s" % (str(varnames), str(values)))
"varnames: %s\nvalues %s" % (str(varnames), str(values)))

# TODO: group varnames and varvalues!
#varnames = [t[0] for t in items]
Expand Down Expand Up @@ -1117,8 +1119,8 @@ def new_with_structure(self, new_structure, scdims=None, verbose=1):
raise NotImplementedError("kptrlatt in new_with_structure")
#new["kptrlatt"] = (np.rint(np.array(new["kptrlatt"]) / iscale)).astype(int)
else:
# Single k-point
pass
# Single k-point
pass

# Add chkprim if not yet done.
new.set_vars_ifnotin(chkprim=0)
Expand Down Expand Up @@ -1217,7 +1219,7 @@ def make_ph_inputs_qpoint(self, qpt, tolerance=None, prtwf=-1, prepgkk=0, manage
# Note: this will work for phonons, but not for the other types of perturbations.
for pert, ph_input in zip(perts, ph_inputs):
rfdir = 3 * [0]
rfdir[pert.idir -1] = 1
rfdir[pert.idir - 1] = 1

ph_input.set_vars(
rfphon=1, # Will consider phonon-type perturbation
Expand Down Expand Up @@ -1402,10 +1404,10 @@ def make_dte_inputs(self, phonon_pert=False, skip_permutations=False, ixc=None,
d3e_pert1_dir=rfdir1, # Direction of the dte perturbation.
d3e_pert2_dir=rfdir2,
d3e_pert3_dir=rfdir3,
d3e_pert1_phon = 1 if pert.i1pert <= na else 0,
d3e_pert2_phon = 1 if pert.i2pert <= na else 0,
d3e_pert3_phon = 1 if pert.i3pert <= na else 0,
d3e_pert1_atpol = atpol,
d3e_pert1_phon=1 if pert.i1pert <= na else 0,
d3e_pert2_phon=1 if pert.i2pert <= na else 0,
d3e_pert3_phon=1 if pert.i3pert <= na else 0,
d3e_pert1_atpol=atpol,
nqpt=1, # One wavevector is to be considered
qpt=(0, 0, 0), # q-wavevector.
optdriver=5, # non-linear response functions, using the 2n+1 theorem.
Expand Down Expand Up @@ -1437,7 +1439,7 @@ def make_bec_inputs(self, tolerance=None, manager=None):
# See tutorespfn/Input/trf1_5.in dataset 3
for pert, inp in zip(perts, multi):
rfdir = 3 * [0]
rfdir[pert.idir -1] = 1
rfdir[pert.idir - 1] = 1

inp.set_vars(
rfphon=1, # Activate the calculation of the atomic dispacement perturbations
Expand Down Expand Up @@ -1480,7 +1482,7 @@ def make_strain_perts_inputs(self, tolerance=None, phonon_pert=True, kptopt=2, m

for pert, inp in zip(perts, multi):
rfdir = 3 * [0]
rfdir[pert.idir -1] = 1
rfdir[pert.idir - 1] = 1

if pert.ipert <= len(self.structure):
inp.set_vars(rfphon=1, # Activate the calculation of the atomic dispacement perturbations
Expand Down Expand Up @@ -1550,11 +1552,12 @@ def abiget_spacegroup(self, tolsym=None, retdict=False, workdir=None, manager=No
retdict: True to return dictionary with space group information instead of Structure.
workdir: Working directory of the fake task used to compute the ibz. Use None for temporary dir.
manager: |TaskManager| of the task. If None, the manager is initialized from the config file.
verbose: Verbosity level.
verbose: Verbosity level.
Return:
|Structure| object with AbinitSpaceGroup obtained from the main output file if retdict is False
else dict with e.g. {'bravais': 'Bravais cF (face-center cubic)', 'spg_number': 227, 'spg_symbol': 'Fd-3m'}.
else dict with e.g.
{'bravais': 'Bravais cF (face-center cubic)', 'spg_number': 227, 'spg_symbol': 'Fd-3m'}.
"""
# Avoid modifications in self.
inp = self.deepcopy()
Expand Down Expand Up @@ -1658,7 +1661,7 @@ def _handle_task_exception(self, task, prev_exc):
# 1) Abinit cannot be executed or runtime errors due e.g to libraries
# 2) IO buffering (Abinit called MPI_ABORT but files are not flushed before aborting.
# Try to return as much iformation as possible to aid debugging
errors = ["Problem in temp Task executed in %s" % task.workdir,
errors = ["Problem in temp Task executed in %s" % task.workdir,
"Previous exception %s" % prev_exc]

try:
Expand Down Expand Up @@ -2227,7 +2230,7 @@ def has_same_variable(kref, vref, other_inp):

for i, inp in enumerate(self):
header = "### DATASET %d ###" % (i + 1)
is_last = (i==self.ndtset - 1)
is_last = (i == self.ndtset - 1)
s = inp.to_string(post=str(i + 1), with_pseudos=is_last and with_pseudos, mode=mode,
with_structure=not has_same_structures, exclude=global_vars)
if s:
Expand All @@ -2236,7 +2239,7 @@ def has_same_variable(kref, vref, other_inp):

lines.append(s)

return "\n".join(lines) if mode=="text" else "\n".join(lines).replace("\n", "<br>")
return "\n".join(lines) if mode == "text" else "\n".join(lines).replace("\n", "<br>")

else:
# single datasets ==> don't append the dataset index to the variables.
Expand Down Expand Up @@ -2566,15 +2569,16 @@ def phbands_and_dos(cls, structure, ngqpt, nqsmall, qppa=None, ndivsm=20, line_d

if lo_to_splitting:
directions = []
rl = structure.lattice.reciprocal_lattice_crystallographic
for i, qpt in enumerate(qptbounds):
if np.array_equal(qpt, (0, 0, 0)):
# anaddb expects cartesian coordinates for the qph2l list
if i > 0:
directions.extend(structure.lattice.reciprocal_lattice_crystallographic.get_cartesian_coords(qptbounds[i-1]))
directions.extend(rl.get_cartesian_coords(qptbounds[i-1]))
directions.append(0)

if i < len(qptbounds) - 1:
directions.extend(structure.lattice.reciprocal_lattice_crystallographic.get_cartesian_coords(qptbounds[i+1]))
directions.extend(rl.get_cartesian_coords(qptbounds[i+1]))
directions.append(0)

if directions:
Expand Down Expand Up @@ -2872,7 +2876,6 @@ def html_link(self, label=None):
return '<a href="%s" target="_blank">%s</a>' % (self.url, self.name if label is None else label)



class OpticError(Exception):
"""Error class raised by OpticInput."""

Expand Down Expand Up @@ -2953,7 +2956,7 @@ def vars(self):
def _check_varname(self, key):
if key not in self._VARNAMES:
raise self.Error("%s is not a valid optic variable.\n"
"If you are sure the name is correct, please change the _VARIABLES list in:\n%s" %
"If you are sure the name is correct, please change the _VARIABLES list in:\n%s" %
(key, __file__))

def get_default(self, key):
Expand Down
4 changes: 2 additions & 2 deletions abipy/abio/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ def get_dtindex_key_value(line):

# (varname, dtindex), [line1, line2 ...]
stack_var, stack_lines = None, []

def pop_stack():
if stack_lines:
key, dtidx = stack_var
Expand Down Expand Up @@ -677,7 +678,6 @@ def yield_figs(self, **kwargs): # pragma: no cover
except Exception:
print("Abinit output files does not contain timopt data")


def compare_gs_scf_cycles(self, others, show=True):
"""
Produce and returns a list of matplotlib_ figure comparing the GS self-consistent
Expand Down Expand Up @@ -974,7 +974,7 @@ class OutNcFile(AbinitNcFile):
def __init__(self, filepath):
super().__init__(filepath)
self.reader = NetcdfReader(filepath)
self._varscache= {k: None for k in self.reader.rootgrp.variables}
self._varscache = {k: None for k in self.reader.rootgrp.variables}

def __dir__(self):
"""Ipython integration."""
Expand Down
10 changes: 5 additions & 5 deletions abipy/abio/robots.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def from_dir(cls, top, walk=True, abspath=False):
Args:
top (str): Root directory
walk: if True, directories inside `top` are included as well.
walk: if True, directories inside `top` are included as well.
abspath: True if paths in index should be absolute. Default: Relative to `top`.
"""
new = cls(*cls._open_files_in_dir(top, walk))
Expand All @@ -98,7 +98,7 @@ def from_dirs(cls, dirpaths, walk=True, abspath=False):
Similar to `from_dir` but accepts a list of directories instead of a single directory.
Args:
walk: if True, directories inside `top` are included as well.
walk: if True, directories inside `top` are included as well.
abspath: True if paths in index should be absolute. Default: Relative to `top`.
"""
items = []
Expand All @@ -119,7 +119,7 @@ def from_dir_glob(cls, pattern, walk=True, abspath=False):
Args:
pattern: Pattern string
walk: if True, directories inside `top` are included as well.
walk: if True, directories inside `top` are included as well.
abspath: True if paths in index should be absolute. Default: Relative to getcwd().
"""
import glob
Expand Down Expand Up @@ -295,7 +295,7 @@ def scan_dir(self, top, walk=True):
Return:
Number of files found.
"""
"""
count = 0
for filepath, abifile in self.__class__._open_files_in_dir(top, walk):
count += 1
Expand Down Expand Up @@ -692,7 +692,7 @@ def close(self):
if self._do_close.pop(abifile.filepath, False):
try:
abifile.close()
except:
except Exception:
print("Exception while closing: ", abifile.filepath)
print(exc)

Expand Down
2 changes: 0 additions & 2 deletions abipy/abio/tests/test_factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ def test_g0w0_with_ppmodel_inputs(self):
flow.register_work(G0W0Work(scf_input, nscf_input, scr_input, sigma_input))
assert flow.build_and_pickle_dump(abivalidate=True) == 0


# The default value of `shifts` changed in v0.3 from (0.5, 0.5, 0.5) to (0.0, 0.0, 0.0)
multi = g0w0_with_ppmodel_inputs(self.si_structure, self.si_pseudo,
scf_kppa, nscf_nband, ecuteps, ecutsigx,
Expand Down Expand Up @@ -301,7 +300,6 @@ def test_phonons_from_gsinput(self):
self.assert_input_equality('phonons_from_gsinput_ph_q_pert_1.json', inp_ph_q_pert_1_obj)
self.assert_input_equality('phonons_from_gsinput_ph_q_pert_2.json', inp_ph_q_pert_2_obj)


def test_elastic_inputs_from_gsinput(self):
"""Testing elastic_inputs_from_gsinput."""
gs_inp = gs_input(self.si_structure, self.si_pseudo, kppa=None, ecut=2, spin_mode="unpolarized")
Expand Down
Loading

0 comments on commit 78ed33e

Please sign in to comment.