Skip to content

Commit 9223a3d

Browse files
authored
Merge pull request #1637 from soto-raul/refactor/replace_os_path_join_with_Pathlib_path
refactor: replaced 'os.path.join()' uses with 'pathlib.Path' / syntax
2 parents 3648a29 + 98a9fce commit 9223a3d

15 files changed

Lines changed: 59 additions & 42 deletions

File tree

install/find_mpi.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22

33
import mpi4py
44
from mpi4py import MPI
5+
from pathlib import Path
56

6-
path = mpi4py.__path__[0]
7+
path = Path(mpi4py.__path__[0])
78
print("\nmpi4py path found is:", path)
89

9-
configfile = os.path.join(path, "mpi.cfg")
10+
configfile = path / "mpi.cfg"
1011
print("\nShowing config file: ", configfile, "\n")
1112

1213
with open(configfile, "r") as confile_handle:

libensemble/executors/executor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,11 +178,11 @@ def workdir_exists(self) -> bool | None:
178178

179179
def file_exists_in_workdir(self, filename: str) -> bool:
180180
"""Returns true if the named file exists in the task's workdir"""
181-
return self.workdir and os.path.exists(os.path.join(self.workdir, filename))
181+
return self.workdir and os.path.exists(Path(self.workdir) / filename)
182182

183183
def read_file_in_workdir(self, filename: str) -> str:
184184
"""Opens and reads the named file in the task's workdir"""
185-
path = os.path.join(self.workdir, filename)
185+
path = Path(self.workdir) / filename
186186
if not os.path.exists(path):
187187
raise ValueError(f"{filename} not found in working directory")
188188
with open(path) as f:

libensemble/manager.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import sys
1313
import time
1414
import traceback
15+
from pathlib import Path
1516
from typing import Any
1617

