Merge pull request #964 from paulromano/unit-tests

Expand unit test suite and report coverage
This commit is contained in:
Sterling Harper 2018-02-05 18:08:30 -05:00 committed by GitHub
commit 2d73fd76ea
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
545 changed files with 2760 additions and 2104 deletions

2
.gitignore vendored
View file

@ -101,3 +101,5 @@ examples/jupyter/plots
.cache/
.tox/
.python-version
.coverage
htmlcov

View file

@ -18,29 +18,27 @@ env:
global:
- FC=gfortran
- MPI_DIR=/usr
- PHDF5_DIR=/usr
- HDF5_DIR=/usr
- HDF5_ROOT=/usr
- OMP_NUM_THREADS=2
- OPENMC_CROSS_SECTIONS=$HOME/nndc_hdf5/cross_sections.xml
- OPENMC_ENDF_DATA=$HOME/endf-b-vii.1
- OPENMC_MULTIPOLE_LIBRARY=$HOME/multipole_lib
- PATH=$PATH:$HOME/NJOY2016/build
- DISPLAY=:99.0
matrix:
- OPENMC_CONFIG="^hdf5-debug$"
- OPENMC_CONFIG="^omp-hdf5-debug$"
- OPENMC_CONFIG="^mpi-hdf5-debug$"
- OPENMC_CONFIG="^phdf5-debug$"
- OMP=n MPI=n PHDF5=n
- OMP=y MPI=n PHDF5=n
- OMP=n MPI=y PHDF5=n
- OMP=n MPI=y PHDF5=y
before_install:
- sudo add-apt-repository ppa:nschloe/hdf5-backports -y
- sudo apt-get update -q
- sudo apt-get install libhdf5-serial-dev libhdf5-mpich-dev -y
install:
- ./tools/ci/travis-install.sh
before_script:
- ./tools/ci/travis-before-script.sh
script:
- ./tools/ci/travis-script.sh
after_success:
- coveralls

View file

@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR)
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(openmc Fortran C CXX)
# Setup output directories
@ -21,11 +21,6 @@ if (${UNIX})
add_definitions(-DUNIX)
endif()
# Set MACOSX_RPATH
if(POLICY CMP0042)
cmake_policy(SET CMP0042 NEW)
endif()
#===============================================================================
# Command line options
#===============================================================================
@ -506,68 +501,3 @@ install(TARGETS ${program} libopenmc
install(DIRECTORY src/relaxng DESTINATION share/openmc)
install(FILES man/man1/openmc.1 DESTINATION share/man/man1)
install(FILES LICENSE DESTINATION "share/doc/${program}" RENAME copyright)
find_package(PythonInterp)
if(PYTHONINTERP_FOUND)
if(debian)
install(CODE "execute_process(
COMMAND ${PYTHON_EXECUTABLE} setup.py install
--root=debian/openmc --install-layout=deb
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})")
else()
install(CODE "set(ENV{PYTHONPATH} \"${CMAKE_INSTALL_PREFIX}/lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages\")")
install(CODE "execute_process(
COMMAND ${PYTHON_EXECUTABLE} setup.py install
--prefix=${CMAKE_INSTALL_PREFIX}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})")
endif()
endif()
#===============================================================================
# Regression tests
#===============================================================================
# This allows for dashboard configuration
include(CTest)
# Get a list of all the tests to run
file(GLOB_RECURSE TESTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_*.py)
# Loop through all the tests
foreach(test ${TESTS})
# Remove unit tests
if(test MATCHES ".*unit_tests.*")
continue()
endif()
# Get test information
get_filename_component(TEST_NAME ${test} NAME)
get_filename_component(TEST_PATH ${test} PATH)
if (DEFINED ENV{MEM_CHECK})
# Generate input files if needed
if (NOT EXISTS "${TEST_PATH}/geometry.xml")
execute_process(COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --build-inputs
WORKING_DIRECTORY ${TEST_PATH})
endif()
# Add serial test
add_test(NAME ${TEST_NAME}
WORKING_DIRECTORY ${TEST_PATH}
COMMAND $<TARGET_FILE:openmc>)
else()
# Check serial/parallel
if (${MPI_ENABLED})
# Preform a parallel test
add_test(NAME ${TEST_NAME}
WORKING_DIRECTORY ${TEST_PATH}
COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --exe $<TARGET_FILE:openmc>
--mpi_exec ${MPI_DIR}/mpiexec)
else()
# Perform a serial test
add_test(NAME ${TEST_NAME}
WORKING_DIRECTORY ${TEST_PATH}
COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --exe $<TARGET_FILE:openmc>)
endif()
endif()
endforeach(test)

View file

@ -27,8 +27,9 @@ except ImportError:
MOCK_MODULES = ['numpy', 'numpy.polynomial', 'numpy.polynomial.polynomial',
'numpy.ctypeslib', 'scipy', 'scipy.sparse', 'scipy.interpolate',
'scipy.integrate', 'scipy.optimize', 'scipy.special',
'scipy.stats', 'h5py', 'pandas', 'uncertainties', 'matplotlib',
'matplotlib.pyplot','openmoc', 'openmc.data.reconstruct']
'scipy.stats', 'scipy.spatial', 'h5py', 'pandas', 'uncertainties',
'matplotlib', 'matplotlib.pyplot','openmoc',
'openmc.data.reconstruct']
sys.modules.update((mod_name, MagicMock()) for mod_name in MOCK_MODULES)
import numpy as np

View file

@ -10,9 +10,10 @@ as debugging.
.. toctree::
:numbered:
:maxdepth: 3
:maxdepth: 2
styleguide
workflow
tests
user-input
docbuild

View file

