Post Processing

post-processing

This notebook demonstrates some basic post-processing tasks that can be performed with the Python API, such as plotting a 2D mesh tally and plotting neutron source sites from an eigenvalue calculation. The problem we will use is a simple reflected pin-cell.

In [1]:
%matplotlib inline
from IPython.display import Image
import numpy as np
import matplotlib.pyplot as plt

import openmc

Generate Input Files

First we need to define materials that will be used in the problem. We'll create three materials for the fuel, water, and cladding of the fuel pin.

In [2]:
# 1.6 enriched fuel
fuel = openmc.Material(name='1.6% Fuel')
fuel.set_density('g/cm3', 10.31341)
fuel.add_nuclide('U235', 3.7503e-4)
fuel.add_nuclide('U238', 2.2625e-2)
fuel.add_nuclide('O16', 4.6007e-2)

# borated water
water = openmc.Material(name='Borated Water')
water.set_density('g/cm3', 0.740582)
water.add_nuclide('H1', 4.9457e-2)
water.add_nuclide('O16', 2.4732e-2)
water.add_nuclide('B10', 8.0042e-6)

# zircaloy
zircaloy = openmc.Material(name='Zircaloy')
zircaloy.set_density('g/cm3', 6.55)
zircaloy.add_nuclide('Zr90', 7.2758e-3)

With our three materials, we can now create a materials file object that can be exported to an actual XML file.

In [3]:
# Instantiate a Materials collection
materials_file = openmc.Materials([fuel, water, zircaloy])

# Export to "materials.xml"
materials_file.export_to_xml()

Now let's move on to the geometry. Our problem will have three regions for the fuel, the clad, and the surrounding coolant. The first step is to create the bounding surfaces -- in this case two cylinders and six reflective planes.

In [4]:
# Create cylinders for the fuel and clad
fuel_outer_radius = openmc.ZCylinder(x0=0.0, y0=0.0, R=0.39218)
clad_outer_radius = openmc.ZCylinder(x0=0.0, y0=0.0, R=0.45720)

# Create boundary planes to surround the geometry
min_x = openmc.XPlane(x0=-0.63, boundary_type='reflective')
max_x = openmc.XPlane(x0=+0.63, boundary_type='reflective')
min_y = openmc.YPlane(y0=-0.63, boundary_type='reflective')
max_y = openmc.YPlane(y0=+0.63, boundary_type='reflective')
min_z = openmc.ZPlane(z0=-0.63, boundary_type='reflective')
max_z = openmc.ZPlane(z0=+0.63, boundary_type='reflective')

With the surfaces defined, we can now create cells that are defined by intersections of half-spaces created by the surfaces.

In [5]:
# Create a Universe to encapsulate a fuel pin
pin_cell_universe = openmc.Universe(name='1.6% Fuel Pin')

# Create fuel Cell
fuel_cell = openmc.Cell(name='1.6% Fuel')
fuel_cell.fill = fuel
fuel_cell.region = -fuel_outer_radius
pin_cell_universe.add_cell(fuel_cell)

# Create a clad Cell
clad_cell = openmc.Cell(name='1.6% Clad')
clad_cell.fill = zircaloy
clad_cell.region = +fuel_outer_radius & -clad_outer_radius
pin_cell_universe.add_cell(clad_cell)

# Create a moderator Cell
moderator_cell = openmc.Cell(name='1.6% Moderator')
moderator_cell.fill = water
moderator_cell.region = +clad_outer_radius
pin_cell_universe.add_cell(moderator_cell)

OpenMC requires that there is a "root" universe. Let us create a root cell that is filled by the pin cell universe and then assign it to the root universe.

In [6]:
# Create root Cell
root_cell = openmc.Cell(name='root cell')
root_cell.fill = pin_cell_universe

# Add boundary planes
root_cell.region = +min_x & -max_x & +min_y & -max_y & +min_z & -max_z

# Create root Universe
root_universe = openmc.Universe(universe_id=0, name='root universe')
root_universe.add_cell(root_cell)

