Coverage for ase/calculators/exciting/runner.py: 58.82%

34 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1"""Binary runner and results class.""" 

2 

3import os 

4import subprocess 

5import time 

6from pathlib import Path 

7 

8 

9class SubprocessRunResults: 

10 """Results returned from subprocess.run().""" 

11 

12 def __init__( 

13 self, 

14 stdout, 

15 stderr, 

16 return_code: int, 

17 process_time: float | None = None, 

18 ): 

19 self.stdout = stdout 

20 self.stderr = stderr 

21 self.return_code = return_code 

22 self.success = return_code == 0 

23 self.process_time = process_time 

24 

25 

26class SimpleBinaryRunner: 

27 """Class to execute a subprocess.""" 

28 

29 path_type = str | Path 

30 

31 def __init__( 

32 self, 

33 binary, 

34 run_argv: list[str], 

35 omp_num_threads: int, 

36 directory: path_type = './', 

37 args=None, 

38 ) -> None: 

39 """Initialise class. 

40 

41 Parameters 

42 ---------- 

43 binary : str 

44 Binary name prepended by full path, or just binary name 

45 (if present in $PATH). 

46 run_argv : list[str] 

47 Run commands sequentially as a list of str. 

48 For example: 

49 * For serial: ['./'] or [''] 

50 * For MPI: ['mpirun', '-np', '2'] 

51 omp_num_threads : int 

52 Number of OMP threads. 

53 args : None 

54 Optional arguments for the binary. 

55 

56 """ 

57 if args is None: 

58 args = [] 

59 self.binary = binary 

60 self.directory = directory 

61 

62 self.run_argv = run_argv 

63 

64 self.omp_num_threads = omp_num_threads 

65 self.args = args 

66 

67 if directory is not None and not Path(directory).is_dir(): 

68 raise OSError(f'Run directory does not exist: {directory}') 

69 

70 if omp_num_threads <= 0: 

71 raise ValueError('Number of OMP threads must be > 0') 

72 

73 def compose_execution_list(self) -> list: 

74 """Generate a complete list of strings to pass to subprocess.run(). 

75 

76 This is done to execute the calculation. 

77 

78 For example, given: 

79 ['mpirun', '-np, '2'] + ['binary.exe'] + ['>', 'std.out'] 

80 

81 return ['mpirun', '-np, '2', 'binary.exe', '>', 'std.out'] 

82 """ 

83 return self.run_argv + [self.binary] + self.args 

84 

85 def run(self) -> SubprocessRunResults: 

86 """Run a binary.""" 

87 execution_list = self.compose_execution_list() 

88 my_env = {**os.environ} 

89 

90 time_start: float = time.time() 

91 result = subprocess.run( 

92 execution_list, 

93 env=my_env, 

94 capture_output=True, 

95 cwd=self.directory, 

96 check=False, 

97 ) 

98 total_time = time.time() - time_start 

99 return SubprocessRunResults( 

100 result.stdout, result.stderr, result.returncode, total_time 

101 )