Debugging a simple photon transport model generated with ChatGPT

I need help debugging a simple model that I asked ChatGPT to make. I want a simple photon transport simulation to play with, so first I asked it just for some code that will plot a random geometry in both 2D and 3D side by side so I can start to visualize it. Couldn’t even get past the first step as ChatGPT and I can’t seem to figure out how to get it working. I’m just running this in a Jupyter Notebook on a Macbook Pro in a miniconda env with openmc installed:

import openmc
import matplotlib.pyplot as plt

# Define materials
water = openmc.Material(1, "h2o")
water.add_nuclide("H1", 2)
water.add_nuclide("O16", 1)
water.set_density("g/cm3", 1.0)

# Define geometry
sphere = openmc.Sphere(r=10, boundary_type="vacuum")
cell = openmc.Cell(fill=water, region=-sphere)
geom = openmc.Geometry([cell])

# Define source
point = openmc.stats.Point((0, 0, 0))
src = openmc.Source(space=point)

# Define tally
tally = openmc.Tally()
tally.filters = [openmc.CellFilter([cell])]
tally.scores = ["flux"]

# Create a model and set the geometry, source, and tallies
model = openmc.model.Model()
model.geometry = geom
model.source = src
model.tallies = [tally]

# Set up the simulation
settings = openmc.Settings()
settings.particles = 1000000
settings.run_mode = 'fixed source'
settings.source = src

# Run the simulation
model.run(particles=1000)

# Create a figure with a 3D plot and a 2D plot side by side
fig = plt.figure(figsize=(12, 6))

# Create a 3D plot
ax1 = fig.add_subplot(121, projection='3d')
openmc.plot_inline(model.geometry.plot(width=400), ax=ax1)

# Create a 2D plot
ax2 = fig.add_subplot(122)
openmc.plot_inline(tally.plot(0), ax=ax2)

# Show the plots
plt.show()
                                %%%%%%%%%%%%%%%
                           %%%%%%%%%%%%%%%%%%%%%%%%
                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                                    %%%%%%%%%%%%%%%%%%%%%%%%
                                     %%%%%%%%%%%%%%%%%%%%%%%%
                 ###############      %%%%%%%%%%%%%%%%%%%%%%%%
                ##################     %%%%%%%%%%%%%%%%%%%%%%%
                ###################     %%%%%%%%%%%%%%%%%%%%%%%
                ####################     %%%%%%%%%%%%%%%%%%%%%%
                #####################     %%%%%%%%%%%%%%%%%%%%%
                ######################     %%%%%%%%%%%%%%%%%%%%
                #######################     %%%%%%%%%%%%%%%%%%
                 #######################     %%%%%%%%%%%%%%%%%
                 ######################     %%%%%%%%%%%%%%%%%
                  ####################     %%%%%%%%%%%%%%%%%
                    #################     %%%%%%%%%%%%%%%%%
                     ###############     %%%%%%%%%%%%%%%%
                       ############     %%%%%%%%%%%%%%%
                          ########     %%%%%%%%%%%%%%
                                      %%%%%%%%%%%

                 | The OpenMC Monte Carlo Code
       Copyright | 2011-2022 MIT, UChicago Argonne LLC, and contributors
         License | https://docs.openmc.org/en/latest/license.html
         Version | 0.13.2
       Date/Time | 2023-02-22 17:02:00
   MPI Processes | 1
  OpenMP Threads | 8

 Reading settings XML file...
 ERROR: Need to specify number of particles.
application called MPI_Abort(MPI_COMM_WORLD, -1) - process 0
[unset]: write_line error; fd=-1 buf=:cmd=abort exitcode=-1
:
system msg for write_line failure : Bad file descriptor
/Users/sshahbazi/miniconda3/envs/openmc/lib/python3.11/site-packages/openmc/mixin.py:70: IDWarning: Another Material instance already exists with id=1.
  warn(msg, IDWarning)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[41], line 37
     34 settings.source = src
     36 # Run the simulation
---> 37 model.run(particles=1000)
     39 # Create a figure with a 3D plot and a 2D plot side by side
     40 fig = plt.figure(figsize=(12, 6))

File ~/miniconda3/envs/openmc/lib/python3.11/site-packages/openmc/model/model.py:588, in Model.run(self, particles, threads, geometry_debug, restart_file, tracks, output, cwd, openmc_exec, mpi_args, event_based)
    585 else:
    586     # Then run via the command line
    587     self.export_to_xml()
--> 588     openmc.run(particles, threads, geometry_debug, restart_file,
    589                tracks, output, Path('.'), openmc_exec, mpi_args,
    590                event_based)
    592 # Get output directory and return the last statepoint written
    593 if self.settings.output and 'path' in self.settings.output:

File ~/miniconda3/envs/openmc/lib/python3.11/site-packages/openmc/executor.py:280, in run(particles, threads, geometry_debug, restart_file, tracks, output, cwd, openmc_exec, mpi_args, event_based)
    234 """Run an OpenMC simulation.
    235 
    236 Parameters
   (...)
    272 
    273 """
    275 args = _process_CLI_arguments(
    276     volume=False, geometry_debug=geometry_debug, particles=particles,
    277     restart_file=restart_file, threads=threads, tracks=tracks,
    278     event_based=event_based, openmc_exec=openmc_exec, mpi_args=mpi_args)
--> 280 _run(args, output, cwd)

File ~/miniconda3/envs/openmc/lib/python3.11/site-packages/openmc/executor.py:118, in _run(args, output, cwd)
    115     error_msg = 'OpenMC aborted unexpectedly.'
    116 error_msg = ' '.join(error_msg.split())
