Merge pull request #1862 from Shimwell/f_strings

Replacing some .formats with F strings
This commit is contained in:
Paul Romano 2021-08-02 22:07:23 -05:00 committed by GitHub
commit c0c0713032
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 213 additions and 234 deletions

View file

@ -360,7 +360,7 @@ class CrossFilter:
right_df = self.right_filter.get_pandas_dataframe(data_size, summary)
left_df = left_df.astype(str)
right_df = right_df.astype(str)
df = '(' + left_df + ' ' + self.binary_op + ' ' + right_df + ')'
df = f'({left_df} {self.binary_op} {right_df})'
return df
@ -405,7 +405,7 @@ class AggregateScore:
def __repr__(self):
string = ', '.join(map(str, self.scores))
string = '{}({})'.format(self.aggregate_op, string)
string = f'{self.aggregate_op}({string})'
return string
@property
@ -476,7 +476,7 @@ class AggregateNuclide:
def __repr__(self):
# Append each nuclide in the aggregate to the string
string = '{}('.format(self.aggregate_op)
string = f'{self.aggregate_op}('
names = [nuclide.name if isinstance(nuclide, openmc.Nuclide)
else str(nuclide) for nuclide in self.nuclides]
string += ', '.join(map(str, names)) + ')'
@ -543,8 +543,7 @@ class AggregateFilter:
def __init__(self, aggregate_filter, bins=None, aggregate_op=None):
self._type = '{}({})'.format(aggregate_op,
aggregate_filter.short_name.lower())
self._type = f'{aggregate_op}({aggregate_filter.short_name.lower()})'
self._bins = None
self._aggregate_filter = None
@ -608,8 +607,8 @@ class AggregateFilter:
@type.setter
def type(self, filter_type):
if filter_type not in _FILTER_TYPES:
msg = 'Unable to set AggregateFilter type to "{}" since it ' \
'is not one of the supported types'.format(filter_type)
msg = f'Unable to set AggregateFilter type to "{filter_type}" ' \
'since it is not one of the supported types'
raise ValueError(msg)
self._type = filter_type
@ -660,8 +659,8 @@ class AggregateFilter:
"""
if filter_bin not in self.bins:
msg = 'Unable to get the bin index for AggregateFilter since ' \
'"{}" is not one of the bins'.format(filter_bin)
msg = ('Unable to get the bin index for AggregateFilter since '
f'"{filter_bin}" is not one of the bins')
raise ValueError(msg)
else:
return self.bins.index(filter_bin)
@ -757,8 +756,7 @@ class AggregateFilter:
"""
if not self.can_merge(other):
msg = 'Unable to merge "{}" with "{}" filters'.format(
self.type, other.type)
msg = f'Unable to merge "{self.type}" with "{other.type}" filters'
raise ValueError(msg)
# Create deep copy of filter to return as merged filter

View file

@ -233,7 +233,7 @@ class Cell(IDManagerMixin):
self._atoms[key] = atom
else:
msg = 'Unrecognized fill_type: {}'.format(self.fill_type)
msg = f'Unrecognized fill_type: {self.fill_type}'
raise ValueError(msg)
return self._atoms
@ -279,8 +279,8 @@ class Cell(IDManagerMixin):
elif not isinstance(fill, (openmc.Material, openmc.Lattice,
openmc.UniverseBase)):
msg = ('Unable to set Cell ID="{0}" to use a non-Material or '
'Universe fill "{1}"'.format(self._id, fill))
msg = (f'Unable to set Cell ID="{self._id}" to use a '
f'non-Material or Universe fill "{fill}"')
raise ValueError(msg)
self._fill = fill
@ -408,10 +408,10 @@ class Cell(IDManagerMixin):
nuclides[name] = (nuclide, density)
else:
raise RuntimeError(
'Volume information is needed to calculate microscopic cross '
'sections for cell {}. This can be done by running a '
'stochastic volume calculation via the '
'openmc.VolumeCalculation object'.format(self.id))
'Volume information is needed to calculate microscopic '
f'cross sections for cell {self.id}. This can be done by '
'running a stochastic volume calculation via the '
'openmc.VolumeCalculation object')
return nuclides

View file

