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