@ -0,0 +1,73 @@
.. _devguide_tests:
==========
Test Suite
==========
Running Tests
-------------
The OpenMC test suite consists of two parts, a regression test suite and a unit
test suite. The regression test suite is based on regression or integrated
testing where different types of input files are configured and the full OpenMC
code is executed. Results from simulations are compared with expected
results. The unit tests are primarily intended to test individual
functions/classes in the OpenMC Python API.
The test suite relies on the third-party `pytest <https://pytest.org>`_
package. To run either or both the regression and unit test suites, it is
assumed that you have OpenMC fully installed, i.e., the :ref:`scripts_openmc`
executable is available on your :envvar:`PATH` and the :mod:`openmc` Python
module is importable. In development where it would be onerous to continually
install OpenMC every time a small change is made, it is recommended to install
OpenMC in development/editable mode. With setuptools, this is accomplished by
running::
python setup.py develop
or using pip (recommended)::
pip install -e .[test]
It is also assumed that you have cross section data available that is pointed to
by the :envvar:`OPENMC_CROSS_SECTIONS` and :envvar:`OPENMC_MULTIPOLE_LIBRARY`
environment variables. Furthermore, to run unit tests for the :mod:`openmc.data`
module, it is necessary to have ENDF/B-VII.1 data available and pointed to by
the :envvar:`OPENMC_ENDF_DATA` environment variable. All data sources can be
obtained using the ``tools/ci/travis-before-script.sh`` script.
To execute the test suite, go to the ``tests/`` directory and run::
pytest
If you want to collect information about source line coverage in the Python API,
you must have the `pytest-cov <https://pypi.python.org/pypi/pytest-cov>`_ plugin
installed and run::
pytest --cov=../openmc --cov-report=html
Adding Tests to the Regression Suite
------------------------------------
To add a new test to the regression test suite, create a sub-directory in the
``tests/regression_tests/`` directory. To configure a test you need to add the
following files to your new test directory:
* OpenMC input XML files, if they are not generated through the Python API
* **test.py** - Python test driver script; please refer to other tests to
see how to construct. Any output files that are generated during testing
must be removed at the end of this script.
* **inputs_true.dat** - ASCII file that contains Python API-generated XML
files concatenated together. When the test is run, inputs that are
generated are compared to this file.
* **results_true.dat** - ASCII file that contains the expected results from
the test. The file *results_test.dat* is compared to this file during the
execution of the python test driver script. When the above files have been
created, generate a *results_test.dat* file and copy it to this name and
commit. It should be noted that this file should be generated with basic
compiler options during openmc configuration and build (e.g., no MPI, no
debug/optimization).
In addition to this description, please see the various types of tests that are
already included in the test suite to see how to create them. If all is
implemented correctly, the new test will automatically be discovered by pytest.

View file

@ -89,139 +89,6 @@ features and bug fixes. The general steps for contributing are as follows:
6. After the pull request has been thoroughly vetted, it is merged back into the
*develop* branch of mit-crpg/openmc.
.. _test suite:
OpenMC Test Suite
-----------------
The purpose of this test suite is to ensure that OpenMC compiles using various
combinations of compiler flags and options, and that all user input options can
be used successfully without breaking the code. The test suite is comprised of
regression tests where different types of input files are configured and the
full OpenMC code is executed. Results from simulations are compared with
expected results. The test suite is comprised of many build configurations
(e.g. debug, mpi, hdf5) and the actual tests which reside in sub-directories
in the tests directory. We recommend to developers to test their branches
before submitting a formal pull request using gfortran and Intel compilers
if available.
The test suite is designed to integrate with cmake using ctest_. It is
configured to run with cross sections from NNDC_ augmented with 0 K elastic
scattering data for select nuclides as well as multipole data. To download the
proper data, run the following commands:
.. code-block:: sh
wget -O nndc_hdf5.tar.xz $(cat <openmc_root>/.travis.yml | grep anl.box | awk '{print $2}')
tar xJvf nndc_hdf5.tar.xz
export OPENMC_CROSS_SECTIONS=$(pwd)/nndc_hdf5/cross_sections.xml
git clone --branch=master git://github.com/smharper/windowed_multipole_library.git wmp_lib
tar xzvf wmp_lib/multipole_lib.tar.gz
export OPENMC_MULTIPOLE_LIBRARY=$(pwd)/multipole_lib
The test suite can be run on an already existing build using:
.. code-block:: sh
cd build
make test
or
.. code-block:: sh
cd build
ctest
There are numerous ctest_ command line options that can be set to have
more control over which tests are executed.
Before running the test suite python script, the following environmental
variables should be set if the default paths are incorrect:
* **FC** - The command for a Fortran compiler (e.g. gfotran, ifort).
* Default - *gfortran*
* **CC** - The command for a C compiler (e.g. gcc, icc).
* Default - *gcc*
* **CXX** - The command for a C++ compiler (e.g. g++, icpc).
* Default - *g++*
* **MPI_DIR** - The path to the MPI directory.
* Default - */opt/mpich/3.2-gnu*
* **HDF5_DIR** - The path to the HDF5 directory.
* Default - */opt/hdf5/1.8.16-gnu*
* **PHDF5_DIR** - The path to the parallel HDF5 directory.
* Default - */opt/phdf5/1.8.16-gnu*
To run the full test suite, the following command can be executed in the
tests directory:
.. code-block:: sh
python run_tests.py
A subset of build configurations and/or tests can be run. To see how to use
the script run:
.. code-block:: sh
python run_tests.py --help
As an example, say we want to run all tests with debug flags only on tests
that have cone and plot in their name. Also, we would like to run this on
4 processors. We can run:
.. code-block:: sh
python run_tests.py -j 4 -C debug -R "cone|plot"
Note that standard regular expression syntax is used for selecting build
configurations and tests. To print out a list of build configurations, we
can run:
.. code-block:: sh
python run_tests.py -p
Adding tests to test suite
++++++++++++++++++++++++++
To add a new test to the test suite, create a sub-directory in the tests
directory that conforms to the regular expression *test_*. To configure
a test you need to add the following files to your new test directory,
*test_name* for example:
* OpenMC input XML files
* **test_name.py** - Python test driver script, please refer to other
tests to see how to construct. Any output files that are generated
during testing must be removed at the end of this script.
* **inputs_true.dat** - ASCII file that contains Python API-generated XML
files concatenated together. When the test is run, inputs that are
generated are compared to this file.
* **results_true.dat** - ASCII file that contains the expected results
from the test. The file *results_test.dat* is compared to this file
during the execution of the python test driver script. When the
above files have been created, generate a *results_test.dat* file and
copy it to this name and commit. It should be noted that this file
should be generated with basic compiler options during openmc
configuration and build (e.g., no MPI/HDF5, no debug/optimization).
In addition to this description, please see the various types of tests that
are already included in the test suite to see how to create them. If all is
implemented correctly, the new test directory will automatically be added
to the CTest framework.
Private Development
-------------------
@ -236,6 +103,27 @@ changes you've made in your private repository back to mit-crpg/openmc
repository, simply follow the steps above with an extra step of pulling a branch
from your private repository into a public fork.
.. _devguide_editable:
Working in "Development" Mode
-----------------------------
If you are making changes to the Python API during development, it is highly
suggested to install the Python API in development/editable mode using
pip_. From the root directory of the OpenMC repository, run:
.. code-block:: sh
pip install -e .[test]
This installs the OpenMC Python package in `"editable" mode
<https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_ so
that 1) it can be imported from a Python interpreter and 2) any changes made are
immediately reflected in the installed version (that is, you don't need to keep
reinstalling it). While the same effect can be achieved using the
:envvar:`PYTHONPATH` environment variable, this is generally discouraged as it
can interfere with virtual environments.
.. _git: http://git-scm.com/
.. _GitHub: https://github.com/
.. _git flow: http://nvie.com/git-model
@ -247,3 +135,4 @@ from your private repository into a public fork.
.. _Bitbucket: https://bitbucket.org
.. _ctest: http://www.cmake.org/cmake/help/v2.8.12/ctest.html
.. _NNDC: http://www.nndc.bnl.gov/endf/b7.1/acefiles.html
.. _pip: https://pip.pypa.io/en/stable/

View file

@ -57,7 +57,6 @@ are no longer supported.
.. _Personal Package Archive: https://launchpad.net/~paulromano/+archive/staging
.. _APT package manager: https://help.ubuntu.com/community/AptGet/Howto
.. _HDF5: http://www.hdfgroup.org/HDF5/
---------------------------------------
Installing from Source on Ubuntu 15.04+
@ -83,9 +82,12 @@ building and installing OpenMC from source.
Installing from Source on Linux or Mac OS X
-------------------------------------------
All OpenMC source code is hosted on GitHub_. If you have git_, the gfortran_
compiler, CMake_, and HDF5_ installed, you can download and install OpenMC be
entering the following commands in a terminal:
All OpenMC source code is hosted on `GitHub
<https://github.com/mit-crpg/openmc>`_. If you have `git
<https://git-scm.com>`_, the `gcc <https://gcc.gnu.org/>`_ compiler suite,
`CMake <http://www.cmake.org>`_, and `HDF5 <https://www.hdfgroup.org/HDF5/>`_
installed, you can download and install OpenMC be entering the following
commands in a terminal:
.. code-block:: sh
@ -104,11 +106,15 @@ should specify an installation directory where you have write access, e.g.
cmake -DCMAKE_INSTALL_PREFIX=$HOME/.local ..
The :mod:`openmc` Python package must be installed separately. The easiest way
to install it is using `pip <https://pip.pypa.io/en/stable/>`_, which is
included by default in Python 2.7 and Python 3.4+. From the root directory of
the OpenMC distribution/repository, run:
.. code-block:: sh
pip install .
If you want to build a parallel version of OpenMC (using OpenMP or MPI),
directions can be found in the :ref:`detailed installation instructions
<usersguide_build>`.
.. _GitHub: https://github.com/mit-crpg/openmc
.. _git: http://git-scm.com
.. _gfortran: http://gcc.gnu.org/wiki/GFortran
.. _CMake: http://www.cmake.org