--> 118 raise RuntimeError(error_msg)

RuntimeError: Need to specify number of particles. application called MPI_Abort(MPI_COMM_WORLD, -1) - process 0 [unset]: write_line error; fd=-1 buf=:cmd=abort exitcode=-1 : system msg for write_line failure : Bad file descriptor

Looks like your buddy ChatGPT needs to read the manual a little more closely :smile: The problem is that the simulation settings need to be specified as part of the model object. That is, you should have:

# Set up the simulation
model.settings.particles = 1000000
model.settings.run_mode = 'fixed source'
model.settings.source = src

You’ll also need to specify the number of batches:

model.settings.batches = ...

Your water material should also have an S(\alpha,\beta) table specified:

water.add_s_alpha_beta("c_H_in_H2O")

The commands for plotting that ChatGPT came up with are not even close to correct. I’d recommend taking a look at our example notebooks, which have ample examples of plotting.

4 Likes

Thanks, Paul. I’m noticing that ChatGPT isn’t quite ready for this. I am going thru the Pin-Cell Jupyter Notebook example and trying to recreate it, but I’m getting a random error that isn’t that descriptive:

import matplotlib as plt
import openmc
uo2 = openmc.Material(1, "uo2")
uo2.add_nuclide('U235', 0.03)
uo2.add_nuclide('U238', 0.97)
uo2.add_nuclide('O16', 2.0)
uo2.set_density('g/cm3', 10.0)

zirconium = openmc.Material(name="zirconium")
zirconium.add_element('Zr', 1.0)
zirconium.set_density('g/cm3', 6.6)

water = openmc.Material(name="h2o")
water.add_nuclide('H1', 2.0)
water.add_nuclide('O16', 1.0)
water.set_density('g/cm3', 1.0)
water.add_s_alpha_beta('c_H_in_H2O')

materials = openmc.Materials([uo2, zirconium, water])
# materials = openmc.Materials()
# materials.append(uo2)
# materials += [zirconium, water]
water.remove_nuclide('O16')
water.add_element('O', 1.0)

# Create PuO2 material
puo2 = openmc.Material()
puo2.add_nuclide('Pu239', 0.94)
puo2.add_nuclide('Pu240', 0.06)
puo2.add_nuclide('O16', 2.0)
puo2.set_density('g/cm3', 11.5)

# Create the mixture
mox = openmc.Material.mix_materials([uo2, puo2], [0.97, 0.03], 'wo')

materials.cross_sections = '/Users/sshahbazi/Desktop/Codes/OpenMC/XS/endfb80_hdf5/cross_sections.xml'
materials.export_to_xml()
# !cat materials.xml

sphere = openmc.Sphere(r=1.0)
inside_sphere = -sphere
outside_sphere = +sphere
z_plane = openmc.ZPlane(0)
northern_hemisphere = -sphere & +z_plane

cell = openmc.Cell()
cell.region = northern_hemisphere
# # or...
# cell = openmc.Cell(region=northern_hemisphere)
cell.fill = water

universe = openmc.Universe()
universe.add_cell(cell)
# # this also works
# universe = openmc.Universe(cells=[cell])
universe.plot(width=(2.0, 2.0), origin=(0.0, 0.0, 0.1))
# universe.plot(width=(2.0, 2.0), basis='xz')
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[18], line 17
     14 universe.add_cell(cell)
     15 # # this also works
     16 # universe = openmc.Universe(cells=[cell])
---> 17 universe.plot(width=(2.0, 2.0), origin=(0.0, 0.0, 0.1))
     18 # universe.plot(width=(2.0, 2.0), basis='xz')

File ~/miniconda3/envs/openmc/lib/python3.11/site-packages/openmc/universe.py:358, in Universe.plot(self, origin, width, pixels, basis, color_by, colors, seed, openmc_exec, axes, **kwargs)
    355 model.plots.append(plot)
    357 # Run OpenMC in geometry plotting mode
--> 358 model.plot_geometry(False, cwd=tmpdir, openmc_exec=openmc_exec)
    360 # Read image from file
    361 img_path = Path(tmpdir) / f'plot_{plot.id}.png'

File ~/miniconda3/envs/openmc/lib/python3.11/site-packages/openmc/model/model.py:705, in Model.plot_geometry(self, output, cwd, openmc_exec)
    703 else:
    704     self.export_to_xml()
--> 705     openmc.plot_geometry(output=output, openmc_exec=openmc_exec)

File ~/miniconda3/envs/openmc/lib/python3.11/site-packages/openmc/executor.py:139, in plot_geometry(output, openmc_exec, cwd)
    121 def plot_geometry(output=True, openmc_exec='openmc', cwd='.'):
    122     """Run OpenMC in plotting mode
    123 
    124     Parameters
   (...)
    137 
    138     """
--> 139     _run([openmc_exec, '-p'], output, cwd)

File ~/miniconda3/envs/openmc/lib/python3.11/site-packages/openmc/executor.py:118, in _run(args, output, cwd)
    115     error_msg = 'OpenMC aborted unexpectedly.'
    116 error_msg = ' '.join(error_msg.split())
--> 118 raise RuntimeError(error_msg)

RuntimeError: OpenMC aborted unexpectedly.

I think plotting geometry when using Jupyter notebook is a common issue - I had it too and haven’t yet found a fix. There was a discussion here and someone apparently fixed it but I couldn’t get it to work so I’m running through docker instead now. OpenMC 'aborts unexpectedly' when plotting - #11 by madhofs

Does somebody have a fix for this? With conda, I get the libpng mismatch (1.4.12 vs 1.6.39 ) error during plotting and with the source installation I get the same error as shayan.