From 194821eecebdde67c1581ecf1d950694307da93a Mon Sep 17 00:00:00 2001 From: Stephan Seitz <stephan.seitz@fau.de> Date: Mon, 5 Aug 2019 18:50:09 +0200 Subject: [PATCH] Run flynt (https://pypi.org/project/flynt/) on pystencils This replaces usages of "" % s by Python's f-strings --- pystencils/astnodes.py | 18 ++++---- pystencils/backends/cbackend.py | 44 +++++++++---------- pystencils/backends/dot.py | 4 +- pystencils/backends/simd_instruction_sets.py | 12 ++--- pystencils/boundaries/boundaryhandling.py | 10 ++--- pystencils/cpu/cpujit.py | 12 ++--- pystencils/cpu/kernelcreation.py | 8 ++-- pystencils/cpu/msvc_detection.py | 4 +- pystencils/cpu/vectorization.py | 2 +- pystencils/data_types.py | 12 ++--- .../datahandling/parallel_datahandling.py | 4 +- .../datahandling/serial_datahandling.py | 8 ++-- pystencils/display_utils.py | 2 +- pystencils/fd/derivative.py | 2 +- pystencils/fd/finitedifferences.py | 10 ++--- pystencils/field.py | 12 ++--- pystencils/gpucuda/indexing.py | 2 +- pystencils/gpucuda/kernelcreation.py | 2 +- pystencils/integer_set_analysis.py | 5 +-- pystencils/jupyter.py | 11 +---- .../kerncraft_coupling/kerncraft_interface.py | 2 +- pystencils/kernelcreation.py | 4 +- pystencils/kernelparameters.py | 6 +-- pystencils/llvm/llvm.py | 2 +- pystencils/placeholder_function.py | 2 +- pystencils/runhelper/parameterstudy.py | 8 ++-- pystencils/simp/assignment_collection.py | 6 +-- pystencils/simp/simplificationstrategy.py | 4 +- pystencils/stencil.py | 4 +- pystencils/transformations.py | 20 ++++----- 30 files changed, 117 insertions(+), 125 deletions(-) diff --git a/pystencils/astnodes.py b/pystencils/astnodes.py index 661cabd1..91ddaca0 100644 --- a/pystencils/astnodes.py +++ b/pystencils/astnodes.py @@ -107,10 +107,10 @@ class Conditional(Node): return result def __str__(self): - return 'if:({!s}) '.format(self.condition_expr) + return f'if:({self.condition_expr!s}) ' def __repr__(self): - return 'if:({!r}) '.format(self.condition_expr) + return f'if:({self.condition_expr!r}) ' def replace_by_true_block(self): """Replaces the conditional by its True block""" @@ -241,7 +241,7 @@ class KernelFunction(Node): def __repr__(self): params = [p.symbol for p in self.get_parameters()] - return '{0} {1}({2})'.format(type(self).__name__, self.function_name, params) + return f'{type(self).__name__} {self.function_name}({params})' def compile(self, *args, **kwargs): if self._compile_function is None: @@ -419,11 +419,11 @@ class LoopOverCoordinate(Node): @staticmethod def get_loop_counter_name(coordinate_to_loop_over): - return "%s_%s" % (LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX, coordinate_to_loop_over) + return f"{LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX}_{coordinate_to_loop_over}" @staticmethod def get_block_loop_counter_name(coordinate_to_loop_over): - return "%s_%s" % (LoopOverCoordinate.BlOCK_LOOP_COUNTER_NAME_PREFIX, coordinate_to_loop_over) + return f"{LoopOverCoordinate.BlOCK_LOOP_COUNTER_NAME_PREFIX}_{coordinate_to_loop_over}" @property def loop_counter_name(self): @@ -545,7 +545,7 @@ class SympyAssignment(Node): replacement.parent = self self.rhs = replacement else: - raise ValueError('%s is not in args of %s' % (replacement, self.__class__)) + raise ValueError(f'{replacement} is not in args of {self.__class__}') def __repr__(self): return repr(self.lhs) + " ← " + repr(self.rhs) @@ -553,7 +553,7 @@ class SympyAssignment(Node): def _repr_html_(self): printed_lhs = sp.latex(self.lhs) printed_rhs = sp.latex(self.rhs) - return "${printed_lhs} \\leftarrow {printed_rhs}$".format(printed_lhs=printed_lhs, printed_rhs=printed_rhs) + return f"${printed_lhs} \\leftarrow {printed_rhs}$" class ResolvedFieldAccess(sp.Indexed): @@ -588,7 +588,7 @@ class ResolvedFieldAccess(sp.Indexed): def __str__(self): top = super(ResolvedFieldAccess, self).__str__() - return "%s (%s)" % (top, self.typed_symbol.dtype) + return f"{top} ({self.typed_symbol.dtype})" def __getnewargs__(self): return self.base, self.indices[0], self.field, self.offsets, self.idx_coordinate_values @@ -720,4 +720,4 @@ class DestructuringBindingsForFieldClass(Node): def get_dummy_symbol(dtype='bool'): - return TypedSymbol('dummy%s' % uuid.uuid4().hex, create_type(dtype)) + return TypedSymbol(f'dummy{uuid.uuid4().hex}', create_type(dtype)) diff --git a/pystencils/backends/cbackend.py b/pystencils/backends/cbackend.py index 965b5d84..f4d0b57d 100644 --- a/pystencils/backends/cbackend.py +++ b/pystencils/backends/cbackend.py @@ -128,7 +128,7 @@ class CustomCodeNode(Node): class PrintNode(CustomCodeNode): # noinspection SpellCheckingInspection def __init__(self, symbol_to_print): - code = '\nstd::cout << "%s = " << %s << std::endl; \n' % (symbol_to_print.name, symbol_to_print.name) + code = f'\nstd::cout << "{symbol_to_print.name} = " << {symbol_to_print.name} << std::endl; \n' super(PrintNode, self).__init__(code, symbols_read=[symbol_to_print], symbols_defined=set()) self.headers.append("<iostream>") @@ -168,12 +168,12 @@ class CBackend: raise NotImplementedError(self.__class__ + " does not support node of type " + str(type(node))) def _print_KernelFunction(self, node): - function_arguments = ["%s %s" % (str(s.symbol.dtype), s.symbol.name) for s in node.get_parameters()] + function_arguments = [f"{str(s.symbol.dtype)} {s.symbol.name}" for s in node.get_parameters()] launch_bounds = "" if self.__class__ == 'cuda': max_threads = node.indexing.max_threads_per_block() if max_threads: - launch_bounds = "__launch_bounds__({}) ".format(max_threads) + launch_bounds = f"__launch_bounds__({max_threads}) " func_declaration = "FUNC_PREFIX %svoid %s(%s)" % (launch_bounds, node.function_name, ", ".join(function_arguments)) if self._signatureOnly: @@ -187,19 +187,19 @@ class CBackend: return "{\n%s\n}" % (self._indent + self._indent.join(block_contents.splitlines(True))) def _print_PragmaBlock(self, node): - return "%s\n%s" % (node.pragma_line, self._print_Block(node)) + return f"{node.pragma_line}\n{self._print_Block(node)}" def _print_LoopOverCoordinate(self, node): counter_symbol = node.loop_counter_name - start = "int %s = %s" % (counter_symbol, self.sympy_printer.doprint(node.start)) - condition = "%s < %s" % (counter_symbol, self.sympy_printer.doprint(node.stop)) - update = "%s += %s" % (counter_symbol, self.sympy_printer.doprint(node.step),) - loop_str = "for (%s; %s; %s)" % (start, condition, update) + start = f"int {counter_symbol} = {self.sympy_printer.doprint(node.start)}" + condition = f"{counter_symbol} < {self.sympy_printer.doprint(node.stop)}" + update = f"{counter_symbol} += {self.sympy_printer.doprint(node.step)}" + loop_str = f"for ({start}; {condition}; {update})" prefix = "\n".join(node.prefix_lines) if prefix: prefix += "\n" - return "%s%s\n%s" % (prefix, loop_str, self._print(node.body)) + return f"{prefix}{loop_str}\n{self._print(node.body)}" def _print_SympyAssignment(self, node): if node.is_declaration: @@ -223,7 +223,7 @@ class CBackend: return self._vector_instruction_set[instr].format("&" + self.sympy_printer.doprint(node.lhs.args[0]), self.sympy_printer.doprint(rhs)) + ';' else: - return "%s = %s;" % (self.sympy_printer.doprint(node.lhs), self.sympy_printer.doprint(node.rhs)) + return f"{self.sympy_printer.doprint(node.lhs)} = {self.sympy_printer.doprint(node.rhs)};" def _print_TemporaryMemoryAllocation(self, node): align = 64 @@ -239,7 +239,7 @@ class CBackend: def _print_TemporaryMemoryFree(self, node): align = 64 - return "free(%s - %d);" % (self.sympy_printer.doprint(node.symbol.name), node.offset(align)) + return f"free({self.sympy_printer.doprint(node.symbol.name)} - {node.offset(align):d});" def _print_SkipIteration(self, _): return "continue;" @@ -253,7 +253,7 @@ class CBackend: raise ValueError("Problem with Conditional inside vectorized loop - use vec_any or vec_all") condition_expr = self.sympy_printer.doprint(node.condition_expr) true_block = self._print_Block(node.true_block) - result = "if (%s)\n%s " % (condition_expr, true_block) + result = f"if ({condition_expr})\n{true_block} " if node.false_block: false_block = self._print_Block(node.false_block) result += "else " + false_block @@ -304,7 +304,7 @@ class CustomSympyPrinter(CCodePrinter): if expr.exp.is_integer and expr.exp.is_number and 0 < expr.exp < 8: return "(" + self._print(sp.Mul(*[expr.base] * expr.exp, evaluate=False)) + ")" elif expr.exp.is_integer and expr.exp.is_number and - 8 < expr.exp < 0: - return "1 / ({})".format(self._print(sp.Mul(*[expr.base] * (-expr.exp), evaluate=False))) + return f"1 / ({self._print(sp.Mul(*([expr.base] * -expr.exp), evaluate=False))})" else: return super(CustomSympyPrinter, self)._print_Pow(expr) @@ -334,7 +334,7 @@ class CustomSympyPrinter(CCodePrinter): return expr.to_c(self._print) if isinstance(expr, reinterpret_cast_func): arg, data_type = expr.args - return "*((%s)(& %s))" % (PointerType(data_type, restrict=False), self._print(arg)) + return f"*(({PointerType(data_type, restrict=False)})(& {self._print(arg)}))" elif isinstance(expr, address_of): assert len(expr.args) == 1, "address_of must only have one argument" return "&(%s)" % self._print(expr.args[0]) @@ -343,21 +343,21 @@ class CustomSympyPrinter(CCodePrinter): if isinstance(arg, sp.Number): return self._typed_number(arg, data_type) else: - return "((%s)(%s))" % (data_type, self._print(arg)) + return f"(({data_type})({self._print(arg)}))" elif isinstance(expr, fast_division): - return "({})".format(self._print(expr.args[0] / expr.args[1])) + return f"({self._print(expr.args[0] / expr.args[1])})" elif isinstance(expr, fast_sqrt): - return "({})".format(self._print(sp.sqrt(expr.args[0]))) + return f"({self._print(sp.sqrt(expr.args[0]))})" elif isinstance(expr, vec_any) or isinstance(expr, vec_all): return self._print(expr.args[0]) elif isinstance(expr, fast_inv_sqrt): - return "({})".format(self._print(1 / sp.sqrt(expr.args[0]))) + return f"({self._print(1 / sp.sqrt(expr.args[0]))})" elif expr.func in infix_functions: - return "(%s %s %s)" % (self._print(expr.args[0]), infix_functions[expr.func], self._print(expr.args[1])) + return f"({self._print(expr.args[0])} {infix_functions[expr.func]} {self._print(expr.args[1])})" elif expr.func == int_power_of_2: return "(1 << (%s))" % (self._print(expr.args[0])) elif expr.func == int_div: - return "((%s) / (%s))" % (self._print(expr.args[0]), self._print(expr.args[1])) + return f"(({self._print(expr.args[0])}) / ({self._print(expr.args[1])}))" else: return super(CustomSympyPrinter, self)._print_Function(expr) @@ -408,14 +408,14 @@ class VectorizedCustomSympyPrinter(CustomSympyPrinter): result = self.instruction_set['/'].format(self._print(expr.args[0]), self._print(expr.args[1])) return result elif expr.func == fast_sqrt: - return "({})".format(self._print(sp.sqrt(expr.args[0]))) + return f"({self._print(sp.sqrt(expr.args[0]))})" elif expr.func == fast_inv_sqrt: result = self._scalarFallback('_print_Function', expr) if not result: if self.instruction_set['rsqrt']: return self.instruction_set['rsqrt'].format(self._print(expr.args[0])) else: - return "({})".format(self._print(1 / sp.sqrt(expr.args[0]))) + return f"({self._print(1 / sp.sqrt(expr.args[0]))})" elif isinstance(expr, vec_any): expr_type = get_type_of_expression(expr.args[0]) if type(expr_type) is not VectorType: diff --git a/pystencils/backends/dot.py b/pystencils/backends/dot.py index 64610c47..ec13d9e8 100644 --- a/pystencils/backends/dot.py +++ b/pystencils/backends/dot.py @@ -52,7 +52,7 @@ class DotPrinter(Printer): def __shortened(node): from pystencils.astnodes import LoopOverCoordinate, KernelFunction, SympyAssignment, Block, Conditional if isinstance(node, LoopOverCoordinate): - return "Loop over dim %d" % (node.coordinate_to_loop_over,) + return f"Loop over dim {node.coordinate_to_loop_over:d}" elif isinstance(node, KernelFunction): params = node.get_parameters() param_names = [p.field_name for p in params if p.is_field_pointer] @@ -65,7 +65,7 @@ def __shortened(node): elif isinstance(node, Conditional): return repr(node) else: - raise NotImplementedError("Cannot handle node type %s" % (type(node),)) + raise NotImplementedError(f"Cannot handle node type {type(node)}") def print_dot(node, view=False, short=False, **kwargs): diff --git a/pystencils/backends/simd_instruction_sets.py b/pystencils/backends/simd_instruction_sets.py index f72b0fec..5b84d3ad 100644 --- a/pystencils/backends/simd_instruction_sets.py +++ b/pystencils/backends/simd_instruction_sets.py @@ -31,7 +31,7 @@ def get_vector_instruction_set(data_type='double', instruction_set='avx'): 'stream': 'stream[0,1]', } for comparison_op, constant in comparisons.items(): - base_names[comparison_op] = 'cmp[0, 1, %s]' % (constant,) + base_names[comparison_op] = f'cmp[0, 1, {constant}]' headers = { 'avx512': ['<immintrin.h>'], @@ -92,10 +92,10 @@ def get_vector_instruction_set(data_type='double', instruction_set='avx'): result['rsqrt'] = None bit_width = result['width'] * (64 if data_type == 'double' else 32) - result['double'] = "__m%dd" % (bit_width,) - result['float'] = "__m%d" % (bit_width,) - result['int'] = "__m%di" % (bit_width,) - result['bool'] = "__m%dd" % (bit_width,) + result['double'] = f"__m{bit_width:d}d" + result['float'] = f"__m{bit_width:d}" + result['int'] = f"__m{bit_width:d}i" + result['bool'] = f"__m{bit_width:d}d" result['headers'] = headers[instruction_set] result['any'] = "%s_movemask_%s({0}) > 0" % (pre, suf) @@ -109,7 +109,7 @@ def get_vector_instruction_set(data_type='double', instruction_set='avx'): result['all'] = '_kortestc_mask%d_u8({0}, {0})' % (size, ) result['blendv'] = '%s_mask_blend_%s({2}, {0}, {1})' % (pre, suf) result['rsqrt'] = "_mm512_rsqrt14_%s({0})" % (suf,) - result['bool'] = "__mmask%d" % (size,) + result['bool'] = f"__mmask{size:d}" if instruction_set == 'avx' and data_type == 'float': result['rsqrt'] = "_mm256_rsqrt_ps({0})" diff --git a/pystencils/boundaries/boundaryhandling.py b/pystencils/boundaries/boundaryhandling.py index d258de4b..0d4f2789 100644 --- a/pystencils/boundaries/boundaryhandling.py +++ b/pystencils/boundaries/boundaryhandling.py @@ -55,13 +55,13 @@ class FlagInterface: self._used_flags.add(flag) assert self._is_power_of_2(flag) return flag - raise ValueError("All available {} flags are reserved".format(self.max_bits)) + raise ValueError(f"All available {self.max_bits} flags are reserved") def reserve_flag(self, flag): assert self._is_power_of_2(flag) flag = self.dtype(flag) if flag in self._used_flags: - raise ValueError("The flag {flag} is already reserved".format(flag=flag)) + raise ValueError(f"The flag {flag} is already reserved") self._used_flags.add(flag) return flag @@ -373,12 +373,12 @@ class BoundaryDataSetter: def __setitem__(self, key, value): if key not in self.boundary_data_names: - raise KeyError("Invalid boundary data name %s. Allowed are %s" % (key, self.boundary_data_names)) + raise KeyError(f"Invalid boundary data name {key}. Allowed are {self.boundary_data_names}") self.index_array[key] = value def __getitem__(self, item): if item not in self.boundary_data_names: - raise KeyError("Invalid boundary data name %s. Allowed are %s" % (item, self.boundary_data_names)) + raise KeyError(f"Invalid boundary data name {item}. Allowed are {self.boundary_data_names}") return self.index_array[item] @@ -418,7 +418,7 @@ class BoundaryOffsetInfo(CustomCodeNode): @staticmethod def _offset_symbols(dim): - return [TypedSymbol("c%s" % (d,), create_type(np.int64)) for d in ['x', 'y', 'z'][:dim]] + return [TypedSymbol(f"c{d}", create_type(np.int64)) for d in ['x', 'y', 'z'][:dim]] INV_DIR_SYMBOL = TypedSymbol("invdir", "int") diff --git a/pystencils/cpu/cpujit.py b/pystencils/cpu/cpujit.py index b69de887..aae931d6 100644 --- a/pystencils/cpu/cpujit.py +++ b/pystencils/cpu/cpujit.py @@ -337,7 +337,7 @@ def create_function_boilerplate_code(parameter_info, name, insert_checks=True): field = param.fields[0] pre_call_code += template_extract_array.format(name=field.name) post_call_code += template_release_buffer.format(name=field.name) - parameters.append("({dtype} *)buffer_{name}.buf".format(dtype=str(field.dtype), name=field.name)) + parameters.append(f"({str(field.dtype)} *)buffer_{field.name}.buf") if insert_checks: np_dtype = field.dtype.numpy_dtype @@ -349,12 +349,12 @@ def create_function_boilerplate_code(parameter_info, name, insert_checks=True): pre_call_code += template_check_array.format(cond=dtype_cond, what="data type", name=field.name, expected=str(field.dtype.numpy_dtype)) - item_size_cond = "buffer_{name}.itemsize == {size}".format(name=field.name, size=item_size) + item_size_cond = f"buffer_{field.name}.itemsize == {item_size}" pre_call_code += template_check_array.format(cond=item_size_cond, what="itemsize", name=field.name, expected=item_size) if field.has_fixed_shape: - shape_cond = ["buffer_{name}.shape[{i}] == {s}".format(s=s, name=field.name, i=i) + shape_cond = [f"buffer_{field.name}.shape[{i}] == {s}" for i, s in enumerate(field.spatial_shape)] shape_cond = " && ".join(shape_cond) pre_call_code += template_check_array.format(cond=shape_cond, what="shape", name=field.name, @@ -377,7 +377,7 @@ def create_function_boilerplate_code(parameter_info, name, insert_checks=True): parameters.append("buffer_{name}.strides[{i}] / {bytes}".format(bytes=item_size, i=param.symbol.coordinate, name=field.name)) elif param.is_field_shape: - parameters.append("buffer_{name}.shape[{i}]".format(i=param.symbol.coordinate, name=param.field_name)) + parameters.append(f"buffer_{param.field_name}.shape[{param.symbol.coordinate}]") else: extract_function, target_type = type_mapping[param.symbol.dtype.numpy_dtype.type] pre_call_code += template_extract_scalar.format(extract_function=extract_function, target_type=target_type, @@ -455,8 +455,8 @@ class ExtensionModuleCode: includes = "\n".join(["#include %s" % (include_file,) for include_file in header_list]) print(includes, file=file) print("\n", file=file) - print("#define RESTRICT %s" % (restrict_qualifier,), file=file) - print("#define FUNC_PREFIX %s" % (function_prefix,), file=file) + print(f"#define RESTRICT {restrict_qualifier}", file=file) + print(f"#define FUNC_PREFIX {function_prefix}", file=file) print("\n", file=file) for ast, name in zip(self._ast_nodes, self._function_names): diff --git a/pystencils/cpu/kernelcreation.py b/pystencils/cpu/kernelcreation.py index fc6765e5..c61a3f90 100644 --- a/pystencils/cpu/kernelcreation.py +++ b/pystencils/cpu/kernelcreation.py @@ -128,7 +128,7 @@ def create_indexed_kernel(assignments: AssignmentOrAstNodeList, index_fields, fu rhs = idx_field[0](name) lhs = TypedSymbol(name, BasicType(data_type.get_element_type(name))) return SympyAssignment(lhs, rhs) - raise ValueError("Index %s not found in any of the passed index fields" % (name,)) + raise ValueError(f"Index {name} not found in any of the passed index fields") coordinate_symbol_assignments = [get_coordinate_symbol_assignment(n) for n in coordinate_names[:spatial_coordinates]] @@ -170,7 +170,7 @@ def add_openmp(ast_node, schedule="static", num_threads=True, collapse=None, ass assert type(ast_node) is ast.KernelFunction body = ast_node.body - threads_clause = "" if num_threads and isinstance(num_threads, bool) else " num_threads(%s)" % (num_threads,) + threads_clause = "" if num_threads and isinstance(num_threads, bool) else f" num_threads({num_threads})" wrapper_block = ast.PragmaBlock('#pragma omp parallel' + threads_clause, body.take_child_nodes()) body.append(wrapper_block) @@ -201,7 +201,7 @@ def add_openmp(ast_node, schedule="static", num_threads=True, collapse=None, ass except TypeError: pass - prefix = "#pragma omp for schedule(%s)" % (schedule,) + prefix = f"#pragma omp for schedule({schedule})" if collapse: - prefix += " collapse(%d)" % (collapse, ) + prefix += f" collapse({collapse:d})" loop_to_parallelize.prefix_lines.append(prefix) diff --git a/pystencils/cpu/msvc_detection.py b/pystencils/cpu/msvc_detection.py index 94b2bcf5..436880e8 100644 --- a/pystencils/cpu/msvc_detection.py +++ b/pystencils/cpu/msvc_detection.py @@ -71,7 +71,7 @@ def normalize_msvc_version(version): def get_environment_from_vc_vars_file(vc_vars_file, arch): out = subprocess.check_output( - 'cmd /u /c "{}" {} && set'.format(vc_vars_file, arch), + f'cmd /u /c "{vc_vars_file}" {arch} && set', stderr=subprocess.STDOUT, ).decode('utf-16le', errors='replace') @@ -81,7 +81,7 @@ def get_environment_from_vc_vars_file(vc_vars_file, arch): def get_vc_vars_path_via_environment_variable(version_nr): # noinspection SpellCheckingInspection - environment_var_name = 'VS%d0COMNTOOLS' % (version_nr,) + environment_var_name = f'VS{version_nr:d}0COMNTOOLS' vc_path = os.environ[environment_var_name] path = os.path.join(vc_path, '..', '..', 'VC', 'vcvarsall.bat') return os.path.abspath(path) diff --git a/pystencils/cpu/vectorization.py b/pystencils/cpu/vectorization.py index 6bf3a26d..3b71a6d9 100644 --- a/pystencils/cpu/vectorization.py +++ b/pystencils/cpu/vectorization.py @@ -116,7 +116,7 @@ def vectorize_inner_loops_and_adapt_load_stores(ast_node, vector_width, assume_a break typed_symbol = base.label assert type(typed_symbol.dtype) is PointerType, \ - "Type of access is {}, {}".format(typed_symbol.dtype, indexed) + f"Type of access is {typed_symbol.dtype}, {indexed}" vec_type = VectorType(typed_symbol.dtype.base_type, vector_width) use_aligned_access = aligned_access and assume_aligned diff --git a/pystencils/data_types.py b/pystencils/data_types.py index 08c1da1c..142eb489 100644 --- a/pystencils/data_types.py +++ b/pystencils/data_types.py @@ -274,7 +274,7 @@ def ctypes_from_llvm(data_type): elif data_type.width == 64: return ctypes.c_int64 else: - raise ValueError("Int width %d is not supported" % data_type.width) + raise ValueError(f"Int width {data_type.width:d} is not supported") elif isinstance(data_type, ir.FloatType): return ctypes.c_float elif isinstance(data_type, ir.DoubleType): @@ -282,7 +282,7 @@ def ctypes_from_llvm(data_type): elif isinstance(data_type, ir.VoidType): return None # Void type is not supported by ctypes else: - raise NotImplementedError('Data type %s of %s is not supported yet' % (type(data_type), data_type)) + raise NotImplementedError(f'Data type {type(data_type)} of {data_type} is not supported yet') def to_llvm_type(data_type): @@ -426,14 +426,14 @@ class BasicType(Type): return 'float' elif name.startswith('int'): width = int(name[len("int"):]) - return "int%d_t" % (width,) + return f"int{width:d}_t" elif name.startswith('uint'): width = int(name[len("uint"):]) - return "uint%d_t" % (width,) + return f"uint{width:d}_t" elif name == 'bool': return 'bool' else: - raise NotImplementedError("Can map numpy to C name for %s" % (name,)) + raise NotImplementedError(f"Can map numpy to C name for {name}") def __init__(self, dtype, const=False): self.const = const @@ -521,7 +521,7 @@ class VectorType(Type): def __str__(self): if self.instruction_set is None: - return "%s[%d]" % (self.base_type, self.width) + return f"{self.base_type}[{self.width:d}]" else: if self.base_type == create_type("int64"): return self.instruction_set['int'] diff --git a/pystencils/datahandling/parallel_datahandling.py b/pystencils/datahandling/parallel_datahandling.py index 4e8d965d..bb5340d9 100644 --- a/pystencils/datahandling/parallel_datahandling.py +++ b/pystencils/datahandling/parallel_datahandling.py @@ -331,7 +331,7 @@ class ParallelDataHandling(DataHandling): ghost_layers = 0 if ghost_layers is True: ghost_layers = min(self.ghost_layers_of_field(n) for n in data_names) - file_name = "%s_%02d" % (file_name, ParallelDataHandling.VTK_COUNTER) + file_name = f"{file_name}_{ParallelDataHandling.VTK_COUNTER:02d}" ParallelDataHandling.VTK_COUNTER += 1 output = wlb.vtk.makeOutput(self.blocks, file_name, ghostLayers=ghost_layers) for n in data_names: @@ -379,7 +379,7 @@ class ParallelDataHandling(DataHandling): if not os.path.exists(directory): os.mkdir(directory) if os.path.isfile(directory): - raise RuntimeError("Trying to save to {}, but file exists already".format(directory)) + raise RuntimeError(f"Trying to save to {directory}, but file exists already") for field_name, data_name in self._field_name_to_cpu_data_name.items(): self.blocks.writeBlockData(data_name, os.path.join(directory, field_name + ".dat")) diff --git a/pystencils/datahandling/serial_datahandling.py b/pystencils/datahandling/serial_datahandling.py index 8c79a093..aeef0b4a 100644 --- a/pystencils/datahandling/serial_datahandling.py +++ b/pystencils/datahandling/serial_datahandling.py @@ -331,7 +331,7 @@ class SerialDataHandling(DataHandling): from pystencils.datahandling.vtk import image_to_vtk def writer(step): - full_file_name = "%s_%08d" % (file_name, step,) + full_file_name = f"{file_name}_{step:08d}" cell_data = {} for name in data_names: field = self._get_field_with_given_number_of_ghost_layers(name, ghost_layers) @@ -348,7 +348,7 @@ class SerialDataHandling(DataHandling): cell_data[name] = tuple(field) else: for i in range(values_per_cell): - cell_data["%s[%d]" % (name, i)] = np.ascontiguousarray(field[..., i]) + cell_data[f"{name}[{i:d}]"] = np.ascontiguousarray(field[..., i]) else: raise NotImplementedError("VTK export for fields with more than one index " "coordinate not implemented") @@ -359,7 +359,7 @@ class SerialDataHandling(DataHandling): from pystencils.datahandling.vtk import image_to_vtk def writer(step): - full_file_name = "%s_%08d" % (file_name, step,) + full_file_name = f"{file_name}_{step:08d}" field = self._get_field_with_given_number_of_ghost_layers(data_name, ghost_layers) if self.dim == 2: field = field[:, :, np.newaxis] @@ -405,7 +405,7 @@ class SerialDataHandling(DataHandling): file_contents = np.load(file) for arr_name, arr_contents in self.cpu_arrays.items(): if arr_name not in file_contents: - print("Skipping read data {} because there is no data with this name in data handling".format(arr_name)) + print(f"Skipping read data {arr_name} because there is no data with this name in data handling") continue if file_contents[arr_name].shape != arr_contents.shape: print("Skipping read data {} because shapes don't match. " diff --git a/pystencils/display_utils.py b/pystencils/display_utils.py index 8cdaa482..d06238e6 100644 --- a/pystencils/display_utils.py +++ b/pystencils/display_utils.py @@ -29,7 +29,7 @@ def highlight_cpp(code: str): from pygments.lexers import CppLexer css = HtmlFormatter().get_style_defs('.highlight') - css_tag = "<style>{css}</style>".format(css=css) + css_tag = f"<style>{css}</style>" display(HTML(css_tag)) return HTML(highlight(code, CppLexer(), HtmlFormatter())) diff --git a/pystencils/fd/derivative.py b/pystencils/fd/derivative.py index 7acd2450..f3157279 100644 --- a/pystencils/fd/derivative.py +++ b/pystencils/fd/derivative.py @@ -109,7 +109,7 @@ class Diff(sp.Expr): return result def __str__(self): - return "D(%s)" % self.arg + return f"D({self.arg})" class DiffOperator(sp.Expr): diff --git a/pystencils/fd/finitedifferences.py b/pystencils/fd/finitedifferences.py index d5bce66e..edebe55c 100644 --- a/pystencils/fd/finitedifferences.py +++ b/pystencils/fd/finitedifferences.py @@ -188,7 +188,7 @@ class Advection(sp.Function): return self.scalar.spatial_dimensions def _latex(self, printer): - name_suffix = "_%s" % self.scalar_index if self.scalar_index is not None else "" + name_suffix = f"_{self.scalar_index}" if self.scalar_index is not None else "" if isinstance(self.vector, Field): return r"\nabla \cdot(%s %s)" % (printer.doprint(sp.Symbol(self.vector.name)), printer.doprint(sp.Symbol(self.scalar.name + name_suffix))) @@ -235,7 +235,7 @@ class Diffusion(sp.Function): return self.scalar.spatial_dimensions def _latex(self, printer): - name_suffix = "_%s" % self.scalar_index if self.scalar_index is not None else "" + name_suffix = f"_{self.scalar_index}" if self.scalar_index is not None else "" coeff = self.diffusion_coeff diff_coeff = sp.Symbol(coeff.name) if isinstance(coeff, Field) else coeff return r"div(%s \nabla %s)" % (printer.doprint(diff_coeff), @@ -268,7 +268,7 @@ class Transient(sp.Function): return None if len(self.args) <= 1 else int(self.args[1]) def _latex(self, printer): - name_suffix = "_%s" % self.scalar_index if self.scalar_index is not None else "" + name_suffix = f"_{self.scalar_index}" if self.scalar_index is not None else "" return r"\partial_t %s" % (printer.doprint(sp.Symbol(self.scalar.name + name_suffix)),) @@ -287,9 +287,9 @@ def grad(var, dim=3): dim: dimension (length) of the gradient vector """ if hasattr(var, "__getitem__"): - return [[sp.Symbol("%s^Delta^%d" % (v.name, i)) for v in var] for i in range(dim)] + return [[sp.Symbol(f"{v.name}^Delta^{i:d}") for v in var] for i in range(dim)] else: - return [sp.Symbol("%s^Delta^%d" % (var.name, i)) for i in range(dim)] + return [sp.Symbol(f"{var.name}^Delta^{i:d}") for i in range(dim)] def discretize_center(term, symbols_to_field_dict, dx, dim=3): diff --git a/pystencils/field.py b/pystencils/field.py index b6437a97..7f7946c0 100644 --- a/pystencils/field.py +++ b/pystencils/field.py @@ -458,7 +458,7 @@ class Field(AbstractField): offset_name = hashlib.md5(pickle.dumps(offsets_and_index)).hexdigest()[:12] superscript = None - symbol_name = "%s_%s" % (field_name, offset_name) + symbol_name = f"{field_name}_{offset_name}" if superscript is not None: symbol_name += "^" + superscript @@ -605,9 +605,9 @@ class Field(AbstractField): n = self._field.latex_name if self._field.latex_name else self._field.name offset_str = ",".join([sp.latex(o) for o in self.offsets]) if self.is_absolute_access: - offset_str = "\\mathbf{}".format(offset_str) + offset_str = f"\\mathbf{offset_str}" elif self.field.spatial_dimensions > 1: - offset_str = "({})".format(offset_str) + offset_str = f"({offset_str})" if self.index and self.index != (0,): return "{{%s}_{%s}^{%s}}" % (n, offset_str, self.index if len(self.index) > 1 else self.index[0]) @@ -618,11 +618,11 @@ class Field(AbstractField): n = self._field.latex_name if self._field.latex_name else self._field.name offset_str = ",".join([sp.latex(o) for o in self.offsets]) if self.is_absolute_access: - offset_str = "[abs]{}".format(offset_str) + offset_str = f"[abs]{offset_str}" if self.index and self.index != (0,): - return "%s[%s](%s)" % (n, offset_str, self.index if len(self.index) > 1 else self.index[0]) + return f"{n}[{offset_str}]({(self.index if len(self.index) > 1 else self.index[0])})" else: - return "%s[%s]" % (n, offset_str) + return f"{n}[{offset_str}]" def get_layout_from_strides(strides: Sequence[int], index_dimension_ids: Optional[List[int]] = None): diff --git a/pystencils/gpucuda/indexing.py b/pystencils/gpucuda/indexing.py index f6f1fbe8..bd210927 100644 --- a/pystencils/gpucuda/indexing.py +++ b/pystencils/gpucuda/indexing.py @@ -289,7 +289,7 @@ def indexing_creator_from_params(gpu_indexing, gpu_indexing_params): elif gpu_indexing == 'line': indexing_creator = LineIndexing else: - raise ValueError("Unknown GPU indexing %s. Valid values are 'block' and 'line'" % (gpu_indexing,)) + raise ValueError(f"Unknown GPU indexing {gpu_indexing}. Valid values are 'block' and 'line'") if gpu_indexing_params: indexing_creator = partial(indexing_creator, **gpu_indexing_params) return indexing_creator diff --git a/pystencils/gpucuda/kernelcreation.py b/pystencils/gpucuda/kernelcreation.py index ff821070..30687260 100644 --- a/pystencils/gpucuda/kernelcreation.py +++ b/pystencils/gpucuda/kernelcreation.py @@ -110,7 +110,7 @@ def created_indexed_cuda_kernel(assignments, index_fields, function_name="kernel rhs = ind_f[0](name) lhs = TypedSymbol(name, BasicType(data_type.get_element_type(name))) return SympyAssignment(lhs, rhs) - raise ValueError("Index %s not found in any of the passed index fields" % (name,)) + raise ValueError(f"Index {name} not found in any of the passed index fields") coordinate_symbol_assignments = [get_coordinate_symbol_assignment(n) for n in coordinate_names[:spatial_coordinates]] diff --git a/pystencils/integer_set_analysis.py b/pystencils/integer_set_analysis.py index 3560ba6c..6859e9bd 100644 --- a/pystencils/integer_set_analysis.py +++ b/pystencils/integer_set_analysis.py @@ -36,13 +36,12 @@ def isl_iteration_set(node: ast.Node): loop_start_str = remove_brackets(str(loop.start)) loop_stop_str = remove_brackets(str(loop.stop)) ctr_name = loop.loop_counter_name - set_string_description = "{} >= {} and {} < {}".format(ctr_name, loop_start_str, ctr_name, loop_stop_str) + set_string_description = f"{ctr_name} >= {loop_start_str} and {ctr_name} < {loop_stop_str}" conditions.append(remove_brackets(set_string_description)) symbol_names = ','.join(degrees_of_freedom) condition_str = ' and '.join(conditions) - set_description = "{{ [{symbol_names}] : {condition_str} }}".format(symbol_names=symbol_names, - condition_str=condition_str) + set_description = f"{{ [{symbol_names}] : {condition_str} }}" return degrees_of_freedom, isl.BasicSet(set_description) diff --git a/pystencils/jupyter.py b/pystencils/jupyter.py index f977e87c..48041a77 100644 --- a/pystencils/jupyter.py +++ b/pystencils/jupyter.py @@ -44,17 +44,10 @@ def log_progress(sequence, every=None, size=None, name='Items'): for index, record in enumerate(sequence, 1): if index == 1 or index % every == 0: if is_iterator: - label.value = '{name}: {index} / ?'.format( - name=name, - index=index - ) + label.value = f'{name}: {index} / ?' else: progress.value = index - label.value = u'{name}: {index} / {size}'.format( - name=name, - index=index, - size=size - ) + label.value = f'{name}: {index} / {size}' yield record except: progress.bar_style = 'danger' diff --git a/pystencils/kerncraft_coupling/kerncraft_interface.py b/pystencils/kerncraft_coupling/kerncraft_interface.py index 37a5109d..bd177149 100644 --- a/pystencils/kerncraft_coupling/kerncraft_interface.py +++ b/pystencils/kerncraft_coupling/kerncraft_interface.py @@ -140,7 +140,7 @@ class PyStencilsKerncraftKernel(KernelCode): """ code = generate_benchmark(self.kernel_ast, likwid=type_ == 'likwid', openmp=openmp) if as_filename: - fp, already_available = self._get_intermediate_file('kernel_{}.c'.format(type_), + fp, already_available = self._get_intermediate_file(f'kernel_{type_}.c', machine_and_compiler_dependent=False) if not already_available: fp.write(code) diff --git a/pystencils/kernelcreation.py b/pystencils/kernelcreation.py index ade980f5..4bd07dc8 100644 --- a/pystencils/kernelcreation.py +++ b/pystencils/kernelcreation.py @@ -102,7 +102,7 @@ def create_kernel(assignments, target='cpu', data_type="double", iteration_slice skip_independence_check=skip_independence_check) return ast else: - raise ValueError("Unknown target %s. Has to be one of 'cpu', 'gpu' or 'llvm' " % (target,)) + raise ValueError(f"Unknown target {target}. Has to be one of 'cpu', 'gpu' or 'llvm' ") def create_indexed_kernel(assignments, index_fields, target='cpu', data_type="double", coordinate_names=('x', 'y', 'z'), @@ -163,7 +163,7 @@ def create_indexed_kernel(assignments, index_fields, target='cpu', data_type="do coordinate_names=coordinate_names, indexing_creator=idx_creator) return ast else: - raise ValueError("Unknown target %s. Has to be either 'cpu' or 'gpu'" % (target,)) + raise ValueError(f"Unknown target {target}. Has to be either 'cpu' or 'gpu'") def create_staggered_kernel(staggered_field, expressions, subexpressions=(), target='cpu', diff --git a/pystencils/kernelparameters.py b/pystencils/kernelparameters.py index 11d30e09..07d3198f 100644 --- a/pystencils/kernelparameters.py +++ b/pystencils/kernelparameters.py @@ -29,7 +29,7 @@ class FieldStrideSymbol(TypedSymbol): return obj def __new_stage2__(cls, field_name, coordinate): - name = "_stride_{name}_{i}".format(name=field_name, i=coordinate) + name = f"_stride_{field_name}_{coordinate}" obj = super(FieldStrideSymbol, cls).__xnew__(cls, name, STRIDE_DTYPE) obj.field_name = field_name obj.coordinate = coordinate @@ -54,7 +54,7 @@ class FieldShapeSymbol(TypedSymbol): def __new_stage2__(cls, field_names, coordinate): names = "_".join([field_name for field_name in field_names]) - name = "_size_{names}_{i}".format(names=names, i=coordinate) + name = f"_size_{names}_{coordinate}" obj = super(FieldShapeSymbol, cls).__xnew__(cls, name, SHAPE_DTYPE) obj.field_names = tuple(field_names) obj.coordinate = coordinate @@ -77,7 +77,7 @@ class FieldPointerSymbol(TypedSymbol): return obj def __new_stage2__(cls, field_name, field_dtype, const): - name = "_data_{name}".format(name=field_name) + name = f"_data_{field_name}" dtype = PointerType(get_base_type(field_dtype), const=const, restrict=True) obj = super(FieldPointerSymbol, cls).__xnew__(cls, name, dtype) obj.field_name = field_name diff --git a/pystencils/llvm/llvm.py b/pystencils/llvm/llvm.py index cf2207c0..9fc9edc8 100644 --- a/pystencils/llvm/llvm.py +++ b/pystencils/llvm/llvm.py @@ -69,7 +69,7 @@ class LLVMPrinter(Printer): # look up parameter with name s val = self.func_arg_map.get(s.name) if not val: - raise LookupError("Symbol not found: %s" % s) + raise LookupError(f"Symbol not found: {s}") return val def _print_Pow(self, expr): diff --git a/pystencils/placeholder_function.py b/pystencils/placeholder_function.py index 18a0574b..8b8aa6ed 100644 --- a/pystencils/placeholder_function.py +++ b/pystencils/placeholder_function.py @@ -34,7 +34,7 @@ def to_placeholder_function(expr, name): """ symbols = list(expr.atoms(sp.Symbol)) symbols.sort(key=lambda e: e.name) - derivative_symbols = [sp.Symbol("_d{}_d{}".format(name, s.name)) for s in symbols] + derivative_symbols = [sp.Symbol(f"_d{name}_d{s.name}") for s in symbols] derivatives = [sp.diff(expr, s) for s in symbols] assignments = [Assignment(sp.Symbol(name), expr)] diff --git a/pystencils/runhelper/parameterstudy.py b/pystencils/runhelper/parameterstudy.py index 0ad27fd5..d1c3d08c 100644 --- a/pystencils/runhelper/parameterstudy.py +++ b/pystencils/runhelper/parameterstudy.py @@ -154,7 +154,7 @@ class ParameterStudy: def next_scenario(self, received_json_data): client_name = received_json_data['client_name'] if len(self.runs) > 0: - run_status = "%d/%d" % (len(self.finished_runs), len(self.all_runs)) + run_status = f"{len(self.finished_runs):d}/{len(self.all_runs):d}" work_status = "%d/%d" % (sum(r.weight for r in self.finished_runs), sum(r.weight for r in self.all_runs)) format_args = { @@ -215,7 +215,7 @@ class ParameterStudy: def log_message(self, fmt, *args): return - print("Listening to connections on {}:{}. Scenarios to simulate: {}".format(ip, port, len(filtered_runs))) + print(f"Listening to connections on {ip}:{port}. Scenarios to simulate: {len(filtered_runs)}") server = HTTPServer((ip, port), ParameterStudyServer) while len(ParameterStudyServer.currently_running) > 0 or len(ParameterStudyServer.runs) > 0: server.handle_request() @@ -241,7 +241,7 @@ class ParameterStudy: from urllib.error import URLError import time parameter_update = {} if parameter_update is None else parameter_update - url = "http://{}:{}".format(server, port) + url = f"http://{server}:{port}" client_name = client_name.format(hostname=socket.gethostname(), pid=os.getpid()) start_time = time.time() while True: @@ -265,7 +265,7 @@ class ParameterStudy: 'client_name': client_name} urlopen(url + '/result', data=json.dumps(answer).encode()) except URLError: - print("Cannot connect to server {} retrying in 5 seconds...".format(url)) + print(f"Cannot connect to server {url} retrying in 5 seconds...") sleep(5) def run_from_command_line(self, argv: Optional[Sequence[str]] = None) -> None: diff --git a/pystencils/simp/assignment_collection.py b/pystencils/simp/assignment_collection.py index c5a18379..33e7e662 100644 --- a/pystencils/simp/assignment_collection.py +++ b/pystencils/simp/assignment_collection.py @@ -337,10 +337,10 @@ class AssignmentCollection: def __str__(self): result = "Subexpressions:\n" for eq in self.subexpressions: - result += "\t{eq}\n".format(eq=eq) + result += f"\t{eq}\n" result += "Main Assignments:\n" for eq in self.main_assignments: - result += "\t{eq}\n".format(eq=eq) + result += f"\t{eq}\n" return result def __iter__(self): @@ -402,6 +402,6 @@ class SymbolGen: return self def __next__(self): - name = "{}_{}".format(self._symbol, self._ctr) + name = f"{self._symbol}_{self._ctr}" self._ctr += 1 return sp.Symbol(name) diff --git a/pystencils/simp/simplificationstrategy.py b/pystencils/simp/simplificationstrategy.py index d9bcafa4..53c860e5 100644 --- a/pystencils/simp/simplificationstrategy.py +++ b/pystencils/simp/simplificationstrategy.py @@ -129,7 +129,7 @@ class SimplificationStrategy: def _repr_html_(self): def print_assignment_collection(title, c): - text = '<h5 style="padding-bottom:10px">%s</h5> <div style="padding-left:20px;">' % (title, ) + text = f'<h5 style="padding-bottom:10px">{title}</h5> <div style="padding-left:20px;">' if self.restrict_symbols: text += "\n".join(["$$" + sp.latex(e) + '$$' for e in c.new_filtered(self.restrict_symbols).main_assignments]) @@ -151,5 +151,5 @@ class SimplificationStrategy: def __repr__(self): result = "Simplification Strategy:\n" for t in self._rules: - result += " - %s\n" % (t.__name__,) + result += f" - {t.__name__}\n" return result diff --git a/pystencils/stencil.py b/pystencils/stencil.py index f2201ccc..9e6d1cba 100644 --- a/pystencils/stencil.py +++ b/pystencils/stencil.py @@ -211,7 +211,7 @@ def offset_component_to_direction_string(coordinate_id: int, value: int) -> str: else: result = name_components[coordinate_id][1] if abs(value) > 1: - result = "%d%s" % (abs(value), result) + result = f"{abs(value):d}{result}" return result @@ -389,7 +389,7 @@ def plot_3d_slicing(stencil, slice_axis=2, figure=None, data=None, **kwargs): for i in range(3): plot_2d(splitted_directions[i], axes=axes[i], data=splitted_data[i], **kwargs) for i in [-1, 0, 1]: - axes[i + 1].set_title("Cut at %s=%d" % (axes_names[slice_axis], i), y=1.08) + axes[i + 1].set_title(f"Cut at {axes_names[slice_axis]}={i:d}", y=1.08) def plot_3d(stencil, figure=None, axes=None, data=None, textsize='8'): diff --git a/pystencils/transformations.py b/pystencils/transformations.py index 60a22d81..3f7a7336 100644 --- a/pystencils/transformations.py +++ b/pystencils/transformations.py @@ -134,7 +134,7 @@ def get_common_shape(field_set): fixed_field_names = ",".join([f.name for f in field_set if f.has_fixed_shape]) var_field_names = ",".join([f.name for f in field_set if not f.has_fixed_shape]) msg = "Mixing fixed-shaped and variable-shape fields in a single kernel is not possible\n" - msg += "Variable shaped: %s \nFixed shaped: %s" % (var_field_names, fixed_field_names) + msg += f"Variable shaped: {var_field_names} \nFixed shaped: {fixed_field_names}" raise ValueError(msg) shape_set = set([f.spatial_shape for f in field_set]) @@ -239,12 +239,12 @@ def create_intermediate_base_pointer(field_access, coordinates, previous_ptr): if coordinate_id < field.spatial_dimensions: offset += field.strides[coordinate_id] * field_access.offsets[coordinate_id] if type(field_access.offsets[coordinate_id]) is int: - name += "_%d%d" % (coordinate_id, field_access.offsets[coordinate_id]) + name += f"_{coordinate_id:d}{field_access.offsets[coordinate_id]:d}" else: list_to_hash.append(field_access.offsets[coordinate_id]) else: if type(coordinate_value) is int: - name += "_%d%d" % (coordinate_id, coordinate_value) + name += f"_{coordinate_id:d}{coordinate_value:d}" else: list_to_hash.append(coordinate_value) @@ -294,10 +294,10 @@ def parse_base_pointer_info(base_pointer_specification, loop_order, spatial_dime def add_new_element(elem): if elem >= spatial_dimensions + index_dimensions: - raise ValueError("Coordinate %d does not exist" % (elem,)) + raise ValueError(f"Coordinate {elem:d} does not exist") new_group.append(elem) if elem in specified_coordinates: - raise ValueError("Coordinate %d specified two times" % (elem,)) + raise ValueError(f"Coordinate {elem:d} specified two times") specified_coordinates.add(elem) for element in spec_group: if type(element) is int: @@ -319,7 +319,7 @@ def parse_base_pointer_info(base_pointer_specification, loop_order, spatial_dime index = int(element[len("index"):]) add_new_element(spatial_dimensions + index) else: - raise ValueError("Unknown specification %s" % (element,)) + raise ValueError(f"Unknown specification {element}") result.append(new_group) @@ -834,12 +834,12 @@ class KernelConstraintsCheck: fai = self.FieldAndIndex(lhs.field, lhs.index) self._field_writes[fai].add(lhs.offsets) if len(self._field_writes[fai]) > 1: - raise ValueError("Field {} is written at two different locations".format(lhs.field.name)) + raise ValueError(f"Field {lhs.field.name} is written at two different locations") elif isinstance(lhs, sp.Symbol): if self.scopes.is_defined_locally(lhs): - raise ValueError("Assignments not in SSA form, multiple assignments to {}".format(lhs.name)) + raise ValueError(f"Assignments not in SSA form, multiple assignments to {lhs.name}") if lhs in self.scopes.free_parameters: - raise ValueError("Symbol {} is written, after it has been read".format(lhs.name)) + raise ValueError(f"Symbol {lhs.name} is written, after it has been read") self.scopes.define_symbol(lhs) def _update_accesses_rhs(self, rhs): @@ -1172,7 +1172,7 @@ def loop_blocking(ast_node: ast.KernelFunction, block_size) -> int: loop_stops[coord] = loop.stop else: assert loop.start == loop_starts[coord] and loop.stop == loop_stops[coord], \ - "Multiple loops over coordinate {} with different loop bounds".format(coord) + f"Multiple loops over coordinate {coord} with different loop bounds" # Create the outer loops that iterate over the blocks outer_loop = None -- GitLab