Skip to content

Commit

Permalink
f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Nov 10, 2023
1 parent d95e2ad commit 3214fe0
Show file tree
Hide file tree
Showing 17 changed files with 44 additions and 50 deletions.
2 changes: 1 addition & 1 deletion pymatgen/analysis/bond_dissociation.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def __init__(
required_keys.append("pcm_dielectric")
for key in required_keys:
if key not in self.molecule_entry:
raise RuntimeError(key + " must be present in molecule entry! Exiting...")
raise RuntimeError(f"{key=} must be present in molecule entry! Exiting...")
for entry in self.filtered_entries:
if key not in entry:
raise RuntimeError(f"{key=} must be present in all fragment entries! Exiting...")
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/gb/grain.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,8 @@ def to_s(x, rjust=10):

outs.extend(
(
"abc : " + " ".join(to_s(i) for i in self.lattice.abc),
"angles: " + " ".join(to_s(i) for i in self.lattice.angles),
f"abc : {' '.join(to_s(i) for i in self.lattice.abc)}",
f"angles: {' '.join(to_s(i) for i in self.lattice.angles)}",
f"Sites ({len(self)})",
)
)
Expand Down
11 changes: 5 additions & 6 deletions pymatgen/analysis/interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def get_kinks(self) -> list[tuple[int, float, float, Reaction, float]]:
num_atoms = [(x * self.comp1.num_atoms + (1 - x) * self.comp2.num_atoms) for x in x_kink]
energy_per_rxt_formula = [
energy_kink[i]
* self._get_elmt_amt_in_rxn(react_kink[i])
* self._get_elem_amt_in_rxn(react_kink[i])
/ num_atoms[i]
* InterfacialReactivity.EV_TO_KJ_PER_MOL
for i in range(2)
Expand All @@ -180,7 +180,7 @@ def get_kinks(self) -> list[tuple[int, float, float, Reaction, float]]:
# Gets balanced reaction at kinks
rxt = self._get_reaction(x)
react_kink.append(rxt)
rxt_energy = normalized_energy * self._get_elmt_amt_in_rxn(rxt) / n_atoms
rxt_energy = normalized_energy * self._get_elem_amt_in_rxn(rxt) / n_atoms
energy_per_rxt_formula.append(rxt_energy * self.EV_TO_KJ_PER_MOL)

index_kink = range(1, len(critical_comp) + 1)
Expand Down Expand Up @@ -316,7 +316,7 @@ def _get_reaction(self, x: float) -> Reaction:

return reaction

def _get_elmt_amt_in_rxn(self, rxn: Reaction) -> int:
def _get_elem_amt_in_rxn(self, rxn: Reaction) -> int:
"""
Computes total number of atoms in a reaction formula for elements
not in external reservoir. This method is used in the calculation
Expand Down Expand Up @@ -474,10 +474,9 @@ def _get_entry_energy(pd: PhaseDiagram, composition: Composition):

if not candidate:
warnings.warn(
"The reactant " + composition.reduced_formula + " has no matching entry with negative formation"
f"The reactant {composition.reduced_formula} has no matching entry with negative formation"
" energy, instead convex hull energy for this"
" composition will be used for reaction energy "
"calculation. "
" composition will be used for reaction energy calculation. "
)
return pd.get_hull_energy(composition)
min_entry_energy = min(candidate)
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -1778,7 +1778,7 @@ def get_decomposition(self, comp: Composition) -> dict[PDEntry, float]:
return pd.get_decomposition(comp)
except ValueError as e:
# NOTE warn when stitching across pds is being used
warnings.warn(str(e) + " Using SLSQP to find decomposition")
warnings.warn(f"{e} Using SLSQP to find decomposition")
competing_entries = self._get_stable_entries_in_space(frozenset(comp.elements))
return _get_slsqp_decomp(comp, competing_entries)

Expand Down
19 changes: 7 additions & 12 deletions pymatgen/analysis/pourbaix_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,15 +251,15 @@ def num_atoms(self):
def to_pretty_string(self) -> str:
"""A pretty string representation."""
if self.phase_type == "Solid":
return self.entry.composition.reduced_formula + "(s)"
return f"{self.entry.composition.reduced_formula}(s)"

return self.entry.name

def __repr__(self):
energy, npH, nPhi, nH2O, entry_id = self.energy, self.npH, self.nPhi, self.nH2O, self.entry_id
return (
f"{type(self).__name__}({self.entry.composition} with {energy = :.4f}, {npH = }, "
f"{nPhi = }, {nH2O = }, {entry_id = })"
f"{type(self).__name__}({self.entry.composition} with {energy=:.4f}, {npH=}, "
f"{nPhi=}, {nH2O=}, {entry_id=})"
)


Expand Down Expand Up @@ -1010,9 +1010,9 @@ def get_pourbaix_plot(
def plot_entry_stability(
self,
entry: Any,
pH_range: tuple[float, float] | None = None,
pH_range: tuple[float, float] = (-2, 16),
pH_resolution: int = 100,
V_range: tuple[float, float] | None = None,
V_range: tuple[float, float] = (-3, 3),
V_resolution: int = 100,
e_hull_max: float = 1,
cmap: str = "RdYlBu_r",
Expand All @@ -1024,9 +1024,9 @@ def plot_entry_stability(
Args:
entry (Any): The entry to plot stability for.
pH_range (tuple[float, float], optional): pH range for the plot. Defaults to [-2, 16].
pH_range (tuple[float, float], optional): pH range for the plot. Defaults to (-2, 16).
pH_resolution (int, optional): pH resolution. Defaults to 100.
V_range (tuple[float, float], optional): Voltage range for the plot. Defaults to [-3, 3].
V_range (tuple[float, float], optional): Voltage range for the plot. Defaults to (-3, 3).
V_resolution (int, optional): Voltage resolution. Defaults to 100.
e_hull_max (float, optional): Maximum energy above the hull. Defaults to 1.
cmap (str, optional): Colormap for the plot. Defaults to "RdYlBu_r".
Expand All @@ -1036,11 +1036,6 @@ def plot_entry_stability(
Returns:
plt.Axes: Matplotlib Axes object with the plotted stability.
"""
if pH_range is None:
pH_range = [-2, 16]
if V_range is None:
V_range = [-3, 3]

# Plot the Pourbaix diagram
ax = self.get_pourbaix_plot(ax=ax, **kwargs)
pH, V = np.mgrid[
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/apps/borg/queen.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def serial_assimilate(self, rootpath):
newdata = self._drone.assimilate(path)
self._data.append(newdata)
count += 1
logger.info(f"{count}/{total} ({count / total :.2%}) done")
logger.info(f"{count}/{total} ({count / total:.2%}) done")
for d in data:
self._data.append(json.loads(d, cls=MontyDecoder))

Expand Down Expand Up @@ -114,4 +114,4 @@ def order_assimilation(args):
status["count"] += 1
count = status["count"]
total = status["total"]
logger.info(f"{count}/{total} ({count / total :.2%}) done")
logger.info(f"{count}/{total} ({count / total:.2%}) done")
2 changes: 1 addition & 1 deletion pymatgen/cli/feff_plot_cross_section.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def main():

data = xmu.as_dict()

ax.set_title(data["calc"] + " Feff9.6 Calculation for " + data["atom"] + " in " + data["formula"] + " unit cell")
ax.set_title(f"{data['calc']} Feff9.6 Calculation for {data['atom']} in {data['formula']} unit cell")
ax.set_xlabel("Energies (eV)")
ax.set_ylabel("Absorption Cross-section")

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/command_line/critic2_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ def from_chgcar(
if chgcar:
input_script += ["load int.CHGCAR id chg_int", "integrable chg_int"]
if zpsp:
zpsp_str = " zpsp " + " ".join(f"{symbol} {zval}" for symbol, zval in zpsp.items())
zpsp_str = f" zpsp {' '.join(f'{symbol} {zval}' for symbol, zval in zpsp.items())}"
input_script[-2] += zpsp_str

# Command to run automatic analysis
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/command_line/gulp_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ def structure_lines(
for site in structure:
coord = [str(i) for i in getattr(site, coords_key)]
specie = site.specie
core_site_desc = specie.symbol + " core " + " ".join(coord) + "\n"
core_site_desc = f"{specie.symbol} core {' '.join(coord)}\n"
gin += core_site_desc
if (specie in _anions and anion_shell_flg) or (specie in _cations and cation_shell_flg):
shel_site_desc = specie.symbol + " shel " + " ".join(coord) + "\n"
Expand Down Expand Up @@ -827,7 +827,7 @@ def __init__(self, bush_lewis_flag):
else:
metal = elmnt.split("_")[0]
# oxi_state = metaloxi.split('_')[1][0]
species_dict[elmnt] = metal + " core " + row.split()[2] + "\n"
species_dict[elmnt] = f"{metal} core {row.split()[2]}\n"
continue

if pot_flg:
Expand Down
14 changes: 7 additions & 7 deletions pymatgen/core/lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -804,13 +804,13 @@ def selling_dist(self, other):
def __repr__(self):
outs = [
"Lattice",
" abc : " + " ".join(map(repr, self.lengths)),
" angles : " + " ".join(map(repr, self.angles)),
" volume : " + repr(self.volume),
" A : " + " ".join(map(repr, self._matrix[0])),
" B : " + " ".join(map(repr, self._matrix[1])),
" C : " + " ".join(map(repr, self._matrix[2])),
" pbc : " + " ".join(map(repr, self._pbc)),
f" abc : {' '.join(map(repr, self.lengths))}",
f" angles : {' '.join(map(repr, self.angles))}",
f" volume : {self.volume!r}",
f" A : {' '.join(map(repr, self._matrix[0]))}",
f" B : {' '.join(map(repr, self._matrix[1]))}",
f" C : {' '.join(map(repr, self._matrix[2]))}",
f" pbc : {' '.join(map(repr, self._pbc))}",
]
return "\n".join(outs)

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/electronic_structure/boltztrap2.py
Original file line number Diff line number Diff line change
Expand Up @@ -1114,7 +1114,7 @@ def plot_props(
temps_all,
prop_out.mean(axis=1),
"s-",
label=str(dop) + " $cm^{-3}$",
label=f"{dop} $cm^{-3}$",
)
elif output == "eigs":
for i in range(3):
Expand Down
10 changes: 5 additions & 5 deletions pymatgen/electronic_structure/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1985,7 +1985,7 @@ def orbital_label(list_orbitals):
label += elem + ","
else:
orb_label = [orb[1:] for orb in orbs]
label += f"{elem}{str(orb_label).replace('[' , '').replace(']' , '').replace(', ', '-')},"
label += f"{elem}{str(orb_label).replace('[', '').replace(']', '').replace(', ', '-')},"
return label[:-1]

if sum_atoms is None and sum_morbs is None:
Expand Down Expand Up @@ -3064,7 +3064,7 @@ def plot_seebeck_temp(self, doping="all", output="average"):
for temp in tlist:
sbk_temp.append(sbk[dt][temp][d])
if output == "average":
ax.plot(tlist, sbk_temp, marker="s", label=str(dop) + " $cm^{-3}$")
ax.plot(tlist, sbk_temp, marker="s", label=f"{dop} $cm^{-3}$")
elif output == "eigs":
for xyz in range(3):
ax.plot(
Expand Down Expand Up @@ -3171,7 +3171,7 @@ def plot_power_factor_temp(self, doping="all", output="average", relaxation_time
for temp in tlist:
pf_temp.append(pf[dt][temp][d])
if output == "average":
ax.plot(tlist, pf_temp, marker="s", label=str(dop) + " $cm^{-3}$")
ax.plot(tlist, pf_temp, marker="s", label=f"{dop} $cm^{-3}$")
elif output == "eigs":
for xyz in range(3):
ax.plot(
Expand Down Expand Up @@ -3698,10 +3698,10 @@ def get_plot(
plot_negative = (not self.are_coops) and (not self.are_cobis)

if integrated:
cohp_label = "I" + cohp_label + " (eV)"
cohp_label = f"I{cohp_label} (eV)"

if plot_negative:
cohp_label = "-" + cohp_label
cohp_label = f"-{cohp_label}"

energy_label = "$E - E_f$ (eV)" if self.zero_at_efermi else "$E$ (eV)"

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/aims/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ def get_aims_control_parameter_str(self, key: str, value: Any, format: str) -> s
Returns:
The line to add to the control.in file
"""
return f"{key :35s}" + (format % value) + "\n"
return f"{key:35s}" + (format % value) + "\n"

def write_file(
self,
Expand Down
8 changes: 4 additions & 4 deletions tests/analysis/test_interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,21 +220,21 @@ def test_get_get_elmt_amt_in_rxt(self):
[Composition("Mn"), Composition("O2"), Composition("Li")],
[Composition("LiMnO2")],
)
test1 = np.isclose(self.irs[2]._get_elmt_amt_in_rxn(rxt1), 3)
test1 = np.isclose(self.irs[2]._get_elem_amt_in_rxn(rxt1), 3)
assert test1, "_get_get_elmt_amt_in_rxt: gpd elements amounts gets error!"

rxt2 = rxt1
rxt2.normalize_to(Composition("Li"), 0.5)
test2 = np.isclose(self.irs[2]._get_elmt_amt_in_rxn(rxt2), 1.5)
test2 = np.isclose(self.irs[2]._get_elem_amt_in_rxn(rxt2), 1.5)
assert test2, "_get_get_elmt_amt_in_rxt: gpd elements amounts gets error!"

rxt3 = Reaction([Composition("O2"), Composition("Li")], [Composition("Li2O")])
# Li is not counted
test3 = np.isclose(self.irs[2]._get_elmt_amt_in_rxn(rxt3), 1)
test3 = np.isclose(self.irs[2]._get_elem_amt_in_rxn(rxt3), 1)
assert test3, "_get_get_elmt_amt_in_rxt: gpd elements amounts gets error!"

# Li is counted
test4 = np.isclose(self.irs[6]._get_elmt_amt_in_rxn(rxt3), 3)
test4 = np.isclose(self.irs[6]._get_elem_amt_in_rxn(rxt3), 3)
assert test4, "_get_get_elmt_amt_in_rxt: pd elements amounts gets error!"

def test_convert(self):
Expand Down
2 changes: 1 addition & 1 deletion tests/core/test_periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def test_attributes(self):

for k, v in is_true.items():
for sym in k:
assert getattr(Element(sym), v), sym + " is false"
assert getattr(Element(sym), v), f"{sym=} is false"

keys = [
"mendeleev_no",
Expand Down
4 changes: 2 additions & 2 deletions tests/io/lammps/test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def test_disassemble(self):
np.testing.assert_array_equal(c_ff.nonbond_coeffs, c.force_field["Pair Coeffs"].values)
base_kws = ["Bond", "Angle", "Dihedral", "Improper"]
for kw in base_kws:
ff_kw = kw + " Coeffs"
ff_kw = f"{kw} Coeffs"
i = random.randint(0, len(c_ff.topo_coeffs[ff_kw]) - 1)
sample_coeff = c_ff.topo_coeffs[ff_kw][i]
np.testing.assert_array_equal(sample_coeff["coeffs"], c.force_field[ff_kw].iloc[i].values, ff_kw)
Expand All @@ -323,7 +323,7 @@ def test_disassemble(self):
assert topo.sites.site_properties["ff_map"] == [atom_labels[i - 1] for i in atoms["type"]]
shift = min(atoms.index)
for kw in base_kws:
ff_kw = kw + " Coeffs"
ff_kw = f"{kw} Coeffs"
ff_coeffs = c_ff.topo_coeffs[ff_kw]
topo_kw = kw + "s"
topos_df = c.topology[topo_kw]
Expand Down
2 changes: 1 addition & 1 deletion tests/io/test_res.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def test_read_spin(self):
with open(res_coc) as f:
lines = f.readlines()
# add spin to a line
lines[25] = lines[25][:-1] + " -1.4\n"
lines[25] = f"{lines[25][:-1]} -1.4\n"
contents = "".join(lines)
provider = AirssProvider.from_str(contents)

Expand Down

0 comments on commit 3214fe0

Please sign in to comment.