Skip to content

Commit 5605aab

Browse files
authored
blacken examples (#4118)
1 parent c85f7fc commit 5605aab

17 files changed

+522
-230
lines changed

pymc3/examples/GHME_2013.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
from pymc3 import HalfCauchy, Model, Normal, get_data, sample
66
from pymc3.distributions.timeseries import GaussianRandomWalk
77

8-
data = pd.read_csv(get_data('pancreatitis.csv'))
9-
countries = ['CYP', 'DNK', 'ESP', 'FIN', 'GBR', 'ISL']
8+
data = pd.read_csv(get_data("pancreatitis.csv"))
9+
countries = ["CYP", "DNK", "ESP", "FIN", "GBR", "ISL"]
1010
data = data[data.area.isin(countries)]
1111

12-
age = data['age'] = np.array(data.age_start + data.age_end) / 2
12+
age = data["age"] = np.array(data.age_start + data.age_end) / 2
1313
rate = data.value = data.value * 1000
1414
group, countries = pd.factorize(data.area, order=countries)
1515

@@ -20,7 +20,7 @@
2020
plt.subplot(2, 3, i + 1)
2121
plt.title(country)
2222
d = data[data.area == country]
23-
plt.plot(d.age, d.value, '.')
23+
plt.plot(d.age, d.value, ".")
2424

2525
plt.ylim(0, rate.max())
2626

@@ -43,33 +43,33 @@ def interpolate(x0, y0, x, group):
4343

4444

4545
with Model() as model:
46-
coeff_sd = HalfCauchy('coeff_sd', 5)
46+
coeff_sd = HalfCauchy("coeff_sd", 5)
4747

48-
y = GaussianRandomWalk('y', sigma=coeff_sd, shape=(nknots, ncountries))
48+
y = GaussianRandomWalk("y", sigma=coeff_sd, shape=(nknots, ncountries))
4949

5050
p = interpolate(knots, y, age, group)
5151

52-
sd = HalfCauchy('sd', 5)
52+
sd = HalfCauchy("sd", 5)
5353

54-
vals = Normal('vals', p, sigma=sd, observed=rate)
54+
vals = Normal("vals", p, sigma=sd, observed=rate)
5555

5656

5757
def run(n=3000):
5858
if n == "short":
5959
n = 150
6060
with model:
61-
trace = sample(n, tune=int(n/2), init='advi+adapt_diag')
61+
trace = sample(n, tune=int(n / 2), init="advi+adapt_diag")
6262

6363
for i, country in enumerate(countries):
6464
plt.subplot(2, 3, i + 1)
6565
plt.title(country)
6666

6767
d = data[data.area == country]
68-
plt.plot(d.age, d.value, '.')
69-
plt.plot(knots, trace[y][::5, :, i].T, color='r', alpha=.01)
68+
plt.plot(d.age, d.value, ".")
69+
plt.plot(knots, trace[y][::5, :, i].T, color="r", alpha=0.01)
7070

7171
plt.ylim(0, rate.max())
7272

7373

74-
if __name__ == '__main__':
74+
if __name__ == "__main__":
7575
run()

pymc3/examples/LKJ_correlation.py

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,41 +14,47 @@
1414
stds = np.ones(4) / 2.0
1515

1616
# Correlation matrix of 4 variables:
17-
corr_r = np.array([[1., 0.75, 0., 0.15],
18-
[0.75, 1., -0.06, 0.19],
19-
[0., -0.06, 1., -0.04],
20-
[0.15, 0.19, -0.04, 1.]])
17+
corr_r = np.array(
18+
[
19+
[1.0, 0.75, 0.0, 0.15],
20+
[0.75, 1.0, -0.06, 0.19],
21+
[0.0, -0.06, 1.0, -0.04],
22+
[0.15, 0.19, -0.04, 1.0],
23+
]
24+
)
2125
cov_matrix = np.diag(stds).dot(corr_r.dot(np.diag(stds)))
2226

2327
dataset = multivariate_normal(mu_r, cov_matrix, size=n_obs)
2428

2529
with pm.Model() as model:
2630

27-
mu = pm.Normal('mu', mu=0, sigma=1, shape=n_var)
31+
mu = pm.Normal("mu", mu=0, sigma=1, shape=n_var)
2832

2933
# Note that we access the distribution for the standard
3034
# deviations, and do not create a new random variable.
3135
sd_dist = pm.HalfCauchy.dist(beta=2.5)
32-
packed_chol = pm.LKJCholeskyCov('chol_cov', n=n_var, eta=1, sd_dist=sd_dist)
36+
packed_chol = pm.LKJCholeskyCov("chol_cov", n=n_var, eta=1, sd_dist=sd_dist)
3337
# compute the covariance matrix
3438
chol = pm.expand_packed_triangular(n_var, packed_chol, lower=True)
3539
cov = tt.dot(chol, chol.T)
3640

3741
# Extract the standard deviations etc
38-
sd = pm.Deterministic('sd', tt.sqrt(tt.diag(cov)))
39-
corr = tt.diag(sd**-1).dot(cov.dot(tt.diag(sd**-1)))
40-
r = pm.Deterministic('r', corr[np.triu_indices(n_var, k=1)])
42+
sd = pm.Deterministic("sd", tt.sqrt(tt.diag(cov)))
43+
corr = tt.diag(sd ** -1).dot(cov.dot(tt.diag(sd ** -1)))
44+
r = pm.Deterministic("r", corr[np.triu_indices(n_var, k=1)])
4145

42-
like = pm.MvNormal('likelihood', mu=mu, chol=chol, observed=dataset)
46+
like = pm.MvNormal("likelihood", mu=mu, chol=chol, observed=dataset)
4347

4448

4549
def run(n=1000):
4650
if n == "short":
4751
n = 50
4852
with model:
4953
trace = pm.sample(n)
50-
pm.traceplot(trace, varnames=['mu', 'r'],
51-
lines={'mu': mu_r, 'r': corr_r[np.triu_indices(n_var, k=1)]})
54+
pm.traceplot(
55+
trace, varnames=["mu", "r"], lines={"mu": mu_r, "r": corr_r[np.triu_indices(n_var, k=1)]}
56+
)
5257

53-
if __name__ == '__main__':
58+
59+
if __name__ == "__main__":
5460
run()

pymc3/examples/arbitrary_stochastic.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,13 @@ def logp(failure, lam, value):
1010

1111
def build_model():
1212
# data
13-
failure = np.array([0., 1.])
14-
value = np.array([1., 0.])
13+
failure = np.array([0.0, 1.0])
14+
value = np.array([1.0, 0.0])
1515

1616
# model
1717
with pm.Model() as model:
18-
lam = pm.Exponential('lam', 1.)
19-
pm.DensityDist('x', logp, observed={'failure': failure,
20-
'lam': lam,
21-
'value': value})
18+
lam = pm.Exponential("lam", 1.0)
19+
pm.DensityDist("x", logp, observed={"failure": failure, "lam": lam, "value": value})
2220
return model
2321

2422

@@ -28,5 +26,6 @@ def run(n_samples=3000):
2826
trace = pm.sample(n_samples)
2927
return trace
3028

29+
3130
if __name__ == "__main__":
3231
run()

pymc3/examples/arma_example.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from theano import scan, shared
33

44
import numpy as np
5+
56
"""
67
ARMA example
78
It is interesting to note just how much more compact this is than the original Stan example
@@ -53,36 +54,36 @@
5354
def build_model():
5455
y = shared(np.array([15, 10, 16, 11, 9, 11, 10, 18], dtype=np.float32))
5556
with pm.Model() as arma_model:
56-
sigma = pm.HalfNormal('sigma', 5.)
57-
theta = pm.Normal('theta', 0., sigma=1.)
58-
phi = pm.Normal('phi', 0., sigma=2.)
59-
mu = pm.Normal('mu', 0., sigma=10.)
57+
sigma = pm.HalfNormal("sigma", 5.0)
58+
theta = pm.Normal("theta", 0.0, sigma=1.0)
59+
phi = pm.Normal("phi", 0.0, sigma=2.0)
60+
mu = pm.Normal("mu", 0.0, sigma=10.0)
6061

6162
err0 = y[0] - (mu + phi * mu)
6263

6364
def calc_next(last_y, this_y, err, mu, phi, theta):
6465
nu_t = mu + phi * last_y + theta * err
6566
return this_y - nu_t
6667

67-
err, _ = scan(fn=calc_next,
68-
sequences=dict(input=y, taps=[-1, 0]),
69-
outputs_info=[err0],
70-
non_sequences=[mu, phi, theta])
68+
err, _ = scan(
69+
fn=calc_next,
70+
sequences=dict(input=y, taps=[-1, 0]),
71+
outputs_info=[err0],
72+
non_sequences=[mu, phi, theta],
73+
)
7174

72-
pm.Potential('like', pm.Normal.dist(0, sigma=sigma).logp(err))
75+
pm.Potential("like", pm.Normal.dist(0, sigma=sigma).logp(err))
7376
return arma_model
7477

7578

7679
def run(n_samples=1000):
7780
model = build_model()
7881
with model:
79-
trace = pm.sample(draws=n_samples,
80-
tune=1000,
81-
target_accept=.99)
82+
trace = pm.sample(draws=n_samples, tune=1000, target_accept=0.99)
8283

8384
pm.plots.traceplot(trace)
8485
pm.plots.forestplot(trace)
8586

8687

87-
if __name__ == '__main__':
88+
if __name__ == "__main__":
8889
run()

pymc3/examples/baseball.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,31 +6,35 @@
66
import pymc3 as pm
77
import numpy as np
88

9+
910
def build_model():
10-
data = np.loadtxt(pm.get_data('efron-morris-75-data.tsv'), delimiter="\t",
11-
skiprows=1, usecols=(2,3))
12-
13-
atbats = pm.floatX(data[:,0])
14-
hits = pm.floatX(data[:,1])
15-
11+
data = np.loadtxt(
12+
pm.get_data("efron-morris-75-data.tsv"), delimiter="\t", skiprows=1, usecols=(2, 3)
13+
)
14+
15+
atbats = pm.floatX(data[:, 0])
16+
hits = pm.floatX(data[:, 1])
17+
1618
N = len(hits)
17-
19+
1820
# we want to bound the kappa below
1921
BoundedKappa = pm.Bound(pm.Pareto, lower=1.0)
20-
22+
2123
with pm.Model() as model:
22-
phi = pm.Uniform('phi', lower=0.0, upper=1.0)
23-
kappa = BoundedKappa('kappa', alpha=1.0001, m=1.5)
24-
thetas = pm.Beta('thetas', alpha=phi*kappa, beta=(1.0-phi)*kappa, shape=N)
25-
ys = pm.Binomial('ys', n=atbats, p=thetas, observed=hits)
24+
phi = pm.Uniform("phi", lower=0.0, upper=1.0)
25+
kappa = BoundedKappa("kappa", alpha=1.0001, m=1.5)
26+
thetas = pm.Beta("thetas", alpha=phi * kappa, beta=(1.0 - phi) * kappa, shape=N)
27+
ys = pm.Binomial("ys", n=atbats, p=thetas, observed=hits)
2628
return model
2729

30+
2831
def run(n=2000):
2932
model = build_model()
3033
with model:
3134
trace = pm.sample(n, target_accept=0.99)
3235

3336
pm.traceplot(trace)
3437

35-
if __name__ == '__main__':
38+
39+
if __name__ == "__main__":
3640
run()

pymc3/examples/custom_dists.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,25 @@
2222
# add scatter to points
2323
xdata = np.random.normal(xdata, 10)
2424
ydata = np.random.normal(ydata, 10)
25-
data = {'x': xdata, 'y': ydata}
25+
data = {"x": xdata, "y": ydata}
2626

2727
# define loglikelihood outside of the model context, otherwise cores wont work:
2828
# Lambdas defined in local namespace are not picklable (see issue #1995)
2929
def loglike1(value):
30-
return -1.5 * tt.log(1 + value**2)
30+
return -1.5 * tt.log(1 + value ** 2)
31+
32+
3133
def loglike2(value):
3234
return -tt.log(tt.abs_(value))
3335

36+
3437
with pm.Model() as model:
35-
alpha = pm.Normal('intercept', mu=0, sigma=100)
38+
alpha = pm.Normal("intercept", mu=0, sigma=100)
3639
# Create custom densities
37-
beta = pm.DensityDist('slope', loglike1, testval=0)
38-
sigma = pm.DensityDist('sigma', loglike2, testval=1)
40+
beta = pm.DensityDist("slope", loglike1, testval=0)
41+
sigma = pm.DensityDist("sigma", loglike2, testval=1)
3942
# Create likelihood
40-
like = pm.Normal('y_est', mu=alpha + beta *
41-
xdata, sigma=sigma, observed=ydata)
43+
like = pm.Normal("y_est", mu=alpha + beta * xdata, sigma=sigma, observed=ydata)
4244

4345
trace = pm.sample(2000, cores=2)
4446

@@ -47,10 +49,11 @@ def loglike2(value):
4749
# Create some convenience routines for plotting
4850
# All functions below written by Jake Vanderplas
4951

52+
5053
def compute_sigma_level(trace1, trace2, nbins=20):
5154
"""From a set of traces, bin by number of standard deviations"""
5255
L, xbins, ybins = np.histogram2d(trace1, trace2, nbins)
53-
L[L == 0] = 1E-16
56+
L[L == 0] = 1e-16
5457

5558
shape = L.shape
5659
L = L.ravel()
@@ -73,37 +76,36 @@ def plot_MCMC_trace(ax, xdata, ydata, trace, scatter=False, **kwargs):
7376
xbins, ybins, sigma = compute_sigma_level(trace[0], trace[1])
7477
ax.contour(xbins, ybins, sigma.T, levels=[0.683, 0.955], **kwargs)
7578
if scatter:
76-
ax.plot(trace[0], trace[1], ',k', alpha=0.1)
77-
ax.set_xlabel(r'$\alpha$')
78-
ax.set_ylabel(r'$\beta$')
79+
ax.plot(trace[0], trace[1], ",k", alpha=0.1)
80+
ax.set_xlabel(r"$\alpha$")
81+
ax.set_ylabel(r"$\beta$")
7982

8083

8184
def plot_MCMC_model(ax, xdata, ydata, trace):
8285
"""Plot the linear model and 2sigma contours"""
83-
ax.plot(xdata, ydata, 'ok')
86+
ax.plot(xdata, ydata, "ok")
8487

8588
alpha, beta = trace[:2]
8689
xfit = np.linspace(-20, 120, 10)
8790
yfit = alpha[:, None] + beta[:, None] * xfit
8891
mu = yfit.mean(0)
8992
sig = 2 * yfit.std(0)
9093

91-
ax.plot(xfit, mu, '-k')
92-
ax.fill_between(xfit, mu - sig, mu + sig, color='lightgray')
94+
ax.plot(xfit, mu, "-k")
95+
ax.fill_between(xfit, mu - sig, mu + sig, color="lightgray")
9396

94-
ax.set_xlabel('x')
95-
ax.set_ylabel('y')
97+
ax.set_xlabel("x")
98+
ax.set_ylabel("y")
9699

97100

98-
def plot_MCMC_results(xdata, ydata, trace, colors='k'):
101+
def plot_MCMC_results(xdata, ydata, trace, colors="k"):
99102
"""Plot both the trace and the model together"""
100103
_, ax = plt.subplots(1, 2, figsize=(10, 4))
101104
plot_MCMC_trace(ax[0], xdata, ydata, trace, True, colors=colors)
102105
plot_MCMC_model(ax[1], xdata, ydata, trace)
103106

104-
pymc3_trace = [trace['intercept'],
105-
trace['slope'],
106-
trace['sigma']]
107+
108+
pymc3_trace = [trace["intercept"], trace["slope"], trace["sigma"]]
107109

108110
plot_MCMC_results(xdata, ydata, pymc3_trace)
109111
plt.show()

0 commit comments

Comments
 (0)