Skip to content

Commit 5d17288

Browse files
committed
Code cleanup
1 parent 861c9b8 commit 5d17288

File tree

13 files changed

+353
-304
lines changed

13 files changed

+353
-304
lines changed

abipy/eph/common.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,27 +22,27 @@ class BaseEphReader(ElectronsReader):
2222
"""
2323

2424
@lazy_property
25-
def ddb_ngqpt(self):
25+
def ddb_ngqpt(self) -> np.ndarray:
2626
"""Q-Mesh for DDB file."""
2727
return self.read_value("ddb_ngqpt")
2828

2929
@lazy_property
30-
def ngqpt(self):
30+
def ngqpt(self) -> np.ndarray:
3131
"""Effective Q-mesh used in to compute integrals (ph_linewidts, e-ph self-energy)."""
3232
return self.read_value("ngqpt")
3333

3434
@lazy_property
35-
def ph_ngqpt(self):
35+
def ph_ngqpt(self) -> np.ndarray:
3636
"""Q-mesh for Phonon DOS, interpolated A2F ..."""
3737
return self.read_value("ph_ngqpt")
3838

3939
@lazy_property
40-
def eph_ngqpt_fine(self):
40+
def eph_ngqpt_fine(self) -> np.ndarray:
4141
"""Q-mesh for interpolated DFPT potentials"""
4242
return self.read_value("eph_ngqpt_fine")
4343

4444
@lazy_property
45-
def common_eph_params(self):
45+
def common_eph_params(self) -> dict:
4646
"""
4747
Read basic parameters (scalars) from the netcdf files produced by the EPH code and cache them
4848
"""

abipy/eph/gpath.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
"""
55
from __future__ import annotations
66

7-
import dataclasses
7+
#import dataclasses
88
import numpy as np
9-
import pandas as pd
9+
#import pandas as pd
1010
import abipy.core.abinit_units as abu
1111

1212
from monty.string import marquee
@@ -27,7 +27,7 @@
2727
from abipy.eph.common import BaseEphReader
2828

2929

30-
def k2s(k_vector, fmt=".3f", threshold = 1e-8) -> str:
30+
def k2s(k_vector, fmt=".3f", threshold=1e-8) -> str:
3131
k_vector = np.asarray(k_vector)
3232
k_vector[np.abs(k_vector) < threshold] = 0
3333

@@ -99,7 +99,7 @@ def params(self) -> dict:
9999
def __str__(self) -> str:
100100
return self.to_string()
101101

102-
def to_string(self, verbose: int=0) -> str:
102+
def to_string(self, verbose: int = 0) -> str:
103103
"""String representation with verbosiy level ``verbose``."""
104104
lines = []; app = lines.append
105105

@@ -126,15 +126,15 @@ def _get_which_g_list(which_g: str) -> list[str]:
126126
return all_choices
127127

128128
if which_g not in all_choices:
129-
raise ValueError(f"Invalid {which=}, should be in {all_choices=}")
129+
raise ValueError(f"Invalid {which_g=}, should be in {all_choices=}")
130130

131131
return [which_g]
132132

133133
def _get_band_range(self, band_range):
134134
return (self.r.bstart, self.r.bstop) if band_range is None else band_range
135135

