diff --git a/pymatgen/analysis/bond_dissociation.py b/pymatgen/analysis/bond_dissociation.py index 3579ac884cf..96c1d853285 100644 --- a/pymatgen/analysis/bond_dissociation.py +++ b/pymatgen/analysis/bond_dissociation.py @@ -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...") diff --git a/pymatgen/analysis/gb/grain.py b/pymatgen/analysis/gb/grain.py index 25e287ba22b..16469bafd49 100644 --- a/pymatgen/analysis/gb/grain.py +++ b/pymatgen/analysis/gb/grain.py @@ -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)})", ) ) diff --git a/pymatgen/analysis/interface_reactions.py b/pymatgen/analysis/interface_reactions.py index f8ec3a6ef7a..336f7e41db5 100644 --- a/pymatgen/analysis/interface_reactions.py +++ b/pymatgen/analysis/interface_reactions.py @@ -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) @@ -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) @@ -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 @@ -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) diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index 3b5d3371173..7c00efaf3fc 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -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) diff --git a/pymatgen/analysis/pourbaix_diagram.py b/pymatgen/analysis/pourbaix_diagram.py index db5e5016083..2bc62487029 100644 --- a/pymatgen/analysis/pourbaix_diagram.py +++ b/pymatgen/analysis/pourbaix_diagram.py @@ -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=})" ) @@ -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", @@ -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". @@ -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[ diff --git a/pymatgen/apps/borg/queen.py b/pymatgen/apps/borg/queen.py index cfad47a3b7a..175f6217e14 100644 --- a/pymatgen/apps/borg/queen.py +++ b/pymatgen/apps/borg/queen.py @@ -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)) @@ -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") diff --git a/pymatgen/cli/feff_plot_cross_section.py b/pymatgen/cli/feff_plot_cross_section.py index 3e1c1643871..a9a59f3a650 100755 --- a/pymatgen/cli/feff_plot_cross_section.py +++ b/pymatgen/cli/feff_plot_cross_section.py @@ -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") diff --git a/pymatgen/command_line/critic2_caller.py b/pymatgen/command_line/critic2_caller.py index ce8c806c5b2..561e7fc6e05 100644 --- a/pymatgen/command_line/critic2_caller.py +++ b/pymatgen/command_line/critic2_caller.py @@ -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 diff --git a/pymatgen/command_line/gulp_caller.py b/pymatgen/command_line/gulp_caller.py index f4d66e53b94..17fb7f6cdd6 100644 --- a/pymatgen/command_line/gulp_caller.py +++ b/pymatgen/command_line/gulp_caller.py @@ -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" @@ -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: diff --git a/pymatgen/core/lattice.py b/pymatgen/core/lattice.py index 2892c72ef0f..5246a4acb0a 100644 --- a/pymatgen/core/lattice.py +++ b/pymatgen/core/lattice.py @@ -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) diff --git a/pymatgen/electronic_structure/boltztrap2.py b/pymatgen/electronic_structure/boltztrap2.py index f52f33c4e83..bff7072d2ed 100644 --- a/pymatgen/electronic_structure/boltztrap2.py +++ b/pymatgen/electronic_structure/boltztrap2.py @@ -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): diff --git a/pymatgen/electronic_structure/plotter.py b/pymatgen/electronic_structure/plotter.py index cb4f029dbcd..2c8f165fbc7 100644 --- a/pymatgen/electronic_structure/plotter.py +++ b/pymatgen/electronic_structure/plotter.py @@ -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: @@ -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( @@ -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( @@ -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)" diff --git a/pymatgen/io/aims/inputs.py b/pymatgen/io/aims/inputs.py index e7057c09e55..a5f7ffb6b0a 100644 --- a/pymatgen/io/aims/inputs.py +++ b/pymatgen/io/aims/inputs.py @@ -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, diff --git a/tests/analysis/test_interface_reactions.py b/tests/analysis/test_interface_reactions.py index 823c2c141c2..73566f7691e 100644 --- a/tests/analysis/test_interface_reactions.py +++ b/tests/analysis/test_interface_reactions.py @@ -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): diff --git a/tests/core/test_periodic_table.py b/tests/core/test_periodic_table.py index 5c675819aa9..24ff4f08f99 100644 --- a/tests/core/test_periodic_table.py +++ b/tests/core/test_periodic_table.py @@ -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", diff --git a/tests/io/lammps/test_data.py b/tests/io/lammps/test_data.py index d056a686137..3de1cec37cf 100644 --- a/tests/io/lammps/test_data.py +++ b/tests/io/lammps/test_data.py @@ -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) @@ -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] diff --git a/tests/io/test_res.py b/tests/io/test_res.py index fa987b475be..171fa19ecb9 100644 --- a/tests/io/test_res.py +++ b/tests/io/test_res.py @@ -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)