Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up core.surface comments and docstrings #3691

Merged
merged 93 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
93 commits
Select commit Hold shift + click to select a range
d473fdf
track test files
DanielYang59 Jan 29, 2024
7b0941b
clean up test code
DanielYang59 Jan 29, 2024
95f6793
Merge branch 'materialsproject:master' into fix-overlap
DanielYang59 Jan 29, 2024
a0feb43
Merge branch 'materialsproject:master' into fix-overlap
DanielYang59 Feb 8, 2024
dc63b6f
Merge branch 'materialsproject:master' into fix-overlap
DanielYang59 Feb 8, 2024
bddaa69
Merge branch 'materialsproject:master' into fix-overlap
DanielYang59 Feb 9, 2024
cd4ca26
Merge branch 'master' into fix-overlap
DanielYang59 Mar 16, 2024
de47641
Merge branch 'materialsproject:master' into fix-overlap
DanielYang59 Mar 16, 2024
a549f70
some `sourcery` fixes
DanielYang59 Mar 16, 2024
50954ee
Merge branch 'materialsproject:master' into fix-overlap
DanielYang59 Mar 17, 2024
7bd1bed
remove debug files
DanielYang59 Mar 17, 2024
003f77a
Merge branch 'fix-overlap' of github.com:DanielYang59/pymatgen into f…
DanielYang59 Mar 17, 2024
ede3fd6
legacy fix for #3681
DanielYang59 Mar 17, 2024
0f95981
`sourcery` fixes (no functional change)
DanielYang59 Mar 17, 2024
26f4d46
(WIP) add type annotations for Slab
DanielYang59 Mar 17, 2024
0a65cb5
WIP-add more type annotations
DanielYang59 Mar 17, 2024
900c251
fix hkl_transformation types plus some mypy errors
janosh Mar 17, 2024
2d81220
Merge branch 'master' into fix-overlap
DanielYang59 Mar 17, 2024
75b3497
remove tolist() and replace import Self
DanielYang59 Mar 18, 2024
18bc3f3
revert renaming get_d
DanielYang59 Mar 18, 2024
c672f5a
fix private func naming
DanielYang59 Mar 18, 2024
91d7c84
fix _is_already_analyzed
DanielYang59 Mar 18, 2024
ec315c5
tweak docstring
DanielYang59 Mar 18, 2024
46cebcb
adjust method order in Slab class
DanielYang59 Mar 20, 2024
ac2ae07
docstring and format tweaks
DanielYang59 Mar 20, 2024
216cf51
docstring tweaks
DanielYang59 Mar 20, 2024
0d6b2b1
Merge branch 'master' into fix-overlap
DanielYang59 Mar 20, 2024
de69331
docstring tweaks
DanielYang59 Mar 21, 2024
6d719df
Merge branch 'fix-overlap' of github.com:DanielYang59/pymatgen into f…
DanielYang59 Mar 21, 2024
4f75a94
fix arg name specie
DanielYang59 Mar 21, 2024
2343e60
use species over specie
DanielYang59 Mar 21, 2024
535300f
clean up symmetrically_remove_atoms
DanielYang59 Mar 21, 2024
79356b7
ignore override mypy error in Slab
DanielYang59 Mar 21, 2024
408d5f1
Merge branch 'master' into fix-overlap
DanielYang59 Mar 22, 2024
44acbed
Merge branch master into fix-overlap
DanielYang59 Mar 29, 2024
54c0ff8
Merge branch 'master' into fix-overlap
DanielYang59 Mar 29, 2024
8827acc
fix merge conflicts
DanielYang59 Mar 29, 2024
4e4b821
Merge branch 'master' into fix-overlap
DanielYang59 Mar 29, 2024
2f50552
pre-commit auto-fixes
pre-commit-ci[bot] Mar 29, 2024
c749b67
Merge branch 'master' into fix-overlap
DanielYang59 Mar 29, 2024
5795087
Merge branch 'master' into fix-overlap
DanielYang59 Mar 29, 2024
662d717
Merge branch 'master' into fix-overlap
DanielYang59 Apr 1, 2024
417a91b
Merge remote-tracking branch 'upstream/master' into fix-overlap
DanielYang59 Apr 3, 2024
b79635c
make docstring more concise and fix mypy error
DanielYang59 Apr 3, 2024
672252a
organise __init__
DanielYang59 Apr 5, 2024
b5d9634
pre-commit auto-fixes
pre-commit-ci[bot] Apr 5, 2024
d3da8e2
NOTE: rename `get_slab` to `_get_slab`
DanielYang59 Apr 5, 2024
feac187
Merge branch 'fix-overlap' of github.com:DanielYang59/pymatgen into f…
DanielYang59 Apr 5, 2024
ae00dac
pre-commit auto-fixes
pre-commit-ci[bot] Apr 5, 2024
bbefcfc
Merge branch 'master' into fix-overlap
DanielYang59 Apr 5, 2024
b1b2944
revert renaming of get_slab to _get_slab
DanielYang59 Apr 5, 2024
bf6241c
Merge branch 'master' into fix-overlap
DanielYang59 Apr 5, 2024
435a73c
docstring tweak
DanielYang59 Apr 5, 2024
cc16ee8
further clean up and fix test
DanielYang59 Apr 5, 2024
4ce22fa
Merge branch 'master' into fix-overlap
DanielYang59 Apr 5, 2024
4afd422
ruff fix
DanielYang59 Apr 5, 2024
836aa57
Merge branch 'fix-overlap' of github.com:DanielYang59/pymatgen into f…
DanielYang59 Apr 5, 2024
ca63c1c
fix unit test for Slab.as_dict
DanielYang59 Apr 5, 2024
af15bd4
add list to np.ndarray convert in slab.from_dict
DanielYang59 Apr 5, 2024
4841bcf
move private methods to where its used
DanielYang59 Apr 5, 2024
fe7c3ee
finish tweaking comments in get_slab method
DanielYang59 Apr 5, 2024
7751ba6
relocate method to where its used
DanielYang59 Apr 5, 2024
5586f89
some mypy fixes
DanielYang59 Apr 5, 2024
62e1453
make comment and docstring more concise
DanielYang59 Apr 6, 2024
0401c8a
add comments for calculate_possible_shifts
DanielYang59 Apr 6, 2024
0ab4cca
add TODO and DEBUG tags
DanielYang59 Apr 6, 2024
5c13636
remove DEBUG tags
DanielYang59 Apr 6, 2024
d446f34
add TODO tag and docstring for get_z_ranges
DanielYang59 Apr 6, 2024
c766447
merge branch master
DanielYang59 Apr 7, 2024
8a52771
add comments for get_slabs method
DanielYang59 Apr 7, 2024
2dfa6b8
clarify second matching
DanielYang59 Apr 7, 2024
acb93ef
mypy fixes
DanielYang59 Apr 7, 2024
e3e29bb
rename a var
DanielYang59 Apr 7, 2024
e4503b0
clean up `move_to_other_side` method
DanielYang59 Apr 8, 2024
0df1ecf
finish cleaning up `repair_broken_bonds`
DanielYang59 Apr 8, 2024
ddb95ca
revise docstring
DanielYang59 Apr 8, 2024
25090fb
clarify comments for `nonstoichiometric_symmetrized_slab`
DanielYang59 Apr 8, 2024
3f5b304
replace `point` with `site`
DanielYang59 Apr 9, 2024
de19180
clean up `get_d`
DanielYang59 Apr 9, 2024
d3b5118
docstring tweaks
DanielYang59 Apr 9, 2024
bf378e5
clean up init for ReconstructionGenerator
DanielYang59 Apr 9, 2024
3954174
Merge branch 'master' into fix-overlap
DanielYang59 Apr 9, 2024
3a095c1
finish cleaning `ReconstructionGenerator`
DanielYang59 Apr 9, 2024
22fd6ab
more comment tweaks
DanielYang59 Apr 9, 2024
0d5d786
tweak module docstring
DanielYang59 Apr 9, 2024
f491994
rename private `is_already_analyzed` to `is_in_miller_family`
DanielYang59 Apr 10, 2024
4987de2
put `generate_all_slabs` closer to `SlabGenerator`
DanielYang59 Apr 10, 2024
c4b27ed
move `get_slab_regions` and `center_slab` closer to `Slab`
DanielYang59 Apr 10, 2024
45a3da9
finish cleaning up `surface`
DanielYang59 Apr 10, 2024
76991f8
add another tag
DanielYang59 Apr 10, 2024
1b5f795
fix typos
janosh Apr 10, 2024
8ea6396
refactor ReconstructionGenerator.get_unreconstructed_slabs
janosh Apr 10, 2024
1b80a2b
CONSTANT_CASE module-scoped reconstructions_archive
janosh Apr 10, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 21 additions & 23 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,8 +578,7 @@ def add_oxidation_state_by_element(self, oxidation_states: dict[str, float]) ->
Returns:
SiteCollection: self with oxidation states.
"""
missing = {el.symbol for el in self.composition} - {*oxidation_states}
if missing:
if missing := {el.symbol for el in self.composition} - {*oxidation_states}:
raise ValueError(f"Oxidation states not specified for all elements, {missing=}")
for site in self:
new_sp = {}
Expand Down Expand Up @@ -792,7 +791,7 @@ def _relax(
# UIP=universal interatomic potential
run_uip = isinstance(calculator, str) and calculator.lower() in ("m3gnet", "chgnet")

calc_params = dict(stress_weight=stress_weight) if not is_molecule else {}
calc_params = {} if is_molecule else dict(stress_weight=stress_weight)
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
calculator = self._prep_calculator(calculator, **calc_params)

# check str is valid optimizer key
Expand Down Expand Up @@ -1031,7 +1030,7 @@ def from_sites(
Returns:
(Structure) Note that missing properties are set as None.
"""
if len(sites) < 1:
if not sites:
raise ValueError(f"You need at least 1 site to construct a {cls.__name__}")
prop_keys: list[str] = []
props = {}
Expand Down Expand Up @@ -1133,9 +1132,7 @@ def from_spacegroup(
if len(species) != len(coords):
raise ValueError(f"Supplied species and coords lengths ({len(species)} vs {len(coords)}) are different!")

frac_coords = (
np.array(coords, dtype=np.float64) if not coords_are_cartesian else latt.get_fractional_coords(coords)
)
frac_coords = latt.get_fractional_coords(coords) if coords_are_cartesian else np.array(coords, dtype=np.float64)

props = {} if site_properties is None else site_properties

Expand Down Expand Up @@ -1236,7 +1233,7 @@ def from_magnetic_spacegroup(
if len(var) != len(species):
raise ValueError(f"Length mismatch: len({name})={len(var)} != {len(species)=}")

frac_coords = coords if not coords_are_cartesian else latt.get_fractional_coords(coords)
frac_coords = latt.get_fractional_coords(coords) if coords_are_cartesian else coords

all_sp: list[str | Element | Species | DummySpecies | Composition] = []
all_coords: list[list[float]] = []
Expand Down Expand Up @@ -2237,7 +2234,7 @@ def interpolate(
if not (interpolate_lattices or self.lattice == end_structure.lattice):
raise ValueError("Structures with different lattices!")

images = np.arange(nimages + 1) / nimages if not isinstance(nimages, collections.abc.Iterable) else nimages
images = nimages if isinstance(nimages, collections.abc.Iterable) else np.arange(nimages + 1) / nimages

# Check that both structures have the same species
for idx, site in enumerate(self):
Expand Down Expand Up @@ -2638,7 +2635,7 @@ def as_dict(self, verbosity=1, fmt=None, **kwargs) -> dict[str, Any]:
JSON-serializable dict representation.
"""
if fmt == "abivars":
"""Returns a dictionary with the ABINIT variables."""
# Returns a dictionary with the ABINIT variables
from pymatgen.io.abinit.abiobjects import structure_to_abivars

return structure_to_abivars(self, **kwargs)
Expand Down Expand Up @@ -3502,7 +3499,7 @@ def get_boxed_structure(
z_max, z_min = max(new_coords[:, 2]), min(new_coords[:, 2])
if x_max > a or x_min < 0 or y_max > b or y_min < 0 or z_max > c or z_min < 0:
raise ValueError("Molecule crosses boundary of box")
if len(all_coords) == 0:
if not all_coords:
break
distances = lattice.get_all_distances(
lattice.get_fractional_coords(new_coords),
Expand Down Expand Up @@ -3587,15 +3584,15 @@ def to(self, filename: str = "", fmt: str = "") -> str | None:
writer: Any
if fmt == "xyz" or fnmatch(filename.lower(), "*.xyz*"):
writer = XYZ(self)
elif any(fmt == ext or fnmatch(filename.lower(), f"*.{ext}*") for ext in ["gjf", "g03", "g09", "com", "inp"]):
elif any(fmt == ext or fnmatch(filename.lower(), f"*.{ext}*") for ext in ("gjf", "g03", "g09", "com", "inp")):
writer = GaussianInput(self)
elif fmt == "json" or fnmatch(filename, "*.json*") or fnmatch(filename, "*.mson*"):
json_str = json.dumps(self.as_dict())
if filename:
with zopen(filename, mode="wt", encoding="utf8") as file:
file.write(json_str)
return json_str
elif fmt in ("yaml", "yml") or fnmatch(filename, "*.yaml*") or fnmatch(filename, "*.yml*"):
elif fmt in {"yaml", "yml"} or fnmatch(filename, "*.yaml*") or fnmatch(filename, "*.yml*"):
yaml = YAML()
str_io = StringIO()
yaml.dump(self.as_dict(), str_io)
Expand Down Expand Up @@ -3685,8 +3682,7 @@ def from_file(cls, filename):
return cls.from_str(contents, fmt="yaml")
from pymatgen.io.babel import BabelMolAdaptor

match = re.search(r"\.(pdb|mol|mdl|sdf|sd|ml2|sy2|mol2|cml|mrv)", filename.lower())
if match:
if match := re.search(r"\.(pdb|mol|mdl|sdf|sd|ml2|sy2|mol2|cml|mrv)", filename.lower()):
new = BabelMolAdaptor.from_file(filename, match.group(1)).pymatgen_mol
new.__class__ = cls
return new
Expand Down Expand Up @@ -3994,13 +3990,14 @@ def substitute(self, index: int, func_group: IMolecule | Molecule | str, bond_or

# Pass value of functional group--either from user-defined or from
# functional.json
if not isinstance(func_group, Molecule):
if isinstance(func_group, Molecule):
fgroup = func_group

DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
else:
# Check to see whether the functional group is in database.
if func_group not in FunctionalGroups:
raise RuntimeError("Can't find functional group in list. Provide explicit coordinate instead")
fgroup = FunctionalGroups[func_group]
else:
fgroup = func_group

# If a bond length can be found, modify func_grp so that the X-group
# bond length is equal to the bond length.
Expand Down Expand Up @@ -4478,22 +4475,23 @@ def from_prototype(cls, prototype: str, species: Sequence, **kwargs) -> Structur
return Structure.from_spacegroup(
"Pm-3m", Lattice.cubic(kwargs["a"]), species, [[0, 0, 0], [0.5, 0.5, 0.5], [0.5, 0.5, 0]]
)
if prototype in ("cscl"):
if prototype == "cscl":
return Structure.from_spacegroup(
"Pm-3m", Lattice.cubic(kwargs["a"]), species, [[0, 0, 0], [0.5, 0.5, 0.5]]
)
if prototype in ("fluorite", "caf2"):
if prototype in {"fluorite", "caf2"}:
return Structure.from_spacegroup(
"Fm-3m", Lattice.cubic(kwargs["a"]), species, [[0, 0, 0], [1 / 4, 1 / 4, 1 / 4]]
)
if prototype in ("antifluorite"):
if prototype == "antifluorite":
return Structure.from_spacegroup(
"Fm-3m", Lattice.cubic(kwargs["a"]), species, [[1 / 4, 1 / 4, 1 / 4], [0, 0, 0]]
)
if prototype in ("zincblende"):
if prototype == "zincblende":
return Structure.from_spacegroup(
"F-43m", Lattice.cubic(kwargs["a"]), species, [[0, 0, 0], [1 / 4, 1 / 4, 3 / 4]]
)

except KeyError as exc:
raise ValueError(f"Required parameter {exc} not specified as a kwargs!") from exc
raise ValueError(f"Unsupported {prototype=}!")
Expand Down Expand Up @@ -4978,5 +4976,5 @@ class StructureError(Exception):
"""


with open(os.path.join(os.path.dirname(__file__), "func_groups.json")) as file:
with open(os.path.join(os.path.dirname(__file__), "func_groups.json"), encoding="utf-8") as file:
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
FunctionalGroups = {k: Molecule(v["species"], v["coords"]) for k, v in json.load(file).items()}
17 changes: 5 additions & 12 deletions pymatgen/core/surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ def __init__(
coords_are_cartesian=False,
site_properties=None,
energy=None,
properties=None,
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
) -> None:
"""Makes a Slab structure, a structure object with additional information
and methods pertaining to slabs.
Expand Down Expand Up @@ -132,8 +131,6 @@ def __init__(
have to be the same length as the atomic species and
fractional_coords. Defaults to None for no properties.
energy (float): A value for the energy.
properties (dict): dictionary containing properties associated
with the whole slab.
"""
self.oriented_unit_cell = oriented_unit_cell
self.miller_index = tuple(miller_index)
Expand Down Expand Up @@ -449,9 +446,6 @@ def add_adsorbate_atom(self, indices, specie, distance) -> Slab:
return self

def __str__(self) -> str:
def to_str(x) -> str:
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
return f"{x:0.6f}"

comp = self.composition
outs = [
f"Slab Summary ({comp.formula})",
Expand Down Expand Up @@ -501,7 +495,6 @@ def from_dict(cls, dct: dict) -> Slab: # type: ignore[override]
scale_factor=dct["scale_factor"],
site_properties=struct.site_properties,
energy=dct["energy"],
properties=dct.get("properties"),
)

def get_surface_sites(self, tag=False):
Expand Down Expand Up @@ -1246,7 +1239,7 @@ def nonstoichiometric_symmetrized_slab(self, init_slab):
# surfaces are symmetric or the number of sites removed has
# exceeded 10 percent of the original slab

c_dir = [site[2] for idx, site in enumerate(slab.frac_coords)]
c_dir = [site[2] for site in slab.frac_coords]

if top:
slab.remove_sites([c_dir.index(max(c_dir))])
Expand All @@ -1267,7 +1260,7 @@ def nonstoichiometric_symmetrized_slab(self, init_slab):


module_dir = os.path.dirname(os.path.abspath(__file__))
with open(f"{module_dir}/reconstructions_archive.json") as data_file:
with open(f"{module_dir}/reconstructions_archive.json", encoding="utf-8") as data_file:
reconstructions_archive = json.load(data_file)


Expand Down Expand Up @@ -1633,10 +1626,10 @@ def hkl_transformation(transf, miller_index):
"""
# Get a matrix of whole numbers (ints)

def lcm(a, b):
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
def _lcm(a, b):
return a * b // math.gcd(a, b)

reduced_transf = reduce(lcm, [int(1 / i) for i in itertools.chain(*transf) if i != 0]) * transf
reduced_transf = reduce(_lcm, [int(1 / i) for i in itertools.chain(*transf) if i != 0]) * transf
reduced_transf = reduced_transf.astype(int)

# perform the transformation
Expand Down Expand Up @@ -1825,7 +1818,7 @@ def get_slab_regions(slab, blength=3.5):
for site in slab:
if all(nn.index not in all_indices for nn in slab.get_neighbors(site, blength)):
upper_fcoords.append(site.frac_coords[2])
coords = copy.copy(last_fcoords) if not fcoords else copy.copy(fcoords)
coords = copy.copy(fcoords) if fcoords else copy.copy(last_fcoords)
min_top = slab[last_indices[coords.index(min(coords))]].frac_coords[2]
ranges = [[0, max(upper_fcoords)], [min_top, 1]]
else:
Expand Down
4 changes: 3 additions & 1 deletion tests/apps/borg/test_queen.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import unittest

from pytest import approx

from pymatgen.apps.borg.hive import VaspToComputedEntryDrone
from pymatgen.apps.borg.queen import BorgQueen
from pymatgen.util.testing import TEST_FILES_DIR
Expand All @@ -20,7 +22,7 @@ def test_get_data(self):
queen = BorgQueen(drone, TEST_DIR, 1)
data = queen.get_data()
assert len(data) == 1
assert data[0].energy == 0.5559329
assert data[0].energy == approx(0.5559329, 1e-4)

def test_load_data(self):
drone = VaspToComputedEntryDrone()
Expand Down
Loading