diff --git a/benchmarks/benchmarks/benchmarks.py b/benchmarks/benchmarks/benchmarks.py index 6ef7e47fa75..0cf4d5e3669 100644 --- a/benchmarks/benchmarks/benchmarks.py +++ b/benchmarks/benchmarks/benchmarks.py @@ -206,7 +206,7 @@ def track_marginal_mixture_model_ess(self, init): _, step = pm.init_nuts( init=init, chains=self.chains, progressbar=False, random_seed=np.arange(self.chains) ) - start = [{k: v for k, v in start.items()} for _ in range(self.chains)] + start = [dict(start) for _ in range(self.chains)] t0 = time.time() idata = pm.sample( draws=self.draws, diff --git a/docs/source/learn/core_notebooks/GLM_linear.ipynb b/docs/source/learn/core_notebooks/GLM_linear.ipynb index 7f4ebca2ad7..e1c7fb872c8 100644 --- a/docs/source/learn/core_notebooks/GLM_linear.ipynb +++ b/docs/source/learn/core_notebooks/GLM_linear.ipynb @@ -119,7 +119,7 @@ "# add noise\n", "y = true_regression_line + rng.normal(scale=0.5, size=size)\n", "\n", - "data = pd.DataFrame(dict(x=x, y=y))" + "data = pd.DataFrame({\"x\": x, \"y\": y})" ] }, { diff --git a/docs/source/learn/core_notebooks/pymc_overview.ipynb b/docs/source/learn/core_notebooks/pymc_overview.ipynb index 97395d75d52..3f4379dd224 100644 --- a/docs/source/learn/core_notebooks/pymc_overview.ipynb +++ b/docs/source/learn/core_notebooks/pymc_overview.ipynb @@ -3372,13 +3372,13 @@ " test_scores[\"score\"].values,\n", " kind=\"hist\",\n", " color=\"C1\",\n", - " hist_kwargs=dict(alpha=0.6),\n", + " hist_kwargs={\"alpha\": 0.6},\n", " label=\"observed\",\n", ")\n", "az.plot_dist(\n", " prior_samples.prior_predictive[\"scores\"],\n", " kind=\"hist\",\n", - " hist_kwargs=dict(alpha=0.6),\n", + " hist_kwargs={\"alpha\": 0.6},\n", " label=\"simulated\",\n", ")\n", "plt.xticks(rotation=45);" diff --git a/pymc/backends/base.py b/pymc/backends/base.py index 477723a6970..6aefed81b80 100644 --- a/pymc/backends/base.py +++ b/pymc/backends/base.py @@ -348,7 +348,7 @@ def nchains(self) -> int: @property def chains(self) -> list[int]: - return list(sorted(self._straces.keys())) + return sorted(self._straces.keys()) @property def report(self) -> SamplerReport: diff --git a/pymc/backends/mcbackend.py b/pymc/backends/mcbackend.py index f60b4e293eb..3e6dd8ba812 100644 --- a/pymc/backends/mcbackend.py +++ b/pymc/backends/mcbackend.py @@ -114,7 +114,7 @@ def __init__( def record(self, draw: Mapping[str, np.ndarray], stats: Sequence[Mapping[str, Any]]): values = self._point_fn(draw) - value_dict = {n: v for n, v in zip(self.varnames, values)} + value_dict = dict(zip(self.varnames, values)) stats_dict = self._statsbj.map(stats) # Apply pickling to objects stats for fname in self._statsbj.object_stats.keys(): diff --git a/pymc/backends/ndarray.py b/pymc/backends/ndarray.py index 23f05488b97..cf57f9805d7 100644 --- a/pymc/backends/ndarray.py +++ b/pymc/backends/ndarray.py @@ -84,7 +84,7 @@ def setup(self, draws, chain, sampler_vars=None) -> None: if self._stats is None: self._stats = [] for sampler in sampler_vars: - data: dict[str, np.ndarray] = dict() + data: dict[str, np.ndarray] = {} self._stats.append(data) for varname, dtype in sampler.items(): data[varname] = np.zeros(draws, dtype=dtype) diff --git a/pymc/distributions/custom.py b/pymc/distributions/custom.py index ec7e30e87fe..2e9a6887087 100644 --- a/pymc/distributions/custom.py +++ b/pymc/distributions/custom.py @@ -162,17 +162,17 @@ def rv_op( rv_type = type( class_name, (CustomDistRV,), - dict( - name=class_name, - inplace=False, - ndim_supp=ndim_supp, - ndims_params=ndims_params, - signature=signature, - dtype=dtype, - _print_name=(class_name, f"\\operatorname{{{class_name}}}"), + { + "name": class_name, + "inplace": False, + "ndim_supp": ndim_supp, + "ndims_params": ndims_params, + "signature": signature, + "dtype": dtype, + "_print_name": (class_name, f"\\operatorname{{{class_name}}}"), # Specific to CustomDist - _random_fn=random, - ), + "_random_fn": random, + }, ) # Dispatch custom methods @@ -278,10 +278,10 @@ def rv_op( class_name, (CustomSymbolicDistRV,), # If logp is not provided, we try to infer it from the dist graph - dict( - inline_logprob=logp is None, - _print_name=(class_name, f"\\operatorname{{{class_name}}}"), - ), + { + "inline_logprob": logp is None, + "_print_name": (class_name, f"\\operatorname{{{class_name}}}"), + }, ) # Dispatch custom methods diff --git a/pymc/distributions/dist_math.py b/pymc/distributions/dist_math.py index 87febe40232..32b61e2f6b5 100644 --- a/pymc/distributions/dist_math.py +++ b/pymc/distributions/dist_math.py @@ -221,7 +221,7 @@ def log_normal(x, mean, **kwargs): rho = kwargs.get("rho") tau = kwargs.get("tau") eps = kwargs.get("eps", 0.0) - check = sum(map(lambda a: a is not None, [sigma, w, rho, tau])) + check = sum(a is not None for a in [sigma, w, rho, tau]) if check > 1: raise ValueError("more than one required kwarg is passed") if check == 0: diff --git a/pymc/distributions/distribution.py b/pymc/distributions/distribution.py index df6f5efa089..1b11f18baef 100644 --- a/pymc/distributions/distribution.py +++ b/pymc/distributions/distribution.py @@ -588,7 +588,7 @@ def inline_symbolic_random_variable(fgraph, node): """ op = node.op if op.inline_logprob: - return clone_replace(op.inner_outputs, {u: v for u, v in zip(op.inner_inputs, node.inputs)}) + return clone_replace(op.inner_outputs, dict(zip(op.inner_inputs, node.inputs))) # Registered before pre-canonicalization which happens at position=-10 diff --git a/pymc/distributions/shape_utils.py b/pymc/distributions/shape_utils.py index 220abac80da..0cedd5da779 100644 --- a/pymc/distributions/shape_utils.py +++ b/pymc/distributions/shape_utils.py @@ -65,10 +65,10 @@ def to_tuple(shape): returned. If it is array-like, tuple(shape) is returned. """ if shape is None: - return tuple() + return () temp = np.atleast_1d(shape) if temp.size == 0: - return tuple() + return () else: return tuple(temp) diff --git a/pymc/distributions/simulator.py b/pymc/distributions/simulator.py index 7bfe3d3958a..dc7700f7d57 100644 --- a/pymc/distributions/simulator.py +++ b/pymc/distributions/simulator.py @@ -241,18 +241,18 @@ def rv_op( sim_op = type( class_name, (SimulatorRV,), - dict( - name=class_name, - ndim_supp=ndim_supp, - ndims_params=ndims_params, - signature=signature, - dtype=dtype, - inplace=False, - fn=fn, - _distance=distance, - _sum_stat=sum_stat, - epsilon=epsilon, - ), + { + "name": class_name, + "ndim_supp": ndim_supp, + "ndims_params": ndims_params, + "signature": signature, + "dtype": dtype, + "inplace": False, + "fn": fn, + "_distance": distance, + "_sum_stat": sum_stat, + "epsilon": epsilon, + }, )() return sim_op(*params, **kwargs) diff --git a/pymc/distributions/timeseries.py b/pymc/distributions/timeseries.py index dcac2708e9c..80b13f56d91 100644 --- a/pymc/distributions/timeseries.py +++ b/pymc/distributions/timeseries.py @@ -239,9 +239,9 @@ def random_walk_logp(op, values, *inputs, **kwargs): (value,) = values # Recreate RV and obtain inner graph rv_node = op.make_node(*inputs) - rv = clone_replace( - op.inner_outputs, replace={u: v for u, v in zip(op.inner_inputs, rv_node.inputs)} - )[op.default_output] + rv = clone_replace(op.inner_outputs, replace=dict(zip(op.inner_inputs, rv_node.inputs)))[ + op.default_output + ] # Obtain logp of the inner graph and collapse steps dimension return logp(rv, value).sum(axis=-1) diff --git a/pymc/func_utils.py b/pymc/func_utils.py index 7aaf91e9c6d..edcaf50952f 100644 --- a/pymc/func_utils.py +++ b/pymc/func_utils.py @@ -199,9 +199,7 @@ def find_constrained_prior( ) # save optimal parameters - opt_params = { - param_name: param_value for param_name, param_value in zip(init_guess.keys(), opt.x) - } + opt_params = dict(zip(init_guess.keys(), opt.x)) if fixed_params is not None: opt_params.update(fixed_params) return opt_params diff --git a/pymc/logprob/mixture.py b/pymc/logprob/mixture.py index 0970fe21ce0..1fd4b1156ce 100644 --- a/pymc/logprob/mixture.py +++ b/pymc/logprob/mixture.py @@ -506,7 +506,7 @@ def split_valued_ifelse(fgraph, node): replacements = {first_valued_out: first_valued_ifelse} if remaining_vars: - first_ifelse_ancestors = set(a for a in ancestors((first_then, first_else)) if a.owner) + first_ifelse_ancestors = {a for a in ancestors((first_then, first_else)) if a.owner} remaining_thens = [then_out for (then_out, _, _, _) in remaining_vars] remaininng_elses = [else_out for (_, else_out, _, _) in remaining_vars] if set(remaining_thens + remaininng_elses) & first_ifelse_ancestors: diff --git a/pymc/logprob/rewriting.py b/pymc/logprob/rewriting.py index bd171441ac7..08373ed7fcd 100644 --- a/pymc/logprob/rewriting.py +++ b/pymc/logprob/rewriting.py @@ -238,7 +238,7 @@ def construct_ir_fgraph( # Replace valued RVs by ValuedVar Ops so that rewrites are aware of conditioning points # We use clones of the value variables so that they are not affected by rewrites cloned_values = tuple(v.clone() for v in rv_values.values()) - ir_rv_values = {rv: value for rv, value in zip(fgraph.outputs, cloned_values)} + ir_rv_values = dict(zip(fgraph.outputs, cloned_values)) replacements = tuple((rv, valued_rv(rv, value)) for rv, value in ir_rv_values.items()) toposort_replace(fgraph, replacements, reverse=True) diff --git a/pymc/logprob/tensor.py b/pymc/logprob/tensor.py index a4f1324c99a..750ace56943 100644 --- a/pymc/logprob/tensor.py +++ b/pymc/logprob/tensor.py @@ -112,7 +112,7 @@ def logprob_join(op, values, axis, *base_rvs, **kwargs): axis=axis, ) - base_rvs_to_split_values = {base_rv: value for base_rv, value in zip(base_rvs, split_values)} + base_rvs_to_split_values = dict(zip(base_rvs, split_values)) logps = [ _logprob_helper(base_var, split_value) for base_var, split_value in base_rvs_to_split_values.items() diff --git a/pymc/sampling/forward.py b/pymc/sampling/forward.py index 7024dca4aca..c1504091e51 100644 --- a/pymc/sampling/forward.py +++ b/pymc/sampling/forward.py @@ -446,7 +446,7 @@ def sample_prior_predictive( ) # All model variables have a name, but mypy does not know this - _log.info(f"Sampling: {list(sorted(volatile_basic_rvs, key=lambda var: var.name))}") # type: ignore + _log.info(f"Sampling: {sorted(volatile_basic_rvs, key=lambda var: var.name)}") # type: ignore values = zip(*(sampler_fn() for i in range(draws))) data = {k: np.stack(v) for k, v in zip(names, values)} @@ -460,7 +460,7 @@ def sample_prior_predictive( if not return_inferencedata: return prior - ikwargs: dict[str, Any] = dict(model=model) + ikwargs: dict[str, Any] = {"model": model} if idata_kwargs: ikwargs.update(idata_kwargs) return pm.to_inference_data(prior=prior, **ikwargs) @@ -850,7 +850,7 @@ def sample_posterior_predictive( ) sampler_fn = point_wrapper(_sampler_fn) # All model variables have a name, but mypy does not know this - _log.info(f"Sampling: {list(sorted(volatile_basic_rvs, key=lambda var: var.name))}") # type: ignore + _log.info(f"Sampling: {sorted(volatile_basic_rvs, key=lambda var: var.name)}") # type: ignore ppc_trace_t = _DefaultTrace(samples) progress = CustomProgress( diff --git a/pymc/sampling/mcmc.py b/pymc/sampling/mcmc.py index 2f17357a910..228850e63e5 100644 --- a/pymc/sampling/mcmc.py +++ b/pymc/sampling/mcmc.py @@ -255,7 +255,7 @@ def _print_step_hierarchy(s: Step, level: int = 0) -> None: def all_continuous(vars): """Check that vars not include discrete variables""" - if any([(var.dtype in discrete_types) for var in vars]): + if any((var.dtype in discrete_types) for var in vars): return False else: return True @@ -947,7 +947,7 @@ def _sample_return( idata = None if compute_convergence_checks or return_inferencedata: - ikwargs: dict[str, Any] = dict(model=model, save_warmup=not discard_tuned_samples) + ikwargs: dict[str, Any] = {"model": model, "save_warmup": not discard_tuned_samples} ikwargs.update(idata_kwargs) idata = pm.to_inference_data(mtrace, **ikwargs) diff --git a/pymc/smc/kernels.py b/pymc/smc/kernels.py index 6576b425dfb..2bfde7583e9 100644 --- a/pymc/smc/kernels.py +++ b/pymc/smc/kernels.py @@ -356,7 +356,7 @@ def _posterior_to_trace(self, chain=0) -> NDArray: var_samples = np.round(var_samples).astype(var.dtype) value.append(var_samples.reshape(shape)) size += new_size - strace.record(point={k: v for k, v in zip(varnames, value)}) + strace.record(point=dict(zip(varnames, value))) return strace diff --git a/pymc/smc/sampling.py b/pymc/smc/sampling.py index 03e64f94c10..4cd3c11771a 100644 --- a/pymc/smc/sampling.py +++ b/pymc/smc/sampling.py @@ -293,7 +293,7 @@ def _save_sample_stats( library=pymc, ) - ikwargs: dict[str, Any] = dict(model=model) + ikwargs: dict[str, Any] = {"model": model} if idata_kwargs is not None: ikwargs.update(idata_kwargs) idata = to_inference_data(trace, **ikwargs) diff --git a/pymc/step_methods/metropolis.py b/pymc/step_methods/metropolis.py index e6f9d9dc77a..21fb6c83e83 100644 --- a/pymc/step_methods/metropolis.py +++ b/pymc/step_methods/metropolis.py @@ -245,7 +245,7 @@ def __init__( self.accepted_sum = np.zeros(dims, dtype=int) # remember initial settings before tuning so they can be reset - self._untuned_settings = dict(scaling=self.scaling, steps_until_tune=tune_interval) + self._untuned_settings = {"scaling": self.scaling, "steps_until_tune": tune_interval} # TODO: This is not being used when compiling the logp function! self.mode = mode @@ -422,7 +422,7 @@ def __init__(self, vars, scaling=1.0, tune=True, tune_interval=100, model=None, vars = get_value_vars_from_user_vars(vars, model) - if not all([v.dtype in pm.discrete_types for v in vars]): + if not all(v.dtype in pm.discrete_types for v in vars): raise ValueError("All variables must be Bernoulli for BinaryMetropolis") super().__init__(vars, [model.compile_logp()], rng=rng) @@ -541,7 +541,7 @@ def __init__(self, vars, order="random", transit_p=0.8, model=None, rng=None): self.shuffle_dims = False self.order = order - if not all([v.dtype in pm.discrete_types for v in vars]): + if not all(v.dtype in pm.discrete_types for v in vars): raise ValueError("All variables must be binary for BinaryGibbsMetropolis") super().__init__(vars, [model.compile_logp()], rng=rng) @@ -1063,12 +1063,12 @@ def __init__( # cache local history for the Z-proposals self._history: list[np.ndarray] = [] # remember initial settings before tuning so they can be reset - self._untuned_settings = dict( - scaling=self.scaling, - lamb=self.lamb, - steps_until_tune=tune_interval, - accepted=self.accepted, - ) + self._untuned_settings = { + "scaling": self.scaling, + "lamb": self.lamb, + "steps_until_tune": tune_interval, + "accepted": self.accepted, + } self.mode = mode diff --git a/pymc/variational/approximations.py b/pymc/variational/approximations.py index d2ff5df970e..1f42e552855 100644 --- a/pymc/variational/approximations.py +++ b/pymc/variational/approximations.py @@ -46,7 +46,7 @@ class MeanFieldGroup(Group): of the method """ - __param_spec__ = dict(mu=("d",), rho=("d",)) + __param_spec__ = {"mu": ("d",), "rho": ("d",)} short_name = "mean_field" alias_names = frozenset(["mf"]) @@ -122,7 +122,7 @@ class FullRankGroup(Group): main drawback of the method is computational cost. """ - __param_spec__ = dict(mu=("d",), L_tril=("int(d * (d + 1) / 2)",)) + __param_spec__ = {"mu": ("d",), "L_tril": ("int(d * (d + 1) / 2)",)} short_name = "full_rank" alias_names = frozenset(["fr"]) @@ -193,14 +193,14 @@ class EmpiricalGroup(Group): """ has_logq = False - __param_spec__ = dict(histogram=("s", "d")) + __param_spec__ = {"histogram": ("s", "d")} short_name = "empirical" @pytensor.config.change_flags(compute_test_value="off") def __init_group__(self, group): super().__init_group__(group) self._check_trace() - if not self._check_user_params(spec_kw=dict(s=-1)): + if not self._check_user_params(spec_kw={"s": -1}): self.shared_params = self.create_shared_params( trace=self._kwargs.get("trace", None), size=self._kwargs.get("size", None), @@ -225,7 +225,7 @@ def create_shared_params(self, trace=None, size=None, jitter=1, start=None): for j in range(len(trace)): histogram[i] = DictToArrayBijection.map(trace.point(j, t)).data i += 1 - return dict(histogram=pytensor.shared(pm.floatX(histogram), "histogram")) + return {"histogram": pytensor.shared(pm.floatX(histogram), "histogram")} def _check_trace(self): trace = self._kwargs.get("trace", None) @@ -236,7 +236,7 @@ def _check_trace(self): " Please help us to refactor: https://github.com/pymc-devs/pymc/issues/5884" ) elif trace is not None and not all( - [self.model.rvs_to_values[var].name in trace.varnames for var in self.group] + self.model.rvs_to_values[var].name in trace.varnames for var in self.group ): raise ValueError("trace has not all free RVs in the group") @@ -344,7 +344,7 @@ def __getattr__(self, item): def __dir__(self): d = set(super().__dir__()) d.update(self.groups[0].__dir__()) - return list(sorted(d)) + return sorted(d) class MeanField(SingleGroupApproximation): diff --git a/pymc/variational/callbacks.py b/pymc/variational/callbacks.py index 36904db5eb1..820e9d7b847 100644 --- a/pymc/variational/callbacks.py +++ b/pymc/variational/callbacks.py @@ -36,9 +36,10 @@ def absolute(current: np.ndarray, prev: np.ndarray) -> np.ndarray: return np.abs(diff) -_diff: dict[str, Callable[[np.ndarray, np.ndarray], np.ndarray]] = dict( - relative=relative, absolute=absolute -) +_diff: dict[str, Callable[[np.ndarray, np.ndarray], np.ndarray]] = { + "relative": relative, + "absolute": absolute, +} class CheckParametersConvergence(Callback): diff --git a/pymc/variational/inference.py b/pymc/variational/inference.py index 0c596d2d981..9a400bb1e6e 100644 --- a/pymc/variational/inference.py +++ b/pymc/variational/inference.py @@ -82,7 +82,7 @@ def _maybe_score(self, score): def run_profiling(self, n=1000, score=None, **kwargs): score = self._maybe_score(score) - fn_kwargs = kwargs.pop("fn_kwargs", dict()) + fn_kwargs = kwargs.pop("fn_kwargs", {}) fn_kwargs["profile"] = True step_func = self.objective.step_function(score=score, fn_kwargs=fn_kwargs, **kwargs) try: @@ -739,7 +739,7 @@ def fit( :class:`Approximation` """ if inf_kwargs is None: - inf_kwargs = dict() + inf_kwargs = {} else: inf_kwargs = inf_kwargs.copy() if random_seed is not None: @@ -752,7 +752,7 @@ def fit( inf_kwargs["start_sigma"] = start_sigma if model is None: model = pm.modelcontext(model) - _select = dict(advi=ADVI, fullrank_advi=FullRankADVI, svgd=SVGD, asvgd=ASVGD) + _select = {"advi": ADVI, "fullrank_advi": FullRankADVI, "svgd": SVGD, "asvgd": ASVGD} if isinstance(method, str): method = method.lower() if method in _select: diff --git a/pymc/variational/opvi.py b/pymc/variational/opvi.py index 96db3b26927..898b6afc54c 100644 --- a/pymc/variational/opvi.py +++ b/pymc/variational/opvi.py @@ -249,7 +249,7 @@ def updates( :class:`ObjectiveUpdates` """ if more_updates is None: - more_updates = dict() + more_updates = {} resulting_updates = ObjectiveUpdates() if self.test_params: self.add_test_updates( @@ -288,7 +288,7 @@ def add_test_updates( if more_tf_params is None: more_tf_params = [] if more_replacements is None: - more_replacements = dict() + more_replacements = {} tf_target = self( tf_n_mc, more_tf_params=more_tf_params, more_replacements=more_replacements ) @@ -309,7 +309,7 @@ def add_obj_updates( if more_obj_params is None: more_obj_params = [] if more_replacements is None: - more_replacements = dict() + more_replacements = {} obj_target = self( obj_n_mc, more_obj_params=more_obj_params, more_replacements=more_replacements ) @@ -526,11 +526,11 @@ def collect_shared_to_list(params): List """ if isinstance(params, dict): - return list( + return [ t[1] for t in sorted(params.items(), key=lambda t: t[0]) if isinstance(t[1], pytensor.compile.SharedVariable) - ) + ] elif params is None: return [] else: @@ -676,11 +676,11 @@ class Group(WithMemoization): initial_dist_map = 0.0 # for handy access using class methods - __param_spec__: dict = dict() + __param_spec__: dict = {} short_name = "" alias_names: frozenset[str] = frozenset() - __param_registry: dict[frozenset, Any] = dict() - __name_registry: dict[str, Any] = dict() + __param_registry: dict[frozenset, Any] = {} + __name_registry: dict[str, Any] = {} @classmethod def register(cls, sbcls): @@ -739,7 +739,7 @@ def __init__( if isinstance(vfam, str): vfam = vfam.lower() if options is None: - options = dict() + options = {} self.options = options self._vfam = vfam self.rng = np.random.RandomState(random_seed) @@ -771,7 +771,7 @@ def _prepare_start(self, start=None): @classmethod def get_param_spec_for(cls, **kwargs): - res = dict() + res = {} for name, fshape in cls.__param_spec__.items(): res[name] = tuple(eval(s, kwargs) for s in fshape) return res @@ -800,7 +800,7 @@ def _check_user_params(self, **kwargs): "Passed parameters do not have a needed set of keys, " f"they should be equal, got {givens}, needed {needed}" ) - self._user_params = dict() + self._user_params = {} spec = self.get_param_spec_for(d=self.ddim, **kwargs.pop("spec_kw", {})) for name, param in self.user_params.items(): shape = spec[name] @@ -1149,7 +1149,7 @@ def var_to_data(self, shared: pt.TensorVariable) -> xarray.Dataset: # This is somewhat similar to `DictToArrayBijection.rmap`, which doesn't work here since we don't have # `RaveledVars` and need to take the information from `self.ordering` instead shared_nda = shared.eval() - result = dict() + result = {} for name, s, shape, dtype in self.ordering.values(): dims = self.model.named_vars_to_dims.get(name, None) if dims is not None: @@ -1206,7 +1206,7 @@ def __init__(self, groups, model=None): model = modelcontext(model) if not model.free_RVs: raise TypeError("Model does not have an free RVs") - self.groups = list() + self.groups = [] seen = set() rest = None for g in groups: @@ -1529,7 +1529,7 @@ def inner(draws=100, *, random_seed: SeedSequenceSeed = None): reseed_rngs(rng_nodes, random_seed) _samples = sample_fn(draws) - return {v_: s_ for v_, s_ in zip(names, _samples)} + return dict(zip(names, _samples)) return inner diff --git a/pyproject.toml b/pyproject.toml index f59054eb132..770fd0e0405 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,7 +37,7 @@ extend-exclude = ["_version.py"] docstring-code-format = true [tool.ruff.lint] -select = ["D", "E", "F", "I", "UP", "W", "RUF"] +select = ["C4", "D", "E", "F", "I", "UP", "W", "RUF"] ignore = [ "E501", "F841", # Local variable name is assigned to but never used diff --git a/tests/backends/fixtures.py b/tests/backends/fixtures.py index ed4e066994f..1b02eb8bcab 100644 --- a/tests/backends/fixtures.py +++ b/tests/backends/fixtures.py @@ -459,8 +459,8 @@ def test_nchains(self): assert self.mtrace.nchains == self.dumped.nchains def test_varnames(self): - trace_names = list(sorted(self.mtrace.varnames)) - dumped_names = list(sorted(self.dumped.varnames)) + trace_names = sorted(self.mtrace.varnames) + dumped_names = sorted(self.dumped.varnames) assert trace_names == dumped_names def test_values(self): diff --git a/tests/backends/test_arviz.py b/tests/backends/test_arviz.py index 99ff551d2b7..18599738ae3 100644 --- a/tests/backends/test_arviz.py +++ b/tests/backends/test_arviz.py @@ -337,7 +337,7 @@ def test_missing_data_model(self): with pytest.warns(ImputationWarning): y = pm.Normal("y", x, 1, observed=data) inference_data = pm.sample( - 100, chains=2, return_inferencedata=True, idata_kwargs=dict(log_likelihood=True) + 100, chains=2, return_inferencedata=True, idata_kwargs={"log_likelihood": True} ) # make sure that data is really missing @@ -370,7 +370,7 @@ def test_mv_missing_data_model(self): draws=10, chains=2, step=pm.Metropolis(), - idata_kwargs=dict(log_likelihood=True), + idata_kwargs={"log_likelihood": True}, ) # make sure that data is really missing @@ -422,7 +422,7 @@ def test_single_observation(self): p = pm.Uniform("p", 0, 1) pm.Binomial("w", p=p, n=2, observed=[1]) inference_data = pm.sample( - 500, chains=2, return_inferencedata=True, idata_kwargs=dict(log_likelihood=True) + 500, chains=2, return_inferencedata=True, idata_kwargs={"log_likelihood": True} ) assert inference_data @@ -607,7 +607,7 @@ def test_multivariate_observations(self): chains=2, tune=100, return_inferencedata=True, - idata_kwargs=dict(log_likelihood=True), + idata_kwargs={"log_likelihood": True}, ) test_dict = { "posterior": ["p"], @@ -688,9 +688,13 @@ def test_include_transformed(self): pm.Uniform("p", 0, 1) # First check that the default is to exclude the transformed variables - sample_kwargs = dict( - tune=5, draws=7, chains=2, cores=1, compute_convergence_checks=False - ) + sample_kwargs = { + "tune": 5, + "draws": 7, + "chains": 2, + "cores": 1, + "compute_convergence_checks": False, + } inference_data = pm.sample(**sample_kwargs, step=pm.Metropolis()) assert "p_interval__" not in inference_data.posterior diff --git a/tests/backends/test_mcbackend.py b/tests/backends/test_mcbackend.py index 6d0704d1a5f..23240af3771 100644 --- a/tests/backends/test_mcbackend.py +++ b/tests/backends/test_mcbackend.py @@ -200,7 +200,7 @@ def test_get_sampler_stats(self): rng = np.random.RandomState(2023) for i in range(N): draw = {"a": rng.normal(), "b_interval__": rng.normal()} - stats = [dict(tune=(i <= 5), s1=i, accepted=bool(rng.randint(0, 2)))] + stats = [{"tune": (i <= 5), "s1": i, "accepted": bool(rng.randint(0, 2))}] cra.record(draw, stats) # Check final state of the chain @@ -251,8 +251,8 @@ def test_get_sampler_stats_compound(self, caplog): tune = i <= 5 draw = {"a": rng.normal(), "b_interval__": rng.normal()} stats = [ - dict(tune=tune, s1=i, accepted=bool(rng.randint(0, 2))), - dict(tune=tune, s2=i, accepted=bool(rng.randint(0, 2))), + {"tune": tune, "s1": i, "accepted": bool(rng.randint(0, 2))}, + {"tune": tune, "s2": i, "accepted": bool(rng.randint(0, 2))}, ] cra.record(draw, stats) diff --git a/tests/distributions/test_discrete.py b/tests/distributions/test_discrete.py index b727c8a9d1d..fa74b729449 100644 --- a/tests/distributions/test_discrete.py +++ b/tests/distributions/test_discrete.py @@ -483,7 +483,7 @@ def test_orderedprobit(self, n): # TODO: Is this test working as expected / still relevant? -@pytest.mark.parametrize("shape", [tuple(), (1,), (3, 1), (3, 2)], ids=str) +@pytest.mark.parametrize("shape", [(), (1,), (3, 1), (3, 2)], ids=str) def test_orderedlogistic_dimensions(shape): # Test for issue #3535 loge = np.log10(np.exp(1)) diff --git a/tests/distributions/test_distribution.py b/tests/distributions/test_distribution.py index 8974a6017a7..545bf177358 100644 --- a/tests/distributions/test_distribution.py +++ b/tests/distributions/test_distribution.py @@ -55,7 +55,7 @@ class TestBugfixes: - @pytest.mark.parametrize("dist_cls,kwargs", [(MvNormal, dict()), (MvStudentT, dict(nu=2))]) + @pytest.mark.parametrize("dist_cls,kwargs", [(MvNormal, {}), (MvStudentT, {"nu": 2})]) @pytest.mark.parametrize("dims", [1, 2, 4]) def test_issue_3051(self, dims, dist_cls, kwargs): mu = np.repeat(0, dims) diff --git a/tests/distributions/test_mixture.py b/tests/distributions/test_mixture.py index e77b1ccf3a0..0e247e5e560 100644 --- a/tests/distributions/test_mixture.py +++ b/tests/distributions/test_mixture.py @@ -812,7 +812,7 @@ def test_normal_mixture_sampling(self, seeded_test): assert_allclose(np.sort(trace["mu"].mean(axis=0)), np.sort(norm_mu), rtol=0.1, atol=0.1) @pytest.mark.parametrize( - "nd, ncomp", [(tuple(), 5), (1, 5), (3, 5), ((3, 3), 5), (3, 3), ((3, 3), 3)], ids=str + "nd, ncomp", [((), 5), (1, 5), (3, 5), ((3, 3), 5), (3, 3), ((3, 3), 3)], ids=str ) def test_normal_mixture_nd(self, seeded_test, nd, ncomp): nd = to_tuple(nd) diff --git a/tests/distributions/test_shape_utils.py b/tests/distributions/test_shape_utils.py index 951772570de..493d7cb8c61 100644 --- a/tests/distributions/test_shape_utils.py +++ b/tests/distributions/test_shape_utils.py @@ -40,21 +40,21 @@ from pymc.model import Model test_shapes = [ - (tuple(), (1,), (4,), (5, 4)), - (tuple(), (1,), (7,), (5, 4)), - (tuple(), (1,), (1, 4), (5, 4)), - (tuple(), (1,), (5, 1), (5, 4)), - (tuple(), (1,), (3, 4), (5, 4)), - (tuple(), (1,), (5, 3), (5, 4)), - (tuple(), (1,), (10, 4), (5, 4)), - (tuple(), (1,), (10,), (5, 4)), - (tuple(), (1,), (1, 1, 4), (5, 4)), - (tuple(), (1,), (10, 1, 4), (5, 4)), - (tuple(), (1,), (10, 5, 4), (5, 4)), + ((), (1,), (4,), (5, 4)), + ((), (1,), (7,), (5, 4)), + ((), (1,), (1, 4), (5, 4)), + ((), (1,), (5, 1), (5, 4)), + ((), (1,), (3, 4), (5, 4)), + ((), (1,), (5, 3), (5, 4)), + ((), (1,), (10, 4), (5, 4)), + ((), (1,), (10,), (5, 4)), + ((), (1,), (1, 1, 4), (5, 4)), + ((), (1,), (10, 1, 4), (5, 4)), + ((), (1,), (10, 5, 4), (5, 4)), ] test_sizes = [ None, - tuple(), + (), 1, (1,), 10, @@ -66,7 +66,7 @@ (5, 4), (1, 1, 1, 1), ] -test_to_shapes = [None, tuple(), (10, 5, 4), (10, 1, 1, 5, 1)] +test_to_shapes = [None, (), (10, 5, 4), (10, 1, 1, 5, 1)] @pytest.fixture(params=test_sizes, ids=str) @@ -180,7 +180,7 @@ def test_simultaneous_size_and_dims(self): assert "ddata" in pmodel.dim_lengths # Size does not include support dims, so this test must use a dist with support dims. - kwargs = dict(name="y", size=(2, 3), mu=pt.ones((3, 4)), cov=pt.eye(4)) + kwargs = {"name": "y", "size": (2, 3), "mu": pt.ones((3, 4)), "cov": pt.eye(4)} y = pm.MvNormal(**kwargs, dims=("dsize", "ddata", "dsupport")) assert pmodel.named_vars_to_dims["y"] == ("dsize", "ddata", "dsupport") @@ -309,7 +309,7 @@ def test_convert_size(self): def test_lazy_flavors(self): assert pm.Uniform.dist(2, [4, 5], size=[3, 2]).eval().shape == (3, 2) assert pm.Uniform.dist(2, [4, 5], shape=[3, 2]).eval().shape == (3, 2) - with pm.Model(coords=dict(town=["Greifswald", "Madrid"])): + with pm.Model(coords={"town": ["Greifswald", "Madrid"]}): assert pm.Normal("n1", mu=[1, 2], dims="town").eval().shape == (2,) assert pm.Normal("n2", mu=[1, 2], dims=["town"]).eval().shape == (2,) @@ -321,7 +321,7 @@ def test_size_from_dims_rng_update(self): """Test that when setting size from dims we update the rng properly See https://github.com/pymc-devs/pymc/issues/5653 """ - with pm.Model(coords=dict(x_dim=range(2))): + with pm.Model(coords={"x_dim": range(2)}): x = pm.Normal("x", dims=("x_dim",)) fn = pm.pytensorf.compile_pymc([], x) diff --git a/tests/distributions/test_timeseries.py b/tests/distributions/test_timeseries.py index 771894737ab..ca4d0eb49e0 100644 --- a/tests/distributions/test_timeseries.py +++ b/tests/distributions/test_timeseries.py @@ -234,7 +234,7 @@ def test_change_size_multivariate(self): ) @pytest.mark.parametrize("steps_source", ("shape", "dims", "observed")) def test_infer_steps(self, init_dist, innovation_dist, shape, steps, steps_source): - shape_source_kwargs = dict(shape=None, dims=None, observed=None) + shape_source_kwargs = {"shape": None, "dims": None, "observed": None} if steps_source == "shape": shape_source_kwargs["shape"] = shape elif steps_source == "dims": @@ -464,12 +464,16 @@ def test_mvstudentt(self, param): @pytest.mark.parametrize( "distribution, init_dist, build_kwargs", [ - (GaussianRandomWalk, Normal.dist(), dict()), - (MvGaussianRandomWalk, Dirichlet.dist(np.ones(3)), dict(mu=np.zeros(3), tau=np.eye(3))), + (GaussianRandomWalk, Normal.dist(), {}), + ( + MvGaussianRandomWalk, + Dirichlet.dist(np.ones(3)), + {"mu": np.zeros(3), "tau": np.eye(3)}, + ), ( MvStudentTRandomWalk, Dirichlet.dist(np.ones(3)), - dict(nu=4, mu=np.zeros(3), tau=np.eye(3)), + {"nu": 4, "mu": np.zeros(3), "tau": np.eye(3)}, ), ], ) @@ -782,12 +786,12 @@ def test_logp(self): def test_batched_size(self, explicit_shape, batched_param): steps, batch_size = 100, 5 param_val = np.square(np.random.randn(batch_size)) - init_kwargs = dict( - omega=1.25, - alpha_1=0.5, - beta_1=0.45, - initial_vol=2.5, - ) + init_kwargs = { + "omega": 1.25, + "alpha_1": 0.5, + "beta_1": 0.45, + "initial_vol": 2.5, + } kwargs0 = init_kwargs.copy() kwargs0[batched_param] = init_kwargs[batched_param] * param_val if explicit_shape: diff --git a/tests/helpers.py b/tests/helpers.py index b9d5c6d0199..ae62d72d565 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -208,8 +208,8 @@ def continuous_steps(self, step, step_kwargs): def equal_sampling_states(this, other): if this.__class__ != other.__class__: return False - this_fields = set([f.name for f in fields(this)]) - other_fields = set([f.name for f in fields(other)]) + this_fields = {f.name for f in fields(this)} + other_fields = {f.name for f in fields(other)} for field in this_fields: this_val = getattr(this, field) other_val = getattr(other, field) diff --git a/tests/logprob/test_scan.py b/tests/logprob/test_scan.py index 09c7e2d952b..381eed221d1 100644 --- a/tests/logprob/test_scan.py +++ b/tests/logprob/test_scan.py @@ -517,7 +517,7 @@ def test_scan_multiple_output_types(): outputs_info=[ None, pt.zeros(()), - dict(initial=pt.ones(2), taps=[-2, -1]), + {"initial": pt.ones(2), "taps": [-2, -1]}, ], ) diff --git a/tests/logprob/test_utils.py b/tests/logprob/test_utils.py index 10cd36fc39a..a982076db73 100644 --- a/tests/logprob/test_utils.py +++ b/tests/logprob/test_utils.py @@ -151,8 +151,7 @@ def test_intermediate_rv(self): res_ancestors = list(ancestors((res,))) assert ( - len(list(n for n in res_ancestors if n.owner and isinstance(n.owner.op, MeasurableOp))) - == 1 + len([n for n in res_ancestors if n.owner and isinstance(n.owner.op, MeasurableOp)]) == 1 ) assert c_value_var in res_ancestors diff --git a/tests/model/test_core.py b/tests/model/test_core.py index cea9edf6471..17304fedc42 100644 --- a/tests/model/test_core.py +++ b/tests/model/test_core.py @@ -321,7 +321,7 @@ def test_invalid_type(self): def setUp(self): extra1 = pt.iscalar("extra1") extra1_ = np.array(0, dtype=extra1.dtype) - extra1.dshape = tuple() + extra1.dshape = () extra1.dsize = 1 val1 = pt.vector("val1") @@ -811,9 +811,9 @@ def test_datalogp_multiple_shapes(): def test_nested_model_coords(): - with pm.Model(name="m1", coords=dict(dim1=range(2))) as m1: + with pm.Model(name="m1", coords={"dim1": range(2)}) as m1: a = pm.Normal("a", dims="dim1") - with pm.Model(name="m2", coords=dict(dim2=range(4))) as m2: + with pm.Model(name="m2", coords={"dim2": range(4)}) as m2: b = pm.Normal("b", dims="dim1") m1.add_coord("dim3", range(4)) c = pm.HalfNormal("c", dims="dim3") @@ -837,7 +837,7 @@ def test_resize_from_set_data_dim_with_coords(self): # Does not resize dim pmodel.set_data("m", [3, 4]) # Resizes, but also passes new coords - pmodel.set_data("m", [1, 2, 3], coords=dict(dim_with_coords=[1, 2, 3])) + pmodel.set_data("m", [1, 2, 3], coords={"dim_with_coords": [1, 2, 3]}) # Resizes, but does not pass new coords with pytest.raises(ValueError, match="'m' variable already had 3"): @@ -971,12 +971,12 @@ def test_set_data_indirect_resize_with_coords(self): # Now the other way around. with warnings.catch_warnings(): warnings.simplefilter("error") - pmodel.set_data("mdata", [1, 2, 3, 4], coords=dict(mdim=["A", "B", "C", "D"])) + pmodel.set_data("mdata", [1, 2, 3, 4], coords={"mdim": ["A", "B", "C", "D"]}) assert pmodel.coords["mdim"] == ("A", "B", "C", "D") # This time with incorrectly sized coord values with pytest.raises(ShapeError, match="new coordinate values"): - pmodel.set_data("mdata", [1, 2], coords=dict(mdim=[1, 2, 3])) + pmodel.set_data("mdata", [1, 2], coords={"mdim": [1, 2, 3]}) def test_set_data_warns_on_resize_of_dims_defined_by_other_data(self): with pm.Model() as pmodel: diff --git a/tests/sampling/test_forward.py b/tests/sampling/test_forward.py index 76c89825d81..2b5ce1265a8 100644 --- a/tests/sampling/test_forward.py +++ b/tests/sampling/test_forward.py @@ -1332,10 +1332,10 @@ def test_pytensor_function_kwargs(self): prior = pm.sample_prior_predictive( draws=5, return_inferencedata=False, - compile_kwargs=dict( - mode=Mode("py"), - updates={sharedvar: sharedvar + 1}, - ), + compile_kwargs={ + "mode": Mode("py"), + "updates": {sharedvar: sharedvar + 1}, + }, ) assert np.all(prior["y"] == np.arange(5)) @@ -1380,10 +1380,10 @@ def test_pytensor_function_kwargs(self): trace=az_from_dict({"x": np.arange(5)}), var_names=["y"], return_inferencedata=False, - compile_kwargs=dict( - mode=Mode("py"), - updates={sharedvar: sharedvar + 1}, - ), + compile_kwargs={ + "mode": Mode("py"), + "updates": {sharedvar: sharedvar + 1}, + }, ) assert np.all(pp["y"] == np.arange(5) * 2) @@ -1467,8 +1467,8 @@ def sample_prior(self, distribution, shape, nested_rvs_info, prior_samples): @pytest.mark.parametrize( ["prior_samples", "shape", "mu", "alpha"], [ - [10, (3,), (None, tuple()), (None, (3,))], - [10, (3,), (None, (3,)), (None, tuple())], + [10, (3,), (None, ()), (None, (3,))], + [10, (3,), (None, (3,)), (None, ())], [ 10, ( @@ -1500,7 +1500,7 @@ def test_NegativeBinomial( prior = self.sample_prior( distribution=pm.NegativeBinomial, shape=shape, - nested_rvs_info=dict(mu=mu, alpha=alpha), + nested_rvs_info={"mu": mu, "alpha": alpha}, prior_samples=prior_samples, ) assert prior["target"].shape == (prior_samples, *shape) @@ -1508,10 +1508,10 @@ def test_NegativeBinomial( @pytest.mark.parametrize( ["prior_samples", "shape", "psi", "mu", "alpha"], [ - [10, (3,), (0.5, tuple()), (None, tuple()), (None, (3,))], - [10, (3,), (0.5, (3,)), (None, tuple()), (None, (3,))], - [10, (3,), (0.5, tuple()), (None, (3,)), (None, tuple())], - [10, (3,), (0.5, (3,)), (None, (3,)), (None, tuple())], + [10, (3,), (0.5, ()), (None, ()), (None, (3,))], + [10, (3,), (0.5, (3,)), (None, ()), (None, (3,))], + [10, (3,), (0.5, ()), (None, (3,)), (None, ())], + [10, (3,), (0.5, (3,)), (None, (3,)), (None, ())], [ 10, ( @@ -1546,7 +1546,7 @@ def test_ZeroInflatedNegativeBinomial( prior = self.sample_prior( distribution=pm.ZeroInflatedNegativeBinomial, shape=shape, - nested_rvs_info=dict(psi=psi, mu=mu, alpha=alpha), + nested_rvs_info={"psi": psi, "mu": mu, "alpha": alpha}, prior_samples=prior_samples, ) assert prior["target"].shape == (prior_samples, *shape) @@ -1554,10 +1554,10 @@ def test_ZeroInflatedNegativeBinomial( @pytest.mark.parametrize( ["prior_samples", "shape", "nu", "sigma"], [ - [10, (3,), (None, tuple()), (None, (3,))], - [10, (3,), (None, tuple()), (None, (3,))], - [10, (3,), (None, (3,)), (None, tuple())], - [10, (3,), (None, (3,)), (None, tuple())], + [10, (3,), (None, ()), (None, (3,))], + [10, (3,), (None, ()), (None, (3,))], + [10, (3,), (None, (3,)), (None, ())], + [10, (3,), (None, (3,)), (None, ())], [ 10, ( @@ -1589,7 +1589,7 @@ def test_Rice( prior = self.sample_prior( distribution=pm.Rice, shape=shape, - nested_rvs_info=dict(nu=nu, sigma=sigma), + nested_rvs_info={"nu": nu, "sigma": sigma}, prior_samples=prior_samples, ) assert prior["target"].shape == (prior_samples, *shape) @@ -1597,10 +1597,10 @@ def test_Rice( @pytest.mark.parametrize( ["prior_samples", "shape", "mu", "sigma", "lower", "upper"], [ - [10, (3,), (None, tuple()), (1.0, tuple()), (None, tuple(), -1), (None, (3,))], - [10, (3,), (None, tuple()), (1.0, tuple()), (None, tuple(), -1), (None, (3,))], - [10, (3,), (None, tuple()), (1.0, tuple()), (None, (3,), -1), (None, tuple())], - [10, (3,), (None, tuple()), (1.0, tuple()), (None, (3,), -1), (None, tuple())], + [10, (3,), (None, ()), (1.0, ()), (None, (), -1), (None, (3,))], + [10, (3,), (None, ()), (1.0, ()), (None, (), -1), (None, (3,))], + [10, (3,), (None, ()), (1.0, ()), (None, (3,), -1), (None, ())], + [10, (3,), (None, ()), (1.0, ()), (None, (3,), -1), (None, ())], [ 10, ( @@ -1608,7 +1608,7 @@ def test_Rice( 3, ), (None, (3,)), - (1.0, tuple()), + (1.0, ()), (None, (3,), -1), (None, (3,)), ], @@ -1619,21 +1619,21 @@ def test_Rice( 3, ), (None, (3,)), - (1.0, tuple()), + (1.0, ()), (None, (3,), -1), (None, (4, 3)), ], - [10, (3,), (0.0, tuple()), (None, tuple()), (None, tuple(), -1), (None, (3,))], - [10, (3,), (0.0, tuple()), (None, tuple()), (None, tuple(), -1), (None, (3,))], - [10, (3,), (0.0, tuple()), (None, tuple()), (None, (3,), -1), (None, tuple())], - [10, (3,), (0.0, tuple()), (None, tuple()), (None, (3,), -1), (None, tuple())], + [10, (3,), (0.0, ()), (None, ()), (None, (), -1), (None, (3,))], + [10, (3,), (0.0, ()), (None, ()), (None, (), -1), (None, (3,))], + [10, (3,), (0.0, ()), (None, ()), (None, (3,), -1), (None, ())], + [10, (3,), (0.0, ()), (None, ()), (None, (3,), -1), (None, ())], [ 10, ( 4, 3, ), - (0.0, tuple()), + (0.0, ()), (None, (3,)), (None, (3,), -1), (None, (3,)), @@ -1644,7 +1644,7 @@ def test_Rice( 4, 3, ), - (0.0, tuple()), + (0.0, ()), (None, (3,)), (None, (3,), -1), (None, (4, 3)), @@ -1664,7 +1664,7 @@ def test_TruncatedNormal( prior = self.sample_prior( distribution=pm.TruncatedNormal, shape=shape, - nested_rvs_info=dict(mu=mu, sigma=sigma, lower=lower, upper=upper), + nested_rvs_info={"mu": mu, "sigma": sigma, "lower": lower, "upper": upper}, prior_samples=prior_samples, ) assert prior["target"].shape == (prior_samples, *shape) @@ -1672,9 +1672,9 @@ def test_TruncatedNormal( @pytest.mark.parametrize( ["prior_samples", "shape", "c", "lower", "upper"], [ - [10, (3,), (None, tuple()), (-1.0, (3,)), (2, tuple())], - [10, (3,), (None, tuple()), (-1.0, tuple()), (None, tuple(), 1)], - [10, (3,), (None, (3,)), (-1.0, tuple()), (None, tuple(), 1)], + [10, (3,), (None, ()), (-1.0, (3,)), (2, ())], + [10, (3,), (None, ()), (-1.0, ()), (None, (), 1)], + [10, (3,), (None, (3,)), (-1.0, ()), (None, (), 1)], [ 10, ( @@ -1682,7 +1682,7 @@ def test_TruncatedNormal( 3, ), (None, (3,)), - (-1.0, tuple()), + (-1.0, ()), (None, (3,), 1), ], [ @@ -1692,7 +1692,7 @@ def test_TruncatedNormal( 3, ), (None, (3,)), - (None, tuple(), -1), + (None, (), -1), (None, (3,), 1), ], ], @@ -1709,7 +1709,7 @@ def test_Triangular( prior = self.sample_prior( distribution=pm.Triangular, shape=shape, - nested_rvs_info=dict(c=c, lower=lower, upper=upper), + nested_rvs_info={"c": c, "lower": lower, "upper": upper}, prior_samples=prior_samples, ) assert prior["target"].shape == (prior_samples, *shape) diff --git a/tests/sampling/test_jax.py b/tests/sampling/test_jax.py index 5f32e1075cc..e9db8e7000e 100644 --- a/tests/sampling/test_jax.py +++ b/tests/sampling/test_jax.py @@ -223,7 +223,7 @@ def test_get_log_likelihood(): draws=10, chains=2, random_seed=1322, - idata_kwargs=dict(log_likelihood=True), + idata_kwargs={"log_likelihood": True}, ) b_true = trace.log_likelihood.b.values @@ -284,14 +284,14 @@ def model_test_idata_kwargs() -> pm.Model: @pytest.mark.parametrize( "idata_kwargs", [ - dict(), - dict(log_likelihood=True), + {}, + {"log_likelihood": True}, # Overwrite models coords - dict(coords={"x_coord": ["x1", "x2"]}), + {"coords": {"x_coord": ["x1", "x2"]}}, # Overwrite dims from dist specification in model - dict(dims={"x": ["x_coord2"]}), + {"dims": {"x": ["x_coord2"]}}, # Overwrite both coords and dims - dict(coords={"x_coord3": ["A", "B"]}, dims={"x": ["x_coord3"]}), + {"coords": {"x_coord3": ["A", "B"]}, "dims": {"x": ["x_coord3"]}}, ], ) @pytest.mark.parametrize("postprocessing_backend", [None, "cpu"]) @@ -377,12 +377,12 @@ def test_get_batched_jittered_initial_points(): ], ) def test_seeding(chains, random_seed, sampler): - sample_kwargs = dict( - tune=100, - draws=5, - chains=chains, - random_seed=random_seed, - ) + sample_kwargs = { + "tune": 100, + "draws": 5, + "chains": chains, + "random_seed": random_seed, + } with pm.Model() as m: pm.Normal("x", mu=0, sigma=1) diff --git a/tests/sampling/test_mcmc.py b/tests/sampling/test_mcmc.py index e39a5612cc5..8ba7b133ba0 100644 --- a/tests/sampling/test_mcmc.py +++ b/tests/sampling/test_mcmc.py @@ -110,7 +110,7 @@ def test_default_sample_does_not_set_global_seed(self, mocked_seed): # Test that when random_seed is None, `np.random.seed` is not called in the main # process. Ideally it would never be called, but PyMC step samplers still rely # on global seeding for reproducible behavior. - kwargs = dict(tune=2, draws=2, random_seed=None) + kwargs = {"tune": 2, "draws": 2, "random_seed": None} with self.model: with warnings.catch_warnings(): warnings.filterwarnings("ignore", ".*number of samples.*", UserWarning) @@ -121,12 +121,12 @@ def test_default_sample_does_not_set_global_seed(self, mocked_seed): def test_sample_does_not_rely_on_external_global_seeding(self): # Tests that sampling does not depend on exertenal global seeding - kwargs = dict( - tune=2, - draws=20, - random_seed=None, - return_inferencedata=False, - ) + kwargs = { + "tune": 2, + "draws": 20, + "random_seed": None, + "return_inferencedata": False, + } with self.model: with warnings.catch_warnings(): warnings.filterwarnings("ignore", ".*number of samples.*", UserWarning) @@ -438,14 +438,14 @@ def test_keep_warning_stat_setting(self, keep_warning_stat): to keep the ``SamplerWarning`` objects from the ``sample_stats.warning`` group. This breaks ``idata.to_netcdf()`` which is why it defaults to ``False``. """ - sample_kwargs = dict( - tune=2, - draws=3, - chains=1, - compute_convergence_checks=False, - discard_tuned_samples=False, - keep_warning_stat=keep_warning_stat, - ) + sample_kwargs = { + "tune": 2, + "draws": 3, + "chains": 1, + "compute_convergence_checks": False, + "discard_tuned_samples": False, + "keep_warning_stat": keep_warning_stat, + } if keep_warning_stat: sample_kwargs["keep_warning_stat"] = True with pm.Model(): diff --git a/tests/sampling/test_mcmc_external.py b/tests/sampling/test_mcmc_external.py index 4c594a2b642..3305d018f1c 100644 --- a/tests/sampling/test_mcmc_external.py +++ b/tests/sampling/test_mcmc_external.py @@ -31,15 +31,15 @@ def test_external_nuts_sampler(recwarn, nuts_sampler): Normal("L", mu=x, sigma=0.1, observed=y) - kwargs = dict( - nuts_sampler=nuts_sampler, - random_seed=123, - chains=2, - tune=500, - draws=500, - progressbar=False, - initvals={"x": 0.0}, - ) + kwargs = { + "nuts_sampler": nuts_sampler, + "random_seed": 123, + "chains": 2, + "tune": 500, + "draws": 500, + "progressbar": False, + "initvals": {"x": 0.0}, + } idata1 = sample(**kwargs) idata2 = sample(**kwargs) diff --git a/tests/stats/test_convergence.py b/tests/stats/test_convergence.py index 4eac933c9e2..f468fc5e5bf 100644 --- a/tests/stats/test_convergence.py +++ b/tests/stats/test_convergence.py @@ -59,8 +59,8 @@ def test_warn_treedepth_multiple_samplers(): def test_log_warning_stats(caplog): - s1 = dict(warning="Temperature too low!") - s2 = dict(warning="Temperature too high!") + s1 = {"warning": "Temperature too low!"} + s2 = {"warning": "Temperature too high!"} stats = [s1, s2] with caplog.at_level(logging.WARNING): @@ -78,7 +78,7 @@ def test_log_warning_stats_knows_SamplerWarning(caplog): "Not that interesting", "debug", ) - stats = [dict(warning=warn)] + stats = [{"warning": warn}] with caplog.at_level(logging.DEBUG, logger="pymc"): convergence.log_warning_stats(stats) diff --git a/tests/step_methods/test_compound.py b/tests/step_methods/test_compound.py index 4a83ec593ca..556deffe320 100644 --- a/tests/step_methods/test_compound.py +++ b/tests/step_methods/test_compound.py @@ -179,8 +179,8 @@ def test_stats_bijection(self): assert bij.n_samplers == 2 w = Warning("hmm") stats_l = [ - dict(a=1.5, b=3), - dict(a=2.5, c=w), + {"a": 1.5, "b": 3}, + {"a": 2.5, "c": w}, ] stats_d = bij.map(stats_l) assert isinstance(stats_d, dict) diff --git a/tests/test_model_graph.py b/tests/test_model_graph.py index 5c2633f226b..866253f4e71 100644 --- a/tests/test_model_graph.py +++ b/tests/test_model_graph.py @@ -436,7 +436,7 @@ class TestModelWithDims(BaseModelGraphTest): model_func = model_with_dims def test_issue_6335_dims_containing_none(self): - with pm.Model(coords=dict(time=np.arange(5))) as pmodel: + with pm.Model(coords={"time": np.arange(5)}) as pmodel: data = pt.as_tensor(np.ones((3, 5))) pm.Deterministic("n", data, dims=(None, "time")) @@ -561,17 +561,15 @@ def test_custom_node_formatting_graphviz(simple_model): } G = model_to_graphviz(simple_model, node_formatters=node_formatters) - body = set(item.strip() for item in G.body) - - items = set( - [ - "a [label=a]", - "b [label=b]", - "c [label=c]", - "a -> b", - "b -> c", - ] - ) + body = {item.strip() for item in G.body} + + items = { + "a [label=a]", + "b [label=b]", + "c [label=c]", + "a -> b", + "b -> c", + } assert body == items diff --git a/tests/test_pytensorf.py b/tests/test_pytensorf.py index de1b14c36d2..f0ae4355976 100644 --- a/tests/test_pytensorf.py +++ b/tests/test_pytensorf.py @@ -546,11 +546,11 @@ def test_nested_updates(self): collect_default_updates(inputs=[], outputs=[x, y, z]) == {rng: next_rng3} fn = compile_pymc([], [x, y, z], random_seed=514) - assert not set(list(np.array(fn()))) & set(list(np.array(fn()))) + assert not set(np.array(fn())) & set(np.array(fn())) # A local myopic rule (as PyMC used before, would not work properly) fn = pytensor.function([], [x, y, z], updates={rng: next_rng1}) - assert set(list(np.array(fn()))) & set(list(np.array(fn()))) + assert set(np.array(fn())) & set(np.array(fn())) def test_collect_default_updates_must_be_shared(self): shared_rng = pytensor.shared(np.random.default_rng()) diff --git a/tests/test_util.py b/tests/test_util.py index 2a8c4164ca8..8771bb05157 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -165,7 +165,7 @@ def test_drop_warning_stat(): "a": np.ones((2, 5, 4)), "warning": np.ones((2, 5, 3), dtype=object), }, - attrs=dict(version="0.1.2"), + attrs={"version": "0.1.2"}, coords={ "adim": [0, 1, None, 3], "warning_dim_0": list("ABC"), diff --git a/tests/variational/test_inference.py b/tests/variational/test_inference.py index df0208633a5..5fb4237e9a3 100644 --- a/tests/variational/test_inference.py +++ b/tests/variational/test_inference.py @@ -62,15 +62,15 @@ def simple_model_data(use_minibatch): mu_post = (n * np.mean(data) / sigma**2 + mu0 / sigma0**2) / d if use_minibatch: data = pm.Minibatch(data, batch_size=128) - return dict( - n=n, - data=data, - mu_post=mu_post, - d=d, - mu0=mu0, - sigma0=sigma0, - sigma=sigma, - ) + return { + "n": n, + "data": data, + "mu_post": mu_post, + "d": d, + "mu0": mu0, + "sigma0": sigma0, + "sigma": sigma, + } @pytest.fixture @@ -95,10 +95,10 @@ def simple_model(simple_model_data): @pytest.fixture( scope="module", params=[ - dict(cls=ADVI, init=dict()), - dict(cls=FullRankADVI, init=dict()), - dict(cls=SVGD, init=dict(n_particles=500, jitter=1)), - dict(cls=ASVGD, init=dict(temperature=1.0)), + {"cls": ADVI, "init": {}}, + {"cls": FullRankADVI, "init": {}}, + {"cls": SVGD, "init": {"n_particles": 500, "jitter": 1}}, + {"cls": ASVGD, "init": {"temperature": 1.0}}, ], ids=["ADVI", "FullRankADVI", "SVGD", "ASVGD"], ) @@ -128,24 +128,40 @@ def inference(inference_spec, simple_model): @pytest.fixture(scope="function") def fit_kwargs(inference, use_minibatch): _select = { - (ADVI, "full"): dict(obj_optimizer=pm.adagrad_window(learning_rate=0.02, n_win=50), n=5000), - (ADVI, "mini"): dict( - obj_optimizer=pm.adagrad_window(learning_rate=0.01, n_win=50), n=12000 - ), - (FullRankADVI, "full"): dict( - obj_optimizer=pm.adagrad_window(learning_rate=0.015, n_win=50), n=6000 - ), - (FullRankADVI, "mini"): dict( - obj_optimizer=pm.adagrad_window(learning_rate=0.007, n_win=50), n=12000 - ), - (SVGD, "full"): dict(obj_optimizer=pm.adagrad_window(learning_rate=0.075, n_win=7), n=300), - (SVGD, "mini"): dict(obj_optimizer=pm.adagrad_window(learning_rate=0.075, n_win=7), n=300), - (ASVGD, "full"): dict( - obj_optimizer=pm.adagrad_window(learning_rate=0.07, n_win=10), n=500, obj_n_mc=300 - ), - (ASVGD, "mini"): dict( - obj_optimizer=pm.adagrad_window(learning_rate=0.07, n_win=10), n=500, obj_n_mc=300 - ), + (ADVI, "full"): { + "obj_optimizer": pm.adagrad_window(learning_rate=0.02, n_win=50), + "n": 5000, + }, + (ADVI, "mini"): { + "obj_optimizer": pm.adagrad_window(learning_rate=0.01, n_win=50), + "n": 12000, + }, + (FullRankADVI, "full"): { + "obj_optimizer": pm.adagrad_window(learning_rate=0.015, n_win=50), + "n": 6000, + }, + (FullRankADVI, "mini"): { + "obj_optimizer": pm.adagrad_window(learning_rate=0.007, n_win=50), + "n": 12000, + }, + (SVGD, "full"): { + "obj_optimizer": pm.adagrad_window(learning_rate=0.075, n_win=7), + "n": 300, + }, + (SVGD, "mini"): { + "obj_optimizer": pm.adagrad_window(learning_rate=0.075, n_win=7), + "n": 300, + }, + (ASVGD, "full"): { + "obj_optimizer": pm.adagrad_window(learning_rate=0.07, n_win=10), + "n": 500, + "obj_n_mc": 300, + }, + (ASVGD, "mini"): { + "obj_optimizer": pm.adagrad_window(learning_rate=0.07, n_win=10), + "n": 500, + "obj_n_mc": 300, + }, } if use_minibatch: key = "mini" @@ -198,16 +214,16 @@ def test_fit_start(inference_spec, simple_model): @pytest.mark.parametrize( ["method", "kwargs", "error"], [ - ("undefined", dict(), KeyError), - (1, dict(), TypeError), - ("advi", dict(total_grad_norm_constraint=10), None), - ("fullrank_advi", dict(), None), - ("svgd", dict(total_grad_norm_constraint=10), None), - ("svgd", dict(start={}), None), + ("undefined", {}, KeyError), + (1, {}, TypeError), + ("advi", {"total_grad_norm_constraint": 10}, None), + ("fullrank_advi", {}, None), + ("svgd", {"total_grad_norm_constraint": 10}, None), + ("svgd", {"start": {}}, None), # start argument is not allowed for ASVGD - ("asvgd", dict(start={}, total_grad_norm_constraint=10), TypeError), - ("asvgd", dict(total_grad_norm_constraint=10), None), - ("nfvi=bad-formula", dict(start={}), KeyError), + ("asvgd", {"start": {}, "total_grad_norm_constraint": 10}, TypeError), + ("asvgd", {"total_grad_norm_constraint": 10}, None), + ("nfvi=bad-formula", {"start": {}}, KeyError), ], ) def test_fit_fn_text(method, kwargs, error): @@ -383,17 +399,17 @@ def hierarchical_model_data(): data = sigma * np.random.randn(*data_shape) + group_mu + mu - return dict( - group_coords=group_coords, - group_shape=group_shape, - data_coords=data_coords, - data_shape=data_shape, - mu=mu, - sigma_group_mu=sigma_group_mu, - sigma=sigma, - group_mu=group_mu, - data=data, - ) + return { + "group_coords": group_coords, + "group_shape": group_shape, + "data_coords": data_coords, + "data_shape": data_shape, + "mu": mu, + "sigma_group_mu": sigma_group_mu, + "sigma": sigma, + "group_mu": group_mu, + "data": data, + } @pytest.fixture @@ -430,7 +446,7 @@ def test_fit_data_coords(hierarchical_model, hierarchical_model_data): assert list(data["group_mu"].coords.keys()) == list( hierarchical_model_data["group_coords"].keys() ) - assert data["mu"].shape == tuple() + assert data["mu"].shape == () def test_multiple_minibatch_variables(): diff --git a/tests/variational/test_opvi.py b/tests/variational/test_opvi.py index 5b02571898a..43ba772216f 100644 --- a/tests/variational/test_opvi.py +++ b/tests/variational/test_opvi.py @@ -83,19 +83,19 @@ def test_group_api_vfam(three_var_model, raises, vfam, type_, kw): [ ( not_raises(), - dict(mu=np.ones((10, 2), "float32"), rho=np.ones((10, 2), "float32")), + {"mu": np.ones((10, 2), "float32"), "rho": np.ones((10, 2), "float32")}, MeanFieldGroup, {}, None, ), ( not_raises(), - dict( - mu=np.ones((10, 2), "float32"), - L_tril=np.ones( + { + "mu": np.ones((10, 2), "float32"), + "L_tril": np.ones( FullRankGroup.get_param_spec_for(d=np.prod((10, 2)))["L_tril"], "float32" ), - ), + }, FullRankGroup, {}, None, diff --git a/tests/variational/test_updates.py b/tests/variational/test_updates.py index cd0e02b22f0..9f591675bb4 100644 --- a/tests/variational/test_updates.py +++ b/tests/variational/test_updates.py @@ -62,9 +62,7 @@ ], # all missing -> partial ids=["all_params", "missing_loss", "missing_params", "all_missing"], ) -@pytest.mark.parametrize( - "kwargs", [dict(), dict(learning_rate=1e-2)], ids=["without_args", "with_args"] -) +@pytest.mark.parametrize("kwargs", [{}, {"learning_rate": 1e-2}], ids=["without_args", "with_args"]) @pytest.mark.parametrize( "loss_and_params", [(_b, [_a]), (_n, [_m]), (_n2, [_a, _m, _m2])], @@ -73,9 +71,9 @@ def test_updates_fast(opt, loss_and_params, kwargs, getter): with pytensor.config.change_flags(compute_test_value="ignore"): loss, param = getter(loss_and_params) - args = dict() + args = {} args.update(**kwargs) - args.update(dict(loss_or_grads=loss, params=param)) + args.update({"loss_or_grads": loss, "params": param}) if loss is None and param is None: updates = opt(**args) # Here we should get new callable