mc3 3.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mc3/__init__.py +25 -0
- mc3/__main__.py +240 -0
- mc3/chain.py +340 -0
- mc3/fit_driver.py +270 -0
- mc3/mcmc_driver.py +378 -0
- mc3/plots/__init__.py +20 -0
- mc3/plots/colors.py +209 -0
- mc3/plots/plot_functions.py +351 -0
- mc3/plots/posterior.py +1278 -0
- mc3/sampler_driver.py +601 -0
- mc3/stats/__init__.py +25 -0
- mc3/stats/dwt.py +229 -0
- mc3/stats/gelman.py +92 -0
- mc3/stats/prayer.py +28 -0
- mc3/stats/stats.py +1043 -0
- mc3/stats/time_averaging.py +199 -0
- mc3/utils/__init__.py +18 -0
- mc3/utils/log.py +269 -0
- mc3/utils/utils.py +470 -0
- mc3/version.py +9 -0
- mc3-3.3.0.dist-info/METADATA +60 -0
- mc3-3.3.0.dist-info/RECORD +26 -0
- mc3-3.3.0.dist-info/WHEEL +5 -0
- mc3-3.3.0.dist-info/entry_points.txt +2 -0
- mc3-3.3.0.dist-info/licenses/LICENSE +19 -0
- mc3-3.3.0.dist-info/top_level.txt +1 -0
mc3/plots/posterior.py
ADDED
|
@@ -0,0 +1,1278 @@
|
|
|
1
|
+
# Copyright (c) 2015-2026 Patricio Cubillos and contributors.
|
|
2
|
+
# mc3 is open-source software under the MIT license (see LICENSE).
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
'subplot',
|
|
6
|
+
'_histogram',
|
|
7
|
+
'_pairwise',
|
|
8
|
+
'hist_2D',
|
|
9
|
+
'Marginal',
|
|
10
|
+
'Figure',
|
|
11
|
+
'Posterior',
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
import copy
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
import matplotlib as mpl
|
|
18
|
+
import matplotlib.pyplot as plt
|
|
19
|
+
from matplotlib import _pylab_helpers
|
|
20
|
+
from matplotlib.colors import is_color_like, to_rgba
|
|
21
|
+
from matplotlib.lines import Line2D
|
|
22
|
+
import scipy.interpolate as si
|
|
23
|
+
|
|
24
|
+
from .. import stats as ms
|
|
25
|
+
from .. import utils as u
|
|
26
|
+
from . import colors
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def is_open(fig):
|
|
30
|
+
"""Check if a figure has been closed."""
|
|
31
|
+
current_figs = [
|
|
32
|
+
manager.canvas.figure
|
|
33
|
+
for manager in _pylab_helpers.Gcf.figs.values()
|
|
34
|
+
]
|
|
35
|
+
return fig in current_figs
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def subplot(rect, margin, pos, nx, ny=None, ymargin=None, dry=False):
|
|
39
|
+
"""
|
|
40
|
+
Create an axis instance for one panel (with index pos) of a grid
|
|
41
|
+
of npanels, where the grid located inside rect (xleft, ybottom,
|
|
42
|
+
xright, ytop).
|
|
43
|
+
|
|
44
|
+
Parameters
|
|
45
|
+
----------
|
|
46
|
+
rect: 1D List/ndarray
|
|
47
|
+
Rectangle with xlo, ylo, xhi, yhi positions of the grid boundaries.
|
|
48
|
+
margin: Float
|
|
49
|
+
Width of margin between panels.
|
|
50
|
+
pos: Integer
|
|
51
|
+
Index of panel to create (as in plt.subplots).
|
|
52
|
+
nx: Integer
|
|
53
|
+
Number of panels along the x axis.
|
|
54
|
+
ny: Integer
|
|
55
|
+
Number of panels along the y axis. If None, assume ny=nx.
|
|
56
|
+
ymargin: Float
|
|
57
|
+
Width of margin between panels along y axes (if None, adopt margin).
|
|
58
|
+
|
|
59
|
+
Returns
|
|
60
|
+
-------
|
|
61
|
+
axes: Matplotlib.axes.Axes
|
|
62
|
+
An Axes instance at the specified position.
|
|
63
|
+
"""
|
|
64
|
+
if ny is None:
|
|
65
|
+
ny = nx
|
|
66
|
+
if ymargin is None:
|
|
67
|
+
ymargin = margin
|
|
68
|
+
|
|
69
|
+
# Size of a panel:
|
|
70
|
+
Dx = rect[2] - rect[0]
|
|
71
|
+
Dy = rect[3] - rect[1]
|
|
72
|
+
dx = Dx/nx - (nx-1.0)* margin/nx
|
|
73
|
+
dy = Dy/ny - (ny-1.0)*ymargin/ny
|
|
74
|
+
# Position of panel pos:
|
|
75
|
+
# Follow plt's scheme, where panel 1 is at the top left panel,
|
|
76
|
+
# panel 2 is to the right of panel 1, and so on:
|
|
77
|
+
xloc = (pos-1) % nx
|
|
78
|
+
yloc = (ny-1) - ((pos-1) // nx)
|
|
79
|
+
# Bottom-left corner of panel:
|
|
80
|
+
xpanel = rect[0] + xloc*(dx+ margin)
|
|
81
|
+
ypanel = rect[1] + yloc*(dy+ymargin)
|
|
82
|
+
|
|
83
|
+
if dry:
|
|
84
|
+
return [xpanel, ypanel, dx, dy]
|
|
85
|
+
return plt.axes([xpanel, ypanel, dx, dy])
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def hist_2D(posterior, ranges, nbins):
|
|
89
|
+
"""Construct 2D histograms."""
|
|
90
|
+
nsamples, npars = np.shape(posterior)
|
|
91
|
+
# Column index matches par index, row index matches par index + 1
|
|
92
|
+
hist_xran = np.zeros((npars, nbins+1))
|
|
93
|
+
hist = np.zeros((npars-1, npars-1, nbins, nbins))
|
|
94
|
+
lmax = np.zeros((npars-1, npars-1))
|
|
95
|
+
for icol in range(npars-1):
|
|
96
|
+
for irow in range(icol, npars-1):
|
|
97
|
+
ran = None
|
|
98
|
+
if ranges[icol] is not None:
|
|
99
|
+
ran = [ranges[irow+1], ranges[icol]]
|
|
100
|
+
h, y, x = np.histogram2d(
|
|
101
|
+
posterior[:,irow+1],
|
|
102
|
+
posterior[:,icol],
|
|
103
|
+
bins=nbins, range=ran, density=False,
|
|
104
|
+
)
|
|
105
|
+
hist[irow, icol] = h
|
|
106
|
+
if icol == 0:
|
|
107
|
+
hist_xran[irow+1] = y
|
|
108
|
+
if irow == 0 and icol == 0:
|
|
109
|
+
hist_xran[irow] = x
|
|
110
|
+
lmax[irow, icol] = np.amax(h) + 1
|
|
111
|
+
return hist_xran, hist, lmax
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _histogram(
|
|
115
|
+
posterior, estimates, ranges, axes,
|
|
116
|
+
nbins, pdf, xpdf, hpd_min, low_bounds, high_bounds,
|
|
117
|
+
linewidth, theme, orientation, alpha=0.6,
|
|
118
|
+
top_pad=1.05,
|
|
119
|
+
clear=True,
|
|
120
|
+
):
|
|
121
|
+
"""
|
|
122
|
+
Lowest-lever routine to plot marginal posterior distributions.
|
|
123
|
+
"""
|
|
124
|
+
nsamples, npars = np.shape(posterior)
|
|
125
|
+
has_credible_interval = (
|
|
126
|
+
hpd_min is not None
|
|
127
|
+
or low_bounds is not None
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
hist_kw = {
|
|
131
|
+
'bins': nbins,
|
|
132
|
+
'linewidth': linewidth,
|
|
133
|
+
'orientation': orientation,
|
|
134
|
+
'facecolor': to_rgba(theme.light_color, alpha=alpha),
|
|
135
|
+
'edgecolor': theme.color,
|
|
136
|
+
'histtype': 'stepfilled',
|
|
137
|
+
'density': True,
|
|
138
|
+
}
|
|
139
|
+
if has_credible_interval:
|
|
140
|
+
hist_kw['facecolor'] = 'none'
|
|
141
|
+
|
|
142
|
+
for i in range(npars):
|
|
143
|
+
if np.any(np.isnan(posterior[:,i])):
|
|
144
|
+
continue
|
|
145
|
+
ax = axes[i]
|
|
146
|
+
if clear:
|
|
147
|
+
ax.clear()
|
|
148
|
+
if orientation == 'vertical':
|
|
149
|
+
xax, yax = ax.xaxis, ax.yaxis
|
|
150
|
+
fill_between = ax.fill_between
|
|
151
|
+
axline = ax.axvline
|
|
152
|
+
else:
|
|
153
|
+
xax, yax = ax.yaxis, ax.xaxis
|
|
154
|
+
fill_between = ax.fill_betweenx
|
|
155
|
+
axline = ax.axhline
|
|
156
|
+
|
|
157
|
+
vals, bins, h = ax.hist(posterior[:,i], range=ranges[i], **hist_kw)
|
|
158
|
+
# Plot the credible intervals as shaded areas:
|
|
159
|
+
if has_credible_interval:
|
|
160
|
+
vals = np.r_[0, vals, 0]
|
|
161
|
+
bins = np.r_[bins[0] - (bins[1]-bins[0]), bins]
|
|
162
|
+
f = si.interp1d(bins+0.5*(bins[1]-bins[0]), vals, kind='nearest')
|
|
163
|
+
xran = (xpdf[i]>ranges[i][0]) & (xpdf[i]<ranges[i][1])
|
|
164
|
+
|
|
165
|
+
if hpd_min is not None:
|
|
166
|
+
x_shade = pdf[i][xran] >= hpd_min[i]
|
|
167
|
+
elif low_bounds is not None:
|
|
168
|
+
x_shade = (
|
|
169
|
+
(xpdf[i][xran] >= low_bounds[i]) &
|
|
170
|
+
(xpdf[i][xran] <= high_bounds[i])
|
|
171
|
+
)
|
|
172
|
+
fill_between(
|
|
173
|
+
xpdf[i][xran], 0.0, f(xpdf[i][xran]),
|
|
174
|
+
where=x_shade,
|
|
175
|
+
facecolor=theme.light_color,
|
|
176
|
+
edgecolor='none',
|
|
177
|
+
interpolate=False,
|
|
178
|
+
alpha=alpha,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
if estimates[i] is not None:
|
|
182
|
+
axline(
|
|
183
|
+
estimates[i],
|
|
184
|
+
dashes=(9,2),
|
|
185
|
+
lw=linewidth,
|
|
186
|
+
color=theme.dark_color,
|
|
187
|
+
)
|
|
188
|
+
ytop = top_pad * np.amax(vals)
|
|
189
|
+
if ytop > yax.get_view_interval()[1]:
|
|
190
|
+
yax.set_view_interval(0, ytop, ignore=True)
|
|
191
|
+
xax.set_view_interval(*ranges[i], ignore=True)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _pairwise(
|
|
195
|
+
hist, hist_xran, axes, ranges, estimates,
|
|
196
|
+
palette, nlevels, absolute_dens, lmax,
|
|
197
|
+
linewidth, theme, alpha=0.8, clear=True,
|
|
198
|
+
swap_axes=False,
|
|
199
|
+
):
|
|
200
|
+
"""
|
|
201
|
+
Lowest-lever routine to plot pair-wise posterior distributions.
|
|
202
|
+
(Everything happening inside the axes)
|
|
203
|
+
"""
|
|
204
|
+
npars = len(ranges)
|
|
205
|
+
# Reset upper boundary to absolute maximum value if requested:
|
|
206
|
+
if absolute_dens:
|
|
207
|
+
lmax[:] = np.amax(lmax)
|
|
208
|
+
|
|
209
|
+
for icol in range(npars-1):
|
|
210
|
+
for irow in range(icol, npars-1):
|
|
211
|
+
ax = axes[irow,icol]
|
|
212
|
+
if swap_axes:
|
|
213
|
+
row, col = icol, irow+1
|
|
214
|
+
histo = hist[col-1,row].T
|
|
215
|
+
else:
|
|
216
|
+
row, col = irow+1, icol
|
|
217
|
+
histo = hist[row-1,col]
|
|
218
|
+
if clear:
|
|
219
|
+
ax.clear()
|
|
220
|
+
extent = (
|
|
221
|
+
hist_xran[col, 0],
|
|
222
|
+
hist_xran[col, -1],
|
|
223
|
+
hist_xran[row, 0],
|
|
224
|
+
hist_xran[row, -1],
|
|
225
|
+
)
|
|
226
|
+
levels = np.zeros(nlevels+1)
|
|
227
|
+
levels[1:] = np.linspace(1.0, lmax[irow,icol], nlevels)
|
|
228
|
+
colors = palette(levels/lmax[irow,icol], alpha=alpha)
|
|
229
|
+
colors[0,3] = 0.0
|
|
230
|
+
colors[1,3] = 0.75*alpha
|
|
231
|
+
cont = ax.contourf(
|
|
232
|
+
histo,
|
|
233
|
+
colors=colors, levels=levels,
|
|
234
|
+
origin='lower', extent=extent,
|
|
235
|
+
)
|
|
236
|
+
edge_color = to_rgba(theme.color, alpha=0.25)
|
|
237
|
+
edge_colors = [edge_color for _ in cont.get_paths()]
|
|
238
|
+
edge_colors[0] = (1,1,1,0)
|
|
239
|
+
cont.set_edgecolor(edge_colors)
|
|
240
|
+
cont.set_linewidth(0.1)
|
|
241
|
+
|
|
242
|
+
if estimates[col] is not None:
|
|
243
|
+
ax.axvline(
|
|
244
|
+
estimates[col],
|
|
245
|
+
dashes=(9,2), lw=linewidth, color=theme.dark_color,
|
|
246
|
+
)
|
|
247
|
+
if estimates[row] is not None:
|
|
248
|
+
ax.axhline(
|
|
249
|
+
estimates[row],
|
|
250
|
+
dashes=(9,2), lw=linewidth, color=theme.dark_color,
|
|
251
|
+
)
|
|
252
|
+
if ranges[col] is not None:
|
|
253
|
+
ax.set_xlim(ranges[col])
|
|
254
|
+
if ranges[row] is not None:
|
|
255
|
+
ax.set_ylim(ranges[row])
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _plot_marginal(obj):
|
|
259
|
+
"""Re-draw everything except the data inside the axes."""
|
|
260
|
+
npars = obj.npars
|
|
261
|
+
ax = obj.hist_axes[0]
|
|
262
|
+
fig = ax.get_figure()
|
|
263
|
+
|
|
264
|
+
for text in obj.stats_texts:
|
|
265
|
+
text.set_visible(False)
|
|
266
|
+
obj.stats_texts = []
|
|
267
|
+
for i in range(npars):
|
|
268
|
+
ax = obj.hist_axes[i]
|
|
269
|
+
if obj.orientation == 'vertical':
|
|
270
|
+
xax, yax = ax.xaxis, ax.yaxis
|
|
271
|
+
else:
|
|
272
|
+
xax, yax = ax.yaxis, ax.xaxis
|
|
273
|
+
|
|
274
|
+
ax.tick_params(
|
|
275
|
+
labelsize=obj.fontsize-1, direction='in', left=False, top=True,
|
|
276
|
+
)
|
|
277
|
+
xax.set_label_text(obj.pnames[i], fontsize=obj.fontsize)
|
|
278
|
+
yax.set_ticklabels([])
|
|
279
|
+
|
|
280
|
+
if obj.show_texts:
|
|
281
|
+
texts = [rf'{obj.source.tex_estimates[i]}']
|
|
282
|
+
obj.stats_texts += colors.rainbow_text(
|
|
283
|
+
ax, texts, obj.fontsize-0.25, loc='inside',
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
if not obj.auto_axes:
|
|
287
|
+
continue
|
|
288
|
+
ax_position = subplot(
|
|
289
|
+
obj.rect, obj.margin, i+1, obj.nx, obj.ny, obj.ymargin, dry=True,
|
|
290
|
+
)
|
|
291
|
+
ax.set_position(ax_position)
|
|
292
|
+
if i == 0:
|
|
293
|
+
pt_to_pix = fig.canvas.get_renderer().points_to_pixels(72.0)
|
|
294
|
+
axes_size_pix = np.amin(ax.get_window_extent().size)
|
|
295
|
+
axes_size_pt = axes_size_pix / pt_to_pix * 72.0
|
|
296
|
+
tick_size = np.amin([3.5, axes_size_pt/15.0])
|
|
297
|
+
ax.tick_params(length=tick_size)
|
|
298
|
+
|
|
299
|
+
if i%obj.nx == 0:
|
|
300
|
+
yax.set_label_text('Posterior', fontsize=obj.fontsize)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _plot_pairwise(obj):
|
|
304
|
+
"""Re-draw everything except the data inside the axes."""
|
|
305
|
+
npars = obj.npars
|
|
306
|
+
|
|
307
|
+
# Estimate size of axes (to later set the length of the ticks)
|
|
308
|
+
ax = obj.pair_axes[0,0]
|
|
309
|
+
fig = ax.get_figure()
|
|
310
|
+
|
|
311
|
+
nx = npars + int(obj.plot_marginal) - 1
|
|
312
|
+
for icol in range(npars-1):
|
|
313
|
+
for irow in range(icol, npars-1):
|
|
314
|
+
ax = obj.pair_axes[irow,icol]
|
|
315
|
+
if obj.orientation == 'vertical':
|
|
316
|
+
h = nx*irow + icol + 1 + npars*int(obj.plot_marginal)
|
|
317
|
+
else:
|
|
318
|
+
h = 2 + (nx+int(obj.plot_marginal))*icol + irow - icol
|
|
319
|
+
|
|
320
|
+
ax_position = subplot(
|
|
321
|
+
obj.rect, obj.margin, h, nx, nx, obj.ymargin, dry=True,
|
|
322
|
+
)
|
|
323
|
+
ax.set_position(ax_position)
|
|
324
|
+
if icol==0 and irow==0:
|
|
325
|
+
pt_to_pix = fig.canvas.get_renderer().points_to_pixels(72.0)
|
|
326
|
+
axes_size_pix = np.amin(ax.get_window_extent().size)
|
|
327
|
+
axes_size_pt = axes_size_pix / pt_to_pix * 72.0
|
|
328
|
+
tick_size = np.amin([3.5, axes_size_pt/15.0])
|
|
329
|
+
# Labels:
|
|
330
|
+
ax.tick_params(
|
|
331
|
+
labelsize=obj.fontsize-1,
|
|
332
|
+
length=tick_size,
|
|
333
|
+
direction='in',
|
|
334
|
+
)
|
|
335
|
+
if icol == 0:
|
|
336
|
+
ax.set_ylabel(obj.pnames[irow+1], size=obj.fontsize)
|
|
337
|
+
else:
|
|
338
|
+
ax.set_yticklabels([])
|
|
339
|
+
if irow == npars-2:
|
|
340
|
+
ax.set_xlabel(obj.pnames[icol], size=obj.fontsize)
|
|
341
|
+
plt.setp(ax.xaxis.get_majorticklabels(), rotation=90)
|
|
342
|
+
else:
|
|
343
|
+
ax.set_xticklabels([])
|
|
344
|
+
|
|
345
|
+
# Re-draw the colorbar:
|
|
346
|
+
colorbar = obj.colorbar
|
|
347
|
+
dx = (obj.rect[2]-obj.rect[0])*0.03
|
|
348
|
+
dy = (obj.rect[3]-obj.rect[1])*0.45
|
|
349
|
+
colorbar.ax.set_position([obj.rect[2]-dx, obj.rect[3]-dy, dx, dy])
|
|
350
|
+
colorbar.ax.clear()
|
|
351
|
+
boundaries = np.linspace(0.0, 1.0, obj.nlevels)
|
|
352
|
+
norm = mpl.colors.BoundaryNorm(boundaries, obj.nlevels)
|
|
353
|
+
cmap = mpl.colors.ListedColormap(obj.palette(boundaries, alpha=0.8))
|
|
354
|
+
mappable = mpl.cm.ScalarMappable(cmap=cmap, norm=norm)
|
|
355
|
+
obj.colorbar = mpl.colorbar.Colorbar(
|
|
356
|
+
ax=colorbar.ax,
|
|
357
|
+
mappable=mappable,
|
|
358
|
+
boundaries=boundaries,
|
|
359
|
+
ticks=np.linspace(0.0, 1.0, 6),
|
|
360
|
+
ticklocation='left',
|
|
361
|
+
)
|
|
362
|
+
colorbar.set_label('Posterior density', fontsize=obj.fontsize)
|
|
363
|
+
colorbar.ax.tick_params(labelsize=obj.fontsize-1, direction='in')
|
|
364
|
+
colorbar.ax.minorticks_off()
|
|
365
|
+
for col in colorbar.ax.collections:
|
|
366
|
+
col.set_edgecolor('face')
|
|
367
|
+
colorbar.ax.set_visible(obj.show_colorbar)
|
|
368
|
+
|
|
369
|
+
# Histogram:
|
|
370
|
+
for text in obj.stats_texts:
|
|
371
|
+
text.set_visible(False)
|
|
372
|
+
obj.stats_texts = []
|
|
373
|
+
nx = npars
|
|
374
|
+
for i in range(npars):
|
|
375
|
+
ax = obj.hist_axes[i]
|
|
376
|
+
ax.set_visible(obj.plot_marginal)
|
|
377
|
+
if not obj.plot_marginal:
|
|
378
|
+
continue
|
|
379
|
+
if obj.orientation == 'vertical':
|
|
380
|
+
xax, yax = ax.xaxis, ax.yaxis
|
|
381
|
+
plt.setp(ax.xaxis.get_majorticklabels(), rotation=90)
|
|
382
|
+
else:
|
|
383
|
+
xax, yax = ax.yaxis, ax.xaxis
|
|
384
|
+
|
|
385
|
+
h = (npars+1)*i + 1
|
|
386
|
+
ax_position = subplot(
|
|
387
|
+
obj.rect, obj.margin, h, nx, nx, obj.ymargin, dry=True)
|
|
388
|
+
ax.set_position(ax_position)
|
|
389
|
+
|
|
390
|
+
ax.tick_params(
|
|
391
|
+
labelsize=obj.fontsize-1,
|
|
392
|
+
length=tick_size,
|
|
393
|
+
direction='in', left=False, top=True,
|
|
394
|
+
)
|
|
395
|
+
if i == npars-1:
|
|
396
|
+
xax.set_label_text(obj.pnames[i], fontsize=obj.fontsize)
|
|
397
|
+
else:
|
|
398
|
+
xax.set_label_text('', fontsize=obj.fontsize)
|
|
399
|
+
xax.set_ticklabels([])
|
|
400
|
+
yax.set_ticklabels([])
|
|
401
|
+
|
|
402
|
+
if not obj.show_texts:
|
|
403
|
+
continue
|
|
404
|
+
elif i < npars-1:
|
|
405
|
+
stats_text = rf'{obj.pnames[i]} = {obj.source.tex_estimates[i]}'
|
|
406
|
+
else:
|
|
407
|
+
stats_text = rf'{obj.source.tex_estimates[i]}'
|
|
408
|
+
texts = [stats_text]
|
|
409
|
+
obj.stats_texts += colors.rainbow_text(ax, texts, obj.fontsize)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
class SoftUpdate:
|
|
413
|
+
""" https://docs.python.org/3/howto/descriptor.html """
|
|
414
|
+
def __set_name__(self, obj, name):
|
|
415
|
+
self.private_name = '_' + name
|
|
416
|
+
|
|
417
|
+
def __get__(self, obj, objtype=None):
|
|
418
|
+
value = getattr(obj, self.private_name)
|
|
419
|
+
return value
|
|
420
|
+
|
|
421
|
+
def __set__(self, obj, value):
|
|
422
|
+
var_name = self.private_name[1:]
|
|
423
|
+
setattr(obj, self.private_name, value)
|
|
424
|
+
setattr(obj.source, var_name, value)
|
|
425
|
+
|
|
426
|
+
# TBD: Inspect this clause
|
|
427
|
+
if hasattr(obj, 'pair_axes'):
|
|
428
|
+
if obj.pair_axes is not None:
|
|
429
|
+
_plot_pairwise(obj)
|
|
430
|
+
plt.draw()
|
|
431
|
+
else:
|
|
432
|
+
if obj.hist_axes is not None:
|
|
433
|
+
_plot_marginal(obj)
|
|
434
|
+
plt.draw()
|
|
435
|
+
|
|
436
|
+
def raise_array_size_error(self, obj, value):
|
|
437
|
+
raise ValueError(
|
|
438
|
+
f"Invalid {self.private_name[1:]} input. Array size "
|
|
439
|
+
f"({len(value)}) does not match number of parameters "
|
|
440
|
+
f"({obj.npars})"
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
class SizeUpdate(SoftUpdate):
|
|
445
|
+
def __set__(self, obj, value):
|
|
446
|
+
setattr(obj, self.private_name, tuple(value))
|
|
447
|
+
if obj.fig is not None:
|
|
448
|
+
obj.fig.set_size_inches(*list(value))
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
class ThemeUpdate(SoftUpdate):
|
|
452
|
+
def __set__(self, obj, value):
|
|
453
|
+
var_name = self.private_name[1:]
|
|
454
|
+
# TBD: add checks
|
|
455
|
+
if isinstance(value, colors.Theme):
|
|
456
|
+
pass
|
|
457
|
+
elif isinstance(value, str) and value in colors.THEMES:
|
|
458
|
+
value = colors.THEMES[value]
|
|
459
|
+
elif is_color_like(value):
|
|
460
|
+
value = colors.Theme(value)
|
|
461
|
+
setattr(obj, self.private_name, value)
|
|
462
|
+
setattr(obj.source, var_name, value)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
class BestpUpdate(SoftUpdate):
|
|
466
|
+
def __set__(self, obj, value):
|
|
467
|
+
var_name = self.private_name[1:]
|
|
468
|
+
if not hasattr(obj, 'npars'):
|
|
469
|
+
return
|
|
470
|
+
if value is None:
|
|
471
|
+
value = [None for _ in range(obj.npars)]
|
|
472
|
+
if len(value) != obj.npars:
|
|
473
|
+
self.raise_array_size_error(obj, value)
|
|
474
|
+
setattr(obj, self.private_name, value)
|
|
475
|
+
setattr(obj.source, var_name, value)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
class StatsUpdate(SoftUpdate):
|
|
479
|
+
def __set__(self, obj, value):
|
|
480
|
+
var_name = self.private_name[1:]
|
|
481
|
+
setattr(obj, self.private_name, value)
|
|
482
|
+
setattr(obj.source, var_name, value)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
class QuantileUpdate(SoftUpdate):
|
|
486
|
+
def __set__(self, obj, value):
|
|
487
|
+
var_name = self.private_name[1:]
|
|
488
|
+
setattr(obj, self.private_name, value)
|
|
489
|
+
setattr(obj.source, var_name, value)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
class RangeUpdate(SoftUpdate):
|
|
493
|
+
def __set__(self, obj, value):
|
|
494
|
+
var_name = self.private_name[1:]
|
|
495
|
+
if not hasattr(obj, 'npars'):
|
|
496
|
+
return
|
|
497
|
+
pmins = np.nanmin(obj.posterior, axis=0)
|
|
498
|
+
pmaxs = np.nanmax(obj.posterior, axis=0)
|
|
499
|
+
# Defaults:
|
|
500
|
+
min_max = [(pmin, pmax) for pmin,pmax in zip(pmins, pmaxs)]
|
|
501
|
+
if value is None:
|
|
502
|
+
value = min_max
|
|
503
|
+
if len(value) != obj.npars:
|
|
504
|
+
self.raise_array_size_error(obj, value)
|
|
505
|
+
for i in range(obj.npars):
|
|
506
|
+
if value[i] is None:
|
|
507
|
+
value[i] = min_max[i]
|
|
508
|
+
setattr(obj, self.private_name, value)
|
|
509
|
+
setattr(obj.source, var_name, value)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
class Marginal():
|
|
513
|
+
"""A mostly-interactive marginal posterior plotting object."""
|
|
514
|
+
# Soft-update properties:
|
|
515
|
+
pnames = SoftUpdate()
|
|
516
|
+
rect = SoftUpdate()
|
|
517
|
+
margin = SoftUpdate()
|
|
518
|
+
ymargin = SoftUpdate()
|
|
519
|
+
fontsize = SoftUpdate()
|
|
520
|
+
figsize = SizeUpdate()
|
|
521
|
+
show_texts = SoftUpdate()
|
|
522
|
+
show_estimates = SoftUpdate()
|
|
523
|
+
|
|
524
|
+
# Properties that require re-drawing:
|
|
525
|
+
bestp = BestpUpdate()
|
|
526
|
+
ranges = RangeUpdate()
|
|
527
|
+
theme = ThemeUpdate()
|
|
528
|
+
quantile = QuantileUpdate()
|
|
529
|
+
statistics = StatsUpdate()
|
|
530
|
+
|
|
531
|
+
def __init__(
|
|
532
|
+
self, source, posterior, pnames, bestp, ranges, theme,
|
|
533
|
+
nx=None, ny=None,
|
|
534
|
+
statistics='med_central', quantile=0.683,
|
|
535
|
+
bins=25, fontsize=11, linewidth=1.5,
|
|
536
|
+
axes=None,
|
|
537
|
+
show_texts=True, show_estimates=True,
|
|
538
|
+
alpha=0.6,
|
|
539
|
+
):
|
|
540
|
+
self.source = source
|
|
541
|
+
self.fig = None
|
|
542
|
+
self.hist_axes = None
|
|
543
|
+
self.posterior = posterior
|
|
544
|
+
nsamples, self.npars = np.shape(posterior)
|
|
545
|
+
|
|
546
|
+
self.pnames = pnames
|
|
547
|
+
self.bestp = bestp
|
|
548
|
+
self.ranges = ranges
|
|
549
|
+
self.theme = theme
|
|
550
|
+
self.alpha = alpha
|
|
551
|
+
|
|
552
|
+
if nx is None or ny is None:
|
|
553
|
+
# Default layout:
|
|
554
|
+
npars = self.npars
|
|
555
|
+
if npars < 6: # Single row, N columns
|
|
556
|
+
nx = npars
|
|
557
|
+
elif npars < 13: # Two rows, up to 6 columns
|
|
558
|
+
nx = (npars+1) // 2
|
|
559
|
+
elif npars < 25: # Six columns, up to 4 rows
|
|
560
|
+
nx = 6
|
|
561
|
+
elif npars < 56: # 7 columns, up to 8 rows
|
|
562
|
+
nx = 7
|
|
563
|
+
else:
|
|
564
|
+
nx = 8 # Stick with 8 columns from now on
|
|
565
|
+
ny = 1 + (npars-1) // nx
|
|
566
|
+
self.nx = nx
|
|
567
|
+
self.ny = ny
|
|
568
|
+
# Default layout sizes:
|
|
569
|
+
dx0 = 0.4
|
|
570
|
+
self.figsize = size = [
|
|
571
|
+
dx0 + 1.45*self.nx,
|
|
572
|
+
1.75*self.ny + 0.1
|
|
573
|
+
]
|
|
574
|
+
self.margin = 0.04 / self.nx
|
|
575
|
+
self.ymargin = 0.275 / self.ny
|
|
576
|
+
self.rect = [
|
|
577
|
+
dx0/size[0], self.ymargin, 1.0 - 0.2/size[0], 1.0 - 0.1/size[1],
|
|
578
|
+
]
|
|
579
|
+
|
|
580
|
+
self.statistics = statistics
|
|
581
|
+
self.quantile = quantile
|
|
582
|
+
self.bins = bins
|
|
583
|
+
self.fontsize = fontsize
|
|
584
|
+
self.linewidth = linewidth
|
|
585
|
+
self.orientation = 'vertical'
|
|
586
|
+
self.show_texts = show_texts
|
|
587
|
+
self.show_estimates = show_estimates
|
|
588
|
+
self.stats_texts = []
|
|
589
|
+
|
|
590
|
+
def update(self):
|
|
591
|
+
# TBD: Need to erase previous axes
|
|
592
|
+
self.plot(
|
|
593
|
+
fignum=self.fignum,
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
def plot(
|
|
597
|
+
self, fignum=None, axes=None, quantile=None,
|
|
598
|
+
savefile=None,
|
|
599
|
+
):
|
|
600
|
+
"""Marginal histogram plot."""
|
|
601
|
+
# Create new figure unless explicitly point to existing axes:
|
|
602
|
+
if axes is not None:
|
|
603
|
+
self.hist_axes = axes
|
|
604
|
+
self.fig = axes[0].get_figure()
|
|
605
|
+
self.auto_axes = False
|
|
606
|
+
else:
|
|
607
|
+
self.fig = plt.figure(fignum)
|
|
608
|
+
self.fig.set_size_inches(self.figsize)
|
|
609
|
+
self.fig.clear()
|
|
610
|
+
self.auto_axes = True # False when user inputs custom axes
|
|
611
|
+
self.fignum = self.fig.number
|
|
612
|
+
self.figsize = self.fig.get_size_inches()
|
|
613
|
+
|
|
614
|
+
if axes is None:
|
|
615
|
+
self.hist_axes = np.tile(None, self.npars)
|
|
616
|
+
for i in range(self.npars):
|
|
617
|
+
self.hist_axes[i] = subplot(
|
|
618
|
+
self.rect, self.margin, i+1, self.nx, self.ny, self.ymargin,
|
|
619
|
+
)
|
|
620
|
+
|
|
621
|
+
if '_like' in self.statistics:
|
|
622
|
+
hpd_min = self.source.hpd_min
|
|
623
|
+
else:
|
|
624
|
+
hpd_min = None
|
|
625
|
+
|
|
626
|
+
estimates = self.source.estimates
|
|
627
|
+
if not self.show_estimates:
|
|
628
|
+
estimates = [None for _ in estimates]
|
|
629
|
+
|
|
630
|
+
_histogram(
|
|
631
|
+
self.posterior, estimates, self.ranges,
|
|
632
|
+
self.hist_axes, self.bins,
|
|
633
|
+
self.source.pdf, self.source.xpdf,
|
|
634
|
+
hpd_min, self.source.low_bounds, self.source.high_bounds,
|
|
635
|
+
self.linewidth, self.theme,
|
|
636
|
+
self.orientation,
|
|
637
|
+
alpha=self.alpha,
|
|
638
|
+
top_pad=1.25,
|
|
639
|
+
)
|
|
640
|
+
_plot_marginal(self)
|
|
641
|
+
|
|
642
|
+
if savefile is not None:
|
|
643
|
+
self.fig.savefig(savefile, dpi=300)
|
|
644
|
+
|
|
645
|
+
def overplot(self, posts, labels=None, nlevels=4, alpha=0.4, axes_mask=None):
|
|
646
|
+
"""
|
|
647
|
+
Overplot additional posteriors in the same figure.
|
|
648
|
+
|
|
649
|
+
This method is still work in progress!
|
|
650
|
+
Note that a call to self.update() or even soft updates
|
|
651
|
+
will remove all/some of the overplot data. In such case
|
|
652
|
+
the user would need to make a new call to self.overplot().
|
|
653
|
+
It is also recommended to set show_estimates=False to
|
|
654
|
+
prevent over-crowding the figures.
|
|
655
|
+
|
|
656
|
+
Parameters
|
|
657
|
+
----------
|
|
658
|
+
posts: 1D iterable of Posterior objects
|
|
659
|
+
Currently there are no checks that these new posteriors
|
|
660
|
+
have the same parameters (nor same statistics) as self.
|
|
661
|
+
The user needs to make sure they are all compartible.
|
|
662
|
+
labels: 1D iterable of strings
|
|
663
|
+
Labels for each posterior. Note that if provided, the
|
|
664
|
+
length of labels has to be one more than posts, because
|
|
665
|
+
it also contains the label for self.
|
|
666
|
+
"""
|
|
667
|
+
all_posts = [self.source] + list(posts)
|
|
668
|
+
for i,post in enumerate(posts):
|
|
669
|
+
estimates = post.estimates
|
|
670
|
+
if not self.show_estimates:
|
|
671
|
+
estimates = [None for _ in estimates]
|
|
672
|
+
hpd_min = None
|
|
673
|
+
if '_like' in self.statistics:
|
|
674
|
+
hpd_min = self.source.hpd_min
|
|
675
|
+
|
|
676
|
+
_histogram(
|
|
677
|
+
post.posterior, estimates, self.ranges,
|
|
678
|
+
self.hist_axes, self.bins,
|
|
679
|
+
post.pdf, post.xpdf,
|
|
680
|
+
hpd_min, post.low_bounds, post.high_bounds,
|
|
681
|
+
self.linewidth, post.theme,
|
|
682
|
+
post.orientation, alpha=alpha,
|
|
683
|
+
clear=False,
|
|
684
|
+
)
|
|
685
|
+
if not self.show_texts:
|
|
686
|
+
return
|
|
687
|
+
text_cols = [post.theme.color for post in all_posts]
|
|
688
|
+
for text in self.stats_texts:
|
|
689
|
+
text.set_visible(False)
|
|
690
|
+
self.stats_texts = []
|
|
691
|
+
|
|
692
|
+
for j in range(self.npars):
|
|
693
|
+
stats_texts = [
|
|
694
|
+
'' if post.mask[j] else rf'{post.tex_estimates[j]}'
|
|
695
|
+
for post in all_posts
|
|
696
|
+
]
|
|
697
|
+
self.stats_texts += colors.rainbow_text(
|
|
698
|
+
self.hist_axes[j], stats_texts, self.fontsize, text_cols,
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
class Figure(Marginal):
|
|
703
|
+
"""A mostly-interactive pair-wise posterior plotting object."""
|
|
704
|
+
# Soft-update properties:
|
|
705
|
+
plot_marginal = SoftUpdate()
|
|
706
|
+
show_colorbar = SoftUpdate()
|
|
707
|
+
|
|
708
|
+
def __init__(
|
|
709
|
+
self, source, posterior, pnames, bestp, ranges, theme,
|
|
710
|
+
plot_marginal=True,
|
|
711
|
+
figsize=None, rect=None, margin=None, ymargin=None,
|
|
712
|
+
statistics='med_central', quantile=0.683,
|
|
713
|
+
bins=25, nlevels=6, fontsize=None, linewidth=None,
|
|
714
|
+
show_texts=True, show_estimates=True,
|
|
715
|
+
show_colorbar=True,
|
|
716
|
+
figure=None,
|
|
717
|
+
fignum=None,
|
|
718
|
+
):
|
|
719
|
+
self.source = source
|
|
720
|
+
self.fig = figure
|
|
721
|
+
self.pair_axes = None
|
|
722
|
+
self.hist_axes = None
|
|
723
|
+
self.posterior = posterior
|
|
724
|
+
self.stats_texts = []
|
|
725
|
+
nsamples, self.npars = np.shape(posterior)
|
|
726
|
+
|
|
727
|
+
if fontsize is None:
|
|
728
|
+
# fs(5)=11.0, fs(20)=6.0
|
|
729
|
+
fontsize = np.clip((38.0 -self.npars)/3.0, 6.0, 11.0)
|
|
730
|
+
if linewidth is None:
|
|
731
|
+
# lw(5)=1.5, lw(10)=1.0, lw(20)=0.7
|
|
732
|
+
if self.npars <= 10:
|
|
733
|
+
linewidth = 2.0 - 0.1*self.npars
|
|
734
|
+
else:
|
|
735
|
+
linewidth = 1.3 - 0.03*self.npars
|
|
736
|
+
linewidth = np.clip(linewidth, 0.7, 1.5)
|
|
737
|
+
if margin is None:
|
|
738
|
+
# m(2)=0.01, m(10)=0.005, m(20)=0.003
|
|
739
|
+
if self.npars <= 10:
|
|
740
|
+
margin = 0.01125 - 0.000625*self.npars
|
|
741
|
+
else:
|
|
742
|
+
margin = 0.007 - 0.0002*self.npars
|
|
743
|
+
margin = np.clip(margin, 0.0025, 0.01)
|
|
744
|
+
|
|
745
|
+
self.pnames = pnames
|
|
746
|
+
self.bestp = bestp
|
|
747
|
+
self.ranges = ranges
|
|
748
|
+
self.theme = theme
|
|
749
|
+
if rect is None:
|
|
750
|
+
rect = [0.1, 0.1, 0.96, 0.96]
|
|
751
|
+
self.rect = rect
|
|
752
|
+
if figsize is None:
|
|
753
|
+
figsize = (8,8)
|
|
754
|
+
self.figsize = figsize
|
|
755
|
+
self.fignum = fignum
|
|
756
|
+
self.plot_marginal = plot_marginal
|
|
757
|
+
self.margin = margin
|
|
758
|
+
self.ymargin = ymargin
|
|
759
|
+
self.statistics = statistics
|
|
760
|
+
self.quantile = quantile
|
|
761
|
+
self.bins = bins
|
|
762
|
+
self.nlevels = nlevels
|
|
763
|
+
self.fontsize = fontsize
|
|
764
|
+
self.linewidth = linewidth
|
|
765
|
+
self.orientation = 'vertical'
|
|
766
|
+
self.show_texts = show_texts
|
|
767
|
+
self.show_estimates = show_estimates
|
|
768
|
+
self.show_colorbar = show_colorbar
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def update(self):
|
|
772
|
+
self.plot(
|
|
773
|
+
self.plot_marginal, figure=self.fig,
|
|
774
|
+
)
|
|
775
|
+
|
|
776
|
+
def plot(
|
|
777
|
+
self, plot_marginal=True, figure=None,
|
|
778
|
+
savefile=None,
|
|
779
|
+
):
|
|
780
|
+
"""Pairwise plus histogram plot."""
|
|
781
|
+
# Can't plot if there are no pairs:
|
|
782
|
+
if self.npars == 1:
|
|
783
|
+
return
|
|
784
|
+
# Create new figure unless explicitly point to an existing one:
|
|
785
|
+
if figure is not None and plt.fignum_exists(figure.number):
|
|
786
|
+
self.fig = figure
|
|
787
|
+
else:
|
|
788
|
+
self.fig = plt.figure(self.fignum)
|
|
789
|
+
self.fig.clear()
|
|
790
|
+
self.fig.set_size_inches(self.figsize)
|
|
791
|
+
self.fignum = self.fig.number
|
|
792
|
+
|
|
793
|
+
# Define the axes:
|
|
794
|
+
npars = self.npars
|
|
795
|
+
nx = npars + int(self.plot_marginal) - 1
|
|
796
|
+
|
|
797
|
+
pair_axes_do_not_exist = (
|
|
798
|
+
self.pair_axes is None or
|
|
799
|
+
self.pair_axes[0,0] not in self.fig.axes
|
|
800
|
+
)
|
|
801
|
+
if pair_axes_do_not_exist:
|
|
802
|
+
self.pair_axes = np.tile(None, (npars-1, npars-1))
|
|
803
|
+
for icol in range(npars-1):
|
|
804
|
+
for irow in range(icol, npars-1):
|
|
805
|
+
h = nx*irow + icol + 1 + npars*int(self.plot_marginal)
|
|
806
|
+
self.pair_axes[irow,icol] = subplot(
|
|
807
|
+
self.rect, self.margin, h, nx, ymargin=self.ymargin,
|
|
808
|
+
)
|
|
809
|
+
|
|
810
|
+
self.palette = copy.copy(self.theme.colormap)
|
|
811
|
+
self.palette.set_under(color='w')
|
|
812
|
+
self.palette.set_bad(color='w')
|
|
813
|
+
|
|
814
|
+
absolute_dens = False
|
|
815
|
+
self.hist_xran, self.hist, self.lmax = hist_2D(
|
|
816
|
+
self.posterior, self.ranges, self.bins,
|
|
817
|
+
)
|
|
818
|
+
|
|
819
|
+
estimates = self.source.estimates
|
|
820
|
+
if not self.show_estimates:
|
|
821
|
+
estimates = [None for _ in estimates]
|
|
822
|
+
|
|
823
|
+
# The pair-wise data:
|
|
824
|
+
_pairwise(
|
|
825
|
+
self.hist, self.hist_xran,
|
|
826
|
+
self.pair_axes, self.ranges, estimates,
|
|
827
|
+
self.palette,
|
|
828
|
+
self.nlevels,
|
|
829
|
+
absolute_dens,
|
|
830
|
+
self.lmax,
|
|
831
|
+
self.linewidth,
|
|
832
|
+
self.theme,
|
|
833
|
+
swap_axes=self.orientation=='upper right',
|
|
834
|
+
)
|
|
835
|
+
|
|
836
|
+
# The colorbar:
|
|
837
|
+
colorbar_does_not_exist = (
|
|
838
|
+
not hasattr(self, 'colorbar') or
|
|
839
|
+
self.colorbar.ax not in self.fig.axes
|
|
840
|
+
)
|
|
841
|
+
if colorbar_does_not_exist:
|
|
842
|
+
dx = (self.rect[2]-self.rect[0])*0.03
|
|
843
|
+
dy = (self.rect[3]-self.rect[1])*0.45
|
|
844
|
+
cb_ax = plt.axes([self.rect[2]-dx, self.rect[3]-dy, dx, dy])
|
|
845
|
+
mappable = mpl.cm.ScalarMappable()
|
|
846
|
+
self.colorbar = mpl.colorbar.Colorbar(cb_ax, mappable)
|
|
847
|
+
|
|
848
|
+
# Marginal posterior:
|
|
849
|
+
hist_axes_do_not_exist = (
|
|
850
|
+
self.hist_axes is None or
|
|
851
|
+
self.hist_axes[0] not in self.fig.axes
|
|
852
|
+
)
|
|
853
|
+
if hist_axes_do_not_exist:
|
|
854
|
+
self.hist_axes = np.tile(None, npars)
|
|
855
|
+
for i in range(npars):
|
|
856
|
+
h = (npars+1)*i + 1
|
|
857
|
+
self.hist_axes[i] = subplot(
|
|
858
|
+
self.rect, self.margin, h, npars, ymargin=self.ymargin,
|
|
859
|
+
)
|
|
860
|
+
|
|
861
|
+
if plot_marginal:
|
|
862
|
+
hpd_min = None
|
|
863
|
+
if '_like' in self.statistics:
|
|
864
|
+
hpd_min = self.source.hpd_min
|
|
865
|
+
_histogram(
|
|
866
|
+
self.posterior, estimates, self.ranges,
|
|
867
|
+
self.hist_axes, self.bins,
|
|
868
|
+
self.source.pdf, self.source.xpdf,
|
|
869
|
+
hpd_min,
|
|
870
|
+
self.source.low_bounds, self.source.high_bounds,
|
|
871
|
+
self.linewidth, self.theme,
|
|
872
|
+
self.orientation,
|
|
873
|
+
)
|
|
874
|
+
_plot_pairwise(self)
|
|
875
|
+
|
|
876
|
+
if savefile is not None:
|
|
877
|
+
self.fig.savefig(savefile, dpi=300)
|
|
878
|
+
|
|
879
|
+
def overplot(self, posts, labels=None, nlevels=4, alpha=0.4):
|
|
880
|
+
"""
|
|
881
|
+
Overplot additional posteriors in the same figure.
|
|
882
|
+
|
|
883
|
+
This method is still work in progress!
|
|
884
|
+
Note that a call to self.update() or even soft updates
|
|
885
|
+
will remove all/some of the overplot data. In such case
|
|
886
|
+
the user would need to make a new call to self.overplot().
|
|
887
|
+
It is also recommended to set show_estimates=False to
|
|
888
|
+
prevent over-crowding the figures.
|
|
889
|
+
|
|
890
|
+
Parameters
|
|
891
|
+
----------
|
|
892
|
+
posts: 1D iterable of Posterior objects
|
|
893
|
+
Currently there are no checks that these new posteriors
|
|
894
|
+
have the same parameters (nor same statistics) as self.
|
|
895
|
+
The user needs to make sure they are all compartible.
|
|
896
|
+
labels: 1D iterable of strings
|
|
897
|
+
Labels for each posterior. Note that if provided, the
|
|
898
|
+
length of labels has to be one more than posts, because
|
|
899
|
+
it also contains the label for self.
|
|
900
|
+
"""
|
|
901
|
+
all_posts = [self.source] + list(posts)
|
|
902
|
+
for post in posts:
|
|
903
|
+
post.hist_xran, post.hist, post.lmax = hist_2D(
|
|
904
|
+
post.posterior, self.ranges, self.bins,
|
|
905
|
+
)
|
|
906
|
+
absolute_dens = False
|
|
907
|
+
estimates = post.estimates
|
|
908
|
+
if not self.show_estimates:
|
|
909
|
+
estimates = [None for _ in estimates]
|
|
910
|
+
|
|
911
|
+
# Pair-wise plots:
|
|
912
|
+
_pairwise(
|
|
913
|
+
post.hist, post.hist_xran,
|
|
914
|
+
self.pair_axes, self.ranges, estimates,
|
|
915
|
+
post.theme.colormap,
|
|
916
|
+
nlevels,
|
|
917
|
+
absolute_dens,
|
|
918
|
+
post.lmax,
|
|
919
|
+
self.linewidth,
|
|
920
|
+
post.theme,
|
|
921
|
+
alpha=alpha,
|
|
922
|
+
clear=False,
|
|
923
|
+
)
|
|
924
|
+
# Posterior labels:
|
|
925
|
+
ax = self.hist_axes[0] if self.plot_marginal else self.pair_axes[0,0]
|
|
926
|
+
if labels is not None:
|
|
927
|
+
ret_handles = [
|
|
928
|
+
Line2D([], [], color=post.theme.color, label=label)
|
|
929
|
+
for post,label in zip(reversed(all_posts),reversed(labels))
|
|
930
|
+
]
|
|
931
|
+
if self.plot_marginal and self.show_texts:
|
|
932
|
+
loc = (2.1, 1.0)
|
|
933
|
+
else:
|
|
934
|
+
loc = (1.1, 0.1)
|
|
935
|
+
leg = ax.legend(
|
|
936
|
+
handles=ret_handles, loc=loc,
|
|
937
|
+
fontsize=self.fontsize,
|
|
938
|
+
labelspacing=0.25,
|
|
939
|
+
)
|
|
940
|
+
self.legend = leg
|
|
941
|
+
|
|
942
|
+
# Histogram plots:
|
|
943
|
+
if not self.plot_marginal:
|
|
944
|
+
return
|
|
945
|
+
for post in posts:
|
|
946
|
+
estimates = post.estimates
|
|
947
|
+
if not self.show_estimates:
|
|
948
|
+
estimates = [None for _ in estimates]
|
|
949
|
+
hpd_min = None
|
|
950
|
+
if '_like' in self.statistics:
|
|
951
|
+
hpd_min = self.source.hpd_min
|
|
952
|
+
|
|
953
|
+
_histogram(
|
|
954
|
+
post.posterior, estimates, self.ranges, self.hist_axes,
|
|
955
|
+
self.bins, post.pdf, post.xpdf,
|
|
956
|
+
hpd_min, post.low_bounds, post.high_bounds,
|
|
957
|
+
self.linewidth, post.theme, post.orientation, alpha=alpha,
|
|
958
|
+
clear=False,
|
|
959
|
+
)
|
|
960
|
+
if not self.show_texts:
|
|
961
|
+
return
|
|
962
|
+
text_cols = [post.theme.color for post in all_posts]
|
|
963
|
+
for text in self.stats_texts:
|
|
964
|
+
text.set_visible(False)
|
|
965
|
+
self.stats_texts = []
|
|
966
|
+
|
|
967
|
+
for j in range(self.npars):
|
|
968
|
+
stats_texts = [
|
|
969
|
+
rf'{self.pnames[j]} = {post.tex_estimates[j]}'
|
|
970
|
+
for post in all_posts
|
|
971
|
+
]
|
|
972
|
+
if j == self.npars-1:
|
|
973
|
+
stats_texts = [text[text.index('=')+2:] for text in stats_texts]
|
|
974
|
+
self.stats_texts += colors.rainbow_text(
|
|
975
|
+
self.hist_axes[j], stats_texts, self.fontsize, text_cols,
|
|
976
|
+
)
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
class ShareUpdate:
|
|
980
|
+
""" https://docs.python.org/3/howto/descriptor.html """
|
|
981
|
+
def __set_name__(self, obj, name):
|
|
982
|
+
self.private_name = '_' + name
|
|
983
|
+
|
|
984
|
+
def __get__(self, obj, objtype=None):
|
|
985
|
+
value = getattr(obj, self.private_name)
|
|
986
|
+
return value
|
|
987
|
+
|
|
988
|
+
def __set__(self, obj, value):
|
|
989
|
+
priv_name = self.private_name
|
|
990
|
+
var_name = self.private_name[1:]
|
|
991
|
+
if hasattr(obj, priv_name) and value is getattr(obj, priv_name):
|
|
992
|
+
return
|
|
993
|
+
setattr(obj, priv_name, value)
|
|
994
|
+
for i in reversed(range(len(obj.figures))):
|
|
995
|
+
fig = obj.figures[i]
|
|
996
|
+
if not is_open(fig.fig):
|
|
997
|
+
obj.figures.pop(i)
|
|
998
|
+
else:
|
|
999
|
+
setattr(fig, var_name, value)
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
class ShareTheme(ShareUpdate):
|
|
1003
|
+
def __set__(self, obj, value):
|
|
1004
|
+
priv_name = self.private_name
|
|
1005
|
+
var_name = self.private_name[1:]
|
|
1006
|
+
if isinstance(value, colors.Theme):
|
|
1007
|
+
pass
|
|
1008
|
+
elif isinstance(value, str) and value in colors.THEMES:
|
|
1009
|
+
value = colors.THEMES[value]
|
|
1010
|
+
elif is_color_like(value):
|
|
1011
|
+
value = colors.Theme(value)
|
|
1012
|
+
if hasattr(obj, priv_name) and value == getattr(obj, priv_name):
|
|
1013
|
+
return
|
|
1014
|
+
setattr(obj, priv_name, value)
|
|
1015
|
+
for i in reversed(range(len(obj.figures))):
|
|
1016
|
+
fig = obj.figures[i]
|
|
1017
|
+
if not is_open(fig.fig):
|
|
1018
|
+
obj.figures.pop(i)
|
|
1019
|
+
else:
|
|
1020
|
+
setattr(fig, var_name, value)
|
|
1021
|
+
|
|
1022
|
+
|
|
1023
|
+
class StatisticsUpdate(ShareUpdate):
|
|
1024
|
+
def __set__(self, obj, value):
|
|
1025
|
+
var_name = self.private_name[1:]
|
|
1026
|
+
priv_name = self.private_name
|
|
1027
|
+
if hasattr(obj, priv_name) and value is getattr(obj, priv_name):
|
|
1028
|
+
return
|
|
1029
|
+
setattr(obj, priv_name, value)
|
|
1030
|
+
for i in reversed(range(len(obj.figures))):
|
|
1031
|
+
fig = obj.figures[i]
|
|
1032
|
+
if not is_open(fig.fig):
|
|
1033
|
+
obj.figures.pop(i)
|
|
1034
|
+
else:
|
|
1035
|
+
setattr(fig, var_name, value)
|
|
1036
|
+
|
|
1037
|
+
has_all_attributes = (
|
|
1038
|
+
hasattr(obj, 'bestp') and
|
|
1039
|
+
hasattr(obj, 'statistics') and
|
|
1040
|
+
hasattr(obj, 'quantile')
|
|
1041
|
+
)
|
|
1042
|
+
if has_all_attributes:
|
|
1043
|
+
for i in range(obj.npars):
|
|
1044
|
+
_, _, obj.hpd_min[i] = ms.cred_region(
|
|
1045
|
+
obj.posterior[:,i],
|
|
1046
|
+
quantile=obj.quantile,
|
|
1047
|
+
)
|
|
1048
|
+
estimates, low_bounds, high_bounds = ms.marginal_statistics(
|
|
1049
|
+
obj.posterior, obj.statistics, obj.quantile,
|
|
1050
|
+
pdf=obj.pdf, xpdf=obj.xpdf,
|
|
1051
|
+
)
|
|
1052
|
+
if obj.statistics.startswith('global_'):
|
|
1053
|
+
obj.estimates = obj.bestp
|
|
1054
|
+
else:
|
|
1055
|
+
obj.estimates = estimates
|
|
1056
|
+
obj.low_bounds = low_bounds
|
|
1057
|
+
obj.high_bounds = high_bounds
|
|
1058
|
+
|
|
1059
|
+
obj.tex_estimates = u.tex_parameters(
|
|
1060
|
+
obj.estimates,
|
|
1061
|
+
obj.low_bounds,
|
|
1062
|
+
obj.high_bounds,
|
|
1063
|
+
significant_digits=2,
|
|
1064
|
+
)
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
class Posterior():
|
|
1068
|
+
"""
|
|
1069
|
+
Classification of posterior plotting tools.
|
|
1070
|
+
|
|
1071
|
+
statistics: String
|
|
1072
|
+
Statistics to use for parameter estimates and uncertainties:
|
|
1073
|
+
global_* use global best-fit (bestp) estimate.
|
|
1074
|
+
max_*: Marginal maximum-likelihood (mode) estimate.
|
|
1075
|
+
med_*: Marginal median estimate.
|
|
1076
|
+
*_like: HPD credible interval.
|
|
1077
|
+
*_central: Central quantile interval.
|
|
1078
|
+
|
|
1079
|
+
Examples
|
|
1080
|
+
--------
|
|
1081
|
+
>>> import mc3
|
|
1082
|
+
|
|
1083
|
+
>>> mcmc = np.load('MCMC_HD209458b_sing_0.29-2.0um_MM2017.npz')
|
|
1084
|
+
>>> posterior, zchain, zmask = mc3.utils.burn(mcmc)
|
|
1085
|
+
>>> pnames = mcmc['texnames']
|
|
1086
|
+
>>> bestp = mcmc['bestp']
|
|
1087
|
+
|
|
1088
|
+
>>> p = mc3.plots.Posterior(posterior, pnames, bestp)
|
|
1089
|
+
>>> f1 = p.plot(savefile=f'pairwise_{6:02d}pars.png')
|
|
1090
|
+
>>> f2 = p.plot_histogram(savefile=f'histogram_{6:02d}pars.png')
|
|
1091
|
+
"""
|
|
1092
|
+
# Soft-update properties:
|
|
1093
|
+
pnames = ShareUpdate()
|
|
1094
|
+
ranges = ShareUpdate()
|
|
1095
|
+
theme = ShareTheme()
|
|
1096
|
+
|
|
1097
|
+
bestp = StatisticsUpdate()
|
|
1098
|
+
statistics = StatisticsUpdate()
|
|
1099
|
+
quantile = StatisticsUpdate()
|
|
1100
|
+
|
|
1101
|
+
show_texts = ShareUpdate()
|
|
1102
|
+
show_estimates = ShareUpdate()
|
|
1103
|
+
show_colorbar = ShareUpdate()
|
|
1104
|
+
|
|
1105
|
+
def __init__(
|
|
1106
|
+
self, posterior, pnames=None, bestp=None, ranges=None,
|
|
1107
|
+
statistics='med_central', quantile=0.683,
|
|
1108
|
+
sample_size=20000,
|
|
1109
|
+
theme='blue', orientation='vertical',
|
|
1110
|
+
show_texts=True, show_estimates=True,
|
|
1111
|
+
show_colorbar=True,
|
|
1112
|
+
seed=314159,
|
|
1113
|
+
mask=None,
|
|
1114
|
+
):
|
|
1115
|
+
self.figures = []
|
|
1116
|
+
nsamples, self.npars = np.shape(posterior)
|
|
1117
|
+
rng = np.random.default_rng(seed)
|
|
1118
|
+
if sample_size < nsamples:
|
|
1119
|
+
sample = rng.choice(nsamples, sample_size, replace=False)
|
|
1120
|
+
sampled_posterior = posterior[sample]
|
|
1121
|
+
else:
|
|
1122
|
+
sampled_posterior = np.copy(posterior)
|
|
1123
|
+
# TBD: enforce posterior as 2D
|
|
1124
|
+
self.posterior = sampled_posterior
|
|
1125
|
+
|
|
1126
|
+
# Defaults:
|
|
1127
|
+
if pnames is None:
|
|
1128
|
+
pnames = [f'p{i:02d}' for i in range(self.npars)]
|
|
1129
|
+
|
|
1130
|
+
self.pnames = pnames
|
|
1131
|
+
self.ranges = ranges
|
|
1132
|
+
self.theme = theme
|
|
1133
|
+
self.orientation = orientation
|
|
1134
|
+
self.show_texts = show_texts
|
|
1135
|
+
self.show_estimates = show_estimates
|
|
1136
|
+
self.show_colorbar = show_colorbar
|
|
1137
|
+
|
|
1138
|
+
self.pdf = [None for _ in range(self.npars)]
|
|
1139
|
+
self.xpdf = [None for _ in range(self.npars)]
|
|
1140
|
+
self.hpd_min = [None for _ in range(self.npars)]
|
|
1141
|
+
for i in range(self.npars):
|
|
1142
|
+
pdf, xpdf, hpd = ms.cred_region(
|
|
1143
|
+
self.posterior[:,i], quantile=quantile,
|
|
1144
|
+
)
|
|
1145
|
+
self.pdf[i] = pdf
|
|
1146
|
+
self.xpdf[i] = xpdf
|
|
1147
|
+
|
|
1148
|
+
# These will trigger the param estimate calcs in StatisticsUpdate():
|
|
1149
|
+
if bestp is None:
|
|
1150
|
+
self.bestp = [None for _ in range(self.npars)]
|
|
1151
|
+
else:
|
|
1152
|
+
self.bestp = bestp
|
|
1153
|
+
self.statistics = statistics
|
|
1154
|
+
self.quantile = quantile
|
|
1155
|
+
if mask is None:
|
|
1156
|
+
mask = np.ones(self.npars, bool)
|
|
1157
|
+
self.mask = mask
|
|
1158
|
+
|
|
1159
|
+
def plot(
|
|
1160
|
+
self, plot_marginal=True,
|
|
1161
|
+
fignum=None, figure=None,
|
|
1162
|
+
quantile=None,
|
|
1163
|
+
linewidth=None, fontsize=None,
|
|
1164
|
+
figsize=None, rect=None,
|
|
1165
|
+
margin=None, ymargin=None,
|
|
1166
|
+
show_texts=None, show_estimates=None,
|
|
1167
|
+
show_colorbar=None,
|
|
1168
|
+
savefile=None,
|
|
1169
|
+
nlevels=None,
|
|
1170
|
+
):
|
|
1171
|
+
"""
|
|
1172
|
+
Plot marginal histograms and pairwise posteriors.
|
|
1173
|
+
"""
|
|
1174
|
+
# Defaults:
|
|
1175
|
+
if quantile is None:
|
|
1176
|
+
quantile = self.quantile
|
|
1177
|
+
if show_estimates is None:
|
|
1178
|
+
show_estimates = self.show_estimates
|
|
1179
|
+
if show_texts is None:
|
|
1180
|
+
show_texts = self.show_texts
|
|
1181
|
+
if show_colorbar is None:
|
|
1182
|
+
show_colorbar = self.show_colorbar
|
|
1183
|
+
if nlevels is None:
|
|
1184
|
+
nlevels = 6
|
|
1185
|
+
|
|
1186
|
+
fig = Figure(
|
|
1187
|
+
self,
|
|
1188
|
+
self.posterior, self.pnames, self.bestp,
|
|
1189
|
+
self.ranges, self.theme,
|
|
1190
|
+
rect=rect,
|
|
1191
|
+
margin=margin,
|
|
1192
|
+
ymargin=ymargin,
|
|
1193
|
+
statistics=self.statistics,
|
|
1194
|
+
quantile=quantile,
|
|
1195
|
+
plot_marginal=plot_marginal,
|
|
1196
|
+
linewidth=linewidth,
|
|
1197
|
+
fontsize=fontsize,
|
|
1198
|
+
figsize=figsize,
|
|
1199
|
+
fignum=fignum,
|
|
1200
|
+
show_texts=show_texts,
|
|
1201
|
+
show_estimates=show_estimates,
|
|
1202
|
+
show_colorbar=show_colorbar,
|
|
1203
|
+
# bins=25,
|
|
1204
|
+
nlevels=nlevels,
|
|
1205
|
+
)
|
|
1206
|
+
self.figures.append(fig)
|
|
1207
|
+
fig.plot(figure=figure, savefile=savefile)
|
|
1208
|
+
return fig
|
|
1209
|
+
|
|
1210
|
+
|
|
1211
|
+
def plot_histogram(
|
|
1212
|
+
self, fignum=None, axes=None, quantile=None,
|
|
1213
|
+
nx=None, ny=None,
|
|
1214
|
+
savefile=None,
|
|
1215
|
+
fontsize=11, linewidth=1.5,
|
|
1216
|
+
show_texts=None, show_estimates=None,
|
|
1217
|
+
alpha=0.6,
|
|
1218
|
+
):
|
|
1219
|
+
"""
|
|
1220
|
+
Plot histogram of marginal posteriors.
|
|
1221
|
+
"""
|
|
1222
|
+
if show_estimates is None:
|
|
1223
|
+
show_estimates = self.show_estimates
|
|
1224
|
+
if show_texts is None:
|
|
1225
|
+
show_texts = self.show_texts
|
|
1226
|
+
if quantile is None:
|
|
1227
|
+
quantile = self.quantile
|
|
1228
|
+
|
|
1229
|
+
fig = Marginal(
|
|
1230
|
+
self,
|
|
1231
|
+
self.posterior, self.pnames, self.bestp,
|
|
1232
|
+
self.ranges, self.theme,
|
|
1233
|
+
statistics=self.statistics,
|
|
1234
|
+
nx=nx, ny=ny,
|
|
1235
|
+
quantile=quantile,
|
|
1236
|
+
fontsize=fontsize,
|
|
1237
|
+
linewidth=linewidth,
|
|
1238
|
+
show_texts=show_texts,
|
|
1239
|
+
show_estimates=show_estimates,
|
|
1240
|
+
alpha=alpha,
|
|
1241
|
+
)
|
|
1242
|
+
self.figures.append(fig)
|
|
1243
|
+
fig.plot(savefile=savefile, fignum=fignum, axes=axes)
|
|
1244
|
+
return fig
|
|
1245
|
+
|
|
1246
|
+
|
|
1247
|
+
def add():
|
|
1248
|
+
"""TBD: Do not call this method."""
|
|
1249
|
+
pass
|
|
1250
|
+
|
|
1251
|
+
def update(self, **kwargs):
|
|
1252
|
+
for key, value in kwargs.items():
|
|
1253
|
+
# If key in valid keys:
|
|
1254
|
+
print(f'{key} = {value}')
|
|
1255
|
+
# Else: throw warning
|
|
1256
|
+
replot = False
|
|
1257
|
+
# if hard-replotting, update parameter in kwargs.keys():
|
|
1258
|
+
# 'bestp' in kwargs.keys():
|
|
1259
|
+
# 'ranges' in kwargs.keys():
|
|
1260
|
+
# 'linewidth' in kwargs.keys():
|
|
1261
|
+
# 'theme' in kwargs.keys()
|
|
1262
|
+
# 'quantile'
|
|
1263
|
+
# 'bins'
|
|
1264
|
+
# 'nlevels'
|
|
1265
|
+
replot = True
|
|
1266
|
+
|
|
1267
|
+
if len(kwargs) == 0:
|
|
1268
|
+
replot = True
|
|
1269
|
+
|
|
1270
|
+
for key, value in kwargs.items():
|
|
1271
|
+
setattr(self, key, value)
|
|
1272
|
+
|
|
1273
|
+
#if replot:
|
|
1274
|
+
for fig in self.figures:
|
|
1275
|
+
fig.update()
|
|
1276
|
+
|
|
1277
|
+
def plot_trace():
|
|
1278
|
+
pass
|