View file

@ -6,17 +6,18 @@ Installation and Configuration
.. currentmodule:: openmc
.. _install_conda:
----------------------------------------
Installing on Linux/Mac with conda-forge
----------------------------------------
`Conda <http://conda.pydata.org/docs/>`_ is an open source package management
system and environment management system for installing multiple versions of
software packages and their dependencies and switching easily between
them. `conda-forge <https://conda-forge.github.io/>`_ is a community-led conda
channel of installable packages. For instructions on installing conda, please
consult their `documentation
<http://conda.pydata.org/docs/install/quick.html>`_.
Conda_ is an open source package management system and environment management
system for installing multiple versions of software packages and their
dependencies and switching easily between them. `conda-forge
<https://conda-forge.github.io/>`_ is a community-led conda channel of
installable packages. For instructions on installing conda, please consult their
`documentation <http://conda.pydata.org/docs/install/quick.html>`_.
Once you have `conda` installed on your system, add the `conda-forge` channel to
your configuration with:
@ -38,6 +39,8 @@ It is possible to list all of the versions of OpenMC available on your platform
conda search openmc --channel conda-forge
.. _install_ppa:
-----------------------------
Installing on Ubuntu with PPA
-----------------------------
@ -68,9 +71,11 @@ are no longer supported.
.. _Personal Package Archive: https://launchpad.net/~paulromano/+archive/staging
.. _APT package manager: https://help.ubuntu.com/community/AptGet/Howto
--------------------
Building from Source
--------------------
.. _install_source:
----------------------
Installing from Source
----------------------
.. _prerequisites:
@ -191,8 +196,8 @@ switch to the source of the latest stable release, run the following commands::
git checkout master
.. _GitHub: https://github.com/mit-crpg/openmc
.. _git: http://git-scm.com
.. _ssh: http://en.wikipedia.org/wiki/Secure_Shell
.. _git: https://git-scm.com
.. _ssh: https://en.wikipedia.org/wiki/Secure_Shell
.. _usersguide_build:
@ -258,14 +263,15 @@ should be used:
Compiling with MPI
++++++++++++++++++
To compile with MPI, set the :envvar:`FC` and :envvar:`CC` environment variables
to the path to the MPI Fortran and C wrappers, respectively. For example, in a
bash shell:
To compile with MPI, set the :envvar:`FC`, :envvar:`CC`, and :envvar:`CXX`
environment variables to the path to the MPI Fortran, C, and C++ wrappers,
respectively. For example, in a bash shell:
.. code-block:: sh
export FC=mpif90
export FC=mpifort
export CC=mpicc
export CXX=mpicxx
cmake /path/to/openmc
Note that in many shells, environment variables can be set for a single command,
@ -273,7 +279,7 @@ i.e.
.. code-block:: sh
FC=mpif90 CC=mpicc cmake /path/to/openmc
FC=mpifort CC=mpicc CXX=mpicxx cmake /path/to/openmc
Selecting HDF5 Installation
+++++++++++++++++++++++++++
@ -349,7 +355,7 @@ follows:
.. code-block:: sh
mkdir build && cd build
FC=ifort CC=icc FFLAGS=-mmic cmake -Dopenmp=on ..
FC=ifort CC=icc CXX=icpc FFLAGS=-mmic cmake -Dopenmp=on ..
make
Note that unless an HDF5 build for the Intel Xeon Phi (Knights Corner) is
@ -364,18 +370,54 @@ Testing Build
To run the test suite, you will first need to download a pre-generated cross
section library along with windowed multipole data. Please refer to our
:ref:`test suite` documentation for further details.
:ref:`devguide_tests` documentation for further details.
--------------------
Python Prerequisites
--------------------
---------------------
Installing Python API
---------------------
OpenMC's :ref:`Python API <pythonapi>` works with either Python 2.7 or Python
3.2+. In addition to Python itself, the API relies on a number of third-party
packages. All prerequisites can be installed using `conda
<http://conda.pydata.org/docs/>`_ (recommended), `pip
<https://pip.pypa.io/en/stable/>`_, or through the package manager in most Linux
distributions.
If you installed OpenMC using :ref:`Conda <install_conda>` or :ref:`PPA
<install_ppa>`, no further steps are necessary in order to use OpenMC's
:ref:`Python API <pythonapi>`. However, if you are :ref:`installing from source
<install_source>`, the Python API is not installed by default when ``make
install`` is run because in many situations it doesn't make sense to install a
Python package in the same location as the ``openmc`` executable (for example,
if you are installing the package into a `virtual environment
<https://docs.python.org/3/tutorial/venv.html>`_). The easiest way to install
the :mod:`openmc` Python package is to use pip_, which is included by default in
Python 2.7 and Python 3.4+. From the root directory of the OpenMC
distribution/repository, run:
.. code-block:: sh
pip install .
pip will first check that all :ref:`required third-party packages
<usersguide_python_prereqs>` have been installed, and if they are not present,
they will be installed by downloading the appropriate packages from the Python
Package Index (`PyPI <https://pypi.org/>`_). However, do note that since pip
runs the ``setup.py`` script which requires NumPy, you will have to first
install NumPy:
.. code-block:: sh
pip install numpy
Installing in "Development" Mode
--------------------------------
If you are primarily doing development with OpenMC, it is strongly recommended
to install the Python package in :ref:`"editable" mode <devguide_editable>`.
.. _usersguide_python_prereqs:
Prerequisites
-------------
The Python API works with either Python 2.7 or Python 3.2+. In addition to
Python itself, the API relies on a number of third-party packages. All
prerequisites can be installed using Conda_ (recommended), pip_, or through the
package manager in most Linux distributions.
.. admonition:: Required
:class: error
@ -457,3 +499,5 @@ schemas.xml file in your own OpenMC source directory.
.. _RELAX NG: http://relaxng.org/
.. _NNDC: http://www.nndc.bnl.gov/endf/b7.1/acefiles.html
.. _ctest: http://www.cmake.org/cmake/help/v2.8.12/ctest.html
.. _Conda: https://conda.io/docs/
.. _pip: https://pip.pypa.io/en/stable/

