RATapi 0.0.0.dev10__cp313-cp313-win_amd64.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.
Files changed (59) hide show
  1. ratapi/__init__.py +29 -0
  2. ratapi/classlist.py +620 -0
  3. ratapi/controls.py +258 -0
  4. ratapi/eventManager.dll +0 -0
  5. ratapi/events.py +88 -0
  6. ratapi/examples/__init__.py +25 -0
  7. ratapi/examples/absorption/__init__.py +1 -0
  8. ratapi/examples/absorption/absorption.py +172 -0
  9. ratapi/examples/absorption/volume_thiol_bilayer.py +141 -0
  10. ratapi/examples/convert_rascal_project/Model_IIb.py +87 -0
  11. ratapi/examples/convert_rascal_project/__init__.py +1 -0
  12. ratapi/examples/convert_rascal_project/convert_rascal.py +49 -0
  13. ratapi/examples/data/D2O_spin_down.dat +100 -0
  14. ratapi/examples/data/D2O_spin_up.dat +101 -0
  15. ratapi/examples/data/DSPC_D2O.dat +82 -0
  16. ratapi/examples/data/DSPC_SMW.dat +82 -0
  17. ratapi/examples/data/H2O_spin_down.dat +102 -0
  18. ratapi/examples/data/H2O_spin_up.dat +102 -0
  19. ratapi/examples/data/__init__.py +1 -0
  20. ratapi/examples/data/c_PLP0016596.dat +146 -0
  21. ratapi/examples/data/c_PLP0016601.dat +97 -0
  22. ratapi/examples/data/c_PLP0016607.dat +104 -0
  23. ratapi/examples/data/d2o_background_data.dat +82 -0
  24. ratapi/examples/domains/__init__.py +1 -0
  25. ratapi/examples/domains/alloy_domains.py +31 -0
  26. ratapi/examples/domains/domains_XY_model.py +72 -0
  27. ratapi/examples/domains/domains_custom_XY.py +86 -0
  28. ratapi/examples/domains/domains_custom_layers.py +60 -0
  29. ratapi/examples/domains/domains_standard_layers.py +92 -0
  30. ratapi/examples/languages/__init__.py +1 -0
  31. ratapi/examples/languages/custom_bilayer.py +69 -0
  32. ratapi/examples/languages/run_custom_file_languages.py +41 -0
  33. ratapi/examples/languages/setup_problem.py +130 -0
  34. ratapi/examples/normal_reflectivity/DSPC_custom_XY.py +149 -0
  35. ratapi/examples/normal_reflectivity/DSPC_custom_layers.py +130 -0
  36. ratapi/examples/normal_reflectivity/DSPC_data_background.py +220 -0
  37. ratapi/examples/normal_reflectivity/DSPC_function_background.py +219 -0
  38. ratapi/examples/normal_reflectivity/DSPC_standard_layers.py +210 -0
  39. ratapi/examples/normal_reflectivity/__init__.py +1 -0
  40. ratapi/examples/normal_reflectivity/background_function.py +16 -0
  41. ratapi/examples/normal_reflectivity/custom_XY_DSPC.py +138 -0
  42. ratapi/examples/normal_reflectivity/custom_bilayer_DSPC.py +87 -0
  43. ratapi/inputs.py +588 -0
  44. ratapi/models.py +677 -0
  45. ratapi/outputs.py +821 -0
  46. ratapi/project.py +1074 -0
  47. ratapi/rat_core.cp313-win_amd64.pyd +0 -0
  48. ratapi/run.py +140 -0
  49. ratapi/utils/__init__.py +1 -0
  50. ratapi/utils/convert.py +564 -0
  51. ratapi/utils/custom_errors.py +40 -0
  52. ratapi/utils/enums.py +204 -0
  53. ratapi/utils/orso.py +247 -0
  54. ratapi/utils/plotting.py +1231 -0
  55. ratapi/wrappers.py +144 -0
  56. ratapi-0.0.0.dev10.dist-info/METADATA +61 -0
  57. ratapi-0.0.0.dev10.dist-info/RECORD +59 -0
  58. ratapi-0.0.0.dev10.dist-info/WHEEL +5 -0
  59. ratapi-0.0.0.dev10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1231 @@
