Merge pull request #679 from paulromano/pyapi-cleanup

Cleanup in Python API based on running pylint
This commit is contained in:
Will Boyd 2016-07-05 09:04:15 -04:00 committed by GitHub
commit ece50c3479
29 changed files with 216 additions and 253 deletions

View file

@ -1,6 +1,5 @@
import sys
import copy
from numbers import Integral
from collections import Iterable
import numpy as np
@ -321,7 +320,7 @@ class CrossFilter(object):
@type.setter
def type(self, filter_type):
if filter_type not in _FILTER_TYPES.values():
if filter_type not in _FILTER_TYPES:
msg = 'Unable to set CrossFilter type to "{0}" since it ' \
'is not one of the supported types'.format(filter_type)
raise ValueError(msg)
@ -576,7 +575,7 @@ class AggregateNuclide(object):
@nuclides.setter
def nuclides(self, nuclides):
cv.check_iterable_type('nuclides', nuclides,
(basestring, Nuclide, CrossNuclide))
(basestring, Nuclide, CrossNuclide))
self._nuclides = nuclides
@aggregate_op.setter
@ -691,7 +690,7 @@ class AggregateFilter(object):
@type.setter
def type(self, filter_type):
if filter_type not in _FILTER_TYPES.values():
if filter_type not in _FILTER_TYPES:
msg = 'Unable to set AggregateFilter type to "{0}" since it ' \
'is not one of the supported types'.format(filter_type)
raise ValueError(msg)

View file

@ -21,6 +21,7 @@ AUTO_CELL_ID = 10000
def reset_auto_cell_id():
"""Reset counter for auto-generated cell IDs."""
global AUTO_CELL_ID
AUTO_CELL_ID = 10000
@ -421,7 +422,7 @@ class Cell(object):
# Append all Cells in each Cell in the Universe to the dictionary
cells = self.get_all_cells()
for cell_id, cell in cells.items():
for cell in cells.values():
materials.update(cell.get_all_materials())
return materials
@ -497,7 +498,7 @@ class Cell(object):
if self.temperature is not None:
if isinstance(self.temperature, Iterable):
element.set("temperature", ' '.join(
str(t) for t in self.temperature))
str(t) for t in self.temperature))
else:
element.set("temperature", str(self.temperature))

View file