View file

@ -168,8 +168,8 @@ ENDF/B-VII.1. It has the following optional arguments:
This script downloads `ENDF/B-VII.1 ACE data
<http://www.nndc.bnl.gov/endf/b7.1/acefiles.html>`_ from NNDC and converts it to
an HDF5 library for use with OpenMC. This data is used for OpenMC's regression
test suite. This script has the following optional arguments:
an HDF5 library for use with OpenMC. This script has the following optional
arguments:
-b, --batch Suppress standard in

View file

@ -211,14 +211,7 @@ class Cell(IDManagerMixin):
@fill.setter
def fill(self, fill):
if fill is not None:
if isinstance(fill, string_types):
if fill.strip().lower() != 'void':
msg = 'Unable to set Cell ID="{0}" to use a non-Material ' \
'or Universe fill "{1}"'.format(self._id, fill)
raise ValueError(msg)
fill = None
elif isinstance(fill, Iterable):
if isinstance(fill, Iterable):
for i, f in enumerate(fill):
if f is not None:
cv.check_type('cell.fill[i]', f, openmc.Material)

View file

@ -587,7 +587,7 @@ def slab_mg(reps=None, as_macro=True):
# Define the materials file
model.xs_data = xs
model.materials.cross_sections = "../1d_mgxs.h5"
model.materials.cross_sections = "../../1d_mgxs.h5"
# Define surfaces.
# Assembly/Problem Boundary

View file

@ -14,8 +14,9 @@ class Geometry(object):
Parameters
----------
root_universe : openmc.Universe, optional
Root universe which contains all others
root : openmc.Universe or Iterable of openmc.Cell, optional
Root universe which contains all others, or an iterable of cells that
should be used to create a root universe.
Attributes
----------
@ -27,11 +28,17 @@ class Geometry(object):
"""
def __init__(self, root_universe=None):
def __init__(self, root=None):
self._root_universe = None
self._offsets = {}
if root_universe is not None:
self.root_universe = root_universe
if root is not None:
if isinstance(root, openmc.Universe):
self.root_universe = root
else:
univ = openmc.Universe()
for cell in root:
univ.add_cell(cell)
self._root_universe = univ
@property
def root_universe(self):
@ -249,7 +256,7 @@ class Geometry(object):
for cell in self.get_all_cells().values():
if cell.fill_type == 'lattice':
if cell.fill not in lattices:
if cell.fill.id not in lattices:
lattices[cell.fill.id] = cell.fill
return lattices
@ -306,9 +313,7 @@ class Geometry(object):
elif not matching and name in material_name:
materials.add(material)
materials = list(materials)
materials.sort(key=lambda x: x.id)
return materials
return sorted(materials, key=lambda x: x.id)
def get_cells_by_name(self, name, case_sensitive=False, matching=False):
"""Return a list of cells with matching names.
@ -346,9 +351,7 @@ class Geometry(object):
elif not matching and name in cell_name:
cells.add(cell)
cells = list(cells)
cells.sort(key=lambda x: x.id)
return cells
return sorted(cells, key=lambda x: x.id)
def get_cells_by_fill_name(self, name, case_sensitive=False, matching=False):
"""Return a list of cells with fills with matching names.
@ -393,9 +396,7 @@ class Geometry(object):
elif not matching and name in fill_name:
cells.add(cell)
cells = list(cells)
cells.sort(key=lambda x: x.id)
return cells
return sorted(cells, key=lambda x: x.id)
def get_universes_by_name(self, name, case_sensitive=False, matching=False):
"""Return a list of universes with matching names.
@ -433,9 +434,7 @@ class Geometry(object):
elif not matching and name in universe_name:
universes.add(universe)
universes = list(universes)
universes.sort(key=lambda x: x.id)
return universes
return sorted(universes, key=lambda x: x.id)
def get_lattices_by_name(self, name, case_sensitive=False, matching=False):
"""Return a list of lattices with matching names.
@ -473,9 +472,7 @@ class Geometry(object):
elif not matching and name in lattice_name:
lattices.add(lattice)
lattices = list(lattices)
lattices.sort(key=lambda x: x.id)
return lattices
return sorted(lattices, key=lambda x: x.id)
def determine_paths(self, instances_only=False):
"""Determine paths through CSG tree for cells and materials.

View file