We now must create a geometry that is assigned a root universe, put the geometry into a geometry file, and export it to XML.

In [7]:
# Create Geometry and set root Universe
geometry = openmc.Geometry(root_universe)
In [8]:
# Export to "geometry.xml"
geometry.export_to_xml()

With the geometry and materials finished, we now just need to define simulation parameters. In this case, we will use 10 inactive batches and 90 active batches each with 5000 particles.

In [9]:
# OpenMC simulation parameters
batches = 100
inactive = 10
particles = 5000

# Instantiate a Settings object
settings_file = openmc.Settings()
settings_file.batches = batches
settings_file.inactive = inactive
settings_file.particles = particles

# Create an initial uniform spatial source distribution over fissionable zones
bounds = [-0.63, -0.63, -0.63, 0.63, 0.63, 0.63]
uniform_dist = openmc.stats.Box(bounds[:3], bounds[3:], only_fissionable=True)
settings_file.source = openmc.source.Source(space=uniform_dist)

# Export to "settings.xml"
settings_file.export_to_xml()

Let us also create a plot file that we can use to verify that our pin cell geometry was created successfully.

In [10]:
# Instantiate a Plot
plot = openmc.Plot(plot_id=1)
plot.filename = 'materials-xy'
plot.origin = [0, 0, 0]
plot.width = [1.26, 1.26]
plot.pixels = [250, 250]
plot.color_by = 'material'

# Instantiate a Plots collection and export to "plots.xml"
plot_file = openmc.Plots([plot])
plot_file.export_to_xml()

With the plots.xml file, we can now generate and view the plot. OpenMC outputs plots in .ppm format, which can be converted into a compressed format like .png with the convert utility.

In [11]:
# Run openmc in plotting mode
openmc.plot_geometry(output=False)
Out[11]:
0
In [12]:
# Convert OpenMC's funky ppm to png
!convert materials-xy.ppm materials-xy.png

# Display the materials plot inline
Image(filename='materials-xy.png')
Out[12]:

As we can see from the plot, we have a nice pin cell with fuel, cladding, and water! Before we run our simulation, we need to tell the code what we want to tally. The following code shows how to create a 2D mesh tally.

In [13]:
# Instantiate an empty Tallies object
tallies_file = openmc.Tallies()
In [14]:
# Create mesh which will be used for tally
mesh = openmc.Mesh()
mesh.dimension = [100, 100]
mesh.lower_left = [-0.63, -0.63]
mesh.upper_right = [0.63, 0.63]

# Create mesh filter for tally
mesh_filter = openmc.MeshFilter(mesh)

# Create mesh tally to score flux and fission rate
tally = openmc.Tally(name='flux')
tally.filters = [mesh_filter]
tally.scores = ['flux', 'fission']
tallies_file.append(tally)
In [15]:
# Export to "tallies.xml"
tallies_file.export_to_xml()

Now we a have a complete set of inputs, so we can go ahead and run our simulation.