@ -1,6 +1,5 @@
import copy
from collections import Iterable
from numbers import Integral, Real
import numpy as np
@ -162,7 +161,7 @@ def check_length(name, value, length_min, length_max=None):
else:
msg = 'Unable to set "{0}" to "{1}" since it must have length ' \
'between "{2}" and "{3}"'.format(name, value, length_min,
length_max)
length_max)
raise ValueError(msg)
@ -255,6 +254,7 @@ class CheckedList(list):
"""
def __init__(self, expected_type, name, items=[]):
super(CheckedList, self).__init__()
self.expected_type = expected_type
self.name = name
for item in items:

View file

@ -15,9 +15,7 @@ from numbers import Real, Integral
from xml.etree import ElementTree as ET
import sys
import numpy as np
from openmc.clean_xml import *
from openmc.clean_xml import clean_xml_indentation
from openmc.checkvalue import (check_type, check_length, check_value,
check_greater_than, check_less_than)
@ -188,7 +186,7 @@ class CMFDMesh(object):
class CMFD(object):
"""Parameters that control the use of coarse-mesh finite difference acceleration
r"""Parameters that control the use of coarse-mesh finite difference acceleration
in OpenMC. This corresponds directly to the cmfd.xml input file.
Attributes

View file

@ -45,9 +45,9 @@ class Element(object):
def __eq__(self, other):
if isinstance(other, Element):
if self._name != other._name:
if self.name != other.name:
return False
elif self._xs != other._xs:
elif self.xs != other.xs:
return False
else:
return True
@ -68,9 +68,6 @@ class Element(object):
def __hash__(self):
return hash(repr(self))
def __hash__(self):
return hash(repr(self))
def __repr__(self):
string = 'Element - {0}\n'.format(self._name)
string += '{0: <16}{1}{2}\n'.format('\tXS', '=\t', self._xs)

View file

@ -6,7 +6,6 @@ import sys
import numpy as np
from openmc import Mesh
from openmc.summary import Summary
import openmc.checkvalue as cv
@ -391,7 +390,7 @@ class Filter(object):
if self.type == 'mesh':
# 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):
if len(self.mesh.dimension) == 3:
nx, ny, nz = self.mesh.dimension
val = (filter_bin[0] - 1) * ny * nz + \
(filter_bin[1] - 1) * nz + \
@ -568,7 +567,7 @@ class Filter(object):
mesh_key = 'mesh {0}'.format(self.mesh.id)
# Find mesh dimensions - use 3D indices for simplicity
if (len(self.mesh.dimension) == 3):
if len(self.mesh.dimension) == 3:
nx, ny, nz = self.mesh.dimension
else:
nx, ny = self.mesh.dimension

View file

@ -1,11 +1,13 @@
from collections import Iterable, OrderedDict
from collections import OrderedDict
from xml.etree import ElementTree as ET
import openmc
from openmc.clean_xml import *
from openmc.clean_xml import sort_xml_elements, clean_xml_indentation
from openmc.checkvalue import check_type
def reset_auto_ids():
"""Reset counters for all auto-generated IDs"""
openmc.reset_auto_material_id()
openmc.reset_auto_surface_id()
openmc.reset_auto_cell_id()
@ -40,10 +42,10 @@ class Geometry(object):
@root_universe.setter
def root_universe(self, root_universe):
check_type('root universe', root_universe, openmc.Universe)
if root_universe._id != 0:
if root_universe.id != 0:
msg = 'Unable to add root Universe "{0}" to Geometry since ' \
'it has ID="{1}" instead of ' \
'ID=0'.format(root_universe, root_universe._id)
'ID=0'.format(root_universe, root_universe.id)
raise ValueError(msg)
self._root_universe = root_universe
@ -281,9 +283,9 @@ class Geometry(object):
The name to match
case_sensitive : bool
Whether to distinguish upper and lower case letters in each
material's name (default is True)
material's name (default is False)
matching : bool
Whether the names must match completely (default is True)
Whether the names must match completely (default is False)
Returns
-------
@ -321,9 +323,9 @@ class Geometry(object):
The name to search match
case_sensitive : bool
Whether to distinguish upper and lower case letters in each
cell's name (default is True)
cell's name (default is False)
matching : bool
Whether the names must match completely (default is True)
Whether the names must match completely (default is False)
Returns
-------
@ -361,9 +363,9 @@ class Geometry(object):
The name to match
case_sensitive : bool
Whether to distinguish upper and lower case letters in each
cell's name (default is True)
cell's name (default is False)
matching : bool
Whether the names must match completely (default is True)
Whether the names must match completely (default is False)
Returns
-------
@ -401,9 +403,9 @@ class Geometry(object):
The name to match
case_sensitive : bool
Whether to distinguish upper and lower case letters in each
universe's name (default is True)
universe's name (default is False)
matching : bool
Whether the names must match completely (default is True)
Whether the names must match completely (default is False)
Returns
-------
@ -441,9 +443,9 @@ class Geometry(object):
The name to match
case_sensitive : bool
Whether to distinguish upper and lower case letters in each
lattice's name (default is True)
lattice's name (default is False)
matching : bool
Whether the names must match completely (default is True)
Whether the names must match completely (default is False)
Returns
-------

View file

@ -6,7 +6,6 @@ from math import sqrt, floor
from numbers import Real, Integral
from xml.etree import ElementTree as ET
import sys
import warnings
import numpy as np
@ -429,14 +428,14 @@ class RectLattice(Lattice):
# For 2D Lattices
if self.ndim == 2:
offset = self._offsets[lat_z, lat_y, lat_x, distribcell_index-1]
offset += self._universes[lat_x][lat_y].get_cell_instance(path,
distribcell_index)
offset += self._universes[lat_x][lat_y].get_cell_instance(
path, distribcell_index)
# For 3D Lattices
else:
offset = self._offsets[lat_z, lat_y, lat_x, distribcell_index-1]
offset += self._universes[lat_z][lat_y][lat_x].get_cell_instance(
path, distribcell_index)
path, distribcell_index)
return offset
@ -908,7 +907,7 @@ class HexLattice(Lattice):
# coordinates
d_min = np.inf
for idx in [(ix, ia, iz), (ix + 1, ia, iz), (ix, ia + 1, iz),
(ix + 1, ia + 1, iz)]:
(ix + 1, ia + 1, iz)]:
p = self.get_local_coordinates(point, idx)
d = p[0]**2 + p[1]**2
if d < d_min:

View file

@ -1,4 +1,3 @@
from numbers import Integral
import sys
from openmc.checkvalue import check_type
@ -39,9 +38,9 @@ class Macroscopic(object):
def __eq__(self, other):
if isinstance(other, Macroscopic):
if self._name != other._name:
if self.name != other.name:
return False
elif self._xs != other._xs:
elif self.xs != other.xs:
return False
else:
return True
@ -78,8 +77,3 @@ class Macroscopic(object):
def xs(self, xs):
check_type('cross-section identifier', xs, basestring)
self._xs = xs
def __repr__(self):
string = 'Macroscopic - {0}\n'.format(self._name)
string += '{0: <16}{1}{2}\n'.format('\tXS', '=\t', self.xs)
return string

View file

@ -1,16 +1,16 @@
from collections import Iterable, OrderedDict
from collections import OrderedDict
from copy import deepcopy
from numbers import Real, Integral
import warnings
from xml.etree import ElementTree as ET
import sys
if sys.version_info[0] >= 3:
basestring = str
import openmc
import openmc.checkvalue as cv
from openmc.clean_xml import *
from openmc.data import natural_abundance
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
@ -18,6 +18,7 @@ AUTO_MATERIAL_ID = 10000
def reset_auto_material_id():
"""Reset counter for auto-generated material IDs."""
global AUTO_MATERIAL_ID
AUTO_MATERIAL_ID = 10000
@ -351,9 +352,9 @@ class Material(object):
if self._macroscopic is None:
self._macroscopic = macroscopic
else:
msg = 'Unable to add a Macroscopic to Material ID="{0}", ' \
'Only One Macroscopic allowed per ' \
'Material!'.format(self._id, macroscopic)
msg = 'Unable to add a Macroscopic to Material ID="{0}". ' \
'Only one Macroscopic allowed per ' \
'Material.'.format(self._id)
raise ValueError(msg)
# Generally speaking, the density for a macroscopic object will
@ -380,7 +381,7 @@ class Material(object):
raise ValueError(msg)
# If the Material contains the Macroscopic, delete it
if macroscopic._name == self._macroscopic.name:
if macroscopic.name == self._macroscopic.name:
self._macroscopic = None
def add_element(self, element, percent, percent_type='ao', expand=False):
@ -446,7 +447,7 @@ class Material(object):
"""
if not isinstance(nuclide, openmc.Element):
if not isinstance(element, openmc.Element):
msg = 'Unable to remove "{0}" in Material ID="{1}" ' \
'since it is not an Element'.format(self.id, element)
raise ValueError(msg)
@ -534,7 +535,7 @@ class Material(object):
def _get_macroscopic_xml(self, macroscopic):
xml_element = ET.Element("macroscopic")
xml_element.set("name", macroscopic._name)
xml_element.set("name", macroscopic.name)
if macroscopic.xs is not None:
xml_element.set("xs", macroscopic.xs)
@ -640,7 +641,7 @@ class Material(object):
if self._macroscopic is None:
# Create nuclide XML subelements
subelements = self.get_nuclides_xml(self._nuclides, distrib=True)
subelements = self._get_nuclides_xml(self._nuclides, distrib=True)
for subelement_nuc in subelements:
subelement.append(subelement_nuc)
@ -650,8 +651,7 @@ class Material(object):
subelement.append(subsubelement)
else:
# Create macroscopic XML subelements
subsubelement = self._get_macroscopic_xml(self._macroscopic,
distrib=True)
subsubelement = self._get_macroscopic_xml(self._macroscopic)
subelement.append(subsubelement)
if len(self._sab) > 0:

View file

@ -16,6 +16,7 @@ AUTO_MESH_ID = 10000
def reset_auto_mesh_id():
"""Reset counter for auto-generated mesh IDs."""
global AUTO_MESH_ID
AUTO_MESH_ID = 10000
@ -63,20 +64,20 @@ class Mesh(object):
def __eq__(self, mesh2):
# Check type
if self._type != mesh2._type:
if self._type != mesh2.type:
return False
# Check dimension
elif self._dimension != mesh2._dimension:
elif self._dimension != mesh2.dimension:
return False
# Check width
elif self._width != mesh2._width:
elif self._width != mesh2.width:
return False
# Check lower left / upper right
elif self._lower_left != mesh2._lower_left and \
self._upper_right != mesh2._upper_right:
elif self._lower_left != mesh2.lower_left and \
self._upper_right != mesh2.upper_right:
return False
else:
@ -129,7 +130,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, basestring)
self._name = name
else:
self._name = ''
@ -137,9 +138,9 @@ class Mesh(object):
@type.setter
def type(self, meshtype):
cv.check_type('type for mesh ID="{0}"'.format(self._id),
meshtype, basestring)
meshtype, basestring)
cv.check_value('type for mesh ID="{0}"'.format(self._id),
meshtype, ['regular'])
meshtype, ['regular'])
self._type = meshtype
@dimension.setter

View file