@ -54,25 +54,6 @@ class Lattice(IDManagerMixin):
self._outer = None
self._universes = None
def __eq__(self, other):
if not isinstance(other, Lattice):
return False
elif self.id != other.id:
return False
elif self.name != other.name:
return False
elif np.any(self.pitch != other.pitch):
return False
elif self.outer != other.outer:
return False
elif np.any(self.universes != other.universes):
return False
else:
return True
def __ne__(self, other):
return not self == other
@property
def name(self):
return self._name
@ -579,7 +560,11 @@ class RectLattice(Lattice):
@property
def ndim(self):
return len(self.pitch)
if self.pitch is not None:
return len(self.pitch)
else:
raise ValueError('Number of dimensions cannot be determined until '
'the lattice pitch has been set.')
@property
def shape(self):
@ -622,12 +607,12 @@ class RectLattice(Lattice):
element coordinate system
"""
ix = floor((point[0] - self.lower_left[0])/self.pitch[0])
iy = floor((point[1] - self.lower_left[1])/self.pitch[1])
ix = int(floor((point[0] - self.lower_left[0])/self.pitch[0]))
iy = int(floor((point[1] - self.lower_left[1])/self.pitch[1]))
if self.ndim == 2:
idx = (ix, iy)
else:
iz = floor((point[2] - self.lower_left[2])/self.pitch[2])
iz = int(floor((point[2] - self.lower_left[2])/self.pitch[2]))
idx = (ix, iy, iz)
return idx, self.get_local_coordinates(point, idx)
@ -1034,10 +1019,10 @@ class HexLattice(Lattice):
iz = 1
else:
z = point[2] - self.center[2]
iz = floor(z/self.pitch[1] + 0.5*self.num_axial)
iz = int(floor(z/self.pitch[1] + 0.5*self.num_axial))
alpha = y - x/sqrt(3.)
ix = floor(x/(sqrt(0.75) * self.pitch[0]))
ia = floor(alpha/self.pitch[0])
ix = int(floor(x/(sqrt(0.75) * self.pitch[0])))
ia = int(floor(alpha/self.pitch[0]))
# Check four lattice elements to see which one is closest based on local
# coordinates

View file

@ -15,7 +15,7 @@ from .mixin import IDManagerMixin
# Units for density supported by OpenMC
DENSITY_UNITS = ['g/cm3', 'g/cc', 'kg/cm3', 'atom/b-cm', 'atom/cm3', 'sum',
DENSITY_UNITS = ['g/cm3', 'g/cc', 'kg/m3', 'atom/b-cm', 'atom/cm3', 'sum',
'macro']
@ -49,7 +49,7 @@ class Material(IDManagerMixin):
density : float
Density of the material (units defined separately)
density_units : str
Units used for `density`. Can be one of 'g/cm3', 'g/cc', 'kg/cm3',
Units used for `density`. Can be one of 'g/cm3', 'g/cc', 'kg/m3',
'atom/b-cm', 'atom/cm3', 'sum', or 'macro'. The 'macro' unit only
applies in the case of a multi-group calculation.
depletable : bool
@ -312,7 +312,7 @@ class Material(IDManagerMixin):
Parameters
----------
units : {'g/cm3', 'g/cc', 'kg/cm3', 'atom/b-cm', 'atom/cm3', 'sum', 'macro'}
units : {'g/cm3', 'g/cc', 'kg/m3', 'atom/b-cm', 'atom/cm3', 'sum', 'macro'}
Physical units of density.
density : float, optional
Value of the density. Must be specified unless units is given as

View file

@ -10,6 +10,7 @@ import itertools
from six import add_metaclass, string_types
import numpy as np
import h5py
import openmc
import openmc.checkvalue as cv
@ -1682,13 +1683,8 @@ class MGXS(object):
ValueError
When this method is called before the multi-group cross section is
computed from tally data.
ImportError
When h5py is not installed.
"""
import h5py
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)

View file

@ -45,14 +45,24 @@ class IDManagerMixin(object):
@id.setter
def id(self, uid):
cls = type(self)
name = cls.__name__
# The first time this is called for a class, we search through the MRO
# to determine which class actually holds next_id and used_ids. Since
# next_id is an integer (immutable), we can't modify it directly through
# the instance without just creating a new attribute
try:
cls = self._id_class
except AttributeError:
for cls in self.__class__.__mro__:
if 'next_id' in cls.__dict__:
break
if uid is None:
while cls.next_id in cls.used_ids:
cls.next_id += 1
self._id = cls.next_id
cls.used_ids.add(cls.next_id)
else:
name = cls.__name__
cv.check_type('{} ID'.format(name), uid, Integral)
cv.check_greater_than('{} ID'.format(name), uid, 0, equality=True)
if uid in cls.used_ids:

View file

@ -12,11 +12,7 @@ from abc import ABCMeta, abstractproperty, abstractmethod
from six import add_metaclass
import numpy as np
try:
import scipy.spatial
_SCIPY_AVAILABLE = True
except ImportError:
_SCIPY_AVAILABLE = False
import scipy.spatial
import openmc
import openmc.checkvalue as cv
@ -742,7 +738,7 @@ def _close_random_pack(domain, particles, contraction_rate):
outer_pf = (4/3 * pi * (outer_diameter[0]/2)**3 * n_particles /
domain.volume)
j = floor(-log10(outer_pf - inner_pf))
j = int(floor(-log10(outer_pf - inner_pf)))
outer_diameter[0] = (outer_diameter[0] - 0.5**j * contraction_rate *
initial_outer_diameter / n_particles)
@ -837,10 +833,6 @@ def _close_random_pack(domain, particles, contraction_rate):
if rods:
inner_diameter[0] = rods[0][0]
if not _SCIPY_AVAILABLE:
raise ImportError('SciPy must be installed to perform '
'close random packing.')
n_particles = len(particles)
diameter = 2*domain.particle_radius

View file

@ -39,10 +39,8 @@ class Region(object):
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
elif str(self) != str(other):
return False
else:
return True
return str(self) == str(other)
def __ne__(self, other):
return not self == other
@ -463,7 +461,7 @@ class Union(Region, MutableSequence):
if memo is None:
memo = {}
clone = copy.deepcopy(self)
clone = deepcopy(self)
clone[:] = [n.clone(memo) for n in self]
return clone
@ -584,6 +582,6 @@ class Complement(Region):
if memo is None:
memo = {}
clone = copy.deepcopy(self)
clone = deepcopy(self)
clone.node = self.node.clone(memo)
return clone

View file

