• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmc-dev / openmc / 25033551588

28 Apr 2026 04:15AM UTC coverage: 81.361% (-0.2%) from 81.566%
25033551588

Pull #3860

github

web-flow
Merge 3714a06cb into 806fb4ce7
Pull Request #3860: Support multiple meshes in R2S calculations

17626 of 25463 branches covered (69.22%)

Branch coverage included in aggregate %.

101 of 120 new or added lines in 2 files covered. (84.17%)

883 existing lines in 34 files now uncovered.

58268 of 67818 relevant lines covered (85.92%)

47113759.34 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.0
/openmc/executor.py
1
from collections.abc import Iterable
11✔
2
from numbers import Integral
11✔
3
import os
11✔
4
import subprocess
11✔
5

6
import openmc
11✔
7
from .plots import _get_plot_image
11✔
8

9

10
def _process_CLI_arguments(volume=False, geometry_debug=False, particles=None,
11✔
11
                           plot=False, restart_file=None, threads=None,
12
                           tracks=False, event_based=None,
13
                           openmc_exec='openmc', mpi_args=None, path_input=None):
14
    """Converts user-readable flags in to command-line arguments to be run with
15
    the OpenMC executable via subprocess.
16

17
    Parameters
18
    ----------
19
    volume : bool, optional
20
        Run in stochastic volume calculation mode. Defaults to False.
21
    geometry_debug : bool, optional
22
        Turn on geometry debugging during simulation. Defaults to False.
23
    particles : int, optional
24
        Number of particles to simulate per generation.
25
    plot : bool, optional
26
        Run in plotting mode. Defaults to False.
27
    restart_file : str or PathLike
28
        Path to restart file to use
29
    threads : int, optional
30
        Number of OpenMP threads. If OpenMC is compiled with OpenMP threading
31
        enabled, the default is implementation-dependent but is usually equal
32
        to the number of hardware threads available (or a value set by the
33
        :envvar:`OMP_NUM_THREADS` environment variable).
34
    tracks : bool, optional
35
        Enables the writing of particles tracks. The number of particle
36
        tracks written to tracks.h5 is limited to 1000 unless
37
        Settings.max_tracks is set. Defaults to False.
38
    event_based : None or bool, optional
39
        Turns on event-based parallelism if True. If None, the value in
40
        the Settings will be used.
41
    openmc_exec : str, optional
42
        Path to OpenMC executable. Defaults to 'openmc'.
43
    mpi_args : list of str, optional
44
        MPI execute command and any additional MPI arguments to pass,
45
        e.g., ['mpiexec', '-n', '8'].
46
    path_input : str or PathLike
47
        Path to a single XML file or a directory containing XML files for the
48
        OpenMC executable to read.
49

50
    .. versionadded:: 0.13.0
51

52
    Returns
53
    -------
54
    args : Iterable of str
55
        The runtime flags converted to CLI arguments of the OpenMC executable
56

57
    """
58

59
    args = [openmc_exec]
11✔
60

61
    if volume:
11✔
62
        args.append('--volume')
11✔
63

64
    if isinstance(particles, Integral) and particles > 0:
11✔
65
        args += ['-n', str(particles)]
×
66

67
    if isinstance(threads, Integral) and threads > 0:
11✔
68
        args += ['-s', str(threads)]
11✔
69

70
    if geometry_debug:
11✔
71
        args.append('-g')
×
72

73
    if event_based is not None:
11✔
74
        if event_based:
11✔
75
            args.append('-e')
1✔
76

77
    if isinstance(restart_file, (str, os.PathLike)):
11✔
78
        args += ['-r', str(restart_file)]
11✔
79

80
    if tracks:
11✔
81
        args.append('-t')
11✔
82

83
    if plot:
11✔
84
        args.append('-p')
×
85

86
    if mpi_args is not None:
11✔
87
        args = mpi_args + args
4✔
88

89
    if path_input is not None:
11✔
90
        args += [path_input]
11✔
91

92
    return args
11✔
93

94

95
def _run(args, output, cwd):
11✔
96
    # Launch a subprocess
