diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 73139a4d58..1a424fccc9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -27,7 +27,7 @@ repos: - id: sphinx-lint args: ["."] - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.3 + rev: v0.11.13 hooks: - id: ruff args: ["--fix", "--output-format=full"] diff --git a/pytensor/bin/pytensor_cache.py b/pytensor/bin/pytensor_cache.py index b5d22876ec..27b9a9213c 100644 --- a/pytensor/bin/pytensor_cache.py +++ b/pytensor/bin/pytensor_cache.py @@ -24,7 +24,7 @@ def print_help(exit_status): if exit_status: - print(f"command \"{' '.join(sys.argv)}\" not recognized") + print(f'command "{" ".join(sys.argv)}" not recognized') print('Type "pytensor-cache" to print the cache location') print('Type "pytensor-cache help" to print this help') print('Type "pytensor-cache clear" to erase the cache') diff --git a/pytensor/compile/function/__init__.py b/pytensor/compile/function/__init__.py index 61e4aa3cfe..ffce6db4fb 100644 --- a/pytensor/compile/function/__init__.py +++ b/pytensor/compile/function/__init__.py @@ -12,7 +12,7 @@ from pytensor.graph import Variable -__all__ = ["types", "pfunc"] +__all__ = ["pfunc", "types"] __docformat__ = "restructuredtext en" _logger = logging.getLogger("pytensor.compile.function") diff --git a/pytensor/compile/function/pfunc.py b/pytensor/compile/function/pfunc.py index 91d6e1a588..0a0e163096 100644 --- a/pytensor/compile/function/pfunc.py +++ b/pytensor/compile/function/pfunc.py @@ -328,8 +328,7 @@ def clone_inputs(i): cloned_outputs = [] # TODO: get Function.__call__ to return None else: raise TypeError( - "output must be an PyTensor Variable or Out " - "instance (or list of them)", + "output must be an PyTensor Variable or Out instance (or list of them)", outputs, ) diff --git a/pytensor/compile/function/types.py b/pytensor/compile/function/types.py index 246354de0f..2ce55e27fb 100644 --- a/pytensor/compile/function/types.py +++ b/pytensor/compile/function/types.py @@ -216,7 +216,7 @@ def add_supervisor_to_fgraph( input for spec, input in zip(input_specs, fgraph.inputs, strict=True) if not ( - spec.mutable or has_destroy_handler and fgraph.has_destroyers([input]) + spec.mutable or (has_destroy_handler and fgraph.has_destroyers([input])) ) ) ) diff --git a/pytensor/compile/monitormode.py b/pytensor/compile/monitormode.py index 40c8c41dfe..305c4cc4af 100644 --- a/pytensor/compile/monitormode.py +++ b/pytensor/compile/monitormode.py @@ -45,8 +45,7 @@ def __init__( optimizer = config.optimizer if linker is not None and not isinstance(linker.mode, MonitorMode): raise Exception( - "MonitorMode can only use its own linker! You " - "should not provide one.", + "MonitorMode can only use its own linker! You should not provide one.", linker, ) diff --git a/pytensor/compile/profiling.py b/pytensor/compile/profiling.py index a68365527f..e07cf3bdb9 100644 --- a/pytensor/compile/profiling.py +++ b/pytensor/compile/profiling.py @@ -935,18 +935,14 @@ def count_running_memory(order, fgraph, nodes_mem, ignore_dmap=False): if dmap and idx2 in dmap: vidx = dmap[idx2] assert len(vidx) == 1, ( - "Here we only support the " - "possibility to destroy one " - "input" + "Here we only support the possibility to destroy one input" ) ins = node.inputs[vidx[0]] if vmap and idx2 in vmap: assert ins is None vidx = vmap[idx2] assert len(vidx) == 1, ( - "Here we only support the " - "possibility to view one " - "input" + "Here we only support the possibility to view one input" ) ins = node.inputs[vidx[0]] if ins is not None: @@ -1093,9 +1089,7 @@ def min_memory_generator(executable_nodes, viewed_by, view_of): assert ins is None vidx = vmap[idx] assert len(vidx) == 1, ( - "Here we only support " - "the possibility to " - "view one input" + "Here we only support the possibility to view one input" ) ins = node.inputs[vidx[0]] if ins is not None: @@ -1304,22 +1298,22 @@ def print_stats(stats1, stats2): print( ( - f" CPU: {int(round(new_max_running_max_memory_size[1] / 1024.0))}KB " - f"({int(round(max_running_max_memory_size[1] / 1024.0))}KB)" + f" CPU: {round(new_max_running_max_memory_size[1] / 1024.0)}KB " + f"({round(max_running_max_memory_size[1] / 1024.0)}KB)" ), file=file, ) print( ( - f" GPU: {int(round(new_max_running_max_memory_size[2] / 1024.0))}KB " - f"({int(round(max_running_max_memory_size[2] / 1024.0))}KB)" + f" GPU: {round(new_max_running_max_memory_size[2] / 1024.0)}KB " + f"({round(max_running_max_memory_size[2] / 1024.0)}KB)" ), file=file, ) print( ( - f" CPU + GPU: {int(round(new_max_running_max_memory_size[0] / 1024.0))}KB " - f"({int(round(max_running_max_memory_size[0] / 1024.0))}KB)" + f" CPU + GPU: {round(new_max_running_max_memory_size[0] / 1024.0)}KB " + f"({round(max_running_max_memory_size[0] / 1024.0)}KB)" ), file=file, ) @@ -1340,15 +1334,15 @@ def print_stats(stats1, stats2): file=file, ) print( - f" CPU: {int(round(new_max_node_memory_size[1] / 1024.0))}KB", + f" CPU: {round(new_max_node_memory_size[1] / 1024.0)}KB", file=file, ) print( - f" GPU: {int(round(new_max_node_memory_size[2] / 1024.0))}KB", + f" GPU: {round(new_max_node_memory_size[2] / 1024.0)}KB", file=file, ) print( - f" CPU + GPU: {int(round(new_max_node_memory_size[0] / 1024.0))}KB", + f" CPU + GPU: {round(new_max_node_memory_size[0] / 1024.0)}KB", file=file, ) print("---", file=file) @@ -1356,7 +1350,7 @@ def print_stats(stats1, stats2): if min_max_peak: print( " Minimum peak from all valid apply node order is " - f"{int(round(min_max_peak / 1024.0))}KB(took {min_peak_time:3f}s to compute)", + f"{round(min_max_peak / 1024.0)}KB(took {min_peak_time:3f}s to compute)", file=file, ) @@ -1405,7 +1399,7 @@ def print_stats(stats1, stats2): print( ( f" ... (remaining {max(0, len(node_mem) - N)} Apply account for " - f"{sum_remaining:4d}B/{size_sum_dense :d}B ({p}) of the" + f"{sum_remaining:4d}B/{size_sum_dense:d}B ({p}) of the" " Apply with dense outputs sizes)" ), file=file, @@ -1545,8 +1539,7 @@ def amdlibm_speed_up(op): return True elif s_op.__class__ not in scalar_op_amdlibm_no_speed_up: print( - "We don't know if amdlibm will accelerate " - "this scalar op.", + "We don't know if amdlibm will accelerate this scalar op.", s_op, file=file, ) diff --git a/pytensor/configdefaults.py b/pytensor/configdefaults.py index ca3c44bf6d..33acb14524 100644 --- a/pytensor/configdefaults.py +++ b/pytensor/configdefaults.py @@ -67,8 +67,7 @@ def _warn_cxx(val): """We only support clang++ as otherwise we hit strange g++/OSX bugs.""" if sys.platform == "darwin" and val and "clang++" not in val: _logger.warning( - "Only clang++ is supported. With g++," - " we end up with strange g++/OSX bugs." + "Only clang++ is supported. With g++, we end up with strange g++/OSX bugs." ) return True diff --git a/pytensor/gradient.py b/pytensor/gradient.py index 96a39e09d9..932d52e3fc 100644 --- a/pytensor/gradient.py +++ b/pytensor/gradient.py @@ -624,8 +624,7 @@ def grad( if cost is not None and isinstance(cost.type, NullType): raise ValueError( - "Can't differentiate a NaN cost. " - f"Cost is NaN because {cost.type.why_null}" + f"Can't differentiate a NaN cost. Cost is NaN because {cost.type.why_null}" ) if cost is not None and cost.type.ndim != 0: @@ -2181,9 +2180,9 @@ def hessian(cost, wrt, consider_constant=None, disconnected_inputs="raise"): sequences=pytensor.tensor.arange(expr.shape[0]), non_sequences=[expr, input], ) - assert ( - not updates - ), "Scan has returned a list of updates; this should not happen." + assert not updates, ( + "Scan has returned a list of updates; this should not happen." + ) hessians.append(hess) return as_list_or_tuple(using_list, using_tuple, hessians) diff --git a/pytensor/graph/basic.py b/pytensor/graph/basic.py index 512f0ef3ab..401d9fe092 100644 --- a/pytensor/graph/basic.py +++ b/pytensor/graph/basic.py @@ -408,7 +408,9 @@ class Variable(Node, Generic[_TypeType, OptionalApplyType]): [b], [c] ) # this works because a has a value associated with it already - assert 4.0 == f(2.5) # bind 2.5 to an internal copy of b and evaluate an internal c + assert 4.0 == f( + 2.5 + ) # bind 2.5 to an internal copy of b and evaluate an internal c pytensor.function( [a], [c] diff --git a/pytensor/graph/features.py b/pytensor/graph/features.py index 3521d3b1ba..3c463cebd4 100644 --- a/pytensor/graph/features.py +++ b/pytensor/graph/features.py @@ -390,8 +390,7 @@ def __init__(self): def on_attach(self, fgraph): if hasattr(fgraph, "checkpoint") or hasattr(fgraph, "revert"): raise AlreadyThere( - "History feature is already present or in" - " conflict with another plugin." + "History feature is already present or in conflict with another plugin." ) self.history[fgraph] = [] # Don't call unpickle here, as ReplaceValidate.on_attach() diff --git a/pytensor/graph/rewriting/basic.py b/pytensor/graph/rewriting/basic.py index 0719870205..d4f29aa07f 100644 --- a/pytensor/graph/rewriting/basic.py +++ b/pytensor/graph/rewriting/basic.py @@ -3044,10 +3044,7 @@ def check_stack_trace(f_or_fgraph, ops_to_check="last", bug_print="raise"): raise ValueError("ops_to_check does not have the right type") if not apply_nodes_to_check: - msg = ( - "Provided op instances/classes are not in the graph or the " - "graph is empty" - ) + msg = "Provided op instances/classes are not in the graph or the graph is empty" if bug_print == "warn": warnings.warn(msg) elif bug_print == "raise": diff --git a/pytensor/graph/rewriting/db.py b/pytensor/graph/rewriting/db.py index fb81622458..a624ca3b48 100644 --- a/pytensor/graph/rewriting/db.py +++ b/pytensor/graph/rewriting/db.py @@ -460,7 +460,7 @@ def query(self, *tags, position_cutoff: int | float | None = None, **kwtags): return ret def print_summary(self, stream=sys.stdout): - print(f"{self.__class__.__name__ } (id {id(self)})", file=stream) + print(f"{self.__class__.__name__} (id {id(self)})", file=stream) positions = list(self.__position__.items()) def c(a, b): diff --git a/pytensor/link/c/basic.py b/pytensor/link/c/basic.py index 8d2a35b9ac..2c98296e22 100644 --- a/pytensor/link/c/basic.py +++ b/pytensor/link/c/basic.py @@ -821,9 +821,9 @@ def code_gen(self): behavior = op.c_code(node, name, isyms, osyms, sub) - assert isinstance( - behavior, str - ), f"{node.op} didn't return a string for c_code" + assert isinstance(behavior, str), ( + f"{node.op} didn't return a string for c_code" + ) # To help understand what is following. It help read the c code. # This prevent different op that generate the same c code # to be merged, I suppose this won't happen... @@ -1752,10 +1752,7 @@ def __call__(self): exc_value.__thunk_trace__ = trace except Exception: print( # noqa: T201 - ( - "ERROR retrieving error_storage." - "Was the error set in the c code?" - ), + ("ERROR retrieving error_storage.Was the error set in the c code?"), end=" ", file=sys.stderr, ) diff --git a/pytensor/link/c/op.py b/pytensor/link/c/op.py index 8ccfa2a9a3..e8ff8b6988 100644 --- a/pytensor/link/c/op.py +++ b/pytensor/link/c/op.py @@ -588,7 +588,7 @@ def c_code(self, node, name, inp, out, sub): {define_macros} {{ if ({self.func_name}({self.format_c_function_args(inp, out)}{params}) != 0) {{ - {sub['fail']} + {sub["fail"]} }} }} {undef_macros} diff --git a/pytensor/link/c/params_type.py b/pytensor/link/c/params_type.py index 457983ce03..dbb8cda8e3 100644 --- a/pytensor/link/c/params_type.py +++ b/pytensor/link/c/params_type.py @@ -116,7 +116,8 @@ def __init__(value_attr1, value_attr2): .. code-block:: python wrapper = ParamsType( - enum1=EnumList("A", ("B", "beta"), "C"), enum2=EnumList(("D", "delta"), "E", "F") + enum1=EnumList("A", ("B", "beta"), "C"), + enum2=EnumList(("D", "delta"), "E", "F"), ) b1 = wrapper.B b2 = wrapper.get_enum("B") @@ -540,7 +541,9 @@ def enum_from_alias(self, alias): wrapper = ParamsType( scalar=ScalarType("int32"), letters=EnumType(A=(1, "alpha"), B=(2, "beta"), C=3), - digits=EnumList(("ZERO", "nothing"), ("ONE", "unit"), ("TWO", "couple")), + digits=EnumList( + ("ZERO", "nothing"), ("ONE", "unit"), ("TWO", "couple") + ), ) print(wrapper.get_enum("C")) # 3 print(wrapper.get_enum("TWO")) # 2 @@ -593,7 +596,9 @@ def __init__(self): self.b = numpy.asarray([[1, 2, 3], [4, 5, 6]]) - params_type = ParamsType(a=ScalarType("int32"), b=dmatrix, c=ScalarType("bool")) + params_type = ParamsType( + a=ScalarType("int32"), b=dmatrix, c=ScalarType("bool") + ) o = MyObject() value_for_c = False @@ -852,20 +857,20 @@ def c_extract(self, name, sub, check_input=True, **kwargs): const char* fields[] = {{{fields_list}}}; if (py_{name} == Py_None) {{ PyErr_SetString(PyExc_ValueError, "ParamsType: expected an object, not None."); - {sub['fail']} + {sub["fail"]} }} for (int i = 0; i < {self.length}; ++i) {{ PyObject* o = PyDict_GetItemString(py_{name}, fields[i]); if (o == NULL) {{ PyErr_Format(PyExc_TypeError, "ParamsType: missing expected attribute \\"%s\\" in object.", fields[i]); - {sub['fail']} + {sub["fail"]} }} {name}->extract(o, i); if ({name}->errorOccurred()) {{ /* The extract code from attribute type should have already raised a Python exception, * so we just print the attribute name in stderr. */ fprintf(stderr, "\\nParamsType: error when extracting value for attribute \\"%s\\".\\n", fields[i]); - {sub['fail']} + {sub["fail"]} }} }} }} diff --git a/pytensor/link/c/type.py b/pytensor/link/c/type.py index 1c35c4897a..84715eebb6 100644 --- a/pytensor/link/c/type.py +++ b/pytensor/link/c/type.py @@ -350,7 +350,11 @@ class EnumType(CType, dict): .. code-block:: python enum = EnumType( - CONSTANT_1=0, CONSTANT_2=1, CONSTANT_3=2, ctype="size_t", cname="MyEnumName" + CONSTANT_1=0, + CONSTANT_2=1, + CONSTANT_3=2, + ctype="size_t", + cname="MyEnumName", ) **Example with aliases** @@ -477,7 +481,7 @@ def get_aliases(self): return tuple(sorted(self.aliases)) def __repr__(self): - names_to_aliases = {constant_name: "" for constant_name in self} + names_to_aliases = dict.fromkeys(self, "") for alias in self.aliases: names_to_aliases[self.aliases[alias]] = f"({alias})" args = ", ".join(f"{k}{names_to_aliases[k]}:{self[k]}" for k in sorted(self)) @@ -674,7 +678,9 @@ class EnumList(EnumType): .. code-block:: python - enum = EnumList(("A", "alpha"), ("B", "beta"), "C", "D", "E", "F", ("G", "gamma")) + enum = EnumList( + ("A", "alpha"), ("B", "beta"), "C", "D", "E", "F", ("G", "gamma") + ) See test class :class:`tests.graph.test_types.TestOpEnumList` for a working example. diff --git a/pytensor/link/numba/dispatch/scalar.py b/pytensor/link/numba/dispatch/scalar.py index 7e4703c8df..0326c6975d 100644 --- a/pytensor/link/numba/dispatch/scalar.py +++ b/pytensor/link/numba/dispatch/scalar.py @@ -119,12 +119,12 @@ def {scalar_op_fn_name}({input_names}): ) if not has_pyx_skip_dispatch: scalar_op_src = f""" -def {scalar_op_fn_name}({', '.join(input_names)}): +def {scalar_op_fn_name}({", ".join(input_names)}): return direct_cast(scalar_func_numba({converted_call_args}), output_dtype) """ else: scalar_op_src = f""" -def {scalar_op_fn_name}({', '.join(input_names)}): +def {scalar_op_fn_name}({", ".join(input_names)}): return direct_cast(scalar_func_numba({converted_call_args}, np.intc(1)), output_dtype) """ diff --git a/pytensor/link/vm.py b/pytensor/link/vm.py index c6e1283806..a2126855e4 100644 --- a/pytensor/link/vm.py +++ b/pytensor/link/vm.py @@ -83,16 +83,16 @@ def calculate_reallocate_info( ins = None if dmap and idx_o in dmap: idx_v = dmap[idx_o] - assert ( - len(idx_v) == 1 - ), "Here we only support the possibility to destroy one input" + assert len(idx_v) == 1, ( + "Here we only support the possibility to destroy one input" + ) ins = node.inputs[idx_v[0]] if vmap and idx_o in vmap: assert ins is None idx_v = vmap[idx_o] - assert ( - len(idx_v) == 1 - ), "Here we only support the possibility to view one input" + assert len(idx_v) == 1, ( + "Here we only support the possibility to view one input" + ) ins = node.inputs[idx_v[0]] if ins is not None: assert isinstance(ins, Variable) diff --git a/pytensor/misc/ordered_set.py b/pytensor/misc/ordered_set.py index c6b6566644..a33cc53c32 100644 --- a/pytensor/misc/ordered_set.py +++ b/pytensor/misc/ordered_set.py @@ -9,7 +9,7 @@ def __init__(self, iterable: Iterable | None = None) -> None: if iterable is None: self.values = {} else: - self.values = {value: None for value in iterable} + self.values = dict.fromkeys(iterable) def __contains__(self, value) -> bool: return value in self.values diff --git a/pytensor/printing.py b/pytensor/printing.py index b7b71622e8..8792f224b9 100644 --- a/pytensor/printing.py +++ b/pytensor/printing.py @@ -294,8 +294,10 @@ def debugprint( if hasattr(var.owner, "op"): if ( isinstance(var.owner.op, HasInnerGraph) - or hasattr(var.owner.op, "scalar_op") - and isinstance(var.owner.op.scalar_op, HasInnerGraph) + or ( + hasattr(var.owner.op, "scalar_op") + and isinstance(var.owner.op.scalar_op, HasInnerGraph) + ) ) and var not in inner_graph_vars: inner_graph_vars.append(var) if print_op_info: @@ -674,8 +676,10 @@ def get_id_str( if hasattr(in_var, "owner") and hasattr(in_var.owner, "op"): if ( isinstance(in_var.owner.op, HasInnerGraph) - or hasattr(in_var.owner.op, "scalar_op") - and isinstance(in_var.owner.op.scalar_op, HasInnerGraph) + or ( + hasattr(in_var.owner.op, "scalar_op") + and isinstance(in_var.owner.op.scalar_op, HasInnerGraph) + ) ) and in_var not in inner_graph_ops: inner_graph_ops.append(in_var) @@ -881,7 +885,9 @@ def process(self, output, pstate): max_i = len(node.inputs) - 1 for i, input in enumerate(node.inputs): new_precedence = self.precedence - if self.assoc == "left" and i != 0 or self.assoc == "right" and i != max_i: + if (self.assoc == "left" and i != 0) or ( + self.assoc == "right" and i != max_i + ): new_precedence += 1e-6 with set_precedence(pstate, new_precedence): diff --git a/pytensor/scalar/basic.py b/pytensor/scalar/basic.py index de92555401..02b1409cff 100644 --- a/pytensor/scalar/basic.py +++ b/pytensor/scalar/basic.py @@ -992,8 +992,7 @@ def as_scalar(x: Any, name: str | None = None) -> ScalarVariable: if isinstance(x, Apply): if len(x.outputs) != 1: raise ValueError( - "It is ambiguous which output of a multi-output" - " Op has to be fetched.", + "It is ambiguous which output of a multi-output Op has to be fetched.", x, ) else: diff --git a/pytensor/scalar/loop.py b/pytensor/scalar/loop.py index 80168fd122..f23c4e1c42 100644 --- a/pytensor/scalar/loop.py +++ b/pytensor/scalar/loop.py @@ -219,7 +219,7 @@ def c_code_template(self): for i, c in enumerate(fgraph.inputs[n_update:], start=n_update + 1) } out_subd = {u: f"%(o{i})s" for i, u in enumerate(fgraph.outputs[:n_update])} - until_subd = {u: "until" for u in fgraph.outputs[n_update:]} + until_subd = dict.fromkeys(fgraph.outputs[n_update:], "until") subd = {**carry_subd, **constant_subd, **until_subd} for var in fgraph.variables: @@ -307,7 +307,7 @@ def c_code_template(self): # Output until flag if self.is_while: - _c_code += f"%(o{len(fgraph.outputs)-1})s = until;\n" + _c_code += f"%(o{len(fgraph.outputs) - 1})s = until;\n" _c_code += "}\n" diff --git a/pytensor/scan/op.py b/pytensor/scan/op.py index c1ae4db04d..aeea76afd9 100644 --- a/pytensor/scan/op.py +++ b/pytensor/scan/op.py @@ -2454,8 +2454,7 @@ def compute_all_gradients(known_grads): for g_y in g_y_s: if str(g_y.dtype) in integer_dtypes: raise TypeError( - "Gradients may never be integers but g_y " - f"has type {g_y.type}" + f"Gradients may never be integers but g_y has type {g_y.type}" ) out_indices = [get_out_idx(self_outputs.index(y)) for y in y_s] diff --git a/pytensor/sparse/basic.py b/pytensor/sparse/basic.py index 7f200b2a7c..396aeaa6b4 100644 --- a/pytensor/sparse/basic.py +++ b/pytensor/sparse/basic.py @@ -174,8 +174,7 @@ def as_sparse_variable(x, name=None, ndim=None, **kwargs): if isinstance(x, Apply): if len(x.outputs) != 1: raise ValueError( - "It is ambiguous which output of a " - "multi-output Op has to be fetched.", + "It is ambiguous which output of a multi-output Op has to be fetched.", x, ) else: @@ -1333,8 +1332,7 @@ def make_node(self, x, index): # of dimension 1 and int/uint dtype. if scipy_ver < [0, 14] and ind.step is not None: raise ValueError( - "Slice with step is not support with current" - " version of Scipy." + "Slice with step is not support with current version of Scipy." ) if ind.step is None or ind.step == 1: step = generic_None diff --git a/pytensor/tensor/_linalg/solve/rewriting.py b/pytensor/tensor/_linalg/solve/rewriting.py index 9ea8db37fc..1c29543cdc 100644 --- a/pytensor/tensor/_linalg/solve/rewriting.py +++ b/pytensor/tensor/_linalg/solve/rewriting.py @@ -166,9 +166,9 @@ def _scan_split_non_sequence_lu_decomposition_solve( eager=True, allowed_assume_a=allowed_assume_a, ) - assert ( - isinstance(replace_dict, dict) and len(replace_dict) > 0 - ), "Rewrite failed" + assert isinstance(replace_dict, dict) and len(replace_dict) > 0, ( + "Rewrite failed" + ) new_scan_fgraph.replace_all(replace_dict.items()) changed = True break # Break to start over with a fresh toposort diff --git a/pytensor/tensor/basic.py b/pytensor/tensor/basic.py index b9e9c3164d..42f0649287 100644 --- a/pytensor/tensor/basic.py +++ b/pytensor/tensor/basic.py @@ -2210,7 +2210,7 @@ def __init__(self, len_splits): self.view_map = {i: [0] for i in range(self.len_splits)} def __str__(self): - return f"{self.__class__.__name__ }{{{self.len_splits}}}" + return f"{self.__class__.__name__}{{{self.len_splits}}}" def make_node(self, x, axis, splits): """WRITEME""" @@ -2583,7 +2583,7 @@ def c_code(self, node, name, inputs, outputs, sub): code = f""" int axis = {axis_def} - PyArrayObject* arrays[{n}] = {{{','.join(arrays)}}}; + PyArrayObject* arrays[{n}] = {{{",".join(arrays)}}}; int out_is_valid = {out} != NULL; {axis_check} @@ -3854,7 +3854,7 @@ def c_code(self, node, nodename, input_names, output_names, sub): PyArrayObject *{out_name}_copy = (PyArrayObject*) PyArray_Copy({out_name}); Py_DECREF({out_name}); if (!{out_name}_copy) {{ - {sub['fail']}; // Error already set by Numpy + {sub["fail"]}; // Error already set by Numpy }} {out_name} = {out_name}_copy; }} @@ -4557,72 +4557,72 @@ def ix_(*args): __all__ = [ - "take_along_axis", - "expand_dims", - "atleast_Nd", + "alloc", + "arange", + "as_tensor", + "as_tensor_variable", "atleast_1d", "atleast_2d", "atleast_3d", + "atleast_Nd", + "cast", "choose", - "swapaxes", - "moveaxis", - "stacklists", + "concatenate", + "constant", + "default", "diag", "diagonal", - "inverse_permutation", - "permute_row_elements", - "mgrid", - "ogrid", - "arange", - "tile", + "empty", + "empty_like", + "expand_dims", + "extract_diag", + "eye", + "fill", + "flatnonzero", "flatten", - "is_flat", - "vertical_stack", - "horizontal_stack", + "full", + "full_like", + "get_scalar_constant_value", + "get_underlying_scalar_constant_value", "get_vector_length", - "concatenate", - "stack", - "roll", + "horizontal_stack", + "identity_like", + "inverse_permutation", + "is_flat", "join", - "split", - "transpose", "matrix_transpose", - "default", - "tensor_copy", - "transfer", - "alloc", - "identity_like", - "eye", - "triu", - "tril", - "tri", - "nonzero_values", - "flatnonzero", + "mgrid", + "moveaxis", "nonzero", + "nonzero_values", + "ogrid", "ones", - "zeros", - "zeros_like", "ones_like", - "fill", + "permute_row_elements", + "roll", + "scalar_from_tensor", "second", - "where", + "split", + "stack", + "stacklists", + "swapaxes", "switch", - "cast", - "scalar_from_tensor", + "take_along_axis", + "tensor_copy", "tensor_from_scalar", - "get_scalar_constant_value", - "get_underlying_scalar_constant_value", - "constant", - "as_tensor_variable", - "as_tensor", - "extract_diag", - "full", - "full_like", - "empty", - "empty_like", + "tile", "trace", + "transfer", + "transpose", + "tri", + "tril", "tril_indices", "tril_indices_from", + "triu", "triu_indices", "triu_indices_from", + "vertical_stack", + "where", + "zeros", + "zeros_like", ] diff --git a/pytensor/tensor/blas.py b/pytensor/tensor/blas.py index fc8afcea50..13fc914c79 100644 --- a/pytensor/tensor/blas.py +++ b/pytensor/tensor/blas.py @@ -1642,8 +1642,7 @@ def R_op(self, inputs, eval_points): ev0 = pytensor.graph.op.get_test_value(eval_points[0]) except TestValueError: pytensor.graph.op.missing_test_message( - "first eval point passed to BatchedDot.R_op " - "has no test value" + "first eval point passed to BatchedDot.R_op has no test value" ) test_values_enabled = False if eval_points[1]: @@ -1651,8 +1650,7 @@ def R_op(self, inputs, eval_points): ev1 = pytensor.graph.op.get_test_value(eval_points[1]) except TestValueError: pytensor.graph.op.missing_test_message( - "second eval point passed to BatchedDot.R_op " - "has no test value" + "second eval point passed to BatchedDot.R_op has no test value" ) test_values_enabled = False diff --git a/pytensor/tensor/conv/abstract_conv.py b/pytensor/tensor/conv/abstract_conv.py index 2bcfa0a551..d4f723a4b0 100644 --- a/pytensor/tensor/conv/abstract_conv.py +++ b/pytensor/tensor/conv/abstract_conv.py @@ -2477,14 +2477,12 @@ def make_node(self, img, kern): img = assert_shape( img, self.imshp, - "AbstractConv shape mismatch: shape of " - "image does not match given imshp.", + "AbstractConv shape mismatch: shape of image does not match given imshp.", ) kern = assert_shape( kern, self.kshp, - "AbstractConv shape mismatch: shape of " - "filters does not match given kshp.", + "AbstractConv shape mismatch: shape of filters does not match given kshp.", ) out_shape = ( diff --git a/pytensor/tensor/einsum.py b/pytensor/tensor/einsum.py index e119b6de11..8e165006ca 100644 --- a/pytensor/tensor/einsum.py +++ b/pytensor/tensor/einsum.py @@ -668,9 +668,9 @@ def filter_singleton_dims(operand, names, other_operand, other_names): einsum_operands = list(tensor_operands) # So we can pop for operand_indices, contracted_names, einstr, _, _ in contraction_list: contracted_names = sorted(contracted_names) - assert len(contracted_names) == len( - set(contracted_names) - ), "The set was needed!" + assert len(contracted_names) == len(set(contracted_names)), ( + "The set was needed!" + ) input_str, result_names = einstr.split("->") input_names = input_str.split(",") diff --git a/pytensor/tensor/elemwise.py b/pytensor/tensor/elemwise.py index 77723917b0..9dfe7412dc 100644 --- a/pytensor/tensor/elemwise.py +++ b/pytensor/tensor/elemwise.py @@ -821,7 +821,7 @@ def _c_all(self, node, nodename, inames, onames, sub): # for each input: # same as range(ndim), but with 'x' at all broadcastable positions orders = [ - [s == 1 and "x" or i for i, s in enumerate(input.type.shape)] + [(s == 1 and "x") or i for i, s in enumerate(input.type.shape)] for input in inputs ] diff --git a/pytensor/tensor/elemwise_cgen.py b/pytensor/tensor/elemwise_cgen.py index 5d50f02ad5..2c2753c5e6 100644 --- a/pytensor/tensor/elemwise_cgen.py +++ b/pytensor/tensor/elemwise_cgen.py @@ -691,10 +691,10 @@ def make_reordered_loop_careduce( counter = iter(range(inp_ndim)) unsorted_vars = dedent( f""" - int dim_lengths[{inp_ndim}] = {{{','.join(f'{inp_var}_n{i}' for i in range(inp_ndim))}}}; - int inp_strides[{inp_ndim}] = {{{','.join(f'{inp_var}_stride{i}' for i in range(inp_ndim))}}}; - int acc_strides[{inp_ndim}] = {{{','.join("0" if i in reduction_axes else f'{acc_var}_stride{next(counter)}'for i in range(inp_ndim))}}}; - bool reduction_axes[{inp_ndim}] = {{{', '.join("1" if i in reduction_axes else "0" for i in range(inp_ndim))}}};\n + int dim_lengths[{inp_ndim}] = {{{",".join(f"{inp_var}_n{i}" for i in range(inp_ndim))}}}; + int inp_strides[{inp_ndim}] = {{{",".join(f"{inp_var}_stride{i}" for i in range(inp_ndim))}}}; + int acc_strides[{inp_ndim}] = {{{",".join("0" if i in reduction_axes else f"{acc_var}_stride{next(counter)}" for i in range(inp_ndim))}}}; + bool reduction_axes[{inp_ndim}] = {{{", ".join("1" if i in reduction_axes else "0" for i in range(inp_ndim))}}};\n """ ) diff --git a/pytensor/tensor/extra_ops.py b/pytensor/tensor/extra_ops.py index 7a1bc75b0b..7945f7a3b5 100644 --- a/pytensor/tensor/extra_ops.py +++ b/pytensor/tensor/extra_ops.py @@ -1564,7 +1564,7 @@ def broadcast_shape_iter( (one,) * (max_dims - len(a)) + tuple( one - if sh == 1 or isinstance(sh, Constant) and sh.value == 1 + if sh == 1 or (isinstance(sh, Constant) and sh.value == 1) else (ps.as_scalar(sh) if not isinstance(sh, Variable) else sh) for sh in a ) @@ -2037,24 +2037,24 @@ def broadcast_with_others(a, others): __all__ = [ - "searchsorted", - "cumsum", - "cumprod", - "diff", + "bartlett", "bincount", - "squeeze", + "broadcast_arrays", + "broadcast_shape", + "broadcast_to", "compress", - "repeat", - "bartlett", + "cumprod", + "cumsum", + "diff", "fill_diagonal", "fill_diagonal_offset", - "unique", - "unravel_index", - "ravel_multi_index", - "broadcast_shape", - "broadcast_to", "geomspace", - "logspace", "linspace", - "broadcast_arrays", + "logspace", + "ravel_multi_index", + "repeat", + "searchsorted", + "squeeze", + "unique", + "unravel_index", ] diff --git a/pytensor/tensor/math.py b/pytensor/tensor/math.py index 714f597b32..87e8bcbd14 100644 --- a/pytensor/tensor/math.py +++ b/pytensor/tensor/math.py @@ -4241,154 +4241,154 @@ def nan_to_num(x, nan=0.0, posinf=None, neginf=None): not_equal = neq __all__ = [ - "max_and_argmax", - "max", - "matmul", - "vecdot", - "matvec", - "vecmat", - "argmax", - "min", - "argmin", - "smallest", - "largest", - "lt", - "less", - "gt", - "greater", - "le", - "less_equal", - "ge", - "greater_equal", - "eq", - "equal", - "neq", - "not_equal", - "isnan", - "isinf", - "isposinf", - "isneginf", + "abs", + "add", + "all", "allclose", - "isclose", "and_", + "angle", + "any", + "arccos", + "arccosh", + "arcsin", + "arcsinh", + "arctan", + "arctan2", + "arctanh", + "argmax", + "argmin", + "betainc", + "betaincinv", "bitwise_and", - "or_", + "bitwise_not", "bitwise_or", - "xor", "bitwise_xor", - "invert", - "bitwise_not", - "abs", - "exp", - "exp2", - "expm1", - "neg", - "reciprocal", - "log", - "log2", - "log10", - "log1p", - "sgn", - "sign", "ceil", - "floor", - "trunc", - "iround", - "round", - "round_half_to_even", - "round_half_away_from_zero", - "sqr", - "square", - "cov", - "sqrt", - "deg2rad", - "rad2deg", + "ceil_intdiv", + "chi2sf", + "clip", + "complex", + "complex_from_polar", + "conj", + "conjugate", "cos", - "arccos", - "sin", - "arcsin", - "tan", - "arctan", - "arctan2", "cosh", - "arccosh", - "sinh", - "arcsinh", - "tanh", - "arctanh", + "cov", + "deg2rad", + "dense_dot", + "digamma", + "divmod", + "dot", + "eq", + "equal", "erf", "erfc", + "erfcinv", "erfcx", "erfinv", - "erfcinv", - "owens_t", + "exp", + "exp2", + "expit", + "expm1", + "floor", + "floor_div", "gamma", - "gammaln", - "psi", - "digamma", - "tri_gamma", - "polygamma", - "chi2sf", "gammainc", "gammaincc", - "gammau", - "gammal", - "gammaincinv", "gammainccinv", - "j0", - "j1", - "jv", + "gammaincinv", + "gammal", + "gammaln", + "gammau", + "ge", + "greater", + "greater_equal", + "gt", + "hyp2f1", "i0", "i1", + "imag", + "int_div", + "invert", + "iround", + "isclose", + "isinf", + "isnan", + "isneginf", + "isposinf", "iv", "ive", + "j0", + "j1", + "jv", "kn", "kv", "kve", - "sigmoid", - "expit", - "softplus", - "log1pexp", + "largest", + "le", + "less", + "less_equal", + "log", "log1mexp", - "betainc", - "betaincinv", - "real", - "imag", - "angle", - "complex", - "conj", - "conjugate", - "complex_from_polar", - "sum", - "prod", + "log1p", + "log1pexp", + "log2", + "log10", + "logaddexp", + "logsumexp", + "lt", + "matmul", + "matvec", + "max", + "max_and_argmax", + "maximum", "mean", "median", - "var", - "std", - "std", - "maximum", + "min", "minimum", - "divmod", - "add", - "sub", - "mul", - "true_div", - "int_div", - "floor_div", - "ceil_intdiv", "mod", - "pow", - "clip", - "dot", - "dense_dot", - "tensordot", + "mul", + "nan_to_num", + "neg", + "neq", + "not_equal", + "or_", "outer", - "any", - "all", - "ptp", + "owens_t", + "polygamma", + "pow", "power", - "logaddexp", - "logsumexp", - "hyp2f1", - "nan_to_num", + "prod", + "psi", + "ptp", + "rad2deg", + "real", + "reciprocal", + "round", + "round_half_away_from_zero", + "round_half_to_even", + "sgn", + "sigmoid", + "sign", + "sin", + "sinh", + "smallest", + "softplus", + "sqr", + "sqrt", + "square", + "std", + "std", + "sub", + "sum", + "tan", + "tanh", + "tensordot", + "tri_gamma", + "true_div", + "trunc", + "var", + "vecdot", + "vecmat", + "xor", ] diff --git a/pytensor/tensor/nlinalg.py b/pytensor/tensor/nlinalg.py index 8fff2a2f59..90a015f29f 100644 --- a/pytensor/tensor/nlinalg.py +++ b/pytensor/tensor/nlinalg.py @@ -1284,20 +1284,20 @@ def kron(a, b): __all__ = [ - "pinv", - "inv", - "trace", - "matrix_dot", "det", "eig", "eigh", - "qr", - "svd", + "inv", + "kron", "lstsq", + "matrix_dot", "matrix_power", "norm", + "pinv", + "qr", "slogdet", + "svd", "tensorinv", "tensorsolve", - "kron", + "trace", ] diff --git a/pytensor/tensor/pad.py b/pytensor/tensor/pad.py index 2a3b8b4588..cd8ce5e166 100644 --- a/pytensor/tensor/pad.py +++ b/pytensor/tensor/pad.py @@ -689,4 +689,4 @@ def pad( return cast(TensorVariable, op) -__all__ = ["pad", "flip"] +__all__ = ["flip", "pad"] diff --git a/pytensor/tensor/random/basic.py b/pytensor/tensor/random/basic.py index ba6ffa8eaa..34e30581c5 100644 --- a/pytensor/tensor/random/basic.py +++ b/pytensor/tensor/random/basic.py @@ -2132,42 +2132,42 @@ def permutation(x, **kwargs): __all__ = [ - "permutation", - "choice", - "integers", - "categorical", - "multinomial", + "bernoulli", + "beta", "betabinom", - "nbinom", "binomial", - "laplace", - "bernoulli", - "truncexpon", - "wald", - "invgamma", - "halfcauchy", + "categorical", "cauchy", - "hypergeometric", - "geometric", - "poisson", + "chisquare", + "choice", "dirichlet", - "multivariate_normal", - "vonmises", - "logistic", - "weibull", "exponential", - "gumbel", - "pareto", - "chisquare", "gamma", - "lognormal", + "gengamma", + "geometric", + "gumbel", + "halfcauchy", "halfnormal", + "hypergeometric", + "integers", + "invgamma", + "laplace", + "logistic", + "lognormal", + "multinomial", + "multivariate_normal", + "nbinom", + "negative_binomial", "normal", - "beta", - "triangular", - "uniform", + "pareto", + "permutation", + "poisson", "standard_normal", - "negative_binomial", - "gengamma", "t", + "triangular", + "truncexpon", + "uniform", + "vonmises", + "wald", + "weibull", ] diff --git a/pytensor/tensor/rewriting/blockwise.py b/pytensor/tensor/rewriting/blockwise.py index 4d2a3715c3..17d1856b55 100644 --- a/pytensor/tensor/rewriting/blockwise.py +++ b/pytensor/tensor/rewriting/blockwise.py @@ -282,8 +282,7 @@ def blockwise_inplace(fgraph, node): allowed_inplace_inputs = [ idx for idx, inp in enumerate(node.inputs) - if - ( + if ( # Constants would need to be recreated every time if inplaced not isinstance(inp, Constant) # We can only inplace on inputs that are not being broadcasted diff --git a/pytensor/tensor/rewriting/elemwise.py b/pytensor/tensor/rewriting/elemwise.py index 98fc4e074c..3be0c7ab1e 100644 --- a/pytensor/tensor/rewriting/elemwise.py +++ b/pytensor/tensor/rewriting/elemwise.py @@ -431,7 +431,7 @@ def local_dimshuffle_lift(fgraph, node): ret = inode.op(*new_inputs, return_list=True) return ret if inode and isinstance(inode.op, DimShuffle): - new_order = [x == "x" and "x" or inode.op.new_order[x] for x in new_order] + new_order = [(x == "x" and "x") or inode.op.new_order[x] for x in new_order] inp = inode.inputs[0] if is_dimshuffle_useless(new_order, inp): diff --git a/pytensor/tensor/rewriting/linalg.py b/pytensor/tensor/rewriting/linalg.py index af42bee236..a15dbfdc0e 100644 --- a/pytensor/tensor/rewriting/linalg.py +++ b/pytensor/tensor/rewriting/linalg.py @@ -384,8 +384,10 @@ def local_lift_through_linalg( outer_op = node.op if y.owner and ( - isinstance(y.owner.op, Blockwise) - and isinstance(y.owner.op.core_op, BlockDiagonal) + ( + isinstance(y.owner.op, Blockwise) + and isinstance(y.owner.op.core_op, BlockDiagonal) + ) or isinstance(y.owner.op, KroneckerProduct) ): input_matrices = y.owner.inputs diff --git a/pytensor/tensor/rewriting/shape.py b/pytensor/tensor/rewriting/shape.py index 1eb10d247b..fe9a21633a 100644 --- a/pytensor/tensor/rewriting/shape.py +++ b/pytensor/tensor/rewriting/shape.py @@ -447,8 +447,7 @@ def update_shape(self, r, other_r): assert all( ( not hasattr(r.type, "shape") - or r.type.shape[i] != 1 - and other_r.type.shape[i] != 1 + or (r.type.shape[i] != 1 and other_r.type.shape[i] != 1) ) or self.lscalar_one.equals(merged_shape[i]) or self.lscalar_one.equals( diff --git a/pytensor/tensor/signal/conv.py b/pytensor/tensor/signal/conv.py index 26c210fda3..f8d05457cf 100644 --- a/pytensor/tensor/signal/conv.py +++ b/pytensor/tensor/signal/conv.py @@ -110,7 +110,7 @@ def c_code(self, node, name, inputs, outputs, sub): if (PyArray_NDIM({in1}) != 1 || PyArray_NDIM({in2}) != 1) {{ PyErr_SetString(PyExc_ValueError, "Convolve1d C code expects 1D arrays."); - {sub['fail']}; + {sub["fail"]}; }} npy_intp n_in2 = PyArray_DIM({in2}, 0); @@ -118,7 +118,7 @@ def c_code(self, node, name, inputs, outputs, sub): // Create a reversed view of in2 if (n_in2 == 0) {{ PyErr_SetString(PyExc_ValueError, "Convolve1d: second input (kernel) cannot be empty."); - {sub['fail']}; + {sub["fail"]}; }} else {{ npy_intp view_dims[1]; view_dims[0] = n_in2; @@ -142,7 +142,7 @@ def c_code(self, node, name, inputs, outputs, sub): if (!in2_flipped_view) {{ PyErr_SetString(PyExc_RuntimeError, "Failed to create flipped kernel view for Convolve1d."); - {sub['fail']}; + {sub["fail"]}; }} Py_INCREF({in2}); @@ -151,7 +151,7 @@ def c_code(self, node, name, inputs, outputs, sub): Py_DECREF(in2_flipped_view); in2_flipped_view = NULL; PyErr_SetString(PyExc_RuntimeError, "Failed to set base object for flipped kernel view in Convolve1d."); - {sub['fail']}; + {sub["fail"]}; }} PyArray_UpdateFlags(in2_flipped_view, (NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS)); }} @@ -162,7 +162,7 @@ def c_code(self, node, name, inputs, outputs, sub): Py_XDECREF(in2_flipped_view); // Clean up the view if correlate fails if (!{out}) {{ // PyArray_Correlate already set an error - {sub['fail']}; + {sub["fail"]}; }} }} """ diff --git a/pytensor/tensor/slinalg.py b/pytensor/tensor/slinalg.py index bbdc9cbba7..b315a1c40f 100644 --- a/pytensor/tensor/slinalg.py +++ b/pytensor/tensor/slinalg.py @@ -1670,17 +1670,17 @@ def block_diag(*matrices: TensorVariable): __all__ = [ + "block_diag", + "cho_solve", "cholesky", - "solve", "eigvalsh", "expm", - "solve_discrete_lyapunov", - "solve_continuous_lyapunov", - "solve_discrete_are", - "solve_triangular", - "block_diag", - "cho_solve", "lu", "lu_factor", "lu_solve", + "solve", + "solve_continuous_lyapunov", + "solve_discrete_are", + "solve_discrete_lyapunov", + "solve_triangular", ] diff --git a/pytensor/tensor/special.py b/pytensor/tensor/special.py index df7edf05ad..60b04bd777 100644 --- a/pytensor/tensor/special.py +++ b/pytensor/tensor/special.py @@ -825,11 +825,11 @@ def betaln(a, b): __all__ = [ - "softmax", - "log_softmax", - "poch", - "factorial", - "logit", "beta", "betaln", + "factorial", + "log_softmax", + "logit", + "poch", + "softmax", ] diff --git a/pytensor/tensor/subtensor.py b/pytensor/tensor/subtensor.py index 278d1e8da6..238109ad89 100644 --- a/pytensor/tensor/subtensor.py +++ b/pytensor/tensor/subtensor.py @@ -3315,9 +3315,9 @@ def flip( __all__ = [ - "take", "flip", - "slice_at_axis", "inc_subtensor", "set_subtensor", + "slice_at_axis", + "take", ] diff --git a/pytensor/tensor/type_other.py b/pytensor/tensor/type_other.py index a9e559504f..b9c587d312 100644 --- a/pytensor/tensor/type_other.py +++ b/pytensor/tensor/type_other.py @@ -137,4 +137,4 @@ def as_symbolic_None(x, **kwargs): return NoneConst -__all__ = ["make_slice", "slicetype", "none_type_t", "NoneConst"] +__all__ = ["NoneConst", "make_slice", "none_type_t", "slicetype"] diff --git a/pytensor/utils.py b/pytensor/utils.py index c81fb74f56..8b1c4dcf20 100644 --- a/pytensor/utils.py +++ b/pytensor/utils.py @@ -12,14 +12,14 @@ __all__ = [ - "get_unbound_function", - "maybe_add_to_os_environ_pathlist", - "subprocess_Popen", - "call_subprocess_Popen", - "output_subprocess_Popen", "LOCAL_BITWIDTH", "PYTHON_INT_BITWIDTH", "NoDuplicateOptWarningFilter", + "call_subprocess_Popen", + "get_unbound_function", + "maybe_add_to_os_environ_pathlist", + "output_subprocess_Popen", + "subprocess_Popen", ] diff --git a/tests/compile/function/test_types.py b/tests/compile/function/test_types.py index 0990dbeca0..38e542318a 100644 --- a/tests/compile/function/test_types.py +++ b/tests/compile/function/test_types.py @@ -47,9 +47,9 @@ class TestFunction: def test_none(self): fn = function([], None) # ok rval = fn() - assert ( - rval != [] - ), "See #254: Using None as function output leads to [] return value" + assert rval != [], ( + "See #254: Using None as function output leads to [] return value" + ) assert rval is None def test_empty(self): diff --git a/tests/graph/test_basic.py b/tests/graph/test_basic.py index 84ffb365b5..591ffc1845 100644 --- a/tests/graph/test_basic.py +++ b/tests/graph/test_basic.py @@ -340,9 +340,9 @@ def test_eval(self): assert self.w.eval({self.x: 1.0, self.y: 2.0}) == 6.0 assert self.w.eval({self.z: 3}) == 6.0 assert hasattr(self.w, "_fn_cache"), "variable must have cache after eval" - assert not hasattr( - pickle.loads(pickle.dumps(self.w)), "_fn_cache" - ), "temporary functions must not be serialized" + assert not hasattr(pickle.loads(pickle.dumps(self.w)), "_fn_cache"), ( + "temporary functions must not be serialized" + ) def test_eval_with_strings(self): assert self.w.eval({"x": 1.0, self.y: 2.0}) == 6.0 diff --git a/tests/link/c/test_params_type.py b/tests/link/c/test_params_type.py index 8fb47077af..6d680c7d5b 100644 --- a/tests/link/c/test_params_type.py +++ b/tests/link/c/test_params_type.py @@ -77,18 +77,18 @@ def c_code(self, node, name, inputs, outputs, sub): Y = outputs[0] float_type = node.inputs[0].type.c_element_type() return f""" - {float_type} a = ({float_type}) (*(npy_float64*) PyArray_GETPTR1({sub['params']}->a, 0)); // 0-D TensorType. - {float_type} b = {sub['params']}->b; // ScalarType. - {float_type} c = ({float_type}) PyFloat_AsDouble({sub['params']}->c); // Generic. + {float_type} a = ({float_type}) (*(npy_float64*) PyArray_GETPTR1({sub["params"]}->a, 0)); // 0-D TensorType. + {float_type} b = {sub["params"]}->b; // ScalarType. + {float_type} c = ({float_type}) PyFloat_AsDouble({sub["params"]}->c); // Generic. Py_XDECREF({Y}); {Y} = (PyArrayObject*)PyArray_EMPTY(PyArray_NDIM({X}), PyArray_DIMS({X}), PyArray_TYPE({X}), PyArray_IS_F_CONTIGUOUS({X})); if (PyArray_CopyInto({Y}, {X}) != 0) {{ PyErr_SetString(PyExc_RuntimeError, "Unable to copy input into output."); - {sub['fail']} + {sub["fail"]} }}; if (quadratic_{name}({Y}, a, b, c) != 0) {{ PyErr_SetString(PyExc_RuntimeError, "Unable to compute quadratic function."); - {sub['fail']} + {sub["fail"]} }} """ diff --git a/tests/link/c/test_type.py b/tests/link/c/test_type.py index 0ebd249bf4..5aa5765a43 100644 --- a/tests/link/c/test_type.py +++ b/tests/link/c/test_type.py @@ -201,7 +201,7 @@ def c_code_cache_version(self): def c_code(self, node, name, inputs, outputs, sub): # params in C code will already contains expected C constant value. return f""" - {outputs[0]} = {sub['params']}; + {outputs[0]} = {sub["params"]}; """ diff --git a/tests/link/jax/test_random.py b/tests/link/jax/test_random.py index 5a26d1617b..9cf148412e 100644 --- a/tests/link/jax/test_random.py +++ b/tests/link/jax/test_random.py @@ -90,9 +90,9 @@ def test_replaced_shared_rng_storage_order(noise_first): # The bug was found when noise used to be the first input of the fgraph # If this changes, the test may need to be tweaked to keep the save coverage - assert isinstance( - f.input_storage[1 - noise_first].type, RandomType - ), "Test may need to be tweaked" + assert isinstance(f.input_storage[1 - noise_first].type, RandomType), ( + "Test may need to be tweaked" + ) # Confirm that input_storage type and fgraph input order are aligned for storage, fgrapn_input in zip( diff --git a/tests/tensor/random/rewriting/test_basic.py b/tests/tensor/random/rewriting/test_basic.py index f8a6c243c0..1ef8e335aa 100644 --- a/tests/tensor/random/rewriting/test_basic.py +++ b/tests/tensor/random/rewriting/test_basic.py @@ -75,9 +75,9 @@ def apply_local_rewrite_to_rv( ).owner.outputs dist_st = op_fn(rv) - assert ( - count_rv_nodes_in_graph([dist_st, next_rng]) == 1 - ), "Function expects a single RV in the graph" + assert count_rv_nodes_in_graph([dist_st, next_rng]) == 1, ( + "Function expects a single RV in the graph" + ) f_inputs = [ p @@ -96,9 +96,9 @@ def apply_local_rewrite_to_rv( ) new_rv, new_next_rng = f_rewritten.maker.fgraph.outputs - assert ( - count_rv_nodes_in_graph([new_rv, new_next_rng]) == 1 - ), "Rewritten should have a single RV in the graph" + assert count_rv_nodes_in_graph([new_rv, new_next_rng]) == 1, ( + "Rewritten should have a single RV in the graph" + ) return new_rv, f_inputs, dist_st, f_rewritten diff --git a/tests/tensor/rewriting/test_blockwise.py b/tests/tensor/rewriting/test_blockwise.py index a17ad18a1f..de1ac8f15b 100644 --- a/tests/tensor/rewriting/test_blockwise.py +++ b/tests/tensor/rewriting/test_blockwise.py @@ -107,9 +107,9 @@ def test_blockwise_alloc(): y = tensor("y", shape=()) out = vector_add(alloc(x, 3, 1, 5), alloc(y, 7, 5)) expected_out = alloc(vector_add(alloc(x, 5), alloc(y, 5)), 3, 7, 5) - assert equal( - [rewrite(out)], [expected_out] - ), None # pytensor.dprint([expected_out, rewrite(out)], print_type=True) + assert equal([rewrite(out)], [expected_out]), ( + None + ) # pytensor.dprint([expected_out, rewrite(out)], print_type=True) x = tensor("x", shape=(5,)) y = tensor("y", shape=()) diff --git a/tests/tensor/rewriting/test_elemwise.py b/tests/tensor/rewriting/test_elemwise.py index cdd1f6bd77..24deb7ce19 100644 --- a/tests/tensor/rewriting/test_elemwise.py +++ b/tests/tensor/rewriting/test_elemwise.py @@ -1032,7 +1032,7 @@ def test_elemwise_fusion(self, case, nb_repeat=1, assert_len_topo=True): def test_fusion_35_inputs(self): r"""Make sure we don't fuse too many `Op`\s and go past the 31 function arguments limit.""" - inpts = vectors(["i%i" % i for i in range(35)]) + inpts = vectors([f"i{i}" for i in range(35)]) # Make an elemwise graph looking like: # sin(i34 + sin(i33 + sin(... i1 + sin(i0) ...))) diff --git a/tests/tensor/rewriting/test_math.py b/tests/tensor/rewriting/test_math.py index 9a092663a9..817178ad26 100644 --- a/tests/tensor/rewriting/test_math.py +++ b/tests/tensor/rewriting/test_math.py @@ -1809,9 +1809,9 @@ def assert_func_pair_rewritten( assert len(topo) in acceptable_topo_lens assert delta_condition - assert ( - isinstance(topo[0].op, DeepCopyOp) == should_copy - ), "Inverse functions not removed!" + assert isinstance(topo[0].op, DeepCopyOp) == should_copy, ( + "Inverse functions not removed!" + ) def test(self): """Test rewrites for consecutive functional inverses.""" diff --git a/tests/tensor/test_blas.py b/tests/tensor/test_blas.py index f3fcf72cc5..0d35f23523 100644 --- a/tests/tensor/test_blas.py +++ b/tests/tensor/test_blas.py @@ -585,9 +585,9 @@ def just_gemm(i, o, ishapes=None, max_graphlen=0, expected_nb_gemm=1): ) nb_gemm = 0 for node in f.maker.fgraph.apply_nodes: - assert not isinstance( - node.op, Dot - ), "_dot22 not changed to gemm_inplace in graph" + assert not isinstance(node.op, Dot), ( + "_dot22 not changed to gemm_inplace in graph" + ) assert node.op != _dot22 if node.op == gemm_inplace: nb_gemm += 1 @@ -603,9 +603,9 @@ def just_gemm(i, o, ishapes=None, max_graphlen=0, expected_nb_gemm=1): assert node.op != gemm_inplace, "gemm_inplace in original graph" graphlen = len(f.maker.fgraph.toposort()) - assert not ( - max_graphlen and (graphlen <= max_graphlen) - ), f"graphlen={graphlen}>{max_graphlen}" + assert not (max_graphlen and (graphlen <= max_graphlen)), ( + f"graphlen={graphlen}>{max_graphlen}" + ) rng = np.random.default_rng(unittest_tools.fetch_seed(234)) r0 = f(*[np.asarray(rng.standard_normal(sh), config.floatX) for sh in ishapes]) diff --git a/tests/tensor/test_elemwise.py b/tests/tensor/test_elemwise.py index e89a70d0f1..6aa9111aef 100644 --- a/tests/tensor/test_elemwise.py +++ b/tests/tensor/test_elemwise.py @@ -255,7 +255,7 @@ class TestBroadcast: cop = Elemwise openmp_minsize = 2 * config.openmp_elemwise_minsize - openmp_minsize_sqrt = int(math.ceil(math.sqrt(openmp_minsize))) + openmp_minsize_sqrt = math.ceil(math.sqrt(openmp_minsize)) # The order is important if you change them. linkers = [PerformLinker, CLinker] diff --git a/tests/tensor/test_math.py b/tests/tensor/test_math.py index 38207d0f5d..ca5ae8587b 100644 --- a/tests/tensor/test_math.py +++ b/tests/tensor/test_math.py @@ -2666,9 +2666,8 @@ def numpy_i_scalar(dtype): # behavior. return - if ( - {a_type, b_type} == {"complex128", "float32"} - or {a_type, b_type} == {"complex128", "float16"} + if {a_type, b_type} == {"complex128", "float32"} or ( + {a_type, b_type} == {"complex128", "float16"} and set(combo) == {"scalar", "array"} and pytensor_dtype == "complex128" and numpy_dtype == "complex64" diff --git a/tests/tensor/test_merge.py b/tests/tensor/test_merge.py index 6d5a884b88..561b5d7c89 100644 --- a/tests/tensor/test_merge.py +++ b/tests/tensor/test_merge.py @@ -48,11 +48,8 @@ def __repr__(self): return self.name def __eq__(self, other): - return ( - self is other - or isinstance(other, MyOp) - and self.x is not None - and self.x == other.x + return self is other or ( + isinstance(other, MyOp) and self.x is not None and self.x == other.x ) def __hash__(self): diff --git a/tests/tensor/test_slinalg.py b/tests/tensor/test_slinalg.py index f18f514244..e3a90f5500 100644 --- a/tests/tensor/test_slinalg.py +++ b/tests/tensor/test_slinalg.py @@ -236,7 +236,7 @@ def test_solve_raises_on_invalid_assume_a(): ("tridiagonal", False, True), ] solve_test_ids = [ - f'{assume_a}_{"lower" if lower else "upper"}_{"A^T" if transposed else "A"}' + f"{assume_a}_{'lower' if lower else 'upper'}_{'A^T' if transposed else 'A'}" for assume_a, lower, transposed in solve_test_cases ] diff --git a/tests/test_config.py b/tests/test_config.py index 2dd3c32180..5dbb71d680 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -233,9 +233,9 @@ def test_config_pickling(): for name in root._config_var_dict: v_original = getattr(root, name) v_restored = getattr(restored, name) - assert ( - v_restored == v_original - ), f"{name} did not survive pickling ({v_restored} != {v_original})" + assert v_restored == v_original, ( + f"{name} did not survive pickling ({v_restored} != {v_original})" + ) # and validate that the test would catch typical problems root = _create_test_config() diff --git a/tests/unittest_tools.py b/tests/unittest_tools.py index 1bdfc01410..7e34b04605 100644 --- a/tests/unittest_tools.py +++ b/tests/unittest_tools.py @@ -42,8 +42,7 @@ def fetch_seed(pseed=None): seed = None except ValueError: warnings.warn( - "Error: config.unittests__rseed contains " - "invalid seed, using None instead" + "Error: config.unittests__rseed contains invalid seed, using None instead" ) seed = None