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. Before defining a material, we must create nuclides that are used in the material.

In [2]:
# Instantiate some Nuclides
h1 = openmc.Nuclide('H1')
b10 = openmc.Nuclide('B10')
o16 = openmc.Nuclide('O16')
u235 = openmc.Nuclide('U235')
u238 = openmc.Nuclide('U238')
zr90 = openmc.Nuclide('Zr90')

With the nuclides we defined, we will now create three materials for the fuel, water, and cladding of the fuel pin.

In [3]:
# 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 [4]:
# 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 [5]:
# 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
# Use both reflective and vacuum boundaries to make life interesting
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 [6]:
# 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 [7]:
# 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 [8]:
# Create Geometry and set root Universe
geometry = openmc.Geometry()
geometry.root_universe = root_universe
In [9]:
# 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 [10]:
# 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 [11]:
# 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 = 'mat'

# 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 [12]:
# Run openmc in plotting mode
openmc.plot_geometry(output=False)
Out[12]:
0
In [13]:
# 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[13]:

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 [14]:
# Instantiate an empty Tallies object
tallies_file = openmc.Tallies()
In [15]:
# 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 [16]:
# 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 [17]:
# Run OpenMC!
openmc.run()
                               %%%%%%%%%%%%%%%
                          %%%%%%%%%%%%%%%%%%%%%%%%
                       %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                                   %%%%%%%%%%%%%%%%%%%%%%%%
                                    %%%%%%%%%%%%%%%%%%%%%%%%
                ###############      %%%%%%%%%%%%%%%%%%%%%%%%
               ##################     %%%%%%%%%%%%%%%%%%%%%%%
               ###################     %%%%%%%%%%%%%%%%%%%%%%%
               ####################     %%%%%%%%%%%%%%%%%%%%%%
               #####################     %%%%%%%%%%%%%%%%%%%%%
               ######################     %%%%%%%%%%%%%%%%%%%%
               #######################     %%%%%%%%%%%%%%%%%%
                #######################     %%%%%%%%%%%%%%%%%
                ######################     %%%%%%%%%%%%%%%%%
                 ####################     %%%%%%%%%%%%%%%%%
                   #################     %%%%%%%%%%%%%%%%%
                    ###############     %%%%%%%%%%%%%%%%
                      ############     %%%%%%%%%%%%%%%
                         ########     %%%%%%%%%%%%%%
                                     %%%%%%%%%%%

                   | The OpenMC Monte Carlo Code
         Copyright | 2011-2016 Massachusetts Institute of Technology
           License | http://openmc.readthedocs.io/en/latest/license.html
           Version | 0.8.0
          Git SHA1 | da5563eddb5f2c2d6b2c9839d518de40962b78f2
         Date/Time | 2016-10-31 12:47:14
    OpenMP Threads | 4

 ===========================================================================
 ========================>     INITIALIZATION     <=========================
 ===========================================================================

 Reading settings XML file...
 Reading geometry XML file...
 Reading materials XML file...
 Reading cross sections XML file...
 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...
 Building neighboring cells lists for each surface...
 Initializing source particles...

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

  Bat./Gen.      k            Average k         
  =========   ========   ====================   
        1/1    1.04359                       
        2/1    1.04244                       
        3/1    1.03020                       
        4/1    1.03630                       
        5/1    1.06478                       
        6/1    1.05450                       
        7/1    1.02369                       
        8/1    1.03454                       
        9/1    1.05309                       
       10/1    1.01741                       
       11/1    1.04344                       
       12/1    1.01457    1.02901 +/- 0.01444
       13/1    1.01643    1.02481 +/- 0.00933
       14/1    1.04657    1.03025 +/- 0.00855
       15/1    1.06420    1.03704 +/- 0.00949
       16/1    1.06048    1.04095 +/- 0.00867
       17/1    1.01627    1.03742 +/- 0.00813
       18/1    1.03667    1.03733 +/- 0.00705
       19/1    1.03977    1.03760 +/- 0.00622
       20/1    1.03996    1.03784 +/- 0.00557
       21/1    1.05663    1.03954 +/- 0.00532
       22/1    1.03944    1.03954 +/- 0.00485
       23/1    1.07702    1.04242 +/- 0.00532
       24/1    1.02378    1.04109 +/- 0.00510
       25/1    1.02817    1.04023 +/- 0.00482
       26/1    1.08000    1.04271 +/- 0.00515
       27/1    1.02733    1.04181 +/- 0.00492
       28/1    1.02993    1.04115 +/- 0.00469
       29/1    1.01755    1.03991 +/- 0.00461
       30/1    1.05836    1.04083 +/- 0.00447
       31/1    1.05936    1.04171 +/- 0.00434
       32/1    1.03683    1.04149 +/- 0.00414
       33/1    1.05112    1.04191 +/- 0.00398
       34/1    1.02927    1.04138 +/- 0.00385
       35/1    1.05326    1.04186 +/- 0.00372
       36/1    1.06014    1.04256 +/- 0.00364
       37/1    1.02320    1.04184 +/- 0.00358
       38/1    1.04297    1.04188 +/- 0.00345
       39/1    1.04544    1.04201 +/- 0.00333
       40/1    1.05178    1.04233 +/- 0.00323
       41/1    1.01744    1.04153 +/- 0.00323
       42/1    1.02376    1.04097 +/- 0.00317
       43/1    1.02344    1.04044 +/- 0.00312
       44/1    1.05813    1.04096 +/- 0.00307
       45/1    1.02370    1.04047 +/- 0.00303
       46/1    1.03536    1.04033 +/- 0.00294
       47/1    1.04344    1.04041 +/- 0.00286
       48/1    1.03879    1.04037 +/- 0.00279
       49/1    1.07122    1.04116 +/- 0.00283
       50/1    1.03861    1.04110 +/- 0.00276
       51/1    1.00812    1.04029 +/- 0.00281
       52/1    1.04620    1.04043 +/- 0.00274
       53/1    1.07050    1.04113 +/- 0.00277
       54/1    1.04038    1.04111 +/- 0.00270
       55/1    1.03770    1.04104 +/- 0.00264
       56/1    1.05627    1.04137 +/- 0.00261
       57/1    1.04191    1.04138 +/- 0.00255
       58/1    1.03633    1.04128 +/- 0.00250
       59/1    1.02002    1.04084 +/- 0.00249
       60/1    1.04293    1.04088 +/- 0.00244
       61/1    1.00919    1.04026 +/- 0.00247
       62/1    1.09274    1.04127 +/- 0.00262
       63/1    1.05344    1.04150 +/- 0.00258
       64/1    1.07892    1.04219 +/- 0.00263
       65/1    1.09293    1.04312 +/- 0.00274
       66/1    1.04485    1.04315 +/- 0.00269
       67/1    1.04794    1.04323 +/- 0.00264
       68/1    1.04183    1.04321 +/- 0.00260
       69/1    1.03052    1.04299 +/- 0.00256
       70/1    1.03630    1.04288 +/- 0.00252
       71/1    1.04611    1.04293 +/- 0.00248
       72/1    1.00214    1.04228 +/- 0.00253
       73/1    1.02488    1.04200 +/- 0.00250
       74/1    1.03607    1.04191 +/- 0.00246
       75/1    1.05488    1.04211 +/- 0.00243
       76/1    1.02252    1.04181 +/- 0.00242
       77/1    1.03196    1.04166 +/- 0.00238
       78/1    1.05769    1.04190 +/- 0.00236
       79/1    1.03101    1.04174 +/- 0.00233
       80/1    1.04693    1.04182 +/- 0.00230
       81/1    1.06110    1.04209 +/- 0.00228
       82/1    1.06273    1.04237 +/- 0.00227
       83/1    1.07699    1.04285 +/- 0.00229
       84/1    1.05740    1.04304 +/- 0.00226
       85/1    1.04040    1.04301 +/- 0.00223
       86/1    1.02147    1.04273 +/- 0.00222
       87/1    1.00842    1.04228 +/- 0.00224
       88/1    1.06173    1.04253 +/- 0.00222
       89/1    1.08649    1.04309 +/- 0.00227
       90/1    1.05826    1.04328 +/- 0.00224
       91/1    1.07673    1.04369 +/- 0.00225
       92/1    1.02425    1.04345 +/- 0.00224
       93/1    1.05359    1.04357 +/- 0.00222
       94/1    1.06085    1.04378 +/- 0.00220
       95/1    1.05319    1.04389 +/- 0.00218
       96/1    1.02321    1.04365 +/- 0.00216
       97/1    1.04124    1.04362 +/- 0.00214
       98/1    1.06307    1.04384 +/- 0.00213
       99/1    1.04616    1.04387 +/- 0.00210
      100/1    1.03278    1.04375 +/- 0.00208
 Creating state point statepoint.100.h5...

 ===========================================================================
 ======================>     SIMULATION FINISHED     <======================
 ===========================================================================


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

 Total time for initialization     =  5.3314E-01 seconds
   Reading cross sections          =  3.6117E-01 seconds
 Total time in simulation          =  3.5193E+02 seconds
   Time in transport only          =  3.5172E+02 seconds
   Time in inactive batches        =  4.7990E+00 seconds
   Time in active batches          =  3.4714E+02 seconds
   Time synchronizing fission bank =  2.3264E-02 seconds
     Sampling source sites         =  1.6661E-02 seconds
     SEND/RECV source sites        =  6.3975E-03 seconds
   Time accumulating tallies       =  2.3345E-02 seconds
 Total time for finalization       =  1.7400E-01 seconds
 Total time elapsed                =  3.5269E+02 seconds
 Calculation Rate (inactive)       =  10418.8 neutrons/second
 Calculation Rate (active)         =  1296.32 neutrons/second

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

 k-effective (Collision)     =  1.04220 +/-  0.00169
 k-effective (Track-length)  =  1.04375 +/-  0.00208
 k-effective (Absorption)    =  1.04213 +/-  0.00151
 Combined k-effective        =  1.04229 +/-  0.00127
 Leakage Fraction            =  0.00000 +/-  0.00000