136136
@add_fig_kwargs
137-
def plot_g_qpath(self, band_range=None, which_g="avg", with_qexp: int=0, scale=1, gmax_mev=250,
137+
def plot_g_qpath(self, band_range=None, which_g="avg", with_qexp: int = 0, scale=1, gmax_mev=250,
138138
ph_modes=None, with_phbands=True, with_ebands=False,
139139
ax_mat=None, fontsize=8, **kwargs) -> Figure:
140140
"""
@@ -481,16 +481,16 @@ def get_gnuq_average_spin(self, spin: int, band_range: list|tuple|None, eps_mev:
481481
# Average over degenerate k+q electrons taking bstart into account.
482482
absg = absg_avg.copy()
483483
for iq in range(self.nq_path):
484-
for n_k in range(nb_in_g):
485-
for m_kq in range(nb_in_g):
486-
w_1 = all_eigens_kq[spin, iq, m_kq + bstart]
487-
g2_nu[:], nn = 0.0, 0
488-
for bsum_kq in range(nb_in_g):
489-
w_2 = all_eigens_kq[spin, iq, bsum_kq + bstart]
490-
if abs(w_2 - w_1) >= eps_ev: continue
491-
nn += 1
492-
g2_nu += absg[iq,:,bsum_kq,n_k] ** 2
493-
absg_avg[iq,:,m_kq,n_k] = np.sqrt(g2_nu / nn)
484+
for n_k in range(nb_in_g):
485+
for m_kq in range(nb_in_g):
486+
w_1 = all_eigens_kq[spin, iq, m_kq + bstart]
487+
g2_nu[:], nn = 0.0, 0
488+
for bsum_kq in range(nb_in_g):
489+
w_2 = all_eigens_kq[spin, iq, bsum_kq + bstart]
490+
if abs(w_2 - w_1) >= eps_ev: continue
491+
nn += 1
492+
g2_nu += absg[iq,:,bsum_kq,n_k] ** 2
493+
absg_avg[iq,:,m_kq,n_k] = np.sqrt(g2_nu / nn)
494494

495495
# Transpose the data: (nq_path, natom3, nb_in_g, nb_in_g) -> (natom3, nq_path, nb_in_g, nb_in_g)
496496
absg_avg, absg_raw = absg_avg.transpose(1, 0, 2, 3).copy(), absg_raw.transpose(1, 0, 2, 3).copy()
@@ -553,11 +553,11 @@ def get_gnuk_average_spin(self, spin: int, band_range: list|tuple|None, eps_mev:
553553
absg_avg = np.zeros_like(absg)
554554
for ik in range(self.nk_path):
555555
for nu in range(natom3):
556-
# Sum the squared values of absg over the degenerate phonon mu indices.
557-
mask_nu = np.abs(phfreqs_ha[iq, :] - phfreqs_ha[iq, nu]) < eps_ha
558-
g2_mn = np.sum(absg[ik, mask_nu, :, :]**2, axis=0)
559-
# Compute the symmetrized value and divide by the number of degenerate ph-modes for this iq.
560-
absg_avg[ik, nu, :, :] = np.sqrt(g2_mn / np.sum(mask_nu))
556+
# Sum the squared values of absg over the degenerate phonon mu indices.
557+
mask_nu = np.abs(phfreqs_ha[iq, :] - phfreqs_ha[iq, nu]) < eps_ha
558+
g2_mn = np.sum(absg[ik, mask_nu, :, :]**2, axis=0)
559+
# Compute the symmetrized value and divide by the number of degenerate ph-modes for this iq.
560+
absg_avg[ik, nu, :, :] = np.sqrt(g2_mn / np.sum(mask_nu))
561561

562562
# MG FIXME: Note the difference with a similar function in gkq here I use absg and not absgk
563563
# Average over degenerate k electrons taking bstart into account.
@@ -645,7 +645,7 @@ def plot_g_qpath(self, which_g="avg", gmax_mev=250, ph_modes=None,
645645

646646
# TODO: Compute common band range.
647647
band_range = None
648-
ref_ifile= 0
648+
ref_ifile = 0
649649
#q_label = r"$|q|^{%d}$" % with_qexp if with_qexp else ""
650650
#g_units = "(meV)" if with_qexp == 0 else r"(meV $\AA^-{%s}$)" % with_qexp
651651

@@ -703,4 +703,4 @@ def write_notebook(self, nbpath=None) -> str:
703703
#nb.cells.extend(self.get_baserobot_code_cells())
704704
#nb.cells.extend(self.get_ebands_code_cells())
705705

706-
return self._write_nb_nbpath(nb, nbpath)
706+
return self._write_nb_nbpath(nb, nbpath)

abipy/eph/gstore.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ def find_iq_glob_qpoint(self, qpoint, spin: int):
476476
#print(f"Found {qpoint = } with index {iq_g = }")
477477
return iq_g, qpoint
478478

479-
raise ValueError(f"Cannot find {qpoint = } in GSTORE.nc")
479+
raise ValueError(f"Cannot find {qpoint=} in GSTORE.nc")
480480

481481
def find_ik_glob_kpoint(self, kpoint, spin: int):
482482
"""Find the internal indices of the kpoint needed to access the gvals array."""
@@ -486,7 +486,7 @@ def find_ik_glob_kpoint(self, kpoint, spin: int):
486486
#print(f"Found {kpoint = } with index {ik_g = }")
487487
return ik_g, kpoint
488488

489-
raise ValueError(f"Cannot find {kpoint = } in GSTORE.nc")
489+
raise ValueError(f"Cannot find {kpoint=} in GSTORE.nc")
490490

491491
# TODO: This fix to read groups should be imported in pymatgen.
492492
@lazy_property
@@ -539,7 +539,7 @@ def neq(self, ref_basename: str | None = None, verbose: int = 0) -> int:
539539
return ierr
540540

541541
@staticmethod
542-
def _neq_two_gstores(gstore1: GstoreFile, gstore2: GstoreFile, verbose: int) -> int:
542+
def _neq_two_gstores(self: GstoreFile, gstore2: GstoreFile, verbose: int) -> int:
543543
"""
544544
Helper function to compare two GSTORE files.
545545
"""
@@ -550,12 +550,12 @@ def _neq_two_gstores(gstore1: GstoreFile, gstore2: GstoreFile, verbose: int) ->
550550
]
551551

552552
for aname in aname_list:
553-
self._compare_attr_name(aname, gstore1, gstore2)
553+
self._compare_attr_name(aname, self, gstore2)
554554

555555
# Now compare the gkq objects for each spin.
556556
ierr = 0
557-
for spin in range(gstore1.nsppol):
558-
gqk1, gqk2 = gstore1.gqk_spin[spin], gstore2.gqk_spin[spin]
557+
for spin in range(self.nsppol):
558+
gqk1, gqk2 = self.gqk_spin[spin], gstore2.gqk_spin[spin]
559559
ierr += gqk1.neq(gqk2, verbose)
560560

561561
return ierr
@@ -585,4 +585,4 @@ def write_notebook(self, nbpath=None) -> str:
585585
#nb.cells.extend(self.get_baserobot_code_cells())
586586
#nb.cells.extend(self.get_ebands_code_cells())
587587

588-
return self._write_nb_nbpath(nb, nbpath)
588+
return self._write_nb_nbpath(nb, nbpath)

abipy/eph/gwan.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ def neq(self, other: Gqk, verbose: int) -> int:
339339
return ierr
340340

341341

342-
class GstoreReader(BaseEphReader):
342+
class GwanReader(BaseEphReader):
343343
"""
344344
Reads data from file and constructs objects.
345345

abipy/eph/varpeq.py

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,12 @@
1111
import pandas as pd
1212
import abipy.core.abinit_units as abu
1313

14-
from collections import defaultdict
1514
from monty.string import marquee
1615
from monty.functools import lazy_property
17-
from monty.termcolor import cprint
16+
#from monty.termcolor import cprint
1817
from abipy.core.func1d import Function1D
1918
from abipy.core.structure import Structure
20-
from abipy.core.kpoints import kpoints_indices, kmesh_from_mpdivs, map_grid2ibz, IrredZone
19+
from abipy.core.kpoints import kpoints_indices, kmesh_from_mpdivs, map_grid2ibz #, IrredZone
2120
from abipy.core.mixins import AbinitNcFile, Has_Structure, Has_ElectronBands, NotebookWriter
2221
from abipy.tools.typing import PathLike
2322
from abipy.tools.plotting import (add_fig_kwargs, get_ax_fig_plt, get_axarray_fig_plt, set_axlims, set_visible,
@@ -107,7 +106,6 @@ class Entry:
107106
# Convert to dictionary: name --> Entry
108107
_ALL_ENTRIES = {e.name: e for e in _ALL_ENTRIES}
109108

110-
111109
class VarpeqFile(AbinitNcFile, Has_Structure, Has_ElectronBands, NotebookWriter):
112110
"""
113111
This file stores the results of a VARPEQ calculations: SCF cycle, A_nk, B_qnu coefficients
@@ -174,7 +172,7 @@ def params(self) -> dict:
174172
def __str__(self) -> str:
175173
return self.to_string()
176174

177-
def to_string(self, verbose: int=0) -> str:
175+
def to_string(self, verbose: int = 0) -> str:
178176
"""String representation with verbosiy level ``verbose``."""
179177
lines = []; app = lines.append
180178

@@ -197,7 +195,7 @@ def to_string(self, verbose: int=0) -> str:
197195
for spin in range(self.nsppol):
198196
polaron = self.polaron_spin[spin]
199197
df = polaron.get_final_results_df()
200-
app(f"Last SCF iteration. Energies in eV units")
198+
app("Last SCF iteration. Energies in eV units")
201199
app(str(df))
202200
app("")
203201

@@ -322,7 +320,7 @@ def ufact_k(k):
322320

323321
return df_list
324322

325-
def get_final_results_df(self, with_params: bool=False) -> pd.DataFrame:
323+
def get_final_results_df(self, with_params: bool = False) -> pd.DataFrame:
326324
"""
327325
Return daframe with the last iteration for all polaronic states.
328326
NB: Energies are in eV.
@@ -342,7 +340,7 @@ def get_final_results_df(self, with_params: bool=False) -> pd.DataFrame:
342340
def __str__(self) -> str:
343341
return self.to_string()
344342

345-
def to_string(self, verbose: int=0) -> str:
343+
def to_string(self, verbose: int = 0) -> str:
346344
"""
347345
String representation with verbosiy level verbose.
348346
"""
@@ -380,7 +378,7 @@ def ngkpt_and_shifts(self) -> tuple:
380378

381379
return ngkpt, shifts
382380

383-
def get_title(self, with_gaps: bool=True) -> str:
381+
def get_title(self, with_gaps: bool = True) -> str:
384382
"""
385383
Return string with title for matplotlib plots.
386384
"""
@@ -462,7 +460,7 @@ def get_b2_interpolator_state(self, interp_method) -> BzRegularGridInterpolator:
462460
return [BzRegularGridInterpolator(self.structure, shifts, np.abs(b_data[pstate])**2, method=interp_method)
463461
for pstate in range(self.nstates)]
464462

465-
def write_a2_bxsf(self, filepath: PathLike, fill_value: float=0.0) -> None:
463+
def write_a2_bxsf(self, filepath: PathLike, fill_value: float = 0.0) -> None:
466464
r"""
467465
Export \sum_n |A_{pnk}|^2 in BXSF format suitable for visualization with xcrysden (use ``xcrysden --bxsf FILE``).
468466
Requires gamma-centered k-mesh.
@@ -480,7 +478,7 @@ def write_a2_bxsf(self, filepath: PathLike, fill_value: float=0.0) -> None:
480478

481479
bxsf_write(filepath, self.structure, 1, self.nstates, ngkpt, a2_data, fermie, unit="Ha")
482480

483-
def write_b2_bxsf(self, filepath: PathLike, fill_value: float=0.0) -> None:
481+
def write_b2_bxsf(self, filepath: PathLike, fill_value: float = 0.0) -> None:
484482
r"""
485483
Export \sum_{\nu} |B_{q\nu}|^2 in BXSF format suitable for visualization with xcrysden (use ``xcrysden --bxsf FILE``).
486484
@@ -554,9 +552,9 @@ def plot_scf_cycle(self, ax_mat=None, fontsize=8, **kwargs) -> Figure:
554552

555553
@add_fig_kwargs
556554
def plot_ank_with_ebands(self, ebands_kpath,
557-
ebands_kmesh=None, lpratio: int=5,
558-
with_ibz_a2dos=True, method="gaussian", step: float=0.05, width: float=0.1,
559-
nksmall: int=20, normalize: bool=False, with_title=True, interp_method="linear",
555+
ebands_kmesh=None, lpratio: int = 5,
556+
with_ibz_a2dos=True, method="gaussian", step: float = 0.05, width: float = 0.1,
557+
nksmall: int = 20, normalize: bool = False, with_title=True, interp_method="linear",
560558
ax_mat=None, ylims=None, scale=10, marker_color="gold", fontsize=12, **kwargs) -> Figure:
561559
"""
562560
Plot electron bands with markers whose size is proportional to |A_nk|^2.
@@ -721,7 +719,7 @@ def plot_bqnu_with_ddb(self, ddb, with_phdos=True, anaddb_kwargs=None, **kwargs)
721719

722720
@add_fig_kwargs
723721
def plot_bqnu_with_phbands(self, phbands_qpath,
724-
phdos_file=None, ddb=None, width=0.001, normalize: bool=True,
722+
phdos_file=None, ddb=None, width=0.001, normalize: bool = True,
725723
verbose=0, anaddb_kwargs=None, with_title=True, interp_method="linear",
726724
ax_mat=None, scale=10, marker_color="gold", fontsize=12, **kwargs) -> Figure:
727725
"""
@@ -773,7 +771,8 @@ def plot_bqnu_with_phbands(self, phbands_qpath,
773771

774772
if not with_phdos:
775773
# Return immediately.
776-
if with_title: fig.suptitle(self.get_title(with_gaps=True))
774+
if with_title:
775+
fig.suptitle(self.get_title(with_gaps=True))
777776
return fig
778777

779778
####################
@@ -803,7 +802,6 @@ def plot_bqnu_with_phbands(self, phbands_qpath,
803802
#with_ibz_b2dos = False
804803

805804
for pstate in range(self.nstates):
806-
807805
# Compute B2(E) by looping over the full BZ.
808806
bqnu_dos = np.zeros(len(phdos_mesh))
809807
for iq_bz, qpoint in enumerate(phbands_qmesh.qpoints):
@@ -815,7 +813,7 @@ def plot_bqnu_with_phbands(self, phbands_qpath,
815813
for w, b2 in zip(freqs_nu, b2_interp_state[pstate].eval_kpoint(qpoint), strict=True):
816814
bqnu_dos += q_weight * b2 * gaussian(phdos_mesh, width, center=w)
817815

818-
bqnu_dos = Function1D(wmesh, bqnu_dos)
816+
bqnu_dos = Function1D(phdos_mesh, bqnu_dos)
819817

820818
ax = ax_mat[pstate, 1]
821819
phdos.plot_ax(ax, exchange_xy=True, normalize=normalize, label="phDOS(E)", color="black")
@@ -946,7 +944,7 @@ def to_string(self, verbose=0) -> str:
946944

947945
return "\n".join(lines)
948946

949-
def get_final_results_df(self, spin=None, sortby=None, with_params: bool=True) -> pd.DataFrame:
947+
def get_final_results_df(self, spin=None, sortby=None, with_params: bool = True) -> pd.DataFrame:
950948
"""
951949
Return dataframe with the last iteration for all polaronic states.
952950
NB: Energies are in eV.
@@ -1046,4 +1044,4 @@ def write_notebook(self, nbpath=None) -> str:
10461044
#nbv.new_code_cell("ebands_plotter = robot.get_ebands_plotter()"),
10471045
])
10481046

1049-
return self._write_nb_nbpath(nb, nbpath)
1047+
return self._write_nb_nbpath(nb, nbpath)

0 commit comments

Comments
 (0)