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..7e2dcda5f6 100644 --- a/pymc/backends/arviz.py +++ b/pymc/backends/arviz.py @@ -26,14 +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 typing import Set # pylint: disable=ungrouped-imports - from pymc.backends.base import MultiTrace # pylint: disable=invalid-name - from pymc.model import Model ___all__ = [""] @@ -145,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 e5e9468db3..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__( @@ -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/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/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 diff --git a/pymc/model.py b/pymc/model.py index 1080543d1a..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. @@ -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, ) @@ -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/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): diff --git a/pymc/tests/test_model.py b/pymc/tests/test_model.py index 650a6295d2..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 @@ -406,7 +407,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/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: 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( 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): 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())