@ -32,16 +32,15 @@ def check_type(name, value, expected_type, expected_iter_type=None, *, none_ok=F
'following types: "{}"'.format(name, value, ', '.join(
[t.__name__ for t in expected_type]))
else:
msg = 'Unable to set "{}" to "{}" which is not of type "{}"'.format(
name, value, expected_type.__name__)
msg = (f'Unable to set "{name}" to "{value}" which is not of type "'
f'{expected_type.__name__}"')
raise TypeError(msg)
if expected_iter_type:
if isinstance(value, np.ndarray):
if not issubclass(value.dtype.type, expected_iter_type):
msg = 'Unable to set "{}" to "{}" since each item must be ' \
'of type "{}"'.format(name, value,
expected_iter_type.__name__)
msg = (f'Unable to set "{name}" to "{value}" since each item '
f'must be of type "{expected_iter_type.__name__}"')
raise TypeError(msg)
else:
return
@ -54,9 +53,8 @@ def check_type(name, value, expected_type, expected_iter_type=None, *, none_ok=F
name, value, ', '.join([t.__name__ for t in
expected_iter_type]))
else:
msg = 'Unable to set "{}" to "{}" since each item must be ' \
'of type "{}"'.format(name, value,
expected_iter_type.__name__)
msg = (f'Unable to set "{name}" to "{value}" since each '
f'item must be of type "{expected_iter_type.__name__}"')
raise TypeError(msg)
@ -106,8 +104,8 @@ def check_iterable_type(name, value, expected_type, min_depth=1, max_depth=1):
if isinstance(current_item, expected_type):
# Is this deep enough?
if len(tree) < min_depth:
msg = 'Error setting "{0}": The item at {1} does not meet the '\
'minimum depth of {2}'.format(name, ind_str, min_depth)
msg = (f'Error setting "{name}": The item at {ind_str} does not '
f'meet the minimum depth of {min_depth}')
raise TypeError(msg)
# This item is okay. Move on to the next item.
@ -123,17 +121,16 @@ def check_iterable_type(name, value, expected_type, min_depth=1, max_depth=1):
# But first, have we exceeded the max depth?
if len(tree) > max_depth:
msg = 'Error setting {0}: Found an iterable at {1}, items '\
'in that iterable exceed the maximum depth of {2}' \
.format(name, ind_str, max_depth)
msg = (f'Error setting {name}: Found an iterable at '
f'{ind_str}, items in that iterable exceed the '
f'maximum depth of {max_depth}')
raise TypeError(msg)
else:
# This item is completely unexpected.
msg = "Error setting {0}: Items must be of type '{1}', but " \
"item at {2} is of type '{3}'"\
.format(name, expected_type.__name__, ind_str,
type(current_item).__name__)
msg = (f'Error setting {name}: Items must be of type '
f'"{expected_type.__name__}", but item at {ind_str} is '
f'of type "{type(current_item).__name__}"')
raise TypeError(msg)
@ -156,17 +153,16 @@ def check_length(name, value, length_min, length_max=None):
if length_max is None:
if len(value) < length_min:
msg = 'Unable to set "{}" to "{}" since it must be at least of ' \
'length "{}"'.format(name, value, length_min)
msg = (f'Unable to set "{name}" to "{value}" since it must be at '
f'least of length "{length_min}"')
raise ValueError(msg)
elif not length_min <= len(value) <= length_max:
if length_min == length_max:
msg = 'Unable to set "{}" to "{}" since it must be of ' \
'length "{}"'.format(name, value, length_min)
msg = (f'Unable to set "{name}" to "{value}" since it must be of '
f'length "{length_min}"')
else:
msg = 'Unable to set "{}" to "{}" since it must have length ' \
'between "{}" and "{}"'.format(name, value, length_min,
length_max)
msg = (f'Unable to set "{name}" to "{value}" since it must have '
f'length between "{length_min}" and "{length_max}"')
raise ValueError(msg)
@ -185,8 +181,8 @@ def check_value(name, value, accepted_values):
"""
if value not in accepted_values:
msg = 'Unable to set "{0}" to "{1}" since it is not in "{2}"'.format(
name, value, accepted_values)
msg = (f'Unable to set "{name}" to "{value}" since it is not in '
f'"{accepted_values}"')
raise ValueError(msg)
@ -208,13 +204,13 @@ def check_less_than(name, value, maximum, equality=False):
if equality:
if value > maximum:
msg = 'Unable to set "{0}" to "{1}" since it is greater than ' \
'"{2}"'.format(name, value, maximum)
msg = (f'Unable to set "{name}" to "{value}" since it is greater '
f'than "{maximum}"')
raise ValueError(msg)
else:
if value >= maximum:
msg = 'Unable to set "{0}" to "{1}" since it is greater than ' \
'or equal to "{2}"'.format(name, value, maximum)
msg = (f'Unable to set "{name}" to "{value}" since it is greater '
f'than or equal to "{maximum}"')
raise ValueError(msg)
@ -236,13 +232,13 @@ def check_greater_than(name, value, minimum, equality=False):
if equality:
if value < minimum:
msg = 'Unable to set "{0}" to "{1}" since it is less than ' \
'"{2}"'.format(name, value, minimum)
msg = (f'Unable to set "{name}" to "{value}" since it is less than '
f'"{minimum}"')
raise ValueError(msg)
else:
if value <= minimum:
msg = 'Unable to set "{0}" to "{1}" since it is less than ' \
'or equal to "{2}"'.format(name, value, minimum)
msg = (f'Unable to set "{name}" to "{value}" since it is less than '
f'or equal to "{minimum}"')
raise ValueError(msg)
@ -265,8 +261,7 @@ def check_filetype_version(obj, expected_type, expected_version):
# Check filetype
if this_filetype != expected_type:
raise IOError('{} is not a {} file.'.format(
obj.filename, expected_type))
raise IOError(f'{obj.filename} is not a {expected_type} file.')
# Check version
if this_version[0] != expected_version:
@ -276,9 +271,9 @@ def check_filetype_version(obj, expected_type, expected_version):
'.'.join(str(v) for v in this_version),
expected_version))
except AttributeError:
raise IOError('Could not read {} file. This most likely means the '
'file was produced by a different version of OpenMC than '
'the one you are using.'.format(obj.filename))
raise IOError(f'Could not read {obj.filename} file. This most likely '
'means the file was produced by a different version of '
'OpenMC than the one you are using.')
class CheckedList(list):

View file

@ -251,8 +251,8 @@ class CMFDMesh:
def _display_mesh_warning(self, mesh_type, variable_label):
if self._mesh_type != mesh_type:
warn_msg = 'Setting {} if mesh type is not set to {} ' \
'will have no effect'.format(variable_label, mesh_type)
warn_msg = (f'Setting {variable_label} if mesh type is not set to '
f'{mesh_type} will have no effect')
warnings.warn(warn_msg, RuntimeWarning)
@ -906,7 +906,7 @@ class CMFDRun:
if filename is None:
batch_str_len = len(str(openmc.lib.settings.get_batches()))
batch_str = str(openmc.lib.current_batch()).zfill(batch_str_len)
filename = 'statepoint.{}.h5'.format(batch_str)
filename = f'statepoint.{batch_str}.h5'
# Call C API statepoint_write to save source distribution with CMFD
# feedback

View file

@ -162,10 +162,9 @@ class Element(str):
abundances[self + '0'] = 1.0
elif len(mutual_nuclides) == 0:
msg = ('Unable to expand element {} because the cross '
msg = (f'Unable to expand element {self} because the cross '
'section library provided does not contain any of '
'the natural isotopes for that element.'
.format(self))
'the natural isotopes for that element.')
raise ValueError(msg)
# If some naturally occurring isotopes are in the library, add them.
@ -205,7 +204,7 @@ class Element(str):
# Check that the element is Uranium
if self.name != 'U':
msg = ('Enrichment procedure for Uranium was requested, '
'but the isotope is {} not U'.format(self))
f'but the isotope is {self} not U')
raise ValueError(msg)
# Check that enrichment_type is not 'ao'
@ -243,9 +242,8 @@ class Element(str):
# Check if it is two-isotope mixture
if len(abundances) != 2:
msg = ('Element {} does not consist of two naturally-occurring '
'isotopes. Please enter isotopic abundances manually.'
.format(self))
msg = (f'Element {self} does not consist of two naturally-occurring '
'isotopes. Please enter isotopic abundances manually.')
raise ValueError(msg)
# Check if the target nuclide is present in the mixture

View file

@ -98,9 +98,9 @@ def plot_inline(plots, openmc_exec='openmc', cwd='.', convert_exec='convert'):
if plots is not None:
for p in plots:
if p.filename is not None:
ppm_file = '{}.ppm'.format(p.filename)
ppm_file = f'{p.filename}.ppm'
else:
ppm_file = 'plot_{}.ppm'.format(p.id)
ppm_file = f'plot_{p.id}.ppm'
png_file = ppm_file.replace('.ppm', '.png')
subprocess.check_call([convert_exec, ppm_file, png_file])
images.append(Image(png_file))

View file

@ -266,8 +266,7 @@ class Filter(IDManagerMixin, metaclass=FilterMeta):
"""
if not self.can_merge(other):
msg = 'Unable to merge "{0}" with "{1}" '.format(
type(self), type(other))
msg = f'Unable to merge "{type(self)}" with "{type(other)}"'
raise ValueError(msg)
# Merge unique filter bins
@ -326,8 +325,8 @@ class Filter(IDManagerMixin, metaclass=FilterMeta):
"""
if filter_bin not in self.bins:
msg = 'Unable to get the bin index for Filter since "{0}" ' \
'is not one of the bins'.format(filter_bin)
msg = ('Unable to get the bin index for Filter since '
f'"{filter_bin}" is not one of the bins')
raise ValueError(msg)
if isinstance(self.bins, np.ndarray):
@ -833,7 +832,7 @@ class MeshFilter(Filter):
filter_dict = {}
# Append mesh ID as outermost index of multi-index
mesh_key = 'mesh {}'.format(self.mesh.id)
mesh_key = f'mesh {self.mesh.id}'
# Find mesh dimensions - use 3D indices for simplicity
n_dim = len(self.mesh.dimension)
@ -955,7 +954,7 @@ class MeshSurfaceFilter(MeshFilter):
filter_dict = {}
# Append mesh ID as outermost index of multi-index
mesh_key = 'mesh {}'.format(self.mesh.id)
mesh_key = f'mesh {self.mesh.id}'
# Find mesh dimensions - use 3D indices for simplicity
n_surfs = 4 * len(self.mesh.dimension)
@ -1106,14 +1105,14 @@ class RealFilter(Filter):
# Make sure that each tuple has values that are increasing
if v1 < v0:
raise ValueError('Values {} and {} appear to be out of order'
.format(v0, v1))
raise ValueError(f'Values {v0} and {v1} appear to be out of '
'order')
for pair0, pair1 in zip(bins[:-1], bins[1:]):
# Successive pairs should be ordered
if pair1[1] < pair0[1]:
raise ValueError('Values {} and {} appear to be out of order'
.format(pair1[1], pair0[1]))
raise ValueError(f'Values {pair1[1]} and {pair0[1]} appear to '
'be out of order')
def can_merge(self, other):
if type(self) is not type(other):
@ -1130,8 +1129,7 @@ class RealFilter(Filter):
def merge(self, other):
if not self.can_merge(other):
msg = 'Unable to merge "{0}" with "{1}" ' \
'filters'.format(type(self), type(other))
msg = f'Unable to merge "{type(self)}" with "{type(other)}" filters'
raise ValueError(msg)
# Merge unique filter bins
@ -1169,8 +1167,8 @@ class RealFilter(Filter):
def get_bin_index(self, filter_bin):
i = np.where(self.bins[:, 1] == filter_bin[1])[0]
if len(i) == 0:
msg = 'Unable to get the bin index for Filter since "{0}" ' \
'is not one of the bins'.format(filter_bin)
msg = (f'Unable to get the bin index for Filter since '
'"{filter_bin}" is not one of the bins')
raise ValueError(msg)
else:
return i[0]
@ -1216,7 +1214,7 @@ class RealFilter(Filter):
# Add the new energy columns to the DataFrame.
if hasattr(self, 'units'):
units = ' [{}]'.format(self.units)
units = f' [{self.units}]'
else:
units = ''
@ -1273,8 +1271,8 @@ class EnergyFilter(RealFilter):
if min_delta < 1E-3:
return deltas.argmin()
else:
msg = 'Unable to get the bin index for Filter since "{0}" ' \
'is not one of the bins'.format(filter_bin)
msg = ('Unable to get the bin index for Filter since '
f'"{filter_bin}" is not one of the bins')
raise ValueError(msg)
def check_bins(self, bins):
@ -1416,8 +1414,8 @@ class DistribcellFilter(Filter):
# Make sure there is only 1 bin.
if not len(bins) == 1:
msg = 'Unable to add bins "{0}" to a DistribcellFilter since ' \
'only a single distribcell can be used per tally'.format(bins)
msg = (f'Unable to add bins "{bins}" to a DistribcellFilter since '
'only a single distribcell can be used per tally')
raise ValueError(msg)
# Check the type and extract the id, if necessary.
@ -1508,7 +1506,7 @@ class DistribcellFilter(Filter):
num_levels = len(paths[0])
for i_level in range(num_levels):
# Use level key as first index in Pandas Multi-index column
level_key = 'level {}'.format(i_level + 1)
level_key = f'level {i_level + 1}'
# Create a dictionary for this level for Pandas Multi-index
level_dict = OrderedDict()

View file

@ -85,7 +85,7 @@ class LegendreFilter(ExpansionFilter):
@ExpansionFilter.order.setter
def order(self, order):
ExpansionFilter.order.__set__(self, order)
self.bins = ['P{}'.format(i) for i in range(order + 1)]
self.bins = [f'P{i}' for i in range(order + 1)]
@classmethod
def from_hdf5(cls, group, **kwargs):
@ -164,7 +164,7 @@ class SpatialLegendreFilter(ExpansionFilter):
@ExpansionFilter.order.setter
def order(self, order):
ExpansionFilter.order.__set__(self, order)
self.bins = ['P{}'.format(i) for i in range(order + 1)]
self.bins = [f'P{i}' for i in range(order + 1)]
@property
def axis(self):
@ -275,7 +275,7 @@ class SphericalHarmonicsFilter(ExpansionFilter):
@ExpansionFilter.order.setter
def order(self, order):
ExpansionFilter.order.__set__(self, order)
self.bins = ['Y{},{}'.format(n, m)
self.bins = [f'Y{n},{m}'
for n in range(order + 1)
for m in range(-n, n + 1)]
@ -401,7 +401,7 @@ class ZernikeFilter(ExpansionFilter):
@ExpansionFilter.order.setter
def order(self, order):
ExpansionFilter.order.__set__(self, order)
self.bins = ['Z{},{}'.format(n, m)
self.bins = [f'Z{n},{m}'
for n in range(order + 1)
for m in range(-n, n + 1, 2)]
@ -522,4 +522,4 @@ class ZernikeRadialFilter(ZernikeFilter):
@ExpansionFilter.order.setter
def order(self, order):
ExpansionFilter.order.__set__(self, order)
self.bins = ['Z{},0'.format(n) for n in range(0, order+1, 2)]
self.bins = [f'Z{n},0' for n in range(0, order+1, 2)]

View file

@ -424,7 +424,7 @@ class Geometry:
domains = []
func = getattr(self, 'get_all_{}s'.format(domain_type))
func = getattr(self, f'get_all_{domain_type}s')
for domain in func().values():
domain_name = domain.name if case_sensitive else domain.name.lower()
if domain_name == name:

View file

@ -106,7 +106,7 @@ class Lattice(IDManagerMixin, ABC):
elif lattice_type == 'hexagonal':
return openmc.HexLattice.from_hdf5(group, universes)
else:
raise ValueError('Unkown lattice type: {}'.format(lattice_type))
raise ValueError(f'Unkown lattice type: {lattice_type}')
def get_unique_universes(self):
"""Determine all unique universes in the lattice
@ -416,7 +416,7 @@ class RectLattice(Lattice):
# Lattice nested Universe IDs
for i, universe in enumerate(np.ravel(self._universes)):
string += '{} '.format(universe._id)
string += f'{universe._id} '
# Add a newline character every time we reach end of row of cells
if (i + 1) % self.shape[0] == 0:
@ -865,7 +865,7 @@ class RectLattice(Lattice):
# Export the Lattice outer Universe (if specified)
if self._outer is not None:
outer = ET.SubElement(lattice_subelement, "outer")
outer.text = '{0}'.format(self._outer._id)
outer.text = str(self._outer._id)
self._outer.create_xml_subelement(xml_element, memo)
# Export Lattice cell dimensions
@ -887,7 +887,7 @@ class RectLattice(Lattice):
universe = self._universes[z][y][x]
# Append Universe ID to the Lattice XML subelement
universe_ids += '{0} '.format(universe._id)
universe_ids += f'{universe._id} '
# Create XML subelement for this Universe
universe.create_xml_subelement(xml_element, memo)
@ -905,7 +905,7 @@ class RectLattice(Lattice):
universe = self._universes[y][x]
# Append Universe ID to Lattice XML subelement
universe_ids += '{0} '.format(universe._id)
universe_ids += f'{universe._id} '
# Create XML subelement for this Universe
universe.create_xml_subelement(xml_element, memo)
@ -1432,7 +1432,7 @@ class HexLattice(Lattice):
# Export the Lattice outer Universe (if specified)
if self._outer is not None:
outer = ET.SubElement(lattice_subelement, "outer")
outer.text = '{0}'.format(self._outer._id)
outer.text = str(self._outer._id)
self._outer.create_xml_subelement(xml_element, memo)
lattice_subelement.set("n_rings", str(self._num_rings))

View file

@ -122,7 +122,7 @@ class Material(IDManagerMixin):
string += '{: <16}=\t{}\n'.format('\tTemperature', self._temperature)
string += '{: <16}=\t{}'.format('\tDensity', self._density)
string += ' [{}]\n'.format(self._density_units)
string += f' [{self._density_units}]\n'
string += '{: <16}\n'.format('\tS(a,b) Tables')
@ -208,7 +208,7 @@ class Material(IDManagerMixin):
@name.setter
def name(self, name):
if name is not None:
cv.check_type('name for Material ID="{}"'.format(self._id),
cv.check_type(f'name for Material ID="{self._id}"',
name, str)
self._name = name
else:
@ -216,13 +216,13 @@ class Material(IDManagerMixin):
@temperature.setter
def temperature(self, temperature):
cv.check_type('Temperature for Material ID="{}"'.format(self._id),
cv.check_type(f'Temperature for Material ID="{self._id}"',
temperature, (Real, type(None)))
self._temperature = temperature
@depletable.setter
def depletable(self, depletable):
cv.check_type('Depletable flag for Material ID="{}"'.format(self.id),
cv.check_type(f'Depletable flag for Material ID="{self._id}"',
depletable, bool)
self._depletable = depletable

View file

@ -47,8 +47,7 @@ class MeshBase(IDManagerMixin, ABC):
@name.setter
def name(self, name):
if name is not None:
cv.check_type('name for mesh ID="{0}"'.format(self._id),
name, str)
cv.check_type(f'name for mesh ID="{self._id}"', name, str)
self._name = name
else:
self._name = ''

View file

@ -2368,8 +2368,8 @@ class MGXSLibrary:
"""
if not isinstance(xsdata, XSdata):
msg = 'Unable to add a non-XSdata "{0}" to the ' \
'MGXSLibrary instance'.format(xsdata)
msg = f'Unable to add a non-XSdata "{xsdata}" to the ' \
'MGXSLibrary instance'
raise ValueError(msg)
if xsdata.energy_groups != self._energy_groups:
@ -2404,8 +2404,8 @@ class MGXSLibrary:
"""
if not isinstance(xsdata, XSdata):
msg = 'Unable to remove a non-XSdata "{0}" from the ' \
'MGXSLibrary instance'.format(xsdata)
msg = f'Unable to remove a non-XSdata "{xsdata}" from the ' \
'MGXSLibrary instance'
raise ValueError(msg)
self._xsdatas.remove(xsdata)

View file

@ -60,11 +60,10 @@ class IDManagerMixin:
cls.used_ids.add(cls.next_id)
else:
name = cls.__name__
cv.check_type('{} ID'.format(name), uid, Integral)
cv.check_greater_than('{} ID'.format(name), uid, 0, equality=True)
cv.check_type(f'{name} ID', uid, Integral)
cv.check_greater_than(f'{name} ID', uid, 0, equality=True)
if uid in cls.used_ids:
msg = 'Another {} instance already exists with id={}.'.format(
name, uid)
msg = f'Another {name} instance already exists with id={uid}.'
warn(msg, IDWarning)
else:
cls.used_ids.add(uid)

View file

@ -26,8 +26,8 @@ class Nuclide(str):
if name.endswith('m'):
name = name[:-1] + '_m1'
msg = 'OpenMC nuclides follow the GND naming convention. Nuclide ' \
'"{}" is being renamed as "{}".'.format(orig_name, name)
msg = ('OpenMC nuclides follow the GND naming convention. '
f'Nuclide "{orig_name}" is being renamed as "{name}".')
warnings.warn(msg)
return super().__new__(cls, name)

View file

@ -193,9 +193,9 @@ def get_openmoc_surface(openmc_surface):
openmoc_surface = openmoc.ZCylinder(x0, y0, R, surface_id, name)
else:
msg = 'Unable to create an OpenMOC Surface from an OpenMC ' \
'Surface of type "{}" since it is not a compatible ' \
'Surface type in OpenMOC'.format(type(openmc_surface))
msg = ('Unable to create an OpenMOC Surface from an OpenMC Surface of '
f'type "{type(openmc_surface)}" since it is not a compatible '
'Surface type in OpenMOC')
raise ValueError(msg)
# Set the boundary condition for this Surface

View file

@ -379,7 +379,7 @@ class Plot(IDManagerMixin):
@show_overlaps.setter
def show_overlaps(self, show_overlaps):
cv.check_type('Show overlaps flag for Plot ID="{}"'.format(self.id),
cv.check_type(f'Show overlaps flag for Plot ID="{self.id}"',
show_overlaps, bool)
self._show_overlaps = show_overlaps
@ -398,8 +398,8 @@ class Plot(IDManagerMixin):
def meshlines(self, meshlines):
cv.check_type('plot meshlines', meshlines, dict)
if 'type' not in meshlines:
msg = 'Unable to set the meshlines to "{}" which ' \
'does not have a "type" key'.format(meshlines)
msg = f'Unable to set the meshlines to "{meshlines}" which ' \
'does not have a "type" key'
raise ValueError(msg)
elif meshlines['type'] not in ['tally', 'entropy', 'ufs', 'cmfd']:
@ -427,7 +427,7 @@ class Plot(IDManagerMixin):
cv.check_type(err_string, color, Iterable)
if isinstance(color, str):
if color.lower() not in _SVG_COLORS:
raise ValueError("'{}' is not a valid color.".format(color))
raise ValueError(f"'{color}' is not a valid color.")
else:
cv.check_length(err_string, color, 3)
for rgb in color:
@ -495,7 +495,7 @@ class Plot(IDManagerMixin):
if np.any(np.isinf((lower_left, upper_right))):
raise ValueError('The geometry does not appear to be bounded '
'in the {} plane.'.format(basis))
f'in the {basis} plane.')
plot = cls()
plot.origin = np.insert((lower_left + upper_right)/2,
@ -568,7 +568,7 @@ class Plot(IDManagerMixin):
# Get a background (R,G,B) tuple to apply in alpha compositing
if isinstance(background, str):
if background.lower() not in _SVG_COLORS:
raise ValueError("'{}' is not a valid color.".format(background))
raise ValueError(f"'{background}' is not a valid color.")
background = _SVG_COLORS[background.lower()]
# Generate a color scheme
@ -706,9 +706,9 @@ class Plot(IDManagerMixin):
# Convert to .png
if self.filename is not None:
ppm_file = '{}.ppm'.format(self.filename)
ppm_file = f'{self.filename}.ppm'
else:
ppm_file = 'plot_{}.ppm'.format(self.id)
ppm_file = f'plot_{self.id}.ppm'
png_file = ppm_file.replace('.ppm', '.png')
subprocess.check_call([convert_exec, ppm_file, png_file])

View file

@ -335,7 +335,7 @@ def _calculate_cexs_nuclide(this, types, temperature=294., sab_name=None,
library = openmc.data.DataLibrary.from_xml(cross_sections)
# Convert temperature to format needed for access in the library
strT = "{}K".format(int(round(temperature)))
strT = f"{int(round(temperature))}K"
T = temperature
# Now we can create the data sets to be plotted
@ -828,8 +828,7 @@ def _calculate_mgxs_nuc_macro(this, types, library, orders=None,
if order < shape[1]:
data[i, :] = temp_data[:, order]
else:
raise ValueError("{} not present in provided MGXS "
"library".format(this))
raise ValueError(f"{this} not present in provided MGXS library")
return data

View file

@ -132,8 +132,8 @@ class Region(ABC):
else:
# Check for invalid characters
if expression[i] not in '-+0123456789':
raise SyntaxError("Invalid character '{}' in expression"
.format(expression[i]))
raise SyntaxError(f"Invalid character '{expression[i]}' in "
"expression")
# If we haven't yet reached the start of a word, start one
if i_start < 0:

View file

@ -485,13 +485,13 @@ class Settings:
@keff_trigger.setter
def keff_trigger(self, keff_trigger):
if not isinstance(keff_trigger, dict):
msg = 'Unable to set a trigger on keff from "{0}" which ' \
'is not a Python dictionary'.format(keff_trigger)
msg = f'Unable to set a trigger on keff from "{keff_trigger}" ' \
'which is not a Python dictionary'
raise ValueError(msg)
elif 'type' not in keff_trigger:
msg = 'Unable to set a trigger on keff from "{0}" which ' \
'does not have a "type" key'.format(keff_trigger)
msg = f'Unable to set a trigger on keff from "{keff_trigger}" ' \
'which does not have a "type" key'
raise ValueError(msg)
elif keff_trigger['type'] not in ['variance', 'std_dev', 'rel_err']:
@ -500,8 +500,8 @@ class Settings:
raise ValueError(msg)
elif 'threshold' not in keff_trigger:
msg = 'Unable to set a trigger on keff from "{0}" which ' \
'does not have a "threshold" key'.format(keff_trigger)
msg = f'Unable to set a trigger on keff from "{keff_trigger}" ' \
'which does not have a "threshold" key'
raise ValueError(msg)
elif not isinstance(keff_trigger['threshold'], Real):
@ -537,7 +537,7 @@ class Settings:
for key, value in output.items():
cv.check_value('output key', key, ('summary', 'tallies', 'path'))
if key in ('summary', 'tallies'):
cv.check_type("output['{}']".format(key), value, bool)
cv.check_type(f"output['{key}']", value, bool)
else:
cv.check_type("output['path']", value, str)
self._output = output
@ -564,8 +564,8 @@ class Settings:
elif key == 'overwrite':
cv.check_type('sourcepoint overwrite', value, bool)
else:
raise ValueError("Unknown key '{}' encountered when setting "
"sourcepoint options.".format(key))
raise ValueError(f"Unknown key '{key}' encountered when "
"setting sourcepoint options.")
self._sourcepoint = sourcepoint
@statepoint.setter
@ -577,8 +577,8 @@ class Settings:
for batch in value:
cv.check_greater_than('statepoint batch', batch, 0)
else:
raise ValueError("Unknown key '{}' encountered when setting "
"statepoint options.".format(key))
raise ValueError(f"Unknown key '{key}' encountered when "
"setting statepoint options.")
self._statepoint = statepoint
@surf_source_read.setter
@ -644,8 +644,8 @@ class Settings:
@cutoff.setter
def cutoff(self, cutoff):
if not isinstance(cutoff, Mapping):
msg = 'Unable to set cutoff from "{0}" which is not a '\
' Python dictionary'.format(cutoff)
msg = f'Unable to set cutoff from "{cutoff}" which is not a '\
'Python dictionary'
raise ValueError(msg)
for key in cutoff:
if key == 'weight':
@ -660,8 +660,8 @@ class Settings:
cv.check_type('energy cutoff', cutoff[key], Real)
cv.check_greater_than('energy cutoff', cutoff[key], 0.0)
else:
msg = 'Unable to set cutoff to "{0}" which is unsupported by '\
'OpenMC'.format(key)
msg = f'Unable to set cutoff to "{key}" which is unsupported ' \
'by OpenMC'
self._cutoff = cutoff
@ -742,8 +742,8 @@ class Settings:
def track(self, track):
cv.check_type('track', track, Iterable, Integral)
if len(track) % 3 != 0:
msg = 'Unable to set the track to "{0}" since its length is ' \
'not a multiple of 3'.format(track)
msg = f'Unable to set the track to "{track}" since its length is ' \
'not a multiple of 3'
raise ValueError(msg)
for t in zip(track[::3], track[1::3], track[2::3]):
cv.check_greater_than('track batch', t[0], 0)
@ -995,7 +995,7 @@ class Settings:
self.entropy_mesh.dimension = (n,)*d
# See if a <mesh> element already exists -- if not, add it
path = "./mesh[@id='{}']".format(self.entropy_mesh.id)
path = f"./mesh[@id='{self.entropy_mesh.id}']"
if root.find(path) is None:
root.append(self.entropy_mesh.to_xml_element())
@ -1033,8 +1033,7 @@ class Settings:
def _create_temperature_subelements(self, root):
if self.temperature:
for key, value in sorted(self.temperature.items()):
element = ET.SubElement(root,
"temperature_{}".format(key))
element = ET.SubElement(root, f"temperature_{key}")
if isinstance(value, bool):
element.text = str(value).lower()
elif key == 'range':
@ -1055,7 +1054,7 @@ class Settings:
def _create_ufs_mesh_subelement(self, root):
if self.ufs_mesh is not None:
# See if a <mesh> element already exists -- if not, add it
path = "./mesh[@id='{}']".format(self.ufs_mesh.id)
path = f"./mesh[@id='{self.ufs_mesh.id}']"
if root.find(path) is None:
root.append(self.ufs_mesh.to_xml_element())
@ -1274,7 +1273,7 @@ class Settings:
def _entropy_mesh_from_xml_element(self, root):
text = get_text(root, 'entropy_mesh')
if text is not None:
path = "./mesh[@id='{}']".format(int(text))
path = f"./mesh[@id='{int(text)}']"
elem = root.find(path)
if elem is not None:
self.entropy_mesh = RegularMesh.from_xml_element(elem)
@ -1339,7 +1338,7 @@ class Settings:
def _ufs_mesh_from_xml_element(self, root):
text = get_text(root, 'ufs_mesh')
if text is not None:
path = "./mesh[@id='{}']".format(int(text))
path = f"./mesh[@id='{int(text)}']"
elem = root.find(path)
if elem is not None:
self.ufs_mesh = RegularMesh.from_xml_element(elem)

View file

@ -373,7 +373,7 @@ class StatePoint:
# Iterate over all tallies
for tally_id in tally_ids:
group = tallies_group['tally {}'.format(tally_id)]
group = tallies_group[f'tally {tally_id}']
# Check if tally is internal and therefore has no data
if group.attrs.get("internal"):
@ -401,8 +401,7 @@ class StatePoint:
filter_ids = group['filters'][()]
filters_group = self._f['tallies/filters']
for filter_id in filter_ids:
filter_group = filters_group['filter {}'.format(
filter_id)]
filter_group = filters_group[f'filter {filter_id}']
new_filter = openmc.Filter.from_hdf5(
filter_group, meshes=self.meshes)
tally.filters.append(new_filter)
@ -443,8 +442,7 @@ class StatePoint:
# Create each derivative object and add it to the dictionary.
for d_id in deriv_ids:
group = self._f['tallies/derivatives/derivative {}'
.format(d_id)]
group = self._f[f'tallies/derivatives/derivative {d_id}']
deriv = openmc.TallyDerivative(derivative_id=d_id)
deriv.variable = group['independent variable'][()].decode()
if deriv.variable == 'density':
@ -657,8 +655,8 @@ class StatePoint:
return
if not isinstance(summary, openmc.Summary):
msg = 'Unable to link statepoint with "{0}" which ' \
'is not a Summary object'.format(summary)
msg = f'Unable to link statepoint with "{summary}" which is not a' \
'Summary object'
raise ValueError(msg)
cells = summary.geometry.get_all_cells()

View file

@ -52,7 +52,7 @@ class SurfaceCoefficient:
def __set__(self, instance, value):
if isinstance(self.value, Real):
raise AttributeError('This coefficient is read-only')
check_type('{} coefficient'.format(self.value), value, Real)
check_type(f'{self.value} coefficient', value, Real)
instance._coefficients[self.value] = value

View file

@ -202,7 +202,7 @@ class Tally(IDManagerMixin):
# Open the HDF5 statepoint file
with h5py.File(self._sp_filename, 'r') as f:
# Extract Tally data from the file
data = f['tallies/tally {}/results'.format(self.id)]
data = f[f'tallies/tally {self.id}/results']
sum_ = data[:, :, 0]
sum_sq = data[:, :, 1]
@ -336,9 +336,9 @@ class Tally(IDManagerMixin):
visited_filters = set()
for f in filters:
if f in visited_filters:
msg = 'Unable to add a duplicate filter "{}" to Tally ID="{}" ' \
'since duplicate filters are not supported in the OpenMC ' \
'Python API'.format(f, self.id)
msg = (f'Unable to add a duplicate filter "{f}" to Tally '
f'ID="{self.id}" since duplicate filters are not '
'supported in the OpenMC Python API')
raise ValueError(msg)
visited_filters.add(f)
@ -352,9 +352,9 @@ class Tally(IDManagerMixin):
visited_nuclides = set()
for nuc in nuclides:
if nuc in visited_nuclides:
msg = 'Unable to add a duplicate nuclide "{}" to Tally ID="{}" ' \
'since duplicate nuclides are not supported in the OpenMC ' \
'Python API'.format(nuc, self.id)
msg = (f'Unable to add a duplicate nuclide "{nuc}" to Tally ID='
f'"{self.id}" since duplicate nuclides are not supported '
'in the OpenMC Python API')
raise ValueError(msg)
visited_nuclides.add(nuc)
@ -369,9 +369,9 @@ class Tally(IDManagerMixin):
for i, score in enumerate(scores):
# If the score is already in the Tally, raise an error
if score in visited_scores:
msg = 'Unable to add a duplicate score "{}" to Tally ID="{}" ' \
'since duplicate scores are not supported in the OpenMC ' \
'Python API'.format(score, self.id)
msg = (f'Unable to add a duplicate score "{score}" to Tally '
f'ID="{self.id}" since duplicate scores are not '
'supported in the OpenMC Python API')
raise ValueError(msg)
visited_scores.add(score)
@ -467,8 +467,8 @@ class Tally(IDManagerMixin):
"""
if score not in self.scores:
msg = 'Unable to remove score "{}" from Tally ID="{}" since ' \
'the Tally does not contain this score'.format(score, self.id)
msg = f'Unable to remove score "{score}" from Tally ' \
f'ID="{self.id}" since the Tally does not contain this score'
raise ValueError(msg)
self._scores.remove(score)
@ -484,8 +484,8 @@ class Tally(IDManagerMixin):
"""
if old_filter not in self.filters:
msg = 'Unable to remove filter "{}" from Tally ID="{}" since the ' \
'Tally does not contain this filter'.format(old_filter, self.id)
msg = f'Unable to remove filter "{old_filter}" from Tally ' \
f'ID="{self.id}" since the Tally does not contain this filter'
raise ValueError(msg)
self._filters.remove(old_filter)
@ -501,8 +501,8 @@ class Tally(IDManagerMixin):
"""
if nuclide not in self.nuclides:
msg = 'Unable to remove nuclide "{}" from Tally ID="{}" since the ' \
'Tally does not contain this nuclide'.format(nuclide, self.id)
msg = f'Unable to remove nuclide "{nuclide}" from Tally ' \
f'ID="{self.id}" since the Tally does not contain this nuclide'
raise ValueError(msg)
self._nuclides.remove(nuclide)
@ -684,8 +684,7 @@ class Tally(IDManagerMixin):
"""
if not self.can_merge(other):
msg = 'Unable to merge tally ID="{}" with "{}"'.format(
other.id, self.id)
msg = f'Unable to merge tally ID="{other.id}" with "{self.id}"'
raise ValueError(msg)
# Create deep copy of tally to return as merged tally
@ -841,14 +840,14 @@ class Tally(IDManagerMixin):
# Scores
if len(self.scores) == 0:
msg = 'Unable to get XML for Tally ID="{}" since it does not ' \
'contain any scores'.format(self.id)
msg = f'Unable to get XML for Tally ID="{self.id}" since it does ' \
'not contain any scores'
raise ValueError(msg)
else:
scores = ''
for score in self.scores:
scores += '{} '.format(score)
scores += f'{score} '
subelement = ET.SubElement(element, "scores")
subelement.text = scores.rstrip(' ')
@ -922,8 +921,8 @@ class Tally(IDManagerMixin):
return test_filter
# If we did not find the Filter, throw an Exception
msg = 'Unable to find filter type "{}" in Tally ID="{}"'.format(
filter_type, self.id)
msg = f'Unable to find filter type "{filter_type}" in Tally ' \
f'ID="{self.id}"'
raise ValueError(msg)
def get_nuclide_index(self, nuclide):
@ -958,8 +957,8 @@ class Tally(IDManagerMixin):
if test_nuclide == nuclide:
return i
msg = ('Unable to get the nuclide index for Tally since "{}" '
'is not one of the nuclides'.format(nuclide))
msg = (f'Unable to get the nuclide index for Tally since "{nuclide}" '
'is not one of the nuclides')
raise KeyError(msg)
def get_score_index(self, score):
@ -987,8 +986,8 @@ class Tally(IDManagerMixin):
score_index = self.scores.index(score)
except ValueError:
msg = 'Unable to get the score index for Tally since "{}" ' \
'is not one of the scores'.format(score)
msg = f'Unable to get the score index for Tally since "{score}" ' \
'is not one of the scores'
raise ValueError(msg)
return score_index
@ -1122,9 +1121,9 @@ class Tally(IDManagerMixin):
for score in scores:
if not isinstance(score, (str, openmc.CrossScore)):
msg = 'Unable to get score indices for score "{}" in Tally ' \
'ID="{}" since it is not a string or CrossScore'\
.format(score, self.id)
msg = f'Unable to get score indices for score "{score}" in ' \
f'ID="{self.id}" since it is not a string or CrossScore ' \
'Tally'
raise ValueError(msg)
# Determine the score indices from any of the requested scores
@ -1196,7 +1195,7 @@ class Tally(IDManagerMixin):
(value == 'rel_err' and self.mean is None) or \
(value == 'sum' and self.sum is None) or \
(value == 'sum_sq' and self.sum_sq is None):
msg = 'The Tally ID="{}" has no data to return'.format(self.id)
msg = f'The Tally ID="{self.id}" has no data to return'
raise ValueError(msg)
# Get filter, nuclide and score indices
@ -1219,9 +1218,9 @@ class Tally(IDManagerMixin):
elif value == 'sum_sq':
data = self.sum_sq[indices]
else:
msg = 'Unable to return results from Tally ID="{}" since the ' \
'the requested value "{}" is not \'mean\', \'std_dev\', ' \
'\'rel_err\', \'sum\', or \'sum_sq\''.format(self.id, value)
msg = f'Unable to return results from Tally ID="{value}" since ' \
f'the requested value "{self.id}" is not \'mean\', ' \
'\'std_dev\', \'rel_err\', \'sum\', or \'sum_sq\''
raise LookupError(msg)
return data
@ -1272,7 +1271,7 @@ class Tally(IDManagerMixin):
# Ensure that the tally has data
if self.mean is None or self.std_dev is None:
msg = 'The Tally ID="{}" has no data to return'.format(self.id)
msg = f'The Tally ID="{self.id}" has no data to return'
raise KeyError(msg)
# Initialize a pandas dataframe for the tally data
@ -1299,7 +1298,7 @@ class Tally(IDManagerMixin):
nuclides.append(nuclide.name)
elif isinstance(nuclide, openmc.AggregateNuclide):
nuclides.append(nuclide.name)
column_name = '{}(nuclide)'.format(nuclide.aggregate_op)
column_name = f'{nuclide.aggregate_op}(nuclide)'
else:
nuclides.append(nuclide)
@ -1318,7 +1317,7 @@ class Tally(IDManagerMixin):
scores.append(str(score))
elif isinstance(score, openmc.AggregateScore):
scores.append(score.name)
column_name = '{}(score)'.format(score.aggregate_op)
column_name = f'{score.aggregate_op}(score)'
tile_factor = data_size / len(self.scores)
df[column_name] = np.tile(scores, int(tile_factor))
@ -1487,8 +1486,8 @@ class Tally(IDManagerMixin):
# Check that results have been read
if not other.derived and other.sum is None:
msg = 'Unable to use tally arithmetic with Tally ID="{}" ' \
'since it does not contain any results.'.format(other.id)
msg = f'Unable to use tally arithmetic with Tally ' \
f'ID="{other.id}" since it does not contain any results.'
raise ValueError(msg)
new_tally = Tally()
@ -1501,7 +1500,7 @@ class Tally(IDManagerMixin):
# Construct a combined derived name from the two tally operands
if self.name != '' and other.name != '':
new_name = '({} {} {})'.format(self.name, binary_op, other.name)
new_name = f'({self.name} {binary_op} {other.name})'
new_tally.name = new_name
# Query the mean and std dev so the tally data is read in from file
@ -1797,12 +1796,12 @@ class Tally(IDManagerMixin):
if filter1 == filter2:
return
elif filter1 not in self.filters:
msg = 'Unable to swap "{}" filter1 in Tally ID="{}" since it ' \
'does not contain such a filter'.format(filter1.type, self.id)
msg = f'Unable to swap "{filter1.type}" filter1 in Tally ' \
f'ID="{self.id}" since it does not contain such a filter'
raise ValueError(msg)
elif filter2 not in self.filters:
msg = 'Unable to swap "{}" filter2 in Tally ID="{}" since it ' \
'does not contain such a filter'.format(filter2.type, self.id)
msg = f'Unable to swap "{filter2.type}" filter2 in Tally ' \
f'ID="{self.id}" since it does not contain such a filter'
raise ValueError(msg)
# Construct lists of tuples for the bins in each of the two filters
@ -1879,8 +1878,8 @@ class Tally(IDManagerMixin):
# Check that results have been read
if not self.derived and self.sum is None:
msg = 'Unable to use tally arithmetic with Tally ID="{}" ' \
'since it does not contain any results.'.format(self.id)
msg = f'Unable to use tally arithmetic with Tally ID="{self.id}" ' \
'since it does not contain any results.'
raise ValueError(msg)
cv.check_type('nuclide1', nuclide1, _NUCLIDE_CLASSES)
@ -1891,14 +1890,12 @@ class Tally(IDManagerMixin):
msg = 'Unable to swap a nuclide with itself'
raise ValueError(msg)
elif nuclide1 not in self.nuclides:
msg = 'Unable to swap nuclide1 "{}" in Tally ID="{}" since it ' \
'does not contain such a nuclide'\
.format(nuclide1.name, self.id)
msg = f'Unable to swap nuclide1 "{nuclide1.name}" in Tally ' \
f'ID="{self.id}" since it does not contain such a nuclide'
raise ValueError(msg)
elif nuclide2 not in self.nuclides:
msg = 'Unable to swap "{}" nuclide2 in Tally ID="{}" since it ' \
'does not contain such a nuclide'\
.format(nuclide2.name, self.id)
msg = f'Unable to swap "{nuclide2.name}" nuclide2 in Tally ' \
f'ID="{self.id}" since it does not contain such a nuclide'
raise ValueError(msg)
# Swap the nuclides in the Tally

View file

@ -327,8 +327,7 @@ class Universe(UniverseBase):
for obj, color in colors.items():
if isinstance(color, str):
if color.lower() not in _SVG_COLORS:
raise ValueError("'{}' is not a valid color."
.format(color))
raise ValueError(f"'{color}' is not a valid color.")
colors[obj] = [x/255 for x in
_SVG_COLORS[color.lower()]] + [1.0]
elif len(color) == 3:
@ -402,8 +401,8 @@ class Universe(UniverseBase):
"""
if not isinstance(cell, openmc.Cell):
msg = 'Unable to add a Cell to Universe ID="{0}" since "{1}" is not ' \
'a Cell'.format(self._id, cell)
msg = f'Unable to add a Cell to Universe ID="{self._id}" since ' \
f'"{cell}" is not a Cell'
raise TypeError(msg)
cell_id = cell.id
@ -422,8 +421,8 @@ class Universe(UniverseBase):
"""
if not isinstance(cells, Iterable):
msg = 'Unable to add Cells to Universe ID="{0}" since "{1}" is not ' \
'iterable'.format(self._id, cells)
msg = f'Unable to add Cells to Universe ID="{self._id}" since ' \
f'"{cells}" is not iterable'
raise TypeError(msg)
for cell in cells:
@ -440,8 +439,8 @@ class Universe(UniverseBase):
"""
if not isinstance(cell, openmc.Cell):
msg = 'Unable to remove a Cell from Universe ID="{0}" since "{1}" is ' \
'not a Cell'.format(self._id, cell)
msg = f'Unable to remove a Cell from Universe ID="{self._id}" ' \
f'since "{cell}" is not a Cell'
raise TypeError(msg)
# If the Cell is in the Universe's list of Cells, delete it
@ -493,9 +492,9 @@ class Universe(UniverseBase):
else:
raise RuntimeError(
'Volume information is needed to calculate microscopic cross '
'sections for universe {}. This can be done by running a '
'stochastic volume calculation via the '
'openmc.VolumeCalculation object'.format(self.id))
f'sections for universe {self.id}. This can be done by running '
'a stochastic volume calculation via the '
'openmc.VolumeCalculation object')
return nuclides
@ -586,10 +585,10 @@ class Universe(UniverseBase):
"""Count the number of instances for each cell in the universe, and
record the count in the :attr:`Cell.num_instances` properties."""
univ_path = path + 'u{}'.format(self.id)
univ_path = path + f'u{self.id}'
for cell in self.cells.values():
cell_path = '{}->c{}'.format(univ_path, cell.id)
cell_path = f'{univ_path}->c{cell.id}'
fill = cell._fill
fill_type = cell.fill_type
@ -619,7 +618,7 @@ class Universe(UniverseBase):
if mat is not None:
mat._num_instances += 1
if not instances_only:
mat._paths.append('{}->m{}'.format(cell_path, mat.id))
mat._paths.append(f'{cell_path}->m{mat.id}')
# Append current path
cell._num_instances += 1

View file

@ -101,10 +101,10 @@ class VolumeCalculation:
continue
if (np.any(np.asarray(lower_left) > ll) or
np.any(np.asarray(upper_right) < ur)):
warnings.warn(
"Specified bounding box is smaller than computed "
"bounding box for cell {}. Volume calculation may "
"be incorrect!".format(c.id))
msg = ('Specified bounding box is smaller than '
f'computed bounding box for cell {c.id}. Volume '
'calculation may be incorrect!')
warnings.warn(msg)
self.lower_left = lower_left
self.upper_right = upper_right