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

openmc-dev / openmc / 21489819490

29 Jan 2026 06:21PM UTC coverage: 80.077% (-1.9%) from 81.953%
21489819490

Pull #3757

github

web-flow
Merge d08626053 into f7a734189
Pull Request #3757: Testing point detectors

16004 of 22621 branches covered (70.75%)

Branch coverage included in aggregate %.

94 of 518 new or added lines in 26 files covered. (18.15%)

1021 existing lines in 52 files now uncovered.

53779 of 64524 relevant lines covered (83.35%)

8016833.26 hits per line

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

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

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

9

10
def _process_CLI_arguments(volume=False, geometry_debug=False, particles=None,
1✔
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]
1✔
60

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

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

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

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

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

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

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

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

86
    if mpi_args is not None:
1✔
UNCOV
87
        args = mpi_args + args
×
88

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

92
    return args
1✔
93

94

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

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

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

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

125
        raise RuntimeError(error_msg)
1✔
126

127

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

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

143
        .. versionadded:: 0.13.3
144

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

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

156

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

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

164

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

177
        .. versionadded:: 0.13.3
178

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

184
    """
185
    from IPython.display import display
×
186

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

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

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

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

200

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

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

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

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

238

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

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

248
    """
249

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

254
    _run(args, output, cwd)
1✔
255

256

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

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

293
        .. versionadded:: 0.12
294

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

299
        .. versionadded:: 0.13.3
300

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

306
    """
307

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

314
    _run(args, output, cwd)
1✔
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