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/outputs.py
ADDED
|
@@ -0,0 +1,821 @@
|
|
|
1
|
+
"""Converts results from the compiled RAT code to python dataclasses."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Union
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
import ratapi.rat_core
|
|
11
|
+
from ratapi.utils.enums import Procedures
|
|
12
|
+
|
|
13
|
+
bayes_results_subclasses = [
|
|
14
|
+
"predictionIntervals",
|
|
15
|
+
"confidenceIntervals",
|
|
16
|
+
"dreamParams",
|
|
17
|
+
"dreamOutput",
|
|
18
|
+
"nestedSamplerOutput",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
bayes_results_fields = {
|
|
22
|
+
"param_fields": {
|
|
23
|
+
"predictionIntervals": [],
|
|
24
|
+
"confidenceIntervals": [],
|
|
25
|
+
"dreamParams": [
|
|
26
|
+
"nParams",
|
|
27
|
+
"nChains",
|
|
28
|
+
"nGenerations",
|
|
29
|
+
"parallel",
|
|
30
|
+
"CPU",
|
|
31
|
+
"jumpProbability",
|
|
32
|
+
"pUnitGamma",
|
|
33
|
+
"nCR",
|
|
34
|
+
"delta",
|
|
35
|
+
"steps",
|
|
36
|
+
"zeta",
|
|
37
|
+
"outlier",
|
|
38
|
+
"adaptPCR",
|
|
39
|
+
"thinning",
|
|
40
|
+
"epsilon",
|
|
41
|
+
"ABC",
|
|
42
|
+
"IO",
|
|
43
|
+
"storeOutput",
|
|
44
|
+
],
|
|
45
|
+
"dreamOutput": ["runtime", "iteration"],
|
|
46
|
+
"nestedSamplerOutput": ["logZ", "logZErr"],
|
|
47
|
+
},
|
|
48
|
+
"list_fields": {
|
|
49
|
+
"predictionIntervals": ["reflectivity"],
|
|
50
|
+
"confidenceIntervals": [],
|
|
51
|
+
"dreamParams": [],
|
|
52
|
+
"dreamOutput": [],
|
|
53
|
+
"nestedSamplerOutput": [],
|
|
54
|
+
},
|
|
55
|
+
"double_list_fields": {
|
|
56
|
+
"predictionIntervals": ["sld"],
|
|
57
|
+
"confidenceIntervals": [],
|
|
58
|
+
"dreamParams": [],
|
|
59
|
+
"dreamOutput": [],
|
|
60
|
+
"nestedSamplerOutput": [],
|
|
61
|
+
},
|
|
62
|
+
"array_fields": {
|
|
63
|
+
"predictionIntervals": ["sampleChi"],
|
|
64
|
+
"confidenceIntervals": ["percentile65", "percentile95", "mean"],
|
|
65
|
+
"dreamParams": ["R"],
|
|
66
|
+
"dreamOutput": ["allChains", "outlierChains", "AR", "R_stat", "CR"],
|
|
67
|
+
"nestedSamplerOutput": ["nestSamples", "postSamples"],
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
results_fields = {
|
|
72
|
+
"list_fields": ["reflectivity", "simulation", "shiftedData", "backgrounds", "resolutions"],
|
|
73
|
+
"double_list_fields": ["sldProfiles", "layers", "resampledLayers"],
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def get_field_string(field: str, value: Any, array_limit: int):
|
|
78
|
+
"""Return a string representation of class fields where large arrays are represented by their shape.
|
|
79
|
+
|
|
80
|
+
An array will be displayed as just its shape if it is multidimensional or 1D and longer than ``array_limit``.
|
|
81
|
+
|
|
82
|
+
Parameters
|
|
83
|
+
----------
|
|
84
|
+
field : str
|
|
85
|
+
The name of the field in the RAT output class.
|
|
86
|
+
value : Any
|
|
87
|
+
The value of the given field in the RAT output class.
|
|
88
|
+
array_limit : int
|
|
89
|
+
The maximum length of 1D arrays which will be fully displayed.
|
|
90
|
+
|
|
91
|
+
Returns
|
|
92
|
+
-------
|
|
93
|
+
field_string : str
|
|
94
|
+
The string representation of the field in the RAT output class.
|
|
95
|
+
|
|
96
|
+
Examples
|
|
97
|
+
--------
|
|
98
|
+
>>> get_field_string("data", 130, 5)
|
|
99
|
+
"data = 130"
|
|
100
|
+
|
|
101
|
+
>>> get_field_string("data", array([1, 2, 3, 4, 5]), 10)
|
|
102
|
+
"data = [1 2 3 4 5]"
|
|
103
|
+
|
|
104
|
+
>>> get_field_string("data", array([1, 2, 3, 4, 5]), 3)
|
|
105
|
+
"data = Data array: [5],"
|
|
106
|
+
|
|
107
|
+
>>> get_field_string("data", array([[1, 2, 3], [4, 5, 6]]), 10)
|
|
108
|
+
"data = Data array: [2 x 3],"
|
|
109
|
+
|
|
110
|
+
"""
|
|
111
|
+
array_text = "Data array: "
|
|
112
|
+
if isinstance(value, list) and len(value) > 0:
|
|
113
|
+
if isinstance(value[0], np.ndarray):
|
|
114
|
+
array_strings = [f"{array_text}[{' x '.join(str(i) for i in array.shape)}]" for array in value]
|
|
115
|
+
field_string = f"{field} = [{', '.join(str(string) for string in array_strings)}],\n"
|
|
116
|
+
elif isinstance(value[0], list) and len(value[0]) > 0 and isinstance(value[0][0], np.ndarray):
|
|
117
|
+
array_strings = [
|
|
118
|
+
[f"{array_text}[{' x '.join(str(i) for i in array.shape)}]" for array in sub_list] for sub_list in value
|
|
119
|
+
]
|
|
120
|
+
list_strings = [f"[{', '.join(string for string in list_string)}]" for list_string in array_strings]
|
|
121
|
+
field_string = f"{field} = [{', '.join(list_strings)}],\n"
|
|
122
|
+
else:
|
|
123
|
+
field_string = f"{field} = {str(value)},\n"
|
|
124
|
+
elif isinstance(value, np.ndarray):
|
|
125
|
+
if value.ndim == 1 and value.size < array_limit:
|
|
126
|
+
field_string = f"{field} = {str(value) if value.size > 0 else '[]'},\n"
|
|
127
|
+
else:
|
|
128
|
+
field_string = f"{field} = {array_text}[{' x '.join(str(i) for i in value.shape)}],\n"
|
|
129
|
+
else:
|
|
130
|
+
field_string = f"{field} = {str(value)},\n"
|
|
131
|
+
|
|
132
|
+
return field_string
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class RATResult:
|
|
136
|
+
"""A mixin class which truncates arrays when the class is displayed."""
|
|
137
|
+
|
|
138
|
+
def __str__(self):
|
|
139
|
+
output = f"{self.__class__.__name__}(\n"
|
|
140
|
+
for key, value in self.__dict__.items():
|
|
141
|
+
output += "\t" + get_field_string(key, value, 100)
|
|
142
|
+
output += ")"
|
|
143
|
+
return output
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@dataclass
|
|
147
|
+
class CalculationResults(RATResult):
|
|
148
|
+
"""The goodness of fit from the Abeles calculation.
|
|
149
|
+
|
|
150
|
+
Parameters
|
|
151
|
+
----------
|
|
152
|
+
chiValues : np.ndarray
|
|
153
|
+
The chi-squared value for each contrast.
|
|
154
|
+
sumChi : float
|
|
155
|
+
The sum of the chiValues array.
|
|
156
|
+
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
chiValues: np.ndarray
|
|
160
|
+
sumChi: float
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@dataclass
|
|
164
|
+
class ContrastParams(RATResult):
|
|
165
|
+
"""The experimental parameters for each contrast.
|
|
166
|
+
|
|
167
|
+
Parameters
|
|
168
|
+
----------
|
|
169
|
+
scalefactors : np.ndarray
|
|
170
|
+
The scalefactor values for each contrast.
|
|
171
|
+
bulkIn : np.ndarray
|
|
172
|
+
The bulk in values for each contrast.
|
|
173
|
+
bulkOut : np.ndarray
|
|
174
|
+
The bulk out values for each contrast.
|
|
175
|
+
subRoughs : np.ndarray
|
|
176
|
+
The substrate roughness values for each contrast.
|
|
177
|
+
resample : np.ndarray
|
|
178
|
+
An array containing whether each contrast was resampled.
|
|
179
|
+
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
scalefactors: np.ndarray
|
|
183
|
+
bulkIn: np.ndarray
|
|
184
|
+
bulkOut: np.ndarray
|
|
185
|
+
subRoughs: np.ndarray
|
|
186
|
+
resample: np.ndarray
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@dataclass
|
|
190
|
+
class Results:
|
|
191
|
+
"""The results of a RAT calculation.
|
|
192
|
+
|
|
193
|
+
Parameters
|
|
194
|
+
----------
|
|
195
|
+
reflectivity : list
|
|
196
|
+
The reflectivity curves for each contrast,
|
|
197
|
+
with the same range as the data
|
|
198
|
+
(``data_range`` in the contrast's ``Data`` object)
|
|
199
|
+
simulation : list
|
|
200
|
+
The reflectivity curves for each contrast,
|
|
201
|
+
which can be a wider range to allow extrapolation
|
|
202
|
+
(``simulation_range`` in the contrast's ``Data`` object).
|
|
203
|
+
shiftedData : list
|
|
204
|
+
The data with scalefactors and background corrections applied.
|
|
205
|
+
backgrounds : list
|
|
206
|
+
The background for each contrast defined over the simulation range.
|
|
207
|
+
resolutions : list
|
|
208
|
+
The resolution for each contrast defined over the simulation range.
|
|
209
|
+
sldProfiles : list
|
|
210
|
+
The SLD profiles for each contrast.
|
|
211
|
+
layers : list
|
|
212
|
+
The array of layer parameter values for each contrast.
|
|
213
|
+
resampledLayers : list
|
|
214
|
+
If resampling is used, the array of layer parameter values for each contrast after resampling has been
|
|
215
|
+
performed.
|
|
216
|
+
calculationResults : CalculationResults
|
|
217
|
+
The chi-squared fit results from the final calculation and fit.
|
|
218
|
+
contrastParams : ContrastParams
|
|
219
|
+
The experimental parameters for the contrasts.
|
|
220
|
+
fitParams : np.ndarray
|
|
221
|
+
The best fit value of the parameter with name ``fitNames[i]``.
|
|
222
|
+
fitNames : list[str]
|
|
223
|
+
The names of the fit parameters, where ``fitNames[i]`` is the name
|
|
224
|
+
of the parameter with value given in ``fitParams[i]``.
|
|
225
|
+
|
|
226
|
+
"""
|
|
227
|
+
|
|
228
|
+
reflectivity: list
|
|
229
|
+
simulation: list
|
|
230
|
+
shiftedData: list
|
|
231
|
+
backgrounds: list
|
|
232
|
+
resolutions: list
|
|
233
|
+
sldProfiles: list
|
|
234
|
+
layers: list
|
|
235
|
+
resampledLayers: list
|
|
236
|
+
calculationResults: CalculationResults
|
|
237
|
+
contrastParams: ContrastParams
|
|
238
|
+
fitParams: np.ndarray
|
|
239
|
+
fitNames: list[str]
|
|
240
|
+
|
|
241
|
+
def __str__(self):
|
|
242
|
+
output = ""
|
|
243
|
+
for key, value in self.__dict__.items():
|
|
244
|
+
output += get_field_string(key, value, 100)
|
|
245
|
+
return output
|
|
246
|
+
|
|
247
|
+
def save(self, filepath: str | Path = "./results.json"):
|
|
248
|
+
"""Save the Results object to a JSON file.
|
|
249
|
+
|
|
250
|
+
Parameters
|
|
251
|
+
----------
|
|
252
|
+
filepath : str or Path
|
|
253
|
+
The path to where the results file will be written.
|
|
254
|
+
"""
|
|
255
|
+
filepath = Path(filepath).with_suffix(".json")
|
|
256
|
+
json_dict = write_core_results_fields(self)
|
|
257
|
+
|
|
258
|
+
filepath.write_text(json.dumps(json_dict))
|
|
259
|
+
|
|
260
|
+
@classmethod
|
|
261
|
+
def load(cls, path: str | Path) -> Union["Results", "BayesResults"]:
|
|
262
|
+
"""Load a Results object from file.
|
|
263
|
+
|
|
264
|
+
Parameters
|
|
265
|
+
----------
|
|
266
|
+
path : str or Path
|
|
267
|
+
The path to the results json file.
|
|
268
|
+
"""
|
|
269
|
+
path = Path(path)
|
|
270
|
+
input_data = path.read_text()
|
|
271
|
+
results_dict = json.loads(input_data)
|
|
272
|
+
|
|
273
|
+
results_dict = read_core_results_fields(results_dict)
|
|
274
|
+
|
|
275
|
+
if all(key in results_dict for key in bayes_results_subclasses):
|
|
276
|
+
results_dict = read_bayes_results_fields(results_dict)
|
|
277
|
+
|
|
278
|
+
return BayesResults(
|
|
279
|
+
reflectivity=results_dict["reflectivity"],
|
|
280
|
+
simulation=results_dict["simulation"],
|
|
281
|
+
shiftedData=results_dict["shiftedData"],
|
|
282
|
+
backgrounds=results_dict["backgrounds"],
|
|
283
|
+
resolutions=results_dict["resolutions"],
|
|
284
|
+
sldProfiles=results_dict["sldProfiles"],
|
|
285
|
+
layers=results_dict["layers"],
|
|
286
|
+
resampledLayers=results_dict["resampledLayers"],
|
|
287
|
+
calculationResults=CalculationResults(**results_dict["calculationResults"]),
|
|
288
|
+
contrastParams=ContrastParams(**results_dict["contrastParams"]),
|
|
289
|
+
fitParams=np.array(results_dict["fitParams"]),
|
|
290
|
+
fitNames=results_dict["fitNames"],
|
|
291
|
+
predictionIntervals=PredictionIntervals(**results_dict["predictionIntervals"]),
|
|
292
|
+
confidenceIntervals=ConfidenceIntervals(**results_dict["confidenceIntervals"]),
|
|
293
|
+
dreamParams=DreamParams(**results_dict["dreamParams"]),
|
|
294
|
+
dreamOutput=DreamOutput(**results_dict["dreamOutput"]),
|
|
295
|
+
nestedSamplerOutput=NestedSamplerOutput(**results_dict["nestedSamplerOutput"]),
|
|
296
|
+
chain=np.array(results_dict["chain"]),
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
else:
|
|
300
|
+
return Results(
|
|
301
|
+
reflectivity=results_dict["reflectivity"],
|
|
302
|
+
simulation=results_dict["simulation"],
|
|
303
|
+
shiftedData=results_dict["shiftedData"],
|
|
304
|
+
backgrounds=results_dict["backgrounds"],
|
|
305
|
+
resolutions=results_dict["resolutions"],
|
|
306
|
+
sldProfiles=results_dict["sldProfiles"],
|
|
307
|
+
layers=results_dict["layers"],
|
|
308
|
+
resampledLayers=results_dict["resampledLayers"],
|
|
309
|
+
calculationResults=CalculationResults(**results_dict["calculationResults"]),
|
|
310
|
+
contrastParams=ContrastParams(**results_dict["contrastParams"]),
|
|
311
|
+
fitParams=np.array(results_dict["fitParams"]),
|
|
312
|
+
fitNames=results_dict["fitNames"],
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
@dataclass
|
|
317
|
+
class PredictionIntervals(RATResult):
|
|
318
|
+
"""The Bayesian prediction intervals for 95% and 65% confidence.
|
|
319
|
+
|
|
320
|
+
For ``reflectivity`` and ``sld``, each list item is an array
|
|
321
|
+
with five rows. The rows represent:
|
|
322
|
+
|
|
323
|
+
- 0: the 5th percentile;
|
|
324
|
+
- 1: the 35th percentile;
|
|
325
|
+
- 2: the mean value of the interval;
|
|
326
|
+
- 3: the 65th percentile;
|
|
327
|
+
- 4: the 95th percentile.
|
|
328
|
+
|
|
329
|
+
Parameters
|
|
330
|
+
----------
|
|
331
|
+
reflectivity : list
|
|
332
|
+
The prediction interval data for reflectivity of each contrast.
|
|
333
|
+
SLD : list
|
|
334
|
+
The prediction interval data for SLD of each contrast.
|
|
335
|
+
sampleChi : np.ndarray
|
|
336
|
+
The value of sumChi at each point of the Markov chain.
|
|
337
|
+
|
|
338
|
+
"""
|
|
339
|
+
|
|
340
|
+
reflectivity: list
|
|
341
|
+
sld: list
|
|
342
|
+
sampleChi: np.ndarray
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@dataclass
|
|
346
|
+
class ConfidenceIntervals(RATResult):
|
|
347
|
+
"""The 65% and 95% confidence intervals for the best fit results.
|
|
348
|
+
|
|
349
|
+
Parameters
|
|
350
|
+
----------
|
|
351
|
+
percentile95 : np.ndarray
|
|
352
|
+
The 95% confidence intervals for each fit parameter.
|
|
353
|
+
percentile65 : np.ndarray
|
|
354
|
+
The 65% confidence intervals for each fit parameter.
|
|
355
|
+
mean : np.ndarray
|
|
356
|
+
The mean values for each fit parameter.
|
|
357
|
+
|
|
358
|
+
"""
|
|
359
|
+
|
|
360
|
+
percentile95: np.ndarray
|
|
361
|
+
percentile65: np.ndarray
|
|
362
|
+
mean: np.ndarray
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
@dataclass
|
|
366
|
+
class DreamParams(RATResult):
|
|
367
|
+
"""The parameters used by the inner DREAM algorithm.
|
|
368
|
+
|
|
369
|
+
Parameters
|
|
370
|
+
----------
|
|
371
|
+
nParams : float
|
|
372
|
+
The number of parameters used by the algorithm.
|
|
373
|
+
nChains : float
|
|
374
|
+
The number of MCMC chains used by the algorithm.
|
|
375
|
+
nGenerations : float
|
|
376
|
+
The number of DE generations calculated per iteration.
|
|
377
|
+
parallel : bool
|
|
378
|
+
Whether the algorithm should run chains in parallel.
|
|
379
|
+
CPU : float
|
|
380
|
+
The number of processor cores used for parallel chains.
|
|
381
|
+
jumpProbability : float
|
|
382
|
+
A probability range for the size of jumps when performing subspace sampling.
|
|
383
|
+
pUnitGamma : float
|
|
384
|
+
The probability that the scaling-down factor of jumps will be ignored
|
|
385
|
+
and a larger jump will be taken for one iteration.
|
|
386
|
+
nCR : float
|
|
387
|
+
The number of crossovers performed each iteration.
|
|
388
|
+
delta : float
|
|
389
|
+
The number of chain mutation pairs proposed each iteration.
|
|
390
|
+
steps : float
|
|
391
|
+
The number of MCMC steps to perform between conversion checks.
|
|
392
|
+
zeta : float
|
|
393
|
+
The ergodicity of the algorithm.
|
|
394
|
+
outlier : str
|
|
395
|
+
What test should be used to detect outliers.
|
|
396
|
+
adaptPCR : bool
|
|
397
|
+
Whether the crossover probability for differential evolution should be
|
|
398
|
+
adapted by the algorithm as it runs.
|
|
399
|
+
thinning : float
|
|
400
|
+
The thinning rate of each Markov chain (to reduce memory intensity)
|
|
401
|
+
epsilon : float
|
|
402
|
+
The cutoff threshold for Approximate Bayesian Computation (if used)
|
|
403
|
+
ABC : bool
|
|
404
|
+
Whether Approximate Bayesian Computation is used.
|
|
405
|
+
IO : bool
|
|
406
|
+
Whether the algorithm should perform IO writes of the model in parallel.
|
|
407
|
+
storeOutput : bool
|
|
408
|
+
Whether output model simulations are performed.
|
|
409
|
+
R : np.ndarray
|
|
410
|
+
An array where row ``i`` is the list of chains
|
|
411
|
+
with which chain ``i`` can mutate.
|
|
412
|
+
|
|
413
|
+
"""
|
|
414
|
+
|
|
415
|
+
nParams: float
|
|
416
|
+
nChains: float
|
|
417
|
+
nGenerations: float
|
|
418
|
+
parallel: bool
|
|
419
|
+
CPU: float
|
|
420
|
+
jumpProbability: float
|
|
421
|
+
pUnitGamma: float
|
|
422
|
+
nCR: float
|
|
423
|
+
delta: float
|
|
424
|
+
steps: float
|
|
425
|
+
zeta: float
|
|
426
|
+
outlier: str
|
|
427
|
+
adaptPCR: bool
|
|
428
|
+
thinning: float
|
|
429
|
+
epsilon: float
|
|
430
|
+
ABC: bool
|
|
431
|
+
IO: bool
|
|
432
|
+
storeOutput: bool
|
|
433
|
+
R: np.ndarray
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
@dataclass
|
|
437
|
+
class DreamOutput(RATResult):
|
|
438
|
+
"""The diagnostic output information from DREAM.
|
|
439
|
+
|
|
440
|
+
Parameters
|
|
441
|
+
----------
|
|
442
|
+
allChains : np.ndarray
|
|
443
|
+
An ``nGenerations`` x ``nParams + 2`` x ``nChains`` size array,
|
|
444
|
+
where ``chain_k = DreamOutput.allChains[:, :, k]``
|
|
445
|
+
is the data of chain ``k`` in the final iteration;
|
|
446
|
+
for generation i of the final iteration, ``chain_k[i, j]`` represents:
|
|
447
|
+
|
|
448
|
+
- the sampled value of parameter ``j`` for ``j in 0:nParams``;
|
|
449
|
+
- the associated log-prior for those sampled values for ``j = nParams + 1``;
|
|
450
|
+
- the associated log-likelihood for those sampled values for ``j = nParams + 2``.
|
|
451
|
+
|
|
452
|
+
outlierChains : np.ndarray
|
|
453
|
+
A two-column array where ``DreamOutput.AR[i, 1]`` is the index of a chain
|
|
454
|
+
and ``DreamOutput.AR[i, 0]`` is the length of that chain when it was removed
|
|
455
|
+
for being an outlier.
|
|
456
|
+
runtime : float
|
|
457
|
+
The runtime of the DREAM algorithm in seconds.
|
|
458
|
+
iteration : float
|
|
459
|
+
The number of iterations performed.
|
|
460
|
+
AR : np.ndarray
|
|
461
|
+
A two-column array where ``DreamOutput.AR[i, 0]`` is an iteration number
|
|
462
|
+
and ``DreamOutput.AR[i, 1]`` is the average acceptance rate of chain step
|
|
463
|
+
proposals for that iteration.
|
|
464
|
+
R_stat : np.ndarray
|
|
465
|
+
An array where ``DreamOutput.R_stat[i, 0]`` is an iteration number and
|
|
466
|
+
``DreamOutput.R_stat[i, j]`` is the convergence statistic for parameter ``j``
|
|
467
|
+
at that iteration (where chains are indexed 1 to ``nParams`` inclusive).
|
|
468
|
+
CR : np.ndarray
|
|
469
|
+
A four-column array where ``DreamOutput.CR[i, 0]`` is an iteration number,
|
|
470
|
+
``and DreamOutput.CR[i, j]`` is the selection probability of the ``j``'th crossover
|
|
471
|
+
value for that iteration.
|
|
472
|
+
|
|
473
|
+
"""
|
|
474
|
+
|
|
475
|
+
allChains: np.ndarray
|
|
476
|
+
outlierChains: np.ndarray
|
|
477
|
+
runtime: float
|
|
478
|
+
iteration: float
|
|
479
|
+
AR: np.ndarray
|
|
480
|
+
R_stat: np.ndarray
|
|
481
|
+
CR: np.ndarray
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
@dataclass
|
|
485
|
+
class NestedSamplerOutput(RATResult):
|
|
486
|
+
"""The output information from the Nested Sampler (ns).
|
|
487
|
+
|
|
488
|
+
Parameters
|
|
489
|
+
----------
|
|
490
|
+
logZ : float
|
|
491
|
+
The natural logarithm of the evidence Z for the parameter values.
|
|
492
|
+
logZErr : float
|
|
493
|
+
The estimated uncertainty in the final value of logZ.
|
|
494
|
+
nestSamples : np.ndarray
|
|
495
|
+
``NestedSamplerOutput.nestSamples[i, j]`` represents the values
|
|
496
|
+
sampled at iteration ``i``, where this value is:
|
|
497
|
+
|
|
498
|
+
- the value sampled for parameter ``j``, for ``j`` in ``0:nParams``,
|
|
499
|
+
- the minimum log-likelihood for ``j = nParams + 1``.
|
|
500
|
+
|
|
501
|
+
postSamples : np.ndarray
|
|
502
|
+
The posterior values at the points sampled in ``NestedSamplerOutput.nestSamples``.
|
|
503
|
+
|
|
504
|
+
"""
|
|
505
|
+
|
|
506
|
+
logZ: float
|
|
507
|
+
logZErr: float
|
|
508
|
+
nestSamples: np.ndarray
|
|
509
|
+
postSamples: np.ndarray
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
@dataclass
|
|
513
|
+
class BayesResults(Results):
|
|
514
|
+
"""The results of a Bayesian RAT calculation.
|
|
515
|
+
|
|
516
|
+
Parameters
|
|
517
|
+
----------
|
|
518
|
+
predictionIntervals : PredictionIntervals
|
|
519
|
+
The prediction intervals.
|
|
520
|
+
confidenceIntervals : ConfidenceIntervals
|
|
521
|
+
The 65% and 95% confidence intervals for the best fit results.
|
|
522
|
+
dreamParams : DreamParams
|
|
523
|
+
The parameters used by DREAM, if relevant.
|
|
524
|
+
dreamOutput : DreamOutput
|
|
525
|
+
The output from DREAM if DREAM was used.
|
|
526
|
+
nestedSamplerOutput : NestedSamplerOutput
|
|
527
|
+
The output from nested sampling if ns was used.
|
|
528
|
+
chain : np.ndarray
|
|
529
|
+
The MCMC chains for each parameter.
|
|
530
|
+
The ``i``'th column of the array contains the chain for parameter ``fitNames[i]``.
|
|
531
|
+
|
|
532
|
+
"""
|
|
533
|
+
|
|
534
|
+
predictionIntervals: PredictionIntervals
|
|
535
|
+
confidenceIntervals: ConfidenceIntervals
|
|
536
|
+
dreamParams: DreamParams
|
|
537
|
+
dreamOutput: DreamOutput
|
|
538
|
+
nestedSamplerOutput: NestedSamplerOutput
|
|
539
|
+
chain: np.ndarray
|
|
540
|
+
|
|
541
|
+
def from_procedure(self) -> Procedures:
|
|
542
|
+
"""Return the procedure that created the result.
|
|
543
|
+
|
|
544
|
+
Returns
|
|
545
|
+
-------
|
|
546
|
+
procedure: Procedures
|
|
547
|
+
The procedure that created the result.
|
|
548
|
+
"""
|
|
549
|
+
samples = self.nestedSamplerOutput.nestSamples
|
|
550
|
+
if samples.shape == (1, 2) and not np.any(samples):
|
|
551
|
+
return Procedures.DREAM
|
|
552
|
+
return Procedures.NS
|
|
553
|
+
|
|
554
|
+
def save(self, filepath: str | Path = "./results.json"):
|
|
555
|
+
"""Save the BayesResults object to a JSON file.
|
|
556
|
+
|
|
557
|
+
Parameters
|
|
558
|
+
----------
|
|
559
|
+
filepath : str or Path
|
|
560
|
+
The path to where the results file will be written.
|
|
561
|
+
"""
|
|
562
|
+
filepath = Path(filepath).with_suffix(".json")
|
|
563
|
+
json_dict = write_core_results_fields(self)
|
|
564
|
+
|
|
565
|
+
# Take each of the subclasses in a BayesResults instance and switch the numpy arrays to lists
|
|
566
|
+
for subclass_name in bayes_results_subclasses:
|
|
567
|
+
subclass = getattr(self, subclass_name)
|
|
568
|
+
subclass_dict = {}
|
|
569
|
+
|
|
570
|
+
for field in bayes_results_fields["param_fields"][subclass_name]:
|
|
571
|
+
subclass_dict[field] = getattr(subclass, field)
|
|
572
|
+
|
|
573
|
+
for field in bayes_results_fields["list_fields"][subclass_name]:
|
|
574
|
+
subclass_dict[field] = [result_array.tolist() for result_array in getattr(subclass, field)]
|
|
575
|
+
|
|
576
|
+
for field in bayes_results_fields["double_list_fields"][subclass_name]:
|
|
577
|
+
subclass_dict[field] = [
|
|
578
|
+
[result_array.tolist() for result_array in inner_list] for inner_list in getattr(subclass, field)
|
|
579
|
+
]
|
|
580
|
+
|
|
581
|
+
for field in bayes_results_fields["array_fields"][subclass_name]:
|
|
582
|
+
subclass_dict[field] = getattr(subclass, field).tolist()
|
|
583
|
+
|
|
584
|
+
json_dict[subclass_name] = subclass_dict
|
|
585
|
+
|
|
586
|
+
json_dict["chain"] = self.chain.tolist()
|
|
587
|
+
filepath.write_text(json.dumps(json_dict))
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def write_core_results_fields(results: Results | BayesResults, json_dict: dict | None = None) -> dict:
|
|
591
|
+
"""Modify the values of the fields that appear in both Results and BayesResults when saving to a json file.
|
|
592
|
+
|
|
593
|
+
Parameters
|
|
594
|
+
----------
|
|
595
|
+
results: Union[Results, BayesResults]
|
|
596
|
+
The results or BayesResults object we are writing to json.
|
|
597
|
+
json_dict: Optional[dict]
|
|
598
|
+
The dictionary containing the json output.
|
|
599
|
+
|
|
600
|
+
Returns
|
|
601
|
+
-------
|
|
602
|
+
json_dict: dict
|
|
603
|
+
The output json dict updated with the fields that appear in both Results and BayesResults.
|
|
604
|
+
"""
|
|
605
|
+
if json_dict is None:
|
|
606
|
+
json_dict = {}
|
|
607
|
+
|
|
608
|
+
for field in results_fields["list_fields"]:
|
|
609
|
+
json_dict[field] = [result_array.tolist() for result_array in getattr(results, field)]
|
|
610
|
+
|
|
611
|
+
for field in results_fields["double_list_fields"]:
|
|
612
|
+
json_dict[field] = [
|
|
613
|
+
[result_array.tolist() for result_array in inner_list] for inner_list in getattr(results, field)
|
|
614
|
+
]
|
|
615
|
+
|
|
616
|
+
json_dict["calculationResults"] = {}
|
|
617
|
+
json_dict["calculationResults"]["chiValues"] = results.calculationResults.chiValues.tolist()
|
|
618
|
+
json_dict["calculationResults"]["sumChi"] = results.calculationResults.sumChi
|
|
619
|
+
|
|
620
|
+
json_dict["contrastParams"] = {}
|
|
621
|
+
for field in results.contrastParams.__dict__:
|
|
622
|
+
json_dict["contrastParams"][field] = getattr(results.contrastParams, field).tolist()
|
|
623
|
+
|
|
624
|
+
json_dict["fitParams"] = results.fitParams.tolist()
|
|
625
|
+
json_dict["fitNames"] = results.fitNames
|
|
626
|
+
|
|
627
|
+
return json_dict
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def read_core_results_fields(results_dict: dict) -> dict:
|
|
631
|
+
"""Modify the values of the fields that appear in both Results and BayesResults when loading a json file.
|
|
632
|
+
|
|
633
|
+
Parameters
|
|
634
|
+
----------
|
|
635
|
+
results_dict: Optional[dict]
|
|
636
|
+
The dictionary containing the json input.
|
|
637
|
+
|
|
638
|
+
Returns
|
|
639
|
+
-------
|
|
640
|
+
results_dict: dict
|
|
641
|
+
The input json dict with the fields that appear in both Results and BayesResults converted to numpy arrays
|
|
642
|
+
where necessary.
|
|
643
|
+
"""
|
|
644
|
+
for field in results_fields["list_fields"]:
|
|
645
|
+
results_dict[field] = [np.array(result_array) for result_array in results_dict[field]]
|
|
646
|
+
|
|
647
|
+
for field in results_fields["double_list_fields"]:
|
|
648
|
+
results_dict[field] = [
|
|
649
|
+
[np.array(result_array) for result_array in inner_list] for inner_list in results_dict[field]
|
|
650
|
+
]
|
|
651
|
+
|
|
652
|
+
results_dict["calculationResults"]["chiValues"] = np.array(results_dict["calculationResults"]["chiValues"])
|
|
653
|
+
|
|
654
|
+
for field in results_dict["contrastParams"]:
|
|
655
|
+
results_dict["contrastParams"][field] = np.array(results_dict["contrastParams"][field])
|
|
656
|
+
|
|
657
|
+
return results_dict
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def read_bayes_results_fields(results_dict: dict) -> dict:
|
|
661
|
+
"""Modify the values of the fields that appear only in BayesResults when loading a json file.
|
|
662
|
+
|
|
663
|
+
Parameters
|
|
664
|
+
----------
|
|
665
|
+
results_dict: Optional[dict]
|
|
666
|
+
The dictionary containing the json input.
|
|
667
|
+
|
|
668
|
+
Returns
|
|
669
|
+
-------
|
|
670
|
+
results_dict: dict
|
|
671
|
+
The input json dict with the fields that appear in both Results and BayesResults converted to numpy arrays
|
|
672
|
+
where necessary.
|
|
673
|
+
"""
|
|
674
|
+
for subclass_name in bayes_results_subclasses:
|
|
675
|
+
subclass_dict = {}
|
|
676
|
+
|
|
677
|
+
for field in bayes_results_fields["param_fields"][subclass_name]:
|
|
678
|
+
subclass_dict[field] = results_dict[subclass_name][field]
|
|
679
|
+
|
|
680
|
+
for field in bayes_results_fields["list_fields"][subclass_name]:
|
|
681
|
+
subclass_dict[field] = [np.array(result_array) for result_array in results_dict[subclass_name][field]]
|
|
682
|
+
|
|
683
|
+
for field in bayes_results_fields["double_list_fields"][subclass_name]:
|
|
684
|
+
subclass_dict[field] = [
|
|
685
|
+
[np.array(result_array) for result_array in inner_list]
|
|
686
|
+
for inner_list in results_dict[subclass_name][field]
|
|
687
|
+
]
|
|
688
|
+
|
|
689
|
+
for field in bayes_results_fields["array_fields"][subclass_name]:
|
|
690
|
+
subclass_dict[field] = np.array(results_dict[subclass_name][field])
|
|
691
|
+
|
|
692
|
+
results_dict[subclass_name] = subclass_dict
|
|
693
|
+
|
|
694
|
+
return results_dict
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def make_results(
|
|
698
|
+
procedure: Procedures,
|
|
699
|
+
output_results: ratapi.rat_core.OutputResult,
|
|
700
|
+
bayes_results: ratapi.rat_core.OutputBayesResult | None = None,
|
|
701
|
+
) -> Results | BayesResults:
|
|
702
|
+
"""Initialise a python Results or BayesResults object using the outputs from a RAT calculation.
|
|
703
|
+
|
|
704
|
+
Parameters
|
|
705
|
+
----------
|
|
706
|
+
procedure : Procedures
|
|
707
|
+
The procedure used by the calculation.
|
|
708
|
+
output_results : ratapi.rat_core.OutputResult
|
|
709
|
+
The C++ output results from the calculation.
|
|
710
|
+
bayes_results : Optional[ratapi.rat_core.OutputBayesResult]
|
|
711
|
+
The optional extra C++ Bayesian output results from a Bayesian calculation.
|
|
712
|
+
|
|
713
|
+
Returns
|
|
714
|
+
-------
|
|
715
|
+
Results or BayesResults
|
|
716
|
+
A result object containing the results of the calculation, of type
|
|
717
|
+
Results for non-Bayesian procedures and BayesResults for Bayesian procedures.
|
|
718
|
+
|
|
719
|
+
"""
|
|
720
|
+
calculation_results = CalculationResults(
|
|
721
|
+
chiValues=output_results.calculationResults.chiValues,
|
|
722
|
+
sumChi=output_results.calculationResults.sumChi,
|
|
723
|
+
)
|
|
724
|
+
contrast_params = ContrastParams(
|
|
725
|
+
scalefactors=output_results.contrastParams.scalefactors,
|
|
726
|
+
bulkIn=output_results.contrastParams.bulkIn,
|
|
727
|
+
bulkOut=output_results.contrastParams.bulkOut,
|
|
728
|
+
subRoughs=output_results.contrastParams.subRoughs,
|
|
729
|
+
resample=output_results.contrastParams.resample,
|
|
730
|
+
)
|
|
731
|
+
|
|
732
|
+
if procedure in [Procedures.NS, Procedures.DREAM]:
|
|
733
|
+
prediction_intervals = PredictionIntervals(
|
|
734
|
+
reflectivity=bayes_results.predictionIntervals.reflectivity,
|
|
735
|
+
sld=bayes_results.predictionIntervals.sld,
|
|
736
|
+
sampleChi=bayes_results.predictionIntervals.sampleChi,
|
|
737
|
+
)
|
|
738
|
+
|
|
739
|
+
confidence_intervals = ConfidenceIntervals(
|
|
740
|
+
percentile95=bayes_results.confidenceIntervals.percentile95,
|
|
741
|
+
percentile65=bayes_results.confidenceIntervals.percentile65,
|
|
742
|
+
mean=bayes_results.confidenceIntervals.mean,
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
dream_params = DreamParams(
|
|
746
|
+
nParams=bayes_results.dreamParams.nParams,
|
|
747
|
+
nChains=bayes_results.dreamParams.nChains,
|
|
748
|
+
nGenerations=bayes_results.dreamParams.nGenerations,
|
|
749
|
+
parallel=bool(bayes_results.dreamParams.parallel),
|
|
750
|
+
CPU=bayes_results.dreamParams.CPU,
|
|
751
|
+
jumpProbability=bayes_results.dreamParams.jumpProbability,
|
|
752
|
+
pUnitGamma=bayes_results.dreamParams.pUnitGamma,
|
|
753
|
+
nCR=bayes_results.dreamParams.nCR,
|
|
754
|
+
delta=bayes_results.dreamParams.delta,
|
|
755
|
+
steps=bayes_results.dreamParams.steps,
|
|
756
|
+
zeta=bayes_results.dreamParams.zeta,
|
|
757
|
+
outlier=bayes_results.dreamParams.outlier,
|
|
758
|
+
adaptPCR=bool(bayes_results.dreamParams.adaptPCR),
|
|
759
|
+
thinning=bayes_results.dreamParams.thinning,
|
|
760
|
+
epsilon=bayes_results.dreamParams.epsilon,
|
|
761
|
+
ABC=bool(bayes_results.dreamParams.ABC),
|
|
762
|
+
IO=bool(bayes_results.dreamParams.IO),
|
|
763
|
+
storeOutput=bool(bayes_results.dreamParams.storeOutput),
|
|
764
|
+
R=bayes_results.dreamParams.R,
|
|
765
|
+
)
|
|
766
|
+
|
|
767
|
+
dream_output = DreamOutput(
|
|
768
|
+
allChains=bayes_results.dreamOutput.allChains,
|
|
769
|
+
outlierChains=bayes_results.dreamOutput.outlierChains,
|
|
770
|
+
runtime=bayes_results.dreamOutput.runtime,
|
|
771
|
+
iteration=bayes_results.dreamOutput.iteration,
|
|
772
|
+
AR=bayes_results.dreamOutput.AR,
|
|
773
|
+
R_stat=bayes_results.dreamOutput.R_stat,
|
|
774
|
+
CR=bayes_results.dreamOutput.CR,
|
|
775
|
+
)
|
|
776
|
+
|
|
777
|
+
nested_sampler_output = NestedSamplerOutput(
|
|
778
|
+
logZ=bayes_results.nestedSamplerOutput.logZ,
|
|
779
|
+
logZErr=bayes_results.nestedSamplerOutput.logZErr,
|
|
780
|
+
nestSamples=bayes_results.nestedSamplerOutput.nestSamples,
|
|
781
|
+
postSamples=bayes_results.nestedSamplerOutput.postSamples,
|
|
782
|
+
)
|
|
783
|
+
|
|
784
|
+
results = BayesResults(
|
|
785
|
+
reflectivity=output_results.reflectivity,
|
|
786
|
+
simulation=output_results.simulation,
|
|
787
|
+
shiftedData=output_results.shiftedData,
|
|
788
|
+
backgrounds=output_results.backgrounds,
|
|
789
|
+
resolutions=output_results.resolutions,
|
|
790
|
+
sldProfiles=output_results.sldProfiles,
|
|
791
|
+
layers=output_results.layers,
|
|
792
|
+
resampledLayers=output_results.resampledLayers,
|
|
793
|
+
calculationResults=calculation_results,
|
|
794
|
+
contrastParams=contrast_params,
|
|
795
|
+
fitParams=output_results.fitParams,
|
|
796
|
+
fitNames=output_results.fitNames,
|
|
797
|
+
predictionIntervals=prediction_intervals,
|
|
798
|
+
confidenceIntervals=confidence_intervals,
|
|
799
|
+
dreamParams=dream_params,
|
|
800
|
+
dreamOutput=dream_output,
|
|
801
|
+
nestedSamplerOutput=nested_sampler_output,
|
|
802
|
+
chain=bayes_results.chain,
|
|
803
|
+
)
|
|
804
|
+
|
|
805
|
+
else:
|
|
806
|
+
results = Results(
|
|
807
|
+
reflectivity=output_results.reflectivity,
|
|
808
|
+
simulation=output_results.simulation,
|
|
809
|
+
shiftedData=output_results.shiftedData,
|
|
810
|
+
backgrounds=output_results.backgrounds,
|
|
811
|
+
resolutions=output_results.resolutions,
|
|
812
|
+
sldProfiles=output_results.sldProfiles,
|
|
813
|
+
layers=output_results.layers,
|
|
814
|
+
resampledLayers=output_results.resampledLayers,
|
|
815
|
+
calculationResults=calculation_results,
|
|
816
|
+
contrastParams=contrast_params,
|
|
817
|
+
fitParams=output_results.fitParams,
|
|
818
|
+
fitNames=output_results.fitNames,
|
|
819
|
+
)
|
|
820
|
+
|
|
821
|
+
return results
|