Skip to content

Commit 36ab005

Browse files
ColCarrollaloctavodia
authored andcommitted
Correct some random errors pylint picks up (#2585)
* Correct some random errors pylint picks up * Fix broken tests
1 parent ce535b3 commit 36ab005

File tree

12 files changed

+46
-57
lines changed

12 files changed

+46
-57
lines changed

pymc3/distributions/multivariate.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ def random(self, point=None, size=None):
239239
try:
240240
dist = stats.multivariate_normal(
241241
mean=mu, cov=cov, allow_singular=True)
242-
except ValueError as error:
242+
except ValueError:
243243
size.append(mu.shape[-1])
244244
return np.nan * np.zeros(size)
245245
return dist.rvs(size)
@@ -473,11 +473,11 @@ class Multinomial(Discrete):
473473
Parameters
474474
----------
475475
n : int or array
476-
Number of trials (n > 0). If n is an array its shape must be (N,) with
476+
Number of trials (n > 0). If n is an array its shape must be (N,) with
477477
N = p.shape[0]
478478
p : one- or two-dimensional array
479479
Probability of each one of the different outcomes. Elements must
480-
be non-negative and sum to 1 along the last axis. They will be
480+
be non-negative and sum to 1 along the last axis. They will be
481481
automatically rescaled otherwise.
482482
"""
483483

@@ -532,7 +532,7 @@ def _random(self, n, p, size=None):
532532
randnum = np.asarray([
533533
np.random.multinomial(nn, p.squeeze(), size=size)
534534
for nn in n
535-
])
535+
])
536536
else:
537537
p = p / p.sum(axis=1, keepdims=True)
538538
randnum = np.asarray([
@@ -605,7 +605,7 @@ def perform(self, node, inputs, outputs):
605605
try:
606606
z[0] = np.array(posdef(x), dtype='int8')
607607
except Exception:
608-
pm._log.exception('Failed to check if positive definite', x)
608+
pm._log.exception('Failed to check if %s positive definite', x)
609609
raise
610610

611611
def infer_shape(self, node, shapes):
@@ -675,11 +675,11 @@ def __init__(self, nu, V, *args, **kwargs):
675675
(nu - p - 1) * V,
676676
np.nan)
677677

678-
def random(self, point=None, size=None):
679-
nu, V = draw_values([self.nu, self.V], point=point)
678+
def random(self, point=None, size=None):
679+
nu, V = draw_values([self.nu, self.V], point=point)
680680
size= 1 if size is None else size
681-
return generate_samples(stats.wishart.rvs, np.asscalar(nu), V,
682-
broadcast_shape=(size,))
681+
return generate_samples(stats.wishart.rvs, np.asscalar(nu), V,
682+
broadcast_shape=(size,))
683683

684684
def logp(self, X):
685685
nu = self.nu
@@ -1049,7 +1049,7 @@ def __init__(self, eta=None, n=None, p=None, transform='interval', *args, **kwar
10491049
self.tri_index[np.triu_indices(n, k=1)[::-1]] = np.arange(shape)
10501050

10511051
def _random(self, n, eta, size=None):
1052-
size = size if isinstance(size, tuple) else (size,)
1052+
size = size if isinstance(size, tuple) else (size,)
10531053
# original implementation in R see:
10541054
# https://github.com/rmcelreath/rethinking/blob/master/R/distributions.r
10551055
beta = eta - 1 + n/2

pymc3/examples/disaster_model_theano_op.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77

88
import pymc3 as pm
9+
from theano.compile.ops import as_op
910
import theano.tensor as tt
1011
from numpy import arange, array, empty
1112

@@ -51,9 +52,9 @@ def rate_(switchpoint, early_mean, late_mean):
5152
step1 = pm.Slice([early_mean, late_mean])
5253
# Use Metropolis for switchpoint, since it accomodates discrete variables
5354
step2 = pm.Metropolis([switchpoint])
54-
55+
5556
# Initial values for stochastic nodes
5657
start = {'early_mean': 2., 'late_mean': 3.}
57-
58+
5859
tr = pm.sample(1000, tune=500, start=start, step=[step1, step2], njobs=2)
5960
pm.traceplot(tr)

pymc3/examples/garch_example.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,4 @@ def run(n=1000):
5757

5858

5959
if __name__ == '__main__':
60-
print(summary(run()))
60+
summary(run())

pymc3/plots/energyplot.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import warnings
2+
13
import matplotlib.pyplot as plt
24
import numpy as np
35
from .kdeplot import kdeplot
@@ -36,8 +38,9 @@ def energyplot(trace, kind='kde', figsize=None, ax=None, legend=True,
3638
try:
3739
energy = trace['energy']
3840
except KeyError:
39-
print('There is no energy information in the passed trace.')
41+
warnings.warn('There is no energy information in the passed trace.')
4042
return ax
43+
4144
series = [('Marginal energy distribution', energy - energy.mean()),
4245
('Energy transition distribution', np.diff(energy))]
4346

pymc3/plots/forestplot.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -101,25 +101,25 @@ def _plot_tree(ax, y, ntiles, show_quartiles, **plot_kwargs):
101101
"""
102102
if show_quartiles:
103103
# Plot median
104-
ax.plot(ntiles[2], y, color=plot_kwargs.get('color', 'blue'),
105-
marker=plot_kwargs.get('marker', 'o'),
104+
ax.plot(ntiles[2], y, color=plot_kwargs.get('color', 'blue'),
105+
marker=plot_kwargs.get('marker', 'o'),
106106
markersize=plot_kwargs.get('markersize', 4))
107107
# Plot quartile interval
108-
ax.errorbar(x=(ntiles[1], ntiles[3]), y=(y, y),
109-
linewidth=plot_kwargs.get('linewidth', 2),
108+
ax.errorbar(x=(ntiles[1], ntiles[3]), y=(y, y),
109+
linewidth=plot_kwargs.get('linewidth', 2),
110110
color=plot_kwargs.get('color', 'blue'))
111111

112112
else:
113113
# Plot median
114-
ax.plot(ntiles[1], y, marker=plot_kwargs.get('marker', 'o'),
114+
ax.plot(ntiles[1], y, marker=plot_kwargs.get('marker', 'o'),
115115
color=plot_kwargs.get('color', 'blue'),
116116
markersize=plot_kwargs.get('markersize', 4))
117117

118118
# Plot outer interval
119-
ax.errorbar(x=(ntiles[0], ntiles[-1]), y=(y, y),
120-
linewidth=int(plot_kwargs.get('linewidth', 2)/2),
119+
ax.errorbar(x=(ntiles[0], ntiles[-1]), y=(y, y),
120+
linewidth=int(plot_kwargs.get('linewidth', 2)/2),
121121
color=plot_kwargs.get('color', 'blue'))
122-
122+
123123
return ax
124124

125125

@@ -227,11 +227,11 @@ def forestplot(trace_obj, varnames=None, transform=identity_transform, alpha=0.0
227227
quants[-1] = var_hpd[1].T
228228

229229
# Ensure x-axis contains range of current interval
230-
if plotrange:
230+
if plotrange is None:
231+
plotrange = [np.min(quants), np.max(quants)]
232+
else:
231233
plotrange = [min(plotrange[0], np.min(quants)),
232234
max(plotrange[1], np.max(quants))]
233-
else:
234-
plotrange = [np.min(quants), np.max(quants)]
235235

236236
# Number of elements in current variable
237237
value = trace_obj.get_values(varname, chains=[chain])[0]
@@ -255,12 +255,10 @@ def forestplot(trace_obj, varnames=None, transform=identity_transform, alpha=0.0
255255
if k > 1:
256256
for q in np.transpose(quants).squeeze():
257257
# Multiple y values
258-
interval_plot = _plot_tree(interval_plot, y, q, quartiles,
259-
**plot_kwargs)
258+
interval_plot = _plot_tree(interval_plot, y, q, quartiles, **plot_kwargs)
260259
y -= 1
261260
else:
262-
interval_plot = _plot_tree(interval_plot, y, quants, quartiles,
263-
**plot_kwargs)
261+
interval_plot = _plot_tree(interval_plot, y, quants, quartiles, **plot_kwargs)
264262

265263
# Increment index
266264
var += k

pymc3/stats.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from collections import namedtuple
1010
from .model import modelcontext
1111
from .util import get_default_varnames
12+
import pymc3 as pm
1213
from pymc3.theanof import floatX
1314

1415
from scipy.misc import logsumexp
@@ -399,7 +400,7 @@ def compare(traces, models, ic='WAIC', method='stacking', b_samples=1000,
399400
It's always 0 for the top-ranked model.
400401
weight: Relative weight for each model.
401402
This can be loosely interpreted as the probability of each model
402-
(among the compared model) given the data. By default the uncertainty
403+
(among the compared model) given the data. By default the uncertainty
403404
in the weights estimation is considered using Bayesian bootstrap.
404405
SE : Standard error of the IC estimate.
405406
If method = BB-pseudo-BMA these values are estimated using Bayesian
@@ -718,10 +719,10 @@ def quantiles(x, qlist=(2.5, 25, 50, 75, 97.5), transform=lambda x: x):
718719
return dict(zip(qlist, quants))
719720

720721
except IndexError:
721-
_log.warning("Too few elements for quantile calculation")
722+
pm._log.warning("Too few elements for quantile calculation")
722723

723724

724-
def df_summary(trace, varnames=None, transform=lambda x: x, stat_funcs=None,
725+
def df_summary(trace, varnames=None, transform=lambda x: x, stat_funcs=None,
725726
extend=False, include_transformed=False,
726727
alpha=0.05, start=0, batches=None):
727728
R"""Create a data frame with summary statistics.

pymc3/step_methods/hmc/integration.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ def __init__(self, potential, logp_dlogp_func):
1414
self._logp_dlogp_func = logp_dlogp_func
1515
self._dtype = self._logp_dlogp_func.dtype
1616
if self._potential.dtype != self._dtype:
17-
raise ValueError("dtypes of potential and logp function "
17+
raise ValueError("dtypes of potential (%s) and logp function (%s)"
1818
"don't match."
1919
% (self._potential.dtype, self._dtype))
2020

pymc3/tests/test_dist_math.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,7 @@ def func(chol_vec, delta):
154154
chol_vec_val = floatX(np.array([0.5, 1., -0.1]))
155155

156156
delta_val = floatX(np.random.randn(1, 2))
157-
try:
158-
utt.verify_grad(func, [chol_vec_val, delta_val])
159-
except ValueError as e:
160-
print(e.args[0])
157+
utt.verify_grad(func, [chol_vec_val, delta_val])
161158

162159
delta_val = floatX(np.random.randn(5, 2))
163160
utt.verify_grad(func, [chol_vec_val, delta_val])

pymc3/tests/test_ndarray_backend.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -63,20 +63,13 @@ class TestNDArray0dSelection(bf.SelectionTestCase):
6363
sampler_vars = STATS1
6464

6565

66-
class TestNDArray0dSelection(bf.SelectionTestCase):
66+
class TestNDArray0dSelection2(bf.SelectionTestCase):
6767
backend = ndarray.NDArray
6868
name = None
6969
shape = ()
7070
sampler_vars = STATS2
7171

7272

73-
class TestNDArray0dSelection(bf.SelectionTestCase):
74-
backend = ndarray.NDArray
75-
name = None
76-
shape = ()
77-
sampler_vars = STATS1
78-
79-
8073
class TestNDArray0dSelectionStats1(bf.SelectionTestCase):
8174
backend = ndarray.NDArray
8275
name = None
@@ -136,7 +129,7 @@ def test_add_values(self):
136129
orig_varnames = list(mtrace.varnames)
137130
name = 'new_var'
138131
vals = mtrace[orig_varnames[0]]
139-
mtrace.add_values({name : vals})
132+
mtrace.add_values({name: vals})
140133
assert len(orig_varnames) == len(mtrace.varnames) - 1
141134
assert name in mtrace.varnames
142135
assert np.all(mtrace[orig_varnames[0]] == mtrace[name])

pymc3/tests/test_plots.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def test_plots():
3333

3434

3535
def test_energyplot():
36-
with asmod.build_model() as model:
36+
with asmod.build_model():
3737
trace = sample()
3838

3939
energyplot(trace)

0 commit comments

Comments
 (0)