Out[17]:
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 [18]:
# 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 [19]:
tally = sp.get_tally(scores=['flux'])
print(tally)
Tally
	ID             =	10000
	Name           =	flux
	Filters        =	
                		MeshFilter	[10000]
	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 [20]:
tally.sum
Out[20]:
array([[[ 0.41167874,  0.        ]],

       [[ 0.40853332,  0.        ]],

       [[ 0.41140779,  0.        ]],

       ..., 
       [[ 0.40957563,  0.        ]],

       [[ 0.40983338,  0.        ]],

       [[ 0.40877195,  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 [21]:
print(tally.mean.shape)
(tally.mean, tally.std_dev)
(10000, 1, 2)
Out[21]:
(array([[[ 0.00457421,  0.        ]],
 
        [[ 0.00453926,  0.        ]],
 
        [[ 0.0045712 ,  0.        ]],
 
        ..., 
        [[ 0.00455084,  0.        ]],
 
        [[ 0.0045537 ,  0.        ]],
 
        [[ 0.00454191,  0.        ]]]),
 array([[[  1.84557765e-05,   0.00000000e+00]],
 
        [[  1.71073587e-05,   0.00000000e+00]],
 
        [[  1.76546641e-05,   0.00000000e+00]],
 
        ..., 
        [[  1.82859458e-05,   0.00000000e+00]],
 
        [[  1.80961726e-05,   0.00000000e+00]],
 
        [[  2.01200499e-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 [22]:
flux = tally.get_slice(scores=['flux'])
fission = tally.get_slice(scores=['fission'])
print(flux)
Tally
	ID             =	10001
	Name           =	flux
	Filters        =	
                		MeshFilter	[10000]
	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 [23]:
flux.std_dev.shape = (100, 100)
flux.mean.shape = (100, 100)
fission.std_dev.shape = (100, 100)
fission.mean.shape = (100, 100)
In [24]:
fig = plt.subplot(121)
fig.imshow(flux.mean)
fig2 = plt.subplot(122)
fig2.imshow(fission.mean)
Out[24]:
<matplotlib.image.AxesImage at 0x7f28799b7ef0>

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 [25]:
# 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 [26]:
sp.source
Out[26]:
array([ (1.0, [-0.04091602298055571, -0.28281765875028614, -0.23969748862718712], [-0.5162507278389928, 0.4979959592686946, 0.6967676876533259], 1167993.2181739977, 0),
       (1.0, [-0.04091602298055571, -0.28281765875028614, -0.23969748862718712], [0.9314318185369252, -0.3421578395220699, 0.12394668317702494], 2076480.0407698506, 0),
       (1.0, [0.07588719867579076, 0.3442630703689722, 0.24037509956303865], [-0.4263739205747279, 0.8745850440707152, -0.23088152923428204], 3435875.6567740417, 0),
       ...,
       (1.0, [-0.2976222011116176, 0.06744830909702038, 0.017418564319938733], [0.5146424164525509, 0.8138247541106745, -0.26987488357492534], 3072272.553085709, 0),
       (1.0, [-0.21734045199173016, -0.10720270103504186, -0.532882255592573], [-0.8802303390142701, -0.22473292046402116, 0.4179589270951574], 5120128.793040418, 0),
       (1.0, [-0.21734045199173016, -0.10720270103504186, -0.532882255592573], [-0.16842874876345693, 0.9852495482818028, 0.030250358683490713], 575131.1093690266, 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 [27]:
sp.source['E']
Out[27]:
array([ 1167993.218174  ,  2076480.04076985,  3435875.65677404, ...,
        3072272.55308571,  5120128.79304042,   575131.10936903])

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 [28]:
# Create log-spaced energy bins from 1 keV to 100 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[28]:
<matplotlib.text.Text at 0x7f2878085908>

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 [29]:
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[29]:
(-0.5, 0.5)