0
# Plotting and Visualization
1
2
Built-in plotting capabilities for posterior analysis, convergence diagnostics, and model comparison. UltraNest provides comprehensive visualization tools to interpret nested sampling results and assess sampling quality.
3
4
## Capabilities
5
6
### Posterior Visualization
7
8
Create publication-quality plots of posterior distributions and parameter correlations.
9
10
```python { .api }
11
def cornerplot(results, **kwargs):
12
"""
13
Create corner plot showing posterior distributions and correlations.
14
15
Parameters:
16
- results (dict): Results from nested sampling run
17
- **kwargs: Additional plotting options including:
18
- parameters (list): Subset of parameters to plot
19
- labels (list): Custom parameter labels
20
- show_titles (bool): Display parameter statistics as titles
21
- title_quantiles (list): Quantiles for title statistics
22
- color (str): Color scheme for plots
23
- bins (int): Number of histogram bins
24
- smooth (bool): Apply smoothing to contours
25
- contour_levels (list): Contour levels to display
26
- range (list): Plot ranges for each parameter
27
- figsize (tuple): Figure size
28
- dpi (int): Resolution for saved plots
29
30
Returns:
31
matplotlib figure: Corner plot figure
32
"""
33
```
34
35
#### Corner Plot Usage
36
37
```python
38
import matplotlib.pyplot as plt
39
from ultranest.plot import cornerplot
40
41
# Create corner plot from results
42
fig = cornerplot(
43
results,
44
labels=['Amplitude', 'Mean', 'Sigma'],
45
show_titles=True,
46
title_quantiles=[0.16, 0.5, 0.84],
47
smooth=True,
48
bins=30
49
)
50
51
plt.savefig('posterior_corner.png', dpi=300, bbox_inches='tight')
52
plt.show()
53
```
54
55
### Convergence Diagnostics
56
57
Monitor sampling convergence and quality through diagnostic plots.
58
59
```python { .api }
60
def runplot(results, **kwargs):
61
"""
62
Create run diagnostic plots showing sampling progress and convergence.
63
64
Parameters:
65
- results (dict): Results from nested sampling run
66
- **kwargs: Plotting options including:
67
- figsize (tuple): Figure size
68
- dpi (int): Plot resolution
69
- show_information (bool): Display information content evolution
70
- show_evidence (bool): Display evidence estimation
71
- show_weights (bool): Display point weights
72
73
Returns:
74
matplotlib figure: Run diagnostic plots
75
"""
76
```
77
78
#### Run Diagnostics Usage
79
80
```python
81
from ultranest.plot import runplot
82
83
# Create convergence diagnostic plots
84
fig = runplot(
85
results,
86
figsize=(12, 8),
87
show_information=True,
88
show_evidence=True
89
)
90
91
plt.savefig('convergence_diagnostics.png', dpi=300, bbox_inches='tight')
92
plt.show()
93
```
94
95
### Parameter Evolution
96
97
Track parameter evolution throughout the sampling process.
98
99
```python { .api }
100
def traceplot(results, **kwargs):
101
"""
102
Create trace plots showing parameter evolution during sampling.
103
104
Parameters:
105
- results (dict): Results from nested sampling run
106
- **kwargs: Plotting options including:
107
- parameters (list): Parameters to include in trace plot
108
- labels (list): Custom parameter labels
109
- figsize (tuple): Figure size
110
- thin (int): Thinning factor for trace lines
111
- alpha (float): Transparency for trace lines
112
113
Returns:
114
matplotlib figure: Trace plot figure
115
"""
116
```
117
118
#### Trace Plot Usage
119
120
```python
121
from ultranest.plot import traceplot
122
123
# Create parameter trace plots
124
fig = traceplot(
125
results,
126
parameters=['amplitude', 'mean', 'sigma'],
127
labels=['Amplitude', 'Mean', 'Sigma'],
128
figsize=(10, 6),
129
thin=10,
130
alpha=0.7
131
)
132
133
plt.savefig('parameter_traces.png', dpi=300, bbox_inches='tight')
134
plt.show()
135
```
136
137
### Statistical Analysis
138
139
Compute and visualize statistical measures from posterior samples.
140
141
```python { .api }
142
def highest_density_interval_from_samples(
143
xsamples,
144
xlo=None,
145
xhi=None,
146
probability_level=0.68
147
):
148
"""
149
Compute highest density interval from samples.
150
151
Parameters:
152
- xsamples (array): Posterior samples
153
- xlo (float, optional): Lower bound for samples
154
- xhi (float, optional): Upper bound for samples
155
- probability_level (float): Credible interval level (default: 0.68)
156
157
Returns:
158
tuple: (lower_bound, upper_bound) of highest density interval
159
"""
160
```
161
162
### Prediction Bands
163
164
Create prediction bands for model validation and forecasting.
165
166
```python { .api }
167
class PredictionBand:
168
"""
169
Class for creating prediction bands from posterior samples.
170
171
Provides methods for computing credible intervals and prediction
172
bands from posterior predictive distributions.
173
"""
174
175
def __init__(self, x, y_samples):
176
"""
177
Initialize prediction band computation.
178
179
Parameters:
180
- x (array): Independent variable values
181
- y_samples (array): Posterior predictive samples, shape (n_samples, n_points)
182
"""
183
184
def compute_bands(self, alpha_levels=[0.68, 0.95]):
185
"""
186
Compute prediction bands at specified confidence levels.
187
188
Parameters:
189
- alpha_levels (list): Confidence levels for bands
190
191
Returns:
192
dict: Band boundaries for each confidence level
193
"""
194
```
195
196
## Comprehensive Visualization Workflow
197
198
### Complete Analysis Pipeline
199
200
```python
201
import matplotlib.pyplot as plt
202
from ultranest import ReactiveNestedSampler
203
from ultranest.plot import cornerplot, runplot, traceplot
204
205
# Run nested sampling
206
sampler = ReactiveNestedSampler(
207
param_names=['amplitude', 'mean', 'sigma'],
208
loglike=loglike,
209
transform=prior_transform
210
)
211
212
results = sampler.run()
213
214
# Create comprehensive visualization suite
215
plt.style.use('seaborn-v0_8') # Set plotting style
216
217
# 1. Corner plot for posterior analysis
218
fig1 = cornerplot(
219
results,
220
labels=['A', r'$\mu$', r'$\sigma$'],
221
show_titles=True,
222
title_quantiles=[0.16, 0.5, 0.84],
223
smooth=True,
224
bins=30,
225
figsize=(10, 10)
226
)
227
fig1.savefig('posterior_corner.png', dpi=300, bbox_inches='tight')
228
229
# 2. Run diagnostics for convergence assessment
230
fig2 = runplot(
231
results,
232
figsize=(12, 8),
233
show_information=True,
234
show_evidence=True
235
)
236
fig2.savefig('run_diagnostics.png', dpi=300, bbox_inches='tight')
237
238
# 3. Parameter traces for sampling quality
239
fig3 = traceplot(
240
results,
241
labels=['Amplitude', 'Mean', 'Sigma'],
242
figsize=(12, 8),
243
thin=5
244
)
245
fig3.savefig('parameter_traces.png', dpi=300, bbox_inches='tight')
246
247
plt.show()
248
```
249
250
### Custom Visualization
251
252
```python
253
import numpy as np
254
import matplotlib.pyplot as plt
255
from ultranest.plot import highest_density_interval_from_samples
256
257
# Extract posterior samples
258
samples = results['samples']
259
weights = results['weights']
260
261
# Weighted resampling for equal-weight samples
262
from ultranest.utils import resample_equal
263
equal_weight_samples = resample_equal(samples, weights)
264
265
# Custom analysis
266
for i, param_name in enumerate(['amplitude', 'mean', 'sigma']):
267
param_samples = equal_weight_samples[:, i]
268
269
# Compute statistics
270
median = np.median(param_samples)
271
hdi_lower, hdi_upper = highest_density_interval_from_samples(
272
param_samples, probability_level=0.68
273
)
274
275
print(f"{param_name}: {median:.3f} [{hdi_lower:.3f}, {hdi_upper:.3f}]")
276
277
# Custom histogram
278
plt.figure(figsize=(8, 5))
279
plt.hist(param_samples, bins=50, alpha=0.7, density=True)
280
plt.axvline(median, color='red', linestyle='--', label='Median')
281
plt.axvline(hdi_lower, color='orange', linestyle=':', label='68% HDI')
282
plt.axvline(hdi_upper, color='orange', linestyle=':')
283
plt.xlabel(param_name)
284
plt.ylabel('Posterior Density')
285
plt.legend()
286
plt.title(f'Posterior Distribution: {param_name}')
287
plt.savefig(f'{param_name}_posterior.png', dpi=300, bbox_inches='tight')
288
plt.show()
289
```
290
291
### Model Comparison Visualization
292
293
```python
294
# Compare multiple models
295
models = ['model_A', 'model_B', 'model_C']
296
evidences = [results_A['logz'], results_B['logz'], results_C['logz']]
297
evidence_errors = [results_A['logzerr'], results_B['logzerr'], results_C['logzerr']]
298
299
# Evidence comparison plot
300
plt.figure(figsize=(10, 6))
301
plt.errorbar(models, evidences, yerr=evidence_errors,
302
fmt='o', capsize=5, capthick=2, markersize=8)
303
plt.ylabel('Log Evidence')
304
plt.title('Model Comparison via Bayesian Evidence')
305
plt.grid(True, alpha=0.3)
306
307
# Add Bayes factors
308
best_evidence = max(evidences)
309
for i, (model, evidence) in enumerate(zip(models, evidences)):
310
bayes_factor = np.exp(evidence - best_evidence)
311
plt.text(i, evidence + 0.5, f'BF: {bayes_factor:.2f}',
312
ha='center', fontsize=10)
313
314
plt.tight_layout()
315
plt.savefig('model_comparison.png', dpi=300, bbox_inches='tight')
316
plt.show()
317
```
318
319
## Plotting Guidelines
320
321
### Publication Quality
322
323
- Use high DPI (300+) for publication figures
324
- Choose appropriate figure sizes for journal requirements
325
- Apply consistent color schemes across related plots
326
- Include error bars and uncertainty estimates
327
- Label axes clearly with units where applicable
328
329
### Diagnostic Interpretation
330
331
- **Corner plots**: Check for parameter correlations and multimodality
332
- **Run plots**: Verify evidence convergence and information gain
333
- **Trace plots**: Assess mixing and identify convergence issues
334
- **Residual plots**: Validate model assumptions and goodness of fit
335
336
### Customization Options
337
338
All plotting functions accept matplotlib-compatible styling options:
339
- Colors, line styles, markers
340
- Font sizes and families
341
- Figure sizes and aspect ratios
342
- Axis limits and tick marks
343
- Legends and annotations
344
345
The plotting system integrates seamlessly with matplotlib for full customization while providing sensible defaults for rapid analysis.