@ -2,7 +2,6 @@ import sys
import os
import copy
import pickle
import warnings
from numbers import Integral
from collections import OrderedDict
from warnings import warn
@ -152,10 +151,6 @@ class Library(object):
def openmc_geometry(self):
return self._openmc_geometry
@property
def openmc_geometry(self):
return self._openmc_geometry
@property
def opencg_geometry(self):
if self._opencg_geometry is None:
@ -279,16 +274,14 @@ class Library(object):
cv.check_iterable_type('domain', domains, openmc.Universe)
all_domains = self.openmc_geometry.get_all_universes()
else:
msg = 'Unable to set domains with ' \
'domain type "{}"'.format(self.domain_type)
raise ValueError(msg)
raise ValueError('Unable to set domains with domain '
'type "{}"'.format(self.domain_type))
# Check that each domain can be found in the geometry
for domain in domains:
if domain not in all_domains:
msg = 'Domain "{}" could not be found in the ' \
'geometry.'.format(domain)
raise ValueError(msg)
raise ValueError('Domain "{}" could not be found in the '
'geometry.'.format(domain))
self._domains = domains
@ -302,9 +295,8 @@ class Library(object):
cv.check_value('correction', correction, ('P0', None))
if correction == 'P0' and self.legendre_order > 0:
msg = 'The P0 correction will be ignored since the scattering ' \
'order {} is greater than zero'.format(self.legendre_order)
warnings.warn(msg)
warn('The P0 correction will be ignored since the scattering '
'order "{}" is greater than zero'.format(self.legendre_order))
self._correction = correction
@ -317,7 +309,7 @@ class Library(object):
if self.correction == 'P0' and legendre_order > 0:
msg = 'The P0 correction will be ignored since the scattering ' \
'order {} is greater than zero'.format(self.legendre_order)
warnings.warn(msg, RuntimeWarning)
warn(msg, RuntimeWarning)
self.correction = None
self._legendre_order = legendre_order
@ -402,7 +394,7 @@ class Library(object):
for domain in self.domains:
for mgxs_type in self.mgxs_types:
mgxs = self.get_mgxs(domain, mgxs_type)
for tally_id, tally in mgxs.tallies.items():
for tally in mgxs.tallies.values():
tallies_file.append(tally, merge=merge)
def load_from_statepoint(self, statepoint):
@ -498,8 +490,8 @@ class Library(object):
# Check that requested domain is included in library
if mgxs_type not in self.mgxs_types:
msg = 'Unable to find MGXS type "{0}"'.format(mgxs_type)
raise ValueError(msg)
msg = 'Unable to find MGXS type "{0}"'.format(mgxs_type)
raise ValueError(msg)
return self.all_mgxs[domain_id][mgxs_type]
@ -922,7 +914,7 @@ class Library(object):
# accounted for approximately by using an adjusted
# absorption cross section.
if 'total' in self.mgxs_types:
xsdata._absorption = \
xsdata.absorption = \
np.subtract(xsdata.total,
np.sum(xsdata.scatter[0, :, :], axis=1))
@ -1184,13 +1176,11 @@ class Library(object):
# Ensure absorption is present
if 'absorption' not in self.mgxs_types:
error_flag = True
msg = '"absorption" MGXS type is required but not provided.'
warn(msg)
warn('An "absorption" MGXS type is required but not provided.')
# Ensure nu-scattering matrix is required
if 'nu-scatter matrix' not in self.mgxs_types:
error_flag = True
msg = '"nu-scatter matrix" MGXS type is required but not provided.'
warn(msg)
warn('A "nu-scatter matrix" MGXS type is required but not provided.')
else:
# Ok, now see the status of scatter and/or multiplicity
if ((('scatter matrix' not in self.mgxs_types) and
@ -1199,24 +1189,20 @@ class Library(object):
# we need total, and not transport.
if 'total' not in self.mgxs_types:
error_flag = True
msg = '"total" MGXS type is required if a ' \
'scattering matrix is not provided.'
warn(msg)
warn('A "total" MGXS type is required if a '
'scattering matrix is not provided.')
# Total or transport can be present, but if using
# self.correction=="P0", then we should use transport.
if (((self.correction is "P0") and
('nu-transport' not in self.mgxs_types))):
error_flag = True
msg = 'A "nu-transport" MGXS type is required since a "P0" ' \
'correction is applied, but a "nu-transport" MGXS is ' \
'not provided.'
warn(msg)
warn('A "nu-transport" MGXS type is required since a "P0" '
'correction is applied, but a "nu-transport" MGXS is '
'not provided.')
elif (((self.correction is None) and
('total' not in self.mgxs_types))):
error_flag = True
msg = '"total" MGXS type is required, but not provided.'
warn(msg)
warn('A "total" MGXS type is required, but not provided.')
if error_flag:
msg = 'Invalid MGXS configuration encountered.'
raise ValueError(msg)
raise ValueError('Invalid MGXS configuration encountered.')

View file

@ -1,6 +1,6 @@
from __future__ import division
from collections import Iterable, OrderedDict
from collections import OrderedDict
from numbers import Integral
import warnings
import os
@ -412,7 +412,7 @@ class MGXS(object):
self.rxn_rate_tally.sparse = sparse
for tally_name in self.tallies:
self.tallies[tally_name].sparse = sparse
self.tallies[tally_name].sparse = sparse
self._sparse = sparse
@ -852,7 +852,7 @@ class MGXS(object):
fine_edges = self.energy_groups.group_edges
# Condense each of the tallies to the coarse group structure
for tally_type, tally in condensed_xs.tallies.items():
for tally in condensed_xs.tallies.values():
# Make condensed tally derived and null out sum, sum_sq
tally._derived = True
@ -993,7 +993,8 @@ class MGXS(object):
slice_nuclides = [nuc for nuc in nuclides if nuc in tally.nuclides]
if len(groups) != 0 and tally.contains_filter('energy'):
tally_slice = tally.get_slice(filters=filters,
filter_bins=filter_bins, nuclides=slice_nuclides)
filter_bins=filter_bins,
nuclides=slice_nuclides)
else:
tally_slice = tally.get_slice(nuclides=slice_nuclides)
slice_xs.tallies[tally_type] = tally_slice
@ -1286,7 +1287,7 @@ class MGXS(object):
num_digits = len(str(self.num_subdomains))
# Create a separate HDF5 group for each subdomain
for i, subdomain in enumerate(subdomains):
for subdomain in subdomains:
# Create an HDF5 group for the subdomain
if self.domain_type == 'distribcell':
@ -1311,9 +1312,11 @@ class MGXS(object):
# Extract the cross section for this subdomain and nuclide
average = self.get_xs(subdomains=[subdomain], nuclides=[nuclide],
xs_type=xs_type, value='mean', row_column=row_column)
xs_type=xs_type, value='mean',
row_column=row_column)
std_dev = self.get_xs(subdomains=[subdomain], nuclides=[nuclide],
xs_type=xs_type, value='std_dev', row_column=row_column)
xs_type=xs_type, value='std_dev',
row_column=row_column)
average = average.squeeze()
std_dev = std_dev.squeeze()
@ -1386,9 +1389,9 @@ class MGXS(object):
longtable=True, index=False)
# Surround LaTeX table with code needed to run pdflatex
with open(filename + '.tex','r') as original:
with open(filename + '.tex', 'r') as original:
data = original.read()
with open(filename + '.tex','w') as modified:
with open(filename + '.tex', 'w') as modified:
modified.write(
'\\documentclass[preview, 12pt, border=1mm]{standalone}\n')
modified.write('\\usepackage{caption}\n')
@ -1451,7 +1454,7 @@ class MGXS(object):
query_nuclides = self.get_all_nuclides()
xs_tally = self.xs_tally.summation(nuclides=query_nuclides)
df = xs_tally.get_pandas_dataframe(
distribcell_paths=distribcell_paths)
distribcell_paths=distribcell_paths)
# Remove nuclide column since it is homogeneous and redundant
df.drop('nuclide', axis=1, inplace=True)
@ -1460,12 +1463,12 @@ class MGXS(object):
elif self.by_nuclide and nuclides != 'all':
xs_tally = self.xs_tally.get_slice(nuclides=nuclides)
df = xs_tally.get_pandas_dataframe(
distribcell_paths=distribcell_paths)
distribcell_paths=distribcell_paths)
# If the user requested all nuclides, keep nuclide column in dataframe
else:
df = self.xs_tally.get_pandas_dataframe(
distribcell_paths=distribcell_paths)
distribcell_paths=distribcell_paths)
# Remove the score column since it is homogeneous and redundant
df = df.drop('score', axis=1)
@ -3443,7 +3446,7 @@ class ScatterMatrixXS(MatrixMGXS):
def get_xs(self, in_groups='all', out_groups='all',
subdomains='all', nuclides='all', moment='all',
xs_type='macro', order_groups='increasing',
row_column='inout', value='mean', **kwargs):
row_column='inout', value='mean'):
r"""Returns an array of multi-group cross sections.
This method constructs a 2D NumPy array for the requested scattering
@ -3530,7 +3533,7 @@ class ScatterMatrixXS(MatrixMGXS):
cv.check_type('moment', moment, Integral)
cv.check_greater_than('moment', moment, 0, equality=True)
cv.check_less_than(
'moment', moment, self.legendre_order, equality=True)
'moment', moment, self.legendre_order, equality=True)
scores = [self.xs_tally.scores[moment]]
else:
scores = []
@ -3641,7 +3644,7 @@ class ScatterMatrixXS(MatrixMGXS):
"""
df = super(ScatterMatrixXS, self).get_pandas_dataframe(
groups, nuclides, xs_type, distribcell_paths)
groups, nuclides, xs_type, distribcell_paths)
# Add a moment column to dataframe
if self.legendre_order > 0:
@ -3660,7 +3663,7 @@ class ScatterMatrixXS(MatrixMGXS):
cv.check_type('moment', moment, Integral)
cv.check_greater_than('moment', moment, 0, equality=True)
cv.check_less_than(
'moment', moment, self.legendre_order, equality=True)
'moment', moment, self.legendre_order, equality=True)
df = df[df['moment'] == 'P{}'.format(moment)]
return df
@ -4601,7 +4604,7 @@ class Chi(MGXS):
# Build the dataframe using the parent class method
df = super(Chi, self).get_pandas_dataframe(
groups, nuclides, xs_type, distribcell_paths=distribcell_paths)
groups, nuclides, xs_type, distribcell_paths=distribcell_paths)
# If user requested micro cross sections, multiply by the atom
# densities to cancel out division made by the parent class method

