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

Docstring tweaks for io.vasp.inputs and format tweaks for some other parts #3996

Merged
merged 18 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
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
3 changes: 1 addition & 2 deletions src/pymatgen/alchemy/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,7 @@ def test(self, structure: Structure):
all_species = set(self.specie_and_min_dist)
for site in structure:
species = set(site.species)
sp_to_test = species.intersection(all_species)
if sp_to_test:
if sp_to_test := species.intersection(all_species):
max_r = max(self.specie_and_min_dist[sp] for sp in sp_to_test)
neighbors = structure.get_neighbors(site, max_r)
for sp in sp_to_test:
Expand Down
15 changes: 5 additions & 10 deletions src/pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,7 @@ def add_edge(
# there should only ever be at most one edge
# between a given (site, jimage) pair and another
# (site, jimage) pair
existing_edge_data = self.graph.get_edge_data(from_index, to_index)
if existing_edge_data:
if existing_edge_data := self.graph.get_edge_data(from_index, to_index):
for d in existing_edge_data.values():
if d["to_jimage"] == to_jimage:
if warn_duplicates:
Expand Down Expand Up @@ -1287,12 +1286,10 @@ def __rmul__(self, other):
def _edges_to_str(cls, g) -> str:
header = "from to to_image "
header_line = "---- ---- ------------"
edge_weight_name = g.graph["edge_weight_name"]
if edge_weight_name:
if g.graph["edge_weight_name"]:
print_weights = True
edge_label = g.graph["edge_weight_name"]
edge_weight_units = g.graph["edge_weight_units"]
if edge_weight_units:
if edge_weight_units := g.graph["edge_weight_units"]:
edge_label += f" ({edge_weight_units})"
header += f" {edge_label}"
header_line += f" {'-' * max([18, len(edge_label)])}"
Expand Down Expand Up @@ -2673,12 +2670,10 @@ def from_dict(cls, dct: dict) -> Self:
def _edges_to_str(cls, g):
header = "from to to_image "
header_line = "---- ---- ------------"
edge_weight_name = g.graph["edge_weight_name"]
if edge_weight_name:
if g.graph["edge_weight_name"]:
print_weights = ["weight"]
edge_label = g.graph["edge_weight_name"]
edge_weight_units = g.graph["edge_weight_units"]
if edge_weight_units:
if edge_weight_units := g.graph["edge_weight_units"]:
edge_label += f" ({edge_weight_units})"
header += f" {edge_label}"
header_line += f" {'-' * max([18, len(edge_label)])}"
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/pourbaix_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,8 +604,7 @@ def _preprocess_pourbaix_entries(self, entries, nproc=None):
else:
# Serial processing of multi-entry generation
for combo in all_combos:
multi_entry = self.process_multientry(combo, prod_comp=tot_comp)
if multi_entry:
if multi_entry := self.process_multientry(combo, prod_comp=tot_comp):
multi_entries.append(multi_entry)

return multi_entries
Expand Down
10 changes: 3 additions & 7 deletions src/pymatgen/analysis/structure_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -968,8 +968,7 @@ def get_rms_anonymous(self, struct1, struct2):
struct1, struct2 = self._process_species([struct1, struct2])
struct1, struct2, fu, s1_supercell = self._preprocess(struct1, struct2)

matches = self._anonymous_match(struct1, struct2, fu, s1_supercell, use_rms=True, break_on_match=False)
if matches:
if matches := self._anonymous_match(struct1, struct2, fu, s1_supercell, use_rms=True, break_on_match=False):
best = min(matches, key=lambda x: x[1][0])
return best[1][0], best[0]

Expand All @@ -993,9 +992,7 @@ def get_best_electronegativity_anonymous_mapping(self, struct1: Structure, struc
struct1, struct2 = self._process_species([struct1, struct2])
struct1, struct2, fu, s1_supercell = self._preprocess(struct1, struct2)

matches = self._anonymous_match(struct1, struct2, fu, s1_supercell, use_rms=True, break_on_match=True)

if matches:
if matches := self._anonymous_match(struct1, struct2, fu, s1_supercell, use_rms=True, break_on_match=True):
min_X_diff = np.inf
best = None
for match in matches:
Expand Down Expand Up @@ -1027,8 +1024,7 @@ def get_all_anonymous_mappings(self, struct1, struct2, niggli=True, include_dist
struct1, struct2 = self._process_species([struct1, struct2])
struct1, struct2, fu, s1_supercell = self._preprocess(struct1, struct2, niggli)

matches = self._anonymous_match(struct1, struct2, fu, s1_supercell, break_on_match=not include_dist)
if matches:
if matches := self._anonymous_match(struct1, struct2, fu, s1_supercell, break_on_match=not include_dist):
if include_dist:
return [(m[0], m[1][0]) for m in matches]

Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/transition_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,7 @@ def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs) -> Self:
if terminal:
for ds in terminal_dirs:
od = ds[0] if idx == 0 else ds[1]
outcar = glob(f"{od}/OUTCAR*")
if outcar:
if outcar := glob(f"{od}/OUTCAR*"):
outcar = sorted(outcar)
outcars.append(Outcar(outcar[-1]))
break
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/apps/borg/hive.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,7 @@ def from_dict(cls, dct: dict) -> Self:

def _get_transformation_history(path):
"""Check for a transformations.json* file and returns the history."""
trans_json = glob(f"{path}/transformations.json*")
if trans_json:
if trans_json := glob(f"{path}/transformations.json*"):
try:
with zopen(trans_json[0]) as file:
return json.load(file)["history"]
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/apps/borg/queen.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ def load_data(self, filename):
def order_assimilation(args):
"""Internal helper method for BorgQueen to process assimilation."""
path, drone, data, status = args
new_data = drone.assimilate(path)
if new_data:
if new_data := drone.assimilate(path):
data.append(json.dumps(new_data, cls=MontyEncoder))
status["count"] += 1
count = status["count"]
Expand Down
11 changes: 5 additions & 6 deletions src/pymatgen/command_line/critic2_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,17 +277,16 @@ def from_path(cls, path, suffix="", zpsp=None) -> Self:
chgcar = Chgcar.from_file(chgcar_path)
chgcar_ref = None

if not zpsp:
potcar_path = get_filepath(
if not zpsp and (
potcar_path := get_filepath(
"POTCAR",
"Could not find POTCAR, will not be able to calculate charge transfer.",
path,
suffix,
)

if potcar_path:
potcar = Potcar.from_file(potcar_path)
zpsp = {p.element: p.zval for p in potcar}
):
potcar = Potcar.from_file(potcar_path)
zpsp = {p.element: p.zval for p in potcar}

if not zpsp:
# try and get reference "all-electron-like" charge density if zpsp not present
Expand Down
12 changes: 4 additions & 8 deletions src/pymatgen/core/periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,10 +380,8 @@ def average_cationic_radius(self) -> FloatWithUnit:
taken over all positive oxidation states of the element for which
data is present.
"""
if "Ionic radii" in self._data:
radii = [v for k, v in self._data["Ionic radii"].items() if int(k) > 0]
if radii:
return FloatWithUnit(sum(radii) / len(radii), "ang")
if "Ionic radii" in self._data and (radii := [v for k, v in self._data["Ionic radii"].items() if int(k) > 0]):
return FloatWithUnit(sum(radii) / len(radii), "ang")
return FloatWithUnit(0.0, "ang")

@property
Expand All @@ -392,10 +390,8 @@ def average_anionic_radius(self) -> FloatWithUnit:
taken over all negative oxidation states of the element for which
data is present.
"""
if "Ionic radii" in self._data:
radii = [v for k, v in self._data["Ionic radii"].items() if int(k) < 0]
if radii:
return FloatWithUnit(sum(radii) / len(radii), "ang")
if "Ionic radii" in self._data and (radii := [v for k, v in self._data["Ionic radii"].items() if int(k) < 0]):
return FloatWithUnit(sum(radii) / len(radii), "ang")
return FloatWithUnit(0.0, "ang")

@property
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/io/abinit/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1059,8 +1059,7 @@ def __init__(self, structure: Structure | Sequence[Structure], pseudos, pseudo_d
pseudo_dir = os.path.abspath(pseudo_dir)
pseudo_paths = [os.path.join(pseudo_dir, p) for p in pseudos]

missing = [p for p in pseudo_paths if not os.path.isfile(p)]
if missing:
if missing := [p for p in pseudo_paths if not os.path.isfile(p)]:
raise self.Error(f"Cannot find the following pseudopotential files:\n{missing}")

pseudos = PseudoTable(pseudo_paths)
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/io/abinit/pseudos.py
Original file line number Diff line number Diff line change
Expand Up @@ -1540,8 +1540,7 @@ def from_dir(cls, top, exts=None, exclude_dirs="_*") -> Self | None:
for filepath in [os.path.join(top, fn) for fn in os.listdir(top)]:
if os.path.isfile(filepath):
try:
pseudo = Pseudo.from_file(filepath)
if pseudo:
if pseudo := Pseudo.from_file(filepath):
pseudos.append(pseudo)
else:
logger.info(f"Skipping file {filepath}")
Expand Down
5 changes: 2 additions & 3 deletions src/pymatgen/io/cp2k/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,13 +932,12 @@ def parse_mulliken(self):
pattern = r"\s+(\d)\s+(\w+)\s+(\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)"
footer = r".+Total charge"

d = self.read_table_pattern(
if self.read_table_pattern(
header_pattern=header,
row_pattern=pattern,
footer_pattern=footer,
last_one_only=False,
)
if d:
):
print("Found data, but not yet implemented!")

def parse_hirshfeld(self):
Expand Down
9 changes: 4 additions & 5 deletions src/pymatgen/io/feff/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,11 @@ def from_file(cls, feff_inp_file: str = "feff.inp", ldos_file: str = "ldos") ->
all_pdos.append(defaultdict(dict))
for k, v in vorb.items():
density = [ldos[pot_index][j][forb[k] + 1] for j in range(d_length)]
updos = density
downdos = None
if downdos:
all_pdos[-1][v] = {Spin.up: updos, Spin.down: downdos}
up_dos = density
if down_dos := None:
all_pdos[-1][v] = {Spin.up: up_dos, Spin.down: down_dos}
else:
all_pdos[-1][v] = {Spin.up: updos}
all_pdos[-1][v] = {Spin.up: up_dos}

pdos = all_pdos
vorb2 = {0: Orbital.s, 1: Orbital.py, 2: Orbital.dxy, 3: Orbital.f0}
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/io/optimade.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ def get_structure(resource: dict) -> Structure:
properties: dict[str, Any] = {"optimade_id": _id}

# Take any prefixed attributes and save them as properties
custom_properties = {k: v for k, v in attributes.items() if k.startswith("_")}
if custom_properties:
if custom_properties := {k: v for k, v in attributes.items() if k.startswith("_")}:
properties["optimade_attributes"] = custom_properties

return Structure(
Expand Down
12 changes: 2 additions & 10 deletions src/pymatgen/io/vasp/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,9 @@ def get_help(cls, tag: str, fmt: str = "text") -> str:
main_doc = soup.find(id="mw-content-text")
if fmt == "text":
output = main_doc.text
output = re.sub("\n{2,}", "\n\n", output)
else:
output = str(main_doc)
return re.sub("\n{2,}", "\n\n", output)

return output
return str(main_doc)

@classmethod
def get_incar_tags(cls) -> list[str]:
Expand All @@ -83,9 +81,3 @@ def get_incar_tags(cls) -> list[str]:
for child in children:
tags.append(child.text.strip())
return tags


if __name__ == "__main__":
doc = VaspDoc()
doc.print_help("ISYM")
print(doc.get_incar_tags())
Loading