From aafc89d475e095a19778739ad77a1b36807ec275 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 6 Oct 2016 17:07:32 -0500 Subject: [PATCH 1/8] Add instructions for installing from conda-forge --- docs/source/quickinstall.rst | 20 +++++++++++++++++++ docs/source/usersguide/install.rst | 32 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/docs/source/quickinstall.rst b/docs/source/quickinstall.rst index 7faa4978dd..8e970d9587 100644 --- a/docs/source/quickinstall.rst +++ b/docs/source/quickinstall.rst @@ -8,6 +8,26 @@ This quick install guide outlines the basic steps needed to install OpenMC on your computer. For more detailed instructions on configuring and installing OpenMC, see :ref:`usersguide_install` in the User's Manual. +---------------------------------------- +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. If +you have `conda` installed on your system, OpenMC can be installed via the +`conda-forge` channel. First, add the `conda-forge` channel with: + +.. code-block:: sh + + conda config --add channels conda-forge + +OpenMC can then be installed with: + +.. code-block:: sh + + conda install openmc + -------------------------------- Installing on Ubuntu through PPA -------------------------------- diff --git a/docs/source/usersguide/install.rst b/docs/source/usersguide/install.rst index 3dab08e9d3..5abd48ee0d 100644 --- a/docs/source/usersguide/install.rst +++ b/docs/source/usersguide/install.rst @@ -4,6 +4,38 @@ Installation and Configuration ============================== +---------------------------------------- +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 +`_. + +Once you have `conda` installed on your system, add the `conda-forge` channel to +your configuration with: + +.. code-block:: sh + + conda config --add channels conda-forge + +Once the `conda-forge` channel has been enabled, OpenMC can then be installed +with: + +.. code-block:: sh + + conda install openmc + +It is possible to list all of the versions of OpenMC available on your platform with: + +.. code-block:: sh + + conda search openmc --channel conda-forge + ----------------------------- Installing on Ubuntu with PPA ----------------------------- From f1ea8cfaaa6f694b5e829e1aeb98393166a694e9 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 6 Oct 2016 17:18:14 -0500 Subject: [PATCH 2/8] Move scripts in data/ folder to scripts/ --- data/readme.rst | 37 ------------------- docs/source/usersguide/install.rst | 34 +++++++---------- .../openmc-convert-mcnp70-data | 0 .../openmc-convert-mcnp71-data | 0 .../openmc-get-jeff-data | 0 .../openmc-get-multipole-data | 0 .../openmc-get-nndc-data | 0 7 files changed, 14 insertions(+), 57 deletions(-) delete mode 100644 data/readme.rst rename data/convert_mcnp_70.py => scripts/openmc-convert-mcnp70-data (100%) rename data/convert_mcnp_71.py => scripts/openmc-convert-mcnp71-data (100%) rename data/get_jeff_data.py => scripts/openmc-get-jeff-data (100%) rename data/get_multipole_data.py => scripts/openmc-get-multipole-data (100%) rename data/get_nndc_data.py => scripts/openmc-get-nndc-data (100%) diff --git a/data/readme.rst b/data/readme.rst deleted file mode 100644 index 03685491d0..0000000000 --- a/data/readme.rst +++ /dev/null @@ -1,37 +0,0 @@ -======================== -cross_sections.xml Files -======================== - -As a reminder, in order to run a simulation with OpenMC, you will need cross -section data for each nuclide in your problem. OpenMC is not currently -distributed with cross section data, so you will have to obtain cross section -data by other means. The `user's guide`_ offers some helpful advice on how you -can obtain cross sections. - -When OpenMC starts up, it needs a cross_sections.xml file that tells it where to -find ACE format cross sections. The files in this directory are configured to -work with a few common cross section sources. - -- **cross_sections_ascii.xml** -- This file matches ENDF/B-VII.0 cross sections - distributed with MCNP5 / MCNP6 beta. - -- **cross_sections_nndc.xml** -- This file matches ENDF/B-VII.1 cross sections - distributed from the `NNDC website`_. - -- **cross_sections_serpent.xml** -- This file matches ENDF/B-VII.0 cross - sections distributed with Serpent 1.1.7. - -- **cross_sections.xml** - This file matches ENDF/B-VII.0 cross sections - distributed with MCNP5 / MCNP6 beta *that have been converted to binary*. - -To use any of these files, you need to follow two steps: - -1. Change the path on the ```` element in the cross_sections.xml file -to the directory containing the ACE files. - -2. Enter the absolute path of the cross_sections.xml on the ```` -element in your settings.xml, or set the CROSS_SECTIONS environment variable to -the full path of the cross_sections.xml file. - -.. _user's guide: http://mit-crpg.github.io/openmc/usersguide/install.html#cross-section-configuration -.. _NNDC website: http://www.nndc.bnl.gov/endf/b7.1/acefiles.html diff --git a/docs/source/usersguide/install.rst b/docs/source/usersguide/install.rst index 5abd48ee0d..0b75bf1904 100644 --- a/docs/source/usersguide/install.rst +++ b/docs/source/usersguide/install.rst @@ -439,13 +439,11 @@ extract the ACE data, fix any deficiencies, and create an HDF5 library: .. code-block:: sh - cd openmc/data - python get_nndc_data.py + openmc-get-nndc-data At this point, you should set the :envvar:`OPENMC_CROSS_SECTIONS` environment -variable to the absolute path of the file -``openmc/data/nndc_hdf5/cross_sections.xml``. This cross section set is used by -the test suite. +variable to the absolute path of the file ``nndc_hdf5/cross_sections.xml``. This +cross section set is used by the test suite. Using JEFF Cross Sections from OECD/NEA --------------------------------------- @@ -456,12 +454,10 @@ and extract the ACE data, fix any deficiencies, and create an HDF5 library. .. code-block:: sh - cd openmc/data - python get_jeff_data.py + openmc-get-jeff-data At this point, you should set the :envvar:`OPENMC_CROSS_SECTIONS` environment -variable to the absolute path of the file -``openmc/data/jeff-3.2-hdf5/cross_sections.xml``. +variable to the absolute path of the file ``jeff-3.2-hdf5/cross_sections.xml``. Using Cross Sections from MCNP ------------------------------ @@ -473,8 +469,7 @@ format, run the following: .. code-block:: sh - cd openmc/data - python convert_mcnp_endf70.py /path/to/mcnpdata/ + openmc-convert-mcnp70-data /path/to/mcnpdata/ where ``/path/to/mcnpdata`` is the directory containing the ``endf70[a-k]`` files. @@ -484,8 +479,7 @@ the following script: .. code-block:: sh - cd openmc/data - python convert_mcnp_endf71.py /path/to/mcnpdata + openmc-convert-mcnp71-data /path/to/mcnpdata where ``/path/to/mcnpdata`` is the directory containing the ``endf71x`` and ``ENDF71SaB`` directories. @@ -502,16 +496,16 @@ that are to be converted: 1. List each ACE library as a positional argument. This is very useful in conjunction with the usual shell utilities (ls, find, etc.). -2. Use the --xml option to specify a pre-v0.9 cross_sections.xml file. -3. Use the --xsdir option to specify a MCNP xsdir file. -4. Use the --xsdata option to specify a Serpent xsdata file. +2. Use the ``--xml`` option to specify a pre-v0.9 cross_sections.xml file. +3. Use the ``--xsdir` option to specify a MCNP xsdir file. +4. Use the ``--xsdata`` option to specify a Serpent xsdata file. The script does not use any extra information from cross_sections.xml/ xsdir/ xsdata files to determine whether the nuclide is metastable. Instead, the ---metastable argument can be used to specify whether the ZAID naming convention -follows the NNDC data convention (1000*Z + A + 300 + 100*m), or the MCNP data -convention (essentially the same as NNDC, except that the first metastable state -of Am242 is 95242 and the ground state is 95642). +``--metastable`` argument can be used to specify whether the ZAID naming +convention follows the NNDC data convention (1000*Z + A + 300 + 100*m), or the +MCNP data convention (essentially the same as NNDC, except that the first +metastable state of Am242 is 95242 and the ground state is 95642). The ``openmc-ace-to-hdf5`` script has the following command-line flags: diff --git a/data/convert_mcnp_70.py b/scripts/openmc-convert-mcnp70-data similarity index 100% rename from data/convert_mcnp_70.py rename to scripts/openmc-convert-mcnp70-data diff --git a/data/convert_mcnp_71.py b/scripts/openmc-convert-mcnp71-data similarity index 100% rename from data/convert_mcnp_71.py rename to scripts/openmc-convert-mcnp71-data diff --git a/data/get_jeff_data.py b/scripts/openmc-get-jeff-data similarity index 100% rename from data/get_jeff_data.py rename to scripts/openmc-get-jeff-data diff --git a/data/get_multipole_data.py b/scripts/openmc-get-multipole-data similarity index 100% rename from data/get_multipole_data.py rename to scripts/openmc-get-multipole-data diff --git a/data/get_nndc_data.py b/scripts/openmc-get-nndc-data similarity index 100% rename from data/get_nndc_data.py rename to scripts/openmc-get-nndc-data From 24af2829b9dc637eeddcd6df06d0bf0be317e504 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 6 Oct 2016 18:21:58 -0500 Subject: [PATCH 3/8] Add description in scripts and use six for imports --- .travis.yml | 2 +- scripts/openmc-convert-mcnp70-data | 19 ++++++++++++--- scripts/openmc-convert-mcnp71-data | 19 ++++++++++++--- scripts/openmc-get-jeff-data | 28 +++++++++++++--------- scripts/openmc-get-multipole-data | 35 ++++++++++++++------------- scripts/openmc-get-nndc-data | 38 +++++++++++++++++------------- setup.py | 2 +- 7 files changed, 91 insertions(+), 52 deletions(-) diff --git a/.travis.yml b/.travis.yml index 46bb847e6a..19535d23b4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,7 +28,7 @@ before_install: - conda config --set always_yes yes --set changeps1 no - conda update -q conda - conda info -a - - conda create -q -n test-environment python=$TRAVIS_PYTHON_VERSION numpy scipy h5py=2.5 pandas + - conda create -q -n test-environment python=$TRAVIS_PYTHON_VERSION six numpy scipy h5py=2.5 pandas - source activate test-environment # Install GCC, MPICH, HDF5, PHDF5 diff --git a/scripts/openmc-convert-mcnp70-data b/scripts/openmc-convert-mcnp70-data index e68bd848e1..a3081e3ee1 100755 --- a/scripts/openmc-convert-mcnp70-data +++ b/scripts/openmc-convert-mcnp70-data @@ -1,7 +1,7 @@ #!/usr/bin/env python from __future__ import print_function -from argparse import ArgumentParser +import argparse from collections import defaultdict import glob import os @@ -9,8 +9,21 @@ import os import openmc.data -# Get path to MCNP data -parser = ArgumentParser() +description = """ +Convert ENDF/B-VII.0 ACE data from the MCNP5/6 distribution into an HDF5 library +that can be used by OpenMC. This assumes that you have a directory containing +files named endf70a, endf70b, ..., endf70k, and endf70sab. + +""" + +class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, + argparse.RawDescriptionHelpFormatter): + pass + +parser = argparse.ArgumentParser( + description=description, + formatter_class=CustomFormatter +) parser.add_argument('-d', '--destination', default='mcnp_endfb70', help='Directory to create new library in') parser.add_argument('mcnpdata', help='Directory containing endf70[a-k] and endf70sab') diff --git a/scripts/openmc-convert-mcnp71-data b/scripts/openmc-convert-mcnp71-data index 7e7fd923f1..9440959197 100755 --- a/scripts/openmc-convert-mcnp71-data +++ b/scripts/openmc-convert-mcnp71-data @@ -1,7 +1,7 @@ #!/usr/bin/env python from __future__ import print_function -from argparse import ArgumentParser +import argparse from collections import defaultdict import glob import os @@ -9,8 +9,21 @@ import os import openmc.data -# Get path to MCNP data -parser = ArgumentParser() +description = """ +Convert ENDF/B-VII.1 ACE data from the MCNP6 distribution into an HDF5 library +that can be used by OpenMC. This assumes that you have a directory containing +subdirectories 'endf71x' and 'ENDF71SaB'. + +""" + +class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, + argparse.RawDescriptionHelpFormatter): + pass + +parser = argparse.ArgumentParser( + description=description, + formatter_class=CustomFormatter +) parser.add_argument('-d', '--destination', default='mcnp_endfb71', help='Directory to create new library in') parser.add_argument('-f', '--fission_energy_release', diff --git a/scripts/openmc-get-jeff-data b/scripts/openmc-get-jeff-data index d0e5839b93..3166b3854e 100755 --- a/scripts/openmc-get-jeff-data +++ b/scripts/openmc-get-jeff-data @@ -10,18 +10,17 @@ import glob import argparse from string import digits +from six.moves import input +from six.moves.urllib.request import urlopen + import openmc.data -try: - from urllib.request import urlopen -except ImportError: - from urllib2 import urlopen -if sys.version_info[0] < 3: - askuser = raw_input -else: - askuser = input +description = """ +Download JEFF 3.2 ACE data from OECD/NEA and convert it to a multi-temperature +HDF5 library for use with OpenMC. +""" download_warning = """ WARNING: This script will download approximately 9 GB of data. Extracting and @@ -32,14 +31,21 @@ space. Note that if you don't need all 11 temperatures, you can modify the Are you sure you want to continue? ([y]/n) """ -parser = argparse.ArgumentParser() +class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, + argparse.RawDescriptionHelpFormatter): + pass + +parser = argparse.ArgumentParser( + description=description, + formatter_class=CustomFormatter +) parser.add_argument('-b', '--batch', action='store_true', help='supresses standard in') parser.add_argument('-d', '--destination', default='jeff-3.2-hdf5', help='Directory to create new library in') args = parser.parse_args() -response = askuser(download_warning) if not args.batch else 'y' +response = input(download_warning) if not args.batch else 'y' if response.lower().startswith('n'): sys.exit() @@ -82,7 +88,7 @@ for f in files: files_complete.append(f) continue else: - overwrite = askuser('Overwrite {}? ([y]/n) '.format(f)) + overwrite = input('Overwrite {}? ([y]/n) '.format(f)) if overwrite.lower().startswith('n'): continue diff --git a/scripts/openmc-get-multipole-data b/scripts/openmc-get-multipole-data index d51c196dcc..bf0add2840 100755 --- a/scripts/openmc-get-multipole-data +++ b/scripts/openmc-get-multipole-data @@ -10,18 +10,27 @@ import glob import hashlib import argparse -parser = argparse.ArgumentParser() +from six.moves import input +from six.moves.urllib.request import urlopen + + +description = """ +Download and extract windowed multipole data based on ENDF/B-VII.1. + +""" + +class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, + argparse.RawDescriptionHelpFormatter): + pass + +parser = argparse.ArgumentParser( + description=description, + formatter_class=CustomFormatter +) parser.add_argument('-b', '--batch', action='store_true', help='supresses standard in') args = parser.parse_args() -try: - from urllib.request import urlopen -except ImportError: - from urllib2 import urlopen - -cwd = os.getcwd() -sys.path.insert(0, os.path.join(cwd, '..')) baseUrl = 'https://github.com/smharper/windowed_multipole_library/blob/master/' files = ['multipole_lib.tar.gz?raw=true'] @@ -54,10 +63,7 @@ for f in files: filesComplete.append(fname) continue else: - if sys.version_info[0] < 3: - overwrite = raw_input('Overwrite {0}? ([y]/n) '.format(fname)) - else: - overwrite = input('Overwrite {0}? ([y]/n) '.format(fname)) + overwrite = input('Overwrite {0}? ([y]/n) '.format(fname)) if overwrite.lower().startswith('n'): continue @@ -110,10 +116,7 @@ os.rmdir('wmp/multipole_lib') # Ask user to delete if not args.batch: - if sys.version_info[0] < 3: - response = raw_input('Delete *.tar.gz files? ([y]/n) ') - else: - response = input('Delete *.tar.gz files? ([y]/n) ') + response = input('Delete *.tar.gz files? ([y]/n) ') else: response = 'y' diff --git a/scripts/openmc-get-nndc-data b/scripts/openmc-get-nndc-data index 5bec3865ec..5231b67ef0 100755 --- a/scripts/openmc-get-nndc-data +++ b/scripts/openmc-get-nndc-data @@ -10,15 +10,28 @@ import glob import hashlib import argparse -parser = argparse.ArgumentParser() +from six.moves import input +from six.moves.urllib.request import urlopen + + +description = """ +Download ENDF/B-VII.1 ACE data from NNDC and convert it to an HDF5 library for +use with OpenMC. + +""" + +class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, + argparse.RawDescriptionHelpFormatter): + pass + +parser = argparse.ArgumentParser( + description=description, + formatter_class=CustomFormatter +) parser.add_argument('-b', '--batch', action='store_true', help='supresses standard in') args = parser.parse_args() -try: - from urllib.request import urlopen -except ImportError: - from urllib2 import urlopen baseUrl = 'http://www.nndc.bnl.gov/endf/b7.1/aceFiles/' files = ['ENDF-B-VII.1-neutron-293.6K.tar.gz', @@ -50,10 +63,7 @@ for f in files: filesComplete.append(f) continue else: - if sys.version_info[0] < 3: - overwrite = raw_input('Overwrite {0}? ([y]/n) '.format(f)) - else: - overwrite = input('Overwrite {0}? ([y]/n) '.format(f)) + overwrite = input('Overwrite {0}? ([y]/n) '.format(f)) if overwrite.lower().startswith('n'): continue @@ -115,10 +125,7 @@ with open(graphite, 'w') as fh: # Ask user to delete if not args.batch: - if sys.version_info[0] < 3: - response = raw_input('Delete *.tar.gz files? ([y]/n) ') - else: - response = input('Delete *.tar.gz files? ([y]/n) ') + response = input('Delete *.tar.gz files? ([y]/n) ') else: response = 'y' @@ -134,10 +141,7 @@ if not response or response.lower().startswith('y'): # Ask user to convert if not args.batch: - if sys.version_info[0] < 3: - response = raw_input('Generate HDF5 library? ([y]/n) ') - else: - response = input('Generate HDF5 library? ([y]/n) ') + response = input('Generate HDF5 library? ([y]/n) ') else: response = 'y' diff --git a/setup.py b/setup.py index 4479bb82c5..fd6a2e1a37 100644 --- a/setup.py +++ b/setup.py @@ -32,7 +32,7 @@ kwargs = {'name': 'openmc', if have_setuptools: kwargs.update({ # Required dependencies - 'install_requires': ['numpy>=1.9', 'h5py', 'matplotlib'], + 'install_requires': ['six', 'numpy>=1.9', 'h5py', 'matplotlib'], # Optional dependencies 'extras_require': { From de009f4c34a322a6a4efc6e8f11668c09e318fa5 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 6 Oct 2016 18:30:42 -0500 Subject: [PATCH 4/8] Use six.add_metaclass to be compatible with Python 2 and 3 --- openmc/data/angle_energy.py | 6 +++--- openmc/data/energy_distribution.py | 5 ++--- openmc/data/function.py | 5 ++--- openmc/filter.py | 9 +++------ openmc/lattice.py | 6 ++---- openmc/mgxs/mdgxs.py | 6 ++---- openmc/mgxs/mgxs.py | 13 ++++--------- openmc/model/triso.py | 5 ++--- openmc/region.py | 5 ++--- openmc/stats/multivariate.py | 9 +++------ openmc/stats/univariate.py | 5 ++--- openmc/surface.py | 10 +++------- 12 files changed, 30 insertions(+), 54 deletions(-) diff --git a/openmc/data/angle_energy.py b/openmc/data/angle_energy.py index 4a5e391e3f..66fb89a53a 100644 --- a/openmc/data/angle_energy.py +++ b/openmc/data/angle_energy.py @@ -1,14 +1,14 @@ from abc import ABCMeta, abstractmethod +from six import add_metaclass + import openmc.data from openmc.mixin import EqualityMixin +@add_metaclass(ABCMeta) class AngleEnergy(EqualityMixin): """Distribution in angle and energy of a secondary particle.""" - - __metaclass = ABCMeta - @abstractmethod def to_hdf5(self, group): pass diff --git a/openmc/data/energy_distribution.py b/openmc/data/energy_distribution.py index a160906353..255b253bae 100644 --- a/openmc/data/energy_distribution.py +++ b/openmc/data/energy_distribution.py @@ -3,6 +3,7 @@ from collections 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 @@ -11,11 +12,9 @@ import openmc.checkvalue as cv from openmc.mixin import EqualityMixin +@add_metaclass(ABCMeta) class EnergyDistribution(EqualityMixin): """Abstract superclass for all energy distributions.""" - - __metaclass__ = ABCMeta - def __init__(self): pass diff --git a/openmc/data/function.py b/openmc/data/function.py index 94a2f0911e..8e539b9088 100644 --- a/openmc/data/function.py +++ b/openmc/data/function.py @@ -2,6 +2,7 @@ from abc import ABCMeta, abstractmethod from collections import Iterable, Callable from numbers import Real, Integral +from six import add_metaclass import numpy as np import openmc.checkvalue as cv @@ -11,11 +12,9 @@ INTERPOLATION_SCHEME = {1: 'histogram', 2: 'linear-linear', 3: 'linear-log', 4: 'log-linear', 5: 'log-log'} +@add_metaclass(ABCMeta) class Function1D(EqualityMixin): """A function of one independent variable with HDF5 support.""" - - __metaclass__ = ABCMeta - @abstractmethod def __call__(self): pass diff --git a/openmc/filter.py b/openmc/filter.py index d11af96f52..72a7db47ae 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -1,21 +1,17 @@ from abc import ABCMeta, abstractproperty from collections import Iterable, OrderedDict import copy -from six import with_metaclass from numbers import Real, Integral import sys from xml.etree import ElementTree as ET +from six import add_metaclass import numpy as np import openmc import openmc.checkvalue as cv -if sys.version_info[0] >= 3: - basestring = str - - _FILTER_TYPES = ['universe', 'material', 'cell', 'cellborn', 'surface', 'mesh', 'energy', 'energyout', 'mu', 'polar', 'azimuthal', 'distribcell', 'delayedgroup'] @@ -37,7 +33,8 @@ class FilterMeta(ABCMeta): **kwargs) -class Filter(with_metaclass(FilterMeta, object)): +@add_metaclass(FilterMeta) +class Filter(object): """Tally modifier that describes phase-space and other characteristics. Parameters diff --git a/openmc/lattice.py b/openmc/lattice.py index c6a5af4109..20fd57442d 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -7,6 +7,7 @@ from numbers import Real, Integral from xml.etree import ElementTree as ET import sys +from six import ABCMeta import numpy as np import openmc.checkvalue as cv @@ -16,6 +17,7 @@ if sys.version_info[0] >= 3: basestring = str +@add_metaclass(ABCMeta) class Lattice(object): """A repeating structure wherein each element is a universe. @@ -42,10 +44,6 @@ class Lattice(object): of the lattice """ - - # This is an abstract class which cannot be instantiated - __metaclass__ = abc.ABCMeta - def __init__(self, lattice_id=None, name=''): # Initialize Lattice class attributes self.id = lattice_id diff --git a/openmc/mgxs/mdgxs.py b/openmc/mgxs/mdgxs.py index 2c616b3682..bb6822d92c 100644 --- a/openmc/mgxs/mdgxs.py +++ b/openmc/mgxs/mdgxs.py @@ -8,6 +8,7 @@ import sys import copy import abc +from six import ABCMeta import numpy as np import openmc @@ -28,6 +29,7 @@ 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. @@ -117,10 +119,6 @@ class MDGXS(MGXS): The key used to index multi-group cross sections in an HDF5 data store """ - - # This is an abstract class which cannot be instantiated - __metaclass__ = abc.ABCMeta - def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name=''): super(MDGXS, self).__init__(domain, domain_type, energy_groups, diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index 65802f2ef0..1520f81d11 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -9,6 +9,7 @@ import copy import abc import itertools +from six import add_metaclass import numpy as np import openmc @@ -61,6 +62,7 @@ _DOMAINS = (openmc.Cell, openmc.Mesh) +@add_metaclass(ABCMeta) class MGXS(object): """An abstract multi-group cross section for some energy group structure within some spatial domain. @@ -145,10 +147,6 @@ class MGXS(object): The key used to index multi-group cross sections in an HDF5 data store """ - - # This is an abstract class which cannot be instantiated - __metaclass__ = abc.ABCMeta - def __init__(self, domain=None, domain_type=None, energy_groups=None, by_nuclide=False, name=''): self._name = '' @@ -1530,7 +1528,7 @@ class MGXS(object): # Override energy groups bounds with indices all_groups = np.arange(self.num_groups, 0, -1, dtype=np.int) - all_groups = np.repeat(all_groups, len(query_nuclides)) + all_groups = np.repeat(all_groups, len(query_nuclides)) if 'energy low [MeV]' in df and 'energyout low [MeV]' in df: df.rename(columns={'energy low [MeV]': 'group in'}, inplace=True) @@ -1616,6 +1614,7 @@ 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 @@ -1703,10 +1702,6 @@ class MatrixMGXS(MGXS): The key used to index multi-group cross sections in an HDF5 data store """ - - # This is an abstract class which cannot be instantiated - __metaclass__ = abc.ABCMeta - @property def filters(self): # Create the non-domain specific Filters for the Tallies diff --git a/openmc/model/triso.py b/openmc/model/triso.py index 5525ea559c..046bd45159 100644 --- a/openmc/model/triso.py +++ b/openmc/model/triso.py @@ -10,6 +10,7 @@ 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 @@ -95,6 +96,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): """Container in which to pack particles. @@ -123,9 +125,6 @@ class _Domain(object): Volume of the container. """ - - __metaclass__ = ABCMeta - def __init__(self, particle_radius, center=[0., 0., 0.]): self._cell_length = None self._limits = None diff --git a/openmc/region.py b/openmc/region.py index a1b9e9fd0d..ce970f8120 100644 --- a/openmc/region.py +++ b/openmc/region.py @@ -1,11 +1,13 @@ from abc import ABCMeta, abstractmethod from collections import Iterable +from six import add_metaclass import numpy as np from openmc.checkvalue import check_type +@add_metaclass(ABCMeta) class Region(object): """Region of space that can be assigned to a cell. @@ -16,9 +18,6 @@ class Region(object): created through operators of the Surface and Region classes. """ - - __metaclass__ = ABCMeta - def __and__(self, other): return Intersection(self, other) diff --git a/openmc/stats/multivariate.py b/openmc/stats/multivariate.py index e49a94ee19..fdae6c789e 100644 --- a/openmc/stats/multivariate.py +++ b/openmc/stats/multivariate.py @@ -5,6 +5,7 @@ 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 @@ -14,6 +15,7 @@ if sys.version_info[0] >= 3: basestring = str +@add_metaclass(ABCMeta) class UnitSphere(object): """Distribution of points on the unit sphere. @@ -31,9 +33,6 @@ class UnitSphere(object): Direction from which polar angle is measured """ - - __metaclass__ = ABCMeta - def __init__(self, reference_uvw=None): self._reference_uvw = None if reference_uvw is not None: @@ -184,6 +183,7 @@ class Monodirectional(UnitSphere): return element +@add_metaclass(ABCMeta) class Spatial(object): """Distribution of locations in three-dimensional Euclidean space. @@ -191,9 +191,6 @@ class Spatial(object): distributions of source sites. """ - - __metaclass__ = ABCMeta - def __init__(self): pass diff --git a/openmc/stats/univariate.py b/openmc/stats/univariate.py index ce0f0fae1d..2fabde8c5f 100644 --- a/openmc/stats/univariate.py +++ b/openmc/stats/univariate.py @@ -4,6 +4,7 @@ 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 @@ -16,6 +17,7 @@ _INTERPOLATION_SCHEMES = ['histogram', 'linear-linear', 'linear-log', 'log-linear', 'log-log'] +@add_metaclass(ABCMeta) class Univariate(EqualityMixin): """Probability distribution of a single random variable. @@ -23,9 +25,6 @@ class Univariate(EqualityMixin): specific probability distribution. """ - - __metaclass__ = ABCMeta - def __init__(self): pass diff --git a/openmc/surface.py b/openmc/surface.py index c33c4ee74c..8745a1867b 100644 --- a/openmc/surface.py +++ b/openmc/surface.py @@ -4,6 +4,7 @@ from xml.etree import ElementTree as ET import sys from math import sqrt +from six import add_metaclass import numpy as np from openmc.checkvalue import check_type, check_value, check_greater_than @@ -642,6 +643,7 @@ class ZPlane(Plane): return point[2] - self.z0 +@add_metaclass(ABCMeta) class Cylinder(Surface): """A cylinder whose length is parallel to the x-, y-, or z-axis. @@ -677,9 +679,6 @@ class Cylinder(Surface): Type of the surface """ - - __metaclass__ = ABCMeta - def __init__(self, surface_id=None, boundary_type='transmission', R=1., name=''): super(Cylinder, self).__init__(surface_id, boundary_type, name=name) @@ -1210,7 +1209,7 @@ class Sphere(Surface): z = point[2] - self.z0 return x**2 + y**2 + z**2 - self.r**2 - +@add_metaclass(ABCMeta) class Cone(Surface): """A conical surface parallel to the x-, y-, or z-axis. @@ -1257,9 +1256,6 @@ class Cone(Surface): Type of the surface """ - - __metaclass__ = ABCMeta - 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) From 5a126d086e7a611cde23dba5aa27bda072d9a5d5 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 6 Oct 2016 21:39:57 -0500 Subject: [PATCH 5/8] Use six.string_types instead of basestring --- openmc/arithmetic.py | 23 ++++++------- openmc/cell.py | 10 +++--- openmc/cmfd.py | 7 ++-- openmc/data/ace.py | 7 ++-- openmc/data/fission_energy.py | 3 -- openmc/data/neutron.py | 8 ++--- openmc/data/product.py | 6 ++-- openmc/data/reaction.py | 3 +- openmc/element.py | 10 +++--- openmc/executor.py | 5 ++- openmc/lattice.py | 9 ++--- openmc/macroscopic.py | 9 +++-- openmc/material.py | 17 +++++---- openmc/mesh.py | 8 ++--- openmc/mgxs/groups.py | 4 --- openmc/mgxs/library.py | 27 +++++++-------- openmc/mgxs/mdgxs.py | 38 ++++++++++---------- openmc/mgxs/mgxs.py | 65 +++++++++++++++++------------------ openmc/mgxs_library.py | 7 ++-- openmc/nuclide.py | 9 +++-- openmc/plots.py | 15 ++++---- openmc/settings.py | 10 +++--- openmc/source.py | 7 ++-- openmc/statepoint.py | 3 -- openmc/stats/multivariate.py | 3 -- openmc/stats/univariate.py | 2 -- openmc/surface.py | 8 ++--- openmc/tallies.py | 28 +++++++-------- openmc/trigger.py | 7 ++-- openmc/universe.py | 5 ++- 30 files changed, 154 insertions(+), 209 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index 1632520c5f..f549537206 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -2,14 +2,13 @@ import sys import copy from collections import Iterable +from six import string_types import numpy as np import openmc from openmc.filter import _FILTER_TYPES import openmc.checkvalue as cv -if sys.version_info[0] >= 3: - basestring = str # Acceptable tally arithmetic binary operations _TALLY_ARITHMETIC_OPS = ['+', '-', '*', '/', '^'] @@ -86,18 +85,18 @@ class CrossScore(object): @left_score.setter def left_score(self, left_score): cv.check_type('left_score', left_score, - (basestring, CrossScore, AggregateScore)) + string_types + (CrossScore, AggregateScore)) self._left_score = left_score @right_score.setter def right_score(self, right_score): cv.check_type('right_score', right_score, - (basestring, CrossScore, AggregateScore)) + string_types + (CrossScore, AggregateScore)) self._right_score = right_score @binary_op.setter def binary_op(self, binary_op): - cv.check_type('binary_op', binary_op, basestring) + cv.check_type('binary_op', binary_op, string_types) 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, basestring) + cv.check_type('binary_op', binary_op, string_types) cv.check_value('binary_op', binary_op, _TALLY_ARITHMETIC_OPS) self._binary_op = binary_op @@ -343,7 +342,7 @@ class CrossFilter(object): @binary_op.setter def binary_op(self, binary_op): - cv.check_type('binary_op', binary_op, basestring) + cv.check_type('binary_op', binary_op, string_types) cv.check_value('binary_op', binary_op, _TALLY_ARITHMETIC_OPS) self._binary_op = binary_op @@ -495,12 +494,12 @@ class AggregateScore(object): @scores.setter def scores(self, scores): - cv.check_iterable_type('scores', scores, basestring) + cv.check_iterable_type('scores', scores, string_types) self._scores = scores @aggregate_op.setter def aggregate_op(self, aggregate_op): - cv.check_type('aggregate_op', aggregate_op, (basestring, CrossScore)) + cv.check_type('aggregate_op', aggregate_op, string_types +(CrossScore,)) cv.check_value('aggregate_op', aggregate_op, _TALLY_AGGREGATE_OPS) self._aggregate_op = aggregate_op @@ -575,12 +574,12 @@ class AggregateNuclide(object): @nuclides.setter def nuclides(self, nuclides): cv.check_iterable_type('nuclides', nuclides, - (basestring, openmc.Nuclide, CrossNuclide)) + string_types + (openmc.Nuclide, CrossNuclide)) self._nuclides = nuclides @aggregate_op.setter def aggregate_op(self, aggregate_op): - cv.check_type('aggregate_op', aggregate_op, basestring) + cv.check_type('aggregate_op', aggregate_op, string_types) cv.check_value('aggregate_op', aggregate_op, _TALLY_AGGREGATE_OPS) self._aggregate_op = aggregate_op @@ -711,7 +710,7 @@ class AggregateFilter(object): @aggregate_op.setter def aggregate_op(self, aggregate_op): - cv.check_type('aggregate_op', aggregate_op, basestring) + cv.check_type('aggregate_op', aggregate_op, string_types) cv.check_value('aggregate_op', aggregate_op, _TALLY_AGGREGATE_OPS) self._aggregate_op = aggregate_op diff --git a/openmc/cell.py b/openmc/cell.py index 1cfc09f372..f950963d27 100644 --- a/openmc/cell.py +++ b/openmc/cell.py @@ -5,6 +5,7 @@ from xml.etree import ElementTree as ET import sys import warnings +from six import string_types import numpy as np import openmc @@ -12,9 +13,6 @@ import openmc.checkvalue as cv from openmc.surface import Halfspace from openmc.region import Region, Intersection, Complement -if sys.version_info[0] >= 3: - basestring = str - # A static variable for auto-generated Cell IDs AUTO_CELL_ID = 10000 @@ -243,7 +241,7 @@ class Cell(object): @name.setter def name(self, name): if name is not None: - cv.check_type('cell name', name, basestring) + cv.check_type('cell name', name, string_types) self._name = name else: self._name = '' @@ -251,7 +249,7 @@ class Cell(object): @fill.setter def fill(self, fill): if fill is not None: - if isinstance(fill, basestring): + 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) @@ -336,7 +334,7 @@ class Cell(object): @distribcell_paths.setter def distribcell_paths(self, distribcell_paths): cv.check_iterable_type('distribcell_paths', distribcell_paths, - basestring) + string_types) self._distribcell_paths = distribcell_paths def add_surface(self, surface, halfspace): diff --git a/openmc/cmfd.py b/openmc/cmfd.py index 76d8685ff1..51acf4d426 100644 --- a/openmc/cmfd.py +++ b/openmc/cmfd.py @@ -15,13 +15,12 @@ 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) -if sys.version_info[0] >= 3: - basestring = str - class CMFDMesh(object): """A structured Cartesian mesh used for Coarse Mesh Finite Difference (CMFD) @@ -339,7 +338,7 @@ class CMFD(object): @display.setter def display(self, display): - check_type('CMFD display', display, basestring) + check_type('CMFD display', display, string_types) 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 831e40fc81..d7ec97edce 100644 --- a/openmc/data/ace.py +++ b/openmc/data/ace.py @@ -20,15 +20,12 @@ from os import SEEK_CUR import struct import sys +from six import string_types import numpy as np from openmc.mixin import EqualityMixin -if sys.version_info[0] >= 3: - basestring = str - - def ascii_to_binary(ascii_file, binary_file): """Convert an ACE file in ASCII format (type 1) to binary format (type 2). @@ -156,7 +153,7 @@ class Library(EqualityMixin): """ def __init__(self, filename, table_names=None, verbose=False): - if isinstance(table_names, basestring): + if isinstance(table_names, string_types): table_names = [table_names] if table_names is not None: table_names = set(table_names) diff --git a/openmc/data/fission_energy.py b/openmc/data/fission_energy.py index 6352915cc6..b527629e23 100644 --- a/openmc/data/fission_energy.py +++ b/openmc/data/fission_energy.py @@ -11,9 +11,6 @@ from .function import Function1D, Tabulated1D, Polynomial, Sum import openmc.checkvalue as cv from openmc.mixin import EqualityMixin -if sys.version_info[0] >= 3: - basestring = str - def _extract_458_data(filename): """Read an ENDF file and extract the MF=1, MT=458 values. diff --git a/openmc/data/neutron.py b/openmc/data/neutron.py index c638dfd9bd..9004eb3c7c 100644 --- a/openmc/data/neutron.py +++ b/openmc/data/neutron.py @@ -5,6 +5,7 @@ from itertools import chain from numbers import Integral, Real from warnings import warn +from six import string_types import numpy as np import h5py @@ -18,9 +19,6 @@ from .urr import ProbabilityTables import openmc.checkvalue as cv from openmc.mixin import EqualityMixin -if sys.version_info[0] >= 3: - basestring = str - def _get_metadata(zaid, metastable_scheme='nndc'): """Return basic identifying data for a nuclide with a given ZAID. @@ -226,7 +224,7 @@ class IncidentNeutron(EqualityMixin): @name.setter def name(self, name): - cv.check_type('name', name, basestring) + cv.check_type('name', name, string_types) self._name = name @property @@ -277,7 +275,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, basestring) + cv.check_type('probability table temperature', key, string_types) cv.check_type('probability tables', value, ProbabilityTables) self._urr = urr diff --git a/openmc/data/product.py b/openmc/data/product.py index 753888f6df..483358c28b 100644 --- a/openmc/data/product.py +++ b/openmc/data/product.py @@ -2,6 +2,7 @@ from collections import Iterable from numbers import Real import sys +from six import string_types import numpy as np import openmc.checkvalue as cv @@ -9,9 +10,6 @@ from openmc.mixin import EqualityMixin from .function import Tabulated1D, Polynomial, Function1D from .angle_energy import AngleEnergy -if sys.version_info[0] >= 3: - basestring = str - class Product(EqualityMixin): """Secondary particle emitted in a nuclear reaction @@ -114,7 +112,7 @@ class Product(EqualityMixin): @particle.setter def particle(self, particle): - cv.check_type('product particle type', particle, basestring) + cv.check_type('product particle type', particle, string_types) self._particle = particle @yield_.setter diff --git a/openmc/data/reaction.py b/openmc/data/reaction.py index eb33e1395f..cfebda374d 100644 --- a/openmc/data/reaction.py +++ b/openmc/data/reaction.py @@ -4,6 +4,7 @@ from copy import deepcopy from numbers import Real, Integral from warnings import warn +from six import string_types import numpy as np import openmc.checkvalue as cv @@ -349,7 +350,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, basestring) + cv.check_type('reaction cross section temperature', key, string_types) cv.check_type('reaction cross section', value, Function1D) self._xs = xs diff --git a/openmc/element.py b/openmc/element.py index 1b16806148..e1484198cf 100644 --- a/openmc/element.py +++ b/openmc/element.py @@ -1,14 +1,12 @@ import re import sys +from six import string_types + import openmc from openmc.checkvalue import check_type, check_length from openmc.data import NATURAL_ABUNDANCE -if sys.version_info[0] >= 3: - basestring = str - - class Element(object): """A natural element used in a material via . Internally, OpenMC will @@ -43,7 +41,7 @@ class Element(object): return False else: return True - elif isinstance(other, basestring) and other == self.name: + elif isinstance(other, string_types) and other == self.name: return True else: return False @@ -78,7 +76,7 @@ class Element(object): @name.setter def name(self, name): - check_type('element name', name, basestring) + check_type('element name', name, string_types) check_length('element name', name, 1, 2) self._name = name diff --git a/openmc/executor.py b/openmc/executor.py index fbd9e5d82a..a20437e1cd 100644 --- a/openmc/executor.py +++ b/openmc/executor.py @@ -3,8 +3,7 @@ import subprocess from numbers import Integral import sys -if sys.version_info[0] >= 3: - basestring = str +from six import string_types def _run(command, output, cwd): @@ -89,7 +88,7 @@ def run(particles=None, threads=None, geometry_debug=False, if geometry_debug: post_args += '-g ' - if isinstance(restart_file, basestring): + if isinstance(restart_file, string_types): post_args += '-r {0} '.format(restart_file) if tracks: diff --git a/openmc/lattice.py b/openmc/lattice.py index 20fd57442d..95c16841ff 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -1,21 +1,18 @@ from __future__ import division -import abc +from abc import ABCMeta from collections import OrderedDict, Iterable from math import sqrt, floor from numbers import Real, Integral from xml.etree import ElementTree as ET import sys -from six import ABCMeta +from six import add_metaclass, string_types import numpy as np import openmc.checkvalue as cv import openmc -if sys.version_info[0] >= 3: - basestring = str - @add_metaclass(ABCMeta) class Lattice(object): @@ -104,7 +101,7 @@ class Lattice(object): @name.setter def name(self, name): if name is not None: - cv.check_type('lattice name', name, basestring) + cv.check_type('lattice name', name, string_types) self._name = name else: self._name = '' diff --git a/openmc/macroscopic.py b/openmc/macroscopic.py index a1ca62c9ab..4d35891417 100644 --- a/openmc/macroscopic.py +++ b/openmc/macroscopic.py @@ -1,9 +1,8 @@ import sys -from openmc.checkvalue import check_type +from six import string_types -if sys.version_info[0] >= 3: - basestring = str +from openmc.checkvalue import check_type class Macroscopic(object): @@ -34,7 +33,7 @@ class Macroscopic(object): return False else: return True - elif isinstance(other, basestring) and other == self.name: + elif isinstance(other, string_types) and other == self.name: return True else: return False @@ -55,5 +54,5 @@ class Macroscopic(object): @name.setter def name(self, name): - check_type('name', name, basestring) + check_type('name', name, string_types) self._name = name diff --git a/openmc/material.py b/openmc/material.py index 0639db5629..6f9c4ba15f 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -5,14 +5,13 @@ import warnings from xml.etree import ElementTree as ET import sys +from six import string_types + import openmc import openmc.data import openmc.checkvalue as cv from openmc.clean_xml import sort_xml_elements, clean_xml_indentation -if sys.version_info[0] >= 3: - basestring = str - # A static variable for auto-generated Material IDs AUTO_MATERIAL_ID = 10000 @@ -207,7 +206,7 @@ class Material(object): def name(self, name): if name is not None: cv.check_type('name for Material ID="{0}"'.format(self._id), - name, basestring) + name, string_types) self._name = name else: self._name = '' @@ -256,7 +255,7 @@ class Material(object): warnings.warn('This feature is not yet implemented in a release ' 'version of openmc') - if not isinstance(filename, basestring) and filename is not None: + if not isinstance(filename, string_types) and filename is not None: msg = 'Unable to add OTF material file to Material ID="{0}" with a ' \ 'non-string name "{1}"'.format(self._id, filename) raise ValueError(msg) @@ -290,7 +289,7 @@ class Material(object): 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(nuclide, (openmc.Nuclide, basestring)): + if not isinstance(nuclide, string_types + (openmc.Nuclide,)): msg = 'Unable to add a Nuclide to Material ID="{0}" with a ' \ 'non-Nuclide value "{1}"'.format(self._id, nuclide) raise ValueError(msg) @@ -355,7 +354,7 @@ class Material(object): 'has already been added'.format(self._id, macroscopic) raise ValueError(msg) - if not isinstance(macroscopic, (openmc.Macroscopic, basestring)): + if not isinstance(macroscopic, string_types + (openmc.Macroscopic,)): msg = 'Unable to add a Macroscopic to Material ID="{0}" with a ' \ 'non-Macroscopic value "{1}"'.format(self._id, macroscopic) raise ValueError(msg) @@ -425,7 +424,7 @@ class Material(object): 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(element, (openmc.Element, basestring)): + if not isinstance(element, string_types + (openmc.Element,)): msg = 'Unable to add an Element to Material ID="{0}" with a ' \ 'non-Element value "{1}"'.format(self._id, element) raise ValueError(msg) @@ -490,7 +489,7 @@ class Material(object): 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(name, basestring): + if not isinstance(name, string_types): msg = 'Unable to add an S(a,b) table to Material ID="{0}" with a ' \ 'non-string table name "{1}"'.format(self._id, name) raise ValueError(msg) diff --git a/openmc/mesh.py b/openmc/mesh.py index 420dba0661..730e54547e 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3,15 +3,13 @@ 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 import openmc -if sys.version_info[0] >= 3: - basestring = str - # "Static" variable for auto-generated and Mesh IDs AUTO_MESH_ID = 10000 @@ -131,7 +129,7 @@ class Mesh(object): def name(self, name): if name is not None: cv.check_type('name for mesh ID="{0}"'.format(self._id), - name, basestring) + name, string_types) self._name = name else: self._name = '' @@ -139,7 +137,7 @@ class Mesh(object): @type.setter def type(self, meshtype): cv.check_type('type for mesh ID="{0}"'.format(self._id), - meshtype, basestring) + meshtype, string_types) cv.check_value('type for mesh ID="{0}"'.format(self._id), meshtype, ['regular']) self._type = meshtype diff --git a/openmc/mgxs/groups.py b/openmc/mgxs/groups.py index 068977d888..9441a80511 100644 --- a/openmc/mgxs/groups.py +++ b/openmc/mgxs/groups.py @@ -8,10 +8,6 @@ import numpy as np import openmc.checkvalue as cv -if sys.version_info[0] >= 3: - basestring = str - - class EnergyGroups(object): """An energy groups structure used for multi-group cross-sections. diff --git a/openmc/mgxs/library.py b/openmc/mgxs/library.py index 4b68952a67..ca1bd1b3ee 100644 --- a/openmc/mgxs/library.py +++ b/openmc/mgxs/library.py @@ -6,6 +6,7 @@ from numbers import Integral from collections import OrderedDict from warnings import warn +from six import string_types import numpy as np import openmc @@ -14,10 +15,6 @@ import openmc.checkvalue as cv from openmc.tallies import ESTIMATOR_TYPES -if sys.version_info[0] >= 3: - basestring = str - - class Library(object): """A multi-energy-group and multi-delayed-group cross section library for some energy group structure. @@ -259,7 +256,7 @@ class Library(object): @name.setter def name(self, name): - cv.check_type('name', name, basestring) + cv.check_type('name', name, string_types) self._name = name @mgxs_types.setter @@ -268,7 +265,7 @@ class Library(object): if mgxs_types == 'all': self._mgxs_types = all_mgxs_types else: - cv.check_iterable_type('mgxs_types', mgxs_types, basestring) + cv.check_iterable_type('mgxs_types', mgxs_types, string_types) for mgxs_type in mgxs_types: cv.check_value('mgxs_type', mgxs_type, all_mgxs_types) self._mgxs_types = mgxs_types @@ -730,8 +727,8 @@ class Library(object): 'since a statepoint has not yet been loaded' raise ValueError(msg) - cv.check_type('filename', filename, basestring) - cv.check_type('directory', directory, basestring) + cv.check_type('filename', filename, string_types) + cv.check_type('directory', directory, string_types) import h5py @@ -773,8 +770,8 @@ class Library(object): """ - cv.check_type('filename', filename, basestring) - cv.check_type('directory', directory, basestring) + cv.check_type('filename', filename, string_types) + cv.check_type('directory', directory, string_types) # Make directory if it does not exist if not os.path.exists(directory): @@ -808,8 +805,8 @@ class Library(object): """ - cv.check_type('filename', filename, basestring) - cv.check_type('directory', directory, basestring) + cv.check_type('filename', filename, string_types) + cv.check_type('directory', directory, string_types) # Make directory if it does not exist if not os.path.exists(directory): @@ -883,8 +880,8 @@ class Library(object): cv.check_type('domain', domain, (openmc.Material, openmc.Cell, openmc.Universe, openmc.Mesh)) - cv.check_type('xsdata_name', xsdata_name, basestring) - cv.check_type('nuclide', nuclide, basestring) + cv.check_type('xsdata_name', xsdata_name, string_types) + cv.check_type('nuclide', nuclide, string_types) cv.check_value('xs_type', xs_type, ['macro', 'micro']) cv.check_type('order', order, (type(None), Integral)) if order is not None: @@ -1069,7 +1066,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, basestring) + cv.check_iterable_type('xsdata_names', xsdata_names, string_types) # 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 bb6822d92c..101edec1d2 100644 --- a/openmc/mgxs/mdgxs.py +++ b/openmc/mgxs/mdgxs.py @@ -6,9 +6,9 @@ import warnings import os import sys import copy -import abc +from abc import ABCMeta -from six import ABCMeta +from six import add_metaclass, string_types import numpy as np import openmc @@ -16,8 +16,6 @@ from openmc.mgxs import MGXS from openmc.mgxs.mgxs import _DOMAIN_TO_FILTER import openmc.checkvalue as cv -if sys.version_info[0] >= 3: - basestring = str # Supported cross section types MDGXS_TYPES = ['delayed-nu-fission', @@ -320,7 +318,7 @@ class MDGXS(MGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -328,7 +326,7 @@ class MDGXS(MGXS): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, basestring): + if not isinstance(groups, string_types): cv.check_iterable_type('groups', groups, Integral) for group in groups: filters.append(openmc.EnergyFilter) @@ -336,7 +334,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, basestring): + if not isinstance(delayed_groups, string_types): cv.check_type('delayed groups', delayed_groups, list, int) for delayed_group in delayed_groups: filters.append(openmc.DelayedGroupFilter) @@ -432,7 +430,7 @@ class MDGXS(MGXS): """ - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) cv.check_iterable_type('energy_groups', groups, Integral) cv.check_type('delayed groups', delayed_groups, list, int) @@ -542,7 +540,7 @@ class MDGXS(MGXS): return # Construct a collection of the subdomains to report - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -559,7 +557,7 @@ class MDGXS(MGXS): elif nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) else: nuclides = ['sum'] @@ -649,8 +647,8 @@ class MDGXS(MGXS): """ - cv.check_type('filename', filename, basestring) - cv.check_type('directory', directory, basestring) + cv.check_type('filename', filename, string_types) + cv.check_type('directory', directory, string_types) cv.check_value('format', format, ['csv', 'excel', 'pickle', 'latex']) cv.check_value('xs_type', xs_type, ['macro', 'micro']) @@ -740,11 +738,11 @@ class MDGXS(MGXS): """ - if not isinstance(groups, basestring): + if not isinstance(groups, string_types): cv.check_iterable_type('groups', groups, Integral) if nuclides != 'all' and nuclides != 'sum': - cv.check_iterable_type('nuclides', nuclides, basestring) - if not isinstance(delayed_groups, basestring): + cv.check_iterable_type('nuclides', nuclides, string_types) + if not isinstance(delayed_groups, string_types): cv.check_type('delayed groups', delayed_groups, list, int) cv.check_value('xs_type', xs_type, ['macro', 'micro']) @@ -819,7 +817,7 @@ class MDGXS(MGXS): columns = ['group in'] # Select out those groups the user requested - if not isinstance(groups, basestring): + if not isinstance(groups, string_types): if 'group in' in df: df = df[df['group in'].isin(groups)] if 'group out' in df: @@ -1210,7 +1208,7 @@ class ChiDelayed(MDGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -1218,7 +1216,7 @@ class ChiDelayed(MDGXS): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, basestring): + if not isinstance(groups, string_types): cv.check_iterable_type('groups', groups, Integral) for group in groups: filters.append(openmc.EnergyoutFilter) @@ -1226,7 +1224,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, basestring): + if not isinstance(delayed_groups, string_types): cv.check_type('delayed groups', delayed_groups, list, int) for delayed_group in delayed_groups: filters.append(openmc.DelayedGroupFilter) @@ -1274,7 +1272,7 @@ class ChiDelayed(MDGXS): # Get chi delayed for user-specified nuclides in the domain else: - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) xs = self.xs_tally.get_values(filters=filters, filter_bins=filter_bins, nuclides=nuclides, value=value) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index 1520f81d11..b839e92151 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -6,10 +6,10 @@ import warnings import os import sys import copy -import abc +from abc import ABCMeta import itertools -from six import add_metaclass +from six import add_metaclass, string_types import numpy as np import openmc @@ -17,9 +17,6 @@ import openmc.checkvalue as cv from openmc.tallies import ESTIMATOR_TYPES from openmc.mgxs import EnergyGroups -if sys.version_info[0] >= 3: - basestring = str - # Supported cross section types MGXS_TYPES = ['total', @@ -366,7 +363,7 @@ class MGXS(object): @name.setter def name(self, name): - cv.check_type('name', name, basestring) + cv.check_type('name', name, string_types) self._name = name @by_nuclide.setter @@ -376,7 +373,7 @@ class MGXS(object): @nuclides.setter def nuclides(self, nuclides): - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) self._nuclides = nuclides @estimator.setter @@ -560,7 +557,7 @@ class MGXS(object): """ - cv.check_type('nuclide', nuclide, basestring) + cv.check_type('nuclide', nuclide, string_types) # Get list of all nuclides in the spatial domain nuclides = self.domain.get_nuclide_densities() @@ -786,7 +783,7 @@ class MGXS(object): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -794,7 +791,7 @@ class MGXS(object): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, basestring): + if not isinstance(groups, string_types): cv.check_iterable_type('groups', groups, Integral) for group in groups: filters.append(openmc.EnergyFilter) @@ -956,7 +953,7 @@ class MGXS(object): """ # Construct a collection of the subdomain filter bins to average across - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains) @@ -1011,7 +1008,7 @@ class MGXS(object): """ - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) cv.check_iterable_type('energy_groups', groups, Integral) # Build lists of filters and filter bins to slice @@ -1165,7 +1162,7 @@ class MGXS(object): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -1182,7 +1179,7 @@ class MGXS(object): elif nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) else: nuclides = ['sum'] @@ -1300,7 +1297,7 @@ class MGXS(object): xs_results = h5py.File(filename, 'w') # Construct a collection of the subdomains to report - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -1321,7 +1318,7 @@ class MGXS(object): elif nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) else: nuclides = ['sum'] @@ -1399,8 +1396,8 @@ class MGXS(object): """ - cv.check_type('filename', filename, basestring) - cv.check_type('directory', directory, basestring) + cv.check_type('filename', filename, string_types) + cv.check_type('directory', directory, string_types) cv.check_value('format', format, ['csv', 'excel', 'pickle', 'latex']) cv.check_value('xs_type', xs_type, ['macro', 'micro']) @@ -1486,10 +1483,10 @@ class MGXS(object): """ - if not isinstance(groups, basestring): + if not isinstance(groups, string_types): cv.check_iterable_type('groups', groups, Integral) if nuclides != 'all' and nuclides != 'sum': - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) cv.check_value('xs_type', xs_type, ['macro', 'micro']) # Get a Pandas DataFrame from the derived xs tally @@ -1561,7 +1558,7 @@ class MGXS(object): columns = ['group in'] # Select out those groups the user requested - if not isinstance(groups, basestring): + if not isinstance(groups, string_types): if 'group in' in df: df = df[df['group in'].isin(groups)] if 'group out' in df: @@ -1781,7 +1778,7 @@ class MatrixMGXS(MGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -1789,7 +1786,7 @@ class MatrixMGXS(MGXS): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(in_groups, basestring): + if not isinstance(in_groups, string_types): cv.check_iterable_type('groups', in_groups, Integral) for group in in_groups: filters.append(openmc.EnergyFilter) @@ -1797,7 +1794,7 @@ class MatrixMGXS(MGXS): self.energy_groups.get_group_bounds(group),)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(out_groups, basestring): + if not isinstance(out_groups, string_types): cv.check_iterable_type('groups', out_groups, Integral) for group in out_groups: filters.append(openmc.EnergyoutFilter) @@ -1943,7 +1940,7 @@ class MatrixMGXS(MGXS): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -1960,7 +1957,7 @@ class MatrixMGXS(MGXS): if nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) else: nuclides = ['sum'] @@ -3616,21 +3613,21 @@ class ScatterMatrixXS(MatrixMGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: filters.append(_DOMAIN_TO_FILTER[self.domain_type]) filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(in_groups, basestring): + if not isinstance(in_groups, string_types): cv.check_iterable_type('groups', in_groups, Integral) for group in in_groups: filters.append(openmc.EnergyFilter) filter_bins.append((self.energy_groups.get_group_bounds(group),)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(out_groups, basestring): + if not isinstance(out_groups, string_types): cv.check_iterable_type('groups', out_groups, Integral) for group in out_groups: filters.append(openmc.EnergyoutFilter) @@ -3804,7 +3801,7 @@ class ScatterMatrixXS(MatrixMGXS): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -3821,7 +3818,7 @@ class ScatterMatrixXS(MatrixMGXS): if nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) else: nuclides = ['sum'] @@ -4604,14 +4601,14 @@ class Chi(MGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, basestring): + if not isinstance(subdomains, string_types): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: filters.append(_DOMAIN_TO_FILTER[self.domain_type]) filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, basestring): + if not isinstance(groups, string_types): cv.check_iterable_type('groups', groups, Integral) for group in groups: filters.append(openmc.EnergyoutFilter) @@ -4656,7 +4653,7 @@ class Chi(MGXS): # Get chi for user-specified nuclides in the domain else: - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) xs = self.xs_tally.get_values(filters=filters, filter_bins=filter_bins, nuclides=nuclides, value=value) diff --git a/openmc/mgxs_library.py b/openmc/mgxs_library.py index 37ad6c1be4..8394d9cc0b 100644 --- a/openmc/mgxs_library.py +++ b/openmc/mgxs_library.py @@ -3,6 +3,7 @@ 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 @@ -11,8 +12,6 @@ from openmc.checkvalue import check_type, check_value, check_greater_than, \ check_iterable_type from openmc.clean_xml import sort_xml_elements, clean_xml_indentation -if sys.version_info[0] >= 3: - basestring = str # Supported incoming particle MGXS angular treatment representations _REPRESENTATIONS = ['isotropic', 'angle'] @@ -360,7 +359,7 @@ class XSdata(object): @name.setter def name(self, name): - check_type('name for XSdata', name, basestring) + check_type('name for XSdata', name, string_types) self._name = name @energy_groups.setter @@ -383,7 +382,7 @@ class XSdata(object): @alias.setter def alias(self, alias): if alias is not None: - check_type('alias', alias, basestring) + check_type('alias', alias, string_types) self._alias = alias else: self._alias = self._name diff --git a/openmc/nuclide.py b/openmc/nuclide.py index 11c59e6879..5b844582c6 100644 --- a/openmc/nuclide.py +++ b/openmc/nuclide.py @@ -2,10 +2,9 @@ from numbers import Integral import sys import warnings -from openmc.checkvalue import check_type +from six import string_types -if sys.version_info[0] >= 3: - basestring = str +from openmc.checkvalue import check_type class Nuclide(object): @@ -39,7 +38,7 @@ class Nuclide(object): return False else: return True - elif isinstance(other, basestring) and other == self.name: + elif isinstance(other, string_types) and other == self.name: return True else: return False @@ -73,7 +72,7 @@ class Nuclide(object): @name.setter def name(self, name): - check_type('name', name, basestring) + check_type('name', name, string_types) self._name = name if '-' in name: diff --git a/openmc/plots.py b/openmc/plots.py index 6915604a3c..48af6f23c3 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -4,14 +4,13 @@ from xml.etree import ElementTree as ET import sys import warnings +from six import string_types import numpy as np import openmc import openmc.checkvalue as cv from openmc.clean_xml import clean_xml_indentation -if sys.version_info[0] >= 3: - basestring = str # A static variable for auto-generated Plot IDs AUTO_PLOT_ID = 10000 @@ -166,7 +165,7 @@ class Plot(object): @name.setter def name(self, name): - cv.check_type('plot name', name, basestring) + cv.check_type('plot name', name, string_types) self._name = name @width.setter @@ -191,24 +190,24 @@ class Plot(object): @filename.setter def filename(self, filename): - cv.check_type('filename', filename, basestring) + cv.check_type('filename', filename, string_types) self._filename = filename @color.setter def color(self, color): - cv.check_type('plot color', color, basestring) + cv.check_type('plot color', color, string_types) cv.check_value('plot color', color, ['cell', 'mat']) self._color = color @type.setter def type(self, plottype): - cv.check_type('plot type', plottype, basestring) + cv.check_type('plot type', plottype, string_types) cv.check_value('plot type', plottype, ['slice', 'voxel']) self._type = plottype @basis.setter def basis(self, basis): - cv.check_type('plot basis', basis, basestring) + cv.check_type('plot basis', basis, string_types) cv.check_value('plot basis', basis, ['xy', 'xz', 'yz']) self._basis = basis @@ -387,7 +386,7 @@ class Plot(object): cv.check_less_than('alpha', alpha, 1., equality=True) # Get a background (R,G,B) tuple to apply in alpha compositing - if isinstance(background, basestring): + if isinstance(background, string_types): if background == 'white': background = (255, 255, 255) elif background == 'black': diff --git a/openmc/settings.py b/openmc/settings.py index f255a8bb10..1e07ca223d 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -4,15 +4,13 @@ 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 import openmc.checkvalue as cv from openmc import Nuclide, VolumeCalculation, Source -if sys.version_info[0] >= 3: - basestring = str - class Settings(object): """Settings used for an OpenMC simulation. @@ -527,7 +525,7 @@ class Settings(object): @output_path.setter def output_path(self, output_path): - cv.check_type('output path', output_path, basestring) + cv.check_type('output path', output_path, string_types) self._output_path = output_path @verbosity.setter @@ -583,12 +581,12 @@ class Settings(object): @cross_sections.setter def cross_sections(self, cross_sections): - cv.check_type('cross sections', cross_sections, basestring) + cv.check_type('cross sections', cross_sections, string_types) self._cross_sections = cross_sections @multipole_library.setter def multipole_library(self, multipole_library): - cv.check_type('cross sections', multipole_library, basestring) + cv.check_type('cross sections', multipole_library, string_types) self._multipole_library = multipole_library @ptables.setter diff --git a/openmc/source.py b/openmc/source.py index ee32cd0f4b..1aee435147 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -2,13 +2,12 @@ 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 -if sys.version_info[0] >= 3: - basestring = str - class Source(object): """Distribution of phase space coordinates for source sites. @@ -79,7 +78,7 @@ class Source(object): @file.setter def file(self, filename): - cv.check_type('source file', filename, basestring) + cv.check_type('source file', filename, string_types) self._file = filename @space.setter diff --git a/openmc/statepoint.py b/openmc/statepoint.py index 1a97b695b4..aaa5c0b840 100644 --- a/openmc/statepoint.py +++ b/openmc/statepoint.py @@ -9,9 +9,6 @@ import numpy as np import openmc import openmc.checkvalue as cv -if sys.version > '3': - long = int - class StatePoint(object): """State information on a simulation at a certain point in time (at the end diff --git a/openmc/stats/multivariate.py b/openmc/stats/multivariate.py index fdae6c789e..ca25cf5fb3 100644 --- a/openmc/stats/multivariate.py +++ b/openmc/stats/multivariate.py @@ -11,9 +11,6 @@ import numpy as np import openmc.checkvalue as cv from openmc.stats.univariate import Univariate, Uniform -if sys.version_info[0] >= 3: - basestring = str - @add_metaclass(ABCMeta) class UnitSphere(object): diff --git a/openmc/stats/univariate.py b/openmc/stats/univariate.py index 2fabde8c5f..dcbb9982c7 100644 --- a/openmc/stats/univariate.py +++ b/openmc/stats/univariate.py @@ -10,8 +10,6 @@ import numpy as np import openmc.checkvalue as cv from openmc.mixin import EqualityMixin -if sys.version_info[0] >= 3: - basestring = str _INTERPOLATION_SCHEMES = ['histogram', 'linear-linear', 'linear-log', 'log-linear', 'log-log'] diff --git a/openmc/surface.py b/openmc/surface.py index 8745a1867b..c88c4ccc7c 100644 --- a/openmc/surface.py +++ b/openmc/surface.py @@ -4,14 +4,12 @@ from xml.etree import ElementTree as ET import sys from math import sqrt -from six import add_metaclass +from six import add_metaclass, string_types import numpy as np from openmc.checkvalue import check_type, check_value, check_greater_than from openmc.region import Region, Intersection -if sys.version_info[0] >= 3: - basestring = str # A static variable for auto-generated Surface IDs AUTO_SURFACE_ID = 10000 @@ -135,14 +133,14 @@ class Surface(object): @name.setter def name(self, name): if name is not None: - check_type('surface name', name, basestring) + check_type('surface name', name, string_types) self._name = name else: self._name = '' @boundary_type.setter def boundary_type(self, boundary_type): - check_type('boundary type', boundary_type, basestring) + check_type('boundary type', boundary_type, string_types) check_value('boundary type', boundary_type, _BC_TYPES) self._boundary_type = boundary_type diff --git a/openmc/tallies.py b/openmc/tallies.py index f9daa7a228..6047131450 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -11,15 +11,13 @@ import sys import warnings from xml.etree import ElementTree as ET +from six import string_types import numpy as np import openmc import openmc.checkvalue as cv from openmc.clean_xml import clean_xml_indentation -if sys.version_info[0] >= 3: - basestring = str - # "Static" variable for auto-generated Tally IDs AUTO_TALLY_ID = 10000 @@ -33,9 +31,9 @@ _PRODUCT_TYPES = ['tensor', 'entrywise'] # The following indicate acceptable types when setting Tally.scores, # Tally.nuclides, and Tally.filters -_SCORE_CLASSES = (basestring, openmc.CrossScore, openmc.AggregateScore) -_NUCLIDE_CLASSES = (basestring, openmc.Nuclide, openmc.CrossNuclide, - openmc.AggregateNuclide) +_SCORE_CLASSES = string_types + (openmc.CrossScore, openmc.AggregateScore) +_NUCLIDE_CLASSES = string_types + (openmc.Nuclide, openmc.CrossNuclide, + openmc.AggregateNuclide) _FILTER_CLASSES = (openmc.Filter, openmc.CrossFilter, openmc.AggregateFilter) # Valid types of estimators @@ -431,7 +429,7 @@ class Tally(object): @name.setter def name(self, name): if name is not None: - cv.check_type('tally name', name, basestring) + cv.check_type('tally name', name, string_types) self._name = name else: self._name = '' @@ -478,7 +476,7 @@ class Tally(object): raise ValueError(msg) # If score is a string, strip whitespace - if isinstance(score, basestring): + if isinstance(score, string_types): scores[i] = score.strip() self._scores = cv.CheckedList(_SCORE_CLASSES, 'tally scores', scores) @@ -1355,7 +1353,7 @@ class Tally(object): """ - cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('nuclides', nuclides, string_types) # Determine the score indices from any of the requested scores if nuclides: @@ -1390,7 +1388,7 @@ class Tally(object): """ for score in scores: - if not isinstance(score, (basestring, openmc.CrossScore)): + if not isinstance(score, string_types + (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) @@ -1585,7 +1583,7 @@ class Tally(object): column_name = 'score' for score in self.scores: - if isinstance(score, (basestring, openmc.CrossScore)): + if isinstance(score, string_types + (openmc.CrossScore,)): scores.append(str(score)) elif isinstance(score, openmc.AggregateScore): scores.append(score.name) @@ -1700,13 +1698,13 @@ class Tally(object): msg = 'The Tally ID="{0}" has no data to export'.format(self.id) raise KeyError(msg) - if not isinstance(filename, basestring): + if not isinstance(filename, string_types): msg = 'Unable to export the results for Tally ID="{0}" to ' \ 'filename="{1}" since it is not a ' \ 'string'.format(self.id, filename) raise ValueError(msg) - elif not isinstance(directory, basestring): + elif not isinstance(directory, string_types): msg = 'Unable to export the results for Tally ID="{0}" to ' \ 'directory="{1}" since it is not a ' \ 'string'.format(self.id, directory) @@ -2354,11 +2352,11 @@ class Tally(object): raise ValueError(msg) # Check that the scores are valid - if not isinstance(score1, (basestring, openmc.CrossScore)): + if not isinstance(score1, string_types + (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, (basestring, openmc.CrossScore)): + elif not isinstance(score2, string_types + (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) diff --git a/openmc/trigger.py b/openmc/trigger.py index f23838dcff..69ec8c6200 100644 --- a/openmc/trigger.py +++ b/openmc/trigger.py @@ -4,10 +4,9 @@ import sys import warnings from collections import Iterable -import openmc.checkvalue as cv +from six import string_types -if sys.version_info[0] >= 3: - basestring = str +import openmc.checkvalue as cv class Trigger(object): @@ -77,7 +76,7 @@ class Trigger(object): @scores.setter def scores(self, scores): - cv.check_type('trigger scores', scores, Iterable, basestring) + cv.check_type('trigger scores', scores, Iterable, string_types) # Set scores making sure not to have duplicates self._scores = [] diff --git a/openmc/universe.py b/openmc/universe.py index c8fb89a384..545b05d5a1 100644 --- a/openmc/universe.py +++ b/openmc/universe.py @@ -3,13 +3,12 @@ from numbers import Integral import random import sys +from six import string_types import numpy as np import openmc import openmc.checkvalue as cv -if sys.version_info[0] >= 3: - basestring = str # A dictionary for storing IDs of cell elements that have already been written, # used to optimize the writing process @@ -118,7 +117,7 @@ class Universe(object): @name.setter def name(self, name): if name is not None: - cv.check_type('universe name', name, basestring) + cv.check_type('universe name', name, string_types) self._name = name else: self._name = '' From fdc22a3d70056a04c412d436153279b09be85f3e Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 6 Oct 2016 21:45:59 -0500 Subject: [PATCH 6/8] Use six to import Tkinter modules in openmc-plot-mesh-tally --- scripts/openmc-plot-mesh-tally | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/scripts/openmc-plot-mesh-tally b/scripts/openmc-plot-mesh-tally index 04f1f06c6c..cf17fabe9a 100755 --- a/scripts/openmc-plot-mesh-tally +++ b/scripts/openmc-plot-mesh-tally @@ -5,6 +5,11 @@ import os import sys +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 @@ -13,19 +18,6 @@ import numpy as np from openmc.statepoint import StatePoint -if sys.version_info[0] < 3: - import Tkinter as tk - import tkFileDialog as filedialog - import tkFont as font - import tkMessageBox as messagebox - import ttk as ttk -else: - import tkinter as tk - import tkinter.filedialog as filedialog - import tkinter.font as font - import tkinter.messagebox as messagebox - import tkinter.ttk as ttk - class MeshPlotter(tk.Frame): def __init__(self, parent, filename): From 5ab6160c2a590685085069cec59cb798c192c64f Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 13 Oct 2016 07:09:50 -0500 Subject: [PATCH 7/8] Move fission Q file to openmc/data and make sure it's accessible from openmc-get-nndc-data --- .../data}/fission_Q_data_endfb71.h5 | Bin scripts/openmc-get-nndc-data | 36 ++++++++---------- setup.py | 2 +- 3 files changed, 17 insertions(+), 21 deletions(-) rename {data => openmc/data}/fission_Q_data_endfb71.h5 (100%) diff --git a/data/fission_Q_data_endfb71.h5 b/openmc/data/fission_Q_data_endfb71.h5 similarity index 100% rename from data/fission_Q_data_endfb71.h5 rename to openmc/data/fission_Q_data_endfb71.h5 diff --git a/scripts/openmc-get-nndc-data b/scripts/openmc-get-nndc-data index 5231b67ef0..fe9d3ff5bd 100755 --- a/scripts/openmc-get-nndc-data +++ b/scripts/openmc-get-nndc-data @@ -13,6 +13,8 @@ import argparse from six.moves import input from six.moves.urllib.request import urlopen +import openmc.data + description = """ Download ENDF/B-VII.1 ACE data from NNDC and convert it to an HDF5 library for @@ -20,6 +22,7 @@ use with OpenMC. """ + class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass @@ -75,7 +78,8 @@ for f in files: if not chunk: break fh.write(chunk) downloaded += len(chunk) - status = '{0:10} [{1:3.2f}%]'.format(downloaded, downloaded * 100. / file_size) + status = '{0:10} [{1:3.2f}%]'.format( + downloaded, downloaded * 100. / file_size) print(status + chr(8)*len(status), end='') print('') filesComplete.append(f) @@ -109,7 +113,7 @@ for f in files: for filename in glob.glob('nndc/293.6K/ENDF-B-VII.1-neutron-293.6K/*'): shutil.move(filename, 'nndc/293.6K/') -#=============================================================================== +# ============================================================================== # EDIT GRAPHITE ZAID (6012 to 6000) print('Changing graphite ZAID from 6012 to 6000') @@ -137,24 +141,16 @@ if not response or response.lower().startswith('y'): os.remove(f) # ============================================================================== -# PROMPT USER TO GENERATE HDF5 LIBRARY +# GENERATE HDF5 LIBRARY -# Ask user to convert -if not args.batch: - response = input('Generate HDF5 library? ([y]/n) ') -else: - response = 'y' +# get a list of all ACE files +ace_files = sorted(glob.glob(os.path.join('nndc', '**', '*.ace*'))) -# Convert files if requested -if not response or response.lower().startswith('y'): - # get a list of all ACE files - ace_files = sorted(glob.glob(os.path.join('nndc', '**', '*.ace*'))) +# Get path to fission energy release data +data_dir = os.path.dirname(sys.modules['openmc.data'].__file__) +fer_file = os.path.join(data_dir, 'fission_Q_data_endfb71.h5') - # Ensure 'import openmc.data' works in the openmc-ace-to-xml script - cwd = os.getcwd() - env = os.environ.copy() - env['PYTHONPATH'] = os.path.join(cwd, '..') - - subprocess.call(['../scripts/openmc-ace-to-hdf5', '-d', 'nndc_hdf5', - '--fission_energy_release', 'fission_Q_data_endfb71.h5'] - + ace_files, env=env) +pwd = os.path.dirname(os.path.realpath(__file__)) +ace2hdf5 = os.path.join(pwd, 'openmc-ace-to-hdf5') +subprocess.call([ace2hdf5, '-d', 'nndc_hdf5', '--fission_energy_release', + fer_file] + ace_files) diff --git a/setup.py b/setup.py index fe1de3df8e..83098a9d5c 100644 --- a/setup.py +++ b/setup.py @@ -50,7 +50,7 @@ if have_setuptools: # Data files 'package_data': { - 'openmc.data': ['mass.mas12'] + 'openmc.data': ['mass.mas12', 'fission_Q_data_endfb71.h5'] }, }) From b605c4441de6d1261024bbcd4b5455b115e2ea20 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 13 Oct 2016 07:31:13 -0500 Subject: [PATCH 8/8] Fix .travis.yml --- .travis.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8df8f320eb..676bfb42f7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -47,11 +47,9 @@ before_script: fi - export OPENMC_CROSS_SECTIONS=$HOME/nndc_hdf5/cross_sections.xml - - cd data - 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 - - cd .. script: - cd tests