View file

@ -9,7 +9,7 @@ import openmc
import openmc.mgxs
from openmc.checkvalue import check_type, check_value, check_greater_than, \
check_iterable_type
from openmc.clean_xml import *
from openmc.clean_xml import sort_xml_elements, clean_xml_indentation
if sys.version_info[0] >= 3:
basestring = str
@ -376,7 +376,7 @@ class XSdata(object):
# Check validity of energy_groups
check_type('energy_groups', energy_groups, openmc.mgxs.EnergyGroups)
if energy_group.group_edges is None:
if energy_groups.group_edges is None:
msg = 'Unable to assign an EnergyGroups object ' \
'with uninitialized group edges'
raise ValueError(msg)
@ -597,10 +597,7 @@ class XSdata(object):
[self.vector_shape, self.matrix_shape])
# Find out if we have a nu-fission matrix or vector
# and set a flag to allow other methods to check this later.
if npnu_fission.shape == self.vector_shape:
self.use_chi = True
else:
self.use_chi = False
self.use_chi = (npnu_fission.shape == self.vector_shape)
self._nu_fission = npnu_fission
if np.sum(self._nu_fission) > 0.0:
@ -873,7 +870,7 @@ class XSdata(object):
check_value('domain_type', scatter.domain_type,
['universe', 'cell', 'material'])
if (self.scatt_type != 'legendre'):
if self.scatt_type != 'legendre':
msg = 'Anisotropic scattering representations other than ' \
'Legendre expansions have not yet been implemented in ' \
'openmc.mgxs.'
@ -1090,9 +1087,9 @@ class MGXSLibrary(object):
@inverse_velocities.setter
def inverse_velocities(self, inverse_velocities):
cv.check_type('inverse_velocities', inverse_velocities, Iterable, Real)
cv.check_greater_than('number of inverse_velocities',
len(inverse_velocities), 0.0)
check_type('inverse_velocities', inverse_velocities, Iterable, Real)
check_greater_than('number of inverse_velocities',
len(inverse_velocities), 0.0)
self._inverse_velocities = np.array(inverse_velocities)
@energy_groups.setter

View file

@ -46,9 +46,9 @@ class Nuclide(object):
def __eq__(self, other):
if isinstance(other, Nuclide):
if self._name != other._name:
if self.name != other.name:
return False
elif self._xs != other._xs:
elif self.xs != other.xs:
return False
else:
return True
@ -71,9 +71,12 @@ class Nuclide(object):
def __repr__(self):
string = 'Nuclide - {0}\n'.format(self._name)
string += '{0: <16}{1}{2}\n'.format('\tXS', '=\t', self._xs)
if self._zaid is not None:
string += '{0: <16}{1}{2}\n'.format('\tZAID', '=\t', self._zaid)
string += '{0: <16}{1}{2}\n'.format('\tXS', '=\t', self.xs)
if self.zaid is not None:
string += '{0: <16}{1}{2}\n'.format('\tZAID', '=\t', self.zaid)
if self.scattering is not None:
string += '{0: <16}{1}{2}\n'.format('\tscattering', '=\t',
self.scattering)
return string
@property
@ -116,13 +119,3 @@ class Nuclide(object):
raise ValueError(msg)
self._scattering = scattering
def __repr__(self):
string = 'Nuclide - {0}\n'.format(self._name)
string += '{0: <16}{1}{2}\n'.format('\tXS', '=\t', self.xs)
if self.zaid is not None:
string += '{0: <16}{1}{2}\n'.format('\tZAID', '=\t', self.zaid)
if self.scattering is not None:
string += '{0: <16}{1}{2}\n'.format('\tscattering', '=\t',
self.scattering)
return string