In [16]:
# Run OpenMC!
openmc.run()
                               %%%%%%%%%%%%%%%
                          %%%%%%%%%%%%%%%%%%%%%%%%
                       %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                                   %%%%%%%%%%%%%%%%%%%%%%%%
                                    %%%%%%%%%%%%%%%%%%%%%%%%
                ###############      %%%%%%%%%%%%%%%%%%%%%%%%
               ##################     %%%%%%%%%%%%%%%%%%%%%%%
               ###################     %%%%%%%%%%%%%%%%%%%%%%%
               ####################     %%%%%%%%%%%%%%%%%%%%%%
               #####################     %%%%%%%%%%%%%%%%%%%%%
               ######################     %%%%%%%%%%%%%%%%%%%%
               #######################     %%%%%%%%%%%%%%%%%%
                #######################     %%%%%%%%%%%%%%%%%
                ######################     %%%%%%%%%%%%%%%%%
                 ####################     %%%%%%%%%%%%%%%%%
                   #################     %%%%%%%%%%%%%%%%%
                    ###############     %%%%%%%%%%%%%%%%
                      ############     %%%%%%%%%%%%%%%
                         ########     %%%%%%%%%%%%%%
                                     %%%%%%%%%%%

                   | The OpenMC Monte Carlo Code
         Copyright | 2011-2017 Massachusetts Institute of Technology
           License | http://openmc.readthedocs.io/en/latest/license.html
           Version | 0.9.0
          Git SHA1 | 9b7cebf7bc34d60e0f1750c3d6cb103df11e8dc4
         Date/Time | 2017-12-04 20:47:36
    OpenMP Threads | 4

 Reading settings XML file...
 Reading cross sections XML file...
 Reading materials XML file...
 Reading geometry XML file...
 Building neighboring cells lists for each surface...
 Reading U235 from /home/romano/openmc/scripts/nndc_hdf5/U235.h5
 Reading U238 from /home/romano/openmc/scripts/nndc_hdf5/U238.h5
 Reading O16 from /home/romano/openmc/scripts/nndc_hdf5/O16.h5
 Reading H1 from /home/romano/openmc/scripts/nndc_hdf5/H1.h5
 Reading B10 from /home/romano/openmc/scripts/nndc_hdf5/B10.h5
 Reading Zr90 from /home/romano/openmc/scripts/nndc_hdf5/Zr90.h5
 Maximum neutron transport energy: 2.00000E+07 eV for U235
 Reading tallies XML file...
 Writing summary.h5 file...
 Initializing source particles...

 ====================>     K EIGENVALUE SIMULATION     <====================

  Bat./Gen.      k            Average k         
  =========   ========   ====================   
        1/1    1.04359                       
        2/1    1.04323                       
        3/1    1.04711                       
        4/1    1.03892                       
        5/1    1.02442                       
        6/1    1.02046                       
        7/1    1.05998                       
        8/1    1.04184                       
        9/1    1.04786                       
       10/1    1.06636                       
       11/1    1.07229                       
       12/1    1.04413    1.05821 +/- 0.01408
       13/1    1.06376    1.06006 +/- 0.00834
       14/1    1.06898    1.06229 +/- 0.00630
       15/1    1.05095    1.06002 +/- 0.00538
       16/1    1.04453    1.05744 +/- 0.00510
       17/1    1.05626    1.05727 +/- 0.00431
       18/1    1.03423    1.05439 +/- 0.00472
       19/1    1.04240    1.05306 +/- 0.00437
       20/1    1.03719    1.05147 +/- 0.00422
       21/1    1.04308    1.05071 +/- 0.00389
       22/1    1.03956    1.04978 +/- 0.00367
       23/1    1.05824    1.05043 +/- 0.00344
       24/1    1.03151    1.04908 +/- 0.00346
       25/1    1.02695    1.04760 +/- 0.00354
       26/1    1.02581    1.04624 +/- 0.00358
       27/1    1.09932    1.04936 +/- 0.00459
       28/1    1.05983    1.04995 +/- 0.00437
       29/1    1.03381    1.04910 +/- 0.00422
       30/1    1.06727    1.05001 +/- 0.00410
       31/1    1.03180    1.04914 +/- 0.00400
       32/1    1.04520    1.04896 +/- 0.00382
       33/1    1.07158    1.04994 +/- 0.00378
       34/1    1.04283    1.04965 +/- 0.00363
       35/1    1.03272    1.04897 +/- 0.00354
       36/1    1.02730    1.04814 +/- 0.00351
       37/1    1.01975    1.04709 +/- 0.00353
       38/1    1.04815    1.04712 +/- 0.00341
       39/1    1.02642    1.04641 +/- 0.00336
       40/1    1.04063    1.04622 +/- 0.00325
       41/1    0.97384    1.04388 +/- 0.00392
       42/1    1.06049    1.04440 +/- 0.00383
       43/1    1.04467    1.04441 +/- 0.00371
       44/1    1.04454    1.04441 +/- 0.00360
       45/1    1.06529    1.04501 +/- 0.00355
       46/1    1.05496    1.04529 +/- 0.00346
       47/1    1.03717    1.04507 +/- 0.00337
       48/1    1.03874    1.04490 +/- 0.00328
       49/1    1.02083    1.04428 +/- 0.00326
       50/1    1.04847    1.04439 +/- 0.00318
       51/1    1.03789    1.04423 +/- 0.00310
       52/1    1.04447    1.04423 +/- 0.00303
       53/1    1.01942    1.04366 +/- 0.00301
       54/1    1.04639    1.04372 +/- 0.00294
       55/1    1.02539    1.04331 +/- 0.00291
       56/1    1.06312    1.04374 +/- 0.00288
       57/1    1.05854    1.04406 +/- 0.00283
       58/1    1.05150    1.04421 +/- 0.00278
       59/1    1.04321    1.04419 +/- 0.00272
       60/1    1.04762    1.04426 +/- 0.00266
       61/1    0.99442    1.04328 +/- 0.00279
       62/1    1.06907    1.04378 +/- 0.00278
       63/1    1.03170    1.04355 +/- 0.00274
       64/1    1.04308    1.04354 +/- 0.00268
       65/1    1.01439    1.04301 +/- 0.00269
       66/1    1.04581    1.04306 +/- 0.00264
       67/1    1.04404    1.04308 +/- 0.00259
       68/1    1.03158    1.04288 +/- 0.00256
       69/1    1.04953    1.04299 +/- 0.00251
       70/1    1.06338    1.04333 +/- 0.00250
       71/1    1.03768    1.04324 +/- 0.00246
       72/1    1.02531    1.04295 +/- 0.00243
       73/1    1.04552    1.04299 +/- 0.00240
       74/1    1.04293    1.04299 +/- 0.00236
       75/1    1.05928    1.04324 +/- 0.00233
       76/1    1.05057    1.04335 +/- 0.00230
       77/1    1.01846    1.04298 +/- 0.00230
       78/1    1.05755    1.04320 +/- 0.00227
       79/1    1.05222    1.04333 +/- 0.00224
       80/1    1.04860    1.04340 +/- 0.00221
       81/1    1.03026    1.04322 +/- 0.00219
       82/1    1.02360    1.04294 +/- 0.00218
       83/1    1.06679    1.04327 +/- 0.00217
       84/1    1.06297    1.04354 +/- 0.00216
       85/1    1.04426    1.04355 +/- 0.00213
       86/1    1.00337    1.04302 +/- 0.00217
       87/1    1.04787    1.04308 +/- 0.00214
       88/1    1.04332    1.04308 +/- 0.00211
       89/1    1.04369    1.04309 +/- 0.00208
       90/1    1.05006    1.04318 +/- 0.00206
       91/1    1.05394    1.04331 +/- 0.00204
       92/1    1.06017    1.04352 +/- 0.00202
       93/1    1.02032    1.04324 +/- 0.00202
       94/1    1.04816    1.04330 +/- 0.00200
       95/1    1.06601    1.04356 +/- 0.00199
       96/1    1.02876    1.04339 +/- 0.00197
       97/1    1.03929    1.04334 +/- 0.00195
       98/1    1.01958    1.04307 +/- 0.00195
       99/1    1.01899    1.04280 +/- 0.00195
      100/1    1.05150    1.04290 +/- 0.00193
 Creating state point statepoint.100.h5...

 =======================>     TIMING STATISTICS     <=======================

 Total time for initialization     =  6.5927E-01 seconds
   Reading cross sections          =  6.1679E-01 seconds
 Total time in simulation          =  1.2768E+02 seconds
   Time in transport only          =  1.2740E+02 seconds
   Time in inactive batches        =  2.7221E+00 seconds
   Time in active batches          =  1.2496E+02 seconds
   Time synchronizing fission bank =  2.4179E-02 seconds
     Sampling source sites         =  1.7261E-02 seconds
     SEND/RECV source sites        =  6.7268E-03 seconds
   Time accumulating tallies       =  1.5442E-02 seconds
 Total time for finalization       =  1.6664E-01 seconds
 Total time elapsed                =  1.2854E+02 seconds
 Calculation Rate (inactive)       =  18368.1 neutrons/second
 Calculation Rate (active)         =  3601.09 neutrons/second

 ============================>     RESULTS     <============================

 k-effective (Collision)     =  1.04331 +/-  0.00192
 k-effective (Track-length)  =  1.04290 +/-  0.00193
 k-effective (Absorption)    =  1.04136 +/-  0.00151
 Combined k-effective        =  1.04183 +/-  0.00122
 Leakage Fraction            =  0.00000 +/-  0.00000

