Skip to content

Commit 913ad94

Browse files
authored
Unreadable string concat ops to f-string (#3162)
* unreadable string concat ops to f-string * more of the same * fix bad return type in IMolecule.from_dict() add literal anno for Molecule.from_str(fmt)
1 parent f4e6057 commit 913ad94

File tree

13 files changed

+112
-179
lines changed

13 files changed

+112
-179
lines changed

pymatgen/analysis/bond_dissociation.py

Lines changed: 19 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -150,20 +150,13 @@ def fragment_and_process(self, bonds):
150150
# If we still have no good entries, something must have gone wrong with the calculations:
151151
if len(good_entries) == 0:
152152
bb = BabelMolAdaptor.from_molecule_graph(RO_frag)
153-
pbmol = bb.pybel_mol
154-
smiles = pbmol.write("smi").split()[0]
153+
pb_mol = bb.pybel_mol
154+
smiles = pb_mol.write("smi").split()[0]
155155
specie = nx.get_node_attributes(self.mol_graph.graph, "specie")
156156
print(
157-
"Missing ring opening fragment resulting from the breakage of "
158-
+ specie[bonds[0][0]]
159-
+ " "
160-
+ specie[bonds[0][1]]
161-
+ " bond "
162-
+ str(bonds[0][0])
163-
+ " "
164-
+ str(bonds[0][1])
165-
+ " which would yield a molecule with this SMILES string: "
166-
+ smiles
157+
f"Missing ring opening fragment resulting from the breakage of {specie[bonds[0][0]]} "
158+
f"{specie[bonds[0][1]]} bond {bonds[0][0]} {bonds[0][1]} which would yield a "
159+
f"molecule with this SMILES string: {smiles}"
167160
)
168161
elif len(good_entries) == 1:
169162
# If we have only one good entry, format it and add it to the list that will eventually return:
@@ -207,18 +200,18 @@ def fragment_and_process(self, bonds):
207200
# If we're missing some of either, tell the user:
208201
if len(frag1_charges_found) < len(self.expected_charges):
209202
bb = BabelMolAdaptor(frags[0].molecule)
210-
pbmol = bb.pybel_mol
211-
smiles = pbmol.write("smi").split()[0]
203+
pb_mol = bb.pybel_mol
204+
smiles = pb_mol.write("smi").split()[0]
212205
for charge in self.expected_charges:
213206
if charge not in frag1_charges_found:
214-
print("Missing charge " + str(charge) + " for fragment " + smiles)
207+
print(f"Missing charge {charge} for fragment {smiles}")
215208
if len(frag2_charges_found) < len(self.expected_charges):
216209
bb = BabelMolAdaptor(frags[1].molecule)
217-
pbmol = bb.pybel_mol
218-
smiles = pbmol.write("smi").split()[0]
210+
pb_mol = bb.pybel_mol
211+
smiles = pb_mol.write("smi").split()[0]
219212
for charge in self.expected_charges:
220213
if charge not in frag2_charges_found:
221-
print("Missing charge " + str(charge) + " for fragment " + smiles)
214+
print(f"Missing charge {charge} for fragment {smiles}")
222215
# Now we attempt to pair fragments with the right total charge, starting with only fragments with no
223216
# structural change:
224217
for frag1 in frag1_entries[0]: # 0 -> no structural change
@@ -282,21 +275,16 @@ def filter_fragment_entries(self, fragment_entries):
282275
for entry in fragment_entries:
283276
# Check and make sure that PCM dielectric is consistent with principle:
284277
if "pcm_dielectric" in self.molecule_entry:
278+
err_msg = (
279+
f"Principle molecule has a PCM dielectric of {self.molecule_entry['pcm_dielectric']}"
280+
" but a fragment entry has [[placeholder]] PCM dielectric! Please only pass fragment entries"
281+
" with PCM details consistent with the principle entry. Exiting..."
282+
)
285283
if "pcm_dielectric" not in entry:
286-
raise RuntimeError(
287-
"Principle molecule has a PCM dielectric of "
288-
+ str(self.molecule_entry["pcm_dielectric"])
289-
+ " but a fragment entry has no PCM dielectric! Please only pass fragment entries"
290-
" with PCM details consistent with the principle entry. Exiting..."
291-
)
284+
raise RuntimeError(err_msg.replace("[[placeholder]]", "no"))
292285
if entry["pcm_dielectric"] != self.molecule_entry["pcm_dielectric"]:
293-
raise RuntimeError(
294-
"Principle molecule has a PCM dielectric of "
295-
+ str(self.molecule_entry["pcm_dielectric"])
296-
+ " but a fragment entry has a different PCM dielectric! Please only pass"
297-
" fragment entries with PCM details consistent with the principle entry."
298-
" Exiting..."
299-
)
286+
raise RuntimeError(err_msg.replace("[[placeholder]]", "a different"))
287+
300288
# Build initial and final molgraphs:
301289
entry["initial_molgraph"] = MoleculeGraph.with_local_env_strategy(
302290
Molecule.from_dict(entry["initial_molecule"]), OpenBabelNN()

pymatgen/analysis/ewald.py

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -411,22 +411,13 @@ def eta(self):
411411
return self._eta
412412

413413
def __str__(self):
414-
if self._compute_forces:
415-
output = [
416-
"Real = " + str(self.real_space_energy),
417-
"Reciprocal = " + str(self.reciprocal_space_energy),
418-
"Point = " + str(self.point_energy),
419-
"Total = " + str(self.total_energy),
420-
"Forces:\n" + str(self.forces),
421-
]
422-
else:
423-
output = [
424-
"Real = " + str(self.real_space_energy),
425-
"Reciprocal = " + str(self.reciprocal_space_energy),
426-
"Point = " + str(self.point_energy),
427-
"Total = " + str(self.total_energy),
428-
"Forces were not computed",
429-
]
414+
output = [
415+
f"Real = {self.real_space_energy}",
416+
f"Reciprocal = {self.reciprocal_space_energy}",
417+
f"Point = {self.point_energy}",
418+
f"Total = {self.total_energy}",
419+
f"Forces:\n{self.forces}" if self._compute_forces else "Forces were not computed",
420+
]
430421
return "\n".join(output)
431422

432423
def as_dict(self, verbosity: int = 0) -> dict:

pymatgen/analysis/fragmenter.py

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,9 @@ def __init__(
105105
for level in range(depth):
106106
# If on the first level, perform one level of fragmentation on the principle molecule graph:
107107
if level == 0:
108+
alph_formula = self.mol_graph.molecule.composition.alphabetical_formula
108109
self.fragments_by_level["0"] = self._fragment_one_level(
109-
{
110-
str(self.mol_graph.molecule.composition.alphabetical_formula)
111-
+ " E"
112-
+ str(len(self.mol_graph.graph.edges())): [self.mol_graph]
113-
}
110+
{f"{alph_formula} E{len(self.mol_graph.graph.edges())}": [self.mol_graph]}
114111
)
115112
else:
116113
num_frags_prev_level = 0
@@ -183,11 +180,8 @@ def _fragment_one_level(self, old_frag_dict):
183180
if self.open_rings:
184181
fragments = [open_ring(old_frag, bond, self.opt_steps)]
185182
for fragment in fragments:
186-
new_frag_key = (
187-
str(fragment.molecule.composition.alphabetical_formula)
188-
+ " E"
189-
+ str(len(fragment.graph.edges()))
190-
)
183+
alph_formula = fragment.molecule.composition.alphabetical_formula
184+
new_frag_key = f"{alph_formula} E{len(fragment.graph.edges())}"
191185
proceed = True
192186
if (
193187
self.assume_previous_thoroughness
@@ -224,11 +218,8 @@ def _open_all_rings(self):
224218
we find. We also temporarily add the principle molecule graph to self.unique_fragments
225219
so that its rings are opened as well.
226220
"""
227-
mol_key = (
228-
str(self.mol_graph.molecule.composition.alphabetical_formula)
229-
+ " E"
230-
+ str(len(self.mol_graph.graph.edges()))
231-
)
221+
alph_formula = self.mol_graph.molecule.composition.alphabetical_formula
222+
mol_key = f"{alph_formula} E{len(self.mol_graph.graph.edges())}"
232223
self.all_unique_frag_dict[mol_key] = [self.mol_graph]
233224
new_frag_keys = {"0": []}
234225
new_frag_key_dict = {}
@@ -238,11 +229,8 @@ def _open_all_rings(self):
238229
if ring_edges != []:
239230
for bond in ring_edges[0]:
240231
new_fragment = open_ring(fragment, [bond], self.opt_steps)
241-
frag_key = (
242-
str(new_fragment.molecule.composition.alphabetical_formula)
243-
+ " E"
244-
+ str(len(new_fragment.graph.edges()))
245-
)
232+
alph_formula = new_fragment.molecule.composition.alphabetical_formula
233+
frag_key = f"{alph_formula} E{len(new_fragment.graph.edges())}"
246234
if frag_key not in self.all_unique_frag_dict:
247235
if frag_key not in new_frag_keys["0"]:
248236
new_frag_keys["0"].append(copy.deepcopy(frag_key))
@@ -276,11 +264,8 @@ def _open_all_rings(self):
276264
if ring_edges != []:
277265
for bond in ring_edges[0]:
278266
new_fragment = open_ring(fragment, [bond], self.opt_steps)
279-
frag_key = (
280-
str(new_fragment.molecule.composition.alphabetical_formula)
281-
+ " E"
282-
+ str(len(new_fragment.graph.edges()))
283-
)
267+
alph_formula = new_fragment.molecule.composition.alphabetical_formula
268+
frag_key = f"{alph_formula} E{len(new_fragment.graph.edges())}"
284269
if frag_key not in self.all_unique_frag_dict:
285270
if frag_key not in new_frag_keys[str(idx)]:
286271
new_frag_keys[str(idx)].append(copy.deepcopy(frag_key))

pymatgen/analysis/graphs.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2091,13 +2091,13 @@ def build_unique_fragments(self):
20912091
frag_dict = {}
20922092
for ii in range(1, len(self.molecule)):
20932093
for combination in combinations(graph.nodes, ii):
2094-
mycomp = []
2094+
comp = []
20952095
for idx in combination:
2096-
mycomp.append(str(self.molecule[idx].specie))
2097-
mycomp = "".join(sorted(mycomp))
2096+
comp.append(str(self.molecule[idx].specie))
2097+
comp = "".join(sorted(comp))
20982098
subgraph = nx.subgraph(graph, combination)
20992099
if nx.is_connected(subgraph):
2100-
mykey = mycomp + str(len(subgraph.edges()))
2100+
mykey = comp + str(len(subgraph.edges()))
21012101
if mykey not in frag_dict:
21022102
frag_dict[mykey] = [copy.deepcopy(subgraph)]
21032103
else:
@@ -2142,11 +2142,8 @@ def build_unique_fragments(self):
21422142
)
21432143
)
21442144

2145-
frag_key = (
2146-
str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula)
2147-
+ " E"
2148-
+ str(len(unique_mol_graph_list[0].graph.edges()))
2149-
)
2145+
alph_formula = unique_mol_graph_list[0].molecule.composition.alphabetical_formula
2146+
frag_key = f"{alph_formula} E{len(unique_mol_graph_list[0].graph.edges())}"
21502147
unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list)
21512148
return unique_mol_graph_dict
21522149

pymatgen/core/structure.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1386,7 +1386,7 @@ def get_sites_in_sphere(
13861386
is included in the returned data
13871387
13881388
Returns:
1389-
[:class:`pymatgen.core.structure.PeriodicNeighbor`]
1389+
PeriodicNeighbor
13901390
"""
13911391
site_fcoords = np.mod(self.frac_coords, 1)
13921392
neighbors: list[PeriodicNeighbor] = []
@@ -1423,7 +1423,7 @@ def get_neighbors(
14231423
is always included in the returned data.
14241424
14251425
Returns:
1426-
[:class:`pymatgen.core.structure.PeriodicNeighbor`]
1426+
PeriodicNeighbor
14271427
"""
14281428
return self.get_all_neighbors(r, include_index=include_index, include_image=include_image, sites=[site])[0]
14291429

@@ -1442,7 +1442,7 @@ def get_neighbors_old(self, site, r, include_index=False, include_image=False):
14421442
is included in the returned data
14431443
14441444
Returns:
1445-
[:class:`pymatgen.core.structure.PeriodicNeighbor`]
1445+
PeriodicNeighbor
14461446
"""
14471447
nn = self.get_sites_in_sphere(site.coords, r, include_index=include_index, include_image=include_image)
14481448
return [d for d in nn if site != d[0]]
@@ -1903,7 +1903,7 @@ def get_all_neighbors_old(self, r, include_index=False, include_image=False, inc
19031903
data. Defaults to True.
19041904
19051905
Returns:
1906-
[:class:`pymatgen.core.structure.PeriodicNeighbor`]
1906+
PeriodicNeighbor
19071907
"""
19081908
# Use same algorithm as get_sites_in_sphere to determine supercell but
19091909
# loop over all atoms in crystal
@@ -3160,7 +3160,7 @@ def as_dict(self):
31603160
return d
31613161

31623162
@classmethod
3163-
def from_dict(cls, d) -> dict:
3163+
def from_dict(cls, d) -> IMolecule | Molecule:
31643164
"""
31653165
Reconstitute a Molecule object from a dict representation created using
31663166
as_dict().
@@ -3198,7 +3198,7 @@ def get_sites_in_sphere(self, pt: ArrayLike, r: float) -> list[Neighbor]:
31983198
r (float): Radius of sphere.
31993199
32003200
Returns:
3201-
[:class:`pymatgen.core.structure.Neighbor`]
3201+
Neighbor
32023202
"""
32033203
neighbors = []
32043204
for i, site in enumerate(self._sites):
@@ -3217,7 +3217,7 @@ def get_neighbors(self, site: Site, r: float) -> list[Neighbor]:
32173217
r (float): Radius of sphere.
32183218
32193219
Returns:
3220-
[:class:`pymatgen.core.structure.Neighbor`]
3220+
Neighbor
32213221
"""
32223222
nns = self.get_sites_in_sphere(site.coords, r)
32233223
return [nn for nn in nns if nn != site]
@@ -3233,7 +3233,7 @@ def get_neighbors_in_shell(self, origin: ArrayLike, r: float, dr: float) -> list
32333233
dr (float): Width of shell.
32343234
32353235
Returns:
3236-
[:class:`pymatgen.core.structure.Neighbor`]
3236+
Neighbor
32373237
"""
32383238
outer = self.get_sites_in_sphere(origin, r + dr)
32393239
inner = r - dr
@@ -3429,7 +3429,9 @@ def to(self, filename: str = "", fmt: str = "") -> str | None:
34293429
return str(writer)
34303430

34313431
@classmethod
3432-
def from_str(cls, input_string: str, fmt: str):
3432+
def from_str(
3433+
cls, input_string: str, fmt: Literal["xyz", "gjf", "g03", "g09", "com", "inp", "json", "yaml"]
3434+
) -> IMolecule | Molecule:
34333435
"""
34343436
Reads the molecule from a string.
34353437
@@ -3448,21 +3450,21 @@ def from_str(cls, input_string: str, fmt: str):
34483450
from pymatgen.io.xyz import XYZ
34493451

34503452
if fmt.lower() == "xyz":
3451-
m = XYZ.from_str(input_string).molecule
3453+
mol = XYZ.from_str(input_string).molecule
34523454
elif fmt in ["gjf", "g03", "g09", "com", "inp"]:
3453-
m = GaussianInput.from_str(input_string).molecule
3455+
mol = GaussianInput.from_str(input_string).molecule
34543456
elif fmt == "json":
3455-
d = json.loads(input_string)
3456-
return cls.from_dict(d)
3457+
dct = json.loads(input_string)
3458+
return cls.from_dict(dct)
34573459
elif fmt == "yaml":
34583460
yaml = YAML()
3459-
d = yaml.load(input_string)
3460-
return cls.from_dict(d)
3461+
dct = yaml.load(input_string)
3462+
return cls.from_dict(dct)
34613463
else:
34623464
from pymatgen.io.babel import BabelMolAdaptor
34633465

3464-
m = BabelMolAdaptor.from_str(input_string, file_format=fmt).pymatgen_mol
3465-
return cls.from_sites(m)
3466+
mol = BabelMolAdaptor.from_str(input_string, file_format=fmt).pymatgen_mol
3467+
return cls.from_sites(mol)
34663468

34673469
@classmethod
34683470
def from_file(cls, filename):

pymatgen/electronic_structure/boltztrap.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -334,9 +334,9 @@ def write_struct(self, output_file):
334334
ops = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]
335335
f.write(f"{len(ops)}\n")
336336

337-
for c in ops:
338-
for row in c:
339-
f.write(f"{' '.join(str(i) for i in row)}\n")
337+
for op in ops:
338+
for row in op:
339+
f.write(f"{' '.join(map(str, row))}\n")
340340

341341
def write_def(self, output_file):
342342
"""
@@ -675,12 +675,8 @@ def run(
675675
logging.info(f"Could not converge with max lpfac; Decrease egrid to {self.energy_grid}")
676676

677677
if not converged:
678-
raise BoltztrapError(
679-
"Doping convergence not reached with lpfac="
680-
+ str(self.lpfac)
681-
+ ", energy_grid="
682-
+ str(self.energy_grid)
683-
)
678+
lpfac, energy_grid = self.lpfac, self.energy_grid
679+
raise BoltztrapError(f"Doping convergence not reached with {lpfac=}, {energy_grid=}")
684680

685681
return path_dir
686682

pymatgen/electronic_structure/plotter.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4012,20 +4012,12 @@ def plot_fermi_surface(
40124012

40134013
if energy_levels is None:
40144014
energy_levels = [en_min + 0.01] if cbm else [en_max - 0.01]
4015-
print("Energy level set to: " + str(energy_levels[0]) + " eV")
4015+
print(f"Energy level set to: {energy_levels[0]} eV")
40164016

40174017
else:
40184018
for e in energy_levels:
40194019
if e > en_max or e < en_min:
4020-
raise BoltztrapError(
4021-
"energy level "
4022-
+ str(e)
4023-
+ " not in the range of possible energies: ["
4024-
+ str(en_min)
4025-
+ ", "
4026-
+ str(en_max)
4027-
+ "]"
4028-
)
4020+
raise BoltztrapError(f"energy level {e} not in the range of possible energies: [{en_min}, {en_max}]")
40294021

40304022
n_surfaces = len(energy_levels)
40314023
if colors is None:

0 commit comments

Comments
 (0)