View file

@ -6,8 +6,8 @@ import numpy as np
try:
import opencg
except ImportError:
msg = 'Unable to import opencg which is needed by openmc.opencg_compatible'
raise ImportError(msg)
raise ImportError('Unable to import opencg which is needed by '
'openmc.opencg_compatible')
import openmc
import openmc.checkvalue as cv
@ -81,7 +81,6 @@ def get_opencg_material(openmc_material):
cv.check_type('openmc_material', openmc_material, openmc.Material)
global OPENCG_MATERIALS
material_id = openmc_material.id
# If this Material was already created, use it
@ -118,7 +117,6 @@ def get_openmc_material(opencg_material):
cv.check_type('opencg_material', opencg_material, opencg.Material)
global OPENMC_MATERIALS
material_id = opencg_material.id
# If this Material was already created, use it
@ -185,7 +183,6 @@ def get_opencg_surface(openmc_surface):
cv.check_type('openmc_surface', openmc_surface, openmc.Surface)
global OPENCG_SURFACES
surface_id = openmc_surface.id
# If this Material was already created, use it
@ -226,21 +223,21 @@ def get_opencg_surface(openmc_surface):
z0 = openmc_surface.z0
R = openmc_surface.r
opencg_surface = opencg.XCylinder(surface_id, name,
boundary, y0, z0, R)
boundary, y0, z0, R)
elif openmc_surface.type == 'y-cylinder':
x0 = openmc_surface.x0
z0 = openmc_surface.z0
R = openmc_surface.r
opencg_surface = opencg.YCylinder(surface_id, name,
boundary, x0, z0, R)
boundary, x0, z0, R)
elif openmc_surface.type == 'z-cylinder':
x0 = openmc_surface.x0
y0 = openmc_surface.y0
R = openmc_surface.r
opencg_surface = opencg.ZCylinder(surface_id, name,
boundary, x0, y0, R)
boundary, x0, y0, R)
# Add the OpenMC Surface to the global collection of all OpenMC Surfaces
OPENMC_SURFACES[surface_id] = openmc_surface
@ -268,7 +265,6 @@ def get_openmc_surface(opencg_surface):
cv.check_type('opencg_surface', opencg_surface, opencg.Surface)
global openmc_surface
surface_id = opencg_surface.id
# If this Surface was already created, use it
@ -356,7 +352,6 @@ def get_compatible_opencg_surfaces(opencg_surface):
cv.check_type('opencg_surface', opencg_surface, opencg.Surface)
global OPENMC_SURFACES
surface_id = opencg_surface.id
# If this Surface was already created, use it
@ -435,7 +430,6 @@ def get_opencg_cell(openmc_cell):
cv.check_type('openmc_cell', openmc_cell, openmc.Cell)
global OPENCG_CELLS
cell_id = openmc_cell.id
# If this Cell was already created, use it
@ -480,7 +474,7 @@ def get_opencg_cell(openmc_cell):
opencg_cell.add_surface(get_opencg_surface(surface), halfspace)
else:
raise NotImplementedError("Complex cells not yet supported "
"in OpenCG.")
"in OpenCG.")
# Add the OpenMC Cell to the global collection of all OpenMC Cells
OPENMC_CELLS[cell_id] = openmc_cell
@ -615,7 +609,7 @@ def make_opencg_cells_compatible(opencg_universe):
# Check all OpenCG Cells in this Universe for compatibility with OpenMC
opencg_cells = opencg_universe.cells
for cell_id, opencg_cell in opencg_cells.items():
for opencg_cell in opencg_cells.values():
# Check each of the OpenCG Surfaces for OpenMC compatibility
surfaces = opencg_cell.surfaces
@ -635,7 +629,7 @@ def make_opencg_cells_compatible(opencg_universe):
# of this block is necessary in the event that there are more
# incompatible Surfaces in this Cell that are not accounted for.
cells = get_compatible_opencg_cells(opencg_cell,
surface, halfspace)
surface, halfspace)
# Remove the non-compatible OpenCG Cell from the Universe
opencg_universe.remove_cell(opencg_cell)
@ -668,7 +662,6 @@ def get_openmc_cell(opencg_cell):
cv.check_type('opencg_cell', opencg_cell, opencg.Cell)
global OPENMC_CELLS
cell_id = opencg_cell.id
# If this Cell was already created, use it
@ -730,7 +723,6 @@ def get_opencg_universe(openmc_universe):
cv.check_type('openmc_universe', openmc_universe, openmc.Universe)
global OPENCG_UNIVERSES
universe_id = openmc_universe.id
# If this Universe was already created, use it
@ -744,7 +736,7 @@ def get_opencg_universe(openmc_universe):
# Convert all OpenMC Cells in this Universe to OpenCG Cells
openmc_cells = openmc_universe.cells
for cell_id, openmc_cell in openmc_cells.items():
for openmc_cell in openmc_cells.values():
opencg_cell = get_opencg_cell(openmc_cell)
opencg_universe.add_cell(opencg_cell)
@ -774,7 +766,6 @@ def get_openmc_universe(opencg_universe):
cv.check_type('opencg_universe', opencg_universe, opencg.Universe)
global OPENMC_UNIVERSES
universe_id = opencg_universe.id
# If this Universe was already created, use it
@ -791,7 +782,7 @@ def get_openmc_universe(opencg_universe):
# Convert all OpenCG Cells in this Universe to OpenMC Cells
opencg_cells = opencg_universe.cells
for cell_id, opencg_cell in opencg_cells.items():
for opencg_cell in opencg_cells.values():
openmc_cell = get_openmc_cell(opencg_cell)
openmc_universe.add_cell(openmc_cell)
@ -821,7 +812,6 @@ def get_opencg_lattice(openmc_lattice):
cv.check_type('openmc_lattice', openmc_lattice, openmc.Lattice)
global OPENCG_LATTICES
lattice_id = openmc_lattice.id
# If this Lattice was already created, use it
@ -915,7 +905,6 @@ def get_openmc_lattice(opencg_lattice):
cv.check_type('opencg_lattice', opencg_lattice, opencg.Lattice)
global OPENMC_LATTICES
lattice_id = opencg_lattice.id
# If this Lattice was already created, use it
@ -1043,7 +1032,7 @@ def get_openmc_geometry(opencg_geometry):
# Make the entire geometry "compatible" before assigning auto IDs
universes = opencg_geometry.get_all_universes()
for universe_id, universe in universes.items():
for universe in universes.values():
if not isinstance(universe, opencg.Lattice):
make_opencg_cells_compatible(universe)

View file

