Skip to content

Commit 38148f0

Browse files
committed
simplify GaussianInput.get_cart_coords() (closes #2893)
add some doc strings
1 parent 017584e commit 38148f0

File tree

3 files changed

+31
-41
lines changed

3 files changed

+31
-41
lines changed

pymatgen/core/structure.py

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,8 @@ def types_of_species(self) -> tuple[Element | Species | DummySpecies]:
267267
# Cannot use set since we want a deterministic algorithm.
268268
types: list[Element | Species | DummySpecies] = []
269269
for site in self:
270-
for sp, v in site.species.items():
271-
if v != 0:
270+
for sp, amt in site.species.items():
271+
if amt != 0:
272272
types.append(sp)
273273
return tuple(sorted(set(types))) # type: ignore
274274

@@ -729,34 +729,28 @@ def __init__(
729729
fractional_coords. Defaults to None for no properties.
730730
"""
731731
if len(species) != len(coords):
732-
raise StructureError(
733-
"The list of atomic species must be of the same length as the list of fractional coordinates."
734-
)
732+
raise StructureError("atomic species and fractional coordinates must have same length")
735733

736-
if isinstance(lattice, Lattice):
737-
self._lattice = lattice
738-
else:
739-
self._lattice = Lattice(lattice)
734+
self._lattice = lattice if isinstance(lattice, Lattice) else Lattice(lattice)
740735

741736
sites = []
742-
for i, sp in enumerate(species):
737+
for idx, specie in enumerate(species):
743738
prop = None
744739
if site_properties:
745-
prop = {k: v[i] for k, v in site_properties.items()}
740+
prop = {k: v[idx] for k, v in site_properties.items()}
746741

747-
sites.append(
748-
PeriodicSite(
749-
sp,
750-
coords[i],
751-
self._lattice,
752-
to_unit_cell,
753-
coords_are_cartesian=coords_are_cartesian,
754-
properties=prop, # type: ignore
755-
)
742+
site = PeriodicSite(
743+
specie,
744+
coords[idx],
745+
self._lattice,
746+
to_unit_cell,
747+
coords_are_cartesian=coords_are_cartesian,
748+
properties=prop, # type: ignore
756749
)
750+
sites.append(site)
757751
self._sites: tuple[PeriodicSite, ...] = tuple(sites)
758752
if validate_proximity and not self.is_valid():
759-
raise StructureError(("Structure contains sites that are ", "less than 0.01 Angstrom apart!"))
753+
raise StructureError("Structure contains sites that are less than 0.01 Angstrom apart!")
760754
self._charge = charge
761755

762756
@classmethod
@@ -4520,5 +4514,5 @@ class StructureError(Exception):
45204514
"""
45214515

45224516

4523-
with open(os.path.join(os.path.dirname(__file__), "func_groups.json")) as f:
4524-
FunctionalGroups = {k: Molecule(v["species"], v["coords"]) for k, v in json.load(f).items()}
4517+
with open(os.path.join(os.path.dirname(__file__), "func_groups.json")) as file:
4518+
FunctionalGroups = {k: Molecule(v["species"], v["coords"]) for k, v in json.load(file).items()}

pymatgen/io/gaussian.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -409,33 +409,27 @@ def get_zmatrix(self):
409409
outputvar.append(f"D{i}={dih:.6f}")
410410
return "\n".join(output) + "\n\n" + "\n".join(outputvar)
411411

412-
def get_cart_coords(self):
413-
"""
414-
Return the Cartesian coordinates of the molecule
415-
"""
416-
417-
def to_s(x):
418-
return f"{x:0.6f}"
419-
412+
def get_cart_coords(self) -> str:
413+
"""Return the Cartesian coordinates of the molecule"""
420414
outs = []
421415
for site in self._mol:
422-
outs.append(" ".join([site.species_string, " ".join(map(to_s, site.coords))]))
416+
outs.append(f"{site.species_string} {' '.join(f'{x:0.6f}' for x in site.coords)}")
423417
return "\n".join(outs)
424418

425419
def __str__(self):
426420
return self.to_string()
427421

428422
def to_string(self, cart_coords=False):
429-
"""
430-
Return GaussianInput string
423+
"""Return GaussianInput string.
431424
432-
Option: when cart_coords is set to True return the Cartesian coordinates
433-
instead of the z-matrix
425+
Args:
426+
cart_coords (bool): If True, return Cartesian coordinates instead of z-matrix.
427+
Defaults to False.
434428
"""
435429

436430
def para_dict_to_string(para, joiner=" "):
437431
para_str = []
438-
# sorted is only done to make unittests work reliably
432+
# sorted is only done to make unit tests work reliably
439433
for par, val in sorted(para.items()):
440434
if val is None or val == "":
441435
para_str.append(par)
@@ -489,8 +483,8 @@ def write_file(self, filename, cart_coords=False):
489483
490484
Option: see __str__ method
491485
"""
492-
with zopen(filename, "w") as f:
493-
f.write(self.to_string(cart_coords))
486+
with zopen(filename, "w") as file:
487+
file.write(self.to_string(cart_coords))
494488

495489
def as_dict(self):
496490
"""

pymatgen/util/coord.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,13 +77,15 @@ def is_coord_subset(subset, superset, atol=1e-8) -> bool:
7777
return all(any_close)
7878

7979

80-
def coord_list_mapping(subset, superset, atol=1e-8):
80+
def coord_list_mapping(subset: ArrayLike, superset: ArrayLike, atol: float = 1e-8):
8181
"""
8282
Gives the index mapping from a subset to a superset.
8383
Subset and superset cannot contain duplicate rows
8484
8585
Args:
86-
subset, superset: List of coords
86+
subset (ArrayLike): List of coords
87+
superset (ArrayLike): List of coords
88+
atol (float): Absolute tolerance. Defaults to 1e-8.
8789
8890
Returns:
8991
list of indices such that superset[indices] = subset

0 commit comments

Comments
 (0)