RATapi 0.0.0.dev0__cp312-cp312-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 +8 -0
- RATapi/classlist.py +387 -0
- RATapi/controls.py +143 -0
- RATapi/eventManager.dll +0 -0
- RATapi/events.py +70 -0
- RATapi/examples/__init__.py +0 -0
- RATapi/examples/absorption/__init__.py +0 -0
- RATapi/examples/absorption/absorption.py +148 -0
- RATapi/examples/absorption/volume_thiol_bilayer.py +138 -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 +0 -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/domains/__init__.py +0 -0
- RATapi/examples/domains/alloy_domains.py +26 -0
- RATapi/examples/domains/domains_XY_model.py +70 -0
- RATapi/examples/domains/domains_custom_XY.py +69 -0
- RATapi/examples/domains/domains_custom_layers.py +46 -0
- RATapi/examples/domains/domains_standard_layers.py +75 -0
- RATapi/examples/languages/__init__.py +0 -0
- RATapi/examples/languages/custom_bilayer.py +66 -0
- RATapi/examples/languages/run_custom_file_languages.py +41 -0
- RATapi/examples/languages/setup_problem.py +130 -0
- RATapi/examples/non_polarised/DSPC_custom_XY.py +140 -0
- RATapi/examples/non_polarised/DSPC_custom_layers.py +121 -0
- RATapi/examples/non_polarised/DSPC_standard_layers.py +358 -0
- RATapi/examples/non_polarised/__init__.py +0 -0
- RATapi/examples/non_polarised/custom_XY_DSPC.py +137 -0
- RATapi/examples/non_polarised/custom_bilayer_DSPC.py +85 -0
- RATapi/inputs.py +471 -0
- RATapi/models.py +288 -0
- RATapi/outputs.py +218 -0
- RATapi/project.py +659 -0
- RATapi/rat_core.cp312-win_amd64.pyd +0 -0
- RATapi/run.py +35 -0
- RATapi/utils/__init__.py +0 -0
- RATapi/utils/custom_errors.py +42 -0
- RATapi/utils/enums.py +101 -0
- RATapi/utils/plotting.py +211 -0
- RATapi/wrappers.py +115 -0
- RATapi-0.0.0.dev0.dist-info/METADATA +57 -0
- RATapi-0.0.0.dev0.dist-info/RECORD +64 -0
- RATapi-0.0.0.dev0.dist-info/WHEEL +5 -0
- RATapi-0.0.0.dev0.dist-info/top_level.txt +2 -0
- tests/__init__.py +0 -0
- tests/conftest.py +4728 -0
- tests/test_classlist.py +882 -0
- tests/test_controls.py +863 -0
- tests/test_custom_errors.py +49 -0
- tests/test_events.py +61 -0
- tests/test_inputs.py +908 -0
- tests/test_models.py +308 -0
- tests/test_outputs.py +31 -0
- tests/test_plotting.py +167 -0
- tests/test_project.py +1387 -0
- tests/test_run.py +570 -0
- tests/test_wrappers.py +57 -0
- tests/utils.py +171 -0
RATapi/project.py
ADDED
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
"""The project module. Defines and stores all the input data required for reflectivity calculations in RAT."""
|
|
2
|
+
|
|
3
|
+
import collections
|
|
4
|
+
import copy
|
|
5
|
+
import functools
|
|
6
|
+
import os
|
|
7
|
+
from typing import Any, Callable
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from pydantic import BaseModel, ValidationError, ValidationInfo, field_validator, model_validator
|
|
11
|
+
|
|
12
|
+
import RATapi.models
|
|
13
|
+
from RATapi.classlist import ClassList
|
|
14
|
+
from RATapi.utils.custom_errors import custom_pydantic_validation_error
|
|
15
|
+
from RATapi.utils.enums import Calculations, Geometries, LayerModels, Priors, TypeOptions
|
|
16
|
+
|
|
17
|
+
# Map project fields to pydantic models
|
|
18
|
+
model_in_classlist = {
|
|
19
|
+
"parameters": "Parameter",
|
|
20
|
+
"bulk_in": "Parameter",
|
|
21
|
+
"bulk_out": "Parameter",
|
|
22
|
+
"scalefactors": "Parameter",
|
|
23
|
+
"domain_ratios": "Parameter",
|
|
24
|
+
"background_parameters": "Parameter",
|
|
25
|
+
"resolution_parameters": "Parameter",
|
|
26
|
+
"backgrounds": "Background",
|
|
27
|
+
"resolutions": "Resolution",
|
|
28
|
+
"custom_files": "CustomFile",
|
|
29
|
+
"data": "Data",
|
|
30
|
+
"layers": "Layer",
|
|
31
|
+
"domain_contrasts": "DomainContrast",
|
|
32
|
+
"contrasts": "Contrast",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
values_defined_in = {
|
|
36
|
+
"backgrounds.value_1": "background_parameters",
|
|
37
|
+
"backgrounds.value_2": "background_parameters",
|
|
38
|
+
"backgrounds.value_3": "background_parameters",
|
|
39
|
+
"backgrounds.value_4": "background_parameters",
|
|
40
|
+
"backgrounds.value_5": "background_parameters",
|
|
41
|
+
"resolutions.value_1": "resolution_parameters",
|
|
42
|
+
"resolutions.value_2": "resolution_parameters",
|
|
43
|
+
"resolutions.value_3": "resolution_parameters",
|
|
44
|
+
"resolutions.value_4": "resolution_parameters",
|
|
45
|
+
"resolutions.value_5": "resolution_parameters",
|
|
46
|
+
"layers.thickness": "parameters",
|
|
47
|
+
"layers.SLD": "parameters",
|
|
48
|
+
"layers.SLD_real": "parameters",
|
|
49
|
+
"layers.SLD_imaginary": "parameters",
|
|
50
|
+
"layers.roughness": "parameters",
|
|
51
|
+
"contrasts.data": "data",
|
|
52
|
+
"contrasts.background": "backgrounds",
|
|
53
|
+
"contrasts.bulk_in": "bulk_in",
|
|
54
|
+
"contrasts.bulk_out": "bulk_out",
|
|
55
|
+
"contrasts.scalefactor": "scalefactors",
|
|
56
|
+
"contrasts.resolution": "resolutions",
|
|
57
|
+
"contrasts.domain_ratio": "domain_ratios",
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
AllFields = collections.namedtuple("AllFields", ["attribute", "fields"])
|
|
61
|
+
model_names_used_in = {
|
|
62
|
+
"background_parameters": AllFields("backgrounds", ["value_1", "value_2", "value_3", "value_4", "value_5"]),
|
|
63
|
+
"resolution_parameters": AllFields("resolutions", ["value_1", "value_2", "value_3", "value_4", "value_5"]),
|
|
64
|
+
"parameters": AllFields("layers", ["thickness", "SLD", "SLD_real", "SLD_imaginary", "roughness", "hydration"]),
|
|
65
|
+
"data": AllFields("contrasts", ["data"]),
|
|
66
|
+
"backgrounds": AllFields("contrasts", ["background"]),
|
|
67
|
+
"bulk_in": AllFields("contrasts", ["bulk_in"]),
|
|
68
|
+
"bulk_out": AllFields("contrasts", ["bulk_out"]),
|
|
69
|
+
"scalefactors": AllFields("contrasts", ["scalefactor"]),
|
|
70
|
+
"domain_ratios": AllFields("contrasts", ["domain_ratio"]),
|
|
71
|
+
"resolutions": AllFields("contrasts", ["resolution"]),
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
# Note that the order of these parameters is hard-coded into RAT
|
|
75
|
+
parameter_class_lists = [
|
|
76
|
+
"parameters",
|
|
77
|
+
"background_parameters",
|
|
78
|
+
"scalefactors",
|
|
79
|
+
"bulk_in",
|
|
80
|
+
"bulk_out",
|
|
81
|
+
"resolution_parameters",
|
|
82
|
+
"domain_ratios",
|
|
83
|
+
]
|
|
84
|
+
class_lists = [
|
|
85
|
+
*parameter_class_lists,
|
|
86
|
+
"backgrounds",
|
|
87
|
+
"resolutions",
|
|
88
|
+
"custom_files",
|
|
89
|
+
"data",
|
|
90
|
+
"layers",
|
|
91
|
+
"domain_contrasts",
|
|
92
|
+
"contrasts",
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class Project(BaseModel, validate_assignment=True, extra="forbid", arbitrary_types_allowed=True):
|
|
97
|
+
"""Defines the input data for a reflectivity calculation in RAT.
|
|
98
|
+
|
|
99
|
+
This class combines the data defined in each of the pydantic models included in "models.py" into the full set of
|
|
100
|
+
inputs required for a reflectivity calculation.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
name: str = ""
|
|
104
|
+
calculation: Calculations = Calculations.NonPolarised
|
|
105
|
+
model: LayerModels = LayerModels.StandardLayers
|
|
106
|
+
geometry: Geometries = Geometries.AirSubstrate
|
|
107
|
+
absorption: bool = False
|
|
108
|
+
|
|
109
|
+
parameters: ClassList = ClassList()
|
|
110
|
+
|
|
111
|
+
bulk_in: ClassList = ClassList(
|
|
112
|
+
RATapi.models.Parameter(
|
|
113
|
+
name="SLD Air",
|
|
114
|
+
min=0.0,
|
|
115
|
+
value=0.0,
|
|
116
|
+
max=0.0,
|
|
117
|
+
fit=False,
|
|
118
|
+
prior_type=Priors.Uniform,
|
|
119
|
+
mu=0.0,
|
|
120
|
+
sigma=np.inf,
|
|
121
|
+
),
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
bulk_out: ClassList = ClassList(
|
|
125
|
+
RATapi.models.Parameter(
|
|
126
|
+
name="SLD D2O",
|
|
127
|
+
min=6.2e-6,
|
|
128
|
+
value=6.35e-6,
|
|
129
|
+
max=6.35e-6,
|
|
130
|
+
fit=False,
|
|
131
|
+
prior_type=Priors.Uniform,
|
|
132
|
+
mu=0.0,
|
|
133
|
+
sigma=np.inf,
|
|
134
|
+
),
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
scalefactors: ClassList = ClassList(
|
|
138
|
+
RATapi.models.Parameter(
|
|
139
|
+
name="Scalefactor 1",
|
|
140
|
+
min=0.02,
|
|
141
|
+
value=0.23,
|
|
142
|
+
max=0.25,
|
|
143
|
+
fit=False,
|
|
144
|
+
prior_type=Priors.Uniform,
|
|
145
|
+
mu=0.0,
|
|
146
|
+
sigma=np.inf,
|
|
147
|
+
),
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
domain_ratios: ClassList = ClassList(
|
|
151
|
+
RATapi.models.Parameter(
|
|
152
|
+
name="Domain Ratio 1",
|
|
153
|
+
min=0.4,
|
|
154
|
+
value=0.5,
|
|
155
|
+
max=0.6,
|
|
156
|
+
fit=False,
|
|
157
|
+
prior_type=Priors.Uniform,
|
|
158
|
+
mu=0.0,
|
|
159
|
+
sigma=np.inf,
|
|
160
|
+
),
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
background_parameters: ClassList = ClassList(
|
|
164
|
+
RATapi.models.Parameter(
|
|
165
|
+
name="Background Param 1",
|
|
166
|
+
min=1e-7,
|
|
167
|
+
value=1e-6,
|
|
168
|
+
max=1e-5,
|
|
169
|
+
fit=False,
|
|
170
|
+
prior_type=Priors.Uniform,
|
|
171
|
+
mu=0.0,
|
|
172
|
+
sigma=np.inf,
|
|
173
|
+
),
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
backgrounds: ClassList = ClassList(
|
|
177
|
+
RATapi.models.Background(name="Background 1", type=TypeOptions.Constant, value_1="Background Param 1"),
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
resolution_parameters: ClassList = ClassList(
|
|
181
|
+
RATapi.models.Parameter(
|
|
182
|
+
name="Resolution Param 1",
|
|
183
|
+
min=0.01,
|
|
184
|
+
value=0.03,
|
|
185
|
+
max=0.05,
|
|
186
|
+
fit=False,
|
|
187
|
+
prior_type=Priors.Uniform,
|
|
188
|
+
mu=0.0,
|
|
189
|
+
sigma=np.inf,
|
|
190
|
+
),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
resolutions: ClassList = ClassList(
|
|
194
|
+
RATapi.models.Resolution(name="Resolution 1", type=TypeOptions.Constant, value_1="Resolution Param 1"),
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
custom_files: ClassList = ClassList()
|
|
198
|
+
data: ClassList = ClassList()
|
|
199
|
+
layers: ClassList = ClassList()
|
|
200
|
+
domain_contrasts: ClassList = ClassList()
|
|
201
|
+
contrasts: ClassList = ClassList()
|
|
202
|
+
|
|
203
|
+
_all_names: dict
|
|
204
|
+
_contrast_model_field: str
|
|
205
|
+
_protected_parameters: dict
|
|
206
|
+
|
|
207
|
+
@field_validator(
|
|
208
|
+
"parameters",
|
|
209
|
+
"bulk_in",
|
|
210
|
+
"bulk_out",
|
|
211
|
+
"scalefactors",
|
|
212
|
+
"background_parameters",
|
|
213
|
+
"backgrounds",
|
|
214
|
+
"resolution_parameters",
|
|
215
|
+
"resolutions",
|
|
216
|
+
"custom_files",
|
|
217
|
+
"data",
|
|
218
|
+
"layers",
|
|
219
|
+
"domain_contrasts",
|
|
220
|
+
"contrasts",
|
|
221
|
+
)
|
|
222
|
+
@classmethod
|
|
223
|
+
def check_class(cls, value: ClassList, info: ValidationInfo) -> ClassList:
|
|
224
|
+
"""Each of the data fields should be a ClassList of the appropriate model."""
|
|
225
|
+
model_name = model_in_classlist[info.field_name]
|
|
226
|
+
# Correct model name if necessary
|
|
227
|
+
if info.field_name == "layers" and info.data["absorption"]:
|
|
228
|
+
model_name = "AbsorptionLayer"
|
|
229
|
+
if info.field_name == "contrasts" and info.data["calculation"] == Calculations.Domains:
|
|
230
|
+
model_name = "ContrastWithRatio"
|
|
231
|
+
|
|
232
|
+
model = getattr(RATapi.models, model_name)
|
|
233
|
+
if not all(isinstance(element, model) for element in value):
|
|
234
|
+
raise ValueError(f'"{info.field_name}" ClassList contains objects other than "{model_name}"')
|
|
235
|
+
return value
|
|
236
|
+
|
|
237
|
+
def model_post_init(self, __context: Any) -> None:
|
|
238
|
+
"""Initialises the class in the ClassLists for empty data fields, sets protected parameters, gets names of all
|
|
239
|
+
defined parameters, determines the contents of the "model" field in contrasts, and wraps ClassList routines to
|
|
240
|
+
control revalidation.
|
|
241
|
+
"""
|
|
242
|
+
# Ensure all ClassLists have the correct _class_handle defined
|
|
243
|
+
layer_field = self.layers
|
|
244
|
+
if not hasattr(layer_field, "_class_handle"):
|
|
245
|
+
if self.absorption:
|
|
246
|
+
layer_field._class_handle = RATapi.models.AbsorptionLayer
|
|
247
|
+
else:
|
|
248
|
+
layer_field._class_handle = RATapi.models.Layer
|
|
249
|
+
|
|
250
|
+
contrast_field = self.contrasts
|
|
251
|
+
if not hasattr(contrast_field, "_class_handle"):
|
|
252
|
+
if self.calculation == Calculations.Domains:
|
|
253
|
+
contrast_field._class_handle = RATapi.models.ContrastWithRatio
|
|
254
|
+
else:
|
|
255
|
+
contrast_field._class_handle = RATapi.models.Contrast
|
|
256
|
+
|
|
257
|
+
for field_name, model in model_in_classlist.items():
|
|
258
|
+
field = getattr(self, field_name)
|
|
259
|
+
if not hasattr(field, "_class_handle"):
|
|
260
|
+
field._class_handle = getattr(RATapi.models, model)
|
|
261
|
+
|
|
262
|
+
if "Substrate Roughness" not in self.parameters.get_names():
|
|
263
|
+
self.parameters.insert(
|
|
264
|
+
0,
|
|
265
|
+
RATapi.models.ProtectedParameter(
|
|
266
|
+
name="Substrate Roughness",
|
|
267
|
+
min=1.0,
|
|
268
|
+
value=3.0,
|
|
269
|
+
max=5.0,
|
|
270
|
+
fit=True,
|
|
271
|
+
prior_type=RATapi.models.Priors.Uniform,
|
|
272
|
+
mu=0.0,
|
|
273
|
+
sigma=np.inf,
|
|
274
|
+
),
|
|
275
|
+
)
|
|
276
|
+
elif "Substrate Roughness" not in self.get_all_protected_parameters().values():
|
|
277
|
+
# If substrate roughness is included as a standard parameter replace it with a protected parameter
|
|
278
|
+
substrate_roughness_values = self.parameters[self.parameters.index("Substrate Roughness")].model_dump()
|
|
279
|
+
self.parameters.remove("Substrate Roughness")
|
|
280
|
+
self.parameters.insert(0, RATapi.models.ProtectedParameter(**substrate_roughness_values))
|
|
281
|
+
|
|
282
|
+
if "Simulation" not in self.data.get_names():
|
|
283
|
+
self.data.insert(0, RATapi.models.Data(name="Simulation", simulation_range=[0.005, 0.7]))
|
|
284
|
+
|
|
285
|
+
self._all_names = self.get_all_names()
|
|
286
|
+
self._contrast_model_field = self.get_contrast_model_field()
|
|
287
|
+
self._protected_parameters = self.get_all_protected_parameters()
|
|
288
|
+
|
|
289
|
+
# Wrap ClassList routines - when any of these routines are called, the wrapper will force revalidation of the
|
|
290
|
+
# model, handle errors and reset previous values if necessary.
|
|
291
|
+
methods_to_wrap = [
|
|
292
|
+
"_setitem",
|
|
293
|
+
"_delitem",
|
|
294
|
+
"_iadd",
|
|
295
|
+
"append",
|
|
296
|
+
"insert",
|
|
297
|
+
"pop",
|
|
298
|
+
"remove",
|
|
299
|
+
"clear",
|
|
300
|
+
"extend",
|
|
301
|
+
"set_fields",
|
|
302
|
+
]
|
|
303
|
+
|
|
304
|
+
for class_list in class_lists:
|
|
305
|
+
attribute = getattr(self, class_list)
|
|
306
|
+
for methodName in methods_to_wrap:
|
|
307
|
+
setattr(attribute, methodName, self._classlist_wrapper(attribute, getattr(attribute, methodName)))
|
|
308
|
+
|
|
309
|
+
@model_validator(mode="after")
|
|
310
|
+
def set_domain_ratios(self) -> "Project":
|
|
311
|
+
"""If we are not running a domains calculation, ensure the domain_ratios component of the model is empty."""
|
|
312
|
+
if self.calculation != Calculations.Domains:
|
|
313
|
+
self.domain_ratios.data = []
|
|
314
|
+
return self
|
|
315
|
+
|
|
316
|
+
@model_validator(mode="after")
|
|
317
|
+
def set_domain_contrasts(self) -> "Project":
|
|
318
|
+
"""If we are not running a domains calculation with standard layers, ensure the domain_contrasts component of
|
|
319
|
+
the model is empty.
|
|
320
|
+
"""
|
|
321
|
+
if not (self.calculation == Calculations.Domains and self.model == LayerModels.StandardLayers):
|
|
322
|
+
self.domain_contrasts.data = []
|
|
323
|
+
return self
|
|
324
|
+
|
|
325
|
+
@model_validator(mode="after")
|
|
326
|
+
def set_layers(self) -> "Project":
|
|
327
|
+
"""If we are not using a standard layers model, ensure the layers component of the model is empty."""
|
|
328
|
+
if self.model != LayerModels.StandardLayers:
|
|
329
|
+
self.layers.data = []
|
|
330
|
+
return self
|
|
331
|
+
|
|
332
|
+
@model_validator(mode="after")
|
|
333
|
+
def set_calculation(self) -> "Project":
|
|
334
|
+
"""Apply the calc setting to the project."""
|
|
335
|
+
contrast_list = []
|
|
336
|
+
handle = self.contrasts._class_handle.__name__
|
|
337
|
+
if self.calculation == Calculations.Domains and handle == "Contrast":
|
|
338
|
+
for contrast in self.contrasts:
|
|
339
|
+
contrast_list.append(RATapi.models.ContrastWithRatio(**contrast.model_dump()))
|
|
340
|
+
self.contrasts.data = contrast_list
|
|
341
|
+
self.domain_ratios.data = [
|
|
342
|
+
RATapi.models.Parameter(
|
|
343
|
+
name="Domain Ratio 1",
|
|
344
|
+
min=0.4,
|
|
345
|
+
value=0.5,
|
|
346
|
+
max=0.6,
|
|
347
|
+
fit=False,
|
|
348
|
+
prior_type=RATapi.models.Priors.Uniform,
|
|
349
|
+
mu=0.0,
|
|
350
|
+
sigma=np.inf,
|
|
351
|
+
),
|
|
352
|
+
]
|
|
353
|
+
self.contrasts._class_handle = RATapi.models.ContrastWithRatio
|
|
354
|
+
elif self.calculation != Calculations.Domains and handle == "ContrastWithRatio":
|
|
355
|
+
for contrast in self.contrasts:
|
|
356
|
+
contrast_params = contrast.model_dump()
|
|
357
|
+
del contrast_params["domain_ratio"]
|
|
358
|
+
contrast_list.append(RATapi.models.Contrast(**contrast_params))
|
|
359
|
+
self.contrasts.data = contrast_list
|
|
360
|
+
self.contrasts._class_handle = RATapi.models.Contrast
|
|
361
|
+
return self
|
|
362
|
+
|
|
363
|
+
@model_validator(mode="after")
|
|
364
|
+
def set_contrast_model_field(self) -> "Project":
|
|
365
|
+
"""The contents of the "model" field of "contrasts" depend on the values of the "calculation" and "model_type"
|
|
366
|
+
defined in the project. If they have changed, clear the contrast models.
|
|
367
|
+
"""
|
|
368
|
+
model_field = self.get_contrast_model_field()
|
|
369
|
+
if model_field != self._contrast_model_field:
|
|
370
|
+
for contrast in self.contrasts:
|
|
371
|
+
contrast.model = []
|
|
372
|
+
self._contrast_model_field = model_field
|
|
373
|
+
return self
|
|
374
|
+
|
|
375
|
+
@model_validator(mode="after")
|
|
376
|
+
def check_contrast_model_length(self) -> "Project":
|
|
377
|
+
"""Given certain values of the "calculation" and "model" defined in the project, the "model" field of
|
|
378
|
+
"contrasts" may be constrained in its length.
|
|
379
|
+
"""
|
|
380
|
+
if self.model == LayerModels.StandardLayers and self.calculation == Calculations.Domains:
|
|
381
|
+
for contrast in self.contrasts:
|
|
382
|
+
if contrast.model and len(contrast.model) != 2:
|
|
383
|
+
raise ValueError(
|
|
384
|
+
'For a standard layers domains calculation the "model" field of "contrasts" must '
|
|
385
|
+
"contain exactly two values.",
|
|
386
|
+
)
|
|
387
|
+
elif self.model != LayerModels.StandardLayers:
|
|
388
|
+
for contrast in self.contrasts:
|
|
389
|
+
if len(contrast.model) > 1:
|
|
390
|
+
raise ValueError(
|
|
391
|
+
'For a custom model calculation the "model" field of "contrasts" cannot contain '
|
|
392
|
+
"more than one value.",
|
|
393
|
+
)
|
|
394
|
+
return self
|
|
395
|
+
|
|
396
|
+
@model_validator(mode="after")
|
|
397
|
+
def set_absorption(self) -> "Project":
|
|
398
|
+
"""Apply the absorption setting to the project."""
|
|
399
|
+
layer_list = []
|
|
400
|
+
handle = self.layers._class_handle.__name__
|
|
401
|
+
if self.absorption and handle == "Layer":
|
|
402
|
+
for layer in self.layers:
|
|
403
|
+
layer_list.append(RATapi.models.AbsorptionLayer(**layer.model_dump()))
|
|
404
|
+
self.layers.data = layer_list
|
|
405
|
+
self.layers._class_handle = RATapi.models.AbsorptionLayer
|
|
406
|
+
elif not self.absorption and handle == "AbsorptionLayer":
|
|
407
|
+
for layer in self.layers:
|
|
408
|
+
layer_params = layer.model_dump()
|
|
409
|
+
del layer_params["SLD_imaginary"]
|
|
410
|
+
layer_list.append(RATapi.models.Layer(**layer_params))
|
|
411
|
+
self.layers.data = layer_list
|
|
412
|
+
self.layers._class_handle = RATapi.models.Layer
|
|
413
|
+
return self
|
|
414
|
+
|
|
415
|
+
@model_validator(mode="after")
|
|
416
|
+
def update_renamed_models(self) -> "Project":
|
|
417
|
+
"""When models defined in the ClassLists are renamed, we need to update that name elsewhere in the project."""
|
|
418
|
+
for class_list in model_names_used_in:
|
|
419
|
+
old_names = self._all_names[class_list]
|
|
420
|
+
new_names = getattr(self, class_list).get_names()
|
|
421
|
+
if len(old_names) == len(new_names):
|
|
422
|
+
name_diff = [(old, new) for (old, new) in zip(old_names, new_names) if old != new]
|
|
423
|
+
for old_name, new_name in name_diff:
|
|
424
|
+
model_names_list = getattr(self, model_names_used_in[class_list].attribute)
|
|
425
|
+
all_matches = model_names_list.get_all_matches(old_name)
|
|
426
|
+
fields = model_names_used_in[class_list].fields
|
|
427
|
+
for index, field in all_matches:
|
|
428
|
+
if field in fields:
|
|
429
|
+
setattr(model_names_list[index], field, new_name)
|
|
430
|
+
self._all_names = self.get_all_names()
|
|
431
|
+
return self
|
|
432
|
+
|
|
433
|
+
@model_validator(mode="after")
|
|
434
|
+
def cross_check_model_values(self) -> "Project":
|
|
435
|
+
"""Certain model fields should contain values defined elsewhere in the project."""
|
|
436
|
+
value_fields = ["value_1", "value_2", "value_3", "value_4", "value_5"]
|
|
437
|
+
self.check_allowed_values("backgrounds", value_fields, self.background_parameters.get_names())
|
|
438
|
+
self.check_allowed_values("resolutions", value_fields, self.resolution_parameters.get_names())
|
|
439
|
+
self.check_allowed_values(
|
|
440
|
+
"layers",
|
|
441
|
+
["thickness", "SLD", "SLD_real", "SLD_imaginary", "roughness"],
|
|
442
|
+
self.parameters.get_names(),
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
self.check_allowed_values("contrasts", ["data"], self.data.get_names())
|
|
446
|
+
self.check_allowed_values("contrasts", ["background"], self.backgrounds.get_names())
|
|
447
|
+
self.check_allowed_values("contrasts", ["bulk_in"], self.bulk_in.get_names())
|
|
448
|
+
self.check_allowed_values("contrasts", ["bulk_out"], self.bulk_out.get_names())
|
|
449
|
+
self.check_allowed_values("contrasts", ["scalefactor"], self.scalefactors.get_names())
|
|
450
|
+
self.check_allowed_values("contrasts", ["resolution"], self.resolutions.get_names())
|
|
451
|
+
self.check_allowed_values("contrasts", ["domain_ratio"], self.domain_ratios.get_names())
|
|
452
|
+
|
|
453
|
+
self.check_contrast_model_allowed_values(
|
|
454
|
+
"contrasts",
|
|
455
|
+
getattr(self, self._contrast_model_field).get_names(),
|
|
456
|
+
self._contrast_model_field,
|
|
457
|
+
)
|
|
458
|
+
self.check_contrast_model_allowed_values("domain_contrasts", self.layers.get_names(), "layers")
|
|
459
|
+
return self
|
|
460
|
+
|
|
461
|
+
@model_validator(mode="after")
|
|
462
|
+
def check_protected_parameters(self) -> "Project":
|
|
463
|
+
"""Protected parameters should not be deleted. If this is attempted, raise an error."""
|
|
464
|
+
for class_list in parameter_class_lists:
|
|
465
|
+
protected_parameters = [
|
|
466
|
+
param.name for param in getattr(self, class_list) if isinstance(param, RATapi.models.ProtectedParameter)
|
|
467
|
+
]
|
|
468
|
+
# All previously existing protected parameters should be present in new list
|
|
469
|
+
if not all(element in protected_parameters for element in self._protected_parameters[class_list]):
|
|
470
|
+
removed_params = [
|
|
471
|
+
param for param in self._protected_parameters[class_list] if param not in protected_parameters
|
|
472
|
+
]
|
|
473
|
+
raise ValueError(f'Can\'t delete the protected parameters: {", ".join(str(i) for i in removed_params)}')
|
|
474
|
+
self._protected_parameters = self.get_all_protected_parameters()
|
|
475
|
+
return self
|
|
476
|
+
|
|
477
|
+
def __str__(self):
|
|
478
|
+
output = ""
|
|
479
|
+
for key, value in self.__dict__.items():
|
|
480
|
+
if value:
|
|
481
|
+
output += f'{key.replace("_", " ").title() + ": " :-<100}\n\n'
|
|
482
|
+
try:
|
|
483
|
+
output += value.value + "\n\n" # For enums
|
|
484
|
+
except AttributeError:
|
|
485
|
+
output += str(value) + "\n\n"
|
|
486
|
+
return output
|
|
487
|
+
|
|
488
|
+
def get_all_names(self):
|
|
489
|
+
"""Record the names of all models defined in the project."""
|
|
490
|
+
return {class_list: getattr(self, class_list).get_names() for class_list in class_lists}
|
|
491
|
+
|
|
492
|
+
def get_all_protected_parameters(self):
|
|
493
|
+
"""Record the protected parameters defined in the project."""
|
|
494
|
+
return {
|
|
495
|
+
class_list: [
|
|
496
|
+
param.name for param in getattr(self, class_list) if isinstance(param, RATapi.models.ProtectedParameter)
|
|
497
|
+
]
|
|
498
|
+
for class_list in parameter_class_lists
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
def check_allowed_values(self, attribute: str, field_list: list[str], allowed_values: list[str]) -> None:
|
|
502
|
+
"""Check the values of the given fields in the given model are in the supplied list of allowed values.
|
|
503
|
+
|
|
504
|
+
Parameters
|
|
505
|
+
----------
|
|
506
|
+
attribute : str
|
|
507
|
+
The attribute of Project being validated.
|
|
508
|
+
field_list : list [str]
|
|
509
|
+
The fields of the attribute to be checked for valid values.
|
|
510
|
+
allowed_values : list [str]
|
|
511
|
+
The list of allowed values for the fields given in field_list.
|
|
512
|
+
|
|
513
|
+
Raises
|
|
514
|
+
------
|
|
515
|
+
ValueError
|
|
516
|
+
Raised if any field in field_list has a value not specified in allowed_values.
|
|
517
|
+
|
|
518
|
+
"""
|
|
519
|
+
class_list = getattr(self, attribute)
|
|
520
|
+
for model in class_list:
|
|
521
|
+
for field in field_list:
|
|
522
|
+
value = getattr(model, field, "")
|
|
523
|
+
if value and value not in allowed_values:
|
|
524
|
+
raise ValueError(
|
|
525
|
+
f'The value "{value}" in the "{field}" field of "{attribute}" must be defined in '
|
|
526
|
+
f'"{values_defined_in[f"{attribute}.{field}"]}".',
|
|
527
|
+
)
|
|
528
|
+
|
|
529
|
+
def check_contrast_model_allowed_values(
|
|
530
|
+
self,
|
|
531
|
+
contrast_attribute: str,
|
|
532
|
+
allowed_values: list[str],
|
|
533
|
+
allowed_field: str,
|
|
534
|
+
) -> None:
|
|
535
|
+
"""The contents of the "model" field of "contrasts" and "domain_contrasts" must be defined elsewhere in the
|
|
536
|
+
project.
|
|
537
|
+
|
|
538
|
+
Parameters
|
|
539
|
+
----------
|
|
540
|
+
contrast_attribute : str
|
|
541
|
+
The specific contrast attribute of Project being validated (either "contrasts" or "domain_contrasts").
|
|
542
|
+
allowed_values : list [str]
|
|
543
|
+
The list of allowed values for the model of the contrast_attribute.
|
|
544
|
+
allowed_field : str
|
|
545
|
+
The name of the field in the project in which the allowed_values are defined.
|
|
546
|
+
|
|
547
|
+
Raises
|
|
548
|
+
------
|
|
549
|
+
ValueError
|
|
550
|
+
Raised if any model in contrast_attribute has a value not specified in allowed_values.
|
|
551
|
+
|
|
552
|
+
"""
|
|
553
|
+
class_list = getattr(self, contrast_attribute)
|
|
554
|
+
for contrast in class_list:
|
|
555
|
+
model_values = contrast.model
|
|
556
|
+
if model_values and not all(value in allowed_values for value in model_values):
|
|
557
|
+
raise ValueError(
|
|
558
|
+
f'The values: "{", ".join(str(i) for i in model_values)}" in the "model" field of '
|
|
559
|
+
f'"{contrast_attribute}" must be defined in "{allowed_field}".',
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
def get_contrast_model_field(self):
|
|
563
|
+
"""Get the field used to define the contents of the "model" field in contrasts.
|
|
564
|
+
|
|
565
|
+
Returns
|
|
566
|
+
-------
|
|
567
|
+
model_field : str
|
|
568
|
+
The name of the field used to define the contrasts' model field.
|
|
569
|
+
|
|
570
|
+
"""
|
|
571
|
+
if self.model == LayerModels.StandardLayers:
|
|
572
|
+
if self.calculation == Calculations.Domains:
|
|
573
|
+
model_field = "domain_contrasts"
|
|
574
|
+
else:
|
|
575
|
+
model_field = "layers"
|
|
576
|
+
else:
|
|
577
|
+
model_field = "custom_files"
|
|
578
|
+
return model_field
|
|
579
|
+
|
|
580
|
+
def write_script(self, obj_name: str = "problem", script: str = "project_script.py"):
|
|
581
|
+
"""Write a python script that can be run to reproduce this project object.
|
|
582
|
+
|
|
583
|
+
Parameters
|
|
584
|
+
----------
|
|
585
|
+
obj_name : str, optional
|
|
586
|
+
The name given to the project object under construction (default is "problem").
|
|
587
|
+
script : str, optional
|
|
588
|
+
The filepath of the generated script (default is "project_script.py").
|
|
589
|
+
|
|
590
|
+
"""
|
|
591
|
+
# Need to ensure correct format for script name
|
|
592
|
+
file_parts = os.path.splitext(script)
|
|
593
|
+
|
|
594
|
+
if not file_parts[1]:
|
|
595
|
+
script += ".py"
|
|
596
|
+
elif file_parts[1] != ".py":
|
|
597
|
+
raise ValueError('The script name provided to "write_script" must use the ".py" format')
|
|
598
|
+
|
|
599
|
+
indent = 4 * " "
|
|
600
|
+
|
|
601
|
+
with open(script, "w") as f:
|
|
602
|
+
f.write(
|
|
603
|
+
'# THIS FILE IS GENERATED FROM RAT VIA THE "WRITE_SCRIPT" ROUTINE. IT IS NOT PART OF THE RAT CODE.'
|
|
604
|
+
"\n\n",
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
# Need imports
|
|
608
|
+
f.write("import RATapi\nfrom RATapi.models import *\nfrom numpy import array, inf\n\n")
|
|
609
|
+
|
|
610
|
+
f.write(
|
|
611
|
+
f"{obj_name} = RATapi.Project(\n{indent}name='{self.name}', calculation='{self.calculation}',"
|
|
612
|
+
f" model='{self.model}', geometry='{self.geometry}', absorption={self.absorption},\n",
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
for class_list in class_lists:
|
|
616
|
+
contents = getattr(self, class_list).data
|
|
617
|
+
if contents:
|
|
618
|
+
f.write(f"{indent}{class_list}=RATapi.ClassList({contents}),\n")
|
|
619
|
+
f.write(f"{indent})\n")
|
|
620
|
+
|
|
621
|
+
def _classlist_wrapper(self, class_list: ClassList, func: Callable):
|
|
622
|
+
"""Defines the function used to wrap around ClassList routines to force revalidation.
|
|
623
|
+
|
|
624
|
+
Parameters
|
|
625
|
+
----------
|
|
626
|
+
class_list : ClassList
|
|
627
|
+
The ClassList defined in the "Project" model that is being modified.
|
|
628
|
+
func : Callable
|
|
629
|
+
The routine being wrapped.
|
|
630
|
+
|
|
631
|
+
Returns
|
|
632
|
+
-------
|
|
633
|
+
wrapped_func : Callable
|
|
634
|
+
The wrapped routine.
|
|
635
|
+
|
|
636
|
+
"""
|
|
637
|
+
|
|
638
|
+
@functools.wraps(func)
|
|
639
|
+
def wrapped_func(*args, **kwargs):
|
|
640
|
+
"""Run the given function and then revalidate the "Project" model. If any exception is raised, restore
|
|
641
|
+
the previous state of the given ClassList and report details of the exception.
|
|
642
|
+
"""
|
|
643
|
+
previous_state = copy.deepcopy(class_list.data)
|
|
644
|
+
return_value = None
|
|
645
|
+
try:
|
|
646
|
+
return_value = func(*args, **kwargs)
|
|
647
|
+
Project.model_validate(self)
|
|
648
|
+
except ValidationError as exc:
|
|
649
|
+
class_list.data = previous_state
|
|
650
|
+
custom_error_list = custom_pydantic_validation_error(exc.errors())
|
|
651
|
+
raise ValidationError.from_exception_data(exc.title, custom_error_list) from None
|
|
652
|
+
except (TypeError, ValueError):
|
|
653
|
+
class_list.data = previous_state
|
|
654
|
+
raise
|
|
655
|
+
finally:
|
|
656
|
+
del previous_state
|
|
657
|
+
return return_value
|
|
658
|
+
|
|
659
|
+
return wrapped_func
|
|
Binary file
|