Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
# serve to show the default.

import os
import sys
from pathlib import Path

import pymc # isort:skip
Expand Down
15 changes: 5 additions & 10 deletions pymc/backends/arviz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__ = [""]

Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion pymc/backends/ndarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions pymc/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__(
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pymc/distributions/distribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion pymc/gp/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions pymc/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions pymc/model_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")

Expand Down Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion pymc/tests/distributions/test_discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
3 changes: 2 additions & 1 deletion pymc/tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.
import pickle
import threading
import traceback
import unittest
import warnings

Expand Down Expand Up @@ -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():
Expand Down
2 changes: 1 addition & 1 deletion pymc/tests/tuning/test_starting.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]))


Expand Down
2 changes: 1 addition & 1 deletion pymc/variational/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion pymc/variational/opvi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion scripts/run_mypy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion setupegg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())