@ -1,6 +1,3 @@
import struct
class Particle(object):
"""Information used to restart a specific particle that caused a simulation to
fail.

View file

@ -8,7 +8,7 @@ import numpy as np
import openmc
import openmc.checkvalue as cv
from openmc.clean_xml import *
from openmc.clean_xml import clean_xml_indentation
if sys.version_info[0] >= 3:
basestring = str
@ -18,6 +18,7 @@ AUTO_PLOT_ID = 10000
def reset_auto_plot_id():
"""Reset counter for auto-generated plot IDs."""
global AUTO_PLOT_ID
AUTO_PLOT_ID = 10000
@ -201,7 +202,7 @@ class Plot(object):
cv.check_type('plot background', background, Iterable, Integral)
cv.check_length('plot background', background, 3)
for rgb in background:
cv.check_greater_than('plot background',rgb, 0, True)
cv.check_greater_than('plot background', rgb, 0, True)
cv.check_less_than('plot background', rgb, 256)
self._background = background
@ -257,7 +258,7 @@ class Plot(object):
string += '{0: <16}{1}{2}\n'.format('\tColor', '=\t', self._color)
string += '{0: <16}{1}{2}\n'.format('\tMask', '=\t',
self._mask_components)
string += '{0: <16}{1}{2}\n'.format('\tMask', '=\t',
string += '{0: <16}{1}{2}\n'.format('\tMask', '=\t',
self._mask_background)
string += '{0: <16}{1}{2}\n'.format('\tCol Spec', '=\t', self._col_spec)
return string
@ -536,8 +537,8 @@ class Plots(cv.CheckedList):
for plot in self:
xml_element = plot.get_plot_xml()
if len(plot._name) > 0:
self._plots_file.append(ET.Comment(plot._name))
if len(plot.name) > 0:
self._plots_file.append(ET.Comment(plot.name))
self._plots_file.append(xml_element)
@ -557,4 +558,4 @@ class Plots(cv.CheckedList):
# Write the XML Tree to the plots.xml file
tree = ET.ElementTree(self._plots_file)
tree.write("plots.xml", xml_declaration=True,
encoding='utf-8', method="xml")
encoding='utf-8', method="xml")

View file

@ -203,7 +203,7 @@ class Region(object):
class Intersection(Region):
"""Intersection of two or more regions.
r"""Intersection of two or more regions.
Instances of Intersection are generally created via the __and__ operator
applied to two instances of :class:`openmc.Region`. This is illustrated in
@ -277,7 +277,7 @@ class Intersection(Region):
class Union(Region):
"""Union of two or more regions.
r"""Union of two or more regions.
Instances of Union are generally created via the __or__ operator applied to
two instances of :class:`openmc.Region`. This is illustrated in the

View file

@ -6,7 +6,7 @@ import sys
import numpy as np
from openmc.clean_xml import *
from openmc.clean_xml import clean_xml_indentation
from openmc.checkvalue import (check_type, check_length, check_value,
check_greater_than, check_less_than)
from openmc import Nuclide
@ -311,7 +311,7 @@ class Settings(object):
@property
def trigger_batch_interval(self):
return self._batch_interval
return self._trigger_batch_interval
@property
def output(self):
@ -1011,7 +1011,7 @@ class Settings(object):
if self._trigger_active is not None:
if self._trigger_subelement is None:
self._trigger_subelement = ET.SubElement(self._settings_file,
"trigger")
"trigger")
element = ET.SubElement(self._trigger_subelement, "active")
element.text = str(self._trigger_active).lower()
@ -1020,7 +1020,7 @@ class Settings(object):
if self._trigger_max_batches is not None:
if self._trigger_subelement is None:
self._trigger_subelement = ET.SubElement(self._settings_file,
"trigger")
"trigger")
element = ET.SubElement(self._trigger_subelement, "max_batches")
element.text = str(self._trigger_max_batches)
@ -1029,7 +1029,7 @@ class Settings(object):
if self._trigger_batch_interval is not None:
if self._trigger_subelement is None:
self._trigger_subelement = ET.SubElement(self._settings_file,
"trigger")
"trigger")
element = ET.SubElement(self._trigger_subelement, "batch_interval")
element.text = str(self._trigger_batch_interval)
@ -1103,14 +1103,16 @@ class Settings(object):
element.text = str(self._multipole_active)
def _create_resonance_scattering_element(self):
if self.resonance_scattering is None: return
if self.resonance_scattering is None:
return
element = ET.SubElement(self._settings_file, "resonance_scattering")
for r in self.resonance_scattering:
if r.nuclide.name != r.nuclide_0K.name:
raise ValueError("The nuclide and nuclide_0K attributes of "
"a ResonantScattering object must have identical names.")
"a ResonantScattering object must have "
"identical names.")
r.create_xml_subelement(element)
def export_to_xml(self):
@ -1159,7 +1161,7 @@ class Settings(object):
# Write the XML Tree to the settings.xml file
tree = ET.ElementTree(self._settings_file)
tree.write("settings.xml", xml_declaration=True,
encoding='utf-8', method="xml")
encoding='utf-8', method="xml")
class ResonanceScattering(object):
@ -1215,15 +1217,17 @@ class ResonanceScattering(object):
@nuclide.setter
def nuclide(self, nuc):
check_type('nuclide', nuc, Nuclide)
if nuc.zaid == None: raise ValueError("The nuclide must have an "
"explicitly defined zaid attribute.")
if nuc.zaid is None:
raise ValueError("The nuclide must have an explicitly defined "
"zaid attribute.")
self._nuclide = nuc
@nuclide_0K.setter
def nuclide_0K(self, nuc):
check_type('nuclide_0K', nuc, Nuclide)
if nuc.zaid == None: raise ValueError("The nuclide_0K must have an "
"explicitly defined zaid attribute.")
if nuc.zaid is None:
raise ValueError("The nuclide_0K must have an explicitly defined "
"zaid attribute.")
self._nuclide_0K = nuc
@method.setter

View file

@ -104,6 +104,14 @@ class Source(object):
self._strength = strength
def to_xml(self):
"""Return XML representation of the source
Returns
-------
element : xml.etree.ElementTree.Element
XML element containing source data
"""
element = ET.Element("source")
element.set("strength", str(self.strength))
if self.file is not None:

View file

@ -558,7 +558,7 @@ class StatePoint(object):
tally = None
# Iterate over all tallies to find the appropriate one
for tally_id, test_tally in self.tallies.items():
for test_tally in self.tallies.values():
# Determine if Tally has queried name
if name and name != test_tally.name:

View file

@ -24,7 +24,7 @@ class Univariate(object):
pass
@abstractmethod
def to_xml(self):
def to_xml(self, element_name):
return ''
@ -180,7 +180,7 @@ class Maxwell(Univariate):
class Watt(Univariate):
"""Watt fission energy spectrum.
r"""Watt fission energy spectrum.
The Watt fission energy spectrum is characterized by two parameters
:math:`a` and :math:`b` and has density function :math:`p(E) dE = c e^{-E/a}

View file

@ -1,7 +1,8 @@
from collections import Iterable
import numpy as np
import re
import numpy as np
import openmc
from openmc.region import Region
@ -301,7 +302,7 @@ class Summary(object):
# Get the distribcell index
ind = self._f['geometry/cells'][key]['distribcell_index'].value
if ind != 0:
cell.distribcell_index = ind
cell.distribcell_index = ind
# Add the Cell to the global dictionary of all Cells
self.cells[index] = cell
@ -608,7 +609,7 @@ class Summary(object):
"""
for index, material in self.materials.items():
for material in self.materials.values():
if material.id == material_id:
return material
@ -629,7 +630,7 @@ class Summary(object):
"""
for index, surface in self.surfaces.items():
for surface in self.surfaces.values():
if surface.id == surface_id:
return surface
@ -650,7 +651,7 @@ class Summary(object):
"""
for index, cell in self.cells.items():
for cell in self.cells.values():
if cell.id == cell_id:
return cell
@ -671,7 +672,7 @@ class Summary(object):
"""
for index, universe in self.universes.items():
for universe in self.universes.values():
if universe.id == universe_id:
return universe
@ -692,7 +693,7 @@ class Summary(object):
"""
for index, lattice in self.lattices.items():
for lattice in self.lattices.values():
if lattice.id == lattice_id:
return lattice

