Skip to content

Commit ae1d40e

Browse files
ColCarrolltwiecki
authored andcommitted
Use logging instead of print (#1416)
1 parent bad2aa6 commit ae1d40e

File tree

7 files changed

+46
-34
lines changed

7 files changed

+46
-34
lines changed

pymc3/__init__.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,10 @@
2525

2626
from . import glm
2727
from .data import *
28+
29+
import logging
30+
_log = logging.getLogger('pymc3')
31+
if not logging.root.handlers:
32+
_log.setLevel(logging.INFO)
33+
handler = logging.StreamHandler()
34+
_log.addHandler(handler)

pymc3/distributions/multivariate.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@
88
import theano.tensor as tt
99

1010
from scipy import stats
11-
from theano.tensor.nlinalg import det, matrix_inverse, trace, eigh
11+
from theano.tensor.nlinalg import det, matrix_inverse, trace
1212

13+
import pymc3 as pm
1314
from . import transforms
1415
from .distribution import Continuous, Discrete, draw_values, generate_samples
1516
from ..model import Deterministic
@@ -20,6 +21,7 @@
2021
__all__ = ['MvNormal', 'MvStudentT', 'Dirichlet',
2122
'Multinomial', 'Wishart', 'WishartBartlett', 'LKJCorr']
2223

24+
2325
def get_tau_cov(mu, tau=None, cov=None):
2426
"""
2527
Find precision and standard deviation
@@ -165,7 +167,6 @@ def logp(self, value):
165167
mu = self.mu
166168

167169
d = S.shape[0]
168-
n = value.shape[0]
169170

170171
X = value - mu
171172

@@ -297,7 +298,7 @@ def random(self, point=None, size=None):
297298
def logp(self, x):
298299
n = self.n
299300
p = self.p
300-
301+
301302
if x.ndim==2:
302303
x_sum = x.sum(axis=0)
303304
n_sum = n * x.shape[0]
@@ -307,16 +308,16 @@ def logp(self, x):
307308

308309
return bound(
309310
factln(n_sum) + tt.sum(x_sum * tt.log(p) - factln(x_sum)),
310-
tt.all(x >= 0),
311-
tt.all(x <= n),
311+
tt.all(x >= 0),
312+
tt.all(x <= n),
312313
tt.eq(tt.sum(x_sum), n_sum),
313314
tt.isclose(p.sum(), 1),
314315
n >= 0)
315316

316317

317318
def posdef(AA):
318319
try:
319-
fct = np.linalg.cholesky(AA)
320+
np.linalg.cholesky(AA)
320321
return 1
321322
except np.linalg.LinAlgError:
322323
return 0
@@ -347,7 +348,7 @@ def perform(self, node, inputs, outputs):
347348
try:
348349
z[0] = np.array(posdef(x), dtype='int8')
349350
except Exception:
350-
print('Failed to check if positive definite', x)
351+
pm._log.exception('Failed to check if positive definite', x)
351352
raise
352353

353354
def infer_shape(self, node, shapes):
@@ -488,9 +489,9 @@ def WishartBartlett(name, S, nu, is_cholesky=False, return_cholesky=False, testv
488489

489490
c = tt.sqrt(ChiSquared('c', nu - np.arange(2, 2 + n_diag), shape=n_diag,
490491
testval=diag_testval))
491-
print('Added new variable c to model diagonal of Wishart.')
492+
pm._log.info('Added new variable c to model diagonal of Wishart.')
492493
z = Normal('z', 0, 1, shape=n_tril, testval=tril_testval)
493-
print('Added new variable z to model off-diagonals of Wishart.')
494+
pm._log.info('Added new variable z to model off-diagonals of Wishart.')
494495
# Construct A matrix
495496
A = tt.zeros(S.shape, dtype=np.float32)
496497
A = tt.set_subtensor(A[diag_idx], c)

pymc3/model.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import theano.tensor as tt
44
from theano.tensor.var import TensorVariable
55

6+
import pymc3 as pm
67
from .memoize import memoize
78
from .theanof import gradient, hessian, inputvars
89
from .vartypes import typefilter, discrete_types, continuous_types
@@ -81,7 +82,7 @@ def get_named_nodes(graph):
8182

8283

8384
def _get_named_nodes(graph, nodes):
84-
if graph.owner == None:
85+
if graph.owner is None:
8586
if graph.name is not None:
8687
nodes.update({graph.name: graph})
8788
else:
@@ -287,11 +288,11 @@ def Var(self, name, dist, data=None):
287288
var = TransformedRV(name=name, distribution=dist, model=self,
288289
transform=dist.transform)
289290
if self.verbose:
290-
print('Applied {transform}-transform to {name}'
291-
' and added transformed {orig_name} to model.'.format(
292-
transform=dist.transform.name,
293-
name=name,
294-
orig_name='{}_{}_'.format(name, dist.transform.name)))
291+
pm._log.info('Applied {transform}-transform to {name}'
292+
' and added transformed {orig_name} to model.'.format(
293+
transform=dist.transform.name,
294+
name=name,
295+
orig_name='{}_{}_'.format(name, dist.transform.name)))
295296
self.deterministics.append(var)
296297
return var
297298
elif isinstance(data, dict):

pymc3/plots.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import numpy as np
22
from scipy.stats import kde, mode
3-
from .stats import autocorr, quantiles, hpd
43
from numpy.linalg import LinAlgError
54
import matplotlib.pyplot as plt
5+
import pymc3 as pm
6+
from .stats import quantiles, hpd
67

78
__all__ = ['traceplot', 'kdeplot', 'kde2plot',
89
'forestplot', 'autocorrplot', 'plot_posterior']
@@ -69,7 +70,7 @@ def traceplot(trace, varnames=None, transform=lambda x: x, figsize=None,
6970
if ax is None:
7071
fig, ax = plt.subplots(n, 2, squeeze=False, figsize=figsize)
7172
elif ax.shape != (n, 2):
72-
print('traceplot requires n*2 subplots')
73+
pm._log.warning('traceplot requires n*2 subplots')
7374
return None
7475

7576
for i, v in enumerate(varnames):
@@ -168,14 +169,14 @@ def kde2plot_op(ax, x, y, grid=200):
168169

169170
def kdeplot(data, ax=None):
170171
if ax is None:
171-
f, ax = subplots(1, 1, squeeze=True)
172+
f, ax = plt.subplots(1, 1, squeeze=True)
172173
kdeplot_op(ax, data)
173174
return ax
174175

175176

176177
def kde2plot(x, y, grid=200, ax=None):
177178
if ax is None:
178-
f, ax = subplots(1, 1, squeeze=True)
179+
f, ax = plt.subplots(1, 1, squeeze=True)
179180
kde2plot_op(ax, x, y, grid)
180181
return ax
181182

pymc3/sampling.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from numpy.random import randint, seed
55
from numpy import shape, asarray
66

7-
from . import backends
7+
import pymc3 as pm
88
from .backends.base import merge_traces, BaseTrace, MultiTrace
99
from .backends.ndarray import NDArray
1010
from .model import modelcontext, Point
@@ -69,7 +69,7 @@ def assign_step_methods(model, step=None, methods=(NUTS, HamiltonianMC, Metropol
6969
if var not in assigned_vars:
7070
selected = max(methods, key=lambda method: method._competence(var))
7171
if model.verbose:
72-
print('Assigned {0} to {1}'.format(selected.__name__, var))
72+
pm._log.info('Assigned {0} to {1}'.format(selected.__name__, var))
7373
selected_steps[selected].append(var)
7474

7575
# Instantiate all selected step methods
@@ -262,7 +262,7 @@ def _choose_backend(trace, chain, shortcuts=None, **kwds):
262262
return NDArray(**kwds)
263263

264264
if shortcuts is None:
265-
shortcuts = backends._shortcuts
265+
shortcuts = pm.backends._shortcuts
266266

267267
try:
268268
backend = shortcuts[trace]['backend']

pymc3/stats.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
from scipy.stats.distributions import pareto
1111

12+
import pymc3 as pm
1213
from .backends import tracetab as ttab
1314

1415
__all__ = ['autocorr', 'autocov', 'dic', 'bpic', 'waic', 'loo', 'hpd', 'quantiles',
@@ -114,7 +115,7 @@ def waic(trace, model=None, n_eff=False):
114115
model : PyMC Model
115116
Optional model. Default None, taken from context.
116117
n_eff: bool
117-
if True the effective number parameters will be returned.
118+
if True the effective number parameters will be returned.
118119
Default False
119120
120121
Returns
@@ -131,8 +132,8 @@ def waic(trace, model=None, n_eff=False):
131132

132133
vars_lpd = np.var(log_py, axis=0)
133134
if np.any(vars_lpd > 0.4):
134-
warnings.warn("""For one or more samples the posterior variance of the
135-
log predictive densities exceeds 0.4. This could be indication of
135+
warnings.warn("""For one or more samples the posterior variance of the
136+
log predictive densities exceeds 0.4. This could be indication of
136137
WAIC starting to fail see http://arxiv.org/abs/1507.04544 for details
137138
""")
138139
p_waic = np.sum(vars_lpd)
@@ -155,7 +156,7 @@ def loo(trace, model=None, n_eff=False):
155156
model : PyMC Model
156157
Optional model. Default None, taken from context.
157158
n_eff: bool
158-
if True the effective number parameters will be computed and returned.
159+
if True the effective number parameters will be computed and returned.
159160
Default False
160161
161162
Returns
@@ -189,7 +190,7 @@ def loo(trace, model=None, n_eff=False):
189190
if np.any(pareto_fit[0] > 0.5):
190191
warnings.warn("""Estimated shape parameter of Pareto distribution
191192
is for one or more samples is greater than 0.5. This may indicate
192-
that the variance of the Pareto smoothed importance sampling estimate
193+
that the variance of the Pareto smoothed importance sampling estimate
193194
is very large.""")
194195

195196
# Calculate expected values of the order statistics of the fitted Pareto
@@ -404,7 +405,7 @@ def quantiles(x, qlist=(2.5, 25, 50, 75, 97.5), transform=lambda x: x):
404405
return dict(zip(qlist, quants))
405406

406407
except IndexError:
407-
print("Too few elements for quantile calculation")
408+
_log.warning("Too few elements for quantile calculation")
408409

409410

410411
def df_summary(trace, varnames=None, stat_funcs=None, extend=False, include_transformed=False,
@@ -438,7 +439,7 @@ def df_summary(trace, varnames=None, stat_funcs=None, extend=False, include_tran
438439
addition to, rather than in place of, the default statistics.
439440
This is only meaningful when `stat_funcs` is not None.
440441
include_transformed : bool
441-
Flag for reporting automatically transformed variables in addition to
442+
Flag for reporting automatically transformed variables in addition to
442443
original variables (defaults to False).
443444
alpha : float
444445
The alpha level for generating posterior intervals. Defaults
@@ -545,7 +546,7 @@ def summary(trace, varnames=None, alpha=0.05, start=0, batches=100, roundto=3,
545546
The number of digits to round posterior statistics.
546547
547548
include_transformed : bool
548-
Flag for summarizing automatically transformed variables in addition to
549+
Flag for summarizing automatically transformed variables in addition to
549550
original variables (defaults to False).
550551
551552
tofile : None or string

pymc3/tuning/starting.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from scipy import optimize
77
import numpy as np
88
from numpy import isfinite, nan_to_num, logical_not
9+
import pymc3 as pm
910
from ..vartypes import discrete_types, typefilter
1011
from ..model import modelcontext, Point
1112
from ..theanof import inputvars
@@ -51,10 +52,10 @@ def find_MAP(start=None, vars=None, fmin=None, return_raw=False,
5152
kwargs["disp"] = model.verbose > 1
5253

5354
if disc_vars and kwargs["disp"]:
54-
print("Warning: vars contains discrete variables. MAP " +
55-
"estimates may not be accurate for the default " +
56-
"parameters. Defaulting to non-gradient minimization " +
57-
"fmin_powell.")
55+
pm._log.warning("Warning: vars contains discrete variables. MAP " +
56+
"estimates may not be accurate for the default " +
57+
"parameters. Defaulting to non-gradient minimization " +
58+
"fmin_powell.")
5859
fmin = optimize.fmin_powell
5960

6061
if fmin is None:

0 commit comments

Comments
 (0)