{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Post Processing\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "from IPython.display import Image\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import openmc"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generate Input Files"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1.6 enriched fuel\n",
    "fuel = openmc.Material(name='1.6% Fuel')\n",
    "fuel.set_density('g/cm3', 10.31341)\n",
    "fuel.add_nuclide('U235', 3.7503e-4)\n",
    "fuel.add_nuclide('U238', 2.2625e-2)\n",
    "fuel.add_nuclide('O16', 4.6007e-2)\n",
    "\n",
    "# borated water\n",
    "water = openmc.Material(name='Borated Water')\n",
    "water.set_density('g/cm3', 0.740582)\n",
    "water.add_nuclide('H1', 4.9457e-2)\n",
    "water.add_nuclide('O16', 2.4732e-2)\n",
    "water.add_nuclide('B10', 8.0042e-6)\n",
    "\n",
    "# zircaloy\n",
    "zircaloy = openmc.Material(name='Zircaloy')\n",
    "zircaloy.set_density('g/cm3', 6.55)\n",
    "zircaloy.add_nuclide('Zr90', 7.2758e-3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With our three materials, we can now create a materials file object that can be exported to an actual XML file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Instantiate a Materials collection\n",
    "materials = openmc.Materials([fuel, water, zircaloy])\n",
    "\n",
    "# Export to \"materials.xml\"\n",
    "materials.export_to_xml()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create cylinders for the fuel and clad\n",
    "fuel_outer_radius = openmc.ZCylinder(x0=0.0, y0=0.0, r=0.39218)\n",
    "clad_outer_radius = openmc.ZCylinder(x0=0.0, y0=0.0, r=0.45720)\n",
    "\n",
    "# Create boundary planes to surround the geometry\n",
    "min_x = openmc.XPlane(x0=-0.63, boundary_type='reflective')\n",
    "max_x = openmc.XPlane(x0=+0.63, boundary_type='reflective')\n",
    "min_y = openmc.YPlane(y0=-0.63, boundary_type='reflective')\n",
    "max_y = openmc.YPlane(y0=+0.63, boundary_type='reflective')\n",
    "min_z = openmc.ZPlane(z0=-0.63, boundary_type='reflective')\n",
    "max_z = openmc.ZPlane(z0=+0.63, boundary_type='reflective')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the surfaces defined, we can now create cells that are defined by intersections of half-spaces created by the surfaces."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a Universe to encapsulate a fuel pin\n",
    "pin_cell_universe = openmc.Universe(name='1.6% Fuel Pin')\n",
    "\n",
    "# Create fuel Cell\n",
    "fuel_cell = openmc.Cell(name='1.6% Fuel')\n",
    "fuel_cell.fill = fuel\n",
    "fuel_cell.region = -fuel_outer_radius\n",
    "pin_cell_universe.add_cell(fuel_cell)\n",
    "\n",
    "# Create a clad Cell\n",
    "clad_cell = openmc.Cell(name='1.6% Clad')\n",
    "clad_cell.fill = zircaloy\n",
    "clad_cell.region = +fuel_outer_radius & -clad_outer_radius\n",
    "pin_cell_universe.add_cell(clad_cell)\n",
    "\n",
    "# Create a moderator Cell\n",
    "moderator_cell = openmc.Cell(name='1.6% Moderator')\n",
    "moderator_cell.fill = water\n",
    "moderator_cell.region = +clad_outer_radius\n",
    "pin_cell_universe.add_cell(moderator_cell)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create root Cell\n",
    "root_cell = openmc.Cell(name='root cell')\n",
    "root_cell.fill = pin_cell_universe\n",
    "\n",
    "# Add boundary planes\n",
    "root_cell.region = +min_x & -max_x & +min_y & -max_y & +min_z & -max_z\n",
    "\n",
    "# Create root Universe\n",
    "root_universe = openmc.Universe(universe_id=0, name='root universe')\n",
    "root_universe.add_cell(root_cell)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now must create a geometry that is assigned a root universe, put the geometry into a geometry file, and export it to XML."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create Geometry and set root Universe\n",
    "geometry = openmc.Geometry(root_universe)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Export to \"geometry.xml\"\n",
    "geometry.export_to_xml()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# OpenMC simulation parameters\n",
    "settings = openmc.Settings()\n",
    "settings.batches = 100\n",
    "settings.inactive = 10\n",
    "settings.particles = 5000\n",
    "\n",
    "# Create an initial uniform spatial source distribution over fissionable zones\n",
    "bounds = [-0.63, -0.63, -0.63, 0.63, 0.63, 0.63]\n",
    "uniform_dist = openmc.stats.Box(bounds[:3], bounds[3:], only_fissionable=True)\n",
    "settings.source = openmc.IndependentSource(space=uniform_dist)\n",
    "\n",
    "# Export to \"settings.xml\"\n",
    "settings.export_to_xml()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us also create a plot file that we can use to verify that our pin cell geometry was created successfully."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "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",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "plot = openmc.Plot.from_geometry(geometry)\n",
    "plot.pixels = (250, 250)\n",
    "plot.to_ipython_image()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Instantiate an empty Tallies object\n",
    "tallies = openmc.Tallies()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create mesh which will be used for tally\n",
    "mesh = openmc.RegularMesh()\n",
    "mesh.dimension = [100, 100]\n",
    "mesh.lower_left = [-0.63, -0.63]\n",
    "mesh.upper_right = [0.63, 0.63]\n",
    "\n",
    "# Create mesh filter for tally\n",
    "mesh_filter = openmc.MeshFilter(mesh)\n",
    "\n",
    "# Create mesh tally to score flux and fission rate\n",
    "tally = openmc.Tally(name='flux')\n",
    "tally.filters = [mesh_filter]\n",
    "tally.scores = ['flux', 'fission']\n",
    "tallies.append(tally)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Export to \"tallies.xml\"\n",
    "tallies.export_to_xml()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we a have a complete set of inputs, so we can go ahead and run our simulation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                %%%%%%%%%%%%%%%\n",
      "                           %%%%%%%%%%%%%%%%%%%%%%%%\n",
      "                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n",
      "                      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n",
      "                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n",
      "                   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n",
      "                                    %%%%%%%%%%%%%%%%%%%%%%%%\n",
      "                                     %%%%%%%%%%%%%%%%%%%%%%%%\n",
      "                 ###############      %%%%%%%%%%%%%%%%%%%%%%%%\n",
      "                ##################     %%%%%%%%%%%%%%%%%%%%%%%\n",
      "                ###################     %%%%%%%%%%%%%%%%%%%%%%%\n",
      "                ####################     %%%%%%%%%%%%%%%%%%%%%%\n",
      "                #####################     %%%%%%%%%%%%%%%%%%%%%\n",
      "                ######################     %%%%%%%%%%%%%%%%%%%%\n",
      "                #######################     %%%%%%%%%%%%%%%%%%\n",
      "                 #######################     %%%%%%%%%%%%%%%%%\n",
      "                 ######################     %%%%%%%%%%%%%%%%%\n",
      "                  ####################     %%%%%%%%%%%%%%%%%\n",
      "                    #################     %%%%%%%%%%%%%%%%%\n",
      "                     ###############     %%%%%%%%%%%%%%%%\n",
      "                       ############     %%%%%%%%%%%%%%%\n",
      "                          ########     %%%%%%%%%%%%%%\n",
      "                                      %%%%%%%%%%%\n",
      "\n",
      "                 | The OpenMC Monte Carlo Code\n",
      "       Copyright | 2011-2023 MIT, UChicago Argonne LLC, and contributors\n",
      "         License | https://docs.openmc.org/en/latest/license.html\n",
      "         Version | 0.13.3\n",
      "        Git SHA1 | 50e39a4e20dc9e0f3d7ccf07333f6a5e6c797c8c\n",
      "       Date/Time | 2023-10-27 00:37:10\n",
      "  OpenMP Threads | 8\n",
      "\n",
      " Reading settings XML file...\n",
      " Reading cross sections XML file...\n",
      " Reading materials XML file...\n",
      " Reading geometry XML file...\n",
      " Reading U235 from /opt/xdata/endfb-vii.1-hdf5/neutron/U235.h5\n",
      " Reading U238 from /opt/xdata/endfb-vii.1-hdf5/neutron/U238.h5\n",
      " Reading O16 from /opt/xdata/endfb-vii.1-hdf5/neutron/O16.h5\n",
      " Reading H1 from /opt/xdata/endfb-vii.1-hdf5/neutron/H1.h5\n",
      " Reading B10 from /opt/xdata/endfb-vii.1-hdf5/neutron/B10.h5\n",
      " Reading Zr90 from /opt/xdata/endfb-vii.1-hdf5/neutron/Zr90.h5\n",
      " Minimum neutron data temperature: 294 K\n",
      " Maximum neutron data temperature: 294 K\n",
      " Reading tallies XML file...\n",
      " Preparing distributed cell instances...\n",
      " Reading plot XML file...\n",
      " Writing summary.h5 file...\n",
      " Maximum neutron transport energy: 20000000 eV for U235\n",
      " Initializing source particles...\n",
      "\n",
      " ====================>     K EIGENVALUE SIMULATION     <====================\n",
      "\n",
      "  Bat./Gen.      k            Average k\n",
      "  =========   ========   ====================\n",
      "        1/1    1.05222\n",
      "        2/1    1.04039\n",
      "        3/1    1.02923\n",
      "        4/1    1.03979\n",
      "        5/1    1.03682\n",
      "        6/1    1.05988\n",
      "        7/1    1.04849\n",
      "        8/1    1.02769\n",
      "        9/1    1.08457\n",
      "       10/1    1.07211\n",
      "       11/1    1.03089\n",
      "       12/1    1.04143    1.03616 +/- 0.00527\n",
      "       13/1    1.05918    1.04383 +/- 0.00825\n",
      "       14/1    1.02158    1.03827 +/- 0.00806\n",
      "       15/1    1.02379    1.03537 +/- 0.00689\n",
      "       16/1    1.06954    1.04107 +/- 0.00800\n",
      "       17/1    1.05054    1.04242 +/- 0.00690\n",
      "       18/1    1.05444    1.04392 +/- 0.00616\n",
      "       19/1    1.07380    1.04724 +/- 0.00637\n",
      "       20/1    1.05148    1.04767 +/- 0.00571\n",
      "       21/1    1.05985    1.04877 +/- 0.00528\n",
      "       22/1    1.04049    1.04808 +/- 0.00487\n",
      "       23/1    1.00283    1.04460 +/- 0.00567\n",
      "       24/1    1.05393    1.04527 +/- 0.00530\n",
      "       25/1    1.05210    1.04572 +/- 0.00495\n",
      "       26/1    1.01377    1.04373 +/- 0.00504\n",
      "       27/1    1.05674    1.04449 +/- 0.00480\n",
      "       28/1    1.03217    1.04381 +/- 0.00458\n",
      "       29/1    1.05243    1.04426 +/- 0.00435\n",
      "       30/1    1.02943    1.04352 +/- 0.00419\n",
      "       31/1    1.07030    1.04480 +/- 0.00419\n",
      "       32/1    1.05439    1.04523 +/- 0.00402\n",
      "       33/1    1.02710    1.04444 +/- 0.00392\n",
      "       34/1    1.02344    1.04357 +/- 0.00385\n",
      "       35/1    1.04084    1.04346 +/- 0.00370\n",
      "       36/1    1.03818    1.04326 +/- 0.00356\n",
      "       37/1    1.05615    1.04373 +/- 0.00346\n",
      "       38/1    1.03077    1.04327 +/- 0.00336\n",
      "       39/1    1.04828    1.04344 +/- 0.00325\n",
      "       40/1    1.04892    1.04363 +/- 0.00314\n",
      "       41/1    1.04616    1.04371 +/- 0.00304\n",
      "       42/1    1.04568    1.04377 +/- 0.00295\n",
      "       43/1    1.02828    1.04330 +/- 0.00289\n",
      "       44/1    1.02634    1.04280 +/- 0.00285\n",
      "       45/1    1.06308    1.04338 +/- 0.00283\n",
      "       46/1    1.04557    1.04344 +/- 0.00275\n",
      "       47/1    1.06041    1.04390 +/- 0.00271\n",
      "       48/1    1.05813    1.04427 +/- 0.00267\n",
      "       49/1    1.05534    1.04456 +/- 0.00261\n",
      "       50/1    1.04697    1.04462 +/- 0.00255\n",
      "       51/1    1.04793    1.04470 +/- 0.00249\n",
      "       52/1    0.99828    1.04359 +/- 0.00267\n",
      "       53/1    1.01921    1.04303 +/- 0.00266\n",
      "       54/1    1.04030    1.04296 +/- 0.00260\n",
      "       55/1    1.01665    1.04238 +/- 0.00261\n",
      "       56/1    1.05756    1.04271 +/- 0.00258\n",
      "       57/1    1.03523    1.04255 +/- 0.00253\n",
      "       58/1    1.03701    1.04244 +/- 0.00248\n",
      "       59/1    1.05190    1.04263 +/- 0.00243\n",
      "       60/1    1.01668    1.04211 +/- 0.00244\n",
      "       61/1    1.04511    1.04217 +/- 0.00239\n",
      "       62/1    1.01641    1.04167 +/- 0.00240\n",
      "       63/1    1.07012    1.04221 +/- 0.00241\n",
      "       64/1    1.05301    1.04241 +/- 0.00237\n",
      "       65/1    1.06213    1.04277 +/- 0.00236\n",
      "       66/1    1.04220    1.04276 +/- 0.00232\n",
      "       67/1    1.05513    1.04298 +/- 0.00229\n",
      "       68/1    1.01721    1.04253 +/- 0.00229\n",
      "       69/1    1.06447    1.04290 +/- 0.00228\n",
      "       70/1    1.05860    1.04316 +/- 0.00226\n",
      "       71/1    1.01646    1.04273 +/- 0.00226\n",
      "       72/1    1.02675    1.04247 +/- 0.00224\n",
      "       73/1    1.07485    1.04298 +/- 0.00226\n",
      "       74/1    1.03000    1.04278 +/- 0.00224\n",
      "       75/1    1.08164    1.04338 +/- 0.00228\n",
      "       76/1    1.04750    1.04344 +/- 0.00225\n",
      "       77/1    1.02581    1.04318 +/- 0.00223\n",
      "       78/1    1.02560    1.04292 +/- 0.00221\n",
      "       79/1    1.04092    1.04289 +/- 0.00218\n",
      "       80/1    1.03475    1.04277 +/- 0.00215\n",
      "       81/1    1.02949    1.04259 +/- 0.00213\n",
      "       82/1    1.04891    1.04267 +/- 0.00210\n",
      "       83/1    1.06470    1.04298 +/- 0.00209\n",
      "       84/1    1.04634    1.04302 +/- 0.00207\n",
      "       85/1    1.04922    1.04310 +/- 0.00204\n",
      "       86/1    1.02642    1.04288 +/- 0.00203\n",
      "       87/1    1.01690    1.04255 +/- 0.00203\n",
      "       88/1    1.06143    1.04279 +/- 0.00202\n",
      "       89/1    1.05653    1.04296 +/- 0.00200\n",
      "       90/1    1.05543    1.04312 +/- 0.00198\n",
      "       91/1    1.06231    1.04336 +/- 0.00197\n",
      "       92/1    1.04363    1.04336 +/- 0.00194\n",
      "       93/1    0.99681    1.04280 +/- 0.00200\n",
      "       94/1    1.03114    1.04266 +/- 0.00198\n",
      "       95/1    1.07076    1.04299 +/- 0.00199\n",
      "       96/1    1.02145    1.04274 +/- 0.00198\n",
      "       97/1    1.03821    1.04269 +/- 0.00196\n",
      "       98/1    1.04462    1.04271 +/- 0.00193\n",
      "       99/1    0.98538    1.04207 +/- 0.00202\n",
      "      100/1    1.01249    1.04174 +/- 0.00202\n",
      " Creating state point statepoint.100.h5...\n",
      "\n",
      " =======================>     TIMING STATISTICS     <=======================\n",
      "\n",
      " Total time for initialization     = 3.7722e-01 seconds\n",
      "   Reading cross sections          = 3.5999e-01 seconds\n",
      " Total time in simulation          = 6.4525e+01 seconds\n",
      "   Time in transport only          = 6.4430e+01 seconds\n",
      "   Time in inactive batches        = 1.6481e+00 seconds\n",
      "   Time in active batches          = 6.2877e+01 seconds\n",
      "   Time synchronizing fission bank = 4.1304e-02 seconds\n",
      "     Sampling source sites         = 3.5765e-02 seconds\n",
      "     SEND/RECV source sites        = 5.4831e-03 seconds\n",
      "   Time accumulating tallies       = 6.4451e-03 seconds\n",
      "   Time writing statepoints        = 6.7978e-03 seconds\n",
      " Total time for finalization       = 2.4647e-02 seconds\n",
      " Total time elapsed                = 6.4937e+01 seconds\n",
      " Calculation Rate (inactive)       = 30338.1 particles/second\n",
      " Calculation Rate (active)         = 7156.83 particles/second\n",
      "\n",
      " ============================>     RESULTS     <============================\n",
      "\n",
      " k-effective (Collision)     = 1.04170 +/- 0.00181\n",
      " k-effective (Track-length)  = 1.04174 +/- 0.00202\n",
      " k-effective (Absorption)    = 1.04258 +/- 0.00148\n",
      " Combined k-effective        = 1.04225 +/- 0.00127\n",
      " Leakage Fraction            = 0.00000 +/- 0.00000\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Run OpenMC!\n",
    "openmc.run()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tally Data Processing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Load the statepoint file\n",
    "sp = openmc.StatePoint('statepoint.100.h5')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next we need to get the tally, which can be done with the ``StatePoint.get_tally(...)`` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tally\n",
      "\tID             =\t1\n",
      "\tName           =\tflux\n",
      "\tFilters        =\tMeshFilter\n",
      "\tNuclides       =\ttotal\n",
      "\tScores         =\t['flux', 'fission']\n",
      "\tEstimator      =\ttracklength\n"
     ]
    }
   ],
   "source": [
    "tally = sp.get_tally(scores=['flux'])\n",
    "print(tally)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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](../methods/tallies.rst#variance). The sum and sum-of-squares can be accessed using the ``sum`` and ``sum_sq`` properties:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[0.4111205 , 0.        ]],\n",
       "\n",
       "       [[0.41061575, 0.        ]],\n",
       "\n",
       "       [[0.40986744, 0.        ]],\n",
       "\n",
       "       ...,\n",
       "\n",
       "       [[0.40879612, 0.        ]],\n",
       "\n",
       "       [[0.40832871, 0.        ]],\n",
       "\n",
       "       [[0.4118188 , 0.        ]]])"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tally.sum"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(10000, 1, 2)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(array([[[0.00456801, 0.        ]],\n",
       " \n",
       "        [[0.0045624 , 0.        ]],\n",
       " \n",
       "        [[0.00455408, 0.        ]],\n",
       " \n",
       "        ...,\n",
       " \n",
       "        [[0.00454218, 0.        ]],\n",
       " \n",
       "        [[0.00453699, 0.        ]],\n",
       " \n",
       "        [[0.00457576, 0.        ]]]),\n",
       " array([[[1.93546369e-05, 0.00000000e+00]],\n",
       " \n",
       "        [[1.65551573e-05, 0.00000000e+00]],\n",
       " \n",
       "        [[1.67835932e-05, 0.00000000e+00]],\n",
       " \n",
       "        ...,\n",
       " \n",
       "        [[1.66301983e-05, 0.00000000e+00]],\n",
       " \n",
       "        [[1.72553624e-05, 0.00000000e+00]],\n",
       " \n",
       "        [[2.05457818e-05, 0.00000000e+00]]]))"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(tally.mean.shape)\n",
    "(tally.mean, tally.std_dev)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tally\n",
      "\tID             =\t2\n",
      "\tName           =\tflux\n",
      "\tFilters        =\tMeshFilter\n",
      "\tNuclides       =\ttotal\n",
      "\tScores         =\t['flux']\n",
      "\tEstimator      =\ttracklength\n"
     ]
    }
   ],
   "source": [
    "flux = tally.get_slice(scores=['flux'])\n",
    "fission = tally.get_slice(scores=['fission'])\n",
    "print(flux)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "flux.std_dev.shape = (100, 100)\n",
    "flux.mean.shape = (100, 100)\n",
    "fission.std_dev.shape = (100, 100)\n",
    "fission.mean.shape = (100, 100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.image.AxesImage at 0x7fa8e8328e90>"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 162484 characters]",
      "text/plain": [
       "<Figure size 640x480 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.subplot(121)\n",
    "fig.imshow(flux.mean)\n",
    "fig2 = plt.subplot(122)\n",
    "fig2.imshow(fission.mean)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 13340 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Determine relative error\n",
    "relative_error = np.zeros_like(flux.std_dev)\n",
    "nonzero = flux.mean > 0\n",
    "relative_error[nonzero] = flux.std_dev[nonzero] / flux.mean[nonzero]\n",
    "\n",
    "# distribution of relative errors\n",
    "ret = plt.hist(relative_error[nonzero], bins=50)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Source Sites"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([((-0.12818551, -0.02456422, -0.43456403), (-0.20124308, -0.34203958,  0.91788352),  588725.34961317, 0.00346319, 1., 0, 0, 0),\n",
       "       ((-0.12818551, -0.02456422, -0.43456403), ( 0.99676617,  0.06738748,  0.04377356),  657059.3168882 , 0.00346319, 1., 0, 0, 0),\n",
       "       ((-0.0502791 , -0.06303921, -0.38288257), ( 0.70313303,  0.69627789, -0.14422568), 2108371.03927001, 0.00345503, 1., 0, 0, 0),\n",
       "       ...,\n",
       "       (( 0.13635569,  0.32155735, -0.58994963), ( 0.60831647, -0.26563692, -0.74792252),  739853.29331269, 0.00379888, 1., 0, 0, 0),\n",
       "       (( 0.30552009, -0.14951375, -0.34244787), (-0.97198566,  0.18342182,  0.14697046), 2602839.75269266, 0.00385486, 1., 0, 0, 0),\n",
       "       (( 0.30552009, -0.14951375, -0.34244787), (-0.71257365, -0.2228104 , -0.66527762), 1669685.00527709, 0.00385486, 1., 0, 0, 0)],\n",
       "      dtype={'names': ['r', 'u', 'E', 'time', 'wgt', 'delayed_group', 'surf_id', 'particle'], 'formats': [[('x', '<f8'), ('y', '<f8'), ('z', '<f8')], [('x', '<f8'), ('y', '<f8'), ('z', '<f8')], '<f8', '<f8', '<f8', '<i4', '<i4', '<i4'], 'offsets': [0, 24, 48, 56, 64, 72, 76, 80], 'itemsize': 104})"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sp.source"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we want, say, only the energies from the source sites, we can simply index the source array with the name of the field:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 588725.34961317,  657059.3168882 , 2108371.03927001, ...,\n",
       "        739853.29331269, 2602839.75269266, 1669685.00527709])"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sp.source['E']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9999999999999999\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Probability/eV')"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 19352 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Create log-spaced energy bins from 1 keV to 10 MeV\n",
    "energy_bins = np.logspace(3,7)\n",
    "\n",
    "# Calculate pdf for source energies\n",
    "probability, bin_edges = np.histogram(sp.source['E'], energy_bins, density=True)\n",
    "\n",
    "# Make sure integrating the PDF gives us unity\n",
    "print(sum(probability*np.diff(energy_bins)))\n",
    "\n",
    "# Plot source energy PDF\n",
    "plt.semilogx(energy_bins[:-1], probability*np.diff(energy_bins), drawstyle='steps')\n",
    "plt.xlabel('Energy (eV)')\n",
    "plt.ylabel('Probability/eV')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(-0.5, 0.5)"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 316352 characters]",
      "text/plain": [
       "<Figure size 640x480 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.quiver(sp.source['r']['x'], sp.source['r']['y'],\n",
    "           sp.source['u']['x'], sp.source['u']['y'],\n",
    "           np.log(sp.source['E']), cmap='jet', scale=20.0)\n",
    "plt.colorbar()\n",
    "plt.xlim((-0.5,0.5))\n",
    "plt.ylim((-0.5,0.5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Close the statepoint file as a matter of best practice\n",
    "sp.close()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