Out[16]:
0

Tally Data Processing

Our simulation ran successfully and created a statepoint file with all the tally data in it. We begin our analysis here loading the statepoint file and 'reading' the results. By default, data from the statepoint file is only read into memory when it is requested. This helps keep the memory use to a minimum even when a statepoint file may be huge.

In [17]:
# Load the statepoint file
sp = openmc.StatePoint('statepoint.100.h5')

Next we need to get the tally, which can be done with the StatePoint.get_tally(...) method.

In [18]:
tally = sp.get_tally(scores=['flux'])
print(tally)
Tally
	ID             =	1
	Name           =	flux
	Filters        =	MeshFilter
	Nuclides       =	total 
	Scores         =	['flux', 'fission']
	Estimator      =	tracklength

The statepoint file actually stores the sum and sum-of-squares for each tally bin from which the mean and variance can be calculated as described here. The sum and sum-of-squares can be accessed using the sum and sum_sq properties:

In [19]:
tally.sum
Out[19]:
array([[[ 0.40981574,  0.        ]],

       [[ 0.40963388,  0.        ]],

       [[ 0.41117481,  0.        ]],

       ..., 
       [[ 0.41179009,  0.        ]],

       [[ 0.41329412,  0.        ]],

       [[ 0.41494587,  0.        ]]])

