diff --git a/.gitignore b/.gitignore index 35f45e747b..65c7285af1 100644 --- a/.gitignore +++ b/.gitignore @@ -42,11 +42,8 @@ results_error.dat inputs_error.dat results_test.dat -# Test build files -tests/build/ -tests/coverage/ -tests/memcheck/ -tests/ctestscript.run +# Test +.pytest_cache/ # HDF5 files *.h5 @@ -101,3 +98,5 @@ examples/jupyter/plots .cache/ .tox/ .python-version +.coverage +htmlcov \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index de8b7dcc73..de83325e03 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,9 @@ sudo: required dist: trusty language: python python: - - "2.7" - "3.4" + - "3.5" + - "3.6" addons: apt: packages: @@ -18,29 +19,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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 409a1b52dc..ea2ddc52ff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 #=============================================================================== @@ -48,14 +43,17 @@ add_definitions(-DMAX_COORD=${maxcoord}) set(MPI_ENABLED FALSE) if($ENV{FC} MATCHES "(mpi[^/]*|ftn)$") message("-- Detected MPI wrapper: $ENV{FC}") - add_definitions(-DMPI) + add_definitions(-DOPENMC_MPI) set(MPI_ENABLED TRUE) + + # Get directory containing MPI wrapper + get_filename_component(MPI_DIR $ENV{FC} DIRECTORY) endif() # Check for Fortran 2008 MPI interface if(MPI_ENABLED AND mpif08) message("-- Using Fortran 2008 MPI bindings") - add_definitions(-DMPIF08) + add_definitions(-DOPENMC_MPIF08) endif() #=============================================================================== @@ -116,10 +114,17 @@ if(CMAKE_Fortran_COMPILER_ID STREQUAL GNU) endif() # GCC compiler options - list(APPEND f90flags -cpp -std=f2008ts -fbacktrace -O2 -fstack-arrays -g) +<<<<<<< HEAD + list(APPEND f90flags -cpp -std=f2008ts -fbacktrace -O2 -g) if(debug) list(REMOVE_ITEM f90flags -O2) list(APPEND f90flags -g -enable-checking -fbacktrace -Wall -Wno-unused-dummy-argument -pedantic +======= + list(APPEND f90flags -cpp -std=f2008ts -fbacktrace -O2 -fstack-arrays) + if(debug) + list(REMOVE_ITEM f90flags -O2 -fstack-arrays) + list(APPEND f90flags -g -Wall -Wno-unused-dummy-argument -pedantic +>>>>>>> 47fbf8282ea94c138f75219bd10fdb31501d3fb7 -fbounds-check -ffpe-trap=invalid,overflow,underflow) list(APPEND ldflags -g -v -da -Q) endif() @@ -347,7 +352,6 @@ set(LIBOPENMC_FORTRAN_SRC src/cmfd_prod_operator.F90 src/cmfd_solver.F90 src/constants.F90 - src/cross_section.F90 src/dict_header.F90 src/distribution_multivariate.F90 src/distribution_univariate.F90 @@ -371,7 +375,6 @@ set(LIBOPENMC_FORTRAN_SRC src/message_passing.F90 src/mgxs_data.F90 src/mgxs_header.F90 - src/multipole.F90 src/multipole_header.F90 src/nuclide_header.F90 src/output.F90 @@ -426,6 +429,7 @@ set(LIBOPENMC_FORTRAN_SRC src/tallies/tally_filter_energyfunc.F90 src/tallies/tally_filter_material.F90 src/tallies/tally_filter_mesh.F90 + src/tallies/tally_filter_meshsurface.F90 src/tallies/tally_filter_mu.F90 src/tallies/tally_filter_polar.F90 src/tallies/tally_filter_surface.F90 @@ -435,8 +439,15 @@ set(LIBOPENMC_FORTRAN_SRC src/tallies/trigger_header.F90 ) set(LIBOPENMC_CXX_SRC + src/error.h + src/hdf5_interface.h + src/random_lcg.cpp src/random_lcg.h - src/random_lcg.cpp) + src/surface.cpp + src/surface.h + src/xml_interface.h + src/pugixml/pugixml.cpp + src/pugixml/pugixml.hpp) add_library(libopenmc SHARED ${LIBOPENMC_FORTRAN_SRC} ${LIBOPENMC_CXX_SRC}) set_target_properties(libopenmc PROPERTIES OUTPUT_NAME openmc) add_executable(${program} src/main.F90) @@ -492,72 +503,8 @@ add_custom_command(TARGET libopenmc POST_BUILD install(TARGETS ${program} libopenmc RUNTIME DESTINATION bin - LIBRARY DESTINATION lib) + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib) 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 $) - 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 $ - --mpi_exec $ENV{MPI_DIR}/bin/mpiexec) - else() - # Perform a serial test - add_test(NAME ${TEST_NAME} - WORKING_DIRECTORY ${TEST_PATH} - COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --exe $) - endif() - endif() -endforeach(test) diff --git a/docs/source/conf.py b/docs/source/conf.py index 9330315903..eeecba23e4 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -18,20 +18,21 @@ on_rtd = os.environ.get('READTHEDOCS', None) == 'True' # On Read the Docs, we need to mock a few third-party modules so we don't get # ImportErrors when building documentation -try: - from unittest.mock import MagicMock -except ImportError: - from mock import Mock as MagicMock +from unittest.mock import MagicMock -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'] +MOCK_MODULES = [ + 'numpy', 'numpy.polynomial', 'numpy.polynomial.polynomial', + 'numpy.ctypeslib', 'scipy', 'scipy.sparse', 'scipy.sparse.linalg', + 'scipy.interpolate', 'scipy.integrate', 'scipy.optimize', 'scipy.special', + '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 +np.ndarray = MagicMock np.polynomial.Polynomial = MagicMock @@ -253,6 +254,6 @@ napoleon_use_ivar = True intersphinx_mapping = { 'python': ('https://docs.python.org/3', None), 'numpy': ('https://docs.scipy.org/doc/numpy/', None), - 'pandas': ('http://pandas.pydata.org/pandas-docs/stable/', None), + 'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None), 'matplotlib': ('https://matplotlib.org/', None) } diff --git a/docs/source/devguide/index.rst b/docs/source/devguide/index.rst index 1a8252383c..e40e7f6359 100644 --- a/docs/source/devguide/index.rst +++ b/docs/source/devguide/index.rst @@ -10,9 +10,10 @@ as debugging. .. toctree:: :numbered: - :maxdepth: 3 + :maxdepth: 2 styleguide workflow + tests user-input docbuild diff --git a/docs/source/devguide/tests.rst b/docs/source/devguide/tests.rst new file mode 100644 index 0000000000..749737b5cb --- /dev/null +++ b/docs/source/devguide/tests.rst @@ -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 `_ +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 `_ 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. diff --git a/docs/source/devguide/workflow.rst b/docs/source/devguide/workflow.rst index 942cee55be..9b27fd655f 100644 --- a/docs/source/devguide/workflow.rst +++ b/docs/source/devguide/workflow.rst @@ -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 /.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 +`_ 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/ diff --git a/docs/source/io_formats/data_wmp.rst b/docs/source/io_formats/data_wmp.rst index d645c6e8f1..6174e85ff7 100644 --- a/docs/source/io_formats/data_wmp.rst +++ b/docs/source/io_formats/data_wmp.rst @@ -28,12 +28,6 @@ Windowed Multipole Library Format ":math:`r`" and ":math:`i`" identifiers, similar to how `h5py`_ does it. - **end_E** (*double*) Highest energy the windowed multipole part of the library is valid for. - - **energy_points** (*double[]*) - Energy grid for the pointwise library in the reaction group. - - **fissionable** (*int*) - 1 if this nuclide has fission data. 0 if it does not. - - **fit_order** (*int*) - The order of the curve fit. - **formalism** (*int*) The formalism of the underlying data. Uses the `ENDF-6`_ format formalism numbers. @@ -51,18 +45,6 @@ Windowed Multipole Library Format - **l_value** (*int[]*) The index for a corresponding pole. Equivalent to the :math:`l` quantum number of the resonance the pole comes from :math:`+1`. - - **length** (*int*) - Total count of poles in `data`. - - **max_w** (*int*) - Maximum number of poles in a window. - - **MT_count** (*int*) - Number of pointwise tables in the library. - - **MT_list** (*int[]*) - A list of available MT identifiers. See `ENDF-6`_ for meaning. - - **n_grid** (*int*) - Total length of the pointwise data. - - **num_l** (*int*) - Number of possible :math:`l` quantum states for this nuclide. - **pseudo_K0RS** (*double[]*) :math:`l` dependent value of @@ -90,13 +72,6 @@ Windowed Multipole Library Format The pole to start from for each window. - **w_end** (*int[]*) The pole to end at for each window. - - **windows** (*int*) - Number of windows. - -**/nuclide/reactions/MT** - - **MT_sigma** (*double[]*) -- Cross section value for this reaction. - - **Q_value** (*double*) -- Energy released in this reaction, in eV. - - **threshold** (*int*) -- The first non-zero entry in ``MT_sigma``. .. _h5py: http://docs.h5py.org/en/latest/ .. _ENDF-6: https://www.oecd-nea.org/dbdata/data/manual-endf/endf102.pdf diff --git a/docs/source/io_formats/depletion_chain.rst b/docs/source/io_formats/depletion_chain.rst new file mode 100644 index 0000000000..b0dd72eb9a --- /dev/null +++ b/docs/source/io_formats/depletion_chain.rst @@ -0,0 +1,102 @@ +.. _io_depletion_chain: + +============================ +Depletion Chain -- chain.xml +============================ + +A depletion chain file has a ```` root element with one or more +```` child elements. The decay, reaction, and fission product data for +each nuclide appears as child elements of ````. + +--------------------- +```` Element +--------------------- + +The ```` element contains information on the decay modes, reactions, +and fission product yields for a given nuclide in the depletion chain. This +element may have the following attributes: + + :name: + Name of the nuclide + + :half_life: + Half-life of the nuclide in [s] + + :decay_modes: + Number of decay modes present + + :decay_energy: + Decay energy released in [eV] + + :reactions: + Number of reactions present + +For each decay mode, a :ref:`io_chain_decay` appears as a child of +````. For each reaction present, a :ref:`io_chain_reaction` appears as +a child of ````. If the nuclide is fissionable, a :ref:`io_chain_nfy` +appears as well. + +.. _io_chain_decay: + +------------------- +```` Element +------------------- + +The ```` element represents a single decay mode and has the following +attributes: + + :type: + The type of the decay, e.g. 'ec/beta+' + + :target: + The daughter nuclide produced from the decay + + :branching_ratio: + The branching ratio for this decay mode + +.. _io_chain_reaction: + +---------------------- +```` Element +---------------------- + +The ```` element represents a single transmutation reaction. This +element has the following attributes: + + :type: + The type of the reaction, e.g., '(n,gamma)' + + :Q: + The Q value of the reaction in [eV] + + :target: + The nuclide produced in the reaction (absent if the type is 'fission') + + :branching_ratio: + The branching ratio for the reaction + +.. _io_chain_nfy: + +------------------------------------ +```` Element +------------------------------------ + +The ```` element provides yields of fission products for +fissionable nuclides. It has the follow sub-elements: + + :energies: + Energies in [eV] at which yields for products are tabulated + + :fission_yields: + + Fission product yields for a single energy point. This element itself has a + number of attributes/sub-elements: + + :energy: + Energy in [eV] at which yields are tabulated + + :products: + Names of fission products + + :data: + Independent yields for each fission product diff --git a/docs/source/io_formats/depletion_results.rst b/docs/source/io_formats/depletion_results.rst new file mode 100644 index 0000000000..d35e251469 --- /dev/null +++ b/docs/source/io_formats/depletion_results.rst @@ -0,0 +1,42 @@ +.. _io_depletion_results: + +============================= +Depletion Results File Format +============================= + +The current version of the depletion results file format is 1.0. + +**/** + +:Attributes: - **filetype** (*char[]*) -- String indicating the type of file. + - **version** (*int[2]*) -- Major and minor version of the + statepoint file format. + +:Datasets: - **eigenvalues** (*double[][]*) -- k-eigenvalues at each + time/stage. This array has shape (number of timesteps, number of + stages). + - **number** (*double[][][][]*) -- Total number of atoms. This array + has shape (number of timesteps, number of stages, number of + materials, number of nuclides). + - **reaction rates** (*double[][][][][]*) -- Reaction rates used to + build depletion matrices. This array has shape (number of + timesteps, number of stages, number of materials, number of + nuclides, number of reactions). + - **time** (*double[][2]*) -- Time in [s] at beginning/end of each + step. + +**/materials//** + +:Attributes: - **index** (*int*) -- Index used in results for this material + - **volume** (*double*) -- Volume of this material in [cm^3] + +**/nuclides//** + +:Attributes: - **atom number index** (*int*) -- Index in array of total atoms + for this nuclide + - **reaction rate index** (*int*) -- Index in array of reaction + rates for this nuclide + +**/reactions//** + +:Attributes: - **index** (*int*) -- Index user in results for this reaction diff --git a/docs/source/io_formats/index.rst b/docs/source/io_formats/index.rst index f3eea21def..c1bb76a29a 100644 --- a/docs/source/io_formats/index.rst +++ b/docs/source/io_formats/index.rst @@ -12,7 +12,7 @@ Input Files .. toctree:: :numbered: - :maxdepth: 2 + :maxdepth: 1 geometry materials @@ -27,9 +27,10 @@ Data Files .. toctree:: :numbered: - :maxdepth: 2 + :maxdepth: 1 cross_sections + depletion_chain nuclear_data mgxs_library data_wmp @@ -41,11 +42,12 @@ Output Files .. toctree:: :numbered: - :maxdepth: 2 + :maxdepth: 1 statepoint source summary + depletion_results particle_restart track voxel diff --git a/docs/source/publications.rst b/docs/source/publications.rst index 7578fee6b1..b88bdc0f0c 100644 --- a/docs/source/publications.rst +++ b/docs/source/publications.rst @@ -57,6 +57,11 @@ Benchmarking Coupling and Multi-physics -------------------------- +- Jun Chen, Liangzhi Cao, Chuanqi Zhao, and Zhouyu Liu, "`Development of + Subchannel Code SUBSC for high-fidelity multi-physics coupling application + `_", Energy Procedia, **127**, + 264-274 (2017). + - Tianliang Hu, Liangzhu Cao, Hongchun Wu, Xianan Du, and Mingtao He, "`Coupled neutrons and thermal-hydraulics simulation of molten salt reactors based on OpenMC/TANSY `_," @@ -98,6 +103,11 @@ Coupling and Multi-physics Geometry and Visualization -------------------------- +- Jin-Yang Li, Long Gu, Hu-Shan Xu, Nadezha Korepanova, Rui Yu, Yan-Lei Zhu, and + Chang-Ping Qin, "`CAD modeling study on FLUKA and OpenMC for accelerator + driven system simulation `_", + *Ann. Nucl. Energy*, **114**, 329-341 (2018). + - Logan Abel, William Boyd, Benoit Forget, and Kord Smith, "Interactive Visualization of Multi-Group Cross Sections on High-Fidelity Spatial Meshes," *Trans. Am. Nucl. Soc.*, **114**, 391-394 (2016). @@ -114,6 +124,11 @@ Geometry and Visualization Miscellaneous ------------- +- Bruno Merk, Dzianis Litskevich, R. Gregg, and A. R. Mount, "`Demand driven + salt clean-up in a molten salt fast reactor -- Defining a priority list + `_", *PLOS One*, **13**, + e0192020 (2018). + - Adam G. Nelson, Samuel Shaner, William Boyd, and Paul K. Romano, "Incorporation of a Multigroup Transport Capability in the OpenMC Monte Carlo Particle Transport Code," *Trans. Am. Nucl. Soc.*, **117**, 679-681 (2017). diff --git a/docs/source/pythonapi/base.rst b/docs/source/pythonapi/base.rst index f1633f3f9d..070b5bd201 100644 --- a/docs/source/pythonapi/base.rst +++ b/docs/source/pythonapi/base.rst @@ -109,6 +109,7 @@ Constructing Tallies openmc.CellbornFilter openmc.SurfaceFilter openmc.MeshFilter + openmc.MeshSurfaceFilter openmc.EnergyFilter openmc.EnergyoutFilter openmc.MuFilter diff --git a/docs/source/pythonapi/data.rst b/docs/source/pythonapi/data.rst index 7f75ddaaaf..7feaa8d608 100644 --- a/docs/source/pythonapi/data.rst +++ b/docs/source/pythonapi/data.rst @@ -32,9 +32,12 @@ Core Functions :template: myfunction.rst openmc.data.atomic_mass + openmc.data.gnd_name openmc.data.linearize openmc.data.thin + openmc.data.water_density openmc.data.write_compact_458_library + openmc.data.zam Angle-Energy Distributions -------------------------- diff --git a/docs/source/pythonapi/deplete.rst b/docs/source/pythonapi/deplete.rst new file mode 100644 index 0000000000..d4055f0fdf --- /dev/null +++ b/docs/source/pythonapi/deplete.rst @@ -0,0 +1,85 @@ +.. _pythonapi_deplete: + +---------------------------------- +:mod:`openmc.deplete` -- Depletion +---------------------------------- + +.. module:: openmc.deplete + +Two functions are provided that implement different time-integration algorithms +for depletion calculations. + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myfunction.rst + + integrator.predictor + integrator.cecm + +Each of these functions expects a "transport operator" to be passed. An operator +specific to OpenMC is available using the following class: + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myclass.rst + + Operator + +When running in parallel using `mpi4py `_, the MPI +intercommunicator used can be changed by modifying the following module +variable. If it is not explicitly modified, it defaults to +``mpi4py.MPI.COMM_WORLD``. + +.. data:: comm + + MPI intercommunicator used to call OpenMC library + + :type: mpi4py.MPI.Comm + +Internal Classes and Functions +------------------------------ + +During a depletion calculation, the depletion chain, reaction rates, and number +densities are managed through a series of internal classes that are not normally +visible to a user. However, should you find yourself wondering about these +classes (e.g., if you want to know what decay modes or reactions are present in +a depletion chain), they are documented here. The following classes store data +for a depletion chain: + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myclass.rst + + Chain + DecayTuple + Nuclide + ReactionTuple + +The following classes are used during a depletion simulation and store auxiliary +data, such as number densities and reaction rates for each material. + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myclass.rst + + AtomNumber + OperatorResult + ReactionRates + Results + ResultsList + TransportOperator + +Each of the integrator functions also relies on a number of "helper" functions +as follows: + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myfunction.rst + + integrator.CRAM16 + integrator.CRAM48 diff --git a/docs/source/pythonapi/index.rst b/docs/source/pythonapi/index.rst index 862acb2384..3c28a21852 100644 --- a/docs/source/pythonapi/index.rst +++ b/docs/source/pythonapi/index.rst @@ -15,14 +15,15 @@ there are many substantial benefits to using the Python API, including: - The ability to define dimensions using variables. - Availability of standard-library modules for working with files. - An entire ecosystem of third-party packages for scientific computing. -- Ability to create materials based on natural elements or uranium enrichment - Automated multi-group cross section generation (:mod:`openmc.mgxs`) +- A fully-featured nuclear data interface (:mod:`openmc.data`) +- Depletion capability (:mod:`openmc.deplete`) - Convenience functions (e.g., a function returning a hexagonal region) - Ability to plot individual universes as geometry is being created - A :math:`k_\text{eff}` search function (:func:`openmc.search_for_keff`) - Random sphere packing for generating TRISO particle locations (:func:`openmc.model.pack_trisos`) -- A fully-featured nuclear data interface (:mod:`openmc.data`) +- Ability to create materials based on natural elements or uranium enrichment For those new to Python, there are many good tutorials available online. We recommend going through the modules from `Codecademy @@ -45,6 +46,7 @@ Modules base model examples + deplete mgxs stats data diff --git a/docs/source/pythonapi/model.rst b/docs/source/pythonapi/model.rst index 4ba247468a..9ed77f3666 100644 --- a/docs/source/pythonapi/model.rst +++ b/docs/source/pythonapi/model.rst @@ -5,16 +5,12 @@ Convenience Functions --------------------- -Several helper functions are available here. Ther first two create rectangular -and hexagonal prisms defined by the intersection of four and six surface -half-spaces, respectively. The last function takes a sequence of surfaces and -returns the regions that separate them. - .. autosummary:: :toctree: generated :nosignatures: :template: myfunction.rst + openmc.model.borated_water openmc.model.get_hexagonal_prism openmc.model.get_rectangular_prism openmc.model.subdivide diff --git a/docs/source/quickinstall.rst b/docs/source/quickinstall.rst index 97980037c5..7176b67be0 100644 --- a/docs/source/quickinstall.rst +++ b/docs/source/quickinstall.rst @@ -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 +`_. If you have `git +`_, the `gcc `_ compiler suite, +`CMake `_, and `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 `_, 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 `. - -.. _GitHub: https://github.com/mit-crpg/openmc -.. _git: http://git-scm.com -.. _gfortran: http://gcc.gnu.org/wiki/GFortran -.. _CMake: http://www.cmake.org diff --git a/docs/source/usersguide/beginners.rst b/docs/source/usersguide/beginners.rst index 22b09a24d3..ec37d0825a 100644 --- a/docs/source/usersguide/beginners.rst +++ b/docs/source/usersguide/beginners.rst @@ -151,8 +151,8 @@ and `Volume II`_. You may also find it helpful to review the following terms: .. _git: http://git-scm.com/ .. _git tutorials: http://git-scm.com/documentation .. _Reactor Concepts Manual: http://www.tayloredge.com/periodic/trivia/ReactorConcepts.pdf -.. _Volume I: http://energy.gov/sites/prod/files/2013/06/f2/h1019v1.pdf -.. _Volume II: http://energy.gov/sites/prod/files/2013/06/f2/h1019v2.pdf +.. _Volume I: https://www.standards.doe.gov/standards-documents/1000/1019-bhdbk-1993-v1 +.. _Volume II: https://www.standards.doe.gov/standards-documents/1000/1019-bhdbk-1993-v2 .. _OpenMC source code: https://github.com/mit-crpg/openmc .. _GitHub: https://github.com/ .. _bug reports: https://github.com/mit-crpg/openmc/issues diff --git a/docs/source/usersguide/install.rst b/docs/source/usersguide/install.rst index b595729236..24bcc7164d 100644 --- a/docs/source/usersguide/install.rst +++ b/docs/source/usersguide/install.rst @@ -6,17 +6,18 @@ Installation and Configuration .. currentmodule:: openmc +.. _install_conda: + ---------------------------------------- Installing on Linux/Mac with conda-forge ---------------------------------------- -`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 `_ is a community-led conda -channel of installable packages. For instructions on installing conda, please -consult their `documentation -`_. +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 +`_ is a community-led conda channel of +installable packages. For instructions on installing conda, please consult their +`documentation `_. 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,26 +370,57 @@ 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 ` 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 +If you installed OpenMC using :ref:`Conda ` or :ref:`PPA +`, no further steps are necessary in order to use OpenMC's +:ref:`Python API `. However, if you are :ref:`installing from 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 +`_). The easiest way to install +the :mod:`openmc` Python package is to use pip_, which is included by default in +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 +` have been installed, and if they are not present, +they will be installed by downloading the appropriate packages from the Python +Package Index (`PyPI `_). 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 `. + +.. _usersguide_python_prereqs: + +Prerequisites +------------- + +The Python API works with Python 3.4+. 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 - `six `_ - The Python API works with both Python 2.7+ and 3.2+. To do so, the six - compatibility library is used. - `NumPy `_ NumPy is used extensively within the Python API for its powerful N-dimensional array. @@ -415,6 +452,11 @@ distributions. .. admonition:: Optional :class: note + `mpi4py `_ + mpi4py provides Python bindings to MPI for running distributed-memory + parallel runs. This package is needed if you plan on running depletion + simulations in parallel using MPI. + `Cython `_ Cython is used for resonance reconstruction for ENDF data converted to :class:`openmc.data.IncidentNeutron`. @@ -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/ diff --git a/docs/source/usersguide/materials.rst b/docs/source/usersguide/materials.rst index b1e0c151f2..8472768489 100644 --- a/docs/source/usersguide/materials.rst +++ b/docs/source/usersguide/materials.rst @@ -43,14 +43,22 @@ of an element, you specify the element itself. For example, Internally, OpenMC stores data on the atomic masses and natural abundances of all known isotopes and then uses this data to determine what isotopes should be added to the material. When the material is later exported to XML for use by the -:ref:`scripts_openmc` executable, you'll see that any natural elements are +:ref:`scripts_openmc` executable, you'll see that any natural elements were expanded to the naturally-occurring isotopes. +The :meth:`Material.add_element` method can also be used to add uranium at a +specified enrichment through the `enrichment` argument. For example, the +following would add 3.2% enriched uranium to a material:: + + mat.add_element('U', 1.0, enrichment=3.2) + +In addition to U235 and U238, concentrations of U234 and U236 will be present +and are determined through a correlation based on measured data. + Often, cross section libraries don't actually have all naturally-occurring isotopes for a given element. For example, in ENDF/B-VII.1, cross section evaluations are given for O16 and O17 but not for O18. If OpenMC is aware of -what cross sections you will be using (either through the -:attr:`Materials.cross_sections` attribute or the +what cross sections you will be using (through the :envvar:`OPENMC_CROSS_SECTIONS` environment variable), it will attempt to only put isotopes in your model for which you have cross section data. In the case of oxygen in ENDF/B-VII.1, the abundance of O18 would end up being lumped with O16. diff --git a/docs/source/usersguide/scripts.rst b/docs/source/usersguide/scripts.rst index 90ca6886d1..2f199fc256 100644 --- a/docs/source/usersguide/scripts.rst +++ b/docs/source/usersguide/scripts.rst @@ -168,8 +168,8 @@ ENDF/B-VII.1. It has the following optional arguments: This script downloads `ENDF/B-VII.1 ACE data `_ 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 diff --git a/examples/xml/pincell/tallies.xml b/examples/xml/pincell/tallies.xml index 0ae36eceda..7e1e0dafe4 100644 --- a/examples/xml/pincell/tallies.xml +++ b/examples/xml/pincell/tallies.xml @@ -8,7 +8,7 @@ - 1 + 2 diff --git a/include/openmc.h b/include/openmc.h index bb04907a52..10c0b2de8e 100644 --- a/include/openmc.h +++ b/include/openmc.h @@ -52,6 +52,7 @@ extern "C" { int openmc_material_filter_get_bins(int32_t index, int32_t** bins, int32_t* n); int openmc_material_filter_set_bins(int32_t index, int32_t n, const int32_t* bins); int openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh); + int openmc_meshsurface_filter_set_mesh(int32_t index, int32_t index_mesh); int openmc_next_batch(); int openmc_nuclide_name(int index, char** name); void openmc_plot_geometry(); diff --git a/openmc/_utils.py b/openmc/_utils.py new file mode 100644 index 0000000000..83455c17aa --- /dev/null +++ b/openmc/_utils.py @@ -0,0 +1,49 @@ +import os.path +from pathlib import Path +from urllib.parse import urlparse +from urllib.request import urlopen + +_BLOCK_SIZE = 16384 + + +def download(url): + """Download file from a URL + + Parameters + ---------- + url : str + URL from which to download + + Returns + ------- + basename : str + Name of file written locally + + """ + req = urlopen(url) + + # Get file size from header + file_size = req.length + + # Check if file already downloaded + basename = Path(urlparse(url).path).name + if os.path.exists(basename): + if os.path.getsize(basename) == file_size: + print('Skipping {}, already downloaded'.format(basename)) + return basename + + # Copy file to disk in chunks + print('Downloading {}... '.format(basename), end='') + downloaded = 0 + with open(basename, 'wb') as fh: + while True: + chunk = req.read(_BLOCK_SIZE) + if not chunk: + break + fh.write(chunk) + downloaded += len(chunk) + status = '{:10} [{:3.2f}%]'.format( + downloaded, downloaded * 100. / file_size) + print(status + '\b'*len(status), end='') + print('') + return basename diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index fe002f1e31..4a5e7486a8 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -2,7 +2,6 @@ import sys import copy from collections import Iterable -from six import string_types import numpy as np import pandas as pd @@ -86,18 +85,18 @@ class CrossScore(object): @left_score.setter def left_score(self, left_score): cv.check_type('left_score', left_score, - string_types + (CrossScore, AggregateScore)) + (str, CrossScore, AggregateScore)) self._left_score = left_score @right_score.setter def right_score(self, right_score): cv.check_type('right_score', right_score, - string_types + (CrossScore, AggregateScore)) + (str, CrossScore, AggregateScore)) self._right_score = right_score @binary_op.setter def binary_op(self, binary_op): - cv.check_type('binary_op', binary_op, string_types) + cv.check_type('binary_op', binary_op, str) cv.check_value('binary_op', binary_op, _TALLY_ARITHMETIC_OPS) self._binary_op = binary_op @@ -202,7 +201,7 @@ class CrossNuclide(object): @binary_op.setter def binary_op(self, binary_op): - cv.check_type('binary_op', binary_op, string_types) + cv.check_type('binary_op', binary_op, str) cv.check_value('binary_op', binary_op, _TALLY_ARITHMETIC_OPS) self._binary_op = binary_op @@ -335,7 +334,7 @@ class CrossFilter(object): @binary_op.setter def binary_op(self, binary_op): - cv.check_type('binary_op', binary_op, string_types) + cv.check_type('binary_op', binary_op, str) cv.check_value('binary_op', binary_op, _TALLY_ARITHMETIC_OPS) self._binary_op = binary_op @@ -482,12 +481,12 @@ class AggregateScore(object): @scores.setter def scores(self, scores): - cv.check_iterable_type('scores', scores, string_types) + cv.check_iterable_type('scores', scores, str) self._scores = scores @aggregate_op.setter def aggregate_op(self, aggregate_op): - cv.check_type('aggregate_op', aggregate_op, string_types +(CrossScore,)) + cv.check_type('aggregate_op', aggregate_op, (str, CrossScore)) cv.check_value('aggregate_op', aggregate_op, _TALLY_AGGREGATE_OPS) self._aggregate_op = aggregate_op @@ -561,13 +560,12 @@ class AggregateNuclide(object): @nuclides.setter def nuclides(self, nuclides): - cv.check_iterable_type('nuclides', nuclides, - string_types + (openmc.Nuclide, CrossNuclide)) + cv.check_iterable_type('nuclides', nuclides, (str, CrossNuclide)) self._nuclides = nuclides @aggregate_op.setter def aggregate_op(self, aggregate_op): - cv.check_type('aggregate_op', aggregate_op, string_types) + cv.check_type('aggregate_op', aggregate_op, str) cv.check_value('aggregate_op', aggregate_op, _TALLY_AGGREGATE_OPS) self._aggregate_op = aggregate_op @@ -690,7 +688,7 @@ class AggregateFilter(object): @aggregate_op.setter def aggregate_op(self, aggregate_op): - cv.check_type('aggregate_op', aggregate_op, string_types) + cv.check_type('aggregate_op', aggregate_op, str) cv.check_value('aggregate_op', aggregate_op, _TALLY_AGGREGATE_OPS) self._aggregate_op = aggregate_op diff --git a/openmc/capi/__init__.py b/openmc/capi/__init__.py index d302001c99..bc173f9946 100644 --- a/openmc/capi/__init__.py +++ b/openmc/capi/__init__.py @@ -15,7 +15,6 @@ objects in the :mod:`openmc.capi` subpackage, for example: from ctypes import CDLL import os import sys -from warnings import warn import pkg_resources @@ -36,10 +35,7 @@ else: # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur - try: - from unittest.mock import Mock - except ImportError: - from mock import Mock + from unittest.mock import Mock _dll = Mock() from .error import * @@ -50,6 +46,3 @@ from .cell import * from .filter import * from .tally import * from .settings import settings - -warn("The Python bindings to OpenMC's C API are still unstable " - "and may change substantially in future releases.", FutureWarning) diff --git a/openmc/capi/cell.py b/openmc/capi/cell.py index 0c4b72c749..0ab3f2583e 100644 --- a/openmc/capi/cell.py +++ b/openmc/capi/cell.py @@ -1,4 +1,4 @@ -from collections import Mapping, Iterable +from collections.abc import Mapping, Iterable from ctypes import c_int, c_int32, c_double, c_char_p, POINTER from weakref import WeakValueDictionary @@ -65,10 +65,7 @@ class Cell(_FortranObjectWithID): if new: # Determine ID to assign if uid is None: - try: - uid = max(mapping) + 1 - except ValueError: - uid = 1 + uid = max(mapping, default=0) + 1 else: if uid in mapping: raise AllocationError('A cell with ID={} has already ' @@ -81,7 +78,7 @@ class Cell(_FortranObjectWithID): index = mapping[uid]._index if index not in cls.__instances: - instance = super(Cell, cls).__new__(cls) + instance = super().__new__(cls) instance._index = index if uid is not None: instance.id = uid diff --git a/openmc/capi/filter.py b/openmc/capi/filter.py index 1b52af6db9..691ecc09cc 100644 --- a/openmc/capi/filter.py +++ b/openmc/capi/filter.py @@ -1,4 +1,4 @@ -from collections import Mapping +from collections.abc import Mapping from ctypes import c_int, c_int32, c_double, c_char_p, POINTER, \ create_string_buffer from weakref import WeakValueDictionary @@ -55,6 +55,9 @@ _dll.openmc_material_filter_set_bins.errcheck = _error_handler _dll.openmc_mesh_filter_set_mesh.argtypes = [c_int32, c_int32] _dll.openmc_mesh_filter_set_mesh.restype = c_int _dll.openmc_mesh_filter_set_mesh.errcheck = _error_handler +_dll.openmc_meshsurface_filter_set_mesh.argtypes = [c_int32, c_int32] +_dll.openmc_meshsurface_filter_set_mesh.restype = c_int +_dll.openmc_meshsurface_filter_set_mesh.errcheck = _error_handler class Filter(_FortranObjectWithID): @@ -66,10 +69,7 @@ class Filter(_FortranObjectWithID): if new: # Determine ID to assign if uid is None: - try: - uid = max(mapping) + 1 - except ValueError: - uid = 1 + uid = max(mapping, default=0) + 1 else: if uid in mapping: raise AllocationError('A filter with ID={} has already ' @@ -87,7 +87,7 @@ class Filter(_FortranObjectWithID): index = mapping[uid]._index if index not in cls.__instances: - instance = super(Filter, cls).__new__(cls) + instance = super().__new__(cls) instance._index = index if uid is not None: instance.id = uid @@ -110,7 +110,7 @@ class EnergyFilter(Filter): filter_type = 'energy' def __init__(self, bins=None, uid=None, new=True, index=None): - super(EnergyFilter, self).__init__(uid, new, index) + super().__init__(uid, new, index) if bins is not None: self.bins = bins @@ -131,7 +131,7 @@ class EnergyFilter(Filter): self._index, len(energies), energies_p) -class EnergyoutFilter(Filter): +class EnergyoutFilter(EnergyFilter): filter_type = 'energyout' @@ -167,7 +167,7 @@ class MaterialFilter(Filter): filter_type = 'material' def __init__(self, bins=None, uid=None, new=True, index=None): - super(MaterialFilter, self).__init__(uid, new, index) + super().__init__(uid, new, index) if bins is not None: self.bins = bins @@ -191,6 +191,10 @@ class MeshFilter(Filter): filter_type = 'mesh' +class MeshSurfaceFilter(Filter): + filter_type = 'meshsurface' + + class MuFilter(Filter): filter_type = 'mu' @@ -219,6 +223,7 @@ _FILTER_TYPE_MAP = { 'energyfunction': EnergyFunctionFilter, 'material': MaterialFilter, 'mesh': MeshFilter, + 'meshsurface': MeshSurfaceFilter, 'mu': MuFilter, 'polar': PolarFilter, 'surface': SurfaceFilter, diff --git a/openmc/capi/material.py b/openmc/capi/material.py index af0e9893e4..62d6df012a 100644 --- a/openmc/capi/material.py +++ b/openmc/capi/material.py @@ -1,4 +1,4 @@ -from collections import Mapping +from collections.abc import Mapping from ctypes import c_int, c_int32, c_double, c_char_p, POINTER from weakref import WeakValueDictionary @@ -78,10 +78,7 @@ class Material(_FortranObjectWithID): if new: # Determine ID to assign if uid is None: - try: - uid = max(mapping) + 1 - except ValueError: - uid = 1 + uid = max(mapping, default=0) + 1 else: if uid in mapping: raise AllocationError('A material with ID={} has already ' diff --git a/openmc/capi/nuclide.py b/openmc/capi/nuclide.py index e07872e583..f66212c971 100644 --- a/openmc/capi/nuclide.py +++ b/openmc/capi/nuclide.py @@ -1,4 +1,4 @@ -from collections import Mapping +from collections.abc import Mapping from ctypes import c_int, c_char_p, POINTER from weakref import WeakValueDictionary @@ -58,7 +58,7 @@ class Nuclide(_FortranObject): def __new__(cls, *args): if args not in cls.__instances: - instance = super(Nuclide, cls).__new__(cls) + instance = super().__new__(cls) cls.__instances[args] = instance return cls.__instances[args] diff --git a/openmc/capi/settings.py b/openmc/capi/settings.py index eede6cf47b..1063d6463e 100644 --- a/openmc/capi/settings.py +++ b/openmc/capi/settings.py @@ -11,8 +11,7 @@ _RUN_MODES = {1: 'fixed source', 5: 'volume'} _dll.openmc_set_seed.argtypes = [c_int64] -_dll.openmc_set_seed.restype = c_int -_dll.openmc_set_seed.errcheck = _error_handler +_dll.openmc_get_seed.restype = c_int64 class _Settings(object): @@ -43,7 +42,7 @@ class _Settings(object): @property def seed(self): - return c_int64.in_dll(_dll, 'seed').value + return _dll.openmc_get_seed() @seed.setter def seed(self, seed): diff --git a/openmc/capi/tally.py b/openmc/capi/tally.py index 751f0e6031..a78347177d 100644 --- a/openmc/capi/tally.py +++ b/openmc/capi/tally.py @@ -1,4 +1,4 @@ -from collections import Mapping +from collections.abc import Mapping from ctypes import c_int, c_int32, c_double, c_char_p, POINTER from weakref import WeakValueDictionary @@ -155,10 +155,7 @@ class Tally(_FortranObjectWithID): if new: # Determine ID to assign if uid is None: - try: - uid = max(mapping) + 1 - except ValueError: - uid = 1 + uid = max(mapping, default=0) + 1 else: if uid in mapping: raise AllocationError('A tally with ID={} has already ' @@ -172,7 +169,7 @@ class Tally(_FortranObjectWithID): index = mapping[uid]._index if index not in cls.__instances: - instance = super(Tally, cls).__new__(cls) + instance = super().__new__(cls) instance._index = index if uid is not None: instance.id = uid diff --git a/openmc/cell.py b/openmc/cell.py index 5975d7f70b..cbfd74b21b 100644 --- a/openmc/cell.py +++ b/openmc/cell.py @@ -1,4 +1,5 @@ -from collections import OrderedDict, Iterable +from collections import OrderedDict +from collections.abc import Iterable from copy import deepcopy from math import cos, sin, pi from numbers import Real, Integral @@ -6,7 +7,6 @@ from xml.etree import ElementTree as ET import sys import warnings -from six import string_types import numpy as np import openmc @@ -203,7 +203,7 @@ class Cell(IDManagerMixin): @name.setter def name(self, name): if name is not None: - cv.check_type('cell name', name, string_types) + cv.check_type('cell name', name, str) self._name = name else: self._name = '' @@ -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) @@ -291,50 +284,6 @@ class Cell(IDManagerMixin): cv.check_type('cell volume', volume, Real) self._volume = volume - def add_surface(self, surface, halfspace): - """Add a half-space to the list of half-spaces whose intersection defines the - cell. - - .. deprecated:: 0.7.1 - Use the :attr:`Cell.region` property to directly specify a Region - expression. - - Parameters - ---------- - surface : openmc.Surface - Quadric surface dividing space - halfspace : {-1, 1} - Indicate whether the negative or positive half-space is to be used - - """ - - warnings.warn("Cell.add_surface(...) has been deprecated and may be " - "removed in a future version. The region for a Cell " - "should be defined using the region property directly.", - DeprecationWarning) - - if not isinstance(surface, openmc.Surface): - msg = 'Unable to add Surface "{0}" to Cell ID="{1}" since it is ' \ - 'not a Surface object'.format(surface, self._id) - raise ValueError(msg) - - if halfspace not in [-1, +1]: - msg = 'Unable to add Surface "{0}" to Cell ID="{1}" with halfspace ' \ - '"{2}" since it is not +/-1'.format(surface, self._id, halfspace) - raise ValueError(msg) - - # If no region has been assigned, simply use the half-space. Otherwise, - # take the intersection of the current region and the half-space - # specified - region = +surface if halfspace == 1 else -surface - if self.region is None: - self.region = region - else: - if isinstance(self.region, Intersection): - self.region &= region - else: - self.region = Intersection(self.region, region) - def add_volume_information(self, volume_calc): """Add volume information to a cell. @@ -346,7 +295,7 @@ class Cell(IDManagerMixin): """ if volume_calc.domain_type == 'cell': if self.id in volume_calc.volumes: - self._volume = volume_calc.volumes[self.id][0] + self._volume = volume_calc.volumes[self.id].n self._atoms = volume_calc.atoms[self.id] else: raise ValueError('No volume information found for this cell.') @@ -386,7 +335,7 @@ class Cell(IDManagerMixin): volume = self.volume for name, atoms in self._atoms.items(): nuclide = openmc.Nuclide(name) - density = 1.0e-24 * atoms[0]/volume # density in atoms/b-cm + density = 1.0e-24 * atoms.n/volume # density in atoms/b-cm nuclides[name] = (nuclide, density) else: raise RuntimeError( diff --git a/openmc/checkvalue.py b/openmc/checkvalue.py index aa4dc067f9..2f80ee4c0c 100644 --- a/openmc/checkvalue.py +++ b/openmc/checkvalue.py @@ -1,5 +1,5 @@ import copy -from collections import Iterable +from collections.abc import Iterable import numpy as np @@ -246,9 +246,9 @@ def check_filetype_version(obj, expected_type, expected_version): ---------- obj : h5py.File HDF5 file to check - expected_type + expected_type : str Expected file type, e.g. 'statepoint' - expected_version + expected_version : int Expected major version number. """ @@ -288,7 +288,7 @@ class CheckedList(list): """ def __init__(self, expected_type, name, items=[]): - super(CheckedList, self).__init__() + super().__init__() self.expected_type = expected_type self.name = name for item in items: @@ -319,7 +319,7 @@ class CheckedList(list): """ check_type(self.name, item, self.expected_type) - super(CheckedList, self).append(item) + super().append(item) def insert(self, index, item): """Insert item before index @@ -333,4 +333,4 @@ class CheckedList(list): """ check_type(self.name, item, self.expected_type) - super(CheckedList, self).insert(index, item) + super().insert(index, item) diff --git a/openmc/cmfd.py b/openmc/cmfd.py index c3df3f1047..5444334b20 100644 --- a/openmc/cmfd.py +++ b/openmc/cmfd.py @@ -10,13 +10,11 @@ References """ -from collections import Iterable +from collections.abc import Iterable from numbers import Real, Integral from xml.etree import ElementTree as ET import sys -from six import string_types - from openmc.clean_xml import clean_xml_indentation from openmc.checkvalue import (check_type, check_length, check_value, check_greater_than, check_less_than) @@ -338,7 +336,7 @@ class CMFD(object): @display.setter def display(self, display): - check_type('CMFD display', display, string_types) + check_type('CMFD display', display, str) check_value('CMFD display', display, ['balance', 'dominance', 'entropy', 'source']) self._display = display diff --git a/openmc/data/ace.py b/openmc/data/ace.py index 9827df5b9d..fa2705220b 100644 --- a/openmc/data/ace.py +++ b/openmc/data/ace.py @@ -15,16 +15,14 @@ generates ACE-format cross sections. """ -from __future__ import division, unicode_literals from os import SEEK_CUR import struct import sys -from six import string_types import numpy as np from openmc.mixin import EqualityMixin -from openmc.data.endf import ENDF_FLOAT_RE +from openmc.data.endf import _ENDF_FLOAT_RE def ascii_to_binary(ascii_file, binary_file): """Convert an ACE file in ASCII format (type 1) to binary format (type 2). @@ -153,7 +151,7 @@ class Library(EqualityMixin): """ def __init__(self, filename, table_names=None, verbose=False): - if isinstance(table_names, string_types): + if isinstance(table_names, str): table_names = [table_names] if table_names is not None: table_names = set(table_names) @@ -351,7 +349,7 @@ class Library(EqualityMixin): # after it). If it's too short, then we apply the ENDF float regular # expression. We don't do this by default because it's expensive! if xss.size != nxs[1] + 1: - datastr = ENDF_FLOAT_RE.sub(r'\1e\2', datastr) + datastr = _ENDF_FLOAT_RE.sub(r'\1e\2', datastr) xss = np.fromstring(datastr, sep=' ') assert xss.size == nxs[1] + 1 diff --git a/openmc/data/angle_distribution.py b/openmc/data/angle_distribution.py index ad3ba89193..a1f498ba61 100644 --- a/openmc/data/angle_distribution.py +++ b/openmc/data/angle_distribution.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from io import StringIO from numbers import Real from warnings import warn @@ -34,7 +34,7 @@ class AngleDistribution(EqualityMixin): """ def __init__(self, energy, mu): - super(AngleDistribution, self).__init__() + super().__init__() self.energy = energy self.mu = mu diff --git a/openmc/data/angle_energy.py b/openmc/data/angle_energy.py index 8bf95152a9..d67cc6b266 100644 --- a/openmc/data/angle_energy.py +++ b/openmc/data/angle_energy.py @@ -1,14 +1,11 @@ from abc import ABCMeta, abstractmethod from io import StringIO -from six import add_metaclass - import openmc.data from openmc.mixin import EqualityMixin -@add_metaclass(ABCMeta) -class AngleEnergy(EqualityMixin): +class AngleEnergy(EqualityMixin, metaclass=ABCMeta): """Distribution in angle and energy of a secondary particle.""" @abstractmethod def to_hdf5(self, group): diff --git a/openmc/data/correlated.py b/openmc/data/correlated.py index 49d116efd0..8cc4509cea 100644 --- a/openmc/data/correlated.py +++ b/openmc/data/correlated.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from numbers import Real, Integral from warnings import warn @@ -45,7 +45,7 @@ class CorrelatedAngleEnergy(AngleEnergy): """ def __init__(self, breakpoints, interpolation, energy, energy_out, mu): - super(CorrelatedAngleEnergy, self).__init__() + super().__init__() self.breakpoints = breakpoints self.interpolation = interpolation self.energy = energy diff --git a/openmc/data/data.py b/openmc/data/data.py index ded6870188..90d5903e73 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -1,6 +1,8 @@ import itertools +from math import sqrt import os import re +from warnings import warn # Isotopic abundances from Meija J, Coplen T B, et al, "Isotopic compositions @@ -133,23 +135,24 @@ ATOMIC_NUMBER = {value: key for key, value in ATOMIC_SYMBOL.items()} _ATOMIC_MASS = {} +_GND_NAME_RE = re.compile(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)') + def atomic_mass(isotope): """Return atomic mass of isotope in atomic mass units. - Atomic mass data comes from the Atomic Mass Evaluation 2012, published in - Chinese Physics C 36 (2012), 1287--1602. + Atomic mass data comes from the `Atomic Mass Evaluation 2012 + `_. Parameters ---------- isotope : str - Name of isotope, e.g. 'Pu239' + Name of isotope, e.g., 'Pu239' Returns ------- - float or None - Atomic mass of isotope in atomic mass units. If the isotope listed does - not have a known atomic mass, None is returned. + float + Atomic mass of isotope in [amu] """ if not _ATOMIC_MASS: @@ -180,7 +183,7 @@ def atomic_mass(isotope): if '_' in isotope: isotope = isotope[:isotope.find('_')] - return _ATOMIC_MASS.get(isotope.lower()) + return _ATOMIC_MASS[isotope.lower()] def atomic_weight(element): @@ -196,16 +199,168 @@ def atomic_weight(element): Returns ------- - float or None - Atomic weight of element in atomic mass units. If the element listed does - not exist, None is returned. + float + Atomic weight of element in [amu] """ weight = 0. for nuclide, abundance in NATURAL_ABUNDANCE.items(): if re.match(r'{}\d+'.format(element), nuclide): weight += atomic_mass(nuclide) * abundance - return None if weight == 0. else weight + if weight > 0.: + return weight + else: + raise ValueError("No naturally-occurring isotopes for element '{}'." + .format(element)) + + +def water_density(temperature, pressure=0.1013): + """Return the density of liquid water at a given temperature and pressure. + + The density is calculated from a polynomial fit using equations and values + from the 2012 version of the IAPWS-IF97 formulation. Only the equations + for region 1 are implemented here. Region 1 is limited to liquid water + below 100 [MPa] with a temperature above 273.15 [K], below 623.15 [K], and + below saturation. + + Reference: International Association for the Properties of Water and Steam, + "Revised Release on the IAPWS Industrial Formulation 1997 for the + Thermodynamic Properties of Water and Steam", IAPWS R7-97(2012). + + Parameters + ---------- + temperature : float + Water temperature in units of [K] + pressure : float + Water pressure in units of [MPa] + + Returns + ------- + float + Water density in units of [g/cm^3] + + """ + + # Make sure the temperature and pressure are inside the min/max region 1 + # bounds. (Relax the 273.15 bound to 273 in case a user wants 0 deg C data + # but they only use 3 digits for their conversion to K.) + if pressure > 100.0: + warn("Results are not valid for pressures above 100 MPa.") + if pressure < 0.0: + warn("Results are not valid for pressures below zero.") + if temperature < 273: + warn("Results are not valid for temperatures below 273.15 K.") + if temperature > 623.15: + warn("Results are not valid for temperatures above 623.15 K.") + + # IAPWS region 4 parameters + n4 = [0.11670521452767e4, -0.72421316703206e6, -0.17073846940092e2, + 0.12020824702470e5, -0.32325550322333e7, 0.14915108613530e2, + -0.48232657361591e4, 0.40511340542057e6, -0.23855557567849, + 0.65017534844798e3] + + # Compute the saturation temperature at the given pressure. + beta = pressure**(0.25) + E = beta**2 + n4[2] * beta + n4[5] + F = n4[0] * beta**2 + n4[3] * beta + n4[6] + G = n4[1] * beta**2 + n4[4] * beta + n4[7] + D = 2.0 * G / (-F - sqrt(F**2 - 4 * E * G)) + T_sat = 0.5 * (n4[9] + D + - sqrt((n4[9] + D)**2 - 4.0 * (n4[8] + n4[9] * D))) + + # Make sure we aren't above saturation. (Relax this bound by .2 degrees + # for deg C to K conversions.) + if temperature > T_sat + 0.2: + warn("Results are not valid for temperatures above saturation " + "(above the boiling point).") + + # IAPWS region 1 parameters + R_GAS_CONSTANT = 0.461526 # kJ / kg / K + ref_p = 16.53 # MPa + ref_T = 1386 # K + n1f = [0.14632971213167, -0.84548187169114, -0.37563603672040e1, + 0.33855169168385e1, -0.95791963387872, 0.15772038513228, + -0.16616417199501e-1, 0.81214629983568e-3, 0.28319080123804e-3, + -0.60706301565874e-3, -0.18990068218419e-1, -0.32529748770505e-1, + -0.21841717175414e-1, -0.52838357969930e-4, -0.47184321073267e-3, + -0.30001780793026e-3, 0.47661393906987e-4, -0.44141845330846e-5, + -0.72694996297594e-15, -0.31679644845054e-4, -0.28270797985312e-5, + -0.85205128120103e-9, -0.22425281908000e-5, -0.65171222895601e-6, + -0.14341729937924e-12, -0.40516996860117e-6, -0.12734301741641e-8, + -0.17424871230634e-9, -0.68762131295531e-18, 0.14478307828521e-19, + 0.26335781662795e-22, -0.11947622640071e-22, 0.18228094581404e-23, + -0.93537087292458e-25] + I1f = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, + 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32] + J1f = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, + 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41] + + # Nondimensionalize the pressure and temperature. + pi = pressure / ref_p + tau = ref_T / temperature + + # Compute the derivative of gamma (dimensionless Gibbs free energy) with + # respect to pi. + gamma1_pi = 0.0 + for n, I, J in zip(n1f, I1f, J1f): + gamma1_pi -= n * I * (7.1 - pi)**(I - 1) * (tau - 1.222)**J + + # Compute the leading coefficient. This sets the units at + # 1 [MPa] * [kg K / kJ] * [1 / K] + # = 1e6 [N / m^2] * 1e-3 [kg K / N / m] * [1 / K] + # = 1e3 [kg / m^3] + # = 1 [g / cm^3] + coeff = pressure / R_GAS_CONSTANT / temperature + + # Compute and return the density. + return coeff / pi / gamma1_pi + + +def gnd_name(Z, A, m=0): + """Return nuclide name using GND convention + + Parameters + ---------- + Z : int + Atomic number + A : int + Mass number + m : int, optional + Metastable state + + Returns + ------- + str + Nuclide name in GND convention, e.g., 'Am242_m1' + + """ + if m > 0: + return '{}{}_m{}'.format(ATOMIC_SYMBOL[Z], A, m) + else: + return '{}{}'.format(ATOMIC_SYMBOL[Z], A) + + +def zam(name): + """Return tuple of (atomic number, mass number, metastable state) + + Parameters + ---------- + name : str + Name of nuclide using GND convention, e.g., 'Am242_m1' + + Returns + ------- + 3-tuple of int + Atomic number, mass number, and metastable state + + """ + try: + symbol, A, state = _GND_NAME_RE.match(name).groups() + except AttributeError: + raise ValueError("'{}' does not appear to be a nuclide name in GND " + "format.".format(name)) + metastable = int(state[2:]) if state else 0 + return (ATOMIC_NUMBER[symbol], int(A), metastable) # Values here are from the Committee on Data for Science and Technology @@ -214,8 +369,9 @@ def atomic_weight(element): # The value of the Boltzman constant in units of eV / K K_BOLTZMANN = 8.6173303e-5 -# Used for converting units in ACE data +# Unit conversions EV_PER_MEV = 1.0e6 +JOULE_PER_EV = 1.6021766208e-19 # Avogadro's constant AVOGADRO = 6.022140857e23 diff --git a/openmc/data/decay.py b/openmc/data/decay.py index 4327b2fc35..bbb059f4fa 100644 --- a/openmc/data/decay.py +++ b/openmc/data/decay.py @@ -1,16 +1,13 @@ -from collections import Iterable, namedtuple +from collections import namedtuple +from collections.abc import Iterable from io import StringIO from math import log from numbers import Real import re from warnings import warn -from six import string_types import numpy as np -try: - from uncertainties import ufloat, unumpy, UFloat -except ImportError: - ufloat = UFloat = namedtuple('UFloat', ['nominal_value', 'std_dev']) +from uncertainties import ufloat, unumpy, UFloat import openmc.checkvalue as cv from openmc.mixin import EqualityMixin @@ -278,12 +275,12 @@ class DecayMode(EqualityMixin): @modes.setter def modes(self, modes): - cv.check_type('decay modes', modes, Iterable, string_types) + cv.check_type('decay modes', modes, Iterable, str) self._modes = modes @parent.setter def parent(self, parent): - cv.check_type('parent nuclide', parent, string_types) + cv.check_type('parent nuclide', parent, str) self._parent = parent @@ -457,6 +454,7 @@ class Decay(EqualityMixin): items, values = get_list_record(file_obj) self.nuclide['spin'] = items[0] self.nuclide['parity'] = items[1] + self.half_life = ufloat(float('inf'), float('inf')) @property def decay_constant(self): diff --git a/openmc/data/endf.py b/openmc/data/endf.py index 0fa75ded89..0d1f402c2f 100644 --- a/openmc/data/endf.py +++ b/openmc/data/endf.py @@ -6,19 +6,18 @@ Data File ENDF-6". The latest version from June 2009 can be found at http://www-nds.iaea.org/ndspub/documents/endf/endf102/endf102.pdf """ -from __future__ import print_function, division, unicode_literals - import io import re import os from math import pi -from collections import OrderedDict, Iterable +from pathlib import PurePath +from collections import OrderedDict +from collections.abc import Iterable -from six import string_types import numpy as np from numpy.polynomial.polynomial import Polynomial -from .data import ATOMIC_SYMBOL +from .data import ATOMIC_SYMBOL, gnd_name from .function import Tabulated1D, INTERPOLATION_SCHEME from openmc.stats.univariate import Uniform, Tabular, Legendre @@ -46,7 +45,7 @@ SUM_RULES = {1: [2, 3], 106: list(range(750, 800)), 107: list(range(800, 850))} -ENDF_FLOAT_RE = re.compile(r'([\s\-\+]?\d*\.\d+)([\+\-]\d+)') +_ENDF_FLOAT_RE = re.compile(r'([\s\-\+]?\d*\.\d+)([\+\-]\d+)') def float_endf(s): @@ -69,7 +68,7 @@ def float_endf(s): The number """ - return float(ENDF_FLOAT_RE.sub(r'\1e\2', s)) + return float(_ENDF_FLOAT_RE.sub(r'\1e\2', s)) def get_text_record(file_obj): @@ -250,6 +249,7 @@ def get_tab2_record(file_obj): return params, Tabulated2D(breakpoints, interpolation) + def get_evaluations(filename): """Return a list of all evaluations within an ENDF file. @@ -301,8 +301,8 @@ class Evaluation(object): """ def __init__(self, filename_or_obj): - if isinstance(filename_or_obj, string_types): - fh = open(filename_or_obj, 'r') + if isinstance(filename_or_obj, (str, PurePath)): + fh = open(str(filename_or_obj), 'r') else: fh = filename_or_obj self.section = {} @@ -425,13 +425,9 @@ class Evaluation(object): @property def gnd_name(self): - symbol = ATOMIC_SYMBOL[self.target['atomic_number']] - A = self.target['mass_number'] - m = self.target['isomeric_state'] - if m > 0: - return '{}{}_m{}'.format(symbol, A, m) - else: - return '{}{}'.format(symbol, A) + return gnd_name(self.target['atomic_number'], + self.target['mass_number'], + self.target['isomeric_state']) class Tabulated2D(object): diff --git a/openmc/data/energy_distribution.py b/openmc/data/energy_distribution.py index c3740beaf0..9e01a4b302 100644 --- a/openmc/data/energy_distribution.py +++ b/openmc/data/energy_distribution.py @@ -1,9 +1,8 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable +from collections.abc import Iterable from numbers import Integral, Real from warnings import warn -from six import add_metaclass import numpy as np from .function import Tabulated1D, INTERPOLATION_SCHEME @@ -14,8 +13,7 @@ from .data import EV_PER_MEV from .endf import get_tab1_record, get_tab2_record -@add_metaclass(ABCMeta) -class EnergyDistribution(EqualityMixin): +class EnergyDistribution(EqualityMixin, metaclass=ABCMeta): """Abstract superclass for all energy distributions.""" def __init__(self): pass @@ -116,7 +114,7 @@ class ArbitraryTabulated(EnergyDistribution): """ def __init__(self, energy, pdf): - super(ArbitraryTabulated, self).__init__() + super().__init__() self.energy = energy self.pdf = pdf @@ -184,7 +182,7 @@ class GeneralEvaporation(EnergyDistribution): """ def __init__(self, theta, g, u): - super(GeneralEvaporation, self).__init__() + super().__init__() self.theta = theta self.g = g self.u = u @@ -247,7 +245,7 @@ class MaxwellEnergy(EnergyDistribution): """ def __init__(self, theta, u): - super(MaxwellEnergy, self).__init__() + super().__init__() self.theta = theta self.u = u @@ -380,7 +378,7 @@ class Evaporation(EnergyDistribution): """ def __init__(self, theta, u): - super(Evaporation, self).__init__() + super().__init__() self.theta = theta self.u = u @@ -516,7 +514,7 @@ class WattEnergy(EnergyDistribution): """ def __init__(self, a, b, u): - super(WattEnergy, self).__init__() + super().__init__() self.a = a self.b = b self.u = u @@ -684,7 +682,7 @@ class MadlandNix(EnergyDistribution): """ def __init__(self, efl, efh, tm): - super(MadlandNix, self).__init__() + super().__init__() self.efl = efl self.efh = efh self.tm = tm @@ -807,7 +805,7 @@ class DiscretePhoton(EnergyDistribution): """ def __init__(self, primary_flag, energy, atomic_weight_ratio): - super(DiscretePhoton, self).__init__() + super().__init__() self.primary_flag = primary_flag self.energy = energy self.atomic_weight_ratio = atomic_weight_ratio @@ -916,7 +914,7 @@ class LevelInelastic(EnergyDistribution): """ def __init__(self, threshold, mass_ratio): - super(LevelInelastic, self).__init__() + super().__init__() self.threshold = threshold self.mass_ratio = mass_ratio @@ -1021,7 +1019,7 @@ class ContinuousTabular(EnergyDistribution): """ def __init__(self, breakpoints, interpolation, energy, energy_out): - super(ContinuousTabular, self).__init__() + super().__init__() self.breakpoints = breakpoints self.interpolation = interpolation self.energy = energy diff --git a/openmc/data/fission_energy.py b/openmc/data/fission_energy.py index a7cf3dfed3..c602ba2c6f 100644 --- a/openmc/data/fission_energy.py +++ b/openmc/data/fission_energy.py @@ -1,4 +1,4 @@ -from collections import Callable +from collections.abc import Callable from copy import deepcopy from io import StringIO import sys diff --git a/openmc/data/function.py b/openmc/data/function.py index 0515a57c0c..3d09e44fc8 100644 --- a/openmc/data/function.py +++ b/openmc/data/function.py @@ -1,8 +1,7 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable, Callable +from collections.abc import Iterable, Callable from numbers import Real, Integral -from six import add_metaclass import numpy as np import openmc.data @@ -14,8 +13,7 @@ INTERPOLATION_SCHEME = {1: 'histogram', 2: 'linear-linear', 3: 'linear-log', 4: 'log-linear', 5: 'log-log'} -@add_metaclass(ABCMeta) -class Function1D(EqualityMixin): +class Function1D(EqualityMixin, metaclass=ABCMeta): """A function of one independent variable with HDF5 support.""" @abstractmethod def __call__(self): pass diff --git a/openmc/data/kalbach_mann.py b/openmc/data/kalbach_mann.py index de9809df3a..4be0c15d52 100644 --- a/openmc/data/kalbach_mann.py +++ b/openmc/data/kalbach_mann.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from numbers import Real, Integral from warnings import warn @@ -53,7 +53,7 @@ class KalbachMann(AngleEnergy): def __init__(self, breakpoints, interpolation, energy, energy_out, precompound, slope): - super(KalbachMann, self).__init__() + super().__init__() self.breakpoints = breakpoints self.interpolation = interpolation self.energy = energy diff --git a/openmc/data/laboratory.py b/openmc/data/laboratory.py index 3c240b88d1..cfedb292b1 100644 --- a/openmc/data/laboratory.py +++ b/openmc/data/laboratory.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from numbers import Real, Integral import numpy as np @@ -44,7 +44,7 @@ class LaboratoryAngleEnergy(AngleEnergy): """ def __init__(self, breakpoints, interpolation, energy, mu, energy_out): - super(LaboratoryAngleEnergy, self).__init__() + super().__init__() self.breakpoints = breakpoints self.interpolation = interpolation self.energy = energy diff --git a/openmc/data/library.py b/openmc/data/library.py index c179f78f8c..34cd380a55 100644 --- a/openmc/data/library.py +++ b/openmc/data/library.py @@ -1,6 +1,5 @@ import os import xml.etree.ElementTree as ET -from six import string_types import h5py @@ -125,7 +124,7 @@ class DataLibrary(EqualityMixin): raise ValueError("Either path or OPENMC_CROSS_SECTIONS " "environmental variable must be set") - check_type('path', path, string_types) + check_type('path', path, str) tree = ET.parse(path) root = tree.getroot() diff --git a/openmc/data/multipole.py b/openmc/data/multipole.py index 4e77e16ea9..f7a78d9532 100644 --- a/openmc/data/multipole.py +++ b/openmc/data/multipole.py @@ -3,7 +3,6 @@ from math import exp, erf, pi, sqrt import h5py import numpy as np -from six import string_types from . import WMP_VERSION from .data import K_BOLTZMANN @@ -25,7 +24,7 @@ _RM_RF = 3 # Residue fission # Multi-level Breit Wigner indices _MLBW_RT = 1 # Residue total -_MLBW_RX = 2 # Residue compettitive +_MLBW_RX = 2 # Residue competitive _MLBW_RA = 3 # Residue absorption _MLBW_RF = 4 # Residue fission @@ -142,6 +141,12 @@ def _broaden_wmp_polynomials(E, dopp, n): class WindowedMultipole(EqualityMixin): """Resonant cross sections represented in the windowed multipole format. + Parameters + ---------- + formalism : {'MLBW', 'RM'} + The R-matrix formalism used to reconstruct resonances. Either 'MLBW' + for multi-level Breit Wigner or 'RM' for Reich-Moore. + Attributes ---------- num_l : Integral @@ -196,11 +201,9 @@ class WindowedMultipole(EqualityMixin): a/E + b/sqrt(E) + c + d sqrt(E) + ... """ - def __init__(self): - self.num_l = None - self.fit_order = None - self.fissionable = None - self.formalism = None + def __init__(self, formalism): + self._num_l = None + self.formalism = formalism self.spacing = None self.sqrtAWR = None self.start_E = None @@ -219,11 +222,15 @@ class WindowedMultipole(EqualityMixin): @property def fit_order(self): - return self._fit_order + return self.curvefit.shape[1] - 1 @property def fissionable(self): - return self._fissionable + if self.formalism == 'RM': + return self.data.shape[1] == 4 + else: + # Assume self.formalism == 'MLBW' + return self.data.shape[1] == 5 @property def formalism(self): @@ -273,35 +280,10 @@ class WindowedMultipole(EqualityMixin): def curvefit(self): return self._curvefit - @num_l.setter - def num_l(self, num_l): - if num_l is not None: - cv.check_type('num_l', num_l, Integral) - cv.check_greater_than('num_l', num_l, 1, equality=True) - cv.check_less_than('num_l', num_l, 4, equality=True) - # There is an if block in _evaluate that assumes num_l <= 4. - self._num_l = num_l - - @fit_order.setter - def fit_order(self, fit_order): - if fit_order is not None: - cv.check_type('fit_order', fit_order, Integral) - cv.check_greater_than('fit_order', fit_order, 2, equality=True) - # _broaden_wmp_polynomials assumes the curve fit has at least 3 - # terms. - self._fit_order = fit_order - - @fissionable.setter - def fissionable(self, fissionable): - if fissionable is not None: - cv.check_type('fissionable', fissionable, bool) - self._fissionable = fissionable - @formalism.setter def formalism(self, formalism): - if formalism is not None: - cv.check_type('formalism', formalism, string_types) - cv.check_value('formalism', formalism, ('MLBW', 'RM')) + cv.check_type('formalism', formalism, str) + cv.check_value('formalism', formalism, ('MLBW', 'RM')) self._formalism = formalism @spacing.setter @@ -338,9 +320,20 @@ class WindowedMultipole(EqualityMixin): cv.check_type('data', data, np.ndarray) if len(data.shape) != 2: raise ValueError('Multipole data arrays must be 2D') - if data.shape[1] not in (3, 4, 5): # 3 or 4 for RM, 4 or 5 for MLBW - raise ValueError('The second dimension of multipole data arrays' - ' must have a length of 3, 4 or 5') + if self.formalism == 'RM': + if data.shape[1] not in (3, 4): + raise ValueError('For the Reich-Moore formalism, ' + 'data.shape[1] must be 3 or 4. One value for the pole.' + ' One each for the total and absorption residues. ' + 'Possibly one more for a fission residue.') + else: + # Assume self.formalism == 'MLBW' + if data.shape[1] not in (4, 5): + raise ValueError('For the Multi-level Breit-Wigner ' + 'formalism, data.shape[1] must be 4 or 5. One value ' + 'for the pole. One each for the total, competitive, ' + 'and absorption residues. Possibly one more for a ' + 'fission residue.') if not np.issubdtype(data.dtype, complex): raise TypeError('Multipole data arrays must be complex dtype') self._data = data @@ -364,6 +357,12 @@ class WindowedMultipole(EqualityMixin): if not np.issubdtype(l_value.dtype, int): raise TypeError('Multipole l_value arrays must be integer' ' dtype') + + self._num_l = len(np.unique(l_value)) + + else: + self._num_l = None + self._l_value = l_value @w_start.setter @@ -429,6 +428,7 @@ class WindowedMultipole(EqualityMixin): format. """ + if isinstance(group_or_filename, h5py.Group): group = group_or_filename else: @@ -443,20 +443,12 @@ class WindowedMultipole(EqualityMixin): 'Python API expects version ' + WMP_VERSION) group = h5file['nuclide'] - out = cls() - - # Read scalar values. Note that group['max_w'] is ignored. - - length = group['length'].value - windows = group['windows'].value - out.num_l = group['num_l'].value - out.fit_order = group['fit_order'].value - out.fissionable = bool(group['fissionable'].value) + # Read scalars. if group['formalism'].value == _FORM_MLBW: - out.formalism = 'MLBW' + out = cls('MLBW') elif group['formalism'].value == _FORM_RM: - out.formalism = 'RM' + out = cls('RM') else: raise ValueError('Unrecognized/Unsupported R-matrix formalism') @@ -467,39 +459,36 @@ class WindowedMultipole(EqualityMixin): # Read arrays. - err = "WMP '{}' array shape is not consistent with the '{}' value" + err = "WMP '{}' array shape is not consistent with the '{}' array shape" out.data = group['data'].value - if out.data.shape[0] != length: - raise ValueError(err.format('data', 'length')) + + out.l_value = group['l_value'].value + if out.l_value.shape[0] != out.data.shape[0]: + raise ValueError(err.format('l_value', 'data')) out.pseudo_k0RS = group['pseudo_K0RS'].value if out.pseudo_k0RS.shape[0] != out.num_l: - raise ValueError(err.format('pseudo_k0RS', 'num_l')) - - out.l_value = group['l_value'].value - if out.l_value.shape[0] != length: - raise ValueError(err.format('l_value', 'length')) + raise ValueError(err.format('pseudo_k0RS', 'l_value')) out.w_start = group['w_start'].value - if out.w_start.shape[0] != windows: - raise ValueError(err.format('w_start', 'windows')) out.w_end = group['w_end'].value - if out.w_end.shape[0] != windows: - raise ValueError(err.format('w_end', 'windows')) + if out.w_end.shape[0] != out.w_start.shape[0]: + raise ValueError(err.format('w_end', 'w_start')) out.broaden_poly = group['broaden_poly'].value.astype(np.bool) - if out.broaden_poly.shape[0] != windows: - raise ValueError(err.format('broaden_poly', 'windows')) + if out.broaden_poly.shape[0] != out.w_start.shape[0]: + raise ValueError(err.format('broaden_poly', 'w_start')) out.curvefit = group['curvefit'].value - if out.curvefit.shape[0] != windows: - raise ValueError(err.format('curvefit', 'windows')) - if out.curvefit.shape[1] != out.fit_order + 1: - raise ValueError(err.format('curvefit', 'fit_order')) + if out.curvefit.shape[0] != out.w_start.shape[0]: + raise ValueError(err.format('curvefit', 'w_start')) - # Note that all the file 3 data (group['reactions/MT...']) are ignored. + # _broaden_wmp_polynomials assumes the curve fit has at least 3 terms. + if out.fit_order < 2: + raise ValueError("Windowed multipole is only supported for " + "curvefits with 3 or more terms.") return out @@ -662,3 +651,47 @@ class WindowedMultipole(EqualityMixin): fun = np.vectorize(lambda x: self._evaluate(x, T)) return fun(E) + + def export_to_hdf5(self, path, libver='earliest'): + """Export windowed multipole data to an HDF5 file. + + Parameters + ---------- + path : str + Path to write HDF5 file to + libver : {'earliest', 'latest'} + Compatibility mode for the HDF5 file. 'latest' will produce files + that are less backwards compatible but have performance benefits. + + """ + + # Open file and write version. + with h5py.File(path, 'w', libver=libver) as f: + f.create_dataset('version', (1, ), dtype='S10') + f['version'][:] = WMP_VERSION.encode('ASCII') + + # Make a nuclide group. + g = f.create_group('nuclide') + + # Write scalars. + if self.formalism == 'MLBW': + g.create_dataset('formalism', + data=np.array(_FORM_MLBW, dtype=np.int32)) + else: + # Assume RM. + g.create_dataset('formalism', + data=np.array(_FORM_RM, dtype=np.int32)) + g.create_dataset('spacing', data=np.array(self.spacing)) + g.create_dataset('sqrtAWR', data=np.array(self.sqrtAWR)) + g.create_dataset('start_E', data=np.array(self.start_E)) + g.create_dataset('end_E', data=np.array(self.end_E)) + + # Write arrays. + g.create_dataset('data', data=self.data) + g.create_dataset('l_value', data=self.l_value) + g.create_dataset('pseudo_K0RS', data=self.pseudo_k0RS) + g.create_dataset('w_start', data=self.w_start) + g.create_dataset('w_end', data=self.w_end) + g.create_dataset('broaden_poly', + data=self.broaden_poly.astype(np.int8)) + g.create_dataset('curvefit', data=self.curvefit) diff --git a/openmc/data/neutron.py b/openmc/data/neutron.py index 7dcac5d6e6..1cc0e38879 100644 --- a/openmc/data/neutron.py +++ b/openmc/data/neutron.py @@ -1,6 +1,6 @@ -from __future__ import division, unicode_literals import sys -from collections import OrderedDict, Iterable, Mapping, MutableMapping +from collections import OrderedDict +from collections.abc import Iterable, Mapping, MutableMapping from io import StringIO from itertools import chain from math import log10 @@ -10,13 +10,12 @@ import shutil import tempfile from warnings import warn -from six import string_types import numpy as np import h5py from . import HDF5_VERSION, HDF5_VERSION_MAJOR from .ace import Library, Table, get_table -from .data import ATOMIC_SYMBOL, K_BOLTZMANN, EV_PER_MEV +from .data import ATOMIC_SYMBOL, K_BOLTZMANN, EV_PER_MEV, gnd_name from .endf import Evaluation, SUM_RULES, get_head_record, get_tab1_record from .fission_energy import FissionEnergyRelease from .function import Tabulated1D, Sum, ResonancesWithBackground @@ -94,9 +93,7 @@ def _get_metadata(zaid, metastable_scheme='nndc'): # Determine name element = ATOMIC_SYMBOL[Z] - name = '{}{}'.format(element, mass_number) - if metastable > 0: - name += '_m{}'.format(metastable) + name = gnd_name(Z, mass_number, metastable) return (name, element, Z, mass_number, metastable) @@ -245,7 +242,7 @@ class IncidentNeutron(EqualityMixin): @name.setter def name(self, name): - cv.check_type('name', name, string_types) + cv.check_type('name', name, str) self._name = name @property @@ -301,7 +298,7 @@ class IncidentNeutron(EqualityMixin): def urr(self, urr): cv.check_type('probability table dictionary', urr, MutableMapping) for key, value in urr: - cv.check_type('probability table temperature', key, string_types) + cv.check_type('probability table temperature', key, str) cv.check_type('probability tables', value, ProbabilityTables) self._urr = urr @@ -842,10 +839,7 @@ class IncidentNeutron(EqualityMixin): Incident neutron continuous-energy data """ - # Create temporary directory -- it would be preferable to use - # TemporaryDirectory(), but it is only available in Python 3.2 - tmpdir = tempfile.mkdtemp() - try: + with tempfile.TemporaryDirectory() as tmpdir: # Run NJOY to create an ACE library ace_file = os.path.join(tmpdir, 'ace') xsdir_file = os.path.join(tmpdir, 'xsdir') @@ -873,8 +867,4 @@ class IncidentNeutron(EqualityMixin): data.energy['0K'] = xs.x data[2].xs['0K'] = xs - finally: - # Get rid of temporary files - shutil.rmtree(tmpdir) - return data diff --git a/openmc/data/njoy.py b/openmc/data/njoy.py index b08b3bdfb3..b2894b3d1c 100644 --- a/openmc/data/njoy.py +++ b/openmc/data/njoy.py @@ -1,4 +1,3 @@ -from __future__ import print_function import argparse from collections import namedtuple from io import StringIO @@ -150,10 +149,7 @@ def run(commands, tapein, tapeout, input_filename=None, stdout=False, with open(input_filename, 'w') as f: f.write(commands) - # Create temporary directory -- it would be preferable to use - # TemporaryDirectory(), but it is only available in Python 3.2 - tmpdir = tempfile.mkdtemp() - try: + with tempfile.TemporaryDirectory() as tmpdir: # Copy evaluations to appropriates 'tapes' for tape_num, filename in tapein.items(): tmpfilename = os.path.join(tmpdir, 'tape{}'.format(tape_num)) @@ -187,8 +183,6 @@ def run(commands, tapein, tapeout, input_filename=None, stdout=False, tmpfilename = os.path.join(tmpdir, 'tape{}'.format(tape_num)) if os.path.isfile(tmpfilename): shutil.move(tmpfilename, filename) - finally: - shutil.rmtree(tmpdir) def make_pendf(filename, pendf='pendf', error=0.001, stdout=False): diff --git a/openmc/data/product.py b/openmc/data/product.py index bcffec0daf..5b8652d771 100644 --- a/openmc/data/product.py +++ b/openmc/data/product.py @@ -1,9 +1,8 @@ -from collections import Iterable +from collections.abc import Iterable from io import StringIO from numbers import Real import sys -from six import string_types import numpy as np import openmc.checkvalue as cv @@ -113,7 +112,7 @@ class Product(EqualityMixin): @particle.setter def particle(self, particle): - cv.check_type('product particle type', particle, string_types) + cv.check_type('product particle type', particle, str) self._particle = particle @yield_.setter diff --git a/openmc/data/reaction.py b/openmc/data/reaction.py index ac3a049ab1..d3df038f55 100644 --- a/openmc/data/reaction.py +++ b/openmc/data/reaction.py @@ -1,11 +1,9 @@ -from __future__ import division, unicode_literals -from collections import Iterable, Callable, MutableMapping +from collections.abc import Iterable, Callable, MutableMapping from copy import deepcopy from numbers import Real, Integral from warnings import warn from io import StringIO -from six import string_types import numpy as np import openmc.checkvalue as cv @@ -863,7 +861,7 @@ class Reaction(EqualityMixin): def xs(self, xs): cv.check_type('reaction cross section dictionary', xs, MutableMapping) for key, value in xs.items(): - cv.check_type('reaction cross section temperature', key, string_types) + cv.check_type('reaction cross section temperature', key, str) cv.check_type('reaction cross section', value, Callable) self._xs = xs diff --git a/openmc/data/resonance.py b/openmc/data/resonance.py index 8feda92df4..d58f706eb9 100644 --- a/openmc/data/resonance.py +++ b/openmc/data/resonance.py @@ -1,4 +1,5 @@ -from collections import defaultdict, MutableSequence, Iterable +from collections import defaultdict +from collections.abc import MutableSequence, Iterable import io import numpy as np @@ -288,8 +289,8 @@ class MultiLevelBreitWigner(ResonanceRange): """ def __init__(self, target_spin, energy_min, energy_max, channel, scattering): - super(MultiLevelBreitWigner, self).__init__( - target_spin, energy_min, energy_max, channel, scattering) + super().__init__(target_spin, energy_min, energy_max, channel, + scattering) self.parameters = None self.q_value = {} self.atomic_weight_ratio = None @@ -490,8 +491,8 @@ class SingleLevelBreitWigner(MultiLevelBreitWigner): """ def __init__(self, target_spin, energy_min, energy_max, channel, scattering): - super(SingleLevelBreitWigner, self).__init__( - target_spin, energy_min, energy_max, channel, scattering) + super().__init__(target_spin, energy_min, energy_max, channel, + scattering) # Set resonance reconstruction function if _reconstruct: @@ -549,8 +550,8 @@ class ReichMoore(ResonanceRange): """ def __init__(self, target_spin, energy_min, energy_max, channel, scattering): - super(ReichMoore, self).__init__( - target_spin, energy_min, energy_max, channel, scattering) + super().__init__(target_spin, energy_min, energy_max, channel, + scattering) self.parameters = None self.angle_distribution = False self.num_l_convergence = 0 @@ -724,8 +725,7 @@ class RMatrixLimited(ResonanceRange): """ def __init__(self, energy_min, energy_max, particle_pairs, spin_groups): - super(RMatrixLimited, self).__init__(0.0, energy_min, energy_max, - None, None) + super().__init__(0.0, energy_min, energy_max, None, None) self.reduced_width = False self.formalism = 3 self.particle_pairs = particle_pairs @@ -931,8 +931,7 @@ class Unresolved(ResonanceRange): """ def __init__(self, target_spin, energy_min, energy_max, scatter): - super(Unresolved, self).__init__( - target_spin, energy_min, energy_max, None, scatter) + super().__init__(target_spin, energy_min, energy_max, None, scatter) self.energies = None self.parameters = None self.add_to_background = False diff --git a/openmc/data/thermal.py b/openmc/data/thermal.py index 68192de039..a036a2680c 100644 --- a/openmc/data/thermal.py +++ b/openmc/data/thermal.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from difflib import get_close_matches from numbers import Real import itertools @@ -623,10 +623,7 @@ class ThermalScattering(EqualityMixin): Thermal scattering data """ - # Create temporary directory -- it would be preferable to use - # TemporaryDirectory(), but it is only available in Python 3.2 - tmpdir = tempfile.mkdtemp() - try: + with tempfile.TemporaryDirectory() as tmpdir: # Run NJOY to create an ACE library ace_file = os.path.join(tmpdir, 'ace') xsdir_file = os.path.join(tmpdir, 'xsdir') @@ -638,8 +635,5 @@ class ThermalScattering(EqualityMixin): data = cls.from_ace(lib.tables[0]) for table in lib.tables[1:]: data.add_temperature_from_ace(table) - finally: - # Get rid of temporary files - shutil.rmtree(tmpdir) return data diff --git a/openmc/data/urr.py b/openmc/data/urr.py index 1f915974b1..0edccf6f06 100644 --- a/openmc/data/urr.py +++ b/openmc/data/urr.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from numbers import Integral, Real import numpy as np diff --git a/openmc/deplete/__init__.py b/openmc/deplete/__init__.py new file mode 100644 index 0000000000..e49c4e69cf --- /dev/null +++ b/openmc/deplete/__init__.py @@ -0,0 +1,24 @@ +""" +openmc.deplete +============== + +A depletion front-end tool. +""" + +from .dummy_comm import DummyCommunicator +try: + from mpi4py import MPI + comm = MPI.COMM_WORLD + have_mpi = True +except ImportError: + comm = DummyCommunicator() + have_mpi = False + +from .nuclide import * +from .chain import * +from .operator import * +from .reaction_rates import * +from .abc import * +from .results import * +from .results_list import * +from .integrator import * diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py new file mode 100644 index 0000000000..8502909a21 --- /dev/null +++ b/openmc/deplete/abc.py @@ -0,0 +1,142 @@ +"""function module. + +This module contains the Operator class, which is then passed to an integrator +to run a full depletion simulation. +""" + +from collections import namedtuple +import os +from pathlib import Path +from abc import ABCMeta, abstractmethod + +from .chain import Chain + +OperatorResult = namedtuple('OperatorResult', ['k', 'rates']) +OperatorResult.__doc__ = """\ +Result of applying transport operator + +Parameters +---------- +k : float + Resulting eigenvalue +rates : openmc.deplete.ReactionRates + Resulting reaction rates + +""" +try: + OperatorResult.k.__doc__ = None + OperatorResult.rates.__doc__ = None +except AttributeError: + # Can't set __doc__ on properties on Python 3.4 + pass + + +class TransportOperator(metaclass=ABCMeta): + """Abstract class defining a transport operator + + Each depletion integrator is written to work with a generic transport + operator that takes a vector of material compositions and returns an + eigenvalue and reaction rates. This abstract class sets the requirements for + such a transport operator. Users should instantiate + :class:`openmc.deplete.Operator` rather than this class. + + Parameters + ---------- + chain_file : str, optional + Path to the depletion chain XML file. Defaults to the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. + + Attributes + ---------- + dilute_initial : float + Initial atom density to add for nuclides that are zero in initial + condition to ensure they exist in the decay chain. Only done for + nuclides with reaction rates. Defaults to 1.0e3. + + """ + def __init__(self, chain_file=None): + self.dilute_initial = 1.0e3 + self.output_dir = '.' + + # Read depletion chain + if chain_file is None: + chain_file = os.environ.get("OPENMC_DEPLETE_CHAIN", None) + if chain_file is None: + raise IOError("No chain specified, either manually or in " + "environment variable OPENMC_DEPLETE_CHAIN.") + self.chain = Chain.from_xml(chain_file) + + @abstractmethod + def __call__(self, vec, print_out=True): + """Runs a simulation. + + Parameters + ---------- + vec : list of numpy.ndarray + Total atoms to be used in function. + print_out : bool, optional + Whether or not to print out time. + + Returns + ------- + openmc.deplete.OperatorResult + Eigenvalue and reaction rates resulting from transport operator + + """ + pass + + def __enter__(self): + # Save current directory and move to specific output directory + self._orig_dir = os.getcwd() + if not self.output_dir.exists(): + self.output_dir.mkdir() # exist_ok parameter is 3.5+ + + # In Python 3.6+, chdir accepts a Path directly + os.chdir(str(self.output_dir)) + + return self.initial_condition() + + def __exit__(self, exc_type, exc_value, traceback): + self.finalize() + os.chdir(self._orig_dir) + + @property + def output_dir(self): + return self._output_dir + + @output_dir.setter + def output_dir(self, output_dir): + self._output_dir = Path(output_dir) + + @abstractmethod + def initial_condition(self): + """Performs final setup and returns initial condition. + + Returns + ------- + list of numpy.ndarray + Total density for initial conditions. + """ + + pass + + @abstractmethod + def get_results_info(self): + """Returns volume list, cell lists, and nuc lists. + + Returns + ------- + volume : list of float + Volumes corresponding to materials in burn_list + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + burn_list : list of int + A list of all cell IDs to be burned. Used for sorting the simulation. + full_burn_list : list of int + All burnable materials in the geometry. + """ + + pass + + def finalize(self): + pass diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py new file mode 100644 index 0000000000..b5357280c0 --- /dev/null +++ b/openmc/deplete/atom_number.py @@ -0,0 +1,214 @@ +"""AtomNumber module. + +An ndarray to store atom densities with string, integer, or slice indexing. +""" +from collections import OrderedDict + +import numpy as np + + +class AtomNumber(object): + """Stores local material compositions (atoms of each nuclide). + + Parameters + ---------- + local_mats : list of str + Material IDs + nuclides : list of str + Nuclides to be tracked + volume : dict + Volume of each material in [cm^3] + n_nuc_burn : int + Number of nuclides to be burned. + + Attributes + ---------- + index_mat : dict + A dictionary mapping material ID as string to index. + index_nuc : dict + A dictionary mapping nuclide name to index. + volume : numpy.ndarray + Volume of each material in [cm^3]. If a volume is not found, it defaults + to 1 so that reading density still works correctly. + number : numpy.ndarray + Array storing total atoms for each material/nuclide + materials : list of str + Material IDs as strings + nuclides : list of str + All nuclide names + burnable_nuclides : list of str + Burnable nuclides names. Used for sorting the simulation. + n_nuc_burn : int + Number of burnable nuclides. + n_nuc : int + Number of nuclides. + + """ + def __init__(self, local_mats, nuclides, volume, n_nuc_burn): + self.index_mat = OrderedDict((mat, i) for i, mat in enumerate(local_mats)) + self.index_nuc = OrderedDict((nuc, i) for i, nuc in enumerate(nuclides)) + + self.volume = np.ones(len(local_mats)) + for mat, val in volume.items(): + if mat in self.index_mat: + ind = self.index_mat[mat] + self.volume[ind] = val + + self.n_nuc_burn = n_nuc_burn + + self.number = np.zeros((len(local_mats), len(nuclides))) + + def __getitem__(self, pos): + """Retrieves total atom number from AtomNumber. + + Parameters + ---------- + pos : tuple + A two-length tuple containing a material index and a nuc index. + These indexes can be strings (which get converted to integers via + the dictionaries), integers used directly, or slices. + + Returns + ------- + numpy.ndarray + The value indexed from self.number. + """ + + mat, nuc = pos + if isinstance(mat, str): + mat = self.index_mat[mat] + if isinstance(nuc, str): + nuc = self.index_nuc[nuc] + + return self.number[mat, nuc] + + def __setitem__(self, pos, val): + """Sets total atom number into AtomNumber. + + Parameters + ---------- + pos : tuple + A two-length tuple containing a material index and a nuc index. + These indexes can be strings (which get converted to integers via + the dictionaries), integers used directly, or slices. + val : float + The value [atom] to set the array to. + + """ + mat, nuc = pos + if isinstance(mat, str): + mat = self.index_mat[mat] + if isinstance(nuc, str): + nuc = self.index_nuc[nuc] + + self.number[mat, nuc] = val + + @property + def materials(self): + return self.index_mat.keys() + + @property + def nuclides(self): + return self.index_nuc.keys() + + @property + def n_nuc(self): + return len(self.index_nuc) + + @property + def burnable_nuclides(self): + return [nuc for nuc, ind in self.index_nuc.items() + if ind < self.n_nuc_burn] + + def get_atom_density(self, mat, nuc): + """Accesses atom density instead of total number. + + Parameters + ---------- + mat : str, int or slice + Material index. + nuc : str, int or slice + Nuclide index. + + Returns + ------- + numpy.ndarray + Density in [atom/cm^3] + + """ + if isinstance(mat, str): + mat = self.index_mat[mat] + if isinstance(nuc, str): + nuc = self.index_nuc[nuc] + + return self[mat, nuc] / self.volume[mat] + + def set_atom_density(self, mat, nuc, val): + """Sets atom density instead of total number. + + Parameters + ---------- + mat : str, int or slice + Material index. + nuc : str, int or slice + Nuclide index. + val : numpy.ndarray + Array of densities to set in [atom/cm^3] + + """ + if isinstance(mat, str): + mat = self.index_mat[mat] + if isinstance(nuc, str): + nuc = self.index_nuc[nuc] + + self[mat, nuc] = val * self.volume[mat] + + def get_mat_slice(self, mat): + """Gets atom quantity indexed by mats for all burned nuclides + + Parameters + ---------- + mat : str, int or slice + Material index. + + Returns + ------- + numpy.ndarray + The slice requested in [atom]. + + """ + if isinstance(mat, str): + mat = self.index_mat[mat] + + return self[mat, :self.n_nuc_burn] + + def set_mat_slice(self, mat, val): + """Sets atom quantity indexed by mats for all burned nuclides + + Parameters + ---------- + mat : str, int or slice + Material index. + val : numpy.ndarray + The slice to set in [atom] + + """ + if isinstance(mat, str): + mat = self.index_mat[mat] + + self[mat, :self.n_nuc_burn] = val + + def set_density(self, total_density): + """Sets density. + + Sets the density in the exact same order as total_density_list outputs, + allowing for internal consistency + + Parameters + ---------- + total_density : list of numpy.ndarray + Total atoms. + + """ + for i, density_slice in enumerate(total_density): + self.set_mat_slice(i, density_slice) diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py new file mode 100644 index 0000000000..1826ca9ca0 --- /dev/null +++ b/openmc/deplete/chain.py @@ -0,0 +1,440 @@ +"""chain module. + +This module contains information about a depletion chain. A depletion chain is +loaded from an .xml file and all the nuclides are linked together. +""" + +from collections import OrderedDict, defaultdict +from io import StringIO +from itertools import chain +import math +import re +import os + +# Try to use lxml if it is available. It preserves the order of attributes and +# provides a pretty-printer by default. If not available, use OpenMC function to +# pretty print. +try: + import lxml.etree as ET + _have_lxml = True +except ImportError: + import xml.etree.ElementTree as ET + _have_lxml = False +import scipy.sparse as sp + +import openmc.data +from openmc.clean_xml import clean_xml_indentation +from .nuclide import Nuclide, DecayTuple, ReactionTuple + + +# tuple of (reaction name, possible MT values, (dA, dZ)) where dA is the change +# in the mass number and dZ is the change in the atomic number +_REACTIONS = [ + ('(n,2n)', set(chain([16], range(875, 892))), (-1, 0)), + ('(n,3n)', {17}, (-2, 0)), + ('(n,4n)', {37}, (-3, 0)), + ('(n,gamma)', {102}, (1, 0)), + ('(n,p)', set(chain([103], range(600, 650))), (0, -1)), + ('(n,a)', set(chain([107], range(800, 850))), (-3, -2)) +] + + +def replace_missing(product, decay_data): + """Replace missing product with suitable decay daughter. + + Parameters + ---------- + product : str + Name of product in GND format, e.g. 'Y86_m1'. + decay_data : dict + Dictionary of decay data + + Returns + ------- + product : str + Replacement for missing product in GND format. + + """ + # Determine atomic number, mass number, and metastable state + Z, A, state = openmc.data.zam(product) + symbol = openmc.data.ATOMIC_SYMBOL[Z] + + # Replace neutron with proton + if Z == 0 and A == 1: + return 'H1' + + # First check if ground state is available + if state: + product = '{}{}'.format(symbol, A) + + # Find isotope with longest half-life + half_life = 0.0 + for nuclide, data in decay_data.items(): + m = re.match(r'{}(\d+)(?:_m\d+)?'.format(symbol), nuclide) + if m: + # If we find a stable nuclide, stop search + if data.nuclide['stable']: + mass_longest_lived = int(m.group(1)) + break + if data.half_life.nominal_value > half_life: + mass_longest_lived = int(m.group(1)) + half_life = data.half_life.nominal_value + + # If mass number of longest-lived isotope is less than that of missing + # product, assume it undergoes beta-. Otherwise assume beta+. + beta_minus = (mass_longest_lived < A) + + # Iterate until we find an existing nuclide + while product not in decay_data: + if Z > 98: + Z -= 2 + A -= 4 + else: + if beta_minus: + Z += 1 + else: + Z -= 1 + product = '{}{}'.format(openmc.data.ATOMIC_SYMBOL[Z], A) + + return product + + +class Chain(object): + """Full representation of a depletion chain. + + A depletion chain can be created by using the :meth:`from_endf` method which + requires a list of ENDF incident neutron, decay, and neutron fission product + yield sublibrary files. The depletion chain used during a depletion + simulation is indicated by either an argument to + :class:`openmc.deplete.Operator` or through the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable. + + Attributes + ---------- + nuclides : list of openmc.deplete.Nuclide + Nuclides present in the chain. + reactions : list of str + Reactions that are tracked in the depletion chain + nuclide_dict : OrderedDict of str to int + Maps a nuclide name to an index in nuclides. + + """ + + def __init__(self): + self.nuclides = [] + self.reactions = [] + self.nuclide_dict = OrderedDict() + + def __contains__(self, nuclide): + return nuclide in self.nuclide_dict + + def __getitem__(self, name): + """Get a Nuclide by name.""" + return self.nuclides[self.nuclide_dict[name]] + + def __len__(self): + """Number of nuclides in chain.""" + return len(self.nuclides) + + @classmethod + def from_endf(cls, decay_files, fpy_files, neutron_files): + """Create a depletion chain from ENDF files. + + Parameters + ---------- + decay_files : list of str + List of ENDF decay sub-library files + fpy_files : list of str + List of ENDF neutron-induced fission product yield sub-library files + neutron_files : list of str + List of ENDF neutron reaction sub-library files + + """ + chain = cls() + + # Create dictionary mapping target to filename + print('Processing neutron sub-library files...') + reactions = {} + for f in neutron_files: + evaluation = openmc.data.endf.Evaluation(f) + name = evaluation.gnd_name + reactions[name] = {} + for mf, mt, nc, mod in evaluation.reaction_list: + if mf == 3: + file_obj = StringIO(evaluation.section[3, mt]) + openmc.data.endf.get_head_record(file_obj) + q_value = openmc.data.endf.get_cont_record(file_obj)[1] + reactions[name][mt] = q_value + + # Determine what decay and FPY nuclides are available + print('Processing decay sub-library files...') + decay_data = {} + for f in decay_files: + data = openmc.data.Decay(f) + # Skip decay data for neutron itself + if data.nuclide['atomic_number'] == 0: + continue + decay_data[data.nuclide['name']] = data + + print('Processing fission product yield sub-library files...') + fpy_data = {} + for f in fpy_files: + data = openmc.data.FissionProductYields(f) + fpy_data[data.nuclide['name']] = data + + print('Creating depletion_chain...') + missing_daughter = [] + missing_rx_product = [] + missing_fpy = [] + missing_fp = [] + + for idx, parent in enumerate(sorted(decay_data, key=openmc.data.zam)): + data = decay_data[parent] + + nuclide = Nuclide() + nuclide.name = parent + + chain.nuclides.append(nuclide) + chain.nuclide_dict[parent] = idx + + if not data.nuclide['stable'] and data.half_life.nominal_value != 0.0: + nuclide.half_life = data.half_life.nominal_value + nuclide.decay_energy = sum(E.nominal_value for E in + data.average_energies.values()) + sum_br = 0.0 + for i, mode in enumerate(data.modes): + type_ = ','.join(mode.modes) + if mode.daughter in decay_data: + target = mode.daughter + else: + print('missing {} {} {}'.format(parent, ','.join(mode.modes), mode.daughter)) + target = replace_missing(mode.daughter, decay_data) + + # Write branching ratio, taking care to ensure sum is unity + br = mode.branching_ratio.nominal_value + sum_br += br + if i == len(data.modes) - 1 and sum_br != 1.0: + br = 1.0 - sum(m.branching_ratio.nominal_value + for m in data.modes[:-1]) + + # Append decay mode + nuclide.decay_modes.append(DecayTuple(type_, target, br)) + + if parent in reactions: + reactions_available = set(reactions[parent].keys()) + for name, mts, changes in _REACTIONS: + if mts & reactions_available: + delta_A, delta_Z = changes + A = data.nuclide['mass_number'] + delta_A + Z = data.nuclide['atomic_number'] + delta_Z + daughter = '{}{}'.format(openmc.data.ATOMIC_SYMBOL[Z], A) + + if name not in chain.reactions: + chain.reactions.append(name) + + if daughter not in decay_data: + missing_rx_product.append((parent, name, daughter)) + + # Store Q value + for mt in sorted(mts): + if mt in reactions[parent]: + q_value = reactions[parent][mt] + break + else: + q_value = 0.0 + + nuclide.reactions.append(ReactionTuple( + name, daughter, q_value, 1.0)) + + if any(mt in reactions_available for mt in [18, 19, 20, 21, 38]): + if parent in fpy_data: + q_value = reactions[parent][18] + nuclide.reactions.append( + ReactionTuple('fission', 0, q_value, 1.0)) + + if 'fission' not in chain.reactions: + chain.reactions.append('fission') + else: + missing_fpy.append(parent) + + if parent in fpy_data: + fpy = fpy_data[parent] + + if fpy.energies is not None: + nuclide.yield_energies = fpy.energies + else: + nuclide.yield_energies = [0.0] + + for E, table in zip(nuclide.yield_energies, fpy.independent): + yield_replace = 0.0 + yields = defaultdict(float) + for product, y in table.items(): + # Handle fission products that have no decay data available + if product not in decay_data: + daughter = replace_missing(product, decay_data) + product = daughter + yield_replace += y.nominal_value + + yields[product] += y.nominal_value + + if yield_replace > 0.0: + missing_fp.append((parent, E, yield_replace)) + + nuclide.yield_data[E] = [] + for k in sorted(yields, key=openmc.data.zam): + nuclide.yield_data[E].append((k, yields[k])) + + # Display warnings + if missing_daughter: + print('The following decay modes have daughters with no decay data:') + for mode in missing_daughter: + print(' {}'.format(mode)) + print('') + + if missing_rx_product: + print('The following reaction products have no decay data:') + for vals in missing_rx_product: + print('{} {} -> {}'.format(*vals)) + print('') + + if missing_fpy: + print('The following fissionable nuclides have no fission product yields:') + for parent in missing_fpy: + print(' ' + parent) + print('') + + if missing_fp: + print('The following nuclides have fission products with no decay data:') + for vals in missing_fp: + print(' {}, E={} eV (total yield={})'.format(*vals)) + + return chain + + @classmethod + def from_xml(cls, filename): + """Reads a depletion chain XML file. + + Parameters + ---------- + filename : str + The path to the depletion chain XML file. + + """ + chain = cls() + + # Load XML tree + root = ET.parse(str(filename)) + + for i, nuclide_elem in enumerate(root.findall('nuclide')): + nuc = Nuclide.from_xml(nuclide_elem) + chain.nuclide_dict[nuc.name] = i + + # Check for reaction paths + for rx in nuc.reactions: + if rx.type not in chain.reactions: + chain.reactions.append(rx.type) + + chain.nuclides.append(nuc) + + return chain + + def export_to_xml(self, filename): + """Writes a depletion chain XML file. + + Parameters + ---------- + filename : str + The path to the depletion chain XML file. + + """ + + root_elem = ET.Element('depletion_chain') + for nuclide in self.nuclides: + root_elem.append(nuclide.to_xml_element()) + + tree = ET.ElementTree(root_elem) + if _have_lxml: + tree.write(str(filename), encoding='utf-8', pretty_print=True) + else: + clean_xml_indentation(root_elem) + tree.write(str(filename), encoding='utf-8') + + def form_matrix(self, rates): + """Forms depletion matrix. + + Parameters + ---------- + rates : numpy.ndarray + 2D array indexed by (nuclide, reaction) + + Returns + ------- + scipy.sparse.csr_matrix + Sparse matrix representing depletion. + + """ + matrix = defaultdict(float) + reactions = set() + + for i, nuc in enumerate(self.nuclides): + + if nuc.n_decay_modes != 0: + # Decay paths + # Loss + decay_constant = math.log(2) / nuc.half_life + + if decay_constant != 0.0: + matrix[i, i] -= decay_constant + + # Gain + for _, target, branching_ratio in nuc.decay_modes: + # Allow for total annihilation for debug purposes + if target != 'Nothing': + branch_val = branching_ratio * decay_constant + + if branch_val != 0.0: + k = self.nuclide_dict[target] + matrix[k, i] += branch_val + + if nuc.name in rates.index_nuc: + # Extract all reactions for this nuclide in this cell + nuc_ind = rates.index_nuc[nuc.name] + nuc_rates = rates[nuc_ind, :] + + for r_type, target, _, br in nuc.reactions: + # Extract reaction index, and then final reaction rate + r_id = rates.index_rx[r_type] + path_rate = nuc_rates[r_id] + + # Loss term -- make sure we only count loss once for + # reactions with branching ratios + if r_type not in reactions: + reactions.add(r_type) + if path_rate != 0.0: + matrix[i, i] -= path_rate + + # Gain term; allow for total annihilation for debug purposes + if target != 'Nothing': + if r_type != 'fission': + if path_rate != 0.0: + k = self.nuclide_dict[target] + matrix[k, i] += path_rate * br + else: + # Assume that we should always use thermal fission + # yields. At some point it would be nice to account + # for the energy-dependence.. + energy, data = sorted(nuc.yield_data.items())[0] + for product, y in data: + yield_val = y * path_rate + if yield_val != 0.0: + k = self.nuclide_dict[product] + matrix[k, i] += yield_val + + # Clear set of reactions + reactions.clear() + + # Use DOK matrix as intermediate representation, then convert to CSR and return + n = len(self) + matrix_dok = sp.dok_matrix((n, n)) + dict.update(matrix_dok, matrix) + return matrix_dok.tocsr() diff --git a/openmc/deplete/dummy_comm.py b/openmc/deplete/dummy_comm.py new file mode 100644 index 0000000000..b3fa272648 --- /dev/null +++ b/openmc/deplete/dummy_comm.py @@ -0,0 +1,27 @@ +class DummyCommunicator(object): + rank = 0 + size = 1 + + def allgather(self, sendobj): + return [sendobj] + + def allreduce(self, sendobj, op=None): + return sendobj + + def barrier(self): + pass + + def bcast(self, obj, root=0): + return obj + + def gather(self, sendobj, root=0): + return [sendobj] + + def py2f(self): + return 0 + + def reduce(self, sendobj, op=None, root=0): + return sendobj + + def scatter(self, sendobj, root=0): + return sendobj[0] diff --git a/openmc/deplete/integrator/__init__.py b/openmc/deplete/integrator/__init__.py new file mode 100644 index 0000000000..cf8caffdfe --- /dev/null +++ b/openmc/deplete/integrator/__init__.py @@ -0,0 +1,10 @@ +""" +Integrator +=========== + +The integrator subcomponents. +""" + +from .cecm import * +from .cram import * +from .predictor import * diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py new file mode 100644 index 0000000000..61b58d0b95 --- /dev/null +++ b/openmc/deplete/integrator/cecm.py @@ -0,0 +1,78 @@ +"""The CE/CM integrator.""" + +import copy +from collections.abc import Iterable + +from .cram import deplete +from ..results import Results + + +def cecm(operator, timesteps, power, print_out=True): + r"""Deplete using the CE/CM algorithm. + + Implements the second order `CE/CM predictor-corrector algorithm + `_. This algorithm is mathematically + defined as: + + .. math:: + y' &= A(y, t) y(t) + + A_p &= A(y_n, t_n) + + y_m &= \text{expm}(A_p h/2) y_n + + A_c &= A(y_m, t_n + h/2) + + y_{n+1} &= \text{expm}(A_c h) y_n + + Parameters + ---------- + operator : openmc.deplete.TransportOperator + The operator object to simulate on. + timesteps : iterable of float + Array of timesteps in units of [s]. Note that values are not cumulative. + power : float or iterable of float + Power of the reactor in [W]. A single value indicates that the power is + constant over all timesteps. An iterable indicates potentially different + power levels for each timestep. For a 2D problem, the power can be given + in [W/cm] as long as the "volume" assigned to a depletion material is + actually an area in [cm^2]. + print_out : bool, optional + Whether or not to print out time. + + """ + if not isinstance(power, Iterable): + power = [power]*len(timesteps) + + # Generate initial conditions + with operator as vec: + chain = operator.chain + t = 0.0 + for i, (dt, p) in enumerate(zip(timesteps, power)): + # Get beginning-of-timestep reaction rates + x = [copy.deepcopy(vec)] + op_results = [operator(x[0], p)] + + # Deplete for first half of timestep + x_middle = deplete(chain, x[0], op_results[0], dt/2, print_out) + + # Get middle-of-timestep reaction rates + x.append(x_middle) + op_results.append(operator(x_middle, p)) + + # Deplete for full timestep using beginning-of-step materials + x_end = deplete(chain, x[0], op_results[1], dt, print_out) + + # Create results, write to disk + Results.save(operator, x, op_results, [t, t + dt], i) + + # Advance time, update vector + t += dt + vec = copy.deepcopy(x_end) + + # Perform one last simulation + x = [copy.deepcopy(vec)] + op_results = [operator(x[0], power[-1])] + + # Create results, write to disk + Results.save(operator, x, op_results, [t, t], len(timesteps)) diff --git a/openmc/deplete/integrator/cram.py b/openmc/deplete/integrator/cram.py new file mode 100644 index 0000000000..85954603a1 --- /dev/null +++ b/openmc/deplete/integrator/cram.py @@ -0,0 +1,227 @@ +"""Chebyshev Rational Approximation Method module + +Implements two different forms of CRAM for use in openmc.deplete. +""" + +from itertools import repeat +from multiprocessing import Pool +import time + +import numpy as np +import scipy.sparse as sp +import scipy.sparse.linalg as sla + +from .. import comm + + +def deplete(chain, x, op_result, dt, print_out): + """Deplete materials using given reaction rates for a specified time + + Parameters + ---------- + chain : openmc.deplete.Chain + Depletion chain + x : list of numpy.ndarray + Atom number vectors for each material + op_result : openmc.deplete.OperatorResult + Result of applying transport operator (contains reaction rates) + dt : float + Time in [s] to deplete for + print_out : bool + Whether to show elapsed time + + Returns + ------- + x_result : list of numpy.ndarray + Updated atom number vectors for each material + + """ + t_start = time.time() + + # Set up iterators + n_mats = len(x) + chains = repeat(chain, n_mats) + vecs = (x[i] for i in range(n_mats)) + rates = (op_result.rates[i, :, :] for i in range(n_mats)) + dts = repeat(dt, n_mats) + + # Use multiprocessing pool to distribute work + with Pool() as pool: + iters = zip(chains, vecs, rates, dts) + x_result = list(pool.starmap(_cram_wrapper, iters)) + + t_end = time.time() + if comm.rank == 0: + if print_out: + print("Time to matexp: ", t_end - t_start) + + return x_result + + +def _cram_wrapper(chain, n0, rates, dt): + """Wraps depletion matrix creation / CRAM solve for multiprocess execution + + Parameters + ---------- + chain : DepletionChain + Depletion chain used to construct the burnup matrix + n0 : numpy.array + Vector to operate a matrix exponent on. + rates : numpy.ndarray + 2D array indexed by nuclide then by cell. + dt : float + Time to integrate to. + + Returns + ------- + numpy.array + Results of the matrix exponent. + """ + A = chain.form_matrix(rates) + return CRAM48(A, n0, dt) + + +def CRAM16(A, n0, dt): + """Chebyshev Rational Approximation Method, order 16 + + Algorithm is the 16th order Chebyshev Rational Approximation Method, + implemented in the more stable `incomplete partial fraction (IPF) + `_ form. + + Parameters + ---------- + A : scipy.linalg.csr_matrix + Matrix to take exponent of. + n0 : numpy.array + Vector to operate a matrix exponent on. + dt : float + Time to integrate to. + + Returns + ------- + numpy.array + Results of the matrix exponent. + + """ + + alpha = np.array([+2.124853710495224e-16, + +5.464930576870210e+3 - 3.797983575308356e+4j, + +9.045112476907548e+1 - 1.115537522430261e+3j, + +2.344818070467641e+2 - 4.228020157070496e+2j, + +9.453304067358312e+1 - 2.951294291446048e+2j, + +7.283792954673409e+2 - 1.205646080220011e+5j, + +3.648229059594851e+1 - 1.155509621409682e+2j, + +2.547321630156819e+1 - 2.639500283021502e+1j, + +2.394538338734709e+1 - 5.650522971778156e+0j], + dtype=np.complex128) + theta = np.array([+0.0, + +3.509103608414918 + 8.436198985884374j, + +5.948152268951177 + 3.587457362018322j, + -5.264971343442647 + 16.22022147316793j, + +1.419375897185666 + 10.92536348449672j, + +6.416177699099435 + 1.194122393370139j, + +4.993174737717997 + 5.996881713603942j, + -1.413928462488886 + 13.49772569889275j, + -10.84391707869699 + 19.27744616718165j], + dtype=np.complex128) + + n = A.shape[0] + + alpha0 = 2.124853710495224e-16 + + k = 8 + + y = np.array(n0, dtype=np.float64) + for l in range(1, k+1): + y = 2.0*np.real(alpha[l]*sla.spsolve(A*dt - theta[l]*sp.eye(n), y)) + y + + y *= alpha0 + return y + + +def CRAM48(A, n0, dt): + """Chebyshev Rational Approximation Method, order 48 + + Algorithm is the 48th order Chebyshev Rational Approximation Method, + implemented in the more stable `incomplete partial fraction (IPF) + `_ form. + + Parameters + ---------- + A : scipy.linalg.csr_matrix + Matrix to take exponent of. + n0 : numpy.array + Vector to operate a matrix exponent on. + dt : float + Time to integrate to. + + Returns + ------- + numpy.array + Results of the matrix exponent. + + """ + + theta_r = np.array([-4.465731934165702e+1, -5.284616241568964e+0, + -8.867715667624458e+0, +3.493013124279215e+0, + +1.564102508858634e+1, +1.742097597385893e+1, + -2.834466755180654e+1, +1.661569367939544e+1, + +8.011836167974721e+0, -2.056267541998229e+0, + +1.449208170441839e+1, +1.853807176907916e+1, + +9.932562704505182e+0, -2.244223871767187e+1, + +8.590014121680897e-1, -1.286192925744479e+1, + +1.164596909542055e+1, +1.806076684783089e+1, + +5.870672154659249e+0, -3.542938819659747e+1, + +1.901323489060250e+1, +1.885508331552577e+1, + -1.734689708174982e+1, +1.316284237125190e+1]) + theta_i = np.array([+6.233225190695437e+1, +4.057499381311059e+1, + +4.325515754166724e+1, +3.281615453173585e+1, + +1.558061616372237e+1, +1.076629305714420e+1, + +5.492841024648724e+1, +1.316994930024688e+1, + +2.780232111309410e+1, +3.794824788914354e+1, + +1.799988210051809e+1, +5.974332563100539e+0, + +2.532823409972962e+1, +5.179633600312162e+1, + +3.536456194294350e+1, +4.600304902833652e+1, + +2.287153304140217e+1, +8.368200580099821e+0, + +3.029700159040121e+1, +5.834381701800013e+1, + +1.194282058271408e+0, +3.583428564427879e+0, + +4.883941101108207e+1, +2.042951874827759e+1]) + theta = np.array(theta_r + theta_i * 1j, dtype=np.complex128) + + alpha_r = np.array([+6.387380733878774e+2, +1.909896179065730e+2, + +4.236195226571914e+2, +4.645770595258726e+2, + +7.765163276752433e+2, +1.907115136768522e+3, + +2.909892685603256e+3, +1.944772206620450e+2, + +1.382799786972332e+5, +5.628442079602433e+3, + +2.151681283794220e+2, +1.324720240514420e+3, + +1.617548476343347e+4, +1.112729040439685e+2, + +1.074624783191125e+2, +8.835727765158191e+1, + +9.354078136054179e+1, +9.418142823531573e+1, + +1.040012390717851e+2, +6.861882624343235e+1, + +8.766654491283722e+1, +1.056007619389650e+2, + +7.738987569039419e+1, +1.041366366475571e+2]) + alpha_i = np.array([-6.743912502859256e+2, -3.973203432721332e+2, + -2.041233768918671e+3, -1.652917287299683e+3, + -1.783617639907328e+4, -5.887068595142284e+4, + -9.953255345514560e+3, -1.427131226068449e+3, + -3.256885197214938e+6, -2.924284515884309e+4, + -1.121774011188224e+3, -6.370088443140973e+4, + -1.008798413156542e+6, -8.837109731680418e+1, + -1.457246116408180e+2, -6.388286188419360e+1, + -2.195424319460237e+2, -6.719055740098035e+2, + -1.693747595553868e+2, -1.177598523430493e+1, + -4.596464999363902e+3, -1.738294585524067e+3, + -4.311715386228984e+1, -2.777743732451969e+2]) + alpha = np.array(alpha_r + alpha_i * 1j, dtype=np.complex128) + n = A.shape[0] + + alpha0 = 2.258038182743983e-47 + + k = 24 + + y = np.array(n0, dtype=np.float64) + for l in range(k): + y = 2.0*np.real(alpha[l]*sla.spsolve(A*dt - theta[l]*sp.eye(n), y)) + y + + y *= alpha0 + return y diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py new file mode 100644 index 0000000000..9be992c16a --- /dev/null +++ b/openmc/deplete/integrator/predictor.py @@ -0,0 +1,66 @@ +"""First-order predictor algorithm.""" + +import copy +from collections.abc import Iterable + +from .cram import deplete +from ..results import Results + + +def predictor(operator, timesteps, power, print_out=True): + r"""Deplete using a first-order predictor algorithm. + + Implements the first-order predictor algorithm. This algorithm is + mathematically defined as: + + .. math:: + y' &= A(y, t) y(t) + + A_p &= A(y_n, t_n) + + y_{n+1} &= \text{expm}(A_p h) y_n + + Parameters + ---------- + operator : openmc.deplete.TransportOperator + The operator object to simulate on. + timesteps : iterable of float + Array of timesteps in units of [s]. Note that values are not cumulative. + power : float or iterable of float + Power of the reactor in [W]. A single value indicates that the power is + constant over all timesteps. An iterable indicates potentially different + power levels for each timestep. For a 2D problem, the power can be given + in [W/cm] as long as the "volume" assigned to a depletion material is + actually an area in [cm^2]. + print_out : bool, optional + Whether or not to print out time. + + """ + if not isinstance(power, Iterable): + power = [power]*len(timesteps) + + # Generate initial conditions + with operator as vec: + chain = operator.chain + t = 0.0 + for i, (dt, p) in enumerate(zip(timesteps, power)): + # Get beginning-of-timestep reaction rates + x = [copy.deepcopy(vec)] + op_results = [operator(x[0], p)] + + # Create results, write to disk + Results.save(operator, x, op_results, [t, t + dt], i) + + # Deplete for full timestep + x_end = deplete(chain, x[0], op_results[0], dt, print_out) + + # Advance time, update vector + t += dt + vec = copy.deepcopy(x_end) + + # Perform one last simulation + x = [copy.deepcopy(vec)] + op_results = [operator(x[0], power[-1])] + + # Create results, write to disk + Results.save(operator, x, op_results, [t, t], len(timesteps)) diff --git a/openmc/deplete/nuclide.py b/openmc/deplete/nuclide.py new file mode 100644 index 0000000000..8a30214c2c --- /dev/null +++ b/openmc/deplete/nuclide.py @@ -0,0 +1,219 @@ +"""Nuclide module. + +Contains the per-nuclide components of a depletion chain. +""" + +from collections import namedtuple +try: + import lxml.etree as ET +except ImportError: + import xml.etree.ElementTree as ET + + +DecayTuple = namedtuple('DecayTuple', 'type target branching_ratio') +DecayTuple.__doc__ = """\ +Decay mode information + +Parameters +---------- +type : str + Type of the decay mode, e.g., 'beta-' +target : str + Nuclide resulting from decay +branching_ratio : float + Branching ratio of the decay mode + +""" +try: + DecayTuple.type.__doc__ = None + DecayTuple.target.__doc__ = None + DecayTuple.branching_ratio.__doc__ = None +except AttributeError: + # Can't set __doc__ on properties on Python 3.4 + pass + + +ReactionTuple = namedtuple('ReactionTuple', 'type target Q branching_ratio') +ReactionTuple.__doc__ = """\ +Transmutation reaction information + +Parameters +---------- +type : str + Type of the reaction, e.g., 'fission' +target : str + nuclide resulting from reaction +Q : float + Q value of the reaction in [eV] +branching_ratio : float + Branching ratio of the reaction + +""" +try: + ReactionTuple.type.__doc__ = None + ReactionTuple.target.__doc__ = None + ReactionTuple.Q.__doc__ = None + ReactionTuple.branching_ratio.__doc__ = None +except AttributeError: + pass + + +class Nuclide(object): + """Decay modes, reactions, and fission yields for a single nuclide. + + Attributes + ---------- + name : str + Name of nuclide. + half_life : float + Half life of nuclide in [s]. + decay_energy : float + Energy deposited from decay in [eV]. + n_decay_modes : int + Number of decay pathways. + decay_modes : list of openmc.deplete.DecayTuple + Decay mode information. Each element of the list is a named tuple with + attributes 'type', 'target', and 'branching_ratio'. + n_reaction_paths : int + Number of possible reaction pathways. + reactions : list of openmc.deplete.ReactionTuple + Reaction information. Each element of the list is a named tuple with + attribute 'type', 'target', 'Q', and 'branching_ratio'. + yield_data : dict of float to list + Maps tabulated energy to list of (product, yield) for all + neutron-induced fission products. + yield_energies : list of float + Energies at which fission product yiels exist + + """ + + def __init__(self): + # Information about the nuclide + self.name = None + self.half_life = None + self.decay_energy = 0.0 + + # Decay paths + self.decay_modes = [] + + # Reaction paths + self.reactions = [] + + # Neutron fission yields, if present + self.yield_data = {} + self.yield_energies = [] + + @property + def n_decay_modes(self): + return len(self.decay_modes) + + @property + def n_reaction_paths(self): + return len(self.reactions) + + @classmethod + def from_xml(cls, element): + """Read nuclide from an XML element. + + Parameters + ---------- + element : xml.etree.ElementTree.Element + XML element to write nuclide data to + + Returns + ------- + nuc : openmc.deplete.Nuclide + Instance of a nuclide + + """ + nuc = cls() + nuc.name = element.get('name') + + # Check for half-life + if 'half_life' in element.attrib: + nuc.half_life = float(element.get('half_life')) + nuc.decay_energy = float(element.get('decay_energy', '0')) + + # Check for decay paths + for decay_elem in element.iter('decay'): + d_type = decay_elem.get('type') + target = decay_elem.get('target') + branching_ratio = float(decay_elem.get('branching_ratio')) + nuc.decay_modes.append(DecayTuple(d_type, target, branching_ratio)) + + # Check for reaction paths + for reaction_elem in element.iter('reaction'): + r_type = reaction_elem.get('type') + Q = float(reaction_elem.get('Q', '0')) + branching_ratio = float(reaction_elem.get('branching_ratio', '1')) + + # If the type is not fission, get target and Q value, otherwise + # just set null values + if r_type != 'fission': + target = reaction_elem.get('target') + else: + target = None + + # Append reaction + nuc.reactions.append(ReactionTuple( + r_type, target, Q, branching_ratio)) + + fpy_elem = element.find('neutron_fission_yields') + if fpy_elem is not None: + for yields_elem in fpy_elem.iter('fission_yields'): + E = float(yields_elem.get('energy')) + products = yields_elem.find('products').text.split() + yields = [float(y) for y in + yields_elem.find('data').text.split()] + nuc.yield_data[E] = list(zip(products, yields)) + nuc.yield_energies = list(sorted(nuc.yield_data.keys())) + + return nuc + + def to_xml_element(self): + """Write nuclide to XML element. + + Returns + ------- + elem : xml.etree.ElementTree.Element + XML element to write nuclide data to + + """ + elem = ET.Element('nuclide') + elem.set('name', self.name) + + if self.half_life is not None: + elem.set('half_life', str(self.half_life)) + elem.set('decay_modes', str(len(self.decay_modes))) + elem.set('decay_energy', str(self.decay_energy)) + for mode, daughter, br in self.decay_modes: + mode_elem = ET.SubElement(elem, 'decay') + mode_elem.set('type', mode) + mode_elem.set('target', daughter) + mode_elem.set('branching_ratio', str(br)) + + elem.set('reactions', str(len(self.reactions))) + for rx, daughter, Q, br in self.reactions: + rx_elem = ET.SubElement(elem, 'reaction') + rx_elem.set('type', rx) + rx_elem.set('Q', str(Q)) + if rx != 'fission': + rx_elem.set('target', daughter) + if br != 1.0: + rx_elem.set('branching_ratio', str(br)) + + if self.yield_data: + fpy_elem = ET.SubElement(elem, 'neutron_fission_yields') + energy_elem = ET.SubElement(fpy_elem, 'energies') + energy_elem.text = ' '.join(str(E) for E in self.yield_energies) + + for E in self.yield_energies: + yields_elem = ET.SubElement(fpy_elem, 'fission_yields') + yields_elem.set('energy', str(E)) + + products_elem = ET.SubElement(yields_elem, 'products') + products_elem.text = ' '.join(x[0] for x in self.yield_data[E]) + data_elem = ET.SubElement(yields_elem, 'data') + data_elem.text = ' '.join(str(x[1]) for x in self.yield_data[E]) + + return elem diff --git a/openmc/deplete/operator.py b/openmc/deplete/operator.py new file mode 100644 index 0000000000..a1d8ffb0b0 --- /dev/null +++ b/openmc/deplete/operator.py @@ -0,0 +1,562 @@ +"""OpenMC transport operator + +This module implements a transport operator for OpenMC so that it can be used by +depletion integrators. The implementation makes use of the Python bindings to +OpenMC's C API so that reading tally results and updating material number +densities is all done in-memory instead of through the filesystem. + +""" + +import copy +from collections import OrderedDict +from itertools import chain +import os +import time +import xml.etree.ElementTree as ET + +import h5py +import numpy as np + +import openmc +import openmc.capi +from openmc.data import JOULE_PER_EV +from . import comm +from .abc import TransportOperator, OperatorResult +from .atom_number import AtomNumber +from .reaction_rates import ReactionRates + + +def _distribute(items): + """Distribute items across MPI communicator + + Parameters + ---------- + items : list + List of items of distribute + + Returns + ------- + list + Items assigned to process that called + + """ + min_size, extra = divmod(len(items), comm.size) + j = 0 + for i in range(comm.size): + chunk_size = min_size + int(i < extra) + if comm.rank == i: + return items[j:j + chunk_size] + j += chunk_size + + +class Operator(TransportOperator): + """OpenMC transport operator for depletion. + + Instances of this class can be used to perform depletion using OpenMC as the + transport operator. Normally, a user needn't call methods of this class + directly. Instead, an instance of this class is passed to an integrator + function, such as :func:`openmc.deplete.integrator.cecm`. + + Parameters + ---------- + geometry : openmc.Geometry + OpenMC geometry object + settings : openmc.Settings + OpenMC Settings object + chain_file : str, optional + Path to the depletion chain XML file. Defaults to the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. + + Attributes + ---------- + geometry : openmc.Geometry + OpenMC geometry object + settings : openmc.Settings + OpenMC settings object + dilute_initial : float + Initial atom density to add for nuclides that are zero in initial + condition to ensure they exist in the decay chain. Only done for + nuclides with reaction rates. Defaults to 1.0e3. + output_dir : pathlib.Path + Path to output directory to save results. + round_number : bool + Whether or not to round output to OpenMC to 8 digits. + Useful in testing, as OpenMC is incredibly sensitive to exact values. + number : openmc.deplete.AtomNumber + Total number of atoms in simulation. + nuclides_with_data : set of str + A set listing all unique nuclides available from cross_sections.xml. + chain : openmc.deplete.Chain + The depletion chain information necessary to form matrices and tallies. + reaction_rates : openmc.deplete.ReactionRates + Reaction rates from the last operator step. + burnable_mats : list of str + All burnable material IDs + local_mats : list of str + All burnable material IDs being managed by a single process + + """ + def __init__(self, geometry, settings, chain_file=None): + super().__init__(chain_file) + self.round_number = False + self.settings = settings + self.geometry = geometry + + # Clear out OpenMC, create task lists, distribute + openmc.reset_auto_ids() + self.burnable_mats, volume, nuclides = self._get_burnable_mats() + self.local_mats = _distribute(self.burnable_mats) + + # Determine which nuclides have incident neutron data + self.nuclides_with_data = self._get_nuclides_with_data() + self._burnable_nucs = [nuc for nuc in self.nuclides_with_data + if nuc in self.chain] + + # Extract number densities from the geometry + self._extract_number(self.local_mats, volume, nuclides) + + # Create reaction rates array + self.reaction_rates = ReactionRates( + self.local_mats, self._burnable_nucs, self.chain.reactions) + + def __call__(self, vec, power, print_out=True): + """Runs a simulation. + + Parameters + ---------- + vec : list of numpy.ndarray + Total atoms to be used in function. + power : float + Power of the reactor in [W] + print_out : bool, optional + Whether or not to print out time. + + Returns + ------- + openmc.deplete.OperatorResult + Eigenvalue and reaction rates resulting from transport operator + + """ + # Prevent OpenMC from complaining about re-creating tallies + openmc.reset_auto_ids() + + # Update status + self.number.set_density(vec) + + time_start = time.time() + + # Update material compositions and tally nuclides + self._update_materials() + self._tally.nuclides = self._get_tally_nuclides() + + # Run OpenMC + openmc.capi.reset() + openmc.capi.run() + + time_openmc = time.time() + + # Extract results + op_result = self._unpack_tallies_and_normalize(power) + + if comm.rank == 0: + time_unpack = time.time() + + if print_out: + print("Time to openmc: ", time_openmc - time_start) + print("Time to unpack: ", time_unpack - time_openmc) + + return copy.deepcopy(op_result) + + def _get_burnable_mats(self): + """Determine depletable materials, volumes, and nuclids + + Returns + ------- + burnable_mats : list of str + List of burnable material IDs + volume : OrderedDict of str to float + Volume of each material in [cm^3] + nuclides : list of str + Nuclides in order of how they'll appear in the simulation. + + """ + burnable_mats = set() + model_nuclides = set() + volume = OrderedDict() + + # Iterate once through the geometry to get dictionaries + for mat in self.geometry.get_all_materials().values(): + for nuclide in mat.get_nuclides(): + model_nuclides.add(nuclide) + if mat.depletable: + burnable_mats.add(str(mat.id)) + if mat.volume is None: + raise RuntimeError("Volume not specified for depletable " + "material with ID={}.".format(mat.id)) + volume[str(mat.id)] = mat.volume + + # Make sure there are burnable materials + if not burnable_mats: + raise RuntimeError( + "No depletable materials were found in the model.") + + # Sort the sets + burnable_mats = sorted(burnable_mats, key=int) + model_nuclides = sorted(model_nuclides) + + # Construct a global nuclide dictionary, burned first + nuclides = list(self.chain.nuclide_dict) + for nuc in model_nuclides: + if nuc not in nuclides: + nuclides.append(nuc) + + return burnable_mats, volume, nuclides + + def _extract_number(self, local_mats, volume, nuclides): + """Construct AtomNumber using geometry + + Parameters + ---------- + local_mats : list of str + Material IDs to be managed by this process + volume : OrderedDict of str to float + Volumes for the above materials in [cm^3] + nuclides : list of str + Nuclides to be used in the simulation. + + """ + self.number = AtomNumber(local_mats, nuclides, volume, len(self.chain)) + + if self.dilute_initial != 0.0: + for nuc in self._burnable_nucs: + self.number.set_atom_density(np.s_[:], nuc, self.dilute_initial) + + # Now extract the number densities and store + for mat in self.geometry.get_all_materials().values(): + if str(mat.id) in local_mats: + self._set_number_from_mat(mat) + + def _set_number_from_mat(self, mat): + """Extracts material and number densities from openmc.Material + + Parameters + ---------- + mat : openmc.Material + The material to read from + + """ + mat_id = str(mat.id) + + for nuclide, density in mat.get_nuclide_atom_densities().values(): + number = density * 1.0e24 + self.number.set_atom_density(mat_id, nuclide, number) + + def initial_condition(self): + """Performs final setup and returns initial condition. + + Returns + ------- + list of numpy.ndarray + Total density for initial conditions. + """ + + # Create XML files + if comm.rank == 0: + self.geometry.export_to_xml() + self.settings.export_to_xml() + self._generate_materials_xml() + + # Initialize OpenMC library + comm.barrier() + openmc.capi.init(comm) + + # Generate tallies in memory + self._generate_tallies() + + # Return number density vector + return list(self.number.get_mat_slice(np.s_[:])) + + def finalize(self): + """Finalize a depletion simulation and release resources.""" + openmc.capi.finalize() + + def _update_materials(self): + """Updates material compositions in OpenMC on all processes.""" + + for rank in range(comm.size): + number_i = comm.bcast(self.number, root=rank) + + for mat in number_i.materials: + nuclides = [] + densities = [] + for nuc in number_i.nuclides: + if nuc in self.nuclides_with_data: + val = 1.0e-24 * number_i.get_atom_density(mat, nuc) + + # If nuclide is zero, do not add to the problem. + if val > 0.0: + if self.round_number: + val_magnitude = np.floor(np.log10(val)) + val_scaled = val / 10**val_magnitude + val_round = round(val_scaled, 8) + + val = val_round * 10**val_magnitude + + nuclides.append(nuc) + densities.append(val) + else: + # Only output warnings if values are significantly + # negative. CRAM does not guarantee positive values. + if val < -1.0e-21: + print("WARNING: nuclide ", nuc, " in material ", mat, + " is negative (density = ", val, " at/barn-cm)") + number_i[mat, nuc] = 0.0 + + mat_internal = openmc.capi.materials[int(mat)] + mat_internal.set_densities(nuclides, densities) + + def _generate_materials_xml(self): + """Creates materials.xml from self.number. + + Due to uncertainty with how MPI interacts with OpenMC API, this + constructs the XML manually. The long term goal is to do this + through direct memory writing. + + """ + materials = openmc.Materials(self.geometry.get_all_materials() + .values()) + + # Sort nuclides according to order in AtomNumber object + nuclides = list(self.number.nuclides) + for mat in materials: + mat._nuclides.sort(key=lambda x: nuclides.index(x[0])) + + materials.export_to_xml() + + def _get_tally_nuclides(self): + """Determine nuclides that should be tallied for reaction rates. + + This method returns a list of all nuclides that have neutron data and + are listed in the depletion chain. Technically, we should tally nuclides + that may not appear in the depletion chain because we still need to get + the fission reaction rate for these nuclides in order to normalize + power, but that is left as a future exercise. + + Returns + ------- + list of str + Tally nuclides + + """ + nuc_set = set() + + # Create the set of all nuclides in the decay chain in materials marked + # for burning in which the number density is greater than zero. + for nuc in self.number.nuclides: + if nuc in self.nuclides_with_data: + if np.sum(self.number[:, nuc]) > 0.0: + nuc_set.add(nuc) + + # Communicate which nuclides have nonzeros to rank 0 + if comm.rank == 0: + for i in range(1, comm.size): + nuc_newset = comm.recv(source=i, tag=i) + nuc_set |= nuc_newset + else: + comm.send(nuc_set, dest=0, tag=comm.rank) + + if comm.rank == 0: + # Sort nuclides in the same order as self.number + nuc_list = [nuc for nuc in self.number.nuclides + if nuc in nuc_set] + else: + nuc_list = None + + # Store list of tally nuclides on each process + nuc_list = comm.bcast(nuc_list) + return [nuc for nuc in nuc_list if nuc in self.chain] + + def _generate_tallies(self): + """Generates depletion tallies. + + Using information from the depletion chain as well as the nuclides + currently in the problem, this function automatically generates a + tally.xml for the simulation. + + """ + # Create tallies for depleting regions + materials = [openmc.capi.materials[int(i)] + for i in self.burnable_mats] + mat_filter = openmc.capi.MaterialFilter(materials) + + # Set up a tally that has a material filter covering each depletable + # material and scores corresponding to all reactions that cause + # transmutation. The nuclides for the tally are set later when eval() is + # called. + self._tally = openmc.capi.Tally() + self._tally.scores = self.chain.reactions + self._tally.filters = [mat_filter] + + def _unpack_tallies_and_normalize(self, power): + """Unpack tallies from OpenMC and return an operator result + + This method uses OpenMC's C API bindings to determine the k-effective + value and reaction rates from the simulation. The reaction rates are + normalized by the user-specified power, summing the product of the + fission reaction rate times the fission Q value for each material. + + Parameters + ---------- + power : float + Power of the reactor in [W] + + Returns + ------- + openmc.deplete.OperatorResult + Eigenvalue and reaction rates resulting from transport operator + + """ + rates = self.reaction_rates + rates[:, :, :] = 0.0 + + k_combined = openmc.capi.keff()[0] + + # Extract tally bins + materials = self.burnable_mats + nuclides = self._tally.nuclides + + # Form fast map + nuc_ind = [rates.index_nuc[nuc] for nuc in nuclides] + react_ind = [rates.index_rx[react] for react in self.chain.reactions] + + # Compute fission power + # TODO : improve this calculation + + # Keep track of energy produced from all reactions in eV per source + # particle + energy = 0.0 + + # Create arrays to store fission Q values, reaction rates, and nuclide + # numbers + fission_Q = np.zeros(rates.n_nuc) + rates_expanded = np.zeros((rates.n_nuc, rates.n_react)) + number = np.zeros(rates.n_nuc) + + fission_ind = rates.index_rx["fission"] + + for nuclide in self.chain.nuclides: + if nuclide.name in rates.index_nuc: + for rx in nuclide.reactions: + if rx.type == 'fission': + ind = rates.index_nuc[nuclide.name] + fission_Q[ind] = rx.Q + break + + # Extract results + for i, mat in enumerate(self.local_mats): + # Get tally index + slab = materials.index(mat) + + # Get material results hyperslab + results = self._tally.results[slab, :, 1] + + # Zero out reaction rates and nuclide numbers + rates_expanded[:] = 0.0 + number[:] = 0.0 + + # Expand into our memory layout + j = 0 + for nuc, i_nuc_results in zip(nuclides, nuc_ind): + number[i_nuc_results] = self.number[mat, nuc] + for react in react_ind: + rates_expanded[i_nuc_results, react] = results[j] + j += 1 + + # Accumulate energy from fission + energy += np.dot(rates_expanded[:, fission_ind], fission_Q) + + # Divide by total number and store + for i_nuc_results in nuc_ind: + if number[i_nuc_results] != 0.0: + for react in react_ind: + rates_expanded[i_nuc_results, react] /= number[i_nuc_results] + + rates[i, :, :] = rates_expanded + + # Reduce energy produced from all processes + energy = comm.allreduce(energy) + + # Determine power in eV/s + power /= JOULE_PER_EV + + # Scale reaction rates to obtain units of reactions/sec + rates *= power / energy + + return OperatorResult(k_combined, rates) + + def _get_nuclides_with_data(self): + """Loads a cross_sections.xml file to find participating nuclides. + + This allows for nuclides that are important in the decay chain but not + important neutronically, or have no cross section data. + """ + + # Reads cross_sections.xml to create a dictionary containing + # participating (burning and not just decaying) nuclides. + + try: + filename = os.environ["OPENMC_CROSS_SECTIONS"] + except KeyError: + filename = None + + nuclides = set() + + try: + tree = ET.parse(filename) + except Exception: + if filename is None: + msg = "No cross_sections.xml specified in materials." + else: + msg = 'Cross section file "{}" is invalid.'.format(filename) + raise IOError(msg) + + root = tree.getroot() + for nuclide_node in root.findall('library'): + mats = nuclide_node.get('materials') + if not mats: + continue + for name in mats.split(): + # Make a burn list of the union of nuclides in cross_sections.xml + # and nuclides in depletion chain. + if name not in nuclides: + nuclides.add(name) + + return nuclides + + def get_results_info(self): + """Returns volume list, material lists, and nuc lists. + + Returns + ------- + volume : dict of str float + Volumes corresponding to materials in full_burn_dict + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + burn_list : list of int + A list of all material IDs to be burned. Used for sorting the simulation. + full_burn_list : list + List of all burnable material IDs + + """ + nuc_list = self.number.burnable_nuclides + burn_list = self.local_mats + + volume = {} + for i, mat in enumerate(burn_list): + volume[mat] = self.number.volume[i] + + # Combine volume dictionaries across processes + volume_list = comm.allgather(volume) + volume = {k: v for d in volume_list for k, v in d.items()} + + return volume, nuc_list, burn_list, self.burnable_mats diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py new file mode 100644 index 0000000000..fddb88b19d --- /dev/null +++ b/openmc/deplete/reaction_rates.py @@ -0,0 +1,139 @@ +"""ReactionRates module. + +An ndarray to store reaction rates with string, integer, or slice indexing. +""" +from collections import OrderedDict + +import numpy as np + + +class ReactionRates(np.ndarray): + """Reaction rates resulting from a transport operator call + + This class is a subclass of :class:`numpy.ndarray` with a few custom + attributes that make it easy to determine what index corresponds to a given + material, nuclide, and reaction rate. + + Parameters + ---------- + local_mats : list of str + Material IDs + nuclides : list of str + Depletable nuclides + reactions : list of str + Transmutation reactions being tracked + + Attributes + ---------- + index_mat : OrderedDict of str to int + A dictionary mapping material ID as string to index. + index_nuc : OrderedDict of str to int + A dictionary mapping nuclide name as string to index. + index_rx : OrderedDict of str to int + A dictionary mapping reaction name as string to index. + n_mat : int + Number of materials. + n_nuc : int + Number of nucs. + n_react : int + Number of reactions. + + """ + + # NumPy arrays can be created 1) explicitly 2) using view casting, and 3) by + # slicing an existing array. Because of these possibilities, it's necessary + # to put initialization logic in __new__ rather than __init__. Additionally, + # subclasses need to handle the multiple ways of creating arrays by using + # the __array_finalize__ method (discussed here: + # https://docs.scipy.org/doc/numpy/user/basics.subclassing.html) + + def __new__(cls, local_mats, nuclides, reactions): + # Create appropriately-sized zeroed-out ndarray + shape = (len(local_mats), len(nuclides), len(reactions)) + obj = super().__new__(cls, shape) + obj[:] = 0.0 + + # Add mapping attributes + obj.index_mat = {mat: i for i, mat in enumerate(local_mats)} + obj.index_nuc = {nuc: i for i, nuc in enumerate(nuclides)} + obj.index_rx = {rx: i for i, rx in enumerate(reactions)} + + return obj + + def __array_finalize__(self, obj): + if obj is None: + return + self.index_mat = getattr(obj, 'index_mat', None) + self.index_nuc = getattr(obj, 'index_nuc', None) + self.index_rx = getattr(obj, 'index_rx', None) + + # Reaction rates are distributed to other processes via multiprocessing, + # which entails pickling the objects. In order to preserve the custom + # attributes, we have to modify how the ndarray is pickled as described + # here: https://stackoverflow.com/a/26599346/1572453 + + def __reduce__(self): + state = super().__reduce__() + new_state = state[2] + (self.index_mat, self.index_nuc, self.index_rx) + return (state[0], state[1], new_state) + + def __setstate__(self, state): + self.index_mat = state[-3] + self.index_nuc = state[-2] + self.index_rx = state[-1] + super().__setstate__(state[0:-3]) + + @property + def n_mat(self): + return len(self.index_mat) + + @property + def n_nuc(self): + return len(self.index_nuc) + + @property + def n_react(self): + return len(self.index_rx) + + def get(self, mat, nuc, rx): + """Get reaction rate by material/nuclide/reaction + + Parameters + ---------- + mat : str + Material ID as a string + nuc : str + Nuclide name + rx : str + Name of the reaction + + Returns + ------- + float + Reaction rate corresponding to given material, nuclide, and reaction + + """ + mat = self.index_mat[mat] + nuc = self.index_nuc[nuc] + rx = self.index_rx[rx] + return self[mat, nuc, rx] + + def set(self, mat, nuc, rx, value): + """Set reaction rate by material/nuclide/reaction + + Parameters + ---------- + mat : str + Material ID as a string + nuc : str + Nuclide name + rx : str + Name of the reaction + value : float + Corresponding reaction rate to set + + """ + mat = self.index_mat[mat] + nuc = self.index_nuc[nuc] + rx = self.index_rx[rx] + self[mat, nuc, rx] = value diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py new file mode 100644 index 0000000000..ab740e61ec --- /dev/null +++ b/openmc/deplete/results.py @@ -0,0 +1,397 @@ +"""The results module. + +Contains results generation and saving capabilities. +""" + +from collections import OrderedDict +import copy + +import numpy as np +import h5py + +from . import comm, have_mpi +from .reaction_rates import ReactionRates + +_VERSION_RESULTS = (1, 0) + + +class Results(object): + """Output of a depletion run + + Attributes + ---------- + k : list of float + Eigenvalue for each substep. + time : list of float + Time at beginning, end of step, in seconds. + n_mat : int + Number of mats. + n_nuc : int + Number of nuclides. + rates : list of ReactionRates + The reaction rates for each substep. + volume : OrderedDict of int to float + Dictionary mapping mat id to volume. + mat_to_ind : OrderedDict of str to int + A dictionary mapping mat ID as string to index. + nuc_to_ind : OrderedDict of str to int + A dictionary mapping nuclide name as string to index. + mat_to_hdf5_ind : OrderedDict of str to int + A dictionary mapping mat ID as string to global index. + n_hdf5_mats : int + Number of materials in entire geometry. + n_stages : int + Number of stages in simulation. + data : numpy.ndarray + Atom quantity, stored by stage, mat, then by nuclide. + + """ + def __init__(self): + self.k = None + self.time = None + self.rates = None + self.volume = None + + self.mat_to_ind = None + self.nuc_to_ind = None + self.mat_to_hdf5_ind = None + + self.data = None + + def __getitem__(self, pos): + """Retrieves an item from results. + + Parameters + ---------- + pos : tuple + A three-length tuple containing a stage index, mat index and a nuc + index. All can be integers or slices. The second two can be + strings corresponding to their respective dictionary. + + Returns + ------- + float + The atoms for stage, mat, nuc + + """ + stage, mat, nuc = pos + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + + return self.data[stage, mat, nuc] + + def __setitem__(self, pos, val): + """Sets an item from results. + + Parameters + ---------- + pos : tuple + A three-length tuple containing a stage index, mat index and a nuc + index. All can be integers or slices. The second two can be + strings corresponding to their respective dictionary. + + val : float + The value to set data to. + + """ + stage, mat, nuc = pos + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + + self.data[stage, mat, nuc] = val + + @property + def n_mat(self): + return len(self.mat_to_ind) + + @property + def n_nuc(self): + return len(self.nuc_to_ind) + + @property + def n_hdf5_mats(self): + return len(self.mat_to_hdf5_ind) + + @property + def n_stages(self): + return self.data.shape[0] + + def allocate(self, volume, nuc_list, burn_list, full_burn_list, stages): + """Allocates memory of Results. + + Parameters + ---------- + volume : dict of str float + Volumes corresponding to materials in full_burn_dict + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + burn_list : list of int + A list of all mat IDs to be burned. Used for sorting the simulation. + full_burn_list : list of str + List of all burnable material IDs + stages : int + Number of stages in simulation. + + """ + self.volume = copy.deepcopy(volume) + self.nuc_to_ind = {nuc: i for i, nuc in enumerate(nuc_list)} + self.mat_to_ind = {mat: i for i, mat in enumerate(burn_list)} + self.mat_to_hdf5_ind = {mat: i for i, mat in enumerate(full_burn_list)} + + # Create storage array + self.data = np.zeros((stages, self.n_mat, self.n_nuc)) + + def export_to_hdf5(self, filename, step): + """Export results to an HDF5 file + + Parameters + ---------- + filename : str + The filename to write to + step : int + What step is this? + + """ + if have_mpi and h5py.get_config().mpi: + kwargs = {'driver': 'mpio', 'comm': comm} + else: + kwargs = {} + + kwargs['mode'] = "w" if step == 0 else "a" + + with h5py.File(filename, **kwargs) as handle: + self._to_hdf5(handle, step) + + def _write_hdf5_metadata(self, handle): + """Writes result metadata in HDF5 file + + Parameters + ---------- + handle : h5py.File or h5py.Group + An hdf5 file or group type to store this in. + + """ + # Create and save the 5 dictionaries: + # quantities + # self.mat_to_ind -> self.volume (TODO: support for changing volumes) + # self.nuc_to_ind + # reactions + # self.rates[0].nuc_to_ind (can be different from above, above is superset) + # self.rates[0].react_to_ind + # these are shared by every step of the simulation, and should be deduplicated. + + # Store concentration mat and nuclide dictionaries (along with volumes) + + handle.attrs['version'] = np.array(_VERSION_RESULTS) + handle.attrs['filetype'] = np.string_('depletion results') + + mat_list = sorted(self.mat_to_hdf5_ind, key=int) + nuc_list = sorted(self.nuc_to_ind) + rxn_list = sorted(self.rates[0].index_rx) + + n_mats = self.n_hdf5_mats + n_nuc_number = len(nuc_list) + n_nuc_rxn = len(self.rates[0].index_nuc) + n_rxn = len(rxn_list) + n_stages = self.n_stages + + mat_group = handle.create_group("materials") + + for mat in mat_list: + mat_single_group = mat_group.create_group(mat) + mat_single_group.attrs["index"] = self.mat_to_hdf5_ind[mat] + mat_single_group.attrs["volume"] = self.volume[mat] + + nuc_group = handle.create_group("nuclides") + + for nuc in nuc_list: + nuc_single_group = nuc_group.create_group(nuc) + nuc_single_group.attrs["atom number index"] = self.nuc_to_ind[nuc] + if nuc in self.rates[0].index_nuc: + nuc_single_group.attrs["reaction rate index"] = self.rates[0].index_nuc[nuc] + + rxn_group = handle.create_group("reactions") + + for rxn in rxn_list: + rxn_single_group = rxn_group.create_group(rxn) + rxn_single_group.attrs["index"] = self.rates[0].index_rx[rxn] + + # Construct array storage + + handle.create_dataset("number", (1, n_stages, n_mats, n_nuc_number), + maxshape=(None, n_stages, n_mats, n_nuc_number), + chunks=(1, 1, n_mats, n_nuc_number), + dtype='float64') + + handle.create_dataset("reaction rates", (1, n_stages, n_mats, n_nuc_rxn, n_rxn), + maxshape=(None, n_stages, n_mats, n_nuc_rxn, n_rxn), + chunks=(1, 1, n_mats, n_nuc_rxn, n_rxn), + dtype='float64') + + handle.create_dataset("eigenvalues", (1, n_stages), + maxshape=(None, n_stages), dtype='float64') + + handle.create_dataset("time", (1, 2), maxshape=(None, 2), dtype='float64') + + def _to_hdf5(self, handle, index): + """Converts results object into an hdf5 object. + + Parameters + ---------- + handle : h5py.File or h5py.Group + An HDF5 file or group type to store this in. + index : int + What step is this? + + """ + if "/number" not in handle: + comm.barrier() + self._write_hdf5_metadata(handle) + + comm.barrier() + + # Grab handles + number_dset = handle["/number"] + rxn_dset = handle["/reaction rates"] + eigenvalues_dset = handle["/eigenvalues"] + time_dset = handle["/time"] + + # Get number of results stored + number_shape = list(number_dset.shape) + number_results = number_shape[0] + + new_shape = index + 1 + + if number_results < new_shape: + # Extend first dimension by 1 + number_shape[0] = new_shape + number_dset.resize(number_shape) + + rxn_shape = list(rxn_dset.shape) + rxn_shape[0] = new_shape + rxn_dset.resize(rxn_shape) + + eigenvalues_shape = list(eigenvalues_dset.shape) + eigenvalues_shape[0] = new_shape + eigenvalues_dset.resize(eigenvalues_shape) + + time_shape = list(time_dset.shape) + time_shape[0] = new_shape + time_dset.resize(time_shape) + + # If nothing to write, just return + if len(self.mat_to_ind) == 0: + return + + # Add data + # Note, for the last step, self.n_stages = 1, even if n_stages != 1. + n_stages = self.n_stages + inds = [self.mat_to_hdf5_ind[mat] for mat in self.mat_to_ind] + low = min(inds) + high = max(inds) + for i in range(n_stages): + number_dset[index, i, low:high+1, :] = self.data[i, :, :] + rxn_dset[index, i, low:high+1, :, :] = self.rates[i][:, :, :] + if comm.rank == 0: + eigenvalues_dset[index, i] = self.k[i] + if comm.rank == 0: + time_dset[index, :] = self.time + + @classmethod + def from_hdf5(cls, handle, step): + """Loads results object from HDF5. + + Parameters + ---------- + handle : h5py.File or h5py.Group + An HDF5 file or group type to load from. + step : int + What step is this? + + """ + results = cls() + + # Grab handles + number_dset = handle["/number"] + eigenvalues_dset = handle["/eigenvalues"] + time_dset = handle["/time"] + + results.data = number_dset[step, :, :, :] + results.k = eigenvalues_dset[step, :] + results.time = time_dset[step, :] + + # Reconstruct dictionaries + results.volume = OrderedDict() + results.mat_to_ind = OrderedDict() + results.nuc_to_ind = OrderedDict() + rxn_nuc_to_ind = OrderedDict() + rxn_to_ind = OrderedDict() + + for mat, mat_handle in handle["/materials"].items(): + vol = mat_handle.attrs["volume"] + ind = mat_handle.attrs["index"] + + results.volume[mat] = vol + results.mat_to_ind[mat] = ind + + for nuc, nuc_handle in handle["/nuclides"].items(): + ind_atom = nuc_handle.attrs["atom number index"] + results.nuc_to_ind[nuc] = ind_atom + + if "reaction rate index" in nuc_handle.attrs: + rxn_nuc_to_ind[nuc] = nuc_handle.attrs["reaction rate index"] + + for rxn, rxn_handle in handle["/reactions"].items(): + rxn_to_ind[rxn] = rxn_handle.attrs["index"] + + results.rates = [] + # Reconstruct reactions + for i in range(results.n_stages): + rate = ReactionRates(results.mat_to_ind, rxn_nuc_to_ind, rxn_to_ind) + + rate[:] = handle["/reaction rates"][step, i, :, :, :] + results.rates.append(rate) + + return results + + @staticmethod + def save(op, x, op_results, t, step_ind): + """Creates and writes depletion results to disk + + Parameters + ---------- + op : openmc.deplete.TransportOperator + The operator used to generate these results. + x : list of list of numpy.array + The prior x vectors. Indexed [i][cell] using the above equation. + op_results : list of openmc.deplete.OperatorResult + Results of applying transport operator + t : list of float + Time indices. + step_ind : int + Step index. + + """ + # Get indexing terms + vol_dict, nuc_list, burn_list, full_burn_list = op.get_results_info() + + # Create results + stages = len(x) + results = Results() + results.allocate(vol_dict, nuc_list, burn_list, full_burn_list, stages) + + n_mat = len(burn_list) + + for i in range(stages): + for mat_i in range(n_mat): + results[i, mat_i, :] = x[i][mat_i][:] + + results.k = [r.k for r in op_results] + results.rates = [r.rates for r in op_results] + results.time = t + + results.export_to_hdf5("depletion_results.h5", step_ind) diff --git a/openmc/deplete/results_list.py b/openmc/deplete/results_list.py new file mode 100644 index 0000000000..d3d45e955b --- /dev/null +++ b/openmc/deplete/results_list.py @@ -0,0 +1,105 @@ +import h5py +import numpy as np + +from .results import Results, _VERSION_RESULTS +from openmc.checkvalue import check_filetype_version + + +class ResultsList(list): + """A list of openmc.deplete.Results objects + + Parameters + ---------- + filename : str + The filename to read from. + + """ + def __init__(self, filename): + super().__init__() + with h5py.File(str(filename), "r") as fh: + check_filetype_version(fh, 'depletion results', _VERSION_RESULTS[0]) + + # Get number of results stored + n = fh["number"].value.shape[0] + + for i in range(n): + self.append(Results.from_hdf5(fh, i)) + + def get_atoms(self, mat, nuc): + """Get nuclide concentration over time from a single material + + Parameters + ---------- + mat : str + Material name to evaluate + nuc : str + Nuclide name to evaluate + + Returns + ------- + time : numpy.ndarray + Array of times in [s] + concentration : numpy.ndarray + Total number of atoms for specified nuclide + + """ + time = np.empty_like(self) + concentration = np.empty_like(self) + + # Evaluate value in each region + for i, result in enumerate(self): + time[i] = result.time[0] + concentration[i] = result[0, mat, nuc] + + return time, concentration + + def get_reaction_rate(self, mat, nuc, rx): + """Get reaction rate in a single material/nuclide over time + + Parameters + ---------- + mat : str + Material name to evaluate + nuc : str + Nuclide name to evaluate + rx : str + Reaction rate to evaluate + + Returns + ------- + time : numpy.ndarray + Array of times in [s] + rate : numpy.ndarray + Array of reaction rates + + """ + time = np.empty_like(self) + rate = np.empty_like(self) + + # Evaluate value in each region + for i, result in enumerate(self): + time[i] = result.time[0] + rate[i] = result.rates[0].get(mat, nuc, rx) * result[0, mat, nuc] + + return time, rate + + def get_eigenvalue(self): + """Evaluates the eigenvalue from a results list. + + Returns + ------- + time : numpy.ndarray + Array of times in [s] + eigenvalue : numpy.ndarray + k-eigenvalue at each time + + """ + time = np.empty_like(self) + eigenvalue = np.empty_like(self) + + # Get time/eigenvalue at each point + for i, result in enumerate(self): + time[i] = result.time[0] + eigenvalue[i] = result.k[0] + + return time, eigenvalue diff --git a/openmc/element.py b/openmc/element.py index 5ba19c63c4..336d1f028b 100644 --- a/openmc/element.py +++ b/openmc/element.py @@ -1,8 +1,6 @@ from collections import OrderedDict import re import os - -from six import string_types from xml.etree import ElementTree as ET import openmc @@ -29,9 +27,9 @@ class Element(str): """ def __new__(cls, name): - cv.check_type('element name', name, string_types) + cv.check_type('element name', name, str) cv.check_length('element name', name, 1, 2) - return super(Element, cls).__new__(cls, name) + return super().__new__(cls, name) @property def name(self): diff --git a/openmc/examples.py b/openmc/examples.py index 3d6a068273..d48d26839f 100644 --- a/openmc/examples.py +++ b/openmc/examples.py @@ -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 diff --git a/openmc/executor.py b/openmc/executor.py index 51215e8b74..8ad2bd8960 100644 --- a/openmc/executor.py +++ b/openmc/executor.py @@ -1,10 +1,7 @@ -from __future__ import print_function -from collections import Iterable +from collections.abc import Iterable import subprocess from numbers import Integral -from six import string_types - import openmc from openmc import VolumeCalculation @@ -15,18 +12,22 @@ def _run(args, output, cwd): stderr=subprocess.STDOUT, universal_newlines=True) # Capture and re-print OpenMC output in real-time + lines = [] while True: # If OpenMC is finished, break loop line = p.stdout.readline() if not line and p.poll() is not None: break + lines.append(line) if output: # If user requested output, print to screen print(line, end='') - # Return the returncode (integer, zero if no problems encountered) - return p.returncode + # Raise an exception if return status is non-zero + if p.returncode != 0: + raise subprocess.CalledProcessError(p.returncode, ' '.join(args), + ''.join(lines)) def plot_geometry(output=True, openmc_exec='openmc', cwd='.'): @@ -41,8 +42,13 @@ def plot_geometry(output=True, openmc_exec='openmc', cwd='.'): cwd : str, optional Path to working directory to run in + Raises + ------ + subprocess.CalledProcessError + If the `openmc` executable returns a non-zero status + """ - return _run([openmc_exec, '-p'], output, cwd) + _run([openmc_exec, '-p'], output, cwd) def plot_inline(plots, openmc_exec='openmc', cwd='.', convert_exec='convert'): @@ -63,6 +69,11 @@ def plot_inline(plots, openmc_exec='openmc', cwd='.', convert_exec='convert'): convert_exec : str, optional Command that can convert PPM files into PNG files + Raises + ------ + subprocess.CalledProcessError + If the `openmc` executable returns a non-zero status + """ from IPython.display import Image, display @@ -121,6 +132,11 @@ def calculate_volumes(threads=None, output=True, cwd='.', Path to working directory to run in. Defaults to the current working directory. + Raises + ------ + subprocess.CalledProcessError + If the `openmc` executable returns a non-zero status + See Also -------- openmc.VolumeCalculation @@ -133,7 +149,7 @@ def calculate_volumes(threads=None, output=True, cwd='.', if mpi_args is not None: args = mpi_args + args - return _run(args, output, cwd) + _run(args, output, cwd) def run(particles=None, threads=None, geometry_debug=False, @@ -167,8 +183,12 @@ def run(particles=None, threads=None, geometry_debug=False, MPI execute command and any additional MPI arguments to pass, e.g. ['mpiexec', '-n', '8']. - """ + Raises + ------ + subprocess.CalledProcessError + If the `openmc` executable returns a non-zero status + """ args = [openmc_exec] if isinstance(particles, Integral) and particles > 0: @@ -180,7 +200,7 @@ def run(particles=None, threads=None, geometry_debug=False, if geometry_debug: args.append('-g') - if isinstance(restart_file, string_types): + if isinstance(restart_file, str): args += ['-r', restart_file] if tracks: @@ -189,4 +209,4 @@ def run(particles=None, threads=None, geometry_debug=False, if mpi_args is not None: args = mpi_args + args - return _run(args, output, cwd) + _run(args, output, cwd) diff --git a/openmc/filter.py b/openmc/filter.py index 21bb64f8d5..c1b9f8dc92 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -1,4 +1,3 @@ -from __future__ import division from abc import ABCMeta from collections import Iterable, OrderedDict import copy @@ -8,7 +7,6 @@ from numbers import Real, Integral import operator from xml.etree import ElementTree as ET -from six import add_metaclass import numpy as np import pandas as pd @@ -17,6 +15,7 @@ import openmc.checkvalue as cv from .cell import Cell from .material import Material from .mixin import IDManagerMixin +from .surface import Surface from .universe import Universe @@ -24,12 +23,11 @@ _FILTER_TYPES = ['universe', 'material', 'cell', 'cellborn', 'surface', 'mesh', 'energy', 'energyout', 'mu', 'polar', 'azimuthal', 'distribcell', 'delayedgroup', 'energyfunction', 'cellfrom'] -_CURRENT_NAMES = {1: 'x-min out', 2: 'x-min in', - 3: 'x-max out', 4: 'x-max in', - 5: 'y-min out', 6: 'y-min in', - 7: 'y-max out', 8: 'y-max in', - 9: 'z-min out', 10: 'z-min in', - 11: 'z-max out', 12: 'z-max in'} +_CURRENT_NAMES = ( + 'x-min out', 'x-min in', 'x-max out', 'x-max in', + 'y-min out', 'y-min in', 'y-max out', 'y-max in', + 'z-min out', 'z-min in', 'z-max out', 'z-max in' +) class FilterMeta(ABCMeta): @@ -66,12 +64,10 @@ class FilterMeta(ABCMeta): namespace[func_name].__doc__ = old_doc # Make the class. - return super(FilterMeta, cls).__new__(cls, name, bases, namespace, - **kwargs) + return super().__new__(cls, name, bases, namespace, **kwargs) -@add_metaclass(FilterMeta) -class Filter(IDManagerMixin): +class Filter(IDManagerMixin, metaclass=FilterMeta): """Tally modifier that describes phase-space and other characteristics. Parameters @@ -501,9 +497,9 @@ class CellFilter(WithIDFilter): Parameters ---------- - bins : openmc.Cell, Integral, or iterable thereof - The Cells to tally. Either openmc.Cell objects or their - Integral ID numbers can be used. + bins : openmc.Cell, int, or iterable thereof + The cells to tally. Either openmc.Cell objects or their ID numbers can + be used. filter_id : int Unique identifier for the filter @@ -568,86 +564,29 @@ class CellbornFilter(WithIDFilter): expected_type = Cell -class SurfaceFilter(Filter): - """Bins particle currents on Mesh surfaces. +class SurfaceFilter(WithIDFilter): + """Filters particles by surface crossing Parameters ---------- - bins : Iterable of Integral - Indices corresponding to which face of a mesh cell the current is - crossing. + bins : openmc.Surface, int, or iterable of Integral + The surfaces to tally over. Either openmc.Surface objects or their ID + numbers can be used. filter_id : int Unique identifier for the filter Attributes ---------- bins : Iterable of Integral - Indices corresponding to which face of a mesh cell the current is - crossing. + The surfaces to tally over. Either openmc.Surface objects or their ID + numbers can be used. id : int Unique identifier for the filter num_bins : Integral The number of filter bins """ - @Filter.bins.setter - def bins(self, bins): - # Format the bins as a 1D numpy array. - bins = np.atleast_1d(bins) - - # Check the bin values. - cv.check_iterable_type('filter bins', bins, Integral) - for edge in bins: - cv.check_greater_than('filter bin', edge, 0, equality=True) - - self._bins = bins - - @property - def num_bins(self): - # Need to handle number of bins carefully -- for surface current - # tallies, the number of bins depends on the mesh, which we don't have a - # reference to in this filter - return self._num_bins - - def get_pandas_dataframe(self, data_size, stride, **kwargs): - """Builds a Pandas DataFrame for the Filter's bins. - - This method constructs a Pandas DataFrame object for the filter with - columns annotated by filter bin information. This is a helper method for - :meth:`Tally.get_pandas_dataframe`. - - Parameters - ---------- - data_size : int - The total number of bins in the tally corresponding to this filter - stride : int - Stride in memory for the filter - - Returns - ------- - pandas.DataFrame - A Pandas DataFrame with a column of strings describing which surface - the current is crossing and which direction it points. The number - of rows in the DataFrame is the same as the total number of bins in - the corresponding tally, with the filter bin appropriately tiled to - map to the corresponding tally bins. - - See also - -------- - Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe() - - """ - # Initialize Pandas DataFrame - df = pd.DataFrame() - - filter_bins = np.repeat(self.bins, stride) - tile_factor = data_size // len(filter_bins) - filter_bins = np.tile(filter_bins, tile_factor) - filter_bins = [_CURRENT_NAMES[x] for x in filter_bins] - df = pd.concat([df, pd.DataFrame( - {self.short_name.lower(): filter_bins})]) - - return df + expected_type = Surface class MeshFilter(Filter): @@ -675,7 +614,7 @@ class MeshFilter(Filter): def __init__(self, mesh, filter_id=None): self.mesh = mesh - super(MeshFilter, self).__init__(mesh.id, filter_id) + super().__init__(mesh.id, filter_id) @classmethod def from_hdf5(cls, group, **kwargs): @@ -693,7 +632,6 @@ class MeshFilter(Filter): filter_id = int(group.name.split('/')[-1].lstrip('filter ')) out = cls(mesh_obj, filter_id=filter_id) - out._num_bins = group['n_bins'].value return out @@ -709,10 +647,7 @@ class MeshFilter(Filter): @property def num_bins(self): - try: - return self._num_bins - except AttributeError: - return reduce(operator.mul, self.mesh.dimension) + return reduce(operator.mul, self.mesh.dimension) def check_bins(self, bins): if not len(bins) == 1: @@ -736,37 +671,40 @@ class MeshFilter(Filter): # Filter bins for a mesh are an (x,y,z) tuple. Convert (x,y,z) to a # single bin -- this is similar to subroutine mesh_indices_to_bin in # openmc/src/mesh.F90. - if len(self.mesh.dimension) == 3: + n_dim = len(self.mesh.dimension) + if n_dim == 3: + i, j, k = filter_bin nx, ny, nz = self.mesh.dimension - val = (filter_bin[0] - 1) * ny * nz + \ - (filter_bin[1] - 1) * nz + \ - (filter_bin[2] - 1) - else: + return (i - 1) + (j - 1)*nx + (k - 1)*nx*ny + elif n_dim == 2: + i, j, *_ = filter_bin nx, ny = self.mesh.dimension - val = (filter_bin[0] - 1) * ny + \ - (filter_bin[1] - 1) - - return val + return (i - 1) + (j - 1)*nx + else: + return filter_bin[0] - 1 def get_bin(self, bin_index): cv.check_type('bin_index', bin_index, Integral) cv.check_greater_than('bin_index', bin_index, 0, equality=True) cv.check_less_than('bin_index', bin_index, self.num_bins) - # Construct 3-tuple of x,y,z cell indices for a 3D mesh - if len(self.mesh.dimension) == 3: + n_dim = len(self.mesh.dimension) + if n_dim == 3: + # Construct 3-tuple of x,y,z cell indices for a 3D mesh nx, ny, nz = self.mesh.dimension - x = bin_index / (ny * nz) - y = (bin_index - (x * ny * nz)) / nz - z = bin_index - (x * ny * nz) - (y * nz) + x = (bin_index % nx) + 1 + y = (bin_index % (nx * ny)) // nx + 1 + z = bin_index // (nx * ny) + 1 return (x, y, z) - # Construct 2-tuple of x,y cell indices for a 2D mesh - else: + elif n_dim == 2: + # Construct 2-tuple of x,y cell indices for a 2D mesh nx, ny = self.mesh.dimension - x = bin_index / ny - y = bin_index - (x * ny) + x = (bin_index % nx) + 1 + y = bin_index // nx + 1 return (x, y) + else: + return (bin_index + 1,) def get_pandas_dataframe(self, data_size, stride, **kwargs): """Builds a Pandas DataFrame for the Filter's bins. @@ -803,7 +741,134 @@ class MeshFilter(Filter): filter_dict = {} # Append Mesh ID as outermost index of multi-index - mesh_key = 'mesh {0}'.format(self.mesh.id) + mesh_key = 'mesh {}'.format(self.mesh.id) + + # Find mesh dimensions - use 3D indices for simplicity + n_dim = len(self.mesh.dimension) + if n_dim == 3: + nx, ny, nz = self.mesh.dimension + elif n_dim == 2: + nx, ny = self.mesh.dimension + nz = 1 + else: + nx = self.mesh.dimension + ny = nz = 1 + + # Generate multi-index sub-column for x-axis + filter_bins = np.arange(1, nx + 1) + repeat_factor = stride + filter_bins = np.repeat(filter_bins, repeat_factor) + tile_factor = data_size // len(filter_bins) + filter_bins = np.tile(filter_bins, tile_factor) + filter_dict[(mesh_key, 'x')] = filter_bins + + # Generate multi-index sub-column for y-axis + filter_bins = np.arange(1, ny + 1) + repeat_factor = nx * stride + filter_bins = np.repeat(filter_bins, repeat_factor) + tile_factor = data_size // len(filter_bins) + filter_bins = np.tile(filter_bins, tile_factor) + filter_dict[(mesh_key, 'y')] = filter_bins + + # Generate multi-index sub-column for z-axis + filter_bins = np.arange(1, nz + 1) + repeat_factor = nx * ny * stride + filter_bins = np.repeat(filter_bins, repeat_factor) + tile_factor = data_size // len(filter_bins) + filter_bins = np.tile(filter_bins, tile_factor) + filter_dict[(mesh_key, 'z')] = filter_bins + + # Initialize a Pandas DataFrame from the mesh dictionary + df = pd.concat([df, pd.DataFrame(filter_dict)]) + + return df + + +class MeshSurfaceFilter(MeshFilter): + """Filter events by surface crossings on a regular, rectangular mesh. + + Parameters + ---------- + mesh : openmc.Mesh + The Mesh object that events will be tallied onto + filter_id : int + Unique identifier for the filter + + Attributes + ---------- + bins : Integral + The Mesh ID + mesh : openmc.Mesh + The Mesh object that events will be tallied onto + id : int + Unique identifier for the filter + num_bins : Integral + The number of filter bins + + """ + + @property + def num_bins(self): + n_dim = len(self.mesh.dimension) + return 4*n_dim*reduce(operator.mul, self.mesh.dimension) + + def get_bin_index(self, filter_bin): + # Split bin into mesh/surface parts + *mesh_tuple, surf = filter_bin + + # Get index for mesh alone + mesh_index = super().get_bin_index(mesh_tuple) + + # Combine surface and mesh index + n_dim = len(self.mesh.dimension) + for surf_index, name in enumerate(_CURRENT_NAMES): + if surf == name: + return 4*n_dim*mesh_index + surf_index + else: + raise ValueError("'{}' is not a valid mesh surface.".format(surf)) + + def get_bin(self, bin_index): + n_dim = len(self.mesh.dimension) + mesh_index, surf_index = divmod(bin_index, 4*n_dim) + mesh_bin = super().get_bin(mesh_index) + return mesh_bin + (_CURRENT_NAMES[surf_index],) + + def get_pandas_dataframe(self, data_size, stride, **kwargs): + """Builds a Pandas DataFrame for the Filter's bins. + + This method constructs a Pandas DataFrame object for the filter with + columns annotated by filter bin information. This is a helper method for + :meth:`Tally.get_pandas_dataframe`. + + Parameters + ---------- + data_size : int + The total number of bins in the tally corresponding to this filter + stride : int + Stride in memory for the filter + + Returns + ------- + pandas.DataFrame + A Pandas DataFrame with three columns describing the x,y,z mesh + cell indices corresponding to each filter bin. The number of rows + in the DataFrame is the same as the total number of bins in the + corresponding tally, with the filter bin appropriately tiled to map + to the corresponding tally bins. + + See also + -------- + Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe() + + """ + # Initialize Pandas DataFrame + df = pd.DataFrame() + + # Initialize dictionary to build Pandas Multi-index column + filter_dict = {} + + # Append Mesh ID as outermost index of multi-index + mesh_key = 'mesh {}'.format(self.mesh.id) # Find mesh dimensions - use 3D indices for simplicity if len(self.mesh.dimension) == 3: @@ -817,7 +882,7 @@ class MeshFilter(Filter): # Generate multi-index sub-column for x-axis filter_bins = np.arange(1, nx + 1) - repeat_factor = ny * nz * stride + repeat_factor = 12 * stride filter_bins = np.repeat(filter_bins, repeat_factor) tile_factor = data_size // len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) @@ -825,7 +890,7 @@ class MeshFilter(Filter): # Generate multi-index sub-column for y-axis filter_bins = np.arange(1, ny + 1) - repeat_factor = nz * stride + repeat_factor = 12 * nx * stride filter_bins = np.repeat(filter_bins, repeat_factor) tile_factor = data_size // len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) @@ -833,16 +898,21 @@ class MeshFilter(Filter): # Generate multi-index sub-column for z-axis filter_bins = np.arange(1, nz + 1) - repeat_factor = stride + repeat_factor = 12 * nx * ny * stride filter_bins = np.repeat(filter_bins, repeat_factor) tile_factor = data_size // len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) filter_dict[(mesh_key, 'z')] = filter_bins - # Initialize a Pandas DataFrame from the mesh dictionary - df = pd.concat([df, pd.DataFrame(filter_dict)]) + # Generate multi-index sub-column for surface + repeat_factor = stride + filter_bins = np.repeat(_CURRENT_NAMES, repeat_factor) + tile_factor = data_size // len(filter_bins) + filter_bins = np.tile(filter_bins, tile_factor) + filter_dict[(mesh_key, 'surf')] = filter_bins - return df + # Initialize a Pandas DataFrame from the mesh dictionary + return pd.concat([df, pd.DataFrame(filter_dict)]) class RealFilter(Filter): @@ -872,7 +942,7 @@ class RealFilter(Filter): # This logic is used when merging tallies with real filters return self.bins[0] >= other.bins[-1] else: - return super(RealFilter, self).__gt__(other) + return super().__gt__(other) @property def num_bins(self): @@ -1130,7 +1200,7 @@ class DistribcellFilter(Filter): def __init__(self, cell, filter_id=None): self._paths = None - super(DistribcellFilter, self).__init__(cell, filter_id) + super().__init__(cell, filter_id) @classmethod def from_hdf5(cls, group, **kwargs): diff --git a/openmc/geometry.py b/openmc/geometry.py index 0738ae615a..1ee93dfd6d 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -1,9 +1,8 @@ -from collections import OrderedDict, Iterable +from collections import OrderedDict +from collections.abc import Iterable from copy import deepcopy from xml.etree import ElementTree as ET -from six import string_types - import openmc from openmc.clean_xml import clean_xml_indentation from openmc.checkvalue import check_type @@ -14,8 +13,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 +27,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): @@ -132,7 +138,7 @@ class Geometry(object): """ # Make sure we are working with an iterable return_list = (isinstance(paths, Iterable) and - not isinstance(paths, string_types)) + not isinstance(paths, str)) path_list = paths if return_list else [paths] indices = [] @@ -249,7 +255,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 +312,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 +350,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 +395,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 +433,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 +471,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. diff --git a/openmc/lattice.py b/openmc/lattice.py index 79f0d43f3b..86cfd5c41b 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -1,13 +1,11 @@ -from __future__ import division - from abc import ABCMeta -from collections import OrderedDict, Iterable +from collections import OrderedDict +from collections.abc import Iterable from copy import deepcopy from math import sqrt, floor from numbers import Real, Integral from xml.etree import ElementTree as ET -from six import add_metaclass, string_types import numpy as np import openmc.checkvalue as cv @@ -15,8 +13,7 @@ import openmc from openmc.mixin import IDManagerMixin -@add_metaclass(ABCMeta) -class Lattice(IDManagerMixin): +class Lattice(IDManagerMixin, metaclass=ABCMeta): """A repeating structure wherein each element is a universe. Parameters @@ -54,25 +51,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 @@ -92,7 +70,7 @@ class Lattice(IDManagerMixin): @name.setter def name(self, name): if name is not None: - cv.check_type('lattice name', name, string_types) + cv.check_type('lattice name', name, str) self._name = name else: self._name = '' @@ -512,7 +490,7 @@ class RectLattice(Lattice): """ def __init__(self, lattice_id=None, name=''): - super(RectLattice, self).__init__(lattice_id, name) + super().__init__(lattice_id, name) # Initialize Lattice class attributes self._lower_left = None @@ -579,7 +557,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): @@ -839,7 +821,7 @@ class HexLattice(Lattice): """ def __init__(self, lattice_id=None, name=''): - super(HexLattice, self).__init__(lattice_id, name) + super().__init__(lattice_id, name) # Initialize Lattice class attributes self._num_rings = None diff --git a/openmc/macroscopic.py b/openmc/macroscopic.py index cdb5cbb395..2a5a22752a 100644 --- a/openmc/macroscopic.py +++ b/openmc/macroscopic.py @@ -1,5 +1,3 @@ -from six import string_types - from openmc.checkvalue import check_type @@ -19,8 +17,8 @@ class Macroscopic(str): """ def __new__(cls, name): - check_type('name', name, string_types) - return super(Macroscopic, cls).__new__(cls, name) + check_type('name', name, str) + return super().__new__(cls, name) @property def name(self): diff --git a/openmc/material.py b/openmc/material.py index e22fe0b8ba..6bfe58f4ac 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -4,7 +4,6 @@ from numbers import Real, Integral import warnings from xml.etree import ElementTree as ET -from six import string_types import numpy as np import openmc @@ -15,7 +14,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'] @@ -25,7 +24,7 @@ class Material(IDManagerMixin): To create a material, one should create an instance of this class, add nuclides or elements with :meth:`Material.add_nuclide` or `Material.add_element`, respectively, and set the total material density - with `Material.export_to_xml()`. The material can then be assigned to a cell + with `Material.set_density()`. The material can then be assigned to a cell using the :attr:`Cell.fill` attribute. Parameters @@ -49,12 +48,11 @@ 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 - Indicate whether the material is depletable. This attribute can be used - by downstream depletion applications. + Indicate whether the material is depletable. nuclides : list of tuple List in which each item is a 3-tuple consisting of a nuclide string, the percent density, and the percent type ('ao' or 'wo'). @@ -75,6 +73,9 @@ class Material(IDManagerMixin): :meth:`Geometry.determine_paths` method. num_instances : int The number of instances of this material throughout the geometry. + fissionable_mass : float + Mass of fissionable nuclides in the material in [g]. Requires that the + :attr:`volume` attribute is set. """ @@ -87,7 +88,7 @@ class Material(IDManagerMixin): self.name = name self.temperature = temperature self._density = None - self._density_units = '' + self._density_units = 'sum' self._depletable = False self._paths = None self._num_instances = None @@ -217,7 +218,7 @@ class Material(IDManagerMixin): def name(self, name): if name is not None: cv.check_type('name for Material ID="{}"'.format(self._id), - name, string_types) + name, str) self._name = name else: self._name = '' @@ -243,9 +244,21 @@ class Material(IDManagerMixin): @isotropic.setter def isotropic(self, isotropic): cv.check_iterable_type('Isotropic scattering nuclides', isotropic, - string_types) + str) self._isotropic = list(isotropic) + @property + def fissionable_mass(self): + if self.volume is None: + raise ValueError("Volume must be set in order to determine mass.") + density = 0.0 + for nuc, atoms_per_cc in self.get_nuclide_atom_densities().values(): + Z = openmc.data.zam(nuc)[0] + if Z >= 90: + density += 1e24 * atoms_per_cc * openmc.data.atomic_mass(nuc) \ + / openmc.data.AVOGADRO + return density*self.volume + @classmethod def from_hdf5(cls, group): """Create material from HDF5 group @@ -300,7 +313,7 @@ class Material(IDManagerMixin): """ if volume_calc.domain_type == 'material': if self.id in volume_calc.volumes: - self._volume = volume_calc.volumes[self.id][0] + self._volume = volume_calc.volumes[self.id].n self._atoms = volume_calc.atoms[self.id] else: raise ValueError('No volume information found for this material.') @@ -312,7 +325,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 @@ -345,7 +358,7 @@ class Material(IDManagerMixin): warnings.warn('This feature is not yet implemented in a release ' 'version of openmc') - if not isinstance(filename, string_types) and filename is not None: + if not isinstance(filename, str) and filename is not None: msg = 'Unable to add OTF material file to Material ID="{}" with a ' \ 'non-string name "{}"'.format(self._id, filename) raise ValueError(msg) @@ -366,33 +379,31 @@ class Material(IDManagerMixin): Parameters ---------- nuclide : str - Nuclide to add + Nuclide to add, e.g., 'Mo95' percent : float Atom or weight percent percent_type : {'ao', 'wo'} 'ao' for atom percent and 'wo' for weight percent """ + cv.check_type('nuclide', nuclide, str) + cv.check_type('percent', percent, Real) + cv.check_value('percent type', percent_type, {'ao', 'wo'}) if self._macroscopic is not None: msg = 'Unable to add a Nuclide to Material ID="{}" as a ' \ 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(nuclide, string_types): - msg = 'Unable to add a Nuclide to Material ID="{}" with a ' \ - 'non-string value "{}"'.format(self._id, nuclide) - raise ValueError(msg) - - elif not isinstance(percent, Real): - msg = 'Unable to add a Nuclide to Material ID="{}" with a ' \ - 'non-floating point value "{}"'.format(self._id, percent) - raise ValueError(msg) - - elif percent_type not in ('ao', 'wo'): - msg = 'Unable to add a Nuclide to Material ID="{}" with a ' \ - 'percent type "{}"'.format(self._id, percent_type) - raise ValueError(msg) + # If nuclide name doesn't look valid, give a warning + try: + Z, _, _ = openmc.data.zam(nuclide) + except ValueError as e: + warnings.warn(str(e)) + else: + # For actinides, have the material be depletable by default + if Z >= 89: + self.depletable = True self._nuclides.append((nuclide, percent, percent_type)) @@ -405,7 +416,7 @@ class Material(IDManagerMixin): Nuclide to remove """ - cv.check_type('nuclide', nuclide, string_types) + cv.check_type('nuclide', nuclide, str) # If the Material contains the Nuclide, delete it for nuc in self._nuclides: @@ -434,7 +445,7 @@ class Material(IDManagerMixin): 'has already been added'.format(self._id, macroscopic) raise ValueError(msg) - if not isinstance(macroscopic, string_types): + if not isinstance(macroscopic, str): msg = 'Unable to add a Macroscopic to Material ID="{}" with a ' \ 'non-string value "{}"'.format(self._id, macroscopic) raise ValueError(msg) @@ -465,7 +476,7 @@ class Material(IDManagerMixin): """ - if not isinstance(macroscopic, string_types): + if not isinstance(macroscopic, str): msg = 'Unable to remove a Macroscopic "{}" in Material ID="{}" ' \ 'since it is not a string'.format(self._id, macroscopic) raise ValueError(msg) @@ -480,7 +491,7 @@ class Material(IDManagerMixin): Parameters ---------- element : str - Element to add + Element to add, e.g., 'Zr' percent : float Atom or weight percent percent_type : {'ao', 'wo'}, optional @@ -492,27 +503,15 @@ class Material(IDManagerMixin): (natural composition). """ + cv.check_type('nuclide', element, str) + cv.check_type('percent', percent, Real) + cv.check_value('percent type', percent_type, {'ao', 'wo'}) if self._macroscopic is not None: msg = 'Unable to add an Element to Material ID="{}" as a ' \ 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(element, string_types): - msg = 'Unable to add an Element to Material ID="{}" with a ' \ - 'non-string value "{}"'.format(self._id, element) - raise ValueError(msg) - - if not isinstance(percent, Real): - msg = 'Unable to add an Element to Material ID="{}" with a ' \ - 'non-floating point value "{}"'.format(self._id, percent) - raise ValueError(msg) - - if percent_type not in ['ao', 'wo']: - msg = 'Unable to add an Element to Material ID="{}" with a ' \ - 'percent type "{}"'.format(self._id, percent_type) - raise ValueError(msg) - if enrichment is not None: if not isinstance(enrichment, Real): msg = 'Unable to add an Element to Material ID="{}" with a ' \ @@ -538,10 +537,15 @@ class Material(IDManagerMixin): format(enrichment, self._id) warnings.warn(msg) + # Make sure element name is just that + if not element.isalpha(): + raise ValueError("Element name should be given by the " + "element's symbol, e.g., 'Zr'") + # Add naturally-occuring isotopes element = openmc.Element(element) for nuclide in element.expand(percent, percent_type, enrichment): - self._nuclides.append(nuclide) + self.add_nuclide(*nuclide) def add_s_alpha_beta(self, name, fraction=1.0): r"""Add an :math:`S(\alpha,\beta)` table to the material @@ -563,7 +567,7 @@ class Material(IDManagerMixin): 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(name, string_types): + if not isinstance(name, str): msg = 'Unable to add an S(a,b) table to Material ID="{}" with a ' \ 'non-string table name "{}"'.format(self._id, name) raise ValueError(msg) @@ -688,6 +692,51 @@ class Material(IDManagerMixin): return nuclides + def get_mass_density(self, nuclide=None): + """Return mass density of one or all nuclides + + Parameters + ---------- + nuclides : str, optional + Nuclide for which density is desired. If not specified, the density + for the entire material is given. + + Returns + ------- + float + Density of the nuclide/material in [g/cm^3] + + """ + mass_density = 0.0 + for nuc, atoms_per_cc in self.get_nuclide_atom_densities().values(): + density_i = 1e24 * atoms_per_cc * openmc.data.atomic_mass(nuc) \ + / openmc.data.AVOGADRO + if nuclide is None or nuclide == nuc: + mass_density += density_i + return mass_density + + def get_mass(self, nuclide=None): + """Return mass of one or all nuclides. + + Note that this method requires that the :attr:`Material.volume` has + already been set. + + Parameters + ---------- + nuclides : str, optional + Nuclide for which mass is desired. If not specified, the density + for the entire material is given. + + Returns + ------- + float + Mass of the nuclide/material in [g] + + """ + if self.volume is None: + raise ValueError("Volume must be set in order to determine mass.") + return self.volume*self.get_mass_density(nuclide) + def clone(self, memo=None): """Create a copy of this material with a new unique ID. @@ -886,7 +935,7 @@ class Materials(cv.CheckedList): """ def __init__(self, materials=None): - super(Materials, self).__init__(Material, 'materials collection') + super().__init__(Material, 'materials collection') self._cross_sections = None self._multipole_library = None @@ -903,49 +952,14 @@ class Materials(cv.CheckedList): @cross_sections.setter def cross_sections(self, cross_sections): - cv.check_type('cross sections', cross_sections, string_types) + cv.check_type('cross sections', cross_sections, str) self._cross_sections = cross_sections @multipole_library.setter def multipole_library(self, multipole_library): - cv.check_type('cross sections', multipole_library, string_types) + cv.check_type('cross sections', multipole_library, str) self._multipole_library = multipole_library - def add_material(self, material): - """Append material to collection - - .. deprecated:: 0.8 - Use :meth:`Materials.append` instead. - - Parameters - ---------- - material : openmc.Material - Material to add - - """ - warnings.warn("Materials.add_material(...) has been deprecated and may be " - "removed in a future version. Use Material.append(...) " - "instead.", DeprecationWarning) - self.append(material) - - def add_materials(self, materials): - """Add multiple materials to the collection - - .. deprecated:: 0.8 - Use compound assignment instead. - - Parameters - ---------- - materials : Iterable of openmc.Material - Materials to add - - """ - warnings.warn("Materials.add_materials(...) has been deprecated and may be " - "removed in a future version. Use compound assignment " - "instead.", DeprecationWarning) - for material in materials: - self.append(material) - def append(self, material): """Append material to collection @@ -955,7 +969,7 @@ class Materials(cv.CheckedList): Material to append """ - super(Materials, self).append(material) + super().append(material) def insert(self, index, material): """Insert material before index @@ -968,24 +982,7 @@ class Materials(cv.CheckedList): Material to insert """ - super(Materials, self).insert(index, material) - - def remove_material(self, material): - """Remove a material from the file - - .. deprecated:: 0.8 - Use :meth:`Materials.remove` instead. - - Parameters - ---------- - material : openmc.Material - Material to remove - - """ - warnings.warn("Materials.remove_material(...) has been deprecated and " - "may be removed in a future version. Use " - "Materials.remove(...) instead.", DeprecationWarning) - self.remove(material) + super().insert(index, material) def make_isotropic_in_lab(self): for material in self: diff --git a/openmc/mesh.py b/openmc/mesh.py index b315b2628b..cd8eb3c5ed 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3,7 +3,6 @@ from numbers import Real, Integral from xml.etree import ElementTree as ET import sys -from six import string_types import numpy as np import openmc.checkvalue as cv @@ -83,11 +82,29 @@ class Mesh(IDManagerMixin): def num_mesh_cells(self): return np.prod(self._dimension) + @property + def indices(self): + ndim = len(self._dimension) + if ndim == 3: + nx, ny, nz = self.dimension + return ((x, y, z) + for z in range(1, nz + 1) + for y in range(1, ny + 1) + for x in range(1, nx + 1)) + elif ndim == 2: + nx, ny = self.dimension + return ((x, y) + for y in range(1, ny + 1) + for x in range(1, nx + 1)) + else: + nx, = self.dimension + return ((x,) for x in range(1, nx + 1)) + @name.setter def name(self, name): if name is not None: cv.check_type('name for mesh ID="{0}"'.format(self._id), - name, string_types) + name, str) self._name = name else: self._name = '' @@ -95,7 +112,7 @@ class Mesh(IDManagerMixin): @type.setter def type(self, meshtype): cv.check_type('type for mesh ID="{0}"'.format(self._id), - meshtype, string_types) + meshtype, str) cv.check_value('type for mesh ID="{0}"'.format(self._id), meshtype, ['regular']) self._type = meshtype diff --git a/openmc/mgxs/library.py b/openmc/mgxs/library.py index b83305783f..ed8e3f076c 100644 --- a/openmc/mgxs/library.py +++ b/openmc/mgxs/library.py @@ -3,10 +3,10 @@ import os import copy import pickle from numbers import Integral -from collections import OrderedDict, Iterable +from collections import OrderedDict +from collections.abc import Iterable from warnings import warn -from six import string_types import numpy as np import openmc @@ -271,7 +271,7 @@ class Library(object): @name.setter def name(self, name): - cv.check_type('name', name, string_types) + cv.check_type('name', name, str) self._name = name @mgxs_types.setter @@ -280,7 +280,7 @@ class Library(object): if mgxs_types == 'all': self._mgxs_types = all_mgxs_types else: - cv.check_iterable_type('mgxs_types', mgxs_types, string_types) + cv.check_iterable_type('mgxs_types', mgxs_types, str) for mgxs_type in mgxs_types: cv.check_value('mgxs_type', mgxs_type, all_mgxs_types) self._mgxs_types = mgxs_types @@ -587,7 +587,7 @@ class Library(object): self._nuclides = statepoint.summary.nuclides if statepoint.run_mode == 'eigenvalue': - self._keff = statepoint.k_combined[0] + self._keff = statepoint.k_combined.n # Load tallies for each MGXS for each domain and mgxs type for domain in self.domains: @@ -814,8 +814,8 @@ class Library(object): 'since a statepoint has not yet been loaded' raise ValueError(msg) - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) import h5py @@ -857,8 +857,8 @@ class Library(object): """ - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) # Make directory if it does not exist if not os.path.exists(directory): @@ -892,8 +892,8 @@ class Library(object): """ - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) # Make directory if it does not exist if not os.path.exists(directory): @@ -953,8 +953,8 @@ class Library(object): cv.check_type('domain', domain, (openmc.Material, openmc.Cell, openmc.Universe, openmc.Mesh)) - cv.check_type('xsdata_name', xsdata_name, string_types) - cv.check_type('nuclide', nuclide, string_types) + cv.check_type('xsdata_name', xsdata_name, str) + cv.check_type('nuclide', nuclide, str) cv.check_value('xs_type', xs_type, ['macro', 'micro']) if subdomain is not None: cv.check_iterable_type('subdomain', subdomain, Integral, @@ -1213,7 +1213,7 @@ class Library(object): cv.check_value('xs_type', xs_type, ['macro', 'micro']) if xsdata_names is not None: - cv.check_iterable_type('xsdata_names', xsdata_names, string_types) + cv.check_iterable_type('xsdata_names', xsdata_names, str) # If gathering material-specific data, set the xs_type to macro if not self.by_nuclide: diff --git a/openmc/mgxs/mdgxs.py b/openmc/mgxs/mdgxs.py index d3f1a0646b..2d278d62d7 100644 --- a/openmc/mgxs/mdgxs.py +++ b/openmc/mgxs/mdgxs.py @@ -1,6 +1,5 @@ -from __future__ import division - -from collections import Iterable, OrderedDict +from collections import OrderedDict +from collections.abc import Iterable import itertools from numbers import Integral import warnings @@ -9,7 +8,6 @@ import sys import copy from abc import ABCMeta -from six import add_metaclass, string_types import numpy as np import openmc @@ -29,7 +27,6 @@ MDGXS_TYPES = ['delayed-nu-fission', MAX_DELAYED_GROUPS = 8 -@add_metaclass(ABCMeta) class MDGXS(MGXS): """An abstract multi-delayed-group cross section for some energy and delayed group structures within some spatial domain. @@ -133,8 +130,8 @@ class MDGXS(MGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(MDGXS, self).__init__(domain, domain_type, energy_groups, - by_nuclide, name, num_polar, num_azimuthal) + super().__init__(domain, domain_type, energy_groups, by_nuclide, name, + num_polar, num_azimuthal) self._delayed_groups = None @@ -355,7 +352,7 @@ class MDGXS(MGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -363,7 +360,7 @@ class MDGXS(MGXS): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) for group in groups: filters.append(openmc.EnergyFilter) @@ -371,7 +368,7 @@ class MDGXS(MGXS): (self.energy_groups.get_group_bounds(group),)) # Construct list of delayed group tuples for all requested groups - if not isinstance(delayed_groups, string_types): + if not isinstance(delayed_groups, str): cv.check_type('delayed groups', delayed_groups, list, int) for delayed_group in delayed_groups: filters.append(openmc.DelayedGroupFilter) @@ -475,7 +472,7 @@ class MDGXS(MGXS): """ - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) cv.check_iterable_type('energy_groups', groups, Integral) cv.check_type('delayed groups', delayed_groups, list, int) @@ -551,7 +548,7 @@ class MDGXS(MGXS): """ - merged_mdgxs = super(MDGXS, self).merge(other) + merged_mdgxs = super().merge(other) # Merge delayed groups if self.delayed_groups != other.delayed_groups: @@ -581,11 +578,11 @@ class MDGXS(MGXS): """ if self.delayed_groups is None: - super(MDGXS, self).print_xs(subdomains, nuclides, xs_type) + super().print_xs(subdomains, nuclides, xs_type) return # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -602,7 +599,7 @@ class MDGXS(MGXS): elif nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -725,8 +722,8 @@ class MDGXS(MGXS): """ - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) cv.check_value('format', format, ['csv', 'excel', 'pickle', 'latex']) cv.check_value('xs_type', xs_type, ['macro', 'micro']) @@ -816,11 +813,11 @@ class MDGXS(MGXS): """ - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) if nuclides != 'all' and nuclides != 'sum': - cv.check_iterable_type('nuclides', nuclides, string_types) - if not isinstance(delayed_groups, string_types): + cv.check_iterable_type('nuclides', nuclides, str) + if not isinstance(delayed_groups, str): cv.check_type('delayed groups', delayed_groups, list, int) cv.check_value('xs_type', xs_type, ['macro', 'micro']) @@ -858,7 +855,7 @@ class MDGXS(MGXS): columns = self._df_convert_columns_to_bins(df) # Select out those groups the user requested - if not isinstance(groups, string_types): + if not isinstance(groups, str): if 'group in' in df: df = df[df['group in'].isin(groups)] if 'group out' in df: @@ -1011,9 +1008,8 @@ class ChiDelayed(MDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(ChiDelayed, self).__init__(domain, domain_type, energy_groups, - delayed_groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'chi-delayed' self._estimator = 'analog' @@ -1059,7 +1055,7 @@ class ChiDelayed(MDGXS): # Compute chi self._xs_tally = self.rxn_rate_tally / delayed_nu_fission_in - super(ChiDelayed, self)._compute_xs() + super()._compute_xs() # Add the coarse energy filter back to the nu-fission tally delayed_nu_fission_in.filters.append(energy_filter) @@ -1131,8 +1127,7 @@ class ChiDelayed(MDGXS): delayed_nu_fission_in.remove_filter(energy_filter) # Call super class method and null out derived tallies - slice_xs = super(ChiDelayed, self).get_slice(nuclides, groups, - delayed_groups) + slice_xs = super().get_slice(nuclides, groups, delayed_groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -1288,7 +1283,7 @@ class ChiDelayed(MDGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -1296,7 +1291,7 @@ class ChiDelayed(MDGXS): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) for group in groups: filters.append(openmc.EnergyoutFilter) @@ -1304,7 +1299,7 @@ class ChiDelayed(MDGXS): (self.energy_groups.get_group_bounds(group),)) # Construct list of delayed group tuples for all requested groups - if not isinstance(delayed_groups, string_types): + if not isinstance(delayed_groups, str): cv.check_type('delayed groups', delayed_groups, list, int) for delayed_group in delayed_groups: filters.append(openmc.DelayedGroupFilter) @@ -1352,7 +1347,7 @@ class ChiDelayed(MDGXS): # Get chi delayed for user-specified nuclides in the domain else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) xs = self.xs_tally.get_values(filters=filters, filter_bins=filter_bins, nuclides=nuclides, value=value) @@ -1525,10 +1520,8 @@ class DelayedNuFissionXS(MDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(DelayedNuFissionXS, self).__init__(domain, domain_type, - energy_groups, delayed_groups, - by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'delayed-nu-fission' @@ -1661,9 +1654,8 @@ class Beta(MDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(Beta, self).__init__(domain, domain_type, energy_groups, - delayed_groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'beta' @property @@ -1689,7 +1681,7 @@ class Beta(MDGXS): # Compute beta self._xs_tally = self.rxn_rate_tally / nu_fission - super(Beta, self)._compute_xs() + super()._compute_xs() return self._xs_tally @@ -1845,9 +1837,8 @@ class DecayRate(MDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(DecayRate, self).__init__(domain, domain_type, energy_groups, - delayed_groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'decay-rate' @property @@ -1882,7 +1873,7 @@ class DecayRate(MDGXS): # Compute the decay rate self._xs_tally = self.rxn_rate_tally / delayed_nu_fission - super(DecayRate, self)._compute_xs() + super()._compute_xs() return self._xs_tally @@ -1914,7 +1905,6 @@ class DecayRate(MDGXS): return self._get_homogenized_mgxs(other_mgxs, 'delayed-nu-fission') -@add_metaclass(ABCMeta) class MatrixMDGXS(MDGXS): """An abstract multi-delayed-group cross section for some energy group and delayed group structure within some spatial domain. This class is @@ -2117,7 +2107,7 @@ class MatrixMDGXS(MDGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -2125,7 +2115,7 @@ class MatrixMDGXS(MDGXS): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(in_groups, string_types): + if not isinstance(in_groups, str): cv.check_iterable_type('groups', in_groups, Integral) for group in in_groups: filters.append(openmc.EnergyFilter) @@ -2133,7 +2123,7 @@ class MatrixMDGXS(MDGXS): self.energy_groups.get_group_bounds(group),)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(out_groups, string_types): + if not isinstance(out_groups, str): cv.check_iterable_type('groups', out_groups, Integral) for group in out_groups: filters.append(openmc.EnergyoutFilter) @@ -2141,7 +2131,7 @@ class MatrixMDGXS(MDGXS): self.energy_groups.get_group_bounds(group),)) # Construct list of delayed group tuples for all requested groups - if not isinstance(delayed_groups, string_types): + if not isinstance(delayed_groups, str): cv.check_type('delayed groups', delayed_groups, list, int) for delayed_group in delayed_groups: filters.append(openmc.DelayedGroupFilter) @@ -2266,8 +2256,7 @@ class MatrixMDGXS(MDGXS): """ # Call super class method and null out derived tallies - slice_xs = super(MatrixMDGXS, self).get_slice(nuclides, in_groups, - delayed_groups) + slice_xs = super().get_slice(nuclides, in_groups, delayed_groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -2312,7 +2301,7 @@ class MatrixMDGXS(MDGXS): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -2329,7 +2318,7 @@ class MatrixMDGXS(MDGXS): if nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -2614,12 +2603,8 @@ class DelayedNuFissionMatrixXS(MatrixMDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(DelayedNuFissionMatrixXS, self).__init__(domain, domain_type, - energy_groups, - delayed_groups, - by_nuclide, name, - num_polar, - num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'delayed-nu-fission' self._hdf5_key = 'delayed-nu-fission matrix' self._estimator = 'analog' diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index a557e51cc1..4932feff1e 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -1,15 +1,12 @@ -from __future__ import division - from collections import OrderedDict from numbers import Integral import warnings import os import copy from abc import ABCMeta -import itertools -from six import add_metaclass, string_types import numpy as np +import h5py import openmc import openmc.checkvalue as cv @@ -115,8 +112,7 @@ def _df_column_convert_to_bin(df, current_name, new_name, values_to_bin, df.rename(columns={current_name: new_name}, inplace=True) -@add_metaclass(ABCMeta) -class MGXS(object): +class MGXS(metaclass=ABCMeta): """An abstract multi-group cross section for some energy group structure within some spatial domain. @@ -579,7 +575,7 @@ class MGXS(object): @name.setter def name(self, name): - cv.check_type('name', name, string_types) + cv.check_type('name', name, str) self._name = name @by_nuclide.setter @@ -589,7 +585,7 @@ class MGXS(object): @nuclides.setter def nuclides(self, nuclides): - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) self._nuclides = nuclides @estimator.setter @@ -805,7 +801,7 @@ class MGXS(object): """ - cv.check_type('nuclide', nuclide, string_types) + cv.check_type('nuclide', nuclide, str) # Get list of all nuclides in the spatial domain nuclides = self.domain.get_nuclide_densities() @@ -940,8 +936,7 @@ class MGXS(object): # NOTE: This is important if tally merging was used if self.domain_type == 'mesh': filters = [_DOMAIN_TO_FILTER[self.domain_type]] - xyz = [range(1, x + 1) for x in self.domain.dimension] - filter_bins = [tuple(itertools.product(*xyz))] + filter_bins = [tuple(self.domain.indices)] elif self.domain_type != 'distribcell': filters = [_DOMAIN_TO_FILTER[self.domain_type]] filter_bins = [(self.domain.id,)] @@ -1032,7 +1027,7 @@ class MGXS(object): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) @@ -1043,7 +1038,7 @@ class MGXS(object): filter_bins.append(tuple(subdomain_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) filters.append(openmc.EnergyFilter) energy_bins = [] @@ -1218,7 +1213,7 @@ class MGXS(object): """ # Construct a collection of the subdomain filter bins to average across - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) subdomains = [(subdomain,) for subdomain in subdomains] subdomains = [tuple(subdomains)] @@ -1375,7 +1370,7 @@ class MGXS(object): """ - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) cv.check_iterable_type('energy_groups', groups, Integral) # Build lists of filters and filter bins to slice @@ -1529,13 +1524,12 @@ class MGXS(object): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) elif self.domain_type == 'mesh': - xyz = [range(1, x + 1) for x in self.domain.dimension] - subdomains = list(itertools.product(*xyz)) + subdomains = list(self.domain.indices) else: subdomains = [self.domain.id] @@ -1546,7 +1540,7 @@ class MGXS(object): elif nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -1682,13 +1676,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) @@ -1702,7 +1691,7 @@ class MGXS(object): xs_results = h5py.File(filename, 'w', libver=libver) # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -1710,8 +1699,7 @@ class MGXS(object): domain_filter = self.xs_tally.find_filter('sum(distribcell)') subdomains = domain_filter.bins elif self.domain_type == 'mesh': - xyz = [range(1, x+1) for x in self.domain.dimension] - subdomains = list(itertools.product(*xyz)) + subdomains = list(self.domain.indices) else: subdomains = [self.domain.id] @@ -1723,7 +1711,7 @@ class MGXS(object): elif nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -1801,8 +1789,8 @@ class MGXS(object): """ - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) cv.check_value('format', format, ['csv', 'excel', 'pickle', 'latex']) cv.check_value('xs_type', xs_type, ['macro', 'micro']) @@ -1888,10 +1876,10 @@ class MGXS(object): """ - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) if nuclides != 'all' and nuclides != 'sum': - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) cv.check_value('xs_type', xs_type, ['macro', 'micro']) # Get a Pandas DataFrame from the derived xs tally @@ -1927,7 +1915,7 @@ class MGXS(object): columns = self._df_convert_columns_to_bins(df) # Select out those groups the user requested - if not isinstance(groups, string_types): + if not isinstance(groups, str): if 'group in' in df: df = df[df['group in'].isin(groups)] if 'group out' in df: @@ -1980,7 +1968,6 @@ class MGXS(object): return 'cm^-1' if xs_type == 'macro' else 'barns' -@add_metaclass(ABCMeta) class MatrixMGXS(MGXS): """An abstract multi-group cross section for some energy group structure within some spatial domain. This class is specifically intended for @@ -2168,7 +2155,7 @@ class MatrixMGXS(MGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) filters.append(_DOMAIN_TO_FILTER[self.domain_type]) @@ -2178,7 +2165,7 @@ class MatrixMGXS(MGXS): filter_bins.append(tuple(subdomain_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(in_groups, string_types): + if not isinstance(in_groups, str): cv.check_iterable_type('groups', in_groups, Integral) filters.append(openmc.EnergyFilter) for group in in_groups: @@ -2186,7 +2173,7 @@ class MatrixMGXS(MGXS): filter_bins.append(tuple(energy_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(out_groups, string_types): + if not isinstance(out_groups, str): cv.check_iterable_type('groups', out_groups, Integral) for group in out_groups: filters.append(openmc.EnergyoutFilter) @@ -2301,7 +2288,7 @@ class MatrixMGXS(MGXS): """ # Call super class method and null out derived tallies - slice_xs = super(MatrixMGXS, self).get_slice(nuclides, in_groups) + slice_xs = super().get_slice(nuclides, in_groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -2346,13 +2333,12 @@ class MatrixMGXS(MGXS): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) elif self.domain_type == 'mesh': - xyz = [range(1, x + 1) for x in self.domain.dimension] - subdomains = list(itertools.product(*xyz)) + subdomains = list(self.domain.indices) else: subdomains = [self.domain.id] @@ -2363,7 +2349,7 @@ class MatrixMGXS(MGXS): if nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -2576,9 +2562,8 @@ class TotalXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(TotalXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'total' @@ -2713,9 +2698,8 @@ class TransportXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, nu=False, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(TransportXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) # Use tracklength estimators for the total MGXS term, and # analog estimators for the transport correction term @@ -2724,7 +2708,7 @@ class TransportXS(MGXS): self.nu = nu def __deepcopy__(self, memo): - clone = super(TransportXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._nu = self.nu return clone @@ -2921,9 +2905,8 @@ class AbsorptionXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(AbsorptionXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'absorption' @@ -3048,9 +3031,8 @@ class CaptureXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(CaptureXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'capture' @property @@ -3203,16 +3185,15 @@ class FissionXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, nu=False, prompt=False, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(FissionXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._nu = False self._prompt = False self.nu = nu self.prompt = prompt def __deepcopy__(self, memo): - clone = super(FissionXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._nu = self.nu clone._prompt = self.prompt return clone @@ -3371,9 +3352,8 @@ class KappaFissionXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(KappaFissionXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'kappa-fission' @@ -3504,13 +3484,12 @@ class ScatterXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1, nu=False): - super(ScatterXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self.nu = nu def __deepcopy__(self, memo): - clone = super(ScatterXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._nu = self.nu return clone @@ -3721,9 +3700,8 @@ class ScatterMatrixXS(MatrixMGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1, nu=False): - super(ScatterMatrixXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._formulation = 'simple' self._correction = 'P0' self._scatter_format = 'legendre' @@ -3734,7 +3712,7 @@ class ScatterMatrixXS(MatrixMGXS): self.nu = nu def __deepcopy__(self, memo): - clone = super(ScatterMatrixXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._formulation = self.formulation clone._correction = self.correction clone._scatter_format = self.scatter_format @@ -3825,7 +3803,7 @@ class ScatterMatrixXS(MatrixMGXS): @property def tally_keys(self): if self.formulation == 'simple': - return super(ScatterMatrixXS, self).tally_keys + return super().tally_keys else: # Add keys for groupwise scattering cross section tally_keys = ['flux (tracklength)', 'scatter'] @@ -4155,7 +4133,7 @@ class ScatterMatrixXS(MatrixMGXS): [score_prefix + '{}'.format(i) for i in range(self.legendre_order + 1)] - super(ScatterMatrixXS, self).load_from_statepoint(statepoint) + super().load_from_statepoint(statepoint) def get_slice(self, nuclides=[], in_groups=[], out_groups=[], legendre_order='same'): @@ -4195,7 +4173,7 @@ class ScatterMatrixXS(MatrixMGXS): """ # Call super class method and null out derived tallies - slice_xs = super(ScatterMatrixXS, self).get_slice(nuclides, in_groups) + slice_xs = super().get_slice(nuclides, in_groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -4311,7 +4289,7 @@ class ScatterMatrixXS(MatrixMGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) filters.append(_DOMAIN_TO_FILTER[self.domain_type]) subdomain_bins = [] @@ -4320,7 +4298,7 @@ class ScatterMatrixXS(MatrixMGXS): filter_bins.append(tuple(subdomain_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(in_groups, string_types): + if not isinstance(in_groups, str): cv.check_iterable_type('groups', in_groups, Integral) filters.append(openmc.EnergyFilter) energy_bins = [] @@ -4330,7 +4308,7 @@ class ScatterMatrixXS(MatrixMGXS): filter_bins.append(tuple(energy_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(out_groups, string_types): + if not isinstance(out_groups, str): cv.check_iterable_type('groups', out_groups, Integral) for group in out_groups: filters.append(openmc.EnergyoutFilter) @@ -4486,8 +4464,7 @@ class ScatterMatrixXS(MatrixMGXS): """ - df = super(ScatterMatrixXS, self).get_pandas_dataframe( - groups, nuclides, xs_type, paths) + df = super().get_pandas_dataframe(groups, nuclides, xs_type, paths) if self.scatter_format == 'legendre': # Add a moment column to dataframe @@ -4543,13 +4520,12 @@ class ScatterMatrixXS(MatrixMGXS): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) elif self.domain_type == 'mesh': - xyz = [range(1, x + 1) for x in self.domain.dimension] - subdomains = list(itertools.product(*xyz)) + subdomains = list(self.domain.indices) else: subdomains = [self.domain.id] @@ -4560,7 +4536,7 @@ class ScatterMatrixXS(MatrixMGXS): if nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -4811,9 +4787,8 @@ class MultiplicityMatrixXS(MatrixMGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(MultiplicityMatrixXS, self).__init__(domain, domain_type, groups, - by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'multiplicity matrix' self._estimator = 'analog' self._valid_estimators = ['analog'] @@ -4848,7 +4823,7 @@ class MultiplicityMatrixXS(MatrixMGXS): # Compute the multiplicity self._xs_tally = self.rxn_rate_tally / scatter - super(MultiplicityMatrixXS, self)._compute_xs() + super()._compute_xs() return self._xs_tally @@ -4977,9 +4952,8 @@ class ScatterProbabilityMatrix(MatrixMGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(ScatterProbabilityMatrix, self).__init__( - domain, domain_type, groups, by_nuclide, - name, num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, + name, num_polar, num_azimuthal) self._rxn_type = 'scatter' self._hdf5_key = 'scatter probability matrix' @@ -5021,7 +4995,7 @@ class ScatterProbabilityMatrix(MatrixMGXS): # Compute the group-to-group probabilities self._xs_tally = self.tallies[self.rxn_type] / norm - super(ScatterProbabilityMatrix, self)._compute_xs() + super()._compute_xs() return self._xs_tally @@ -5151,9 +5125,8 @@ class NuFissionMatrixXS(MatrixMGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1, prompt=False): - super(NuFissionMatrixXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) if not prompt: self._rxn_type = 'nu-fission' self._hdf5_key = 'nu-fission matrix' @@ -5174,7 +5147,7 @@ class NuFissionMatrixXS(MatrixMGXS): self._prompt = prompt def __deepcopy__(self, memo): - clone = super(NuFissionMatrixXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._prompt = self.prompt return clone @@ -5308,8 +5281,8 @@ class Chi(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, prompt=False, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(Chi, self).__init__(domain, domain_type, groups, by_nuclide, - name, num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) if not prompt: self._rxn_type = 'chi' else: @@ -5319,7 +5292,7 @@ class Chi(MGXS): self.prompt = prompt def __deepcopy__(self, memo): - clone = super(Chi, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._prompt = self.prompt return clone @@ -5449,7 +5422,7 @@ class Chi(MGXS): nu_fission_in.remove_filter(energy_filter) # Call super class method and null out derived tallies - slice_xs = super(Chi, self).get_slice(nuclides, groups) + slice_xs = super().get_slice(nuclides, groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -5586,7 +5559,7 @@ class Chi(MGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) filters.append(_DOMAIN_TO_FILTER[self.domain_type]) @@ -5596,7 +5569,7 @@ class Chi(MGXS): filter_bins.append(tuple(subdomain_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) filters.append(openmc.EnergyoutFilter) energy_bins = [] @@ -5644,7 +5617,7 @@ class Chi(MGXS): # Get chi for user-specified nuclides in the domain else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) xs = self.xs_tally.get_values(filters=filters, filter_bins=filter_bins, nuclides=nuclides, value=value) @@ -5727,8 +5700,7 @@ class Chi(MGXS): """ # Build the dataframe using the parent class method - df = super(Chi, self).get_pandas_dataframe( - groups, nuclides, xs_type, paths=paths) + df = super().get_pandas_dataframe(groups, nuclides, xs_type, paths=paths) # If user requested micro cross sections, multiply by the atom # densities to cancel out division made by the parent class method @@ -5886,9 +5858,8 @@ class InverseVelocity(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(InverseVelocity, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'inverse-velocity' def get_units(self, xs_type='macro'): diff --git a/openmc/mgxs_library.py b/openmc/mgxs_library.py index ebfae2fb0d..e315f33140 100644 --- a/openmc/mgxs_library.py +++ b/openmc/mgxs_library.py @@ -2,7 +2,6 @@ import copy from numbers import Real, Integral import os -from six import string_types import numpy as np import h5py from scipy.interpolate import interp1d @@ -381,7 +380,7 @@ class XSdata(object): @name.setter def name(self, name): - check_type('name for XSdata', name, string_types) + check_type('name for XSdata', name, str) self._name = name @energy_groups.setter @@ -2517,7 +2516,7 @@ class MGXSLibrary(object): """ - check_type('filename', filename, string_types) + check_type('filename', filename, str) # Create and write to the HDF5 file file = h5py.File(filename, "w", libver=libver) diff --git a/openmc/mixin.py b/openmc/mixin.py index d724fc32a0..09a63ae4e4 100644 --- a/openmc/mixin.py +++ b/openmc/mixin.py @@ -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: diff --git a/openmc/model/funcs.py b/openmc/model/funcs.py index 589765d2c8..e974f93b1b 100644 --- a/openmc/model/funcs.py +++ b/openmc/model/funcs.py @@ -1,10 +1,103 @@ -from __future__ import division -from collections import Iterable, OrderedDict +from collections import OrderedDict +from collections.abc import Iterable from math import sqrt from numbers import Real from openmc import XPlane, YPlane, Plane, ZCylinder from openmc.checkvalue import check_type, check_value +import openmc.data + + +def borated_water(boron_ppm, temperature=293., pressure=0.1013, temp_unit='K', + press_unit='MPa', density=None, **kwargs): + """Return a Material with the composition of boron dissolved in water. + + The water density can be determined from a temperature and pressure, or it + can be set directly. + + The concentration of boron has no effect on the stoichiometric ratio of H + and O---they are fixed at 2-1. + + Parameters + ---------- + boron_ppm : float + The weight fraction in parts-per-million of elemental boron in the + water. + temperature : float + Temperature in [K] used to compute water density. + pressure : float + Pressure in [MPa] used to compute water density. + temp_unit : {'K', 'C', 'F'} + The units used for the `temperature` argument. + press_unit : {'MPa', 'psi'} + The units used for the `pressure` argument. + density : float + Water density in [g / cm^3]. If specified, this value overrides the + temperature and pressure arguments. + **kwargs + All keyword arguments are passed to the created Material object. + + Returns + ------- + openmc.Material + + """ + # Perform any necessary unit conversions. + check_value('temperature unit', temp_unit, ('K', 'C', 'F')) + if temp_unit == 'K': + T = temperature + elif temp_unit == 'C': + T = temperature + 273.15 + elif temp_unit == 'F': + T = (temperature + 459.67) * 5.0 / 9.0 + check_value('pressure unit', press_unit, ('MPa', 'psi')) + if press_unit == 'MPa': + P = pressure + elif press_unit == 'psi': + P = pressure * 0.006895 + + # Set the density of water, either from an explicitly given density or from + # temperature and pressure. + if density is not None: + water_density = density + else: + water_density = openmc.data.water_density(T, P) + + # Compute the density of the solution. + solution_density = water_density / (1 - boron_ppm * 1e-6) + + # Compute the molar mass of pure water. + hydrogen = openmc.Element('H') + oxygen = openmc.Element('O') + M_H2O = 0.0 + for iso_name, frac, junk in hydrogen.expand(2.0, 'ao'): + M_H2O += frac * openmc.data.atomic_mass(iso_name) + for iso_name, frac, junk in oxygen.expand(1.0, 'ao'): + M_H2O += frac * openmc.data.atomic_mass(iso_name) + + # Compute the molar mass of boron. + boron = openmc.Element('B') + M_B = 0.0 + for iso_name, frac, junk in boron.expand(1.0, 'ao'): + M_B += frac * openmc.data.atomic_mass(iso_name) + + # Compute the number fractions of each element. + frac_H2O = (1 - boron_ppm * 1e-6) / M_H2O + frac_H = 2 * frac_H2O + frac_O = frac_H2O + frac_B = boron_ppm * 1e-6 / M_B + + # Build the material. + if density is None: + out = openmc.Material(temperature=T, **kwargs) + else: + out = openmc.Material(**kwargs) + out.add_element('H', frac_H, 'ao') + out.add_element('O', frac_O, 'ao') + out.add_element('B', frac_B, 'ao') + out.set_density('g/cc', solution_density) + out.add_s_alpha_beta('c_H_in_H2O') + return out def get_rectangular_prism(width, height, axis='z', origin=(0., 0.), diff --git a/openmc/model/model.py b/openmc/model/model.py index 17de6fc2e6..7a81292c1a 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -1,7 +1,7 @@ -from collections import Iterable +from collections.abc import Iterable import openmc -from openmc.checkvalue import check_type +from openmc.checkvalue import check_type, check_value class Model(object): @@ -136,9 +136,49 @@ class Model(object): for plot in plots: self._plots.append(plot) - def export_to_xml(self): - """Export model to XML files. + def deplete(self, timesteps, power, chain_file=None, method='cecm', + **kwargs): + """Deplete model using specified timesteps/power + + Parameters + ---------- + timesteps : iterable of float + Array of timesteps in units of [s]. Note that values are not + cumulative. + power : float or iterable of float + Power of the reactor in [W]. A single value indicates that the power + is constant over all timesteps. An iterable indicates potentially + different power levels for each timestep. For a 2D problem, the + power can be given in [W/cm] as long as the "volume" assigned to a + depletion material is actually an area in [cm^2]. + chain_file : str, optional + Path to the depletion chain XML file. Defaults to the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. + method : {'cecm', 'predictor'} + Integration method used for depletion + **kwargs + Keyword arguments passed to integration function (e.g., + :func:`openmc.deplete.integrator.cecm`) + """ + # Import the depletion module. This is done here rather than the module + # header to delay importing openmc.capi (through openmc.deplete) which + # can be tough to install properly. + import openmc.deplete as dep + + # Create OpenMC transport operator + op = dep.Operator(self.geometry, self.settings, chain_file) + + # Perform depletion + if method == 'predictor': + dep.integrator.predictor(op, timesteps, power, **kwargs) + elif method == 'cecm': + dep.integrator.cecm(op, timesteps, power, **kwargs) + else: + check_value('method', method, ('cecm', 'predictor')) + + def export_to_xml(self): + """Export model to XML files.""" self.settings.export_to_xml() self.geometry.export_to_xml() @@ -166,19 +206,17 @@ class Model(object): Parameters ---------- **kwargs - All keyword arguments are passed to openmc.run + All keyword arguments are passed to :func:`openmc.run` Returns ------- - 2-tuple of float + uncertainties.UFloat Combined estimator of k-effective from the statepoint """ self.export_to_xml() - return_code = openmc.run(**kwargs) - - assert (return_code == 0), "OpenMC did not execute successfully" + openmc.run(**kwargs) n = self.settings.batches if self.settings.statepoint is not None: diff --git a/openmc/model/triso.py b/openmc/model/triso.py index 67bf3bc442..5fe51b6644 100644 --- a/openmc/model/triso.py +++ b/openmc/model/triso.py @@ -1,22 +1,17 @@ -from __future__ import division import copy import warnings import itertools import random -from collections import Iterable, defaultdict +from collections import defaultdict +from collections.abc import Iterable from numbers import Real from random import uniform, gauss from heapq import heappush, heappop from math import pi, sin, cos, floor, log10, sqrt 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 @@ -51,7 +46,7 @@ class TRISO(openmc.Cell): def __init__(self, outer_radius, fill, center=(0., 0., 0.)): self._surface = openmc.Sphere(R=outer_radius) - super(TRISO, self).__init__(fill=fill, region=-self._surface) + super().__init__(fill=fill, region=-self._surface) self.center = np.asarray(center) @property @@ -96,8 +91,7 @@ class TRISO(openmc.Cell): k_min:k_max+1, j_min:j_max+1, i_min:i_max+1])) -@add_metaclass(ABCMeta) -class _Domain(object): +class _Domain(metaclass=ABCMeta): """Container in which to pack particles. Parameters @@ -252,7 +246,7 @@ class _CubicDomain(_Domain): """ def __init__(self, length, particle_radius, center=[0., 0., 0.]): - super(_CubicDomain, self).__init__(particle_radius, center) + super().__init__(particle_radius, center) self.length = length @property @@ -331,7 +325,7 @@ class _CylindricalDomain(_Domain): """ def __init__(self, length, radius, particle_radius, center=[0., 0., 0.]): - super(_CylindricalDomain, self).__init__(particle_radius, center) + super().__init__(particle_radius, center) self.length = length self.radius = radius @@ -421,7 +415,7 @@ class _SphericalDomain(_Domain): """ def __init__(self, radius, particle_radius, center=[0., 0., 0.]): - super(_SphericalDomain, self).__init__(particle_radius, center) + super().__init__(particle_radius, center) self.radius = radius @property @@ -837,10 +831,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 diff --git a/openmc/nuclide.py b/openmc/nuclide.py index 2e5a8e1193..f7c725040f 100644 --- a/openmc/nuclide.py +++ b/openmc/nuclide.py @@ -1,7 +1,5 @@ import warnings -from six import string_types - import openmc.checkvalue as cv @@ -34,7 +32,7 @@ class Nuclide(str): '"{}" is being renamed as "{}".'.format(orig_name, name) warnings.warn(msg) - return super(Nuclide, cls).__new__(cls, name) + return super().__new__(cls, name) @property def name(self): diff --git a/openmc/plots.py b/openmc/plots.py index a60b2a3094..8eff78b1d9 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -1,10 +1,10 @@ -from collections import Iterable, Mapping +from collections.abc import Iterable, Mapping from numbers import Real, Integral from xml.etree import ElementTree as ET +import subprocess import sys import warnings -from six import string_types import numpy as np import openmc @@ -297,7 +297,7 @@ class Plot(IDManagerMixin): @name.setter def name(self, name): - cv.check_type('plot name', name, string_types) + cv.check_type('plot name', name, str) self._name = name @width.setter @@ -322,7 +322,7 @@ class Plot(IDManagerMixin): @filename.setter def filename(self, filename): - cv.check_type('filename', filename, string_types) + cv.check_type('filename', filename, str) self._filename = filename @color_by.setter @@ -343,7 +343,7 @@ class Plot(IDManagerMixin): @background.setter def background(self, background): cv.check_type('plot background', background, Iterable) - if isinstance(background, string_types): + if isinstance(background, str): if background.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color.".format(background)) else: @@ -359,7 +359,7 @@ class Plot(IDManagerMixin): for key, value in colors.items(): cv.check_type('plot color key', key, (openmc.Cell, openmc.Material)) cv.check_type('plot color value', value, Iterable) - if isinstance(value, string_types): + if isinstance(value, str): if value.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color.".format(value)) else: @@ -380,7 +380,7 @@ class Plot(IDManagerMixin): @mask_background.setter def mask_background(self, mask_background): cv.check_type('plot mask background', mask_background, Iterable) - if isinstance(mask_background, string_types): + if isinstance(mask_background, str): if mask_background.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color.".format(mask_background)) else: @@ -558,7 +558,7 @@ class Plot(IDManagerMixin): cv.check_type('background', background, Iterable) # Get a background (R,G,B) tuple to apply in alpha compositing - if isinstance(background, string_types): + if isinstance(background, str): if background.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color.".format(background)) background = _SVG_COLORS[background.lower()] @@ -570,7 +570,7 @@ class Plot(IDManagerMixin): # other than those the user wishes to highlight for domain, color in self.colors.items(): if domain not in domains: - if isinstance(color, string_types): + if isinstance(color, str): color = _SVG_COLORS[color.lower()] r, g, b = color r = int(((1-alpha) * background[0]) + (alpha * r)) @@ -610,7 +610,7 @@ class Plot(IDManagerMixin): if self._background is not None: subelement = ET.SubElement(element, "background") color = self._background - if isinstance(color, string_types): + if isinstance(color, str): color = _SVG_COLORS[color.lower()] subelement.text = ' '.join(str(x) for x in color) @@ -619,7 +619,7 @@ class Plot(IDManagerMixin): key=lambda x: x[0].id): subelement = ET.SubElement(element, "color") subelement.set("id", str(domain.id)) - if isinstance(color, string_types): + if isinstance(color, str): color = _SVG_COLORS[color.lower()] subelement.set("rgb", ' '.join(str(x) for x in color)) @@ -629,7 +629,7 @@ class Plot(IDManagerMixin): str(d.id) for d in self._mask_components)) color = self._mask_background if color is not None: - if isinstance(color, string_types): + if isinstance(color, str): color = _SVG_COLORS[color.lower()] subelement.set("background", ' '.join( str(x) for x in color)) @@ -651,6 +651,49 @@ class Plot(IDManagerMixin): return element + def to_ipython_image(self, openmc_exec='openmc', cwd='.', + convert_exec='convert'): + """Render plot as an image + + This method runs OpenMC in plotting mode to produce a bitmap image which + is then converted to a .png file and loaded in as an + :class:`IPython.display.Image` object. As such, it requires that your + model geometry, materials, and settings have already been exported to + XML. + + Parameters + ---------- + openmc_exec : str + Path to OpenMC executable + cwd : str, optional + Path to working directory to run in + convert_exec : str, optional + Command that can convert PPM files into PNG files + + Returns + ------- + IPython.display.Image + Image generated + + """ + from IPython.display import Image + + # Create plots.xml + Plots([self]).export_to_xml() + + # Run OpenMC in geometry plotting mode + openmc.plot_geometry(False, openmc_exec, cwd) + + # Convert to .png + if self.filename is not None: + ppm_file = '{}.ppm'.format(self.filename) + else: + ppm_file = 'plot_{}.ppm'.format(self.id) + png_file = ppm_file.replace('.ppm', '.png') + subprocess.check_call([convert_exec, ppm_file, png_file]) + + return Image(png_file) + class Plots(cv.CheckedList): """Collection of Plots used for an OpenMC simulation. @@ -674,28 +717,11 @@ class Plots(cv.CheckedList): """ def __init__(self, plots=None): - super(Plots, self).__init__(Plot, 'plots collection') + super().__init__(Plot, 'plots collection') self._plots_file = ET.Element("plots") if plots is not None: self += plots - def add_plot(self, plot): - """Add a plot to the file. - - .. deprecated:: 0.8 - Use :meth:`Plots.append` instead. - - Parameters - ---------- - plot : openmc.Plot - Plot to add - - """ - warnings.warn("Plots.add_plot(...) has been deprecated and may be " - "removed in a future version. Use Plots.append(...) " - "instead.", DeprecationWarning) - self.append(plot) - def append(self, plot): """Append plot to collection @@ -705,7 +731,7 @@ class Plots(cv.CheckedList): Plot to append """ - super(Plots, self).append(plot) + super().append(plot) def insert(self, index, plot): """Insert plot before index @@ -718,24 +744,7 @@ class Plots(cv.CheckedList): Plot to insert """ - super(Plots, self).insert(index, plot) - - def remove_plot(self, plot): - """Remove a plot from the file. - - .. deprecated:: 0.8 - Use :meth:`Plots.remove` instead. - - Parameters - ---------- - plot : openmc.Plot - Plot to remove - - """ - warnings.warn("Plots.remove_plot(...) has been deprecated and may be " - "removed in a future version. Use Plots.remove(...) " - "instead.", DeprecationWarning) - self.remove(plot) + super().insert(index, plot) def colorize(self, geometry, seed=1): """Generate a consistent color scheme for each domain in each plot. diff --git a/openmc/plotter.py b/openmc/plotter.py index 810ee5d27c..191b50c563 100644 --- a/openmc/plotter.py +++ b/openmc/plotter.py @@ -2,8 +2,6 @@ from numbers import Integral, Real from itertools import chain import string -from six import string_types -import matplotlib.pyplot as plt import numpy as np import openmc.checkvalue as cv @@ -126,6 +124,8 @@ def plot_xs(this, types, divisor_types=None, temperature=294., data_type=None, generated. """ + import matplotlib.pyplot as plt + cv.check_type("plot_CE", plot_CE, bool) if data_type is None: @@ -137,7 +137,7 @@ def plot_xs(this, types, divisor_types=None, temperature=294., data_type=None, data_type = 'material' elif isinstance(this, openmc.Macroscopic): data_type = 'macroscopic' - elif isinstance(this, string_types): + elif isinstance(this, str): if this[-1] in string.digits: data_type = 'nuclide' else: @@ -275,7 +275,7 @@ def calculate_cexs(this, data_type, types, temperature=294., sab_name=None, # Check types cv.check_type('temperature', temperature, Real) if sab_name: - cv.check_type('sab_name', sab_name, string_types) + cv.check_type('sab_name', sab_name, str) if enrichment: cv.check_type('enrichment', enrichment, Real) @@ -648,7 +648,7 @@ def calculate_mgxs(this, data_type, types, orders=None, temperature=294., cv.check_type('temperature', temperature, Real) if enrichment: cv.check_type('enrichment', enrichment, Real) - cv.check_iterable_type('types', types, string_types) + cv.check_iterable_type('types', types, str) cv.check_type("cross_sections", cross_sections, str) library = openmc.MGXSLibrary.from_hdf5(cross_sections) diff --git a/openmc/region.py b/openmc/region.py index eeafd28326..f82db8553b 100644 --- a/openmc/region.py +++ b/openmc/region.py @@ -1,15 +1,14 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable, OrderedDict, MutableSequence +from collections import OrderedDict +from collections.abc import Iterable, MutableSequence from copy import deepcopy -from six import add_metaclass import numpy as np from openmc.checkvalue import check_type -@add_metaclass(ABCMeta) -class Region(object): +class Region(metaclass=ABCMeta): """Region of space that can be assigned to a cell. Region is an abstract base class that is inherited by @@ -39,10 +38,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 +460,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 +581,6 @@ class Complement(Region): if memo is None: memo = {} - clone = copy.deepcopy(self) + clone = deepcopy(self) clone.node = self.node.clone(memo) return clone diff --git a/openmc/search.py b/openmc/search.py index 7f91438fd7..6be8a50ea5 100644 --- a/openmc/search.py +++ b/openmc/search.py @@ -1,4 +1,4 @@ -from collections import Callable +from collections.abc import Callable from numbers import Real import scipy.optimize as sopt @@ -60,9 +60,9 @@ def _search_keff(guess, target, model_builder, model_args, print_iterations, if print_iterations: text = 'Iteration: {}; Guess of {:.2e} produced a keff of ' + \ '{:1.5f} +/- {:1.5f}' - print(text.format(len(guesses), guess, keff[0], keff[1])) + print(text.format(len(guesses), guess, keff.n, keff.s)) - return (keff[0] - target) + return keff.n - target def search_for_keff(model_builder, initial_guess=None, target=1.0, diff --git a/openmc/settings.py b/openmc/settings.py index 9ead82ec61..62cfc27aaa 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -1,10 +1,9 @@ -from collections import Iterable, MutableSequence, Mapping +from collections.abc import Iterable, MutableSequence, Mapping from numbers import Real, Integral import warnings from xml.etree import ElementTree as ET import sys -from six import string_types import numpy as np from openmc.clean_xml import clean_xml_indentation @@ -29,13 +28,6 @@ class Settings(object): deviation. create_fission_neutrons : bool Indicate whether fission neutrons should be created or not. - cross_sections : str - Indicates the path to an XML cross section listing file (usually named - cross_sections.xml). If it is not set, the - :envvar:`OPENMC_CROSS_SECTIONS` environment variable will be used for - continuous-energy calculations and - :envvar:`OPENMC_MG_CROSS_SECTIONS` will be used for multi-group - calculations to find the path to the XML cross section file. cutoff : dict Dictionary defining weight cutoff and energy cutoff. The dictionary may have three keys, 'weight', 'weight_avg' and 'energy'. Value for 'weight' @@ -60,13 +52,10 @@ 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 - Indicates the path to a directory containing a windowed multipole - cross section library. If it is not set, the - :envvar:`OPENMC_MULTIPOLE_LIBRARY` environment variable will be used. A - multipole library is optional. no_reduce : bool Indicate that all user-defined and global tallies should not be reduced across processes in a parallel calculation. @@ -220,19 +209,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): @@ -274,14 +256,6 @@ class Settings(object): def confidence_intervals(self): return self._confidence_intervals - @property - def cross_sections(self): - return self._cross_sections - - @property - def multipole_library(self): - return self._multipole_library - @property def ptables(self): return self._ptables @@ -362,30 +336,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 +348,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) @@ -484,7 +438,7 @@ class Settings(object): if key in ('summary', 'tallies'): cv.check_type("output['{}']".format(key), value, bool) else: - cv.check_type("output['path']", value, string_types) + cv.check_type("output['path']", value, str) self._output = output @verbosity.setter @@ -531,23 +485,6 @@ class Settings(object): cv.check_type('confidence interval', confidence_intervals, bool) self._confidence_intervals = confidence_intervals - @cross_sections.setter - def cross_sections(self, cross_sections): - warnings.warn('Settings.cross_sections has been deprecated and will be ' - 'removed in a future version. Materials.cross_sections ' - 'should defined instead.', DeprecationWarning) - cv.check_type('cross sections', cross_sections, string_types) - self._cross_sections = cross_sections - - @multipole_library.setter - def multipole_library(self, multipole_library): - warnings.warn('Settings.multipole_library has been deprecated and will ' - 'be removed in a future version. ' - 'Materials.multipole_library should defined instead.', - DeprecationWarning) - cv.check_type('multipole library', multipole_library, string_types) - self._multipole_library = multipole_library - @ptables.setter def ptables(self, ptables): cv.check_type('probability tables', ptables, bool) @@ -696,85 +633,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) @@ -796,7 +654,7 @@ class Settings(object): cv.check_greater_than(name, value, 0) elif key == 'nuclides': cv.check_type('resonance scattering nuclides', value, - Iterable, string_types) + Iterable, str) self._resonance_scattering = res @volume_calculations.setter @@ -812,6 +670,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 @@ -913,16 +777,6 @@ class Settings(object): element = ET.SubElement(root, "confidence_intervals") element.text = str(self._confidence_intervals).lower() - def _create_cross_sections_subelement(self, root): - if self._cross_sections is not None: - element = ET.SubElement(root, "cross_sections") - element.text = str(self._cross_sections) - - def _create_multipole_library_subelement(self, root): - if self._multipole_library is not None: - element = ET.SubElement(root, "multipole_library") - element.text = str(self._multipole_library) - def _create_ptables_subelement(self, root): if self._ptables is not None: element = ET.SubElement(root, "ptables") @@ -1033,33 +887,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 +912,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. @@ -1109,8 +941,6 @@ class Settings(object): self._create_statepoint_subelement(root_element) self._create_sourcepoint_subelement(root_element) self._create_confidence_intervals(root_element) - self._create_cross_sections_subelement(root_element) - self._create_multipole_library_subelement(root_element) self._create_energy_mode_subelement(root_element) self._create_max_order_subelement(root_element) self._create_ptables_subelement(root_element) @@ -1128,10 +958,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) diff --git a/openmc/source.py b/openmc/source.py index 1aee435147..932062278c 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -2,8 +2,6 @@ from numbers import Real import sys from xml.etree import ElementTree as ET -from six import string_types - from openmc.stats.univariate import Univariate from openmc.stats.multivariate import UnitSphere, Spatial import openmc.checkvalue as cv @@ -78,7 +76,7 @@ class Source(object): @file.setter def file(self, filename): - cv.check_type('source file', filename, string_types) + cv.check_type('source file', filename, str) self._file = filename @space.setter diff --git a/openmc/statepoint.py b/openmc/statepoint.py index 4656e08560..eb011d8742 100644 --- a/openmc/statepoint.py +++ b/openmc/statepoint.py @@ -1,3 +1,4 @@ +from datetime import datetime import re import os import warnings @@ -5,6 +6,7 @@ import glob import numpy as np import h5py +from uncertainties import ufloat import openmc import openmc.checkvalue as cv @@ -47,8 +49,8 @@ class StatePoint(object): CMFD fission source distribution over all mesh cells and energy groups. current_batch : int Number of batches simulated - date_and_time : str - Date and time when simulation began + date_and_time : datetime.datetime + Date and time at which statepoint was written entropy : numpy.ndarray Shannon entropy of fission source at each batch filters : dict @@ -59,8 +61,8 @@ class StatePoint(object): global_tallies : numpy.ndarray of compound datatype Global tallies for k-effective estimates and leakage. The compound datatype has fields 'name', 'sum', 'sum_sq', 'mean', and 'std_dev'. - k_combined : list - Combined estimator for k-effective and its uncertainty + k_combined : uncertainties.UFloat + Combined estimator for k-effective k_col_abs : float Cross-product of collision and absorption estimates of k-effective k_col_tra : float @@ -187,7 +189,8 @@ class StatePoint(object): @property def date_and_time(self): - return self._f.attrs['date_and_time'].decode() + s = self._f.attrs['date_and_time'].decode() + return datetime.strptime(s, '%Y-%m-%d %H:%M:%S') @property def entropy(self): @@ -255,7 +258,7 @@ class StatePoint(object): @property def k_combined(self): if self.run_mode == 'eigenvalue': - return self._f['k_combined'].value + return ufloat(*self._f['k_combined'].value) else: return None @@ -457,7 +460,7 @@ class StatePoint(object): @property def version(self): - return tuple(self._f.attrs['version']) + return tuple(self._f.attrs['openmc_version']) @property def summary(self): diff --git a/openmc/stats/multivariate.py b/openmc/stats/multivariate.py index 0ab11b7c54..ac788c3443 100644 --- a/openmc/stats/multivariate.py +++ b/openmc/stats/multivariate.py @@ -1,19 +1,17 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable +from collections.abc import Iterable from math import pi from numbers import Real import sys from xml.etree import ElementTree as ET -from six import add_metaclass import numpy as np import openmc.checkvalue as cv from openmc.stats.univariate import Univariate, Uniform -@add_metaclass(ABCMeta) -class UnitSphere(object): +class UnitSphere(metaclass=ABCMeta): """Distribution of points on the unit sphere. This abstract class is used for angular distributions, since a direction is @@ -77,7 +75,7 @@ class PolarAzimuthal(UnitSphere): """ def __init__(self, mu=None, phi=None, reference_uvw=[0., 0., 1.]): - super(PolarAzimuthal, self).__init__(reference_uvw) + super().__init__(reference_uvw) if mu is not None: self.mu = mu else: @@ -130,7 +128,7 @@ class Isotropic(UnitSphere): """ def __init__(self): - super(Isotropic, self).__init__() + super().__init__() def to_xml_element(self): """Return XML representation of the isotropic distribution @@ -163,7 +161,7 @@ class Monodirectional(UnitSphere): def __init__(self, reference_uvw=[1., 0., 0.]): - super(Monodirectional, self).__init__(reference_uvw) + super().__init__(reference_uvw) def to_xml_element(self): """Return XML representation of the monodirectional distribution @@ -181,8 +179,7 @@ class Monodirectional(UnitSphere): return element -@add_metaclass(ABCMeta) -class Spatial(object): +class Spatial(metaclass=ABCMeta): """Distribution of locations in three-dimensional Euclidean space. Classes derived from this abstract class can be used for spatial @@ -225,7 +222,7 @@ class CartesianIndependent(Spatial): def __init__(self, x, y, z): - super(CartesianIndependent, self).__init__() + super().__init__() self.x = x self.y = y self.z = z @@ -301,7 +298,7 @@ class Box(Spatial): def __init__(self, lower_left, upper_right, only_fissionable=False): - super(Box, self).__init__() + super().__init__() self.lower_left = lower_left self.upper_right = upper_right self.only_fissionable = only_fissionable @@ -374,7 +371,7 @@ class Point(Spatial): """ def __init__(self, xyz=(0., 0., 0.)): - super(Point, self).__init__() + super().__init__() self.xyz = xyz @property diff --git a/openmc/stats/univariate.py b/openmc/stats/univariate.py index c0476ce45c..16a9dbb9e7 100644 --- a/openmc/stats/univariate.py +++ b/openmc/stats/univariate.py @@ -1,10 +1,9 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable +from collections.abc import Iterable from numbers import Real import sys from xml.etree import ElementTree as ET -from six import add_metaclass import numpy as np import openmc.checkvalue as cv @@ -15,8 +14,7 @@ _INTERPOLATION_SCHEMES = ['histogram', 'linear-linear', 'linear-log', 'log-linear', 'log-log'] -@add_metaclass(ABCMeta) -class Univariate(EqualityMixin): +class Univariate(EqualityMixin, metaclass=ABCMeta): """Probability distribution of a single random variable. The Univariate class is an abstract class that can be derived to implement a @@ -59,7 +57,7 @@ class Discrete(Univariate): """ def __init__(self, x, p): - super(Discrete, self).__init__() + super().__init__() self.x = x self.p = p @@ -133,7 +131,7 @@ class Uniform(Univariate): """ def __init__(self, a=0.0, b=1.0): - super(Uniform, self).__init__() + super().__init__() self.a = a self.b = b @@ -194,17 +192,17 @@ 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 """ def __init__(self, theta): - super(Maxwell, self).__init__() + super().__init__() self.theta = theta def __len__(self): @@ -250,21 +248,21 @@ 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 """ def __init__(self, a=0.988e6, b=2.249e-6): - super(Watt, self).__init__() + super().__init__() self.a = a self.b = b @@ -344,7 +342,7 @@ class Tabular(Univariate): def __init__(self, x, p, interpolation='linear-linear', ignore_negative=False): - super(Tabular, self).__init__() + super().__init__() self._ignore_negative = ignore_negative self.x = x self.p = p @@ -444,10 +442,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 @@ -473,7 +470,7 @@ class Mixture(Univariate): """ def __init__(self, probability, distribution): - super(Mixture, self).__init__() + super().__init__() self.probability = probability self.distribution = distribution diff --git a/openmc/summary.py b/openmc/summary.py index 34743757b4..aa98025c08 100644 --- a/openmc/summary.py +++ b/openmc/summary.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable import re import warnings diff --git a/openmc/surface.py b/openmc/surface.py index 6c29ed458c..ad5053e370 100644 --- a/openmc/surface.py +++ b/openmc/surface.py @@ -1,4 +1,3 @@ -from __future__ import division from abc import ABCMeta from collections import OrderedDict from copy import deepcopy @@ -6,7 +5,6 @@ from functools import partial from numbers import Real, Integral from xml.etree import ElementTree as ET -from six import add_metaclass, string_types import numpy as np from openmc.checkvalue import check_type, check_value @@ -115,14 +113,14 @@ class Surface(IDManagerMixin): @name.setter def name(self, name): if name is not None: - check_type('surface name', name, string_types) + check_type('surface name', name, str) self._name = name else: self._name = '' @boundary_type.setter def boundary_type(self, boundary_type): - check_type('boundary type', boundary_type, string_types) + check_type('boundary type', boundary_type, str) check_value('boundary type', boundary_type, _BOUNDARY_TYPES) self._boundary_type = boundary_type @@ -328,7 +326,7 @@ class Plane(Surface): def __init__(self, surface_id=None, boundary_type='transmission', A=1., B=0., C=0., D=0., name=''): - super(Plane, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'plane' self._coeff_keys = ['A', 'B', 'C', 'D'] @@ -412,7 +410,7 @@ class Plane(Surface): XML element containing source data """ - element = super(Plane, self).to_xml_element() + element = super().to_xml_element() # Add periodic surface pair information if self.boundary_type == 'periodic': @@ -462,7 +460,7 @@ class XPlane(Plane): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., name=''): - super(XPlane, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'x-plane' self._coeff_keys = ['x0'] @@ -568,7 +566,7 @@ class YPlane(Plane): def __init__(self, surface_id=None, boundary_type='transmission', y0=0., name=''): # Initialize YPlane class attributes - super(YPlane, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'y-plane' self._coeff_keys = ['y0'] @@ -674,7 +672,7 @@ class ZPlane(Plane): def __init__(self, surface_id=None, boundary_type='transmission', z0=0., name=''): # Initialize ZPlane class attributes - super(ZPlane, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'z-plane' self._coeff_keys = ['z0'] @@ -738,8 +736,7 @@ class ZPlane(Plane): return point[2] - self.z0 -@add_metaclass(ABCMeta) -class Cylinder(Surface): +class Cylinder(Surface, metaclass=ABCMeta): """A cylinder whose length is parallel to the x-, y-, or z-axis. Parameters @@ -776,7 +773,7 @@ class Cylinder(Surface): """ def __init__(self, surface_id=None, boundary_type='transmission', R=1., name=''): - super(Cylinder, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._coeff_keys = ['R'] self.r = R @@ -836,7 +833,7 @@ class XCylinder(Cylinder): def __init__(self, surface_id=None, boundary_type='transmission', y0=0., z0=0., R=1., name=''): - super(XCylinder, self).__init__(surface_id, boundary_type, R, name=name) + super().__init__(surface_id, boundary_type, R, name=name) self._type = 'x-cylinder' self._coeff_keys = ['y0', 'z0', 'R'] @@ -958,7 +955,7 @@ class YCylinder(Cylinder): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., z0=0., R=1., name=''): - super(YCylinder, self).__init__(surface_id, boundary_type, R, name=name) + super().__init__(surface_id, boundary_type, R, name=name) self._type = 'y-cylinder' self._coeff_keys = ['x0', 'z0', 'R'] @@ -1080,7 +1077,7 @@ class ZCylinder(Cylinder): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., R=1., name=''): - super(ZCylinder, self).__init__(surface_id, boundary_type, R, name=name) + super().__init__(surface_id, boundary_type, R, name=name) self._type = 'z-cylinder' self._coeff_keys = ['x0', 'y0', 'R'] @@ -1206,7 +1203,7 @@ class Sphere(Surface): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R=1., name=''): - super(Sphere, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'sphere' self._coeff_keys = ['x0', 'y0', 'z0', 'R'] @@ -1305,8 +1302,7 @@ class Sphere(Surface): return x**2 + y**2 + z**2 - self.r**2 -@add_metaclass(ABCMeta) -class Cone(Surface): +class Cone(Surface, metaclass=ABCMeta): """A conical surface parallel to the x-, y-, or z-axis. Parameters @@ -1354,7 +1350,7 @@ class Cone(Surface): """ def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R2=1., name=''): - super(Cone, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._coeff_keys = ['x0', 'y0', 'z0', 'R2'] self.x0 = x0 @@ -1376,7 +1372,7 @@ class Cone(Surface): @property def r2(self): - return self.coefficients['r2'] + return self.coefficients['R2'] @x0.setter def x0(self, x0): @@ -1449,7 +1445,7 @@ class XCone(Cone): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R2=1., name=''): - super(XCone, self).__init__(surface_id, boundary_type, x0, y0, + super().__init__(surface_id, boundary_type, x0, y0, z0, R2, name=name) self._type = 'x-cone' @@ -1525,7 +1521,7 @@ class YCone(Cone): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R2=1., name=''): - super(YCone, self).__init__(surface_id, boundary_type, x0, y0, z0, + super().__init__(surface_id, boundary_type, x0, y0, z0, R2, name=name) self._type = 'y-cone' @@ -1601,7 +1597,7 @@ class ZCone(Cone): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R2=1., name=''): - super(ZCone, self).__init__(surface_id, boundary_type, x0, y0, z0, + super().__init__(surface_id, boundary_type, x0, y0, z0, R2, name=name) self._type = 'z-cone' @@ -1666,7 +1662,7 @@ class Quadric(Surface): def __init__(self, surface_id=None, boundary_type='transmission', a=0., b=0., c=0., d=0., e=0., f=0., g=0., h=0., j=0., k=0., name=''): - super(Quadric, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'quadric' self._coeff_keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k'] diff --git a/openmc/tallies.py b/openmc/tallies.py index 235ad2472e..6c055d1913 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -1,6 +1,4 @@ -from __future__ import division - -from collections import Iterable, MutableSequence +from collections.abc import Iterable, MutableSequence import copy import re from functools import partial, reduce @@ -10,7 +8,6 @@ import operator import warnings from xml.etree import ElementTree as ET -from six import string_types import numpy as np import pandas as pd import scipy.sparse as sps @@ -31,9 +28,8 @@ _PRODUCT_TYPES = ['tensor', 'entrywise'] # The following indicate acceptable types when setting Tally.scores, # Tally.nuclides, and Tally.filters -_SCORE_CLASSES = string_types + (openmc.CrossScore, openmc.AggregateScore) -_NUCLIDE_CLASSES = string_types + (openmc.Nuclide, openmc.CrossNuclide, - openmc.AggregateNuclide) +_SCORE_CLASSES = (str, openmc.CrossScore, openmc.AggregateScore) +_NUCLIDE_CLASSES = (str, openmc.CrossNuclide, openmc.AggregateNuclide) _FILTER_CLASSES = (openmc.Filter, openmc.CrossFilter, openmc.AggregateFilter) # Valid types of estimators @@ -336,30 +332,10 @@ class Tally(IDManagerMixin): self._triggers = cv.CheckedList(openmc.Trigger, 'tally triggers', triggers) - def add_trigger(self, trigger): - """Add a tally trigger to the tally - - .. deprecated:: 0.8 - Use the Tally.triggers property directly, i.e., - Tally.triggers.append(...) - - Parameters - ---------- - trigger : openmc.Trigger - Trigger to add - - """ - - warnings.warn('Tally.add_trigger(...) has been deprecated and may be ' - 'removed in a future version. Tally triggers should be ' - 'defined using the triggers property directly.', - DeprecationWarning) - self.triggers.append(trigger) - @name.setter def name(self, name): if name is not None: - cv.check_type('tally name', name, string_types) + cv.check_type('tally name', name, str) self._name = name else: self._name = '' @@ -412,85 +388,11 @@ class Tally(IDManagerMixin): raise ValueError(msg) # If score is a string, strip whitespace - if isinstance(score, string_types): + if isinstance(score, str): scores[i] = score.strip() self._scores = cv.CheckedList(_SCORE_CLASSES, 'tally scores', scores) - def add_filter(self, new_filter): - """Add a filter to the tally - - .. deprecated:: 0.8 - Use the Tally.filters property directly, i.e., - Tally.filters.append(...) - - Parameters - ---------- - new_filter : Filter, CrossFilter or AggregateFilter - A filter to specify a discretization of the tally across some - dimension (e.g., 'energy', 'cell'). The filter should be a Filter - object when a user is adding filters to a Tally for input file - generation or when the Tally is created from a StatePoint. The - filter may be a CrossFilter or AggregateFilter for derived tallies - created by tally arithmetic. - - """ - - warnings.warn('Tally.add_filter(...) has been deprecated and may be ' - 'removed in a future version. Tally filters should be ' - 'defined using the filters property directly.', - DeprecationWarning) - self.filters.append(new_filter) - - def add_nuclide(self, nuclide): - """Specify that scores for a particular nuclide should be accumulated - - .. deprecated:: 0.8 - Use the Tally.nuclides property directly, i.e., - Tally.nuclides.append(...) - - Parameters - ---------- - nuclide : str, openmc.Nuclide, CrossNuclide or AggregateNuclide - Nuclide to add to the tally. The nuclide should be a Nuclide object - when a user is adding nuclides to a Tally for input file generation. - The nuclide is a str when a Tally is created from a StatePoint file - (e.g., 'H1', 'U235') unless a Summary has been linked with the - StatePoint. The nuclide may be a CrossNuclide or AggregateNuclide - for derived tallies created by tally arithmetic. - - """ - - warnings.warn('Tally.add_nuclide(...) has been deprecated and may be ' - 'removed in a future version. Tally nuclides should be ' - 'defined using the nuclides property directly.', - DeprecationWarning) - self.nuclides.append(nuclide) - - def add_score(self, score): - """Specify a quantity to be scored - - .. deprecated:: 0.8 - Use the Tally.scores property directly, i.e., - Tally.scores.append(...) - - Parameters - ---------- - score : str, CrossScore or AggregateScore - A score to be accumulated (e.g., 'flux', 'nu-fission'). The score - should be a str when a user is adding scores to a Tally for input - file generation or when the Tally is created from a StatePoint. The - score may be a CrossScore or AggregateScore for derived tallies - created by tally arithmetic. - - """ - - warnings.warn('Tally.add_score(...) has been deprecated and may be ' - 'removed in a future version. Tally scores should be ' - 'defined using the scores property directly.', - DeprecationWarning) - self.scores.append(score) - @num_realizations.setter def num_realizations(self, num_realizations): cv.check_type('number of realizations', num_realizations, Integral) @@ -1262,9 +1164,7 @@ class Tally(IDManagerMixin): if not user_filter: # Create list of 2- or 3-tuples tuples for mesh cell bins if isinstance(self_filter, openmc.MeshFilter): - dimension = self_filter.mesh.dimension - xyz = [range(1, x+1) for x in dimension] - bins = list(product(*xyz)) + bins = list(self_filter.mesh.indices) # Create list of 2-tuples for energy boundary bins elif isinstance(self_filter, (openmc.EnergyFilter, @@ -1327,7 +1227,7 @@ class Tally(IDManagerMixin): """ - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) # Determine the score indices from any of the requested scores if nuclides: @@ -1362,7 +1262,7 @@ class Tally(IDManagerMixin): """ for score in scores: - if not isinstance(score, string_types + (openmc.CrossScore,)): + if not isinstance(score, (str, openmc.CrossScore)): msg = 'Unable to get score indices for score "{0}" in Tally ' \ 'ID="{1}" since it is not a string or CrossScore'\ .format(score, self.id) @@ -1508,8 +1408,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 """ @@ -1557,7 +1455,7 @@ class Tally(IDManagerMixin): column_name = 'score' for score in self.scores: - if isinstance(score, string_types + (openmc.CrossScore,)): + if isinstance(score, (str, openmc.CrossScore)): scores.append(str(score)) elif isinstance(score, openmc.AggregateScore): scores.append(score.name) @@ -1776,19 +1674,22 @@ class Tally(IDManagerMixin): new_tally._std_dev = np.sqrt(data['self']['std. dev.']**2 + data['other']['std. dev.']**2) elif binary_op == '*': - self_rel_err = data['self']['std. dev.'] / data['self']['mean'] - other_rel_err = data['other']['std. dev.'] / data['other']['mean'] + with np.errstate(divide='ignore', invalid='ignore'): + self_rel_err = data['self']['std. dev.'] / data['self']['mean'] + other_rel_err = data['other']['std. dev.'] / data['other']['mean'] new_tally._mean = data['self']['mean'] * data['other']['mean'] new_tally._std_dev = np.abs(new_tally.mean) * \ np.sqrt(self_rel_err**2 + other_rel_err**2) elif binary_op == '/': - self_rel_err = data['self']['std. dev.'] / data['self']['mean'] - other_rel_err = data['other']['std. dev.'] / data['other']['mean'] - new_tally._mean = data['self']['mean'] / data['other']['mean'] + with np.errstate(divide='ignore', invalid='ignore'): + self_rel_err = data['self']['std. dev.'] / data['self']['mean'] + other_rel_err = data['other']['std. dev.'] / data['other']['mean'] + new_tally._mean = data['self']['mean'] / data['other']['mean'] new_tally._std_dev = np.abs(new_tally.mean) * \ np.sqrt(self_rel_err**2 + other_rel_err**2) elif binary_op == '^': - mean_ratio = data['other']['mean'] / data['self']['mean'] + with np.errstate(divide='ignore', invalid='ignore'): + mean_ratio = data['other']['mean'] / data['self']['mean'] first_term = mean_ratio * data['self']['std. dev.'] second_term = \ np.log(data['self']['mean']) * data['other']['std. dev.'] @@ -2194,11 +2095,11 @@ class Tally(IDManagerMixin): raise ValueError(msg) # Check that the scores are valid - if not isinstance(score1, string_types + (openmc.CrossScore,)): + if not isinstance(score1, (str, openmc.CrossScore)): msg = 'Unable to swap score1 "{0}" in Tally ID="{1}" since it is ' \ 'not a string or CrossScore'.format(score1, self.id) raise ValueError(msg) - elif not isinstance(score2, string_types + (openmc.CrossScore,)): + elif not isinstance(score2, (str, openmc.CrossScore)): msg = 'Unable to swap score2 "{0}" in Tally ID="{1}" since it is ' \ 'not a string or CrossScore'.format(score2, self.id) raise ValueError(msg) @@ -2837,7 +2738,7 @@ class Tally(IDManagerMixin): new_filter = filter_type(bins) # Set number of bins manually for mesh/distribcell filters - if filter_type in (openmc.DistribcellFilter, openmc.MeshFilter): + if filter_type is openmc.DistribcellFilter: new_filter._num_bins = find_filter._num_bins # Replace existing filter with new one @@ -3248,30 +3149,10 @@ class Tallies(cv.CheckedList): """ def __init__(self, tallies=None): - super(Tallies, self).__init__(Tally, 'tallies collection') + super().__init__(Tally, 'tallies collection') if tallies is not None: self += tallies - def add_tally(self, tally, merge=False): - """Append tally to collection - - .. deprecated:: 0.8 - Use :meth:`Tallies.append` instead. - - Parameters - ---------- - tally : openmc.Tally - Tally to add - merge : bool - Indicate whether the tally should be merged with an existing tally, - if possible. Defaults to False. - - """ - warnings.warn("Tallies.add_tally(...) has been deprecated and may be " - "removed in a future version. Use Tallies.append(...) " - "instead.", DeprecationWarning) - self.append(tally, merge) - def append(self, tally, merge=False): """Append tally to collection @@ -3305,10 +3186,10 @@ class Tallies(cv.CheckedList): # If no mergeable tally was found, simply add this tally if not merged: - super(Tallies, self).append(tally) + super().append(tally) else: - super(Tallies, self).append(tally) + super().append(tally) def insert(self, index, item): """Insert tally before index @@ -3321,25 +3202,7 @@ class Tallies(cv.CheckedList): Tally to insert """ - super(Tallies, self).insert(index, item) - - def remove_tally(self, tally): - """Remove a tally from the collection - - .. deprecated:: 0.8 - Use :meth:`Tallies.remove` instead. - - Parameters - ---------- - tally : openmc.Tally - Tally to remove - - """ - warnings.warn("Tallies.remove_tally(...) has been deprecated and may " - "be removed in a future version. Use Tallies.remove(...) " - "instead.", DeprecationWarning) - - self.remove(tally) + super().insert(index, item) def merge_tallies(self): """Merge any mergeable tallies together. Note that n-way merges are @@ -3365,41 +3228,6 @@ class Tallies(cv.CheckedList): # Continue iterating from the first loop break - def add_mesh(self, mesh): - """Add a mesh to the file - - .. deprecated:: 0.8 - Meshes that appear in a tally are automatically added to the - collection. - - Parameters - ---------- - mesh : openmc.Mesh - Mesh to add to the file - - """ - - warnings.warn("Tallies.add_mesh(...) has been deprecated and may be " - "removed in a future version. Meshes that appear in a " - "tally are automatically added to the collection.", - DeprecationWarning) - - def remove_mesh(self, mesh): - """Remove a mesh from the file - - .. deprecated:: 0.8 - Meshes do not need to be managed explicitly. - - Parameters - ---------- - mesh : openmc.Mesh - Mesh to remove from the file - - """ - warnings.warn("Tallies.remove_mesh(...) has been deprecated and may be " - "removed in a future version. Meshes do not need to be " - "managed explicitly.", DeprecationWarning) - def _create_tally_subelements(self, root_element): for tally in self: root_element.append(tally.to_xml_element()) diff --git a/openmc/tally_derivative.py b/openmc/tally_derivative.py index facc56f447..9be748b2cb 100644 --- a/openmc/tally_derivative.py +++ b/openmc/tally_derivative.py @@ -1,11 +1,7 @@ -from __future__ import division - import sys from numbers import Integral from xml.etree import ElementTree as ET -from six import string_types - import openmc.checkvalue as cv from openmc.mixin import EqualityMixin, IDManagerMixin @@ -81,7 +77,7 @@ class TallyDerivative(EqualityMixin, IDManagerMixin): @variable.setter def variable(self, var): if var is not None: - cv.check_type('derivative variable', var, string_types) + cv.check_type('derivative variable', var, str) cv.check_value('derivative variable', var, ('density', 'nuclide_density', 'temperature')) self._variable = var @@ -95,7 +91,7 @@ class TallyDerivative(EqualityMixin, IDManagerMixin): @nuclide.setter def nuclide(self, nuc): if nuc is not None: - cv.check_type('derivative nuclide', nuc, string_types) + cv.check_type('derivative nuclide', nuc, str) self._nuclide = nuc def to_xml_element(self): diff --git a/openmc/trigger.py b/openmc/trigger.py index 69ec8c6200..71f9c0b92b 100644 --- a/openmc/trigger.py +++ b/openmc/trigger.py @@ -2,9 +2,7 @@ from numbers import Real from xml.etree import ElementTree as ET import sys import warnings -from collections import Iterable - -from six import string_types +from collections.abc import Iterable import openmc.checkvalue as cv @@ -76,7 +74,7 @@ class Trigger(object): @scores.setter def scores(self, scores): - cv.check_type('trigger scores', scores, Iterable, string_types) + cv.check_type('trigger scores', scores, Iterable, str) # Set scores making sure not to have duplicates self._scores = [] @@ -84,23 +82,6 @@ class Trigger(object): if score not in self._scores: self._scores.append(score) - - def add_score(self, score): - """Add a score to the list of scores to be checked against the trigger. - - Parameters - ---------- - score : str - Score to append - - """ - - warnings.warn('Trigger.add_score(...) has been deprecated and may be ' - 'removed in a future version. Tally trigger scores should ' - 'be defined using the scores property directly.', - DeprecationWarning) - self.scores.append(score) - def get_trigger_xml(self, element): """Return XML representation of the trigger diff --git a/openmc/universe.py b/openmc/universe.py index 92b152ca09..294b114dd2 100644 --- a/openmc/universe.py +++ b/openmc/universe.py @@ -1,12 +1,9 @@ -from __future__ import division from collections import OrderedDict, Iterable from copy import copy, deepcopy from numbers import Integral, Real import random import sys -from six import string_types -import matplotlib.pyplot as plt import numpy as np import openmc @@ -92,12 +89,12 @@ 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): if name is not None: - cv.check_type('universe name', name, string_types) + cv.check_type('universe name', name, str) self._name = name else: self._name = '' @@ -148,7 +145,7 @@ class Universe(IDManagerMixin): """ if volume_calc.domain_type == 'universe': if self.id in volume_calc.volumes: - self._volume = volume_calc.volumes[self.id][0] + self._volume = volume_calc.volumes[self.id].n self._atoms = volume_calc.atoms[self.id] else: raise ValueError('No volume information found for this universe.') @@ -186,10 +183,14 @@ class Universe(IDManagerMixin): return [] def plot(self, origin=(0., 0., 0.), width=(1., 1.), pixels=(200, 200), - basis='xy', color_by='cell', colors=None, filename=None, seed=None, + basis='xy', color_by='cell', colors=None, seed=None, **kwargs): """Display a slice plot of the universe. + To display or save the plot, call :func:`matplotlib.pyplot.show` or + :func:`matplotlib.pyplot.savefig`. In a Jupyter notebook, enabling the + matplotlib inline backend will show the plot inline. + Parameters ---------- origin : Iterable of float @@ -214,9 +215,6 @@ class Universe(IDManagerMixin): water = openmc.Cell(fill=h2o) universe.plot(..., colors={water: (0., 0., 1.)) - filename : str or None - Filename to save plot to. If no filename is given, the plot will be - displayed using the currently enabled matplotlib backend. seed : hashable object or None Hashable object which is used to seed the random number generator used to select colors. If None, the generator is seeded from the @@ -225,7 +223,14 @@ class Universe(IDManagerMixin): All keyword arguments are passed to :func:`matplotlib.pyplot.imshow`. + Returns + ------- + matplotlib.image.AxesImage + Resulting image + """ + import matplotlib.pyplot as plt + # Seed the random number generator if seed is not None: random.seed(seed) @@ -237,7 +242,7 @@ class Universe(IDManagerMixin): # Convert to RGBA if necessary colors = copy(colors) for obj, color in colors.items(): - if isinstance(color, string_types): + if isinstance(color, str): if color.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color." .format(color)) @@ -300,14 +305,8 @@ class Universe(IDManagerMixin): img[j, i, :] = colors[obj] # Display image - plt.imshow(img, extent=(x_min, x_max, y_min, y_max), - interpolation='nearest', **kwargs) - - # Show or save the plot - if filename is None: - plt.show() - else: - plt.savefig(filename) + return plt.imshow(img, extent=(x_min, x_max, y_min, y_max), + interpolation='nearest', **kwargs) def add_cell(self, cell): """Add a cell to the universe. @@ -322,7 +321,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 +341,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 +359,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: @@ -407,7 +406,7 @@ class Universe(IDManagerMixin): volume = self.volume for name, atoms in self._atoms.items(): nuclide = openmc.Nuclide(name) - density = 1.0e-24 * atoms[0]/volume # density in atoms/b-cm + density = 1.0e-24 * atoms.n/volume # density in atoms/b-cm nuclides[name] = (nuclide, density) else: raise RuntimeError( diff --git a/openmc/volume.py b/openmc/volume.py index cccb3c6a27..af7c356aed 100644 --- a/openmc/volume.py +++ b/openmc/volume.py @@ -1,4 +1,5 @@ -from collections import Iterable, Mapping, OrderedDict +from collections import OrderedDict +from collections.abc import Iterable, Mapping from numbers import Real, Integral from xml.etree import ElementTree as ET import warnings @@ -6,6 +7,7 @@ import warnings import numpy as np import pandas as pd import h5py +from uncertainties import ufloat import openmc import openmc.checkvalue as cv @@ -136,11 +138,10 @@ class VolumeCalculation(object): @property def atoms_dataframe(self): items = [] - columns = [self.domain_type.capitalize(), 'Nuclide', 'Atoms', - 'Uncertainty'] + columns = [self.domain_type.capitalize(), 'Nuclide', 'Atoms'] for uid, atoms_dict in self.atoms.items(): for name, atoms in atoms_dict.items(): - items.append((uid, name, atoms[0], atoms[1])) + items.append((uid, name, atoms)) return pd.DataFrame.from_records(items, columns=columns) @@ -210,13 +211,13 @@ class VolumeCalculation(object): domain_id = int(obj_name[7:]) ids.append(domain_id) group = f[obj_name] - volume = tuple(group['volume'].value) + volume = ufloat(*group['volume'].value) nucnames = group['nuclides'].value atoms_ = group['atoms'].value atom_dict = OrderedDict() for name_i, atoms_i in zip(nucnames, atoms_): - atom_dict[name_i.decode()] = tuple(atoms_i) + atom_dict[name_i.decode()] = ufloat(*atoms_i) volumes[domain_id] = volume atoms[domain_id] = atom_dict diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000000..cdd367ea9d --- /dev/null +++ b/pytest.ini @@ -0,0 +1,5 @@ +[pytest] +python_files = test*.py +python_classes = NoThanks +filterwarnings = ignore::UserWarning +addopts = -rs diff --git a/readme.rst b/readme.rst index b7366fe3e1..32cbb34e14 100644 --- a/readme.rst +++ b/readme.rst @@ -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 diff --git a/scripts/openmc-ace-to-hdf5 b/scripts/openmc-ace-to-hdf5 index 3235a2da63..29c987e07c 100755 --- a/scripts/openmc-ace-to-hdf5 +++ b/scripts/openmc-ace-to-hdf5 @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 import argparse import os diff --git a/scripts/openmc-convert-mcnp70-data b/scripts/openmc-convert-mcnp70-data index 0489b25de4..75b3b0a5a8 100755 --- a/scripts/openmc-convert-mcnp70-data +++ b/scripts/openmc-convert-mcnp70-data @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import print_function import argparse from collections import defaultdict import glob diff --git a/scripts/openmc-convert-mcnp71-data b/scripts/openmc-convert-mcnp71-data index 061f8f46f0..ce8c427d60 100755 --- a/scripts/openmc-convert-mcnp71-data +++ b/scripts/openmc-convert-mcnp71-data @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import print_function import argparse from collections import defaultdict import glob diff --git a/scripts/openmc-get-jeff-data b/scripts/openmc-get-jeff-data index 6d9e086a91..03b58163b0 100755 --- a/scripts/openmc-get-jeff-data +++ b/scripts/openmc-get-jeff-data @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import print_function import os from collections import defaultdict import sys @@ -9,9 +8,7 @@ import zipfile import glob import argparse from string import digits - -from six.moves import input -from six.moves.urllib.request import urlopen +from urllib.request import urlopen import openmc.data @@ -44,7 +41,7 @@ parser.add_argument('-b', '--batch', action='store_true', parser.add_argument('-d', '--destination', default='jeff-3.2-hdf5', help='Directory to create new library in') parser.add_argument('--libver', choices=['earliest', 'latest'], - default='earliest', help="Output HDF5 versioning. Use " + default='latest', help="Output HDF5 versioning. Use " "'earliest' for backwards compatibility or 'latest' for " "performance") args = parser.parse_args() diff --git a/scripts/openmc-get-multipole-data b/scripts/openmc-get-multipole-data index bf0add2840..ea25396488 100755 --- a/scripts/openmc-get-multipole-data +++ b/scripts/openmc-get-multipole-data @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import print_function import os import shutil import subprocess @@ -9,9 +8,7 @@ import tarfile import glob import hashlib import argparse - -from six.moves import input -from six.moves.urllib.request import urlopen +from urllib.request import urlopen description = """ diff --git a/scripts/openmc-get-nndc-data b/scripts/openmc-get-nndc-data index e2c1e7ce3a..a04eed6cd6 100755 --- a/scripts/openmc-get-nndc-data +++ b/scripts/openmc-get-nndc-data @@ -1,6 +1,5 @@ #!/usr/bin/env python -from __future__ import print_function import os import shutil import subprocess @@ -9,9 +8,7 @@ import tarfile import glob import hashlib import argparse - -from six.moves import input -from six.moves.urllib.request import urlopen +from urllib.request import urlopen import openmc.data diff --git a/scripts/openmc-make-depletion-chain b/scripts/openmc-make-depletion-chain new file mode 100755 index 0000000000..7c08f984e9 --- /dev/null +++ b/scripts/openmc-make-depletion-chain @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 + +import glob +import os +from zipfile import ZipFile + +from openmc._utils import download +import openmc.deplete + + +URLS = [ + 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-neutrons.zip', + 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-decay.zip', + 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-nfy.zip' +] + +def main(): + for url in URLS: + basename = download(url) + with ZipFile(basename, 'r') as zf: + print('Extracting {}...'.format(basename)) + zf.extractall() + + decay_files = glob.glob(os.path.join('decay', '*.endf')) + nfy_files = glob.glob(os.path.join('nfy', '*.endf')) + neutron_files = glob.glob(os.path.join('neutrons', '*.endf')) + + chain = openmc.deplete.Chain.from_endf(decay_files, nfy_files, neutron_files) + chain.export_to_xml('chain_endfb71.xml') + + +if __name__ == '__main__': + main() diff --git a/scripts/openmc-plot-mesh-tally b/scripts/openmc-plot-mesh-tally index c273a6d592..0dfb29b9b3 100755 --- a/scripts/openmc-plot-mesh-tally +++ b/scripts/openmc-plot-mesh-tally @@ -1,16 +1,16 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """Python script to plot tally data generated by OpenMC.""" import os import sys import argparse +import tkinter as tk +import tkinter.filedialog as filedialog +import tkinter.font as font +import tkinter.messagebox as messagebox +import tkinter.ttk as ttk -import six.moves.tkinter as tk -import six.moves.tkinter_filedialog as filedialog -import six.moves.tkinter_font as font -import six.moves.tkinter_messagebox as messagebox -import six.moves.tkinter_ttk as ttk from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg from matplotlib.figure import Figure diff --git a/scripts/openmc-track-to-vtk b/scripts/openmc-track-to-vtk index 1dd632f9dd..fa154a2a7f 100755 --- a/scripts/openmc-track-to-vtk +++ b/scripts/openmc-track-to-vtk @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """Convert HDF5 particle track to VTK poly data. diff --git a/scripts/openmc-update-inputs b/scripts/openmc-update-inputs index 3eb850207e..ef7cdf47bb 100755 --- a/scripts/openmc-update-inputs +++ b/scripts/openmc-update-inputs @@ -1,10 +1,8 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """Update OpenMC's input XML files to the latest format. """ -from __future__ import print_function - import argparse from difflib import get_close_matches from itertools import chain diff --git a/scripts/openmc-update-mgxs b/scripts/openmc-update-mgxs index f33adfc005..8559affb95 100755 --- a/scripts/openmc-update-mgxs +++ b/scripts/openmc-update-mgxs @@ -1,10 +1,9 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """Update OpenMC's deprecated multi-group cross section XML files to the latest HDF5-based format. """ -from __future__ import print_function import os import warnings import xml.etree.ElementTree as ET diff --git a/scripts/openmc-validate-xml b/scripts/openmc-validate-xml index e5a45f4691..f36ba2b5d3 100755 --- a/scripts/openmc-validate-xml +++ b/scripts/openmc-validate-xml @@ -1,6 +1,4 @@ -#!/usr/bin/env python - -from __future__ import print_function +#!/usr/bin/env python3 import os import sys diff --git a/scripts/openmc-voxel-to-silovtk b/scripts/openmc-voxel-to-silovtk index 9748cc3bba..e0cfc0a5ba 100755 --- a/scripts/openmc-voxel-to-silovtk +++ b/scripts/openmc-voxel-to-silovtk @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import division, print_function import struct import sys from argparse import ArgumentParser diff --git a/setup.py b/setup.py index 338fe5fec8..2a42dd65dd 100755 --- a/setup.py +++ b/setup.py @@ -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 @@ -48,11 +48,7 @@ kwargs = { 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Topic :: Scientific/Engineering' - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.2', - 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', @@ -60,7 +56,7 @@ kwargs = { # Required dependencies 'install_requires': [ - 'six', 'numpy>=1.9', 'h5py', 'scipy', 'ipython', 'matplotlib', + 'numpy>=1.9', 'h5py', 'scipy', 'ipython', 'matplotlib', 'pandas', 'lxml', 'uncertainties' ], diff --git a/src/api.F90 b/src/api.F90 index eb9a996950..df183c292f 100644 --- a/src/api.F90 +++ b/src/api.F90 @@ -18,7 +18,7 @@ module openmc_api use initialize, only: openmc_init use particle_header, only: Particle use plot, only: openmc_plot_geometry - use random_lcg, only: seed, openmc_set_seed + use random_lcg, only: openmc_get_seed, openmc_set_seed use settings use simulation_header use source_header, only: openmc_extend_sources, openmc_source_set_strength @@ -60,6 +60,7 @@ module openmc_api public :: openmc_get_filter_next_id public :: openmc_get_material_index public :: openmc_get_nuclide_index + public :: openmc_get_seed public :: openmc_get_tally_index public :: openmc_global_tallies public :: openmc_hard_reset @@ -74,11 +75,13 @@ module openmc_api public :: openmc_material_filter_get_bins public :: openmc_material_filter_set_bins public :: openmc_mesh_filter_set_mesh + public :: openmc_meshsurface_filter_set_mesh public :: openmc_next_batch public :: openmc_nuclide_name public :: openmc_plot_geometry public :: openmc_reset public :: openmc_run + public :: openmc_set_seed public :: openmc_simulation_finalize public :: openmc_simulation_init public :: openmc_source_bank @@ -119,6 +122,8 @@ contains energy_min_neutron = ZERO entropy_on = .false. gen_per_batch = 1 + index_entropy_mesh = -1 + index_ufs_mesh = -1 keff = ONE legendre_to_tabular = .true. legendre_to_tabular_points = 33 @@ -142,7 +147,7 @@ contains run_CE = .true. run_mode = NONE satisfy_triggers = .false. - seed = 1_8 + call openmc_set_seed(DEFAULT_SEED) source_latest = .false. source_separate = .false. source_write = .true. @@ -171,7 +176,7 @@ contains ! Close FORTRAN interface. call h5close_f(err) -#ifdef MPI +#ifdef OPENMC_MPI ! Free all MPI types call MPI_TYPE_FREE(MPI_BANK, err) #endif @@ -228,8 +233,6 @@ contains !=============================================================================== subroutine openmc_hard_reset() bind(C) - integer :: err - ! Reset all tallies and timers call openmc_reset() @@ -238,7 +241,7 @@ contains total_gen = 0 ! Reset the random number generator state - err = openmc_set_seed(1_8) + call openmc_set_seed(DEFAULT_SEED) end subroutine openmc_hard_reset !=============================================================================== @@ -273,8 +276,9 @@ contains ! Clear active tally lists call active_analog_tallies % clear() call active_tracklength_tallies % clear() - call active_current_tallies % clear() + call active_meshsurf_tallies % clear() call active_collision_tallies % clear() + call active_surface_tallies % clear() call active_tallies % clear() ! Reset timers diff --git a/src/cmfd_data.F90 b/src/cmfd_data.F90 index 521be5e3f2..3152f1eb2b 100644 --- a/src/cmfd_data.F90 +++ b/src/cmfd_data.F90 @@ -73,12 +73,10 @@ contains integer :: ital ! tally object index integer :: ijk(3) ! indices for mesh cell integer :: score_index ! index to pull from tally object - integer :: i_filt ! index in filters array integer :: i_filter_mesh ! index for mesh filter integer :: i_filter_ein ! index for incoming energy filter integer :: i_filter_eout ! index for outgoing energy filter - integer :: i_filter_surf ! index for surface filter - integer :: stride_surf ! stride for surface filter + integer :: i_mesh ! flattend index for mesh logical :: energy_filters! energy filters present real(8) :: flux ! temp variable for flux type(RegularMesh), pointer :: m ! pointer for mesh object @@ -95,10 +93,10 @@ contains ! Associate tallies and mesh associate (t => cmfd_tallies(1) % obj) - i_filt = t % filter(t % find_filter(FILTER_MESH)) + i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) end associate - select type(filt => filters(i_filt) % obj) + select type(filt => filters(i_filter_mesh) % obj) type is (MeshFilter) m => meshes(filt % mesh) end select @@ -115,16 +113,16 @@ contains ! Associate tallies and mesh associate (t => cmfd_tallies(ital) % obj) - i_filt = t % filter(t % find_filter(FILTER_MESH)) - select type(filt => filters(i_filt) % obj) - type is (MeshFilter) - m => meshes(filt % mesh) - end select + + if (ital < 3) then + i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) + else + i_filter_mesh = t % filter(t % find_filter(FILTER_MESHSURFACE)) + end if ! Check for energy filters energy_filters = (t % find_filter(FILTER_ENERGYIN) > 0) - i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) if (energy_filters) then i_filter_ein = t % filter(t % find_filter(FILTER_ENERGYIN)) i_filter_eout = t % filter(t % find_filter(FILTER_ENERGYOUT)) @@ -247,65 +245,62 @@ contains else if (ital == 3) then - i_filter_surf = t % filter(t % find_filter(FILTER_SURFACE)) - stride_surf = t % stride(t % find_filter(FILTER_SURFACE)) - ! Initialize and filter for energy do l = 1, size(t % filter) call filter_matches(t % filter(l)) % bins % clear() call filter_matches(t % filter(l)) % bins % push_back(1) end do + + ! Set the bin for this mesh cell + i_mesh = m % get_bin_from_indices([ i, j, k ]) + filter_matches(i_filter_mesh) % bins % data(1) = 12*(i_mesh - 1) + 1 + + ! Set the energy bin if needed if (energy_filters) then filter_matches(i_filter_ein) % bins % data(1) = ng - h + 1 end if - ! Get the bin for this mesh cell - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices([ i, j, k ]) - - score_index = 1 + score_index = 0 do l = 1, size(t % filter) - if (t % filter(l) == i_filter_surf) cycle score_index = score_index + (filter_matches(t % filter(l)) & % bins % data(1) - 1) * t % stride(l) end do ! Left surface cmfd % current(1,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_LEFT - 1) * stride_surf) + score_index + OUT_LEFT) cmfd % current(2,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_LEFT - 1) * stride_surf) + score_index + IN_LEFT) ! Right surface cmfd % current(3,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_RIGHT - 1) * stride_surf) + score_index + IN_RIGHT) cmfd % current(4,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_RIGHT - 1) * stride_surf) + score_index + OUT_RIGHT) ! Back surface cmfd % current(5,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_BACK - 1) * stride_surf) + score_index + OUT_BACK) cmfd % current(6,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_BACK - 1) * stride_surf) + score_index + IN_BACK) ! Front surface cmfd % current(7,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_FRONT - 1) * stride_surf) + score_index + IN_FRONT) cmfd % current(8,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_FRONT - 1) * stride_surf) + score_index + OUT_FRONT) - ! Bottom surface + ! Left surface cmfd % current(9,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_BOTTOM - 1) * stride_surf) + score_index + OUT_BOTTOM) cmfd % current(10,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_BOTTOM - 1) * stride_surf) + score_index + IN_BOTTOM) - ! Top surface + ! Right surface cmfd % current(11,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_TOP - 1) * stride_surf) + score_index + IN_TOP) cmfd % current(12,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_TOP - 1) * stride_surf) - + score_index + OUT_TOP) end if TALLY end do OUTGROUP diff --git a/src/cmfd_execute.F90 b/src/cmfd_execute.F90 index 9cdb751a40..af8d57a807 100644 --- a/src/cmfd_execute.F90 +++ b/src/cmfd_execute.F90 @@ -105,7 +105,7 @@ contains real(8) :: hxyz(3) ! cell dimensions of current ijk cell real(8) :: vol ! volume of cell real(8),allocatable :: source(:,:,:,:) ! tmp source array for entropy -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif @@ -197,7 +197,7 @@ contains end if -#ifdef MPI +#ifdef OPENMC_MPI ! Broadcast full source to all procs call MPI_BCAST(cmfd % cmfd_src, n, MPI_REAL8, 0, mpi_intracomm, mpi_err) #endif @@ -234,7 +234,7 @@ contains real(8) :: norm ! normalization factor logical :: outside ! any source sites outside mesh logical :: in_mesh ! source site is inside mesh -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err #endif @@ -291,7 +291,7 @@ contains if (.not. cmfd_feedback) return ! Broadcast weight factors to all procs -#ifdef MPI +#ifdef OPENMC_MPI call MPI_BCAST(cmfd % weightfactors, ng*nx*ny*nz, MPI_REAL8, 0, & mpi_intracomm, mpi_err) #endif diff --git a/src/cmfd_input.F90 b/src/cmfd_input.F90 index dbfabb2540..86f4e2400e 100644 --- a/src/cmfd_input.F90 +++ b/src/cmfd_input.F90 @@ -373,7 +373,7 @@ contains ! Determine number of filters energy_filters = check_for_node(node_mesh, "energy") - n = merge(5, 3, energy_filters) + n = merge(4, 2, energy_filters) ! Extend filters array so we can add CMFD filters err = openmc_extend_filters(n, i_filt_start, i_filt_end) @@ -409,44 +409,15 @@ contains ! Duplicate the mesh filter for the mesh current tally since other ! tallies use this filter and we need to change the dimension i_filt = i_filt + 1 - err = openmc_filter_set_type(i_filt, C_CHAR_'mesh' // C_NULL_CHAR) + err = openmc_filter_set_type(i_filt, C_CHAR_'meshsurface' // C_NULL_CHAR) call openmc_get_filter_next_id(filt_id) err = openmc_filter_set_id(i_filt, filt_id) - err = openmc_mesh_filter_set_mesh(i_filt, i_start) + err = openmc_meshsurface_filter_set_mesh(i_filt, i_start) - ! We need to increase the dimension by one since we also need - ! currents coming into and out of the boundary mesh cells. - filters(i_filt) % obj % n_bins = product(m % dimension + 1) - - ! Set up surface filter - i_filt = i_filt + 1 - allocate(SurfaceFilter :: filters(i_filt) % obj) - select type(filt => filters(i_filt) % obj) - type is(SurfaceFilter) - filt % id = i_filt - filt % n_bins = 4 * m % n_dimension - allocate(filt % surfaces(4 * m % n_dimension)) - if (m % n_dimension == 2) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, IN_RIGHT, OUT_RIGHT, & - OUT_BACK, IN_BACK, IN_FRONT, OUT_FRONT /) - elseif (m % n_dimension == 3) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, IN_RIGHT, OUT_RIGHT, & - OUT_BACK, IN_BACK, IN_FRONT, OUT_FRONT, & - OUT_BOTTOM, IN_BOTTOM, IN_TOP, OUT_TOP /) - end if - filt % current = .true. - ! Add filter to dictionary - call filter_dict % set(filt % id, i_filt) - end select ! Initialize filters do i = i_filt_start, i_filt_end - select type (filt => filters(i) % obj) - type is (SurfaceFilter) - ! Don't do anything - class default - call filt % initialize() - end select + call filters(i) % obj % initialize() end do ! Allocate tallies @@ -564,13 +535,9 @@ contains ! Set tally estimator to analog t % estimator = ESTIMATOR_ANALOG - ! Set the surface filter index in the tally find_filter array - n_filter = n_filter + 1 - ! Allocate and set filters allocate(filter_indices(n_filter)) - filter_indices(1) = i_filt_end - 1 - filter_indices(n_filter) = i_filt_end + filter_indices(1) = i_filt_end if (energy_filters) then filter_indices(2) = i_filt_start + 1 end if @@ -588,7 +555,7 @@ contains ! Set macro bins t % score_bins(1) = SCORE_CURRENT - t % type = TALLY_MESH_CURRENT + t % type = TALLY_MESH_SURFACE end if ! Make CMFD tallies active from the start diff --git a/src/constants.F90 b/src/constants.F90 index 331a644f09..0e138f0ee5 100644 --- a/src/constants.F90 +++ b/src/constants.F90 @@ -43,9 +43,9 @@ module constants real(8), parameter :: TINY_BIT = 1e-8_8 ! User for precision in geometry - real(8), parameter :: FP_PRECISION = 1e-14_8 - real(8), parameter :: FP_REL_PRECISION = 1e-5_8 - real(8), parameter :: FP_COINCIDENT = 1e-12_8 + real(C_DOUBLE), bind(C, name='FP_PRECISION') :: FP_PRECISION = 1e-14_8 + real(C_DOUBLE), bind(C, name='FP_REL_PRECISION') :: FP_REL_PRECISION = 1e-5_8 + real(C_DOUBLE), bind(C, name='FP_COINCIDENT') :: FP_COINCIDENT = 1e-12_8 ! Maximum number of collisions/crossings integer, parameter :: MAX_EVENTS = 1000000 @@ -95,11 +95,10 @@ module constants ! GEOMETRY-RELATED CONSTANTS ! Boundary conditions - integer, parameter :: & - BC_TRANSMIT = 0, & ! Transmission boundary condition (default) - BC_VACUUM = 1, & ! Vacuum boundary condition - BC_REFLECT = 2, & ! Reflecting boundary condition - BC_PERIODIC = 3 ! Periodic boundary condition + integer(C_INT), bind(C, name="BC_TRANSMIT") :: BC_TRANSMIT + integer(C_INT), bind(C, name="BC_VACUUM") :: BC_VACUUM + integer(C_INT), bind(C, name="BC_REFLECT") :: BC_REFLECT + integer(C_INT), bind(C, name="BC_PERIODIC") :: BC_PERIODIC ! Logical operators for cell definitions integer, parameter :: & @@ -293,7 +292,7 @@ module constants ! Tally type integer, parameter :: & TALLY_VOLUME = 1, & - TALLY_MESH_CURRENT = 2, & + TALLY_MESH_SURFACE = 2, & TALLY_SURFACE = 3 ! Tally estimator types @@ -359,7 +358,7 @@ module constants integer, parameter :: NO_BIN_FOUND = -1 ! Tally filter and map types - integer, parameter :: N_FILTER_TYPES = 15 + integer, parameter :: N_FILTER_TYPES = 16 integer, parameter :: & FILTER_UNIVERSE = 1, & FILTER_MATERIAL = 2, & @@ -375,7 +374,8 @@ module constants FILTER_AZIMUTHAL = 12, & FILTER_DELAYEDGROUP = 13, & FILTER_ENERGYFUNCTION = 14, & - FILTER_CELLFROM = 15 + FILTER_CELLFROM = 15, & + FILTER_MESHSURFACE = 16 ! Mesh types integer, parameter :: & diff --git a/src/cross_section.F90 b/src/cross_section.F90 deleted file mode 100644 index 69e5779669..0000000000 --- a/src/cross_section.F90 +++ /dev/null @@ -1,912 +0,0 @@ -module cross_section - - use algorithm, only: binary_search - use constants - use error, only: fatal_error - use list_header, only: ListElemInt - use material_header, only: Material, materials - use math, only: faddeeva, w_derivative, broaden_wmp_polynomials - use multipole_header, only: FORM_RM, FORM_MLBW, MP_EA, RM_RT, RM_RA, RM_RF, & - MLBW_RT, MLBW_RX, MLBW_RA, MLBW_RF, FIT_T, FIT_A,& - FIT_F, MultipoleArray - use nuclide_header - use particle_header, only: Particle - use random_lcg, only: prn, future_prn, prn_set_stream - use sab_header, only: SAlphaBeta, sab_tables - use settings - use simulation_header - use tally_header, only: active_tallies - - implicit none - -contains - -!=============================================================================== -! CALCULATE_XS determines the macroscopic cross sections for the material the -! particle is currently traveling through. -!=============================================================================== - - subroutine calculate_xs(p) - - type(Particle), intent(inout) :: p - - integer :: i ! loop index over nuclides - integer :: i_nuclide ! index into nuclides array - integer :: i_sab ! index into sab_tables array - integer :: j ! index in mat % i_sab_nuclides - integer :: i_grid ! index into logarithmic mapping array or material - ! union grid - real(8) :: atom_density ! atom density of a nuclide - real(8) :: sab_frac ! fraction of atoms affected by S(a,b) - logical :: check_sab ! should we check for S(a,b) table? - - ! Set all material macroscopic cross sections to zero - material_xs % total = ZERO - material_xs % elastic = ZERO - material_xs % absorption = ZERO - material_xs % fission = ZERO - material_xs % nu_fission = ZERO - - ! Exit subroutine if material is void - if (p % material == MATERIAL_VOID) return - - associate (mat => materials(p % material)) - ! Find energy index on energy grid - i_grid = int(log(p % E/energy_min_neutron)/log_spacing) - - ! Determine if this material has S(a,b) tables - check_sab = (mat % n_sab > 0) - - ! Initialize position in i_sab_nuclides - j = 1 - - ! Add contribution from each nuclide in material - do i = 1, mat % n_nuclides - ! ====================================================================== - ! CHECK FOR S(A,B) TABLE - - i_sab = 0 - sab_frac = ZERO - - ! Check if this nuclide matches one of the S(a,b) tables specified. - ! This relies on i_sab_nuclides being in sorted order - if (check_sab) then - if (i == mat % i_sab_nuclides(j)) then - ! Get index in sab_tables - i_sab = mat % i_sab_tables(j) - sab_frac = mat % sab_fracs(j) - - ! If particle energy is greater than the highest energy for the - ! S(a,b) table, then don't use the S(a,b) table - if (p % E > sab_tables(i_sab) % data(1) % threshold_inelastic) then - i_sab = 0 - end if - - ! Increment position in i_sab_nuclides - j = j + 1 - - ! Don't check for S(a,b) tables if there are no more left - if (j > size(mat % i_sab_tables)) check_sab = .false. - end if - end if - - ! ====================================================================== - ! CALCULATE MICROSCOPIC CROSS SECTION - - ! Determine microscopic cross sections for this nuclide - i_nuclide = mat % nuclide(i) - - ! Calculate microscopic cross section for this nuclide - if (p % E /= micro_xs(i_nuclide) % last_E & - .or. p % sqrtkT /= micro_xs(i_nuclide) % last_sqrtkT & - .or. i_sab /= micro_xs(i_nuclide) % index_sab & - .or. sab_frac /= micro_xs(i_nuclide) % sab_frac) then - call calculate_nuclide_xs(i_nuclide, i_sab, p % E, i_grid, & - p % sqrtkT, sab_frac) - end if - - ! ====================================================================== - ! ADD TO MACROSCOPIC CROSS SECTION - - ! Copy atom density of nuclide in material - atom_density = mat % atom_density(i) - - ! Add contributions to material macroscopic total cross section - material_xs % total = material_xs % total + & - atom_density * micro_xs(i_nuclide) % total - - ! Add contributions to material macroscopic scattering cross section - material_xs % elastic = material_xs % elastic + & - atom_density * micro_xs(i_nuclide) % elastic - - ! Add contributions to material macroscopic absorption cross section - material_xs % absorption = material_xs % absorption + & - atom_density * micro_xs(i_nuclide) % absorption - - ! Add contributions to material macroscopic fission cross section - material_xs % fission = material_xs % fission + & - atom_density * micro_xs(i_nuclide) % fission - - ! Add contributions to material macroscopic nu-fission cross section - material_xs % nu_fission = material_xs % nu_fission + & - atom_density * micro_xs(i_nuclide) % nu_fission - end do - end associate - - end subroutine calculate_xs - -!=============================================================================== -! CALCULATE_NUCLIDE_XS determines microscopic cross sections for a nuclide of a -! given index in the nuclides array at the energy of the given particle -!=============================================================================== - - subroutine calculate_nuclide_xs(i_nuclide, i_sab, E, i_log_union, sqrtkT, & - sab_frac) - integer, intent(in) :: i_nuclide ! index into nuclides array - integer, intent(in) :: i_sab ! index into sab_tables array - real(8), intent(in) :: E ! energy - integer, intent(in) :: i_log_union ! index into logarithmic mapping array or - ! material union energy grid - real(8), intent(in) :: sqrtkT ! square root of kT, material dependent - real(8), intent(in) :: sab_frac ! fraction of atoms affected by S(a,b) - - logical :: use_mp ! true if XS can be calculated with windowed multipole - integer :: i_temp ! index for temperature - integer :: i_grid ! index on nuclide energy grid - integer :: i_low ! lower logarithmic mapping index - integer :: i_high ! upper logarithmic mapping index - integer :: i_rxn ! reaction index - integer :: j ! index in DEPLETION_RX - real(8) :: f ! interp factor on nuclide energy grid - real(8) :: kT ! temperature in eV - real(8) :: sig_t, sig_a, sig_f ! Intermediate multipole variables - - ! Initialize cached cross sections to zero - micro_xs(i_nuclide) % thermal = ZERO - micro_xs(i_nuclide) % thermal_elastic = ZERO - - associate (nuc => nuclides(i_nuclide)) - ! Check to see if there is multipole data present at this energy - use_mp = .false. - if (nuc % mp_present) then - if (E >= nuc % multipole % start_E .and. & - E <= nuc % multipole % end_E) then - use_mp = .true. - end if - end if - - ! Evaluate multipole or interpolate - if (use_mp) then - ! Call multipole kernel - call multipole_eval(nuc % multipole, E, sqrtkT, sig_t, sig_a, sig_f) - - micro_xs(i_nuclide) % total = sig_t - micro_xs(i_nuclide) % absorption = sig_a - micro_xs(i_nuclide) % elastic = sig_t - sig_a - - if (nuc % fissionable) then - micro_xs(i_nuclide) % fission = sig_f - micro_xs(i_nuclide) % nu_fission = sig_f * nuc % nu(E, EMISSION_TOTAL) - else - micro_xs(i_nuclide) % fission = ZERO - micro_xs(i_nuclide) % nu_fission = ZERO - end if - - if (need_depletion_rx) then - ! Initialize all reaction cross sections to zero - micro_xs(i_nuclide) % reaction(:) = ZERO - - ! Only non-zero reaction is (n,gamma) - micro_xs(i_nuclide) % reaction(4) = sig_a - sig_f - end if - - ! Ensure these values are set - ! Note, the only time either is used is in one of 4 places: - ! 1. physics.F90 - scatter - For inelastic scatter. - ! 2. physics.F90 - sample_fission - For partial fissions. - ! 3. tally.F90 - score_general - For tallying on MTxxx reactions. - ! 4. cross_section.F90 - calculate_urr_xs - For unresolved purposes. - ! It is worth noting that none of these occur in the resolved - ! resonance range, so the value here does not matter. index_temp is - ! set to -1 to force a segfault in case a developer messes up and tries - ! to use it with multipole. - micro_xs(i_nuclide) % index_temp = -1 - micro_xs(i_nuclide) % index_grid = 0 - micro_xs(i_nuclide) % interp_factor = ZERO - - else - ! Find the appropriate temperature index. - kT = sqrtkT**2 - select case (temperature_method) - case (TEMPERATURE_NEAREST) - i_temp = minloc(abs(nuclides(i_nuclide) % kTs - kT), dim=1) - - case (TEMPERATURE_INTERPOLATION) - ! Find temperatures that bound the actual temperature - do i_temp = 1, size(nuc % kTs) - 1 - if (nuc % kTs(i_temp) <= kT .and. kT < nuc % kTs(i_temp + 1)) exit - end do - - ! Randomly sample between temperature i and i+1 - f = (kT - nuc % kTs(i_temp)) / & - (nuc % kTs(i_temp + 1) - nuc % kTs(i_temp)) - if (f > prn()) i_temp = i_temp + 1 - end select - - associate (grid => nuc % grid(i_temp), xs => nuc % sum_xs(i_temp)) - ! Determine the energy grid index using a logarithmic mapping to - ! reduce the energy range over which a binary search needs to be - ! performed - - if (E < grid % energy(1)) then - i_grid = 1 - elseif (E > grid % energy(size(grid % energy))) then - i_grid = size(grid % energy) - 1 - else - ! Determine bounding indices based on which equal log-spaced - ! interval the energy is in - i_low = grid % grid_index(i_log_union) - i_high = grid % grid_index(i_log_union + 1) + 1 - - ! Perform binary search over reduced range - i_grid = binary_search(grid % energy(i_low:i_high), & - i_high - i_low + 1, E) + i_low - 1 - end if - - ! check for rare case where two energy points are the same - if (grid % energy(i_grid) == grid % energy(i_grid + 1)) & - i_grid = i_grid + 1 - - ! calculate interpolation factor - f = (E - grid % energy(i_grid)) / & - (grid % energy(i_grid + 1) - grid % energy(i_grid)) - - micro_xs(i_nuclide) % index_temp = i_temp - micro_xs(i_nuclide) % index_grid = i_grid - micro_xs(i_nuclide) % interp_factor = f - - ! Calculate microscopic nuclide total cross section - micro_xs(i_nuclide) % total = (ONE - f) * xs % total(i_grid) & - + f * xs % total(i_grid + 1) - - ! Calculate microscopic nuclide elastic cross section - micro_xs(i_nuclide) % elastic = (ONE - f) * xs % elastic(i_grid) & - + f * xs % elastic(i_grid + 1) - - ! Calculate microscopic nuclide absorption cross section - micro_xs(i_nuclide) % absorption = (ONE - f) * xs % absorption( & - i_grid) + f * xs % absorption(i_grid + 1) - - if (nuc % fissionable) then - ! Calculate microscopic nuclide total cross section - micro_xs(i_nuclide) % fission = (ONE - f) * xs % fission(i_grid) & - + f * xs % fission(i_grid + 1) - - ! Calculate microscopic nuclide nu-fission cross section - micro_xs(i_nuclide) % nu_fission = (ONE - f) * xs % nu_fission( & - i_grid) + f * xs % nu_fission(i_grid + 1) - else - micro_xs(i_nuclide) % fission = ZERO - micro_xs(i_nuclide) % nu_fission = ZERO - end if - end associate - - ! Depletion-related reactions - if (need_depletion_rx) then - do j = 1, 6 - ! Initialize reaction xs to zero - micro_xs(i_nuclide) % reaction(j) = ZERO - - ! If reaction is present and energy is greater than threshold, set - ! the reaction xs appropriately - i_rxn = nuc % reaction_index(DEPLETION_RX(j)) - if (i_rxn > 0) then - associate (xs => nuc % reactions(i_rxn) % xs(i_temp)) - if (i_grid >= xs % threshold) then - micro_xs(i_nuclide) % reaction(j) = (ONE - f) * & - xs % value(i_grid - xs % threshold + 1) + & - f * xs % value(i_grid - xs % threshold + 2) - end if - end associate - end if - end do - end if - - end if - - ! Initialize sab treatment to false - micro_xs(i_nuclide) % index_sab = NONE - micro_xs(i_nuclide) % sab_frac = ZERO - - ! Initialize URR probability table treatment to false - micro_xs(i_nuclide) % use_ptable = .false. - - ! If there is S(a,b) data for this nuclide, we need to set the sab_scatter - ! and sab_elastic cross sections and correct the total and elastic cross - ! sections. - - if (i_sab > 0) then - call calculate_sab_xs(i_nuclide, i_sab, E, sqrtkT, sab_frac) - end if - - ! If the particle is in the unresolved resonance range and there are - ! probability tables, we need to determine cross sections from the table - - if (urr_ptables_on .and. nuc % urr_present .and. .not. use_mp) then - if (E > nuc % urr_data(i_temp) % energy(1) .and. E < nuc % & - urr_data(i_temp) % energy(nuc % urr_data(i_temp) % n_energy)) then - call calculate_urr_xs(i_nuclide, i_temp, E) - end if - end if - - micro_xs(i_nuclide) % last_E = E - micro_xs(i_nuclide) % last_sqrtkT = sqrtkT - end associate - - end subroutine calculate_nuclide_xs - -!=============================================================================== -! CALCULATE_SAB_XS determines the elastic and inelastic scattering -! cross-sections in the thermal energy range. These cross sections replace a -! fraction of whatever data were taken from the normal Nuclide table. -!=============================================================================== - - subroutine calculate_sab_xs(i_nuclide, i_sab, E, sqrtkT, sab_frac) - integer, intent(in) :: i_nuclide ! index into nuclides array - integer, intent(in) :: i_sab ! index into sab_tables array - real(8), intent(in) :: E ! energy - real(8), intent(in) :: sqrtkT ! temperature - real(8), intent(in) :: sab_frac ! fraction of atoms affected by S(a,b) - - integer :: i_grid ! index on S(a,b) energy grid - integer :: i_temp ! temperature index - real(8) :: f ! interp factor on S(a,b) energy grid - real(8) :: inelastic ! S(a,b) inelastic cross section - real(8) :: elastic ! S(a,b) elastic cross section - real(8) :: kT - - ! Set flag that S(a,b) treatment should be used for scattering - micro_xs(i_nuclide) % index_sab = i_sab - - ! Determine temperature for S(a,b) table - kT = sqrtkT**2 - if (temperature_method == TEMPERATURE_NEAREST) then - ! If using nearest temperature, do linear search on temperature - do i_temp = 1, size(sab_tables(i_sab) % kTs) - if (abs(sab_tables(i_sab) % kTs(i_temp) - kT) < & - K_BOLTZMANN*temperature_tolerance) exit - end do - else - ! Find temperatures that bound the actual temperature - do i_temp = 1, size(sab_tables(i_sab) % kTs) - 1 - if (sab_tables(i_sab) % kTs(i_temp) <= kT .and. & - kT < sab_tables(i_sab) % kTs(i_temp + 1)) exit - end do - - ! Randomly sample between temperature i and i+1 - f = (kT - sab_tables(i_sab) % kTs(i_temp)) / & - (sab_tables(i_sab) % kTs(i_temp + 1) & - - sab_tables(i_sab) % kTs(i_temp)) - if (f > prn()) i_temp = i_temp + 1 - end if - - - ! Get pointer to S(a,b) table - associate (sab => sab_tables(i_sab) % data(i_temp)) - - ! Get index and interpolation factor for inelastic grid - if (E < sab % inelastic_e_in(1)) then - i_grid = 1 - f = ZERO - else - i_grid = binary_search(sab % inelastic_e_in, sab % n_inelastic_e_in, E) - f = (E - sab%inelastic_e_in(i_grid)) / & - (sab%inelastic_e_in(i_grid+1) - sab%inelastic_e_in(i_grid)) - end if - - ! Calculate S(a,b) inelastic scattering cross section - inelastic = (ONE - f) * sab % inelastic_sigma(i_grid) + & - f * sab % inelastic_sigma(i_grid + 1) - - ! Check for elastic data - if (E < sab % threshold_elastic) then - ! Determine whether elastic scattering is given in the coherent or - ! incoherent approximation. For coherent, the cross section is - ! represented as P/E whereas for incoherent, it is simply P - - if (sab % elastic_mode == SAB_ELASTIC_EXACT) then - if (E < sab % elastic_e_in(1)) then - ! If energy is below that of the lowest Bragg peak, the elastic - ! cross section will be zero - elastic = ZERO - else - i_grid = binary_search(sab % elastic_e_in, & - sab % n_elastic_e_in, E) - elastic = sab % elastic_P(i_grid) / E - end if - else - ! Determine index on elastic energy grid - if (E < sab % elastic_e_in(1)) then - i_grid = 1 - else - i_grid = binary_search(sab % elastic_e_in, & - sab % n_elastic_e_in, E) - end if - - ! Get interpolation factor for elastic grid - f = (E - sab%elastic_e_in(i_grid))/(sab%elastic_e_in(i_grid+1) - & - sab%elastic_e_in(i_grid)) - - ! Calculate S(a,b) elastic scattering cross section - elastic = (ONE - f) * sab % elastic_P(i_grid) + & - f * sab % elastic_P(i_grid + 1) - end if - else - ! No elastic data - elastic = ZERO - end if - end associate - - ! Store the S(a,b) cross sections. - micro_xs(i_nuclide) % thermal = sab_frac * (elastic + inelastic) - micro_xs(i_nuclide) % thermal_elastic = sab_frac * elastic - - ! Correct total and elastic cross sections - micro_xs(i_nuclide) % total = micro_xs(i_nuclide) % total & - + micro_xs(i_nuclide) % thermal & - - sab_frac * micro_xs(i_nuclide) % elastic - micro_xs(i_nuclide) % elastic = micro_xs(i_nuclide) % thermal & - + (ONE - sab_frac) * micro_xs(i_nuclide) % elastic - - ! Save temperature index and thermal fraction - micro_xs(i_nuclide) % index_temp_sab = i_temp - micro_xs(i_nuclide) % sab_frac = sab_frac - - end subroutine calculate_sab_xs - -!=============================================================================== -! CALCULATE_URR_XS determines cross sections in the unresolved resonance range -! from probability tables -!=============================================================================== - - subroutine calculate_urr_xs(i_nuclide, i_temp, E) - integer, intent(in) :: i_nuclide ! index into nuclides array - integer, intent(in) :: i_temp ! temperature index - real(8), intent(in) :: E ! energy - - integer :: i_energy ! index for energy - integer :: i_low ! band index at lower bounding energy - integer :: i_up ! band index at upper bounding energy - real(8) :: f ! interpolation factor - real(8) :: r ! pseudo-random number - real(8) :: elastic ! elastic cross section - real(8) :: capture ! (n,gamma) cross section - real(8) :: fission ! fission cross section - real(8) :: inelastic ! inelastic cross section - - micro_xs(i_nuclide) % use_ptable = .true. - - associate (nuc => nuclides(i_nuclide), urr => nuclides(i_nuclide) % urr_data(i_temp)) - ! determine energy table - i_energy = 1 - do - if (E < urr % energy(i_energy + 1)) exit - i_energy = i_energy + 1 - end do - - ! determine interpolation factor on table - f = (E - urr % energy(i_energy)) / & - (urr % energy(i_energy + 1) - urr % energy(i_energy)) - - ! sample probability table using the cumulative distribution - - ! Random numbers for xs calculation are sampled from a separated stream. - ! This guarantees the randomness and, at the same time, makes sure we reuse - ! random number for the same nuclide at different temperatures, therefore - ! preserving correlation of temperature in probability tables. - call prn_set_stream(STREAM_URR_PTABLE) - r = future_prn(int(i_nuclide, 8)) - call prn_set_stream(STREAM_TRACKING) - - i_low = 1 - do - if (urr % prob(i_energy, URR_CUM_PROB, i_low) > r) exit - i_low = i_low + 1 - end do - i_up = 1 - do - if (urr % prob(i_energy + 1, URR_CUM_PROB, i_up) > r) exit - i_up = i_up + 1 - end do - - ! determine elastic, fission, and capture cross sections from probability - ! table - if (urr % interp == LINEAR_LINEAR) then - elastic = (ONE - f) * urr % prob(i_energy, URR_ELASTIC, i_low) + & - f * urr % prob(i_energy + 1, URR_ELASTIC, i_up) - fission = (ONE - f) * urr % prob(i_energy, URR_FISSION, i_low) + & - f * urr % prob(i_energy + 1, URR_FISSION, i_up) - capture = (ONE - f) * urr % prob(i_energy, URR_N_GAMMA, i_low) + & - f * urr % prob(i_energy + 1, URR_N_GAMMA, i_up) - elseif (urr % interp == LOG_LOG) then - ! Get logarithmic interpolation factor - f = log(E / urr % energy(i_energy)) / & - log(urr % energy(i_energy + 1) / urr % energy(i_energy)) - - ! Calculate elastic cross section/factor - elastic = ZERO - if (urr % prob(i_energy, URR_ELASTIC, i_low) > ZERO .and. & - urr % prob(i_energy + 1, URR_ELASTIC, i_up) > ZERO) then - elastic = exp((ONE - f) * log(urr % prob(i_energy, URR_ELASTIC, & - i_low)) + f * log(urr % prob(i_energy + 1, URR_ELASTIC, & - i_up))) - end if - - ! Calculate fission cross section/factor - fission = ZERO - if (urr % prob(i_energy, URR_FISSION, i_low) > ZERO .and. & - urr % prob(i_energy + 1, URR_FISSION, i_up) > ZERO) then - fission = exp((ONE - f) * log(urr % prob(i_energy, URR_FISSION, & - i_low)) + f * log(urr % prob(i_energy + 1, URR_FISSION, & - i_up))) - end if - - ! Calculate capture cross section/factor - capture = ZERO - if (urr % prob(i_energy, URR_N_GAMMA, i_low) > ZERO .and. & - urr % prob(i_energy + 1, URR_N_GAMMA, i_up) > ZERO) then - capture = exp((ONE - f) * log(urr % prob(i_energy, URR_N_GAMMA, & - i_low)) + f * log(urr % prob(i_energy + 1, URR_N_GAMMA, & - i_up))) - end if - end if - - ! Determine treatment of inelastic scattering - inelastic = ZERO - if (urr % inelastic_flag > 0) then - ! Get index on energy grid and interpolation factor - i_energy = micro_xs(i_nuclide) % index_grid - f = micro_xs(i_nuclide) % interp_factor - - ! Determine inelastic scattering cross section - associate (xs => nuc % reactions(nuc % urr_inelastic) % xs(i_temp)) - if (i_energy >= xs % threshold) then - inelastic = (ONE - f) * xs % value(i_energy - xs % threshold + 1) + & - f * xs % value(i_energy - xs % threshold + 2) - end if - end associate - end if - - ! Multiply by smooth cross-section if needed - if (urr % multiply_smooth) then - elastic = elastic * micro_xs(i_nuclide) % elastic - capture = capture * (micro_xs(i_nuclide) % absorption - & - micro_xs(i_nuclide) % fission) - fission = fission * micro_xs(i_nuclide) % fission - end if - - ! Check for negative values - if (elastic < ZERO) elastic = ZERO - if (fission < ZERO) fission = ZERO - if (capture < ZERO) capture = ZERO - - ! Set elastic, absorption, fission, and total cross sections. Note that the - ! total cross section is calculated as sum of partials rather than using the - ! table-provided value - micro_xs(i_nuclide) % elastic = elastic - micro_xs(i_nuclide) % absorption = capture + fission - micro_xs(i_nuclide) % fission = fission - micro_xs(i_nuclide) % total = elastic + inelastic + capture + fission - - ! Determine nu-fission cross section - if (nuc % fissionable) then - micro_xs(i_nuclide) % nu_fission = nuc % nu(E, EMISSION_TOTAL) * & - micro_xs(i_nuclide) % fission - end if - end associate - - end subroutine calculate_urr_xs - -!=============================================================================== -! MULTIPOLE_EVAL evaluates the windowed multipole equations for cross -! sections in the resolved resonance regions -!=============================================================================== - - subroutine multipole_eval(multipole, E, sqrtkT, sig_t, sig_a, sig_f) - type(MultipoleArray), intent(in) :: multipole ! The windowed multipole - ! object to process. - real(8), intent(in) :: E ! The energy at which to - ! evaluate the cross section - real(8), intent(in) :: sqrtkT ! The temperature in the form - ! sqrt(kT), at which - ! to evaluate the XS. - real(8), intent(out) :: sig_t ! Total cross section - real(8), intent(out) :: sig_a ! Absorption cross section - real(8), intent(out) :: sig_f ! Fission cross section - complex(8) :: psi_chi ! The value of the psi-chi function for the - ! asymptotic form - complex(8) :: c_temp ! complex temporary variable - complex(8) :: w_val ! The faddeeva function evaluated at Z - complex(8) :: Z ! sqrt(atomic weight ratio / kT) * (sqrt(E) - pole) - complex(8) :: sig_t_factor(multipole % num_l) - real(8) :: broadened_polynomials(multipole % fit_order + 1) - real(8) :: sqrtE ! sqrt(E), eV - real(8) :: invE ! 1/E, eV - real(8) :: dopp ! sqrt(atomic weight ratio / kT) = 1 / (2 sqrt(xi)) - real(8) :: temp ! real temporary value - integer :: i_pole ! index of pole - integer :: i_poly ! index of curvefit - integer :: i_window ! index of window - integer :: startw ! window start pointer (for poles) - integer :: endw ! window end pointer - - ! ========================================================================== - ! Bookkeeping - - ! Define some frequently used variables. - sqrtE = sqrt(E) - invE = ONE / E - - ! Locate us. - i_window = floor((sqrtE - sqrt(multipole % start_E)) / multipole % spacing & - + ONE) - startw = multipole % w_start(i_window) - endw = multipole % w_end(i_window) - - ! Fill in factors. - if (startw <= endw) then - call compute_sig_t_factor(multipole, sqrtE, sig_t_factor) - end if - - ! Initialize the ouptut cross sections. - sig_t = ZERO - sig_a = ZERO - sig_f = ZERO - - ! ========================================================================== - ! Add the contribution from the curvefit polynomial. - - if (sqrtkT /= ZERO .and. multipole % broaden_poly(i_window) == 1) then - ! Broaden the curvefit. - dopp = multipole % sqrtAWR / sqrtkT - call broaden_wmp_polynomials(E, dopp, multipole % fit_order + 1, & - broadened_polynomials) - do i_poly = 1, multipole % fit_order+1 - sig_t = sig_t + multipole % curvefit(FIT_T, i_poly, i_window) & - * broadened_polynomials(i_poly) - sig_a = sig_a + multipole % curvefit(FIT_A, i_poly, i_window) & - * broadened_polynomials(i_poly) - if (multipole % fissionable) then - sig_f = sig_f + multipole % curvefit(FIT_F, i_poly, i_window) & - * broadened_polynomials(i_poly) - end if - end do - else ! Evaluate as if it were a polynomial - temp = invE - do i_poly = 1, multipole % fit_order+1 - sig_t = sig_t + multipole % curvefit(FIT_T, i_poly, i_window) * temp - sig_a = sig_a + multipole % curvefit(FIT_A, i_poly, i_window) * temp - if (multipole % fissionable) then - sig_f = sig_f + multipole % curvefit(FIT_F, i_poly, i_window) * temp - end if - temp = temp * sqrtE - end do - end if - - ! ========================================================================== - ! Add the contribution from the poles in this window. - - if (sqrtkT == ZERO) then - ! If at 0K, use asymptotic form. - do i_pole = startw, endw - psi_chi = -ONEI / (multipole % data(MP_EA, i_pole) - sqrtE) - c_temp = psi_chi / E - if (multipole % formalism == FORM_MLBW) then - sig_t = sig_t + real(multipole % data(MLBW_RT, i_pole) * c_temp * & - sig_t_factor(multipole % l_value(i_pole))) & - + real(multipole % data(MLBW_RX, i_pole) * c_temp) - sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * c_temp) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * c_temp) - end if - else if (multipole % formalism == FORM_RM) then - sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * c_temp * & - sig_t_factor(multipole % l_value(i_pole))) - sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * c_temp) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * c_temp) - end if - end if - end do - else - ! At temperature, use Faddeeva function-based form. - dopp = multipole % sqrtAWR / sqrtkT - if (endw >= startw) then - do i_pole = startw, endw - Z = (sqrtE - multipole % data(MP_EA, i_pole)) * dopp - w_val = faddeeva(Z) * dopp * invE * SQRT_PI - if (multipole % formalism == FORM_MLBW) then - sig_t = sig_t + real((multipole % data(MLBW_RT, i_pole) * & - sig_t_factor(multipole % l_value(i_pole)) + & - multipole % data(MLBW_RX, i_pole)) * w_val) - sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * w_val) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * w_val) - end if - else if (multipole % formalism == FORM_RM) then - sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * w_val * & - sig_t_factor(multipole % l_value(i_pole))) - sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * w_val) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * w_val) - end if - end if - end do - end if - end if - end subroutine multipole_eval - -!=============================================================================== -! MULTIPOLE_DERIV_EVAL evaluates the windowed multipole equations for the -! derivative of cross sections in the resolved resonance regions with respect to -! temperature. -!=============================================================================== - - subroutine multipole_deriv_eval(multipole, E, sqrtkT, sig_t, sig_a, sig_f) - type(MultipoleArray), intent(in) :: multipole ! The windowed multipole - ! object to process. - real(8), intent(in) :: E ! The energy at which to - ! evaluate the cross section - real(8), intent(in) :: sqrtkT ! The temperature in the form - ! sqrt(kT), at which to - ! evaluate the XS. - real(8), intent(out) :: sig_t ! Total cross section - real(8), intent(out) :: sig_a ! Absorption cross section - real(8), intent(out) :: sig_f ! Fission cross section - complex(8) :: w_val ! The faddeeva function evaluated at Z - complex(8) :: Z ! sqrt(atomic weight ratio / kT) * (sqrt(E) - pole) - complex(8) :: sig_t_factor(multipole % num_l) - real(8) :: sqrtE ! sqrt(E), eV - real(8) :: invE ! 1/E, eV - real(8) :: dopp ! sqrt(atomic weight ratio / kT) - integer :: i_pole ! index of pole - integer :: i_window ! index of window - integer :: startw ! window start pointer (for poles) - integer :: endw ! window end pointer - real(8) :: T - - ! ========================================================================== - ! Bookkeeping - - ! Define some frequently used variables. - sqrtE = sqrt(E) - invE = ONE / E - T = sqrtkT**2 / K_BOLTZMANN - - if (sqrtkT == ZERO) call fatal_error("Windowed multipole temperature & - &derivatives are not implemented for 0 Kelvin cross sections.") - - ! Locate us - i_window = floor((sqrtE - sqrt(multipole % start_E)) / multipole % spacing & - + ONE) - startw = multipole % w_start(i_window) - endw = multipole % w_end(i_window) - - ! Fill in factors. - if (startw <= endw) then - call compute_sig_t_factor(multipole, sqrtE, sig_t_factor) - end if - - ! Initialize the ouptut cross sections. - sig_t = ZERO - sig_a = ZERO - sig_f = ZERO - - ! TODO Polynomials: Some of the curvefit polynomials Doppler broaden so - ! rigorously we should be computing the derivative of those. But in - ! practice, those derivatives are only large at very low energy and they - ! have no effect on reactor calculations. - - ! ========================================================================== - ! Add the contribution from the poles in this window. - - dopp = multipole % sqrtAWR / sqrtkT - if (endw >= startw) then - do i_pole = startw, endw - Z = (sqrtE - multipole % data(MP_EA, i_pole)) * dopp - w_val = -invE * SQRT_PI * HALF * w_derivative(Z, 2) - if (multipole % formalism == FORM_MLBW) then - sig_t = sig_t + real((multipole % data(MLBW_RT, i_pole) * & - sig_t_factor(multipole%l_value(i_pole)) + & - multipole % data(MLBW_RX, i_pole)) * w_val) - sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * w_val) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * w_val) - end if - else if (multipole % formalism == FORM_RM) then - sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * w_val * & - sig_t_factor(multipole % l_value(i_pole))) - sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * w_val) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * w_val) - end if - end if - end do - sig_t = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_t - sig_a = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_a - sig_f = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_f - end if - end subroutine multipole_deriv_eval - -!=============================================================================== -! COMPUTE_SIG_T_FACTOR calculates the sig_t_factor, a factor inside of the sig_t -! equation not present in the sig_a and sig_f equations. -!=============================================================================== - - subroutine compute_sig_t_factor(multipole, sqrtE, sig_t_factor) - type(MultipoleArray), intent(in) :: multipole - real(8), intent(in) :: sqrtE - complex(8), intent(out) :: sig_t_factor(multipole % num_l) - - integer :: iL - real(8) :: twophi(multipole % num_l) - real(8) :: arg - - do iL = 1, multipole % num_l - twophi(iL) = multipole % pseudo_k0RS(iL) * sqrtE - if (iL == 2) then - twophi(iL) = twophi(iL) - atan(twophi(iL)) - else if (iL == 3) then - arg = 3.0_8 * twophi(iL) / (3.0_8 - twophi(iL)**2) - twophi(iL) = twophi(iL) - atan(arg) - else if (iL == 4) then - arg = twophi(iL) * (15.0_8 - twophi(iL)**2) & - / (15.0_8 - 6.0_8 * twophi(iL)**2) - twophi(iL) = twophi(iL) - atan(arg) - end if - end do - - twophi = 2.0_8 * twophi - sig_t_factor = cmplx(cos(twophi), -sin(twophi), KIND=8) - end subroutine compute_sig_t_factor - -!=============================================================================== -! 0K_ELASTIC_XS determines the microscopic 0K elastic cross section -! for a given nuclide at the trial relative energy used in resonance scattering -!=============================================================================== - - pure function elastic_xs_0K(E, nuc) result(xs_out) - real(8), intent(in) :: E ! trial energy - type(Nuclide), intent(in) :: nuc ! target nuclide at temperature - real(8) :: xs_out ! 0K xs at trial energy - - integer :: i_grid ! index on nuclide energy grid - integer :: n_grid - real(8) :: f ! interp factor on nuclide energy grid - - ! Determine index on nuclide energy grid - n_grid = size(nuc % energy_0K) - if (E < nuc % energy_0K(1)) then - i_grid = 1 - elseif (E > nuc % energy_0K(n_grid)) then - i_grid = n_grid - 1 - else - i_grid = binary_search(nuc % energy_0K, n_grid, E) - end if - - ! check for rare case where two energy points are the same - if (nuc % energy_0K(i_grid) == nuc % energy_0K(i_grid+1)) then - i_grid = i_grid + 1 - end if - - ! calculate interpolation factor - f = (E - nuc % energy_0K(i_grid)) & - & / (nuc % energy_0K(i_grid + 1) - nuc % energy_0K(i_grid)) - - ! Calculate microscopic nuclide elastic cross section - xs_out = (ONE - f) * nuc % elastic_0K(i_grid) & - & + f * nuc % elastic_0K(i_grid + 1) - - end function elastic_xs_0K - -end module cross_section diff --git a/src/eigenvalue.F90 b/src/eigenvalue.F90 index 27ae4063ea..7a11d1fb48 100644 --- a/src/eigenvalue.F90 +++ b/src/eigenvalue.F90 @@ -42,11 +42,11 @@ contains type(Bank), save, allocatable :: & & temp_sites(:) ! local array of extra sites on each node -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code integer(8) :: n ! number of sites to send/recv integer :: neighbor ! processor to send/recv data from -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 type(MPI_Request) :: request(20) #else integer :: request(20) ! communication request for send/recving sites @@ -66,7 +66,7 @@ contains ! fission bank its own sites starts in order to ensure reproducibility by ! skipping ahead to the proper seed. -#ifdef MPI +#ifdef OPENMC_MPI start = 0_8 call MPI_EXSCAN(n_bank, start, 1, MPI_INTEGER8, MPI_SUM, & mpi_intracomm, mpi_err) @@ -148,7 +148,7 @@ contains ! neighboring processors, we have to perform an ALLGATHER to determine the ! indices for all processors -#ifdef MPI +#ifdef OPENMC_MPI ! First do an exclusive scan to get the starting indices for start = 0_8 call MPI_EXSCAN(index_temp, start, 1, MPI_INTEGER8, MPI_SUM, & @@ -191,7 +191,7 @@ contains call time_bank_sample % stop() call time_bank_sendrecv % start() -#ifdef MPI +#ifdef OPENMC_MPI ! ========================================================================== ! SEND BANK SITES TO NEIGHBORS @@ -343,14 +343,14 @@ contains subroutine calculate_generation_keff() real(8) :: keff_reduced -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif ! Get keff for this generation by subtracting off the starting value keff_generation = global_tallies(RESULT_VALUE, K_TRACKLENGTH) - keff_generation -#ifdef MPI +#ifdef OPENMC_MPI ! Combine values across all processors call MPI_ALLREDUCE(keff_generation, keff_reduced, 1, MPI_REAL8, & MPI_SUM, mpi_intracomm, mpi_err) @@ -584,7 +584,7 @@ contains real(8) :: total ! total weight in source bank logical :: sites_outside ! were there sites outside the ufs mesh? -#ifdef MPI +#ifdef OPENMC_MPI integer :: n ! total number of ufs mesh cells integer :: mpi_err ! MPI error code #endif @@ -608,7 +608,7 @@ contains call fatal_error("Source sites outside of the UFS mesh!") end if -#ifdef MPI +#ifdef OPENMC_MPI ! Send source fraction to all processors n = product(m % dimension) call MPI_BCAST(source_frac, n, MPI_REAL8, 0, mpi_intracomm, mpi_err) diff --git a/src/error.F90 b/src/error.F90 index 27004d729a..0a5af302d6 100644 --- a/src/error.F90 +++ b/src/error.F90 @@ -128,7 +128,7 @@ contains integer :: line_wrap ! length of line integer :: length ! length of message integer :: indent ! length of indentation -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err #endif @@ -180,7 +180,7 @@ contains end if end do -#ifdef MPI +#ifdef OPENMC_MPI ! Abort MPI call MPI_ABORT(mpi_intracomm, code, mpi_err) #endif @@ -194,6 +194,14 @@ contains end subroutine fatal_error + subroutine fatal_error_from_c(message, message_len) bind(C) + integer(C_INT), intent(in), value :: message_len + character(kind=C_CHAR), intent(in) :: message(message_len) + character(message_len+1) :: message_out + write(message_out, *) message + call fatal_error(message_out) + end subroutine + !=============================================================================== ! WRITE_MESSAGE displays an informational message to the log file and the ! standard output stream. diff --git a/src/error.h b/src/error.h new file mode 100644 index 0000000000..4c3373b3e3 --- /dev/null +++ b/src/error.h @@ -0,0 +1,34 @@ +#ifndef ERROR_H +#define ERROR_H + +#include +#include +#include + + +namespace openmc { + + +extern "C" void fatal_error_from_c(const char *message, int message_len); + + +void fatal_error(const char *message) +{ + fatal_error_from_c(message, strlen(message)); +} + + +void fatal_error(const std::string &message) +{ + fatal_error_from_c(message.c_str(), message.length()); +} + + +void fatal_error(const std::stringstream &message) +{ + std::string out {message.str()}; + fatal_error_from_c(out.c_str(), out.length()); +} + +} // namespace openmc +#endif // ERROR_H diff --git a/src/geometry.F90 b/src/geometry.F90 index ced62e6813..0bacd7b5d1 100644 --- a/src/geometry.F90 +++ b/src/geometry.F90 @@ -10,6 +10,8 @@ module geometry use stl_vector, only: VectorInt use string, only: to_str + use, intrinsic :: ISO_C_BINDING + implicit none contains @@ -63,7 +65,7 @@ contains in_cell = .false. exit else - actual_sense = surfaces(abs(token))%obj%sense(& + actual_sense = surfaces(abs(token)) % sense( & p%coord(p%n_coord)%xyz, p%coord(p%n_coord)%uvw) if (actual_sense .neqv. (token > 0)) then in_cell = .false. @@ -112,7 +114,7 @@ contains elseif (-token == p%surface) then stack(i_stack) = .false. else - actual_sense = surfaces(abs(token))%obj%sense(& + actual_sense = surfaces(abs(token)) % sense( & p%coord(p%n_coord)%xyz, p%coord(p%n_coord)%uvw) stack(i_stack) = (actual_sense .eqv. (token > 0)) end if @@ -480,9 +482,9 @@ contains real(8) :: d_surf ! distance to surface real(8) :: x0,y0,z0 ! coefficients for surface real(8) :: xyz_cross(3) ! coordinates at projected surface crossing + real(8) :: surf_uvw(3) ! surface normal direction logical :: coincident ! is particle on surface? type(Cell), pointer :: c - class(Surface), pointer :: surf class(Lattice), pointer :: lat ! inialize distance to infinity (huge) @@ -517,8 +519,8 @@ contains if (index_surf >= OP_UNION) cycle ! Calculate distance to surface - surf => surfaces(index_surf) % obj - d = surf % distance(p % coord(j) % xyz, p % coord(j) % uvw, coincident) + d = surfaces(index_surf) % distance(p % coord(j) % xyz, & + p % coord(j) % uvw, logical(coincident, kind=C_BOOL)) ! Check if calculated distance is new minimum if (d < d_surf) then @@ -737,9 +739,8 @@ contains ! traveling into if the surface is crossed if (.not. c % simple) then xyz_cross(:) = p % coord(j) % xyz + d_surf*p % coord(j) % uvw - surf => surfaces(abs(level_surf_cross)) % obj - if (dot_product(p % coord(j) % uvw, & - surf % normal(xyz_cross)) > ZERO) then + call surfaces(abs(level_surf_cross)) % normal(xyz_cross, surf_uvw) + if (dot_product(p % coord(j) % uvw, surf_uvw) > ZERO) then surface_crossed = abs(level_surf_cross) else surface_crossed = -abs(level_surf_cross) @@ -804,15 +805,15 @@ contains ! Copy positive neighbors to Surface instance n = neighbor_pos(i)%size() if (n > 0) then - allocate(surfaces(i)%obj%neighbor_pos(n)) - surfaces(i)%obj%neighbor_pos(:) = neighbor_pos(i)%data(1:n) + allocate(surfaces(i)%neighbor_pos(n)) + surfaces(i)%neighbor_pos(:) = neighbor_pos(i)%data(1:n) end if ! Copy negative neighbors to Surface instance n = neighbor_neg(i)%size() if (n > 0) then - allocate(surfaces(i)%obj%neighbor_neg(n)) - surfaces(i)%obj%neighbor_neg(:) = neighbor_neg(i)%data(1:n) + allocate(surfaces(i)%neighbor_neg(n)) + surfaces(i)%neighbor_neg(:) = neighbor_neg(i)%data(1:n) end if end do diff --git a/src/hdf5_interface.F90 b/src/hdf5_interface.F90 index e8c39b923c..410149d9e7 100644 --- a/src/hdf5_interface.F90 +++ b/src/hdf5_interface.F90 @@ -124,7 +124,7 @@ contains ! Setup file access property list with parallel I/O access call h5pcreate_f(H5P_FILE_ACCESS_F, plist, hdf5_err) #ifdef PHDF5 -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 call h5pset_fapl_mpio_f(plist, mpi_intracomm%MPI_VAL, & MPI_INFO_NULL%MPI_VAL, hdf5_err) #else @@ -174,7 +174,7 @@ contains ! Setup file access property list with parallel I/O access call h5pcreate_f(H5P_FILE_ACCESS_F, plist, hdf5_err) #ifdef PHDF5 -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 call h5pset_fapl_mpio_f(plist, mpi_intracomm%MPI_VAL, & MPI_INFO_NULL%MPI_VAL, hdf5_err) #else diff --git a/src/hdf5_interface.h b/src/hdf5_interface.h new file mode 100644 index 0000000000..7ec9ada9b6 --- /dev/null +++ b/src/hdf5_interface.h @@ -0,0 +1,91 @@ +#ifndef HDF5_INTERFACE_H +#define HDF5_INTERFACE_H + +#include +#include + +#include "hdf5.h" + +#include "error.h" + + +namespace openmc { + + +hid_t +create_group(hid_t parent_id, char const *name) +{ + hid_t out = H5Gcreate(parent_id, name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); + if (out < 0) { + std::string err_msg{"Failed to create HDF5 group \""}; + err_msg += name; + err_msg += "\""; + fatal_error(err_msg); + } + return out; +} + + +hid_t +create_group(hid_t parent_id, const std::string &name) +{ + return create_group(parent_id, name.c_str()); +} + + +void +close_group(hid_t group_id) +{ + herr_t err = H5Gclose(group_id); + if (err < 0) { + fatal_error("Failed to close HDF5 group"); + } +} + + +template void +write_double_1D(hid_t group_id, char const *name, + std::array &buffer) +{ + hsize_t dims[1]{array_len}; + hid_t dataspace = H5Screate_simple(1, dims, NULL); + + hid_t dataset = H5Dcreate(group_id, name, H5T_NATIVE_DOUBLE, dataspace, + H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); + + H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, + &buffer[0]); + + H5Sclose(dataspace); + H5Dclose(dataset); +} + + +void +write_string(hid_t group_id, char const *name, char const *buffer) +{ + size_t buffer_len = strlen(buffer); + hid_t datatype = H5Tcopy(H5T_C_S1); + H5Tset_size(datatype, buffer_len); + + hid_t dataspace = H5Screate(H5S_SCALAR); + + hid_t dataset = H5Dcreate(group_id, name, datatype, dataspace, + H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); + + H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); + + H5Tclose(datatype); + H5Sclose(dataspace); + H5Dclose(dataset); +} + + +void +write_string(hid_t group_id, char const *name, const std::string &buffer) +{ + write_string(group_id, name, buffer.c_str()); +} + +} // namespace openmc +#endif //HDF5_INTERFACE_H diff --git a/src/initialize.F90 b/src/initialize.F90 index dd7894f96b..7b699b9cb7 100644 --- a/src/initialize.F90 +++ b/src/initialize.F90 @@ -44,7 +44,6 @@ contains subroutine openmc_init(intracomm) bind(C) integer, intent(in), optional :: intracomm ! MPI intracommunicator - integer :: err #ifdef _OPENMP character(MAX_WORD_LEN) :: envvar #endif @@ -52,8 +51,8 @@ contains ! Copy the communicator to a new variable. This is done to avoid changing ! the signature of this subroutine. If MPI is being used but no communicator ! was passed, assume MPI_COMM_WORLD. -#ifdef MPI -#ifdef MPIF08 +#ifdef OPENMC_MPI +#ifdef OPENMC_MPIF08 type(MPI_Comm), intent(in) :: comm ! MPI intracommunicator if (present(intracomm)) then comm % MPI_VAL = intracomm @@ -74,7 +73,7 @@ contains call time_total%start() call time_initialize%start() -#ifdef MPI +#ifdef OPENMC_MPI ! Setup MPI call initialize_mpi(comm) #endif @@ -95,7 +94,7 @@ contains ! Initialize random number generator -- if the user specifies a seed, it ! will be re-initialized later - err = openmc_set_seed(DEFAULT_SEED) + call openmc_set_seed(DEFAULT_SEED) ! Read XML input files call read_input_xml() @@ -108,7 +107,7 @@ contains end subroutine openmc_init -#ifdef MPI +#ifdef OPENMC_MPI !=============================================================================== ! INITIALIZE_MPI starts up the Message Passing Interface (MPI) and determines ! the number of processors the problem is being run with as well as the rank of @@ -116,7 +115,7 @@ contains !=============================================================================== subroutine initialize_mpi(intracomm) -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 type(MPI_Comm), intent(in) :: intracomm ! MPI intracommunicator #else integer, intent(in) :: intracomm ! MPI intracommunicator @@ -124,7 +123,7 @@ contains integer :: mpi_err ! MPI error code integer :: bank_blocks(5) ! Count for each datatype -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 type(MPI_Datatype) :: bank_types(5) #else integer :: bank_types(5) ! Datatypes diff --git a/src/input_xml.F90 b/src/input_xml.F90 index bd56422cb5..a29bb08e83 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -10,7 +10,7 @@ module input_xml use distribution_multivariate use distribution_univariate use endf, only: reaction_name - use error, only: fatal_error, warning, write_message + use error, only: fatal_error, warning, write_message, openmc_err_msg use geometry, only: calc_offsets, maximum_levels, count_instance, & neighbor_lists use geometry_header @@ -21,7 +21,6 @@ module input_xml use message_passing use mgxs_data, only: create_macro_xs, read_mgxs use mgxs_header - use multipole, only: multipole_read use nuclide_header use output, only: title, header, print_plot use plot_header @@ -48,6 +47,14 @@ module input_xml implicit none save + interface + subroutine read_surfaces(node_ptr) bind(C, name='read_surfaces') + use ISO_C_BINDING + implicit none + type(C_PTR) :: node_ptr + end subroutine read_surfaces + end interface + contains !=============================================================================== @@ -341,7 +348,7 @@ contains ! Copy random number seed if specified if (check_for_node(root, "seed")) then call get_node_value(root, "seed", seed) - err = openmc_set_seed(seed) + call openmc_set_seed(seed) end if ! Number of bins for logarithmic grid @@ -911,28 +918,20 @@ contains integer :: id integer :: univ_id integer :: n_cells_in_univ - integer :: coeffs_reqd - integer :: i_xmin, i_xmax, i_ymin, i_ymax, i_zmin, i_zmax - real(8) :: xmin, xmax, ymin, ymax, zmin, zmax integer, allocatable :: temp_int_array(:) real(8) :: phi, theta, psi - real(8), allocatable :: coeffs(:) logical :: file_exists logical :: boundary_exists character(MAX_LINE_LEN) :: filename - character(MAX_WORD_LEN) :: word character(MAX_WORD_LEN), allocatable :: sarray(:) character(:), allocatable :: region_spec type(Cell), pointer :: c - class(Surface), pointer :: s class(Lattice), pointer :: lat type(XMLDocument) :: doc type(XMLNode) :: root type(XMLNode) :: node_cell - type(XMLNode) :: node_surf type(XMLNode) :: node_lat type(XMLNode), allocatable :: node_cell_list(:) - type(XMLNode), allocatable :: node_surf_list(:) type(XMLNode), allocatable :: node_rlat_list(:) type(XMLNode), allocatable :: node_hlat_list(:) type(VectorInt) :: tokens @@ -964,218 +963,18 @@ contains ! applied to a surface boundary_exists = .false. - ! get pointer to list of xml - call get_node_list(root, "surface", node_surf_list) + call read_surfaces(root % ptr) - ! Get number of tags - n_surfaces = size(node_surf_list) - - ! Check for no surfaces - if (n_surfaces == 0) then - call fatal_error("No surfaces found in geometry.xml!") - end if - - xmin = INFINITY - xmax = -INFINITY - ymin = INFINITY - ymax = -INFINITY - zmin = INFINITY - zmax = -INFINITY - - ! Allocate cells array + ! Allocate surfaces array allocate(surfaces(n_surfaces)) do i = 1, n_surfaces - ! Get pointer to i-th surface node - node_surf = node_surf_list(i) + surfaces(i) % ptr = surface_pointer_c(i - 1); - ! Copy and interpret surface type - word = '' - if (check_for_node(node_surf, "type")) & - call get_node_value(node_surf, "type", word) - select case(to_lower(word)) - case ('x-plane') - coeffs_reqd = 1 - allocate(SurfaceXPlane :: surfaces(i)%obj) - case ('y-plane') - coeffs_reqd = 1 - allocate(SurfaceYPlane :: surfaces(i)%obj) - case ('z-plane') - coeffs_reqd = 1 - allocate(SurfaceZPlane :: surfaces(i)%obj) - case ('plane') - coeffs_reqd = 4 - allocate(SurfacePlane :: surfaces(i)%obj) - case ('x-cylinder') - coeffs_reqd = 3 - allocate(SurfaceXCylinder :: surfaces(i)%obj) - case ('y-cylinder') - coeffs_reqd = 3 - allocate(SurfaceYCylinder :: surfaces(i)%obj) - case ('z-cylinder') - coeffs_reqd = 3 - allocate(SurfaceZCylinder :: surfaces(i)%obj) - case ('sphere') - coeffs_reqd = 4 - allocate(SurfaceSphere :: surfaces(i)%obj) - case ('x-cone') - coeffs_reqd = 4 - allocate(SurfaceXCone :: surfaces(i)%obj) - case ('y-cone') - coeffs_reqd = 4 - allocate(SurfaceYCone :: surfaces(i)%obj) - case ('z-cone') - coeffs_reqd = 4 - allocate(SurfaceZCone :: surfaces(i)%obj) - case ('quadric') - coeffs_reqd = 10 - allocate(SurfaceQuadric :: surfaces(i)%obj) - case default - call fatal_error("Invalid surface type: " // trim(word)) - end select + if (surfaces(i) % bc() /= BC_TRANSMIT) boundary_exists = .true. - s => surfaces(i)%obj - - ! Copy data into cells - if (check_for_node(node_surf, "id")) then - call get_node_value(node_surf, "id", s%id) - else - call fatal_error("Must specify id of surface in geometry XML file.") - end if - - ! Check to make sure 'id' hasn't been used - if (surface_dict % has(s%id)) then - call fatal_error("Two or more surfaces use the same unique ID: " & - // to_str(s%id)) - end if - - ! Copy surface name - if (check_for_node(node_surf, "name")) then - call get_node_value(node_surf, "name", s%name) - end if - - ! Check to make sure that the proper number of coefficients - ! have been specified for the given type of surface. Then copy - ! surface coordinates. - - n = node_word_count(node_surf, "coeffs") - if (n < coeffs_reqd) then - call fatal_error("Not enough coefficients specified for surface: " & - // trim(to_str(s%id))) - elseif (n > coeffs_reqd) then - call fatal_error("Too many coefficients specified for surface: " & - // trim(to_str(s%id))) - end if - - allocate(coeffs(n)) - call get_node_array(node_surf, "coeffs", coeffs) - - select type(s) - type is (SurfaceXPlane) - s%x0 = coeffs(1) - - ! Determine outer surfaces - xmin = min(xmin, s % x0) - xmax = max(xmax, s % x0) - if (xmin == s % x0) i_xmin = i - if (xmax == s % x0) i_xmax = i - type is (SurfaceYPlane) - s%y0 = coeffs(1) - - ! Determine outer surfaces - ymin = min(ymin, s % y0) - ymax = max(ymax, s % y0) - if (ymin == s % y0) i_ymin = i - if (ymax == s % y0) i_ymax = i - type is (SurfaceZPlane) - s%z0 = coeffs(1) - - ! Determine outer surfaces - zmin = min(zmin, s % z0) - zmax = max(zmax, s % z0) - if (zmin == s % z0) i_zmin = i - if (zmax == s % z0) i_zmax = i - type is (SurfacePlane) - s%A = coeffs(1) - s%B = coeffs(2) - s%C = coeffs(3) - s%D = coeffs(4) - type is (SurfaceXCylinder) - s%y0 = coeffs(1) - s%z0 = coeffs(2) - s%r = coeffs(3) - type is (SurfaceYCylinder) - s%x0 = coeffs(1) - s%z0 = coeffs(2) - s%r = coeffs(3) - type is (SurfaceZCylinder) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%r = coeffs(3) - type is (SurfaceSphere) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%z0 = coeffs(3) - s%r = coeffs(4) - type is (SurfaceXCone) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%z0 = coeffs(3) - s%r2 = coeffs(4) - type is (SurfaceYCone) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%z0 = coeffs(3) - s%r2 = coeffs(4) - type is (SurfaceZCone) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%z0 = coeffs(3) - s%r2 = coeffs(4) - type is (SurfaceQuadric) - s%A = coeffs(1) - s%B = coeffs(2) - s%C = coeffs(3) - s%D = coeffs(4) - s%E = coeffs(5) - s%F = coeffs(6) - s%G = coeffs(7) - s%H = coeffs(8) - s%J = coeffs(9) - s%K = coeffs(10) - end select - - ! No longer need coefficients - deallocate(coeffs) - - ! Boundary conditions - word = '' - if (check_for_node(node_surf, "boundary")) & - call get_node_value(node_surf, "boundary", word) - select case (to_lower(word)) - case ('transmission', 'transmit', '') - s%bc = BC_TRANSMIT - case ('vacuum') - s%bc = BC_VACUUM - boundary_exists = .true. - case ('reflective', 'reflect', 'reflecting') - s%bc = BC_REFLECT - boundary_exists = .true. - case ('periodic') - s%bc = BC_PERIODIC - boundary_exists = .true. - - ! Check for specification of periodic surface - if (check_for_node(node_surf, "periodic_surface_id")) then - call get_node_value(node_surf, "periodic_surface_id", & - s % i_periodic) - end if - case default - call fatal_error("Unknown boundary condition '" // trim(word) // & - &"' specified on surface " // trim(to_str(s%id))) - end select ! Add surface to dictionary - call surface_dict % set(s%id, i) + call surface_dict % set(surfaces(i) % id(), i) end do ! Check to make sure a boundary condition was applied to at least one @@ -1186,76 +985,6 @@ contains end if end if - ! Determine opposite side for periodic boundaries - do i = 1, size(surfaces) - if (surfaces(i) % obj % bc == BC_PERIODIC) then - select type (surf => surfaces(i) % obj) - type is (SurfaceXPlane) - if (surf % i_periodic == NONE) then - if (i == i_xmin) then - surf % i_periodic = i_xmax - elseif (i == i_xmax) then - surf % i_periodic = i_xmin - else - call fatal_error("Periodic boundary condition applied to & - &interior surface.") - end if - else - surf % i_periodic = surface_dict % get(surf % i_periodic) - end if - - type is (SurfaceYPlane) - if (surf % i_periodic == NONE) then - if (i == i_ymin) then - surf % i_periodic = i_ymax - elseif (i == i_ymax) then - surf % i_periodic = i_ymin - else - call fatal_error("Periodic boundary condition applied to & - &interior surface.") - end if - else - surf % i_periodic = surface_dict % get(surf % i_periodic) - end if - - type is (SurfaceZPlane) - if (surf % i_periodic == NONE) then - if (i == i_zmin) then - surf % i_periodic = i_zmax - elseif (i == i_zmax) then - surf % i_periodic = i_zmin - else - call fatal_error("Periodic boundary condition applied to & - &interior surface.") - end if - else - surf % i_periodic = surface_dict % get(surf % i_periodic) - end if - - type is (SurfacePlane) - if (surf % i_periodic == NONE) then - call fatal_error("No matching periodic surface specified for & - &periodic boundary condition on surface " // & - trim(to_str(surf % id)) // ".") - else - surf % i_periodic = surface_dict % get(surf % i_periodic) - end if - - class default - call fatal_error("Periodic boundary condition applied to & - &non-planar surface.") - end select - - ! Make sure opposite surface is also periodic - associate (surf => surfaces(i) % obj) - if (surfaces(surf % i_periodic) % obj % bc /= BC_PERIODIC) then - call fatal_error("Could not find matching surface for periodic & - &boundary on surface " // trim(to_str(surf % id)) // ".") - end if - end associate - end if - end do - ! ========================================================================== ! READ CELLS FROM GEOMETRY.XML @@ -2468,7 +2197,6 @@ contains integer :: l ! another loop index integer :: filter_id ! user-specified identifier for filter integer :: i_filt ! index in filters array - integer :: i_filter_mesh ! index of mesh filter integer :: i_elem ! index of entry in dictionary integer :: n ! size of arrays in mesh specification integer :: n_words ! number of words read @@ -2480,7 +2208,6 @@ contains integer :: trig_ind ! index of triggers array for each tally integer :: user_trig_ind ! index of user-specified triggers for each tally integer :: i_start, i_end - integer :: i_filt_start, i_filt_end integer(C_INT) :: err real(8) :: threshold ! trigger convergence threshold integer :: n_order ! moment order requested @@ -2629,13 +2356,13 @@ contains call get_node_value(node_filt, "type", temp_str) temp_str = to_lower(temp_str) - ! Determine number of bins + ! Make sure bins have been set select case(temp_str) case ("energy", "energyout", "mu", "polar", "azimuthal") if (.not. check_for_node(node_filt, "bins")) then call fatal_error("Bins not set in filter " // trim(to_str(filter_id))) end if - case ("mesh", "universe", "material", "cell", "distribcell", & + case ("mesh", "meshsurface", "universe", "material", "cell", "distribcell", & "cellborn", "cellfrom", "surface", "delayedgroup") if (.not. check_for_node(node_filt, "bins")) then call fatal_error("Bins not set in filter " // trim(to_str(filter_id))) @@ -2644,6 +2371,7 @@ contains ! Allocate according to the filter type err = openmc_filter_set_type(i_start + i - 1, to_c_string(temp_str)) + if (err /= 0) call fatal_error(to_f_string(openmc_err_msg)) ! Read filter data from XML call f % obj % from_xml(node_filt) @@ -3106,18 +2834,18 @@ contains &t % find_filter(FILTER_CELL) > 0 .or. & &t % find_filter(FILTER_CELLFROM) > 0) then - ! Check to make sure that mesh currents are not desired as well - if (t % find_filter(FILTER_MESH) > 0) then - call fatal_error("Cannot tally other mesh currents & - &in the same tally as surface currents") + ! Check to make sure that mesh surface currents are not desired as well + if (t % find_filter(FILTER_MESHSURFACE) > 0) then + call fatal_error("Cannot tally mesh surface currents & + &in the same tally as normal surface currents") end if t % type = TALLY_SURFACE t % score_bins(j) = SCORE_CURRENT - else if (t % find_filter(FILTER_MESH) > 0) then + else if (t % find_filter(FILTER_MESHSURFACE) > 0) then t % score_bins(j) = SCORE_CURRENT - t % type = TALLY_MESH_CURRENT + t % type = TALLY_MESH_SURFACE ! Check to make sure that current is the only desired response ! for this tally @@ -3125,75 +2853,6 @@ contains call fatal_error("Cannot tally other scores in the & &same tally as surface currents") end if - - ! Get index of mesh filter - i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) - - ! Check to make sure mesh filter was specified - if (i_filter_mesh == 0) then - call fatal_error("Cannot tally surface current without a mesh & - &filter.") - end if - - ! Get pointer to mesh - select type(filt => filters(i_filter_mesh) % obj) - type is (MeshFilter) - m => meshes(filt % mesh) - end select - - ! Extend the filters array so we can add a surface filter and - ! mesh filter - err = openmc_extend_filters(2, i_filt_start, i_filt_end) - - ! Duplicate the mesh filter since other tallies might use this - ! filter and we need to change the dimension - filters(i_filt_start) = filters(i_filter_mesh) - - ! We need to increase the dimension by one since we also need - ! currents coming into and out of the boundary mesh cells. - filters(i_filt_start) % obj % n_bins = product(m % dimension + 1) - - ! Set ID - call openmc_get_filter_next_id(filter_id) - err = openmc_filter_set_id(i_filt_start, filter_id) - - - ! Add surface filter - allocate(SurfaceFilter :: filters(i_filt_end) % obj) - select type (filt => filters(i_filt_end) % obj) - type is (SurfaceFilter) - filt % n_bins = 4 * m % n_dimension - allocate(filt % surfaces(4 * m % n_dimension)) - if (m % n_dimension == 1) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, OUT_RIGHT, IN_RIGHT /) - elseif (m % n_dimension == 2) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, OUT_RIGHT, IN_RIGHT, & - OUT_BACK, IN_BACK, OUT_FRONT, IN_FRONT /) - elseif (m % n_dimension == 3) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, OUT_RIGHT, IN_RIGHT, & - OUT_BACK, IN_BACK, OUT_FRONT, IN_FRONT, OUT_BOTTOM, & - IN_BOTTOM, OUT_TOP, IN_TOP /) - end if - filt % current = .true. - - ! Set ID - call openmc_get_filter_next_id(filter_id) - err = openmc_filter_set_id(i_filt_end, filter_id) - end select - - ! Copy filter indices to resized array - n_filter = size(t % filter) - allocate(temp_filter(n_filter + 1)) - temp_filter(1:size(t % filter)) = t % filter - n_filter = n_filter + 1 - - ! Set mesh and surface filters - temp_filter(t % find_filter(FILTER_MESH)) = i_filt_start - temp_filter(n_filter) = i_filt_end - - ! Set filters - err = openmc_tally_set_filters(i_start + i - 1, n_filter, temp_filter) - deallocate(temp_filter) end if case ('events') @@ -4461,7 +4120,7 @@ contains group_id = open_group(file_id, name) call nuclides(i_nuclide) % from_hdf5(group_id, nuc_temps(i_nuclide), & temperature_method, temperature_tolerance, temperature_range, & - master) + master, i_nuclide) call close_group(group_id) call file_close(file_id) @@ -4535,12 +4194,16 @@ contains ! Show which nuclide results in lowest energy for neutron transport do i = 1, size(nuclides) - if (nuclides(i) % grid(1) % energy(size(nuclides(i) % grid(1) % energy)) & - == energy_max_neutron) then - call write_message("Maximum neutron transport energy: " // & - trim(to_str(energy_max_neutron)) // " eV for " // & - trim(adjustl(nuclides(i) % name)), 7) - exit + ! If a nuclide is present in a material that's not used in the model, its + ! grid has not been allocated + if (size(nuclides(i) % grid) > 0) then + if (nuclides(i) % grid(1) % energy(size(nuclides(i) % grid(1) % energy)) & + == energy_max_neutron) then + call write_message("Maximum neutron transport energy: " // & + trim(to_str(energy_max_neutron)) // " eV for " // & + trim(adjustl(nuclides(i) % name)), 7) + exit + end if end if end do @@ -4643,7 +4306,7 @@ contains allocate(nuc % multipole) ! Call the read routine - call multipole_read(filename, nuc % multipole, i_table) + call nuc % multipole % from_hdf5(filename) nuc % mp_present = .true. end associate diff --git a/src/main.F90 b/src/main.F90 index d8e52643c1..120bdd1e0c 100644 --- a/src/main.F90 +++ b/src/main.F90 @@ -9,13 +9,13 @@ program main implicit none -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif ! Initialize run -- when run with MPI, pass communicator -#ifdef MPI -#ifdef MPIF08 +#ifdef OPENMC_MPI +#ifdef OPENMC_MPIF08 call openmc_init(MPI_COMM_WORLD % MPI_VAL) #else call openmc_init(MPI_COMM_WORLD) @@ -39,7 +39,7 @@ program main ! finalize run call openmc_finalize() -#ifdef MPI +#ifdef OPENMC_MPI ! If MPI is in use and enabled, terminate it call MPI_FINALIZE(mpi_err) #endif diff --git a/src/material_header.F90 b/src/material_header.F90 index a3ce32db3d..038e529bee 100644 --- a/src/material_header.F90 +++ b/src/material_header.F90 @@ -7,6 +7,7 @@ module material_header use error use nuclide_header use sab_header + use simulation_header, only: log_spacing use stl_vector, only: VectorReal, VectorInt use string, only: to_str @@ -64,6 +65,7 @@ module material_header procedure :: set_density => material_set_density procedure :: init_nuclide_index => material_init_nuclide_index procedure :: assign_sab_tables => material_assign_sab_tables + procedure :: calculate_xs => material_calculate_xs end type Material integer(C_INT32_T), public, bind(C) :: n_materials ! # of materials @@ -248,6 +250,115 @@ contains if (allocated(this % names)) deallocate(this % names) end subroutine material_assign_sab_tables +!=============================================================================== +! MATERIAL_CALCULATE_XS determines the macroscopic cross sections for the material the +! particle is currently traveling through. +!=============================================================================== + + subroutine material_calculate_xs(this, E, sqrtkT, micro_xs, nuclides, & + material_xs) + class(Material), intent(in) :: this + real(8), intent(in) :: E ! Particle energy + real(8), intent(in) :: sqrtkT ! Last temperature sampled + type(Nuclide), allocatable, intent(in) :: nuclides(:) + type(NuclideMicroXS), allocatable, intent(inout) :: micro_xs(:) ! Cache for each nuclide + type(MaterialMacroXS), intent(inout) :: material_xs ! Cache for current material + + integer :: i ! loop index over nuclides + integer :: i_nuclide ! index into nuclides array + integer :: i_sab ! index into sab_tables array + integer :: j ! index in this % i_sab_nuclides + integer :: i_grid ! index into logarithmic mapping array or material + ! union grid + real(8) :: atom_density ! atom density of a nuclide + real(8) :: sab_frac ! fraction of atoms affected by S(a,b) + logical :: check_sab ! should we check for S(a,b) table? + + ! Set all material macroscopic cross sections to zero + material_xs % total = ZERO + material_xs % absorption = ZERO + material_xs % fission = ZERO + material_xs % nu_fission = ZERO + + ! Find energy index on energy grid + i_grid = int(log(E/energy_min_neutron)/log_spacing) + + ! Determine if this material has S(a,b) tables + check_sab = (this % n_sab > 0) + + ! Initialize position in i_sab_nuclides + j = 1 + + ! Add contribution from each nuclide in material + do i = 1, this % n_nuclides + ! ====================================================================== + ! CHECK FOR S(A,B) TABLE + + i_sab = 0 + sab_frac = ZERO + + ! Check if this nuclide matches one of the S(a,b) tables specified. + ! This relies on i_sab_nuclides being in sorted order + if (check_sab) then + if (i == this % i_sab_nuclides(j)) then + ! Get index in sab_tables + i_sab = this % i_sab_tables(j) + sab_frac = this % sab_fracs(j) + + ! If particle energy is greater than the highest energy for the + ! S(a,b) table, then don't use the S(a,b) table + if (E > sab_tables(i_sab) % data(1) % threshold_inelastic) then + i_sab = 0 + end if + + ! Increment position in i_sab_nuclides + j = j + 1 + + ! Don't check for S(a,b) tables if there are no more left + if (j > size(this % i_sab_tables)) check_sab = .false. + end if + end if + + ! ====================================================================== + ! CALCULATE MICROSCOPIC CROSS SECTION + + ! Determine microscopic cross sections for this nuclide + i_nuclide = this % nuclide(i) + + ! Calculate microscopic cross section for this nuclide + if (E /= micro_xs(i_nuclide) % last_E & + .or. sqrtkT /= micro_xs(i_nuclide) % last_sqrtkT & + .or. i_sab /= micro_xs(i_nuclide) % index_sab & + .or. sab_frac /= micro_xs(i_nuclide) % sab_frac) then + call nuclides(i_nuclide) % calculate_xs(i_sab, E, i_grid, & + sqrtkT, sab_frac, micro_xs(i_nuclide)) + end if + + ! ====================================================================== + ! ADD TO MACROSCOPIC CROSS SECTION + + ! Copy atom density of nuclide in material + atom_density = this % atom_density(i) + + ! Add contributions to material macroscopic total cross section + material_xs % total = material_xs % total + & + atom_density * micro_xs(i_nuclide) % total + + ! Add contributions to material macroscopic absorption cross section + material_xs % absorption = material_xs % absorption + & + atom_density * micro_xs(i_nuclide) % absorption + + ! Add contributions to material macroscopic fission cross section + material_xs % fission = material_xs % fission + & + atom_density * micro_xs(i_nuclide) % fission + + ! Add contributions to material macroscopic nu-fission cross section + material_xs % nu_fission = material_xs % nu_fission + & + atom_density * micro_xs(i_nuclide) % nu_fission + end do + + end subroutine material_calculate_xs + !=============================================================================== ! FREE_MEMORY_MATERIAL deallocates global arrays defined in this module !=============================================================================== diff --git a/src/mesh.F90 b/src/mesh.F90 index e997890a4a..790dc7d889 100644 --- a/src/mesh.F90 +++ b/src/mesh.F90 @@ -34,7 +34,7 @@ contains integer :: n ! number of energy groups / size integer :: mesh_bin ! mesh bin integer :: e_bin ! energy bin -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif logical :: outside ! was any site outside mesh? @@ -86,7 +86,7 @@ contains cnt_(e_bin, mesh_bin) = cnt_(e_bin, mesh_bin) + bank_array(i) % wgt end do FISSION_SITES -#ifdef MPI +#ifdef OPENMC_MPI ! collect values from all processors n = size(cnt_) call MPI_REDUCE(cnt_, cnt, n, MPI_REAL8, MPI_SUM, 0, mpi_intracomm, mpi_err) diff --git a/src/message_passing.F90 b/src/message_passing.F90 index 0f2b94d1af..7391a632c7 100644 --- a/src/message_passing.F90 +++ b/src/message_passing.F90 @@ -1,7 +1,7 @@ module message_passing -#ifdef MPI -#ifdef MPIF08 +#ifdef OPENMC_MPI +#ifdef OPENMC_MPIF08 use mpi_f08 #else use mpi @@ -16,7 +16,7 @@ module message_passing integer :: rank = 0 ! rank of process logical :: master = .true. ! master process? logical :: mpi_enabled = .false. ! is MPI in use and initialized? -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 type(MPI_Datatype) :: MPI_BANK ! MPI datatype for fission bank type(MPI_Comm) :: mpi_intracomm ! MPI intra-communicator #else diff --git a/src/mgxs_header.F90 b/src/mgxs_header.F90 index a99939f4c3..6eabefae3c 100644 --- a/src/mgxs_header.F90 +++ b/src/mgxs_header.F90 @@ -163,10 +163,11 @@ module mgxs_header real(8), intent(inout) :: wgt ! Particle weight end subroutine mgxs_sample_scatter_ - subroutine mgxs_calculate_xs_(this, gin, uvw, xs) + subroutine mgxs_calculate_xs_(this, gin, sqrtkT, uvw, xs) import Mgxs, MaterialMacroXS - class(Mgxs), intent(in) :: this + class(Mgxs), intent(inout) :: this integer, intent(in) :: gin ! Incoming neutron group + real(8), intent(in) :: sqrtkT ! Material temperature real(8), intent(in) :: uvw(3) ! Incoming neutron direction type(MaterialMacroXS), intent(inout) :: xs ! Resultant Mgxs Data end subroutine mgxs_calculate_xs_ @@ -3481,12 +3482,16 @@ contains ! for the material the particle is currently traveling through. !=============================================================================== - subroutine mgxsiso_calculate_xs(this, gin, uvw, xs) - class(MgxsIso), intent(in) :: this + subroutine mgxsiso_calculate_xs(this, gin, sqrtkT, uvw, xs) + class(MgxsIso), intent(inout) :: this integer, intent(in) :: gin ! Incoming neutron group + real(8), intent(in) :: sqrtkT ! Material temperature real(8), intent(in) :: uvw(3) ! Incoming neutron direction type(MaterialMacroXS), intent(inout) :: xs ! Resultant Mgxs Data + ! Update the temperature index + call this % find_temperature(sqrtkT) + xs % total = this % xs(this % index_temp) % total(gin) xs % absorption = this % xs(this % index_temp) % absorption(gin) xs % nu_fission = & @@ -3495,15 +3500,19 @@ contains end subroutine mgxsiso_calculate_xs - subroutine mgxsang_calculate_xs(this, gin, uvw, xs) - class(MgxsAngle), intent(in) :: this + subroutine mgxsang_calculate_xs(this, gin, sqrtkT, uvw, xs) + class(MgxsAngle), intent(inout) :: this integer, intent(in) :: gin ! Incoming neutron group + real(8), intent(in) :: sqrtkT ! Material temperature real(8), intent(in) :: uvw(3) ! Incoming neutron direction type(MaterialMacroXS), intent(inout) :: xs ! Resultant Mgxs Data integer :: iazi, ipol + ! Update the temperature and angle indices + call this % find_temperature(sqrtkT) call find_angle(this % polar, this % azimuthal, uvw, iazi, ipol) + xs % total = this % xs(this % index_temp) % & total(gin, iazi, ipol) xs % absorption = this % xs(this % index_temp) % & diff --git a/src/multipole.F90 b/src/multipole.F90 deleted file mode 100644 index 0282adb7d9..0000000000 --- a/src/multipole.F90 +++ /dev/null @@ -1,89 +0,0 @@ -module multipole - - use hdf5 - - use constants - use error, only: fatal_error - use hdf5_interface - use multipole_header, only: MultipoleArray, FIT_T, FIT_A, FIT_F, & - MP_FISS, FORM_MLBW, FORM_RM - use nuclide_header, only: nuclides - - implicit none - -contains - -!=============================================================================== -! MULTIPOLE_READ Reads in a multipole HDF5 file with the original API -! specification. Subject to change as the library format matures. -!=============================================================================== - - subroutine multipole_read(filename, multipole, i_table) - character(len=*), intent(in) :: filename ! Filename of the - ! multipole library - ! to load - type(MultipoleArray), intent(out), target :: multipole ! The object to fill - integer, intent(in) :: i_table ! index in nuclides/ - ! sab_tables - - integer(HID_T) :: file_id - integer(HID_T) :: group_id - - ! Intermediate loading components - integer :: is_fissionable - character(len=10) :: version - - associate (nuc => nuclides(i_table)) - - ! Open file for reading and move into the /isotope group - file_id = file_open(filename, 'r', parallel=.true.) - group_id = open_group(file_id, "/nuclide") - - ! Check the file version number. - call read_dataset(version, file_id, "version") - if (version /= VERSION_MULTIPOLE) call fatal_error("The current multipole& - & format version is " // trim(VERSION_MULTIPOLE) // " but the file "& - // trim(filename) // " uses version " // trim(version) // ".") - - ! Load in all the array size scalars - call read_dataset(multipole % length, group_id, "length") - call read_dataset(multipole % windows, group_id, "windows") - call read_dataset(multipole % num_l, group_id, "num_l") - call read_dataset(multipole % fit_order, group_id, "fit_order") - call read_dataset(multipole % max_w, group_id, "max_w") - call read_dataset(is_fissionable, group_id, "fissionable") - if (is_fissionable == MP_FISS) then - multipole % fissionable = .true. - else - multipole % fissionable = .false. - end if - call read_dataset(multipole % formalism, group_id, "formalism") - - call read_dataset(multipole % spacing, group_id, "spacing") - call read_dataset(multipole % sqrtAWR, group_id, "sqrtAWR") - call read_dataset(multipole % start_E, group_id, "start_E") - call read_dataset(multipole % end_E, group_id, "end_E") - - ! Allocate the multipole array components - call multipole % allocate() - - ! Read in arrays - call read_dataset(multipole % data, group_id, "data") - call read_dataset(multipole % pseudo_k0RS, group_id, "pseudo_K0RS") - call read_dataset(multipole % l_value, group_id, "l_value") - call read_dataset(multipole % w_start, group_id, "w_start") - call read_dataset(multipole % w_end, group_id, "w_end") - call read_dataset(multipole % broaden_poly, group_id, "broaden_poly") - - call read_dataset(multipole % curvefit, group_id, "curvefit") - - call close_group(group_id) - - ! Close file - call file_close(file_id) - - end associate - - end subroutine multipole_read - -end module multipole diff --git a/src/multipole_header.F90 b/src/multipole_header.F90 index 143047b0b5..7fb438bce1 100644 --- a/src/multipole_header.F90 +++ b/src/multipole_header.F90 @@ -1,5 +1,12 @@ module multipole_header + use hdf5 + + use constants + use dict_header, only: DictIntInt + use error, only: fatal_error + use hdf5_interface + implicit none !======================================================================== @@ -29,9 +36,6 @@ module multipole_header FIT_A = 2, & ! Absorption FIT_F = 3 ! Fission - ! Value of 'true' when checking if nuclide is fissionable - integer, parameter :: MP_FISS = 1 - !=============================================================================== ! MULTIPOLE contains all the components needed for the windowed multipole ! temperature dependent cross section libraries for the resolved resonance @@ -42,87 +46,142 @@ module multipole_header !========================================================================= ! Isotope Properties - logical :: fissionable = .false. ! Is this isotope fissionable? - integer :: length ! Number of poles - integer, allocatable :: l_value(:) ! The l index of the pole - real(8), allocatable :: pseudo_k0RS(:) ! The value (sqrt(2*mass neutron)/reduced planck constant) - ! * AWR/(AWR + 1) * scattering radius for each l - complex(8), allocatable :: data(:,:) ! Contains all of the pole-residue data - real(8) :: sqrtAWR ! Square root of the atomic weight ratio + + logical :: fissionable ! Is this isotope fissionable? + integer, allocatable :: l_value(:) ! The l index of the pole + integer :: num_l ! Number of unique l values + real(8), allocatable :: pseudo_k0RS(:) ! The value (sqrt(2*mass neutron + ! /reduced planck constant) + ! * AWR/(AWR + 1) + ! * scattering radius for + ! each l + complex(8), allocatable :: data(:,:) ! Poles and residues + real(8) :: sqrtAWR ! Square root of the atomic + ! weight ratio + integer :: formalism ! R-matrix formalism !========================================================================= ! Windows - integer :: windows ! Number of windows - integer :: fit_order ! Order of the fit. 1 linear, 2 quadratic, etc. + integer :: fit_order ! Order of the fit. 1 linear, + ! 2 quadratic, etc. real(8) :: start_E ! Start energy for the windows real(8) :: end_E ! End energy for the windows - real(8) :: spacing ! The actual spacing in sqrt(E) space. - ! spacing = sqrt(multipole_w%endE - multipole_w%startE)/multipole_w%windows - integer, allocatable :: w_start(:) ! Contains the index of the pole at the start of the window - integer, allocatable :: w_end(:) ! Contains the index of the pole at the end of the window - real(8), allocatable :: curvefit(:,:,:) ! Contains the fitting function. (reaction type, coeff index, window index) + real(8) :: spacing ! The actual spacing in sqrt(E) + ! space. + ! spacing = sqrt(multipole_w % endE - multipole_w % startE) + ! / multipole_w % windows + integer, allocatable :: w_start(:) ! Contains the index of the pole at + ! the start of the window + integer, allocatable :: w_end(:) ! Contains the index of the pole at + ! the end of the window + real(8), allocatable :: curvefit(:,:,:) ! Contains the fitting function. + ! (reaction type, coeff index, + ! window index) integer, allocatable :: broaden_poly(:) ! if 1, broaden, if 0, don't. - !========================================================================= - ! Storage Helpers - integer :: num_l - integer :: max_w + contains - integer :: formalism + procedure :: from_hdf5 => multipole_from_hdf5 - contains - procedure :: allocate => multipole_allocate ! Allocates Multipole end type MultipoleArray contains !=============================================================================== -! MULTIPOLE_ALLOCATE allocates necessary data for Multipole. +! FROM_HDF5 loads multipole data from an HDF5 file. !=============================================================================== - subroutine multipole_allocate(multipole) - class(MultipoleArray), intent(inout) :: multipole ! Multipole object to allocate. + subroutine multipole_from_hdf5(this, filename) + class(MultipoleArray), intent(inout) :: this + character(len=*), intent(in) :: filename - ! This function assumes length, numL, fissionable, windows, fitorder, - ! and formalism are known + character(len=10) :: version + integer :: i, n_poles, n_residue_types, n_windows + integer(HSIZE_T) :: dims_1d(1), dims_2d(2), dims_3d(3) + integer(HID_T) :: file_id + integer(HID_T) :: group_id + integer(HID_T) :: dset + type(DictIntInt) :: l_val_dict - ! Allocate the pole-residue storage. - ! MLBW has one more pole than Reich-Moore, and fissionable nuclides - ! have further one more. - if (multipole % formalism == FORM_MLBW) then - if (multipole % fissionable) then - allocate(multipole % data(5, multipole % length)) - else - allocate(multipole % data(4, multipole % length)) - end if - else if (multipole % formalism == FORM_RM) then - if (multipole % fissionable) then - allocate(multipole % data(4, multipole % length)) - else - allocate(multipole % data(3, multipole % length)) - end if + ! Open file for reading and move into the /isotope group + file_id = file_open(filename, 'r', parallel=.true.) + group_id = open_group(file_id, "/nuclide") + + ! Check the file version number. + call read_dataset(version, file_id, "version") + if (version /= VERSION_MULTIPOLE) call fatal_error("The current multipole& + & format version is " // trim(VERSION_MULTIPOLE) // " but the file "& + // trim(filename) // " uses version " // trim(version) // ".") + + ! Read scalar values. + call read_dataset(this % formalism, group_id, "formalism") + call read_dataset(this % spacing, group_id, "spacing") + call read_dataset(this % sqrtAWR, group_id, "sqrtAWR") + call read_dataset(this % start_E, group_id, "start_E") + call read_dataset(this % end_E, group_id, "end_E") + + ! Read the "data" array. Use its shape to figure out the number of poles + ! and residue types in this data. + dset = open_dataset(group_id, "data") + call get_shape(dset, dims_2d) + n_residue_types = int(dims_2d(1), 4) - 1 + n_poles = int(dims_2d(2), 4) + allocate(this % data(n_residue_types+1, n_poles)) + call read_dataset(this % data, dset) + call close_dataset(dset) + + ! Check to see if this data includes fission residues. + if (this % formalism == FORM_RM) then + this % fissionable = (n_residue_types == 3) + else + ! Assume FORM_MLBW. + this % fissionable = (n_residue_types == 4) + end if + + ! Read the "l_value" array. + allocate(this % l_value(n_poles)) + call read_dataset(this % l_value, group_id, "l_value") + + ! Figure out the number of unique l values in the l_value array. + do i = 1, n_poles + if (.not. l_val_dict % has(this % l_value(i))) then + call l_val_dict % set(this % l_value(i), 0) end if + end do + this % num_l = l_val_dict % size() + call l_val_dict % clear() - ! Allocate the l value table for each pole-residue set. - allocate(multipole % l_value(multipole % length)) + ! Read the "pseudo_K0RS" array. + allocate(this % pseudo_k0RS(this % num_l)) + call read_dataset(this % pseudo_k0RS, group_id, "pseudo_K0RS") - ! Allocate the table of pseudo_k0RS values at each l. - allocate(multipole % pseudo_k0RS(multipole % num_l)) + ! Read the "w_start" array and use its shape to figure out the number of + ! windows. + dset = open_dataset(group_id, "w_start") + call get_shape(dset, dims_1d) + n_windows = int(dims_1d(1), 4) + allocate(this % w_start(n_windows)) + call read_dataset(this % w_start, dset) + call close_dataset(dset) - ! Allocate window start, window end - allocate(multipole % w_start(multipole % windows)) - allocate(multipole % w_end(multipole % windows)) + ! Read the "w_end" and "broaden_poly" arrays. + allocate(this % w_end(n_windows)) + call read_dataset(this % w_end, group_id, "w_end") + allocate(this % broaden_poly(n_windows)) + call read_dataset(this % broaden_poly, group_id, "broaden_poly") - ! Allocate broaden_poly - allocate(multipole % broaden_poly(multipole % windows)) + ! Read the "curvefit" array. + dset = open_dataset(group_id, "curvefit") + call get_shape(dset, dims_3d) + allocate(this % curvefit(dims_3d(1), dims_3d(2), dims_3d(3))) + call read_dataset(this % curvefit, dset) + call close_dataset(dset) + this % fit_order = int(dims_3d(2), 4) - 1 - ! Allocate curvefit - if(multipole % fissionable) then - allocate(multipole % curvefit(FIT_F, multipole % fit_order+1, multipole % windows)) - else - allocate(multipole % curvefit(FIT_A, multipole % fit_order+1, multipole % windows)) - end if - end subroutine + ! Close the group and file. + call close_group(group_id) + call file_close(file_id) + end subroutine multipole_from_hdf5 end module multipole_header diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index 38e89b6483..8362f5d41e 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -3,26 +3,33 @@ module nuclide_header use, intrinsic :: ISO_FORTRAN_ENV use, intrinsic :: ISO_C_BINDING - use hdf5, only: HID_T, HSIZE_T, SIZE_T + use hdf5, only: HID_T, HSIZE_T, SIZE_T - use algorithm, only: sort, find + use algorithm, only: sort, find, binary_search use constants - use dict_header, only: DictIntInt, DictCharInt - use endf, only: reaction_name, is_fission, is_disappearance - use endf_header, only: Function1D, Polynomial, Tabulated1D + use dict_header, only: DictIntInt, DictCharInt + use endf, only: reaction_name, is_fission, is_disappearance + use endf_header, only: Function1D, Polynomial, Tabulated1D use error use hdf5_interface - use list_header, only: ListInt - use math, only: evaluate_legendre + use list_header, only: ListInt + use math, only: faddeeva, w_derivative, & + broaden_wmp_polynomials + use multipole_header, only: FORM_RM, FORM_MLBW, MP_EA, RM_RT, RM_RA, & + RM_RF, MLBW_RT, MLBW_RX, MLBW_RA, MLBW_RF, & + FIT_T, FIT_A, FIT_F, MultipoleArray use message_passing - use multipole_header, only: MultipoleArray - use product_header, only: AngleEnergyContainer - use reaction_header, only: Reaction + use multipole_header, only: MultipoleArray + use product_header, only: AngleEnergyContainer + use random_lcg, only: prn, future_prn, prn_set_stream + use reaction_header, only: Reaction + use sab_header, only: SAlphaBeta, sab_tables use secondary_uncorrelated, only: UncorrelatedAngleEnergy use settings - use stl_vector, only: VectorInt, VectorReal + use stl_vector, only: VectorInt, VectorReal use string - use urr_header, only: UrrData + use simulation_header, only: need_depletion_rx + use urr_header, only: UrrData implicit none @@ -36,13 +43,18 @@ module nuclide_header real(8), allocatable :: energy(:) ! energy values corresponding to xs end type EnergyGrid + ! Positions for first dimension of Nuclide % xs + integer, parameter :: & + XS_TOTAL = 1, & + XS_ABSORPTION = 2, & + XS_FISSION = 3, & + XS_NU_FISSION = 4 + + ! The array within SumXS is of shape (4, n_energy) where the first dimension + ! corresponds to the following values: 1) total, 2) absorption (MT > 100), 3) + ! fission, 4) neutron production type SumXS - real(8), allocatable :: total(:) ! total cross section - real(8), allocatable :: elastic(:) ! elastic scattering - real(8), allocatable :: fission(:) ! fission - real(8), allocatable :: nu_fission(:) ! neutron production - real(8), allocatable :: absorption(:) ! absorption (MT > 100) - real(8), allocatable :: heating(:) ! heating + real(8), allocatable :: value(:,:) end type SumXS type :: Nuclide @@ -52,6 +64,7 @@ module nuclide_header integer :: A ! mass number integer :: metastable ! metastable state real(8) :: awr ! Atomic Weight Ratio + integer :: i_nuclide ! The nuclides index in the nuclides array real(8), allocatable :: kTs(:) ! temperature in eV (k*T) ! Fission information @@ -61,7 +74,7 @@ module nuclide_header type(EnergyGrid), allocatable :: grid(:) ! Microscopic cross sections - type(SumXS), allocatable :: sum_xs(:) + type(SumXS), allocatable :: xs(:) ! Resonance scattering info logical :: resonant = .false. ! resonant scatterer? @@ -87,6 +100,7 @@ module nuclide_header ! Reactions type(Reaction), allocatable :: reactions(:) + integer, allocatable :: index_inelastic_scatter(:) ! Array that maps MT values to index in reactions; used at tally-time. Note ! that ENDF-102 does not assign any MT values above 891. @@ -103,6 +117,8 @@ module nuclide_header procedure :: init_grid => nuclide_init_grid procedure :: nu => nuclide_nu procedure, private :: create_derived => nuclide_create_derived + procedure :: calculate_xs => nuclide_calculate_xs + procedure :: calculate_elastic_xs => nuclide_calculate_elastic_xs end type Nuclide !=============================================================================== @@ -110,14 +126,19 @@ module nuclide_header ! nuclide at the current energy !=============================================================================== + ! Arbitrary value to indicate invalid cache state for elastic scattering + ! (NuclideMicroXS % elastic) + real(8), parameter :: CACHE_INVALID = dble(Z"FFE0000000000000") + type NuclideMicroXS ! Microscopic cross sections in barns real(8) :: total - real(8) :: elastic ! If sab_frac is not 1 or 0, then this value is - ! averaged over bound and non-bound nuclei real(8) :: absorption ! absorption (disappearance) real(8) :: fission ! fission real(8) :: nu_fission ! neutron production from fission + + real(8) :: elastic ! If sab_frac is not 1 or 0, then this value is + ! averaged over bound and non-bound nuclei real(8) :: thermal ! Bound thermal elastic & inelastic scattering real(8) :: thermal_elastic ! Bound thermal elastic scattering @@ -148,7 +169,6 @@ module nuclide_header type MaterialMacroXS real(8) :: total ! macroscopic total xs - real(8) :: elastic ! macroscopic elastic scattering xs real(8) :: absorption ! macroscopic absorption xs real(8) :: fission ! macroscopic fission xs real(8) :: nu_fission ! macroscopic production xs @@ -250,7 +270,7 @@ contains end subroutine nuclide_clear subroutine nuclide_from_hdf5(this, group_id, temperature, method, tolerance, & - minmax, master) + minmax, master, i_nuclide) class(Nuclide), intent(inout) :: this integer(HID_T), intent(in) :: group_id type(VectorReal), intent(in) :: temperature ! list of desired temperatures @@ -258,6 +278,7 @@ contains real(8), intent(in) :: tolerance real(8), intent(in) :: minmax(2) ! range of temperatures logical, intent(in) :: master ! if this is the master proc + integer, intent(in) :: i_nuclide ! Nuclide index in nuclides integer :: i integer :: i_closest @@ -282,6 +303,7 @@ contains real(8) :: temp_actual type(VectorInt) :: MTs type(VectorInt) :: temps_to_read + type(VectorInt) :: index_inelastic_scatter ! Get name of nuclide from group name_len = len(this % name) @@ -449,10 +471,25 @@ contains end if end if + ! Add the reaction index to the scattering array if this is an inelastic + ! scatter reaction + if (MTs % data(i) /= N_FISSION .and. MTs % data(i) /= N_F .and. & + MTs % data(i) /= N_NF .and. MTs % data(i) /= N_2NF .and. & + MTs % data(i) /= N_3NF .and. MTs % data(i) < 200 .and. & + MTs % data(i) /= N_LEVEL .and. MTs % data(i) /= ELASTIC) then + + call index_inelastic_scatter % push_back(i) + end if + call close_group(rx_group) end do call close_group(rxs_group) + ! Recast to a regular array to save space + allocate(this % index_inelastic_scatter(index_inelastic_scatter % size())) + this % index_inelastic_scatter = & + index_inelastic_scatter % data(1: index_inelastic_scatter % size()) + ! Read unresolved resonance probability tables if present if (object_exists(group_id, 'urr')) then this % urr_present = .true. @@ -551,6 +588,9 @@ contains ! Create derived cross section data call this % create_derived() + ! Finalize with the nuclide index + this % i_nuclide = i_nuclide + end subroutine nuclide_from_hdf5 subroutine nuclide_create_derived(this) @@ -566,21 +606,13 @@ contains type(VectorInt) :: MTs n_temperature = size(this % kTs) - allocate(this % sum_xs(n_temperature)) + allocate(this % xs(n_temperature)) this % reaction_index(:) = 0 do i = 1, n_temperature ! Allocate and initialize derived cross sections n_grid = size(this % grid(i) % energy) - allocate(this % sum_xs(i) % total(n_grid)) - allocate(this % sum_xs(i) % elastic(n_grid)) - allocate(this % sum_xs(i) % fission(n_grid)) - allocate(this % sum_xs(i) % nu_fission(n_grid)) - allocate(this % sum_xs(i) % absorption(n_grid)) - this % sum_xs(i) % total(:) = ZERO - this % sum_xs(i) % elastic(:) = ZERO - this % sum_xs(i) % fission(:) = ZERO - this % sum_xs(i) % nu_fission(:) = ZERO - this % sum_xs(i) % absorption(:) = ZERO + allocate(this % xs(i) % value(4,n_grid)) + this % xs(i) % value(:,:) = ZERO end do i_fission = 0 @@ -607,17 +639,14 @@ contains j = rx % xs(t) % threshold n = size(rx % xs(t) % value) - ! Copy elastic - if (rx % MT == ELASTIC) this % sum_xs(t) % elastic(:) = rx % xs(t) % value - ! Add contribution to total cross section - this % sum_xs(t) % total(j:j+n-1) = this % sum_xs(t) % total(j:j+n-1) + & - rx % xs(t) % value + this % xs(t) % value(XS_TOTAL,j:j+n-1) = this % xs(t) % & + value(XS_TOTAL,j:j+n-1) + rx % xs(t) % value ! Add contribution to absorption cross section if (is_disappearance(rx % MT)) then - this % sum_xs(t) % absorption(j:j+n-1) = this % sum_xs(t) % & - absorption(j:j+n-1) + rx % xs(t) % value + this % xs(t) % value(XS_ABSORPTION,j:j+n-1) = this % xs(t) % & + value(XS_ABSORPTION,j:j+n-1) + rx % xs(t) % value end if ! Information about fission reactions @@ -633,12 +662,12 @@ contains ! Add contribution to fission cross section if (is_fission(rx % MT)) then this % fissionable = .true. - this % sum_xs(t) % fission(j:j+n-1) = this % sum_xs(t) % & - fission(j:j+n-1) + rx % xs(t) % value + this % xs(t) % value(XS_FISSION,j:j+n-1) = this % xs(t) % & + value(XS_FISSION,j:j+n-1) + rx % xs(t) % value ! Also need to add fission cross sections to absorption - this % sum_xs(t) % absorption(j:j+n-1) = this % sum_xs(t) % & - absorption(j:j+n-1) + rx % xs(t) % value + this % xs(t) % value(XS_ABSORPTION,j:j+n-1) = this % xs(t) % & + value(XS_ABSORPTION,j:j+n-1) + rx % xs(t) % value ! If total fission reaction is present, there's no need to store the ! reaction cross-section since it was copied to this % fission @@ -689,12 +718,11 @@ contains ! Calculate nu-fission cross section do t = 1, n_temperature if (this % fissionable) then - do i = 1, size(this % sum_xs(t) % fission) - this % sum_xs(t) % nu_fission(i) = this % nu(this % grid(t) % energy(i), & - EMISSION_TOTAL) * this % sum_xs(t) % fission(i) + do i = 1, n_grid + this % xs(t) % value(XS_NU_FISSION,i) = & + this % nu(this % grid(t) % energy(i), EMISSION_TOTAL) * & + this % xs(t) % value(XS_FISSION,i) end do - else - this % sum_xs(t) % nu_fission(:) = ZERO end if end do end subroutine nuclide_create_derived @@ -803,6 +831,729 @@ contains end subroutine nuclide_init_grid +!=============================================================================== +! NUCLIDE_CALCULATE_XS determines microscopic cross sections for the nuclide +! at the energy of the given particle +!=============================================================================== + + subroutine nuclide_calculate_xs(this, i_sab, E, i_log_union, sqrtkT, & + sab_frac, micro_xs) + class(Nuclide), intent(in) :: this ! Nuclide object + integer, intent(in) :: i_sab ! index into sab_tables array + real(8), intent(in) :: E ! energy + integer, intent(in) :: i_log_union ! index into logarithmic mapping array or + ! material union energy grid + real(8), intent(in) :: sqrtkT ! square root of kT, material dependent + real(8), intent(in) :: sab_frac ! fraction of atoms affected by S(a,b) + type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache + + logical :: use_mp ! true if XS can be calculated with windowed multipole + integer :: i_temp ! index for temperature + integer :: i_grid ! index on nuclide energy grid + integer :: i_low ! lower logarithmic mapping index + integer :: i_high ! upper logarithmic mapping index + integer :: i_rxn ! reaction index + integer :: j ! index in DEPLETION_RX + real(8) :: f ! interp factor on nuclide energy grid + real(8) :: kT ! temperature in eV + real(8) :: sig_t, sig_a, sig_f ! Intermediate multipole variables + + ! Initialize cached cross sections to zero + micro_xs % elastic = CACHE_INVALID + micro_xs % thermal = ZERO + micro_xs % thermal_elastic = ZERO + + ! Check to see if there is multipole data present at this energy + use_mp = .false. + if (this % mp_present) then + if (E >= this % multipole % start_E .and. & + E <= this % multipole % end_E) then + use_mp = .true. + end if + end if + + ! Evaluate multipole or interpolate + if (use_mp) then + ! Call multipole kernel + call multipole_eval(this % multipole, E, sqrtkT, sig_t, sig_a, sig_f) + + micro_xs % total = sig_t + micro_xs % absorption = sig_a + micro_xs % fission = sig_f + + if (this % fissionable) then + micro_xs % nu_fission = sig_f * this % nu(E, EMISSION_TOTAL) + else + micro_xs % nu_fission = ZERO + end if + + if (need_depletion_rx) then + ! Initialize all reaction cross sections to zero + micro_xs % reaction(:) = ZERO + + ! Only non-zero reaction is (n,gamma) + micro_xs % reaction(4) = sig_a - sig_f + end if + + ! Ensure these values are set + ! Note, the only time either is used is in one of 4 places: + ! 1. physics.F90 - scatter - For inelastic scatter. + ! 2. physics.F90 - sample_fission - For partial fissions. + ! 3. tally.F90 - score_general - For tallying on MTxxx reactions. + ! 4. nuclide_header.F90 - calculate_urr_xs - For unresolved purposes. + ! It is worth noting that none of these occur in the resolved + ! resonance range, so the value here does not matter. index_temp is + ! set to -1 to force a segfault in case a developer messes up and tries + ! to use it with multipole. + micro_xs % index_temp = -1 + micro_xs % index_grid = 0 + micro_xs % interp_factor = ZERO + + else + ! Find the appropriate temperature index. + kT = sqrtkT**2 + select case (temperature_method) + case (TEMPERATURE_NEAREST) + i_temp = minloc(abs(this % kTs - kT), dim=1) + + case (TEMPERATURE_INTERPOLATION) + ! Find temperatures that bound the actual temperature + do i_temp = 1, size(this % kTs) - 1 + if (this % kTs(i_temp) <= kT .and. kT < this % kTs(i_temp + 1)) exit + end do + + ! Randomly sample between temperature i and i+1 + f = (kT - this % kTs(i_temp)) / & + (this % kTs(i_temp + 1) - this % kTs(i_temp)) + if (f > prn()) i_temp = i_temp + 1 + end select + + associate (grid => this % grid(i_temp), xs => this % xs(i_temp)) + ! Determine the energy grid index using a logarithmic mapping to + ! reduce the energy range over which a binary search needs to be + ! performed + + if (E < grid % energy(1)) then + i_grid = 1 + elseif (E > grid % energy(size(grid % energy))) then + i_grid = size(grid % energy) - 1 + else + ! Determine bounding indices based on which equal log-spaced + ! interval the energy is in + i_low = grid % grid_index(i_log_union) + i_high = grid % grid_index(i_log_union + 1) + 1 + + ! Perform binary search over reduced range + i_grid = binary_search(grid % energy(i_low:i_high), & + i_high - i_low + 1, E) + i_low - 1 + end if + + ! check for rare case where two energy points are the same + if (grid % energy(i_grid) == grid % energy(i_grid + 1)) & + i_grid = i_grid + 1 + + ! calculate interpolation factor + f = (E - grid % energy(i_grid)) / & + (grid % energy(i_grid + 1) - grid % energy(i_grid)) + + micro_xs % index_temp = i_temp + micro_xs % index_grid = i_grid + micro_xs % interp_factor = f + + ! Calculate microscopic nuclide total cross section + micro_xs % total = (ONE - f) * xs % value(XS_TOTAL,i_grid) & + + f * xs % value(XS_TOTAL,i_grid + 1) + + ! Calculate microscopic nuclide absorption cross section + micro_xs % absorption = (ONE - f) * xs % value(XS_ABSORPTION, & + i_grid) + f * xs % value(XS_ABSORPTION,i_grid + 1) + + if (this % fissionable) then + ! Calculate microscopic nuclide total cross section + micro_xs % fission = (ONE - f) * xs % value(XS_FISSION,i_grid) & + + f * xs % value(XS_FISSION,i_grid + 1) + + ! Calculate microscopic nuclide nu-fission cross section + micro_xs % nu_fission = (ONE - f) * xs % value(XS_NU_FISSION, & + i_grid) + f * xs % value(XS_NU_FISSION,i_grid + 1) + else + micro_xs % fission = ZERO + micro_xs % nu_fission = ZERO + end if + end associate + + ! Depletion-related reactions + if (need_depletion_rx) then + do j = 1, 6 + ! Initialize reaction xs to zero + micro_xs % reaction(j) = ZERO + + ! If reaction is present and energy is greater than threshold, set + ! the reaction xs appropriately + i_rxn = this % reaction_index(DEPLETION_RX(j)) + if (i_rxn > 0) then + associate (xs => this % reactions(i_rxn) % xs(i_temp)) + if (i_grid >= xs % threshold) then + micro_xs % reaction(j) = (ONE - f) * & + xs % value(i_grid - xs % threshold + 1) + & + f * xs % value(i_grid - xs % threshold + 2) + end if + end associate + end if + end do + end if + + end if + + ! Initialize sab treatment to false + micro_xs % index_sab = NONE + micro_xs % sab_frac = ZERO + + ! Initialize URR probability table treatment to false + micro_xs % use_ptable = .false. + + ! If there is S(a,b) data for this nuclide, we need to set the sab_scatter + ! and sab_elastic cross sections and correct the total and elastic cross + ! sections. + + if (i_sab > 0) then + call calculate_sab_xs(this, i_sab, E, sqrtkT, sab_frac, micro_xs) + end if + + ! If the particle is in the unresolved resonance range and there are + ! probability tables, we need to determine cross sections from the table + + if (urr_ptables_on .and. this % urr_present .and. .not. use_mp) then + if (E > this % urr_data(i_temp) % energy(1) .and. E < this % & + urr_data(i_temp) % energy(this % urr_data(i_temp) % n_energy)) then + call calculate_urr_xs(this, i_temp, E, micro_xs) + end if + end if + + micro_xs % last_E = E + micro_xs % last_sqrtkT = sqrtkT + + end subroutine nuclide_calculate_xs + +!=============================================================================== +! NUCLIDE_CALCULATE_ELASTIC_XS precalculates the free atom elastic scattering +! cross section. Normally it is not needed until a collision actually occurs in +! a material. However, in the thermal and unresolved resonance regions, we have +! to calculate it early to adjust the total cross section correctly. +!=============================================================================== + + subroutine nuclide_calculate_elastic_xs(this, micro_xs) + class(Nuclide), intent(in) :: this + type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache + + integer :: i_temp + integer :: i_grid + real(8) :: f + + ! Get temperature index, grid index, and interpolation factor + i_temp = micro_xs % index_temp + i_grid = micro_xs % index_grid + f = micro_xs % interp_factor + + if (i_temp > 0) then + associate (xs => this % reactions(1) % xs(i_temp) % value) + micro_xs % elastic = (ONE - f) * xs(i_grid) + f * xs(i_grid + 1) + end associate + else + ! For multipole, elastic is total - absorption + micro_xs % elastic = micro_xs % total - micro_xs % absorption + end if + end subroutine nuclide_calculate_elastic_xs + +!=============================================================================== +! CALCULATE_SAB_XS determines the elastic and inelastic scattering +! cross-sections in the thermal energy range. These cross sections replace a +! fraction of whatever data were taken from the normal Nuclide table. +!=============================================================================== + + subroutine calculate_sab_xs(this, i_sab, E, sqrtkT, sab_frac, micro_xs) + class(Nuclide), intent(in) :: this ! Nuclide object + integer, intent(in) :: i_sab ! index into sab_tables array + real(8), intent(in) :: E ! energy + real(8), intent(in) :: sqrtkT ! temperature + real(8), intent(in) :: sab_frac ! fraction of atoms affected by S(a,b) + type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache + + integer :: i_temp ! temperature index + real(8) :: inelastic ! S(a,b) inelastic cross section + real(8) :: elastic ! S(a,b) elastic cross section + + ! Set flag that S(a,b) treatment should be used for scattering + micro_xs % index_sab = i_sab + + ! Calculate the S(a,b) cross section + call sab_tables(i_sab) % calculate_xs(E, sqrtkT, i_temp, elastic, inelastic) + + ! Store the S(a,b) cross sections. + micro_xs % thermal = sab_frac * (elastic + inelastic) + micro_xs % thermal_elastic = sab_frac * elastic + + ! Calculate free atom elastic cross section + call this % calculate_elastic_xs(micro_xs) + + ! Correct total and elastic cross sections + micro_xs % total = micro_xs % total + micro_xs % thermal - & + sab_frac * micro_xs % elastic + micro_xs % elastic = micro_xs % thermal + (ONE - sab_frac) * & + micro_xs % elastic + + ! Save temperature index and thermal fraction + micro_xs % index_temp_sab = i_temp + micro_xs % sab_frac = sab_frac + + end subroutine calculate_sab_xs + +!=============================================================================== +! MULTIPOLE_EVAL evaluates the windowed multipole equations for cross +! sections in the resolved resonance regions +!=============================================================================== + + subroutine multipole_eval(multipole, E, sqrtkT, sig_t, sig_a, sig_f) + type(MultipoleArray), intent(in) :: multipole ! The windowed multipole + ! object to process. + real(8), intent(in) :: E ! The energy at which to + ! evaluate the cross section + real(8), intent(in) :: sqrtkT ! The temperature in the form + ! sqrt(kT), at which + ! to evaluate the XS. + real(8), intent(out) :: sig_t ! Total cross section + real(8), intent(out) :: sig_a ! Absorption cross section + real(8), intent(out) :: sig_f ! Fission cross section + complex(8) :: psi_chi ! The value of the psi-chi function for the + ! asymptotic form + complex(8) :: c_temp ! complex temporary variable + complex(8) :: w_val ! The faddeeva function evaluated at Z + complex(8) :: Z ! sqrt(atomic weight ratio / kT) * (sqrt(E) - pole) + complex(8) :: sig_t_factor(multipole % num_l) + real(8) :: broadened_polynomials(multipole % fit_order + 1) + real(8) :: sqrtE ! sqrt(E), eV + real(8) :: invE ! 1/E, eV + real(8) :: dopp ! sqrt(atomic weight ratio / kT) = 1 / (2 sqrt(xi)) + real(8) :: temp ! real temporary value + integer :: i_pole ! index of pole + integer :: i_poly ! index of curvefit + integer :: i_window ! index of window + integer :: startw ! window start pointer (for poles) + integer :: endw ! window end pointer + + ! ========================================================================== + ! Bookkeeping + + ! Define some frequently used variables. + sqrtE = sqrt(E) + invE = ONE / E + + ! Locate us. + i_window = floor((sqrtE - sqrt(multipole % start_E)) / multipole % spacing & + + ONE) + startw = multipole % w_start(i_window) + endw = multipole % w_end(i_window) + + ! Fill in factors. + if (startw <= endw) then + call compute_sig_t_factor(multipole, sqrtE, sig_t_factor) + end if + + ! Initialize the ouptut cross sections. + sig_t = ZERO + sig_a = ZERO + sig_f = ZERO + + ! ========================================================================== + ! Add the contribution from the curvefit polynomial. + + if (sqrtkT /= ZERO .and. multipole % broaden_poly(i_window) == 1) then + ! Broaden the curvefit. + dopp = multipole % sqrtAWR / sqrtkT + call broaden_wmp_polynomials(E, dopp, multipole % fit_order + 1, & + broadened_polynomials) + do i_poly = 1, multipole % fit_order+1 + sig_t = sig_t + multipole % curvefit(FIT_T, i_poly, i_window) & + * broadened_polynomials(i_poly) + sig_a = sig_a + multipole % curvefit(FIT_A, i_poly, i_window) & + * broadened_polynomials(i_poly) + if (multipole % fissionable) then + sig_f = sig_f + multipole % curvefit(FIT_F, i_poly, i_window) & + * broadened_polynomials(i_poly) + end if + end do + else ! Evaluate as if it were a polynomial + temp = invE + do i_poly = 1, multipole % fit_order+1 + sig_t = sig_t + multipole % curvefit(FIT_T, i_poly, i_window) * temp + sig_a = sig_a + multipole % curvefit(FIT_A, i_poly, i_window) * temp + if (multipole % fissionable) then + sig_f = sig_f + multipole % curvefit(FIT_F, i_poly, i_window) * temp + end if + temp = temp * sqrtE + end do + end if + + ! ========================================================================== + ! Add the contribution from the poles in this window. + + if (sqrtkT == ZERO) then + ! If at 0K, use asymptotic form. + do i_pole = startw, endw + psi_chi = -ONEI / (multipole % data(MP_EA, i_pole) - sqrtE) + c_temp = psi_chi / E + if (multipole % formalism == FORM_MLBW) then + sig_t = sig_t + real(multipole % data(MLBW_RT, i_pole) * c_temp * & + sig_t_factor(multipole % l_value(i_pole))) & + + real(multipole % data(MLBW_RX, i_pole) * c_temp) + sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * c_temp) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * c_temp) + end if + else if (multipole % formalism == FORM_RM) then + sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * c_temp * & + sig_t_factor(multipole % l_value(i_pole))) + sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * c_temp) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * c_temp) + end if + end if + end do + else + ! At temperature, use Faddeeva function-based form. + dopp = multipole % sqrtAWR / sqrtkT + if (endw >= startw) then + do i_pole = startw, endw + Z = (sqrtE - multipole % data(MP_EA, i_pole)) * dopp + w_val = faddeeva(Z) * dopp * invE * SQRT_PI + if (multipole % formalism == FORM_MLBW) then + sig_t = sig_t + real((multipole % data(MLBW_RT, i_pole) * & + sig_t_factor(multipole % l_value(i_pole)) + & + multipole % data(MLBW_RX, i_pole)) * w_val) + sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * w_val) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * w_val) + end if + else if (multipole % formalism == FORM_RM) then + sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * w_val * & + sig_t_factor(multipole % l_value(i_pole))) + sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * w_val) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * w_val) + end if + end if + end do + end if + end if + end subroutine multipole_eval + +!=============================================================================== +! MULTIPOLE_DERIV_EVAL evaluates the windowed multipole equations for the +! derivative of cross sections in the resolved resonance regions with respect to +! temperature. +!=============================================================================== + + subroutine multipole_deriv_eval(multipole, E, sqrtkT, sig_t, sig_a, sig_f) + type(MultipoleArray), intent(in) :: multipole ! The windowed multipole + ! object to process. + real(8), intent(in) :: E ! The energy at which to + ! evaluate the cross section + real(8), intent(in) :: sqrtkT ! The temperature in the form + ! sqrt(kT), at which to + ! evaluate the XS. + real(8), intent(out) :: sig_t ! Total cross section + real(8), intent(out) :: sig_a ! Absorption cross section + real(8), intent(out) :: sig_f ! Fission cross section + complex(8) :: w_val ! The faddeeva function evaluated at Z + complex(8) :: Z ! sqrt(atomic weight ratio / kT) * (sqrt(E) - pole) + complex(8) :: sig_t_factor(multipole % num_l) + real(8) :: sqrtE ! sqrt(E), eV + real(8) :: invE ! 1/E, eV + real(8) :: dopp ! sqrt(atomic weight ratio / kT) + integer :: i_pole ! index of pole + integer :: i_window ! index of window + integer :: startw ! window start pointer (for poles) + integer :: endw ! window end pointer + real(8) :: T + + ! ========================================================================== + ! Bookkeeping + + ! Define some frequently used variables. + sqrtE = sqrt(E) + invE = ONE / E + T = sqrtkT**2 / K_BOLTZMANN + + if (sqrtkT == ZERO) call fatal_error("Windowed multipole temperature & + &derivatives are not implemented for 0 Kelvin cross sections.") + + ! Locate us + i_window = floor((sqrtE - sqrt(multipole % start_E)) / multipole % spacing & + + ONE) + startw = multipole % w_start(i_window) + endw = multipole % w_end(i_window) + + ! Fill in factors. + if (startw <= endw) then + call compute_sig_t_factor(multipole, sqrtE, sig_t_factor) + end if + + ! Initialize the ouptut cross sections. + sig_t = ZERO + sig_a = ZERO + sig_f = ZERO + + ! TODO Polynomials: Some of the curvefit polynomials Doppler broaden so + ! rigorously we should be computing the derivative of those. But in + ! practice, those derivatives are only large at very low energy and they + ! have no effect on reactor calculations. + + ! ========================================================================== + ! Add the contribution from the poles in this window. + + dopp = multipole % sqrtAWR / sqrtkT + if (endw >= startw) then + do i_pole = startw, endw + Z = (sqrtE - multipole % data(MP_EA, i_pole)) * dopp + w_val = -invE * SQRT_PI * HALF * w_derivative(Z, 2) + if (multipole % formalism == FORM_MLBW) then + sig_t = sig_t + real((multipole % data(MLBW_RT, i_pole) * & + sig_t_factor(multipole%l_value(i_pole)) + & + multipole % data(MLBW_RX, i_pole)) * w_val) + sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * w_val) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * w_val) + end if + else if (multipole % formalism == FORM_RM) then + sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * w_val * & + sig_t_factor(multipole % l_value(i_pole))) + sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * w_val) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * w_val) + end if + end if + end do + sig_t = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_t + sig_a = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_a + sig_f = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_f + end if + end subroutine multipole_deriv_eval + +!=============================================================================== +! COMPUTE_SIG_T_FACTOR calculates the sig_t_factor, a factor inside of the sig_t +! equation not present in the sig_a and sig_f equations. +!=============================================================================== + + subroutine compute_sig_t_factor(multipole, sqrtE, sig_t_factor) + type(MultipoleArray), intent(in) :: multipole + real(8), intent(in) :: sqrtE + complex(8), intent(out) :: sig_t_factor(multipole % num_l) + + integer :: iL + real(8) :: twophi(multipole % num_l) + real(8) :: arg + + do iL = 1, multipole % num_l + twophi(iL) = multipole % pseudo_k0RS(iL) * sqrtE + if (iL == 2) then + twophi(iL) = twophi(iL) - atan(twophi(iL)) + else if (iL == 3) then + arg = 3.0_8 * twophi(iL) / (3.0_8 - twophi(iL)**2) + twophi(iL) = twophi(iL) - atan(arg) + else if (iL == 4) then + arg = twophi(iL) * (15.0_8 - twophi(iL)**2) & + / (15.0_8 - 6.0_8 * twophi(iL)**2) + twophi(iL) = twophi(iL) - atan(arg) + end if + end do + + twophi = 2.0_8 * twophi + sig_t_factor = cmplx(cos(twophi), -sin(twophi), KIND=8) + end subroutine compute_sig_t_factor + +!=============================================================================== +! 0K_ELASTIC_XS determines the microscopic 0K elastic cross section +! for a given nuclide at the trial relative energy used in resonance scattering +!=============================================================================== + + pure function elastic_xs_0K(E, nuc) result(xs_out) + real(8), intent(in) :: E ! trial energy + type(Nuclide), intent(in) :: nuc ! target nuclide at temperature + real(8) :: xs_out ! 0K xs at trial energy + + integer :: i_grid ! index on nuclide energy grid + integer :: n_grid + real(8) :: f ! interp factor on nuclide energy grid + + ! Determine index on nuclide energy grid + n_grid = size(nuc % energy_0K) + if (E < nuc % energy_0K(1)) then + i_grid = 1 + elseif (E > nuc % energy_0K(n_grid)) then + i_grid = n_grid - 1 + else + i_grid = binary_search(nuc % energy_0K, n_grid, E) + end if + + ! check for rare case where two energy points are the same + if (nuc % energy_0K(i_grid) == nuc % energy_0K(i_grid+1)) then + i_grid = i_grid + 1 + end if + + ! calculate interpolation factor + f = (E - nuc % energy_0K(i_grid)) & + & / (nuc % energy_0K(i_grid + 1) - nuc % energy_0K(i_grid)) + + ! Calculate microscopic nuclide elastic cross section + xs_out = (ONE - f) * nuc % elastic_0K(i_grid) & + & + f * nuc % elastic_0K(i_grid + 1) + + end function elastic_xs_0K + +!=============================================================================== +! CALCULATE_URR_XS determines cross sections in the unresolved resonance range +! from probability tables +!=============================================================================== + + subroutine calculate_urr_xs(this, i_temp, E, micro_xs) + class(Nuclide), intent(in) :: this ! Nuclide object + integer, intent(in) :: i_temp ! temperature index + real(8), intent(in) :: E ! energy + type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache + + integer :: i_energy ! index for energy + integer :: i_low ! band index at lower bounding energy + integer :: i_up ! band index at upper bounding energy + real(8) :: f ! interpolation factor + real(8) :: r ! pseudo-random number + real(8) :: elastic ! elastic cross section + real(8) :: capture ! (n,gamma) cross section + real(8) :: fission ! fission cross section + real(8) :: inelastic ! inelastic cross section + + micro_xs % use_ptable = .true. + + associate (urr => this % urr_data(i_temp)) + ! determine energy table + i_energy = 1 + do + if (E < urr % energy(i_energy + 1)) exit + i_energy = i_energy + 1 + end do + + ! determine interpolation factor on table + f = (E - urr % energy(i_energy)) / & + (urr % energy(i_energy + 1) - urr % energy(i_energy)) + + ! sample probability table using the cumulative distribution + + ! Random numbers for xs calculation are sampled from a separated stream. + ! This guarantees the randomness and, at the same time, makes sure we reuse + ! random number for the same nuclide at different temperatures, therefore + ! preserving correlation of temperature in probability tables. + call prn_set_stream(STREAM_URR_PTABLE) + r = future_prn(int(this % i_nuclide, 8)) + call prn_set_stream(STREAM_TRACKING) + + i_low = 1 + do + if (urr % prob(i_energy, URR_CUM_PROB, i_low) > r) exit + i_low = i_low + 1 + end do + i_up = 1 + do + if (urr % prob(i_energy + 1, URR_CUM_PROB, i_up) > r) exit + i_up = i_up + 1 + end do + + ! determine elastic, fission, and capture cross sections from probability + ! table + if (urr % interp == LINEAR_LINEAR) then + elastic = (ONE - f) * urr % prob(i_energy, URR_ELASTIC, i_low) + & + f * urr % prob(i_energy + 1, URR_ELASTIC, i_up) + fission = (ONE - f) * urr % prob(i_energy, URR_FISSION, i_low) + & + f * urr % prob(i_energy + 1, URR_FISSION, i_up) + capture = (ONE - f) * urr % prob(i_energy, URR_N_GAMMA, i_low) + & + f * urr % prob(i_energy + 1, URR_N_GAMMA, i_up) + elseif (urr % interp == LOG_LOG) then + ! Get logarithmic interpolation factor + f = log(E / urr % energy(i_energy)) / & + log(urr % energy(i_energy + 1) / urr % energy(i_energy)) + + ! Calculate elastic cross section/factor + elastic = ZERO + if (urr % prob(i_energy, URR_ELASTIC, i_low) > ZERO .and. & + urr % prob(i_energy + 1, URR_ELASTIC, i_up) > ZERO) then + elastic = exp((ONE - f) * log(urr % prob(i_energy, URR_ELASTIC, & + i_low)) + f * log(urr % prob(i_energy + 1, URR_ELASTIC, & + i_up))) + end if + + ! Calculate fission cross section/factor + fission = ZERO + if (urr % prob(i_energy, URR_FISSION, i_low) > ZERO .and. & + urr % prob(i_energy + 1, URR_FISSION, i_up) > ZERO) then + fission = exp((ONE - f) * log(urr % prob(i_energy, URR_FISSION, & + i_low)) + f * log(urr % prob(i_energy + 1, URR_FISSION, & + i_up))) + end if + + ! Calculate capture cross section/factor + capture = ZERO + if (urr % prob(i_energy, URR_N_GAMMA, i_low) > ZERO .and. & + urr % prob(i_energy + 1, URR_N_GAMMA, i_up) > ZERO) then + capture = exp((ONE - f) * log(urr % prob(i_energy, URR_N_GAMMA, & + i_low)) + f * log(urr % prob(i_energy + 1, URR_N_GAMMA, & + i_up))) + end if + end if + + ! Determine treatment of inelastic scattering + inelastic = ZERO + if (urr % inelastic_flag > 0) then + ! Get index on energy grid and interpolation factor + i_energy = micro_xs % index_grid + f = micro_xs % interp_factor + + ! Determine inelastic scattering cross section + associate (xs => this % reactions(this % urr_inelastic) % xs(i_temp)) + if (i_energy >= xs % threshold) then + inelastic = (ONE - f) * xs % value(i_energy - xs % threshold + 1) + & + f * xs % value(i_energy - xs % threshold + 2) + end if + end associate + end if + + ! Multiply by smooth cross-section if needed + if (urr % multiply_smooth) then + call this % calculate_elastic_xs(micro_xs) + elastic = elastic * micro_xs % elastic + capture = capture * (micro_xs % absorption - micro_xs % fission) + fission = fission * micro_xs % fission + end if + + ! Check for negative values + if (elastic < ZERO) elastic = ZERO + if (fission < ZERO) fission = ZERO + if (capture < ZERO) capture = ZERO + + ! Set elastic, absorption, fission, and total cross sections. Note that the + ! total cross section is calculated as sum of partials rather than using the + ! table-provided value + micro_xs % elastic = elastic + micro_xs % absorption = capture + fission + micro_xs % fission = fission + micro_xs % total = elastic + inelastic + capture + fission + + ! Determine nu-fission cross section + if (this % fissionable) then + micro_xs % nu_fission = this % nu(E, EMISSION_TOTAL) * & + micro_xs % fission + end if + end associate + + end subroutine calculate_urr_xs + !=============================================================================== ! CHECK_DATA_VERSION checks for the right version of nuclear data within HDF5 ! files @@ -920,7 +1671,7 @@ contains group_id = open_group(file_id, name_) call nuclides(n) % from_hdf5(group_id, temperature, & temperature_method, temperature_tolerance, minmax, & - master) + master, n) call close_group(group_id) call file_close(file_id) diff --git a/src/output.F90 b/src/output.F90 index 9a144721dc..b6809ca82f 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -88,7 +88,7 @@ contains ! Write the date and time write(UNIT=OUTPUT_UNIT, FMT='(9X,"Date/Time | ",A)') time_stamp() -#ifdef MPI +#ifdef OPENMC_MPI ! Write number of processors write(UNIT=OUTPUT_UNIT, FMT='(5X,"MPI Processes | ",A)') & trim(to_str(n_procs)) @@ -165,12 +165,12 @@ contains subroutine print_version() if (master) then - write(UNIT=OUTPUT_UNIT, FMT='(1X,A,1X,I1,".",I1,".",I1)') & + write(UNIT=OUTPUT_UNIT, FMT='(1X,A,1X,I1,".",I2,".",I1)') & "OpenMC version", VERSION_MAJOR, VERSION_MINOR, VERSION_RELEASE #ifdef GIT_SHA1 write(UNIT=OUTPUT_UNIT, FMT='(1X,A,A)') "Git SHA1: ", GIT_SHA1 #endif - write(UNIT=OUTPUT_UNIT, FMT=*) "Copyright (c) 2011-2015 & + write(UNIT=OUTPUT_UNIT, FMT=*) "Copyright (c) 2011-2018 & &Massachusetts Institute of Technology" write(UNIT=OUTPUT_UNIT, FMT=*) "MIT/X license at & &" @@ -259,7 +259,7 @@ contains ! Print surface if (p % surface /= NONE) then - write(ou,*) ' Surface = ' // to_str(sign(surfaces(i)%obj%id, p % surface)) + write(ou,*) ' Surface = ' // to_str(sign(surfaces(i)%id(), p % surface)) end if ! Display weight, energy, grid index, and interpolation factor @@ -356,7 +356,7 @@ contains integer :: n ! number of active generations ! Determine overall generation and number of active generations - i = overall_generation() + i = current_batch*gen_per_batch n = i - n_inactive*gen_per_batch ! write out information batch and option independent output @@ -771,12 +771,6 @@ contains end associate end if - ! Handle surface current tallies separately - if (t % type == TALLY_MESH_CURRENT) then - call write_surface_current(t, unit_tally) - cycle - end if - ! WARNING: Admittedly, the logic for moving for printing results is ! extremely confusing and took quite a bit of time to get correct. The ! logic is structured this way since it is not practical to have a do @@ -938,188 +932,6 @@ contains end subroutine write_tallies -!=============================================================================== -! WRITE_SURFACE_CURRENT writes out surface current tallies over a mesh to the -! tallies.out file. -!=============================================================================== - - subroutine write_surface_current(t, unit_tally) - type(TallyObject), intent(in) :: t - integer, intent(in) :: unit_tally - - integer :: i ! mesh index - integer :: j ! loop index over tally filters - integer :: ijk(3) ! indices of mesh cells - integer :: n_dim ! number of mesh dimensions - integer :: n_cells ! number of mesh cells - integer :: l ! index for energy - integer :: i_filter_mesh ! index for mesh filter - integer :: i_filter_ein ! index for incoming energy filter - integer :: i_filter_surf ! index for surface filter - integer :: stride_surf ! stride for surface filter - integer :: n ! number of incoming energy bins - integer :: filter_index ! index in results array for filters - integer :: nr ! number of realizations - real(8) :: x(2) ! mean and standard deviation - logical :: print_ebin ! should incoming energy bin be displayed? - logical :: energy_filters ! energy filters present - character(MAX_LINE_LEN) :: string - type(RegularMesh), pointer :: m - type(TallyFilterMatch), allocatable :: matches(:) - - allocate(matches(n_filters)) - - nr = t % n_realizations - - ! Get pointer to mesh - i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) - select type(filt => filters(i_filter_mesh) % obj) - type is (MeshFilter) - m => meshes(filt % mesh) - end select - - ! Get surface filter index and stride - i_filter_surf = t % filter(t % find_filter(FILTER_SURFACE)) - stride_surf = t % stride(t % find_filter(FILTER_SURFACE)) - - ! initialize bins array - do j = 1, size(t % filter) - call matches(t % filter(j)) % bins % clear() - call matches(t % filter(j)) % bins % push_back(1) - end do - - ! determine how many energy in bins there are - energy_filters = (t % find_filter(FILTER_ENERGYIN) > 0) - if (energy_filters) then - print_ebin = .true. - i_filter_ein = t % filter(t % find_filter(FILTER_ENERGYIN)) - n = filters(i_filter_ein) % obj % n_bins - else - print_ebin = .false. - n = 1 - end if - - ! Get the dimensions and number of cells in the mesh - n_dim = m % n_dimension - n_cells = product(m % dimension) - - ! Loop over all the mesh cells - do i = 1, n_cells - - ! Get the indices for this cell - call m % get_indices_from_bin(i, ijk) - matches(i_filter_mesh) % bins % data(1) = i - - ! Write the header for this cell - if (n_dim == 1) then - string = "Mesh Index (" // trim(to_str(ijk(1))) // ")" - else if (n_dim == 2) then - string = "Mesh Index (" // trim(to_str(ijk(1))) // ", " & - // trim(to_str(ijk(2))) // ")" - else if (n_dim == 3) then - string = "Mesh Index (" // trim(to_str(ijk(1))) // ", " & - // trim(to_str(ijk(2))) // ", " // trim(to_str(ijk(3))) // ")" - end if - - write(UNIT=unit_tally, FMT='(1X,A)') trim(string) - - do l = 1, n - if (print_ebin) then - ! Set incoming energy bin - matches(i_filter_ein) % bins % data(1) = l - - ! Write incoming energy bin - write(UNIT=unit_tally, FMT='(3X,A)') & - trim(filters(i_filter_ein) % obj % text_label( & - matches(i_filter_ein) % bins % data(1))) - end if - - filter_index = 1 - do j = 1, size(t % filter) - if (t % filter(j) == i_filter_surf) cycle - filter_index = filter_index + (matches(t % filter(j)) & - % bins % data(1) - 1) * t % stride(j) - end do - - associate(r => t % results(RESULT_SUM:RESULT_SUM_SQ, :, :)) - - ! Left Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_LEFT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Left", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_LEFT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Left", to_str(x(1)), trim(to_str(x(2))) - - ! Right Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_RIGHT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Right", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_RIGHT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Right", to_str(x(1)), trim(to_str(x(2))) - - if (n_dim >= 2) then - - ! Back Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_BACK - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Back", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_BACK - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Back", to_str(x(1)), trim(to_str(x(2))) - - ! Front Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_FRONT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Front", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_FRONT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Front", to_str(x(1)), trim(to_str(x(2))) - end if - - if (n_dim == 3) then - - ! Bottom Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_BOTTOM - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Bottom", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_BOTTOM - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Bottom", to_str(x(1)), trim(to_str(x(2))) - - ! Top Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_TOP - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Top", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_TOP - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Top", to_str(x(1)), trim(to_str(x(2))) - end if - end associate - end do - end do - - end subroutine write_surface_current - !=============================================================================== ! MEAN_STDEV computes the sample mean and standard deviation of the mean of a ! single tally score diff --git a/src/physics.F90 b/src/physics.F90 index d13313e05a..b614b81851 100644 --- a/src/physics.F90 +++ b/src/physics.F90 @@ -2,7 +2,6 @@ module physics use algorithm, only: binary_search use constants - use cross_section, only: elastic_xs_0K use endf, only: reaction_name use error, only: fatal_error, warning, write_message use material_header, only: Material, materials @@ -311,6 +310,7 @@ contains integer, intent(in) :: i_nuc_mat integer :: i + integer :: j integer :: i_temp integer :: i_grid real(8) :: f @@ -338,6 +338,11 @@ contains micro_xs(i_nuclide) % absorption) sampled = .false. + ! Calculate elastic cross section if it wasn't precalculated + if (micro_xs(i_nuclide) % elastic == CACHE_INVALID) then + call nuc % calculate_elastic_xs(micro_xs(i_nuclide)) + end if + prob = micro_xs(i_nuclide) % elastic - micro_xs(i_nuclide) % thermal if (prob > cutoff) then ! ======================================================================= @@ -374,11 +379,10 @@ contains ! ======================================================================= ! INELASTIC SCATTERING - ! note that indexing starts from 2 since nuc % reactions(1) is elastic - ! scattering - i = 1 + j = 0 do while (prob < cutoff) - i = i + 1 + j = j + 1 + i = nuc % index_inelastic_scatter(j) ! Check to make sure inelastic scattering reaction sampled if (i > size(nuc % reactions)) then @@ -387,24 +391,14 @@ contains &// trim(nuc % name)) end if - associate (rx => nuc % reactions(i)) - ! Skip fission reactions - if (rx % MT == N_FISSION .or. rx % MT == N_F .or. rx % MT == N_NF & - .or. rx % MT == N_2NF .or. rx % MT == N_3NF) cycle + associate (rx => nuc % reactions(i), & + xs => nuc % reactions(i) % xs(i_temp)) + ! if energy is below threshold for this reaction, skip it + if (i_grid < xs % threshold) cycle - ! Some materials have gas production cross sections with MT > 200 that - ! are duplicates. Also MT=4 is total level inelastic scattering which - ! should be skipped - if (rx % MT >= 200 .or. rx % MT == N_LEVEL) cycle - - associate (xs => rx % xs(i_temp)) - ! if energy is below threshold for this reaction, skip it - if (i_grid < xs % threshold) cycle - - ! add to cumulative probability - prob = prob + ((ONE - f)*xs % value(i_grid - xs % threshold + 1) & - + f*(xs % value(i_grid - xs % threshold + 2))) - end associate + ! add to cumulative probability + prob = prob + ((ONE - f)*xs % value(i_grid - xs % threshold + 1) & + + f*(xs % value(i_grid - xs % threshold + 2))) end associate end do @@ -931,11 +925,14 @@ contains maxval(nuc % elastic_0K(i_E_low + 1 : i_E_up)), xs_up) DBRC_REJECT_LOOP: do - ! sample target velocity with the constant cross section (cxs) approx. - call sample_cxs_target_velocity(nuc, v_target, E, uvw, kT) + TARGET_ENERGY_LOOP: do + ! sample target velocity with the constant cross section (cxs) approx. + call sample_cxs_target_velocity(nuc, v_target, E, uvw, kT) + E_rel = dot_product((v_neut - v_target), (v_neut - v_target)) + if (E_rel < E_up) exit TARGET_ENERGY_LOOP + end do TARGET_ENERGY_LOOP ! perform Doppler broadening rejection correction (dbrc) - E_rel = dot_product((v_neut - v_target), (v_neut - v_target)) xs_0K = elastic_xs_0K(E_rel, nuc) R = xs_0K / xs_max if (prn() < R) exit DBRC_REJECT_LOOP diff --git a/src/random_lcg.F90 b/src/random_lcg.F90 index 839bd729a9..d64717cf42 100644 --- a/src/random_lcg.F90 +++ b/src/random_lcg.F90 @@ -4,8 +4,6 @@ module random_lcg implicit none - integer(C_INT64_T), bind(C) :: seed - interface function prn() result(pseudo_rn) bind(C) use ISO_C_BINDING @@ -38,11 +36,16 @@ module random_lcg integer(C_INT), value :: n end subroutine prn_set_stream - function openmc_set_seed(new_seed) result(err) bind(C) + function openmc_get_seed() result(seed) bind(C) + use ISO_C_BINDING + implicit none + integer(C_INT64_T) :: seed + end function openmc_get_seed + + subroutine openmc_set_seed(new_seed) bind(C) use ISO_C_BINDING implicit none integer(C_INT64_T), value :: new_seed - integer(C_INT) :: err - end function openmc_set_seed + end subroutine openmc_set_seed end interface end module random_lcg diff --git a/src/random_lcg.cpp b/src/random_lcg.cpp index 047bda8e54..2a57316cb6 100644 --- a/src/random_lcg.cpp +++ b/src/random_lcg.cpp @@ -2,6 +2,9 @@ #include +namespace openmc { + + // Constants extern "C" const int N_STREAMS {5}; extern "C" const int STREAM_TRACKING {0}; @@ -130,7 +133,9 @@ prn_set_stream(int i) // API FUNCTIONS //============================================================================== -extern "C" int +extern "C" int64_t openmc_get_seed() {return seed;} + +extern "C" void openmc_set_seed(int64_t new_seed) { seed = new_seed; @@ -141,5 +146,6 @@ openmc_set_seed(int64_t new_seed) } prn_set_stream(STREAM_TRACKING); } - return 0; } + +} // namespace openmc diff --git a/src/random_lcg.h b/src/random_lcg.h index 04191254f3..29b3fca47d 100644 --- a/src/random_lcg.h +++ b/src/random_lcg.h @@ -3,6 +3,9 @@ #include + +namespace openmc { + //============================================================================== // Module constants. //============================================================================== @@ -74,12 +77,19 @@ extern "C" void prn_set_stream(int n); // API FUNCTIONS //============================================================================== +//============================================================================== +//! Get OpenMC's master seed. +//============================================================================== + +extern "C" int64_t openmc_get_seed(); + //============================================================================== //! Set OpenMC's master seed. //! @param new_seed The master seed. All other seeds will be derived from this //! one. //============================================================================== -extern "C" int openmc_set_seed(int64_t new_seed); +extern "C" void openmc_set_seed(int64_t new_seed); +} // namespace openmc #endif // RANDOM_LCG_H diff --git a/src/relaxng/settings.rnc b/src/relaxng/settings.rnc index 19a2948c58..282c685db1 100644 --- a/src/relaxng/settings.rnc +++ b/src/relaxng/settings.rnc @@ -3,6 +3,8 @@ element settings { element confidence_intervals { xsd:boolean }? & + element create_fission_neutrons { xsd:boolean }? & + element cutoff { (element weight { xsd:double } | attribute weight { xsd:double })? & (element weight_avg { xsd:double } | attribute weight_avg { xsd:double })? diff --git a/src/relaxng/settings.rng b/src/relaxng/settings.rng index 606b978290..0018cb16bd 100644 --- a/src/relaxng/settings.rng +++ b/src/relaxng/settings.rng @@ -11,6 +11,11 @@ + + + + + diff --git a/src/relaxng/tallies.rnc b/src/relaxng/tallies.rnc index 5ab8971e6c..204284c480 100644 --- a/src/relaxng/tallies.rnc +++ b/src/relaxng/tallies.rnc @@ -35,14 +35,14 @@ element tallies { element filter { (element id { xsd:int } | attribute id { xsd:int }) & ( - ( (element type { ( "cell" | "cellfrom" | "cellborn" | "material" | - "universe" | "surface" | "distribcell" | "mesh" | "energy" | - "energyout" | "mu" | "polar" | "azimuthal" | "delayedgroup" | - "energyfunction") } | - attribute type { ( "cell" | "cellfrom" | "cellborn" | "material" | - "universe" | "surface" | "distribcell" | "mesh" | "energy" | - "energyout" | "mu" | "polar" | "azimuthal" | "delayedgroup" | - "energyfunction") }) & + ( (element type { ( "cell" | "cellfrom" | "cellborn" | "material" | + "universe" | "surface" | "distribcell" | "mesh" | "energy" | + "energyout" | "mu" | "polar" | "azimuthal" | "delayedgroup" | + "energyfunction" | "meshsurface") } | + attribute type { ( "cell" | "cellfrom" | "cellborn" | "material" | + "universe" | "surface" | "distribcell" | "mesh" | "energy" | + "energyout" | "mu" | "polar" | "azimuthal" | "delayedgroup" | + "energyfunction" | "meshsurface") }) & (element bins { list { xsd:double+ } } | attribute bins { list { xsd:double+ } }) ) | diff --git a/src/relaxng/tallies.rng b/src/relaxng/tallies.rng index bad2fdce91..15b6f5b249 100644 --- a/src/relaxng/tallies.rng +++ b/src/relaxng/tallies.rng @@ -182,6 +182,7 @@ azimuthal delayedgroup energyfunction + meshsurface @@ -201,6 +202,7 @@ azimuthal delayedgroup energyfunction + meshsurface diff --git a/src/sab_header.F90 b/src/sab_header.F90 index 6dd617790b..eca8e555a1 100644 --- a/src/sab_header.F90 +++ b/src/sab_header.F90 @@ -3,7 +3,7 @@ module sab_header use, intrinsic :: ISO_C_BINDING use, intrinsic :: ISO_FORTRAN_ENV - use algorithm, only: find, sort + use algorithm, only: find, sort, binary_search use constants use dict_header, only: DictIntInt, DictCharInt use distribution_univariate, only: Tabular @@ -12,7 +12,9 @@ module sab_header use hdf5_interface, only: read_attribute, get_shape, open_group, close_group, & open_dataset, read_dataset, close_dataset, get_datasets, object_exists, & get_name + use random_lcg, only: prn use secondary_correlated, only: CorrelatedAngleEnergy + use settings use stl_vector, only: VectorInt, VectorReal use string, only: to_str, str_to_int @@ -77,6 +79,7 @@ module sab_header type(SabData), allocatable :: data(:) contains procedure :: from_hdf5 => salphabeta_from_hdf5 + procedure :: calculate_xs => sab_calculate_xs end type SAlphaBeta ! S(a,b) tables @@ -360,6 +363,104 @@ contains call close_group(kT_group) end subroutine salphabeta_from_hdf5 +!=============================================================================== +! SAB_CALCULATE_XS determines the elastic and inelastic scattering +! cross-sections in the thermal energy range. +!=============================================================================== + + subroutine sab_calculate_xs(this, E, sqrtkT, i_temp, elastic, inelastic) + class(SAlphaBeta), intent(in) :: this ! S(a,b) object + real(8), intent(in) :: E ! energy + real(8), intent(in) :: sqrtkT ! temperature + integer, intent(out) :: i_temp ! index in the S(a,b)'s temperature + real(8), intent(out) :: elastic ! thermal elastic cross section + real(8), intent(out) :: inelastic ! thermal inelastic cross section + + integer :: i_grid ! index on S(a,b) energy grid + real(8) :: f ! interp factor on S(a,b) energy grid + real(8) :: kT + + ! Determine temperature for S(a,b) table + kT = sqrtkT**2 + if (temperature_method == TEMPERATURE_NEAREST) then + ! If using nearest temperature, do linear search on temperature + do i_temp = 1, size(this % kTs) + if (abs(this % kTs(i_temp) - kT) < & + K_BOLTZMANN*temperature_tolerance) exit + end do + else + ! Find temperatures that bound the actual temperature + do i_temp = 1, size(this % kTs) - 1 + if (this % kTs(i_temp) <= kT .and. & + kT < this % kTs(i_temp + 1)) exit + end do + + ! Randomly sample between temperature i and i+1 + f = (kT - this % kTs(i_temp)) / & + (this % kTs(i_temp + 1) - this % kTs(i_temp)) + if (f > prn()) i_temp = i_temp + 1 + end if + + + ! Get pointer to S(a,b) table + associate (sab => this % data(i_temp)) + + ! Get index and interpolation factor for inelastic grid + if (E < sab % inelastic_e_in(1)) then + i_grid = 1 + f = ZERO + else + i_grid = binary_search(sab % inelastic_e_in, sab % n_inelastic_e_in, E) + f = (E - sab%inelastic_e_in(i_grid)) / & + (sab%inelastic_e_in(i_grid+1) - sab%inelastic_e_in(i_grid)) + end if + + ! Calculate S(a,b) inelastic scattering cross section + inelastic = (ONE - f) * sab % inelastic_sigma(i_grid) + & + f * sab % inelastic_sigma(i_grid + 1) + + ! Check for elastic data + if (E < sab % threshold_elastic) then + ! Determine whether elastic scattering is given in the coherent or + ! incoherent approximation. For coherent, the cross section is + ! represented as P/E whereas for incoherent, it is simply P + + if (sab % elastic_mode == SAB_ELASTIC_EXACT) then + if (E < sab % elastic_e_in(1)) then + ! If energy is below that of the lowest Bragg peak, the elastic + ! cross section will be zero + elastic = ZERO + else + i_grid = binary_search(sab % elastic_e_in, & + sab % n_elastic_e_in, E) + elastic = sab % elastic_P(i_grid) / E + end if + else + ! Determine index on elastic energy grid + if (E < sab % elastic_e_in(1)) then + i_grid = 1 + else + i_grid = binary_search(sab % elastic_e_in, & + sab % n_elastic_e_in, E) + end if + + ! Get interpolation factor for elastic grid + f = (E - sab%elastic_e_in(i_grid))/(sab%elastic_e_in(i_grid+1) - & + sab%elastic_e_in(i_grid)) + + ! Calculate S(a,b) elastic scattering cross section + elastic = (ONE - f) * sab % elastic_P(i_grid) + & + f * sab % elastic_P(i_grid + 1) + end if + else + ! No elastic data + elastic = ZERO + end if + end associate + + end subroutine sab_calculate_xs + + !=============================================================================== ! FREE_MEMORY_SAB deallocates global arrays defined in this module !=============================================================================== diff --git a/src/simulation.F90 b/src/simulation.F90 index e86ea960f3..e1a1dcc750 100644 --- a/src/simulation.F90 +++ b/src/simulation.F90 @@ -294,8 +294,6 @@ contains if (master .and. verbosity >= 7) then if (current_gen /= gen_per_batch) then call print_generation() - else - call print_batch_keff() end if end if @@ -320,7 +318,7 @@ contains subroutine finalize_batch() -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif @@ -338,11 +336,13 @@ contains if (run_mode == MODE_EIGENVALUE) then ! Perform CMFD calculation if on if (cmfd_on) call execute_cmfd() + ! Write batch output + if (master .and. verbosity >= 7) call print_batch_keff() end if ! Check_triggers if (master) call check_triggers() -#ifdef MPI +#ifdef OPENMC_MPI call MPI_BCAST(satisfy_triggers, 1, MPI_LOGICAL, 0, & mpi_intracomm, mpi_err) #endif @@ -434,6 +434,13 @@ contains allocate(filter_matches(n_filters)) !$omp end parallel + ! Reset global variables -- this is done before loading state point (as that + ! will potentially populate k_generation and entropy) + current_batch = 0 + call k_generation % clear() + call entropy % clear() + need_depletion_rx = .false. + ! If this is a restart run, load the state point data and binary source ! file if (restart_run) then @@ -452,10 +459,6 @@ contains end if end if - ! Reset global variables - current_batch = 0 - need_depletion_rx = .false. - ! Set flag indicating initialization is done simulation_initialized = .true. @@ -469,11 +472,17 @@ contains subroutine openmc_simulation_finalize() bind(C) integer :: i ! loop index -#ifdef MPI +#ifdef OPENMC_MPI integer :: n ! size of arrays integer :: mpi_err ! MPI error code + integer :: count_per_filter ! number of result values for one filter bin integer(8) :: temp real(8) :: tempr(3) ! temporary array for communication +#ifdef OPENMC_MPIF08 + type(MPI_Datatype) :: result_block +#else + integer :: result_block +#endif #endif ! Skip if simulation was never run @@ -494,13 +503,28 @@ contains ! Increment total number of generations total_gen = total_gen + current_batch*gen_per_batch -#ifdef MPI +#ifdef OPENMC_MPI ! Broadcast tally results so that each process has access to results if (allocated(tallies)) then do i = 1, size(tallies) - !n = size(tallies(i) % obj % results) - !call MPI_BCAST(tallies(i) % obj % results, n, MPI_DOUBLE, 0, & - ! mpi_intracomm, mpi_err) +<<<<<<< HEAD + n = size(tallies(i) % obj % results) + call MPI_BCAST(tallies(i) % obj % results, n, MPI_DOUBLE, 0, & + mpi_intracomm, mpi_err) +======= + associate (results => tallies(i) % obj % results) + ! Create a new datatype that consists of all values for a given filter + ! bin and then use that to broadcast. This is done to minimize the + ! chance of the 'count' argument of MPI_BCAST exceeding 2**31 + n = size(results, 3) + count_per_filter = size(results, 1) * size(results, 2) + call MPI_TYPE_CONTIGUOUS(count_per_filter, MPI_DOUBLE, & + result_block, mpi_err) + call MPI_TYPE_COMMIT(result_block, mpi_err) + call MPI_BCAST(results, n, result_block, 0, mpi_intracomm, mpi_err) + call MPI_TYPE_FREE(result_block, mpi_err) + end associate +>>>>>>> 47fbf8282ea94c138f75219bd10fdb31501d3fb7 end do end if diff --git a/src/source.F90 b/src/source.F90 index 557120e979..5beecd8870 100644 --- a/src/source.F90 +++ b/src/source.F90 @@ -1,7 +1,7 @@ module source use hdf5, only: HID_T -#ifdef MPI +#ifdef OPENMC_MPI use message_passing #endif diff --git a/src/state_point.F90 b/src/state_point.F90 index f7a8928987..980a7333cd 100644 --- a/src/state_point.F90 +++ b/src/state_point.F90 @@ -26,7 +26,7 @@ module state_point use mgxs_header, only: nuclides_MG use nuclide_header, only: nuclides use output, only: time_stamp - use random_lcg, only: seed + use random_lcg, only: openmc_get_seed, openmc_set_seed use settings use simulation_header use string, only: to_str, count_digits, zero_padded, to_f_string @@ -97,7 +97,7 @@ contains call write_attribute(file_id, "path", path_input) ! Write out random number seed - call write_dataset(file_id, "seed", seed) + call write_dataset(file_id, "seed", openmc_get_seed()) ! Write run information if (run_CE) then @@ -523,7 +523,7 @@ contains integer(HID_T) :: tallies_group, tally_group real(8), allocatable :: tally_temp(:,:,:) ! contiguous array of results real(8), target :: global_temp(3,N_GLOBAL_TALLIES) -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code real(8) :: dummy ! temporary receive buffer for non-root reduces #endif @@ -543,7 +543,7 @@ contains end if -#ifdef MPI +#ifdef OPENMC_MPI ! Reduce global tallies n_bins = size(global_tallies) call MPI_REDUCE(global_tallies, global_temp, n_bins, MPI_REAL8, MPI_SUM, & @@ -586,7 +586,7 @@ contains ! The MPI_IN_PLACE specifier allows the master to copy values into ! a receive buffer without having a temporary variable -#ifdef MPI +#ifdef OPENMC_MPI call MPI_REDUCE(MPI_IN_PLACE, tally_temp, n_bins, MPI_REAL8, & MPI_SUM, 0, mpi_intracomm, mpi_err) #endif @@ -610,7 +610,7 @@ contains deallocate(dummy_tally % results) else ! Receive buffer not significant at other processors -#ifdef MPI +#ifdef OPENMC_MPI call MPI_REDUCE(tally_temp, dummy, n_bins, MPI_REAL8, MPI_SUM, & 0, mpi_intracomm, mpi_err) #endif @@ -642,6 +642,7 @@ contains integer :: n integer :: int_array(3) integer, allocatable :: array(:) + integer(C_INT64_T) :: seed integer(HID_T) :: file_id integer(HID_T) :: cmfd_group integer(HID_T) :: tallies_group @@ -672,6 +673,7 @@ contains ! Read and overwrite random number seed call read_dataset(seed, file_id, "seed") + call openmc_set_seed(seed) ! It is not impossible for a state point to be generated from a CE run but ! to be loaded in to an MG run (or vice versa), check to prevent that. @@ -849,7 +851,7 @@ contains integer(HID_T) :: plist ! property list #else integer :: i -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code type(Bank), allocatable, target :: temp_source(:) #endif @@ -897,7 +899,7 @@ contains dspace, dset, hdf5_err) ! Save source bank sites since the souce_bank array is overwritten below -#ifdef MPI +#ifdef OPENMC_MPI allocate(temp_source(work)) temp_source(:) = source_bank(:) #endif @@ -907,7 +909,7 @@ contains dims(1) = work_index(i+1) - work_index(i) call h5screate_simple_f(1, dims, memspace, hdf5_err) -#ifdef MPI +#ifdef OPENMC_MPI ! Receive source sites from other processes if (i > 0) then call MPI_RECV(source_bank, int(dims(1)), MPI_BANK, i, i, & @@ -933,12 +935,12 @@ contains call h5dclose_f(dset, hdf5_err) ! Restore state of source bank -#ifdef MPI +#ifdef OPENMC_MPI source_bank(:) = temp_source(:) deallocate(temp_source) #endif else -#ifdef MPI +#ifdef OPENMC_MPI call MPI_SEND(source_bank, int(work), MPI_BANK, 0, rank, & mpi_intracomm, mpi_err) #endif diff --git a/src/summary.F90 b/src/summary.F90 index 0f45ef1bbd..3aeb42178b 100644 --- a/src/summary.F90 +++ b/src/summary.F90 @@ -122,13 +122,11 @@ contains real(8), allocatable :: cell_temperatures(:) integer(HID_T) :: geom_group integer(HID_T) :: cells_group, cell_group - integer(HID_T) :: surfaces_group, surface_group + integer(HID_T) :: surfaces_group integer(HID_T) :: universes_group, univ_group integer(HID_T) :: lattices_group, lattice_group - real(8), allocatable :: coeffs(:) character(:), allocatable :: region_spec type(Cell), pointer :: c - class(Surface), pointer :: s class(Lattice), pointer :: lat ! Use H5LT interface to write number of geometry objects @@ -223,7 +221,7 @@ contains region_spec = trim(region_spec) // " |" case default region_spec = trim(region_spec) // " " // to_str(& - sign(surfaces(abs(k))%obj%id, k)) + sign(surfaces(abs(k))%id(), k)) end select end do call write_dataset(cell_group, "region", adjustl(region_spec)) @@ -241,92 +239,7 @@ contains ! Write information on each surface SURFACE_LOOP: do i = 1, n_surfaces - s => surfaces(i)%obj - surface_group = create_group(surfaces_group, "surface " // & - trim(to_str(s%id))) - - ! Write name for this surface - call write_dataset(surface_group, "name", s%name) - - ! Write surface type - select type (s) - type is (SurfaceXPlane) - call write_dataset(surface_group, "type", "x-plane") - allocate(coeffs(1)) - coeffs(1) = s%x0 - - type is (SurfaceYPlane) - call write_dataset(surface_group, "type", "y-plane") - allocate(coeffs(1)) - coeffs(1) = s%y0 - - type is (SurfaceZPlane) - call write_dataset(surface_group, "type", "z-plane") - allocate(coeffs(1)) - coeffs(1) = s%z0 - - type is (SurfacePlane) - call write_dataset(surface_group, "type", "plane") - allocate(coeffs(4)) - coeffs(:) = [s%A, s%B, s%C, s%D] - - type is (SurfaceXCylinder) - call write_dataset(surface_group, "type", "x-cylinder") - allocate(coeffs(3)) - coeffs(:) = [s%y0, s%z0, s%r] - - type is (SurfaceYCylinder) - call write_dataset(surface_group, "type", "y-cylinder") - allocate(coeffs(3)) - coeffs(:) = [s%x0, s%z0, s%r] - - type is (SurfaceZCylinder) - call write_dataset(surface_group, "type", "z-cylinder") - allocate(coeffs(3)) - coeffs(:) = [s%x0, s%y0, s%r] - - type is (SurfaceSphere) - call write_dataset(surface_group, "type", "sphere") - allocate(coeffs(4)) - coeffs(:) = [s%x0, s%y0, s%z0, s%r] - - type is (SurfaceXCone) - call write_dataset(surface_group, "type", "x-cone") - allocate(coeffs(4)) - coeffs(:) = [s%x0, s%y0, s%z0, s%r2] - - type is (SurfaceYCone) - call write_dataset(surface_group, "type", "y-cone") - allocate(coeffs(4)) - coeffs(:) = [s%x0, s%y0, s%z0, s%r2] - - type is (SurfaceZCone) - call write_dataset(surface_group, "type", "z-cone") - allocate(coeffs(4)) - coeffs(:) = [s%x0, s%y0, s%z0, s%r2] - - type is (SurfaceQuadric) - call write_dataset(surface_group, "type", "quadric") - allocate(coeffs(10)) - coeffs(:) = [s%A, s%B, s%C, s%D, s%E, s%F, s%G, s%H, s%J, s%K] - - end select - call write_dataset(surface_group, "coefficients", coeffs) - deallocate(coeffs) - - ! Write boundary type - select case (s%bc) - case (BC_TRANSMIT) - call write_dataset(surface_group, "boundary_type", "transmission") - case (BC_VACUUM) - call write_dataset(surface_group, "boundary_type", "vacuum") - case (BC_REFLECT) - call write_dataset(surface_group, "boundary_type", "reflective") - case (BC_PERIODIC) - call write_dataset(surface_group, "boundary_type", "periodic") - end select - - call close_group(surface_group) + call surfaces(i) % to_hdf5(surfaces_group) end do SURFACE_LOOP call close_group(surfaces_group) diff --git a/src/surface.cpp b/src/surface.cpp new file mode 100644 index 0000000000..9abfd23d2e --- /dev/null +++ b/src/surface.cpp @@ -0,0 +1,1235 @@ +#include "surface.h" + +#include +#include +#include + +#include "error.h" +#include "hdf5_interface.h" +#include "xml_interface.h" + + +namespace openmc { + +//============================================================================== +// Helper functions for reading the "coeffs" node of an XML surface element +//============================================================================== + +int word_count(const std::string &text) +{ + bool in_word = false; + int count {0}; + for (auto c = text.begin(); c != text.end(); c++) { + if (std::isspace(*c)) { + if (in_word) { + in_word = false; + count++; + } + } else { + in_word = true; + } + } + if (in_word) count++; + return count; +} + +void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1) +{ + // Check the given number of coefficients. + std::string coeffs = get_node_value(surf_node, "coeffs"); + int n_words = word_count(coeffs); + if (n_words != 1) { + std::stringstream err_msg; + err_msg << "Surface " << surf_id << " expects 1 coeff but was given " + << n_words; + fatal_error(err_msg); + } + + // Parse the coefficients. + int stat = sscanf(coeffs.c_str(), "%lf", &c1); + if (stat != 1) { + fatal_error("Something went wrong reading surface coeffs"); + } +} + +void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, + double &c3) +{ + // Check the given number of coefficients. + std::string coeffs = get_node_value(surf_node, "coeffs"); + int n_words = word_count(coeffs); + if (n_words != 3) { + std::stringstream err_msg; + err_msg << "Surface " << surf_id << " expects 3 coeffs but was given " + << n_words; + fatal_error(err_msg); + } + + // Parse the coefficients. + int stat = sscanf(coeffs.c_str(), "%lf %lf %lf", &c1, &c2, &c3); + if (stat != 3) { + fatal_error("Something went wrong reading surface coeffs"); + } +} + +void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, + double &c3, double &c4) +{ + // Check the given number of coefficients. + std::string coeffs = get_node_value(surf_node, "coeffs"); + int n_words = word_count(coeffs); + if (n_words != 4) { + std::stringstream err_msg; + err_msg << "Surface " << surf_id << " expects 4 coeffs but was given " + << n_words; + fatal_error(err_msg); + } + + // Parse the coefficients. + int stat = sscanf(coeffs.c_str(), "%lf %lf %lf %lf", &c1, &c2, &c3, &c4); + if (stat != 4) { + fatal_error("Something went wrong reading surface coeffs"); + } +} + +void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, + double &c3, double &c4, double &c5, double &c6, double &c7, + double &c8, double &c9, double &c10) +{ + // Check the given number of coefficients. + std::string coeffs = get_node_value(surf_node, "coeffs"); + int n_words = word_count(coeffs); + if (n_words != 10) { + std::stringstream err_msg; + err_msg << "Surface " << surf_id << " expects 10 coeffs but was given " + << n_words; + fatal_error(err_msg); + } + + // Parse the coefficients. + int stat = sscanf(coeffs.c_str(), "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", + &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9, &c10); + if (stat != 10) { + fatal_error("Something went wrong reading surface coeffs"); + } +} + +//============================================================================== +// Surface implementation +//============================================================================== + +Surface::Surface(pugi::xml_node surf_node) +{ + if (check_for_node(surf_node, "id")) { + id = stoi(get_node_value(surf_node, "id")); + } else { + fatal_error("Must specify id of surface in geometry XML file."); + } + + if (check_for_node(surf_node, "name")) { + name = get_node_value(surf_node, "name"); + } + + if (check_for_node(surf_node, "boundary")) { + std::string surf_bc = get_node_value(surf_node, "boundary"); + + if (surf_bc == "transmission" || surf_bc == "transmit" ||surf_bc.empty()) { + bc = BC_TRANSMIT; + + } else if (surf_bc == "vacuum") { + bc = BC_VACUUM; + + } else if (surf_bc == "reflective" || surf_bc == "reflect" + || surf_bc == "reflecting") { + bc = BC_REFLECT; + } else if (surf_bc == "periodic") { + bc = BC_PERIODIC; + } else { + std::stringstream err_msg; + err_msg << "Unknown boundary condition \"" << surf_bc + << "\" specified on surface " << id; + fatal_error(err_msg); + } + + } else { + bc = BC_TRANSMIT; + } + +} + +bool +Surface::sense(const double xyz[3], const double uvw[3]) const +{ + // Evaluate the surface equation at the particle's coordinates to determine + // which side the particle is on. + const double f = evaluate(xyz); + + // Check which side of surface the point is on. + if (std::abs(f) < FP_COINCIDENT) { + // Particle may be coincident with this surface. To determine the sense, we + // look at the direction of the particle relative to the surface normal (by + // default in the positive direction) via their dot product. + double norm[3]; + normal(xyz, norm); + return uvw[0] * norm[0] + uvw[1] * norm[1] + uvw[2] * norm[2] > 0.0; + } + return f > 0.0; +} + +void +Surface::reflect(const double xyz[3], double uvw[3]) const +{ + // Determine projection of direction onto normal and squared magnitude of + // normal. + double norm[3]; + normal(xyz, norm); + const double projection = norm[0]*uvw[0] + norm[1]*uvw[1] + norm[2]*uvw[2]; + const double magnitude = norm[0]*norm[0] + norm[1]*norm[1] + norm[2]*norm[2]; + + // Reflect direction according to normal. + uvw[0] -= 2.0 * projection / magnitude * norm[0]; + uvw[1] -= 2.0 * projection / magnitude * norm[1]; + uvw[2] -= 2.0 * projection / magnitude * norm[2]; +} + +void +Surface::to_hdf5(hid_t group_id) const +{ + std::string group_name {"surface "}; + group_name += std::to_string(id); + + hid_t surf_group = create_group(group_id, group_name); + + switch(bc) { + case BC_TRANSMIT : + write_string(surf_group, "boundary_type", "transmission"); + break; + case BC_VACUUM : + write_string(surf_group, "boundary_type", "vacuum"); + break; + case BC_REFLECT : + write_string(surf_group, "boundary_type", "reflective"); + break; + case BC_PERIODIC : + write_string(surf_group, "boundary_type", "periodic"); + break; + } + + if (!name.empty()) { + write_string(surf_group, "name", name); + } + + to_hdf5_inner(surf_group); + + close_group(surf_group); +} + +//============================================================================== +// PeriodicSurface implementation +//============================================================================== + +PeriodicSurface::PeriodicSurface(pugi::xml_node surf_node) + : Surface {surf_node} +{ + if (check_for_node(surf_node, "periodic_surface_id")) { + i_periodic = stoi(get_node_value(surf_node, "periodic_surface_id")); + } +} + +//============================================================================== +// Generic functions for x-, y-, and z-, planes. +//============================================================================== + +// The template parameter indicates the axis normal to the plane. +template double +axis_aligned_plane_evaluate(const double xyz[3], double offset) +{ + return xyz[i] - offset; +} + +// The template parameter indicates the axis normal to the plane. +template double +axis_aligned_plane_distance(const double xyz[3], const double uvw[3], + bool coincident, double offset) +{ + const double f = offset - xyz[i]; + if (coincident or std::abs(f) < FP_COINCIDENT or uvw[i] == 0.0) return INFTY; + const double d = f / uvw[i]; + if (d < 0.0) return INFTY; + return d; +} + +// The first template parameter indicates the axis normal to the plane. The +// other two parameters indicate the other two axes. +template void +axis_aligned_plane_normal(const double xyz[3], double uvw[3]) +{ + uvw[i1] = 1.0; + uvw[i2] = 0.0; + uvw[i3] = 0.0; +} + +//============================================================================== +// SurfaceXPlane implementation +//============================================================================== + +SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) + : PeriodicSurface(surf_node) +{ + read_coeffs(surf_node, id, x0); +} + +inline double SurfaceXPlane::evaluate(const double xyz[3]) const +{ + return axis_aligned_plane_evaluate<0>(xyz, x0); +} + +inline double SurfaceXPlane::distance(const double xyz[3], const double uvw[3], + bool coincident) const +{ + return axis_aligned_plane_distance<0>(xyz, uvw, coincident, x0); +} + +inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const +{ + axis_aligned_plane_normal<0, 1, 2>(xyz, uvw); +} + +void SurfaceXPlane::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "x-plane"); + std::array coeffs {{x0}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +bool SurfaceXPlane::periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const +{ + double other_norm[3]; + other->normal(xyz, other_norm); + if (other_norm[0] == 1 and other_norm[1] == 0 and other_norm[2] == 0) { + xyz[0] = x0; + return false; + } else { + // Assume the partner is an YPlane (the only supported partner). Use the + // evaluate function to find y0, then adjust xyz and uvw for rotational + // symmetry. + double xyz_test[3] {0, 0, 0}; + double y0 = -other->evaluate(xyz_test); + xyz[1] = xyz[0] - x0 + y0; + xyz[0] = x0; + + double u = uvw[0]; + uvw[0] = -uvw[1]; + uvw[1] = u; + + return true; + } +} + +BoundingBox +SurfaceXPlane::bounding_box() const +{ + BoundingBox out {x0, x0, -INFTY, INFTY, -INFTY, INFTY}; + return out; +} + +//============================================================================== +// SurfaceYPlane implementation +//============================================================================== + +SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) + : PeriodicSurface(surf_node) +{ + read_coeffs(surf_node, id, y0); +} + +inline double SurfaceYPlane::evaluate(const double xyz[3]) const +{ + return axis_aligned_plane_evaluate<1>(xyz, y0); +} + +inline double SurfaceYPlane::distance(const double xyz[3], const double uvw[3], + bool coincident) const +{ + return axis_aligned_plane_distance<1>(xyz, uvw, coincident, y0); +} + +inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const +{ + axis_aligned_plane_normal<1, 0, 2>(xyz, uvw); +} + +void SurfaceYPlane::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "y-plane"); + std::array coeffs {{y0}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +bool SurfaceYPlane::periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const +{ + double other_norm[3]; + other->normal(xyz, other_norm); + if (other_norm[0] == 0 and other_norm[1] == 1 and other_norm[2] == 0) { + // The periodic partner is also aligned along y. Just change the y coord. + xyz[1] = y0; + return false; + } else { + // Assume the partner is an XPlane (the only supported partner). Use the + // evaluate function to find x0, then adjust xyz and uvw for rotational + // symmetry. + double xyz_test[3] {0, 0, 0}; + double x0 = -other->evaluate(xyz_test); + xyz[0] = xyz[1] - y0 + x0; + xyz[1] = y0; + + double u = uvw[0]; + uvw[0] = uvw[1]; + uvw[1] = -u; + + return true; + } +} + +BoundingBox +SurfaceYPlane::bounding_box() const +{ + BoundingBox out {-INFTY, INFTY, y0, y0, -INFTY, INFTY}; + return out; +} + +//============================================================================== +// SurfaceZPlane implementation +//============================================================================== + +SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) + : PeriodicSurface(surf_node) +{ + read_coeffs(surf_node, id, z0); +} + +inline double SurfaceZPlane::evaluate(const double xyz[3]) const +{ + return axis_aligned_plane_evaluate<2>(xyz, z0); +} + +inline double SurfaceZPlane::distance(const double xyz[3], const double uvw[3], + bool coincident) const +{ + return axis_aligned_plane_distance<2>(xyz, uvw, coincident, z0); +} + +inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const +{ + axis_aligned_plane_normal<2, 0, 1>(xyz, uvw); +} + +void SurfaceZPlane::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "z-plane"); + std::array coeffs {{z0}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +bool SurfaceZPlane::periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const +{ + // Assume the other plane is aligned along z. Just change the z coord. + xyz[2] = z0; + return false; +} + +BoundingBox +SurfaceZPlane::bounding_box() const +{ + BoundingBox out {-INFTY, INFTY, -INFTY, INFTY, z0, z0}; + return out; +} + +//============================================================================== +// SurfacePlane implementation +//============================================================================== + +SurfacePlane::SurfacePlane(pugi::xml_node surf_node) + : PeriodicSurface(surf_node) +{ + read_coeffs(surf_node, id, A, B, C, D); +} + +double +SurfacePlane::evaluate(const double xyz[3]) const +{ + return A*xyz[0] + B*xyz[1] + C*xyz[2] - D; +} + +double +SurfacePlane::distance(const double xyz[3], const double uvw[3], + bool coincident) const +{ + const double f = A*xyz[0] + B*xyz[1] + C*xyz[2] - D; + const double projection = A*uvw[0] + B*uvw[1] + C*uvw[2]; + if (coincident or std::abs(f) < FP_COINCIDENT or projection == 0.0) { + return INFTY; + } else { + const double d = -f / projection; + if (d < 0.0) return INFTY; + return d; + } +} + +void +SurfacePlane::normal(const double xyz[3], double uvw[3]) const +{ + uvw[0] = A; + uvw[1] = B; + uvw[2] = C; +} + +void SurfacePlane::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "plane"); + std::array coeffs {{A, B, C, D}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +bool SurfacePlane::periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const +{ + // This function assumes the other plane shares this plane's normal direction. + + // Determine the distance to intersection. + double d = evaluate(xyz) / (A*A + B*B + C*C); + + // Move the particle that distance along the normal vector. + xyz[0] -= d * A; + xyz[1] -= d * B; + xyz[2] -= d * C; + + return false; +} + +BoundingBox +SurfacePlane::bounding_box() const +{ + BoundingBox out {-INFTY, INFTY, -INFTY, INFTY, -INFTY, INFTY}; + return out; +} + +//============================================================================== +// Generic functions for x-, y-, and z-, cylinders +//============================================================================== + +// The template parameters indicate the axes perpendicular to the axis of the +// cylinder. offset1 and offset2 should correspond with i1 and i2, +// respectively. +template double +axis_aligned_cylinder_evaluate(const double xyz[3], double offset1, + double offset2, double radius) +{ + const double xyz1 = xyz[i1] - offset1; + const double xyz2 = xyz[i2] - offset2; + return xyz1*xyz1 + xyz2*xyz2 - radius*radius; +} + +// The first template parameter indicates which axis the cylinder is aligned to. +// The other two parameters indicate the other two axes. offset1 and offset2 +// should correspond with i2 and i3, respectively. +template double +axis_aligned_cylinder_distance(const double xyz[3], const double uvw[3], + bool coincident, double offset1, double offset2, double radius) +{ + const double a = 1.0 - uvw[i1]*uvw[i1]; // u^2 + v^2 + if (a == 0.0) return INFTY; + + const double xyz2 = xyz[i2] - offset1; + const double xyz3 = xyz[i3] - offset2; + const double k = xyz2 * uvw[i2] + xyz3 * uvw[i3]; + const double c = xyz2*xyz2 + xyz3*xyz3 - radius*radius; + const double quad = k*k - a*c; + + if (quad < 0.0) { + // No intersection with cylinder. + return INFTY; + + } else if (coincident or std::abs(c) < FP_COINCIDENT) { + // Particle is on the cylinder, thus one distance is positive/negative + // and the other is zero. The sign of k determines if we are facing in or + // out. + if (k >= 0.0) { + return INFTY; + } else { + return (-k + sqrt(quad)) / a; + } + + } else if (c < 0.0) { + // Particle is inside the cylinder, thus one distance must be negative + // and one must be positive. The positive distance will be the one with + // negative sign on sqrt(quad). + return (-k + sqrt(quad)) / a; + + } else { + // Particle is outside the cylinder, thus both distances are either + // positive or negative. If positive, the smaller distance is the one + // with positive sign on sqrt(quad). + const double d = (-k - sqrt(quad)) / a; + if (d < 0.0) return INFTY; + return d; + } +} + +// The first template parameter indicates which axis the cylinder is aligned to. +// The other two parameters indicate the other two axes. offset1 and offset2 +// should correspond with i2 and i3, respectively. +template void +axis_aligned_cylinder_normal(const double xyz[3], double uvw[3], double offset1, + double offset2) +{ + uvw[i2] = 2.0 * (xyz[i2] - offset1); + uvw[i3] = 2.0 * (xyz[i3] - offset2); + uvw[i1] = 0.0; +} + +//============================================================================== +// SurfaceXCylinder implementation +//============================================================================== + +SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) + : Surface(surf_node) +{ + read_coeffs(surf_node, id, y0, z0, r); +} + +inline double SurfaceXCylinder::evaluate(const double xyz[3]) const +{ + return axis_aligned_cylinder_evaluate<1, 2>(xyz, y0, z0, r); +} + +inline double SurfaceXCylinder::distance(const double xyz[3], + const double uvw[3], bool coincident) const +{ + return axis_aligned_cylinder_distance<0, 1, 2>(xyz, uvw, coincident, y0, z0, + r); +} + +inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const +{ + axis_aligned_cylinder_normal<0, 1, 2>(xyz, uvw, y0, z0); +} + + +void SurfaceXCylinder::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "x-cylinder"); + std::array coeffs {{y0, z0, r}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +//============================================================================== +// SurfaceYCylinder implementation +//============================================================================== + +SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) + : Surface(surf_node) +{ + read_coeffs(surf_node, id, x0, z0, r); +} + +inline double SurfaceYCylinder::evaluate(const double xyz[3]) const +{ + return axis_aligned_cylinder_evaluate<0, 2>(xyz, x0, z0, r); +} + +inline double SurfaceYCylinder::distance(const double xyz[3], + const double uvw[3], bool coincident) const +{ + return axis_aligned_cylinder_distance<1, 0, 2>(xyz, uvw, coincident, x0, z0, + r); +} + +inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const +{ + axis_aligned_cylinder_normal<1, 0, 2>(xyz, uvw, x0, z0); +} + +void SurfaceYCylinder::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "y-cylinder"); + std::array coeffs {{x0, z0, r}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +//============================================================================== +// SurfaceZCylinder implementation +//============================================================================== + +SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) + : Surface(surf_node) +{ + read_coeffs(surf_node, id, x0, y0, r); +} + +inline double SurfaceZCylinder::evaluate(const double xyz[3]) const +{ + return axis_aligned_cylinder_evaluate<0, 1>(xyz, x0, y0, r); +} + +inline double SurfaceZCylinder::distance(const double xyz[3], + const double uvw[3], bool coincident) const +{ + return axis_aligned_cylinder_distance<2, 0, 1>(xyz, uvw, coincident, x0, y0, + r); +} + +inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const +{ + axis_aligned_cylinder_normal<2, 0, 1>(xyz, uvw, x0, y0); +} + +void SurfaceZCylinder::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "z-cylinder"); + std::array coeffs {{x0, y0, r}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +//============================================================================== +// SurfaceSphere implementation +//============================================================================== + +SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) + : Surface(surf_node) +{ + read_coeffs(surf_node, id, x0, y0, z0, r); +} + +double SurfaceSphere::evaluate(const double xyz[3]) const +{ + const double x = xyz[0] - x0; + const double y = xyz[1] - y0; + const double z = xyz[2] - z0; + return x*x + y*y + z*z - r*r; +} + +double SurfaceSphere::distance(const double xyz[3], const double uvw[3], + bool coincident) const +{ + const double x = xyz[0] - x0; + const double y = xyz[1] - y0; + const double z = xyz[2] - z0; + const double k = x*uvw[0] + y*uvw[1] + z*uvw[2]; + const double c = x*x + y*y + z*z - r*r; + const double quad = k*k - c; + + if (quad < 0.0) { + // No intersection with sphere. + return INFTY; + + } else if (coincident or std::abs(c) < FP_COINCIDENT) { + // Particle is on the sphere, thus one distance is positive/negative and + // the other is zero. The sign of k determines if we are facing in or out. + if (k >= 0.0) { + return INFTY; + } else { + return -k + sqrt(quad); + } + + } else if (c < 0.0) { + // Particle is inside the sphere, thus one distance must be negative and + // one must be positive. The positive distance will be the one with + // negative sign on sqrt(quad) + return -k + sqrt(quad); + + } else { + // Particle is outside the sphere, thus both distances are either positive + // or negative. If positive, the smaller distance is the one with positive + // sign on sqrt(quad). + const double d = -k - sqrt(quad); + if (d < 0.0) return INFTY; + return d; + } +} + +inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const +{ + uvw[0] = 2.0 * (xyz[0] - x0); + uvw[1] = 2.0 * (xyz[1] - y0); + uvw[2] = 2.0 * (xyz[2] - z0); +} + +void SurfaceSphere::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "sphere"); + std::array coeffs {{x0, y0, z0, r}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +//============================================================================== +// Generic functions for x-, y-, and z-, cones +//============================================================================== + +// The first template parameter indicates which axis the cone is aligned to. +// The other two parameters indicate the other two axes. offset1, offset2, +// and offset3 should correspond with i1, i2, and i3, respectively. +template double +axis_aligned_cone_evaluate(const double xyz[3], double offset1, + double offset2, double offset3, double radius_sq) +{ + const double xyz1 = xyz[i1] - offset1; + const double xyz2 = xyz[i2] - offset2; + const double xyz3 = xyz[i3] - offset3; + return xyz2*xyz2 + xyz3*xyz3 - radius_sq*xyz1*xyz1; +} + +// The first template parameter indicates which axis the cone is aligned to. +// The other two parameters indicate the other two axes. offset1, offset2, +// and offset3 should correspond with i1, i2, and i3, respectively. +template double +axis_aligned_cone_distance(const double xyz[3], const double uvw[3], + bool coincident, double offset1, double offset2, double offset3, + double radius_sq) +{ + const double xyz1 = xyz[i1] - offset1; + const double xyz2 = xyz[i2] - offset2; + const double xyz3 = xyz[i3] - offset3; + const double a = uvw[i2]*uvw[i2] + uvw[i3]*uvw[i3] + - radius_sq*uvw[i1]*uvw[i1]; + const double k = xyz2*uvw[i2] + xyz3*uvw[i3] - radius_sq*xyz1*uvw[i1]; + const double c = xyz2*xyz2 + xyz3*xyz3 - radius_sq*xyz1*xyz1; + double quad = k*k - a*c; + + double d; + + if (quad < 0.0) { + // No intersection with cone. + return INFTY; + + } else if (coincident or std::abs(c) < FP_COINCIDENT) { + // Particle is on the cone, thus one distance is positive/negative + // and the other is zero. The sign of k determines if we are facing in or + // out. + if (k >= 0.0) { + d = (-k - sqrt(quad)) / a; + } else { + d = (-k + sqrt(quad)) / a; + } + + } else { + // Calculate both solutions to the quadratic. + quad = sqrt(quad); + d = (-k - quad) / a; + const double b = (-k + quad) / a; + + // Determine the smallest positive solution. + if (d < 0.0) { + if (b > 0.0) d = b; + } else { + if (b > 0.0) { + if (b < d) d = b; + } + } + } + + // If the distance was negative, set boundary distance to infinity. + if (d <= 0.0) return INFTY; + return d; +} + +// The first template parameter indicates which axis the cone is aligned to. +// The other two parameters indicate the other two axes. offset1, offset2, +// and offset3 should correspond with i1, i2, and i3, respectively. +template void +axis_aligned_cone_normal(const double xyz[3], double uvw[3], double offset1, + double offset2, double offset3, double radius_sq) +{ + uvw[i1] = -2.0 * radius_sq * (xyz[i1] - offset1); + uvw[i2] = 2.0 * (xyz[i2] - offset2); + uvw[i3] = 2.0 * (xyz[i3] - offset3); +} + +//============================================================================== +// SurfaceXCone implementation +//============================================================================== + +SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) + : Surface(surf_node) +{ + read_coeffs(surf_node, id, x0, y0, z0, r_sq); +} + +inline double SurfaceXCone::evaluate(const double xyz[3]) const +{ + return axis_aligned_cone_evaluate<0, 1, 2>(xyz, x0, y0, z0, r_sq); +} + +inline double SurfaceXCone::distance(const double xyz[3], + const double uvw[3], bool coincident) const +{ + return axis_aligned_cone_distance<0, 1, 2>(xyz, uvw, coincident, x0, y0, z0, + r_sq); +} + +inline void SurfaceXCone::normal(const double xyz[3], double uvw[3]) const +{ + axis_aligned_cone_normal<0, 1, 2>(xyz, uvw, x0, y0, z0, r_sq); +} + +void SurfaceXCone::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "x-cone"); + std::array coeffs {{x0, y0, z0, r_sq}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +//============================================================================== +// SurfaceYCone implementation +//============================================================================== + +SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) + : Surface(surf_node) +{ + read_coeffs(surf_node, id, x0, y0, z0, r_sq); +} + +inline double SurfaceYCone::evaluate(const double xyz[3]) const +{ + return axis_aligned_cone_evaluate<1, 0, 2>(xyz, y0, x0, z0, r_sq); +} + +inline double SurfaceYCone::distance(const double xyz[3], + const double uvw[3], bool coincident) const +{ + return axis_aligned_cone_distance<1, 0, 2>(xyz, uvw, coincident, y0, x0, z0, + r_sq); +} + +inline void SurfaceYCone::normal(const double xyz[3], double uvw[3]) const +{ + axis_aligned_cone_normal<1, 0, 2>(xyz, uvw, y0, x0, z0, r_sq); +} + +void SurfaceYCone::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "y-cone"); + std::array coeffs {{x0, y0, z0, r_sq}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +//============================================================================== +// SurfaceZCone implementation +//============================================================================== + +SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) + : Surface(surf_node) +{ + read_coeffs(surf_node, id, x0, y0, z0, r_sq); +} + +inline double SurfaceZCone::evaluate(const double xyz[3]) const +{ + return axis_aligned_cone_evaluate<2, 0, 1>(xyz, z0, x0, y0, r_sq); +} + +inline double SurfaceZCone::distance(const double xyz[3], + const double uvw[3], bool coincident) const +{ + return axis_aligned_cone_distance<2, 0, 1>(xyz, uvw, coincident, z0, x0, y0, + r_sq); +} + +inline void SurfaceZCone::normal(const double xyz[3], double uvw[3]) const +{ + axis_aligned_cone_normal<2, 0, 1>(xyz, uvw, z0, x0, y0, r_sq); +} + +void SurfaceZCone::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "z-cone"); + std::array coeffs {{x0, y0, z0, r_sq}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +//============================================================================== +// SurfaceQuadric implementation +//============================================================================== + +SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) + : Surface(surf_node) +{ + read_coeffs(surf_node, id, A, B, C, D, E, F, G, H, J, K); +} + +double +SurfaceQuadric::evaluate(const double xyz[3]) const +{ + const double &x = xyz[0]; + const double &y = xyz[1]; + const double &z = xyz[2]; + return x*(A*x + D*y + G) + + y*(B*y + E*z + H) + + z*(C*z + F*x + J) + K; +} + +double +SurfaceQuadric::distance(const double xyz[3], + const double uvw[3], bool coincident) const +{ + const double &x = xyz[0]; + const double &y = xyz[1]; + const double &z = xyz[2]; + const double &u = uvw[0]; + const double &v = uvw[1]; + const double &w = uvw[2]; + + const double a = A*u*u + B*v*v + C*w*w + D*u*v + E*v*w + F*u*w; + const double k = (A*u*x + B*v*y + C*w*z + 0.5*(D*(u*y + v*x) + + E*(v*z + w*y) + F*(w*x + u*z) + G*u + H*v + J*w)); + const double c = A*x*x + B*y*y + C*z*z + D*x*y + E*y*z + F*x*z + G*x + H*y + + J*z + K; + double quad = k*k - a*c; + + double d; + + if (quad < 0.0) { + // No intersection with surface. + return INFTY; + + } else if (coincident or std::abs(c) < FP_COINCIDENT) { + // Particle is on the surface, thus one distance is positive/negative and + // the other is zero. The sign of k determines which distance is zero and + // which is not. + if (k >= 0.0) { + d = (-k - sqrt(quad)) / a; + } else { + d = (-k + sqrt(quad)) / a; + } + + } else { + // Calculate both solutions to the quadratic. + quad = sqrt(quad); + d = (-k - quad) / a; + double b = (-k + quad) / a; + + // Determine the smallest positive solution. + if (d < 0.0) { + if (b > 0.0) d = b; + } else { + if (b > 0.0) { + if (b < d) d = b; + } + } + } + + // If the distance was negative, set boundary distance to infinity. + if (d <= 0.0) return INFTY; + return d; +} + +void +SurfaceQuadric::normal(const double xyz[3], double uvw[3]) const +{ + const double &x = xyz[0]; + const double &y = xyz[1]; + const double &z = xyz[2]; + uvw[0] = 2.0*A*x + D*y + F*z + G; + uvw[1] = 2.0*B*y + D*x + E*z + H; + uvw[2] = 2.0*C*z + E*y + F*x + J; +} + +void SurfaceQuadric::to_hdf5_inner(hid_t group_id) const +{ + write_string(group_id, "type", "quadric"); + std::array coeffs {{A, B, C, D, E, F, G, H, J, K}}; + write_double_1D(group_id, "coefficients", coeffs); +} + +//============================================================================== + +extern "C" void +read_surfaces(pugi::xml_node *node) +{ + // Count the number of surfaces. + for (pugi::xml_node surf_node: node->children("surface")) {n_surfaces++;} + if (n_surfaces == 0) { + fatal_error("No surfaces found in geometry.xml!"); + } + + // Allocate the array of Surface pointers. + surfaces_c = new Surface* [n_surfaces]; + + // Loop over XML surface elements and populate the array. + { + pugi::xml_node surf_node; + int i_surf; + for (surf_node = node->child("surface"), i_surf = 0; surf_node; + surf_node = surf_node.next_sibling("surface"), i_surf++) { + std::string surf_type = get_node_value(surf_node, "type"); + + if (surf_type == "x-plane") { + surfaces_c[i_surf] = new SurfaceXPlane(surf_node); + + } else if (surf_type == "y-plane") { + surfaces_c[i_surf] = new SurfaceYPlane(surf_node); + + } else if (surf_type == "z-plane") { + surfaces_c[i_surf] = new SurfaceZPlane(surf_node); + + } else if (surf_type == "plane") { + surfaces_c[i_surf] = new SurfacePlane(surf_node); + + } else if (surf_type == "x-cylinder") { + surfaces_c[i_surf] = new SurfaceXCylinder(surf_node); + + } else if (surf_type == "y-cylinder") { + surfaces_c[i_surf] = new SurfaceYCylinder(surf_node); + + } else if (surf_type == "z-cylinder") { + surfaces_c[i_surf] = new SurfaceZCylinder(surf_node); + + } else if (surf_type == "sphere") { + surfaces_c[i_surf] = new SurfaceSphere(surf_node); + + } else if (surf_type == "x-cone") { + surfaces_c[i_surf] = new SurfaceXCone(surf_node); + + } else if (surf_type == "y-cone") { + surfaces_c[i_surf] = new SurfaceYCone(surf_node); + + } else if (surf_type == "z-cone") { + surfaces_c[i_surf] = new SurfaceZCone(surf_node); + + } else if (surf_type == "quadric") { + surfaces_c[i_surf] = new SurfaceQuadric(surf_node); + + } else { + std::stringstream err_msg; + err_msg << "Invalid surface type, \"" << surf_type << "\""; + fatal_error(err_msg); + } + } + } + + // Fill the surface dictionary. + for (int i_surf = 0; i_surf < n_surfaces; i_surf++) { + int id = surfaces_c[i_surf]->id; + auto in_dict = surface_dict.find(id); + if (in_dict == surface_dict.end()) { + surface_dict[id] = i_surf; + } else { + std::stringstream err_msg; + err_msg << "Two or more surfaces use the same unique ID: " << id; + fatal_error(err_msg); + } + } + + // Find the global bounding box (of periodic BC surfaces). + double xmin {INFTY}, xmax {-INFTY}, ymin {INFTY}, ymax {-INFTY}, + zmin {INFTY}, zmax {-INFTY}; + int i_xmin, i_xmax, i_ymin, i_ymax, i_zmin, i_zmax; + for (int i_surf = 0; i_surf < n_surfaces; i_surf++) { + if (surfaces_c[i_surf]->bc == BC_PERIODIC) { + // Downcast to the PeriodicSurface type. + Surface *surf_base = surfaces_c[i_surf]; + PeriodicSurface *surf = dynamic_cast(surf_base); + + // Make sure this surface inherits from PeriodicSurface. + if (!surf) { + std::stringstream err_msg; + err_msg << "Periodic boundary condition not supported for surface " + << surf_base->id + << ". Periodic BCs are only supported for planar surfaces."; + fatal_error(err_msg); + } + + // See if this surface makes part of the global bounding box. + BoundingBox bb = surf->bounding_box(); + if (bb.xmin > -INFTY and bb.xmin < xmin) { + xmin = bb.xmin; + i_xmin = i_surf; + } + if (bb.xmax < INFTY and bb.xmax > xmax) { + xmax = bb.xmax; + i_xmax = i_surf; + } + if (bb.ymin > -INFTY and bb.ymin < ymin) { + ymin = bb.ymin; + i_ymin = i_surf; + } + if (bb.ymax < INFTY and bb.ymax > ymax) { + ymax = bb.ymax; + i_ymax = i_surf; + } + if (bb.zmin > -INFTY and bb.zmin < zmin) { + zmin = bb.zmin; + i_zmin = i_surf; + } + if (bb.zmax < INFTY and bb.zmax > zmax) { + zmax = bb.zmax; + i_zmax = i_surf; + } + } + } + + // Set i_periodic for periodic BC surfaces. + for (int i_surf = 0; i_surf < n_surfaces; i_surf++) { + if (surfaces_c[i_surf]->bc == BC_PERIODIC) { + // Downcast to the PeriodicSurface type. + Surface *surf_base = surfaces_c[i_surf]; + PeriodicSurface *surf = dynamic_cast(surf_base); + + // Also try downcasting to the SurfacePlane type (which must be handled + // differently). + SurfacePlane *surf_p = dynamic_cast(surf); + + if (!surf_p) { + // This is not a SurfacePlane. + if (surf->i_periodic == C_NONE) { + // The user did not specify the matching periodic surface. See if we + // can find the partnered surface from the bounding box information. + if (i_surf == i_xmin) { + surf->i_periodic = i_xmax; + } else if (i_surf == i_xmax) { + surf->i_periodic = i_xmin; + } else if (i_surf == i_ymin) { + surf->i_periodic = i_ymax; + } else if (i_surf == i_ymax) { + surf->i_periodic = i_ymin; + } else if (i_surf == i_zmin) { + surf->i_periodic = i_zmax; + } else if (i_surf == i_zmax) { + surf->i_periodic = i_zmin; + } else { + fatal_error("Periodic boundary condition applied to interior " + "surface"); + } + } else { + // Convert the surface id to an index. + surf->i_periodic = surface_dict[surf->i_periodic]; + } + } else { + // This is a SurfacePlane. We won't try to find it's partner if the + // user didn't specify one. + if (surf->i_periodic == C_NONE) { + std::stringstream err_msg; + err_msg << "No matching periodic surface specified for periodic " + "boundary condition on surface " << surf->id; + fatal_error(err_msg); + } else { + // Convert the surface id to an index. + surf->i_periodic = surface_dict[surf->i_periodic]; + } + } + + // Make sure the opposite surface is also periodic. + if (surfaces_c[surf->i_periodic]->bc != BC_PERIODIC) { + std::stringstream err_msg; + err_msg << "Could not find matching surface for periodic boundary " + "condition on surface " << surf->id; + fatal_error(err_msg); + } + } + } +} + +} // namespace openmc diff --git a/src/surface.h b/src/surface.h new file mode 100644 index 0000000000..627a8fbae2 --- /dev/null +++ b/src/surface.h @@ -0,0 +1,427 @@ +#ifndef SURFACE_H +#define SURFACE_H + +#include +#include // For numeric_limits +#include + +#include "hdf5.h" +#include "pugixml/pugixml.hpp" + + +namespace openmc { + +//============================================================================== +// Module constants +//============================================================================== + +extern "C" const int BC_TRANSMIT {0}; +extern "C" const int BC_VACUUM {1}; +extern "C" const int BC_REFLECT {2}; +extern "C" const int BC_PERIODIC {3}; + +//============================================================================== +// Constants that should eventually be moved out of this file +//============================================================================== + +extern "C" double FP_COINCIDENT; +constexpr double INFTY{std::numeric_limits::max()}; +constexpr int C_NONE {-1}; + +//============================================================================== +// Global variables +//============================================================================== + +// Braces force n_surfaces to be defined here, not just declared. +extern "C" {int32_t n_surfaces {0};} + +class Surface; +Surface **surfaces_c; + +std::map surface_dict; + +//============================================================================== +//! Coordinates for an axis-aligned cube that bounds a geometric object. +//============================================================================== + +struct BoundingBox +{ + double xmin; + double xmax; + double ymin; + double ymax; + double zmin; + double zmax; +}; + +//============================================================================== +//! A geometry primitive used to define regions of 3D space. +//============================================================================== + +class Surface +{ +public: + int id; //!< Unique ID + //int neighbor_pos[], //!< List of cells on positive side + // neighbor_neg[]; //!< List of cells on negative side + int bc; //!< Boundary condition + std::string name{""}; //!< User-defined name + + explicit Surface(pugi::xml_node surf_node); + + virtual ~Surface() {} + + //! Determine which side of a surface a point lies on. + //! @param xyz[3] The 3D Cartesian coordinate of a point. + //! @param uvw[3] A direction used to "break ties" and pick a sense when the + //! point is very close to the surface. + //! @return true if the point is on the "positive" side of the surface and + //! false otherwise. + bool sense(const double xyz[3], const double uvw[3]) const; + + //! Determine the direction of a ray reflected from the surface. + //! @param xyz[3] The point at which the ray is incident. + //! @param uvw[3] A direction. This is both an input and an output parameter. + //! It specifies the icident direction on input and the reflected direction + //! on output. + void reflect(const double xyz[3], double uvw[3]) const; + + //! Evaluate the equation describing the surface. + //! + //! Surfaces can be described by some function f(x, y, z) = 0. This member + //! function evaluates that mathematical function. + //! @param xyz[3] A 3D Cartesian coordinate. + virtual double evaluate(const double xyz[3]) const = 0; + + //! Compute the distance between a point and the surface along a ray. + //! @param xyz[3] A 3D Cartesian coordinate. + //! @param uvw[3] The direction of the ray. + //! @param coincident A hint to the code that the given point should lie + //! exactly on the surface. + virtual double distance(const double xyz[3], const double uvw[3], + bool coincident) const = 0; + + //! Compute the local outward normal direction of the surface. + //! @param xyz[3] A 3D Cartesian coordinate. + //! @param uvw[3] This output argument provides the normal. + virtual void normal(const double xyz[3], double uvw[3]) const = 0; + + //! Write all information needed to reconstruct the surface to an HDF5 group. + //! @param group_id An HDF5 group id. + void to_hdf5(hid_t group_id) const; + +protected: + virtual void to_hdf5_inner(hid_t group_id) const = 0; +}; + +//============================================================================== +//! A `Surface` that supports periodic boundary conditions. +//! +//! Translational periodicity is supported for the `XPlane`, `YPlane`, `ZPlane`, +//! and `Plane` types. Rotational periodicity is supported for +//! `XPlane`-`YPlane` pairs. +//============================================================================== + +class PeriodicSurface : public Surface +{ +public: + int i_periodic{C_NONE}; //!< Index of corresponding periodic surface + + explicit PeriodicSurface(pugi::xml_node surf_node); + + //! Translate a particle onto this surface from a periodic partner surface. + //! @param other A pointer to the partner surface in this periodic BC. + //! @param xyz[3] A point on the partner surface that will be translated onto + //! this surface. + //! @param uvw[3] A direction that will be rotated for systems with rotational + //! periodicity. + //! @return true if this surface and its partner make a rotationally-periodic + //! boundary condition. + virtual bool periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const = 0; + + //! Get the bounding box for this surface. + virtual BoundingBox bounding_box() const = 0; +}; + +//============================================================================== +//! A plane perpendicular to the x-axis. +// +//! The plane is described by the equation \f$x - x_0 = 0\f$ +//============================================================================== + +class SurfaceXPlane : public PeriodicSurface +{ + double x0; +public: + explicit SurfaceXPlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], bool coincident) + const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; + BoundingBox bounding_box() const; +}; + +//============================================================================== +//! A plane perpendicular to the y-axis. +// +//! The plane is described by the equation \f$y - y_0 = 0\f$ +//============================================================================== + +class SurfaceYPlane : public PeriodicSurface +{ + double y0; +public: + explicit SurfaceYPlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; + BoundingBox bounding_box() const; +}; + +//============================================================================== +//! A plane perpendicular to the z-axis. +// +//! The plane is described by the equation \f$z - z_0 = 0\f$ +//============================================================================== + +class SurfaceZPlane : public PeriodicSurface +{ + double z0; +public: + explicit SurfaceZPlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; + BoundingBox bounding_box() const; +}; + +//============================================================================== +//! A general plane. +// +//! The plane is described by the equation \f$A x + B y + C z - D = 0\f$ +//============================================================================== + +class SurfacePlane : public PeriodicSurface +{ + double A, B, C, D; +public: + explicit SurfacePlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], bool coincident) + const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; + BoundingBox bounding_box() const; +}; + +//============================================================================== +//! A cylinder aligned along the x-axis. +// +//! The cylinder is described by the equation +//! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ +//============================================================================== + +class SurfaceXCylinder : public Surface +{ + double y0, z0, r; +public: + explicit SurfaceXCylinder(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cylinder aligned along the y-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 = 0\f$ +//============================================================================== + +class SurfaceYCylinder : public Surface +{ + double x0, z0, r; +public: + explicit SurfaceYCylinder(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cylinder aligned along the z-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 = 0\f$ +//============================================================================== + +class SurfaceZCylinder : public Surface +{ + double x0, y0, r; +public: + explicit SurfaceZCylinder(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A sphere. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ +//============================================================================== + +class SurfaceSphere : public Surface +{ + double x0, y0, z0, r; +public: + explicit SurfaceSphere(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cone aligned along the x-axis. +// +//! The cylinder is described by the equation +//! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 (x - x_0)^2 = 0\f$ +//============================================================================== + +class SurfaceXCone : public Surface +{ + double x0, y0, z0, r_sq; +public: + explicit SurfaceXCone(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cone aligned along the y-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 (y - y_0)^2 = 0\f$ +//============================================================================== + +class SurfaceYCone : public Surface +{ + double x0, y0, z0, r_sq; +public: + explicit SurfaceYCone(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cone aligned along the z-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 (z - z_0)^2 = 0\f$ +//============================================================================== + +class SurfaceZCone : public Surface +{ + double x0, y0, z0, r_sq; +public: + explicit SurfaceZCone(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A general surface described by a quadratic equation. +// +//! \f$A x^2 + B y^2 + C z^2 + D x y + E y z + F x z + G x + H y + J z + K = 0\f$ +//============================================================================== + +class SurfaceQuadric : public Surface +{ + // Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 + double A, B, C, D, E, F, G, H, J, K; +public: + explicit SurfaceQuadric(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +// Fortran compatibility functions +//============================================================================== + +extern "C" Surface* surface_pointer(int surf_ind) {return surfaces_c[surf_ind];} + +extern "C" int surface_id(Surface *surf) {return surf->id;} + +extern "C" int surface_bc(Surface *surf) {return surf->bc;} + +extern "C" bool surface_sense(Surface *surf, double xyz[3], double uvw[3]) +{return surf->sense(xyz, uvw);} + +extern "C" void surface_reflect(Surface *surf, double xyz[3], double uvw[3]) +{surf->reflect(xyz, uvw);} + +extern "C" double +surface_distance(Surface *surf, double xyz[3], double uvw[3], bool coincident) +{return surf->distance(xyz, uvw, coincident);} + +extern "C" void surface_normal(Surface *surf, double xyz[3], double uvw[3]) +{return surf->normal(xyz, uvw);} + +extern "C" void surface_to_hdf5(Surface *surf, hid_t group) +{surf->to_hdf5(group);} + +extern "C" int surface_i_periodic(PeriodicSurface *surf) +{return surf->i_periodic;} + +extern "C" bool +surface_periodic(PeriodicSurface *surf, PeriodicSurface *other, double xyz[3], + double uvw[3]) +{return surf->periodic_translate(other, xyz, uvw);} + +extern "C" void free_memory_surfaces_c() +{ + for (int i = 0; i < n_surfaces; i++) {delete surfaces_c[i];} + delete surfaces_c; + surfaces_c = nullptr; + n_surfaces = 0; + surface_dict.clear(); +} + +} // namespace openmc +#endif // SURFACE_H diff --git a/src/surface_header.F90 b/src/surface_header.F90 index ed4ef86e09..9ed89a14e9 100644 --- a/src/surface_header.F90 +++ b/src/surface_header.F90 @@ -1,1073 +1,212 @@ module surface_header use, intrinsic :: ISO_C_BINDING + use hdf5 - use constants, only: NONE, ONE, TWO, ZERO, HALF, INFINITY, FP_COINCIDENT use dict_header, only: DictIntInt implicit none + interface + pure function surface_pointer_c(surf_ind) & + bind(C, name='surface_pointer') result(ptr) + use ISO_C_BINDING + implicit none + integer(C_INT), intent(in), value :: surf_ind + type(C_PTR) :: ptr + end function surface_pointer_c + + pure function surface_id_c(surf_ptr) bind(C, name='surface_id') result(id) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + integer(C_INT) :: id + end function surface_id_c + + pure function surface_bc_c(surf_ptr) bind(C, name='surface_bc') result(bc) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + integer(C_INT) :: bc + end function surface_bc_c + + pure function surface_sense_c(surf_ptr, xyz, uvw) & + bind(C, name='surface_sense') result(sense) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + real(C_DOUBLE), intent(in) :: xyz(3) + real(C_DOUBLE), intent(in) :: uvw(3) + logical(C_BOOL) :: sense + end function surface_sense_c + + pure subroutine surface_reflect_c(surf_ptr, xyz, uvw) & + bind(C, name='surface_reflect') + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + end subroutine surface_reflect_c + + pure function surface_distance_c(surf_ptr, xyz, uvw, coincident) & + bind(C, name='surface_distance') result(d) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(in) :: uvw(3); + logical(C_BOOL), intent(in), value :: coincident; + real(C_DOUBLE) :: d; + end function surface_distance_c + + pure subroutine surface_normal_c(surf_ptr, xyz, uvw) & + bind(C, name='surface_normal') + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(out) :: uvw(3); + end subroutine surface_normal_c + + subroutine surface_to_hdf5_c(surf_ptr, group) & + bind(C, name='surface_to_hdf5') + use ISO_C_BINDING + use hdf5 + implicit none + type(C_PTR), intent(in), value :: surf_ptr + integer(HID_T), intent(in), value :: group + end subroutine surface_to_hdf5_c + + pure function surface_i_periodic_c(surf_ptr) & + bind(C, name="surface_i_periodic") result(i_periodic) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + integer(C_INT) :: i_periodic + end function surface_i_periodic_c + + function surface_periodic_c(surf_ptr, other_ptr, xyz, uvw) & + bind(C, name="surface_periodic") result(rotational) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + type(C_PTR), intent(in), value :: other_ptr + real(C_DOUBLE), intent(inout) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + logical(C_BOOL) :: rotational + end function surface_periodic_c + + subroutine free_memory_surfaces_c() bind(C) + end subroutine free_memory_surfaces_c + end interface + !=============================================================================== ! SURFACE type defines a first- or second-order surface that can be used to ! construct closed volumes (cells) !=============================================================================== - type, abstract :: Surface - integer :: id ! Unique ID + type :: Surface integer, allocatable :: & neighbor_pos(:), & ! List of cells on positive side neighbor_neg(:) ! List of cells on negative side - integer :: bc ! Boundary condition - integer :: i_periodic = NONE ! Index of corresponding periodic surface - character(len=104) :: name = "" ! User-defined name + type(C_PTR) :: ptr + contains - procedure :: sense - procedure :: reflect - procedure(surface_evaluate_), deferred :: evaluate - procedure(surface_distance_), deferred :: distance - procedure(surface_normal_), deferred :: normal + + procedure :: id => surface_id + procedure :: bc => surface_bc + procedure :: sense => surface_sense + procedure :: reflect => surface_reflect + procedure :: distance => surface_distance + procedure :: normal => surface_normal + procedure :: to_hdf5 => surface_to_hdf5 + procedure :: i_periodic => surface_i_periodic + procedure :: periodic_translate => surface_periodic + end type Surface - abstract interface - pure function surface_evaluate_(this, xyz) result(f) - import Surface - class(Surface), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - end function surface_evaluate_ - - pure function surface_distance_(this, xyz, uvw, coincident) result(d) - import Surface - class(Surface), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - end function surface_distance_ - - pure function surface_normal_(this, xyz) result(uvw) - import Surface - class(Surface), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - end function surface_normal_ - end interface - -!=============================================================================== -! SURFACECONTAINER allows us to store an array of different types of surfaces -!=============================================================================== - - type :: SurfaceContainer - class(Surface), allocatable :: obj - end type SurfaceContainer - -!=============================================================================== -! All the derived types below are extensions of the abstract Surface type. They -! inherent the reflect() and sense() type-bound procedures and must implement -! evaluate(), distance(), and normal() -!=============================================================================== - - type, extends(Surface) :: SurfaceXPlane - ! x = x0 - real(8) :: x0 - contains - procedure :: evaluate => x_plane_evaluate - procedure :: distance => x_plane_distance - procedure :: normal => x_plane_normal - end type SurfaceXPlane - - type, extends(Surface) :: SurfaceYPlane - ! y = y0 - real(8) :: y0 - contains - procedure :: evaluate => y_plane_evaluate - procedure :: distance => y_plane_distance - procedure :: normal => y_plane_normal - end type SurfaceYPlane - - type, extends(Surface) :: SurfaceZPlane - ! z = z0 - real(8) :: z0 - contains - procedure :: evaluate => z_plane_evaluate - procedure :: distance => z_plane_distance - procedure :: normal => z_plane_normal - end type SurfaceZPlane - - type, extends(Surface) :: SurfacePlane - ! Ax + By + Cz = D - real(8) :: A - real(8) :: B - real(8) :: C - real(8) :: D - contains - procedure :: evaluate => plane_evaluate - procedure :: distance => plane_distance - procedure :: normal => plane_normal - end type SurfacePlane - - type, extends(Surface) :: SurfaceXCylinder - ! (y - y0)^2 + (z - z0)^2 = R^2 - real(8) :: y0 - real(8) :: z0 - real(8) :: r - contains - procedure :: evaluate => x_cylinder_evaluate - procedure :: distance => x_cylinder_distance - procedure :: normal => x_cylinder_normal - end type SurfaceXCylinder - - type, extends(Surface) :: SurfaceYCylinder - ! (x - x0)^2 + (z - z0)^2 = R^2 - real(8) :: x0 - real(8) :: z0 - real(8) :: r - contains - procedure :: evaluate => y_cylinder_evaluate - procedure :: distance => y_cylinder_distance - procedure :: normal => y_cylinder_normal - end type SurfaceYCylinder - - type, extends(Surface) :: SurfaceZCylinder - ! (x - x0)^2 + (y - y0)^2 = R^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: r - contains - procedure :: evaluate => z_cylinder_evaluate - procedure :: distance => z_cylinder_distance - procedure :: normal => z_cylinder_normal - end type SurfaceZCylinder - - type, extends(Surface) :: SurfaceSphere - ! (x - x0)^2 + (y - y0)^2 + (z - z0)^2 = R^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: z0 - real(8) :: r - contains - procedure :: evaluate => sphere_evaluate - procedure :: distance => sphere_distance - procedure :: normal => sphere_normal - end type SurfaceSphere - - type, extends(Surface) :: SurfaceXCone - ! (y - y0)^2 + (z - z0)^2 = R^2*(x - x0)^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: z0 - real(8) :: r2 - contains - procedure :: evaluate => x_cone_evaluate - procedure :: distance => x_cone_distance - procedure :: normal => x_cone_normal - end type SurfaceXCone - - type, extends(Surface) :: SurfaceYCone - ! (x - x0)^2 + (z - z0)^2 = R^2*(y - y0)^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: z0 - real(8) :: r2 - contains - procedure :: evaluate => y_cone_evaluate - procedure :: distance => y_cone_distance - procedure :: normal => y_cone_normal - end type SurfaceYCone - - type, extends(Surface) :: SurfaceZCone - ! (x - x0)^2 + (y - y0)^2 = R^2*(z - z0)^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: z0 - real(8) :: r2 - contains - procedure :: evaluate => z_cone_evaluate - procedure :: distance => z_cone_distance - procedure :: normal => z_cone_normal - end type SurfaceZCone - - type, extends(Surface) :: SurfaceQuadric - ! Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 - real(8) :: A, B, C, D, E, F, G, H, J, K - contains - procedure :: evaluate => quadric_evaluate - procedure :: distance => quadric_distance - procedure :: normal => quadric_normal - end type SurfaceQuadric - integer(C_INT32_T), bind(C) :: n_surfaces ! # of surfaces - type(SurfaceContainer), allocatable, target :: surfaces(:) + type(Surface), allocatable, target :: surfaces(:) ! Dictionary that maps user IDs to indices in 'surfaces' type(DictIntInt) :: surface_dict contains -!=============================================================================== -! SENSE determines whether a point is on the 'positive' or 'negative' side of a -! surface. This routine is crucial for determining what cell a particular point -! is in. The positive side is indicated by a returned value of .true. and the -! negative side is indicated by a returned value of .false. -!=============================================================================== - - pure function sense(this, xyz, uvw) result(s) - class(Surface), intent(in) :: this ! surface - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical :: s ! sense of particle - - real(8) :: f ! surface function evaluated at point - - ! Evaluate the surface equation at the particle's coordinates to determine - ! which side the particle is on - f = this%evaluate(xyz) - - ! Check which side of surface the point is on - if (abs(f) < FP_COINCIDENT) then - ! Particle may be coincident with this surface. To determine the sense, we - ! look at the direction of the particle relative to the surface normal (by - ! default in the positive direction) via their dot product. - s = (dot_product(uvw, this%normal(xyz)) > ZERO) - else - s = (f > ZERO) - end if - end function sense - -!=============================================================================== -! REFLECT determines the direction a particle will travel if it is specularly -! reflected from the surface at a given position and direction. The position is -! needed because the reflection is performed using the surface normal, which -! depends on the position for second-order surfaces. -!=============================================================================== - - pure subroutine reflect(this, xyz, uvw) + pure function surface_id(this) result(id) class(Surface), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(inout) :: uvw(3) - - real(8) :: projection - real(8) :: magnitude - real(8) :: n(3) - - ! Construct normal vector - n(:) = this%normal(xyz) - - ! Determine projection of direction onto normal and squared magnitude of - ! normal - projection = n(1)*uvw(1) + n(2)*uvw(2) + n(3)*uvw(3) - magnitude = n(1)*n(1) + n(2)*n(2) + n(3)*n(3) - - ! Reflect direction according to normal - uvw(:) = uvw - TWO*projection/magnitude * n - end subroutine reflect - -!=============================================================================== -! SurfaceXPlane Implementation -!=============================================================================== - - pure function x_plane_evaluate(this, xyz) result(f) - class(SurfaceXPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - f = xyz(1) - this%x0 - end function x_plane_evaluate - - pure function x_plane_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceXPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: f - - f = this%x0 - xyz(1) - if (coincident .or. abs(f) < FP_COINCIDENT .or. uvw(1) == ZERO) then - d = INFINITY - else - d = f/uvw(1) - if (d < ZERO) d = INFINITY - end if - end function x_plane_distance - - pure function x_plane_normal(this, xyz) result(uvw) - class(SurfaceXPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = [ONE, ZERO, ZERO] - end function x_plane_normal - -!=============================================================================== -! SurfaceYPlane Implementation -!=============================================================================== - - pure function y_plane_evaluate(this, xyz) result(f) - class(SurfaceYPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - f = xyz(2) - this%y0 - end function y_plane_evaluate - - pure function y_plane_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceYPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: f - - f = this%y0 - xyz(2) - if (coincident .or. abs(f) < FP_COINCIDENT .or. uvw(2) == ZERO) then - d = INFINITY - else - d = f/uvw(2) - if (d < ZERO) d = INFINITY - end if - end function y_plane_distance - - pure function y_plane_normal(this, xyz) result(uvw) - class(SurfaceYPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = [ZERO, ONE, ZERO] - end function y_plane_normal - -!=============================================================================== -! SurfaceZPlane Implementation -!=============================================================================== - - pure function z_plane_evaluate(this, xyz) result(f) - - class(SurfaceZPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - f = xyz(3) - this%z0 - - end function z_plane_evaluate - - pure function z_plane_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceZPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: f - - f = this%z0 - xyz(3) - if (coincident .or. abs(f) < FP_COINCIDENT .or. uvw(3) == ZERO) then - d = INFINITY - else - d = f/uvw(3) - if (d < ZERO) d = INFINITY - end if - end function z_plane_distance - - pure function z_plane_normal(this, xyz) result(uvw) - class(SurfaceZPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = [ZERO, ZERO, ONE] - end function z_plane_normal - -!=============================================================================== -! SurfacePlane Implementation -!=============================================================================== - - pure function plane_evaluate(this, xyz) result(f) - class(SurfacePlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - f = this%A*xyz(1) + this%B*xyz(2) + this%C*xyz(3) - this%D - end function plane_evaluate - - pure function plane_distance(this, xyz, uvw, coincident) result(d) - class(SurfacePlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: f - real(8) :: projection - - f = this%A*xyz(1) + this%B*xyz(2) + this%C*xyz(3) - this%D - projection = this%A*uvw(1) + this%B*uvw(2) + this%C*uvw(3) - if (coincident .or. abs(f) < FP_COINCIDENT .or. projection == ZERO) then - d = INFINITY - else - d = -f/projection - if (d < ZERO) d = INFINITY - end if - end function plane_distance - - pure function plane_normal(this, xyz) result(uvw) - class(SurfacePlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = [this%A, this%B, this%C] - end function plane_normal - -!=============================================================================== -! SurfaceXCylinder Implementation -!=============================================================================== - - pure function x_cylinder_evaluate(this, xyz) result(f) - class(SurfaceXCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: y, z - - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = y*y + z*z - this%r*this%r - end function x_cylinder_evaluate - - pure function x_cylinder_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceXCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: y, z, k, a, c, quad - - a = ONE - uvw(1)*uvw(1) ! v^2 + w^2 - if (a == ZERO) then - d = INFINITY - else - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - k = y*uvw(2) + z*uvw(3) - c = y*y + z*z - this%r*this%r - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cylinder - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cylinder, thus one distance is positive/negative - ! and the other is zero. The sign of k determines if we are facing in or - ! out - - if (k >= ZERO) then - d = INFINITY - else - d = (-k + sqrt(quad))/a - end if - - elseif (c < ZERO) then - ! particle is inside the cylinder, thus one distance must be negative - ! and one must be positive. The positive distance will be the one with - ! negative sign on sqrt(quad) - - d = (-k + sqrt(quad))/a - - else - ! particle is outside the cylinder, thus both distances are either - ! positive or negative. If positive, the smaller distance is the one - ! with positive sign on sqrt(quad) - - d = (-k - sqrt(quad))/a - if (d < ZERO) d = INFINITY - - end if - end if - end function x_cylinder_distance - - pure function x_cylinder_normal(this, xyz) result(uvw) - class(SurfaceXCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = ZERO - uvw(2) = TWO*(xyz(2) - this%y0) - uvw(3) = TWO*(xyz(3) - this%z0) - end function x_cylinder_normal - -!=============================================================================== -! SurfaceYCylinder Implementation -!=============================================================================== - - pure function y_cylinder_evaluate(this, xyz) result(f) - class(SurfaceYCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, z - - x = xyz(1) - this%x0 - z = xyz(3) - this%z0 - f = x*x + z*z - this%r*this%r - end function y_cylinder_evaluate - - pure function y_cylinder_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceYCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, z, k, a, c, quad - - a = ONE - uvw(2)*uvw(2) ! u^2 + w^2 - if (a == ZERO) then - d = INFINITY - else - x = xyz(1) - this%x0 - z = xyz(3) - this%z0 - k = x*uvw(1) + z*uvw(3) - c = x*x + z*z - this%r*this%r - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cylinder - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cylinder, thus one distance is positive/negative - ! and the other is zero. The sign of k determines if we are facing in or - ! out - - if (k >= ZERO) then - d = INFINITY - else - d = (-k + sqrt(quad))/a - end if - - elseif (c < ZERO) then - ! particle is inside the cylinder, thus one distance must be negative - ! and one must be positive. The positive distance will be the one with - ! negative sign on sqrt(quad) - - d = (-k + sqrt(quad))/a - - else - ! particle is outside the cylinder, thus both distances are either - ! positive or negative. If positive, the smaller distance is the one - ! with positive sign on sqrt(quad) - - d = (-k - sqrt(quad))/a - if (d < ZERO) d = INFINITY - - end if - end if - end function y_cylinder_distance - - pure function y_cylinder_normal(this, xyz) result(uvw) - class(SurfaceYCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = TWO*(xyz(1) - this%x0) - uvw(2) = ZERO - uvw(3) = TWO*(xyz(3) - this%z0) - end function y_cylinder_normal - -!=============================================================================== -! SurfaceZCylinder Implementation -!=============================================================================== - - pure function z_cylinder_evaluate(this, xyz) result(f) - class(SurfaceZCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - f = x*x + y*y - this%r*this%r - end function z_cylinder_evaluate - - pure function z_cylinder_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceZCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, k, a, c, quad - - a = ONE - uvw(3)*uvw(3) ! u^2 + v^2 - if (a == ZERO) then - d = INFINITY - else - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - k = x*uvw(1) + y*uvw(2) - c = x*x + y*y - this%r*this%r - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cylinder - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cylinder, thus one distance is positive/negative - ! and the other is zero. The sign of k determines if we are facing in or - ! out - - if (k >= ZERO) then - d = INFINITY - else - d = (-k + sqrt(quad))/a - end if - - elseif (c < ZERO) then - ! particle is inside the cylinder, thus one distance must be negative - ! and one must be positive. The positive distance will be the one with - ! negative sign on sqrt(quad) - - d = (-k + sqrt(quad))/a - - else - ! particle is outside the cylinder, thus both distances are either - ! positive or negative. If positive, the smaller distance is the one - ! with positive sign on sqrt(quad) - - d = (-k - sqrt(quad))/a - if (d < ZERO) d = INFINITY - - end if - end if - end function z_cylinder_distance - - pure function z_cylinder_normal(this, xyz) result(uvw) - class(SurfaceZCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = TWO*(xyz(1) - this%x0) - uvw(2) = TWO*(xyz(2) - this%y0) - uvw(3) = ZERO - end function z_cylinder_normal - -!=============================================================================== -! SurfaceSphere Implementation -!=============================================================================== - - pure function sphere_evaluate(this, xyz) result(f) - class(SurfaceSphere), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y, z - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = x*x + y*y + z*z - this%r*this%r - end function sphere_evaluate - - pure function sphere_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceSphere), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, z, k, c, quad - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - k = x*uvw(1) + y*uvw(2) + z*uvw(3) - c = x*x + y*y + z*z - this%r*this%r - quad = k*k - c - - if (quad < ZERO) then - ! no intersection with sphere - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the sphere, thus one distance is positive/negative and - ! the other is zero. The sign of k determines if we are facing in or out - - if (k >= ZERO) then - d = INFINITY - else - d = -k + sqrt(quad) - end if - - elseif (c < ZERO) then - ! particle is inside the sphere, thus one distance must be negative and - ! one must be positive. The positive distance will be the one with - ! negative sign on sqrt(quad) - - d = -k + sqrt(quad) - - else - ! particle is outside the sphere, thus both distances are either positive - ! or negative. If positive, the smaller distance is the one with positive - ! sign on sqrt(quad) - - d = -k - sqrt(quad) - if (d < ZERO) d = INFINITY - - end if - end function sphere_distance - - pure function sphere_normal(this, xyz) result(uvw) - class(SurfaceSphere), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = TWO*(xyz - [this%x0, this%y0, this%z0]) - end function sphere_normal - -!=============================================================================== -! SurfaceXCone Implementation -!=============================================================================== - - pure function x_cone_evaluate(this, xyz) result(f) - class(SurfaceXCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y, z - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = y*y + z*z - this%r2*x*x - end function x_cone_evaluate - - pure function x_cone_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceXCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, z, k, a, b, c, quad - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - a = uvw(2)*uvw(2) + uvw(3)*uvw(3) - this%r2*uvw(1)*uvw(1) - k = y*uvw(2) + z*uvw(3) - this%r2*x*uvw(1) - c = y*y + z*z - this%r2*x*x - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cone - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cone, thus one distance is positive/negative and the - ! other is zero. The sign of k determines which distance is zero and which - ! is not. - - if (k >= ZERO) then - d = (-k - sqrt(quad))/a - else - d = (-k + sqrt(quad))/a - end if - - else - ! calculate both solutions to the quadratic - quad = sqrt(quad) - d = (-k - quad)/a - b = (-k + quad)/a - - ! determine the smallest positive solution - if (d < ZERO) then - if (b > ZERO) then - d = b - end if - else - if (b > ZERO) d = min(d, b) - end if - end if - - ! If the distance was negative, set boundary distance to infinity - if (d <= ZERO) d = INFINITY - end function x_cone_distance - - pure function x_cone_normal(this, xyz) result(uvw) - class(SurfaceXCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = -TWO*this%r2*(xyz(1) - this%x0) - uvw(2) = TWO*(xyz(2) - this%y0) - uvw(3) = TWO*(xyz(3) - this%z0) - end function x_cone_normal - -!=============================================================================== -! SurfaceYCone Implementation -!=============================================================================== - - pure function y_cone_evaluate(this, xyz) result(f) - class(SurfaceYCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y, z - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = x*x + z*z - this%r2*y*y - end function y_cone_evaluate - - pure function y_cone_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceYCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, z, k, a, b, c, quad - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - a = uvw(1)*uvw(1) + uvw(3)*uvw(3) - this%r2*uvw(2)*uvw(2) - k = x*uvw(1) + z*uvw(3) - this%r2*y*uvw(2) - c = x*x + z*z - this%r2*y*y - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cone - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cone, thus one distance is positive/negative and the - ! other is zero. The sign of k determines which distance is zero and which - ! is not. - - if (k >= ZERO) then - d = (-k - sqrt(quad))/a - else - d = (-k + sqrt(quad))/a - end if - - else - ! calculate both solutions to the quadratic - quad = sqrt(quad) - d = (-k - quad)/a - b = (-k + quad)/a - - ! determine the smallest positive solution - if (d < ZERO) then - if (b > ZERO) then - d = b - end if - else - if (b > ZERO) d = min(d, b) - end if - end if - - ! If the distance was negative, set boundary distance to infinity - if (d <= ZERO) d = INFINITY - end function y_cone_distance - - pure function y_cone_normal(this, xyz) result(uvw) - class(SurfaceYCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = TWO*(xyz(1) - this%x0) - uvw(2) = -TWO*this%r2*(xyz(2) - this%y0) - uvw(3) = TWO*(xyz(3) - this%z0) - end function y_cone_normal - -!=============================================================================== -! SurfaceZCone Implementation -!=============================================================================== - - pure function z_cone_evaluate(this, xyz) result(f) - class(SurfaceZCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y, z - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = x*x + y*y - this%r2*z*z - end function z_cone_evaluate - - pure function z_cone_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceZCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, z, k, a, b, c, quad - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - a = uvw(1)*uvw(1) + uvw(2)*uvw(2) - this%r2*uvw(3)*uvw(3) - k = x*uvw(1) + y*uvw(2) - this%r2*z*uvw(3) - c = x*x + y*y - this%r2*z*z - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cone - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cone, thus one distance is positive/negative and the - ! other is zero. The sign of k determines which distance is zero and which - ! is not. - - if (k >= ZERO) then - d = (-k - sqrt(quad))/a - else - d = (-k + sqrt(quad))/a - end if - - else - ! calculate both solutions to the quadratic - quad = sqrt(quad) - d = (-k - quad)/a - b = (-k + quad)/a - - ! determine the smallest positive solution - if (d < ZERO) then - if (b > ZERO) then - d = b - end if - else - if (b > ZERO) d = min(d, b) - end if - end if - - ! If the distance was negative, set boundary distance to infinity - if (d <= ZERO) d = INFINITY - end function z_cone_distance - - pure function z_cone_normal(this, xyz) result(uvw) - class(SurfaceZCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = TWO*(xyz(1) - this%x0) - uvw(2) = TWO*(xyz(2) - this%y0) - uvw(3) = -TWO*this%r2*(xyz(3) - this%z0) - end function z_cone_normal - -!=============================================================================== -! SurfaceQuadric Implementation -!=============================================================================== - - pure function quadric_evaluate(this, xyz) result(f) - class(SurfaceQuadric), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - associate (x => xyz(1), y => xyz(2), z => xyz(3)) - f = x*(this%A*x + this%D*y + this%G) + & - y*(this%B*y + this%E*z + this%H) + & - z*(this%C*z + this%F*x + this%J) + this%K - end associate - end function quadric_evaluate - - pure function quadric_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceQuadric), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: a, k, c - real(8) :: quad, b - - associate (x => xyz(1), y => xyz(2), z => xyz(3), & - u => uvw(1), v => uvw(2), w => uvw(3)) - - a = this%A*u*u + this%B*v*v + this%C*w*w + this%D*u*v + this%E*v*w + & - this%F*u*w - k = (this%A*u*x + this%B*v*y + this%C*w*z + HALF*(this%D*(u*y + v*x) + & - this%E*(v*z + w*y) + this%F*(w*x + u*z) + this%G*u + this%H*v + & - this%J*w)) - c = this%A*x*x + this%B*y*y + this%C*z*z + this%D*x*y + this%E*y*z + & - this%F*x*z + this%G*x + this%H*y + this%J*z + this%K - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with surface - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the surface, thus one distance is positive/negative and - ! the other is zero. The sign of k determines which distance is zero and - ! which is not. - - if (k >= ZERO) then - d = (-k - sqrt(quad))/a - else - d = (-k + sqrt(quad))/a - end if - - else - ! calculate both solutions to the quadratic - quad = sqrt(quad) - d = (-k - quad)/a - b = (-k + quad)/a - - ! determine the smallest positive solution - if (d < ZERO) then - if (b > ZERO) then - d = b - end if - else - if (b > ZERO) d = min(d, b) - end if - end if - - ! If the distance was negative, set boundary distance to infinity - if (d <= ZERO) d = INFINITY - end associate - end function quadric_distance - - pure function quadric_normal(this, xyz) result(uvw) - class(SurfaceQuadric), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - associate (x => xyz(1), y => xyz(2), z => xyz(3)) - uvw(1) = TWO*this%A*x + this%D*y + this%F*z + this%G - uvw(2) = TWO*this%B*y + this%D*x + this%E*z + this%H - uvw(3) = TWO*this%C*z + this%E*y + this%F*x + this%J - end associate - end function quadric_normal + integer(C_INT) :: id + id = surface_id_c(this % ptr) + end function surface_id + + pure function surface_bc(this) result(bc) + class(Surface), intent(in) :: this + integer(C_INT) :: bc + bc = surface_bc_c(this % ptr) + end function surface_bc + + pure function surface_sense(this, xyz, uvw) result(sense) + class(Surface), intent(in) :: this + real(C_DOUBLE), intent(in) :: xyz(3) + real(C_DOUBLE), intent(in) :: uvw(3) + logical(C_BOOL) :: sense + sense = surface_sense_c(this % ptr, xyz, uvw) + end function surface_sense + + pure subroutine surface_reflect(this, xyz, uvw) + class(Surface), intent(in) :: this + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + call surface_reflect_c(this % ptr, xyz, uvw) + end subroutine surface_reflect + + pure function surface_distance(this, xyz, uvw, coincident) result(d) + class(Surface), intent(in) :: this + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(in) :: uvw(3); + logical(C_BOOL), intent(in) :: coincident; + real(C_DOUBLE) :: d; + d = surface_distance_c(this % ptr, xyz, uvw, coincident) + end function surface_distance + + pure subroutine surface_normal(this, xyz, uvw) + class(Surface), intent(in) :: this + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(out) :: uvw(3); + call surface_normal_c(this % ptr, xyz, uvw) + end subroutine surface_normal + + subroutine surface_to_hdf5(this, group) + class(Surface), intent(in) :: this + integer(HID_T), intent(in) :: group + call surface_to_hdf5_c(this % ptr, group) + end subroutine surface_to_hdf5 + + pure function surface_i_periodic(this) result(i_periodic) + class(Surface), intent(in) :: this + integer(C_INT) :: i_periodic + i_periodic = surface_i_periodic_c(this % ptr) + end function surface_i_periodic + + function surface_periodic(this, other, xyz, uvw) result(rotational) + class(Surface), intent(in) :: this + class(Surface), intent(in) :: other + real(C_DOUBLE), intent(inout) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + logical(C_BOOL) :: rotational + rotational = surface_periodic_c(this % ptr, other % ptr, xyz, uvw) + end function surface_periodic !=============================================================================== ! FREE_MEMORY_SURFACES deallocates global arrays defined in this module !=============================================================================== subroutine free_memory_surfaces() - n_surfaces = 0 if (allocated(surfaces)) deallocate(surfaces) call surface_dict % clear() + call free_memory_surfaces_c() end subroutine free_memory_surfaces end module surface_header diff --git a/src/tallies/tally.F90 b/src/tallies/tally.F90 index 7684a36aa6..f4d12be7e1 100644 --- a/src/tallies/tally.F90 +++ b/src/tallies/tally.F90 @@ -4,7 +4,6 @@ module tally use algorithm, only: binary_search use constants - use cross_section, only: multipole_deriv_eval use dict_header, only: EMPTY use error, only: fatal_error use geometry_header @@ -1017,9 +1016,26 @@ contains else if (i_nuclide > 0) then + if (micro_xs(i_nuclide) % elastic == CACHE_INVALID) then + call nuclides(i_nuclide) % calculate_elastic_xs(micro_xs(i_nuclide)) + end if score = micro_xs(i_nuclide) % elastic * atom_density * flux else - score = material_xs % elastic * flux + score = ZERO + if (p % material /= MATERIAL_VOID) then + do l = 1, materials(p % material) % n_nuclides + ! Get atom density + atom_density_ = materials(p % material) % atom_density(l) + + ! Get index in nuclides array + i_nuc = materials(p % material) % nuclide(l) + if (micro_xs(i_nuc) % elastic == CACHE_INVALID) then + call nuclides(i_nuc) % calculate_elastic_xs(micro_xs(i_nuc)) + end if + + score = score + micro_xs(i_nuc) % elastic * atom_density_ * flux + end do + end if end if end if @@ -3048,9 +3064,9 @@ contains ! tally total or partial currents between two cells !=============================================================================== - subroutine score_surface_tally(p) - - type(Particle), intent(in) :: p + subroutine score_surface_tally(p, tally_vec) + type(Particle), intent(in) :: p + type(VectorInt), intent(in) :: tally_vec integer :: i integer :: i_tally @@ -3070,9 +3086,9 @@ contains ! No collision, so no weight change when survival biasing flux = p % wgt - TALLY_LOOP: do i = 1, active_surface_tallies % size() + TALLY_LOOP: do i = 1, tally_vec % size() ! Get index of tally and pointer to tally - i_tally = active_surface_tallies % data(i) + i_tally = tally_vec % data(i) associate (t => tallies(i_tally) % obj) ! Find all valid bins in each filter if they have not already been found @@ -3172,290 +3188,6 @@ contains end subroutine score_surface_tally -!=============================================================================== -! SCORE_SURFACE_CURRENT tallies surface crossings in a mesh tally by manually -! determining which mesh surfaces were crossed -!=============================================================================== - - subroutine score_surface_current(p) - - type(Particle), intent(in) :: p - - integer :: i - integer :: i_tally - integer :: j, k ! loop indices - integer :: n_dim ! num dimensions of the mesh - integer :: d1 ! dimension index - integer :: d2 ! dimension index - integer :: d3 ! dimension index - integer :: ijk0(3) ! indices of starting coordinates - integer :: ijk1(3) ! indices of ending coordinates - integer :: n_cross ! number of surface crossings - integer :: filter_index ! index of scoring bin - integer :: i_filter_mesh ! index of mesh filter in filters array - integer :: i_filter_surf ! index of surface filter in filters - integer :: i_filter_energy ! index of energy filter in filters - real(8) :: uvw(3) ! cosine of angle of particle - real(8) :: xyz0(3) ! starting/intermediate coordinates - real(8) :: xyz1(3) ! ending coordinates of particle - real(8) :: xyz_cross(3) ! coordinates of bounding surfaces - real(8) :: d(3) ! distance to each bounding surface - real(8) :: distance ! actual distance traveled - integer :: matching_bin ! next valid filter bin - logical :: start_in_mesh ! particle's starting xyz in mesh? - logical :: end_in_mesh ! particle's ending xyz in mesh? - logical :: cross_surface ! whether the particle crosses a surface - logical :: energy_filter ! energy filter present - type(RegularMesh), pointer :: m - - TALLY_LOOP: do i = 1, active_current_tallies % size() - ! Copy starting and ending location of particle - xyz0 = p % last_xyz_current - xyz1 = p % coord(1) % xyz - - ! Get pointer to tally - i_tally = active_current_tallies % data(i) - associate (t => tallies(i_tally) % obj) - - ! Check for energy filter - energy_filter = (t % find_filter(FILTER_ENERGYIN) > 0) - - ! Get index for mesh, surface, and energy filters - i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) - i_filter_surf = t % filter(t % find_filter(FILTER_SURFACE)) - if (energy_filter) then - i_filter_energy = t % filter(t % find_filter(FILTER_ENERGYIN)) - end if - - ! Reset the matching bins arrays - call filter_matches(i_filter_mesh) % bins % resize(1) - call filter_matches(i_filter_surf) % bins % resize(1) - if (energy_filter) then - call filter_matches(i_filter_energy) % bins % resize(1) - end if - - ! Get pointer to mesh - select type(filt => filters(i_filter_mesh) % obj) - type is (MeshFilter) - m => meshes(filt % mesh) - end select - - n_dim = m % n_dimension - - ! Determine indices for starting and ending location - call m % get_indices(xyz0, ijk0, start_in_mesh) - call m % get_indices(xyz1, ijk1, end_in_mesh) - - ! Check to see if start or end is in mesh -- if not, check if track still - ! intersects with mesh - if ((.not. start_in_mesh) .and. (.not. end_in_mesh)) then - if (.not. m % intersects(xyz0, xyz1)) cycle - end if - - ! Calculate number of surface crossings - n_cross = sum(abs(ijk1(:n_dim) - ijk0(:n_dim))) - if (n_cross == 0) then - cycle - end if - - ! Copy particle's direction - uvw = p % coord(1) % uvw - - ! Determine incoming energy bin. We need to tell the energy filter this - ! is a tracklength tally so it uses the pre-collision energy. - if (energy_filter) then - call filter_matches(i_filter_energy) % bins % clear() - call filter_matches(i_filter_energy) % weights % clear() - call filters(i_filter_energy) % obj % get_all_bins(p, & - ESTIMATOR_TRACKLENGTH, filter_matches(i_filter_energy)) - if (filter_matches(i_filter_energy) % bins % size() == 0) cycle - matching_bin = filter_matches(i_filter_energy) % bins % data(1) - filter_matches(i_filter_energy) % bins % data(1) = matching_bin - end if - - ! Bounding coordinates - do d1 = 1, n_dim - if (uvw(d1) > 0) then - xyz_cross(d1) = m % lower_left(d1) + ijk0(d1) * m % width(d1) - else - xyz_cross(d1) = m % lower_left(d1) + (ijk0(d1) - 1) * m % width(d1) - end if - end do - - do j = 1, n_cross - ! Reset scoring bin index - filter_matches(i_filter_surf) % bins % data(1) = 0 - - ! Set the distances to infinity - d = INFINITY - - ! Calculate distance to each bounding surface. We need to treat - ! special case where the cosine of the angle is zero since this would - ! result in a divide-by-zero. - do d1 = 1, n_dim - if (uvw(d1) == 0) then - d(d1) = INFINITY - else - d(d1) = (xyz_cross(d1) - xyz0(d1))/uvw(d1) - end if - end do - - ! Determine the closest bounding surface of the mesh cell by - ! calculating the minimum distance. Then use the minimum distance and - ! direction of the particle to determine which surface was crossed. - distance = minval(d) - - ! Loop over the dimensions - do d1 = 1, n_dim - - ! Get the other dimensions. - if (d1 == 1) then - d2 = mod(d1, 3) + 1 - d3 = mod(d1 + 1, 3) + 1 - else - d2 = mod(d1 + 1, 3) + 1 - d3 = mod(d1, 3) + 1 - end if - - ! Check whether distance is the shortest distance - if (distance == d(d1)) then - - ! Check whether particle is moving in positive d1 direction - if (uvw(d1) > 0) then - - ! Outward current on d1 max surface - if (all(ijk0(:n_dim) >= 1) .and. & - all(ijk0(:n_dim) <= m % dimension)) then - filter_matches(i_filter_surf) % bins % data(1) = d1 * 4 - 1 - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices(ijk0) - filter_index = 1 - do k = 1, size(t % filter) - filter_index = filter_index + (filter_matches(t % & - filter(k)) % bins % data(1) - 1) * t % stride(k) - end do -!$omp atomic - t % results(RESULT_VALUE, 1, filter_index) = & - t % results(RESULT_VALUE, 1, filter_index) + p % wgt - end if - - ! Inward current on d1 min surface - cross_surface = .false. - select case(n_dim) - - case (1) - if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1)) then - cross_surface = .true. - end if - - case (2) - if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1) .and. & - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2)) then - cross_surface = .true. - end if - - case (3) - if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1) .and. & - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2) .and. & - ijk0(d3) >= 1 .and. ijk0(d3) <= m % dimension(d3)) then - cross_surface = .true. - end if - end select - - ! If the particle crossed the surface, tally the current - if (cross_surface) then - ijk0(d1) = ijk0(d1) + 1 - filter_matches(i_filter_surf) % bins % data(1) = d1 * 4 - 2 - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices(ijk0) - filter_index = 1 - do k = 1, size(t % filter) - filter_index = filter_index + (filter_matches(t % & - filter(k)) % bins % data(1) - 1) * t % stride(k) - end do -!$omp atomic - t % results(RESULT_VALUE, 1, filter_index) = & - t % results(RESULT_VALUE, 1, filter_index) + p % wgt - ijk0(d1) = ijk0(d1) - 1 - end if - - ijk0(d1) = ijk0(d1) + 1 - xyz_cross(d1) = xyz_cross(d1) + m % width(d1) - - ! The particle is moving in the negative d1 direction - else - - ! Outward current on d1 min surface - if (all(ijk0(:n_dim) >= 1) .and. & - all(ijk0(:n_dim) <= m % dimension)) then - filter_matches(i_filter_surf) % bins % data(1) = d1 * 4 - 3 - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices(ijk0) - filter_index = 1 - do k = 1, size(t % filter) - filter_index = filter_index + (filter_matches(t % & - filter(k)) % bins % data(1) - 1) * t % stride(k) - end do -!$omp atomic - t % results(RESULT_VALUE, 1, filter_index) = & - t % results(RESULT_VALUE, 1, filter_index) + p % wgt - end if - - ! Inward current on d1 max surface - cross_surface = .false. - select case(n_dim) - - case (1) - if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1) then - cross_surface = .true. - end if - - case (2) - if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1 .and.& - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2)) then - cross_surface = .true. - end if - - case (3) - if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1 .and.& - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2) .and. & - ijk0(d3) >= 1 .and. ijk0(d3) <= m % dimension(d3)) then - cross_surface = .true. - end if - end select - - ! If the particle crossed the surface, tally the current - if (cross_surface) then - ijk0(d1) = ijk0(d1) - 1 - filter_matches(i_filter_surf) % bins % data(1) = d1 * 4 - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices(ijk0) - filter_index = 1 - do k = 1, size(t % filter) - filter_index = filter_index + (filter_matches(t % & - filter(k)) % bins % data(1) - 1) * t % stride(k) - end do -!$omp atomic - t % results(RESULT_VALUE, 1, filter_index) = & - t % results(RESULT_VALUE, 1, filter_index) + p % wgt - ijk0(d1) = ijk0(d1) + 1 - end if - - ijk0(d1) = ijk0(d1) - 1 - xyz_cross(d1) = xyz_cross(d1) - m % width(d1) - end if - end if - end do - - ! Calculate new coordinates - xyz0 = xyz0 + distance * uvw - end do - - end associate - end do TALLY_LOOP - - end subroutine score_surface_current - !=============================================================================== ! APPLY_DERIVATIVE_TO_SCORE multiply the given score by its relative derivative !=============================================================================== @@ -4241,7 +3973,7 @@ contains real(C_DOUBLE) :: k_tra ! Copy of batch tracklength estimate of keff real(C_DOUBLE) :: val -#ifdef MPI +#ifdef OPENMC_MPI ! Combine tally results onto master process if (reduce_tallies) call reduce_tally_results() #endif @@ -4289,7 +4021,7 @@ contains ! REDUCE_TALLY_RESULTS collects all the results from tallies onto one processor !=============================================================================== -#ifdef MPI +#ifdef OPENMC_MPI subroutine reduce_tally_results() integer :: i @@ -4359,7 +4091,7 @@ contains call active_collision_tallies % clear() call active_tracklength_tallies % clear() call active_surface_tallies % clear() - call active_current_tallies % clear() + call active_meshsurf_tallies % clear() do i = 1, n_tallies associate (t => tallies(i) % obj) @@ -4376,8 +4108,8 @@ contains elseif (t % estimator == ESTIMATOR_COLLISION) then call active_collision_tallies % push_back(i) end if - elseif (t % type == TALLY_MESH_CURRENT) then - call active_current_tallies % push_back(i) + elseif (t % type == TALLY_MESH_SURFACE) then + call active_meshsurf_tallies % push_back(i) elseif (t % type == TALLY_SURFACE) then call active_surface_tallies % push_back(i) end if diff --git a/src/tallies/tally_filter.F90 b/src/tallies/tally_filter.F90 index 587f8dd902..3d6eaaef21 100644 --- a/src/tallies/tally_filter.F90 +++ b/src/tallies/tally_filter.F90 @@ -19,6 +19,7 @@ module tally_filter use tally_filter_energyfunc use tally_filter_material use tally_filter_mesh + use tally_filter_meshsurface use tally_filter_mu use tally_filter_polar use tally_filter_surface @@ -67,6 +68,8 @@ contains type_ = 'material' type is (MeshFilter) type_ = 'mesh' + type is (MeshSurfaceFilter) + type_ = 'meshsurface' type is (MuFilter) type_ = 'mu' type is (PolarFilter) @@ -136,6 +139,8 @@ contains allocate(MaterialFilter :: filters(index) % obj) case ('mesh') allocate(MeshFilter :: filters(index) % obj) + case ('meshsurface') + allocate(MeshSurfaceFilter :: filters(index) % obj) case ('mu') allocate(MuFilter :: filters(index) % obj) case ('polar') diff --git a/src/tallies/tally_filter_energy.F90 b/src/tallies/tally_filter_energy.F90 index 2a247cf358..caba6755d1 100644 --- a/src/tallies/tally_filter_energy.F90 +++ b/src/tallies/tally_filter_energy.F90 @@ -211,6 +211,10 @@ contains energies = C_LOC(f % bins) n = size(f % bins) err = 0 + type is (EnergyoutFilter) + energies = C_LOC(f % bins) + n = size(f % bins) + err = 0 class default err = E_INVALID_TYPE call set_errmsg("Tried to get energy bins on a non-energy filter.") @@ -242,6 +246,11 @@ contains if (allocated(f % bins)) deallocate(f % bins) allocate(f % bins(n)) f % bins(:) = energies + type is (EnergyoutFilter) + f % n_bins = n - 1 + if (allocated(f % bins)) deallocate(f % bins) + allocate(f % bins(n)) + f % bins(:) = energies class default err = E_INVALID_TYPE call set_errmsg("Tried to get energy bins on a non-energy filter.") diff --git a/src/tallies/tally_filter_mesh.F90 b/src/tallies/tally_filter_mesh.F90 index 2092e7e717..3c0e6250c2 100644 --- a/src/tallies/tally_filter_mesh.F90 +++ b/src/tallies/tally_filter_mesh.F90 @@ -84,7 +84,6 @@ contains integer :: ijk1(3) ! indices of ending coordinates integer :: search_iter ! loop count for intersection search integer :: bin - real(8) :: weight ! weight to be pushed back real(8) :: uvw(3) ! cosine of angle of particle real(8) :: xyz0(3) ! starting/intermediate coordinates real(8) :: xyz1(3) ! ending coordinates of particle @@ -96,8 +95,6 @@ contains logical :: end_in_mesh ! ending coordinates inside mesh? type(RegularMesh), pointer :: m - weight = ERROR_REAL - ! Get a pointer to the mesh. m => meshes(this % mesh) n = m % n_dimension diff --git a/src/tallies/tally_filter_meshsurface.F90 b/src/tallies/tally_filter_meshsurface.F90 new file mode 100644 index 0000000000..e1e8c48033 --- /dev/null +++ b/src/tallies/tally_filter_meshsurface.F90 @@ -0,0 +1,334 @@ +module tally_filter_meshsurface + + use, intrinsic :: ISO_C_BINDING + + use hdf5 + + use constants + use dict_header, only: EMPTY + use error + use mesh_header, only: RegularMesh, meshes, n_meshes, mesh_dict + use hdf5_interface + use particle_header, only: Particle + use string, only: to_str + use tally_filter_header + use xml_interface + + implicit none + private + public :: openmc_meshsurface_filter_set_mesh + +!=============================================================================== +! MESHFILTER indexes the location of particle events to a regular mesh. For +! tracklength tallies, it will produce multiple valid bins and the bin weight +! will correspond to the fraction of the track length that lies in that bin. +!=============================================================================== + + type, public, extends(TallyFilter) :: MeshSurfaceFilter + integer :: mesh + contains + procedure :: from_xml + procedure :: get_all_bins + procedure :: to_statepoint + procedure :: text_label + end type MeshSurfaceFilter + +contains + + subroutine from_xml(this, node) + class(MeshSurfaceFilter), intent(inout) :: this + type(XMLNode), intent(in) :: node + + integer :: i_mesh + integer :: id + integer :: n + integer :: n_dim + integer :: val + + n = node_word_count(node, "bins") + + if (n /= 1) call fatal_error("Only one mesh can be & + &specified per meshsurface filter.") + + ! Determine id of mesh + call get_node_value(node, "bins", id) + + ! Get pointer to mesh + val = mesh_dict % get(id) + if (val /= EMPTY) then + i_mesh = val + else + call fatal_error("Could not find mesh " // trim(to_str(id)) & + // " specified on filter.") + end if + + ! Determine number of bins + n_dim = meshes(i_mesh) % n_dimension + this % n_bins = 4*n_dim*product(meshes(i_mesh) % dimension) + + ! Store the index of the mesh + this % mesh = i_mesh + end subroutine from_xml + + subroutine get_all_bins(this, p, estimator, match) + class(MeshSurfaceFilter), intent(in) :: this + type(Particle), intent(in) :: p + integer, intent(in) :: estimator + type(TallyFilterMatch), intent(inout) :: match + + integer :: j ! loop indices + integer :: n_dim ! num dimensions of the mesh + integer :: d1 ! dimension index + integer :: ijk0(3) ! indices of starting coordinates + integer :: ijk1(3) ! indices of ending coordinates + integer :: n_cross ! number of surface crossings + integer :: i_mesh ! flattened mesh bin index + integer :: i_surf ! surface index (1--12) + integer :: i_bin ! actual index for filter + real(8) :: uvw(3) ! cosine of angle of particle + real(8) :: xyz0(3) ! starting/intermediate coordinates + real(8) :: xyz1(3) ! ending coordinates of particle + real(8) :: xyz_cross(3) ! coordinates of bounding surfaces + real(8) :: d(3) ! distance to each bounding surface + real(8) :: distance ! actual distance traveled + logical :: start_in_mesh ! particle's starting xyz in mesh? + logical :: end_in_mesh ! particle's ending xyz in mesh? + + ! Copy starting and ending location of particle + xyz0 = p % last_xyz_current + xyz1 = p % coord(1) % xyz + + associate (m => meshes(this % mesh)) + n_dim = m % n_dimension + + ! Determine indices for starting and ending location + call m % get_indices(xyz0, ijk0, start_in_mesh) + call m % get_indices(xyz1, ijk1, end_in_mesh) + + ! Check to see if start or end is in mesh -- if not, check if track still + ! intersects with mesh + if ((.not. start_in_mesh) .and. (.not. end_in_mesh)) then + if (.not. m % intersects(xyz0, xyz1)) return + end if + + ! Calculate number of surface crossings + n_cross = sum(abs(ijk1(:n_dim) - ijk0(:n_dim))) + if (n_cross == 0) return + + ! Copy particle's direction + uvw = p % coord(1) % uvw + + ! Bounding coordinates + do d1 = 1, n_dim + if (uvw(d1) > 0) then + xyz_cross(d1) = m % lower_left(d1) + ijk0(d1) * m % width(d1) + else + xyz_cross(d1) = m % lower_left(d1) + (ijk0(d1) - 1) * m % width(d1) + end if + end do + + do j = 1, n_cross + ! Set the distances to infinity + d = INFINITY + + ! Calculate distance to each bounding surface. We need to treat + ! special case where the cosine of the angle is zero since this would + ! result in a divide-by-zero. + do d1 = 1, n_dim + if (uvw(d1) == 0) then + d(d1) = INFINITY + else + d(d1) = (xyz_cross(d1) - xyz0(d1))/uvw(d1) + end if + end do + + ! Determine the closest bounding surface of the mesh cell by + ! calculating the minimum distance. Then use the minimum distance and + ! direction of the particle to determine which surface was crossed. + distance = minval(d) + + ! Loop over the dimensions + do d1 = 1, n_dim + + ! Check whether distance is the shortest distance + if (distance == d(d1)) then + + ! Check whether particle is moving in positive d1 direction + if (uvw(d1) > 0) then + + ! Outward current on d1 max surface + if (all(ijk0(:n_dim) >= 1) .and. & + all(ijk0(:n_dim) <= m % dimension)) then + i_surf = d1 * 4 - 1 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*(i_mesh - 1) + i_surf + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + end if + + ! Advance position + ijk0(d1) = ijk0(d1) + 1 + xyz_cross(d1) = xyz_cross(d1) + m % width(d1) + + ! If the particle crossed the surface, tally the inward current on + ! d1 min surface + if (all(ijk0(:n_dim) >= 1) .and. & + all(ijk0(:n_dim) <= m % dimension)) then + i_surf = d1 * 4 - 2 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*(i_mesh - 1) + i_surf + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + end if + + else + ! The particle is moving in the negative d1 direction + + ! Outward current on d1 min surface + if (all(ijk0(:n_dim) >= 1) .and. & + all(ijk0(:n_dim) <= m % dimension)) then + i_surf = d1 * 4 - 3 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*(i_mesh - 1) + i_surf + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + end if + + ! Advance position + ijk0(d1) = ijk0(d1) - 1 + xyz_cross(d1) = xyz_cross(d1) - m % width(d1) + + ! If the particle crossed the surface, tally the inward current on + ! d1 max surface + if (all(ijk0(:n_dim) >= 1) .and. & + all(ijk0(:n_dim) <= m % dimension)) then + i_surf = d1 * 4 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*(i_mesh - 1) + i_surf + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + end if + end if + end if + end do + + ! Calculate new coordinates + xyz0 = xyz0 + distance * uvw + end do + end associate + + end subroutine get_all_bins + + subroutine to_statepoint(this, filter_group) + class(MeshSurfaceFilter), intent(in) :: this + integer(HID_T), intent(in) :: filter_group + + call write_dataset(filter_group, "type", "meshsurface") + call write_dataset(filter_group, "n_bins", this % n_bins) + call write_dataset(filter_group, "bins", meshes(this % mesh) % id) + end subroutine to_statepoint + + function text_label(this, bin) result(label) + class(MeshSurfaceFilter), intent(in) :: this + integer, intent(in) :: bin + character(MAX_LINE_LEN) :: label + + integer :: i_mesh + integer :: i_surf + integer :: n_dim + integer, allocatable :: ijk(:) + + associate (m => meshes(this % mesh)) + n_dim = m % n_dimension + allocate(ijk(n_dim)) + + ! Get flattend mesh index and surface index + i_mesh = (bin - 1) / (4*n_dim) + 1 + i_surf = mod(bin - 1, 4*n_dim) + 1 + + ! Get mesh index part of label + call m % get_indices_from_bin(i_mesh, ijk) + if (m % n_dimension == 1) then + label = "Mesh Index (" // trim(to_str(ijk(1))) // ")" + elseif (m % n_dimension == 2) then + label = "Mesh Index (" // trim(to_str(ijk(1))) // ", " // & + trim(to_str(ijk(2))) // ")" + elseif (m % n_dimension == 3) then + label = "Mesh Index (" // trim(to_str(ijk(1))) // ", " // & + trim(to_str(ijk(2))) // ", " // trim(to_str(ijk(3))) // ")" + end if + + ! Get surface part of label + select case (i_surf) + case (OUT_LEFT) + label = trim(label) // " Outgoing, x-min" + case (IN_LEFT) + label = trim(label) // " Incoming, x-min" + case (OUT_RIGHT) + label = trim(label) // " Outgoing, x-max" + case (IN_RIGHT) + label = trim(label) // " Incoming, x-max" + case (OUT_BACK) + label = trim(label) // " Outgoing, y-min" + case (IN_BACK) + label = trim(label) // " Incoming, y-min" + case (OUT_FRONT) + label = trim(label) // " Outgoing, y-max" + case (IN_FRONT) + label = trim(label) // " Incoming, y-max" + case (OUT_BOTTOM) + label = trim(label) // " Outgoing, z-min" + case (IN_BOTTOM) + label = trim(label) // " Incoming, z-min" + case (OUT_TOP) + label = trim(label) // " Outgoing, z-max" + case (IN_TOP) + label = trim(label) // " Incoming, z-max" + end select + end associate + end function text_label + +!=============================================================================== +! C API FUNCTIONS +!=============================================================================== + + function openmc_meshsurface_filter_set_mesh(index, index_mesh) result(err) bind(C) + ! Set the mesh for a mesh surface filter + integer(C_INT32_T), value, intent(in) :: index + integer(C_INT32_T), value, intent(in) :: index_mesh + integer(C_INT) :: err + + integer :: n_dim + + err = 0 + if (index >= 1 .and. index <= n_filters) then + if (allocated(filters(index) % obj)) then + select type (f => filters(index) % obj) + type is (MeshSurfaceFilter) + if (index_mesh >= 1 .and. index_mesh <= n_meshes) then + f % mesh = index_mesh + n_dim = meshes(index_mesh) % n_dimension + f % n_bins = 4*n_dim*product(meshes(index_mesh) % dimension) + else + err = E_OUT_OF_BOUNDS + call set_errmsg("Index in 'meshes' array is out of bounds.") + end if + class default + err = E_INVALID_TYPE + call set_errmsg("Tried to set mesh on a non-mesh filter.") + end select + else + err = E_ALLOCATE + call set_errmsg("Filter type has not been set yet.") + end if + else + err = E_OUT_OF_BOUNDS + call set_errmsg("Index in filters array out of bounds.") + end if + end function openmc_meshsurface_filter_set_mesh + +end module tally_filter_meshsurface diff --git a/src/tallies/tally_filter_surface.F90 b/src/tallies/tally_filter_surface.F90 index daecd88917..df3bf36031 100644 --- a/src/tallies/tally_filter_surface.F90 +++ b/src/tallies/tally_filter_surface.F90 @@ -105,7 +105,7 @@ contains integer, intent(in) :: bin character(MAX_LINE_LEN) :: label - label = "Surface " // to_str(surfaces(this % surfaces(bin)) % obj % id) + label = "Surface " // to_str(surfaces(this % surfaces(bin)) % id()) end function text_label_surface end module tally_filter_surface diff --git a/src/tallies/tally_header.F90 b/src/tallies/tally_header.F90 index 474e77d1ce..0495ce14dc 100644 --- a/src/tallies/tally_header.F90 +++ b/src/tallies/tally_header.F90 @@ -144,7 +144,7 @@ module tally_header ! Active tally lists type(VectorInt), public :: active_analog_tallies type(VectorInt), public :: active_tracklength_tallies - type(VectorInt), public :: active_current_tallies + type(VectorInt), public :: active_meshsurf_tallies type(VectorInt), public :: active_collision_tallies type(VectorInt), public :: active_tallies type(VectorInt), public :: active_surface_tallies @@ -336,6 +336,8 @@ contains j = FILTER_SURFACE type is (MeshFilter) j = FILTER_MESH + type is (MeshSurfaceFilter) + j = FILTER_MESHSURFACE type is (EnergyFilter) j = FILTER_ENERGYIN type is (EnergyoutFilter) @@ -416,7 +418,7 @@ contains ! Deallocate tally node lists call active_analog_tallies % clear() call active_tracklength_tallies % clear() - call active_current_tallies % clear() + call active_meshsurf_tallies % clear() call active_collision_tallies % clear() call active_surface_tallies % clear() call active_tallies % clear() @@ -732,8 +734,10 @@ contains integer :: MT character(C_CHAR), pointer :: string(:) character(len=:, kind=C_CHAR), allocatable :: score_ + logical :: depletion_rx err = E_UNASSIGNED + depletion_rx = .false. if (index >= 1 .and. index <= size(tallies)) then associate (t => tallies(index) % obj) if (allocated(t % score_bins)) deallocate(t % score_bins) @@ -757,10 +761,13 @@ contains t % score_bins(i) = SCORE_NU_SCATTER case ('(n,2n)') t % score_bins(i) = N_2N + depletion_rx = .true. case ('(n,3n)') t % score_bins(i) = N_3N + depletion_rx = .true. case ('(n,4n)') t % score_bins(i) = N_4N + depletion_rx = .true. case ('absorption') t % score_bins(i) = SCORE_ABSORPTION case ('fission', '18') @@ -829,8 +836,10 @@ contains t % score_bins(i) = N_NC case ('(n,gamma)') t % score_bins(i) = N_GAMMA + depletion_rx = .true. case ('(n,p)') t % score_bins(i) = N_P + depletion_rx = .true. case ('(n,d)') t % score_bins(i) = N_D case ('(n,t)') @@ -839,6 +848,7 @@ contains t % score_bins(i) = N_3HE case ('(n,a)') t % score_bins(i) = N_A + depletion_rx = .true. case ('(n,2a)') t % score_bins(i) = N_2A case ('(n,3a)') @@ -879,6 +889,7 @@ contains end do err = 0 + t % depletion_rx = depletion_rx end associate else err = E_OUT_OF_BOUNDS diff --git a/src/tallies/trigger.F90 b/src/tallies/trigger.F90 index 9e9b06d205..7dcb3d71eb 100644 --- a/src/tallies/trigger.F90 +++ b/src/tallies/trigger.F90 @@ -2,7 +2,7 @@ module trigger use, intrinsic :: ISO_C_BINDING -#ifdef MPI +#ifdef OPENMC_MPI use message_passing #endif @@ -168,7 +168,7 @@ contains trigger % variance = ZERO ! Mesh current tally triggers require special treatment - if (t % type == TALLY_MESH_CURRENT) then + if (t % type == TALLY_MESH_SURFACE) then call compute_tally_current(t, trigger) else diff --git a/src/tracking.F90 b/src/tracking.F90 index 65769a7f18..3fe6a065b7 100644 --- a/src/tracking.F90 +++ b/src/tracking.F90 @@ -1,11 +1,11 @@ module tracking use constants - use cross_section, only: calculate_xs - use error, only: fatal_error, warning, write_message + use error, only: warning, write_message use geometry_header, only: cells - use geometry, only: find_cell, distance_to_boundary, cross_lattice, & + use geometry, only: find_cell, distance_to_boundary, cross_lattice,& check_cell_overlap + use material_header, only: materials, Material use message_passing use mgxs_header use nuclide_header @@ -19,9 +19,9 @@ module tracking use surface_header use tally_header use tally, only: score_analog_tally, score_tracklength_tally, & - score_collision_tally, score_surface_current, & - score_track_derivative, score_surface_tally, & - score_collision_derivative, zero_flux_derivs + score_collision_tally, score_surface_tally, & + score_track_derivative, zero_flux_derivs, & + score_collision_derivative use track_output, only: initialize_particle_track, write_particle_track, & add_particle_track, finalize_particle_track @@ -85,7 +85,9 @@ contains if (p % coord(p % n_coord) % cell == NONE) then call find_cell(p, found_cell) if (.not. found_cell) then - call fatal_error("Could not locate particle " // trim(to_str(p % id))) + call p % mark_as_lost("Could not find the cell containing" & + // " particle " // trim(to_str(p %id))) + return end if ! set birth cell attribute @@ -98,29 +100,30 @@ contains if (check_overlaps) call check_cell_overlap(p) ! Calculate microscopic and macroscopic cross sections - if (run_CE) then - ! If the material is the same as the last material and the temperature - ! hasn't changed, we don't need to lookup cross sections again. - if (p % material /= p % last_material .or. & - p % sqrtkT /= p % last_sqrtkT) call calculate_xs(p) - else - ! Since the MGXS can be angle dependent, this needs to be done - ! After every collision for the MGXS mode - if (p % material /= MATERIAL_VOID) then - ! Update the temperature index - call macro_xs(p % material) % obj % find_temperature(p % sqrtkT) - ! Get the data - call macro_xs(p % material) % obj % calculate_xs(p % g, & - p % coord(p % n_coord) % uvw, material_xs) + if (p % material /= MATERIAL_VOID) then + if (run_CE) then + if (p % material /= p % last_material .or. & + p % sqrtkT /= p % last_sqrtkT) then + ! If the material is the same as the last material and the + ! temperature hasn't changed, we don't need to lookup cross + ! sections again. + call materials(p % material) % calculate_xs(p % E, p % sqrtkT, & + micro_xs, nuclides, material_xs) + end if else - material_xs % total = ZERO - material_xs % absorption = ZERO - material_xs % nu_fission = ZERO - end if + ! Get the MG data + call macro_xs(p % material) % obj % calculate_xs(p % g, p % sqrtkT, & + p % coord(p % n_coord) % uvw, material_xs) - ! Finally, update the particle group while we have already checked for - ! if multi-group - p % last_g = p % g + ! Finally, update the particle group while we have already checked + ! for if multi-group + p % last_g = p % g + end if + else + material_xs % total = ZERO + material_xs % absorption = ZERO + material_xs % fission = ZERO + material_xs % nu_fission = ZERO end if ! Find the distance to the nearest boundary @@ -182,7 +185,8 @@ contains p % event = EVENT_SURFACE end if ! Score cell to cell partial currents - if(active_surface_tallies % size() > 0) call score_surface_tally(p) + if(active_surface_tallies % size() > 0) & + call score_surface_tally(p, active_surface_tallies) else ! ==================================================================== ! PARTICLE HAS COLLISION @@ -197,7 +201,8 @@ contains ! since the direction of the particle will change and we need to use the ! pre-collision direction to figure out what mesh surfaces were crossed - if (active_current_tallies % size() > 0) call score_surface_current(p) + if (active_meshsurf_tallies % size() > 0) & + call score_surface_tally(p, active_meshsurf_tallies) ! Clear surface component p % surface = NONE @@ -290,20 +295,20 @@ contains real(8) :: v ! y-component of direction real(8) :: w ! z-component of direction real(8) :: norm ! "norm" of surface normal - real(8) :: d ! distance between point and plane real(8) :: xyz(3) ! Saved global coordinate integer :: i_surface ! index in surfaces logical :: rotational ! if rotational periodic BC applied logical :: found ! particle found in universe? class(Surface), pointer :: surf + class(Surface), pointer :: surf2 ! periodic partner surface i_surface = abs(p % surface) - surf => surfaces(i_surface)%obj + surf => surfaces(i_surface) if (verbosity >= 10 .or. trace) then - call write_message(" Crossing surface " // trim(to_str(surf % id))) + call write_message(" Crossing surface " // trim(to_str(surf % id()))) end if - if (surf % bc == BC_VACUUM .and. (run_mode /= MODE_PLOTTING)) then + if (surf % bc() == BC_VACUUM .and. (run_mode /= MODE_PLOTTING)) then ! ======================================================================= ! PARTICLE LEAKS OUT OF PROBLEM @@ -314,12 +319,12 @@ contains ! forward slightly so that if the mesh boundary is on the surface, it is ! still processed - if (active_current_tallies % size() > 0) then + if (active_meshsurf_tallies % size() > 0) then ! TODO: Find a better solution to score surface currents than ! physically moving the particle forward slightly p % coord(1) % xyz = p % coord(1) % xyz + TINY_BIT * p % coord(1) % uvw - call score_surface_current(p) + call score_surface_tally(p, active_meshsurf_tallies) end if ! Score to global leakage tally @@ -328,11 +333,11 @@ contains ! Display message if (verbosity >= 10 .or. trace) then call write_message(" Leaked out of surface " & - &// trim(to_str(surf % id))) + &// trim(to_str(surf % id()))) end if return - elseif (surf % bc == BC_REFLECT .and. (run_mode /= MODE_PLOTTING)) then + elseif (surf % bc() == BC_REFLECT .and. (run_mode /= MODE_PLOTTING)) then ! ======================================================================= ! PARTICLE REFLECTS FROM SURFACE @@ -347,15 +352,15 @@ contains ! particle to change -- artificially move the particle slightly back in ! case the surface crossing is coincident with a mesh boundary - if (active_current_tallies % size() > 0) then + if (active_meshsurf_tallies % size() > 0) then xyz = p % coord(1) % xyz p % coord(1) % xyz = p % coord(1) % xyz - TINY_BIT * p % coord(1) % uvw - call score_surface_current(p) + call score_surface_tally(p, active_meshsurf_tallies) p % coord(1) % xyz = xyz end if ! Reflect particle off surface - call surf%reflect(p%coord(1)%xyz, p%coord(1)%uvw) + call surf % reflect(p%coord(1)%xyz, p%coord(1)%uvw) ! Make sure new particle direction is normalized u = p%coord(1)%uvw(1) @@ -376,7 +381,7 @@ contains call find_cell(p, found) if (.not. found) then call p % mark_as_lost("Couldn't find particle after reflecting& - & from surface " // trim(to_str(surf % id)) // ".") + & from surface " // trim(to_str(surf % id())) // ".") return end if @@ -386,10 +391,10 @@ contains ! Diagnostic message if (verbosity >= 10 .or. trace) then call write_message(" Reflected from surface " & - &// trim(to_str(surf%id))) + &// trim(to_str(surf%id()))) end if return - elseif (surf % bc == BC_PERIODIC .and. run_mode /= MODE_PLOTTING) then + elseif (surf % bc() == BC_PERIODIC .and. run_mode /= MODE_PLOTTING) then ! ======================================================================= ! PERIODIC BOUNDARY @@ -404,78 +409,26 @@ contains ! Score surface currents since reflection causes the direction of the ! particle to change -- artificially move the particle slightly back in ! case the surface crossing is coincident with a mesh boundary - - if (active_current_tallies % size() > 0) then + if (active_meshsurf_tallies % size() > 0) then xyz = p % coord(1) % xyz p % coord(1) % xyz = p % coord(1) % xyz - TINY_BIT * p % coord(1) % uvw - call score_surface_current(p) + call score_surface_tally(p, active_meshsurf_tallies) p % coord(1) % xyz = xyz end if - rotational = .false. - select type (surf) - type is (SurfaceXPlane) - select type (opposite => surfaces(surf % i_periodic) % obj) - type is (SurfaceXPlane) - p % coord(1) % xyz(1) = opposite % x0 - type is (SurfaceYPlane) - rotational = .true. + ! Get a pointer to the partner periodic surface. Offset the index to + ! correct for C vs. Fortran indexing. + surf2 => surfaces(surf % i_periodic() + 1) - ! Rotate direction - u = p % coord(1) % uvw(1) - v = p % coord(1) % uvw(2) - p % coord(1) % uvw(1) = v - p % coord(1) % uvw(2) = -u - - ! Rotate position - p % coord(1) % xyz(1) = surf % x0 + p % coord(1) % xyz(2) - opposite % y0 - p % coord(1) % xyz(2) = opposite % y0 - end select - - type is (SurfaceYPlane) - select type (opposite => surfaces(surf % i_periodic) % obj) - type is (SurfaceYPlane) - p % coord(1) % xyz(2) = opposite % y0 - type is (SurfaceXPlane) - rotational = .true. - - ! Rotate direction - u = p % coord(1) % uvw(1) - v = p % coord(1) % uvw(2) - p % coord(1) % uvw(1) = -v - p % coord(1) % uvw(2) = u - - ! Rotate position - p % coord(1) % xyz(2) = surf % y0 + p % coord(1) % xyz(1) - opposite % x0 - p % coord(1) % xyz(1) = opposite % x0 - end select - - type is (SurfaceZPlane) - select type (opposite => surfaces(surf % i_periodic) % obj) - type is (SurfaceZPlane) - p % coord(1) % xyz(3) = opposite % z0 - end select - - type is (SurfacePlane) - select type (opposite => surfaces(surf % i_periodic) % obj) - type is (SurfacePlane) - ! Get surface normal for opposite plane - xyz(:) = opposite % normal(p % coord(1) % xyz) - - ! Determine distance to plane - norm = xyz(1)*xyz(1) + xyz(2)*xyz(2) + xyz(3)*xyz(3) - d = opposite % evaluate(p % coord(1) % xyz) / norm - - ! Move particle along normal vector based on distance - p % coord(1) % xyz(:) = p % coord(1) % xyz(:) - d*xyz - end select - end select + ! Adjust the particle's location and direction. + rotational = surf2 % periodic_translate(surf, p % coord(1) % xyz, & + p % coord(1) % uvw) ! Reassign particle's surface if (rotational) then - p % surface = surf % i_periodic + p % surface = surf % i_periodic() + 1 else - p % surface = sign(surf % i_periodic, p % surface) + p % surface = sign(surf % i_periodic() + 1, p % surface) end if ! Figure out what cell particle is in now @@ -483,7 +436,8 @@ contains call find_cell(p, found) if (.not. found) then call p % mark_as_lost("Couldn't find particle after hitting & - &periodic boundary on surface " // trim(to_str(surf % id)) // ".") + &periodic boundary on surface " // trim(to_str(surf % id())) & + // ".") return end if @@ -493,7 +447,7 @@ contains ! Diagnostic message if (verbosity >= 10 .or. trace) then call write_message(" Hit periodic boundary on surface " & - // trim(to_str(surf%id))) + // trim(to_str(surf%id()))) end if return end if @@ -540,7 +494,7 @@ contains if (.not. found) then call p % mark_as_lost("After particle " // trim(to_str(p % id)) & - // " crossed surface " // trim(to_str(surf % id)) & + // " crossed surface " // trim(to_str(surf % id())) & // " it could not be located in any cell and it did not leak.") return end if diff --git a/src/volume_calc.F90 b/src/volume_calc.F90 index 5985a236b3..e374f21064 100644 --- a/src/volume_calc.F90 +++ b/src/volume_calc.F90 @@ -136,7 +136,7 @@ contains integer :: total_hits ! total hits for a single domain (summed over materials) integer :: min_samples ! minimum number of samples per process integer :: remainder ! leftover samples from uneven divide -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code integer :: m ! index over materials integer :: n ! number of materials @@ -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 @@ -279,7 +281,7 @@ contains total_hits = 0 if (master) then -#ifdef MPI +#ifdef OPENMC_MPI do j = 1, n_procs - 1 call MPI_RECV(n, 1, MPI_INTEGER, j, 0, mpi_intracomm, & MPI_STATUS_IGNORE, mpi_err) @@ -341,7 +343,7 @@ contains end do else -#ifdef MPI +#ifdef OPENMC_MPI n = master_indices(i_domain) % size() allocate(data(2*n)) do k = 0, n - 1 diff --git a/src/xml_interface.h b/src/xml_interface.h new file mode 100644 index 0000000000..778497562b --- /dev/null +++ b/src/xml_interface.h @@ -0,0 +1,48 @@ +#ifndef XML_INTERFACE_H +#define XML_INTERFACE_H + +#include // for std::transform +#include +#include + +#include "pugixml/pugixml.hpp" + + +namespace openmc { + +bool +check_for_node(pugi::xml_node node, const char *name) +{ + return node.attribute(name) || node.child(name); +} + + +std::string +get_node_value(pugi::xml_node node, const char *name) +{ + // Search for either an attribute or child tag and get the data as a char*. + const pugi::char_t *value_char; + if (node.attribute(name)) { + value_char = node.attribute(name).value(); + } else if (node.child(name)) { + value_char = node.child_value(name); + } else { + std::stringstream err_msg; + err_msg << "Node \"" << name << "\" is not a member of the \"" + << node.name() << "\" XML node"; + fatal_error(err_msg); + } + + // Convert to lowercase string. + std::string value(value_char); + std::transform(value.begin(), value.end(), value.begin(), ::tolower); + + // Remove whitespace. + value.erase(0, value.find_first_not_of(" \t\r\n")); + value.erase(value.find_last_not_of(" \t\r\n") + 1); + + return value; +} + +} // namespace openmc +#endif // XML_INTERFACE_H diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000..5c21cd9380 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +from contextlib import contextmanager +import os +import tempfile + + +@contextmanager +def cdtemp(): + """Context manager to change to/return from a tmpdir.""" + with tempfile.TemporaryDirectory() as tmpdir: + cwd = os.getcwd() + try: + os.chdir(tmpdir) + yield + finally: + os.chdir(cwd) diff --git a/tests/chain_simple.xml b/tests/chain_simple.xml new file mode 100644 index 0000000000..c2e50a370f --- /dev/null +++ b/tests/chain_simple.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + 2.53000e-02 + + Gd157 Gd156 I135 Xe135 Xe136 Cs135 + 1.093250e-04 2.087260e-04 2.780820e-02 6.759540e-03 2.392300e-02 4.356330e-05 + + + + + + + 2.53000e-02 + + Gd157 Gd156 I135 Xe135 Xe136 Cs135 + 6.142710e-5 1.483250e-04 0.0292737 0.002566345 0.0219242 4.9097e-6 + + + + + + + 2.53000e-02 + + Gd157 Gd156 I135 Xe135 Xe136 Cs135 + 4.141120e-04 7.605360e-04 0.0135457 0.00026864 0.0024432 3.7100E-07 + + + + diff --git a/tests/check_source.py b/tests/check_source.py index 3a79d44c28..78cef2a0cd 100755 --- a/tests/check_source.py +++ b/tests/check_source.py @@ -1,6 +1,4 @@ -#!/usr/bin/env python - -from __future__ import print_function +#!/usr/bin/env python3 import glob from string import whitespace diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000..dc55e8e1e9 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,28 @@ +import pytest + +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) + + +@pytest.fixture +def run_in_tmpdir(tmpdir): + orig = tmpdir.chdir() + try: + yield + finally: + orig.chdir() diff --git a/tests/convert_precision.py b/tests/convert_precision.py deleted file mode 100755 index 625fe49ca9..0000000000 --- a/tests/convert_precision.py +++ /dev/null @@ -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('..') diff --git a/tests/dummy_operator.py b/tests/dummy_operator.py new file mode 100644 index 0000000000..05fe97a950 --- /dev/null +++ b/tests/dummy_operator.py @@ -0,0 +1,156 @@ +import numpy as np +import scipy.sparse as sp +from openmc.deplete.reaction_rates import ReactionRates +from openmc.deplete.abc import TransportOperator, OperatorResult + + +class DummyOperator(TransportOperator): + """This is a dummy operator class with no statistical uncertainty. + + y_1' = sin(y_2) y_1 + cos(y_1) y_2 + y_2' = -cos(y_2) y_1 + sin(y_1) y_2 + + y_1(0) = 1 + y_2(0) = 1 + + y_1(1.5) ~ 2.3197067076743316 + y_2(1.5) ~ 3.1726475740397628 + + """ + def __init__(self): + pass + + def __call__(self, vec, power, print_out=False): + """Evaluates F(y) + + Parameters + ---------- + vec : list of numpy.array + Total atoms to be used in function. + power : float + Power in [W] + print_out : bool, optional, ignored + Whether or not to print out time. + + Returns + ------- + openmc.deplete.OperatorResult + Result of transport operator + + """ + mats = ["1"] + nuclides = ["1", "2"] + reactions = ["1"] + + reaction_rates = ReactionRates(mats, nuclides, reactions) + + reaction_rates[0, 0, 0] = vec[0][0] + reaction_rates[0, 1, 0] = vec[0][1] + + # Create a fake rates object + return OperatorResult(0.0, reaction_rates) + + @property + def chain(self): + return self + + def form_matrix(self, rates): + """Forms the f(y) matrix in y' = f(y)y. + + Nominally a depletion matrix, this is abstracted on the off chance + that the function f has nothing to do with depletion at all. + + Parameters + ---------- + rates : numpy.ndarray + Slice of reaction rates for a single material + + Returns + ------- + scipy.sparse.csr_matrix + Sparse matrix representing f(y). + """ + + y_1 = rates[0, 0] + y_2 = rates[1, 0] + + mat = np.zeros((2, 2)) + a11 = np.sin(y_2) + a12 = np.cos(y_1) + a21 = -np.cos(y_2) + a22 = np.sin(y_1) + + return sp.csr_matrix(np.array([[a11, a12], [a21, a22]])) + + @property + def volume(self): + """ + volume : dict of str float + Volumes of material + """ + + return {"1": 0.0} + + @property + def nuc_list(self): + """ + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + """ + + return ["1", "2"] + + @property + def local_mats(self): + """ + local_mats : list of str + A list of all material IDs to be burned. Used for sorting the simulation. + """ + + return ["1"] + + @property + def burnable_mats(self): + """Maps cell name to index in global geometry.""" + return self.local_mats + + + @property + def reaction_rates(self): + """ + reaction_rates : ReactionRates + Reaction rates from the last operator step. + """ + mats = ["1"] + nuclides = ["1", "2"] + reactions = ["1"] + + return ReactionRates(mats, nuclides, reactions) + + def initial_condition(self): + """Returns initial vector. + + Returns + ------- + list of numpy.array + Total density for initial conditions. + """ + + return [np.array((1.0, 1.0))] + + def get_results_info(self): + """Returns volume list, cell lists, and nuc lists. + + Returns + ------- + volume : dict of str float + Volumes corresponding to materials in full_burn_dict + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + burn_list : list of int + A list of all cell IDs to be burned. Used for sorting the simulation. + full_burn_list : OrderedDict of str to int + Maps cell name to index in global geometry. + + """ + return self.volume, self.nuc_list, self.local_mats, self.burnable_mats diff --git a/tests/readme.rst b/tests/readme.rst index f2e2bb1c12..5e4b0227be 100644 --- a/tests/readme.rst +++ b/tests/readme.rst @@ -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=/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. diff --git a/tests/regression_tests/__init__.py b/tests/regression_tests/__init__.py new file mode 100644 index 0000000000..965a7f94db --- /dev/null +++ b/tests/regression_tests/__init__.py @@ -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 +} diff --git a/tests/regression_tests/asymmetric_lattice/__init__.py b/tests/regression_tests/asymmetric_lattice/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_asymmetric_lattice/inputs_true.dat b/tests/regression_tests/asymmetric_lattice/inputs_true.dat similarity index 99% rename from tests/test_asymmetric_lattice/inputs_true.dat rename to tests/regression_tests/asymmetric_lattice/inputs_true.dat index 672f6bee12..bbdc79715b 100644 --- a/tests/test_asymmetric_lattice/inputs_true.dat +++ b/tests/regression_tests/asymmetric_lattice/inputs_true.dat @@ -56,7 +56,7 @@ - + diff --git a/tests/test_asymmetric_lattice/results_true.dat b/tests/regression_tests/asymmetric_lattice/results_true.dat similarity index 100% rename from tests/test_asymmetric_lattice/results_true.dat rename to tests/regression_tests/asymmetric_lattice/results_true.dat diff --git a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py b/tests/regression_tests/asymmetric_lattice/test.py similarity index 94% rename from tests/test_asymmetric_lattice/test_asymmetric_lattice.py rename to tests/regression_tests/asymmetric_lattice/test.py index 58c1b22ab5..d6a0ab9b73 100644 --- a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py +++ b/tests/regression_tests/asymmetric_lattice/test.py @@ -1,17 +1,15 @@ -#!/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): - super(AsymmetricLatticeTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Extract universes encapsulating fuel and water assemblies geometry = self._model.geometry @@ -90,6 +88,6 @@ class AsymmetricLatticeTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_asymmetric_lattice(): harness = AsymmetricLatticeTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/cmfd_feed/__init__.py b/tests/regression_tests/cmfd_feed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_cmfd_feed/cmfd.xml b/tests/regression_tests/cmfd_feed/cmfd.xml similarity index 100% rename from tests/test_cmfd_feed/cmfd.xml rename to tests/regression_tests/cmfd_feed/cmfd.xml diff --git a/tests/test_cmfd_feed/geometry.xml b/tests/regression_tests/cmfd_feed/geometry.xml similarity index 100% rename from tests/test_cmfd_feed/geometry.xml rename to tests/regression_tests/cmfd_feed/geometry.xml diff --git a/tests/test_cmfd_feed/materials.xml b/tests/regression_tests/cmfd_feed/materials.xml similarity index 100% rename from tests/test_cmfd_feed/materials.xml rename to tests/regression_tests/cmfd_feed/materials.xml diff --git a/tests/regression_tests/cmfd_feed/results_true.dat b/tests/regression_tests/cmfd_feed/results_true.dat new file mode 100644 index 0000000000..5e6750fe6b --- /dev/null +++ b/tests/regression_tests/cmfd_feed/results_true.dat @@ -0,0 +1,487 @@ +k-combined: +1.169891E+00 6.289489E-03 +tally 1: +1.173922E+01 +1.385461E+01 +2.164076E+01 +4.699368E+01 +2.906462E+01 +8.464937E+01 +3.382312E+01 +1.147095E+02 +3.632006E+01 +1.323878E+02 +3.655413E+01 +1.341064E+02 +3.347757E+01 +1.124264E+02 +2.931336E+01 +8.607239E+01 +2.182947E+01 +4.789565E+01 +1.147668E+01 +1.325716E+01 +tally 2: +2.298190E+01 +2.667071E+01 +1.600292E+01 +1.293670E+01 +2.252427E+00 +2.605738E-01 +4.268506E+01 +9.161216E+01 +3.022909E+01 +4.598915E+01 +3.873926E+00 +7.615035E-01 +5.680399E+01 +1.623879E+02 +4.033805E+01 +8.196263E+01 +5.280610E+00 +1.414008E+00 +6.814742E+01 +2.331778E+02 +4.851618E+01 +1.182330E+02 +6.261805E+00 +1.983205E+00 +7.392923E+01 +2.740255E+02 +5.253586E+01 +1.384152E+02 +6.733810E+00 +2.278242E+00 +7.332860E+01 +2.698608E+02 +5.227405E+01 +1.371810E+02 +6.714658E+00 +2.273652E+00 +6.830172E+01 +2.340687E+02 +4.867159E+01 +1.188724E+02 +6.215002E+00 +1.956978E+00 +5.885634E+01 +1.736180E+02 +4.170434E+01 +8.719622E+01 +5.253064E+00 +1.396224E+00 +4.371848E+01 +9.592893E+01 +3.106403E+01 +4.844308E+01 +3.818076E+00 +7.509442E-01 +2.338413E+01 +2.752467E+01 +1.636713E+01 +1.347770E+01 +2.219928E+00 +2.515492E-01 +tally 3: +1.538752E+01 +1.196478E+01 +1.079685E+00 +6.010786E-02 +2.911906E+01 +4.269070E+01 +1.822657E+00 +1.671850E-01 +3.885421E+01 +7.608218E+01 +2.541516E+00 +3.262451E-01 +4.673300E+01 +1.097036E+02 +2.885307E+00 +4.214444E-01 +5.059247E+01 +1.283984E+02 +3.222796E+00 +5.237329E-01 +5.034856E+01 +1.272538E+02 +3.230225E+00 +5.273424E-01 +4.688476E+01 +1.103152E+02 +2.941287E+00 +4.363749E-01 +4.013746E+01 +8.077506E+01 +2.634234E+00 +3.520270E-01 +2.996887E+01 +4.509953E+01 +1.946504E+00 +1.919104E-01 +1.575260E+01 +1.248707E+01 +1.020705E+00 +5.413569E-02 +tally 4: +3.049469E+00 +4.677325E-01 +0.000000E+00 +0.000000E+00 +2.770358E+00 +3.879191E-01 +5.514939E+00 +1.528899E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +5.514939E+00 +1.528899E+00 +2.770358E+00 +3.879191E-01 +5.032131E+00 +1.275040E+00 +7.294002E+00 +2.675589E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +7.294002E+00 +2.675589E+00 +5.032131E+00 +1.275040E+00 +7.036008E+00 +2.490718E+00 +8.668860E+00 +3.776102E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +8.668860E+00 +3.776102E+00 +7.036008E+00 +2.490718E+00 +8.352414E+00 +3.501945E+00 +9.345868E+00 +4.380719E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +9.345868E+00 +4.380719E+00 +8.352414E+00 +3.501945E+00 +9.093766E+00 +4.158282E+00 +9.223771E+00 +4.270120E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +9.223771E+00 +4.270120E+00 +9.093766E+00 +4.158282E+00 +9.219150E+00 +4.264346E+00 +8.530966E+00 +3.651778E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +8.530966E+00 +3.651778E+00 +9.219150E+00 +4.264346E+00 +8.690373E+00 +3.785262E+00 +7.204424E+00 +2.604203E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +7.204424E+00 +2.604203E+00 +8.690373E+00 +3.785262E+00 +7.513640E+00 +2.833028E+00 +5.326721E+00 +1.426975E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +5.326721E+00 +1.426975E+00 +7.513640E+00 +2.833028E+00 +5.662215E+00 +1.607757E+00 +2.848381E+00 +4.093396E-01 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +2.848381E+00 +4.093396E-01 +5.662215E+00 +1.607757E+00 +3.025812E+00 +4.597241E-01 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +cmfd indices +1.000000E+01 +1.000000E+00 +1.000000E+00 +1.000000E+00 +k cmfd +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +1.170416E+00 +1.172966E+00 +1.165537E+00 +1.170979E+00 +1.161922E+00 +1.157523E+00 +1.158873E+00 +1.162877E+00 +1.167101E+00 +1.168130E+00 +1.170570E+00 +1.168115E+00 +1.174081E+00 +1.169458E+00 +1.167848E+00 +1.165116E+00 +cmfd entropy +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +3.203643E+00 +3.207943E+00 +3.213367E+00 +3.214360E+00 +3.219634E+00 +3.222232E+00 +3.221744E+00 +3.224544E+00 +3.225990E+00 +3.227769E+00 +3.227417E+00 +3.230728E+00 +3.231662E+00 +3.233316E+00 +3.233193E+00 +3.232564E+00 +cmfd balance +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +4.009062E-03 +4.431773E-03 +3.152666E-03 +3.510383E-03 +2.052089E-03 +2.068651E-03 +1.502427E-03 +1.589825E-03 +1.566020E-03 +1.219160E-03 +1.017888E-03 +9.771622E-04 +1.010120E-03 +1.073382E-03 +1.172758E-03 +9.827332E-04 +cmfd dominance ratio + 0.000E+00 + 0.000E+00 + 0.000E+00 + 0.000E+00 + 5.397E-01 + 5.425E-01 + 5.481E-01 + 5.473E-01 + 5.503E-01 + 5.502E-01 + 5.483E-01 + 5.520E-01 + 5.505E-01 + 3.216E-01 + 5.373E-01 + 5.517E-01 + 5.508E-01 + 5.524E-01 + 5.524E-01 + 5.523E-01 +cmfd openmc source comparison +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +6.959834E-03 +5.655657E-03 +3.886185E-03 +4.035116E-03 +3.043277E-03 +5.455475E-03 +4.515311E-03 +2.439840E-03 +2.114032E-03 +2.673132E-03 +2.431749E-03 +4.330928E-03 +3.404647E-03 +3.680298E-03 +3.309620E-03 +3.705541E-03 +cmfd source +4.697085E-02 +7.920706E-02 +1.107968E-01 +1.250932E-01 +1.383930E-01 +1.380648E-01 +1.246874E-01 +1.113705E-01 +8.203754E-02 +4.337882E-02 diff --git a/tests/test_cmfd_feed/settings.xml b/tests/regression_tests/cmfd_feed/settings.xml similarity index 100% rename from tests/test_cmfd_feed/settings.xml rename to tests/regression_tests/cmfd_feed/settings.xml diff --git a/tests/test_cmfd_feed/tallies.xml b/tests/regression_tests/cmfd_feed/tallies.xml similarity index 100% rename from tests/test_cmfd_feed/tallies.xml rename to tests/regression_tests/cmfd_feed/tallies.xml diff --git a/tests/regression_tests/cmfd_feed/test.py b/tests/regression_tests/cmfd_feed/test.py new file mode 100644 index 0000000000..4fc39d96ad --- /dev/null +++ b/tests/regression_tests/cmfd_feed/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import CMFDTestHarness + + +def test_cmfd_feed(): + harness = CMFDTestHarness('statepoint.20.h5') + harness.main() diff --git a/tests/regression_tests/cmfd_nofeed/__init__.py b/tests/regression_tests/cmfd_nofeed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_cmfd_nofeed/cmfd.xml b/tests/regression_tests/cmfd_nofeed/cmfd.xml similarity index 100% rename from tests/test_cmfd_nofeed/cmfd.xml rename to tests/regression_tests/cmfd_nofeed/cmfd.xml diff --git a/tests/test_cmfd_nofeed/geometry.xml b/tests/regression_tests/cmfd_nofeed/geometry.xml similarity index 100% rename from tests/test_cmfd_nofeed/geometry.xml rename to tests/regression_tests/cmfd_nofeed/geometry.xml diff --git a/tests/test_cmfd_nofeed/materials.xml b/tests/regression_tests/cmfd_nofeed/materials.xml similarity index 100% rename from tests/test_cmfd_nofeed/materials.xml rename to tests/regression_tests/cmfd_nofeed/materials.xml diff --git a/tests/regression_tests/cmfd_nofeed/results_true.dat b/tests/regression_tests/cmfd_nofeed/results_true.dat new file mode 100644 index 0000000000..f00966cf8f --- /dev/null +++ b/tests/regression_tests/cmfd_nofeed/results_true.dat @@ -0,0 +1,487 @@ +k-combined: +1.167381E+00 9.433835E-03 +tally 1: +1.196137E+01 +1.442469E+01 +2.133858E+01 +4.600709E+01 +2.874353E+01 +8.287541E+01 +3.400779E+01 +1.158949E+02 +3.736442E+01 +1.398466E+02 +3.705095E+01 +1.376767E+02 +3.486173E+01 +1.220362E+02 +2.910935E+01 +8.507178E+01 +2.034762E+01 +4.156717E+01 +1.074969E+01 +1.160731E+01 +tally 2: +2.321994E+01 +2.726751E+01 +1.624000E+01 +1.334217E+01 +2.239367E+00 +2.607315E-01 +4.184801E+01 +8.813954E+01 +2.955600E+01 +4.401685E+01 +3.937924E+00 +7.877545E-01 +5.620224E+01 +1.589242E+02 +3.981400E+01 +7.983679E+01 +5.183337E+00 +1.367303E+00 +6.834724E+01 +2.342245E+02 +4.869600E+01 +1.189597E+02 +6.288549E+00 +1.997858E+00 +7.481522E+01 +2.802998E+02 +5.346500E+01 +1.431835E+02 +6.691123E+00 +2.252645E+00 +7.381412E+01 +2.733775E+02 +5.269700E+01 +1.393729E+02 +6.846095E+00 +2.360683E+00 +6.907776E+01 +2.396752E+02 +4.918500E+01 +1.215909E+02 +6.400076E+00 +2.073871E+00 +5.783261E+01 +1.680814E+02 +4.107800E+01 +8.480751E+01 +5.269220E+00 +1.404986E+00 +4.120212E+01 +8.516647E+01 +2.930300E+01 +4.310295E+01 +3.730803E+00 +7.015777E-01 +2.228419E+01 +2.504034E+01 +1.554100E+01 +1.217931E+01 +2.126451E+00 +2.315275E-01 +tally 3: +1.561100E+01 +1.233967E+01 +1.095984E+00 +6.181385E-02 +2.847800E+01 +4.088161E+01 +1.815209E+00 +1.669969E-01 +3.834200E+01 +7.408022E+01 +2.446116E+00 +3.017833E-01 +4.687600E+01 +1.102381E+02 +2.954924E+00 +4.412808E-01 +5.155100E+01 +1.331461E+02 +3.204713E+00 +5.178543E-01 +5.067700E+01 +1.289238E+02 +3.246709E+00 +5.326372E-01 +4.738600E+01 +1.128834E+02 +3.035962E+00 +4.640209E-01 +3.953600E+01 +7.858196E+01 +2.507574E+00 +3.186455E-01 +2.819300E+01 +3.991455E+01 +1.846612E+00 +1.725570E-01 +1.497500E+01 +1.131312E+01 +9.213727E-01 +4.422000E-02 +tally 4: +3.090000E+00 +4.810640E-01 +0.000000E+00 +0.000000E+00 +2.833000E+00 +4.078910E-01 +5.555000E+00 +1.551579E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +5.555000E+00 +1.551579E+00 +2.833000E+00 +4.078910E-01 +5.095000E+00 +1.310819E+00 +7.271000E+00 +2.659755E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +7.271000E+00 +2.659755E+00 +5.095000E+00 +1.310819E+00 +7.026000E+00 +2.486552E+00 +8.577000E+00 +3.703215E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +8.577000E+00 +3.703215E+00 +7.026000E+00 +2.486552E+00 +8.572000E+00 +3.680852E+00 +9.393000E+00 +4.422429E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +9.393000E+00 +4.422429E+00 +8.572000E+00 +3.680852E+00 +9.261000E+00 +4.304411E+00 +9.265000E+00 +4.305625E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +9.265000E+00 +4.305625E+00 +9.261000E+00 +4.304411E+00 +9.303000E+00 +4.350791E+00 +8.535000E+00 +3.659395E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +8.535000E+00 +3.659395E+00 +9.303000E+00 +4.350791E+00 +8.693000E+00 +3.799545E+00 +7.104000E+00 +2.544182E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +7.104000E+00 +2.544182E+00 +8.693000E+00 +3.799545E+00 +7.334000E+00 +2.700052E+00 +5.168000E+00 +1.344390E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +5.168000E+00 +1.344390E+00 +7.334000E+00 +2.700052E+00 +5.416000E+00 +1.471086E+00 +2.724000E+00 +3.745680E-01 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +2.724000E+00 +3.745680E-01 +5.416000E+00 +1.471086E+00 +2.960000E+00 +4.397840E-01 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +cmfd indices +1.000000E+01 +1.000000E+00 +1.000000E+00 +1.000000E+00 +k cmfd +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +1.170416E+00 +1.172572E+00 +1.171159E+00 +1.170281E+00 +1.159698E+00 +1.151967E+00 +1.146706E+00 +1.147136E+00 +1.152154E+00 +1.156980E+00 +1.156370E+00 +1.155974E+00 +1.155295E+00 +1.154881E+00 +1.153714E+00 +1.159485E+00 +cmfd entropy +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +3.203643E+00 +3.204555E+00 +3.210935E+00 +3.213980E+00 +3.219204E+00 +3.222234E+00 +3.226210E+00 +3.226808E+00 +3.224445E+00 +3.222460E+00 +3.222458E+00 +3.222447E+00 +3.220832E+00 +3.220841E+00 +3.221580E+00 +3.220523E+00 +cmfd balance +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +4.009062E-03 +4.869662E-03 +2.997290E-03 +2.711191E-03 +1.688329E-03 +1.855396E-03 +1.403979E-03 +1.398429E-03 +1.818398E-03 +1.761250E-03 +1.646649E-03 +1.480119E-03 +1.399559E-03 +1.400162E-03 +1.178363E-03 +1.292280E-03 +cmfd dominance ratio + 0.000E+00 + 0.000E+00 + 0.000E+00 + 0.000E+00 + 5.397E-01 + 5.405E-01 + 5.412E-01 + 5.428E-01 + 5.460E-01 + 4.530E-01 + 5.528E-01 + 5.531E-01 + 5.493E-01 + 5.468E-01 + 5.482E-01 + 5.487E-01 + 5.471E-01 + 5.465E-01 + 5.461E-01 + 5.443E-01 +cmfd openmc source comparison +0.000000E+00 +0.000000E+00 +0.000000E+00 +0.000000E+00 +6.959834E-03 +5.494667E-03 +4.076255E-03 +4.451119E-03 +3.035588E-03 +3.391772E-03 +1.907994E-03 +2.482495E-03 +2.994916E-03 +3.104682E-03 +2.309343E-03 +2.151358E-03 +2.348849E-03 +1.976731E-03 +2.080638E-03 +2.301327E-03 +cmfd source +4.638920E-02 +7.751172E-02 +1.056089E-01 +1.282509E-01 +1.396713E-01 +1.415740E-01 +1.323405E-01 +1.092839E-01 +7.981779E-02 +3.955174E-02 diff --git a/tests/test_cmfd_nofeed/settings.xml b/tests/regression_tests/cmfd_nofeed/settings.xml similarity index 100% rename from tests/test_cmfd_nofeed/settings.xml rename to tests/regression_tests/cmfd_nofeed/settings.xml diff --git a/tests/test_cmfd_nofeed/tallies.xml b/tests/regression_tests/cmfd_nofeed/tallies.xml similarity index 100% rename from tests/test_cmfd_nofeed/tallies.xml rename to tests/regression_tests/cmfd_nofeed/tallies.xml diff --git a/tests/regression_tests/cmfd_nofeed/test.py b/tests/regression_tests/cmfd_nofeed/test.py new file mode 100644 index 0000000000..a3c7301738 --- /dev/null +++ b/tests/regression_tests/cmfd_nofeed/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import CMFDTestHarness + + +def test_cmfd_nofeed(): + harness = CMFDTestHarness('statepoint.20.h5') + harness.main() diff --git a/tests/regression_tests/complex_cell/__init__.py b/tests/regression_tests/complex_cell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_complex_cell/geometry.xml b/tests/regression_tests/complex_cell/geometry.xml similarity index 100% rename from tests/test_complex_cell/geometry.xml rename to tests/regression_tests/complex_cell/geometry.xml diff --git a/tests/test_complex_cell/materials.xml b/tests/regression_tests/complex_cell/materials.xml similarity index 100% rename from tests/test_complex_cell/materials.xml rename to tests/regression_tests/complex_cell/materials.xml diff --git a/tests/test_complex_cell/results_true.dat b/tests/regression_tests/complex_cell/results_true.dat similarity index 100% rename from tests/test_complex_cell/results_true.dat rename to tests/regression_tests/complex_cell/results_true.dat diff --git a/tests/test_complex_cell/settings.xml b/tests/regression_tests/complex_cell/settings.xml similarity index 100% rename from tests/test_complex_cell/settings.xml rename to tests/regression_tests/complex_cell/settings.xml diff --git a/tests/test_complex_cell/tallies.xml b/tests/regression_tests/complex_cell/tallies.xml similarity index 100% rename from tests/test_complex_cell/tallies.xml rename to tests/regression_tests/complex_cell/tallies.xml diff --git a/tests/regression_tests/complex_cell/test.py b/tests/regression_tests/complex_cell/test.py new file mode 100755 index 0000000000..77cbd6cb7d --- /dev/null +++ b/tests/regression_tests/complex_cell/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_complex_cell(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/confidence_intervals/__init__.py b/tests/regression_tests/confidence_intervals/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_confidence_intervals/geometry.xml b/tests/regression_tests/confidence_intervals/geometry.xml similarity index 100% rename from tests/test_confidence_intervals/geometry.xml rename to tests/regression_tests/confidence_intervals/geometry.xml diff --git a/tests/test_confidence_intervals/materials.xml b/tests/regression_tests/confidence_intervals/materials.xml similarity index 100% rename from tests/test_confidence_intervals/materials.xml rename to tests/regression_tests/confidence_intervals/materials.xml diff --git a/tests/test_confidence_intervals/results_true.dat b/tests/regression_tests/confidence_intervals/results_true.dat similarity index 100% rename from tests/test_confidence_intervals/results_true.dat rename to tests/regression_tests/confidence_intervals/results_true.dat diff --git a/tests/test_confidence_intervals/settings.xml b/tests/regression_tests/confidence_intervals/settings.xml similarity index 100% rename from tests/test_confidence_intervals/settings.xml rename to tests/regression_tests/confidence_intervals/settings.xml diff --git a/tests/test_confidence_intervals/tallies.xml b/tests/regression_tests/confidence_intervals/tallies.xml similarity index 100% rename from tests/test_confidence_intervals/tallies.xml rename to tests/regression_tests/confidence_intervals/tallies.xml diff --git a/tests/regression_tests/confidence_intervals/test.py b/tests/regression_tests/confidence_intervals/test.py new file mode 100755 index 0000000000..3227418280 --- /dev/null +++ b/tests/regression_tests/confidence_intervals/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_confidence_intervals(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/conftest.py b/tests/regression_tests/conftest.py new file mode 100644 index 0000000000..00ef247dc4 --- /dev/null +++ b/tests/regression_tests/conftest.py @@ -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() diff --git a/tests/regression_tests/create_fission_neutrons/__init__.py b/tests/regression_tests/create_fission_neutrons/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_create_fission_neutrons/inputs_true.dat b/tests/regression_tests/create_fission_neutrons/inputs_true.dat similarity index 96% rename from tests/test_create_fission_neutrons/inputs_true.dat rename to tests/regression_tests/create_fission_neutrons/inputs_true.dat index 9aeabbb57b..b0ca896476 100644 --- a/tests/test_create_fission_neutrons/inputs_true.dat +++ b/tests/regression_tests/create_fission_neutrons/inputs_true.dat @@ -10,7 +10,7 @@ - + diff --git a/tests/test_create_fission_neutrons/results_true.dat b/tests/regression_tests/create_fission_neutrons/results_true.dat similarity index 100% rename from tests/test_create_fission_neutrons/results_true.dat rename to tests/regression_tests/create_fission_neutrons/results_true.dat diff --git a/tests/test_create_fission_neutrons/test_create_fission_neutrons.py b/tests/regression_tests/create_fission_neutrons/test.py similarity index 94% rename from tests/test_create_fission_neutrons/test_create_fission_neutrons.py rename to tests/regression_tests/create_fission_neutrons/test.py index 87abeda7fe..f1c1d072cb 100755 --- a/tests/test_create_fission_neutrons/test_create_fission_neutrons.py +++ b/tests/regression_tests/create_fission_neutrons/test.py @@ -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() diff --git a/tests/regression_tests/density/__init__.py b/tests/regression_tests/density/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_density/geometry.xml b/tests/regression_tests/density/geometry.xml similarity index 100% rename from tests/test_density/geometry.xml rename to tests/regression_tests/density/geometry.xml diff --git a/tests/test_density/materials.xml b/tests/regression_tests/density/materials.xml similarity index 100% rename from tests/test_density/materials.xml rename to tests/regression_tests/density/materials.xml diff --git a/tests/test_density/results_true.dat b/tests/regression_tests/density/results_true.dat similarity index 100% rename from tests/test_density/results_true.dat rename to tests/regression_tests/density/results_true.dat diff --git a/tests/test_density/settings.xml b/tests/regression_tests/density/settings.xml similarity index 100% rename from tests/test_density/settings.xml rename to tests/regression_tests/density/settings.xml diff --git a/tests/regression_tests/density/test.py b/tests/regression_tests/density/test.py new file mode 100644 index 0000000000..f3ae6b4144 --- /dev/null +++ b/tests/regression_tests/density/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_density(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/diff_tally/__init__.py b/tests/regression_tests/diff_tally/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_diff_tally/inputs_true.dat b/tests/regression_tests/diff_tally/inputs_true.dat similarity index 99% rename from tests/test_diff_tally/inputs_true.dat rename to tests/regression_tests/diff_tally/inputs_true.dat index ff134bd5c3..909475f962 100644 --- a/tests/test_diff_tally/inputs_true.dat +++ b/tests/regression_tests/diff_tally/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/test_diff_tally/results_true.dat b/tests/regression_tests/diff_tally/results_true.dat similarity index 100% rename from tests/test_diff_tally/results_true.dat rename to tests/regression_tests/diff_tally/results_true.dat diff --git a/tests/test_diff_tally/test_diff_tally.py b/tests/regression_tests/diff_tally/test.py similarity index 76% rename from tests/test_diff_tally/test_diff_tally.py rename to tests/regression_tests/diff_tally/test.py index 02798e70e0..de5423fd9f 100644 --- a/tests/test_diff_tally/test_diff_tally.py +++ b/tests/regression_tests/diff_tally/test.py @@ -1,18 +1,16 @@ -#!/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 +import pytest + +from tests.testing_harness import PyAPITestHarness + class DiffTallyTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(DiffTallyTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Set settings explicitly self._model.settings.batches = 3 @@ -58,30 +56,25 @@ class DiffTallyTestHarness(PyAPITestHarness): # Cover the flux score. for i in range(5): t = openmc.Tally() - t.add_score('flux') - t.add_filter(filt_mats) + t.scores = ['flux'] + t.filters = [filt_mats] t.derivative = derivs[i] self._model.tallies.append(t) # Cover supported scores with a collision estimator. for i in range(5): t = openmc.Tally() - t.add_score('total') - t.add_score('absorption') - t.add_score('scatter') - t.add_score('fission') - t.add_score('nu-fission') - t.add_filter(filt_mats) - t.add_nuclide('total') - t.add_nuclide('U235') + t.scores = ['total', 'absorption', 'scatter', 'fission', 'nu-fission'] + t.filters = [filt_mats] + t.nuclides = ['total', 'U235'] t.derivative = derivs[i] self._model.tallies.append(t) # Cover an analog estimator. for i in range(5): t = openmc.Tally() - t.add_score('absorption') - t.add_filter(filt_mats) + t.scores = ['absorption'] + t.filters = [filt_mats] t.estimator = 'analog' t.derivative = derivs[i] self._model.tallies.append(t) @@ -89,23 +82,18 @@ class DiffTallyTestHarness(PyAPITestHarness): # Energyout filter and total nuclide for the density derivatives. for i in range(2): t = openmc.Tally() - t.add_score('nu-fission') - t.add_score('scatter') - t.add_filter(filt_mats) - t.add_filter(filt_eout) - t.add_nuclide('total') - t.add_nuclide('U235') + t.scores = ['nu-fission', 'scatter'] + t.filters = [filt_mats, filt_eout] + t.nuclides = ['total', 'U235'] t.derivative = derivs[i] self._model.tallies.append(t) # Energyout filter without total nuclide for other derivatives. for i in range(2, 5): t = openmc.Tally() - t.add_score('nu-fission') - t.add_score('scatter') - t.add_filter(filt_mats) - t.add_filter(filt_eout) - t.add_nuclide('U235') + t.scores = ['nu-fission', 'scatter'] + t.filters = [filt_mats, filt_eout] + t.nuclides = ['U235'] t.derivative = derivs[i] self._model.tallies.append(t) @@ -125,6 +113,9 @@ class DiffTallyTestHarness(PyAPITestHarness): return df.to_csv(None, columns=cols, index=False, float_format='%.7e') -if __name__ == '__main__': +@pytest.mark.skipif('OPENMC_MULTIPOLE_LIBRARY' not in os.environ, + reason='OPENMC_MULTIPOLE_LIBRARY environment variable ' + 'must be set') +def test_diff_tally(): harness = DiffTallyTestHarness('statepoint.3.h5') harness.main() diff --git a/tests/regression_tests/distribmat/__init__.py b/tests/regression_tests/distribmat/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_distribmat/inputs_true.dat b/tests/regression_tests/distribmat/inputs_true.dat similarity index 96% rename from tests/test_distribmat/inputs_true.dat rename to tests/regression_tests/distribmat/inputs_true.dat index 85d35b0810..39e611e16a 100644 --- a/tests/test_distribmat/inputs_true.dat +++ b/tests/regression_tests/distribmat/inputs_true.dat @@ -26,11 +26,11 @@ - + - + diff --git a/tests/test_distribmat/results_true.dat b/tests/regression_tests/distribmat/results_true.dat similarity index 100% rename from tests/test_distribmat/results_true.dat rename to tests/regression_tests/distribmat/results_true.dat diff --git a/tests/test_distribmat/test_distribmat.py b/tests/regression_tests/distribmat/test.py similarity index 93% rename from tests/test_distribmat/test_distribmat.py rename to tests/regression_tests/distribmat/test.py index 9dd5d319a2..de1b778772 100644 --- a/tests/test_distribmat/test_distribmat.py +++ b/tests/regression_tests/distribmat/test.py @@ -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): @@ -97,12 +93,12 @@ class DistribmatTestHarness(PyAPITestHarness): plots.export_to_xml() def _get_results(self): - outstr = super(DistribmatTestHarness, self)._get_results() + outstr = super()._get_results() su = openmc.Summary('summary.h5') outstr += str(su.geometry.get_all_cells()[11]) return outstr -if __name__ == '__main__': +def test_distribmat(): harness = DistribmatTestHarness('statepoint.5.h5') harness.main() diff --git a/tests/regression_tests/eigenvalue_genperbatch/__init__.py b/tests/regression_tests/eigenvalue_genperbatch/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_eigenvalue_genperbatch/geometry.xml b/tests/regression_tests/eigenvalue_genperbatch/geometry.xml similarity index 100% rename from tests/test_eigenvalue_genperbatch/geometry.xml rename to tests/regression_tests/eigenvalue_genperbatch/geometry.xml diff --git a/tests/test_eigenvalue_genperbatch/materials.xml b/tests/regression_tests/eigenvalue_genperbatch/materials.xml similarity index 100% rename from tests/test_eigenvalue_genperbatch/materials.xml rename to tests/regression_tests/eigenvalue_genperbatch/materials.xml diff --git a/tests/test_eigenvalue_genperbatch/results_true.dat b/tests/regression_tests/eigenvalue_genperbatch/results_true.dat similarity index 100% rename from tests/test_eigenvalue_genperbatch/results_true.dat rename to tests/regression_tests/eigenvalue_genperbatch/results_true.dat diff --git a/tests/test_eigenvalue_genperbatch/settings.xml b/tests/regression_tests/eigenvalue_genperbatch/settings.xml similarity index 100% rename from tests/test_eigenvalue_genperbatch/settings.xml rename to tests/regression_tests/eigenvalue_genperbatch/settings.xml diff --git a/tests/regression_tests/eigenvalue_genperbatch/test.py b/tests/regression_tests/eigenvalue_genperbatch/test.py new file mode 100644 index 0000000000..0dfb112428 --- /dev/null +++ b/tests/regression_tests/eigenvalue_genperbatch/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_eigenvalue_genperbatch(): + harness = TestHarness('statepoint.7.h5') + harness.main() diff --git a/tests/regression_tests/eigenvalue_no_inactive/__init__.py b/tests/regression_tests/eigenvalue_no_inactive/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_eigenvalue_no_inactive/geometry.xml b/tests/regression_tests/eigenvalue_no_inactive/geometry.xml similarity index 100% rename from tests/test_eigenvalue_no_inactive/geometry.xml rename to tests/regression_tests/eigenvalue_no_inactive/geometry.xml diff --git a/tests/test_eigenvalue_no_inactive/materials.xml b/tests/regression_tests/eigenvalue_no_inactive/materials.xml similarity index 100% rename from tests/test_eigenvalue_no_inactive/materials.xml rename to tests/regression_tests/eigenvalue_no_inactive/materials.xml diff --git a/tests/test_eigenvalue_no_inactive/results_true.dat b/tests/regression_tests/eigenvalue_no_inactive/results_true.dat similarity index 100% rename from tests/test_eigenvalue_no_inactive/results_true.dat rename to tests/regression_tests/eigenvalue_no_inactive/results_true.dat diff --git a/tests/test_eigenvalue_no_inactive/settings.xml b/tests/regression_tests/eigenvalue_no_inactive/settings.xml similarity index 100% rename from tests/test_eigenvalue_no_inactive/settings.xml rename to tests/regression_tests/eigenvalue_no_inactive/settings.xml diff --git a/tests/regression_tests/eigenvalue_no_inactive/test.py b/tests/regression_tests/eigenvalue_no_inactive/test.py new file mode 100644 index 0000000000..5ab4900153 --- /dev/null +++ b/tests/regression_tests/eigenvalue_no_inactive/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_eigenvalue_no_inactive(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/energy_cutoff/__init__.py b/tests/regression_tests/energy_cutoff/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_energy_cutoff/inputs_true.dat b/tests/regression_tests/energy_cutoff/inputs_true.dat similarity index 100% rename from tests/test_energy_cutoff/inputs_true.dat rename to tests/regression_tests/energy_cutoff/inputs_true.dat diff --git a/tests/test_energy_cutoff/results_true.dat b/tests/regression_tests/energy_cutoff/results_true.dat similarity index 100% rename from tests/test_energy_cutoff/results_true.dat rename to tests/regression_tests/energy_cutoff/results_true.dat diff --git a/tests/test_energy_cutoff/test_energy_cutoff.py b/tests/regression_tests/energy_cutoff/test.py similarity index 94% rename from tests/test_energy_cutoff/test_energy_cutoff.py rename to tests/regression_tests/energy_cutoff/test.py index 3aa3400c7a..8b16149947 100755 --- a/tests/test_energy_cutoff/test_energy_cutoff.py +++ b/tests/regression_tests/energy_cutoff/test.py @@ -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 EnergyCutoffTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -73,6 +69,6 @@ class EnergyCutoffTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_energy_cutoff(): harness = EnergyCutoffTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/energy_grid/__init__.py b/tests/regression_tests/energy_grid/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_energy_grid/geometry.xml b/tests/regression_tests/energy_grid/geometry.xml similarity index 100% rename from tests/test_energy_grid/geometry.xml rename to tests/regression_tests/energy_grid/geometry.xml diff --git a/tests/test_energy_grid/materials.xml b/tests/regression_tests/energy_grid/materials.xml similarity index 100% rename from tests/test_energy_grid/materials.xml rename to tests/regression_tests/energy_grid/materials.xml diff --git a/tests/test_energy_grid/results_true.dat b/tests/regression_tests/energy_grid/results_true.dat similarity index 100% rename from tests/test_energy_grid/results_true.dat rename to tests/regression_tests/energy_grid/results_true.dat diff --git a/tests/test_energy_grid/settings.xml b/tests/regression_tests/energy_grid/settings.xml similarity index 100% rename from tests/test_energy_grid/settings.xml rename to tests/regression_tests/energy_grid/settings.xml diff --git a/tests/regression_tests/energy_grid/test.py b/tests/regression_tests/energy_grid/test.py new file mode 100644 index 0000000000..889bdfbc61 --- /dev/null +++ b/tests/regression_tests/energy_grid/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_energy_grid(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/energy_laws/__init__.py b/tests/regression_tests/energy_laws/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_energy_laws/geometry.xml b/tests/regression_tests/energy_laws/geometry.xml similarity index 100% rename from tests/test_energy_laws/geometry.xml rename to tests/regression_tests/energy_laws/geometry.xml diff --git a/tests/test_energy_laws/materials.xml b/tests/regression_tests/energy_laws/materials.xml similarity index 100% rename from tests/test_energy_laws/materials.xml rename to tests/regression_tests/energy_laws/materials.xml diff --git a/tests/test_energy_laws/results_true.dat b/tests/regression_tests/energy_laws/results_true.dat similarity index 100% rename from tests/test_energy_laws/results_true.dat rename to tests/regression_tests/energy_laws/results_true.dat diff --git a/tests/test_energy_laws/settings.xml b/tests/regression_tests/energy_laws/settings.xml similarity index 100% rename from tests/test_energy_laws/settings.xml rename to tests/regression_tests/energy_laws/settings.xml diff --git a/tests/test_energy_laws/test_energy_laws.py b/tests/regression_tests/energy_laws/test.py similarity index 81% rename from tests/test_energy_laws/test_energy_laws.py rename to tests/regression_tests/energy_laws/test.py index 254126ff30..8f9bbde356 100644 --- a/tests/test_energy_laws/test_energy_laws.py +++ b/tests/regression_tests/energy_laws/test.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - """The purpose of this test is to provide coverage of energy distributions that are not covered in other tests. It has a single material with the following nuclides: @@ -18,13 +16,9 @@ that use linear-linear interpolation. """ -import glob -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_energy_laws(): harness = TestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/enrichment/__init__.py b/tests/regression_tests/enrichment/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_enrichment/test_enrichment.py b/tests/regression_tests/enrichment/test.py similarity index 88% rename from tests/test_enrichment/test_enrichment.py rename to tests/regression_tests/enrichment/test.py index fa65d6dce0..a20838c7cb 100644 --- a/tests/test_enrichment/test_enrichment.py +++ b/tests/regression_tests/enrichment/test.py @@ -1,17 +1,13 @@ -#!/usr/bin/env python - import os import sys import numpy as np -sys.path.insert(0, os.pardir) -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from openmc import Material from openmc.data import NATURAL_ABUNDANCE, atomic_mass -if __name__ == '__main__': +def test_enrichment(): # This test doesn't require an OpenMC run. We just need to make sure the # element.expand() method expands Uranium to the proper enrichment. diff --git a/tests/regression_tests/entropy/__init__.py b/tests/regression_tests/entropy/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_entropy/geometry.xml b/tests/regression_tests/entropy/geometry.xml similarity index 100% rename from tests/test_entropy/geometry.xml rename to tests/regression_tests/entropy/geometry.xml diff --git a/tests/test_entropy/materials.xml b/tests/regression_tests/entropy/materials.xml similarity index 100% rename from tests/test_entropy/materials.xml rename to tests/regression_tests/entropy/materials.xml diff --git a/tests/test_entropy/results_true.dat b/tests/regression_tests/entropy/results_true.dat similarity index 100% rename from tests/test_entropy/results_true.dat rename to tests/regression_tests/entropy/results_true.dat diff --git a/tests/test_entropy/settings.xml b/tests/regression_tests/entropy/settings.xml similarity index 100% rename from tests/test_entropy/settings.xml rename to tests/regression_tests/entropy/settings.xml diff --git a/tests/test_entropy/test_entropy.py b/tests/regression_tests/entropy/test.py similarity index 70% rename from tests/test_entropy/test_entropy.py rename to tests/regression_tests/entropy/test.py index 36e2170af8..10a11e3008 100644 --- a/tests/test_entropy/test_entropy.py +++ b/tests/regression_tests/entropy/test.py @@ -1,12 +1,10 @@ -#!/usr/bin/env python - import glob import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness + from openmc import StatePoint +from tests.testing_harness import TestHarness + class EntropyTestHarness(TestHarness): def _get_results(self): @@ -16,16 +14,16 @@ class EntropyTestHarness(TestHarness): with StatePoint(statepoint) as sp: # Write out k-combined. outstr = 'k-combined:\n' - outstr += '{0:12.6E} {1:12.6E}\n'.format(*sp.k_combined) + outstr += '{:12.6E} {:12.6E}\n'.format(sp.k_combined.n, sp.k_combined.s) # Write out entropy data. outstr += 'entropy:\n' - results = ['{0:12.6E}'.format(x) for x in sp.entropy] + results = ['{:12.6E}'.format(x) for x in sp.entropy] outstr += '\n'.join(results) + '\n' return outstr -if __name__ == '__main__': +def test_entropy(): harness = EntropyTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/example_geometry.py b/tests/regression_tests/example_geometry.py new file mode 100644 index 0000000000..ca10c1f725 --- /dev/null +++ b/tests/regression_tests/example_geometry.py @@ -0,0 +1,378 @@ +"""An example file showing how to make a geometry. + +This particular example creates a 3x3 geometry, with 8 regular pins and one +Gd-157 2 wt-percent enriched. All pins are segmented. +""" + +from collections import OrderedDict +import math + +import numpy as np +import openmc + + +def density_to_mat(dens_dict): + """Generates an OpenMC material from a cell ID and self.number_density. + + Parameters + ---------- + dens_dict : dict + Dictionary mapping nuclide names to densities + + Returns + ------- + openmc.Material + The OpenMC material filled with nuclides. + + """ + mat = openmc.Material() + for key in dens_dict: + mat.add_nuclide(key, 1.0e-24*dens_dict[key]) + mat.set_density('sum') + + return mat + + +def generate_initial_number_density(): + """ Generates initial number density. + + These results were from a CASMO5 run in which the gadolinium pin was + loaded with 2 wt percent of Gd-157. + """ + + # Concentration to be used for all fuel pins + fuel_dict = OrderedDict() + fuel_dict['U235'] = 1.05692e21 + fuel_dict['U234'] = 1.00506e19 + fuel_dict['U238'] = 2.21371e22 + fuel_dict['O16'] = 4.62954e22 + fuel_dict['O17'] = 1.127684e20 + fuel_dict['I135'] = 1.0e10 + fuel_dict['Xe135'] = 1.0e10 + fuel_dict['Xe136'] = 1.0e10 + fuel_dict['Cs135'] = 1.0e10 + fuel_dict['Gd156'] = 1.0e10 + fuel_dict['Gd157'] = 1.0e10 + # fuel_dict['O18'] = 9.51352e19 # Does not exist in ENDF71, merged into 17 + + # Concentration to be used for the gadolinium fuel pin + fuel_gd_dict = OrderedDict() + fuel_gd_dict['U235'] = 1.03579e21 + fuel_gd_dict['U238'] = 2.16943e22 + fuel_gd_dict['Gd156'] = 3.95517E+10 + fuel_gd_dict['Gd157'] = 1.08156e20 + fuel_gd_dict['O16'] = 4.64035e22 + fuel_dict['I135'] = 1.0e10 + fuel_dict['Xe136'] = 1.0e10 + fuel_dict['Xe135'] = 1.0e10 + fuel_dict['Cs135'] = 1.0e10 + # There are a whole bunch of 1e-10 stuff here. + + # Concentration to be used for cladding + clad_dict = OrderedDict() + clad_dict['O16'] = 3.07427e20 + clad_dict['O17'] = 7.48868e17 + clad_dict['Cr50'] = 3.29620e18 + clad_dict['Cr52'] = 6.35639e19 + clad_dict['Cr53'] = 7.20763e18 + clad_dict['Cr54'] = 1.79413e18 + clad_dict['Fe54'] = 5.57350e18 + clad_dict['Fe56'] = 8.74921e19 + clad_dict['Fe57'] = 2.02057e18 + clad_dict['Fe58'] = 2.68901e17 + clad_dict['Cr50'] = 3.29620e18 + clad_dict['Cr52'] = 6.35639e19 + clad_dict['Cr53'] = 7.20763e18 + clad_dict['Cr54'] = 1.79413e18 + clad_dict['Ni58'] = 2.51631e19 + clad_dict['Ni60'] = 9.69278e18 + clad_dict['Ni61'] = 4.21338e17 + clad_dict['Ni62'] = 1.34341e18 + clad_dict['Ni64'] = 3.43127e17 + clad_dict['Zr90'] = 2.18320e22 + clad_dict['Zr91'] = 4.76104e21 + clad_dict['Zr92'] = 7.27734e21 + clad_dict['Zr94'] = 7.37494e21 + clad_dict['Zr96'] = 1.18814e21 + clad_dict['Sn112'] = 4.67352e18 + clad_dict['Sn114'] = 3.17992e18 + clad_dict['Sn115'] = 1.63814e18 + clad_dict['Sn116'] = 7.00546e19 + clad_dict['Sn117'] = 3.70027e19 + clad_dict['Sn118'] = 1.16694e20 + clad_dict['Sn119'] = 4.13872e19 + clad_dict['Sn120'] = 1.56973e20 + clad_dict['Sn122'] = 2.23076e19 + clad_dict['Sn124'] = 2.78966e19 + + # Gap concentration + # Funny enough, the example problem uses air. + gap_dict = OrderedDict() + gap_dict['O16'] = 7.86548e18 + gap_dict['O17'] = 2.99548e15 + gap_dict['N14'] = 3.38646e19 + gap_dict['N15'] = 1.23717e17 + + # Concentration to be used for coolant + # No boron + cool_dict = OrderedDict() + cool_dict['H1'] = 4.68063e22 + cool_dict['O16'] = 2.33427e22 + cool_dict['O17'] = 8.89086e18 + + # Store these dictionaries in the initial conditions dictionary + initial_density = OrderedDict() + initial_density['fuel_gd'] = fuel_gd_dict + initial_density['fuel'] = fuel_dict + initial_density['gap'] = gap_dict + initial_density['clad'] = clad_dict + initial_density['cool'] = cool_dict + + # Set up libraries to use + temperature = OrderedDict() + sab = OrderedDict() + + # Toggle betweeen MCNP and NNDC data + MCNP = False + + if MCNP: + temperature['fuel_gd'] = 900.0 + temperature['fuel'] = 900.0 + # We approximate temperature of everything as 600K, even though it was + # actually 580K. + temperature['gap'] = 600.0 + temperature['clad'] = 600.0 + temperature['cool'] = 600.0 + else: + temperature['fuel_gd'] = 293.6 + temperature['fuel'] = 293.6 + temperature['gap'] = 293.6 + temperature['clad'] = 293.6 + temperature['cool'] = 293.6 + + sab['cool'] = 'c_H_in_H2O' + + # Set up burnable materials + burn = OrderedDict() + burn['fuel_gd'] = True + burn['fuel'] = True + burn['gap'] = False + burn['clad'] = False + burn['cool'] = False + + return temperature, sab, initial_density, burn + +def segment_pin(n_rings, n_wedges, r_fuel, r_gap, r_clad): + """ Calculates a segmented pin. + + Separates a pin with n_rings and n_wedges. All cells have equal volume. + Pin is centered at origin. + """ + + # Calculate all the volumes of interest + v_fuel = math.pi * r_fuel**2 + v_gap = math.pi * r_gap**2 - v_fuel + v_clad = math.pi * r_clad**2 - v_fuel - v_gap + v_ring = v_fuel / n_rings + v_segment = v_ring / n_wedges + + # Compute ring radiuses + r_rings = np.zeros(n_rings) + + for i in range(n_rings): + r_rings[i] = math.sqrt(1.0/(math.pi) * v_ring * (i+1)) + + # Compute thetas + theta = np.linspace(0, 2*math.pi, n_wedges + 1) + + # Compute surfaces + fuel_rings = [openmc.ZCylinder(x0=0, y0=0, R=r_rings[i]) + for i in range(n_rings)] + + fuel_wedges = [openmc.Plane(A=math.cos(theta[i]), B=math.sin(theta[i])) + for i in range(n_wedges)] + + gap_ring = openmc.ZCylinder(x0=0, y0=0, R=r_gap) + clad_ring = openmc.ZCylinder(x0=0, y0=0, R=r_clad) + + # Create cells + fuel_cells = [] + if n_wedges == 1: + for i in range(n_rings): + cell = openmc.Cell(name='fuel') + if i == 0: + cell.region = -fuel_rings[0] + else: + cell.region = +fuel_rings[i-1] & -fuel_rings[i] + fuel_cells.append(cell) + else: + for i in range(n_rings): + for j in range(n_wedges): + cell = openmc.Cell(name='fuel') + if i == 0: + if j != n_wedges-1: + cell.region = (-fuel_rings[0] + & +fuel_wedges[j] + & -fuel_wedges[j+1]) + else: + cell.region = (-fuel_rings[0] + & +fuel_wedges[j] + & -fuel_wedges[0]) + else: + if j != n_wedges-1: + cell.region = (+fuel_rings[i-1] + & -fuel_rings[i] + & +fuel_wedges[j] + & -fuel_wedges[j+1]) + else: + cell.region = (+fuel_rings[i-1] + & -fuel_rings[i] + & +fuel_wedges[j] + & -fuel_wedges[0]) + fuel_cells.append(cell) + + # Gap ring + gap_cell = openmc.Cell(name='gap') + gap_cell.region = +fuel_rings[-1] & -gap_ring + fuel_cells.append(gap_cell) + + # Clad ring + clad_cell = openmc.Cell(name='clad') + clad_cell.region = +gap_ring & -clad_ring + fuel_cells.append(clad_cell) + + # Moderator + mod_cell = openmc.Cell(name='cool') + mod_cell.region = +clad_ring + fuel_cells.append(mod_cell) + + # Form universe + fuel_u = openmc.Universe() + fuel_u.add_cells(fuel_cells) + + return fuel_u, v_segment, v_gap, v_clad + +def generate_geometry(n_rings, n_wedges): + """ Generates example geometry. + + This function creates the initial geometry, a 9 pin reflective problem. + One pin, containing gadolinium, is discretized into sectors. + + In addition to what one would do with the general OpenMC geometry code, it + is necessary to create a dictionary, volume, that maps a cell ID to a + volume. Further, by naming cells the same as the above materials, the code + can automatically handle the mapping. + + Parameters + ---------- + n_rings : int + Number of rings to generate for the geometry + n_wedges : int + Number of wedges to generate for the geometry + """ + + pitch = 1.26197 + r_fuel = 0.412275 + r_gap = 0.418987 + r_clad = 0.476121 + + n_pin = 3 + + # This table describes the 'fuel' to actual type mapping + # It's not necessary to do it this way. Just adjust the initial conditions + # below. + mapping = ['fuel', 'fuel', 'fuel', + 'fuel', 'fuel_gd', 'fuel', + 'fuel', 'fuel', 'fuel'] + + # Form pin cell + fuel_u, v_segment, v_gap, v_clad = segment_pin(n_rings, n_wedges, r_fuel, r_gap, r_clad) + + # Form lattice + all_water_c = openmc.Cell(name='cool') + all_water_u = openmc.Universe(cells=(all_water_c, )) + + lattice = openmc.RectLattice() + lattice.pitch = [pitch]*2 + lattice.lower_left = [-pitch*n_pin/2, -pitch*n_pin/2] + lattice_array = [[fuel_u for i in range(n_pin)] for j in range(n_pin)] + lattice.universes = lattice_array + lattice.outer = all_water_u + + # Bound universe + x_low = openmc.XPlane(x0=-pitch*n_pin/2, boundary_type='reflective') + x_high = openmc.XPlane(x0=pitch*n_pin/2, boundary_type='reflective') + y_low = openmc.YPlane(y0=-pitch*n_pin/2, boundary_type='reflective') + y_high = openmc.YPlane(y0=pitch*n_pin/2, boundary_type='reflective') + z_low = openmc.ZPlane(z0=-10, boundary_type='reflective') + z_high = openmc.ZPlane(z0=10, boundary_type='reflective') + + # Compute bounding box + lower_left = [-pitch*n_pin/2, -pitch*n_pin/2, -10] + upper_right = [pitch*n_pin/2, pitch*n_pin/2, 10] + + root_c = openmc.Cell(fill=lattice) + root_c.region = (+x_low & -x_high + & +y_low & -y_high + & +z_low & -z_high) + root_u = openmc.Universe(universe_id=0, cells=(root_c, )) + geometry = openmc.Geometry(root_u) + + v_cool = pitch**2 - (v_gap + v_clad + n_rings * n_wedges * v_segment) + + # Store volumes for later usage + volume = {'fuel': v_segment, 'gap':v_gap, 'clad':v_clad, 'cool':v_cool} + + return geometry, volume, mapping, lower_left, upper_right + +def generate_problem(n_rings=5, n_wedges=8): + """ Merges geometry and materials. + + This function initializes the materials for each cell using the dictionaries + provided by generate_initial_number_density. It is assumed a cell named + 'fuel' will have further region differentiation (see mapping). + + Parameters + ---------- + n_rings : int, optional + Number of rings to generate for the geometry + n_wedges : int, optional + Number of wedges to generate for the geometry + """ + + # Get materials dictionary, geometry, and volumes + temperature, sab, initial_density, burn = generate_initial_number_density() + geometry, volume, mapping, lower_left, upper_right = generate_geometry(n_rings, n_wedges) + + # Apply distribmats, fill geometry + cells = geometry.root_universe.get_all_cells() + for cell_id in cells: + cell = cells[cell_id] + if cell.name == 'fuel': + + omc_mats = [] + + for cell_type in mapping: + omc_mat = density_to_mat(initial_density[cell_type]) + + if cell_type in sab: + omc_mat.add_s_alpha_beta(sab[cell_type]) + omc_mat.temperature = temperature[cell_type] + omc_mat.depletable = burn[cell_type] + omc_mat.volume = volume['fuel'] + + omc_mats.append(omc_mat) + + cell.fill = omc_mats + elif cell.name != '': + omc_mat = density_to_mat(initial_density[cell.name]) + + if cell.name in sab: + omc_mat.add_s_alpha_beta(sab[cell.name]) + omc_mat.temperature = temperature[cell.name] + omc_mat.depletable = burn[cell.name] + omc_mat.volume = volume[cell.name] + + cell.fill = omc_mat + + return geometry, lower_left, upper_right diff --git a/tests/regression_tests/filter_distribcell/__init__.py b/tests/regression_tests/filter_distribcell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_filter_distribcell/case-1/geometry.xml b/tests/regression_tests/filter_distribcell/case-1/geometry.xml similarity index 100% rename from tests/test_filter_distribcell/case-1/geometry.xml rename to tests/regression_tests/filter_distribcell/case-1/geometry.xml diff --git a/tests/test_filter_distribcell/case-1/materials.xml b/tests/regression_tests/filter_distribcell/case-1/materials.xml similarity index 100% rename from tests/test_filter_distribcell/case-1/materials.xml rename to tests/regression_tests/filter_distribcell/case-1/materials.xml diff --git a/tests/test_filter_distribcell/case-1/results_true.dat b/tests/regression_tests/filter_distribcell/case-1/results_true.dat similarity index 100% rename from tests/test_filter_distribcell/case-1/results_true.dat rename to tests/regression_tests/filter_distribcell/case-1/results_true.dat diff --git a/tests/test_filter_distribcell/case-1/settings.xml b/tests/regression_tests/filter_distribcell/case-1/settings.xml similarity index 100% rename from tests/test_filter_distribcell/case-1/settings.xml rename to tests/regression_tests/filter_distribcell/case-1/settings.xml diff --git a/tests/test_filter_distribcell/case-1/tallies.xml b/tests/regression_tests/filter_distribcell/case-1/tallies.xml similarity index 100% rename from tests/test_filter_distribcell/case-1/tallies.xml rename to tests/regression_tests/filter_distribcell/case-1/tallies.xml diff --git a/tests/test_filter_distribcell/case-2/geometry.xml b/tests/regression_tests/filter_distribcell/case-2/geometry.xml similarity index 100% rename from tests/test_filter_distribcell/case-2/geometry.xml rename to tests/regression_tests/filter_distribcell/case-2/geometry.xml diff --git a/tests/test_filter_distribcell/case-2/materials.xml b/tests/regression_tests/filter_distribcell/case-2/materials.xml similarity index 100% rename from tests/test_filter_distribcell/case-2/materials.xml rename to tests/regression_tests/filter_distribcell/case-2/materials.xml diff --git a/tests/test_filter_distribcell/case-2/results_true.dat b/tests/regression_tests/filter_distribcell/case-2/results_true.dat similarity index 100% rename from tests/test_filter_distribcell/case-2/results_true.dat rename to tests/regression_tests/filter_distribcell/case-2/results_true.dat diff --git a/tests/test_filter_distribcell/case-2/settings.xml b/tests/regression_tests/filter_distribcell/case-2/settings.xml similarity index 100% rename from tests/test_filter_distribcell/case-2/settings.xml rename to tests/regression_tests/filter_distribcell/case-2/settings.xml diff --git a/tests/test_filter_distribcell/case-2/tallies.xml b/tests/regression_tests/filter_distribcell/case-2/tallies.xml similarity index 100% rename from tests/test_filter_distribcell/case-2/tallies.xml rename to tests/regression_tests/filter_distribcell/case-2/tallies.xml diff --git a/tests/test_filter_distribcell/case-3/geometry.xml b/tests/regression_tests/filter_distribcell/case-3/geometry.xml similarity index 100% rename from tests/test_filter_distribcell/case-3/geometry.xml rename to tests/regression_tests/filter_distribcell/case-3/geometry.xml diff --git a/tests/test_filter_distribcell/case-3/materials.xml b/tests/regression_tests/filter_distribcell/case-3/materials.xml similarity index 100% rename from tests/test_filter_distribcell/case-3/materials.xml rename to tests/regression_tests/filter_distribcell/case-3/materials.xml diff --git a/tests/test_filter_distribcell/case-3/results_true.dat b/tests/regression_tests/filter_distribcell/case-3/results_true.dat similarity index 100% rename from tests/test_filter_distribcell/case-3/results_true.dat rename to tests/regression_tests/filter_distribcell/case-3/results_true.dat diff --git a/tests/test_filter_distribcell/case-3/settings.xml b/tests/regression_tests/filter_distribcell/case-3/settings.xml similarity index 100% rename from tests/test_filter_distribcell/case-3/settings.xml rename to tests/regression_tests/filter_distribcell/case-3/settings.xml diff --git a/tests/test_filter_distribcell/case-3/tallies.xml b/tests/regression_tests/filter_distribcell/case-3/tallies.xml similarity index 100% rename from tests/test_filter_distribcell/case-3/tallies.xml rename to tests/regression_tests/filter_distribcell/case-3/tallies.xml diff --git a/tests/test_filter_distribcell/case-4/geometry.xml b/tests/regression_tests/filter_distribcell/case-4/geometry.xml similarity index 100% rename from tests/test_filter_distribcell/case-4/geometry.xml rename to tests/regression_tests/filter_distribcell/case-4/geometry.xml diff --git a/tests/test_filter_distribcell/case-4/materials.xml b/tests/regression_tests/filter_distribcell/case-4/materials.xml similarity index 100% rename from tests/test_filter_distribcell/case-4/materials.xml rename to tests/regression_tests/filter_distribcell/case-4/materials.xml diff --git a/tests/test_filter_distribcell/case-4/results_true.dat b/tests/regression_tests/filter_distribcell/case-4/results_true.dat similarity index 100% rename from tests/test_filter_distribcell/case-4/results_true.dat rename to tests/regression_tests/filter_distribcell/case-4/results_true.dat diff --git a/tests/test_filter_distribcell/case-4/settings.xml b/tests/regression_tests/filter_distribcell/case-4/settings.xml similarity index 100% rename from tests/test_filter_distribcell/case-4/settings.xml rename to tests/regression_tests/filter_distribcell/case-4/settings.xml diff --git a/tests/test_filter_distribcell/case-4/tallies.xml b/tests/regression_tests/filter_distribcell/case-4/tallies.xml similarity index 100% rename from tests/test_filter_distribcell/case-4/tallies.xml rename to tests/regression_tests/filter_distribcell/case-4/tallies.xml diff --git a/tests/test_filter_distribcell/test_filter_distribcell.py b/tests/regression_tests/filter_distribcell/test.py similarity index 93% rename from tests/test_filter_distribcell/test_filter_distribcell.py rename to tests/regression_tests/filter_distribcell/test.py index f0fc270399..028c6a7790 100644 --- a/tests/test_filter_distribcell/test_filter_distribcell.py +++ b/tests/regression_tests/filter_distribcell/test.py @@ -1,16 +1,12 @@ -#!/usr/bin/env python - import glob -import hashlib import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import * + +from tests.testing_harness import * class DistribcellTestHarness(TestHarness): def __init__(self): - super(DistribcellTestHarness, self).__init__(None) + super().__init__(None) def execute_test(self): """Run OpenMC with the appropriate arguments and check the outputs.""" @@ -72,6 +68,6 @@ class DistribcellTestHarness(TestHarness): 'Tally output file does not exist.' -if __name__ == '__main__': +def test_filter_distribcell(): harness = DistribcellTestHarness() harness.main() diff --git a/tests/regression_tests/filter_energyfun/__init__.py b/tests/regression_tests/filter_energyfun/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_filter_energyfun/inputs_true.dat b/tests/regression_tests/filter_energyfun/inputs_true.dat similarity index 99% rename from tests/test_filter_energyfun/inputs_true.dat rename to tests/regression_tests/filter_energyfun/inputs_true.dat index d857451cb0..418354fc2b 100644 --- a/tests/test_filter_energyfun/inputs_true.dat +++ b/tests/regression_tests/filter_energyfun/inputs_true.dat @@ -148,7 +148,7 @@ - + @@ -156,7 +156,7 @@ - + diff --git a/tests/test_filter_energyfun/results_true.dat b/tests/regression_tests/filter_energyfun/results_true.dat similarity index 100% rename from tests/test_filter_energyfun/results_true.dat rename to tests/regression_tests/filter_energyfun/results_true.dat diff --git a/tests/test_filter_energyfun/test_filter_energyfun.py b/tests/regression_tests/filter_energyfun/test.py similarity index 80% rename from tests/test_filter_energyfun/test_filter_energyfun.py rename to tests/regression_tests/filter_energyfun/test.py index 7e787edff2..7c5645b651 100644 --- a/tests/test_filter_energyfun/test_filter_energyfun.py +++ b/tests/regression_tests/filter_energyfun/test.py @@ -1,16 +1,11 @@ -#!/usr/bin/env python - -import os -import sys -import glob -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + class FilterEnergyFunHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(FilterEnergyFunHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Add Am241 to the fuel. self._model.materials[1].add_nuclide('Am241', 1e-7) @@ -38,8 +33,7 @@ class FilterEnergyFunHarness(PyAPITestHarness): def _get_results(self): # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Use tally arithmetic to compute the branching ratio. br_tally = sp.tallies[2] / sp.tallies[1] @@ -48,6 +42,6 @@ class FilterEnergyFunHarness(PyAPITestHarness): return br_tally.get_pandas_dataframe().to_string() + '\n' -if __name__ == '__main__': +def test_filter_energyfun(): harness = FilterEnergyFunHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/filter_mesh/__init__.py b/tests/regression_tests/filter_mesh/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_filter_mesh/inputs_true.dat b/tests/regression_tests/filter_mesh/inputs_true.dat similarity index 97% rename from tests/test_filter_mesh/inputs_true.dat rename to tests/regression_tests/filter_mesh/inputs_true.dat index 6d14f9e7e3..511b298482 100644 --- a/tests/test_filter_mesh/inputs_true.dat +++ b/tests/regression_tests/filter_mesh/inputs_true.dat @@ -148,7 +148,7 @@ - + @@ -327,18 +327,27 @@ 1 + + 1 + 2 + + 2 + 3 + + 3 + 1 total - 1 + 4 current @@ -346,7 +355,7 @@ total - 2 + 5 current @@ -354,7 +363,7 @@ total - 3 + 6 current diff --git a/tests/regression_tests/filter_mesh/results_true.dat b/tests/regression_tests/filter_mesh/results_true.dat new file mode 100644 index 0000000000..f331238b70 --- /dev/null +++ b/tests/regression_tests/filter_mesh/results_true.dat @@ -0,0 +1 @@ +46950c046648faaa5ff3cb7b4fdd03667ae3c6da96a7ed8121761291de452cf88481f53e967ed52407d77d90109ae24839967a22ae216531a0e1491f5051ea72 \ No newline at end of file diff --git a/tests/test_filter_mesh/test_filter_mesh.py b/tests/regression_tests/filter_mesh/test.py similarity index 81% rename from tests/test_filter_mesh/test_filter_mesh.py rename to tests/regression_tests/filter_mesh/test.py index 7b9e8bd16b..8a7f7a6fca 100644 --- a/tests/test_filter_mesh/test_filter_mesh.py +++ b/tests/regression_tests/filter_mesh/test.py @@ -1,15 +1,11 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import HashedPyAPITestHarness import openmc +from tests.testing_harness import HashedPyAPITestHarness + class FilterMeshTestHarness(HashedPyAPITestHarness): def __init__(self, *args, **kwargs): - super(FilterMeshTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize Meshes mesh_1d = openmc.Mesh(mesh_id=1) @@ -34,6 +30,9 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): mesh_1d_filter = openmc.MeshFilter(mesh_1d) mesh_2d_filter = openmc.MeshFilter(mesh_2d) mesh_3d_filter = openmc.MeshFilter(mesh_3d) + meshsurf_1d_filter = openmc.MeshSurfaceFilter(mesh_1d) + meshsurf_2d_filter = openmc.MeshSurfaceFilter(mesh_2d) + meshsurf_3d_filter = openmc.MeshSurfaceFilter(mesh_3d) # Initialized the tallies tally = openmc.Tally(name='tally 1') @@ -42,7 +41,7 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): self._model.tallies.append(tally) tally = openmc.Tally(name='tally 2') - tally.filters = [mesh_1d_filter] + tally.filters = [meshsurf_1d_filter] tally.scores = ['current'] self._model.tallies.append(tally) @@ -52,7 +51,7 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): self._model.tallies.append(tally) tally = openmc.Tally(name='tally 4') - tally.filters = [mesh_2d_filter] + tally.filters = [meshsurf_2d_filter] tally.scores = ['current'] self._model.tallies.append(tally) @@ -62,11 +61,11 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): self._model.tallies.append(tally) tally = openmc.Tally(name='tally 6') - tally.filters = [mesh_3d_filter] + tally.filters = [meshsurf_3d_filter] tally.scores = ['current'] self._model.tallies.append(tally) -if __name__ == '__main__': +def test_filter_mesh(): harness = FilterMeshTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/fixed_source/__init__.py b/tests/regression_tests/fixed_source/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_fixed_source/inputs_true.dat b/tests/regression_tests/fixed_source/inputs_true.dat similarity index 95% rename from tests/test_fixed_source/inputs_true.dat rename to tests/regression_tests/fixed_source/inputs_true.dat index 2e0d57b0c1..f1aebb3b2b 100644 --- a/tests/test_fixed_source/inputs_true.dat +++ b/tests/regression_tests/fixed_source/inputs_true.dat @@ -5,7 +5,7 @@ - + diff --git a/tests/test_fixed_source/results_true.dat b/tests/regression_tests/fixed_source/results_true.dat similarity index 100% rename from tests/test_fixed_source/results_true.dat rename to tests/regression_tests/fixed_source/results_true.dat diff --git a/tests/test_fixed_source/test_fixed_source.py b/tests/regression_tests/fixed_source/test.py similarity index 86% rename from tests/test_fixed_source/test_fixed_source.py rename to tests/regression_tests/fixed_source/test.py index db58e2f706..7d98de9fc3 100644 --- a/tests/test_fixed_source/test_fixed_source.py +++ b/tests/regression_tests/fixed_source/test.py @@ -1,22 +1,17 @@ -#!/usr/bin/env python - -import glob -import os -import sys import numpy as np -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness + import openmc import openmc.stats +from tests.testing_harness import PyAPITestHarness + class FixedSourceTestHarness(PyAPITestHarness): def _get_results(self): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] outstr = '' - with openmc.StatePoint(statepoint) as sp: + with openmc.StatePoint(self._sp_name) as sp: # Write out tally data. for i, tally_ind in enumerate(sp.tallies): tally = sp.tallies[tally_ind] @@ -36,7 +31,7 @@ class FixedSourceTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_fixed_source(): mat = openmc.Material() mat.add_nuclide('O16', 1.0) mat.add_nuclide('U238', 0.0001) diff --git a/tests/regression_tests/infinite_cell/__init__.py b/tests/regression_tests/infinite_cell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_infinite_cell/geometry.xml b/tests/regression_tests/infinite_cell/geometry.xml similarity index 100% rename from tests/test_infinite_cell/geometry.xml rename to tests/regression_tests/infinite_cell/geometry.xml diff --git a/tests/test_infinite_cell/materials.xml b/tests/regression_tests/infinite_cell/materials.xml similarity index 100% rename from tests/test_infinite_cell/materials.xml rename to tests/regression_tests/infinite_cell/materials.xml diff --git a/tests/test_infinite_cell/results_true.dat b/tests/regression_tests/infinite_cell/results_true.dat similarity index 100% rename from tests/test_infinite_cell/results_true.dat rename to tests/regression_tests/infinite_cell/results_true.dat diff --git a/tests/test_infinite_cell/settings.xml b/tests/regression_tests/infinite_cell/settings.xml similarity index 100% rename from tests/test_infinite_cell/settings.xml rename to tests/regression_tests/infinite_cell/settings.xml diff --git a/tests/regression_tests/infinite_cell/test.py b/tests/regression_tests/infinite_cell/test.py new file mode 100644 index 0000000000..59abec3003 --- /dev/null +++ b/tests/regression_tests/infinite_cell/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_infinite_cell(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/iso_in_lab/__init__.py b/tests/regression_tests/iso_in_lab/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_iso_in_lab/inputs_true.dat b/tests/regression_tests/iso_in_lab/inputs_true.dat similarity index 99% rename from tests/test_iso_in_lab/inputs_true.dat rename to tests/regression_tests/iso_in_lab/inputs_true.dat index 9e30f245f9..2a302ada67 100644 --- a/tests/test_iso_in_lab/inputs_true.dat +++ b/tests/regression_tests/iso_in_lab/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/test_iso_in_lab/results_true.dat b/tests/regression_tests/iso_in_lab/results_true.dat similarity index 100% rename from tests/test_iso_in_lab/results_true.dat rename to tests/regression_tests/iso_in_lab/results_true.dat diff --git a/tests/test_iso_in_lab/test_iso_in_lab.py b/tests/regression_tests/iso_in_lab/test.py similarity index 52% rename from tests/test_iso_in_lab/test_iso_in_lab.py rename to tests/regression_tests/iso_in_lab/test.py index 60b5bc2dee..0e8edc2186 100644 --- a/tests/test_iso_in_lab/test_iso_in_lab.py +++ b/tests/regression_tests/iso_in_lab/test.py @@ -1,12 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': +def test_iso_in_lab(): # Force iso-in-lab scattering. harness = PyAPITestHarness('statepoint.10.h5') harness._model.materials.make_isotropic_in_lab() diff --git a/tests/regression_tests/lattice/__init__.py b/tests/regression_tests/lattice/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_lattice/geometry.xml b/tests/regression_tests/lattice/geometry.xml similarity index 100% rename from tests/test_lattice/geometry.xml rename to tests/regression_tests/lattice/geometry.xml diff --git a/tests/test_lattice/materials.xml b/tests/regression_tests/lattice/materials.xml similarity index 100% rename from tests/test_lattice/materials.xml rename to tests/regression_tests/lattice/materials.xml diff --git a/tests/test_lattice/results_true.dat b/tests/regression_tests/lattice/results_true.dat similarity index 100% rename from tests/test_lattice/results_true.dat rename to tests/regression_tests/lattice/results_true.dat diff --git a/tests/test_lattice/settings.xml b/tests/regression_tests/lattice/settings.xml similarity index 100% rename from tests/test_lattice/settings.xml rename to tests/regression_tests/lattice/settings.xml diff --git a/tests/regression_tests/lattice/test.py b/tests/regression_tests/lattice/test.py new file mode 100644 index 0000000000..a32b9a629c --- /dev/null +++ b/tests/regression_tests/lattice/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_lattice(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/lattice_hex/__init__.py b/tests/regression_tests/lattice_hex/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_lattice_hex/geometry.xml b/tests/regression_tests/lattice_hex/geometry.xml similarity index 100% rename from tests/test_lattice_hex/geometry.xml rename to tests/regression_tests/lattice_hex/geometry.xml diff --git a/tests/test_lattice_hex/materials.xml b/tests/regression_tests/lattice_hex/materials.xml similarity index 100% rename from tests/test_lattice_hex/materials.xml rename to tests/regression_tests/lattice_hex/materials.xml diff --git a/tests/test_lattice_hex/plots.xml b/tests/regression_tests/lattice_hex/plots.xml similarity index 100% rename from tests/test_lattice_hex/plots.xml rename to tests/regression_tests/lattice_hex/plots.xml diff --git a/tests/test_lattice_hex/results_true.dat b/tests/regression_tests/lattice_hex/results_true.dat similarity index 100% rename from tests/test_lattice_hex/results_true.dat rename to tests/regression_tests/lattice_hex/results_true.dat diff --git a/tests/test_lattice_hex/settings.xml b/tests/regression_tests/lattice_hex/settings.xml similarity index 100% rename from tests/test_lattice_hex/settings.xml rename to tests/regression_tests/lattice_hex/settings.xml diff --git a/tests/regression_tests/lattice_hex/test.py b/tests/regression_tests/lattice_hex/test.py new file mode 100644 index 0000000000..eb63f84df5 --- /dev/null +++ b/tests/regression_tests/lattice_hex/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_lattice_hex(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/lattice_mixed/__init__.py b/tests/regression_tests/lattice_mixed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_lattice_mixed/geometry.xml b/tests/regression_tests/lattice_mixed/geometry.xml similarity index 100% rename from tests/test_lattice_mixed/geometry.xml rename to tests/regression_tests/lattice_mixed/geometry.xml diff --git a/tests/test_lattice_mixed/materials.xml b/tests/regression_tests/lattice_mixed/materials.xml similarity index 100% rename from tests/test_lattice_mixed/materials.xml rename to tests/regression_tests/lattice_mixed/materials.xml diff --git a/tests/test_lattice_mixed/plots.xml b/tests/regression_tests/lattice_mixed/plots.xml similarity index 100% rename from tests/test_lattice_mixed/plots.xml rename to tests/regression_tests/lattice_mixed/plots.xml diff --git a/tests/test_lattice_mixed/results_true.dat b/tests/regression_tests/lattice_mixed/results_true.dat similarity index 100% rename from tests/test_lattice_mixed/results_true.dat rename to tests/regression_tests/lattice_mixed/results_true.dat diff --git a/tests/test_lattice_mixed/settings.xml b/tests/regression_tests/lattice_mixed/settings.xml similarity index 100% rename from tests/test_lattice_mixed/settings.xml rename to tests/regression_tests/lattice_mixed/settings.xml diff --git a/tests/regression_tests/lattice_mixed/test.py b/tests/regression_tests/lattice_mixed/test.py new file mode 100644 index 0000000000..3df1d7a4f3 --- /dev/null +++ b/tests/regression_tests/lattice_mixed/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_lattice_mixed(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/lattice_multiple/__init__.py b/tests/regression_tests/lattice_multiple/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_lattice_multiple/geometry.xml b/tests/regression_tests/lattice_multiple/geometry.xml similarity index 100% rename from tests/test_lattice_multiple/geometry.xml rename to tests/regression_tests/lattice_multiple/geometry.xml diff --git a/tests/test_lattice_multiple/materials.xml b/tests/regression_tests/lattice_multiple/materials.xml similarity index 100% rename from tests/test_lattice_multiple/materials.xml rename to tests/regression_tests/lattice_multiple/materials.xml diff --git a/tests/test_lattice_multiple/results_true.dat b/tests/regression_tests/lattice_multiple/results_true.dat similarity index 100% rename from tests/test_lattice_multiple/results_true.dat rename to tests/regression_tests/lattice_multiple/results_true.dat diff --git a/tests/test_lattice_multiple/settings.xml b/tests/regression_tests/lattice_multiple/settings.xml similarity index 100% rename from tests/test_lattice_multiple/settings.xml rename to tests/regression_tests/lattice_multiple/settings.xml diff --git a/tests/regression_tests/lattice_multiple/test.py b/tests/regression_tests/lattice_multiple/test.py new file mode 100644 index 0000000000..f0672d9a4e --- /dev/null +++ b/tests/regression_tests/lattice_multiple/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_lattice_multiple(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/mg_basic/__init__.py b/tests/regression_tests/mg_basic/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mg_basic/inputs_true.dat b/tests/regression_tests/mg_basic/inputs_true.dat similarity index 98% rename from tests/test_mg_basic/inputs_true.dat rename to tests/regression_tests/mg_basic/inputs_true.dat index 220b1de240..a0efdbde0f 100644 --- a/tests/test_mg_basic/inputs_true.dat +++ b/tests/regression_tests/mg_basic/inputs_true.dat @@ -32,7 +32,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_basic/results_true.dat b/tests/regression_tests/mg_basic/results_true.dat similarity index 100% rename from tests/test_mg_basic/results_true.dat rename to tests/regression_tests/mg_basic/results_true.dat diff --git a/tests/regression_tests/mg_basic/test.py b/tests/regression_tests/mg_basic/test.py new file mode 100644 index 0000000000..3c22e60408 --- /dev/null +++ b/tests/regression_tests/mg_basic/test.py @@ -0,0 +1,9 @@ +from openmc.examples import slab_mg + +from tests.testing_harness import PyAPITestHarness + + +def test_mg_basic(): + model = slab_mg() + harness = PyAPITestHarness('statepoint.10.h5', model) + harness.main() diff --git a/tests/regression_tests/mg_convert/__init__.py b/tests/regression_tests/mg_convert/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mg_convert/inputs_true.dat b/tests/regression_tests/mg_convert/inputs_true.dat similarity index 100% rename from tests/test_mg_convert/inputs_true.dat rename to tests/regression_tests/mg_convert/inputs_true.dat diff --git a/tests/test_mg_convert/results_true.dat b/tests/regression_tests/mg_convert/results_true.dat similarity index 100% rename from tests/test_mg_convert/results_true.dat rename to tests/regression_tests/mg_convert/results_true.dat diff --git a/tests/test_mg_convert/test_mg_convert.py b/tests/regression_tests/mg_convert/test.py similarity index 86% rename from tests/test_mg_convert/test_mg_convert.py rename to tests/regression_tests/mg_convert/test.py index 9d13714580..1ace10c80b 100755 --- a/tests/test_mg_convert/test_mg_convert.py +++ b/tests/regression_tests/mg_convert/test.py @@ -1,15 +1,12 @@ -#!/usr/bin/env python - import os -import sys import hashlib -sys.path.insert(0, os.pardir) import numpy as np - -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness +from tests.regression_tests import config + # OpenMC simulation parameters batches = 10 inactive = 5 @@ -137,27 +134,18 @@ class MGXSTestHarness(PyAPITestHarness): for case in cases: build_mgxs_library(case) - if self._opts.mpi_exec is not None: - mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - returncode = openmc.run(openmc_exec=self._opts.exe, - mpi_args=mpi_args) + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(openmc_exec=config['exe'], mpi_args=mpi_args) else: - returncode = openmc.run(openmc_exec=self._opts.exe) + openmc.run(openmc_exec=config['exe']) - assert returncode == 0, 'OpenMC did not exit successfully.' - - sp = openmc.StatePoint('statepoint.' + str(batches) + '.h5') - - # Write out k-combined. - outstr += 'k-combined:\n' - form = '{0:12.6E} {1:12.6E}\n' - outstr += form.format(sp.k_combined[0], sp.k_combined[1]) - - # Enforce closing statepoint and summary files so HDF5 - # does not throw an error during the next OpenMC execution - sp._f.close() - sp._summary._f.close() + with openmc.StatePoint('statepoint.{}.h5'.format(batches)) as sp: + # Write out k-combined. + outstr += 'k-combined:\n' + form = '{:12.6E} {:12.6E}\n' + outstr += form.format(sp.k_combined.n, sp.k_combined.s) return outstr @@ -171,7 +159,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr def _cleanup(self): - super(MGXSTestHarness, self)._cleanup() + super()._cleanup() f = os.path.join(os.getcwd(), 'mgxs.h5') if os.path.exists(f): os.remove(f) @@ -205,6 +193,6 @@ class MGXSTestHarness(PyAPITestHarness): self._cleanup() -if __name__ == '__main__': +def test_mg_convert(): harness = MGXSTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/mg_legendre/__init__.py b/tests/regression_tests/mg_legendre/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mg_legendre/inputs_true.dat b/tests/regression_tests/mg_legendre/inputs_true.dat similarity index 96% rename from tests/test_mg_legendre/inputs_true.dat rename to tests/regression_tests/mg_legendre/inputs_true.dat index 9b63fb944c..7548080955 100644 --- a/tests/test_mg_legendre/inputs_true.dat +++ b/tests/regression_tests/mg_legendre/inputs_true.dat @@ -14,7 +14,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_legendre/results_true.dat b/tests/regression_tests/mg_legendre/results_true.dat similarity index 100% rename from tests/test_mg_legendre/results_true.dat rename to tests/regression_tests/mg_legendre/results_true.dat diff --git a/tests/test_mg_legendre/test_mg_legendre.py b/tests/regression_tests/mg_legendre/test.py similarity index 58% rename from tests/test_mg_legendre/test_mg_legendre.py rename to tests/regression_tests/mg_legendre/test.py index eee0f0800f..5a57f758e8 100644 --- a/tests/test_mg_legendre/test_mg_legendre.py +++ b/tests/regression_tests/mg_legendre/test.py @@ -1,14 +1,9 @@ -#!/usr/bin/env python - -import os -import sys - -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness from openmc.examples import slab_mg +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': + +def test_mg_legendre(): model = slab_mg(reps=['iso']) model.settings.tabular_legendre = {'enable': False} diff --git a/tests/regression_tests/mg_max_order/__init__.py b/tests/regression_tests/mg_max_order/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mg_max_order/inputs_true.dat b/tests/regression_tests/mg_max_order/inputs_true.dat similarity index 96% rename from tests/test_mg_max_order/inputs_true.dat rename to tests/regression_tests/mg_max_order/inputs_true.dat index 3954bc73a7..023d468d4f 100644 --- a/tests/test_mg_max_order/inputs_true.dat +++ b/tests/regression_tests/mg_max_order/inputs_true.dat @@ -14,7 +14,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_max_order/results_true.dat b/tests/regression_tests/mg_max_order/results_true.dat similarity index 100% rename from tests/test_mg_max_order/results_true.dat rename to tests/regression_tests/mg_max_order/results_true.dat diff --git a/tests/test_mg_max_order/test_mg_max_order.py b/tests/regression_tests/mg_max_order/test.py similarity index 55% rename from tests/test_mg_max_order/test_mg_max_order.py rename to tests/regression_tests/mg_max_order/test.py index 8ac0f58785..20cc4f805d 100644 --- a/tests/test_mg_max_order/test_mg_max_order.py +++ b/tests/regression_tests/mg_max_order/test.py @@ -1,14 +1,9 @@ -#!/usr/bin/env python - -import os -import sys - -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness from openmc.examples import slab_mg +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': + +def test_mg_max_order(): model = slab_mg(reps=['iso']) model.settings.max_order = 1 harness = PyAPITestHarness('statepoint.10.h5', model) diff --git a/tests/regression_tests/mg_nuclide/__init__.py b/tests/regression_tests/mg_nuclide/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mg_nuclide/inputs_true.dat b/tests/regression_tests/mg_nuclide/inputs_true.dat similarity index 98% rename from tests/test_mg_nuclide/inputs_true.dat rename to tests/regression_tests/mg_nuclide/inputs_true.dat index d42b15480d..e11b9e3f07 100644 --- a/tests/test_mg_nuclide/inputs_true.dat +++ b/tests/regression_tests/mg_nuclide/inputs_true.dat @@ -32,7 +32,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_nuclide/results_true.dat b/tests/regression_tests/mg_nuclide/results_true.dat similarity index 100% rename from tests/test_mg_nuclide/results_true.dat rename to tests/regression_tests/mg_nuclide/results_true.dat diff --git a/tests/test_mg_nuclide/test_mg_nuclide.py b/tests/regression_tests/mg_nuclide/test.py similarity index 51% rename from tests/test_mg_nuclide/test_mg_nuclide.py rename to tests/regression_tests/mg_nuclide/test.py index 0f3c9dd6d7..44206ef28f 100644 --- a/tests/test_mg_nuclide/test_mg_nuclide.py +++ b/tests/regression_tests/mg_nuclide/test.py @@ -1,14 +1,9 @@ -#!/usr/bin/env python - -import os -import sys - -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness from openmc.examples import slab_mg +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': + +def test_mg_nuclide(): model = slab_mg(as_macro=False) harness = PyAPITestHarness('statepoint.10.h5', model) harness.main() diff --git a/tests/regression_tests/mg_survival_biasing/__init__.py b/tests/regression_tests/mg_survival_biasing/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mg_survival_biasing/inputs_true.dat b/tests/regression_tests/mg_survival_biasing/inputs_true.dat similarity index 98% rename from tests/test_mg_survival_biasing/inputs_true.dat rename to tests/regression_tests/mg_survival_biasing/inputs_true.dat index 057af68105..4bc79d48e3 100644 --- a/tests/test_mg_survival_biasing/inputs_true.dat +++ b/tests/regression_tests/mg_survival_biasing/inputs_true.dat @@ -32,7 +32,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_survival_biasing/results_true.dat b/tests/regression_tests/mg_survival_biasing/results_true.dat similarity index 100% rename from tests/test_mg_survival_biasing/results_true.dat rename to tests/regression_tests/mg_survival_biasing/results_true.dat diff --git a/tests/test_mg_survival_biasing/test_mg_survival_biasing.py b/tests/regression_tests/mg_survival_biasing/test.py similarity index 55% rename from tests/test_mg_survival_biasing/test_mg_survival_biasing.py rename to tests/regression_tests/mg_survival_biasing/test.py index 9886ad3e49..3c6c77a370 100644 --- a/tests/test_mg_survival_biasing/test_mg_survival_biasing.py +++ b/tests/regression_tests/mg_survival_biasing/test.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness from openmc.examples import slab_mg +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': + +def test_mg_survival_biasing(): model = slab_mg() model.settings.survival_biasing = True harness = PyAPITestHarness('statepoint.10.h5', model) diff --git a/tests/regression_tests/mg_tallies/__init__.py b/tests/regression_tests/mg_tallies/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mg_tallies/inputs_true.dat b/tests/regression_tests/mg_tallies/inputs_true.dat similarity index 99% rename from tests/test_mg_tallies/inputs_true.dat rename to tests/regression_tests/mg_tallies/inputs_true.dat index 0c71689aea..7b5067014f 100644 --- a/tests/test_mg_tallies/inputs_true.dat +++ b/tests/regression_tests/mg_tallies/inputs_true.dat @@ -32,7 +32,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_tallies/results_true.dat b/tests/regression_tests/mg_tallies/results_true.dat similarity index 100% rename from tests/test_mg_tallies/results_true.dat rename to tests/regression_tests/mg_tallies/results_true.dat diff --git a/tests/test_mg_tallies/test_mg_tallies.py b/tests/regression_tests/mg_tallies/test.py similarity index 95% rename from tests/test_mg_tallies/test_mg_tallies.py rename to tests/regression_tests/mg_tallies/test.py index aeafae3182..8952cc4ad8 100644 --- a/tests/test_mg_tallies/test_mg_tallies.py +++ b/tests/regression_tests/mg_tallies/test.py @@ -1,14 +1,10 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import HashedPyAPITestHarness import openmc from openmc.examples import slab_mg +from tests.testing_harness import HashedPyAPITestHarness -if __name__ == '__main__': + +def test_mg_tallies(): model = slab_mg(as_macro=False) # Instantiate a tally mesh diff --git a/tests/regression_tests/mgxs_library_ce_to_mg/__init__.py b/tests/regression_tests/mgxs_library_ce_to_mg/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mgxs_library_ce_to_mg/inputs_true.dat b/tests/regression_tests/mgxs_library_ce_to_mg/inputs_true.dat similarity index 99% rename from tests/test_mgxs_library_ce_to_mg/inputs_true.dat rename to tests/regression_tests/mgxs_library_ce_to_mg/inputs_true.dat index 8e8cde2818..70996fe378 100644 --- a/tests/test_mgxs_library_ce_to_mg/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_ce_to_mg/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/test_mgxs_library_ce_to_mg/results_true.dat b/tests/regression_tests/mgxs_library_ce_to_mg/results_true.dat similarity index 100% rename from tests/test_mgxs_library_ce_to_mg/results_true.dat rename to tests/regression_tests/mgxs_library_ce_to_mg/results_true.dat diff --git a/tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py b/tests/regression_tests/mgxs_library_ce_to_mg/test.py similarity index 64% rename from tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py rename to tests/regression_tests/mgxs_library_ce_to_mg/test.py index aaa83a70db..72f052e68e 100644 --- a/tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py +++ b/tests/regression_tests/mgxs_library_ce_to_mg/test.py @@ -1,19 +1,17 @@ -#!/usr/bin/env python - import os -import sys -import glob -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness + import openmc import openmc.mgxs from openmc.examples import pwr_pin_cell +from tests.testing_harness import PyAPITestHarness +from tests.regression_tests import config + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): # Generate inputs using parent class routine - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) @@ -34,20 +32,15 @@ class MGXSTestHarness(PyAPITestHarness): def _run_openmc(self): # Initial run - if self._opts.mpi_exec is not None: - mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - returncode = openmc.run(openmc_exec=self._opts.exe, - mpi_args=mpi_args) + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(openmc_exec=config['exe'], mpi_args=mpi_args) else: - returncode = openmc.run(openmc_exec=self._opts.exe) - - assert returncode == 0, 'CE OpenMC calculation did not exit' \ - 'successfully.' + openmc.run(openmc_exec=config['exe']) # Build MG Inputs # Get data needed to execute Library calculations. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) self.mgxs_lib.load_from_statepoint(sp) self._model.mgxs_file, self._model.materials, \ self._model.geometry = self.mgxs_lib.create_mg_mode() @@ -62,8 +55,8 @@ class MGXSTestHarness(PyAPITestHarness): self._model.materials.export_to_xml() self._model.mgxs_file.export_to_hdf5() # Dont need tallies.xml, so remove the file - if os.path.exists('./tallies.xml'): - os.remove('./tallies.xml') + if os.path.exists('tallies.xml'): + os.remove('tallies.xml') # Enforce closing statepoint and summary files so HDF5 # does not throw an error during the next OpenMC execution @@ -71,21 +64,20 @@ class MGXSTestHarness(PyAPITestHarness): sp._summary._f.close() # Re-run MG mode. - if self._opts.mpi_exec is not None: - mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - returncode = openmc.run(openmc_exec=self._opts.exe, - mpi_args=mpi_args) + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(openmc_exec=config['exe'], mpi_args=mpi_args) else: - returncode = openmc.run(openmc_exec=self._opts.exe) + openmc.run(openmc_exec=config['exe']) def _cleanup(self): - super(MGXSTestHarness, self)._cleanup() - f = os.path.join(os.getcwd(), 'mgxs.h5') + super()._cleanup() + f = 'mgxs.h5' if os.path.exists(f): os.remove(f) -if __name__ == '__main__': +def test_mgxs_library_ce_to_mg(): # Set the input set to use the pincell model model = pwr_pin_cell() diff --git a/tests/regression_tests/mgxs_library_condense/__init__.py b/tests/regression_tests/mgxs_library_condense/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mgxs_library_no_nuclides/inputs_true.dat b/tests/regression_tests/mgxs_library_condense/inputs_true.dat similarity index 99% rename from tests/test_mgxs_library_no_nuclides/inputs_true.dat rename to tests/regression_tests/mgxs_library_condense/inputs_true.dat index d2f28d0fe0..ef6c4c5206 100644 --- a/tests/test_mgxs_library_no_nuclides/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_condense/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/test_mgxs_library_condense/results_true.dat b/tests/regression_tests/mgxs_library_condense/results_true.dat similarity index 100% rename from tests/test_mgxs_library_condense/results_true.dat rename to tests/regression_tests/mgxs_library_condense/results_true.dat diff --git a/tests/test_mgxs_library_condense/test_mgxs_library_condense.py b/tests/regression_tests/mgxs_library_condense/test.py similarity index 85% rename from tests/test_mgxs_library_condense/test_mgxs_library_condense.py rename to tests/regression_tests/mgxs_library_condense/test.py index 127980da6e..167772e2fd 100644 --- a/tests/test_mgxs_library_condense/test_mgxs_library_condense.py +++ b/tests/regression_tests/mgxs_library_condense/test.py @@ -1,19 +1,15 @@ -#!/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 import openmc.mgxs from openmc.examples import pwr_pin_cell +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) @@ -38,8 +34,7 @@ class MGXSTestHarness(PyAPITestHarness): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -65,7 +60,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_condense(): # Use the pincell model model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) diff --git a/tests/regression_tests/mgxs_library_distribcell/__init__.py b/tests/regression_tests/mgxs_library_distribcell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mgxs_library_distribcell/inputs_true.dat b/tests/regression_tests/mgxs_library_distribcell/inputs_true.dat similarity index 99% rename from tests/test_mgxs_library_distribcell/inputs_true.dat rename to tests/regression_tests/mgxs_library_distribcell/inputs_true.dat index d7a4a186ac..ba7dc05ff7 100644 --- a/tests/test_mgxs_library_distribcell/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_distribcell/inputs_true.dat @@ -39,7 +39,7 @@ - + diff --git a/tests/test_mgxs_library_distribcell/results_true.dat b/tests/regression_tests/mgxs_library_distribcell/results_true.dat similarity index 100% rename from tests/test_mgxs_library_distribcell/results_true.dat rename to tests/regression_tests/mgxs_library_distribcell/results_true.dat diff --git a/tests/test_mgxs_library_distribcell/test_mgxs_library_distribcell.py b/tests/regression_tests/mgxs_library_distribcell/test.py similarity index 86% rename from tests/test_mgxs_library_distribcell/test_mgxs_library_distribcell.py rename to tests/regression_tests/mgxs_library_distribcell/test.py index 38f16c5884..5290d313bb 100644 --- a/tests/test_mgxs_library_distribcell/test_mgxs_library_distribcell.py +++ b/tests/regression_tests/mgxs_library_distribcell/test.py @@ -1,20 +1,16 @@ -#!/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 import openmc.mgxs from openmc.examples import pwr_assembly +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): # Generate inputs using parent class routine - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a one-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 20.e6]) @@ -43,8 +39,7 @@ class MGXSTestHarness(PyAPITestHarness): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -69,7 +64,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_distribcell(): model = pwr_assembly() harness = MGXSTestHarness('statepoint.10.h5', model) harness.main() diff --git a/tests/regression_tests/mgxs_library_hdf5/__init__.py b/tests/regression_tests/mgxs_library_hdf5/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mgxs_library_condense/inputs_true.dat b/tests/regression_tests/mgxs_library_hdf5/inputs_true.dat similarity index 99% rename from tests/test_mgxs_library_condense/inputs_true.dat rename to tests/regression_tests/mgxs_library_hdf5/inputs_true.dat index d2f28d0fe0..ef6c4c5206 100644 --- a/tests/test_mgxs_library_condense/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_hdf5/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/test_mgxs_library_hdf5/results_true.dat b/tests/regression_tests/mgxs_library_hdf5/results_true.dat similarity index 100% rename from tests/test_mgxs_library_hdf5/results_true.dat rename to tests/regression_tests/mgxs_library_hdf5/results_true.dat diff --git a/tests/test_mgxs_library_hdf5/test_mgxs_library_hdf5.py b/tests/regression_tests/mgxs_library_hdf5/test.py similarity index 79% rename from tests/test_mgxs_library_hdf5/test_mgxs_library_hdf5.py rename to tests/regression_tests/mgxs_library_hdf5/test.py index 31a9d96126..9811ab2155 100644 --- a/tests/test_mgxs_library_hdf5/test_mgxs_library_hdf5.py +++ b/tests/regression_tests/mgxs_library_hdf5/test.py @@ -1,27 +1,19 @@ -#!/usr/bin/env python - import os -import sys -import glob import hashlib import numpy as np import h5py - -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness import openmc import openmc.mgxs from openmc.examples import pwr_pin_cell - -np.set_printoptions(formatter={'float_kind': '{:.8e}'.format}) +from tests.testing_harness import PyAPITestHarness class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): # Generate inputs using parent class routine - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) @@ -46,8 +38,7 @@ class MGXSTestHarness(PyAPITestHarness): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -76,13 +67,17 @@ class MGXSTestHarness(PyAPITestHarness): return outstr def _cleanup(self): - super(MGXSTestHarness, self)._cleanup() - f = os.path.join(os.getcwd(), 'mgxs.h5') + super()._cleanup() + f = 'mgxs.h5' if os.path.exists(f): os.remove(f) -if __name__ == '__main__': - model = pwr_pin_cell() - harness = MGXSTestHarness('statepoint.10.h5', model) - harness.main() +def test_mgxs_library_hdf5(): + try: + np.set_printoptions(formatter={'float_kind': '{:.8e}'.format}) + model = pwr_pin_cell() + harness = MGXSTestHarness('statepoint.10.h5', model) + harness.main() + finally: + np.set_printoptions(formatter=None) diff --git a/tests/regression_tests/mgxs_library_mesh/__init__.py b/tests/regression_tests/mgxs_library_mesh/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mgxs_library_mesh/inputs_true.dat b/tests/regression_tests/mgxs_library_mesh/inputs_true.dat similarity index 99% rename from tests/test_mgxs_library_mesh/inputs_true.dat rename to tests/regression_tests/mgxs_library_mesh/inputs_true.dat index 4756b27bfb..aa2c904b19 100644 --- a/tests/test_mgxs_library_mesh/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_mesh/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/test_mgxs_library_mesh/results_true.dat b/tests/regression_tests/mgxs_library_mesh/results_true.dat similarity index 60% rename from tests/test_mgxs_library_mesh/results_true.dat rename to tests/regression_tests/mgxs_library_mesh/results_true.dat index c167628bcc..4b9303fbf3 100644 --- a/tests/test_mgxs_library_mesh/results_true.dat +++ b/tests/regression_tests/mgxs_library_mesh/results_true.dat @@ -1,62 +1,62 @@ mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.762544 0.085298 -1 1 2 1 1 total 0.653375 0.153317 -2 2 1 1 1 total 0.644837 0.088457 +2 1 2 1 1 total 0.644837 0.088457 +1 2 1 1 1 total 0.653375 0.153317 3 2 2 1 1 total 0.676480 0.094215 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.473988 0.088732 -1 1 2 1 1 total 0.379821 0.167092 -2 2 1 1 1 total 0.399254 0.091318 +2 1 2 1 1 total 0.399254 0.091318 +1 2 1 1 1 total 0.379821 0.167092 3 2 2 1 1 total 0.424265 0.099551 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.473988 0.088732 -1 1 2 1 1 total 0.379821 0.167092 -2 2 1 1 1 total 0.399254 0.091318 +2 1 2 1 1 total 0.399254 0.091318 +1 2 1 1 1 total 0.379821 0.167092 3 2 2 1 1 total 0.424265 0.099551 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.027288 0.005813 -1 1 2 1 1 total 0.019449 0.004420 -2 2 1 1 1 total 0.020262 0.003701 +2 1 2 1 1 total 0.020262 0.003701 +1 2 1 1 1 total 0.019449 0.004420 3 2 2 1 1 total 0.021266 0.002869 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.016037 0.006339 -1 1 2 1 1 total 0.012153 0.003804 -2 2 1 1 1 total 0.013018 0.003521 +2 1 2 1 1 total 0.013018 0.003521 +1 2 1 1 1 total 0.012153 0.003804 3 2 2 1 1 total 0.012965 0.002454 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.011251 0.003050 -1 1 2 1 1 total 0.007296 0.001795 -2 2 1 1 1 total 0.007243 0.001219 +2 1 2 1 1 total 0.007243 0.001219 +1 2 1 1 1 total 0.007296 0.001795 3 2 2 1 1 total 0.008301 0.001066 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.027498 0.007445 -1 1 2 1 1 total 0.017912 0.004426 -2 2 1 1 1 total 0.017954 0.003077 +2 1 2 1 1 total 0.017954 0.003077 +1 2 1 1 1 total 0.017912 0.004426 3 2 2 1 1 total 0.020469 0.002617 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 2.177345e+06 589804.299388 -1 1 2 1 1 total 1.413154e+06 347806.623417 -2 2 1 1 1 total 1.404096e+06 236476.851953 +2 1 2 1 1 total 1.404096e+06 236476.851953 +1 2 1 1 1 total 1.413154e+06 347806.623417 3 2 2 1 1 total 1.608259e+06 206502.707865 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.735256 0.080216 -1 1 2 1 1 total 0.633925 0.149098 -2 2 1 1 1 total 0.624575 0.084974 +2 1 2 1 1 total 0.624575 0.084974 +1 2 1 1 1 total 0.633925 0.149098 3 2 2 1 1 total 0.655214 0.091422 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.763779 0.070696 -1 1 2 1 1 total 0.640809 0.158369 -2 2 1 1 1 total 0.628158 0.064356 +2 1 2 1 1 total 0.628158 0.064356 +1 2 1 1 1 total 0.640809 0.158369 3 2 2 1 1 total 0.645171 0.080467 mesh 1 group in group out nuclide moment mean std. dev. x y z @@ -64,14 +64,14 @@ 1 1 1 1 1 1 total P1 0.288556 0.024446 2 1 1 1 1 1 total P2 0.082441 0.011443 3 1 1 1 1 1 total P3 -0.005627 0.012638 -4 1 2 1 1 1 total P0 0.640809 0.158369 -5 1 2 1 1 1 total P1 0.273553 0.066437 -6 1 2 1 1 1 total P2 0.108446 0.024435 -7 1 2 1 1 1 total P3 0.012229 0.003785 -8 2 1 1 1 1 total P0 0.628158 0.064356 -9 2 1 1 1 1 total P1 0.245583 0.022676 -10 2 1 1 1 1 total P2 0.086370 0.007833 -11 2 1 1 1 1 total P3 0.019590 0.005345 +8 1 2 1 1 1 total P0 0.628158 0.064356 +9 1 2 1 1 1 total P1 0.245583 0.022676 +10 1 2 1 1 1 total P2 0.086370 0.007833 +11 1 2 1 1 1 total P3 0.019590 0.005345 +4 2 1 1 1 1 total P0 0.640809 0.158369 +5 2 1 1 1 1 total P1 0.273553 0.066437 +6 2 1 1 1 1 total P2 0.108446 0.024435 +7 2 1 1 1 1 total P3 0.012229 0.003785 12 2 2 1 1 1 total P0 0.645171 0.080467 13 2 2 1 1 1 total P1 0.252215 0.032154 14 2 2 1 1 1 total P2 0.089251 0.009734 @@ -82,14 +82,14 @@ 1 1 1 1 1 1 total P1 0.288556 0.024446 2 1 1 1 1 1 total P2 0.082441 0.011443 3 1 1 1 1 1 total P3 -0.005627 0.012638 -4 1 2 1 1 1 total P0 0.640809 0.158369 -5 1 2 1 1 1 total P1 0.273553 0.066437 -6 1 2 1 1 1 total P2 0.108446 0.024435 -7 1 2 1 1 1 total P3 0.012229 0.003785 -8 2 1 1 1 1 total P0 0.628158 0.064356 -9 2 1 1 1 1 total P1 0.245583 0.022676 -10 2 1 1 1 1 total P2 0.086370 0.007833 -11 2 1 1 1 1 total P3 0.019590 0.005345 +8 1 2 1 1 1 total P0 0.628158 0.064356 +9 1 2 1 1 1 total P1 0.245583 0.022676 +10 1 2 1 1 1 total P2 0.086370 0.007833 +11 1 2 1 1 1 total P3 0.019590 0.005345 +4 2 1 1 1 1 total P0 0.640809 0.158369 +5 2 1 1 1 1 total P1 0.273553 0.066437 +6 2 1 1 1 1 total P2 0.108446 0.024435 +7 2 1 1 1 1 total P3 0.012229 0.003785 12 2 2 1 1 1 total P0 0.645171 0.080467 13 2 2 1 1 1 total P1 0.252215 0.032154 14 2 2 1 1 1 total P2 0.089251 0.009734 @@ -97,20 +97,20 @@ mesh 1 group in group out nuclide mean std. dev. x y z 0 1 1 1 1 1 total 1.0 0.108337 -1 1 2 1 1 1 total 1.0 0.238517 -2 2 1 1 1 1 total 1.0 0.113128 +2 1 2 1 1 1 total 1.0 0.113128 +1 2 1 1 1 1 total 1.0 0.238517 3 2 2 1 1 1 total 1.0 0.132597 mesh 1 group in group out nuclide mean std. dev. x y z 0 1 1 1 1 1 total 0.015584 0.003404 -1 1 2 1 1 1 total 0.014200 0.003676 -2 2 1 1 1 1 total 0.017684 0.002499 +2 1 2 1 1 1 total 0.017684 0.002499 +1 2 1 1 1 1 total 0.014200 0.003676 3 2 2 1 1 1 total 0.022409 0.002481 mesh 1 group in group out nuclide mean std. dev. x y z 0 1 1 1 1 1 total 1.0 0.108337 -1 1 2 1 1 1 total 1.0 0.238517 -2 2 1 1 1 1 total 1.0 0.113128 +2 1 2 1 1 1 total 1.0 0.113128 +1 2 1 1 1 1 total 1.0 0.238517 3 2 2 1 1 1 total 1.0 0.132597 mesh 1 group in group out nuclide moment mean std. dev. x y z @@ -118,14 +118,14 @@ 1 1 1 1 1 1 total P1 0.277780 0.041434 2 1 1 1 1 1 total P2 0.079362 0.014706 3 1 1 1 1 1 total P3 -0.005417 0.012184 -4 1 2 1 1 1 total P0 0.633925 0.212349 -5 1 2 1 1 1 total P1 0.270615 0.089799 -6 1 2 1 1 1 total P2 0.107281 0.034246 -7 1 2 1 1 1 total P3 0.012098 0.004637 -8 2 1 1 1 1 total P0 0.624575 0.110512 -9 2 1 1 1 1 total P1 0.244182 0.041824 -10 2 1 1 1 1 total P2 0.085877 0.014634 -11 2 1 1 1 1 total P3 0.019478 0.006012 +8 1 2 1 1 1 total P0 0.624575 0.110512 +9 1 2 1 1 1 total P1 0.244182 0.041824 +10 1 2 1 1 1 total P2 0.085877 0.014634 +11 1 2 1 1 1 total P3 0.019478 0.006012 +4 2 1 1 1 1 total P0 0.633925 0.212349 +5 2 1 1 1 1 total P1 0.270615 0.089799 +6 2 1 1 1 1 total P2 0.107281 0.034246 +7 2 1 1 1 1 total P3 0.012098 0.004637 12 2 2 1 1 1 total P0 0.655214 0.126119 13 2 2 1 1 1 total P1 0.256141 0.049765 14 2 2 1 1 1 total P2 0.090641 0.016563 @@ -136,14 +136,14 @@ 1 1 1 1 1 1 total P1 0.277780 0.051210 2 1 1 1 1 1 total P2 0.079362 0.017035 3 1 1 1 1 1 total P3 -0.005417 0.012198 -4 1 2 1 1 1 total P0 0.633925 0.260681 -5 1 2 1 1 1 total P1 0.270615 0.110590 -6 1 2 1 1 1 total P2 0.107281 0.042750 -7 1 2 1 1 1 total P3 0.012098 0.005462 -8 2 1 1 1 1 total P0 0.624575 0.131169 -9 2 1 1 1 1 total P1 0.244182 0.050123 -10 2 1 1 1 1 total P2 0.085877 0.017565 -11 2 1 1 1 1 total P3 0.019478 0.006403 +8 1 2 1 1 1 total P0 0.624575 0.131169 +9 1 2 1 1 1 total P1 0.244182 0.050123 +10 1 2 1 1 1 total P2 0.085877 0.017565 +11 1 2 1 1 1 total P3 0.019478 0.006403 +4 2 1 1 1 1 total P0 0.633925 0.260681 +5 2 1 1 1 1 total P1 0.270615 0.110590 +6 2 1 1 1 1 total P2 0.107281 0.042750 +7 2 1 1 1 1 total P3 0.012098 0.005462 12 2 2 1 1 1 total P0 0.655214 0.153147 13 2 2 1 1 1 total P1 0.256141 0.060250 14 2 2 1 1 1 total P2 0.090641 0.020464 @@ -151,32 +151,32 @@ mesh 1 group out nuclide mean std. dev. x y z 0 1 1 1 1 total 1.0 0.300047 -1 1 2 1 1 total 1.0 0.262180 -2 2 1 1 1 total 1.0 0.178169 +2 1 2 1 1 total 1.0 0.178169 +1 2 1 1 1 total 1.0 0.262180 3 2 2 1 1 total 1.0 0.104797 mesh 1 group out nuclide mean std. dev. x y z 0 1 1 1 1 total 1.0 0.300047 -1 1 2 1 1 total 1.0 0.262180 -2 2 1 1 1 total 1.0 0.178169 +2 1 2 1 1 total 1.0 0.178169 +1 2 1 1 1 total 1.0 0.262180 3 2 2 1 1 total 1.0 0.108931 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 7.097008e-07 1.458546e-07 -1 1 2 1 1 total 3.984535e-07 1.157576e-07 -2 2 1 1 1 total 4.407745e-07 7.903907e-08 +2 1 2 1 1 total 4.407745e-07 7.903907e-08 +1 2 1 1 1 total 3.984535e-07 1.157576e-07 3 2 2 1 1 total 4.750476e-07 6.207437e-08 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.027311 0.007397 -1 1 2 1 1 total 0.017783 0.004394 -2 2 1 1 1 total 0.017820 0.003054 +2 1 2 1 1 total 0.017820 0.003054 +1 2 1 1 1 total 0.017783 0.004394 3 2 2 1 1 total 0.020320 0.002598 mesh 1 group in group out nuclide mean std. dev. x y z 0 1 1 1 1 1 total 0.015584 0.003404 -1 1 2 1 1 1 total 0.014200 0.003676 -2 2 1 1 1 1 total 0.017684 0.002499 +2 1 2 1 1 1 total 0.017684 0.002499 +1 2 1 1 1 1 total 0.014200 0.003676 3 2 2 1 1 1 total 0.022259 0.002508 mesh 1 delayedgroup group in nuclide mean std. dev. x y z @@ -186,18 +186,18 @@ 3 1 1 1 4 1 total 0.000072 1.866015e-05 4 1 1 1 5 1 total 0.000031 7.654909e-06 5 1 1 1 6 1 total 0.000013 3.206343e-06 -6 1 2 1 1 1 total 0.000004 1.003100e-06 -7 1 2 1 2 1 total 0.000022 5.425275e-06 -8 1 2 1 3 1 total 0.000021 5.324236e-06 -9 1 2 1 4 1 total 0.000050 1.251572e-05 -10 1 2 1 5 1 total 0.000022 5.762184e-06 -11 1 2 1 6 1 total 0.000009 2.391676e-06 -12 2 1 1 1 1 total 0.000004 6.723192e-07 -13 2 1 1 2 1 total 0.000022 3.706235e-06 -14 2 1 1 3 1 total 0.000022 3.674263e-06 -15 2 1 1 4 1 total 0.000052 8.774048e-06 -16 2 1 1 5 1 total 0.000024 4.168024e-06 -17 2 1 1 6 1 total 0.000010 1.726268e-06 +12 1 2 1 1 1 total 0.000004 6.723192e-07 +13 1 2 1 2 1 total 0.000022 3.706235e-06 +14 1 2 1 3 1 total 0.000022 3.674263e-06 +15 1 2 1 4 1 total 0.000052 8.774048e-06 +16 1 2 1 5 1 total 0.000024 4.168024e-06 +17 1 2 1 6 1 total 0.000010 1.726268e-06 +6 2 1 1 1 1 total 0.000004 1.003100e-06 +7 2 1 1 2 1 total 0.000022 5.425275e-06 +8 2 1 1 3 1 total 0.000021 5.324236e-06 +9 2 1 1 4 1 total 0.000050 1.251572e-05 +10 2 1 1 5 1 total 0.000022 5.762184e-06 +11 2 1 1 6 1 total 0.000009 2.391676e-06 18 2 2 1 1 1 total 0.000005 5.962367e-07 19 2 2 1 2 1 total 0.000025 3.200900e-06 20 2 2 1 3 1 total 0.000025 3.127442e-06 @@ -212,18 +212,18 @@ 3 1 1 1 4 1 total 0.0 0.000000 4 1 1 1 5 1 total 0.0 0.000000 5 1 1 1 6 1 total 0.0 0.000000 -6 1 2 1 1 1 total 0.0 0.000000 -7 1 2 1 2 1 total 0.0 0.000000 -8 1 2 1 3 1 total 0.0 0.000000 -9 1 2 1 4 1 total 0.0 0.000000 -10 1 2 1 5 1 total 0.0 0.000000 -11 1 2 1 6 1 total 0.0 0.000000 -12 2 1 1 1 1 total 0.0 0.000000 -13 2 1 1 2 1 total 0.0 0.000000 -14 2 1 1 3 1 total 0.0 0.000000 -15 2 1 1 4 1 total 0.0 0.000000 -16 2 1 1 5 1 total 0.0 0.000000 -17 2 1 1 6 1 total 0.0 0.000000 +12 1 2 1 1 1 total 0.0 0.000000 +13 1 2 1 2 1 total 0.0 0.000000 +14 1 2 1 3 1 total 0.0 0.000000 +15 1 2 1 4 1 total 0.0 0.000000 +16 1 2 1 5 1 total 0.0 0.000000 +17 1 2 1 6 1 total 0.0 0.000000 +6 2 1 1 1 1 total 0.0 0.000000 +7 2 1 1 2 1 total 0.0 0.000000 +8 2 1 1 3 1 total 0.0 0.000000 +9 2 1 1 4 1 total 0.0 0.000000 +10 2 1 1 5 1 total 0.0 0.000000 +11 2 1 1 6 1 total 0.0 0.000000 18 2 2 1 1 1 total 0.0 0.000000 19 2 2 1 2 1 total 0.0 0.000000 20 2 2 1 3 1 total 1.0 1.414214 @@ -238,18 +238,18 @@ 3 1 1 1 4 1 total 0.002629 0.000950 4 1 1 1 5 1 total 0.001125 0.000398 5 1 1 1 6 1 total 0.000470 0.000166 -6 1 2 1 1 1 total 0.000228 0.000057 -7 1 2 1 2 1 total 0.001222 0.000309 -8 1 2 1 3 1 total 0.001193 0.000304 -9 1 2 1 4 1 total 0.002780 0.000713 -10 1 2 1 5 1 total 0.001250 0.000328 -11 1 2 1 6 1 total 0.000520 0.000136 -12 2 1 1 1 1 total 0.000225 0.000044 -13 2 1 1 2 1 total 0.001232 0.000242 -14 2 1 1 3 1 total 0.001216 0.000239 -15 2 1 1 4 1 total 0.002882 0.000570 -16 2 1 1 5 1 total 0.001345 0.000270 -17 2 1 1 6 1 total 0.000558 0.000112 +12 1 2 1 1 1 total 0.000225 0.000044 +13 1 2 1 2 1 total 0.001232 0.000242 +14 1 2 1 3 1 total 0.001216 0.000239 +15 1 2 1 4 1 total 0.002882 0.000570 +16 1 2 1 5 1 total 0.001345 0.000270 +17 1 2 1 6 1 total 0.000558 0.000112 +6 2 1 1 1 1 total 0.000228 0.000057 +7 2 1 1 2 1 total 0.001222 0.000309 +8 2 1 1 3 1 total 0.001193 0.000304 +9 2 1 1 4 1 total 0.002780 0.000713 +10 2 1 1 5 1 total 0.001250 0.000328 +11 2 1 1 6 1 total 0.000520 0.000136 18 2 2 1 1 1 total 0.000227 0.000027 19 2 2 1 2 1 total 0.001225 0.000143 20 2 2 1 3 1 total 0.001201 0.000140 @@ -264,18 +264,18 @@ 3 1 1 1 4 1 total 0.304289 0.106753 4 1 1 1 5 1 total 0.855760 0.286466 5 1 1 1 6 1 total 2.874120 0.965609 -6 1 2 1 1 1 total 0.013357 0.003345 -7 1 2 1 2 1 total 0.032590 0.008273 -8 1 2 1 3 1 total 0.121103 0.031074 -9 1 2 1 4 1 total 0.306111 0.080011 -10 1 2 1 5 1 total 0.862660 0.235694 -11 1 2 1 6 1 total 2.897534 0.788926 -12 2 1 1 1 1 total 0.013367 0.002548 -13 2 1 1 2 1 total 0.032520 0.006266 -14 2 1 1 3 1 total 0.121250 0.023544 -15 2 1 1 4 1 total 0.307552 0.060464 -16 2 1 1 5 1 total 0.867665 0.175131 -17 2 1 1 6 1 total 2.914635 0.587161 +12 1 2 1 1 1 total 0.013367 0.002548 +13 1 2 1 2 1 total 0.032520 0.006266 +14 1 2 1 3 1 total 0.121250 0.023544 +15 1 2 1 4 1 total 0.307552 0.060464 +16 1 2 1 5 1 total 0.867665 0.175131 +17 1 2 1 6 1 total 2.914635 0.587161 +6 2 1 1 1 1 total 0.013357 0.003345 +7 2 1 1 2 1 total 0.032590 0.008273 +8 2 1 1 3 1 total 0.121103 0.031074 +9 2 1 1 4 1 total 0.306111 0.080011 +10 2 1 1 5 1 total 0.862660 0.235694 +11 2 1 1 6 1 total 2.897534 0.788926 18 2 2 1 1 1 total 0.013360 0.001587 19 2 2 1 2 1 total 0.032564 0.003810 20 2 2 1 3 1 total 0.121158 0.014038 @@ -290,18 +290,18 @@ 3 1 1 1 4 1 1 total 0.00000 0.000000 4 1 1 1 5 1 1 total 0.00000 0.000000 5 1 1 1 6 1 1 total 0.00000 0.000000 -6 1 2 1 1 1 1 total 0.00000 0.000000 -7 1 2 1 2 1 1 total 0.00000 0.000000 -8 1 2 1 3 1 1 total 0.00000 0.000000 -9 1 2 1 4 1 1 total 0.00000 0.000000 -10 1 2 1 5 1 1 total 0.00000 0.000000 -11 1 2 1 6 1 1 total 0.00000 0.000000 -12 2 1 1 1 1 1 total 0.00000 0.000000 -13 2 1 1 2 1 1 total 0.00000 0.000000 -14 2 1 1 3 1 1 total 0.00000 0.000000 -15 2 1 1 4 1 1 total 0.00000 0.000000 -16 2 1 1 5 1 1 total 0.00000 0.000000 -17 2 1 1 6 1 1 total 0.00000 0.000000 +12 1 2 1 1 1 1 total 0.00000 0.000000 +13 1 2 1 2 1 1 total 0.00000 0.000000 +14 1 2 1 3 1 1 total 0.00000 0.000000 +15 1 2 1 4 1 1 total 0.00000 0.000000 +16 1 2 1 5 1 1 total 0.00000 0.000000 +17 1 2 1 6 1 1 total 0.00000 0.000000 +6 2 1 1 1 1 1 total 0.00000 0.000000 +7 2 1 1 2 1 1 total 0.00000 0.000000 +8 2 1 1 3 1 1 total 0.00000 0.000000 +9 2 1 1 4 1 1 total 0.00000 0.000000 +10 2 1 1 5 1 1 total 0.00000 0.000000 +11 2 1 1 6 1 1 total 0.00000 0.000000 18 2 2 1 1 1 1 total 0.00000 0.000000 19 2 2 1 2 1 1 total 0.00000 0.000000 20 2 2 1 3 1 1 total 0.00015 0.000151 diff --git a/tests/test_mgxs_library_mesh/test_mgxs_library_mesh.py b/tests/regression_tests/mgxs_library_mesh/test.py similarity index 86% rename from tests/test_mgxs_library_mesh/test_mgxs_library_mesh.py rename to tests/regression_tests/mgxs_library_mesh/test.py index e0a3307bc3..a9d24da934 100644 --- a/tests/test_mgxs_library_mesh/test_mgxs_library_mesh.py +++ b/tests/regression_tests/mgxs_library_mesh/test.py @@ -1,18 +1,14 @@ -#!/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 import openmc.mgxs +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a one-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 20.e6]) @@ -47,8 +43,7 @@ class MGXSTestHarness(PyAPITestHarness): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -70,6 +65,6 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_mesh(): harness = MGXSTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/mgxs_library_no_nuclides/__init__.py b/tests/regression_tests/mgxs_library_no_nuclides/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mgxs_library_hdf5/inputs_true.dat b/tests/regression_tests/mgxs_library_no_nuclides/inputs_true.dat similarity index 99% rename from tests/test_mgxs_library_hdf5/inputs_true.dat rename to tests/regression_tests/mgxs_library_no_nuclides/inputs_true.dat index d2f28d0fe0..ef6c4c5206 100644 --- a/tests/test_mgxs_library_hdf5/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_no_nuclides/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/test_mgxs_library_no_nuclides/results_true.dat b/tests/regression_tests/mgxs_library_no_nuclides/results_true.dat similarity index 100% rename from tests/test_mgxs_library_no_nuclides/results_true.dat rename to tests/regression_tests/mgxs_library_no_nuclides/results_true.dat diff --git a/tests/test_mgxs_library_no_nuclides/test_mgxs_library_no_nuclides.py b/tests/regression_tests/mgxs_library_no_nuclides/test.py similarity index 84% rename from tests/test_mgxs_library_no_nuclides/test_mgxs_library_no_nuclides.py rename to tests/regression_tests/mgxs_library_no_nuclides/test.py index 793cfc7146..506ac238fc 100644 --- a/tests/test_mgxs_library_no_nuclides/test_mgxs_library_no_nuclides.py +++ b/tests/regression_tests/mgxs_library_no_nuclides/test.py @@ -1,20 +1,16 @@ -#!/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 import openmc.mgxs from openmc.examples import pwr_pin_cell +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): # Generate inputs using parent class routine - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) @@ -39,8 +35,7 @@ class MGXSTestHarness(PyAPITestHarness): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -62,7 +57,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_no_nuclides(): model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) harness.main() diff --git a/tests/regression_tests/mgxs_library_nuclides/__init__.py b/tests/regression_tests/mgxs_library_nuclides/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_mgxs_library_nuclides/inputs_true.dat b/tests/regression_tests/mgxs_library_nuclides/inputs_true.dat similarity index 99% rename from tests/test_mgxs_library_nuclides/inputs_true.dat rename to tests/regression_tests/mgxs_library_nuclides/inputs_true.dat index 826eb5b623..b720bfcbba 100644 --- a/tests/test_mgxs_library_nuclides/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_nuclides/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/test_mgxs_library_nuclides/results_true.dat b/tests/regression_tests/mgxs_library_nuclides/results_true.dat similarity index 100% rename from tests/test_mgxs_library_nuclides/results_true.dat rename to tests/regression_tests/mgxs_library_nuclides/results_true.dat diff --git a/tests/test_mgxs_library_nuclides/test_mgxs_library_nuclides.py b/tests/regression_tests/mgxs_library_nuclides/test.py similarity index 83% rename from tests/test_mgxs_library_nuclides/test_mgxs_library_nuclides.py rename to tests/regression_tests/mgxs_library_nuclides/test.py index 9e54e1bb6b..c64c277098 100644 --- a/tests/test_mgxs_library_nuclides/test_mgxs_library_nuclides.py +++ b/tests/regression_tests/mgxs_library_nuclides/test.py @@ -1,19 +1,15 @@ -#!/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 import openmc.mgxs from openmc.examples import pwr_pin_cell +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) @@ -35,8 +31,7 @@ class MGXSTestHarness(PyAPITestHarness): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -58,7 +53,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_nuclides(): model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) harness.main() diff --git a/tests/regression_tests/multipole/__init__.py b/tests/regression_tests/multipole/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_multipole/inputs_true.dat b/tests/regression_tests/multipole/inputs_true.dat similarity index 97% rename from tests/test_multipole/inputs_true.dat rename to tests/regression_tests/multipole/inputs_true.dat index 0d1fe99bdc..d1ef3e00aa 100644 --- a/tests/test_multipole/inputs_true.dat +++ b/tests/regression_tests/multipole/inputs_true.dat @@ -27,7 +27,7 @@ - + diff --git a/tests/test_multipole/results_true.dat b/tests/regression_tests/multipole/results_true.dat similarity index 100% rename from tests/test_multipole/results_true.dat rename to tests/regression_tests/multipole/results_true.dat diff --git a/tests/test_multipole/test_multipole.py b/tests/regression_tests/multipole/test.py similarity index 81% rename from tests/test_multipole/test_multipole.py rename to tests/regression_tests/multipole/test.py index 294185312a..5c79d4d6b6 100644 --- a/tests/test_multipole/test_multipole.py +++ b/tests/regression_tests/multipole/test.py @@ -1,10 +1,10 @@ -#!/usr/bin/env python import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness, PyAPITestHarness + import openmc import openmc.model +import pytest + +from tests.testing_harness import TestHarness, PyAPITestHarness def make_model(): @@ -67,21 +67,17 @@ def make_model(): class MultipoleTestHarness(PyAPITestHarness): - def execute_test(self): - if not 'OPENMC_MULTIPOLE_LIBRARY' in os.environ: - raise RuntimeError("The 'OPENMC_MULTIPOLE_LIBRARY' environment " - "variable must be specified for this test.") - else: - super(MultipoleTestHarness, self).execute_test() - def _get_results(self): - outstr = super(MultipoleTestHarness, self)._get_results() + outstr = super()._get_results() su = openmc.Summary('summary.h5') outstr += str(su.geometry.get_all_cells()[11]) return outstr -if __name__ == '__main__': +@pytest.mark.skipif('OPENMC_MULTIPOLE_LIBRARY' not in os.environ, + reason='OPENMC_MULTIPOLE_LIBRARY environment variable ' + 'must be set') +def test_multipole(): model = make_model() harness = MultipoleTestHarness('statepoint.5.h5', model) harness.main() diff --git a/tests/regression_tests/output/__init__.py b/tests/regression_tests/output/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_output/geometry.xml b/tests/regression_tests/output/geometry.xml similarity index 100% rename from tests/test_output/geometry.xml rename to tests/regression_tests/output/geometry.xml diff --git a/tests/test_output/materials.xml b/tests/regression_tests/output/materials.xml similarity index 100% rename from tests/test_output/materials.xml rename to tests/regression_tests/output/materials.xml diff --git a/tests/test_output/results_true.dat b/tests/regression_tests/output/results_true.dat similarity index 100% rename from tests/test_output/results_true.dat rename to tests/regression_tests/output/results_true.dat diff --git a/tests/test_output/settings.xml b/tests/regression_tests/output/settings.xml similarity index 100% rename from tests/test_output/settings.xml rename to tests/regression_tests/output/settings.xml diff --git a/tests/test_output/test_output.py b/tests/regression_tests/output/test.py similarity index 64% rename from tests/test_output/test_output.py rename to tests/regression_tests/output/test.py index 475b3e9f02..d9568ba4b0 100644 --- a/tests/test_output/test_output.py +++ b/tests/regression_tests/output/test.py @@ -1,10 +1,7 @@ -#!/usr/bin/env python - -import glob import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness +import glob + +from tests.testing_harness import TestHarness class OutputTestHarness(TestHarness): @@ -21,13 +18,11 @@ class OutputTestHarness(TestHarness): def _cleanup(self): TestHarness._cleanup(self) - output = glob.glob(os.path.join(os.getcwd(), 'summary.*')) - output.append(os.path.join(os.getcwd(), 'cross_sections.out')) - for f in output: - if os.path.exists(f): - os.remove(f) + f = 'summary.h5' + if os.path.exists(f): + os.remove(f) -if __name__ == '__main__': +def test_output(): harness = OutputTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/particle_restart_eigval/__init__.py b/tests/regression_tests/particle_restart_eigval/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_particle_restart_eigval/geometry.xml b/tests/regression_tests/particle_restart_eigval/geometry.xml similarity index 100% rename from tests/test_particle_restart_eigval/geometry.xml rename to tests/regression_tests/particle_restart_eigval/geometry.xml diff --git a/tests/test_particle_restart_eigval/materials.xml b/tests/regression_tests/particle_restart_eigval/materials.xml similarity index 100% rename from tests/test_particle_restart_eigval/materials.xml rename to tests/regression_tests/particle_restart_eigval/materials.xml diff --git a/tests/test_particle_restart_eigval/results_true.dat b/tests/regression_tests/particle_restart_eigval/results_true.dat similarity index 100% rename from tests/test_particle_restart_eigval/results_true.dat rename to tests/regression_tests/particle_restart_eigval/results_true.dat diff --git a/tests/test_particle_restart_eigval/settings.xml b/tests/regression_tests/particle_restart_eigval/settings.xml similarity index 100% rename from tests/test_particle_restart_eigval/settings.xml rename to tests/regression_tests/particle_restart_eigval/settings.xml diff --git a/tests/regression_tests/particle_restart_eigval/test.py b/tests/regression_tests/particle_restart_eigval/test.py new file mode 100644 index 0000000000..a30eb97870 --- /dev/null +++ b/tests/regression_tests/particle_restart_eigval/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import ParticleRestartTestHarness + + +def test_particle_restart_eigval(): + harness = ParticleRestartTestHarness('particle_10_1030.h5') + harness.main() diff --git a/tests/regression_tests/particle_restart_fixed/__init__.py b/tests/regression_tests/particle_restart_fixed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_particle_restart_fixed/geometry.xml b/tests/regression_tests/particle_restart_fixed/geometry.xml similarity index 100% rename from tests/test_particle_restart_fixed/geometry.xml rename to tests/regression_tests/particle_restart_fixed/geometry.xml diff --git a/tests/test_particle_restart_fixed/materials.xml b/tests/regression_tests/particle_restart_fixed/materials.xml similarity index 100% rename from tests/test_particle_restart_fixed/materials.xml rename to tests/regression_tests/particle_restart_fixed/materials.xml diff --git a/tests/test_particle_restart_fixed/results_true.dat b/tests/regression_tests/particle_restart_fixed/results_true.dat similarity index 100% rename from tests/test_particle_restart_fixed/results_true.dat rename to tests/regression_tests/particle_restart_fixed/results_true.dat diff --git a/tests/test_particle_restart_fixed/settings.xml b/tests/regression_tests/particle_restart_fixed/settings.xml similarity index 100% rename from tests/test_particle_restart_fixed/settings.xml rename to tests/regression_tests/particle_restart_fixed/settings.xml diff --git a/tests/regression_tests/particle_restart_fixed/test.py b/tests/regression_tests/particle_restart_fixed/test.py new file mode 100644 index 0000000000..463568ecca --- /dev/null +++ b/tests/regression_tests/particle_restart_fixed/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import ParticleRestartTestHarness + + +def test_particle_restart_fixed(): + harness = ParticleRestartTestHarness('particle_7_144.h5') + harness.main() diff --git a/tests/regression_tests/periodic/__init__.py b/tests/regression_tests/periodic/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_periodic/inputs_true.dat b/tests/regression_tests/periodic/inputs_true.dat similarity index 97% rename from tests/test_periodic/inputs_true.dat rename to tests/regression_tests/periodic/inputs_true.dat index 61958701b2..6f613a1602 100644 --- a/tests/test_periodic/inputs_true.dat +++ b/tests/regression_tests/periodic/inputs_true.dat @@ -18,7 +18,7 @@ - + diff --git a/tests/test_periodic/results_true.dat b/tests/regression_tests/periodic/results_true.dat similarity index 100% rename from tests/test_periodic/results_true.dat rename to tests/regression_tests/periodic/results_true.dat diff --git a/tests/test_periodic/test_periodic.py b/tests/regression_tests/periodic/test.py similarity index 92% rename from tests/test_periodic/test_periodic.py rename to tests/regression_tests/periodic/test.py index 3883654c13..d746ebdd5f 100644 --- a/tests/test_periodic/test_periodic.py +++ b/tests/regression_tests/periodic/test.py @@ -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 PeriodicTest(PyAPITestHarness): def _build_inputs(self): @@ -55,6 +51,6 @@ class PeriodicTest(PyAPITestHarness): settings.export_to_xml() -if __name__ == '__main__': +def test_periodic(): harness = PeriodicTest('statepoint.4.h5') harness.main() diff --git a/tests/regression_tests/plot/__init__.py b/tests/regression_tests/plot/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_plot/geometry.xml b/tests/regression_tests/plot/geometry.xml similarity index 100% rename from tests/test_plot/geometry.xml rename to tests/regression_tests/plot/geometry.xml diff --git a/tests/test_plot/materials.xml b/tests/regression_tests/plot/materials.xml similarity index 100% rename from tests/test_plot/materials.xml rename to tests/regression_tests/plot/materials.xml diff --git a/tests/test_plot/plots.xml b/tests/regression_tests/plot/plots.xml similarity index 100% rename from tests/test_plot/plots.xml rename to tests/regression_tests/plot/plots.xml diff --git a/tests/test_plot/results_true.dat b/tests/regression_tests/plot/results_true.dat similarity index 100% rename from tests/test_plot/results_true.dat rename to tests/regression_tests/plot/results_true.dat diff --git a/tests/test_plot/settings.xml b/tests/regression_tests/plot/settings.xml similarity index 100% rename from tests/test_plot/settings.xml rename to tests/regression_tests/plot/settings.xml diff --git a/tests/test_plot/test_plot.py b/tests/regression_tests/plot/test.py similarity index 71% rename from tests/test_plot/test_plot.py rename to tests/regression_tests/plot/test.py index d484925cb4..bfaef019c1 100644 --- a/tests/test_plot/test_plot.py +++ b/tests/regression_tests/plot/test.py @@ -1,39 +1,33 @@ -#!/usr/bin/env python - import glob import hashlib import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness import h5py - import openmc +from tests.testing_harness import TestHarness +from tests.regression_tests import config + class PlotTestHarness(TestHarness): """Specialized TestHarness for running OpenMC plotting tests.""" def __init__(self, plot_names): - super(PlotTestHarness, self).__init__(None) + super().__init__(None) self._plot_names = plot_names def _run_openmc(self): - returncode = openmc.plot_geometry(openmc_exec=self._opts.exe) - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.plot_geometry(openmc_exec=config['exe']) def _test_output_created(self): """Make sure *.ppm has been created.""" for fname in self._plot_names: - assert os.path.exists(os.path.join(os.getcwd(), fname)), \ - 'Plot output file does not exist.' + assert os.path.exists(fname), 'Plot output file does not exist.' def _cleanup(self): - super(PlotTestHarness, self)._cleanup() + super()._cleanup() for fname in self._plot_names: - path = os.path.join(os.getcwd(), fname) - if os.path.exists(path): - os.remove(path) + if os.path.exists(fname): + os.remove(fname) def _get_results(self): """Return a string hash of the plot files.""" @@ -61,7 +55,7 @@ class PlotTestHarness(TestHarness): return outstr -if __name__ == '__main__': +def test_plot(): harness = PlotTestHarness(('plot_1.ppm', 'plot_2.ppm', 'plot_3.ppm', 'plot_4.h5')) harness.main() diff --git a/tests/regression_tests/ptables_off/__init__.py b/tests/regression_tests/ptables_off/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_ptables_off/geometry.xml b/tests/regression_tests/ptables_off/geometry.xml similarity index 100% rename from tests/test_ptables_off/geometry.xml rename to tests/regression_tests/ptables_off/geometry.xml diff --git a/tests/test_ptables_off/materials.xml b/tests/regression_tests/ptables_off/materials.xml similarity index 100% rename from tests/test_ptables_off/materials.xml rename to tests/regression_tests/ptables_off/materials.xml diff --git a/tests/test_ptables_off/results_true.dat b/tests/regression_tests/ptables_off/results_true.dat similarity index 100% rename from tests/test_ptables_off/results_true.dat rename to tests/regression_tests/ptables_off/results_true.dat diff --git a/tests/test_ptables_off/settings.xml b/tests/regression_tests/ptables_off/settings.xml similarity index 100% rename from tests/test_ptables_off/settings.xml rename to tests/regression_tests/ptables_off/settings.xml diff --git a/tests/regression_tests/ptables_off/test.py b/tests/regression_tests/ptables_off/test.py new file mode 100644 index 0000000000..cc316f8c3e --- /dev/null +++ b/tests/regression_tests/ptables_off/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_ptables_off(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/quadric_surfaces/__init__.py b/tests/regression_tests/quadric_surfaces/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_quadric_surfaces/geometry.xml b/tests/regression_tests/quadric_surfaces/geometry.xml similarity index 100% rename from tests/test_quadric_surfaces/geometry.xml rename to tests/regression_tests/quadric_surfaces/geometry.xml diff --git a/tests/test_quadric_surfaces/materials.xml b/tests/regression_tests/quadric_surfaces/materials.xml similarity index 100% rename from tests/test_quadric_surfaces/materials.xml rename to tests/regression_tests/quadric_surfaces/materials.xml diff --git a/tests/test_quadric_surfaces/results_true.dat b/tests/regression_tests/quadric_surfaces/results_true.dat similarity index 100% rename from tests/test_quadric_surfaces/results_true.dat rename to tests/regression_tests/quadric_surfaces/results_true.dat diff --git a/tests/test_quadric_surfaces/settings.xml b/tests/regression_tests/quadric_surfaces/settings.xml similarity index 100% rename from tests/test_quadric_surfaces/settings.xml rename to tests/regression_tests/quadric_surfaces/settings.xml diff --git a/tests/regression_tests/quadric_surfaces/test.py b/tests/regression_tests/quadric_surfaces/test.py new file mode 100755 index 0000000000..862ee9bf41 --- /dev/null +++ b/tests/regression_tests/quadric_surfaces/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_quadric_surfaces(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/reflective_plane/__init__.py b/tests/regression_tests/reflective_plane/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_reflective_plane/geometry.xml b/tests/regression_tests/reflective_plane/geometry.xml similarity index 100% rename from tests/test_reflective_plane/geometry.xml rename to tests/regression_tests/reflective_plane/geometry.xml diff --git a/tests/test_reflective_plane/materials.xml b/tests/regression_tests/reflective_plane/materials.xml similarity index 100% rename from tests/test_reflective_plane/materials.xml rename to tests/regression_tests/reflective_plane/materials.xml diff --git a/tests/test_reflective_plane/results_true.dat b/tests/regression_tests/reflective_plane/results_true.dat similarity index 100% rename from tests/test_reflective_plane/results_true.dat rename to tests/regression_tests/reflective_plane/results_true.dat diff --git a/tests/test_reflective_plane/settings.xml b/tests/regression_tests/reflective_plane/settings.xml similarity index 100% rename from tests/test_reflective_plane/settings.xml rename to tests/regression_tests/reflective_plane/settings.xml diff --git a/tests/regression_tests/reflective_plane/test.py b/tests/regression_tests/reflective_plane/test.py new file mode 100644 index 0000000000..906174f338 --- /dev/null +++ b/tests/regression_tests/reflective_plane/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_reflective_plane(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/resonance_scattering/__init__.py b/tests/regression_tests/resonance_scattering/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_resonance_scattering/inputs_true.dat b/tests/regression_tests/resonance_scattering/inputs_true.dat similarity index 96% rename from tests/test_resonance_scattering/inputs_true.dat rename to tests/regression_tests/resonance_scattering/inputs_true.dat index 70fe165fd5..2301ccf762 100644 --- a/tests/test_resonance_scattering/inputs_true.dat +++ b/tests/regression_tests/resonance_scattering/inputs_true.dat @@ -5,7 +5,7 @@ - + diff --git a/tests/test_resonance_scattering/results_true.dat b/tests/regression_tests/resonance_scattering/results_true.dat similarity index 100% rename from tests/test_resonance_scattering/results_true.dat rename to tests/regression_tests/resonance_scattering/results_true.dat diff --git a/tests/test_resonance_scattering/test_resonance_scattering.py b/tests/regression_tests/resonance_scattering/test.py similarity index 90% rename from tests/test_resonance_scattering/test_resonance_scattering.py rename to tests/regression_tests/resonance_scattering/test.py index 94c9f5c3de..15e9d68944 100644 --- a/tests/test_resonance_scattering/test_resonance_scattering.py +++ b/tests/regression_tests/resonance_scattering/test.py @@ -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 ResonanceScatteringTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -46,6 +42,6 @@ class ResonanceScatteringTestHarness(PyAPITestHarness): settings.export_to_xml() -if __name__ == '__main__': +def test_resonance_scattering(): harness = ResonanceScatteringTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/rotation/__init__.py b/tests/regression_tests/rotation/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_rotation/geometry.xml b/tests/regression_tests/rotation/geometry.xml similarity index 100% rename from tests/test_rotation/geometry.xml rename to tests/regression_tests/rotation/geometry.xml diff --git a/tests/test_rotation/materials.xml b/tests/regression_tests/rotation/materials.xml similarity index 100% rename from tests/test_rotation/materials.xml rename to tests/regression_tests/rotation/materials.xml diff --git a/tests/test_rotation/results_true.dat b/tests/regression_tests/rotation/results_true.dat similarity index 100% rename from tests/test_rotation/results_true.dat rename to tests/regression_tests/rotation/results_true.dat diff --git a/tests/test_rotation/settings.xml b/tests/regression_tests/rotation/settings.xml similarity index 100% rename from tests/test_rotation/settings.xml rename to tests/regression_tests/rotation/settings.xml diff --git a/tests/regression_tests/rotation/test.py b/tests/regression_tests/rotation/test.py new file mode 100644 index 0000000000..31c3d8d655 --- /dev/null +++ b/tests/regression_tests/rotation/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_rotation(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/salphabeta/__init__.py b/tests/regression_tests/salphabeta/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_salphabeta/inputs_true.dat b/tests/regression_tests/salphabeta/inputs_true.dat similarity index 92% rename from tests/test_salphabeta/inputs_true.dat rename to tests/regression_tests/salphabeta/inputs_true.dat index 02e6813f02..ede96d3769 100644 --- a/tests/test_salphabeta/inputs_true.dat +++ b/tests/regression_tests/salphabeta/inputs_true.dat @@ -12,19 +12,19 @@ - + - + - + @@ -32,7 +32,7 @@ - + diff --git a/tests/test_salphabeta/results_true.dat b/tests/regression_tests/salphabeta/results_true.dat similarity index 100% rename from tests/test_salphabeta/results_true.dat rename to tests/regression_tests/salphabeta/results_true.dat diff --git a/tests/test_salphabeta/test_salphabeta.py b/tests/regression_tests/salphabeta/test.py similarity index 93% rename from tests/test_salphabeta/test_salphabeta.py rename to tests/regression_tests/salphabeta/test.py index 600c703324..e69ada5ba3 100644 --- a/tests/test_salphabeta/test_salphabeta.py +++ b/tests/regression_tests/salphabeta/test.py @@ -1,13 +1,8 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) - -from testing_harness import PyAPITestHarness import openmc import openmc.model +from tests.testing_harness import PyAPITestHarness + def make_model(): model = openmc.model.Model() @@ -78,7 +73,7 @@ def make_model(): return model -if __name__ == '__main__': +def test_salphabeta(): model = make_model() harness = PyAPITestHarness('statepoint.5.h5', model) harness.main() diff --git a/tests/regression_tests/score_current/__init__.py b/tests/regression_tests/score_current/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_score_current/geometry.xml b/tests/regression_tests/score_current/geometry.xml similarity index 100% rename from tests/test_score_current/geometry.xml rename to tests/regression_tests/score_current/geometry.xml diff --git a/tests/test_score_current/materials.xml b/tests/regression_tests/score_current/materials.xml similarity index 100% rename from tests/test_score_current/materials.xml rename to tests/regression_tests/score_current/materials.xml diff --git a/tests/regression_tests/score_current/results_true.dat b/tests/regression_tests/score_current/results_true.dat new file mode 100644 index 0000000000..dedc473de9 --- /dev/null +++ b/tests/regression_tests/score_current/results_true.dat @@ -0,0 +1 @@ +138b312cdaa822c9b62f757b3259522004b679c4ed289a92798b29a6442c26d12c53256635be273f13e3703816ff50a1b9f52d79770eade01e482384ac0d389f \ No newline at end of file diff --git a/tests/test_score_current/settings.xml b/tests/regression_tests/score_current/settings.xml similarity index 100% rename from tests/test_score_current/settings.xml rename to tests/regression_tests/score_current/settings.xml diff --git a/tests/test_score_current/tallies.xml b/tests/regression_tests/score_current/tallies.xml similarity index 94% rename from tests/test_score_current/tallies.xml rename to tests/regression_tests/score_current/tallies.xml index 3b8f60adba..a381e4c2e2 100644 --- a/tests/test_score_current/tallies.xml +++ b/tests/regression_tests/score_current/tallies.xml @@ -9,7 +9,7 @@ - mesh + meshsurface 1 diff --git a/tests/regression_tests/score_current/test.py b/tests/regression_tests/score_current/test.py new file mode 100644 index 0000000000..21c5d08812 --- /dev/null +++ b/tests/regression_tests/score_current/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import HashedTestHarness + + +def test_score_current(): + harness = HashedTestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/seed/__init__.py b/tests/regression_tests/seed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_seed/geometry.xml b/tests/regression_tests/seed/geometry.xml similarity index 100% rename from tests/test_seed/geometry.xml rename to tests/regression_tests/seed/geometry.xml diff --git a/tests/test_seed/materials.xml b/tests/regression_tests/seed/materials.xml similarity index 100% rename from tests/test_seed/materials.xml rename to tests/regression_tests/seed/materials.xml diff --git a/tests/test_seed/results_true.dat b/tests/regression_tests/seed/results_true.dat similarity index 100% rename from tests/test_seed/results_true.dat rename to tests/regression_tests/seed/results_true.dat diff --git a/tests/test_seed/settings.xml b/tests/regression_tests/seed/settings.xml similarity index 100% rename from tests/test_seed/settings.xml rename to tests/regression_tests/seed/settings.xml diff --git a/tests/regression_tests/seed/test.py b/tests/regression_tests/seed/test.py new file mode 100644 index 0000000000..8b2f031b3e --- /dev/null +++ b/tests/regression_tests/seed/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_seed(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/source/__init__.py b/tests/regression_tests/source/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_source/inputs_true.dat b/tests/regression_tests/source/inputs_true.dat similarity index 98% rename from tests/test_source/inputs_true.dat rename to tests/regression_tests/source/inputs_true.dat index da230e0e50..6dd913edc0 100644 --- a/tests/test_source/inputs_true.dat +++ b/tests/regression_tests/source/inputs_true.dat @@ -5,7 +5,7 @@ - + 294 diff --git a/tests/test_source/results_true.dat b/tests/regression_tests/source/results_true.dat similarity index 100% rename from tests/test_source/results_true.dat rename to tests/regression_tests/source/results_true.dat diff --git a/tests/test_source/test_source.py b/tests/regression_tests/source/test.py similarity index 94% rename from tests/test_source/test_source.py rename to tests/regression_tests/source/test.py index a872ab4816..00171a2551 100644 --- a/tests/test_source/test_source.py +++ b/tests/regression_tests/source/test.py @@ -1,15 +1,10 @@ -#!/usr/bin/env python - from math import pi -import os -import sys import numpy as np - -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + class SourceTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -63,6 +58,6 @@ class SourceTestHarness(PyAPITestHarness): settings.export_to_xml() -if __name__ == '__main__': +def test_source(): harness = SourceTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/source_file/__init__.py b/tests/regression_tests/source_file/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_source_file/geometry.xml b/tests/regression_tests/source_file/geometry.xml similarity index 100% rename from tests/test_source_file/geometry.xml rename to tests/regression_tests/source_file/geometry.xml diff --git a/tests/test_source_file/materials.xml b/tests/regression_tests/source_file/materials.xml similarity index 100% rename from tests/test_source_file/materials.xml rename to tests/regression_tests/source_file/materials.xml diff --git a/tests/test_source_file/results_true.dat b/tests/regression_tests/source_file/results_true.dat similarity index 100% rename from tests/test_source_file/results_true.dat rename to tests/regression_tests/source_file/results_true.dat diff --git a/tests/test_source_file/settings.xml b/tests/regression_tests/source_file/settings.xml similarity index 100% rename from tests/test_source_file/settings.xml rename to tests/regression_tests/source_file/settings.xml diff --git a/tests/test_source_file/test_source_file.py b/tests/regression_tests/source_file/test.py similarity index 96% rename from tests/test_source_file/test_source_file.py rename to tests/regression_tests/source_file/test.py index 5631814b4c..b4d9c4a31d 100644 --- a/tests/test_source_file/test_source_file.py +++ b/tests/regression_tests/source_file/test.py @@ -2,9 +2,8 @@ import glob import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import * + +from tests.testing_harness import * settings1=""" @@ -97,6 +96,6 @@ class SourceFileTestHarness(TestHarness): fh.write(settings1) -if __name__ == '__main__': +def test_source_file(): harness = SourceFileTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/sourcepoint_batch/__init__.py b/tests/regression_tests/sourcepoint_batch/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_sourcepoint_batch/geometry.xml b/tests/regression_tests/sourcepoint_batch/geometry.xml similarity index 100% rename from tests/test_sourcepoint_batch/geometry.xml rename to tests/regression_tests/sourcepoint_batch/geometry.xml diff --git a/tests/test_sourcepoint_batch/materials.xml b/tests/regression_tests/sourcepoint_batch/materials.xml similarity index 100% rename from tests/test_sourcepoint_batch/materials.xml rename to tests/regression_tests/sourcepoint_batch/materials.xml diff --git a/tests/test_sourcepoint_batch/results_true.dat b/tests/regression_tests/sourcepoint_batch/results_true.dat similarity index 100% rename from tests/test_sourcepoint_batch/results_true.dat rename to tests/regression_tests/sourcepoint_batch/results_true.dat diff --git a/tests/test_sourcepoint_batch/settings.xml b/tests/regression_tests/sourcepoint_batch/settings.xml similarity index 100% rename from tests/test_sourcepoint_batch/settings.xml rename to tests/regression_tests/sourcepoint_batch/settings.xml diff --git a/tests/test_sourcepoint_batch/test_sourcepoint_batch.py b/tests/regression_tests/sourcepoint_batch/test.py similarity index 52% rename from tests/test_sourcepoint_batch/test_sourcepoint_batch.py rename to tests/regression_tests/sourcepoint_batch/test.py index d5ea0e48b2..3086b5610d 100644 --- a/tests/test_sourcepoint_batch/test_sourcepoint_batch.py +++ b/tests/regression_tests/sourcepoint_batch/test.py @@ -1,20 +1,15 @@ -#!/usr/bin/env python - import glob -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness + from openmc import StatePoint +from tests.testing_harness import TestHarness + class SourcepointTestHarness(TestHarness): def _test_output_created(self): - """Make sure statepoint.* files have been created.""" - statepoint = glob.glob(os.path.join(os.getcwd(), 'statepoint.*')) - assert len(statepoint) == 5, '5 statepoint files must exist.' - assert statepoint[0].endswith('h5'), \ - 'Statepoint file is not a HDF5 file.' + """Make sure statepoint files have been created.""" + statepoint = glob.glob('statepoint.*.h5') + assert len(statepoint) == 5, 'Five statepoint files must exist.' def _get_results(self): """Digest info in the statepoint and return as a string.""" @@ -22,8 +17,7 @@ class SourcepointTestHarness(TestHarness): outstr = TestHarness._get_results(self) # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - with StatePoint(statepoint) as sp: + with StatePoint(self._sp_name) as sp: # Add the source information. xyz = sp.source[0]['xyz'] outstr += ' '.join(['{0:12.6E}'.format(x) for x in xyz]) @@ -32,6 +26,6 @@ class SourcepointTestHarness(TestHarness): return outstr -if __name__ == '__main__': +def test_sourcepoint_batch(): harness = SourcepointTestHarness('statepoint.08.h5') harness.main() diff --git a/tests/regression_tests/sourcepoint_latest/__init__.py b/tests/regression_tests/sourcepoint_latest/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_sourcepoint_latest/geometry.xml b/tests/regression_tests/sourcepoint_latest/geometry.xml similarity index 100% rename from tests/test_sourcepoint_latest/geometry.xml rename to tests/regression_tests/sourcepoint_latest/geometry.xml diff --git a/tests/test_sourcepoint_latest/materials.xml b/tests/regression_tests/sourcepoint_latest/materials.xml similarity index 100% rename from tests/test_sourcepoint_latest/materials.xml rename to tests/regression_tests/sourcepoint_latest/materials.xml diff --git a/tests/test_sourcepoint_latest/results_true.dat b/tests/regression_tests/sourcepoint_latest/results_true.dat similarity index 100% rename from tests/test_sourcepoint_latest/results_true.dat rename to tests/regression_tests/sourcepoint_latest/results_true.dat diff --git a/tests/test_sourcepoint_latest/settings.xml b/tests/regression_tests/sourcepoint_latest/settings.xml similarity index 100% rename from tests/test_sourcepoint_latest/settings.xml rename to tests/regression_tests/sourcepoint_latest/settings.xml diff --git a/tests/test_sourcepoint_latest/test_sourcepoint_latest.py b/tests/regression_tests/sourcepoint_latest/test.py similarity index 58% rename from tests/test_sourcepoint_latest/test_sourcepoint_latest.py rename to tests/regression_tests/sourcepoint_latest/test.py index c64cc20cc7..d14b566ad8 100644 --- a/tests/test_sourcepoint_latest/test_sourcepoint_latest.py +++ b/tests/regression_tests/sourcepoint_latest/test.py @@ -1,22 +1,18 @@ -#!/usr/bin/env python - import os import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness + +from tests.testing_harness import TestHarness class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) - source = glob.glob(os.path.join(os.getcwd(), 'source.*')) + source = glob.glob(os.path.join(os.getcwd(), 'source.*.h5')) assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' - assert source[0].endswith('h5'), \ - 'Source file is not a HDF5 file.' -if __name__ == '__main__': +def test_sourcepoint_latest(): harness = TestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/sourcepoint_restart/__init__.py b/tests/regression_tests/sourcepoint_restart/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_sourcepoint_restart/geometry.xml b/tests/regression_tests/sourcepoint_restart/geometry.xml similarity index 100% rename from tests/test_sourcepoint_restart/geometry.xml rename to tests/regression_tests/sourcepoint_restart/geometry.xml diff --git a/tests/test_sourcepoint_restart/materials.xml b/tests/regression_tests/sourcepoint_restart/materials.xml similarity index 100% rename from tests/test_sourcepoint_restart/materials.xml rename to tests/regression_tests/sourcepoint_restart/materials.xml diff --git a/tests/test_sourcepoint_restart/results_true.dat b/tests/regression_tests/sourcepoint_restart/results_true.dat similarity index 100% rename from tests/test_sourcepoint_restart/results_true.dat rename to tests/regression_tests/sourcepoint_restart/results_true.dat diff --git a/tests/test_sourcepoint_restart/settings.xml b/tests/regression_tests/sourcepoint_restart/settings.xml similarity index 100% rename from tests/test_sourcepoint_restart/settings.xml rename to tests/regression_tests/sourcepoint_restart/settings.xml diff --git a/tests/test_sourcepoint_restart/tallies.xml b/tests/regression_tests/sourcepoint_restart/tallies.xml similarity index 100% rename from tests/test_sourcepoint_restart/tallies.xml rename to tests/regression_tests/sourcepoint_restart/tallies.xml diff --git a/tests/regression_tests/sourcepoint_restart/test.py b/tests/regression_tests/sourcepoint_restart/test.py new file mode 100644 index 0000000000..32f53ec238 --- /dev/null +++ b/tests/regression_tests/sourcepoint_restart/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_sourcepoint_restart(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/statepoint_batch/__init__.py b/tests/regression_tests/statepoint_batch/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_statepoint_batch/geometry.xml b/tests/regression_tests/statepoint_batch/geometry.xml similarity index 100% rename from tests/test_statepoint_batch/geometry.xml rename to tests/regression_tests/statepoint_batch/geometry.xml diff --git a/tests/test_statepoint_batch/materials.xml b/tests/regression_tests/statepoint_batch/materials.xml similarity index 100% rename from tests/test_statepoint_batch/materials.xml rename to tests/regression_tests/statepoint_batch/materials.xml diff --git a/tests/test_statepoint_batch/results_true.dat b/tests/regression_tests/statepoint_batch/results_true.dat similarity index 100% rename from tests/test_statepoint_batch/results_true.dat rename to tests/regression_tests/statepoint_batch/results_true.dat diff --git a/tests/test_statepoint_batch/settings.xml b/tests/regression_tests/statepoint_batch/settings.xml similarity index 100% rename from tests/test_statepoint_batch/settings.xml rename to tests/regression_tests/statepoint_batch/settings.xml diff --git a/tests/test_statepoint_batch/test_statepoint_batch.py b/tests/regression_tests/statepoint_batch/test.py similarity index 66% rename from tests/test_statepoint_batch/test_statepoint_batch.py rename to tests/regression_tests/statepoint_batch/test.py index e3e2391ba1..323b28fc65 100644 --- a/tests/test_statepoint_batch/test_statepoint_batch.py +++ b/tests/regression_tests/statepoint_batch/test.py @@ -1,14 +1,9 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness class StatepointTestHarness(TestHarness): def __init__(self): - super(StatepointTestHarness, self).__init__(None) + super().__init__(None) def _test_output_created(self): """Make sure statepoint files have been created.""" @@ -18,6 +13,6 @@ class StatepointTestHarness(TestHarness): TestHarness._test_output_created(self) -if __name__ == '__main__': +def test_statepoint_batch(): harness = StatepointTestHarness() harness.main() diff --git a/tests/regression_tests/statepoint_restart/__init__.py b/tests/regression_tests/statepoint_restart/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_statepoint_restart/geometry.xml b/tests/regression_tests/statepoint_restart/geometry.xml similarity index 100% rename from tests/test_statepoint_restart/geometry.xml rename to tests/regression_tests/statepoint_restart/geometry.xml diff --git a/tests/test_statepoint_restart/materials.xml b/tests/regression_tests/statepoint_restart/materials.xml similarity index 100% rename from tests/test_statepoint_restart/materials.xml rename to tests/regression_tests/statepoint_restart/materials.xml diff --git a/tests/test_statepoint_restart/results_true.dat b/tests/regression_tests/statepoint_restart/results_true.dat similarity index 100% rename from tests/test_statepoint_restart/results_true.dat rename to tests/regression_tests/statepoint_restart/results_true.dat diff --git a/tests/test_statepoint_restart/settings.xml b/tests/regression_tests/statepoint_restart/settings.xml similarity index 100% rename from tests/test_statepoint_restart/settings.xml rename to tests/regression_tests/statepoint_restart/settings.xml diff --git a/tests/test_statepoint_restart/tallies.xml b/tests/regression_tests/statepoint_restart/tallies.xml similarity index 100% rename from tests/test_statepoint_restart/tallies.xml rename to tests/regression_tests/statepoint_restart/tallies.xml diff --git a/tests/test_statepoint_restart/test_statepoint_restart.py b/tests/regression_tests/statepoint_restart/test.py similarity index 68% rename from tests/test_statepoint_restart/test_statepoint_restart.py rename to tests/regression_tests/statepoint_restart/test.py index 2c1c444958..4575607f7d 100644 --- a/tests/test_statepoint_restart/test_statepoint_restart.py +++ b/tests/regression_tests/statepoint_restart/test.py @@ -1,16 +1,15 @@ -#!/usr/bin/env python - import glob import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness + import openmc +from tests.testing_harness import TestHarness +from tests.regression_tests import config + class StatepointRestartTestHarness(TestHarness): def __init__(self, final_sp, restart_sp): - super(StatepointRestartTestHarness, self).__init__(final_sp) + super().__init__(final_sp) self._restart_sp = restart_sp def execute_test(self): @@ -48,19 +47,15 @@ class StatepointRestartTestHarness(TestHarness): statepoint = statepoint[0] # Run OpenMC - if self._opts.mpi_exec is not None: - mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - returncode = openmc.run(restart_file=statepoint, - openmc_exec=self._opts.exe, - mpi_args=mpi_args) + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(restart_file=statepoint, openmc_exec=config['exe'], + mpi_args=mpi_args) else: - returncode = openmc.run(openmc_exec=self._opts.exe, - restart_file=statepoint) - - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.run(openmc_exec=config['exe'], restart_file=statepoint) -if __name__ == '__main__': +def test_statepoint_restart(): harness = StatepointRestartTestHarness('statepoint.10.h5', 'statepoint.07.h5') harness.main() diff --git a/tests/regression_tests/statepoint_sourcesep/__init__.py b/tests/regression_tests/statepoint_sourcesep/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_statepoint_sourcesep/geometry.xml b/tests/regression_tests/statepoint_sourcesep/geometry.xml similarity index 100% rename from tests/test_statepoint_sourcesep/geometry.xml rename to tests/regression_tests/statepoint_sourcesep/geometry.xml diff --git a/tests/test_statepoint_sourcesep/materials.xml b/tests/regression_tests/statepoint_sourcesep/materials.xml similarity index 100% rename from tests/test_statepoint_sourcesep/materials.xml rename to tests/regression_tests/statepoint_sourcesep/materials.xml diff --git a/tests/test_statepoint_sourcesep/results_true.dat b/tests/regression_tests/statepoint_sourcesep/results_true.dat similarity index 100% rename from tests/test_statepoint_sourcesep/results_true.dat rename to tests/regression_tests/statepoint_sourcesep/results_true.dat diff --git a/tests/test_statepoint_sourcesep/settings.xml b/tests/regression_tests/statepoint_sourcesep/settings.xml similarity index 100% rename from tests/test_statepoint_sourcesep/settings.xml rename to tests/regression_tests/statepoint_sourcesep/settings.xml diff --git a/tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py b/tests/regression_tests/statepoint_sourcesep/test.py similarity index 60% rename from tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py rename to tests/regression_tests/statepoint_sourcesep/test.py index f4bdcfb7b3..3d63ca8ee5 100644 --- a/tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py +++ b/tests/regression_tests/statepoint_sourcesep/test.py @@ -1,30 +1,25 @@ -#!/usr/bin/env python - import glob import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness + +from tests.testing_harness import TestHarness class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) - source = glob.glob(os.path.join(os.getcwd(), 'source.*')) + source = glob.glob('source.*.h5') assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' - assert source[0].endswith('h5'), \ - 'Source file is not a HDF5 file.' def _cleanup(self): TestHarness._cleanup(self) - output = glob.glob(os.path.join(os.getcwd(), 'source.*')) + output = glob.glob('source.*.h5') for f in output: if os.path.exists(f): os.remove(f) -if __name__ == '__main__': +def test_statepoint_sourcesep(): harness = SourcepointTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/surface_tally/__init__.py b/tests/regression_tests/surface_tally/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_surface_tally/inputs_true.dat b/tests/regression_tests/surface_tally/inputs_true.dat similarity index 97% rename from tests/test_surface_tally/inputs_true.dat rename to tests/regression_tests/surface_tally/inputs_true.dat index e66d44273a..fc10110eee 100644 --- a/tests/test_surface_tally/inputs_true.dat +++ b/tests/regression_tests/surface_tally/inputs_true.dat @@ -11,7 +11,7 @@ - + diff --git a/tests/test_surface_tally/results_true.dat b/tests/regression_tests/surface_tally/results_true.dat similarity index 100% rename from tests/test_surface_tally/results_true.dat rename to tests/regression_tests/surface_tally/results_true.dat diff --git a/tests/test_surface_tally/test_surface_tally.py b/tests/regression_tests/surface_tally/test.py similarity index 98% rename from tests/test_surface_tally/test_surface_tally.py rename to tests/regression_tests/surface_tally/test.py index ae525a6838..6995b7780c 100644 --- a/tests/test_surface_tally/test_surface_tally.py +++ b/tests/regression_tests/surface_tally/test.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness import numpy as np import openmc import pandas as pd +from tests.testing_harness import PyAPITestHarness + class SurfaceTallyTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -178,6 +174,6 @@ class SurfaceTallyTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_surface_tally(): harness = SurfaceTallyTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/survival_biasing/__init__.py b/tests/regression_tests/survival_biasing/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_survival_biasing/geometry.xml b/tests/regression_tests/survival_biasing/geometry.xml similarity index 100% rename from tests/test_survival_biasing/geometry.xml rename to tests/regression_tests/survival_biasing/geometry.xml diff --git a/tests/test_survival_biasing/materials.xml b/tests/regression_tests/survival_biasing/materials.xml similarity index 100% rename from tests/test_survival_biasing/materials.xml rename to tests/regression_tests/survival_biasing/materials.xml diff --git a/tests/test_survival_biasing/results_true.dat b/tests/regression_tests/survival_biasing/results_true.dat similarity index 100% rename from tests/test_survival_biasing/results_true.dat rename to tests/regression_tests/survival_biasing/results_true.dat diff --git a/tests/test_survival_biasing/settings.xml b/tests/regression_tests/survival_biasing/settings.xml similarity index 100% rename from tests/test_survival_biasing/settings.xml rename to tests/regression_tests/survival_biasing/settings.xml diff --git a/tests/test_survival_biasing/tallies.xml b/tests/regression_tests/survival_biasing/tallies.xml similarity index 100% rename from tests/test_survival_biasing/tallies.xml rename to tests/regression_tests/survival_biasing/tallies.xml diff --git a/tests/regression_tests/survival_biasing/test.py b/tests/regression_tests/survival_biasing/test.py new file mode 100644 index 0000000000..39e6faed8e --- /dev/null +++ b/tests/regression_tests/survival_biasing/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_survival_biasing(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/tallies/__init__.py b/tests/regression_tests/tallies/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_tallies/inputs_true.dat b/tests/regression_tests/tallies/inputs_true.dat similarity index 99% rename from tests/test_tallies/inputs_true.dat rename to tests/regression_tests/tallies/inputs_true.dat index a85491e943..2c33a8fa0d 100644 --- a/tests/test_tallies/inputs_true.dat +++ b/tests/regression_tests/tallies/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/test_tallies/results_true.dat b/tests/regression_tests/tallies/results_true.dat similarity index 100% rename from tests/test_tallies/results_true.dat rename to tests/regression_tests/tallies/results_true.dat diff --git a/tests/test_tallies/test_tallies.py b/tests/regression_tests/tallies/test.py similarity index 97% rename from tests/test_tallies/test_tallies.py rename to tests/regression_tests/tallies/test.py index 577d2babc0..e3aebfd986 100644 --- a/tests/test_tallies/test_tallies.py +++ b/tests/regression_tests/tallies/test.py @@ -1,15 +1,10 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) - -from testing_harness import HashedPyAPITestHarness from openmc.filter import * from openmc import Mesh, Tally, Tallies +from tests.testing_harness import HashedPyAPITestHarness -if __name__ == '__main__': + +def test_tallies(): harness = HashedPyAPITestHarness('statepoint.5.h5') model = harness._model diff --git a/tests/regression_tests/tally_aggregation/__init__.py b/tests/regression_tests/tally_aggregation/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_tally_aggregation/inputs_true.dat b/tests/regression_tests/tally_aggregation/inputs_true.dat similarity index 99% rename from tests/test_tally_aggregation/inputs_true.dat rename to tests/regression_tests/tally_aggregation/inputs_true.dat index 7a8bf46133..86806572a0 100644 --- a/tests/test_tally_aggregation/inputs_true.dat +++ b/tests/regression_tests/tally_aggregation/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/test_tally_aggregation/results_true.dat b/tests/regression_tests/tally_aggregation/results_true.dat similarity index 100% rename from tests/test_tally_aggregation/results_true.dat rename to tests/regression_tests/tally_aggregation/results_true.dat diff --git a/tests/test_tally_aggregation/test_tally_aggregation.py b/tests/regression_tests/tally_aggregation/test.py similarity index 85% rename from tests/test_tally_aggregation/test_tally_aggregation.py rename to tests/regression_tests/tally_aggregation/test.py index cf291e0266..f7df543ded 100644 --- a/tests/test_tally_aggregation/test_tally_aggregation.py +++ b/tests/regression_tests/tally_aggregation/test.py @@ -1,17 +1,13 @@ -#!/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 TallyAggregationTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(TallyAggregationTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize the filters energy_filter = openmc.EnergyFilter([0.0, 0.253, 1.0e3, 1.0e6, 20.0e6]) @@ -28,8 +24,7 @@ class TallyAggregationTestHarness(PyAPITestHarness): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Extract the tally of interest tally = sp.get_tally(name='distribcell tally') @@ -66,6 +61,6 @@ class TallyAggregationTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_tally_aggregation(): harness = TallyAggregationTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/tally_arithmetic/__init__.py b/tests/regression_tests/tally_arithmetic/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_tally_arithmetic/inputs_true.dat b/tests/regression_tests/tally_arithmetic/inputs_true.dat similarity index 99% rename from tests/test_tally_arithmetic/inputs_true.dat rename to tests/regression_tests/tally_arithmetic/inputs_true.dat index 743ca3c582..3605005add 100644 --- a/tests/test_tally_arithmetic/inputs_true.dat +++ b/tests/regression_tests/tally_arithmetic/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/test_tally_arithmetic/results_true.dat b/tests/regression_tests/tally_arithmetic/results_true.dat similarity index 100% rename from tests/test_tally_arithmetic/results_true.dat rename to tests/regression_tests/tally_arithmetic/results_true.dat diff --git a/tests/test_tally_arithmetic/test_tally_arithmetic.py b/tests/regression_tests/tally_arithmetic/test.py similarity index 87% rename from tests/test_tally_arithmetic/test_tally_arithmetic.py rename to tests/regression_tests/tally_arithmetic/test.py index 593a0a2917..3adf0c5bef 100644 --- a/tests/test_tally_arithmetic/test_tally_arithmetic.py +++ b/tests/regression_tests/tally_arithmetic/test.py @@ -1,17 +1,13 @@ -#!/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 TallyArithmeticTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(TallyArithmeticTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize Mesh mesh = openmc.Mesh(mesh_id=1) @@ -43,8 +39,7 @@ class TallyArithmeticTestHarness(PyAPITestHarness): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Load the tallies tally_1 = sp.get_tally(name='tally 1') @@ -80,6 +75,6 @@ class TallyArithmeticTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_tally_arithmetic(): harness = TallyArithmeticTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/tally_assumesep/__init__.py b/tests/regression_tests/tally_assumesep/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_tally_assumesep/geometry.xml b/tests/regression_tests/tally_assumesep/geometry.xml similarity index 100% rename from tests/test_tally_assumesep/geometry.xml rename to tests/regression_tests/tally_assumesep/geometry.xml diff --git a/tests/test_tally_assumesep/materials.xml b/tests/regression_tests/tally_assumesep/materials.xml similarity index 100% rename from tests/test_tally_assumesep/materials.xml rename to tests/regression_tests/tally_assumesep/materials.xml diff --git a/tests/test_tally_assumesep/results_true.dat b/tests/regression_tests/tally_assumesep/results_true.dat similarity index 100% rename from tests/test_tally_assumesep/results_true.dat rename to tests/regression_tests/tally_assumesep/results_true.dat diff --git a/tests/test_tally_assumesep/settings.xml b/tests/regression_tests/tally_assumesep/settings.xml similarity index 100% rename from tests/test_tally_assumesep/settings.xml rename to tests/regression_tests/tally_assumesep/settings.xml diff --git a/tests/test_tally_assumesep/tallies.xml b/tests/regression_tests/tally_assumesep/tallies.xml similarity index 100% rename from tests/test_tally_assumesep/tallies.xml rename to tests/regression_tests/tally_assumesep/tallies.xml diff --git a/tests/regression_tests/tally_assumesep/test.py b/tests/regression_tests/tally_assumesep/test.py new file mode 100644 index 0000000000..64595ced22 --- /dev/null +++ b/tests/regression_tests/tally_assumesep/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_tally_assumesep(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/tally_nuclides/__init__.py b/tests/regression_tests/tally_nuclides/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_tally_nuclides/geometry.xml b/tests/regression_tests/tally_nuclides/geometry.xml similarity index 100% rename from tests/test_tally_nuclides/geometry.xml rename to tests/regression_tests/tally_nuclides/geometry.xml diff --git a/tests/test_tally_nuclides/materials.xml b/tests/regression_tests/tally_nuclides/materials.xml similarity index 100% rename from tests/test_tally_nuclides/materials.xml rename to tests/regression_tests/tally_nuclides/materials.xml diff --git a/tests/test_tally_nuclides/results_true.dat b/tests/regression_tests/tally_nuclides/results_true.dat similarity index 100% rename from tests/test_tally_nuclides/results_true.dat rename to tests/regression_tests/tally_nuclides/results_true.dat diff --git a/tests/test_tally_nuclides/settings.xml b/tests/regression_tests/tally_nuclides/settings.xml similarity index 100% rename from tests/test_tally_nuclides/settings.xml rename to tests/regression_tests/tally_nuclides/settings.xml diff --git a/tests/test_tally_nuclides/tallies.xml b/tests/regression_tests/tally_nuclides/tallies.xml similarity index 100% rename from tests/test_tally_nuclides/tallies.xml rename to tests/regression_tests/tally_nuclides/tallies.xml diff --git a/tests/regression_tests/tally_nuclides/test.py b/tests/regression_tests/tally_nuclides/test.py new file mode 100644 index 0000000000..ee1f4b600e --- /dev/null +++ b/tests/regression_tests/tally_nuclides/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_tally_nuclides(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/tally_slice_merge/__init__.py b/tests/regression_tests/tally_slice_merge/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_tally_slice_merge/inputs_true.dat b/tests/regression_tests/tally_slice_merge/inputs_true.dat similarity index 99% rename from tests/test_tally_slice_merge/inputs_true.dat rename to tests/regression_tests/tally_slice_merge/inputs_true.dat index b1c089c965..ccd3655f9e 100644 --- a/tests/test_tally_slice_merge/inputs_true.dat +++ b/tests/regression_tests/tally_slice_merge/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/test_tally_slice_merge/results_true.dat b/tests/regression_tests/tally_slice_merge/results_true.dat similarity index 76% rename from tests/test_tally_slice_merge/results_true.dat rename to tests/regression_tests/tally_slice_merge/results_true.dat index 4f1d6c6e2c..461c4faa87 100644 --- a/tests/test_tally_slice_merge/results_true.dat +++ b/tests/regression_tests/tally_slice_merge/results_true.dat @@ -48,20 +48,20 @@ 13 (500, 5000, 50000) 6.25e-01 2.00e+07 U235 nu-fission 0.00e+00 0.00e+00 14 (500, 5000, 50000) 6.25e-01 2.00e+07 U238 fission 0.00e+00 0.00e+00 15 (500, 5000, 50000) 6.25e-01 2.00e+07 U238 nu-fission 0.00e+00 0.00e+00 - sum(mesh) energy low [eV] energy high [eV] nuclide score mean std. dev. -0 ((1, 1, 1), (1, 2, 1)) 0.00e+00 6.25e-01 U235 fission 1.48e-02 3.65e-03 -1 ((1, 1, 1), (1, 2, 1)) 0.00e+00 6.25e-01 U235 nu-fission 3.60e-02 8.90e-03 -2 ((1, 1, 1), (1, 2, 1)) 0.00e+00 6.25e-01 U238 fission 2.06e-08 4.98e-09 -3 ((1, 1, 1), (1, 2, 1)) 0.00e+00 6.25e-01 U238 nu-fission 5.14e-08 1.24e-08 -4 ((1, 1, 1), (1, 2, 1)) 6.25e-01 2.00e+07 U235 fission 2.23e-03 3.92e-04 -5 ((1, 1, 1), (1, 2, 1)) 6.25e-01 2.00e+07 U235 nu-fission 5.45e-03 9.56e-04 -6 ((1, 1, 1), (1, 2, 1)) 6.25e-01 2.00e+07 U238 fission 5.58e-04 2.08e-04 -7 ((1, 1, 1), (1, 2, 1)) 6.25e-01 2.00e+07 U238 nu-fission 1.50e-03 5.43e-04 -8 ((2, 1, 1), (2, 2, 1)) 0.00e+00 6.25e-01 U235 fission 2.56e-02 5.50e-03 -9 ((2, 1, 1), (2, 2, 1)) 0.00e+00 6.25e-01 U235 nu-fission 6.24e-02 1.34e-02 -10 ((2, 1, 1), (2, 2, 1)) 0.00e+00 6.25e-01 U238 fission 3.55e-08 7.70e-09 -11 ((2, 1, 1), (2, 2, 1)) 0.00e+00 6.25e-01 U238 nu-fission 8.85e-08 1.92e-08 -12 ((2, 1, 1), (2, 2, 1)) 6.25e-01 2.00e+07 U235 fission 5.01e-03 1.38e-03 -13 ((2, 1, 1), (2, 2, 1)) 6.25e-01 2.00e+07 U235 nu-fission 1.22e-02 3.37e-03 -14 ((2, 1, 1), (2, 2, 1)) 6.25e-01 2.00e+07 U238 fission 2.40e-03 2.69e-04 -15 ((2, 1, 1), (2, 2, 1)) 6.25e-01 2.00e+07 U238 nu-fission 6.60e-03 7.63e-04 + sum(mesh) energy low [eV] energy high [eV] nuclide score mean std. dev. +0 ((1, 1), (1, 2)) 0.00e+00 6.25e-01 U235 fission 0.00e+00 0.00e+00 +1 ((1, 1), (1, 2)) 0.00e+00 6.25e-01 U235 nu-fission 0.00e+00 0.00e+00 +2 ((1, 1), (1, 2)) 0.00e+00 6.25e-01 U238 fission 0.00e+00 0.00e+00 +3 ((1, 1), (1, 2)) 0.00e+00 6.25e-01 U238 nu-fission 0.00e+00 0.00e+00 +4 ((1, 1), (1, 2)) 6.25e-01 2.00e+07 U235 fission 1.60e-04 1.60e-04 +5 ((1, 1), (1, 2)) 6.25e-01 2.00e+07 U235 nu-fission 3.91e-04 3.91e-04 +6 ((1, 1), (1, 2)) 6.25e-01 2.00e+07 U238 fission 5.12e-05 5.12e-05 +7 ((1, 1), (1, 2)) 6.25e-01 2.00e+07 U238 nu-fission 1.36e-04 1.36e-04 +8 ((2, 1), (2, 2)) 0.00e+00 6.25e-01 U235 fission 4.04e-02 6.60e-03 +9 ((2, 1), (2, 2)) 0.00e+00 6.25e-01 U235 nu-fission 9.85e-02 1.61e-02 +10 ((2, 1), (2, 2)) 0.00e+00 6.25e-01 U238 fission 5.61e-08 9.18e-09 +11 ((2, 1), (2, 2)) 0.00e+00 6.25e-01 U238 nu-fission 1.40e-07 2.29e-08 +12 ((2, 1), (2, 2)) 6.25e-01 2.00e+07 U235 fission 7.08e-03 1.43e-03 +13 ((2, 1), (2, 2)) 6.25e-01 2.00e+07 U235 nu-fission 1.73e-02 3.48e-03 +14 ((2, 1), (2, 2)) 6.25e-01 2.00e+07 U238 fission 2.91e-03 3.36e-04 +15 ((2, 1), (2, 2)) 6.25e-01 2.00e+07 U238 nu-fission 7.96e-03 9.27e-04 diff --git a/tests/test_tally_slice_merge/test_tally_slice_merge.py b/tests/regression_tests/tally_slice_merge/test.py similarity index 90% rename from tests/test_tally_slice_merge/test_tally_slice_merge.py rename to tests/regression_tests/tally_slice_merge/test.py index d917d2dadb..e52d0fde49 100644 --- a/tests/test_tally_slice_merge/test_tally_slice_merge.py +++ b/tests/regression_tests/tally_slice_merge/test.py @@ -1,20 +1,14 @@ -#!/usr/bin/env python - -from __future__ import division - -import os -import sys -import glob import hashlib import itertools -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness + import openmc +from tests.testing_harness import PyAPITestHarness + class TallySliceMergeTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(TallySliceMergeTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Define nuclides and scores to add to both tallies self.nuclides = ['U235', 'U238'] @@ -85,8 +79,7 @@ class TallySliceMergeTestHarness(PyAPITestHarness): """Digest info in the statepoint and return as a string.""" # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Extract the cell tally tallies = [sp.get_tally(name='cell tally')] @@ -133,10 +126,10 @@ class TallySliceMergeTestHarness(PyAPITestHarness): # Sum up a few subdomains from the distribcell tally sum1 = distribcell_tally.summation(filter_type=openmc.DistribcellFilter, - filter_bins=[0,100,2000,30000]) + filter_bins=[0, 100, 2000, 30000]) # Sum up a few subdomains from the distribcell tally sum2 = distribcell_tally.summation(filter_type=openmc.DistribcellFilter, - filter_bins=[500,5000,50000]) + filter_bins=[500, 5000, 50000]) # Merge the distribcell tally slices merge_tally = sum1.merge(sum2) @@ -150,10 +143,10 @@ class TallySliceMergeTestHarness(PyAPITestHarness): # Sum up a few subdomains from the mesh tally sum1 = mesh_tally.summation(filter_type=openmc.MeshFilter, - filter_bins=[(1,1,1), (1,2,1)]) + filter_bins=[(1, 1), (1, 2)]) # Sum up a few subdomains from the mesh tally sum2 = mesh_tally.summation(filter_type=openmc.MeshFilter, - filter_bins=[(2,1,1), (2,2,1)]) + filter_bins=[(2, 1), (2, 2)]) # Merge the mesh tally slices merge_tally = sum1.merge(sum2) @@ -171,6 +164,6 @@ class TallySliceMergeTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_tally_slice_merge(): harness = TallySliceMergeTestHarness('statepoint.10.h5') harness.main() diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py new file mode 100644 index 0000000000..19e2c7664b --- /dev/null +++ b/tests/regression_tests/test_deplete_full.py @@ -0,0 +1,102 @@ +""" Full system test suite. """ + +from math import floor +import shutil +from pathlib import Path + +import numpy as np +import openmc +from openmc.data import JOULE_PER_EV +import openmc.deplete + +from tests.regression_tests import config +from .example_geometry import generate_problem + + +def test_full(run_in_tmpdir): + """Full system test suite. + + Runs an entire OpenMC simulation with depletion coupling and verifies + that the outputs match a reference file. Sensitive to changes in + OpenMC. + + This test runs a complete OpenMC simulation and tests the outputs. + It will take a while. + """ + + n_rings = 2 + n_wedges = 4 + + # Load geometry from example + geometry, lower_left, upper_right = generate_problem(n_rings, n_wedges) + + # OpenMC-specific settings + settings = openmc.Settings() + settings.particles = 100 + settings.batches = 100 + settings.inactive = 40 + space = openmc.stats.Box(lower_left, upper_right) + settings.source = openmc.Source(space=space) + settings.seed = 1 + settings.verbosity = 3 + + # Create operator + chain_file = Path(__file__).parents[1] / 'chain_simple.xml' + op = openmc.deplete.Operator(geometry, settings, chain_file) + op.round_number = True + + # Power and timesteps + dt1 = 15.*24*60*60 # 15 days + dt2 = 1.5*30*24*60*60 # 1.5 months + N = floor(dt2/dt1) + dt = np.full(N, dt1) + power = 2.337e15*4*JOULE_PER_EV*1e6 # MeV/second cm from CASMO + + # Perform simulation using the predictor algorithm + openmc.deplete.integrator.predictor(op, dt, power) + + # Get path to test and reference results + path_test = op.output_dir / 'depletion_results.h5' + path_reference = Path(__file__).with_name('test_reference.h5') + + # If updating results, do so and return + if config['update']: + shutil.copyfile(str(path_test), str(path_reference)) + return + + # Load the reference/test results + res_test = openmc.deplete.ResultsList(path_test) + res_ref = openmc.deplete.ResultsList(path_reference) + + # Assert same mats + for mat in res_ref[0].mat_to_ind: + assert mat in res_test[0].mat_to_ind, \ + "Material {} not in new results.".format(mat) + for nuc in res_ref[0].nuc_to_ind: + assert nuc in res_test[0].nuc_to_ind, \ + "Nuclide {} not in new results.".format(nuc) + + for mat in res_test[0].mat_to_ind: + assert mat in res_ref[0].mat_to_ind, \ + "Material {} not in old results.".format(mat) + for nuc in res_test[0].nuc_to_ind: + assert nuc in res_ref[0].nuc_to_ind, \ + "Nuclide {} not in old results.".format(nuc) + + tol = 1.0e-6 + for mat in res_test[0].mat_to_ind: + for nuc in res_test[0].nuc_to_ind: + _, y_test = res_test.get_atoms(mat, nuc) + _, y_old = res_ref.get_atoms(mat, nuc) + + # Test each point + correct = True + for i, ref in enumerate(y_old): + if ref != y_test[i]: + if ref != 0.0: + correct = np.abs(y_test[i] - ref) / ref <= tol + else: + correct = False + + assert correct, "Discrepancy in mat {} and nuc {}\n{}\n{}".format( + mat, nuc, y_old, y_test) diff --git a/tests/regression_tests/test_reference.h5 b/tests/regression_tests/test_reference.h5 new file mode 100644 index 0000000000..5323a9a904 Binary files /dev/null and b/tests/regression_tests/test_reference.h5 differ diff --git a/tests/regression_tests/trace/__init__.py b/tests/regression_tests/trace/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_trace/geometry.xml b/tests/regression_tests/trace/geometry.xml similarity index 100% rename from tests/test_trace/geometry.xml rename to tests/regression_tests/trace/geometry.xml diff --git a/tests/test_trace/materials.xml b/tests/regression_tests/trace/materials.xml similarity index 100% rename from tests/test_trace/materials.xml rename to tests/regression_tests/trace/materials.xml diff --git a/tests/test_trace/results_true.dat b/tests/regression_tests/trace/results_true.dat similarity index 100% rename from tests/test_trace/results_true.dat rename to tests/regression_tests/trace/results_true.dat diff --git a/tests/test_trace/settings.xml b/tests/regression_tests/trace/settings.xml similarity index 100% rename from tests/test_trace/settings.xml rename to tests/regression_tests/trace/settings.xml diff --git a/tests/regression_tests/trace/test.py b/tests/regression_tests/trace/test.py new file mode 100644 index 0000000000..79dcaa1060 --- /dev/null +++ b/tests/regression_tests/trace/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_trace(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/track_output/__init__.py b/tests/regression_tests/track_output/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_track_output/geometry.xml b/tests/regression_tests/track_output/geometry.xml similarity index 100% rename from tests/test_track_output/geometry.xml rename to tests/regression_tests/track_output/geometry.xml diff --git a/tests/test_track_output/materials.xml b/tests/regression_tests/track_output/materials.xml similarity index 100% rename from tests/test_track_output/materials.xml rename to tests/regression_tests/track_output/materials.xml diff --git a/tests/test_track_output/results_true.dat b/tests/regression_tests/track_output/results_true.dat similarity index 100% rename from tests/test_track_output/results_true.dat rename to tests/regression_tests/track_output/results_true.dat diff --git a/tests/test_track_output/settings.xml b/tests/regression_tests/track_output/settings.xml similarity index 100% rename from tests/test_track_output/settings.xml rename to tests/regression_tests/track_output/settings.xml diff --git a/tests/test_track_output/test_track_output.py b/tests/regression_tests/track_output/test.py similarity index 79% rename from tests/test_track_output/test_track_output.py rename to tests/regression_tests/track_output/test.py index 0357aae19e..22eac03bfc 100644 --- a/tests/test_track_output/test_track_output.py +++ b/tests/regression_tests/track_output/test.py @@ -1,12 +1,11 @@ -#!/usr/bin/env python - import glob import os from subprocess import call import shutil -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness + +import pytest + +from tests.testing_harness import TestHarness class TrackTestHarness(TestHarness): @@ -39,14 +38,9 @@ class TrackTestHarness(TestHarness): os.remove(f) -if __name__ == '__main__': +def test_track_output(): # If vtk python module is not available, we can't run track.py so skip this # test. - try: - import vtk - except ImportError: - print('----------------Skipping test-------------') - shutil.copy('results_true.dat', 'results_test.dat') - exit() + vtk = pytest.importorskip('vtk') harness = TrackTestHarness('statepoint.2.h5') harness.main() diff --git a/tests/regression_tests/translation/__init__.py b/tests/regression_tests/translation/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_translation/geometry.xml b/tests/regression_tests/translation/geometry.xml similarity index 100% rename from tests/test_translation/geometry.xml rename to tests/regression_tests/translation/geometry.xml diff --git a/tests/test_translation/materials.xml b/tests/regression_tests/translation/materials.xml similarity index 100% rename from tests/test_translation/materials.xml rename to tests/regression_tests/translation/materials.xml diff --git a/tests/test_translation/results_true.dat b/tests/regression_tests/translation/results_true.dat similarity index 100% rename from tests/test_translation/results_true.dat rename to tests/regression_tests/translation/results_true.dat diff --git a/tests/test_translation/settings.xml b/tests/regression_tests/translation/settings.xml similarity index 100% rename from tests/test_translation/settings.xml rename to tests/regression_tests/translation/settings.xml diff --git a/tests/regression_tests/translation/test.py b/tests/regression_tests/translation/test.py new file mode 100644 index 0000000000..876db736b9 --- /dev/null +++ b/tests/regression_tests/translation/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_translation(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/trigger_batch_interval/__init__.py b/tests/regression_tests/trigger_batch_interval/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_trigger_batch_interval/geometry.xml b/tests/regression_tests/trigger_batch_interval/geometry.xml similarity index 100% rename from tests/test_trigger_batch_interval/geometry.xml rename to tests/regression_tests/trigger_batch_interval/geometry.xml diff --git a/tests/test_trigger_batch_interval/materials.xml b/tests/regression_tests/trigger_batch_interval/materials.xml similarity index 100% rename from tests/test_trigger_batch_interval/materials.xml rename to tests/regression_tests/trigger_batch_interval/materials.xml diff --git a/tests/test_trigger_batch_interval/results_true.dat b/tests/regression_tests/trigger_batch_interval/results_true.dat similarity index 100% rename from tests/test_trigger_batch_interval/results_true.dat rename to tests/regression_tests/trigger_batch_interval/results_true.dat diff --git a/tests/test_trigger_batch_interval/settings.xml b/tests/regression_tests/trigger_batch_interval/settings.xml similarity index 100% rename from tests/test_trigger_batch_interval/settings.xml rename to tests/regression_tests/trigger_batch_interval/settings.xml diff --git a/tests/test_trigger_batch_interval/tallies.xml b/tests/regression_tests/trigger_batch_interval/tallies.xml similarity index 100% rename from tests/test_trigger_batch_interval/tallies.xml rename to tests/regression_tests/trigger_batch_interval/tallies.xml diff --git a/tests/regression_tests/trigger_batch_interval/test.py b/tests/regression_tests/trigger_batch_interval/test.py new file mode 100644 index 0000000000..e161745022 --- /dev/null +++ b/tests/regression_tests/trigger_batch_interval/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_trigger_batch_interval(): + harness = TestHarness('statepoint.15.h5') + harness.main() diff --git a/tests/regression_tests/trigger_no_batch_interval/__init__.py b/tests/regression_tests/trigger_no_batch_interval/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_trigger_no_batch_interval/geometry.xml b/tests/regression_tests/trigger_no_batch_interval/geometry.xml similarity index 100% rename from tests/test_trigger_no_batch_interval/geometry.xml rename to tests/regression_tests/trigger_no_batch_interval/geometry.xml diff --git a/tests/test_trigger_no_batch_interval/materials.xml b/tests/regression_tests/trigger_no_batch_interval/materials.xml similarity index 100% rename from tests/test_trigger_no_batch_interval/materials.xml rename to tests/regression_tests/trigger_no_batch_interval/materials.xml diff --git a/tests/test_trigger_no_batch_interval/results_true.dat b/tests/regression_tests/trigger_no_batch_interval/results_true.dat similarity index 100% rename from tests/test_trigger_no_batch_interval/results_true.dat rename to tests/regression_tests/trigger_no_batch_interval/results_true.dat diff --git a/tests/test_trigger_no_batch_interval/settings.xml b/tests/regression_tests/trigger_no_batch_interval/settings.xml similarity index 100% rename from tests/test_trigger_no_batch_interval/settings.xml rename to tests/regression_tests/trigger_no_batch_interval/settings.xml diff --git a/tests/test_trigger_no_batch_interval/tallies.xml b/tests/regression_tests/trigger_no_batch_interval/tallies.xml similarity index 100% rename from tests/test_trigger_no_batch_interval/tallies.xml rename to tests/regression_tests/trigger_no_batch_interval/tallies.xml diff --git a/tests/regression_tests/trigger_no_batch_interval/test.py b/tests/regression_tests/trigger_no_batch_interval/test.py new file mode 100644 index 0000000000..4a40def5aa --- /dev/null +++ b/tests/regression_tests/trigger_no_batch_interval/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_trigger_no_batch_interval(): + harness = TestHarness('statepoint.15.h5') + harness.main() diff --git a/tests/regression_tests/trigger_no_status/__init__.py b/tests/regression_tests/trigger_no_status/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_trigger_no_status/geometry.xml b/tests/regression_tests/trigger_no_status/geometry.xml similarity index 100% rename from tests/test_trigger_no_status/geometry.xml rename to tests/regression_tests/trigger_no_status/geometry.xml diff --git a/tests/test_trigger_no_status/materials.xml b/tests/regression_tests/trigger_no_status/materials.xml similarity index 100% rename from tests/test_trigger_no_status/materials.xml rename to tests/regression_tests/trigger_no_status/materials.xml diff --git a/tests/test_trigger_no_status/results_true.dat b/tests/regression_tests/trigger_no_status/results_true.dat similarity index 100% rename from tests/test_trigger_no_status/results_true.dat rename to tests/regression_tests/trigger_no_status/results_true.dat diff --git a/tests/test_trigger_no_status/settings.xml b/tests/regression_tests/trigger_no_status/settings.xml similarity index 100% rename from tests/test_trigger_no_status/settings.xml rename to tests/regression_tests/trigger_no_status/settings.xml diff --git a/tests/test_trigger_no_status/tallies.xml b/tests/regression_tests/trigger_no_status/tallies.xml similarity index 100% rename from tests/test_trigger_no_status/tallies.xml rename to tests/regression_tests/trigger_no_status/tallies.xml diff --git a/tests/regression_tests/trigger_no_status/test.py b/tests/regression_tests/trigger_no_status/test.py new file mode 100644 index 0000000000..75ae9a8cc9 --- /dev/null +++ b/tests/regression_tests/trigger_no_status/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_trigger_no_status(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/trigger_tallies/__init__.py b/tests/regression_tests/trigger_tallies/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_trigger_tallies/geometry.xml b/tests/regression_tests/trigger_tallies/geometry.xml similarity index 100% rename from tests/test_trigger_tallies/geometry.xml rename to tests/regression_tests/trigger_tallies/geometry.xml diff --git a/tests/test_trigger_tallies/materials.xml b/tests/regression_tests/trigger_tallies/materials.xml similarity index 100% rename from tests/test_trigger_tallies/materials.xml rename to tests/regression_tests/trigger_tallies/materials.xml diff --git a/tests/test_trigger_tallies/results_true.dat b/tests/regression_tests/trigger_tallies/results_true.dat similarity index 100% rename from tests/test_trigger_tallies/results_true.dat rename to tests/regression_tests/trigger_tallies/results_true.dat diff --git a/tests/test_trigger_tallies/settings.xml b/tests/regression_tests/trigger_tallies/settings.xml similarity index 100% rename from tests/test_trigger_tallies/settings.xml rename to tests/regression_tests/trigger_tallies/settings.xml diff --git a/tests/test_trigger_tallies/tallies.xml b/tests/regression_tests/trigger_tallies/tallies.xml similarity index 100% rename from tests/test_trigger_tallies/tallies.xml rename to tests/regression_tests/trigger_tallies/tallies.xml diff --git a/tests/regression_tests/trigger_tallies/test.py b/tests/regression_tests/trigger_tallies/test.py new file mode 100644 index 0000000000..f8493c0c68 --- /dev/null +++ b/tests/regression_tests/trigger_tallies/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_trigger_tallies(): + harness = TestHarness('statepoint.15.h5') + harness.main() diff --git a/tests/regression_tests/triso/__init__.py b/tests/regression_tests/triso/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_triso/inputs_true.dat b/tests/regression_tests/triso/inputs_true.dat similarity index 99% rename from tests/test_triso/inputs_true.dat rename to tests/regression_tests/triso/inputs_true.dat index fdbc1cb5f1..6d674b4502 100644 --- a/tests/test_triso/inputs_true.dat +++ b/tests/regression_tests/triso/inputs_true.dat @@ -393,7 +393,7 @@ - + diff --git a/tests/test_triso/results_true.dat b/tests/regression_tests/triso/results_true.dat similarity index 100% rename from tests/test_triso/results_true.dat rename to tests/regression_tests/triso/results_true.dat diff --git a/tests/test_triso/test_triso.py b/tests/regression_tests/triso/test.py similarity index 95% rename from tests/test_triso/test_triso.py rename to tests/regression_tests/triso/test.py index e5c823c01f..174bba94fd 100644 --- a/tests/test_triso/test_triso.py +++ b/tests/regression_tests/triso/test.py @@ -1,18 +1,12 @@ -#!/usr/bin/env python - -import os -import sys -import glob import random from math import sqrt import numpy as np - -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness import openmc import openmc.model +from tests.testing_harness import PyAPITestHarness + class TRISOTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -96,6 +90,6 @@ class TRISOTestHarness(PyAPITestHarness): mats.export_to_xml() -if __name__ == '__main__': +def test_triso(): harness = TRISOTestHarness('statepoint.5.h5') harness.main() diff --git a/tests/regression_tests/uniform_fs/__init__.py b/tests/regression_tests/uniform_fs/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_uniform_fs/geometry.xml b/tests/regression_tests/uniform_fs/geometry.xml similarity index 100% rename from tests/test_uniform_fs/geometry.xml rename to tests/regression_tests/uniform_fs/geometry.xml diff --git a/tests/test_uniform_fs/materials.xml b/tests/regression_tests/uniform_fs/materials.xml similarity index 100% rename from tests/test_uniform_fs/materials.xml rename to tests/regression_tests/uniform_fs/materials.xml diff --git a/tests/test_uniform_fs/results_true.dat b/tests/regression_tests/uniform_fs/results_true.dat similarity index 100% rename from tests/test_uniform_fs/results_true.dat rename to tests/regression_tests/uniform_fs/results_true.dat diff --git a/tests/test_uniform_fs/settings.xml b/tests/regression_tests/uniform_fs/settings.xml similarity index 100% rename from tests/test_uniform_fs/settings.xml rename to tests/regression_tests/uniform_fs/settings.xml diff --git a/tests/regression_tests/uniform_fs/test.py b/tests/regression_tests/uniform_fs/test.py new file mode 100644 index 0000000000..64d997909c --- /dev/null +++ b/tests/regression_tests/uniform_fs/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_uniform_fs(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/universe/__init__.py b/tests/regression_tests/universe/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_universe/geometry.xml b/tests/regression_tests/universe/geometry.xml similarity index 100% rename from tests/test_universe/geometry.xml rename to tests/regression_tests/universe/geometry.xml diff --git a/tests/test_universe/materials.xml b/tests/regression_tests/universe/materials.xml similarity index 100% rename from tests/test_universe/materials.xml rename to tests/regression_tests/universe/materials.xml diff --git a/tests/test_universe/results_true.dat b/tests/regression_tests/universe/results_true.dat similarity index 100% rename from tests/test_universe/results_true.dat rename to tests/regression_tests/universe/results_true.dat diff --git a/tests/test_universe/settings.xml b/tests/regression_tests/universe/settings.xml similarity index 100% rename from tests/test_universe/settings.xml rename to tests/regression_tests/universe/settings.xml diff --git a/tests/regression_tests/universe/test.py b/tests/regression_tests/universe/test.py new file mode 100644 index 0000000000..d5ed9645bd --- /dev/null +++ b/tests/regression_tests/universe/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_universe(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/void/__init__.py b/tests/regression_tests/void/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_void/geometry.xml b/tests/regression_tests/void/geometry.xml similarity index 100% rename from tests/test_void/geometry.xml rename to tests/regression_tests/void/geometry.xml diff --git a/tests/test_void/materials.xml b/tests/regression_tests/void/materials.xml similarity index 100% rename from tests/test_void/materials.xml rename to tests/regression_tests/void/materials.xml diff --git a/tests/test_void/results_true.dat b/tests/regression_tests/void/results_true.dat similarity index 100% rename from tests/test_void/results_true.dat rename to tests/regression_tests/void/results_true.dat diff --git a/tests/test_void/settings.xml b/tests/regression_tests/void/settings.xml similarity index 100% rename from tests/test_void/settings.xml rename to tests/regression_tests/void/settings.xml diff --git a/tests/regression_tests/void/test.py b/tests/regression_tests/void/test.py new file mode 100644 index 0000000000..af16f2ac80 --- /dev/null +++ b/tests/regression_tests/void/test.py @@ -0,0 +1,6 @@ +from tests.testing_harness import TestHarness + + +def test_void(): + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/regression_tests/volume_calc/__init__.py b/tests/regression_tests/volume_calc/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_volume_calc/inputs_true.dat b/tests/regression_tests/volume_calc/inputs_true.dat similarity index 97% rename from tests/test_volume_calc/inputs_true.dat rename to tests/regression_tests/volume_calc/inputs_true.dat index 28f1cbd9fc..607921af26 100644 --- a/tests/test_volume_calc/inputs_true.dat +++ b/tests/regression_tests/volume_calc/inputs_true.dat @@ -18,7 +18,7 @@ - + diff --git a/tests/regression_tests/volume_calc/results_true.dat b/tests/regression_tests/volume_calc/results_true.dat new file mode 100644 index 0000000000..466139cd68 --- /dev/null +++ b/tests/regression_tests/volume_calc/results_true.dat @@ -0,0 +1,30 @@ +Volume calculation 0 +Domain 1: 31.47+/-0.07 cm^3 +Domain 2: 2.093+/-0.031 cm^3 +Domain 3: 2.049+/-0.031 cm^3 + Cell Nuclide Atoms +0 1 U235 (3.482+/-0.008)e+23 +1 1 Mo99 (3.482+/-0.008)e+22 +2 2 H1 (1.400+/-0.021)e+23 +3 2 O16 (7.00+/-0.10)e+22 +4 2 B10 (7.00+/-0.10)e+18 +5 3 H1 (1.370+/-0.021)e+23 +6 3 O16 (6.85+/-0.10)e+22 +7 3 B10 (6.85+/-0.10)e+18 +Volume calculation 1 +Domain 1: 4.14+/-0.04 cm^3 +Domain 2: 31.47+/-0.07 cm^3 + Material Nuclide Atoms +0 1 H1 (2.770+/-0.029)e+23 +1 1 O16 (1.385+/-0.014)e+23 +2 1 B10 (1.385+/-0.014)e+19 +3 2 U235 (3.482+/-0.008)e+23 +4 2 Mo99 (3.482+/-0.008)e+22 +Volume calculation 2 +Domain 0: 35.61+/-0.07 cm^3 + Universe Nuclide Atoms +0 0 H1 (2.770+/-0.029)e+23 +1 0 O16 (1.385+/-0.014)e+23 +2 0 B10 (1.385+/-0.014)e+19 +3 0 U235 (3.482+/-0.008)e+23 +4 0 Mo99 (3.482+/-0.008)e+22 diff --git a/tests/test_volume_calc/test_volume_calc.py b/tests/regression_tests/volume_calc/test.py similarity index 87% rename from tests/test_volume_calc/test_volume_calc.py rename to tests/regression_tests/volume_calc/test.py index 003528b0df..fda4b33210 100644 --- a/tests/test_volume_calc/test_volume_calc.py +++ b/tests/regression_tests/volume_calc/test.py @@ -1,12 +1,11 @@ -#!/usr/bin/env python - import os import glob import sys -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness + import openmc +from tests.testing_harness import PyAPITestHarness + class VolumeTest(PyAPITestHarness): def _build_inputs(self): @@ -57,8 +56,7 @@ class VolumeTest(PyAPITestHarness): def _get_results(self): outstr = '' - for i, filename in enumerate(sorted(glob.glob(os.path.join( - os.getcwd(), 'volume_*.h5')))): + for i, filename in enumerate(sorted(glob.glob('volume_*.h5'))): outstr += 'Volume calculation {}\n'.format(i) # Read volume calculation results @@ -66,8 +64,7 @@ class VolumeTest(PyAPITestHarness): # Write cell volumes and total # of atoms for each nuclide for uid, volume in sorted(volume_calc.volumes.items()): - outstr += 'Domain {0}: {1[0]:.4f} +/- {1[1]:.4f} cm^3\n'.format( - uid, volume) + outstr += 'Domain {}: {} cm^3\n'.format(uid, volume) outstr += str(volume_calc.atoms_dataframe) + '\n' return outstr @@ -75,6 +72,6 @@ class VolumeTest(PyAPITestHarness): def _test_output_created(self): pass -if __name__ == '__main__': +def test_volume_calc(): harness = VolumeTest('') harness.main() diff --git a/tests/run_tests.py b/tests/run_tests.py deleted file mode 100755 index 6e6b886a50..0000000000 --- a/tests/run_tests.py +++ /dev/null @@ -1,552 +0,0 @@ -#!/usr/bin/env python - -from __future__ import print_function - -import os -import sys -import shutil -import re -import glob -import socket -from subprocess import call, check_output -from collections import OrderedDict -from argparse import ArgumentParser - -# Command line parsing -parser = ArgumentParser() -parser.add_argument('-j', '--parallel', dest='n_procs', default='1', - help="Number of parallel jobs.") -parser.add_argument('-R', '--tests-regex', dest='regex_tests', - help="Run tests matching regular expression. \ - Test names are the directories present in tests folder.\ - This uses standard regex syntax to select tests.") -parser.add_argument('-C', '--build-config', dest='build_config', - help="Build configurations matching regular expression. \ - Specific build configurations can be printed out with \ - optional argument -p, --print. This uses standard \ - regex syntax to select build configurations.") -parser.add_argument('-l', '--list', action="store_true", - dest="list_build_configs", default=False, - help="List out build configurations.") -parser.add_argument("-p", "--project", dest="project", default="", - help="project name for build") -parser.add_argument("-D", "--dashboard", dest="dash", - help="Dash name -- Experimental, Nightly, Continuous") -parser.add_argument("-u", "--update", action="store_true", dest="update", - help="Allow CTest to update repo. (WARNING: may overwrite\ - changes that were not pushed.") -parser.add_argument("-s", "--script", action="store_true", dest="script", - help="Activate CTest scripting mode for coverage, valgrind\ - and dashboard capability.") -args = parser.parse_args() - -# Default compiler paths -FC = 'gfortran' -CC = 'gcc' -CXX = 'g++' -MPI_DIR = '/opt/mpich/3.2-gnu' -HDF5_DIR = '/opt/hdf5/1.8.16-gnu' -PHDF5_DIR = '/opt/phdf5/1.8.16-gnu' - -# Script mode for extra capability -script_mode = False - -# Override default compiler paths if environmental vars are found -if 'FC' in os.environ: - FC = os.environ['FC'] -if 'CC' in os.environ: - CC = os.environ['CC'] -if 'CXX' in os.environ: - CXX = os.environ['CXX'] -if 'MPI_DIR' in os.environ: - MPI_DIR = os.environ['MPI_DIR'] -if 'HDF5_DIR' in os.environ: - HDF5_DIR = os.environ['HDF5_DIR'] -if 'PHDF5_DIR' in os.environ: - PHDF5_DIR = os.environ['PHDF5_DIR'] - -# CTest script template -ctest_str = """set (CTEST_SOURCE_DIRECTORY "{source_dir}") -set (CTEST_BINARY_DIRECTORY "{build_dir}") - -set(CTEST_SITE "{host_name}") -set (CTEST_BUILD_NAME "{build_name}") -set (CTEST_CMAKE_GENERATOR "Unix Makefiles") -set (CTEST_BUILD_OPTIONS "{build_opts}") - -set(CTEST_UPDATE_COMMAND "git") - -set(CTEST_CONFIGURE_COMMAND "${{CMAKE_COMMAND}} -H${{CTEST_SOURCE_DIRECTORY}} -B${{CTEST_BINARY_DIRECTORY}} ${{CTEST_BUILD_OPTIONS}}") -set(CTEST_MEMORYCHECK_COMMAND "{valgrind_cmd}") -set(CTEST_MEMORYCHECK_COMMAND_OPTIONS "--tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes") -#set(CTEST_MEMORYCHECK_SUPPRESSIONS_FILE ${{CTEST_SOURCE_DIRECTORY}}/../tests/valgrind.supp) -set(MEM_CHECK {mem_check}) -if(MEM_CHECK) -set(ENV{{MEM_CHECK}} ${{MEM_CHECK}}) -endif() - -set(CTEST_COVERAGE_COMMAND "gcov") -set(COVERAGE {coverage}) -set(ENV{{COVERAGE}} ${{COVERAGE}}) - -{subproject} - -ctest_start("{dashboard}") -ctest_configure(RETURN_VALUE res) -{update} -ctest_build(RETURN_VALUE res) -if(NOT MEM_CHECK) -ctest_test({tests} PARALLEL_LEVEL {n_procs}, RETURN_VALUE res) -endif() -if(MEM_CHECK) -ctest_memcheck({tests} RETURN_VALUE res) -endif(MEM_CHECK) -if(COVERAGE) -ctest_coverage(RETURN_VALUE res) -endif(COVERAGE) -{submit} - -if (res EQUAL 0) -else() -message(FATAL_ERROR "") -endif() -""" - -# Define test data structure -tests = OrderedDict() - - -def cleanup(path): - """Remove generated output files.""" - for dirpath, dirnames, filenames in os.walk(path): - for fname in filenames: - for ext in ['.h5', '.ppm', '.voxel']: - if fname.endswith(ext) and fname != '1d_mgxs.h5': - os.remove(os.path.join(dirpath, fname)) - - -def which(program): - def is_exe(fpath): - return os.path.isfile(fpath) and os.access(fpath, os.X_OK) - - fpath, fname = os.path.split(program) - if fpath: - if is_exe(program): - return program - else: - for path in os.environ["PATH"].split(os.pathsep): - path = path.strip('"') - exe_file = os.path.join(path, program) - if is_exe(exe_file): - return exe_file - return None - - -class Test(object): - def __init__(self, name, debug=False, optimize=False, mpi=False, openmp=False, - phdf5=False, valgrind=False, coverage=False): - self.name = name - self.debug = debug - self.optimize = optimize - self.mpi = mpi - self.openmp = openmp - self.phdf5 = phdf5 - self.valgrind = valgrind - self.coverage = coverage - self.success = True - self.msg = None - self.skipped = False - self.cmake = ['cmake', '-H..', '-Bbuild', - '-DPYTHON_EXECUTABLE=' + sys.executable] - - # Check for MPI - if self.mpi: - if os.path.exists(os.path.join(MPI_DIR, 'bin', 'mpifort')): - self.fc = os.path.join(MPI_DIR, 'bin', 'mpifort') - else: - self.fc = os.path.join(MPI_DIR, 'bin', 'mpif90') - self.cc = os.path.join(MPI_DIR, 'bin', 'mpicc') - self.cxx = os.path.join(MPI_DIR, 'bin', 'mpicxx') - else: - self.fc = FC - self.cc = CC - self.cxx = CXX - - # Sets the build name that will show up on the CDash - def get_build_name(self): - self.build_name = args.project + '_' + self.name - return self.build_name - - # Sets up build options for various tests. It is used both - # in script and non-script modes - def get_build_opts(self): - build_str = "" - if self.debug: - build_str += "-Ddebug=ON " - if self.optimize: - build_str += "-Doptimize=ON " - if not self.openmp: - build_str += "-Dopenmp=OFF " - if self.coverage: - build_str += "-Dcoverage=ON " - if self.phdf5: - build_str += "-DHDF5_PREFER_PARALLEL=ON " - else: - build_str += "-DHDF5_PREFER_PARALLEL=OFF " - self.build_opts = build_str - return self.build_opts - - # Write out the ctest script to tests directory - def create_ctest_script(self, ctest_vars): - with open('ctestscript.run', 'w') as fh: - fh.write(ctest_str.format(**ctest_vars)) - - # Runs the ctest script which performs all the cmake/ctest/cdash - def run_ctest_script(self): - os.environ['FC'] = self.fc - os.environ['CC'] = self.cc - os.environ['CXX'] = self.cxx - if self.mpi: - os.environ['MPI_DIR'] = MPI_DIR - if self.phdf5: - os.environ['HDF5_ROOT'] = PHDF5_DIR - else: - os.environ['HDF5_ROOT'] = HDF5_DIR - rc = call(['ctest', '-S', 'ctestscript.run', '-V']) - if rc != 0: - self.success = False - self.msg = 'Failed on ctest script.' - - # Runs cmake when in non-script mode - def run_cmake(self): - build_opts = self.build_opts.split() - self.cmake += build_opts - - os.environ['FC'] = self.fc - os.environ['CC'] = self.cc - os.environ['CXX'] = self.cxx - if self.mpi: - os.environ['MPI_DIR'] = MPI_DIR - if self.phdf5: - os.environ['HDF5_ROOT'] = PHDF5_DIR - self.cmake.append('-DHDF5_PREFER_PARALLEL=ON') - else: - os.environ['HDF5_ROOT'] = HDF5_DIR - self.cmake.append('-DHDF5_PREFER_PARALLEL=OFF') - rc = call(self.cmake) - if rc != 0: - self.success = False - self.msg = 'Failed on cmake.' - - # Runs make when in non-script mode - def run_make(self): - if not self.success: - return - - # Default make string - make_list = ['make', '-s'] - - # Check for parallel - if args.n_procs is not None: - make_list.append('-j') - make_list.append(args.n_procs) - - # Run make - rc = call(make_list) - if rc != 0: - self.success = False - self.msg = 'Failed on make.' - - # Runs ctest when in non-script mode - def run_ctests(self): - if not self.success: - return - - # Default ctest string - ctest_list = ['ctest'] - - # Check for parallel - if args.n_procs is not None: - ctest_list.append('-j') - ctest_list.append(args.n_procs) - - # Check for subset of tests - if args.regex_tests is not None: - ctest_list.append('-R') - ctest_list.append(args.regex_tests) - - # Run ctests - rc = call(ctest_list) - if rc != 0: - self.success = False - self.msg = 'Failed on testing.' - - -# Simple function to add a test to the global tests dictionary -def add_test(name, debug=False, optimize=False, mpi=False, openmp=False, - phdf5=False, valgrind=False, coverage=False): - tests.update({name: Test(name, debug, optimize, mpi, openmp, phdf5, - valgrind, coverage)}) - -# List of all tests that may be run. User can add -C to command line to specify -# a subset of these configurations -add_test('hdf5-normal') -add_test('hdf5-debug', debug=True) -add_test('hdf5-optimize', optimize=True) -add_test('omp-hdf5-normal', openmp=True) -add_test('omp-hdf5-debug', openmp=True, debug=True) -add_test('omp-hdf5-optimize', openmp=True, optimize=True) -add_test('mpi-hdf5-normal', mpi=True) -add_test('mpi-hdf5-debug', mpi=True, debug=True) -add_test('mpi-hdf5-optimize', mpi=True, optimize=True) -add_test('phdf5-normal', mpi=True, phdf5=True) -add_test('phdf5-debug', mpi=True, phdf5=True, debug=True) -add_test('phdf5-optimize', mpi=True, phdf5=True, optimize=True) -add_test('phdf5-omp-normal', mpi=True, phdf5=True, openmp=True) -add_test('phdf5-omp-debug', mpi=True, phdf5=True, openmp=True, debug=True) -add_test('phdf5-omp-optimize', mpi=True, phdf5=True, openmp=True, optimize=True) -add_test('hdf5-debug_valgrind', debug=True, valgrind=True) -add_test('hdf5-debug_coverage', debug=True, coverage=True) - -# Check to see if we should just print build configuration information to user -if args.list_build_configs: - for key in tests: - print('Configuration Name: {0}'.format(key)) - print(' Debug Flags:..........{0}'.format(tests[key].debug)) - print(' Optimization Flags:...{0}'.format(tests[key].optimize)) - print(' MPI Active:...........{0}'.format(tests[key].mpi)) - print(' OpenMP Active:........{0}'.format(tests[key].openmp)) - print(' Valgrind Test:........{0}'.format(tests[key].valgrind)) - print(' Coverage Test:........{0}\n'.format(tests[key].coverage)) - exit() - -# Delete items of dictionary that don't match regular expression -if args.build_config is not None: - to_delete = [] - for key in tests: - if not re.search(args.build_config, key): - to_delete.append(key) - for key in to_delete: - del tests[key] - -# Check for dashboard and determine whether to push results to server -# Note that there are only 3 basic dashboards: -# Experimental, Nightly, Continuous. On the CDash end, these can be -# reorganized into groups when a hostname, dashboard and build name -# are matched. -if args.dash is None: - dash = 'Experimental' - submit = '' -else: - dash = args.dash - submit = 'ctest_submit()' - -# Check for update command, which will run git fetch/merge and will delete -# any changes to repo that were not pushed to remote origin -update = 'ctest_update()' if args.update else '' - -# Check for CTest scipts mode -# Sets up whether we should use just the basic ctest command or use -# CTest scripting to perform tests. -script_mode = (args.dash is not None or args.script) - -# Setup CTest script vars. Not used in non-script mode -pwd = os.getcwd() -ctest_vars = { - 'source_dir': os.path.join(pwd, os.pardir), - 'build_dir': os.path.join(pwd, 'build'), - 'host_name': socket.gethostname(), - 'dashboard': dash, - 'submit': submit, - 'update': update, - 'n_procs': args.n_procs -} - -# Check project name -subprop = "set_property(GLOBAL PROPERTY SubProject {0})" -if args.project == "": - ctest_vars.update({'subproject': ''}) -elif args.project == 'develop': - ctest_vars.update({'subproject': ''}) -else: - ctest_vars.update({'subproject': subprop.format(args.project)}) - -# Set up default valgrind tests (subset of all tests) -# Currently takes too long to run all the tests with valgrind -# Only used in script mode -valgrind_default_tests = "cmfd_feed|confidence_intervals|\ -density|eigenvalue_genperbatch|energy_grid|entropy|\ -lattice_multiple|output|plotreflective_plane|\ -rotation|salphabetascore_absorption|seed|source_energy_mono|\ -sourcepoint_batch|statepoint_interval|survival_biasing|\ -tally_assumesep|translation|uniform_fs|universe|void" - -# Delete items of dictionary if valgrind or coverage and not in script mode -to_delete = [] -if not script_mode: - for key in tests: - if re.search('valgrind|coverage', key): - to_delete.append(key) - -for key in to_delete: - del tests[key] - -# Check if tests is empty -if not tests: - print('No tests to run.') - exit() - -# Begin testing -shutil.rmtree('build', ignore_errors=True) -cleanup('.') -for key in iter(tests): - test = tests[key] - - # Extra display if not in script mode - if not script_mode: - print('-'*(len(key) + 6)) - print(key + ' tests') - print('-'*(len(key) + 6)) - sys.stdout.flush() - - # Verify fortran compiler exists - if which(test.fc) is None: - test.msg = 'Compiler not found: {0}'.format(test.fc) - test.success = False - continue - - # Verify valgrind command exists - if test.valgrind: - valgrind_cmd = which('valgrind') - if valgrind_cmd is None: - test.msg = 'No valgrind executable found.' - test.success = False - continue - else: - valgrind_cmd = '' - - # Verify gcov/lcov exist - if test.coverage: - if which('gcov') is None: - test.msg = 'No {} executable found.'.format(exe) - test.success = False - continue - - # Set test specific CTest script vars. Not used in non-script mode - ctest_vars.update({'build_name': test.get_build_name()}) - ctest_vars.update({'build_opts': test.get_build_opts()}) - ctest_vars.update({'mem_check': test.valgrind}) - ctest_vars.update({'coverage': test.coverage}) - ctest_vars.update({'valgrind_cmd': valgrind_cmd}) - - # Check for user custom tests - # INCLUDE is a CTest command that allows for a subset - # of tests to be executed. Only used in script mode. - if args.regex_tests is None: - ctest_vars.update({'tests': ''}) - - # No user tests, use default valgrind tests - if test.valgrind: - ctest_vars.update({'tests': 'INCLUDE {0}'. - format(valgrind_default_tests)}) - else: - ctest_vars.update({'tests': 'INCLUDE {0}'. - format(args.regex_tests)}) - - # Main part of code that does the ctest execution. - # It is broken up by two modes, script and non-script - if script_mode: - - # Create ctest script - test.create_ctest_script(ctest_vars) - - # Run test - test.run_ctest_script() - - else: - - # Run CMAKE to configure build - test.run_cmake() - - # Go into build directory - os.chdir('build') - - # Build OpenMC - test.run_make() - - # Run tests - test.run_ctests() - - # Leave build directory - os.chdir(os.pardir) - - # Copy over log file - if script_mode: - logfile = glob.glob('build/Testing/Temporary/LastTest_*.log') - else: - logfile = glob.glob('build/Testing/Temporary/LastTest.log') - if len(logfile) > 0: - logfilename = os.path.split(logfile[0])[1] - logfilename = os.path.splitext(logfilename)[0] - logfilename = logfilename + '_{0}.log'.format(test.name) - shutil.copy(logfile[0], logfilename) - - # For coverage builds, use lcov to generate HTML output - if test.coverage: - if which('lcov') is None or which('genhtml') is None: - print('No lcov/genhtml command found. ' - 'Could not generate coverage report.') - else: - shutil.rmtree('coverage', ignore_errors=True) - call(['lcov', '--directory', '.', '--capture', - '--output-file', 'coverage.info']) - call(['genhtml', '--output-directory', 'coverage', 'coverage.info']) - os.remove('coverage.info') - - if test.valgrind: - # Copy memcheck output to memcheck directory - shutil.rmtree('memcheck', ignore_errors=True) - os.mkdir('memcheck') - memcheck_out = glob.glob('build/Testing/Temporary/MemoryChecker.*.log') - for fname in memcheck_out: - shutil.copy(fname, 'memcheck/') - - # Remove generated XML files - xml_files = check_output(['git', 'ls-files', '.', '--exclude-standard', - '--others']).split() - for f in xml_files: - os.remove(f) - - # Clear build directory and remove binary and hdf5 files - shutil.rmtree('build', ignore_errors=True) - if script_mode: - os.remove('ctestscript.run') - cleanup('.') - -# Print out summary of results -print('\n' + '='*54) -print('Summary of Compilation Option Testing:\n') - -if sys.stdout.isatty(): - OK = '\033[92m' - FAIL = '\033[91m' - ENDC = '\033[0m' - BOLD = '\033[1m' -else: - OK = '' - FAIL = '' - ENDC = '' - BOLD = '' - -return_code = 0 - -for test in tests: - print(test + '.'*(50 - len(test)), end='') - if tests[test].success: - print(BOLD + OK + '[OK]' + ENDC) - else: - print(BOLD + FAIL + '[FAILED]' + ENDC) - print(' '*len(test)+tests[test].msg) - return_code = 1 - -sys.exit(return_code) diff --git a/tests/test_cmfd_feed/results_true.dat b/tests/test_cmfd_feed/results_true.dat deleted file mode 100644 index d5eed3d3c5..0000000000 --- a/tests/test_cmfd_feed/results_true.dat +++ /dev/null @@ -1,1303 +0,0 @@ -k-combined: -1.169891E+00 6.289489E-03 -tally 1: -1.173922E+01 -1.385461E+01 -2.164076E+01 -4.699368E+01 -2.906462E+01 -8.464937E+01 -3.382312E+01 -1.147095E+02 -3.632006E+01 -1.323878E+02 -3.655413E+01 -1.341064E+02 -3.347757E+01 -1.124264E+02 -2.931336E+01 -8.607239E+01 -2.182947E+01 -4.789565E+01 -1.147668E+01 -1.325716E+01 -tally 2: -2.298190E+01 -2.667071E+01 -1.600292E+01 -1.293670E+01 -2.252427E+00 -2.605738E-01 -4.268506E+01 -9.161216E+01 -3.022909E+01 -4.598915E+01 -3.873926E+00 -7.615035E-01 -5.680399E+01 -1.623879E+02 -4.033805E+01 -8.196263E+01 -5.280610E+00 -1.414008E+00 -6.814742E+01 -2.331778E+02 -4.851618E+01 -1.182330E+02 -6.261805E+00 -1.983205E+00 -7.392923E+01 -2.740255E+02 -5.253586E+01 -1.384152E+02 -6.733810E+00 -2.278242E+00 -7.332860E+01 -2.698608E+02 -5.227405E+01 -1.371810E+02 -6.714658E+00 -2.273652E+00 -6.830172E+01 -2.340687E+02 -4.867159E+01 -1.188724E+02 -6.215002E+00 -1.956978E+00 -5.885634E+01 -1.736180E+02 -4.170434E+01 -8.719622E+01 -5.253064E+00 -1.396224E+00 -4.371848E+01 -9.592893E+01 -3.106403E+01 -4.844308E+01 -3.818076E+00 -7.509442E-01 -2.338413E+01 -2.752467E+01 -1.636713E+01 -1.347770E+01 -2.219928E+00 -2.515492E-01 -tally 3: -1.538752E+01 -1.196478E+01 -1.079685E+00 -6.010786E-02 -2.911906E+01 -4.269070E+01 -1.822657E+00 -1.671850E-01 -3.885421E+01 -7.608218E+01 -2.541516E+00 -3.262451E-01 -4.673300E+01 -1.097036E+02 -2.885307E+00 -4.214444E-01 -5.059247E+01 -1.283984E+02 -3.222796E+00 -5.237329E-01 -5.034856E+01 -1.272538E+02 -3.230225E+00 -5.273424E-01 -4.688476E+01 -1.103152E+02 -2.941287E+00 -4.363749E-01 -4.013746E+01 -8.077506E+01 -2.634234E+00 -3.520270E-01 -2.996887E+01 -4.509953E+01 -1.946504E+00 -1.919104E-01 -1.575260E+01 -1.248707E+01 -1.020705E+00 -5.413569E-02 -tally 4: -3.049469E+00 -4.677325E-01 -0.000000E+00 -0.000000E+00 -2.770358E+00 -3.879191E-01 -5.514939E+00 -1.528899E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -5.514939E+00 -1.528899E+00 -2.770358E+00 -3.879191E-01 -5.032131E+00 -1.275040E+00 -7.294002E+00 -2.675589E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -7.294002E+00 -2.675589E+00 -5.032131E+00 -1.275040E+00 -7.036008E+00 -2.490718E+00 -8.668860E+00 -3.776102E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -8.668860E+00 -3.776102E+00 -7.036008E+00 -2.490718E+00 -8.352414E+00 -3.501945E+00 -9.345868E+00 -4.380719E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -9.345868E+00 -4.380719E+00 -8.352414E+00 -3.501945E+00 -9.093766E+00 -4.158282E+00 -9.223771E+00 -4.270120E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -9.223771E+00 -4.270120E+00 -9.093766E+00 -4.158282E+00 -9.219150E+00 -4.264346E+00 -8.530966E+00 -3.651778E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -8.530966E+00 -3.651778E+00 -9.219150E+00 -4.264346E+00 -8.690373E+00 -3.785262E+00 -7.204424E+00 -2.604203E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -7.204424E+00 -2.604203E+00 -8.690373E+00 -3.785262E+00 -7.513640E+00 -2.833028E+00 -5.326721E+00 -1.426975E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -5.326721E+00 -1.426975E+00 -7.513640E+00 -2.833028E+00 -5.662215E+00 -1.607757E+00 -2.848381E+00 -4.093396E-01 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -2.848381E+00 -4.093396E-01 -5.662215E+00 -1.607757E+00 -3.025812E+00 -4.597241E-01 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -cmfd indices -1.000000E+01 -1.000000E+00 -1.000000E+00 -1.000000E+00 -k cmfd -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -1.170416E+00 -1.172966E+00 -1.165537E+00 -1.170979E+00 -1.161922E+00 -1.157523E+00 -1.158873E+00 -1.162877E+00 -1.167101E+00 -1.168130E+00 -1.170570E+00 -1.168115E+00 -1.174081E+00 -1.169458E+00 -1.167848E+00 -1.165116E+00 -cmfd entropy -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -3.203643E+00 -3.207943E+00 -3.213367E+00 -3.214360E+00 -3.219634E+00 -3.222232E+00 -3.221744E+00 -3.224544E+00 -3.225990E+00 -3.227769E+00 -3.227417E+00 -3.230728E+00 -3.231662E+00 -3.233316E+00 -3.233193E+00 -3.232564E+00 -cmfd balance -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -4.009062E-03 -4.431773E-03 -3.152666E-03 -3.510383E-03 -2.052089E-03 -2.068651E-03 -1.502427E-03 -1.589825E-03 -1.566020E-03 -1.219160E-03 -1.017888E-03 -9.771622E-04 -1.010120E-03 -1.073382E-03 -1.172758E-03 -9.827332E-04 -cmfd dominance ratio - 0.000E+00 - 0.000E+00 - 0.000E+00 - 0.000E+00 - 5.397E-01 - 5.425E-01 - 5.481E-01 - 5.473E-01 - 5.503E-01 - 5.502E-01 - 5.483E-01 - 5.520E-01 - 5.505E-01 - 3.216E-01 - 5.373E-01 - 5.517E-01 - 5.508E-01 - 5.524E-01 - 5.524E-01 - 5.523E-01 -cmfd openmc source comparison -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -6.959834E-03 -5.655657E-03 -3.886185E-03 -4.035116E-03 -3.043277E-03 -5.455475E-03 -4.515311E-03 -2.439840E-03 -2.114032E-03 -2.673132E-03 -2.431749E-03 -4.330928E-03 -3.404647E-03 -3.680298E-03 -3.309620E-03 -3.705541E-03 -cmfd source -4.697085E-02 -7.920706E-02 -1.107968E-01 -1.250932E-01 -1.383930E-01 -1.380648E-01 -1.246874E-01 -1.113705E-01 -8.203754E-02 -4.337882E-02 diff --git a/tests/test_cmfd_feed/test_cmfd_feed.py b/tests/test_cmfd_feed/test_cmfd_feed.py deleted file mode 100644 index 17bebf68c0..0000000000 --- a/tests/test_cmfd_feed/test_cmfd_feed.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import CMFDTestHarness - - -if __name__ == '__main__': - harness = CMFDTestHarness('statepoint.20.h5') - harness.main() diff --git a/tests/test_cmfd_nofeed/results_true.dat b/tests/test_cmfd_nofeed/results_true.dat deleted file mode 100644 index a3fbfb9549..0000000000 --- a/tests/test_cmfd_nofeed/results_true.dat +++ /dev/null @@ -1,1303 +0,0 @@ -k-combined: -1.167381E+00 9.433835E-03 -tally 1: -1.196137E+01 -1.442469E+01 -2.133858E+01 -4.600709E+01 -2.874353E+01 -8.287541E+01 -3.400779E+01 -1.158949E+02 -3.736442E+01 -1.398466E+02 -3.705095E+01 -1.376767E+02 -3.486173E+01 -1.220362E+02 -2.910935E+01 -8.507178E+01 -2.034762E+01 -4.156717E+01 -1.074969E+01 -1.160731E+01 -tally 2: -2.321994E+01 -2.726751E+01 -1.624000E+01 -1.334217E+01 -2.239367E+00 -2.607315E-01 -4.184801E+01 -8.813954E+01 -2.955600E+01 -4.401685E+01 -3.937924E+00 -7.877545E-01 -5.620224E+01 -1.589242E+02 -3.981400E+01 -7.983679E+01 -5.183337E+00 -1.367303E+00 -6.834724E+01 -2.342245E+02 -4.869600E+01 -1.189597E+02 -6.288549E+00 -1.997858E+00 -7.481522E+01 -2.802998E+02 -5.346500E+01 -1.431835E+02 -6.691123E+00 -2.252645E+00 -7.381412E+01 -2.733775E+02 -5.269700E+01 -1.393729E+02 -6.846095E+00 -2.360683E+00 -6.907776E+01 -2.396752E+02 -4.918500E+01 -1.215909E+02 -6.400076E+00 -2.073871E+00 -5.783261E+01 -1.680814E+02 -4.107800E+01 -8.480751E+01 -5.269220E+00 -1.404986E+00 -4.120212E+01 -8.516647E+01 -2.930300E+01 -4.310295E+01 -3.730803E+00 -7.015777E-01 -2.228419E+01 -2.504034E+01 -1.554100E+01 -1.217931E+01 -2.126451E+00 -2.315275E-01 -tally 3: -1.561100E+01 -1.233967E+01 -1.095984E+00 -6.181385E-02 -2.847800E+01 -4.088161E+01 -1.815209E+00 -1.669969E-01 -3.834200E+01 -7.408022E+01 -2.446116E+00 -3.017833E-01 -4.687600E+01 -1.102381E+02 -2.954924E+00 -4.412808E-01 -5.155100E+01 -1.331461E+02 -3.204713E+00 -5.178543E-01 -5.067700E+01 -1.289238E+02 -3.246709E+00 -5.326372E-01 -4.738600E+01 -1.128834E+02 -3.035962E+00 -4.640209E-01 -3.953600E+01 -7.858196E+01 -2.507574E+00 -3.186455E-01 -2.819300E+01 -3.991455E+01 -1.846612E+00 -1.725570E-01 -1.497500E+01 -1.131312E+01 -9.213727E-01 -4.422000E-02 -tally 4: -3.090000E+00 -4.810640E-01 -0.000000E+00 -0.000000E+00 -2.833000E+00 -4.078910E-01 -5.555000E+00 -1.551579E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -5.555000E+00 -1.551579E+00 -2.833000E+00 -4.078910E-01 -5.095000E+00 -1.310819E+00 -7.271000E+00 -2.659755E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -7.271000E+00 -2.659755E+00 -5.095000E+00 -1.310819E+00 -7.026000E+00 -2.486552E+00 -8.577000E+00 -3.703215E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -8.577000E+00 -3.703215E+00 -7.026000E+00 -2.486552E+00 -8.572000E+00 -3.680852E+00 -9.393000E+00 -4.422429E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -9.393000E+00 -4.422429E+00 -8.572000E+00 -3.680852E+00 -9.261000E+00 -4.304411E+00 -9.265000E+00 -4.305625E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -9.265000E+00 -4.305625E+00 -9.261000E+00 -4.304411E+00 -9.303000E+00 -4.350791E+00 -8.535000E+00 -3.659395E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -8.535000E+00 -3.659395E+00 -9.303000E+00 -4.350791E+00 -8.693000E+00 -3.799545E+00 -7.104000E+00 -2.544182E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -7.104000E+00 -2.544182E+00 -8.693000E+00 -3.799545E+00 -7.334000E+00 -2.700052E+00 -5.168000E+00 -1.344390E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -5.168000E+00 -1.344390E+00 -7.334000E+00 -2.700052E+00 -5.416000E+00 -1.471086E+00 -2.724000E+00 -3.745680E-01 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -2.724000E+00 -3.745680E-01 -5.416000E+00 -1.471086E+00 -2.960000E+00 -4.397840E-01 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -cmfd indices -1.000000E+01 -1.000000E+00 -1.000000E+00 -1.000000E+00 -k cmfd -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -1.170416E+00 -1.172572E+00 -1.171159E+00 -1.170281E+00 -1.159698E+00 -1.151967E+00 -1.146706E+00 -1.147136E+00 -1.152154E+00 -1.156980E+00 -1.156370E+00 -1.155974E+00 -1.155295E+00 -1.154881E+00 -1.153714E+00 -1.159485E+00 -cmfd entropy -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -3.203643E+00 -3.204555E+00 -3.210935E+00 -3.213980E+00 -3.219204E+00 -3.222234E+00 -3.226210E+00 -3.226808E+00 -3.224445E+00 -3.222460E+00 -3.222458E+00 -3.222447E+00 -3.220832E+00 -3.220841E+00 -3.221580E+00 -3.220523E+00 -cmfd balance -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -4.009062E-03 -4.869662E-03 -2.997290E-03 -2.711191E-03 -1.688329E-03 -1.855396E-03 -1.403979E-03 -1.398429E-03 -1.818398E-03 -1.761250E-03 -1.646649E-03 -1.480119E-03 -1.399559E-03 -1.400162E-03 -1.178363E-03 -1.292280E-03 -cmfd dominance ratio - 0.000E+00 - 0.000E+00 - 0.000E+00 - 0.000E+00 - 5.397E-01 - 5.405E-01 - 5.412E-01 - 5.428E-01 - 5.460E-01 - 4.530E-01 - 5.528E-01 - 5.531E-01 - 5.493E-01 - 5.468E-01 - 5.482E-01 - 5.487E-01 - 5.471E-01 - 5.465E-01 - 5.461E-01 - 5.443E-01 -cmfd openmc source comparison -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -6.959834E-03 -5.494667E-03 -4.076255E-03 -4.451119E-03 -3.035588E-03 -3.391772E-03 -1.907994E-03 -2.482495E-03 -2.994916E-03 -3.104682E-03 -2.309343E-03 -2.151358E-03 -2.348849E-03 -1.976731E-03 -2.080638E-03 -2.301327E-03 -cmfd source -4.638920E-02 -7.751172E-02 -1.056089E-01 -1.282509E-01 -1.396713E-01 -1.415740E-01 -1.323405E-01 -1.092839E-01 -7.981779E-02 -3.955174E-02 diff --git a/tests/test_cmfd_nofeed/test_cmfd_nofeed.py b/tests/test_cmfd_nofeed/test_cmfd_nofeed.py deleted file mode 100644 index 17bebf68c0..0000000000 --- a/tests/test_cmfd_nofeed/test_cmfd_nofeed.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import CMFDTestHarness - - -if __name__ == '__main__': - harness = CMFDTestHarness('statepoint.20.h5') - harness.main() diff --git a/tests/test_complex_cell/test_complex_cell.py b/tests/test_complex_cell/test_complex_cell.py deleted file mode 100755 index 0669165e25..0000000000 --- a/tests/test_complex_cell/test_complex_cell.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python - -import sys -sys.path.insert(0, '..') -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_confidence_intervals/test_confidence_intervals.py b/tests/test_confidence_intervals/test_confidence_intervals.py deleted file mode 100755 index b04fcc6eba..0000000000 --- a/tests/test_confidence_intervals/test_confidence_intervals.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_density/test_density.py b/tests/test_density/test_density.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_density/test_density.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_eigenvalue_genperbatch/test_eigenvalue_genperbatch.py b/tests/test_eigenvalue_genperbatch/test_eigenvalue_genperbatch.py deleted file mode 100644 index 59a60b63a4..0000000000 --- a/tests/test_eigenvalue_genperbatch/test_eigenvalue_genperbatch.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.7.h5') - harness.main() diff --git a/tests/test_eigenvalue_no_inactive/test_eigenvalue_no_inactive.py b/tests/test_eigenvalue_no_inactive/test_eigenvalue_no_inactive.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_eigenvalue_no_inactive/test_eigenvalue_no_inactive.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_energy_grid/test_energy_grid.py b/tests/test_energy_grid/test_energy_grid.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_energy_grid/test_energy_grid.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_filter_mesh/results_true.dat b/tests/test_filter_mesh/results_true.dat deleted file mode 100644 index ac3439da50..0000000000 --- a/tests/test_filter_mesh/results_true.dat +++ /dev/null @@ -1 +0,0 @@ -804d161cb8eae506d3247a533d122f44a01d3cedd566b3c65c71a0b51326dd9b97f8bbf45af7304b500476f3f854d91b10ccad94122d15f23641b05b835fada6 \ No newline at end of file diff --git a/tests/test_infinite_cell/test_infinite_cell.py b/tests/test_infinite_cell/test_infinite_cell.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_infinite_cell/test_infinite_cell.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_lattice/test_lattice.py b/tests/test_lattice/test_lattice.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_lattice/test_lattice.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_lattice_hex/test_lattice_hex.py b/tests/test_lattice_hex/test_lattice_hex.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_lattice_hex/test_lattice_hex.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_lattice_mixed/test_lattice_mixed.py b/tests/test_lattice_mixed/test_lattice_mixed.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_lattice_mixed/test_lattice_mixed.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_lattice_multiple/test_lattice_multiple.py b/tests/test_lattice_multiple/test_lattice_multiple.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_lattice_multiple/test_lattice_multiple.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_mg_basic/test_mg_basic.py b/tests/test_mg_basic/test_mg_basic.py deleted file mode 100644 index 21871efd72..0000000000 --- a/tests/test_mg_basic/test_mg_basic.py +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import PyAPITestHarness -from openmc.examples import slab_mg - - -if __name__ == '__main__': - model = slab_mg() - harness = PyAPITestHarness('statepoint.10.h5', model) - harness.main() diff --git a/tests/test_particle_restart_eigval/test_particle_restart_eigval.py b/tests/test_particle_restart_eigval/test_particle_restart_eigval.py deleted file mode 100644 index 1ebbd3ea53..0000000000 --- a/tests/test_particle_restart_eigval/test_particle_restart_eigval.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import ParticleRestartTestHarness - - -if __name__ == '__main__': - harness = ParticleRestartTestHarness('particle_10_1030.h5') - harness.main() diff --git a/tests/test_particle_restart_fixed/test_particle_restart_fixed.py b/tests/test_particle_restart_fixed/test_particle_restart_fixed.py deleted file mode 100644 index df0398c6eb..0000000000 --- a/tests/test_particle_restart_fixed/test_particle_restart_fixed.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import ParticleRestartTestHarness - - -if __name__ == '__main__': - harness = ParticleRestartTestHarness('particle_7_144.h5') - harness.main() diff --git a/tests/test_ptables_off/test_ptables_off.py b/tests/test_ptables_off/test_ptables_off.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_ptables_off/test_ptables_off.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_quadric_surfaces/test_quadric_surfaces.py b/tests/test_quadric_surfaces/test_quadric_surfaces.py deleted file mode 100755 index b04fcc6eba..0000000000 --- a/tests/test_quadric_surfaces/test_quadric_surfaces.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_reflective_plane/test_reflective_plane.py b/tests/test_reflective_plane/test_reflective_plane.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_reflective_plane/test_reflective_plane.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_rotation/test_rotation.py b/tests/test_rotation/test_rotation.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_rotation/test_rotation.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_score_current/results_true.dat b/tests/test_score_current/results_true.dat deleted file mode 100644 index 75d61b7188..0000000000 --- a/tests/test_score_current/results_true.dat +++ /dev/null @@ -1 +0,0 @@ -4675d5101f4f829369c39cb33d654430836b934ab07c165777ba6e214bdf3a698b8082f4f9bb9e78f1f0e495b30ea02cf9b3d14622c59915d818d678a1e5b7b1 \ No newline at end of file diff --git a/tests/test_score_current/test_score_current.py b/tests/test_score_current/test_score_current.py deleted file mode 100644 index ea5886a639..0000000000 --- a/tests/test_score_current/test_score_current.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import HashedTestHarness - - -if __name__ == '__main__': - harness = HashedTestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_seed/test_seed.py b/tests/test_seed/test_seed.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_seed/test_seed.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_sourcepoint_restart/test_sourcepoint_restart.py b/tests/test_sourcepoint_restart/test_sourcepoint_restart.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_sourcepoint_restart/test_sourcepoint_restart.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_survival_biasing/test_survival_biasing.py b/tests/test_survival_biasing/test_survival_biasing.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_survival_biasing/test_survival_biasing.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_tally_assumesep/test_tally_assumesep.py b/tests/test_tally_assumesep/test_tally_assumesep.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_tally_assumesep/test_tally_assumesep.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_tally_nuclides/test_tally_nuclides.py b/tests/test_tally_nuclides/test_tally_nuclides.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_tally_nuclides/test_tally_nuclides.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_trace/test_trace.py b/tests/test_trace/test_trace.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_trace/test_trace.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_translation/test_translation.py b/tests/test_translation/test_translation.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_translation/test_translation.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_trigger_batch_interval/test_trigger_batch_interval.py b/tests/test_trigger_batch_interval/test_trigger_batch_interval.py deleted file mode 100644 index fb88ada001..0000000000 --- a/tests/test_trigger_batch_interval/test_trigger_batch_interval.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.15.h5') - harness.main() diff --git a/tests/test_trigger_no_batch_interval/test_trigger_no_batch_interval.py b/tests/test_trigger_no_batch_interval/test_trigger_no_batch_interval.py deleted file mode 100644 index fb88ada001..0000000000 --- a/tests/test_trigger_no_batch_interval/test_trigger_no_batch_interval.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.15.h5') - harness.main() diff --git a/tests/test_trigger_no_status/test_trigger_no_status.py b/tests/test_trigger_no_status/test_trigger_no_status.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_trigger_no_status/test_trigger_no_status.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_trigger_tallies/test_trigger_tallies.py b/tests/test_trigger_tallies/test_trigger_tallies.py deleted file mode 100644 index fb88ada001..0000000000 --- a/tests/test_trigger_tallies/test_trigger_tallies.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.15.h5') - harness.main() diff --git a/tests/test_uniform_fs/test_uniform_fs.py b/tests/test_uniform_fs/test_uniform_fs.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_uniform_fs/test_uniform_fs.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_universe/test_universe.py b/tests/test_universe/test_universe.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_universe/test_universe.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_void/test_void.py b/tests/test_void/test_void.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_void/test_void.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_volume_calc/results_true.dat b/tests/test_volume_calc/results_true.dat deleted file mode 100644 index 8eb2a61acf..0000000000 --- a/tests/test_volume_calc/results_true.dat +++ /dev/null @@ -1,30 +0,0 @@ -Volume calculation 0 -Domain 1: 31.4693 +/- 0.0721 cm^3 -Domain 2: 2.0933 +/- 0.0310 cm^3 -Domain 3: 2.0486 +/- 0.0307 cm^3 - Cell Nuclide Atoms Uncertainty -0 1 U235 3.481769e+23 7.979991e+20 -1 1 Mo99 3.481769e+22 7.979991e+19 -2 2 H1 1.399770e+23 2.072914e+21 -3 2 O16 6.998852e+22 1.036457e+21 -4 2 B10 6.998852e+18 1.036457e+17 -5 3 H1 1.369920e+23 2.051689e+21 -6 3 O16 6.849599e+22 1.025844e+21 -7 3 B10 6.849599e+18 1.025844e+17 -Volume calculation 1 -Domain 1: 4.1419 +/- 0.0426 cm^3 -Domain 2: 31.4693 +/- 0.0721 cm^3 - Material Nuclide Atoms Uncertainty -0 1 H1 2.769690e+23 2.850067e+21 -1 1 O16 1.384845e+23 1.425034e+21 -2 1 B10 1.384845e+19 1.425034e+17 -3 2 U235 3.481769e+23 7.979991e+20 -4 2 Mo99 3.481769e+22 7.979991e+19 -Volume calculation 2 -Domain 0: 35.6112 +/- 0.0664 cm^3 - Universe Nuclide Atoms Uncertainty -0 0 H1 2.769690e+23 2.850067e+21 -1 0 O16 1.384845e+23 1.425034e+21 -2 0 B10 1.384845e+19 1.425034e+17 -3 0 U235 3.481769e+23 7.979991e+20 -4 0 Mo99 3.481769e+22 7.979991e+19 diff --git a/tests/testing_harness.py b/tests/testing_harness.py index 428bf5c4b7..fb07575ce7 100644 --- a/tests/testing_harness.py +++ b/tests/testing_harness.py @@ -1,5 +1,3 @@ -from __future__ import print_function - from difflib import unified_diff import filecmp import glob @@ -10,30 +8,21 @@ import shutil import sys import numpy as np - -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) import openmc from openmc.examples import pwr_core +from tests.regression_tests import config + class TestHarness(object): """General class for running OpenMC regression tests.""" def __init__(self, statepoint_name): self._sp_name = statepoint_name - self.parser = OptionParser() - self.parser.add_option('--exe', dest='exe', default='openmc') - self.parser.add_option('--mpi_exec', dest='mpi_exec', default=None) - self.parser.add_option('--mpi_np', dest='mpi_np', default='2') - self.parser.add_option('--update', dest='update', action='store_true', - default=False) - self._opts = None - self._args = None def main(self): """Accept commandline arguments and either run or update tests.""" - (self._opts, self._args) = self.parser.parse_args() - if self._opts.update: + if config['update']: self.update_results() else: self.execute_test() @@ -61,15 +50,11 @@ class TestHarness(object): self._cleanup() def _run_openmc(self): - if self._opts.mpi_exec is not None: - returncode = openmc.run( - openmc_exec=self._opts.exe, - mpi_args=[self._opts.mpi_exec, '-n', self._opts.mpi_np]) - + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(openmc_exec=config['exe'], mpi_args=mpi_args) else: - returncode = openmc.run(openmc_exec=self._opts.exe) - - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.run(openmc_exec=config['exe']) def _test_output_created(self): """Make sure statepoint.* and tallies.out have been created.""" @@ -90,7 +75,7 @@ class TestHarness(object): # Write out k-combined. outstr = 'k-combined:\n' form = '{0:12.6E} {1:12.6E}\n' - outstr += form.format(sp.k_combined[0], sp.k_combined[1]) + outstr += form.format(sp.k_combined.n, sp.k_combined.s) # Write out tally data. for i, tally_ind in enumerate(sp.tallies): @@ -142,7 +127,7 @@ class HashedTestHarness(TestHarness): def _get_results(self): """Digest info in the statepoint and return as a string.""" - return super(HashedTestHarness, self)._get_results(True) + return super()._get_results(True) class CMFDTestHarness(TestHarness): @@ -152,7 +137,7 @@ class CMFDTestHarness(TestHarness): """Digest info in the statepoint and return as a string.""" # Write out the eigenvalue and tallies. - outstr = super(CMFDTestHarness, self)._get_results() + outstr = super()._get_results() # Read the statepoint file. statepoint = glob.glob(self._sp_name)[0] @@ -184,18 +169,16 @@ class ParticleRestartTestHarness(TestHarness): def _run_openmc(self): # Set arguments - args = {'openmc_exec': self._opts.exe} - if self._opts.mpi_exec is not None: - args['mpi_args'] = [self._opts.mpi_exec, '-n', self._opts.mpi_np] + args = {'openmc_exec': config['exe']} + if config['mpi']: + args['mpi_args'] = [config['mpiexec'], '-n', config['mpi_np']] # Initial run - returncode = openmc.run(**args) - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.run(**args) # Run particle restart args.update({'restart_file': self._sp_name}) - returncode = openmc.run(**args) - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.run(**args) def _test_output_created(self): """Make sure the restart file has been created.""" @@ -237,9 +220,7 @@ class ParticleRestartTestHarness(TestHarness): class PyAPITestHarness(TestHarness): def __init__(self, statepoint_name, model=None): - super(PyAPITestHarness, self).__init__(statepoint_name) - self.parser.add_option('-b', '--build-inputs', dest='build_only', - action='store_true', default=False) + super().__init__(statepoint_name) if model is None: self._model = pwr_core() else: @@ -249,10 +230,9 @@ class PyAPITestHarness(TestHarness): def main(self): """Accept commandline arguments and either run or update tests.""" - (self._opts, self._args) = self.parser.parse_args() - if self._opts.build_only: + if config['build_inputs']: self._build_inputs() - elif self._opts.update: + elif config['update']: self.update_results() else: self.execute_test() @@ -320,7 +300,7 @@ class PyAPITestHarness(TestHarness): def _cleanup(self): """Delete XMLs, statepoints, tally, and test files.""" - super(PyAPITestHarness, self)._cleanup() + super()._cleanup() output = ['materials.xml', 'geometry.xml', 'settings.xml', 'tallies.xml', 'plots.xml', 'inputs_test.dat'] for f in output: @@ -331,4 +311,4 @@ class PyAPITestHarness(TestHarness): class HashedPyAPITestHarness(PyAPITestHarness): def _get_results(self): """Digest info in the statepoint and return as a string.""" - return super(HashedPyAPITestHarness, self)._get_results(True) + return super()._get_results(True) diff --git a/tests/unit_tests/__init__.py b/tests/unit_tests/__init__.py new file mode 100644 index 0000000000..59a520c12a --- /dev/null +++ b/tests/unit_tests/__init__.py @@ -0,0 +1,9 @@ +import numpy as np +import pytest + + +def assert_unbounded(obj): + """Assert that a region/cell is unbounded.""" + ll, ur = obj.bounding_box + assert ll == pytest.approx((-np.inf, -np.inf, -np.inf)) + assert ur == pytest.approx((np.inf, np.inf, np.inf)) diff --git a/tests/unit_tests/conftest.py b/tests/unit_tests/conftest.py new file mode 100644 index 0000000000..1434eaf3b4 --- /dev/null +++ b/tests/unit_tests/conftest.py @@ -0,0 +1,62 @@ +import openmc +import pytest + + +@pytest.fixture(scope='module') +def uo2(): + m = openmc.Material(material_id=100, name='UO2') + m.add_nuclide('U235', 1.0) + m.add_nuclide('O16', 2.0) + m.set_density('g/cm3', 10.0) + m.depletable = True + return m + + +@pytest.fixture(scope='module') +def water(): + m = openmc.Material(name='light water') + m.add_nuclide('H1', 2.0) + m.add_nuclide('O16', 1.0) + m.set_density('g/cm3', 1.0) + m.add_s_alpha_beta('c_H_in_H2O') + return m + + +@pytest.fixture(scope='module') +def sphere_model(): + model = openmc.model.Model() + m = openmc.Material() + m.add_nuclide('U235', 1.0) + m.set_density('g/cm3', 1.0) + model.materials.append(m) + + sph = openmc.Sphere(boundary_type='vacuum') + c = openmc.Cell(fill=m, region=-sph) + model.geometry.root_universe = openmc.Universe(cells=[c]) + + model.settings.particles = 100 + model.settings.batches = 10 + model.settings.run_mode = 'fixed source' + model.settings.source = openmc.Source(space=openmc.stats.Point()) + return model + + +@pytest.fixture +def cell_with_lattice(): + m_inside = [openmc.Material(), openmc.Material(), None, openmc.Material()] + m_outside = openmc.Material() + + cyl = openmc.ZCylinder(R=1.0) + inside_cyl = openmc.Cell(fill=m_inside, region=-cyl) + outside_cyl = openmc.Cell(fill=m_outside, region=+cyl) + univ = openmc.Universe(cells=[inside_cyl, outside_cyl]) + + lattice = openmc.RectLattice(name='My Lattice') + lattice.lower_left = (-4.0, -4.0) + lattice.pitch = (4.0, 4.0) + lattice.universes = [[univ, univ], [univ, univ]] + main_cell = openmc.Cell(fill=lattice) + + return ([inside_cyl, outside_cyl, main_cell], + [m_inside[0], m_inside[1], m_inside[3], m_outside], + univ, lattice) diff --git a/tests/unit_tests/test_capi.py b/tests/unit_tests/test_capi.py index ba9ac5c9e0..8bc6c3d15c 100644 --- a/tests/unit_tests/test_capi.py +++ b/tests/unit_tests/test_capi.py @@ -1,6 +1,4 @@ -#!/usr/bin/env python - -from collections import Mapping +from collections.abc import Mapping import os import numpy as np @@ -8,11 +6,15 @@ import pytest import openmc import openmc.capi +from tests import cdtemp + @pytest.fixture(scope='module') def pincell_model(): """Set up a model to test with and delete files when done""" + openmc.reset_auto_ids() pincell = openmc.examples.pwr_pin_cell() + pincell.settings.verbosity = 1 # Add a tally filter1 = openmc.MaterialFilter(pincell.materials) @@ -23,17 +25,10 @@ def pincell_model(): mat_tally.scores = ['total', 'elastic', '(n,gamma)'] pincell.tallies.append(mat_tally) - # Write XML files - pincell.export_to_xml() - - yield - - # Delete generated files - files = ['geometry.xml', 'materials.xml', 'settings.xml', 'tallies.xml', - 'statepoint.10.h5', 'summary.h5', 'test_sp.h5'] - for f in files: - if os.path.exists(f): - os.remove(f) + # Write XML files in tmpdir + with cdtemp(): + pincell.export_to_xml() + yield @pytest.fixture(scope='module') @@ -228,6 +223,19 @@ def test_by_batch(capi_run): openmc.capi.simulation_finalize() +def test_reproduce_keff(capi_init): + # Get k-effective after run + openmc.capi.hard_reset() + openmc.capi.run() + keff0 = openmc.capi.keff() + + # Reset, run again, and get k-effective again. they should match + openmc.capi.hard_reset() + openmc.capi.run() + keff1 = openmc.capi.keff() + assert keff0 == pytest.approx(keff1) + + def test_find_cell(capi_init): cell, instance = openmc.capi.find_cell((0., 0., 0.)) assert cell is openmc.capi.cells[1] diff --git a/tests/unit_tests/test_cell.py b/tests/unit_tests/test_cell.py new file mode 100644 index 0000000000..d01d94a324 --- /dev/null +++ b/tests/unit_tests/test_cell.py @@ -0,0 +1,168 @@ +import xml.etree. ElementTree as ET + +import numpy as np +import openmc +import pytest + +from tests.unit_tests import assert_unbounded + + +def test_contains(): + # Cell with specified region + s = openmc.XPlane() + c = openmc.Cell(region=+s) + assert (1.0, 0.0, 0.0) in c + assert (-1.0, 0.0, 0.0) not in c + + # Cell with no region + c = openmc.Cell() + assert (10.0, -4., 2.0) in c + + +def test_repr(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + repr(cells[0]) # cell with distributed materials + repr(cells[1]) # cell with material + repr(cells[2]) # cell with lattice + + # Empty cell + c = openmc.Cell() + repr(c) + + +def test_bounding_box(): + zcyl = openmc.ZCylinder() + c = openmc.Cell(region=-zcyl) + ll, ur = c.bounding_box + assert ll == pytest.approx((-1., -1., -np.inf)) + assert ur == pytest.approx((1., 1., np.inf)) + + # Cell with no region specified + c = openmc.Cell() + assert_unbounded(c) + + +def test_clone(): + m = openmc.Material() + cyl = openmc.ZCylinder() + c = openmc.Cell(fill=m, region=-cyl) + c.temperature = 650. + + c2 = c.clone() + assert c2.id != c.id + assert c2.fill != c.fill + assert c2.region != c.region + assert c2.temperature == c.temperature + + +def test_temperature(cell_with_lattice): + # Make sure temperature propagates through universes + m = openmc.Material() + s = openmc.XPlane() + c1 = openmc.Cell(fill=m, region=+s) + c2 = openmc.Cell(fill=m, region=-s) + u1 = openmc.Universe(cells=[c1, c2]) + c = openmc.Cell(fill=u1) + + c.temperature = 400.0 + assert c1.temperature == 400.0 + assert c2.temperature == 400.0 + with pytest.raises(ValueError): + c.temperature = -100. + + # distributed temperature + cells, _, _, _ = cell_with_lattice + c = cells[0] + c.temperature = (300., 600., 900.) + + +def test_rotation(): + u = openmc.Universe() + c = openmc.Cell(fill=u) + c.rotation = (180.0, 0.0, 0.0) + assert np.allclose(c.rotation_matrix, [ + [1., 0., 0.], + [0., -1., 0.], + [0., 0., -1.] + ]) + + c.rotation = (0.0, 90.0, 0.0) + assert np.allclose(c.rotation_matrix, [ + [0., 0., -1.], + [0., 1., 0.], + [1., 0., 0.] + ]) + + +def test_get_nuclides(uo2): + c = openmc.Cell(fill=uo2) + nucs = c.get_nuclides() + assert nucs == ['U235', 'O16'] + + +def test_nuclide_densities(uo2): + c = openmc.Cell(fill=uo2) + expected_nucs = ['U235', 'O16'] + expected_density = [1.0, 2.0] + tuples = list(c.get_nuclide_densities().values()) + for nuc, density, t in zip(expected_nucs, expected_density, tuples): + assert nuc == t[0] + assert density == t[1] + + # Empty cell + c = openmc.Cell() + assert not c.get_nuclide_densities() + + +def test_get_all_universes(cell_with_lattice): + # Cell with nested universes + c1 = openmc.Cell() + u1 = openmc.Universe(cells=[c1]) + c2 = openmc.Cell(fill=u1) + u2 = openmc.Universe(cells=[c2]) + c3 = openmc.Cell(fill=u2) + univs = set(c3.get_all_universes().values()) + assert not (univs ^ {u1, u2}) + + # Cell with lattice + cells, mats, univ, lattice = cell_with_lattice + univs = set(cells[-1].get_all_universes().values()) + assert not (univs ^ {univ}) + + +def test_get_all_materials(cell_with_lattice): + # Normal cell + m = openmc.Material() + c = openmc.Cell(fill=m) + test_mats = set(c.get_all_materials().values()) + assert not(test_mats ^ {m}) + + # Cell filled with distributed materials + cells, mats, univ, lattice = cell_with_lattice + c = cells[0] + test_mats = set(c.get_all_materials().values()) + assert not (test_mats ^ set(m for m in c.fill if m is not None)) + + # Cell filled with universe + c = cells[-1] + test_mats = set(c.get_all_materials().values()) + assert not (test_mats ^ set(mats)) + + +def test_to_xml_element(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + + c = cells[-1] + root = ET.Element('geometry') + elem = c.create_xml_subelement(root) + assert elem.tag == 'cell' + assert elem.get('id') == str(c.id) + assert elem.get('region') is None + surf_elem = root.find('surface') + assert surf_elem.get('id') == str(cells[0].region.surface.id) + + c = cells[0] + c.temperature = 900.0 + elem = c.create_xml_subelement(root) + assert elem.get('region') == str(c.region) + assert elem.get('temperature') == str(c.temperature) diff --git a/tests/unit_tests/test_data_misc.py b/tests/unit_tests/test_data_misc.py index aeeb04c0fb..34686b567f 100644 --- a/tests/unit_tests/test_data_misc.py +++ b/tests/unit_tests/test_data_misc.py @@ -48,3 +48,44 @@ def test_thin(): x_thin, y_thin = openmc.data.thin(x, y) f = openmc.data.Tabulated1D(x_thin, y_thin) assert f(1.0) == pytest.approx(np.sin(1.0), 0.001) + + +def test_atomic_mass(): + assert openmc.data.atomic_mass('H1') == 1.00782503223 + assert openmc.data.atomic_mass('U235') == 235.043930131 + with pytest.raises(KeyError): + openmc.data.atomic_mass('U100') + + +def test_atomic_weight(): + assert openmc.data.atomic_weight('C') == 12.011115164862904 + with pytest.raises(ValueError): + openmc.data.atomic_weight('Qt') + + +def test_water_density(): + dens = openmc.data.water_density + # These test values are from IAPWS R7-97(2012). They are actually specific + # volumes so they need to be inverted. They also need to be divided by 1000 + # to convert from [kg / m^3] to [g / cm^3]. + assert dens(300.0, 3.0) == pytest.approx(1e-3/0.100215168e-2, 1e-6) + assert dens(300.0, 80.0) == pytest.approx(1e-3/0.971180894e-3, 1e-6) + assert dens(500.0, 3.0) == pytest.approx(1e-3/0.120241800e-2, 1e-6) + + +def test_gnd_name(): + assert openmc.data.gnd_name(1, 1) == 'H1' + assert openmc.data.gnd_name(40, 90) == ('Zr90') + assert openmc.data.gnd_name(95, 242, 0) == ('Am242') + assert openmc.data.gnd_name(95, 242, 1) == ('Am242_m1') + assert openmc.data.gnd_name(95, 242, 10) == ('Am242_m10') + + +def test_zam(): + assert openmc.data.zam('H1') == (1, 1, 0) + assert openmc.data.zam('Zr90') == (40, 90, 0) + assert openmc.data.zam('Am242') == (95, 242, 0) + assert openmc.data.zam('Am242_m1') == (95, 242, 1) + assert openmc.data.zam('Am242_m10') == (95, 242, 10) + with pytest.raises(ValueError): + openmc.data.zam('garbage') diff --git a/tests/unit_tests/test_data_multipole.py b/tests/unit_tests/test_data_multipole.py index dc30677e80..a1cc5bc02c 100644 --- a/tests/unit_tests/test_data_multipole.py +++ b/tests/unit_tests/test_data_multipole.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - import os import numpy as np @@ -7,6 +5,11 @@ import pytest import openmc.data +pytestmark = pytest.mark.skipif( + 'OPENMC_MULTIPOLE_LIBRARY' not in os.environ, + reason='OPENMC_MULTIPOLE_LIBRARY environment variable must be set') + + @pytest.fixture(scope='module') def u235(): directory = os.environ['OPENMC_MULTIPOLE_LIBRARY'] @@ -14,6 +17,13 @@ def u235(): return openmc.data.WindowedMultipole.from_hdf5(filename) +@pytest.fixture(scope='module') +def u234(): + directory = os.environ['OPENMC_MULTIPOLE_LIBRARY'] + filename = os.path.join(directory, '092234.h5') + return openmc.data.WindowedMultipole.from_hdf5(filename) + + @pytest.fixture(scope='module') def fe56(): directory = os.environ['OPENMC_MULTIPOLE_LIBRARY'] @@ -21,8 +31,8 @@ def fe56(): return openmc.data.WindowedMultipole.from_hdf5(filename) -def test_evaluate(u235): - """Make sure multipole object can be called.""" +def test_evaluate_rm(u235): + """Make sure a Reich-Moore multipole object can be called.""" energies = [1e-3, 1.0, 10.0, 50.] total, absorption, fission = u235(energies, 0.0) assert total[1] == pytest.approx(90.64895383) @@ -30,6 +40,15 @@ def test_evaluate(u235): assert total[1] == pytest.approx(91.12534964) +def test_evaluate_mlbw(u234): + """Make sure a Multi-Level Breit-Wigner multipole object can be called.""" + energies = [1e-3, 1.0, 10.0, 50.] + total, absorption, fission = u234(energies, 0.0) + assert total[3] == pytest.approx(15.02827953) + total, absorption, fission = u234(energies, 300.0) + assert total[3] == pytest.approx(15.08269143) + + def test_high_l(fe56): """Test a nuclide (Fe56) with a high l-value (4).""" energies = [1e-3, 1.0, 10.0, 1e3, 1e5] @@ -37,3 +56,9 @@ def test_high_l(fe56): assert total[0] == pytest.approx(25.072619556789267) total, absorption, fission = fe56(energies, 300.0) assert total[0] == pytest.approx(27.85535792368082) + + +def test_export_to_hdf5(tmpdir, u235): + filename = str(tmpdir.join('092235.h5')) + u235.export_to_hdf5(filename) + assert os.path.exists(filename) diff --git a/tests/unit_tests/test_data_neutron.py b/tests/unit_tests/test_data_neutron.py index e314d32a42..5713bfbc57 100644 --- a/tests/unit_tests/test_data_neutron.py +++ b/tests/unit_tests/test_data_neutron.py @@ -213,6 +213,7 @@ def test_export_to_hdf5(tmpdir, pu239, gd154): with pytest.raises(NotImplementedError): gd154.export_to_hdf5('gd154.h5') + def test_slbw(xe135): res = xe135.resonances assert isinstance(res, openmc.data.Resonances) diff --git a/tests/unit_tests/test_deplete_atom_number.py b/tests/unit_tests/test_deplete_atom_number.py new file mode 100644 index 0000000000..4cc9207ca9 --- /dev/null +++ b/tests/unit_tests/test_deplete_atom_number.py @@ -0,0 +1,147 @@ +""" Tests for the AtomNumber class """ + +import numpy as np +from openmc.deplete import atom_number + + +def test_indexing(): + """Tests the __getitem__ and __setitem__ routines simultaneously.""" + + local_mats = ["10000", "10001"] + nuclides = ["U238", "U235", "U234"] + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) + + number["10000", "U238"] = 1.0 + number["10001", "U238"] = 2.0 + number["10000", "U235"] = 3.0 + number["10001", "U235"] = 4.0 + + # String indexing + assert number["10000", "U238"] == 1.0 + assert number["10001", "U238"] == 2.0 + assert number["10000", "U235"] == 3.0 + assert number["10001", "U235"] == 4.0 + + # Int indexing + assert number[0, 0] == 1.0 + assert number[1, 0] == 2.0 + assert number[0, 1] == 3.0 + assert number[1, 1] == 4.0 + + number[0, 0] = 5.0 + + assert number[0, 0] == 5.0 + assert number["10000", "U238"] == 5.0 + + +def test_properties(): + """Test properties. """ + local_mats = ["10000", "10001"] + nuclides = ["U238", "U235", "Gd157"] + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) + + assert list(number.materials) == ["10000", "10001"] + assert number.n_nuc == 3 + assert list(number.nuclides) == ["U238", "U235", "Gd157"] + assert number.burnable_nuclides == ["U238", "U235"] + + +def test_density_indexing(): + """Tests the get and set_atom_density routines simultaneously.""" + + local_mats = ["10000", "10001", "10002"] + nuclides = ["U238", "U235", "U234"] + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) + + number.set_atom_density("10000", "U238", 1.0) + number.set_atom_density("10001", "U238", 2.0) + number.set_atom_density("10002", "U238", 3.0) + number.set_atom_density("10000", "U235", 4.0) + number.set_atom_density("10001", "U235", 5.0) + number.set_atom_density("10002", "U235", 6.0) + number.set_atom_density("10000", "U234", 7.0) + number.set_atom_density("10001", "U234", 8.0) + number.set_atom_density("10002", "U234", 9.0) + + # String indexing + assert number.get_atom_density("10000", "U238") == 1.0 + assert number.get_atom_density("10001", "U238") == 2.0 + assert number.get_atom_density("10002", "U238") == 3.0 + assert number.get_atom_density("10000", "U235") == 4.0 + assert number.get_atom_density("10001", "U235") == 5.0 + assert number.get_atom_density("10002", "U235") == 6.0 + assert number.get_atom_density("10000", "U234") == 7.0 + assert number.get_atom_density("10001", "U234") == 8.0 + assert number.get_atom_density("10002", "U234") == 9.0 + + # Int indexing + assert number.get_atom_density(0, 0) == 1.0 + assert number.get_atom_density(1, 0) == 2.0 + assert number.get_atom_density(2, 0) == 3.0 + assert number.get_atom_density(0, 1) == 4.0 + assert number.get_atom_density(1, 1) == 5.0 + assert number.get_atom_density(2, 1) == 6.0 + assert number.get_atom_density(0, 2) == 7.0 + assert number.get_atom_density(1, 2) == 8.0 + assert number.get_atom_density(2, 2) == 9.0 + + + number.set_atom_density(0, 0, 5.0) + assert number.get_atom_density(0, 0) == 5.0 + + # Verify volume is used correctly + assert number[0, 0] == 5.0 * 0.38 + assert number[1, 0] == 2.0 * 0.21 + assert number[2, 0] == 3.0 * 1.0 + assert number[0, 1] == 4.0 * 0.38 + assert number[1, 1] == 5.0 * 0.21 + assert number[2, 1] == 6.0 * 1.0 + assert number[0, 2] == 7.0 * 0.38 + assert number[1, 2] == 8.0 * 0.21 + assert number[2, 2] == 9.0 * 1.0 + + +def test_get_mat_slice(): + """Tests getting slices.""" + + local_mats = ["10000", "10001", "10002"] + nuclides = ["U238", "U235", "U234"] + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) + + number.number = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) + + sl = number.get_mat_slice(0) + + np.testing.assert_array_equal(sl, np.array([1.0, 2.0])) + + sl = number.get_mat_slice("10000") + + np.testing.assert_array_equal(sl, np.array([1.0, 2.0])) + + +def test_set_mat_slice(): + """Tests getting slices.""" + + local_mats = ["10000", "10001", "10002"] + nuclides = ["U238", "U235", "U234"] + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) + + number.set_mat_slice(0, [1.0, 2.0]) + + assert number[0, 0] == 1.0 + assert number[0, 1] == 2.0 + + number.set_mat_slice("10000", [3.0, 4.0]) + + assert number[0, 0] == 3.0 + assert number[0, 1] == 4.0 diff --git a/tests/unit_tests/test_deplete_cecm.py b/tests/unit_tests/test_deplete_cecm.py new file mode 100644 index 0000000000..466a2eec74 --- /dev/null +++ b/tests/unit_tests/test_deplete_cecm.py @@ -0,0 +1,37 @@ +"""Regression tests for openmc.deplete.integrator.cecm algorithm. + +These tests integrate a simple test problem described in dummy_geometry.py. +""" + +from pytest import approx +import openmc.deplete + +from tests import dummy_operator + + +def test_cecm(run_in_tmpdir): + """Integral regression test of integrator algorithm using CE/CM.""" + + op = dummy_operator.DummyOperator() + op.output_dir = "test_integrator_regression" + + # Perform simulation using the MCNPX/MCNP6 algorithm + dt = [0.75, 0.75] + power = 1.0 + openmc.deplete.cecm(op, dt, power, print_out=False) + + # Load the files + res = openmc.deplete.ResultsList(op.output_dir / "depletion_results.h5") + + _, y1 = res.get_atoms("1", "1") + _, y2 = res.get_atoms("1", "2") + + # Mathematica solution + s1 = [1.86872629872102, 1.395525772416039] + s2 = [2.18097439443550, 2.69429754646747] + + assert y1[1] == approx(s1[0]) + assert y2[1] == approx(s1[1]) + + assert y1[2] == approx(s2[0]) + assert y2[2] == approx(s2[1]) diff --git a/tests/unit_tests/test_deplete_chain.py b/tests/unit_tests/test_deplete_chain.py new file mode 100644 index 0000000000..1fe83ad98a --- /dev/null +++ b/tests/unit_tests/test_deplete_chain.py @@ -0,0 +1,233 @@ +"""Tests for openmc.deplete.Chain class.""" + +from collections.abc import Mapping +import os +from pathlib import Path + +import numpy as np +from openmc.data import zam, ATOMIC_SYMBOL +from openmc.deplete import comm, Chain, reaction_rates, nuclide +import pytest + +from tests import cdtemp + +_ENDF_DATA = Path(os.environ['OPENMC_ENDF_DATA']) + +_TEST_CHAIN = """\ + + + + + + + + + + + + + + + + 0.0253 + + A B + 0.0292737 0.002566345 + + + + +""" + + +@pytest.fixture(scope='module') +def simple_chain(): + with cdtemp(): + with open('chain_test.xml', 'w') as fh: + fh.write(_TEST_CHAIN) + yield Chain.from_xml('chain_test.xml') + + +def test_init(): + """Test depletion chain initialization.""" + chain = Chain() + + assert isinstance(chain.nuclides, list) + assert isinstance(chain.nuclide_dict, Mapping) + + +def test_len(): + """Test depletion chain length.""" + chain = Chain() + chain.nuclides = ["NucA", "NucB", "NucC"] + + assert len(chain) == 3 + + +def test_from_endf(): + """Test depletion chain building from ENDF files""" + decay_data = (_ENDF_DATA / 'decay').glob('*.endf') + fpy_data = (_ENDF_DATA / 'nfy').glob('*.endf') + neutron_data = (_ENDF_DATA / 'neutrons').glob('*.endf') + chain = Chain.from_endf(decay_data, fpy_data, neutron_data) + + assert len(chain) == len(chain.nuclides) == len(chain.nuclide_dict) == 3820 + for nuc in chain.nuclides: + assert nuc == chain[nuc.name] + + +def test_from_xml(simple_chain): + """Read chain_test.xml and ensure all values are correct.""" + # Unfortunately, this routine touches a lot of the code, but most of + # the components external to depletion_chain.py are simple storage + # types. + + chain = simple_chain + + # Basic checks + assert len(chain) == 3 + + # A tests + nuc = chain["A"] + + assert nuc.name == "A" + assert nuc.half_life == 2.36520E+04 + assert nuc.n_decay_modes == 2 + modes = nuc.decay_modes + assert [m.target for m in modes] == ["B", "C"] + assert [m.type for m in modes] == ["beta1", "beta2"] + assert [m.branching_ratio for m in modes] == [0.6, 0.4] + assert nuc.n_reaction_paths == 1 + assert [r.target for r in nuc.reactions] == ["C"] + assert [r.type for r in nuc.reactions] == ["(n,gamma)"] + assert [r.branching_ratio for r in nuc.reactions] == [1.0] + + # B tests + nuc = chain["B"] + + assert nuc.name == "B" + assert nuc.half_life == 3.29040E+04 + assert nuc.n_decay_modes == 1 + modes = nuc.decay_modes + assert [m.target for m in modes] == ["A"] + assert [m.type for m in modes] == ["beta"] + assert [m.branching_ratio for m in modes] == [1.0] + assert nuc.n_reaction_paths == 1 + assert [r.target for r in nuc.reactions] == ["C"] + assert [r.type for r in nuc.reactions] == ["(n,gamma)"] + assert [r.branching_ratio for r in nuc.reactions] == [1.0] + + # C tests + nuc = chain["C"] + + assert nuc.name == "C" + assert nuc.n_decay_modes == 0 + assert nuc.n_reaction_paths == 3 + assert [r.target for r in nuc.reactions] == [None, "A", "B"] + assert [r.type for r in nuc.reactions] == ["fission", "(n,gamma)", "(n,gamma)"] + assert [r.branching_ratio for r in nuc.reactions] == [1.0, 0.7, 0.3] + + # Yield tests + assert nuc.yield_energies == [0.0253] + assert list(nuc.yield_data) == [0.0253] + assert nuc.yield_data[0.0253] == [("A", 0.0292737), ("B", 0.002566345)] + + +def test_export_to_xml(run_in_tmpdir): + """Test writing a depletion chain to XML.""" + + # Prevent different MPI ranks from conflicting + filename = 'test{}.xml'.format(comm.rank) + + A = nuclide.Nuclide() + A.name = "A" + A.half_life = 2.36520e4 + A.decay_modes = [ + nuclide.DecayTuple("beta1", "B", 0.6), + nuclide.DecayTuple("beta2", "C", 0.4) + ] + A.reactions = [nuclide.ReactionTuple("(n,gamma)", "C", 0.0, 1.0)] + + B = nuclide.Nuclide() + B.name = "B" + B.half_life = 3.29040e4 + B.decay_modes = [nuclide.DecayTuple("beta", "A", 1.0)] + B.reactions = [nuclide.ReactionTuple("(n,gamma)", "C", 0.0, 1.0)] + + C = nuclide.Nuclide() + C.name = "C" + C.reactions = [ + nuclide.ReactionTuple("fission", None, 2.0e8, 1.0), + nuclide.ReactionTuple("(n,gamma)", "A", 0.0, 0.7), + nuclide.ReactionTuple("(n,gamma)", "B", 0.0, 0.3) + ] + C.yield_energies = [0.0253] + C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} + + chain = Chain() + chain.nuclides = [A, B, C] + chain.export_to_xml(filename) + + chain_xml = open(filename, 'r').read() + assert _TEST_CHAIN == chain_xml + + +def test_form_matrix(simple_chain): + """ Using chain_test, and a dummy reaction rate, compute the matrix. """ + # Relies on test_from_xml passing. + + chain = simple_chain + + mats = ["10000", "10001"] + nuclides = ["A", "B", "C"] + + react = reaction_rates.ReactionRates(mats, nuclides, chain.reactions) + + react.set("10000", "C", "fission", 1.0) + react.set("10000", "A", "(n,gamma)", 2.0) + react.set("10000", "B", "(n,gamma)", 3.0) + react.set("10000", "C", "(n,gamma)", 4.0) + + mat = chain.form_matrix(react[0, :, :]) + # Loss A, decay, (n, gamma) + mat00 = -np.log(2) / 2.36520E+04 - 2 + # A -> B, decay, 0.6 branching ratio + mat10 = np.log(2) / 2.36520E+04 * 0.6 + # A -> C, decay, 0.4 branching ratio + (n,gamma) + mat20 = np.log(2) / 2.36520E+04 * 0.4 + 2 + + # B -> A, decay, 1.0 branching ratio + mat01 = np.log(2)/3.29040E+04 + # Loss B, decay, (n, gamma) + mat11 = -np.log(2)/3.29040E+04 - 3 + # B -> C, (n, gamma) + mat21 = 3 + + # C -> A fission, (n, gamma) + mat02 = 0.0292737 * 1.0 + 4.0 * 0.7 + # C -> B fission, (n, gamma) + mat12 = 0.002566345 * 1.0 + 4.0 * 0.3 + # Loss C, fission, (n, gamma) + mat22 = -1.0 - 4.0 + + assert mat[0, 0] == mat00 + assert mat[1, 0] == mat10 + assert mat[2, 0] == mat20 + assert mat[0, 1] == mat01 + assert mat[1, 1] == mat11 + assert mat[2, 1] == mat21 + assert mat[0, 2] == mat02 + assert mat[1, 2] == mat12 + assert mat[2, 2] == mat22 + + +def test_getitem(): + """ Test nuc_by_ind converter function. """ + chain = Chain() + chain.nuclides = ["NucA", "NucB", "NucC"] + chain.nuclide_dict = {nuc: chain.nuclides.index(nuc) + for nuc in chain.nuclides} + + assert "NucA" == chain["NucA"] + assert "NucB" == chain["NucB"] + assert "NucC" == chain["NucC"] diff --git a/tests/unit_tests/test_deplete_cram.py b/tests/unit_tests/test_deplete_cram.py new file mode 100644 index 0000000000..21b93d17e3 --- /dev/null +++ b/tests/unit_tests/test_deplete_cram.py @@ -0,0 +1,37 @@ +""" Tests for cram.py + +Compares a few Mathematica matrix exponentials to CRAM16/CRAM48. +""" + +from pytest import approx +import numpy as np +import scipy.sparse as sp +from openmc.deplete.integrator import CRAM16, CRAM48 + + +def test_CRAM16(): + """Test 16-term CRAM.""" + x = np.array([1.0, 1.0]) + mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]]) + dt = 0.1 + + z = CRAM16(mat, x, dt) + + # Solution from mathematica + z0 = np.array((0.904837418035960, 0.576799023327476)) + + assert z == approx(z0) + + +def test_CRAM48(): + """Test 48-term CRAM.""" + x = np.array([1.0, 1.0]) + mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]]) + dt = 0.1 + + z = CRAM48(mat, x, dt) + + # Solution from mathematica + z0 = np.array((0.904837418035960, 0.576799023327476)) + + assert z == approx(z0) diff --git a/tests/unit_tests/test_deplete_integrator.py b/tests/unit_tests/test_deplete_integrator.py new file mode 100644 index 0000000000..a1768625b2 --- /dev/null +++ b/tests/unit_tests/test_deplete_integrator.py @@ -0,0 +1,93 @@ +"""Tests for saving results + +It is worth noting that openmc.deplete.integrate is extremely complex, to the +point I am unsure if it can be reasonably unit-tested. For the time being, it +will be left unimplemented and testing will be done via regression. + +""" + +import copy +import os +from unittest.mock import MagicMock + +import numpy as np +from openmc.deplete import (ReactionRates, Results, ResultsList, comm, + OperatorResult) + + +def test_results_save(run_in_tmpdir): + """Test data save module""" + + stages = 3 + + np.random.seed(comm.rank) + + # Mock geometry + op = MagicMock() + + vol_dict = {} + full_burn_list = [] + + for i in range(comm.size): + vol_dict[str(2*i)] = 1.2 + vol_dict[str(2*i + 1)] = 1.2 + full_burn_list.append(str(2*i)) + full_burn_list.append(str(2*i + 1)) + + burn_list = full_burn_list[2*comm.rank : 2*comm.rank + 2] + nuc_list = ["na", "nb"] + + op.get_results_info.return_value = vol_dict, nuc_list, burn_list, full_burn_list + + # Construct x + x1 = [] + x2 = [] + + for i in range(stages): + x1.append([np.random.rand(2), np.random.rand(2)]) + x2.append([np.random.rand(2), np.random.rand(2)]) + + # Construct r + r1 = ReactionRates(burn_list, ["na", "nb"], ["ra", "rb"]) + r1[:] = np.random.rand(2, 2, 2) + + rate1 = [] + rate2 = [] + + for i in range(stages): + rate1.append(copy.deepcopy(r1)) + r1[:] = np.random.rand(2, 2, 2) + rate2.append(copy.deepcopy(r1)) + r1[:] = np.random.rand(2, 2, 2) + + # Create global terms + eigvl1 = np.random.rand(stages) + eigvl2 = np.random.rand(stages) + + eigvl1 = comm.bcast(eigvl1, root=0) + eigvl2 = comm.bcast(eigvl2, root=0) + + t1 = [0.0, 1.0] + t2 = [1.0, 2.0] + + op_result1 = [OperatorResult(k, rates) for k, rates in zip(eigvl1, rate1)] + op_result2 = [OperatorResult(k, rates) for k, rates in zip(eigvl2, rate2)] + Results.save(op, x1, op_result1, t1, 0) + Results.save(op, x2, op_result2, t2, 1) + + # Load the files + res = ResultsList("depletion_results.h5") + + for i in range(stages): + for mat_i, mat in enumerate(burn_list): + for nuc_i, nuc in enumerate(nuc_list): + assert res[0][i, mat, nuc] == x1[i][mat_i][nuc_i] + assert res[1][i, mat, nuc] == x2[i][mat_i][nuc_i] + np.testing.assert_array_equal(res[0].rates[i], rate1[i]) + np.testing.assert_array_equal(res[1].rates[i], rate2[i]) + + np.testing.assert_array_equal(res[0].k, eigvl1) + np.testing.assert_array_equal(res[0].time, t1) + + np.testing.assert_array_equal(res[1].k, eigvl2) + np.testing.assert_array_equal(res[1].time, t2) diff --git a/tests/unit_tests/test_deplete_nuclide.py b/tests/unit_tests/test_deplete_nuclide.py new file mode 100644 index 0000000000..f2a101d2a9 --- /dev/null +++ b/tests/unit_tests/test_deplete_nuclide.py @@ -0,0 +1,116 @@ +"""Tests for the openmc.deplete.Nuclide class.""" + +import xml.etree.ElementTree as ET + +from openmc.deplete import nuclide + + +def test_n_decay_modes(): + """ Test the decay mode count parameter. """ + + nuc = nuclide.Nuclide() + + nuc.decay_modes = [ + nuclide.DecayTuple("beta1", "a", 0.5), + nuclide.DecayTuple("beta2", "b", 0.3), + nuclide.DecayTuple("beta3", "c", 0.2) + ] + + assert nuc.n_decay_modes == 3 + + +def test_n_reaction_paths(): + """ Test the reaction path count parameter. """ + + nuc = nuclide.Nuclide() + + nuc.reactions = [ + nuclide.ReactionTuple("(n,2n)", "a", 0.0, 1.0), + nuclide.ReactionTuple("(n,3n)", "b", 0.0, 1.0), + nuclide.ReactionTuple("(n,4n)", "c", 0.0, 1.0) + ] + + assert nuc.n_reaction_paths == 3 + + +def test_from_xml(): + """Test reading nuclide data from an XML element.""" + + data = """ + + + + + + + + + + 0.0253 + + Te134 Zr100 Xe138 + 0.062155 0.0497641 0.0481413 + + + + """ + + element = ET.fromstring(data) + u235 = nuclide.Nuclide.from_xml(element) + + assert u235.decay_modes == [ + nuclide.DecayTuple('sf', 'U235', 7.2e-11), + nuclide.DecayTuple('alpha', 'Th231', 1 - 7.2e-11) + ] + assert u235.reactions == [ + nuclide.ReactionTuple('(n,2n)', 'U234', -5297781.0, 1.0), + nuclide.ReactionTuple('(n,3n)', 'U233', -12142300.0, 1.0), + nuclide.ReactionTuple('(n,4n)', 'U232', -17885600.0, 1.0), + nuclide.ReactionTuple('(n,gamma)', 'U236', 6545200.0, 1.0), + nuclide.ReactionTuple('fission', None, 193405400.0, 1.0), + ] + assert u235.yield_energies == [0.0253] + assert u235.yield_data == { + 0.0253: [('Te134', 0.062155), ('Zr100', 0.0497641), + ('Xe138', 0.0481413)] + } + + +def test_to_xml_element(): + """Test writing nuclide data to an XML element.""" + + C = nuclide.Nuclide() + C.name = "C" + C.half_life = 0.123 + C.decay_modes = [ + nuclide.DecayTuple('beta-', 'B', 0.99), + nuclide.DecayTuple('alpha', 'D', 0.01) + ] + C.reactions = [ + nuclide.ReactionTuple('fission', None, 2.0e8, 1.0), + nuclide.ReactionTuple('(n,gamma)', 'A', 0.0, 1.0) + ] + C.yield_energies = [0.0253] + C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} + element = C.to_xml_element() + + assert element.get("half_life") == "0.123" + + decay_elems = element.findall("decay") + assert len(decay_elems) == 2 + assert decay_elems[0].get("type") == "beta-" + assert decay_elems[0].get("target") == "B" + assert decay_elems[0].get("branching_ratio") == "0.99" + assert decay_elems[1].get("type") == "alpha" + assert decay_elems[1].get("target") == "D" + assert decay_elems[1].get("branching_ratio") == "0.01" + + rx_elems = element.findall("reaction") + assert len(rx_elems) == 2 + assert rx_elems[0].get("type") == "fission" + assert float(rx_elems[0].get("Q")) == 2.0e8 + assert rx_elems[1].get("type") == "(n,gamma)" + assert rx_elems[1].get("target") == "A" + assert float(rx_elems[1].get("Q")) == 0.0 + + assert element.find('neutron_fission_yields') is not None diff --git a/tests/unit_tests/test_deplete_predictor.py b/tests/unit_tests/test_deplete_predictor.py new file mode 100644 index 0000000000..50803e5085 --- /dev/null +++ b/tests/unit_tests/test_deplete_predictor.py @@ -0,0 +1,37 @@ +"""Regression tests for openmc.deplete.integrator.predictor algorithm. + +These tests integrate a simple test problem described in dummy_geometry.py. +""" + +from pytest import approx +import openmc.deplete + +from tests import dummy_operator + + +def test_predictor(run_in_tmpdir): + """Integral regression test of integrator algorithm using predictor/corrector""" + + op = dummy_operator.DummyOperator() + op.output_dir = "test_integrator_regression" + + # Perform simulation using the predictor algorithm + dt = [0.75, 0.75] + power = 1.0 + openmc.deplete.predictor(op, dt, power, print_out=False) + + # Load the files + res = openmc.deplete.ResultsList(op.output_dir / "depletion_results.h5") + + _, y1 = res.get_atoms("1", "1") + _, y2 = res.get_atoms("1", "2") + + # Mathematica solution + s1 = [2.46847546272295, 0.986431226850467] + s2 = [4.11525874568034, -0.0581692232513460] + + assert y1[1] == approx(s1[0]) + assert y2[1] == approx(s1[1]) + + assert y1[2] == approx(s2[0]) + assert y2[2] == approx(s2[1]) diff --git a/tests/unit_tests/test_deplete_reaction.py b/tests/unit_tests/test_deplete_reaction.py new file mode 100644 index 0000000000..18639a27a1 --- /dev/null +++ b/tests/unit_tests/test_deplete_reaction.py @@ -0,0 +1,63 @@ +"""Tests for the openmc.deplete.ReactionRates class.""" + +import numpy as np +from openmc.deplete import ReactionRates + + +def test_get_set(): + """Tests the get/set methods.""" + + local_mats = ["10000", "10001"] + nuclides = ["U238", "U235"] + reactions = ["fission", "(n,gamma)"] + + rates = ReactionRates(local_mats, nuclides, reactions) + assert rates.shape == (2, 2, 2) + assert np.all(rates == 0.0) + + rates.set("10000", "U238", "fission", 1.0) + rates.set("10001", "U238", "fission", 2.0) + rates.set("10000", "U235", "fission", 3.0) + rates.set("10001", "U235", "fission", 4.0) + rates.set("10000", "U238", "(n,gamma)", 5.0) + rates.set("10001", "U238", "(n,gamma)", 6.0) + rates.set("10000", "U235", "(n,gamma)", 7.0) + rates.set("10001", "U235", "(n,gamma)", 8.0) + + # String indexing + assert rates.get("10000", "U238", "fission") == 1.0 + assert rates.get("10001", "U238", "fission") == 2.0 + assert rates.get("10000", "U235", "fission") == 3.0 + assert rates.get("10001", "U235", "fission") == 4.0 + assert rates.get("10000", "U238", "(n,gamma)") == 5.0 + assert rates.get("10001", "U238", "(n,gamma)") == 6.0 + assert rates.get("10000", "U235", "(n,gamma)") == 7.0 + assert rates.get("10001", "U235", "(n,gamma)") == 8.0 + + # Int indexing + assert rates[0, 0, 0] == 1.0 + assert rates[1, 0, 0] == 2.0 + assert rates[0, 1, 0] == 3.0 + assert rates[1, 1, 0] == 4.0 + assert rates[0, 0, 1] == 5.0 + assert rates[1, 0, 1] == 6.0 + assert rates[0, 1, 1] == 7.0 + assert rates[1, 1, 1] == 8.0 + + rates[0, 0, 0] = 5.0 + + assert rates[0, 0, 0] == 5.0 + assert rates.get("10000", "U238", "fission") == 5.0 + + +def test_properties(): + """Test number of materials property.""" + local_mats = ["10000", "10001"] + nuclides = ["U238", "U235", "Gd157"] + reactions = ["fission", "(n,gamma)", "(n,2n)", "(n,3n)"] + + rates = ReactionRates(local_mats, nuclides, reactions) + + assert rates.n_mat == 2 + assert rates.n_nuc == 3 + assert rates.n_react == 4 diff --git a/tests/unit_tests/test_deplete_resultslist.py b/tests/unit_tests/test_deplete_resultslist.py new file mode 100644 index 0000000000..aad8cd9f68 --- /dev/null +++ b/tests/unit_tests/test_deplete_resultslist.py @@ -0,0 +1,51 @@ +"""Tests the ResultsList class""" + +from pathlib import Path + +import numpy as np +import pytest +import openmc.deplete + + +@pytest.fixture +def res(): + """Load the reference results""" + filename = Path(__file__).parents[1] / 'regression_tests' / 'test_reference.h5' + return openmc.deplete.ResultsList(filename) + + +def test_get_atoms(res): + """Tests evaluating single nuclide concentration.""" + t, n = res.get_atoms("1", "Xe135") + + t_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + n_ref = [6.6747328233649218e+08, 3.5421791038348462e+14, + 3.6208592242443462e+14, 3.3799758969347038e+14] + + np.testing.assert_array_equal(t, t_ref) + np.testing.assert_array_equal(n, n_ref) + +def test_get_reaction_rate(res): + """Tests evaluating reaction rate.""" + t, r = res.get_reaction_rate("1", "Xe135", "(n,gamma)") + + t_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + n_ref = np.array([6.6747328233649218e+08, 3.5421791038348462e+14, + 3.6208592242443462e+14, 3.3799758969347038e+14]) + xs_ref = np.array([4.0594392323131994e-05, 3.9249546927524987e-05, + 3.8394587728581798e-05, 4.1521845978371697e-05]) + + np.testing.assert_array_equal(t, t_ref) + np.testing.assert_array_equal(r, n_ref * xs_ref) + + +def test_get_eigenvalue(res): + """Tests evaluating eigenvalue.""" + t, k = res.get_eigenvalue() + + t_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + k_ref = [1.181281798790367, 1.1798750921988739, 1.1965943696058159, + 1.2207119847790813] + + np.testing.assert_array_equal(t, t_ref) + np.testing.assert_array_equal(k, k_ref) diff --git a/tests/unit_tests/test_geometry.py b/tests/unit_tests/test_geometry.py new file mode 100644 index 0000000000..93d2fa6341 --- /dev/null +++ b/tests/unit_tests/test_geometry.py @@ -0,0 +1,246 @@ +import xml.etree.ElementTree as ET + +import numpy as np +import openmc +import pytest + + +def test_volume(run_in_tmpdir, uo2): + """Test adding volume information from a volume calculation.""" + # Create model with nested spheres + model = openmc.model.Model() + model.materials.append(uo2) + inner = openmc.Sphere(R=1.) + outer = openmc.Sphere(R=2., boundary_type='vacuum') + c1 = openmc.Cell(fill=uo2, region=-inner) + c2 = openmc.Cell(region=+inner & -outer) + u = openmc.Universe(cells=[c1, c2]) + model.geometry.root_universe = u + model.settings.particles = 100 + model.settings.batches = 10 + model.settings.run_mode = 'fixed source' + model.settings.source = openmc.Source(space=openmc.stats.Point()) + + ll, ur = model.geometry.bounding_box + assert ll == pytest.approx((-outer.r, -outer.r, -outer.r)) + assert ur == pytest.approx((outer.r, outer.r, outer.r)) + model.settings.volume_calculations + + for domain in (c1, uo2, u): + # Run stochastic volume calculation + volume_calc = openmc.VolumeCalculation( + domains=[domain], samples=1000, lower_left=ll, upper_right=ur) + model.settings.volume_calculations = [volume_calc] + model.export_to_xml() + openmc.calculate_volumes() + + # Load results and add volume information + volume_calc.load_results('volume_1.h5') + model.geometry.add_volume_information(volume_calc) + + # get_nuclide_densities relies on volume information + nucs = set(domain.get_nuclide_densities()) + assert not nucs ^ {'U235', 'O16'} + + +def test_export_xml(run_in_tmpdir, uo2): + s1 = openmc.Sphere(R=1.) + s2 = openmc.Sphere(R=2., boundary_type='reflective') + c1 = openmc.Cell(fill=uo2, region=-s1) + c2 = openmc.Cell(fill=uo2, region=+s1 & -s2) + geom = openmc.Geometry([c1, c2]) + geom.export_to_xml() + + doc = ET.parse('geometry.xml') + root = doc.getroot() + assert root.tag == 'geometry' + cells = root.findall('cell') + assert [int(c.get('id')) for c in cells] == [c1.id, c2.id] + surfs = root.findall('surface') + assert [int(s.get('id')) for s in surfs] == [s1.id, s2.id] + + +def test_find(uo2): + xp = openmc.XPlane() + c1 = openmc.Cell(fill=uo2, region=+xp) + c2 = openmc.Cell(region=-xp) + u1 = openmc.Universe(cells=(c1, c2)) + + cyl = openmc.ZCylinder() + c3 = openmc.Cell(fill=u1, region=-cyl) + c4 = openmc.Cell(region=+cyl) + geom = openmc.Geometry((c3, c4)) + + seq = geom.find((0.5, 0., 0.)) + assert seq[-1] == c1 + seq = geom.find((-0.5, 0., 0.)) + assert seq[-1] == c2 + seq = geom.find((-1.5, 0., 0.)) + assert seq[-1] == c4 + + +def test_get_all_cells(): + cells = [openmc.Cell() for i in range(5)] + cells2 = [openmc.Cell() for i in range(3)] + cells[0].fill = openmc.Universe(cells=cells2) + geom = openmc.Geometry(cells) + + all_cells = set(geom.get_all_cells().values()) + assert not all_cells ^ set(cells + cells2) + + +def test_get_all_materials(): + m1 = openmc.Material() + m2 = openmc.Material() + c1 = openmc.Cell(fill=m1) + u1 = openmc.Universe(cells=[c1]) + + s = openmc.Sphere() + c2 = openmc.Cell(fill=u1, region=-s) + c3 = openmc.Cell(fill=m2, region=+s) + geom = openmc.Geometry([c2, c3]) + + all_mats = set(geom.get_all_materials().values()) + assert not all_mats ^ {m1, m2} + + +def test_get_all_material_cells(): + m1 = openmc.Material() + m2 = openmc.Material() + c1 = openmc.Cell(fill=m1) + u1 = openmc.Universe(cells=[c1]) + + s = openmc.Sphere() + c2 = openmc.Cell(fill=u1, region=-s) + c3 = openmc.Cell(fill=m2, region=+s) + geom = openmc.Geometry([c2, c3]) + + all_cells = set(geom.get_all_material_cells().values()) + assert not all_cells ^ {c1, c3} + + +def test_get_all_material_universes(): + m1 = openmc.Material() + m2 = openmc.Material() + c1 = openmc.Cell(fill=m1) + u1 = openmc.Universe(cells=[c1]) + + s = openmc.Sphere() + c2 = openmc.Cell(fill=u1, region=-s) + c3 = openmc.Cell(fill=m2, region=+s) + geom = openmc.Geometry([c2, c3]) + + all_univs = set(geom.get_all_material_universes().values()) + assert not all_univs ^ {u1, geom.root_universe} + + +def test_get_all_lattices(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + geom = openmc.Geometry([cells[-1]]) + + lats = list(geom.get_all_lattices().values()) + assert lats == [lattice] + + +def test_get_all_surfaces(uo2): + planes = [openmc.ZPlane(z0=z) for z in np.linspace(-100., 100.)] + slabs = [] + for region in openmc.model.subdivide(planes): + slabs.append(openmc.Cell(fill=uo2, region=region)) + geom = openmc.Geometry(slabs) + + surfs = set(geom.get_all_surfaces().values()) + assert not surfs ^ set(planes) + + +def test_get_by_name(): + m1 = openmc.Material(name='zircaloy') + m1.add_element('Zr', 1.0) + m2 = openmc.Material(name='Zirconium') + m2.add_element('Zr', 1.0) + + c1 = openmc.Cell(fill=m1, name='cell1') + u1 = openmc.Universe(name='Zircaloy universe', cells=[c1]) + + cyl = openmc.ZCylinder() + c2 = openmc.Cell(fill=u1, region=-cyl, name='cell2') + c3 = openmc.Cell(fill=m2, region=+cyl, name='Cell3') + root = openmc.Universe(name='root Universe', cells=[c2, c3]) + geom = openmc.Geometry(root) + + mats = set(geom.get_materials_by_name('zirc')) + assert not mats ^ {m1, m2} + mats = set(geom.get_materials_by_name('zirc', True)) + assert not mats ^ {m1} + mats = set(geom.get_materials_by_name('zirconium', False, True)) + assert not mats ^ {m2} + mats = geom.get_materials_by_name('zirconium', True, True) + assert not mats + + cells = set(geom.get_cells_by_name('cell')) + assert not cells ^ {c1, c2, c3} + cells = set(geom.get_cells_by_name('cell', True)) + assert not cells ^ {c1, c2} + cells = set(geom.get_cells_by_name('cell3', False, True)) + assert not cells ^ {c3} + cells = geom.get_cells_by_name('cell3', True, True) + assert not cells + + cells = set(geom.get_cells_by_fill_name('Zircaloy')) + assert not cells ^ {c1, c2} + cells = set(geom.get_cells_by_fill_name('Zircaloy', True)) + assert not cells ^ {c2} + cells = set(geom.get_cells_by_fill_name('Zircaloy', False, True)) + assert not cells ^ {c1} + cells = geom.get_cells_by_fill_name('Zircaloy', True, True) + assert not cells + + univs = set(geom.get_universes_by_name('universe')) + assert not univs ^ {u1, root} + univs = set(geom.get_universes_by_name('universe', True)) + assert not univs ^ {u1} + univs = set(geom.get_universes_by_name('universe', True, True)) + assert not univs + + +def test_get_lattice_by_name(cell_with_lattice): + cells, _, _, lattice = cell_with_lattice + geom = openmc.Geometry([cells[-1]]) + + f = geom.get_lattices_by_name + assert f('lattice') == [lattice] + assert f('lattice', True) == [] + assert f('Lattice', True) == [lattice] + assert f('my lattice', False, True) == [lattice] + assert f('my lattice', True, True) == [] + + +def test_clone(): + c1 = openmc.Cell() + c2 = openmc.Cell() + root = openmc.Universe(cells=[c1, c2]) + geom = openmc.Geometry(root) + + clone = geom.clone() + root_clone = clone.root_universe + + assert root.id != root_clone.id + assert not (set(root.cells) & set(root_clone.cells)) + + +def test_determine_paths(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + u = openmc.Universe(cells=[cells[-1]]) + geom = openmc.Geometry(u) + + geom.determine_paths() + assert len(cells[0].paths) == 4 + assert len(cells[1].paths) == 4 + assert len(cells[2].paths) == 1 + assert len(mats[0].paths) == 1 + assert len(mats[-1].paths) == 4 + + # Test get_instances + for i in range(4): + assert geom.get_instances(cells[0].paths[i]) == i + assert geom.get_instances(mats[-1].paths[i]) == i diff --git a/tests/unit_tests/test_lattice.py b/tests/unit_tests/test_lattice.py new file mode 100644 index 0000000000..47dc1c029e --- /dev/null +++ b/tests/unit_tests/test_lattice.py @@ -0,0 +1,344 @@ +from math import sqrt +import xml.etree.ElementTree as ET + +import openmc +import pytest + + +@pytest.fixture(scope='module') +def pincell1(uo2, water): + cyl = openmc.ZCylinder(R=0.35) + fuel = openmc.Cell(fill=uo2, region=-cyl) + moderator = openmc.Cell(fill=water, region=+cyl) + + univ = openmc.Universe(cells=[fuel, moderator]) + univ.fuel = fuel + univ.moderator = moderator + return univ + + +@pytest.fixture(scope='module') +def pincell2(uo2, water): + cyl = openmc.ZCylinder(R=0.4) + fuel = openmc.Cell(fill=uo2, region=-cyl) + moderator = openmc.Cell(fill=water, region=+cyl) + + univ = openmc.Universe(cells=[fuel, moderator]) + univ.fuel = fuel + univ.moderator = moderator + return univ + + +@pytest.fixture(scope='module') +def zr(): + zr = openmc.Material() + zr.add_element('Zr', 1.0) + zr.set_density('g/cm3', 1.0) + return zr + + +@pytest.fixture(scope='module') +def rlat2(pincell1, pincell2, uo2, water, zr): + """2D Rectangular lattice for testing.""" + all_zr = openmc.Cell(fill=zr) + pitch = 1.2 + n = 3 + u1, u2 = pincell1, pincell2 + lattice = openmc.RectLattice() + lattice.lower_left = (-pitch*n/2, -pitch*n/2) + lattice.pitch = (pitch, pitch) + lattice.outer = openmc.Universe(cells=[all_zr]) + lattice.universes = [ + [u1, u2, u1], + [u2, u1, u2], + [u2, u1, u1] + ] + + # Add extra attributes for comparison purpose + lattice.cells = [u1.fuel, u1.moderator, u2.fuel, u2.moderator, all_zr] + lattice.mats = [uo2, water, zr] + lattice.univs = [u1, u2, lattice.outer] + return lattice + + +@pytest.fixture(scope='module') +def rlat3(pincell1, pincell2, uo2, water, zr): + """3D Rectangular lattice for testing.""" + + # Create another universe for top layer + hydrogen = openmc.Material() + hydrogen.add_element('H', 1.0) + hydrogen.set_density('g/cm3', 0.09) + h_cell = openmc.Cell(fill=hydrogen) + u3 = openmc.Universe(cells=[h_cell]) + + all_zr = openmc.Cell(fill=zr) + pitch = 1.2 + n = 3 + u1, u2 = pincell1, pincell2 + lattice = openmc.RectLattice() + lattice.lower_left = (-pitch*n/2, -pitch*n/2, -10.0) + lattice.pitch = (pitch, pitch, 10.0) + lattice.outer = openmc.Universe(cells=[all_zr]) + lattice.universes = [ + [[u1, u2, u1], + [u2, u1, u2], + [u2, u1, u1]], + [[u3, u1, u2], + [u1, u3, u2], + [u2, u1, u1]] + ] + + # Add extra attributes for comparison purpose + lattice.cells = [u1.fuel, u1.moderator, u2.fuel, u2.moderator, + h_cell, all_zr] + lattice.mats = [uo2, water, zr, hydrogen] + lattice.univs = [u1, u2, u3, lattice.outer] + return lattice + + +@pytest.fixture(scope='module') +def hlat2(pincell1, pincell2, uo2, water, zr): + """2D Hexagonal lattice for testing.""" + all_zr = openmc.Cell(fill=zr) + pitch = 1.2 + u1, u2 = pincell1, pincell2 + lattice = openmc.HexLattice() + lattice.center = (0., 0.) + lattice.pitch = (pitch,) + lattice.outer = openmc.Universe(cells=[all_zr]) + lattice.universes = [ + [u2, u1, u1, u1, u1, u1, u1, u1, u1, u1, u1, u1], + [u2, u1, u1, u1, u1, u1], + [u2] + ] + + # Add extra attributes for comparison purpose + lattice.cells = [u1.fuel, u1.moderator, u2.fuel, u2.moderator, all_zr] + lattice.mats = [uo2, water, zr] + lattice.univs = [u1, u2, lattice.outer] + return lattice + + +@pytest.fixture(scope='module') +def hlat3(pincell1, pincell2, uo2, water, zr): + """3D Hexagonal lattice for testing.""" + + # Create another universe for top layer + hydrogen = openmc.Material() + hydrogen.add_element('H', 1.0) + hydrogen.set_density('g/cm3', 0.09) + h_cell = openmc.Cell(fill=hydrogen) + u3 = openmc.Universe(cells=[h_cell]) + + all_zr = openmc.Cell(fill=zr) + pitch = 1.2 + u1, u2 = pincell1, pincell2 + lattice = openmc.HexLattice() + lattice.center = (0., 0., 0.) + lattice.pitch = (pitch, 10.0) + lattice.outer = openmc.Universe(cells=[all_zr]) + lattice.universes = [ + [[u2, u1, u1, u1, u1, u1, u1, u1, u1, u1, u1, u1], + [u2, u1, u1, u1, u1, u1], + [u2]], + [[u1, u1, u1, u1, u1, u1, u3, u1, u1, u1, u1, u1], + [u1, u1, u1, u3, u1, u1], + [u3]] + ] + + # Add extra attributes for comparison purpose + lattice.cells = [u1.fuel, u1.moderator, u2.fuel, u2.moderator, + h_cell, all_zr] + lattice.mats = [uo2, water, zr, hydrogen] + lattice.univs = [u1, u2, u3, lattice.outer] + return lattice + + +def test_get_nuclides(rlat2, rlat3, hlat2, hlat3): + for lat in (rlat2, hlat2): + nucs = rlat2.get_nuclides() + assert sorted(nucs) == ['H1', 'O16', 'U235', + 'Zr90', 'Zr91', 'Zr92', 'Zr94', 'Zr96'] + for lat in (rlat3, hlat3): + nucs = rlat3.get_nuclides() + assert sorted(nucs) == ['H1', 'H2', 'O16', 'U235', + 'Zr90', 'Zr91', 'Zr92', 'Zr94', 'Zr96'] + + +def test_get_all_cells(rlat2, rlat3, hlat2, hlat3): + for lat in (rlat2, rlat3, hlat2, hlat3): + cells = set(lat.get_all_cells().values()) + assert not cells ^ set(lat.cells) + + +def test_get_all_materials(rlat2, rlat3, hlat2, hlat3): + for lat in (rlat2, rlat3, hlat2, hlat3): + mats = set(lat.get_all_materials().values()) + assert not mats ^ set(lat.mats) + + +def test_get_all_universes(rlat2, rlat3, hlat2, hlat3): + for lat in (rlat2, rlat3, hlat2, hlat3): + univs = set(lat.get_all_universes().values()) + assert not univs ^ set(lat.univs) + + +def test_get_universe(rlat2, rlat3, hlat2, hlat3): + u1, u2, outer = rlat2.univs + assert rlat2.get_universe((0, 0)) == u2 + assert rlat2.get_universe((1, 0)) == u1 + assert rlat2.get_universe((0, 1)) == u2 + + u1, u2, u3, outer = rlat3.univs + assert rlat3.get_universe((0, 0, 0)) == u2 + assert rlat3.get_universe((2, 2, 0)) == u1 + assert rlat3.get_universe((0, 2, 1)) == u3 + assert rlat3.get_universe((2, 1, 1)) == u2 + + u1, u2, outer = hlat2.univs + assert hlat2.get_universe((0, 0)) == u2 + assert hlat2.get_universe((0, 2)) == u2 + assert hlat2.get_universe((1, 0)) == u1 + assert hlat2.get_universe((-2, 2)) == u1 + + u1, u2, u3, outer = hlat3.univs + assert hlat3.get_universe((0, 0, 0)) == u2 + assert hlat3.get_universe((0, 0, 1)) == u3 + assert hlat3.get_universe((0, 2, 0)) == u2 + assert hlat3.get_universe((0, 2, 1)) == u1 + assert hlat3.get_universe((0, -2, 0)) == u1 + assert hlat3.get_universe((0, -2, 1)) == u3 + + +def test_find(rlat2, rlat3, hlat2, hlat3): + pitch = rlat2.pitch[0] + seq = rlat2.find((0., 0., 0.)) + assert seq[-1] == rlat2.cells[0] + seq = rlat2.find((pitch, 0., 0.)) + assert seq[-1] == rlat2.cells[2] + seq = rlat2.find((0., -pitch, 0.)) + assert seq[-1] == rlat2.cells[0] + seq = rlat2.find((pitch*100, 0., 0.)) + assert seq[-1] == rlat2.cells[-1] + seq = rlat3.find((-pitch, pitch, 5.0)) + assert seq[-1] == rlat3.cells[-2] + + pitch = hlat2.pitch[0] + seq = hlat2.find((0., 0., 0.)) + assert seq[-1] == hlat2.cells[2] + seq = hlat2.find((0.5, 0., 0.)) + assert seq[-1] == hlat2.cells[3] + seq = hlat2.find((sqrt(3)*pitch, 0., 0.)) + assert seq[-1] == hlat2.cells[0] + seq = hlat2.find((0., pitch, 0.)) + assert seq[-1] == hlat2.cells[2] + + # bottom of 3D lattice + seq = hlat3.find((0., 0., -5.)) + assert seq[-1] == hlat3.cells[2] + seq = hlat3.find((0., pitch, -5.)) + assert seq[-1] == hlat3.cells[2] + seq = hlat3.find((0., -pitch, -5.)) + assert seq[-1] == hlat3.cells[0] + seq = hlat3.find((sqrt(3)*pitch, 0., -5.)) + assert seq[-1] == hlat3.cells[0] + + # top of 3D lattice + seq = hlat3.find((0., 0., 5.)) + assert seq[-1] == hlat3.cells[-2] + seq = hlat3.find((0., pitch, 5.)) + assert seq[-1] == hlat3.cells[0] + seq = hlat3.find((0., -pitch, 5.)) + assert seq[-1] == hlat3.cells[-2] + seq = hlat3.find((sqrt(3)*pitch, 0., 5.)) + assert seq[-1] == hlat3.cells[0] + + +def test_clone(rlat2, hlat2, hlat3): + rlat_clone = rlat2.clone() + assert rlat_clone.id != rlat2.id + assert rlat_clone.lower_left == rlat2.lower_left + assert rlat_clone.pitch == rlat2.pitch + + hlat_clone = hlat2.clone() + assert hlat_clone.id != hlat2.id + assert hlat_clone.center == hlat2.center + assert hlat_clone.pitch == hlat2.pitch + + hlat_clone = hlat3.clone() + assert hlat_clone.id != hlat3.id + assert hlat_clone.center == hlat3.center + assert hlat_clone.pitch == hlat3.pitch + + +def test_repr(rlat2, rlat3, hlat2, hlat3): + repr(rlat2) + repr(rlat3) + repr(hlat2) + repr(hlat3) + + +def test_indices_rect(rlat2, rlat3): + # (y, x) indices + assert rlat2.indices == [(0, 0), (0, 1), (0, 2), + (1, 0), (1, 1), (1, 2), + (2, 0), (2, 1), (2, 2)] + # (z, y, x) indices + assert rlat3.indices == [ + (0, 0, 0), (0, 0, 1), (0, 0, 2), + (0, 1, 0), (0, 1, 1), (0, 1, 2), + (0, 2, 0), (0, 2, 1), (0, 2, 2), + (1, 0, 0), (1, 0, 1), (1, 0, 2), + (1, 1, 0), (1, 1, 1), (1, 1, 2), + (1, 2, 0), (1, 2, 1), (1, 2, 2) + ] + + +def test_indices_hex(hlat2, hlat3): + # (r, i) indices + assert hlat2.indices == ( + [(0, i) for i in range(12)] + + [(1, i) for i in range(6)] + + [(2, 0)] + ) + + # (z, r, i) indices + assert hlat3.indices == ( + [(0, 0, i) for i in range(12)] + + [(0, 1, i) for i in range(6)] + + [(0, 2, 0)] + + [(1, 0, i) for i in range(12)] + + [(1, 1, i) for i in range(6)] + + [(1, 2, 0)] + ) + + +def test_xml_rect(rlat2, rlat3): + for lat in (rlat2, rlat3): + geom = ET.Element('geometry') + lat.create_xml_subelement(geom) + elem = geom.find('lattice') + assert elem.tag == 'lattice' + assert elem.get('id') == str(lat.id) + assert len(elem.find('pitch').text.split()) == lat.ndim + assert len(elem.find('lower_left').text.split()) == lat.ndim + assert len(elem.find('universes').text.split()) == len(lat.indices) + + +def test_xml_hex(hlat2, hlat3): + for lat in (hlat2, hlat3): + geom = ET.Element('geometry') + lat.create_xml_subelement(geom) + elem = geom.find('hex_lattice') + assert elem.tag == 'hex_lattice' + assert elem.get('id') == str(lat.id) + assert len(elem.find('center').text.split()) == lat.ndim + assert len(elem.find('pitch').text.split()) == lat.ndim - 1 + assert len(elem.find('universes').text.split()) == len(lat.indices) + + +def test_show_indices(): + for i in range(1, 11): + lines = openmc.HexLattice.show_indices(i).split('\n') + assert len(lines) == 4*i - 3 diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py new file mode 100644 index 0000000000..b7b745408d --- /dev/null +++ b/tests/unit_tests/test_material.py @@ -0,0 +1,184 @@ +import openmc +import openmc.model +import openmc.stats +import openmc.examples +import pytest + + +def test_attributes(uo2): + assert uo2.name == 'UO2' + assert uo2.id == 100 + assert uo2.depletable + + +def test_nuclides(uo2): + """Test adding/removing nuclides.""" + m = openmc.Material() + m.add_nuclide('U235', 1.0) + with pytest.raises(TypeError): + m.add_nuclide('H1', '1.0') + with pytest.raises(TypeError): + m.add_nuclide(1.0, 'H1') + with pytest.raises(ValueError): + m.add_nuclide('H1', 1.0, 'oa') + m.remove_nuclide('U235') + + +def test_elements(): + """Test adding elements.""" + m = openmc.Material() + m.add_element('Zr', 1.0) + m.add_element('U', 1.0, enrichment=4.5) + with pytest.raises(ValueError): + m.add_element('U', 1.0, enrichment=100.0) + with pytest.raises(ValueError): + m.add_element('Pu', 1.0, enrichment=3.0) + + +def test_density(): + m = openmc.Material() + for unit in ['g/cm3', 'g/cc', 'kg/m3', 'atom/b-cm', 'atom/cm3']: + m.set_density(unit, 1.0) + with pytest.raises(ValueError): + m.set_density('g/litre', 1.0) + + +def test_salphabeta(): + m = openmc.Material() + m.add_s_alpha_beta('c_H_in_H2O', 0.5) + + +def test_repr(): + m = openmc.Material() + m.add_nuclide('Zr90', 1.0) + m.add_nuclide('H2', 0.5) + m.add_s_alpha_beta('c_D_in_D2O') + m.set_density('sum') + m.temperature = 600.0 + repr(m) + + +def test_macroscopic(run_in_tmpdir): + m = openmc.Material(name='UO2') + m.add_macroscopic('UO2') + with pytest.raises(ValueError): + m.add_nuclide('H1', 1.0) + with pytest.raises(ValueError): + m.add_element('O', 1.0) + with pytest.raises(ValueError): + m.add_macroscopic('Other') + + m2 = openmc.Material() + m2.add_nuclide('He4', 1.0) + with pytest.raises(ValueError): + m2.add_macroscopic('UO2') + + # Make sure we can remove/add macroscopic + m.remove_macroscopic('UO2') + m.add_macroscopic('UO2') + repr(m) + + # Make sure we can export a material with macroscopic data + mats = openmc.Materials([m]) + mats.export_to_xml() + + +def test_paths(): + model = openmc.examples.pwr_assembly() + model.geometry.determine_paths() + fuel = model.materials[0] + assert fuel.num_instances == 264 + assert len(fuel.paths) == 264 + + +def test_isotropic(): + m1 = openmc.Material() + m1.add_nuclide('U235', 1.0) + m1.add_nuclide('O16', 2.0) + m1.isotropic = ['O16'] + assert m1.isotropic == ['O16'] + + m2 = openmc.Material() + m2.add_nuclide('H1', 1.0) + mats = openmc.Materials([m1, m2]) + mats.make_isotropic_in_lab() + assert m1.isotropic == ['U235', 'O16'] + assert m2.isotropic == ['H1'] + + +def test_get_nuclide_densities(uo2): + nucs = uo2.get_nuclide_densities() + for nuc, density, density_type in nucs.values(): + assert nuc in ('U235', 'O16') + assert density > 0 + assert density_type in ('ao', 'wo') + + +def test_get_nuclide_atom_densities(uo2): + nucs = uo2.get_nuclide_atom_densities() + for nuc, density in nucs.values(): + assert nuc in ('U235', 'O16') + assert density > 0 + + +def test_mass(): + m = openmc.Material() + m.add_nuclide('Zr90', 1.0, 'wo') + m.add_nuclide('U235', 1.0, 'wo') + m.set_density('g/cm3', 2.0) + m.volume = 10.0 + + assert m.get_mass_density('Zr90') == pytest.approx(1.0) + assert m.get_mass_density('U235') == pytest.approx(1.0) + assert m.get_mass_density() == pytest.approx(2.0) + + assert m.get_mass('Zr90') == pytest.approx(10.0) + assert m.get_mass('U235') == pytest.approx(10.0) + assert m.get_mass() == pytest.approx(20.0) + assert m.fissionable_mass == pytest.approx(10.0) + + +def test_materials(run_in_tmpdir): + m1 = openmc.Material() + m1.add_nuclide('U235', 1.0, 'wo') + m1.add_nuclide('O16', 2.0, 'wo') + m1.set_density('g/cm3', 10.0) + m1.depletable = True + m1.temperature = 900.0 + + m2 = openmc.Material() + m2.add_nuclide('H1', 2.0) + m2.add_nuclide('O16', 1.0) + m2.add_s_alpha_beta('c_H_in_H2O') + m2.set_density('kg/m3', 1000.0) + + mats = openmc.Materials([m1, m2]) + mats.cross_sections = '/some/fake/cross_sections.xml' + mats.multipole_library = '/some/awesome/mp_lib/' + mats.export_to_xml() + + +def test_borated_water(): + # Test against reference values from the BEAVRS benchmark. + m = openmc.model.borated_water(975, 566.5, 15.51, material_id=50) + assert m.density == pytest.approx(0.7405, 1e-3) + assert m.temperature == pytest.approx(566.5) + assert m._sab[0][0] == 'c_H_in_H2O' + ref_dens = {'B10':8.0023e-06, 'B11':3.2210e-05, 'H1':4.9458e-02, + 'O16':2.4672e-02} + nuc_dens = m.get_nuclide_atom_densities() + for nuclide in ref_dens: + assert nuc_dens[nuclide][1] == pytest.approx(ref_dens[nuclide], 1e-2) + assert m.id == 50 + + # Test the Celsius conversion. + m = openmc.model.borated_water(975, 293.35, 15.51, 'C') + assert m.density == pytest.approx(0.7405, 1e-3) + + # Test Fahrenheit and psi conversions. + m = openmc.model.borated_water(975, 560.0, 2250.0, 'F', 'psi') + assert m.density == pytest.approx(0.7405, 1e-3) + + # Test the density override + m = openmc.model.borated_water(975, 566.5, 15.51, density=0.9) + assert m.density == pytest.approx(0.9, 1e-3) diff --git a/tests/unit_tests/test_plots.py b/tests/unit_tests/test_plots.py new file mode 100644 index 0000000000..d48b609c1e --- /dev/null +++ b/tests/unit_tests/test_plots.py @@ -0,0 +1,90 @@ +import openmc +import openmc.examples +import pytest + + +@pytest.fixture(scope='module') +def myplot(): + plot = openmc.Plot(name='myplot') + plot.width = (100., 100.) + plot.origin = (2., 3., -10.) + plot.pixels = (500, 500) + plot.filename = 'myplot' + plot.type = 'slice' + plot.basis = 'yz' + plot.background = (0, 0, 0) + plot.background = 'black' + + plot.color_by = 'material' + m1, m2 = openmc.Material(), openmc.Material() + plot.colors = {m1: (0, 255, 0), m2: (0, 0, 255)} + plot.colors = {m1: 'green', m2: 'blue'} + + plot.mask_components = [openmc.Material()] + plot.mask_background = (255, 255, 255) + plot.mask_background = 'white' + + plot.level = 1 + plot.meshlines = { + 'type': 'tally', + 'id': 1, + 'linewidth': 2, + 'color': (40, 30, 20) + } + return plot + + +def test_attributes(myplot): + assert myplot.name == 'myplot' + + +def test_repr(myplot): + r = repr(myplot) + assert isinstance(r, str) + + +def test_from_geometry(): + width = 25. + s = openmc.Sphere(R=width/2, boundary_type='vacuum') + c = openmc.Cell(region=-s) + univ = openmc.Universe(cells=[c]) + geom = openmc.Geometry(univ) + + for basis in ('xy', 'yz', 'xz'): + plot = openmc.Plot.from_geometry(geom, basis) + assert plot.origin == pytest.approx((0., 0., 0.)) + assert plot.width == pytest.approx((width, width)) + + +def test_highlight_domains(): + plot = openmc.Plot() + plot.color_by = 'material' + plots = openmc.Plots([plot]) + + model = openmc.examples.pwr_pin_cell() + mats = {m for m in model.materials if 'UO2' in m.name} + plots.highlight_domains(model.geometry, mats) + + +def test_to_xml_element(myplot): + elem = myplot.to_xml_element() + assert 'id' in elem.attrib + assert 'color_by' in elem.attrib + assert 'type' in elem.attrib + assert elem.find('origin') is not None + assert elem.find('width') is not None + assert elem.find('pixels') is not None + assert elem.find('background').text == '0 0 0' + + +def test_plots(run_in_tmpdir): + p1 = openmc.Plot(name='plot1') + p2 = openmc.Plot(name='plot2') + plots = openmc.Plots([p1, p2]) + assert len(plots) == 2 + + p3 = openmc.Plot(name='plot3') + plots.append(p3) + assert len(plots) == 3 + + plots.export_to_xml() diff --git a/tests/unit_tests/test_region.py b/tests/unit_tests/test_region.py new file mode 100644 index 0000000000..377c8fbd58 --- /dev/null +++ b/tests/unit_tests/test_region.py @@ -0,0 +1,162 @@ +import numpy as np +import pytest +import openmc + +from tests.unit_tests import assert_unbounded + + +@pytest.fixture +def reset(): + openmc.reset_auto_ids() + + +def test_union(reset): + s1 = openmc.XPlane(surface_id=1, x0=5) + s2 = openmc.XPlane(surface_id=2, x0=-5) + region = +s1 | -s2 + assert isinstance(region, openmc.Union) + + # Check bounding box + assert_unbounded(region) + + # __contains__ + assert (6, 0, 0) in region + assert (-6, 0, 0) in region + assert (0, 0, 0) not in region + + # string representation + assert str(region) == '(1 | -2)' + + # Combining region with intersection + s3 = openmc.YPlane(surface_id=3) + reg2 = region & +s3 + assert (6, 1, 0) in reg2 + assert (6, -1, 0) not in reg2 + assert str(reg2) == '((1 | -2) 3)' + + +def test_intersection(reset): + s1 = openmc.XPlane(surface_id=1, x0=5) + s2 = openmc.XPlane(surface_id=2, x0=-5) + region = -s1 & +s2 + assert isinstance(region, openmc.Intersection) + + # Check bounding box + ll, ur = region.bounding_box + assert ll == pytest.approx((-5, -np.inf, -np.inf)) + assert ur == pytest.approx((5, np.inf, np.inf)) + + # __contains__ + assert (6, 0, 0) not in region + assert (-6, 0, 0) not in region + assert (0, 0, 0) in region + + # string representation + assert str(region) == '(-1 2)' + + # Combining region with union + s3 = openmc.YPlane(surface_id=3) + reg2 = region | +s3 + assert (-6, 2, 0) in reg2 + assert (-6, -2, 0) not in reg2 + assert str(reg2) == '((-1 2) | 3)' + + +def test_complement(reset): + zcyl = openmc.ZCylinder(surface_id=1, R=1.) + z0 = openmc.ZPlane(surface_id=2, z0=-5.) + z1 = openmc.ZPlane(surface_id=3, z0=5.) + outside = +zcyl | -z0 | +z1 + inside = ~outside + outside_equiv = ~(-zcyl & +z0 & -z1) + inside_equiv = ~outside_equiv + + # Check bounding box + for region in (inside, inside_equiv): + ll, ur = region.bounding_box + assert ll == pytest.approx((-1., -1., -5.)) + assert ur == pytest.approx((1., 1., 5.)) + assert_unbounded(outside) + assert_unbounded(outside_equiv) + + # string represention + assert str(inside) == '~(1 | -2 | 3)' + + # evaluate method + assert (0, 0, 0) in inside + assert (0, 0, 0) not in outside + assert (0, 0, 6) not in inside + assert (0, 0, 6) in outside + + +def test_get_surfaces(): + s1 = openmc.XPlane() + s2 = openmc.YPlane() + s3 = openmc.ZPlane() + region = (+s1 & -s2) | +s3 + + # Make sure get_surfaces() returns all surfaces + surfs = set(region.get_surfaces().values()) + assert not (surfs ^ {s1, s2, s3}) + + inverse = ~region + surfs = set(inverse.get_surfaces().values()) + assert not (surfs ^ {s1, s2, s3}) + + +def test_extend_clone(): + s1 = openmc.XPlane() + s2 = openmc.YPlane() + s3 = openmc.ZPlane() + s4 = openmc.ZCylinder() + + # extend intersection + r1 = +s1 & -s2 + r1 &= +s3 & -s4 + assert r1[:] == [+s1, -s2, +s3, -s4] + + # extend union + r2 = +s1 | -s2 + r2 |= +s3 | -s4 + assert r2[:] == [+s1, -s2, +s3, -s4] + + # clone methods + r3 = r1.clone() + assert len(r3) == len(r1) + r4 = r2.clone() + assert len(r4) == len(r2) + + r5 = ~r1 + r6 = r5.clone() + + +def test_from_expression(reset): + # Create surface dictionary + s1 = openmc.ZCylinder(surface_id=1) + s2 = openmc.ZPlane(surface_id=2, z0=-10.) + s3 = openmc.ZPlane(surface_id=3, z0=10.) + surfs = {1: s1, 2: s2, 3: s3} + + r = openmc.Region.from_expression('-1 2 -3', surfs) + assert isinstance(r, openmc.Intersection) + assert r[:] == [-s1, +s2, -s3] + + r = openmc.Region.from_expression('+1 | -2 | +3', surfs) + assert isinstance(r, openmc.Union) + assert r[:] == [+s1, -s2, +s3] + + r = openmc.Region.from_expression('~(-1)', surfs) + assert r == +s1 + + # Since & has higher precendence than |, the resulting region should be an + # instance of Union + r = openmc.Region.from_expression('1 -2 | 3', surfs) + assert isinstance(r, openmc.Union) + assert isinstance(r[0], openmc.Intersection) + assert r[0][:] == [+s1, -s2] + + # ...but not if we use parentheses + r = openmc.Region.from_expression('1 (-2 | 3)', surfs) + assert isinstance(r, openmc.Intersection) + assert isinstance(r[1], openmc.Union) + assert r[1][:] == [-s2, +s3] diff --git a/tests/unit_tests/test_settings.py b/tests/unit_tests/test_settings.py new file mode 100644 index 0000000000..e3bfc697eb --- /dev/null +++ b/tests/unit_tests/test_settings.py @@ -0,0 +1,55 @@ +import openmc +import openmc.stats + + +def test_export_to_xml(run_in_tmpdir): + s = openmc.Settings() + s.run_mode = 'fixed source' + s.batches = 1000 + s.generations_per_batch = 10 + s.inactive = 100 + s.particles = 1000000 + s.keff_trigger = {'type': 'std_dev', 'threshold': 0.001} + s.energy_mode = 'continuous-energy' + s.max_order = 5 + s.source = openmc.Source(space=openmc.stats.Point()) + s.output = {'summary': True, 'tallies': False, 'path': 'here'} + s.verbosity = 7 + s.sourcepoint = {'batches': [50, 150, 500, 1000], 'separate': True, + 'write': True, 'overwrite': True} + s.statepoint = {'batches': [50, 150, 500, 1000]} + s.confidence_intervals = True + s.cross_sections = '/path/to/cross_sections.xml' + s.multipole_library = '/path/to/wmp/' + s.ptables = True + s.run_cmfd = False + s.seed = 17 + s.survival_biasing = True + s.cutoff = {'weight': 0.25, 'weight_avg': 0.5, 'energy': 1.0e-5} + mesh = openmc.Mesh() + mesh.lower_left = (-10., -10., -10.) + mesh.upper_right = (10., 10., 10.) + mesh.dimension = (5, 5, 5) + s.entropy_mesh = mesh + s.trigger_active = True + s.trigger_max_batches = 10000 + s.trigger_batch_interval = 50 + s.no_reduce = False + s.tabular_legendre = {'enable': True, 'num_points': 50} + s.temperature = {'default': 293.6, 'method': 'interpolation', + 'multipole': True, 'range': (200., 1000.)} + s.threads = 8 + s.trace = (10, 1, 20) + s.track = [1, 1, 1, 2, 1, 1] + s.ufs_mesh = mesh + s.resonance_scattering = {'enable': True, 'method': 'ares', + 'energy_min': 1.0, 'energy_max': 1000.0, + 'nuclides': ['U235', 'U238', 'Pu239']} + s.volume_calculations = openmc.VolumeCalculation( + domains=[openmc.Cell()], samples=1000, lower_left=(-10., -10., -10.), + upper_right = (10., 10., 10.)) + s.create_fission_neutrons = True + s.log_grid_bins = 2000 + + # Make sure exporting XML works + s.export_to_xml() diff --git a/tests/unit_tests/test_source.py b/tests/unit_tests/test_source.py new file mode 100644 index 0000000000..3c963d0527 --- /dev/null +++ b/tests/unit_tests/test_source.py @@ -0,0 +1,30 @@ +import openmc +import openmc.stats + + +def test_source(): + space = openmc.stats.Point() + energy = openmc.stats.Discrete([1.0e6], [1.0]) + angle = openmc.stats.Isotropic() + + src = openmc.Source(space=space, angle=angle, energy=energy) + assert src.space == space + assert src.angle == angle + assert src.energy == energy + assert src.strength == 1.0 + + elem = src.to_xml_element() + assert 'strength' in elem.attrib + assert elem.find('space') is not None + assert elem.find('angle') is not None + assert elem.find('energy') is not None + + +def test_source_file(): + filename = 'source.h5' + src = openmc.Source(filename=filename) + assert src.file == filename + + elem = src.to_xml_element() + assert 'strength' in elem.attrib + assert 'file' in elem.attrib diff --git a/tests/unit_tests/test_stats.py b/tests/unit_tests/test_stats.py new file mode 100644 index 0000000000..388408bb22 --- /dev/null +++ b/tests/unit_tests/test_stats.py @@ -0,0 +1,179 @@ +from math import pi + +import numpy as np +import pytest +import openmc +import openmc.stats + + +def test_discrete(): + x = [0.0, 1.0, 10.0] + p = [0.3, 0.2, 0.5] + d = openmc.stats.Discrete(x, p) + assert d.x == x + assert d.p == p + assert len(d) == len(x) + d.to_xml_element('distribution') + + # Single point + d2 = openmc.stats.Discrete(1e6, 1.0) + assert d2.x == [1e6] + assert d2.p == [1.0] + assert len(d2) == 1 + + +def test_uniform(): + a, b = 10.0, 20.0 + d = openmc.stats.Uniform(a, b) + assert d.a == a + assert d.b == b + assert len(d) == 2 + + t = d.to_tabular() + assert t.x == [a, b] + assert t.p == [1/(b-a), 1/(b-a)] + assert t.interpolation == 'histogram' + + d.to_xml_element('distribution') + + +def test_maxwell(): + theta = 1.2895e6 + d = openmc.stats.Maxwell(theta) + assert d.theta == theta + assert len(d) == 1 + d.to_xml_element('distribution') + + +def test_watt(): + a, b = 0.965e6, 2.29e-6 + d = openmc.stats.Watt(a, b) + assert d.a == a + assert d.b == b + assert len(d) == 2 + d.to_xml_element('distribution') + + +def test_tabular(): + x = [0.0, 5.0, 7.0] + p = [0.1, 0.2, 0.05] + d = openmc.stats.Tabular(x, p, 'linear-linear') + assert d.x == x + assert d.p == p + assert d.interpolation == 'linear-linear' + assert len(d) == len(x) + d.to_xml_element('distribution') + + +def test_legendre(): + # Pu239 elastic scattering at 100 keV + coeffs = [1.000e+0, 1.536e-1, 1.772e-2, 5.945e-4, 3.497e-5, 1.881e-5] + d = openmc.stats.Legendre(coeffs) + assert d.coefficients == pytest.approx(coeffs) + assert len(d) == len(coeffs) + + # Integrating distribution should yield one + mu = np.linspace(-1., 1., 1000) + assert np.trapz(d(mu), mu) == pytest.approx(1.0, rel=1e-4) + + with pytest.raises(NotImplementedError): + d.to_xml_element('distribution') + + +def test_mixture(): + d1 = openmc.stats.Uniform(0, 5) + d2 = openmc.stats.Uniform(3, 7) + p = [0.5, 0.5] + mix = openmc.stats.Mixture(p, [d1, d2]) + assert mix.probability == p + assert mix.distribution == [d1, d2] + assert len(mix) == 4 + + with pytest.raises(NotImplementedError): + mix.to_xml_element('distribution') + + +def test_polar_azimuthal(): + # default polar-azimuthal should be uniform in mu and phi + d = openmc.stats.PolarAzimuthal() + assert isinstance(d.mu, openmc.stats.Uniform) + assert d.mu.a == -1. + assert d.mu.b == 1. + assert isinstance(d.phi, openmc.stats.Uniform) + assert d.phi.a == 0. + assert d.phi.b == 2*pi + + mu = openmc.stats.Discrete(1., 1.) + phi = openmc.stats.Discrete(0., 1.) + d = openmc.stats.PolarAzimuthal(mu, phi) + assert d.mu == mu + assert d.phi == phi + + elem = d.to_xml_element() + assert elem.tag == 'angle' + assert elem.attrib['type'] == 'mu-phi' + assert elem.find('mu') is not None + assert elem.find('phi') is not None + + +def test_isotropic(): + d = openmc.stats.Isotropic() + elem = d.to_xml_element() + assert elem.tag == 'angle' + assert elem.attrib['type'] == 'isotropic' + + +def test_monodirectional(): + d = openmc.stats.Monodirectional((1., 0., 0.)) + assert d.reference_uvw == pytest.approx((1., 0., 0.)) + + elem = d.to_xml_element() + assert elem.tag == 'angle' + assert elem.attrib['type'] == 'monodirectional' + + +def test_cartesian(): + x = openmc.stats.Uniform(-10., 10.) + y = openmc.stats.Uniform(-10., 10.) + z = openmc.stats.Uniform(0., 20.) + d = openmc.stats.CartesianIndependent(x, y, z) + assert d.x == x + assert d.y == y + assert d.z == z + + elem = d.to_xml_element() + assert elem.tag == 'space' + assert elem.attrib['type'] == 'cartesian' + assert elem.find('x') is not None + assert elem.find('y') is not None + + +def test_box(): + lower_left = (-10., -10., -10.) + upper_right = (10., 10., 10.) + d = openmc.stats.Box(lower_left, upper_right) + assert d.lower_left == pytest.approx(lower_left) + assert d.upper_right == pytest.approx(upper_right) + assert not d.only_fissionable + + elem = d.to_xml_element() + assert elem.tag == 'space' + assert elem.attrib['type'] == 'box' + assert elem.find('parameters') is not None + + # only fissionable parameter + d2 = openmc.stats.Box(lower_left, upper_right, True) + assert d2.only_fissionable + elem = d2.to_xml_element() + assert elem.attrib['type'] == 'fission' + + +def test_point(): + p = (-4., 2., 10.) + d = openmc.stats.Point(p) + assert d.xyz == pytest.approx(p) + + elem = d.to_xml_element() + assert elem.tag == 'space' + assert elem.attrib['type'] == 'point' + assert elem.find('parameters') is not None diff --git a/tests/unit_tests/test_surface.py b/tests/unit_tests/test_surface.py new file mode 100644 index 0000000000..3db84cc053 --- /dev/null +++ b/tests/unit_tests/test_surface.py @@ -0,0 +1,259 @@ +import numpy as np +import openmc +import pytest + + +def assert_infinite_bb(s): + ll, ur = (-s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + + +def test_plane(): + s = openmc.Plane(A=1, B=2, C=-1, D=3, name='my plane') + assert s.a == 1 + assert s.b == 2 + assert s.c == -1 + assert s.d == 3 + assert s.boundary_type == 'transmission' + assert s.name == 'my plane' + assert s.type == 'plane' + + # Generic planes don't have well-defined bounding boxes + assert_infinite_bb(s) + + # evaluate method + x, y, z = (4, 3, 6) + assert s.evaluate((x, y, z)) == pytest.approx(s.a*x + s.b*y + s.c*z - s.d) + + # Make sure repr works + repr(s) + + +def test_xplane(): + s = openmc.XPlane(x0=3., boundary_type='reflective') + assert s.x0 == 3. + assert s.boundary_type == 'reflective' + + # Check bounding box + ll, ur = (+s).bounding_box + assert ll == pytest.approx((3., -np.inf, -np.inf)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ur == pytest.approx((3., np.inf, np.inf)) + assert np.all(np.isinf(ll)) + + # __contains__ on associated half-spaces + assert (5, 0, 0) in +s + assert (5, 0, 0) not in -s + assert (-2, 1, 10) in -s + assert (-2, 1, 10) not in +s + + # evaluate method + assert s.evaluate((5., 0., 0.)) == pytest.approx(2.) + + # Make sure repr works + repr(s) + + +def test_yplane(): + s = openmc.YPlane(y0=3.) + assert s.y0 == 3. + + # Check bounding box + ll, ur = (+s).bounding_box + assert ll == pytest.approx((-np.inf, 3., -np.inf)) + assert np.all(np.isinf(ur)) + ll, ur = s.bounding_box('-') + assert ur == pytest.approx((np.inf, 3., np.inf)) + assert np.all(np.isinf(ll)) + + # __contains__ on associated half-spaces + assert (0, 5, 0) in +s + assert (0, 5, 0) not in -s + assert (-2, 1, 10) in -s + assert (-2, 1, 10) not in +s + + # evaluate method + assert s.evaluate((0., 0., 0.)) == pytest.approx(-3.) + + +def test_zplane(): + s = openmc.ZPlane(z0=3.) + assert s.z0 == 3. + + # Check bounding box + ll, ur = (+s).bounding_box + assert ll == pytest.approx((-np.inf, -np.inf, 3.)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ur == pytest.approx((np.inf, np.inf, 3.)) + assert np.all(np.isinf(ll)) + + # __contains__ on associated half-spaces + assert (0, 0, 5) in +s + assert (0, 0, 5) not in -s + assert (-2, 1, -10) in -s + assert (-2, 1, -10) not in +s + + # evaluate method + assert s.evaluate((0., 0., 10.)) == pytest.approx(7.) + + # Make sure repr works + repr(s) + + +def test_xcylinder(): + y, z, r = 3, 5, 2 + s = openmc.XCylinder(y0=y, z0=z, R=r) + assert s.y0 == y + assert s.z0 == z + assert s.r == r + + # Check bounding box + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ll == pytest.approx((-np.inf, y-r, z-r)) + assert ur == pytest.approx((np.inf, y+r, z+r)) + + # evaluate method + assert s.evaluate((0, y, z)) == pytest.approx(-r**2) + + # Make sure repr works + repr(s) + + +def test_periodic(): + x = openmc.XPlane(boundary_type='periodic') + y = openmc.YPlane(boundary_type='periodic') + x.periodic_surface = y + assert y.periodic_surface == x + with pytest.raises(TypeError): + x.periodic_surface = openmc.Sphere() + + +def test_ycylinder(): + x, z, r = 3, 5, 2 + s = openmc.YCylinder(x0=x, z0=z, R=r) + assert s.x0 == x + assert s.z0 == z + assert s.r == r + + # Check bounding box + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ll == pytest.approx((x-r, -np.inf, z-r)) + assert ur == pytest.approx((x+r, np.inf, z+r)) + + # evaluate method + assert s.evaluate((x, 0, z)) == pytest.approx(-r**2) + + +def test_zcylinder(): + x, y, r = 3, 5, 2 + s = openmc.ZCylinder(x0=x, y0=y, R=r) + assert s.x0 == x + assert s.y0 == y + assert s.r == r + + # Check bounding box + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ll == pytest.approx((x-r, y-r, -np.inf)) + assert ur == pytest.approx((x+r, y+r, np.inf)) + + # evaluate method + assert s.evaluate((x, y, 0)) == pytest.approx(-r**2) + + # Make sure repr works + repr(s) + + +def test_sphere(): + x, y, z, r = -3, 5, 6, 2 + s = openmc.Sphere(x0=x, y0=y, z0=z, R=r) + assert s.x0 == x + assert s.y0 == y + assert s.z0 == z + assert s.r == r + + # Check bounding box + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ll == pytest.approx((x-r, y-r, z-r)) + assert ur == pytest.approx((x+r, y+r, z+r)) + + # evaluate method + assert s.evaluate((x, y, z)) == pytest.approx(-r**2) + + # Make sure repr works + repr(s) + + +def cone_common(apex, r2, cls): + x, y, z = apex + s = cls(x0=x, y0=y, z0=z, R2=r2) + assert s.x0 == x + assert s.y0 == y + assert s.z0 == z + assert s.r2 == r2 + + # Check bounding box + assert_infinite_bb(s) + + # evaluate method -- should be zero at apex + assert s.evaluate((x, y, z)) == pytest.approx(0.0) + + # Make sure repr works + repr(s) + + +def test_xcone(): + apex = (10, 0, 0) + r2 = 4 + cone_common(apex, r2, openmc.XCone) + + +def test_ycone(): + apex = (10, 0, 0) + r2 = 4 + cone_common(apex, r2, openmc.YCone) + + +def test_zcone(): + apex = (10, 0, 0) + r2 = 4 + cone_common(apex, r2, openmc.ZCone) + + +def test_quadric(): + # Make a sphere from a quadric + r = 10.0 + coeffs = {'a': 1, 'b': 1, 'c': 1, 'k': -r**2} + s = openmc.Quadric(**coeffs) + assert s.a == coeffs['a'] + assert s.b == coeffs['b'] + assert s.c == coeffs['c'] + assert s.k == coeffs['k'] + + # All other coeffs should be zero + for coeff in ('d', 'e', 'f', 'g', 'h', 'j'): + assert getattr(s, coeff) == 0.0 + + # Check bounding box + assert_infinite_bb(s) + + # evaluate method + assert s.evaluate((0., 0., 0.)) == pytest.approx(coeffs['k']) + assert s.evaluate((1., 1., 1.)) == pytest.approx(3 + coeffs['k']) diff --git a/tests/unit_tests/test_universe.py b/tests/unit_tests/test_universe.py new file mode 100644 index 0000000000..89904524b6 --- /dev/null +++ b/tests/unit_tests/test_universe.py @@ -0,0 +1,112 @@ +import xml.etree.ElementTree as ET + +import numpy as np +import openmc +import pytest + +from tests.unit_tests import assert_unbounded + + +def test_basic(): + c1 = openmc.Cell() + c2 = openmc.Cell() + c3 = openmc.Cell() + u = openmc.Universe(name='cool', cells=(c1, c2, c3)) + assert u.name == 'cool' + + cells = set(u.cells.values()) + assert not (cells ^ {c1, c2, c3}) + + # Test __repr__ + repr(u) + + with pytest.raises(TypeError): + u.add_cell(openmc.Material()) + with pytest.raises(TypeError): + u.add_cells(c1) + + u.remove_cell(c3) + cells = set(u.cells.values()) + assert not (cells ^ {c1, c2}) + + u.clear_cells() + assert not set(u.cells) + + +def test_bounding_box(): + cyl1 = openmc.ZCylinder(R=1.0) + cyl2 = openmc.ZCylinder(R=2.0) + c1 = openmc.Cell(region=-cyl1) + c2 = openmc.Cell(region=+cyl1 & -cyl2) + + u = openmc.Universe(cells=[c1, c2]) + ll, ur = u.bounding_box + assert ll == pytest.approx((-2., -2., -np.inf)) + assert ur == pytest.approx((2., 2., np.inf)) + + u = openmc.Universe() + assert_unbounded(u) + + +def test_plot(run_in_tmpdir, sphere_model): + m = sphere_model.materials[0] + univ = sphere_model.geometry.root_universe + + colors = {m: 'limegreen'} + for basis in ('xy', 'yz', 'xz'): + univ.plot( + basis=basis, + pixels=(10, 10), + color_by='material', + colors=colors, + ) + + +def test_get_nuclides(uo2): + c = openmc.Cell(fill=uo2) + univ = openmc.Universe(cells=[c]) + nucs = univ.get_nuclides() + assert nucs == ['U235', 'O16'] + + +def test_cells(): + cells = [openmc.Cell() for i in range(5)] + cells2 = [openmc.Cell() for i in range(3)] + cells[0].fill = openmc.Universe(cells=cells2) + u = openmc.Universe(cells=cells) + assert not (set(u.cells.values()) ^ set(cells)) + + all_cells = set(u.get_all_cells().values()) + assert not (all_cells ^ set(cells + cells2)) + + +def test_get_all_materials(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + test_mats = set(univ.get_all_materials().values()) + assert not (test_mats ^ set(mats)) + + +def test_get_all_universes(): + c1 = openmc.Cell() + u1 = openmc.Universe(cells=[c1]) + c2 = openmc.Cell() + u2 = openmc.Universe(cells=[c2]) + c3 = openmc.Cell(fill=u1) + c4 = openmc.Cell(fill=u2) + u3 = openmc.Universe(cells=[c3, c4]) + + univs = set(u3.get_all_universes().values()) + assert not (univs ^ {u1, u2}) + + +def test_create_xml(cell_with_lattice): + cells = [openmc.Cell() for i in range(5)] + u = openmc.Universe(cells=cells) + + geom = ET.Element('geom') + u.create_xml_subelement(geom) + cell_elems = geom.findall('cell') + assert len(cell_elems) == len(cells) + assert all(c.get('universe') == str(u.id) for c in cell_elems) + assert not (set(c.get('id') for c in cell_elems) ^ + set(str(c.id) for c in cells)) diff --git a/tests/update_results.py b/tests/update_results.py deleted file mode 100755 index 5656003331..0000000000 --- a/tests/update_results.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python - -from __future__ import print_function - -import os -import re -from subprocess import Popen, call, STDOUT, PIPE -from glob import glob -from optparse import OptionParser - -parser = OptionParser() -parser.add_option('-R', '--tests-regex', dest='regex_tests', - help="Run tests matching regular expression. \ - Test names are the directories present in tests folder.\ - This uses standard regex syntax to select tests.") -(opts, args) = parser.parse_args() -cwd = os.getcwd() - -# Terminal color configurations -OKGREEN = '\033[92m' -FAIL = '\033[91m' -ENDC = '\033[0m' -BOLD = '\033[1m' - -# Get a list of all test folders -folders = glob('test_*') - -# Check to see if a subset of tests is specified on command line -if opts.regex_tests is not None: - folders = [item for item in folders if re.search(opts.regex_tests, item)] - -# Loop around directories -for adir in sorted(folders): - - # Go into that directory - os.chdir(adir) - pwd = os.path.abspath(os.path.dirname('settings.xml')) - os.putenv('PWD', pwd) - - # Print status to screen - print(adir, end="") - sz = len(adir) - for i in range(35 - sz): - print('.', end="") - - # Find the test executable - test_exec = glob('test_*.py') - assert len(test_exec) == 1, 'There must be only one test executable per ' \ - 'test directory' - - # Update the test results - proc = Popen(['python', test_exec[0], '--update']) - returncode = proc.wait() - if returncode == 0: - print(BOLD + OKGREEN + "[OK]" + ENDC) - else: - print(BOLD + FAIL + "[FAILED]" + ENDC) - - # Go back a directory - os.chdir('..') diff --git a/tests/valgrind.supp b/tests/valgrind.supp deleted file mode 100644 index ad302c5397..0000000000 --- a/tests/valgrind.supp +++ /dev/null @@ -1,63 +0,0 @@ -{ - Create HDF5 statepoint file - Memcheck:Addr4 - fun:H5_build_extpath - fun:H5F_open - fun:H5Fcreate - fun:h5fcreate_c_ - fun:__h5f_MOD_h5fcreate_f - fun:__hdf5_interface_MOD_hdf5_file_create - fun:__output_interface_MOD_file_create - fun:__state_point_MOD_write_state_point - fun:__eigenvalue_MOD_finalize_batch - fun:__eigenvalue_MOD_run_eigenvalue - fun:MAIN__ - fun:main -} -{ - Open HDF5 statepoint file - Memcheck:Addr4 - fun:H5_build_extpath - fun:H5F_open - fun:H5Fopen - fun:h5fopen_c_ - fun:__h5f_MOD_h5fopen_f - fun:__hdf5_interface_MOD_hdf5_file_open - fun:__output_interface_MOD_file_open - fun:__state_point_MOD_write_source_point - fun:__eigenvalue_MOD_finalize_batch - fun:__eigenvalue_MOD_run_eigenvalue - fun:MAIN__ - fun:main -} -{ - Create HDF5 summary file - Memcheck:Addr4 - fun:H5_build_extpath - fun:H5F_open - fun:H5Fcreate - fun:h5fcreate_c_ - fun:__h5f_MOD_h5fcreate_f - fun:__hdf5_interface_MOD_hdf5_file_create - fun:__output_interface_MOD_file_create - fun:__hdf5_summary_MOD_hdf5_write_summary - fun:__initialize_MOD_initialize_run - fun:MAIN__ - fun:main -} -{ - Create HDF5 track file - Memcheck:Addr4 - fun:H5_build_extpath - fun:H5F_open - fun:H5Fcreate - fun:h5fcreate_c_ - fun:__h5f_MOD_h5fcreate_f - fun:__hdf5_interface_MOD_hdf5_file_create - fun:__output_interface_MOD_file_create - fun:__track_output_MOD_finalize_particle_track - fun:__tracking_MOD_transport - fun:__eigenvalue_MOD_run_eigenvalue - fun:MAIN__ - fun:main -} diff --git a/tools/ci/travis-before-script.sh b/tools/ci/travis-before-script.sh index bbf4980b0f..d0df06f2fd 100755 --- a/tools/ci/travis-before-script.sh +++ b/tools/ci/travis-before-script.sh @@ -1,6 +1,10 @@ #!/bin/bash set -ex +# Allow tests that require GUI as described at: +# https://docs.travis-ci.com/user/gui-and-headless-browsers/#Using-xvfb-to-Run-Tests-That-Require-a-GUI +sh -e /etc/init.d/xvfb start + # Download NNDC HDF5 data if [[ ! -e $HOME/nndc_hdf5/cross_sections.xml ]]; then wget https://anl.box.com/shared/static/a6sw2cep34wlz6b9i9jwiotaqoayxcxt.xz -O - | tar -C $HOME -xvJ diff --git a/tools/ci/travis-install.py b/tools/ci/travis-install.py new file mode 100644 index 0000000000..15e4d576b7 --- /dev/null +++ b/tools/ci/travis-install.py @@ -0,0 +1,70 @@ +import os +import shutil +import subprocess + + +def which(program): + def is_exe(fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ["PATH"].split(os.pathsep): + path = path.strip('"') + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + return None + + +def install(omp=False, mpi=False, phdf5=False): + # Create build directory and change to it + shutil.rmtree('build', ignore_errors=True) + os.mkdir('build') + os.chdir('build') + + # Build in debug mode by default + cmake_cmd = ['cmake', '-Ddebug=on'] + + # Turn off OpenMP if specified + if not omp: + cmake_cmd.append('-Dopenmp=off') + + # Use MPI wrappers when building in parallel + if mpi: + os.environ['FC'] = 'mpifort' if which('mpifort') else 'mpif90' + os.environ['CC'] = 'mpicc' + os.environ['CXX'] = 'mpicxx' + + # Tell CMake to prefer parallel HDF5 if specified + if phdf5: + if not mpi: + raise ValueError('Parallel HDF5 must be used in ' + 'conjunction with MPI.') + cmake_cmd.append('-DHDF5_PREFER_PARALLEL=ON') + else: + cmake_cmd.append('-DHDF5_PREFER_PARALLEL=OFF') + + # Build and install + cmake_cmd.append('..') + print(' '.join(cmake_cmd)) + subprocess.check_call(cmake_cmd) + subprocess.check_call(['make', '-j']) + subprocess.check_call(['sudo', 'make', 'install']) + + +def main(): + # Convert Travis matrix environment variables into arguments for install() + omp = (os.environ.get('OMP') == 'y') + mpi = (os.environ.get('MPI') == 'y') + phdf5 = (os.environ.get('PHDF5') == 'y') + + # Build and install + install(omp, mpi, phdf5) + + +if __name__ == '__main__': + main() diff --git a/tools/ci/travis-install.sh b/tools/ci/travis-install.sh index 354ae7f7f4..2342cdadbc 100755 --- a/tools/ci/travis-install.sh +++ b/tools/ci/travis-install.sh @@ -4,16 +4,30 @@ set -ex # Install NJOY 2016 ./tools/ci/travis-install-njoy.sh -# Running OpenMC's setup.py requires numpy/cython already -pip install numpy cython +# Running OpenMC's setup.py requires numpy/cython already. NumPy float +# formatting changed in version 1.14, so stick with a lower version until we can +# handle it in our test suite +pip install 'numpy<1.14' +pip install cython # pytest installed by default -- make sure we get latest pip install --upgrade pytest # Pandas stopped supporting Python 3.4 with version 0.21 -if [[ "$TRAVIS_PYTHON_VERSION" == "3.4" ]]; then +if [[ $TRAVIS_PYTHON_VERSION == "3.4" ]]; then pip install pandas==0.20.3 fi -# Install OpenMC in editable mode +# Install mpi4py for MPI configurations +if [[ $MPI == 'y' ]]; then + pip install --no-binary=mpi4py mpi4py +fi + +# Build and install OpenMC executable +python tools/ci/travis-install.py + +# Install Python API in editable mode pip install -e .[test] + +# For uploading to coveralls +pip install python-coveralls diff --git a/tools/ci/travis-script.sh b/tools/ci/travis-script.sh index 978a2811c4..ee445b517f 100755 --- a/tools/ci/travis-script.sh +++ b/tools/ci/travis-script.sh @@ -1,8 +1,14 @@ #!/bin/bash set -ex -cd tests -if [[ $TRAVIS_PYTHON_VERSION == "3.4" && $OPENMC_CONFIG == '^hdf5-debug$' ]]; then - ./check_source.py + +# Run source check +if [[ $TRAVIS_PYTHON_VERSION == "3.4" && $OMP == 'n' && $MPI == 'n' ]]; then + pushd tests && python check_source.py && popd +fi + +# Run regression and unit tests +if [[ $MPI == 'y' ]]; then + pytest --cov=openmc -v --mpi tests +else + pytest --cov=openmc -v tests fi -./run_tests.py -C $OPENMC_CONFIG -j 2 -pytest --cov=../openmc -v unit_tests/