View file

@ -19,6 +19,7 @@ _BC_TYPES = ['transmission', 'vacuum', 'reflective', 'periodic']
def reset_auto_surface_id():
"""Reset counters for all auto-generated surface IDs"""
global AUTO_SURFACE_ID
AUTO_SURFACE_ID = 10000
@ -1814,18 +1815,20 @@ def make_hexagon_region(edge_length=1., orientation='y'):
right = XPlane(x0=sqrt(3.)/2.*l)
left = XPlane(x0=-sqrt(3.)/2.*l)
c = sqrt(3.)/3.
ur = Plane(A=c, B=1., D=l) # y = -x/sqrt(3) + a
ul = Plane(A=-c, B=1., D=l) # y = x/sqrt(3) + a
lr = Plane(A=-c, B=1., D=-l) # y = x/sqrt(3) - a
ll = Plane(A=c, B=1., D=-l) # y = -x/sqrt(3) - a
return Intersection(-right, +left, -ur, -ul, +lr, +ll)
upper_right = Plane(A=c, B=1., D=l) # y = -x/sqrt(3) + a
upper_left = Plane(A=-c, B=1., D=l) # y = x/sqrt(3) + a
lower_right = Plane(A=-c, B=1., D=-l) # y = x/sqrt(3) - a
lower_left = Plane(A=c, B=1., D=-l) # y = -x/sqrt(3) - a
return Intersection(-right, +left, -upper_right, -upper_left,
+lower_right, +lower_left)
elif orientation == 'x':
top = YPlane(y0=sqrt(3.)/2.*l)
bottom = YPlane(y0=-sqrt(3.)/2.*l)
c = sqrt(3.)
ur = Plane(A=c, B=1., D=c*l) # y = -sqrt(3)*(x - a)
lr = Plane(A=-c, B=1., D=-c*l) # y = sqrt(3)*(x + a)
ll = Plane(A=c, B=1., D=-c*l) # y = -sqrt(3)*(x + a)
ul = Plane(A=-c, B=1., D=c*l) # y = sqrt(3)*(x + a)
return Intersection(-top, +bottom, -ur, +lr, +ll, -ul)
upper_right = Plane(A=c, B=1., D=c*l) # y = -sqrt(3)*(x - a)
lower_right = Plane(A=-c, B=1., D=-c*l) # y = sqrt(3)*(x + a)
lower_left = Plane(A=c, B=1., D=-c*l) # y = -sqrt(3)*(x + a)
upper_left = Plane(A=-c, B=1., D=c*l) # y = sqrt(3)*(x + a)
return Intersection(-top, +bottom, -upper_right, +lower_right,
+lower_left, -upper_left)

View file