However, the mean and standard deviation of the mean are usually what you are more interested in. The Tally class also has properties mean and std_dev which automatically calculate these statistics on-the-fly.

In [20]:
print(tally.mean.shape)
(tally.mean, tally.std_dev)
(10000, 1, 2)
Out[20]:
(array([[[ 0.00455351,  0.        ]],
 
        [[ 0.00455149,  0.        ]],
 
        [[ 0.00456861,  0.        ]],
 
        ..., 
        [[ 0.00457545,  0.        ]],
 
        [[ 0.00459216,  0.        ]],
 
        [[ 0.00461051,  0.        ]]]),
 array([[[  2.00748004e-05,   0.00000000e+00]],
 
        [[  1.75039529e-05,   0.00000000e+00]],
 
        [[  1.96093103e-05,   0.00000000e+00]],
 
        ..., 
        [[  1.69721143e-05,   0.00000000e+00]],
 
        [[  1.58964240e-05,   0.00000000e+00]],
 
        [[  1.81009205e-05,   0.00000000e+00]]]))

The tally data has three dimensions: one for filter combinations, one for nuclides, and one for scores. We see that there are 10000 filter combinations (corresponding to the 100 x 100 mesh bins), a single nuclide (since none was specified), and two scores. If we only want to look at a single score, we can use the get_slice(...) method as follows.

In [21]:
flux = tally.get_slice(scores=['flux'])
fission = tally.get_slice(scores=['fission'])
print(flux)
Tally
	ID             =	2
	Name           =	flux
	Filters        =	MeshFilter
	Nuclides       =	total 
	Scores         =	['flux']
	Estimator      =	tracklength

To get the bins into a form that we can plot, we can simply change the shape of the array since it is a numpy array.