97
    p = subprocess.Popen(args, cwd=cwd, stdout=subprocess.PIPE,
11✔
98
                         stderr=subprocess.STDOUT, universal_newlines=True)
99

100
    # Capture and re-print OpenMC output in real-time
101
    lines = []
11✔
102
    while True:
11✔
103
        # If OpenMC is finished, break loop
104
        line = p.stdout.readline()
11✔
105
        if not line and p.poll() is not None:
11✔
106
            p.stdout.close()
11✔
107
            break
11✔
108

109
        lines.append(line)
11✔
110
        if output:
11✔
111
            # If user requested output, print to screen
112
            print(line, end='')
11✔
113

114
    # Raise an exception if return status is non-zero
115
    if p.returncode != 0:
11✔
116
        # Get error message from output and simplify whitespace
117
        output = ''.join(lines)
11✔
118
        if 'ERROR: ' in output:
11✔
119
            _, _, error_msg = output.partition('ERROR: ')
11✔
120
        elif 'what()' in output:
×
UNCOV
121
            _, _, error_msg = output.partition('what(): ')
×
122
        else:
UNCOV
123
            error_msg = 'OpenMC aborted unexpectedly.'
×
124
        error_msg = ' '.join(error_msg.split())
11✔
125

126
        raise RuntimeError(error_msg)
11✔
127

128

129
def plot_geometry(output=True, openmc_exec='openmc', cwd='.', path_input=None):
11✔
130
    """Run OpenMC in plotting mode
131

132
    Parameters
133
    ----------
134
    output : bool, optional
135
        Capture OpenMC output from standard out
136
    openmc_exec : str, optional
137
        Path to OpenMC executable
138
    cwd : str, optional
139
        Path to working directory to run in
140
    path_input : str
141
        Path to a single XML file or a directory containing XML files for the
142
        OpenMC executable to read.
143

144
        .. versionadded:: 0.13.3
145

146
    Raises
147
    ------
148
    RuntimeError
149
        If the `openmc` executable returns a non-zero status
150

151
    """
152
    args = [openmc_exec, '-p']
11✔
153
    if path_input is not None:
11✔
154
        args += [path_input]
11✔
155
    _run(args, output, cwd)
11✔
156

157

158
def plot_inline(plots, openmc_exec='openmc', cwd='.', path_input=None):
11✔
159
    """Display plots inline in a Jupyter notebook.
160

161
    .. versionchanged:: 0.13.0
162
        The *convert_exec* argument was removed since OpenMC now produces
163
        .png images directly.
164

165

166
    Parameters
167
    ----------
168
    plots : Iterable of openmc.PlotBase
169
        Plots to display
170
    openmc_exec : str
171
        Path to OpenMC executable
172
    cwd : str, optional
173
        Path to working directory to run in
174
    path_input : str
175
        Path to a single XML file or a directory containing XML files for the
176
        OpenMC executable to read.
177

178
        .. versionadded:: 0.13.3
179

180
    Raises
181
    ------
182
    RuntimeError
183
        If the `openmc` executable returns a non-zero status
184

185
    """
UNCOV
186
    from IPython.display import display
×
187

188
    if not isinstance(plots, Iterable):
×
UNCOV
189
        plots = [plots]
×
190

191
    # Create plots.xml
UNCOV
192
    openmc.Plots(plots).export_to_xml(cwd)
×
193

194
    # Run OpenMC in geometry plotting mode
UNCOV
195
    plot_geometry(False, openmc_exec, cwd, path_input)
×
196

197
    if plots is not None:
×
198
        images = [_get_plot_image(p, cwd) for p in plots]
×
UNCOV
199
        display(*images)
×
200

201

202
def calculate_volumes(threads=None, output=True, cwd='.',
11✔
203
                      openmc_exec='openmc', mpi_args=None,
204
                      path_input=None):