@ -60,6 +60,8 @@ class Settings(object):
type are 'variance', 'std_dev', and 'rel_err'. The threshold value
should be a float indicating the variance, standard deviation, or
relative error used.
log_grid_bins : int
Number of bins for logarithmic energy grid search
max_order : None or int
Maximum scattering order to apply globally when in multi-group mode.
multipole_library : str
@ -220,19 +222,12 @@ class Settings(object):
# Uniform fission source subelement
self._ufs_mesh = None
# Domain decomposition subelement
self._dd_mesh_dimension = None
self._dd_mesh_lower_left = None
self._dd_mesh_upper_right = None
self._dd_nodemap = None
self._dd_allow_leakage = False
self._dd_count_interactions = False
self._resonance_scattering = {}
self._volume_calculations = cv.CheckedList(
VolumeCalculation, 'volume calculations')
self._create_fission_neutrons = None
self._log_grid_bins = None
@property
def run_mode(self):
@ -362,30 +357,6 @@ class Settings(object):
def ufs_mesh(self):
return self._ufs_mesh
@property
def dd_mesh_dimension(self):
return self._dd_mesh_dimension
@property
def dd_mesh_lower_left(self):
return self._dd_mesh_lower_left
@property
def dd_mesh_upper_right(self):
return self._dd_mesh_upper_right
@property
def dd_nodemap(self):
return self._dd_nodemap
@property
def dd_allow_leakage(self):
return self._dd_allow_leakage
@property
def dd_count_interactions(self):
return self._dd_count_interactions
@property
def resonance_scattering(self):
return self._resonance_scattering
@ -398,6 +369,10 @@ class Settings(object):
def create_fission_neutrons(self):
return self._create_fission_neutrons
@property
def log_grid_bins(self):
return self._log_grid_bins
@run_mode.setter
def run_mode(self, run_mode):
cv.check_value('run mode', run_mode, _RUN_MODES)
@ -696,85 +671,6 @@ class Settings(object):
cv.check_length('UFS mesh upper-right corner', ufs_mesh.upper_right, 3)
self._ufs_mesh = ufs_mesh
@dd_mesh_dimension.setter
def dd_mesh_dimension(self, dimension):
# TODO: remove this when domain decomposition is merged
warnings.warn('This feature is not yet implemented in a release '
'version of openmc')
cv.check_type('DD mesh dimension', dimension, Iterable, Integral)
cv.check_length('DD mesh dimension', dimension, 3)
self._dd_mesh_dimension = dimension
@dd_mesh_lower_left.setter
def dd_mesh_lower_left(self, lower_left):
# TODO: remove this when domain decomposition is merged
warnings.warn('This feature is not yet implemented in a release '
'version of openmc')
cv.check_type('DD mesh lower left corner', lower_left, Iterable, Real)
cv.check_length('DD mesh lower left corner', lower_left, 3)
self._dd_mesh_lower_left = lower_left
@dd_mesh_upper_right.setter
def dd_mesh_upper_right(self, upper_right):
# TODO: remove this when domain decomposition is merged
warnings.warn('This feature is not yet implemented in a release '
'version of openmc')
cv.check_type('DD mesh upper right corner', upper_right, Iterable, Real)
cv.check_length('DD mesh upper right corner', upper_right, 3)
self._dd_mesh_upper_right = upper_right
@dd_nodemap.setter
def dd_nodemap(self, nodemap):
# TODO: remove this when domain decomposition is merged
warnings.warn('This feature is not yet implemented in a release '
'version of openmc')
cv.check_type('DD nodemap', nodemap, Iterable)
nodemap = np.array(nodemap).flatten()
if self._dd_mesh_dimension is None:
msg = 'Must set DD mesh dimension before setting the nodemap'
raise ValueError(msg)
else:
len_nodemap = np.prod(self._dd_mesh_dimension)
if len(nodemap) < len_nodemap or len(nodemap) > len_nodemap:
msg = 'Unable to set DD nodemap with length "{0}" which ' \
'does not have the same dimensionality as the domain ' \
'mesh'.format(len(nodemap))
raise ValueError(msg)
self._dd_nodemap = nodemap
@dd_allow_leakage.setter
def dd_allow_leakage(self, allow):
# TODO: remove this when domain decomposition is merged
warnings.warn('This feature is not yet implemented in a release '
'version of openmc')
cv.check_type('DD allow leakage', allow, bool)
self._dd_allow_leakage = allow
@dd_count_interactions.setter
def dd_count_interactions(self, interactions):
# TODO: remove this when domain decomposition is merged
warnings.warn('This feature is not yet implemented in a release '
'version of openmc')
cv.check_type('DD count interactions', interactions, bool)
self._dd_count_interactions = interactions
@resonance_scattering.setter
def resonance_scattering(self, res):
cv.check_type('resonance scattering settings', res, Mapping)
@ -812,6 +708,12 @@ class Settings(object):
create_fission_neutrons, bool)
self._create_fission_neutrons = create_fission_neutrons
@log_grid_bins.setter
def log_grid_bins(self, log_grid_bins):
cv.check_type('log grid bins', log_grid_bins, Real)
cv.check_greater_than('log grid bins', log_grid_bins, 0)
self._log_grid_bins = log_grid_bins
def _create_run_mode_subelement(self, root):
elem = ET.SubElement(root, "run_mode")
elem.text = self._run_mode
@ -1033,33 +935,6 @@ class Settings(object):
subelement = ET.SubElement(root, "ufs_mesh")
subelement.text = str(self.ufs_mesh.id)
def _create_dd_subelement(self, root):
if self._dd_mesh_lower_left is not None and \
self._dd_mesh_upper_right is not None and \
self._dd_mesh_dimension is not None:
element = ET.SubElement(root, "domain_decomposition")
subelement = ET.SubElement(element, "mesh")
subsubelement = ET.SubElement(subelement, "dimension")
subsubelement.text = ' '.join(map(str, self._dd_mesh_dimension))
subsubelement = ET.SubElement(subelement, "lower_left")
subsubelement.text = ' '.join(map(str, self._dd_mesh_lower_left))
subsubelement = ET.SubElement(subelement, "upper_right")
subsubelement.text = ' '.join(map(str, self._dd_mesh_upper_right))
if self._dd_nodemap is not None:
subelement = ET.SubElement(element, "nodemap")
subelement.text = ' '.join(map(str, self._dd_nodemap))
subelement = ET.SubElement(element, "allow_leakage")
subelement.text = str(self._dd_allow_leakage).lower()
subelement = ET.SubElement(element, "count_interactions")
subelement.text = str(self._dd_count_interactions).lower()
def _create_resonance_scattering_subelement(self, root):
res = self.resonance_scattering
if res:
@ -1085,6 +960,11 @@ class Settings(object):
elem = ET.SubElement(root, "create_fission_neutrons")
elem.text = str(self._create_fission_neutrons).lower()
def _create_log_grid_bins_subelement(self, root):
if self._log_grid_bins is not None:
elem = ET.SubElement(root, "log_grid_bins")
elem.text = str(self._log_grid_bins)
def export_to_xml(self, path='settings.xml'):
"""Export simulation settings to an XML file.
@ -1128,10 +1008,10 @@ class Settings(object):
self._create_trace_subelement(root_element)
self._create_track_subelement(root_element)
self._create_ufs_mesh_subelement(root_element)
self._create_dd_subelement(root_element)
self._create_resonance_scattering_subelement(root_element)
self._create_volume_calcs_subelement(root_element)
self._create_create_fission_neutrons_subelement(root_element)
self._create_log_grid_bins_subelement(root_element)
# Clean the indentation in the file to be user-readable
clean_xml_indentation(root_element)

View file

@ -194,12 +194,12 @@ class Maxwell(Univariate):
Parameters
----------
theta : float
Effective temperature for distribution
Effective temperature for distribution in eV
Attributes
----------
theta : float
Effective temperature for distribution
Effective temperature for distribution in eV
"""
@ -250,16 +250,16 @@ class Watt(Univariate):
Parameters
----------
a : float
First parameter of distribution
First parameter of distribution in units of eV
b : float
Second parameter of distribution
Second parameter of distribution in units of 1/eV
Attributes
----------
a : float
First parameter of distribution
First parameter of distribution in units of eV
b : float
Second parameter of distribution
Second parameter of distribution in units of 1/eV
"""
@ -444,10 +444,9 @@ class Legendre(Univariate):
def coefficients(self, coefficients):
cv.check_type('Legendre expansion coefficients', coefficients,
Iterable, Real)
for l in range(len(coefficients)):
coefficients[l] *= (2.*l + 1.)/2.
self._legendre_polynomial = np.polynomial.legendre.Legendre(
coefficients)
l = np.arange(len(coefficients))
coeffs = (2.*l + 1.)/2. * np.array(coefficients)
self._legendre_polynomial = np.polynomial.Legendre(coeffs)
def to_xml_element(self, element_name):
raise NotImplementedError

View file

@ -1376,7 +1376,7 @@ class Cone(Surface):
@property
def r2(self):
return self.coefficients['r2']
return self.coefficients['R2']
@x0.setter
def x0(self, x0):

View file

@ -1508,8 +1508,6 @@ class Tally(IDManagerMixin):
------
KeyError
When this method is called before the Tally is populated with data
ImportError
When Pandas can not be found on the caller's system
"""

View file

@ -92,7 +92,7 @@ class Universe(IDManagerMixin):
return openmc.Union(regions).bounding_box
else:
# Infinite bounding box
return openmc.Intersection().bounding_box
return openmc.Intersection([]).bounding_box
@name.setter
def name(self, name):
@ -322,7 +322,7 @@ class Universe(IDManagerMixin):
if not isinstance(cell, openmc.Cell):
msg = 'Unable to add a Cell to Universe ID="{0}" since "{1}" is not ' \
'a Cell'.format(self._id, cell)
raise ValueError(msg)
raise TypeError(msg)
cell_id = cell.id
@ -342,7 +342,7 @@ class Universe(IDManagerMixin):
if not isinstance(cells, Iterable):
msg = 'Unable to add Cells to Universe ID="{0}" since "{1}" is not ' \
'iterable'.format(self._id, cells)
raise ValueError(msg)
raise TypeError(msg)
for cell in cells:
self.add_cell(cell)
@ -360,7 +360,7 @@ class Universe(IDManagerMixin):
if not isinstance(cell, openmc.Cell):
msg = 'Unable to remove a Cell from Universe ID="{0}" since "{1}" is ' \
'not a Cell'.format(self._id, cell)
raise ValueError(msg)
raise TypeError(msg)
# If the Cell is in the Universe's list of Cells, delete it
if cell.id in self._cells:

4
pytest.ini Normal file
View file

@ -0,0 +1,4 @@
[pytest]
python_files = test*.py
python_classes = NoThanks
filterwarnings = ignore::UserWarning

View file

@ -2,7 +2,7 @@
OpenMC Monte Carlo Particle Transport Code
==========================================
|licensebadge| |travisbadge|
|licensebadge| |travisbadge| |coverallsbadge|
The OpenMC project aims to provide a fully-featured Monte Carlo particle
transport code based on modern methods. It is a constructive solid geometry,
@ -74,3 +74,7 @@ OpenMC is distributed under the MIT/X license_.
.. |travisbadge| image:: https://travis-ci.org/mit-crpg/openmc.svg?branch=develop
:target: https://travis-ci.org/mit-crpg/openmc
:alt: Travis CI build status (Linux)
.. |coverallsbadge| image:: https://coveralls.io/repos/github/mit-crpg/openmc/badge.svg?branch=develop
:target: https://coveralls.io/github/mit-crpg/openmc?branch=develop
:alt: Code Coverage

View file