In [22]:
flux.std_dev.shape = (100, 100)
flux.mean.shape = (100, 100)
fission.std_dev.shape = (100, 100)
fission.mean.shape = (100, 100)
In [23]:
fig = plt.subplot(121)
fig.imshow(flux.mean)
fig2 = plt.subplot(122)
fig2.imshow(fission.mean)
Out[23]:
<matplotlib.image.AxesImage at 0x7f4e6fcf8358>

Now let's say we want to look at the distribution of relative errors of our tally bins for flux. First we create a new variable called relative_error and set it to the ratio of the standard deviation and the mean, being careful not to divide by zero in case some bins were never scored to.

In [24]:
# Determine relative error
relative_error = np.zeros_like(flux.std_dev)
nonzero = flux.mean > 0
relative_error[nonzero] = flux.std_dev[nonzero] / flux.mean[nonzero]

# distribution of relative errors
ret = plt.hist(relative_error[nonzero], bins=50)

Source Sites

Source sites can be accessed from the source property. As shown below, the source sites are represented as a numpy array with a structured datatype.

In [25]:
sp.source
Out[25]:
array([ (1.0, [0.08865821621194064, 0.3784631548839458, 0.3904972254761878], [-0.1326194120629367, 0.6232164386612264, 0.7707226233389667], 1192346.6320091304, 0),
       (1.0, [0.08865821621194064, 0.3784631548839458, 0.3904972254761878], [-0.6644604177986176, -0.6182443857504494, 0.41984072297352965], 356616.8122252148, 0),
       (1.0, [-0.0524358478826145, -0.2989344511695743, -0.17188682459930016], [0.26140031911472983, 0.8973965547376798, 0.35545646246996265], 836460.5302888667, 0),
       ...,
       (1.0, [-0.1061743912824093, 0.2687838889464804, 0.3209783107825243], [0.04074864852534854, 0.6722488179526406, -0.7392029994559244], 4419569.703536596, 0),
       (1.0, [-0.1061743912824093, 0.2687838889464804, 0.3209783107825243], [0.2921501228867853, 0.9089796683155593, 0.2973285527596903], 2716068.3317314633, 0),
       (1.0, [0.24742871049665383, 0.2887788071034633, 0.12388141872813332], [0.9088435703078486, -0.040848021273558396, -0.4151322727373983], 1005076.8690394862, 0)], 
      dtype=[('wgt', '<f8'), ('xyz', '<f8', (3,)), ('uvw', '<f8', (3,)), ('E', '<f8'), ('delayed_group', '<i4')])

If we want, say, only the energies from the source sites, we can simply index the source array with the name of the field:

In [26]:
sp.source['E']
Out[26]:
array([ 1192346.63200913,   356616.81222521,   836460.53028887, ...,
        4419569.7035366 ,  2716068.33173146,  1005076.86903949])

Now, we can look at things like the energy distribution of source sites. Note that we don't directly use the matplotlib.pyplot.hist method since our binning is logarithmic.

In [27]:
# Create log-spaced energy bins from 1 keV to 10 MeV
energy_bins = np.logspace(3,7)

# Calculate pdf for source energies
probability, bin_edges = np.histogram(sp.source['E'], energy_bins, density=True)

# Make sure integrating the PDF gives us unity
print(sum(probability*np.diff(energy_bins)))

# Plot source energy PDF
plt.semilogx(energy_bins[:-1], probability*np.diff(energy_bins), linestyle='steps')
plt.xlabel('Energy (eV)')
plt.ylabel('Probability/eV')
1.0
Out[27]:
<matplotlib.text.Text at 0x7f4e6fa81400>

Let's also look at the spatial distribution of the sites. To make the plot a little more interesting, we can also include the direction of the particle emitted from the source and color each source by the logarithm of its energy.

In [28]:
plt.quiver(sp.source['xyz'][:,0], sp.source['xyz'][:,1],
           sp.source['uvw'][:,0], sp.source['uvw'][:,1],
           np.log(sp.source['E']), cmap='jet', scale=20.0)
plt.colorbar()
plt.xlim((-0.5,0.5))
plt.ylim((-0.5,0.5))
Out[28]:
(-0.5, 0.5)