From 0e12f8126e513379e69189a1fbe49ed8d2e04be9 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Tue, 31 Oct 2023 06:38:49 -0700 Subject: [PATCH] os.makedirs() use exist_ok=True --- dev_scripts/chemenv/explicit_permutations.py | 7 ++-- .../get_plane_permutations_optimized.py | 3 +- pymatgen/cli/pmg_config.py | 3 +- pymatgen/electronic_structure/boltztrap.py | 14 ++++---- pymatgen/io/abinit/inputs.py | 3 +- pymatgen/io/cp2k/sets.py | 17 ++++----- pymatgen/io/feff/sets.py | 25 ++++++------- pymatgen/io/lammps/inputs.py | 4 +-- pymatgen/io/vasp/inputs.py | 14 ++++---- pymatgen/io/vasp/sets.py | 4 +-- pymatgen/symmetry/kpath.py | 36 +++++++++---------- tests/io/feff/test_sets.py | 10 +++--- 12 files changed, 63 insertions(+), 77 deletions(-) diff --git a/dev_scripts/chemenv/explicit_permutations.py b/dev_scripts/chemenv/explicit_permutations.py index b55154914a9..3ff40e1d513 100644 --- a/dev_scripts/chemenv/explicit_permutations.py +++ b/dev_scripts/chemenv/explicit_permutations.py @@ -91,8 +91,7 @@ class Algo: if len(cg.algorithms) != 1: raise ValueError("Multiple algorithms !") cg._algorithms = [ExplicitPermutationsAlgorithm(permutations=explicit_permutations)] - newgeom_dir = "new_geometry_files" - if not os.path.exists(newgeom_dir): - os.makedirs(newgeom_dir) - with open(f"{newgeom_dir}/{cg_symbol}.json", "w") as f: + new_geom_dir = "new_geometry_files" + os.makedirs(new_geom_dir, exist_ok=True) + with open(f"{new_geom_dir}/{cg_symbol}.json", "w") as f: json.dump(cg.as_dict(), f) diff --git a/dev_scripts/chemenv/get_plane_permutations_optimized.py b/dev_scripts/chemenv/get_plane_permutations_optimized.py index b5927896e27..a41deb4a28e 100644 --- a/dev_scripts/chemenv/get_plane_permutations_optimized.py +++ b/dev_scripts/chemenv/get_plane_permutations_optimized.py @@ -431,7 +431,6 @@ def random_permutations_iterator(initial_permutation, n_permutations): ) if test == "y": new_geom_dir = "new_geometry_files" - if not os.path.exists(new_geom_dir): - os.makedirs(new_geom_dir) + os.makedirs(new_geom_dir, exist_ok=True) with open(f"{new_geom_dir}/{cg_symbol}.json", "w") as file: json.dump(cg.as_dict(), file) diff --git a/pymatgen/cli/pmg_config.py b/pymatgen/cli/pmg_config.py index 6c09c63c492..e81ba67a7da 100755 --- a/pymatgen/cli/pmg_config.py +++ b/pymatgen/cli/pmg_config.py @@ -143,8 +143,7 @@ def setup_potcars(potcar_dirs: list[str]): if len(filenames) > 0: try: base_dir = os.path.join(target_dir, basename) - if not os.path.exists(base_dir): - os.makedirs(base_dir) + os.makedirs(base_dir, exist_ok=True) fname = filenames[0] dest = os.path.join(base_dir, os.path.basename(fname)) shutil.copy(fname, dest) diff --git a/pymatgen/electronic_structure/boltztrap.py b/pymatgen/electronic_structure/boltztrap.py index 7934e005b8d..4bfe0e65d89 100644 --- a/pymatgen/electronic_structure/boltztrap.py +++ b/pymatgen/electronic_structure/boltztrap.py @@ -545,18 +545,19 @@ def run( if convergence and not write_input: raise ValueError("Convergence mode requires write_input to be true") - if self.run_type in ("BANDS", "DOS", "FERMI"): + run_type = self.run_type + if run_type in ("BANDS", "DOS", "FERMI"): convergence = False if self.lpfac > max_lpfac: max_lpfac = self.lpfac - if self.run_type == "BANDS" and self.bs.is_spin_polarized: + if run_type == "BANDS" and self.bs.is_spin_polarized: print( - f"Reminder: for run_type {self.run_type}, spin component are not separated! " + f"Reminder: for {run_type=}, spin component are not separated! " "(you have a spin polarized band structure)" ) - if self.run_type in ("FERMI", "DOS") and self.spin is None: + if run_type in ("FERMI", "DOS") and self.spin is None: if self.bs.is_spin_polarized: raise BoltztrapError("Spin parameter must be specified for spin polarized band structures!") self.spin = 1 @@ -568,9 +569,8 @@ def run( else: path_dir = os.path.abspath(os.path.join(path_dir, dir_bz_name)) - if not os.path.exists(path_dir): - os.mkdir(path_dir) - elif clear_dir: + os.mkdir(path_dir, exist_ok=True) + if clear_dir: for c in os.listdir(path_dir): os.remove(os.path.join(path_dir, c)) diff --git a/pymatgen/io/abinit/inputs.py b/pymatgen/io/abinit/inputs.py index 64e014f6805..ee836ecc91f 100644 --- a/pymatgen/io/abinit/inputs.py +++ b/pymatgen/io/abinit/inputs.py @@ -614,8 +614,7 @@ def __str__(self): def write(self, filepath="run.abi"): """Write the input file to file to filepath.""" dirname = os.path.dirname(os.path.abspath(filepath)) - if not os.path.exists(dirname): - os.makedirs(dirname) + os.makedirs(dirname, exist_ok=True) # Write the input file. with open(filepath, "w") as fh: diff --git a/pymatgen/io/cp2k/sets.py b/pymatgen/io/cp2k/sets.py index 7992685173f..8df8da3e98b 100644 --- a/pymatgen/io/cp2k/sets.py +++ b/pymatgen/io/cp2k/sets.py @@ -507,11 +507,10 @@ def match_elecs(x): break if basis is None: - if basis_and_potential.get(el, {}).get("basis"): - warnings.warn(f"Unable to validate basis for {el}. Exact name provided will be put in input file.") - basis = basis_and_potential[el].get("basis") - else: - raise ValueError("No explicit basis found and matching has failed.") + if not basis_and_potential.get(el, {}).get("basis"): + raise ValueError(f"No explicit basis found for {el} and matching has failed.") + warnings.warn(f"Unable to validate basis for {el}. Exact name provided will be put in input file.") + basis = basis_and_potential[el].get("basis") if aux_basis is None and basis_and_potential.get(el, {}).get("aux_basis"): warnings.warn( @@ -528,7 +527,7 @@ def match_elecs(x): else: raise ValueError("No explicit potential found and matching has failed.") - if basis.filename: + if hasattr(basis, "filename"): data["basis_filenames"].append(basis.filename) pfn1 = data.get("potential_filename") pfn2 = potential.filename @@ -539,11 +538,7 @@ def match_elecs(x): ) data["potential_filename"] = pfn2 - data[el] = { - "basis": basis, - "aux_basis": aux_basis, - "potential": potential, - } + data[el] = {"basis": basis, "aux_basis": aux_basis, "potential": potential} return data @staticmethod diff --git a/pymatgen/io/feff/sets.py b/pymatgen/io/feff/sets.py index 87d99e0a675..9761195914d 100644 --- a/pymatgen/io/feff/sets.py +++ b/pymatgen/io/feff/sets.py @@ -91,8 +91,8 @@ def write_input(self, output_dir=".", make_dir_if_not_present=True): make_dir_if_not_present: Set to True if you want the directory ( and the whole path) to be created if it is not present. """ - if make_dir_if_not_present and not os.path.exists(output_dir): - os.makedirs(output_dir) + if make_dir_if_not_present: + os.makedirs(output_dir, exist_ok=True) feff = self.all_input() @@ -282,16 +282,16 @@ def __str__(self): output.append("") return "\n".join(output) - @staticmethod - def from_directory(input_dir): + @classmethod + def from_directory(cls, input_dir): """ Read in a set of FEFF input files from a directory, which is useful when existing FEFF input needs some adjustment. """ sub_d = {} for fname, ftype in [("HEADER", Header), ("PARAMETERS", Tags)]: - fullzpath = zpath(os.path.join(input_dir, fname)) - sub_d[fname.lower()] = ftype.from_file(fullzpath) + full_zpath = zpath(os.path.join(input_dir, fname)) + sub_d[fname.lower()] = ftype.from_file(full_zpath) # Generation of FEFFDict set requires absorbing atom, need to search # the index of absorption atom in the structure according to the @@ -299,10 +299,10 @@ def from_directory(input_dir): absorber_index = [] radius = None - feffinp = zpath(f"{input_dir}/feff.inp") + feff_inp = zpath(f"{input_dir}/feff.inp") if "RECIPROCAL" not in sub_d["parameters"]: - input_atoms = Atoms.cluster_from_file(feffinp) + input_atoms = Atoms.cluster_from_file(feff_inp) shell_species = np.array([x.species_string for x in input_atoms]) # First row of distance matrix represents the distance from the absorber to @@ -313,12 +313,7 @@ def from_directory(input_dir): from math import ceil radius = int( - ceil( - input_atoms.get_distance( - input_atoms.index(input_atoms[0]), - input_atoms.index(input_atoms[-1]), - ) - ) + ceil(input_atoms.get_distance(input_atoms.index(input_atoms[0]), input_atoms.index(input_atoms[-1]))) ) for site_index, site in enumerate(sub_d["header"].struct): @@ -342,7 +337,7 @@ def from_directory(input_dir): CONFIG = loadfn(f"{MODULE_DIR}/MPXANESSet.yaml") if radius is None: radius = 10 - return FEFFDictSet( + return cls( absorber_index[0], sub_d["header"].struct, radius=radius, diff --git a/pymatgen/io/lammps/inputs.py b/pymatgen/io/lammps/inputs.py index 7ec83f71c97..0966f0a3fe7 100644 --- a/pymatgen/io/lammps/inputs.py +++ b/pymatgen/io/lammps/inputs.py @@ -1077,8 +1077,8 @@ def write_lammps_inputs( variables = {} if settings is None else settings template = Template(script_template) input_script = template.safe_substitute(**variables) - if make_dir_if_not_present and not os.path.exists(output_dir): - os.makedirs(output_dir) + if make_dir_if_not_present: + os.makedirs(output_dir, exist_ok=True) with open(os.path.join(output_dir, script_filename), "w") as f: f.write(input_script) read_data = re.search(r"read_data\s+(.*)\n", input_script) diff --git a/pymatgen/io/vasp/inputs.py b/pymatgen/io/vasp/inputs.py index 53981b9b4ed..560ac548615 100644 --- a/pymatgen/io/vasp/inputs.py +++ b/pymatgen/io/vasp/inputs.py @@ -2565,15 +2565,15 @@ def write_input(self, output_dir=".", make_dir_if_not_present=True): make_dir_if_not_present (bool): Create the directory if not present. Defaults to True. """ - if make_dir_if_not_present and not os.path.exists(output_dir): - os.makedirs(output_dir) + if make_dir_if_not_present: + os.makedirs(output_dir, exist_ok=True) for k, v in self.items(): if v is not None: with zopen(os.path.join(output_dir, k), "wt") as f: f.write(str(v)) - @staticmethod - def from_directory(input_dir, optional_files=None): + @classmethod + def from_directory(cls, input_dir, optional_files=None): """ Read in a set of VASP input from a directory. Note that only the standard INCAR, POSCAR, POTCAR and KPOINTS files are read unless @@ -2593,8 +2593,8 @@ def from_directory(input_dir, optional_files=None): ("POTCAR", Potcar), ]: try: - fullzpath = zpath(os.path.join(input_dir, fname)) - sub_d[fname.lower()] = ftype.from_file(fullzpath) + full_zpath = zpath(os.path.join(input_dir, fname)) + sub_d[fname.lower()] = ftype.from_file(full_zpath) except FileNotFoundError: # handle the case where there is no KPOINTS file sub_d[fname.lower()] = None @@ -2602,7 +2602,7 @@ def from_directory(input_dir, optional_files=None): if optional_files is not None: for fname, ftype in optional_files.items(): sub_d["optional_files"][fname] = ftype.from_file(os.path.join(input_dir, fname)) - return VaspInput(**sub_d) + return cls(**sub_d) def run_vasp( self, diff --git a/pymatgen/io/vasp/sets.py b/pymatgen/io/vasp/sets.py index 90e69a006b4..4f060d40b5e 100644 --- a/pymatgen/io/vasp/sets.py +++ b/pymatgen/io/vasp/sets.py @@ -162,8 +162,8 @@ def write_input( same name as the InputSet (e.g., MPStaticSet.zip) """ if potcar_spec: - if make_dir_if_not_present and not os.path.exists(output_dir): - os.makedirs(output_dir) + if make_dir_if_not_present: + os.makedirs(output_dir, exist_ok=True) with zopen(f"{output_dir}/POTCAR.spec", "wt") as file: file.write("\n".join(self.potcar_symbols)) diff --git a/pymatgen/symmetry/kpath.py b/pymatgen/symmetry/kpath.py index 55d1ad85677..f0f3f6c0587 100644 --- a/pymatgen/symmetry/kpath.py +++ b/pymatgen/symmetry/kpath.py @@ -1333,7 +1333,7 @@ def _choose_path( line_orbits_in_path = [] point_orbits_in_path = [] - for i, little_group in enumerate(little_groups_lines): + for idx, little_group in enumerate(little_groups_lines): add_rep = False nC2 = 0 nC3 = 0 @@ -1355,8 +1355,8 @@ def _choose_path( add_rep = True if add_rep: - line_orbits_in_path.append(i) - line = key_lines_inds_orbits[i][0] + line_orbits_in_path.append(idx) + line = key_lines_inds_orbits[idx][0] ind0 = line[0] ind1 = line[1] found0 = False @@ -1377,9 +1377,9 @@ def _choose_path( unconnected = [] - for i in range(len(key_points_inds_orbits)): - if i not in point_orbits_in_path: - unconnected.append(i) + for idx in range(len(key_points_inds_orbits)): + if idx not in point_orbits_in_path: + unconnected.append(idx) for ind in unconnected: connect = False @@ -1420,22 +1420,22 @@ def _get_key_points(self): # pymatgen gives BZ in Cartesian coordinates; convert to fractional in # the primitive basis for reciprocal space - for i, facet in enumerate(bz): + for idx, facet in enumerate(bz): for j, vert in enumerate(facet): vert = self._rec_lattice.get_fractional_coords(vert) - bz[i][j] = vert + bz[idx][j] = vert pop = [] - for i, facet in enumerate(bz): + for idx, facet in enumerate(bz): rounded_facet = np.around(facet, decimals=decimals) u, indices = np.unique(rounded_facet, axis=0, return_index=True) if len(u) in [1, 2]: - pop.append(i) + pop.append(idx) else: - bz[i] = [facet[j] for j in np.sort(indices)] + bz[idx] = [facet[j] for j in np.sort(indices)] bz = [bz[i] for i in range(len(bz)) if i not in pop] # use vertex points to calculate edge- and face- centers - for i, facet in enumerate(bz): + for idx, facet in enumerate(bz): bz_as_key_point_inds.append([]) for j, vert in enumerate(facet): edge_center = (vert + facet[j + 1]) / 2 if j != len(facet) - 1 else (vert + facet[0]) / 2.0 @@ -1443,30 +1443,30 @@ def _get_key_points(self): duplicateedge = False for k, point in enumerate(key_points): if np.allclose(vert, point, atol=self._atol): - bz_as_key_point_inds[i].append(k) + bz_as_key_point_inds[idx].append(k) duplicatevert = True break for k, point in enumerate(key_points): if np.allclose(edge_center, point, atol=self._atol): - bz_as_key_point_inds[i].append(k) + bz_as_key_point_inds[idx].append(k) duplicateedge = True break if not duplicatevert: key_points.append(vert) - bz_as_key_point_inds[i].append(len(key_points) - 1) + bz_as_key_point_inds[idx].append(len(key_points) - 1) if not duplicateedge: key_points.append(edge_center) - bz_as_key_point_inds[i].append(len(key_points) - 1) + bz_as_key_point_inds[idx].append(len(key_points) - 1) if len(facet) == 4: # parallelogram facet face_center = (facet[0] + facet[1] + facet[2] + facet[3]) / 4.0 key_points.append(face_center) face_center_inds.append(len(key_points) - 1) - bz_as_key_point_inds[i].append(len(key_points) - 1) + bz_as_key_point_inds[idx].append(len(key_points) - 1) else: # hexagonal facet face_center = (facet[0] + facet[1] + facet[2] + facet[3] + facet[4] + facet[5]) / 6.0 key_points.append(face_center) face_center_inds.append(len(key_points) - 1) - bz_as_key_point_inds[i].append(len(key_points) - 1) + bz_as_key_point_inds[idx].append(len(key_points) - 1) # add gamma point key_points.append(np.array([0, 0, 0])) diff --git a/tests/io/feff/test_sets.py b/tests/io/feff/test_sets.py index e5cb0314f02..980dd333ece 100644 --- a/tests/io/feff/test_sets.py +++ b/tests/io/feff/test_sets.py @@ -208,11 +208,11 @@ def test_post_feffset(self): assert "RECIPROCAL" in feff_reci_input.tags feff_reci_input.write_input(f"{self.tmp_path}/Dup_reci") - assert os.path.exists(f"{self.tmp_path}/Dup_reci/HEADER") - assert os.path.exists(f"{self.tmp_path}/Dup_reci/feff.inp") - assert os.path.exists(f"{self.tmp_path}/Dup_reci/PARAMETERS") - assert not os.path.exists(f"{self.tmp_path}/Dup_reci/ATOMS") - assert not os.path.exists(f"{self.tmp_path}/Dup_reci/POTENTIALS") + assert os.path.isfile(f"{self.tmp_path}/Dup_reci/HEADER") + assert os.path.isfile(f"{self.tmp_path}/Dup_reci/feff.inp") + assert os.path.isfile(f"{self.tmp_path}/Dup_reci/PARAMETERS") + assert not os.path.isfile(f"{self.tmp_path}/Dup_reci/ATOMS") + assert not os.path.isfile(f"{self.tmp_path}/Dup_reci/POTENTIALS") tags_original = Tags.from_file(f"{self.tmp_path}/xanes_reci/feff.inp") tags_output = Tags.from_file(f"{self.tmp_path}/Dup_reci/feff.inp")