@ -26,7 +26,7 @@ with open('openmc/__init__.py', 'r') as f:
kwargs = {
'name': 'openmc',
'version': version,
'packages': find_packages(),
'packages': find_packages(exclude=['tests*']),
'scripts': glob.glob('scripts/openmc-*'),
# Data files and librarries

View file

@ -193,11 +193,13 @@ contains
if (this % domain_type == FILTER_MATERIAL) then
i_material = p % material
do i_domain = 1, size(this % domain_id)
if (i_material == materials(i_domain) % id) then
call check_hit(i_domain, i_material, indices, hits, n_mat)
end if
end do
if (i_material /= MATERIAL_VOID) then
do i_domain = 1, size(this % domain_id)
if (materials(i_material) % id == this % domain_id(i_domain)) then
call check_hit(i_domain, i_material, indices, hits, n_mat)
end if
end do
end if
elseif (this % domain_type == FILTER_CELL) THEN
do level = 1, p % n_coord

0
tests/__init__.py Normal file
View file

17
tests/conftest.py Normal file
View file

@ -0,0 +1,17 @@
from tests.regression_tests import config as regression_config
def pytest_addoption(parser):
parser.addoption('--exe')
parser.addoption('--mpi', action='store_true')
parser.addoption('--mpiexec')
parser.addoption('--mpi-np')
parser.addoption('--update', action='store_true')
parser.addoption('--build-inputs', action='store_true')
def pytest_configure(config):
opts = ['exe', 'mpi', 'mpiexec', 'mpi_np', 'update', 'build_inputs']
for opt in opts:
if config.getoption(opt) is not None:
regression_config[opt] = config.getoption(opt)

View file

@ -1,23 +0,0 @@
#!/usr/bin/env python
import os
import glob
dirs = glob.glob('test_*')
for adir in dirs:
os.chdir(adir)
files = glob.glob('results.py')
if len(files) > 0:
files = files[0]
with open(files, 'r') as fh:
intxt = fh.read()
intxt = intxt.replace('14.8E', '12.6E')
with open(files, 'w') as fh:
fh.write(intxt)
os.chdir('..')

View file

@ -1,58 +1 @@
=================
OpenMC Test Suite
=================
The purpose of this test suite is to ensure that OpenMC compiles using various
combinations of compiler flags and options and that all user input options can
be used successfully without breaking the code. The test suite is based on
regression or integrated testing where different types of input files are
configured and the full OpenMC code is executed. Results from simulations
are compared with expected results. The test suite is comprised of many
build configurations (e.g. debug, mpi, hdf5) and the actual tests which
reside in sub-directories in the tests directory.
The test suite is designed to integrate with cmake using ctest_. To run the
full test suite run:
.. code-block:: sh
python run_tests.py
The test suite is configured to run with cross sections from NNDC_. To
download these cross sections please do the following:
.. code-block:: sh
cd ../data
python get_nndc.py
export CROSS_SECTIONS=<path_to_data_folder>/nndc/cross_sections.xml
The environmental variable **CROSS_SECTIONS** can be used to quickly switch
between the cross sections set for the test suite and cross section set for
your simulations.
A subset of build configurations and/or tests can be run. To see how to use
the script run:
.. code-block:: sh
python run_tests.py --help
As an example, say we want to run all tests with debug flags only on tests
that have cone and plot in their name. Also, we would like to run this on
4 processors. We can run:
.. code-block:: sh
python run_tests.py -j 4 -C debug -R "cone|plot"
Note that standard regular expression syntax is used for selecting build
configurations and tests. To print out a list of build configurations, we
can run:
.. code-block:: sh
python run_tests.py -p
.. _ctest: http://www.cmake.org/cmake/help/v2.8.12/ctest.html
.. _NNDC: http://http://www.nndc.bnl.gov/endf/b7.1/acefiles.html
See docs/source/devguide/tests.rst for information on the OpenMC test suite.

View file

@ -0,0 +1,9 @@
# Test configuration options for regression tests
config = {
'exe': 'openmc',
'mpi': False,
'mpiexec': 'mpiexec',
'mpi_np': '2',
'update': False,
'build_inputs': False
}

View file

@ -1,13 +1,11 @@
#!/usr/bin/env python
import os
import sys
import glob
import hashlib
sys.path.insert(0, os.pardir)
from testing_harness import PyAPITestHarness
import openmc
from tests.testing_harness import PyAPITestHarness
class AsymmetricLatticeTestHarness(PyAPITestHarness):
def __init__(self, *args, **kwargs):
@ -90,6 +88,6 @@ class AsymmetricLatticeTestHarness(PyAPITestHarness):
return outstr
if __name__ == '__main__':
def test_asymmetric_lattice():
harness = AsymmetricLatticeTestHarness('statepoint.10.h5')
harness.main()

View file

@ -0,0 +1,6 @@
from tests.testing_harness import CMFDTestHarness
def test_cmfd_feed():
harness = CMFDTestHarness('statepoint.20.h5')
harness.main()

View file

@ -0,0 +1,6 @@
from tests.testing_harness import CMFDTestHarness
def test_cmfd_nofeed():
harness = CMFDTestHarness('statepoint.20.h5')
harness.main()

View file

@ -0,0 +1,6 @@
from tests.testing_harness import TestHarness
def test_complex_cell():
harness = TestHarness('statepoint.10.h5')
harness.main()

View file

@ -0,0 +1,6 @@
from tests.testing_harness import TestHarness
def test_confidence_intervals():
harness = TestHarness('statepoint.10.h5')
harness.main()

View file

@ -0,0 +1,15 @@
import openmc
import pytest
@pytest.fixture(scope='module', autouse=True)
def setup_regression_test(request):
# Reset autogenerated IDs assigned to OpenMC objects
openmc.reset_auto_ids()
# Change to test directory
olddir = request.fspath.dirpath().chdir()
try:
yield
finally:
olddir.chdir()

View file

@ -1,11 +1,7 @@
#!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import PyAPITestHarness
import openmc
from tests.testing_harness import PyAPITestHarness
class CreateFissionNeutronsTestHarness(PyAPITestHarness):
def _build_inputs(self):
@ -69,6 +65,6 @@ class CreateFissionNeutronsTestHarness(PyAPITestHarness):
return outstr
if __name__ == '__main__':
def test_create_fission_neutrons():
harness = CreateFissionNeutronsTestHarness('statepoint.10.h5')
harness.main()

View file

@ -0,0 +1,6 @@
from tests.testing_harness import TestHarness
def test_density():
harness = TestHarness('statepoint.10.h5')
harness.main()

View file

@ -1,15 +1,12 @@
#!/usr/bin/env python
import glob
import os
import sys
import pandas as pd
sys.path.insert(0, os.pardir)
from testing_harness import PyAPITestHarness
import openmc
from tests.testing_harness import PyAPITestHarness
class DiffTallyTestHarness(PyAPITestHarness):
def __init__(self, *args, **kwargs):
super(DiffTallyTestHarness, self).__init__(*args, **kwargs)
@ -125,6 +122,6 @@ class DiffTallyTestHarness(PyAPITestHarness):
return df.to_csv(None, columns=cols, index=False, float_format='%.7e')
if __name__ == '__main__':
def test_diff_tally():
harness = DiffTallyTestHarness('statepoint.3.h5')
harness.main()

View file

@ -1,11 +1,7 @@
#!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness, PyAPITestHarness
import openmc
from tests.testing_harness import TestHarness, PyAPITestHarness
class DistribmatTestHarness(PyAPITestHarness):
def _build_inputs(self):
@ -103,6 +99,6 @@ class DistribmatTestHarness(PyAPITestHarness):
return outstr
if __name__ == '__main__':
def test_distribmat():
harness = DistribmatTestHarness('statepoint.5.h5')
harness.main()

View file

@ -0,0 +1,6 @@
from tests.testing_harness import TestHarness
def test_eigenvalue_genperbatch():
harness = TestHarness('statepoint.7.h5')
harness.main()

View file

@ -0,0 +1,6 @@
from tests.testing_harness import TestHarness
def test_eigenvalue_no_inactive():
harness = TestHarness('statepoint.10.h5')
harness.main()

Some files were not shown because too many files have changed in this diff Show more