@ -1,6 +1,6 @@
from __future__ import division
from collections import Iterable, MutableSequence, defaultdict
from collections import Iterable, MutableSequence
import copy
from functools import partial
import os
@ -13,11 +13,12 @@ from xml.etree import ElementTree as ET
import numpy as np
from openmc import Mesh, Filter, Trigger, Nuclide
from openmc.arithmetic import *
from openmc import Filter, Trigger, Nuclide
from openmc.arithmetic import CrossScore, CrossNuclide, CrossFilter, \
AggregateScore, AggregateNuclide, AggregateFilter
from openmc.filter import _FILTER_TYPES
import openmc.checkvalue as cv
from openmc.clean_xml import *
from openmc.clean_xml import clean_xml_indentation
if sys.version_info[0] >= 3:
basestring = str
@ -41,6 +42,7 @@ _FILTER_CLASSES = (Filter, CrossFilter, AggregateFilter)
def reset_auto_tally_id():
"""Reset counter for auto-generated tally IDs."""
global AUTO_TALLY_ID
AUTO_TALLY_ID = 10000
@ -177,7 +179,7 @@ class Tally(object):
for self_filter in self.filters:
string += '{0: <16}\t\t{1}\t{2}\n'.format('', self_filter.type,
self_filter.bins)
self_filter.bins)
string += '{0: <16}{1}'.format('\tNuclides', '=\t')
@ -386,7 +388,7 @@ class Tally(object):
@estimator.setter
def estimator(self, estimator):
cv.check_value('estimator', estimator,
['analog', 'tracklength', 'collision'])
['analog', 'tracklength', 'collision'])
self._estimator = estimator
@triggers.setter
@ -762,10 +764,7 @@ class Tally(object):
no_nuclides_match = False
# Either all nuclides should match, or none should
if no_nuclides_match or all_nuclides_match:
return True
else:
return False
return no_nuclides_match or all_nuclides_match
def _can_merge_scores(self, other):
"""Determine if another tally's scores can be merged with this one's
@ -802,10 +801,7 @@ class Tally(object):
return False
# Either all scores should match, or none should
if no_scores_match or all_scores_match:
return True
else:
return False
return no_scores_match or all_scores_match
def can_merge(self, other):
"""Determine if another tally can be merged with this one
@ -901,7 +897,7 @@ class Tally(object):
# Search for mergeable filters
for i, filter1 in enumerate(self.filters):
for j, filter2 in enumerate(other.filters):
for filter2 in other.filters:
if filter1 != filter2 and filter1.can_merge(filter2):
other_copy._swap_filters(other_copy.filters[i], filter2)
merged_tally.filters[i] = filter1.merge(filter2)
@ -1058,7 +1054,7 @@ class Tally(object):
for score in self.scores:
scores += '{0} '.format(score)
subelement = ET.SubElement(element, "scores")
subelement = ET.SubElement(element, "scores")
subelement.text = scores.rstrip(' ')
# Tally estimator type
@ -1192,7 +1188,7 @@ class Tally(object):
# If the Summary was linked, then values are Nuclide objects
if isinstance(test_nuclide, Nuclide):
if test_nuclide._name == nuclide:
if test_nuclide.name == nuclide:
nuclide_index = i
break
@ -1557,7 +1553,7 @@ class Tally(object):
# Append each Filter's DataFrame to the overall DataFrame
for self_filter in self.filters:
filter_df = self_filter.get_pandas_dataframe(
data_size, distribcell_paths)
data_size, distribcell_paths)
df = pd.concat([df, filter_df], axis=1)
# Include DataFrame column for nuclides if user requested it
@ -1673,7 +1669,7 @@ class Tally(object):
return data
def export_results(self, filename='tally-results', directory='.',
format='hdf5', append=True):
format='hdf5', append=True):
"""Exports tallly results to an HDF5 or Python pickle binary file.
Parameters
@ -1719,7 +1715,7 @@ class Tally(object):
elif not isinstance(append, bool):
msg = 'Unable to export the results for Tally ID="{0}" since the ' \
'append parameter is not True/False'.format(self.id, append)
'append parameter is not True/False'.format(self.id)
raise ValueError(msg)
# Make directory if it does not exist
@ -1776,7 +1772,7 @@ class Tally(object):
filename = directory + '/' + filename + '.pkl'
if os.path.exists(filename) and append:
tally_results = pickle.load(file(filename, 'rb'))
tally_results = pickle.load(open(filename, 'rb'))
else:
tally_results = {}
@ -1815,7 +1811,7 @@ class Tally(object):
pickle.dump(tally_results, open(filename, 'wb'))
def hybrid_product(self, other, binary_op, filter_product=None,
nuclide_product=None, score_product=None):
nuclide_product=None, score_product=None):
"""Combines filters, scores and nuclides with another tally.
This is a helper method for the tally arithmetic operator overloaded
@ -2451,7 +2447,7 @@ class Tally(object):
new_tally._std_dev = self.std_dev
new_tally.estimator = self.estimator
new_tally.with_summary = self.with_summary
new_tally.num_realization = self.num_realizations
new_tally.num_realizations = self.num_realizations
new_tally.filters = copy.deepcopy(self.filters)
new_tally.nuclides = copy.deepcopy(self.nuclides)
@ -2522,7 +2518,7 @@ class Tally(object):
new_tally._std_dev = self.std_dev
new_tally.estimator = self.estimator
new_tally.with_summary = self.with_summary
new_tally.num_realization = self.num_realizations
new_tally.num_realizations = self.num_realizations
new_tally.filters = copy.deepcopy(self.filters)
new_tally.nuclides = copy.deepcopy(self.nuclides)
@ -2594,7 +2590,7 @@ class Tally(object):
new_tally._std_dev = self.std_dev * np.abs(other)
new_tally.estimator = self.estimator
new_tally.with_summary = self.with_summary
new_tally.num_realization = self.num_realizations
new_tally.num_realizations = self.num_realizations
new_tally.filters = copy.deepcopy(self.filters)
new_tally.nuclides = copy.deepcopy(self.nuclides)
@ -2666,7 +2662,7 @@ class Tally(object):
new_tally._std_dev = self.std_dev * np.abs(1. / other)
new_tally.estimator = self.estimator
new_tally.with_summary = self.with_summary
new_tally.num_realization = self.num_realizations
new_tally.num_realizations = self.num_realizations
new_tally.filters = copy.deepcopy(self.filters)
new_tally.nuclides = copy.deepcopy(self.nuclides)
@ -2742,7 +2738,7 @@ class Tally(object):
new_tally._std_dev = np.abs(new_tally._mean * power * self_rel_err)
new_tally.estimator = self.estimator
new_tally.with_summary = self.with_summary
new_tally.num_realization = self.num_realizations
new_tally.num_realizations = self.num_realizations
new_tally.filters = copy.deepcopy(self.filters)
new_tally.nuclides = copy.deepcopy(self.nuclides)
@ -3149,7 +3145,7 @@ class Tally(object):
return tally_sum
def average(self, scores=[], filter_type=None,
filter_bins=[], nuclides=[], remove_filter=False):
filter_bins=[], nuclides=[], remove_filter=False):
"""Vectorized average of tally data across scores, filter bins and/or
nuclides using tally aggregation.
@ -3577,4 +3573,4 @@ class Tallies(cv.CheckedList):
# Write the XML Tree to the tallies.xml file
tree = ET.ElementTree(self._tallies_file)
tree.write("tallies.xml", xml_declaration=True,
encoding='utf-8', method="xml")
encoding='utf-8', method="xml")

View file

@ -40,10 +40,7 @@ class Trigger(object):
self._scores = []
def __eq__(self, other):
if str(self) == str(other):
return True
else:
return False
return str(self) == str(other)
def __ne__(self, other):
return not self == other
@ -70,7 +67,7 @@ class Trigger(object):
@trigger_type.setter
def trigger_type(self, trigger_type):
cv.check_value('tally trigger type', trigger_type,
['variance', 'std_dev', 'rel_err'])
['variance', 'std_dev', 'rel_err'])
self._trigger_type = trigger_type
@threshold.setter

View file

@ -1,9 +1,7 @@
from collections import OrderedDict, Iterable
from numbers import Integral
from xml.etree import ElementTree as ET
import random
import sys
import warnings
import numpy as np
@ -22,6 +20,7 @@ AUTO_UNIVERSE_ID = 10000
def reset_auto_universe_id():
"""Reset counter for auto-generated universe IDs."""
global AUTO_UNIVERSE_ID
AUTO_UNIVERSE_ID = 10000
@ -256,7 +255,7 @@ class Universe(object):
if obj not in colors:
colors[obj] = (random.random(), random.random(),
random.random(), 1.0)
img[j,i,:] = colors[obj]
img[j, i, :] = colors[obj]
# Display image
plt.imshow(img, extent=(x_min, x_max, y_min, y_max))
@ -282,7 +281,7 @@ class Universe(object):
'a Cell'.format(self._id, cell)
raise ValueError(msg)
cell_id = cell._id
cell_id = cell.id
if cell_id not in self._cells:
self._cells[cell_id] = cell
@ -364,7 +363,7 @@ class Universe(object):
nuclides = OrderedDict()
# Append all Nuclides in each Cell in the Universe to the dictionary
for cell_id, cell in self._cells.items():
for cell in self._cells.values():
nuclides.update(cell.get_all_nuclides())
return nuclides
@ -386,7 +385,7 @@ class Universe(object):
cells.update(self._cells)
# Append all Cells in each Cell in the Universe to the dictionary
for cell_id, cell in self._cells.items():
for cell in self._cells.values():
cells.update(cell.get_all_cells())
return cells
@ -406,7 +405,7 @@ class Universe(object):
# Append all Cells in each Cell in the Universe to the dictionary
cells = self.get_all_cells()
for cell_id, cell in cells.items():
for cell in cells.values():
materials.update(cell.get_all_materials())
return materials
@ -428,7 +427,7 @@ class Universe(object):
universes = OrderedDict()
# Append all Universes containing each Cell to the dictionary
for cell_id, cell in cells.items():
for cell in cells.values():
universes.update(cell.get_all_universes())
return universes

View file

@ -1,7 +1,6 @@
#!/usr/bin/env python
import glob
import os
try:
from setuptools import setup
have_setuptools = True