1
+ """Plot results using the matplotlib library."""
2
+
3
+ import copy
4
+ import types
5
+ from collections.abc import Callable
6
+ from functools import partial, wraps
7
+ from math import ceil, floor, sqrt
8
+ from statistics import stdev
9
+ from typing import Literal
10
+
11
+ import matplotlib
12
+ import matplotlib.figure
13
+ import matplotlib.pyplot as plt
14
+ import matplotlib.transforms as mtransforms
15
+ import numpy as np
16
+ from matplotlib.axes._axes import Axes
17
+ from scipy.ndimage import gaussian_filter1d
18
+ from scipy.stats import gaussian_kde, lognorm, norm
19
+
20
+ import ratapi
21
+ import ratapi.inputs
22
+ import ratapi.outputs
23
+ from ratapi.rat_core import PlotEventData, makeSLDProfile
24
+
25
+
26
+ def _extract_plot_data(event_data: PlotEventData, q4: bool, show_error_bar: bool, shift_value: float):
27
+ """Extract the plot data for the sld, ref, error plot lines.
28
+
29
+ Parameters
30
+ ----------
31
+ event_data : PlotEventData
32
+ The plot event data that contains all the information
33
+ to generate the ref and sld plots
34
+ q4 : bool, default: False
35
+ Controls whether Q^4 is plotted on the reflectivity plot
36
+ show_error_bar : bool, default: True
37
+ Controls whether the error bars are shown
38
+ shift_value : float
39
+ A value between 1 and 100 that controls the spacing between the reflectivity plots for each of the contrasts
40
+
41
+ Returns
42
+ -------
43
+ plot_values : dict
44
+ A dict containing the data for the sld, ref, error plot lines.
45
+
46
+ """
47
+ results = {"ref": [], "error": [], "sld": [], "sld_resample": []}
48
+
49
+ if shift_value < 1 or shift_value > 100:
50
+ raise ValueError("Parameter `shift_value` must be between 1 and 100")
51
+
52
+ for i, (r, data, sld) in enumerate(
53
+ zip(event_data.reflectivity, event_data.shiftedData, event_data.sldProfiles, strict=False)
54
+ ):
55
+ # Calculate the divisor
56
+ div = 1 if i == 0 and not q4 else 10 ** ((i / 100) * shift_value)
57
+ q4_data = 1 if not q4 or not event_data.dataPresent[i] else data[:, 0] ** 4
58
+ mult = q4_data / div
59
+
60
+ # Plot the reflectivity on plot (1,1)
61
+ results["ref"].append([r[:, 0], r[:, 1] * mult])
62
+
63
+ if event_data.dataPresent[i]:
64
+ sd_x = data[:, 0]
65
+ sd_y, sd_e = map(lambda x: x * mult, (data[:, 1], data[:, 2]))
66
+
67
+ if show_error_bar:
68
+ errors = np.zeros(len(sd_e))
69
+ valid = sd_y - sd_e >= 0
70
+ errors[valid] = sd_e[valid]
71
+ valid |= sd_y < 0
72
+
73
+ results["error"].append([sd_x[valid], sd_y[valid], sd_e[valid]])
74
+
75
+ results["sld"].append([])
76
+ for j in range(len(sld)):
77
+ results["sld"][-1].append([sld[j][:, 0], sld[j][:, 1]])
78
+
79
+ results["sld_resample"].append([])
80
+ if event_data.resample[i] == 1 or event_data.modelType == "custom xy":
81
+ layers = event_data.resampledLayers[i][0]
82
+ for j in range(len(event_data.resampledLayers[i])):
83
+ layer = event_data.resampledLayers[i][j]
84
+ if layers.shape[1] == 4:
85
+ layer = np.delete(layer, 2, 1)
86
+ new_profile = makeSLDProfile(
87
+ layers[0, 1], # Bulk In
88
+ layers[-1, 1], # Bulk Out
89
+ layer,
90
+ event_data.subRoughs[i], # roughness
91
+ 1,
92
+ )
93
+
94
+ results["sld_resample"][-1].append([new_profile[:, 0] - 49, new_profile[:, 1]])
95
+
96
+ return results
97
+
98
+
99
+ def plot_ref_sld_helper(
100
+ data: PlotEventData,
101
+ fig: matplotlib.figure.Figure,
102
+ delay: bool = True,
103
+ confidence_intervals: dict | None = None,
104
+ linear_x: bool = False,
105
+ q4: bool = False,
106
+ show_error_bar: bool = True,
107
+ show_grid: bool = False,
108
+ show_legend: bool = True,
109
+ shift_value: float = 100,
110
+ animated=False,
111
+ ):
112
+ """Clear the previous plots and updates the ref and SLD plots.
113
+
114
+ Parameters
115
+ ----------
116
+ data : PlotEventData
117
+ The plot event data that contains all the information
118
+ to generate the ref and sld plots
119
+ fig : matplotlib.figure.Figure
120
+ The figure object that has two subplots
121
+ delay : bool, default: True
122
+ Controls whether to delay 0.005s after plot is created
123
+ confidence_intervals : dict or None, default None
124
+ The Bayesian confidence intervals for reflectivity and SLD.
125
+ Only relevant if the procedure used is Bayesian (NS or DREAM)
126
+ linear_x : bool, default: False
127
+ Controls whether the x-axis on reflectivity plot uses the linear scale
128
+ q4 : bool, default: False
129
+ Controls whether Q^4 is plotted on the reflectivity plot
130
+ show_error_bar : bool, default: True
131
+ Controls whether the error bars are shown
132
+ show_grid : bool, default: False
133
+ Controls whether the grid is shown
134
+ show_legend : bool, default: True
135
+ Controls whether the legend is shown
136
+ shift_value : float, default: 100
137
+ A value between 1 and 100 that controls the spacing between the reflectivity plots for each of the contrasts
138
+ animated : bool, default: False
139
+ Controls whether the animated property of foreground plot elements should be set.
140
+
141
+ """
142
+ preserve_zoom = False
143
+
144
+ if len(fig.axes) != 2:
145
+ fig.clf()
146
+ fig.subplots(1, 2)
147
+
148
+ fig.subplots_adjust(wspace=0.3)
149
+
150
+ ref_plot: plt.Axes = fig.axes[0]
151
+ sld_plot: plt.Axes = fig.axes[1]
152
+ if ref_plot.lines and fig.canvas.toolbar is not None:
153
+ preserve_zoom = True
154
+ fig.canvas.toolbar.push_current()
155
+
156
+ # Clears the previous plots
157
+ ref_plot.cla()
158
+ sld_plot.cla()
159
+
160
+ plot_data = _extract_plot_data(data, q4, show_error_bar, shift_value)
161
+ for i, name in enumerate(data.contrastNames):
162
+ ref_plot.plot(plot_data["ref"][i][0], plot_data["ref"][i][1], label=name, linewidth=1, animated=animated)
163
+ color = ref_plot.get_lines()[-1].get_color()
164
+
165
+ # Plot confidence intervals if required
166
+ if confidence_intervals is not None:
167
+ # Calculate the divisor
168
+ div = 1 if i == 0 and not q4 else 10 ** ((i / 100) * shift_value)
169
+ ref_min, ref_max = confidence_intervals["reflectivity"][i]
170
+ mult = (1 if not q4 else plot_data["ref"][i][0] ** 4) / div
171
+ ref_plot.fill_between(plot_data["ref"][i][0], ref_min * mult, ref_max * mult, alpha=0.6, color="grey")
172
+
173
+ if data.dataPresent[i] and show_error_bar:
174
+ # Plot the errorbars
175
+ ref_plot.errorbar(
176
+ x=plot_data["error"][i][0],
177
+ y=plot_data["error"][i][1],
178
+ yerr=plot_data["error"][i][2],
179
+ elinewidth=1,
180
+ ecolor=color,
181
+ marker=".",
182
+ markersize=3,
183
+ linestyle="none",
184
+ color=color,
185
+ capsize=0,
186
+ animated=animated,
187
+ )
188
+
189
+ # Plot the slds on plot (1,2)
190
+ for j in range(len(plot_data["sld"][i])):
191
+ label = name if len(plot_data["sld"][i]) == 1 else f"{name} Domain {j + 1}"
192
+ sld_plot.plot(
193
+ plot_data["sld"][i][j][0], plot_data["sld"][i][j][1], label=label, linewidth=1, animated=animated
194
+ )
195
+
196
+ # Plot confidence intervals if required
197
+ if confidence_intervals is not None:
198
+ sld_min, sld_max = confidence_intervals["sld"][i][j]
199
+ sld_plot.fill_between(plot_data["sld"][i][j][0], sld_min, sld_max, alpha=0.6, color="grey")
200
+
201
+ for j in range(len(plot_data["sld_resample"][i])):
202
+ sld_plot.plot(
203
+ plot_data["sld_resample"][i][j][0],
204
+ plot_data["sld_resample"][i][j][1],
205
+ color=color,
206
+ linewidth=1,
207
+ animated=animated,
208
+ )
209
+
210
+ # Format the axis
211
+ ref_plot.set_yscale("log")
212
+ if not linear_x:
213
+ ref_plot.set_xscale("log")
214
+ ref_plot.set_xlabel("$Q_{z} (\u00c5^{-1})$")
215
+ ref_plot.set_ylabel("Reflectivity")
216
+
217
+ sld_plot.set_xlabel("$Z (\u00c5)$")
218
+ sld_plot.set_ylabel("$SLD (\u00c5^{-2})$", labelpad=1)
219
+
220
+ if show_legend:
221
+ ref_plot.legend()
222
+ sld_plot.legend()
223
+
224
+ if show_grid:
225
+ ref_plot.grid()
226
+ sld_plot.grid()
227
+
228
+ if preserve_zoom:
229
+ fig.canvas.toolbar.back()
230
+ if delay:
231
+ plt.pause(0.005)
232
+
233
+
234
+ def plot_ref_sld(
235
+ project: ratapi.Project,
236
+ results: ratapi.outputs.Results | ratapi.outputs.BayesResults,
237
+ block: bool = False,
238
+ fig: matplotlib.figure.Figure | None = None,
239
+ return_fig: bool = False,
240
+ bayes: Literal[65, 95, None] = None,
241
+ linear_x: bool = False,
242
+ q4: bool = False,
243
+ show_error_bar: bool = True,
244
+ show_grid: bool = False,
245
+ show_legend: bool = True,
246
+ shift_value: float = 100,
247
+ ) -> plt.Figure | None:
248
+ """Plot the reflectivity and SLD profiles.
249
+
250
+ Parameters
251
+ ----------
252
+ project : Project
253
+ An instance of the Project class
254
+ results : Union[Results, BayesResults]
255
+ The result from the calculation
256
+ block : bool, default: False
257
+ Indicates the plot should block until it is closed
258
+ fig : matplotlib.figure.Figure, optional
259
+ The figure object that has two subplots
260
+ return_fig : bool, default False
261
+ If True, return the figure instead of displaying it.
262
+ bayes : 65, 95 or None, default None
263
+ Whether to shade Bayesian confidence intervals. Can be `None`
264
+ (if no intervals), `65` to show 65% confidence intervals,
265
+ and `95` to show 95% confidence intervals.
266
+ linear_x : bool, default: False
267
+ Controls whether the x-axis on reflectivity plot uses the linear scale
268
+ q4 : bool, default: False
269
+ Controls whether Q^4 is plotted on the reflectivity plot
270
+ show_error_bar : bool, default: True
271
+ Controls whether the error bars are shown
272
+ show_grid : bool, default: False
273
+ Controls whether the grid is shown
274
+ show_legend : bool, default: True
275
+ Controls whether the legend is shown
276
+ shift_value : float, default: 100
277
+ A value between 1 and 100 that controls the spacing between the reflectivity plots for each of the contrasts
278
+
279
+ Returns
280
+ -------
281
+ Figure or None
282
+ Returns Figure if `return_fig` is True, else returns nothing.
283
+
284
+ """
285
+ data = PlotEventData()
286
+
287
+ # We need to take a copy of reflectivity and SLD in case we are plotting a
288
+ # shaded plot and will therefore change the plotted data to that from the
289
+ # centre of the Bayesian distribution
290
+ data.modelType = project.model
291
+ data.reflectivity = copy.deepcopy(results.reflectivity)
292
+ data.shiftedData = results.shiftedData
293
+ data.sldProfiles = copy.deepcopy(results.sldProfiles)
294
+ data.resampledLayers = results.resampledLayers
295
+ data.dataPresent = ratapi.inputs.make_data_present(project)
296
+ data.subRoughs = results.contrastParams.subRoughs
297
+ data.resample = ratapi.inputs.make_resample(project)
298
+ data.contrastNames = [contrast.name for contrast in project.contrasts]
299
+
300
+ if bayes:
301
+ if isinstance(results, ratapi.outputs.BayesResults):
302
+ # the predictionIntervals data consists of 5 rows:
303
+ # row 0: min with 95% confidence
304
+ # row 1: min with 65% confidence
305
+ # row 2: mean
306
+ # row 3: max with 65% confidence
307
+ # row 4: max with 95% confidence
308
+ if bayes == 95:
309
+ interval = [0, 4]
310
+ elif bayes == 65:
311
+ interval = [1, 3]
312
+ else:
313
+ raise ValueError("Parameter `bayes` must be 95, 65 or None")
314
+ confidence_intervals = {
315
+ "reflectivity": [
316
+ (ref_inter[interval[0]], ref_inter[interval[1]])
317
+ for ref_inter in results.predictionIntervals.reflectivity
318
+ ],
319
+ "sld": [
320
+ [(sld_inter[interval[0]], sld_inter[interval[1]]) for sld_inter in sld]
321
+ for sld in results.predictionIntervals.sld
322
+ ],
323
+ }
324
+ # For a shaded plot, use the mean values from predictionIntervals
325
+ for reflectivity, mean_reflectivity in zip(
326
+ data.reflectivity, results.predictionIntervals.reflectivity, strict=False
327
+ ):
328
+ reflectivity[:, 1] = mean_reflectivity[2]
329
+ for sldProfile, mean_sld_profile in zip(data.sldProfiles, results.predictionIntervals.sld, strict=False):
330
+ for sld, mean_sld in zip(sldProfile, mean_sld_profile, strict=False):
331
+ sld[:, 1] = mean_sld[2]
332
+ else:
333
+ raise ValueError(
334
+ "Shaded confidence intervals are only available for the results of Bayesian analysis (NS or DREAM)"
335
+ )
336
+ else:
337
+ confidence_intervals = None
338
+
339
+ if fig is None:
340
+ fig = plt.subplots(1, 2)[0]
341
+ elif len(fig.axes) != 2:
342
+ fig.clf()
343
+ fig.subplots(1, 2)
344
+
345
+ plot_ref_sld_helper(
346
+ data,
347
+ fig,
348
+ confidence_intervals=confidence_intervals,
349
+ linear_x=linear_x,
350
+ q4=q4,
351
+ show_error_bar=show_error_bar,
352
+ show_grid=show_grid,
353
+ show_legend=show_legend,
354
+ shift_value=shift_value,
355
+ )
356
+
357
+ if return_fig:
358
+ return fig
359
+
360
+ plt.show(block=block)
361
+
362
+
363
+ class BlittingSupport:
364
+ """Create a SLD plot that uses blitting to get faster draws.
365
+
366
+ The blit plot stores the background from an
367
+ initial draw then updates the foreground (lines and error bars) if the background is not changed.
368
+
369
+ Parameters
370
+ ----------
371
+ data : PlotEventData
372
+ The plot event data that contains all the information
373
+ to generate the ref and sld plots
374
+ fig : matplotlib.figure.Figure, optional
375
+ The figure class that has two subplots
376
+ linear_x : bool, default: False
377
+ Controls whether the x-axis on reflectivity plot uses the linear scale
378
+ q4 : bool, default: False
379
+ Controls whether Q^4 is plotted on the reflectivity plot
380
+ show_error_bar : bool, default: True
381
+ Controls whether the error bars are shown
382
+ show_grid : bool, default: False
383
+ Controls whether the grid is shown
384
+ show_legend : bool, default: True
385
+ Controls whether the legend is shown
386
+ shift_value : float, default: 100
387
+ A value between 1 and 100 that controls the spacing between the reflectivity plots for each of the contrasts
388
+ """
389
+
390
+ def __init__(
391
+ self,
392
+ data,
393
+ fig=None,
394
+ linear_x: bool = False,
395
+ q4: bool = False,
396
+ show_error_bar: bool = True,
397
+ show_grid: bool = False,
398
+ show_legend: bool = True,
399
+ shift_value: float = 100,
400
+ ):
401
+ self.figure = fig
402
+ self.linear_x = linear_x
403
+ self.q4 = q4
404
+ self.show_error_bar = show_error_bar
405
+ self.show_grid = show_grid
406
+ self.show_legend = show_legend
407
+ self.shift_value = shift_value
408
+ self.update_plot(data)
409
+ self.event_id = self.figure.canvas.mpl_connect("resize_event", self.resizeEvent)
410
+
411
+ def __del__(self):
412
+ self.figure.canvas.mpl_disconnect(self.event_id)
413
+
414
+ def resizeEvent(self, _event):
415
+ """Ensure the background is updated after a resize event."""
416
+ self.__background_changed = True
417
+
418
+ def update(self, data):
419
+ """Update the foreground, if background has not changed otherwise it updates full plot.
420
+
421
+ Parameters
422
+ ----------
423
+ data : PlotEventData
424
+ The plot event data that contains all the information
425
+ to generate the ref and sld plots
426
+ """
427
+ if self.__background_changed:
428
+ self.update_plot(data)
429
+ else:
430
+ self.update_foreground(data)
431
+
432
+ def __setattr__(self, name, value):
433
+ old_value = getattr(self, name, None)
434
+ if value == old_value:
435
+ return
436
+
437
+ super().__setattr__(name, value)
438
+ if name in ["figure", "linear_x", "q4", "show_error_bar", "show_grid", "show_legend", "shift_value"]:
439
+ self.__background_changed = True
440
+
441
+ def set_animated(self, is_animated: bool):
442
+ """Set the animated property of foreground plot elements.
443
+
444
+ Parameters
445
+ ----------
446
+ is_animated : bool
447
+ Indicates if the animated property should be set.
448
+ """
449
+ for line in self.figure.axes[0].lines:
450
+ line.set_animated(is_animated)
451
+ for line in self.figure.axes[1].lines:
452
+ line.set_animated(is_animated)
453
+ for container in self.figure.axes[0].containers:
454
+ container[2][0].set_animated(is_animated)
455
+
456
+ def adjust_error_bar(self, error_bar_container, x, y, y_error):
457
+ """Adjust the error bar data.
458
+
459
+ Parameters
460
+ ----------
461
+ error_bar_container : Tuple
462
+ Tuple containing the artist of the errorbar i.e. (data line, cap lines, bar lines)
463
+ x : np.ndarray
464
+ The shifted data x axis data
465
+ y : np.ndarray
466
+ The shifted data y axis data
467
+ y_error : np.ndarray
468
+ The shifted data y axis error data
469
+ """
470
+ line, _, (bars_y,) = error_bar_container
471
+
472
+ line.set_data(x, y)
473
+ x_base = x
474
+ y_base = y
475
+
476
+ y_error_top = y_base + y_error
477
+ y_error_bottom = y_base - y_error
478
+
479
+ new_segments_y = [
480
+ np.array([[x, yt], [x, yb]]) for x, yt, yb in zip(x_base, y_error_top, y_error_bottom, strict=False)
481
+ ]
482
+ bars_y.set_segments(new_segments_y)
483
+
484
+ def update_plot(self, data):
485
+ """Update the full plot.
486
+
487
+ Parameters
488
+ ----------
489
+ data : PlotEventData
490
+ The plot event data that contains all the information
491
+ to generate the ref and sld plots
492
+ """
493
+ if self.figure is not None:
494
+ self.figure.clf()
495
+
496
+ self.figure.tight_layout()
497
+ plot_ref_sld_helper(
498
+ data,
499
+ self.figure,
500
+ linear_x=self.linear_x,
501
+ q4=self.q4,
502
+ show_error_bar=self.show_error_bar,
503
+ show_grid=self.show_grid,
504
+ show_legend=self.show_legend,
505
+ animated=True,
506
+ )
507
+ self.figure.canvas.draw()
508
+ self.bg = self.figure.canvas.copy_from_bbox(self.figure.bbox)
509
+ for line in self.figure.axes[0].lines:
510
+ self.figure.axes[0].draw_artist(line)
511
+ for line in self.figure.axes[1].lines:
512
+ self.figure.axes[1].draw_artist(line)
513
+ for container in self.figure.axes[0].containers:
514
+ self.figure.axes[0].draw_artist(container[2][0])
515
+ self.figure.canvas.blit(self.figure.bbox)
516
+ self.set_animated(False)
517
+ self.__background_changed = False
518
+
519
+ def update_foreground(self, data):
520
+ """Update the plot foreground only.
521
+
522
+ Parameters
523
+ ----------
524
+ data : PlotEventData
525
+ The plot event data that contains all the information
526
+ to generate the ref and sld plots
527
+ """
528
+ self.set_animated(True)
529
+ self.figure.canvas.restore_region(self.bg)
530
+ plot_data = _extract_plot_data(data, self.q4, self.show_error_bar, self.shift_value)
531
+
532
+ offset = 2 if self.show_error_bar else 1
533
+ for i in range(
534
+ 0,
535
+ len(self.figure.axes[0].lines),
536
+ ):
537
+ self.figure.axes[0].lines[i].set_data(plot_data["ref"][i // offset][0], plot_data["ref"][i // offset][1])
538
+ self.figure.axes[0].draw_artist(self.figure.axes[0].lines[i])
539
+
540
+ i = 0
541
+ for j in range(len(plot_data["sld"])):
542
+ for sld in plot_data["sld"][j]:
543
+ self.figure.axes[1].lines[i].set_data(sld[0], sld[1])
544
+ self.figure.axes[1].draw_artist(self.figure.axes[1].lines[i])
545
+ i += 1
546
+
547
+ for resampled in plot_data["sld_resample"][j]:
548
+ self.figure.axes[1].lines[i].set_data(resampled[0], resampled[1])
549
+ self.figure.axes[1].draw_artist(self.figure.axes[1].lines[i])
550
+ i += 1
551
+
552
+ for i, container in enumerate(self.figure.axes[0].containers):
553
+ self.adjust_error_bar(
554
+ container, plot_data["error"][i][0], plot_data["error"][i][1], plot_data["error"][i][2]
555
+ )
556
+ self.figure.axes[0].draw_artist(container[2][0])
557
+ self.figure.axes[0].draw_artist(container[0])
558
+
559
+ self.figure.canvas.blit(self.figure.bbox)
560
+ self.figure.canvas.flush_events()
561
+ self.set_animated(False)
562
+
563
+
564
+ class LivePlot:
565
+ """Create a plot that gets updates from the plot event during a calculation.
566
+
567
+ Parameters
568
+ ----------
569
+ block : bool, default: False
570
+ Indicates the plot should block until it is closed
571
+
572
+ """
573
+
574
+ def __init__(self, block=False):
575
+ self.block = block
576
+ self.closed = False
577
+ self.blit_plot = None
578
+
579
+ def __enter__(self):
580
+ self.figure = plt.subplots(1, 2)[0]
581
+ self.figure.canvas.mpl_connect("close_event", self._setCloseState)
582
+ self.figure.show()
583
+ ratapi.events.register(ratapi.events.EventTypes.Plot, self.plotEvent)
584
+
585
+ return self.figure
586
+
587
+ def _setCloseState(self, _):
588
+ """Close event handler."""
589
+ self.closed = True
590
+
591
+ def plotEvent(self, event):
592
+ """Plot the figure from plot event data.
593
+
594
+ This is a callback for the plot event.
595
+
596
+ Parameters
597
+ ----------
598
+ event: PlotEventData
599
+ The plot event data.
600
+
601
+ """
602
+ if not self.closed and self.figure.number in plt.get_fignums():
603
+ if self.blit_plot is None:
604
+ self.blit_plot = BlittingSupport(event, self.figure)
605
+ else:
606
+ self.blit_plot.update(event)
607
+
608
+ def __exit__(self, _exc_type, _exc_val, _traceback):
609
+ ratapi.events.clear(ratapi.events.EventTypes.Plot, self.plotEvent)
610
+ if not self.closed and self.figure.number in plt.get_fignums():
611
+ plt.show(block=self.block)
612
+
613
+
614
+ def assert_bayesian(name: str):
615
+ """Ensure the results passed to a function are Bayesian.
616
+
617
+ This is a decorator.
618
+
619
+ Parameters
620
+ ----------
621
+ name : str
622
+ The name of the plot for the error message.
623
+
624
+ """
625
+
626
+ def decorator(func: Callable):
627
+ @wraps(func)
628
+ def inner(results, *args, **kwargs):
629
+ if isinstance(results, ratapi.outputs.BayesResults):
630
+ return func(results, *args, **kwargs)
631
+ raise ValueError(f"{name} plots are only available for the results of Bayesian analysis (NS or DREAM)")
632
+
633
+ return inner
634
+
635
+ return decorator
636
+
637
+
638
+ def name_to_index(param: str | int, names: list[str]):
639
+ """Convert parameter names to indices."""
640
+ if isinstance(param, str):
641
+ if param not in names:
642
+ raise ValueError(f"Parameter {param} is not in this analysis.")
643
+ param = names.index(param)
644
+ elif isinstance(param, int):
645
+ if param > len(names) or param < 0:
646
+ raise IndexError(f"Index {param} has been given, but indices must be between zero and {len(names)}.")
647
+ else:
648
+ raise ValueError(f"Parameters must be given as indices or names, not {type(param)}.")
649
+ return param
650
+
651
+
652
+ @assert_bayesian("Corner")
653
+ def plot_corner(
654
+ results: ratapi.outputs.BayesResults,
655
+ params: list[int | str] | None = None,
656
+ smooth: bool = True,
657
+ block: bool = False,
658
+ fig: matplotlib.figure.Figure | None = None,
659
+ return_fig: bool = False,
660
+ hist_kwargs: dict | None = None,
661
+ hist2d_kwargs: dict | None = None,
662
+ progress_callback: Callable[[int, int], None] | None = None,
663
+ ):
664
+ """Create a corner plot from a Bayesian analysis.
665
+
666
+ Parameters
667
+ ----------
668
+ results : BayesResults
669
+ The results from a Bayesian calculation.
670
+ params : list[int or str], default None
671
+ The indices or names of a subset of parameters if required.
672
+ If None, uses all indices.
673
+ smooth : bool, default True
674
+ Whether to apply Gaussian smoothing to the corner plot.
675
+ block : bool, default False
676
+ Whether Python should block until the plot is closed.
677
+ fig : matplotlib.figure.Figure, optional
678
+ The figure object to use for plot.
679
+ return_fig: bool, default False
680
+ If True, return the figure as an object instead of showing it.
681
+ hist_kwargs : dict
682
+ Extra keyword arguments to pass to the 1d histograms.
683
+ Default is {'density': True, 'bins': 25}
684
+ hist2d_kwargs : dict
685
+ Extra keyword arguments to pass to the 2d histograms.
686
+ Default is {'density': True, 'bins': 25}
687
+ progress_callback: Union[Callable[[int, int], None], None]
688
+ Callback function for providing progress during plot creation
689
+ First argument is current completed sub plot and second is total number of sub plots
690
+
691
+ Returns
692
+ -------
693
+ Figure or None
694
+ If `return_fig` is True, return the figure - otherwise, return nothing.
695
+
696
+ """
697
+ fitname_to_index = partial(name_to_index, names=results.fitNames)
698
+
699
+ if params is None:
700
+ params = range(0, len(results.fitNames))
701
+ else:
702
+ params = list(map(fitname_to_index, params))
703
+
704
+ # defaults are applied inside each function - just pass blank dicts for now
705
+ if hist_kwargs is None:
706
+ hist_kwargs = {}
707
+ if hist2d_kwargs is None:
708
+ hist2d_kwargs = {}
709
+
710
+ num_params = len(params)
711
+ total_count = num_params + (num_params**2 - num_params) // 2
712
+
713
+ if fig is None:
714
+ fig, axes = plt.subplots(num_params, num_params, figsize=(11, 10), subplot_kw={"visible": False})
715
+ else:
716
+ fig.clf()
717
+ axes = fig.subplots(num_params, num_params, subplot_kw={"visible": False})
718
+
719
+ # i is row, j is column
720
+ current_count = 0
721
+ for i in range(num_params):
722
+ for j in range(i + 1):
723
+ row_param = params[i]
724
+ col_param = params[j]
725
+ current_axes: Axes = axes if isinstance(axes, matplotlib.axes.Axes) else axes[i][j]
726
+ current_axes.tick_params(which="both", labelsize="medium")
727
+ current_axes.xaxis.offsetText.set_fontsize("small")
728
+ current_axes.yaxis.offsetText.set_fontsize("small")
729
+ current_axes.set_visible(True)
730
+ if i == j: # diagonal: histograms
731
+ plot_one_hist(results, param=row_param, smooth=smooth, axes=current_axes, **hist_kwargs)
732
+ elif i > j: # lower triangle: 2d histograms
733
+ plot_contour(
734
+ results, x_param=col_param, y_param=row_param, smooth=smooth, axes=current_axes, **hist2d_kwargs
735
+ )
736
+
737
+ # remove label if on inside of corner plot
738
+ if j != 0:
739
+ current_axes.get_yaxis().set_visible(False)
740
+ if i != len(params) - 1:
741
+ current_axes.get_xaxis().set_visible(False)
742
+ # make labels invisible as titles cover that
743
+ current_axes.yaxis._update_offset_text_position = types.MethodType(
744
+ _y_update_offset_text_position, current_axes.yaxis
745
+ )
746
+ current_axes.yaxis.offset_text_position = "center"
747
+ current_axes.set_ylabel("")
748
+ current_axes.set_xlabel("")
749
+ if progress_callback is not None:
750
+ current_count += 1
751
+ progress_callback(current_count, total_count)
752
+ if return_fig:
753
+ return fig
754
+ plt.show(block=block)
755
+
756
+
757
+ @assert_bayesian("Histogram")
758
+ def plot_one_hist(
759
+ results: ratapi.outputs.BayesResults,
760
+ param: int | str,
761
+ smooth: bool = True,
762
+ sigma: float | None = None,
763
+ estimated_density: Literal["normal", "lognor", "kernel", None] = None,
764
+ axes: Axes | None = None,
765
+ block: bool = False,
766
+ return_fig: bool = False,
767
+ **hist_settings,
768
+ ):
769
+ """Plot the marginalised posterior for a parameter of a Bayesian analysis.
770
+
771
+ Parameters
772
+ ----------
773
+ results : BayesResults
774
+ The results from a Bayesian calculation.
775
+ param : Union[int, str]
776
+ Either the index or name of a parameter.
777
+ block : bool, default False
778
+ Whether Python should block until the plot is closed.
779
+ smooth : bool, default True
780
+ Whether to apply Gaussian smoothing to the histogram.
781
+ Defaults to True.
782
+ sigma: float or None, default None
783
+ If given, is used as the sigma-parameter for the Gaussian smoothing.
784
+ If None, the default (1/3rd of parameter chain standard deviation) is used.
785
+ estimated_density : 'normal', 'lognor', 'kernel' or None, default None
786
+ If None (default), ignore. Else, add an estimated density
787
+ of the given form on top of the histogram by the following estimations:
788
+ 'normal': normal Gaussian.
789
+ 'lognor': Log-normal probability density.
790
+ 'kernel': kernel density estimation.
791
+ axes: Axes or None, default None
792
+ If provided, plot on the given Axes object.
793
+ block : bool, default False
794
+ Whether Python should block until the plot is closed.
795
+ return_fig: bool, default False
796
+ If True, return the figure as an object instead of showing it.
797
+ **hist_settings :
798
+ Settings passed to `np.histogram`. By default, the settings
799
+ passed are `bins = 25` and `density = True`.
800
+
801
+ Returns
802
+ -------
803
+ Figure or None
804
+ If `return_fig` is True, return the figure - otherwise, return nothing.
805
+
806
+ """
807
+ chain = results.chain
808
+ param = name_to_index(param, results.fitNames)
809
+
810
+ if axes is None:
811
+ fig, axes = plt.subplots(1, 1)
812
+ else:
813
+ fig = None
814
+
815
+ # apply default settings if not set by user
816
+ default_settings = {"bins": 25, "density": True}
817
+ hist_settings = {**default_settings, **hist_settings}
818
+
819
+ parameter_chain = chain[:, param]
820
+ counts, bins = np.histogram(parameter_chain, **hist_settings)
821
+ mean_y = np.mean(parameter_chain)
822
+ sd_y = np.std(parameter_chain)
823
+
824
+ if smooth:
825
+ if sigma is None:
826
+ sigma = sd_y / 2
827
+ counts = gaussian_filter1d(counts, sigma)
828
+ axes.hist(
829
+ bins[:-1],
830
+ bins,
831
+ weights=counts,
832
+ edgecolor="black",
833
+ linewidth=1.2,
834
+ color="white",
835
+ )
836
+
837
+ axes.set_title(results.fitNames[param], loc="left", fontsize="medium")
838
+
839
+ if estimated_density:
840
+ dx = bins[1] - bins[0]
841
+ if estimated_density == "normal":
842
+ t = np.linspace(mean_y - 3.5 * sd_y, mean_y + 3.5 * sd_y)
843
+ axes.plot(t, norm.pdf(t, loc=mean_y, scale=sd_y**2))
844
+ elif estimated_density == "lognor":
845
+ t = np.linspace(bins[0] - 0.5 * dx, bins[-1] + 2 * dx)
846
+ axes.plot(t, lognorm.pdf(t, np.mean(np.log(parameter_chain)), np.std(np.log(parameter_chain))))
847
+ elif estimated_density == "kernel":
848
+ t = np.linspace(bins[0] - 2 * dx, bins[-1] + 2 * dx, 200)
849
+ kde = gaussian_kde(parameter_chain)
850
+ axes.plot(t, kde.evaluate(t))
851
+ else:
852
+ raise ValueError(
853
+ f"{estimated_density} is not a supported estimated density function."
854
+ " Supported functions are 'normal' 'lognor' or 'kernel'."
855
+ )
856
+
857
+ # adding the estimated density extends the figure range - reset it to histogram range
858
+ x_range = hist_settings.get("range", (parameter_chain.min(), parameter_chain.max()))
859
+ axes.set_xlim(x_range)
860
+
861
+ if fig is not None:
862
+ if return_fig:
863
+ return fig
864
+ plt.show(block=block)
865
+
866
+
867
+ def _y_update_offset_text_position(axis, _bboxes, bboxes2):
868
+ """Update the position of the Y axis offset text using the provided bounding boxes.
869
+
870
+ Adapted from https://github.com/matplotlib/matplotlib/issues/4476#issuecomment-105627334.
871
+
872
+ Parameters
873
+ ----------
874
+ axis : matplotlib.axis.YAxis
875
+ Y axis to update.
876
+ _bboxes : List
877
+ list of bounding boxes
878
+ bboxes2 : List
879
+ list of bounding boxes
880
+ """
881
+ x, y = axis.offsetText.get_position()
882
+
883
+ if axis.offset_text_position == "left":
884
+ # y in axes coords, x in display coords
885
+ axis.offsetText.set_transform(
886
+ mtransforms.blended_transform_factory(axis.axes.transAxes, mtransforms.IdentityTransform())
887
+ )
888
+
889
+ top = axis.axes.bbox.ymax
890
+ y = top + axis.OFFSETTEXTPAD * axis.figure.dpi / 72.0
891
+
892
+ else:
893
+ # x & y in display coords
894
+ axis.offsetText.set_transform(mtransforms.IdentityTransform())
895
+
896
+ # Northwest of upper-right corner of right-hand extent of tick labels
897
+ if bboxes2:
898
+ bbox = mtransforms.Bbox.union(bboxes2)
899
+ else:
900
+ bbox = axis.axes.bbox
901
+ center = bbox.ymin + (bbox.ymax - bbox.ymin) / 2
902
+ x = bbox.xmin - axis.OFFSETTEXTPAD * axis.figure.dpi / 72.0
903
+ y = center
904
+ x_offset = 110
905
+ axis.offsetText.set_position((x - x_offset, y))
906
+
907
+
908
+ @assert_bayesian("Contour")
909
+ def plot_contour(
910
+ results: ratapi.outputs.BayesResults,
911
+ x_param: int | str,
912
+ y_param: int | str,
913
+ smooth: bool = True,
914
+ sigma: tuple[float] | None = None,
915
+ axes: Axes | None = None,
916
+ block: bool = False,
917
+ return_fig: bool = False,
918
+ **hist2d_settings,
919
+ ):
920
+ """Plot a 2D histogram of two indexed chain parameters, with contours.
921
+
922
+ Parameters
923
+ ----------
924
+ results : ratapi.outputs.BayesResults
925
+ The results of a Bayesian analysis.
926
+ x_param : int
927
+ The index or name of the parameter on the x-axis.
928
+ y_param : int
929
+ The index or name ofthe parameter on the y-axis.
930
+ smooth : bool, default True
931
+ If True, apply Gaussian smoothing to the histogram.
932
+ sigma : tuple[float] or None, default None
933
+ If given, is used as parameters for Gaussian smoothing in x and y direction respectively.
934
+ If None, defaults to the standard deviation of the parameter chain in either direction.
935
+ axes: Axes or None, default None
936
+ If provided, plot on the given Axes object.
937
+ block : bool, default False
938
+ Whether Python should block until the plot is closed.
939
+ return_fig: bool, default False
940
+ If True, return the figure as an object instead of showing it.
941
+ **hist2d_settings:
942
+ Settings passed to `np.histogram2d`.
943
+ Default settings are `bins = 25` and `density = True`.
944
+
945
+ Returns
946
+ -------
947
+ Figure or None
948
+ If `return_fig` is True, return the figure - otherwise, return nothing.
949
+
950
+ """
951
+ if axes is None:
952
+ fig, axes = plt.subplots(1, 1)
953
+ else:
954
+ fig = None
955
+ x_param = name_to_index(x_param, results.fitNames)
956
+ y_param = name_to_index(y_param, results.fitNames)
957
+
958
+ default_settings = {"bins": 25, "density": True}
959
+ hist2d_settings = {**default_settings, **hist2d_settings}
960
+
961
+ counts, x_bins, y_bins = np.histogram2d(results.chain[:, x_param], results.chain[:, y_param], **hist2d_settings)
962
+ if smooth:
963
+ if sigma is None:
964
+ sigma_x = stdev(results.chain[:, x_param]) / 2
965
+ sigma_y = stdev(results.chain[:, y_param]) / 2
966
+ else:
967
+ sigma_x, sigma_y = sigma
968
+ # perform a 1d smooth along both axes
969
+ counts = gaussian_filter1d(counts, axis=0, sigma=sigma_x)
970
+ counts = gaussian_filter1d(counts, axis=1, sigma=sigma_y)
971
+
972
+ axes.pcolormesh(x_bins, y_bins, counts.max() - counts, cmap=matplotlib.colormaps["Greys"].reversed())
973
+ axes.contour(x_bins[:-1], y_bins[:-1], counts.max() - counts, colors="black")
974
+ axes.set_xlabel(results.fitNames[x_param])
975
+ axes.set_ylabel(results.fitNames[y_param])
976
+
977
+ if fig is not None:
978
+ if return_fig:
979
+ return fig
980
+ plt.show(block=block)
981
+
982
+
983
+ def panel_plot_helper(
984
+ plot_func: Callable,
985
+ indices: list[int],
986
+ fig: matplotlib.figure.Figure | None = None,
987
+ progress_callback: Callable[[int, int], None] | None = None,
988
+ ) -> matplotlib.figure.Figure:
989
+ """Generate a panel-based plot from a single plot function.
990
+
991
+ Parameters
992
+ ----------
993
+ plot_func : Callable
994
+ A function which plots one parameter on an Axes object, given its index.
995
+ indices : list[int]
996
+ The list of indices to pass into ``plot_func``.
997
+ fig : matplotlib.figure.Figure, optional
998
+ The figure object to use for plot.
999
+ progress_callback: Union[Callable[[int, int], None], None]
1000
+ Callback function for providing progress during plot creation
1001
+ First argument is current completed sub plot and second is total number of sub plots
1002
+
1003
+ Returns
1004
+ -------
1005
+ matplotlib.figure.Figure
1006
+ A figure containing a grid of plots over the indices in `indices`.
1007
+
1008
+ """
1009
+ nplots = len(indices)
1010
+ nrows, ncols = ceil(sqrt(nplots)), round(sqrt(nplots))
1011
+
1012
+ if fig is None:
1013
+ fig = plt.subplots(nrows, ncols, figsize=(11, 10), subplot_kw={"visible": False})[0]
1014
+ else:
1015
+ fig.clf()
1016
+ fig.subplots(nrows, ncols, subplot_kw={"visible": False})
1017
+ axs = fig.get_axes()
1018
+ for index, plot_num in enumerate(indices):
1019
+ axs[index].tick_params(which="both", labelsize="medium")
1020
+ axs[index].xaxis.offsetText.set_fontsize("small")
1021
+ axs[index].yaxis.offsetText.set_fontsize("small")
1022
+ axs[index].set_visible(True)
1023
+ plot_func(axs[index], plot_num)
1024
+ if progress_callback is not None:
1025
+ progress_callback(index, nplots)
1026
+
1027
+ fig.tight_layout()
1028
+ return fig
1029
+
1030
+
1031
+ @assert_bayesian("Histogram")
1032
+ def plot_hists(
1033
+ results: ratapi.outputs.BayesResults,
1034
+ params: list[int | str] | None = None,
1035
+ smooth: bool = True,
1036
+ sigma: float | None = None,
1037
+ estimated_density: dict[Literal["normal", "lognor", "kernel", None]]
1038
+ | Literal["normal", "lognor", "kernel", None] = None,
1039
+ block: bool = False,
1040
+ fig: matplotlib.figure.Figure | None = None,
1041
+ return_fig: bool = False,
1042
+ progress_callback: Callable[[int, int], None] | None = None,
1043
+ **hist_settings,
1044
+ ):
1045
+ """Plot marginalised posteriors for several parameters from a Bayesian analysis.
1046
+
1047
+ Parameters
1048
+ ----------
1049
+ results : BayesResults
1050
+ The results from a Bayesian calculation.
1051
+ params : list[int], default None
1052
+ The indices or names of a subset of parameters if required.
1053
+ If None, uses all indices.
1054
+ smooth : bool, default True
1055
+ Whether to apply a Gaussian smoothing to the histogram.
1056
+ Defaults to True.
1057
+ sigma: float or None, default None
1058
+ If given, is used as the sigma-parameter for the Gaussian smoothing.
1059
+ If None, the default (1/3rd of parameter chain standard deviation) is used.
1060
+ estimated_density : dict, default None
1061
+ If None (default), ignore.
1062
+ Can also be a string 'normal', 'lognor' or 'kernel' to apply the same estimated density to all parameters.
1063
+ Else, a dictionary where the keys are
1064
+ indices or names of parameters, and values denote an estimated density
1065
+ of the given form on top of the histogram:
1066
+ None : do not plot estimated density for this parameter.
1067
+ 'normal': normal Gaussian.
1068
+ 'lognor': Log-normal probability density.
1069
+ 'kernel': kernel density estimation.
1070
+ To provide a default estimated density function to all parameters that haven't been specifically set,
1071
+ pass the 'default' key,
1072
+ e.g. to apply 'normal' to all unset parameters, set `estimated_density = {'default': 'normal'}`.
1073
+ block : bool, default False
1074
+ Whether Python should block until the plot is closed.
1075
+ fig : matplotlib.figure.Figure, optional
1076
+ The figure object to use for plot.
1077
+ return_fig: bool, default False
1078
+ If True, return the figure as an object instead of showing it.
1079
+ progress_callback: Union[Callable[[int, int], None], None]
1080
+ Callback function for providing progress during plot creation
1081
+ First argument is current completed sub plot and second is total number of sub plots
1082
+ hist_settings :
1083
+ Settings passed to `np.histogram`. By default, the settings
1084
+ passed are `bins = 25` and `density = True`.
1085
+
1086
+ Returns
1087
+ -------
1088
+ Figure or None
1089
+ If `return_fig` is True, return the figure - otherwise, return nothing.
1090
+
1091
+ """
1092
+ # first convert names to indices if given
1093
+ fitname_to_index = partial(name_to_index, names=results.fitNames)
1094
+
1095
+ if params is None:
1096
+ params = range(0, len(results.fitNames))
1097
+ else:
1098
+ params = list(map(fitname_to_index, params))
1099
+
1100
+ if estimated_density is not None:
1101
+
1102
+ def validate_dens_type(dens_type: str | None, param: str):
1103
+ """Check estimated density is a supported type."""
1104
+ if dens_type not in [None, "normal", "lognor", "kernel"]:
1105
+ raise ValueError(
1106
+ f"Parameter {param} has estimated density function {dens_type},"
1107
+ " which is not supported. Supported estimated density functions"
1108
+ " are 'normal', 'lognor', and 'kernel'."
1109
+ )
1110
+ return dens_type
1111
+
1112
+ if isinstance(estimated_density, str):
1113
+ validate_dens_type(estimated_density, "default")
1114
+ estimated_density = {fitname_to_index(param): estimated_density for param in params}
1115
+ else:
1116
+ default = estimated_density.pop("default", None)
1117
+ validate_dens_type(default, "default")
1118
+ default_density = {fitname_to_index(param): default for param in params}
1119
+ # convert names to indices and ensure density types given are correct
1120
+ estimated_density = {
1121
+ name_to_index(k, results.fitNames): validate_dens_type(v, k) for k, v in estimated_density.items()
1122
+ }
1123
+ # merge other estimated densities into default dict
1124
+ estimated_density = {**default_density, **estimated_density}
1125
+ else:
1126
+ estimated_density = {}
1127
+
1128
+ fig = panel_plot_helper(
1129
+ lambda ax, i: plot_one_hist(
1130
+ results,
1131
+ i,
1132
+ smooth=smooth,
1133
+ sigma=sigma,
1134
+ estimated_density=estimated_density.get(i),
1135
+ axes=ax,
1136
+ **hist_settings,
1137
+ ),
1138
+ params,
1139
+ fig,
1140
+ progress_callback,
1141
+ )
1142
+ if return_fig:
1143
+ return fig
1144
+ plt.show(block=block)
1145
+
1146
+
1147
+ @assert_bayesian("Chain")
1148
+ def plot_chain(
1149
+ results: ratapi.outputs.BayesResults,
1150
+ params: list[int | str] | None = None,
1151
+ maxpoints: int = 15000,
1152
+ block: bool = False,
1153
+ fig: matplotlib.figure.Figure | None = None,
1154
+ return_fig: bool = False,
1155
+ progress_callback: Callable[[int, int], None] | None = None,
1156
+ ):
1157
+ """Plot the MCMC chain for each parameter of a Bayesian analysis.
1158
+
1159
+ Parameters
1160
+ ----------
1161
+ results : ratapi.outputs.BayesResults
1162
+ The results of a Bayesian analysis.
1163
+ params : list[int], default None
1164
+ The indices or names of a subset of parameters if required.
1165
+ If None, uses all indices.
1166
+ maxpoints : int
1167
+ The maximum number of points to plot for each parameter.
1168
+ block : bool, default False
1169
+ Whether Python should block until the plot is closed.
1170
+ fig : matplotlib.figure.Figure, optional
1171
+ The figure object to use for plot.
1172
+ return_fig: bool, default False
1173
+ If True, return the figure as an object instead of showing it.
1174
+ progress_callback: Union[Callable[[int, int], None], None]
1175
+ Callback function for providing progress during plot creation
1176
+ First argument is current completed sub plot and second is total number of sub plots
1177
+
1178
+ Returns
1179
+ -------
1180
+ Figure or None
1181
+ If `return_fig` is True, return the figure - otherwise, return nothing.
1182
+
1183
+ """
1184
+ chain = results.chain
1185
+ nsimulations, _ = chain.shape
1186
+ # skip is to evenly distribute points plotted
1187
+ # all points will be plotted if maxpoints < nsimulations
1188
+ skip = max(floor(nsimulations / maxpoints), 1)
1189
+
1190
+ # convert names to indices if given
1191
+ fitname_to_index = partial(name_to_index, names=results.fitNames)
1192
+
1193
+ if params is None:
1194
+ params = range(0, len(results.fitNames))
1195
+ else:
1196
+ params = list(map(fitname_to_index, params))
1197
+
1198
+ def plot_one_chain(axes: Axes, i: int):
1199
+ axes.plot(range(0, nsimulations, skip), chain[:, i][0:nsimulations:skip])
1200
+ axes.set_title(results.fitNames[i], fontsize="small")
1201
+
1202
+ fig = panel_plot_helper(plot_one_chain, params, fig, progress_callback)
1203
+ if return_fig:
1204
+ return fig
1205
+ plt.show(block=block)
1206
+
1207
+
1208
+ def plot_bayes(project: ratapi.Project, results: ratapi.outputs.BayesResults):
1209
+ """Plot the results of a Bayesian analysis with confidence information.
1210
+
1211
+ This produces an unshaded reflectivity/SLD plot, a reflectivity/SLD plot with shaded 95% confidence
1212
+ intervals, a grid of histograms giving probability density for each parameter, and a corner plot for
1213
+ all parameters.
1214
+
1215
+ Parameters
1216
+ ----------
1217
+ project : Project
1218
+ An instance of the Project class
1219
+ results : Union[Results, BayesResults]
1220
+ The result from the calculation
1221
+ block : bool, default: False
1222
+ Indicates the plot should block until it is closed
1223
+
1224
+ """
1225
+ if isinstance(results, ratapi.outputs.BayesResults):
1226
+ plot_ref_sld(project, results)
1227
+ plot_ref_sld(project, results, bayes=95)
1228
+ plot_hists(results)
1229
+ plot_corner(results)
1230
+ else:
1231
+ raise ValueError("Bayes plots are only available for the results of Bayesian analysis (NS or DREAM)")