205
    """Run stochastic volume calculations in OpenMC.
206

207
    This function runs OpenMC in stochastic volume calculation mode. To specify
208
    the parameters of a volume calculation, one must first create a
209
    :class:`openmc.VolumeCalculation` instance and assign it to
210
    :attr:`openmc.Settings.volume_calculations`. For example:
211

212
    >>> vol = openmc.VolumeCalculation(domains=[cell1, cell2], samples=100000)
213
    >>> settings = openmc.Settings()
214
    >>> settings.volume_calculations = [vol]
215
    >>> settings.export_to_xml()
216
    >>> openmc.calculate_volumes()
217

218
    Parameters
219
    ----------
220
    threads : int, optional
221
        Number of OpenMP threads. If OpenMC is compiled with OpenMP threading
222
        enabled, the default is implementation-dependent but is usually equal
223
        to the number of hardware threads available (or a value set by the
224
        :envvar:`OMP_NUM_THREADS` environment variable).
225
    output : bool, optional
226
        Capture OpenMC output from standard out
227
    openmc_exec : str, optional
228
        Path to OpenMC executable. Defaults to 'openmc'.
229
    mpi_args : list of str, optional
230
        MPI execute command and any additional MPI arguments to pass,
231
        e.g., ['mpiexec', '-n', '8'].
232
    cwd : str, optional
233
        Path to working directory to run in. Defaults to the current working
234
        directory.
235
    path_input : str or PathLike
236
        Path to a single XML file or a directory containing XML files for the
237
        OpenMC executable to read.
238

239

240
    Raises
241
    ------
242
    RuntimeError
243
        If the `openmc` executable returns a non-zero status
244

245
    See Also
246
    --------
247
    openmc.VolumeCalculation
248

249
    """
250

251
    args = _process_CLI_arguments(volume=True, threads=threads,
11✔
252
                                  openmc_exec=openmc_exec, mpi_args=mpi_args,
253
                                  path_input=path_input)
254

255
    _run(args, output, cwd)
11✔
256

257

258
def run(particles=None, threads=None, geometry_debug=False,
11✔
259
        restart_file=None, tracks=False, output=True, cwd='.',
260
        openmc_exec='openmc', mpi_args=None, event_based=False,
261
        path_input=None):
262
    """Run an OpenMC simulation.
263

264
    Parameters
265
    ----------
266
    particles : int, optional
267
        Number of particles to simulate per generation.
268
    threads : int, optional
269
        Number of OpenMP threads. If OpenMC is compiled with OpenMP threading
270
        enabled, the default is implementation-dependent but is usually equal to
271
        the number of hardware threads available (or a value set by the
272
        :envvar:`OMP_NUM_THREADS` environment variable).
273
    geometry_debug : bool, optional
274
        Turn on geometry debugging during simulation. Defaults to False.
275
    restart_file : str or PathLike
276
        Path to restart file to use
277
    tracks : bool, optional
278
        Enables the writing of particles tracks. The number of particle tracks
279
        written to tracks.h5 is limited to 1000 unless Settings.max_tracks is
280
        set. Defaults to False.
281
    output : bool
282
        Capture OpenMC output from standard out
283
    cwd : str, optional
284
        Path to working directory to run in. Defaults to the current working
285
        directory.
286
    openmc_exec : str, optional
287
        Path to OpenMC executable. Defaults to 'openmc'.
288
    mpi_args : list of str, optional
289
        MPI execute command and any additional MPI arguments to pass, e.g.,
290
        ['mpiexec', '-n', '8'].
291
    event_based : bool, optional
292
        Turns on event-based parallelism, instead of default history-based
293

294
        .. versionadded:: 0.12
295

296
    path_input : str or PathLike
297
        Path to a single XML file or a directory containing XML files for the
298
        OpenMC executable to read.
299

300
        .. versionadded:: 0.13.3
301

302
    Raises
303
    ------
304
    RuntimeError
305
        If the `openmc` executable returns a non-zero status
306

307
    """
308

309
    args = _process_CLI_arguments(
11✔
310
        volume=False, geometry_debug=geometry_debug, particles=particles,
311
        restart_file=restart_file, threads=threads, tracks=tracks,
312
        event_based=event_based, openmc_exec=openmc_exec, mpi_args=mpi_args,
313
        path_input=path_input)
314

315
    _run(args, output, cwd)
11✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc