From f7c266f4686a2e730ce018cf6fbf2ae1b1315936 Mon Sep 17 00:00:00 2001 From: Virgile Andreani Date: Mon, 14 Nov 2022 17:13:17 -0500 Subject: [PATCH 1/7] Use `a not in b` instead of `not a in b` --- pymc/data.py | 2 +- pymc/model.py | 2 +- pymc/model_graph.py | 4 ++-- pymc/tests/test_model.py | 2 +- pymc/tests/tuning/test_starting.py | 2 +- scripts/run_mypy.py | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pymc/data.py b/pymc/data.py index e5e9468db3..fa11a8f189 100644 --- a/pymc/data.py +++ b/pymc/data.py @@ -708,7 +708,7 @@ def Data( xshape = x.shape # Register new dimension lengths for d, dname in enumerate(dims): - if not dname in model.dim_lengths: + if dname not in model.dim_lengths: model.add_coord( name=dname, # Note: Coordinate values can't be taken from diff --git a/pymc/model.py b/pymc/model.py index 1080543d1a..50da9880c9 100644 --- a/pymc/model.py +++ b/pymc/model.py @@ -1292,7 +1292,7 @@ def register_rv( # the length of the corresponding RV dimension. if dims is not None: for d, dname in enumerate(dims): - if not dname in self.dim_lengths: + if dname not in self.dim_lengths: self.add_coord(dname, values=None, length=rv_var.shape[d]) if data is None: diff --git a/pymc/model_graph.py b/pymc/model_graph.py index 93eed6ce01..d44bec8842 100644 --- a/pymc/model_graph.py +++ b/pymc/model_graph.py @@ -355,7 +355,7 @@ def model_to_networkx( model_to_networkx(schools) """ - if not "plain" in formatting: + if "plain" not in formatting: raise ValueError(f"Unsupported formatting for graph nodes: '{formatting}'. See docstring.") @@ -419,7 +419,7 @@ def model_to_graphviz( model_to_graphviz(schools) """ - if not "plain" in formatting: + if "plain" not in formatting: raise ValueError(f"Unsupported formatting for graph nodes: '{formatting}'. See docstring.") if formatting != "plain": warnings.warn( diff --git a/pymc/tests/test_model.py b/pymc/tests/test_model.py index 650a6295d2..5bedfa2e57 100644 --- a/pymc/tests/test_model.py +++ b/pymc/tests/test_model.py @@ -406,7 +406,7 @@ def test_multiple_observed_rv(): assert not model["x"] == model["mu"] assert model["x"] == model["x"] assert model["x"] in model.observed_RVs - assert not model["x"] in model.value_vars + assert model["x"] not in model.value_vars def test_tempered_logp_dlogp(): diff --git a/pymc/tests/tuning/test_starting.py b/pymc/tests/tuning/test_starting.py index e4902e8ced..c68a61df52 100644 --- a/pymc/tests/tuning/test_starting.py +++ b/pymc/tests/tuning/test_starting.py @@ -42,7 +42,7 @@ def test_mle_jacobian(bounded): def test_tune_not_inplace(): orig_scaling = np.array([0.001, 0.1]) returned_scaling = tune(orig_scaling, acc_rate=0.6) - assert not returned_scaling is orig_scaling + assert returned_scaling is not orig_scaling assert np.all(orig_scaling == np.array([0.001, 0.1])) diff --git a/scripts/run_mypy.py b/scripts/run_mypy.py index 5bd538c793..4ba0d40e0d 100644 --- a/scripts/run_mypy.py +++ b/scripts/run_mypy.py @@ -144,7 +144,7 @@ def check_no_unexpected_results(mypy_lines: Iterator[str]): all_files = { str(fp).replace(str(DP_ROOT), "").strip(os.sep).replace(os.sep, "/") for fp in DP_ROOT.glob("pymc/**/*.py") - if not "tests" in str(fp) + if "tests" not in str(fp) } failing = set(df.reset_index().file.str.replace(os.sep, "/", regex=False)) if not failing.issubset(all_files): From 0af501d75418622c8c6220fe4f4e5d2ab6fe8de8 Mon Sep 17 00:00:00 2001 From: Virgile Andreani Date: Mon, 14 Nov 2022 17:17:21 -0500 Subject: [PATCH 2/7] Remove unnecessary imports --- docs/source/conf.py | 1 - pymc/backends/arviz.py | 1 - setup.py | 1 - setupegg.py | 1 - 4 files changed, 4 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index 0293b0355f..99c346bdaa 100755 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -17,7 +17,6 @@ # serve to show the default. import os -import sys from pathlib import Path import pymc # isort:skip diff --git a/pymc/backends/arviz.py b/pymc/backends/arviz.py index 19864a5281..1b2969d07e 100644 --- a/pymc/backends/arviz.py +++ b/pymc/backends/arviz.py @@ -30,7 +30,6 @@ from pymc.util import get_default_varnames if TYPE_CHECKING: - from typing import Set # pylint: disable=ungrouped-imports from pymc.backends.base import MultiTrace # pylint: disable=invalid-name from pymc.model import Model diff --git a/setup.py b/setup.py index b1f534be5b..e88e837aed 100755 --- a/setup.py +++ b/setup.py @@ -12,7 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import re from codecs import open from os.path import dirname, join, realpath diff --git a/setupegg.py b/setupegg.py index 888a65c9b1..fdf78d2816 100755 --- a/setupegg.py +++ b/setupegg.py @@ -17,7 +17,6 @@ A setup.py script to use setuptools, which gives egg goodness, etc. """ -from setuptools import setup with open("setup.py") as s: exec(s.read()) From 41aa2e7301b16f23a9d38989a245ce28b9aa97a2 Mon Sep 17 00:00:00 2001 From: Virgile Andreani Date: Mon, 14 Nov 2022 17:25:24 -0500 Subject: [PATCH 3/7] Fix a warning raising --- pymc/gp/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pymc/gp/util.py b/pymc/gp/util.py index 68dc46cd9e..8e109a7f63 100644 --- a/pymc/gp/util.py +++ b/pymc/gp/util.py @@ -136,7 +136,7 @@ def kmeans_inducing_points(n_inducing, X, **kmeans_kwargs): Xw = X / scaling if "k_or_guess" in kmeans_kwargs: - warn.UserWarning("Use `n_inducing` to set the `k_or_guess` parameter instead.") + warnings.warn("Use `n_inducing` to set the `k_or_guess` parameter instead.") Xu, distortion = kmeans(Xw, k_or_guess=n_inducing, **kmeans_kwargs) return Xu * scaling From 47665f1907558d716ce77d0a8697fee6f93024af Mon Sep 17 00:00:00 2001 From: Virgile Andreani Date: Mon, 14 Nov 2022 17:28:54 -0500 Subject: [PATCH 4/7] Remove unnecessary f string --- pymc/model.py | 2 +- pymc/variational/inference.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pymc/model.py b/pymc/model.py index 50da9880c9..313e5df10e 100644 --- a/pymc/model.py +++ b/pymc/model.py @@ -1093,7 +1093,7 @@ def set_dim(self, name: str, new_length: int, coord_values: Optional[Sequence] = len_cvals = len(coord_values) if len_cvals != new_length: raise ShapeError( - f"Length of new coordinate values does not match the new dimension length.", + "Length of new coordinate values does not match the new dimension length.", actual=len_cvals, expected=new_length, ) diff --git a/pymc/variational/inference.py b/pymc/variational/inference.py index 82da26d3ab..b2f8a4a0ba 100644 --- a/pymc/variational/inference.py +++ b/pymc/variational/inference.py @@ -258,7 +258,7 @@ def _infmean(input_array): ) else: if n == 0: - logger.info(f"Initialization only") + logger.info("Initialization only") elif n < 10: logger.info(f"Finished [100%]: Loss = {scores[-1]:,.5g}") else: From a677e3b62a1eeea5bfc8b2a1bc66940dbb1d72b5 Mon Sep 17 00:00:00 2001 From: Virgile Andreani Date: Mon, 14 Nov 2022 17:29:06 -0500 Subject: [PATCH 5/7] Add missing traceback import --- pymc/tests/test_model.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pymc/tests/test_model.py b/pymc/tests/test_model.py index 5bedfa2e57..68f99d1e8a 100644 --- a/pymc/tests/test_model.py +++ b/pymc/tests/test_model.py @@ -13,6 +13,7 @@ # limitations under the License. import pickle import threading +import traceback import unittest import warnings From 62150004f8e55feac07352c66e18973dd75f8bda Mon Sep 17 00:00:00 2001 From: Virgile Andreani Date: Mon, 14 Nov 2022 17:34:39 -0500 Subject: [PATCH 6/7] Fix typo --- pymc/tests/distributions/test_discrete.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pymc/tests/distributions/test_discrete.py b/pymc/tests/distributions/test_discrete.py index 23229bdd74..7f326c79fd 100644 --- a/pymc/tests/distributions/test_discrete.py +++ b/pymc/tests/distributions/test_discrete.py @@ -69,7 +69,7 @@ def categorical_logpdf(value, p): if value >= 0 and value <= len(p): return floatX(np.log(np.moveaxis(p, -1, 0)[value])) else: - return -inf + return -np.inf def invlogit(x, eps=sys.float_info.epsilon): From b658bb994f1d3fe2c5aa432bd0da5e3ce2658459 Mon Sep 17 00:00:00 2001 From: Virgile Andreani Date: Mon, 14 Nov 2022 18:16:32 -0500 Subject: [PATCH 7/7] Use new-style typing annotations, not comments --- pymc/backends/arviz.py | 14 +++++--------- pymc/backends/ndarray.py | 2 +- pymc/data.py | 2 +- pymc/distributions/distribution.py | 4 ++-- pymc/model.py | 2 +- pymc/variational/opvi.py | 2 +- 6 files changed, 11 insertions(+), 15 deletions(-) diff --git a/pymc/backends/arviz.py b/pymc/backends/arviz.py index 1b2969d07e..7e2dcda5f6 100644 --- a/pymc/backends/arviz.py +++ b/pymc/backends/arviz.py @@ -26,13 +26,11 @@ import pymc from pymc.aesaraf import extract_obs_data -from pymc.model import modelcontext +from pymc.model import Model, modelcontext from pymc.util import get_default_varnames if TYPE_CHECKING: - from pymc.backends.base import MultiTrace # pylint: disable=invalid-name - from pymc.model import Model ___all__ = [""] @@ -144,12 +142,10 @@ def insert(self, k: str, v, idx: int): class InferenceDataConverter: # pylint: disable=too-many-instance-attributes """Encapsulate InferenceData specific logic.""" - model = None # type: Optional[Model] - nchains = None # type: int - ndraws = None # type: int - posterior_predictive = None # Type: Optional[Mapping[str, np.ndarray]] - predictions = None # Type: Optional[Mapping[str, np.ndarray]] - prior = None # Type: Optional[Mapping[str, np.ndarray]] + model: Optional[Model] = None + posterior_predictive: Optional[Mapping[str, np.ndarray]] = None + predictions: Optional[Mapping[str, np.ndarray]] = None + prior: Optional[Mapping[str, np.ndarray]] = None def __init__( self, diff --git a/pymc/backends/ndarray.py b/pymc/backends/ndarray.py index c5913f682e..df1aa010a5 100644 --- a/pymc/backends/ndarray.py +++ b/pymc/backends/ndarray.py @@ -85,7 +85,7 @@ def setup(self, draws, chain, sampler_vars=None) -> None: if self._stats is None: self._stats = [] for sampler in sampler_vars: - data = dict() # type: Dict[str, np.ndarray] + data: Dict[str, np.ndarray] = dict() self._stats.append(data) for varname, dtype in sampler.items(): data[varname] = np.zeros(draws, dtype=dtype) diff --git a/pymc/data.py b/pymc/data.py index fa11a8f189..54042f8f75 100644 --- a/pymc/data.py +++ b/pymc/data.py @@ -301,7 +301,7 @@ class Minibatch(TensorVariable): >>> assert x.eval().shape == (2, 20, 20, 40, 10) """ - RNG = collections.defaultdict(list) # type: Dict[str, List[Any]] + RNG: Dict[str, List[Any]] = collections.defaultdict(list) @aesara.config.change_flags(compute_test_value="raise") def __init__( diff --git a/pymc/distributions/distribution.py b/pymc/distributions/distribution.py index 13cad0cf5d..cc19d036c9 100644 --- a/pymc/distributions/distribution.py +++ b/pymc/distributions/distribution.py @@ -63,9 +63,9 @@ DIST_PARAMETER_TYPES: TypeAlias = Union[np.ndarray, int, float, TensorVariable] -vectorized_ppc = contextvars.ContextVar( +vectorized_ppc: contextvars.ContextVar[Optional[Callable]] = contextvars.ContextVar( "vectorized_ppc", default=None -) # type: contextvars.ContextVar[Optional[Callable]] +) PLATFORM = sys.platform diff --git a/pymc/model.py b/pymc/model.py index 313e5df10e..37e77ffb9d 100644 --- a/pymc/model.py +++ b/pymc/model.py @@ -188,7 +188,7 @@ def get_context(cls, error_if_none=True) -> Optional[T]: on the stack, or ``None``. If ``error_if_none`` is True (default), raise a ``TypeError`` instead of returning ``None``.""" try: - candidate = cls.get_contexts()[-1] # type: Optional[T] + candidate: Optional[T] = cls.get_contexts()[-1] except IndexError as e: # Calling code expects to get a TypeError if the entity # is unfound, and there's too much to fix. diff --git a/pymc/variational/opvi.py b/pymc/variational/opvi.py index 9002b381c2..f0c854b66f 100644 --- a/pymc/variational/opvi.py +++ b/pymc/variational/opvi.py @@ -1482,7 +1482,7 @@ def sample( if random_seed is not None: (random_seed,) = _get_seeds_per_chain(random_seed, 1) - samples = self.sample_dict_fn(draws, random_seed=random_seed) # type: dict + samples: dict = self.sample_dict_fn(draws, random_seed=random_seed) points = ({name: records[i] for name, records in samples.items()} for i in range(draws)) trace = NDArray(