Skip to content

Commit cf1d135

Browse files
Upgrade pre-commit from main and apply automated code style
Except the check against print statements.
1 parent c332f8c commit cf1d135

22 files changed

+141
-85
lines changed

.pre-commit-config.yaml

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
exclude: ^(docs/logos|pymc3/tests/data)/
22
repos:
33
- repo: https://github.com/pre-commit/pre-commit-hooks
4-
rev: v3.4.0
4+
rev: v4.0.1
55
hooks:
66
- id: check-merge-conflict
77
- id: check-toml
@@ -14,44 +14,43 @@ repos:
1414
exclude: ^requirements-dev\.txt$
1515
- id: trailing-whitespace
1616
- repo: https://github.com/PyCQA/isort
17-
rev: 5.7.0
17+
rev: 5.10.1
1818
hooks:
1919
- id: isort
2020
name: isort
2121
- repo: https://github.com/asottile/pyupgrade
22-
rev: v2.10.0
22+
rev: v2.29.1
2323
hooks:
2424
- id: pyupgrade
2525
args: [--py37-plus]
2626
- repo: https://github.com/psf/black
27-
rev: 20.8b1
27+
rev: 21.12b0
2828
hooks:
2929
- id: black
3030
- repo: https://github.com/PyCQA/pylint
31-
rev: pylint-2.6.0
31+
rev: v2.12.2
3232
hooks:
3333
- id: pylint
3434
args: [--rcfile=.pylintrc]
35-
files: ^pymc3/
35+
files: ^pymc/
36+
- repo: https://github.com/MarcoGorelli/madforhooks
37+
rev: 0.2.1
38+
hooks:
39+
- id: conda-env-sorter
40+
files: ^conda-envs/environment-dev-py.+\.yml$
3641
- repo: local
3742
hooks:
3843
- id: check-no-tests-are-ignored
44+
additional_dependencies: [pandas,pyyaml]
3945
entry: python scripts/check_all_tests_are_covered.py
4046
files: ^\.github/workflows/pytest\.yml$
4147
language: python
4248
name: Check no tests are ignored
4349
pass_filenames: false
44-
- id: conda-env-sort
45-
additional_dependencies: [pyyaml]
46-
entry: python scripts/sort_conda_envs.py
47-
files: ^conda-envs/environment-dev-py37\.yml$
48-
language: python
49-
name: Sort dependencies in conda envs
50-
types: [yaml]
5150
- id: pip-from-conda
5251
additional_dependencies: [pyyaml]
5352
entry: python scripts/generate_pip_deps_from_conda.py
54-
files: ^conda-envs/
53+
files: ^conda-envs/environment-dev-py.+.yml$
5554
language: python
5655
name: Generate pip dependency from conda
5756
- id: no-relative-imports

docs/source/sphinxext/gallery_generator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ def build_gallery(srcdir, gallery):
194194
with open(table_of_contents_file) as toc:
195195
table_of_contents = toc.read()
196196

197-
js_contents = "Gallery.examples = {}\n{}".format(json.dumps(data), table_of_contents)
197+
js_contents = f"Gallery.examples = {json.dumps(data)}\n{table_of_contents}"
198198

199199
with open(js_file, "w") as js:
200200
js.write(js_contents)

pymc3/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def __set_compiler_flags():
6363

6464

6565
def _hotfix_theano_printing():
66-
""" This is a workaround for https://github.com/pymc-devs/aesara/issues/309 """
66+
"""This is a workaround for https://github.com/pymc-devs/aesara/issues/309"""
6767
try:
6868
import pydot
6969
import theano.printing

pymc3/backends/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ def __getattr__(self, name):
364364
return self.get_values(name)
365365
if name in self.stat_names:
366366
return self.get_sampler_stats(name)
367-
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))
367+
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
368368

369369
def __len__(self):
370370
chain = self.chains[-1]

pymc3/distributions/distribution.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def __new__(cls, name, *args, **kwargs):
9595
data = kwargs.pop("observed", None)
9696
cls.data = data
9797
if isinstance(data, ObservedRV) or isinstance(data, FreeRV):
98-
raise TypeError("observed needs to be data but got: {}".format(type(data)))
98+
raise TypeError(f"observed needs to be data but got: {type(data)}")
9999
total_size = kwargs.pop("total_size", None)
100100

101101
dims = kwargs.pop("dims", None)

