From 192f4436a0d26ab2610579df4520953250b5e8af Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Thu, 29 Jul 2021 18:25:37 +0100 Subject: [PATCH 1/6] replaced .format with f string --- openmc/arithmetic.py | 18 +++---- openmc/cell.py | 14 +++--- openmc/checkvalue.py | 73 +++++++++++++-------------- openmc/cmfd.py | 6 +-- openmc/element.py | 14 +++--- openmc/executor.py | 4 +- openmc/filter.py | 38 +++++++------- openmc/filter_expansion.py | 10 ++-- openmc/geometry.py | 2 +- openmc/lattice.py | 12 ++--- openmc/material.py | 8 +-- openmc/mesh.py | 3 +- openmc/mgxs_library.py | 8 +-- openmc/mixin.py | 7 ++- openmc/nuclide.py | 4 +- openmc/openmoc_compatible.py | 6 +-- openmc/plots.py | 18 +++---- openmc/plotter.py | 5 +- openmc/region.py | 4 +- openmc/settings.py | 45 +++++++++-------- openmc/statepoint.py | 12 ++--- openmc/surface.py | 2 +- openmc/tallies.py | 96 ++++++++++++++++++------------------ 23 files changed, 196 insertions(+), 213 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index 0daea5f79d..c565cda0db 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -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)) + ')' @@ -545,6 +545,7 @@ class AggregateFilter: 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 +609,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 +661,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 = f'Unable to get the bin index for AggregateFilter since ' \ + '"{filter_bin}" is not one of the bins' raise ValueError(msg) else: return self.bins.index(filter_bin) @@ -757,8 +758,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 diff --git a/openmc/cell.py b/openmc/cell.py index af1a07f9a9..e784e1cfbf 100644 --- a/openmc/cell.py +++ b/openmc/cell.py @@ -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 ' + '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)) + f'Volume information is needed to calculate microscopic ' + 'cross sections for cell {self.id}. This can be done by ' + 'running a stochastic volume calculation via the ' + 'openmc.VolumeCalculation object') return nuclides diff --git a/openmc/checkvalue.py b/openmc/checkvalue.py index a59b38a630..3c76890f75 100644 --- a/openmc/checkvalue.py +++ b/openmc/checkvalue.py @@ -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 "' + '{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 ' + '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 = ('Unable to set "{name}" to "{value}" since each ' + '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 ' + '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 ' + '{ind_str}, items in that iterable exceed the ' + '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 ' + '"{expected_type.__name__}", but item at {ind_str} is ' + '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 ' + '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 ' + '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 ' + '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 ' + '"{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 ' + '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 ' + '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 ' + '"{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 ' + '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): diff --git a/openmc/cmfd.py b/openmc/cmfd.py index 61bda9ed99..52665035f3 100644 --- a/openmc/cmfd.py +++ b/openmc/cmfd.py @@ -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 = ('Setting {variable_label} if mesh type is not set to ' + '{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 diff --git a/openmc/element.py b/openmc/element.py index 2eacaf867d..acae7b400c 100644 --- a/openmc/element.py +++ b/openmc/element.py @@ -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. @@ -204,8 +203,8 @@ 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)) + msg = (f'Enrichment procedure for Uranium was requested, ' + '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 diff --git a/openmc/executor.py b/openmc/executor.py index 008290c181..e8f0de2c7e 100644 --- a/openmc/executor.py +++ b/openmc/executor.py @@ -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)) diff --git a/openmc/filter.py b/openmc/filter.py index e46effa7bd..fd1be41e3b 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -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 = (f'Unable to get the bin index for Filter since ' + '"{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('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 = (f'Unable to get the bin index for Filter since ' + '"{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() diff --git a/openmc/filter_expansion.py b/openmc/filter_expansion.py index c26d5437b3..9a915d18fa 100644 --- a/openmc/filter_expansion.py +++ b/openmc/filter_expansion.py @@ -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)] diff --git a/openmc/geometry.py b/openmc/geometry.py index 8f7bf05f85..58a33c1b12 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -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: diff --git a/openmc/lattice.py b/openmc/lattice.py index 5112dde05a..72d82b2c58 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -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 = f'{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 = f'{self._outer._id}' self._outer.create_xml_subelement(xml_element, memo) lattice_subelement.set("n_rings", str(self._num_rings)) diff --git a/openmc/material.py b/openmc/material.py index c6a8e6f44a..4d43664336 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -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 diff --git a/openmc/mesh.py b/openmc/mesh.py index 7ef18b1ceb..0e35aa6fea 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -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 = '' diff --git a/openmc/mgxs_library.py b/openmc/mgxs_library.py index 00a155142f..d7d4b6f2f8 100644 --- a/openmc/mgxs_library.py +++ b/openmc/mgxs_library.py @@ -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) diff --git a/openmc/mixin.py b/openmc/mixin.py index dc2e91f51a..516162464d 100644 --- a/openmc/mixin.py +++ b/openmc/mixin.py @@ -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) diff --git a/openmc/nuclide.py b/openmc/nuclide.py index fcbfc2d606..2394aa0a40 100644 --- a/openmc/nuclide.py +++ b/openmc/nuclide.py @@ -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 = (f'OpenMC nuclides follow the GND naming convention. ' + 'Nuclide "{orig_name}" is being renamed as "{name}".') warnings.warn(msg) return super().__new__(cls, name) diff --git a/openmc/openmoc_compatible.py b/openmc/openmoc_compatible.py index 1ae120df6f..cc8d5cfc86 100644 --- a/openmc/openmoc_compatible.py +++ b/openmc/openmoc_compatible.py @@ -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 = (f'Unable to create an OpenMOC Surface from an OpenMC Surface of ' + 'type "{type(openmc_surface)}" since it is not a compatible ' + 'Surface type in OpenMOC') raise ValueError(msg) # Set the boundary condition for this Surface diff --git a/openmc/plots.py b/openmc/plots.py index f275a84818..ca90d39f04 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -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: @@ -494,8 +494,8 @@ class Plot(IDManagerMixin): upper_right = upper_right[np.array(pick_index)] if np.any(np.isinf((lower_left, upper_right))): - raise ValueError('The geometry does not appear to be bounded ' - 'in the {} plane.'.format(basis)) + raise ValueError(f'The geometry does not appear to be bounded ' + '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]) diff --git a/openmc/plotter.py b/openmc/plotter.py index c6f069aa62..576cb28fce 100644 --- a/openmc/plotter.py +++ b/openmc/plotter.py @@ -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 diff --git a/openmc/region.py b/openmc/region.py index 69273e5de9..cfdc3e81e9 100644 --- a/openmc/region.py +++ b/openmc/region.py @@ -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: diff --git a/openmc/settings.py b/openmc/settings.py index 7696aee9fc..7e5e37dc1f 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -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 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 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) diff --git a/openmc/statepoint.py b/openmc/statepoint.py index 0ce3206573..cd8651ea3b 100644 --- a/openmc/statepoint.py +++ b/openmc/statepoint.py @@ -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 = 'Unable to link statepoint with "{summary}" which is not a' \ + 'Summary object' raise ValueError(msg) cells = summary.geometry.get_all_cells() diff --git a/openmc/surface.py b/openmc/surface.py index ac0cb1b0b2..41477fd1c9 100644 --- a/openmc/surface.py +++ b/openmc/surface.py @@ -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 diff --git a/openmc/tallies.py b/openmc/tallies.py index 048bd99513..bdeffa8f55 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -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 ' + '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 = ('Unable to add a duplicate nuclide "{nuc}" to Tally ID=' + '"{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 ' + '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 ' \ + '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 ' \ + '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 ' \ + '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 = '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 = 'Unable to find filter type "{filter_type}" in Tally ' \ + '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 ' \ + '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 ' \ + '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 ' \ + '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 ' \ + '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 ' \ + '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,9 +1890,8 @@ 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 ' \ + '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 ' \ From 021aab98794319fa6590b3f32777a6f2c61f685f Mon Sep 17 00:00:00 2001 From: Jonathan Date: Thu, 29 Jul 2021 20:28:51 +0100 Subject: [PATCH 2/6] replaced .format with f strings --- openmc/arithmetic.py | 2 -- openmc/checkvalue.py | 2 +- openmc/cmfd.py | 2 +- openmc/filter.py | 4 ++-- openmc/statepoint.py | 2 +- openmc/tallies.py | 6 +++--- openmc/universe.py | 29 ++++++++++++++--------------- openmc/volume.py | 6 +++--- 8 files changed, 25 insertions(+), 28 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index c565cda0db..c723fb3e99 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -543,8 +543,6 @@ 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 diff --git a/openmc/checkvalue.py b/openmc/checkvalue.py index 3c76890f75..09ee4e400e 100644 --- a/openmc/checkvalue.py +++ b/openmc/checkvalue.py @@ -28,7 +28,7 @@ def check_type(name, value, expected_type, expected_iter_type=None, *, none_ok=F if not isinstance(value, expected_type): if isinstance(expected_type, Iterable): - msg = 'Unable to set "{}" to "{}" which is not one of the ' \ + msg = f'Unable to set "{}" to "{}" which is not one of the ' \ 'following types: "{}"'.format(name, value, ', '.join( [t.__name__ for t in expected_type])) else: diff --git a/openmc/cmfd.py b/openmc/cmfd.py index 52665035f3..f9bd83f9bc 100644 --- a/openmc/cmfd.py +++ b/openmc/cmfd.py @@ -251,7 +251,7 @@ class CMFDMesh: def _display_mesh_warning(self, mesh_type, variable_label): if self._mesh_type != mesh_type: - warn_msg = ('Setting {variable_label} if mesh type is not set to ' + warn_msg = (f'Setting {variable_label} if mesh type is not set to ' '{mesh_type} will have no effect') warnings.warn(warn_msg, RuntimeWarning) diff --git a/openmc/filter.py b/openmc/filter.py index fd1be41e3b..a9e9f2433e 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -1111,7 +1111,7 @@ class RealFilter(Filter): for pair0, pair1 in zip(bins[:-1], bins[1:]): # Successive pairs should be ordered if pair1[1] < pair0[1]: - raise ValueError('Values {pair1[1]} and {pair0[1]} appear to ' + raise ValueError(f'Values {pair1[1]} and {pair0[1]} appear to ' 'be out of order') def can_merge(self, other): @@ -1414,7 +1414,7 @@ class DistribcellFilter(Filter): # Make sure there is only 1 bin. if not len(bins) == 1: - msg =(f'Unable to add bins "{bins}" to a DistribcellFilter since ' + msg = (f'Unable to add bins "{bins}" to a DistribcellFilter since ' 'only a single distribcell can be used per tally') raise ValueError(msg) diff --git a/openmc/statepoint.py b/openmc/statepoint.py index cd8651ea3b..894730cbe9 100644 --- a/openmc/statepoint.py +++ b/openmc/statepoint.py @@ -655,7 +655,7 @@ class StatePoint: return if not isinstance(summary, openmc.Summary): - msg = 'Unable to link statepoint with "{summary}" which is not a' \ + msg = f'Unable to link statepoint with "{summary}" which is not a' \ 'Summary object' raise ValueError(msg) diff --git a/openmc/tallies.py b/openmc/tallies.py index bdeffa8f55..33d059f17c 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -352,7 +352,7 @@ class Tally(IDManagerMixin): visited_nuclides = set() for nuc in nuclides: if nuc in visited_nuclides: - msg = ('Unable to add a duplicate nuclide "{nuc}" to Tally ID=' + msg = (f'Unable to add a duplicate nuclide "{nuc}" to Tally ID=' '"{self.id}" since duplicate nuclides are not supported ' 'in the OpenMC Python API') raise ValueError(msg) @@ -684,7 +684,7 @@ class Tally(IDManagerMixin): """ if not self.can_merge(other): - msg = 'Unable to merge tally ID="{other.id}" with "{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 @@ -921,7 +921,7 @@ class Tally(IDManagerMixin): return test_filter # If we did not find the Filter, throw an Exception - msg = 'Unable to find filter type "{filter_type}" in Tally ' \ + msg = f'Unable to find filter type "{filter_type}" in Tally ' \ 'ID="{self.id}"' raise ValueError(msg) diff --git a/openmc/universe.py b/openmc/universe.py index 5cfb985793..a8b6d51e98 100644 --- a/openmc/universe.py +++ b/openmc/universe.py @@ -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 ' \ + '"{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 ' \ + '"{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}" ' \ + 'since "{cell}" is not a Cell' raise TypeError(msg) # If the Cell is in the Universe's list of Cells, delete it @@ -492,10 +491,10 @@ class Universe(UniverseBase): nuclides[name] = (nuclide, density) 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'Volume information is needed to calculate microscopic cross ' + '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 diff --git a/openmc/volume.py b/openmc/volume.py index 7a9ef17371..7c86f1fe9e 100644 --- a/openmc/volume.py +++ b/openmc/volume.py @@ -102,9 +102,9 @@ class VolumeCalculation: 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)) + f"Specified bounding box is smaller than computed " + "bounding box for cell {c.id}. Volume calculation " + "may be incorrect!") self.lower_left = lower_left self.upper_right = upper_right From 268424cd343f49364f62be0faf7ed711148a43d8 Mon Sep 17 00:00:00 2001 From: Jonathan Date: Thu, 29 Jul 2021 20:36:10 +0100 Subject: [PATCH 3/6] another format to f string conversion --- openmc/checkvalue.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmc/checkvalue.py b/openmc/checkvalue.py index 09ee4e400e..dff18ae2bd 100644 --- a/openmc/checkvalue.py +++ b/openmc/checkvalue.py @@ -53,7 +53,7 @@ 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 "{name}" to "{value}" since each ' + msg = (f'Unable to set "{name}" to "{value}" since each ' 'item must be of type "{expected_iter_type.__name__}"') raise TypeError(msg) From 747094be1ae45503d369fa5c24c007f5158753a1 Mon Sep 17 00:00:00 2001 From: Jonathan Date: Thu, 29 Jul 2021 20:55:40 +0100 Subject: [PATCH 4/6] returned to .format --- openmc/checkvalue.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmc/checkvalue.py b/openmc/checkvalue.py index dff18ae2bd..c90797043c 100644 --- a/openmc/checkvalue.py +++ b/openmc/checkvalue.py @@ -28,7 +28,7 @@ def check_type(name, value, expected_type, expected_iter_type=None, *, none_ok=F if not isinstance(value, expected_type): if isinstance(expected_type, Iterable): - msg = f'Unable to set "{}" to "{}" which is not one of the ' \ + msg = 'Unable to set "{}" to "{}" which is not one of the ' \ 'following types: "{}"'.format(name, value, ', '.join( [t.__name__ for t in expected_type])) else: From 2453b04b6282d46b8c7ad50956522f7e42d80a1c Mon Sep 17 00:00:00 2001 From: Jonathan Date: Sat, 31 Jul 2021 22:33:45 +0100 Subject: [PATCH 5/6] corrected multiline f strings --- openmc/arithmetic.py | 4 ++-- openmc/cell.py | 6 +++--- openmc/checkvalue.py | 32 ++++++++++++++++---------------- openmc/cmfd.py | 2 +- openmc/element.py | 4 ++-- openmc/filter.py | 8 ++++---- openmc/nuclide.py | 4 ++-- openmc/openmoc_compatible.py | 4 ++-- openmc/plots.py | 4 ++-- openmc/tallies.py | 31 +++++++++++++++---------------- openmc/universe.py | 10 +++++----- openmc/volume.py | 8 ++++---- 12 files changed, 58 insertions(+), 59 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index c723fb3e99..618c7c4a1a 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -659,8 +659,8 @@ class AggregateFilter: """ if filter_bin not in self.bins: - msg = f'Unable to get the bin index for AggregateFilter since ' \ - '"{filter_bin}" is not one of the bins' + 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) diff --git a/openmc/cell.py b/openmc/cell.py index e784e1cfbf..2ff1d5fcd4 100644 --- a/openmc/cell.py +++ b/openmc/cell.py @@ -280,7 +280,7 @@ class Cell(IDManagerMixin): elif not isinstance(fill, (openmc.Material, openmc.Lattice, openmc.UniverseBase)): msg = (f'Unable to set Cell ID="{self._id}" to use a ' - 'non-Material or Universe fill "{fill}"') + f'non-Material or Universe fill "{fill}"') raise ValueError(msg) self._fill = fill @@ -408,8 +408,8 @@ class Cell(IDManagerMixin): nuclides[name] = (nuclide, density) else: raise RuntimeError( - f'Volume information is needed to calculate microscopic ' - 'cross sections for cell {self.id}. This can be done by ' + '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') diff --git a/openmc/checkvalue.py b/openmc/checkvalue.py index c90797043c..d50b3fcaec 100644 --- a/openmc/checkvalue.py +++ b/openmc/checkvalue.py @@ -33,14 +33,14 @@ def check_type(name, value, expected_type, expected_iter_type=None, *, none_ok=F [t.__name__ for t in expected_type])) else: msg = (f'Unable to set "{name}" to "{value}" which is not of type "' - '{expected_type.__name__}"') + 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 = (f'Unable to set "{name}" to "{value}" since each item ' - 'must be of type "{expected_iter_type.__name__}"') + f'must be of type "{expected_iter_type.__name__}"') raise TypeError(msg) else: return @@ -54,7 +54,7 @@ def check_type(name, value, expected_type, expected_iter_type=None, *, none_ok=F expected_iter_type])) else: msg = (f'Unable to set "{name}" to "{value}" since each ' - 'item must be of type "{expected_iter_type.__name__}"') + f'item must be of type "{expected_iter_type.__name__}"') raise TypeError(msg) @@ -105,7 +105,7 @@ def check_iterable_type(name, value, expected_type, min_depth=1, max_depth=1): # Is this deep enough? if len(tree) < min_depth: msg = (f'Error setting "{name}": The item at {ind_str} does not ' - 'meet the minimum depth of {min_depth}') + f'meet the minimum depth of {min_depth}') raise TypeError(msg) # This item is okay. Move on to the next item. @@ -122,15 +122,15 @@ 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 = (f'Error setting {name}: Found an iterable at ' - '{ind_str}, items in that iterable exceed the ' - 'maximum depth of {max_depth}') + 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 = (f'Error setting {name}: Items must be of type ' - '"{expected_type.__name__}", but item at {ind_str} is ' - 'of type "{type(current_item).__name__}"') + f'"{expected_type.__name__}", but item at {ind_str} is ' + f'of type "{type(current_item).__name__}"') raise TypeError(msg) @@ -154,15 +154,15 @@ def check_length(name, value, length_min, length_max=None): if length_max is None: if len(value) < length_min: msg = (f'Unable to set "{name}" to "{value}" since it must be at ' - 'least of length "{length_min}"') + f'least of length "{length_min}"') raise ValueError(msg) elif not length_min <= len(value) <= length_max: if length_min == length_max: msg = (f'Unable to set "{name}" to "{value}" since it must be of ' - 'length "{length_min}"') + f'length "{length_min}"') else: msg = (f'Unable to set "{name}" to "{value}" since it must have ' - 'length between "{length_min}" and "{length_max}"') + f'length between "{length_min}" and "{length_max}"') raise ValueError(msg) @@ -182,7 +182,7 @@ def check_value(name, value, accepted_values): if value not in accepted_values: msg = (f'Unable to set "{name}" to "{value}" since it is not in ' - '"{accepted_values}"') + f'"{accepted_values}"') raise ValueError(msg) @@ -205,12 +205,12 @@ def check_less_than(name, value, maximum, equality=False): if equality: if value > maximum: msg = (f'Unable to set "{name}" to "{value}" since it is greater ' - 'than "{maximum}"') + f'than "{maximum}"') raise ValueError(msg) else: if value >= maximum: msg = (f'Unable to set "{name}" to "{value}" since it is greater ' - 'than or equal to "{maximum}"') + f'than or equal to "{maximum}"') raise ValueError(msg) @@ -233,12 +233,12 @@ def check_greater_than(name, value, minimum, equality=False): if equality: if value < minimum: msg = (f'Unable to set "{name}" to "{value}" since it is less than ' - '"{minimum}"') + f'"{minimum}"') raise ValueError(msg) else: if value <= minimum: msg = (f'Unable to set "{name}" to "{value}" since it is less than ' - 'or equal to "{minimum}"') + f'or equal to "{minimum}"') raise ValueError(msg) diff --git a/openmc/cmfd.py b/openmc/cmfd.py index f9bd83f9bc..080e558be6 100644 --- a/openmc/cmfd.py +++ b/openmc/cmfd.py @@ -252,7 +252,7 @@ class CMFDMesh: def _display_mesh_warning(self, mesh_type, variable_label): if self._mesh_type != mesh_type: warn_msg = (f'Setting {variable_label} if mesh type is not set to ' - '{mesh_type} will have no effect') + f'{mesh_type} will have no effect') warnings.warn(warn_msg, RuntimeWarning) diff --git a/openmc/element.py b/openmc/element.py index acae7b400c..0d37ab7266 100644 --- a/openmc/element.py +++ b/openmc/element.py @@ -203,8 +203,8 @@ class Element(str): # Check that the element is Uranium if self.name != 'U': - msg = (f'Enrichment procedure for Uranium was requested, ' - 'but the isotope is {self} not U') + msg = ('Enrichment procedure for Uranium was requested, ' + f'but the isotope is {self} not U') raise ValueError(msg) # Check that enrichment_type is not 'ao' diff --git a/openmc/filter.py b/openmc/filter.py index a9e9f2433e..95be1774d0 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -325,8 +325,8 @@ class Filter(IDManagerMixin, metaclass=FilterMeta): """ if filter_bin not in self.bins: - msg = (f'Unable to get the bin index for Filter since ' - '"{filter_bin}" is not one of the bins') + 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): @@ -1271,8 +1271,8 @@ class EnergyFilter(RealFilter): if min_delta < 1E-3: return deltas.argmin() else: - msg = (f'Unable to get the bin index for Filter since ' - '"{filter_bin}" is not one of the bins') + 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): diff --git a/openmc/nuclide.py b/openmc/nuclide.py index 2394aa0a40..196c8d7701 100644 --- a/openmc/nuclide.py +++ b/openmc/nuclide.py @@ -26,8 +26,8 @@ class Nuclide(str): if name.endswith('m'): name = name[:-1] + '_m1' - msg = (f'OpenMC nuclides follow the GND naming convention. ' - 'Nuclide "{orig_name}" is being renamed as "{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) diff --git a/openmc/openmoc_compatible.py b/openmc/openmoc_compatible.py index cc8d5cfc86..3fd54520ba 100644 --- a/openmc/openmoc_compatible.py +++ b/openmc/openmoc_compatible.py @@ -193,8 +193,8 @@ def get_openmoc_surface(openmc_surface): openmoc_surface = openmoc.ZCylinder(x0, y0, R, surface_id, name) else: - msg = (f'Unable to create an OpenMOC Surface from an OpenMC Surface of ' - 'type "{type(openmc_surface)}" since it is not a compatible ' + 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) diff --git a/openmc/plots.py b/openmc/plots.py index ca90d39f04..0abff20d7b 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -494,8 +494,8 @@ class Plot(IDManagerMixin): upper_right = upper_right[np.array(pick_index)] if np.any(np.isinf((lower_left, upper_right))): - raise ValueError(f'The geometry does not appear to be bounded ' - 'in the {basis} plane.') + raise ValueError('The geometry does not appear to be bounded ' + f'in the {basis} plane.') plot = cls() plot.origin = np.insert((lower_left + upper_right)/2, diff --git a/openmc/tallies.py b/openmc/tallies.py index 33d059f17c..d99eb41ff1 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -337,7 +337,7 @@ class Tally(IDManagerMixin): for f in filters: if f in visited_filters: msg = (f'Unable to add a duplicate filter "{f}" to Tally ' - 'ID="{self.id}" since duplicate filters are not ' + f'ID="{self.id}" since duplicate filters are not ' 'supported in the OpenMC Python API') raise ValueError(msg) visited_filters.add(f) @@ -353,7 +353,7 @@ class Tally(IDManagerMixin): for nuc in nuclides: if nuc in visited_nuclides: msg = (f'Unable to add a duplicate nuclide "{nuc}" to Tally ID=' - '"{self.id}" since duplicate nuclides are not supported ' + f'"{self.id}" since duplicate nuclides are not supported ' 'in the OpenMC Python API') raise ValueError(msg) visited_nuclides.add(nuc) @@ -370,7 +370,7 @@ class Tally(IDManagerMixin): # If the score is already in the Tally, raise an error if score in visited_scores: msg = (f'Unable to add a duplicate score "{score}" to Tally ' - 'ID="{self.id}" since duplicate scores are not ' + f'ID="{self.id}" since duplicate scores are not ' 'supported in the OpenMC Python API') raise ValueError(msg) visited_scores.add(score) @@ -468,7 +468,7 @@ class Tally(IDManagerMixin): if score not in self.scores: msg = f'Unable to remove score "{score}" from Tally ' \ - 'ID="{self.id}" since the Tally does not contain this score' + f'ID="{self.id}" since the Tally does not contain this score' raise ValueError(msg) self._scores.remove(score) @@ -485,7 +485,7 @@ class Tally(IDManagerMixin): if old_filter not in self.filters: msg = f'Unable to remove filter "{old_filter}" from Tally ' \ - 'ID="{self.id}" since the Tally does not contain this filter' + f'ID="{self.id}" since the Tally does not contain this filter' raise ValueError(msg) self._filters.remove(old_filter) @@ -502,7 +502,7 @@ class Tally(IDManagerMixin): if nuclide not in self.nuclides: msg = f'Unable to remove nuclide "{nuclide}" from Tally ' \ - 'ID="{self.id}" since the Tally does not contain this nuclide' + f'ID="{self.id}" since the Tally does not contain this nuclide' raise ValueError(msg) self._nuclides.remove(nuclide) @@ -922,7 +922,7 @@ class Tally(IDManagerMixin): # If we did not find the Filter, throw an Exception msg = f'Unable to find filter type "{filter_type}" in Tally ' \ - 'ID="{self.id}"' + f'ID="{self.id}"' raise ValueError(msg) def get_nuclide_index(self, nuclide): @@ -1122,7 +1122,7 @@ class Tally(IDManagerMixin): for score in scores: if not isinstance(score, (str, openmc.CrossScore)): msg = f'Unable to get score indices for score "{score}" in ' \ - 'ID="{self.id}" since it is not a string or CrossScore ' \ + f'ID="{self.id}" since it is not a string or CrossScore ' \ 'Tally' raise ValueError(msg) @@ -1219,7 +1219,7 @@ class Tally(IDManagerMixin): data = self.sum_sq[indices] else: msg = f'Unable to return results from Tally ID="{value}" since ' \ - 'the requested value "{self.id}" is not \'mean\', ' \ + f'the requested value "{self.id}" is not \'mean\', ' \ '\'std_dev\', \'rel_err\', \'sum\', or \'sum_sq\'' raise LookupError(msg) @@ -1487,7 +1487,7 @@ class Tally(IDManagerMixin): # Check that results have been read if not other.derived and other.sum is None: msg = f'Unable to use tally arithmetic with Tally ' \ - 'ID="{other.id}" since it does not contain any results.' + f'ID="{other.id}" since it does not contain any results.' raise ValueError(msg) new_tally = Tally() @@ -1797,11 +1797,11 @@ class Tally(IDManagerMixin): return elif filter1 not in self.filters: msg = f'Unable to swap "{filter1.type}" filter1 in Tally ' \ - 'ID="{self.id}" since it does not contain such a filter' + f'ID="{self.id}" since it does not contain such a filter' raise ValueError(msg) elif filter2 not in self.filters: msg = f'Unable to swap "{filter2.type}" filter2 in Tally ' \ - 'ID="{self.id}" since it does not contain such a filter' + 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 @@ -1891,12 +1891,11 @@ class Tally(IDManagerMixin): raise ValueError(msg) elif nuclide1 not in self.nuclides: msg = f'Unable to swap nuclide1 "{nuclide1.name}" in Tally ' \ - 'ID="{self.id}" since it does not contain such a nuclide' + 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 diff --git a/openmc/universe.py b/openmc/universe.py index a8b6d51e98..e971be1c0b 100644 --- a/openmc/universe.py +++ b/openmc/universe.py @@ -402,7 +402,7 @@ class Universe(UniverseBase): if not isinstance(cell, openmc.Cell): msg = f'Unable to add a Cell to Universe ID="{self._id}" since ' \ - '"{cell}" is not a Cell' + f'"{cell}" is not a Cell' raise TypeError(msg) cell_id = cell.id @@ -422,7 +422,7 @@ class Universe(UniverseBase): if not isinstance(cells, Iterable): msg = f'Unable to add Cells to Universe ID="{self._id}" since ' \ - '"{cells}" is not iterable' + f'"{cells}" is not iterable' raise TypeError(msg) for cell in cells: @@ -440,7 +440,7 @@ class Universe(UniverseBase): if not isinstance(cell, openmc.Cell): msg = f'Unable to remove a Cell from Universe ID="{self._id}" ' \ - 'since "{cell}" is not a Cell' + f'since "{cell}" is not a Cell' raise TypeError(msg) # If the Cell is in the Universe's list of Cells, delete it @@ -491,8 +491,8 @@ class Universe(UniverseBase): nuclides[name] = (nuclide, density) else: raise RuntimeError( - f'Volume information is needed to calculate microscopic cross ' - 'sections for universe {self.id}. This can be done by running ' + 'Volume information is needed to calculate microscopic cross ' + f'sections for universe {self.id}. This can be done by running ' 'a stochastic volume calculation via the ' 'openmc.VolumeCalculation object') diff --git a/openmc/volume.py b/openmc/volume.py index 7c86f1fe9e..9acf58ca3b 100644 --- a/openmc/volume.py +++ b/openmc/volume.py @@ -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( - f"Specified bounding box is smaller than computed " - "bounding box for cell {c.id}. Volume calculation " - "may be incorrect!") + 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 From 0bba16e0bff9cfd11e6180f2d1f341500d31f68b Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Mon, 2 Aug 2021 21:27:27 +0100 Subject: [PATCH 6/6] using str() as suggested by review Co-authored-by: Paul Romano --- openmc/lattice.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openmc/lattice.py b/openmc/lattice.py index 72d82b2c58..648b1438e4 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -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 = f'{self._outer._id}' + outer.text = str(self._outer._id) self._outer.create_xml_subelement(xml_element, memo) # Export Lattice cell dimensions @@ -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 = f'{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))