1718
import numpy as np
@@ -338,7 +339,7 @@ def _save_every_k(self, fname: str, count: int, k: int, complete: bool) -> None:
338339
def _save_every_k_sims(self, complete: bool) -> None:
339340
"""Saves history every kth sim step"""
340341
self._save_every_k(
341-
os.path.join(self.libE_specs["workflow_dir_path"], "{}_{}after_sim_{}.npy"),
342+
str(Path(self.libE_specs["workflow_dir_path"]) / "{}_{}after_sim_{}.npy"),
342343
self.hist.sim_ended_count,
343344
self.libE_specs["save_every_k_sims"],
344345
complete,
@@ -347,7 +348,7 @@ def _save_every_k_sims(self, complete: bool) -> None:
347348
def _save_every_k_gens(self, complete: bool) -> None:
348349
"""Saves history every kth gen step"""
349350
self._save_every_k(
350-
os.path.join(self.libE_specs["workflow_dir_path"], "{}_{}after_gen_{}.npy"),
351+
str(Path(self.libE_specs["workflow_dir_path"]) / "{}_{}after_gen_{}.npy"),
351352
self.hist.index,
352353
self.libE_specs["save_every_k_gens"],
353354
complete,

libensemble/resources/resources.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import logging
77
import os
88
import socket
9+
from pathlib import Path
910

1011
from libensemble.resources import node_resources
1112
from libensemble.resources.env_resources import EnvResources
@@ -295,8 +296,8 @@ def get_global_nodelist(node_file=Resources.DEFAULT_NODEFILE, rundir=None, env_r
295296
296297
In dedicated mode, any node with a libE worker is removed from the list.
297298
"""
298-
top_level_dir = rundir or os.getcwd()
299-
node_filepath = os.path.join(top_level_dir, node_file)
299+
top_level_dir = Path(rundir) if rundir else Path.cwd()
300+
node_filepath = top_level_dir / node_file
300301
global_nodelist = []
301302
if os.path.isfile(node_filepath):
302303
with open(node_filepath, "r") as f:

libensemble/tests/run_tests.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,16 @@
3535
# Test Directories - all relative to project root dir
3636
CODE_DIR = "libensemble"
3737
LIBE_SRC_DIR = CODE_DIR
38-
TESTING_DIR = os.path.join(CODE_DIR, "tests")
38+
TESTING_DIR = Path(CODE_DIR) / "tests"
3939
UNIT_TEST_SUBDIRS = [
4040
"unit_tests",
4141
"unit_tests_mpi_import",
4242
"unit_tests_nompi",
4343
"unit_tests_logger",
4444
]
45-
UNIT_TEST_DIRS = [os.path.join(TESTING_DIR, subdir) for subdir in UNIT_TEST_SUBDIRS]
46-
REG_TEST_SUBDIR = os.path.join(TESTING_DIR, "regression_tests")
47-
FUNC_TEST_SUBDIR = os.path.join(TESTING_DIR, "functionality_tests")
45+
UNIT_TEST_DIRS = [TESTING_DIR / subdir for subdir in UNIT_TEST_SUBDIRS]
46+
REG_TEST_SUBDIR = TESTING_DIR / "regression_tests"
47+
FUNC_TEST_SUBDIR = TESTING_DIR / "functionality_tests"
4848

4949
# Coverage merge and report dir
5050
COV_MERGE_DIR = TESTING_DIR
@@ -132,12 +132,13 @@ def cleanup(root_dir):
132132
]
133133
dirs_to_clean = UNIT_TEST_DIRS + [REG_TEST_SUBDIR, FUNC_TEST_SUBDIR]
134134
for dir_path in dirs_to_clean:
135-
full_path = os.path.join(root_dir, dir_path)
136-
if "libensemble/tests/" not in full_path.replace("\\", "/"):
137-
cprint(f"Safety check failed for {full_path}. Check directory", style="red")
135+
full_path = Path(root_dir) / dir_path
136+
full_path_str = str(full_path)
137+
if "libensemble/tests/" not in full_path_str.replace("\\", "/"):
138+
cprint(f"Safety check failed for {full_path_str}. Check directory", style="red")
138139
sys.exit(2)
139140
for pattern in patterns:
140-
for file_path in glob.glob(os.path.join(full_path, pattern)):
141+
for file_path in glob.glob(str(full_path / pattern)):
141142
try:
142143
if os.path.isfile(file_path) or os.path.islink(file_path):
143144
os.remove(file_path)
@@ -199,8 +200,8 @@ def print_test_failed(test_num, test_script_name, comm, nprocs, duration):
199200
def merge_coverage_reports(root_dir):
200201
"""Merge coverage data from multiple tests and generate a report."""
201202
print_heading("Generating coverage reports")
202-
tests_dir = os.path.join(root_dir, "libensemble", "tests")
203-
cov_files = glob.glob(os.path.join(tests_dir, "**", ".cov_*"), recursive=True)
203+
tests_dir = Path(root_dir) / "libensemble" / "tests"
204+
cov_files = glob.glob(str(tests_dir / "**" / ".cov_*"), recursive=True)
204205

205206
if cov_files:
206207
try:
@@ -262,11 +263,11 @@ def is_open_mpi():
262263
def build_forces(root_dir):
263264
"""Build forces.x using mpicc."""
264265
cprint("Building forces.x before running regression tests...", style="yellow", newline=True)
265-
forces_app_dir = os.path.join(root_dir, "libensemble/tests/scaling_tests/forces/forces_app")
266+
forces_app_dir = Path(root_dir) / "libensemble/tests/scaling_tests/forces/forces_app"
266267
subprocess.run(["mpicc", "-O3", "-o", "forces.x", "forces.c", "-lm"], cwd=forces_app_dir, check=True)
267-
destination_dir = os.path.join(root_dir, "libensemble/tests/forces_app")
268+
destination_dir = Path(root_dir) / "libensemble/tests/forces_app"
268269
os.makedirs(destination_dir, exist_ok=True)
269-
shutil.copy(os.path.join(forces_app_dir, "forces.x"), destination_dir)
270+
shutil.copy(forces_app_dir / "forces.x", destination_dir)
270271

271272

272273
def skip_test(directives, args, current_os):
@@ -335,7 +336,7 @@ def run_unit_tests(root_dir, python_exec, args):
335336
print_heading(f"Running unit tests (with pytest)")
336337
for dir_path in UNIT_TEST_DIRS:
337338
cprint(f"Entering unit test dir: {dir_path}", style="yellow", newline=True)
338-
full_path = os.path.join(root_dir, dir_path)
339+
full_path = Path(root_dir) / dir_path
339340
cov_rep = cov_report_type + ":cov_unit"
340341
cmd = python_exec + ["-m", "pytest", "--color=yes", "--timeout=120", "--cov", "--cov-report", cov_rep]
341342
if args.e:
@@ -366,8 +367,8 @@ def run_regression_tests(root_dir, python_exec, args, current_os):
366367
reg_test_list = REG_TEST_LIST
367368
reg_test_files = []
368369
for dir_path in test_dirs:
369-
full_path = os.path.join(root_dir, dir_path)
370-
reg_test_files.extend(glob.glob(os.path.join(full_path, reg_test_list)))
370+
full_path = Path(root_dir) / dir_path
371+
reg_test_files.extend(glob.glob(str(full_path / reg_test_list)))
371372

372373
reg_test_files = sorted(reg_test_files)
373374
reg_pass = 0

libensemble/tests/scaling_tests/forces/forces_adv/forces_simf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import time
3+
from pathlib import Path
34

45
import numpy as np
56

@@ -101,7 +102,7 @@ def run_forces(H, persis_info, sim_specs, libE_info):
101102

102103
# Stat file to check for bad runs
103104
statfile = "forces.stat"
104-
filepath = os.path.join(task.workdir, statfile)
105+
filepath = Path(task.workdir) / statfile
105106
line = None
106107

107108
poll_interval = 0.1 # secs

libensemble/tests/scaling_tests/forces/forces_adv/forces_support.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
from pathlib import Path
23

34
outfiles = ["err.txt", "forces.stat", "out.txt"]
45

@@ -18,6 +19,7 @@ def test_libe_stats(status):
1819

1920

2021
def test_ensemble_dir(libE_specs, dir, nworkers, sim_max):
22+
dir = Path(dir)
2123
if not os.path.isdir(dir):
2224
print(f"Specified ensemble directory {dir} not found.")
2325
return
@@ -36,11 +38,11 @@ def test_ensemble_dir(libE_specs, dir, nworkers, sim_max):
3638

3739
worker_dirs = [i for i in os.listdir(dir) if i.startswith("worker")]
3840
for worker_dir in worker_dirs:
39-
sim_dirs = [i for i in os.listdir(os.path.join(dir, worker_dir)) if i.startswith("sim")]
41+
sim_dirs = [i for i in os.listdir(dir / worker_dir) if i.startswith("sim")]
4042
num_sim_dirs += len(sim_dirs)
4143

4244
for sim_dir in sim_dirs:
43-
files_found.append(all([i in os.listdir(os.path.join(dir, worker_dir, sim_dir)) for i in outfiles]))
45+
files_found.append(all([i in os.listdir(dir / worker_dir / sim_dir) for i in outfiles]))
4446

4547
assert (
4648
num_sim_dirs == sim_max
@@ -62,7 +64,7 @@ def test_ensemble_dir(libE_specs, dir, nworkers, sim_max):
6264

6365
files_found = []
6466
for sim_dir in sim_dirs:
65-
files_found.append(all([i in os.listdir(os.path.join(dir, sim_dir)) for i in outfiles]))
67+
files_found.append(all([i in os.listdir(dir / sim_dir) for i in outfiles]))
6668

6769
assert all(
6870
files_found

libensemble/tests/scaling_tests/forces/forces_adv/run_libe_forces.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/usr/bin/env python
22
import os
33
import sys
4+
from pathlib import Path
45

56
import numpy as np
67
from forces_simf import run_forces # Sim func from current dir
@@ -28,7 +29,7 @@
2829

2930
nworkers, is_manager, libE_specs, _ = parse_args()
3031

31-
sim_app = os.path.join(os.getcwd(), "../forces_app/forces.x")
32+
sim_app = Path.cwd() / "../forces_app/forces.x"
3233

3334
if not os.path.isfile(sim_app):
3435
sys.exit("forces.x not found - please build first in ../forces_app dir")

libensemble/tests/scaling_tests/forces/forces_gpu/run_libe_forces.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import os
1919
import sys
20+
from pathlib import Path
2021

2122
import numpy as np
2223
from forces_simf import run_forces # Sim func from current dir
@@ -30,7 +31,7 @@
3031
if __name__ == "__main__":
3132
# Initialize MPI Executor
3233
exctr = MPIExecutor()
33-
sim_app = os.path.join(os.getcwd(), "../forces_app/forces.x")
34+
sim_app = Path.cwd() / "../forces_app/forces.x"
3435

3536
if not os.path.isfile(sim_app):
3637
sys.exit("forces.x not found - please build first in ../forces_app dir")

libensemble/tests/scaling_tests/forces/forces_gpu_var_resources/run_libe_forces.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import os
2222
import sys
23+
from pathlib import Path
2324

2425
import numpy as np
2526
from forces_simf import run_forces # Sim func from current dir
@@ -33,7 +34,7 @@
3334
if __name__ == "__main__":
3435
# Initialize MPI Executor
3536
exctr = MPIExecutor()
36-
sim_app = os.path.join(os.getcwd(), "../forces_app/forces.x")
37+
sim_app = Path.cwd() / "../forces_app/forces.x"
3738

3839
if not os.path.isfile(sim_app):
3940
sys.exit("forces.x not found - please build first in ../forces_app dir")

0 commit comments

Comments
 (0)