Skip to content

Commit

Permalink
os.makedirs() use exist_ok=True
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Oct 31, 2023
1 parent 2709068 commit 0e12f81
Show file tree
Hide file tree
Showing 12 changed files with 63 additions and 77 deletions.
7 changes: 3 additions & 4 deletions dev_scripts/chemenv/explicit_permutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
3 changes: 1 addition & 2 deletions dev_scripts/chemenv/get_plane_permutations_optimized.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
3 changes: 1 addition & 2 deletions pymatgen/cli/pmg_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 7 additions & 7 deletions pymatgen/electronic_structure/boltztrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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))

Expand Down
3 changes: 1 addition & 2 deletions pymatgen/io/abinit/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
17 changes: 6 additions & 11 deletions pymatgen/io/cp2k/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand All @@ -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
Expand Down
25 changes: 10 additions & 15 deletions pymatgen/io/feff/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -282,27 +282,27 @@ 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
# distance matrix and shell species information contained in feff.inp

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
Expand All @@ -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):
Expand All @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/io/lammps/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 7 additions & 7 deletions pymatgen/io/vasp/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -2593,16 +2593,16 @@ 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

sub_d["optional_files"] = {}
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,
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/io/vasp/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
36 changes: 18 additions & 18 deletions pymatgen/symmetry/kpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -1420,53 +1420,53 @@ 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
duplicatevert = False
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]))
Expand Down
10 changes: 5 additions & 5 deletions tests/io/feff/test_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit 0e12f81

Please sign in to comment.