pymc3/distributions/posterior_predictive.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ def __init__(self, vars, trace: _TraceDict, samples, model: Model | None, size=N
342342
self.size = size
343343
self.logger = logging.getLogger("posterior_predictive")
344344

345-
def __enter__(self) -> "_PosteriorPredictiveSampler":
345+
def __enter__(self) -> _PosteriorPredictiveSampler:
346346
self._tok = vectorized_ppc.set(posterior_predictive_draw_values)
347347
return self
348348

pymc3/gp/cov.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ def __array_wrap__(self, result):
155155
class Combination(Covariance):
156156
def __init__(self, factor_list):
157157
input_dim = max(
158-
[factor.input_dim for factor in factor_list if isinstance(factor, Covariance)]
158+
factor.input_dim for factor in factor_list if isinstance(factor, Covariance)
159159
)
160160
super().__init__(input_dim=input_dim)
161161
self.factor_list = []

pymc3/gp/util.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def infer_shape(X, n_points=None):
3636

3737

3838
def stabilize(K):
39-
""" adds small diagonal to a covariance matrix """
39+
"""adds small diagonal to a covariance matrix"""
4040
return K + 1e-6 * tt.identity_like(K)
4141

4242

@@ -62,7 +62,7 @@ def kmeans_inducing_points(n_inducing, X):
6262

6363

6464
def conditioned_vars(varnames):
65-
""" Decorator for validating attrs that are conditioned on. """
65+
"""Decorator for validating attrs that are conditioned on."""
6666

6767
def gp_wrapper(cls):
6868
def make_getter(name):

pymc3/model.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -723,7 +723,7 @@ def __call__(self, array, grad_out=None, extra_vars=None):
723723

724724
if array.shape != (self.size,):
725725
raise ValueError(
726-
"Invalid shape for array. Must be {} but is {}.".format((self.size,), array.shape)
726+
f"Invalid shape for array. Must be {(self.size,)} but is {array.shape}."
727727
)
728728

729729
if grad_out is None:

pymc3/model_graph.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def _filter_parents(self, var, parents) -> Set[VarName]:
8484
if self.transform_map[p] != var.name:
8585
keep.add(self.transform_map[p])
8686
else:
87-
raise AssertionError("Do not know what to do with {}".format(get_var_name(p)))
87+
raise AssertionError(f"Do not know what to do with {get_var_name(p)}")
8888
return keep
8989

9090
def get_parents(self, var: Tensor) -> Set[VarName]:

pymc3/ode/ode.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def _simulate(self, y0, theta):
136136

137137
def make_node(self, y0, theta):
138138
inputs = (y0, theta)
139-
_log.debug("make_node for inputs {}".format(hash(inputs)))
139+
_log.debug(f"make_node for inputs {hash(inputs)}")
140140
states = self._otypes[0]()
141141
sens = self._otypes[1]()
142142

@@ -220,7 +220,7 @@ def infer_shape(self, fgraph, node, input_shapes):
220220
return output_shapes
221221

222222
def grad(self, inputs, output_grads):
223-
_log.debug("grad w.r.t. inputs {}".format(hash(tuple(inputs))))
223+
_log.debug(f"grad w.r.t. inputs {hash(tuple(inputs))}")
224224

225225
# fetch symbolic sensitivity output node from cache
226226
ihash = hash(tuple(inputs))

pymc3/step_methods/hmc/quadpotential.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -161,13 +161,9 @@ def __init__(
161161
if initial_mean.ndim != 1:
162162
raise ValueError("Initial mean must be one-dimensional.")
163163
if initial_diag is not None and len(initial_diag) != n:
164-
raise ValueError(
165-
"Wrong shape for initial_diag: expected {} got {}".format(n, len(initial_diag))
166-
)
164+
raise ValueError(f"Wrong shape for initial_diag: expected {n} got {len(initial_diag)}")
167165
if len(initial_mean) != n:
168-
raise ValueError(
169-
"Wrong shape for initial_mean: expected {} got {}".format(n, len(initial_mean))
170-
)
166+
raise ValueError(f"Wrong shape for initial_mean: expected {n} got {len(initial_mean)}")
171167

172168
if dtype is None:
173169
dtype = theano.config.floatX
@@ -520,9 +516,7 @@ def __init__(
520516
if initial_cov is not None and initial_cov.shape != (n, n):
521517
raise ValueError(f"Wrong shape for initial_cov: expected {n} got {initial_cov.shape}")
522518
if len(initial_mean) != n:
523-
raise ValueError(
524-
"Wrong shape for initial_mean: expected {} got {}".format(n, len(initial_mean))
525-
)
519+
raise ValueError(f"Wrong shape for initial_mean: expected {n} got {len(initial_mean)}")
526520

527521
if dtype is None:
528522
dtype = theano.config.floatX

pymc3/step_methods/mlda.py

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -883,24 +883,16 @@ def update_error_estimate(self, accepted, skipped_logp):
883883
pm.set_data(
884884
{
885885
"mu_B": sum(
886-
[
887-
bias.get_mu()
888-
for bias in self.bias_all[
889-
: len(self.bias_all) - self.num_levels + 2
890-
]
891-
]
886+
bias.get_mu()
887+
for bias in self.bias_all[: len(self.bias_all) - self.num_levels + 2]
892888
)
893889
}
894890
)
895891
pm.set_data(
896892
{
897893
"Sigma_B": sum(
898-
[
899-
bias.get_sigma()
900-
for bias in self.bias_all[
901-
: len(self.bias_all) - self.num_levels + 2
902-
]
903-
]
894+
bias.get_sigma()
895+
for bias in self.bias_all[: len(self.bias_all) - self.num_levels + 2]
904896
)
905897
}
906898
)
@@ -979,7 +971,7 @@ def extract_Q_estimate(trace, levels):
979971

980972
Q_0_raw = trace.get_sampler_stats("Q_0")
981973
# total number of base level samples from all iterations
982-
total_base_level_samples = sum([it.shape[0] for it in Q_0_raw])
974+
total_base_level_samples = sum(it.shape[0] for it in Q_0_raw)
983975
Q_0 = np.concatenate(Q_0_raw).reshape((1, total_base_level_samples))
984976
ess_Q_0 = az.ess(np.array(Q_0, np.float64))
985977
Q_0_var = Q_0.var() / ess_Q_0
@@ -989,7 +981,7 @@ def extract_Q_estimate(trace, levels):
989981
for l in range(1, levels):
990982
Q_diff_raw = trace.get_sampler_stats(f"Q_{l}_{l-1}")
991983
# total number of samples from all iterations
992-
total_level_samples = sum([it.shape[0] for it in Q_diff_raw])
984+
total_level_samples = sum(it.shape[0] for it in Q_diff_raw)
993985
Q_diff = np.concatenate(Q_diff_raw).reshape((1, total_level_samples))
994986
ess_diff = az.ess(np.array(Q_diff, np.float64))
995987

pymc3/tests/test_distributions.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ def multinomial_logpdf(value, n, p):
280280

281281

282282
def dirichlet_multinomial_logpmf(value, n, a):
283-
value, n, a = [np.asarray(x) for x in [value, n, a]]
283+
value, n, a = (np.asarray(x) for x in [value, n, a])
284284
assert value.ndim == 1
285285
assert n.ndim == 0
286286
assert a.shape == value.shape
@@ -1875,7 +1875,7 @@ def test_multinomial_vec(self):
18751875
)
18761876

18771877
assert_almost_equal(
1878-
sum([model_single.fastlogp({"m": val}) for val in vals]),
1878+
sum(model_single.fastlogp({"m": val}) for val in vals),
18791879
model_many.fastlogp({"m": vals}),
18801880
decimal=4,
18811881
)
@@ -1889,7 +1889,7 @@ def test_multinomial_vec_1d_n(self):
18891889
Multinomial("m", n=ns, p=p, shape=vals.shape)
18901890

18911891
assert_almost_equal(
1892-
sum([multinomial_logpdf(val, n, p) for val, n in zip(vals, ns)]),
1892+
sum(multinomial_logpdf(val, n, p) for val, n in zip(vals, ns)),
18931893
model.fastlogp({"m": vals}),
18941894
decimal=4,
18951895
)
@@ -1903,7 +1903,7 @@ def test_multinomial_vec_1d_n_2d_p(self):
19031903
Multinomial("m", n=ns, p=ps, shape=vals.shape)
19041904

19051905
assert_almost_equal(
1906-
sum([multinomial_logpdf(val, n, p) for val, n, p in zip(vals, ns, ps)]),
1906+
sum(multinomial_logpdf(val, n, p) for val, n, p in zip(vals, ns, ps)),
19071907
model.fastlogp({"m": vals}),
19081908
decimal=4,
19091909
)
@@ -1917,7 +1917,7 @@ def test_multinomial_vec_2d_p(self):
19171917
Multinomial("m", n=n, p=ps, shape=vals.shape)
19181918

19191919
assert_almost_equal(
1920-
sum([multinomial_logpdf(val, n, p) for val, p in zip(vals, ps)]),
1920+
sum(multinomial_logpdf(val, n, p) for val, p in zip(vals, ps)),
19211921
model.fastlogp({"m": vals}),
19221922
decimal=4,
19231923
)
@@ -2009,7 +2009,7 @@ def test_dirichlet_multinomial_vec(self):
20092009
)
20102010

20112011
assert_almost_equal(
2012-
sum([model_single.fastlogp({"m": val}) for val in vals]),
2012+
sum(model_single.fastlogp({"m": val}) for val in vals),
20132013
model_many.fastlogp({"m": vals}),
20142014
decimal=4,
20152015
)
@@ -2023,7 +2023,7 @@ def test_dirichlet_multinomial_vec_1d_n(self):
20232023
DirichletMultinomial("m", n=ns, a=a, shape=vals.shape)
20242024

20252025
assert_almost_equal(
2026-
sum([dirichlet_multinomial_logpmf(val, n, a) for val, n in zip(vals, ns)]),
2026+
sum(dirichlet_multinomial_logpmf(val, n, a) for val, n in zip(vals, ns)),
20272027
model.fastlogp({"m": vals}),
20282028
decimal=4,
20292029
)
@@ -2037,7 +2037,7 @@ def test_dirichlet_multinomial_vec_1d_n_2d_a(self):
20372037
DirichletMultinomial("m", n=ns, a=as_, shape=vals.shape)
20382038

20392039
assert_almost_equal(
2040-
sum([dirichlet_multinomial_logpmf(val, n, a) for val, n, a in zip(vals, ns, as_)]),
2040+
sum(dirichlet_multinomial_logpmf(val, n, a) for val, n, a in zip(vals, ns, as_)),
20412041
model.fastlogp({"m": vals}),
20422042
decimal=4,
20432043
)
@@ -2051,7 +2051,7 @@ def test_dirichlet_multinomial_vec_2d_a(self):
20512051
DirichletMultinomial("m", n=n, a=as_, shape=vals.shape)
20522052

20532053
assert_almost_equal(
2054-
sum([dirichlet_multinomial_logpmf(val, n, a) for val, a in zip(vals, as_)]),
2054+
sum(dirichlet_multinomial_logpmf(val, n, a) for val, a in zip(vals, as_)),
20552055
model.fastlogp({"m": vals}),
20562056
decimal=4,
20572057
)

pymc3/tests/test_distributions_random.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ def setup_method(self, *args, **kwargs):
216216
self.model = pm.Model()
217217

218218
def get_random_variable(self, shape, with_vector_params=False, name=None):
219-
""" Creates a RandomVariable of the parametrized distribution. """
219+
"""Creates a RandomVariable of the parametrized distribution."""
220220
if with_vector_params:
221221
params = {
222222
key: value * np.ones(self.shape, dtype=np.dtype(type(value)))
@@ -240,7 +240,7 @@ def get_random_variable(self, shape, with_vector_params=False, name=None):
240240

241241
@staticmethod
242242
def sample_random_variable(random_variable, size):
243-
""" Draws samples from a RandomVariable using its .random() method. """
243+
"""Draws samples from a RandomVariable using its .random() method."""
244244
try:
245245
if size is None:
246246
return random_variable.random()
@@ -255,7 +255,7 @@ def sample_random_variable(random_variable, size):
255255
@pytest.mark.parametrize("size", [None, (), 1, (1,), 5, (4, 5)], ids=str)
256256
@pytest.mark.parametrize("shape", [None, ()], ids=str)
257257
def test_scalar_distribution_shape(self, shape, size):
258-
""" Draws samples of different [size] from a scalar [shape] RV. """
258+
"""Draws samples of different [size] from a scalar [shape] RV."""
259259
rv = self.get_random_variable(shape)
260260
exp_shape = self.default_shape if shape is None else tuple(np.atleast_1d(shape))
261261
exp_size = self.default_size if size is None else tuple(np.atleast_1d(size))
@@ -275,7 +275,7 @@ def test_scalar_distribution_shape(self, shape, size):
275275
"shape", [None, (), (1,), (1, 1), (1, 2), (10, 11, 1), (9, 10, 2)], ids=str
276276
)
277277
def test_scalar_sample_shape(self, shape, size):
278-
""" Draws samples of scalar [size] from a [shape] RV. """
278+
"""Draws samples of scalar [size] from a [shape] RV."""
279279
rv = self.get_random_variable(shape)
280280
exp_shape = self.default_shape if shape is None else tuple(np.atleast_1d(shape))
281281
exp_size = self.default_size if size is None else tuple(np.atleast_1d(size))

pymc3/tests/test_modelcontext.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def test_thread_safety(self):
3434
that thread A enters the context manager first, then B,
3535
then A attempts to declare a variable while B is still in the context manager.
3636
"""
37-
aInCtxt, bInCtxt, aDone = [threading.Event() for _ in range(3)]
37+
aInCtxt, bInCtxt, aDone = (threading.Event() for _ in range(3))
3838
modelA = Model()
3939
modelB = Model()
4040

pymc3/tests/test_random.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ def test_draw_value():
4444

4545
assert _draw_value(5) == 5
4646
assert _draw_value(5.0) == 5
47-
assert isinstance(_draw_value(5.0), type(5.0))
48-
assert isinstance(_draw_value(5), type(5))
47+
assert isinstance(_draw_value(5.0), float)
48+
assert isinstance(_draw_value(5), int)
4949

5050
with pm.Model():
5151
mu = 2 * tt.constant(np.array([5.0, 6.0])) + theano.shared(np.array(5))

0 commit comments

Comments
 (0)