RATapi 0.0.0.dev2__tar.gz → 0.0.0.dev3__tar.gz
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-0.0.0.dev2 → RATapi-0.0.0.dev3}/PKG-INFO +2 -1
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/classlist.py +140 -44
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/controls.py +33 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/inputs.py +52 -14
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/models.py +24 -2
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/outputs.py +0 -4
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/project.py +206 -92
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/run.py +2 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/utils/convert.py +74 -2
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/utils/plotting.py +67 -27
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi.egg-info/PKG-INFO +2 -1
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi.egg-info/requires.txt +3 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/cpp/rat.cpp +6 -11
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/setup.py +2 -1
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/MANIFEST.in +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/events.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/absorption/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/absorption/absorption.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/absorption/volume_thiol_bilayer.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/convert_rascal_project/Model_IIb.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/convert_rascal_project/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/convert_rascal_project/convert_rascal.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/D2O_spin_down.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/D2O_spin_up.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/DSPC_D2O.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/DSPC_SMW.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/H2O_spin_down.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/H2O_spin_up.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/c_PLP0016596.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/c_PLP0016601.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/data/c_PLP0016607.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/domains/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/domains/alloy_domains.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/domains/domains_XY_model.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/domains/domains_custom_XY.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/domains/domains_custom_layers.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/domains/domains_standard_layers.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/languages/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/languages/custom_bilayer.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/languages/run_custom_file_languages.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/languages/setup_problem.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/DSPC_custom_XY.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/DSPC_custom_layers.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/DSPC_standard_layers.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/custom_XY_DSPC.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/custom_bilayer_DSPC.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/utils/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/utils/custom_errors.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/utils/enums.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi/wrappers.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi.egg-info/SOURCES.txt +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi.egg-info/dependency_links.txt +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi.egg-info/not-zip-safe +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/RATapi.egg-info/top_level.txt +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/README.md +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/pyproject.toml +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev3}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: RATapi
|
|
3
|
-
Version: 0.0.0.
|
|
3
|
+
Version: 0.0.0.dev3
|
|
4
4
|
Summary: Python extension for the Reflectivity Analysis Toolbox (RAT)
|
|
5
5
|
Home-page: https://github.com/RascalSoftware/python-RAT
|
|
6
6
|
Author:
|
|
@@ -16,6 +16,7 @@ Provides-Extra: Matlab_2022a
|
|
|
16
16
|
Provides-Extra: Matlab_2022b
|
|
17
17
|
Provides-Extra: Matlab_2023a
|
|
18
18
|
Provides-Extra: Matlab_2023b
|
|
19
|
+
Provides-Extra: Matlab_2024a
|
|
19
20
|
Provides-Extra: Matlab_latest
|
|
20
21
|
|
|
21
22
|
python-RAT
|
|
@@ -5,14 +5,16 @@ class.
|
|
|
5
5
|
import collections
|
|
6
6
|
import contextlib
|
|
7
7
|
import warnings
|
|
8
|
-
from collections.abc import
|
|
9
|
-
from typing import Any, Union
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from typing import Any, Generic, TypeVar, Union
|
|
10
10
|
|
|
11
11
|
import numpy as np
|
|
12
12
|
import prettytable
|
|
13
13
|
|
|
14
|
+
T = TypeVar("T")
|
|
14
15
|
|
|
15
|
-
|
|
16
|
+
|
|
17
|
+
class ClassList(collections.UserList, Generic[T]):
|
|
16
18
|
"""List of instances of a particular class.
|
|
17
19
|
|
|
18
20
|
This class subclasses collections.UserList to construct a list intended to store ONLY instances of a particular
|
|
@@ -30,14 +32,14 @@ class ClassList(collections.UserList):
|
|
|
30
32
|
|
|
31
33
|
Parameters
|
|
32
34
|
----------
|
|
33
|
-
init_list : Sequence [
|
|
35
|
+
init_list : Sequence [T] or T, optional
|
|
34
36
|
An instance, or list of instance(s), of the class to be used in this ClassList.
|
|
35
37
|
name_field : str, optional
|
|
36
38
|
The field used to define unique objects in the ClassList (default is "name").
|
|
37
39
|
|
|
38
40
|
"""
|
|
39
41
|
|
|
40
|
-
def __init__(self, init_list: Union[Sequence[
|
|
42
|
+
def __init__(self, init_list: Union[Sequence[T], T] = None, name_field: str = "name") -> None:
|
|
41
43
|
self.name_field = name_field
|
|
42
44
|
|
|
43
45
|
# Set input as list if necessary
|
|
@@ -81,23 +83,23 @@ class ClassList(collections.UserList):
|
|
|
81
83
|
output = str(self.data)
|
|
82
84
|
return output
|
|
83
85
|
|
|
84
|
-
def __getitem__(self, index: Union[int, slice, str,
|
|
86
|
+
def __getitem__(self, index: Union[int, slice, str, T]) -> T:
|
|
85
87
|
"""Get an item by its index, name, a slice, or the object itself."""
|
|
86
88
|
if isinstance(index, (int, slice)):
|
|
87
89
|
return self.data[index]
|
|
88
|
-
elif isinstance(index, (str,
|
|
90
|
+
elif isinstance(index, (str, self._class_handle)):
|
|
89
91
|
return self.data[self.index(index)]
|
|
90
92
|
else:
|
|
91
93
|
raise IndexError("ClassLists can only be indexed by integers, slices, name strings, or objects.")
|
|
92
94
|
|
|
93
|
-
def __setitem__(self, index: int, item:
|
|
95
|
+
def __setitem__(self, index: int, item: T) -> None:
|
|
94
96
|
"""Replace the object at an existing index of the ClassList."""
|
|
95
97
|
self._setitem(index, item)
|
|
96
98
|
|
|
97
|
-
def _setitem(self, index: int, item:
|
|
99
|
+
def _setitem(self, index: int, item: T) -> None:
|
|
98
100
|
"""Auxiliary routine of "__setitem__" used to enable wrapping."""
|
|
99
|
-
self._check_classes(
|
|
100
|
-
self._check_unique_name_fields(
|
|
101
|
+
self._check_classes([item])
|
|
102
|
+
self._check_unique_name_fields([item])
|
|
101
103
|
self.data[index] = item
|
|
102
104
|
|
|
103
105
|
def __delitem__(self, index: int) -> None:
|
|
@@ -108,18 +110,18 @@ class ClassList(collections.UserList):
|
|
|
108
110
|
"""Auxiliary routine of "__delitem__" used to enable wrapping."""
|
|
109
111
|
del self.data[index]
|
|
110
112
|
|
|
111
|
-
def __iadd__(self, other: Sequence[
|
|
113
|
+
def __iadd__(self, other: Sequence[T]) -> "ClassList":
|
|
112
114
|
"""Define in-place addition using the "+=" operator."""
|
|
113
115
|
return self._iadd(other)
|
|
114
116
|
|
|
115
|
-
def _iadd(self, other: Sequence[
|
|
117
|
+
def _iadd(self, other: Sequence[T]) -> "ClassList":
|
|
116
118
|
"""Auxiliary routine of "__iadd__" used to enable wrapping."""
|
|
117
119
|
if other and not (isinstance(other, Sequence) and not isinstance(other, str)):
|
|
118
120
|
other = [other]
|
|
119
121
|
if not hasattr(self, "_class_handle"):
|
|
120
122
|
self._class_handle = self._determine_class_handle(self + other)
|
|
121
|
-
self._check_classes(
|
|
122
|
-
self._check_unique_name_fields(
|
|
123
|
+
self._check_classes(other)
|
|
124
|
+
self._check_unique_name_fields(other)
|
|
123
125
|
super().__iadd__(other)
|
|
124
126
|
return self
|
|
125
127
|
|
|
@@ -135,13 +137,13 @@ class ClassList(collections.UserList):
|
|
|
135
137
|
"""Define in-place multiplication using the "*=" operator."""
|
|
136
138
|
raise TypeError(f"unsupported operand type(s) for *=: '{self.__class__.__name__}' and '{n.__class__.__name__}'")
|
|
137
139
|
|
|
138
|
-
def append(self, obj:
|
|
140
|
+
def append(self, obj: T = None, **kwargs) -> None:
|
|
139
141
|
"""Append a new object to the ClassList using either the object itself, or keyword arguments to set attribute
|
|
140
142
|
values.
|
|
141
143
|
|
|
142
144
|
Parameters
|
|
143
145
|
----------
|
|
144
|
-
obj :
|
|
146
|
+
obj : T, optional
|
|
145
147
|
An instance of the class specified by self._class_handle.
|
|
146
148
|
**kwargs : dict[str, Any], optional
|
|
147
149
|
The input keyword arguments for a new object in the ClassList.
|
|
@@ -168,8 +170,8 @@ class ClassList(collections.UserList):
|
|
|
168
170
|
if obj:
|
|
169
171
|
if not hasattr(self, "_class_handle"):
|
|
170
172
|
self._class_handle = type(obj)
|
|
171
|
-
self._check_classes(
|
|
172
|
-
self._check_unique_name_fields(
|
|
173
|
+
self._check_classes([obj])
|
|
174
|
+
self._check_unique_name_fields([obj])
|
|
173
175
|
self.data.append(obj)
|
|
174
176
|
else:
|
|
175
177
|
if not hasattr(self, "_class_handle"):
|
|
@@ -180,7 +182,7 @@ class ClassList(collections.UserList):
|
|
|
180
182
|
self._validate_name_field(kwargs)
|
|
181
183
|
self.data.append(self._class_handle(**kwargs))
|
|
182
184
|
|
|
183
|
-
def insert(self, index: int, obj:
|
|
185
|
+
def insert(self, index: int, obj: T = None, **kwargs) -> None:
|
|
184
186
|
"""Insert a new object into the ClassList at a given index using either the object itself, or keyword arguments
|
|
185
187
|
to set attribute values.
|
|
186
188
|
|
|
@@ -188,7 +190,7 @@ class ClassList(collections.UserList):
|
|
|
188
190
|
----------
|
|
189
191
|
index: int
|
|
190
192
|
The index at which to insert a new object in the ClassList.
|
|
191
|
-
obj :
|
|
193
|
+
obj : T, optional
|
|
192
194
|
An instance of the class specified by self._class_handle.
|
|
193
195
|
**kwargs : dict[str, Any], optional
|
|
194
196
|
The input keyword arguments for a new object in the ClassList.
|
|
@@ -215,8 +217,8 @@ class ClassList(collections.UserList):
|
|
|
215
217
|
if obj:
|
|
216
218
|
if not hasattr(self, "_class_handle"):
|
|
217
219
|
self._class_handle = type(obj)
|
|
218
|
-
self._check_classes(
|
|
219
|
-
self._check_unique_name_fields(
|
|
220
|
+
self._check_classes([obj])
|
|
221
|
+
self._check_unique_name_fields([obj])
|
|
220
222
|
self.data.insert(index, obj)
|
|
221
223
|
else:
|
|
222
224
|
if not hasattr(self, "_class_handle"):
|
|
@@ -227,33 +229,33 @@ class ClassList(collections.UserList):
|
|
|
227
229
|
self._validate_name_field(kwargs)
|
|
228
230
|
self.data.insert(index, self._class_handle(**kwargs))
|
|
229
231
|
|
|
230
|
-
def remove(self, item: Union[
|
|
232
|
+
def remove(self, item: Union[T, str]) -> None:
|
|
231
233
|
"""Remove an object from the ClassList using either the object itself or its name_field value."""
|
|
232
234
|
item = self._get_item_from_name_field(item)
|
|
233
235
|
self.data.remove(item)
|
|
234
236
|
|
|
235
|
-
def count(self, item: Union[
|
|
237
|
+
def count(self, item: Union[T, str]) -> int:
|
|
236
238
|
"""Return the number of times an object appears in the ClassList using either the object itself or its
|
|
237
239
|
name_field value.
|
|
238
240
|
"""
|
|
239
241
|
item = self._get_item_from_name_field(item)
|
|
240
242
|
return self.data.count(item)
|
|
241
243
|
|
|
242
|
-
def index(self, item: Union[
|
|
244
|
+
def index(self, item: Union[T, str], offset: bool = False, *args) -> int:
|
|
243
245
|
"""Return the index of a particular object in the ClassList using either the object itself or its
|
|
244
246
|
name_field value. If offset is specified, add one to the index. This is used to account for one-based indexing.
|
|
245
247
|
"""
|
|
246
248
|
item = self._get_item_from_name_field(item)
|
|
247
249
|
return self.data.index(item, *args) + int(offset)
|
|
248
250
|
|
|
249
|
-
def extend(self, other: Sequence[
|
|
251
|
+
def extend(self, other: Sequence[T]) -> None:
|
|
250
252
|
"""Extend the ClassList by adding another sequence."""
|
|
251
253
|
if other and not (isinstance(other, Sequence) and not isinstance(other, str)):
|
|
252
254
|
other = [other]
|
|
253
255
|
if not hasattr(self, "_class_handle"):
|
|
254
256
|
self._class_handle = self._determine_class_handle(self + other)
|
|
255
|
-
self._check_classes(
|
|
256
|
-
self._check_unique_name_fields(
|
|
257
|
+
self._check_classes(other)
|
|
258
|
+
self._check_unique_name_fields(other)
|
|
257
259
|
self.data.extend(other)
|
|
258
260
|
|
|
259
261
|
def set_fields(self, index: int, **kwargs) -> None:
|
|
@@ -312,13 +314,14 @@ class ClassList(collections.UserList):
|
|
|
312
314
|
"""
|
|
313
315
|
names = [name.lower() for name in self.get_names()]
|
|
314
316
|
with contextlib.suppress(KeyError):
|
|
315
|
-
|
|
317
|
+
name = input_args[self.name_field].lower()
|
|
318
|
+
if name in names:
|
|
316
319
|
raise ValueError(
|
|
317
320
|
f"Input arguments contain the {self.name_field} '{input_args[self.name_field]}', "
|
|
318
|
-
f"which is already specified
|
|
321
|
+
f"which is already specified at index {names.index(name)} of the ClassList",
|
|
319
322
|
)
|
|
320
323
|
|
|
321
|
-
def _check_unique_name_fields(self, input_list:
|
|
324
|
+
def _check_unique_name_fields(self, input_list: Sequence[T]) -> None:
|
|
322
325
|
"""Raise a ValueError if any value of the name_field attribute is used more than once in a list of class
|
|
323
326
|
objects.
|
|
324
327
|
|
|
@@ -333,11 +336,49 @@ class ClassList(collections.UserList):
|
|
|
333
336
|
Raised if the input list defines more than one object with the same value of name_field.
|
|
334
337
|
|
|
335
338
|
"""
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
+
error_list = []
|
|
340
|
+
try:
|
|
341
|
+
existing_names = [name.lower() for name in self.get_names()]
|
|
342
|
+
except AttributeError:
|
|
343
|
+
existing_names = []
|
|
344
|
+
|
|
345
|
+
new_names = [getattr(model, self.name_field).lower() for model in input_list if hasattr(model, self.name_field)]
|
|
346
|
+
full_names = existing_names + new_names
|
|
347
|
+
|
|
348
|
+
# There are duplicate names if this test fails
|
|
349
|
+
if len(set(full_names)) != len(full_names):
|
|
350
|
+
unique_names = [*dict.fromkeys(new_names)]
|
|
351
|
+
|
|
352
|
+
for name in unique_names:
|
|
353
|
+
existing_indices = [i for i, other_name in enumerate(existing_names) if other_name == name]
|
|
354
|
+
new_indices = [i for i, other_name in enumerate(new_names) if other_name == name]
|
|
355
|
+
if (len(existing_indices) + len(new_indices)) > 1:
|
|
356
|
+
existing_string = ""
|
|
357
|
+
new_string = ""
|
|
358
|
+
if existing_indices:
|
|
359
|
+
existing_list = ", ".join(str(i) for i in existing_indices[:-1])
|
|
360
|
+
existing_string = (
|
|
361
|
+
f" item{f's {existing_list} and ' if existing_list else ' '}"
|
|
362
|
+
f"{existing_indices[-1]} of the existing ClassList"
|
|
363
|
+
)
|
|
364
|
+
if new_indices:
|
|
365
|
+
new_list = ", ".join(str(i) for i in new_indices[:-1])
|
|
366
|
+
new_string = (
|
|
367
|
+
f" item{f's {new_list} and ' if new_list else ' '}" f"{new_indices[-1]} of the input list"
|
|
368
|
+
)
|
|
369
|
+
error_list.append(
|
|
370
|
+
f" '{name}' is shared between{existing_string}"
|
|
371
|
+
f"{', and' if existing_string and new_string else ''}{new_string}"
|
|
372
|
+
)
|
|
339
373
|
|
|
340
|
-
|
|
374
|
+
if error_list:
|
|
375
|
+
newline = "\n"
|
|
376
|
+
raise ValueError(
|
|
377
|
+
f"The value of the '{self.name_field}' attribute must be unique for each item in the ClassList:\n"
|
|
378
|
+
f"{newline.join(error for error in error_list)}"
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
def _check_classes(self, input_list: Sequence[T]) -> None:
|
|
341
382
|
"""Raise a ValueError if any object in a list of objects is not of the type specified by self._class_handle.
|
|
342
383
|
|
|
343
384
|
Parameters
|
|
@@ -348,23 +389,31 @@ class ClassList(collections.UserList):
|
|
|
348
389
|
Raises
|
|
349
390
|
------
|
|
350
391
|
ValueError
|
|
351
|
-
Raised if the input list
|
|
392
|
+
Raised if the input list contains objects of any type other than that given in self._class_handle.
|
|
352
393
|
|
|
353
394
|
"""
|
|
354
|
-
|
|
355
|
-
|
|
395
|
+
error_list = []
|
|
396
|
+
for i, element in enumerate(input_list):
|
|
397
|
+
if not isinstance(element, self._class_handle):
|
|
398
|
+
error_list.append(f" index {i} is of type {type(element).__name__}")
|
|
399
|
+
if error_list:
|
|
400
|
+
newline = "\n"
|
|
401
|
+
raise ValueError(
|
|
402
|
+
f"This ClassList only supports elements of type {self._class_handle.__name__}. "
|
|
403
|
+
f"In the input list:\n{newline.join(error for error in error_list)}\n"
|
|
404
|
+
)
|
|
356
405
|
|
|
357
|
-
def _get_item_from_name_field(self, value: Union[
|
|
406
|
+
def _get_item_from_name_field(self, value: Union[T, str]) -> Union[T, str]:
|
|
358
407
|
"""Return the object with the given value of the name_field attribute in the ClassList.
|
|
359
408
|
|
|
360
409
|
Parameters
|
|
361
410
|
----------
|
|
362
|
-
value :
|
|
411
|
+
value : T or str
|
|
363
412
|
Either an object in the ClassList, or the value of the name_field attribute of an object in the ClassList.
|
|
364
413
|
|
|
365
414
|
Returns
|
|
366
415
|
-------
|
|
367
|
-
instance :
|
|
416
|
+
instance : T or str
|
|
368
417
|
Either the object with the value of the name_field attribute given by value, or the input value if an
|
|
369
418
|
object with that value of the name_field attribute cannot be found.
|
|
370
419
|
|
|
@@ -377,9 +426,9 @@ class ClassList(collections.UserList):
|
|
|
377
426
|
return next((model for model in self.data if getattr(model, self.name_field).lower() == lower_value), value)
|
|
378
427
|
|
|
379
428
|
@staticmethod
|
|
380
|
-
def _determine_class_handle(input_list: Sequence[
|
|
429
|
+
def _determine_class_handle(input_list: Sequence[T]):
|
|
381
430
|
"""When inputting a sequence of object to a ClassList, the _class_handle should be set as the type of the
|
|
382
|
-
element which satisfies "issubclass" for all
|
|
431
|
+
element which satisfies "issubclass" for all the other elements.
|
|
383
432
|
|
|
384
433
|
Parameters
|
|
385
434
|
----------
|
|
@@ -401,3 +450,50 @@ class ClassList(collections.UserList):
|
|
|
401
450
|
class_handle = type(input_list[0])
|
|
402
451
|
|
|
403
452
|
return class_handle
|
|
453
|
+
|
|
454
|
+
# Pydantic core schema which allows ClassLists to be validated
|
|
455
|
+
# in short: it validates that each ClassList is indeed a ClassList,
|
|
456
|
+
# and then validates ClassList.data as though it were a typed list
|
|
457
|
+
# e.g. ClassList[str] data is validated like list[str]
|
|
458
|
+
@classmethod
|
|
459
|
+
def __get_pydantic_core_schema__(cls, source: Any, handler):
|
|
460
|
+
# import here so that the ClassList can be instantiated and used without Pydantic installed
|
|
461
|
+
from pydantic import ValidatorFunctionWrapHandler
|
|
462
|
+
from pydantic.types import (
|
|
463
|
+
core_schema, # import core_schema through here rather than making pydantic_core a dependency
|
|
464
|
+
)
|
|
465
|
+
from typing_extensions import get_args, get_origin
|
|
466
|
+
|
|
467
|
+
# if annotated with a class, get the item type of that class
|
|
468
|
+
origin = get_origin(source)
|
|
469
|
+
item_tp = Any if origin is None else get_args(source)[0]
|
|
470
|
+
|
|
471
|
+
list_schema = handler.generate_schema(list[item_tp])
|
|
472
|
+
|
|
473
|
+
def coerce(v: Any, handler: ValidatorFunctionWrapHandler) -> ClassList[T]:
|
|
474
|
+
"""If a sequence is given, try to coerce it to a ClassList."""
|
|
475
|
+
if isinstance(v, Sequence):
|
|
476
|
+
classlist = ClassList()
|
|
477
|
+
if len(v) > 0 and isinstance(v[0], dict):
|
|
478
|
+
# we want to be OK if the type is a model and is passed as a dict;
|
|
479
|
+
# pydantic will coerce it or fall over later
|
|
480
|
+
classlist._class_handle = dict
|
|
481
|
+
elif item_tp is not Any:
|
|
482
|
+
classlist._class_handle = item_tp
|
|
483
|
+
classlist.extend(v)
|
|
484
|
+
v = classlist
|
|
485
|
+
v = handler(v)
|
|
486
|
+
return v
|
|
487
|
+
|
|
488
|
+
def validate_items(v: ClassList[T], handler: ValidatorFunctionWrapHandler) -> ClassList[T]:
|
|
489
|
+
v.data = handler(v.data)
|
|
490
|
+
return v
|
|
491
|
+
|
|
492
|
+
schema = core_schema.chain_schema(
|
|
493
|
+
[
|
|
494
|
+
core_schema.no_info_wrap_validator_function(coerce, core_schema.is_instance_schema(cls)),
|
|
495
|
+
core_schema.no_info_wrap_validator_function(validate_items, list_schema),
|
|
496
|
+
],
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
return schema
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import os
|
|
3
|
+
import tempfile
|
|
1
4
|
import warnings
|
|
2
5
|
|
|
3
6
|
import prettytable
|
|
@@ -70,6 +73,8 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
|
|
|
70
73
|
pUnitGamma: float = Field(0.2, gt=0.0, lt=1.0)
|
|
71
74
|
boundHandling: BoundHandling = BoundHandling.Reflect
|
|
72
75
|
adaptPCR: bool = True
|
|
76
|
+
# Private field for IPC file
|
|
77
|
+
_IPCFilePath: str = ""
|
|
73
78
|
|
|
74
79
|
@model_validator(mode="wrap")
|
|
75
80
|
def warn_setting_incorrect_properties(self, handler: ValidatorFunctionWrapHandler) -> "Controls":
|
|
@@ -131,3 +136,31 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
|
|
|
131
136
|
table.field_names = ["Property", "Value"]
|
|
132
137
|
table.add_rows([[k, v] for k, v in self.model_dump().items()])
|
|
133
138
|
return table.get_string()
|
|
139
|
+
|
|
140
|
+
def initialise_IPC(self):
|
|
141
|
+
"""Setup the inter-process communication file."""
|
|
142
|
+
IPC_obj, self._IPCFilePath = tempfile.mkstemp()
|
|
143
|
+
os.write(IPC_obj, b"0")
|
|
144
|
+
os.close(IPC_obj)
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
def sendStopEvent(self):
|
|
148
|
+
"""Sends the stop event via the inter-process communication file.
|
|
149
|
+
|
|
150
|
+
Warnings
|
|
151
|
+
--------
|
|
152
|
+
UserWarning
|
|
153
|
+
Raised if we try to delete an IPC file that was not initialised.
|
|
154
|
+
"""
|
|
155
|
+
if os.path.isfile(self._IPCFilePath):
|
|
156
|
+
with open(self._IPCFilePath, "wb") as f:
|
|
157
|
+
f.write(b"1")
|
|
158
|
+
else:
|
|
159
|
+
warnings.warn("An IPC file was not initialised.", UserWarning, stacklevel=2)
|
|
160
|
+
return None
|
|
161
|
+
|
|
162
|
+
def delete_IPC(self):
|
|
163
|
+
"""Delete the inter-process communication file."""
|
|
164
|
+
with contextlib.suppress(FileNotFoundError):
|
|
165
|
+
os.remove(self._IPCFilePath)
|
|
166
|
+
return None
|
|
@@ -279,6 +279,52 @@ def check_indices(problem: ProblemDefinition) -> None:
|
|
|
279
279
|
)
|
|
280
280
|
|
|
281
281
|
|
|
282
|
+
class FileHandles:
|
|
283
|
+
"""Class to defer creation of custom file handles.
|
|
284
|
+
|
|
285
|
+
Parameters
|
|
286
|
+
----------
|
|
287
|
+
files : ClassList[CustomFile]
|
|
288
|
+
A list of custom file models.
|
|
289
|
+
"""
|
|
290
|
+
|
|
291
|
+
def __init__(self, files):
|
|
292
|
+
self.index = 0
|
|
293
|
+
self.files = [*files]
|
|
294
|
+
|
|
295
|
+
def __iter__(self):
|
|
296
|
+
self.index = 0
|
|
297
|
+
return self
|
|
298
|
+
|
|
299
|
+
def get_handle(self, index):
|
|
300
|
+
"""Returns file handle for a given custom file.
|
|
301
|
+
|
|
302
|
+
Parameters
|
|
303
|
+
----------
|
|
304
|
+
index : int
|
|
305
|
+
The index of the custom file.
|
|
306
|
+
|
|
307
|
+
"""
|
|
308
|
+
custom_file = self.files[index]
|
|
309
|
+
full_path = os.path.join(custom_file.path, custom_file.filename)
|
|
310
|
+
if custom_file.language == Languages.Python:
|
|
311
|
+
file_handle = get_python_handle(custom_file.filename, custom_file.function_name, custom_file.path)
|
|
312
|
+
elif custom_file.language == Languages.Matlab:
|
|
313
|
+
file_handle = RATapi.wrappers.MatlabWrapper(full_path).getHandle()
|
|
314
|
+
elif custom_file.language == Languages.Cpp:
|
|
315
|
+
file_handle = RATapi.wrappers.DylibWrapper(full_path, custom_file.function_name).getHandle()
|
|
316
|
+
|
|
317
|
+
return file_handle
|
|
318
|
+
|
|
319
|
+
def __next__(self):
|
|
320
|
+
if self.index < len(self.files):
|
|
321
|
+
custom_file = self.get_handle(self.index)
|
|
322
|
+
self.index += 1
|
|
323
|
+
return custom_file
|
|
324
|
+
else:
|
|
325
|
+
raise StopIteration
|
|
326
|
+
|
|
327
|
+
|
|
282
328
|
def make_cells(project: RATapi.Project) -> Cells:
|
|
283
329
|
"""Constructs the cells input required for the compiled RAT code.
|
|
284
330
|
|
|
@@ -344,24 +390,14 @@ def make_cells(project: RATapi.Project) -> Cells:
|
|
|
344
390
|
else:
|
|
345
391
|
simulation_limits.append([0.0, 0.0])
|
|
346
392
|
|
|
347
|
-
file_handles = []
|
|
348
|
-
for custom_file in project.custom_files:
|
|
349
|
-
full_path = os.path.join(custom_file.path, custom_file.filename)
|
|
350
|
-
if custom_file.language == Languages.Python:
|
|
351
|
-
file_handles.append(get_python_handle(custom_file.filename, custom_file.function_name, custom_file.path))
|
|
352
|
-
elif custom_file.language == Languages.Matlab:
|
|
353
|
-
file_handles.append(RATapi.wrappers.MatlabWrapper(full_path).getHandle())
|
|
354
|
-
elif custom_file.language == Languages.Cpp:
|
|
355
|
-
file_handles.append(RATapi.wrappers.DylibWrapper(full_path, custom_file.function_name).getHandle())
|
|
356
|
-
|
|
357
393
|
# Populate the set of cells
|
|
358
394
|
cells = Cells()
|
|
359
395
|
cells.f1 = [[0, 1]] * len(project.contrasts) # This is marked as "to do" in RAT
|
|
360
396
|
cells.f2 = all_data
|
|
361
397
|
cells.f3 = data_limits
|
|
362
398
|
cells.f4 = simulation_limits
|
|
363
|
-
cells.f5 = [contrast_model if contrast_model else [
|
|
364
|
-
cells.f6 = layer_details if project.model == LayerModels.StandardLayers else [
|
|
399
|
+
cells.f5 = [contrast_model if contrast_model else [] for contrast_model in contrast_models]
|
|
400
|
+
cells.f6 = layer_details if project.model == LayerModels.StandardLayers else []
|
|
365
401
|
cells.f7 = [param.name for param in project.parameters]
|
|
366
402
|
cells.f8 = [param.name for param in project.background_parameters]
|
|
367
403
|
cells.f9 = [param.name for param in project.scalefactors]
|
|
@@ -369,7 +405,7 @@ def make_cells(project: RATapi.Project) -> Cells:
|
|
|
369
405
|
cells.f11 = [param.name for param in project.bulk_in]
|
|
370
406
|
cells.f12 = [param.name for param in project.bulk_out]
|
|
371
407
|
cells.f13 = [param.name for param in project.resolution_parameters]
|
|
372
|
-
cells.f14 =
|
|
408
|
+
cells.f14 = FileHandles(project.custom_files)
|
|
373
409
|
cells.f15 = [param.type for param in project.backgrounds]
|
|
374
410
|
cells.f16 = [param.type for param in project.resolutions]
|
|
375
411
|
|
|
@@ -381,7 +417,7 @@ def make_cells(project: RATapi.Project) -> Cells:
|
|
|
381
417
|
for domain_contrast in project.domain_contrasts
|
|
382
418
|
]
|
|
383
419
|
cells.f19 = [
|
|
384
|
-
domain_contrast_model if domain_contrast_model else
|
|
420
|
+
domain_contrast_model if domain_contrast_model else [] for domain_contrast_model in domain_contrast_models
|
|
385
421
|
]
|
|
386
422
|
|
|
387
423
|
cells.f20 = [param.name for param in project.domain_ratios]
|
|
@@ -470,4 +506,6 @@ def make_controls(input_controls: RATapi.Controls, checks: Checks) -> Control:
|
|
|
470
506
|
# IPC
|
|
471
507
|
controls.IPCFilePath = ""
|
|
472
508
|
|
|
509
|
+
controls.IPCFilePath = input_controls._IPCFilePath
|
|
510
|
+
|
|
473
511
|
return controls
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""The models module. Contains the pydantic models used by RAT to store project parameters."""
|
|
2
2
|
|
|
3
3
|
import pathlib
|
|
4
|
-
from typing import Any
|
|
4
|
+
from typing import Any
|
|
5
5
|
|
|
6
6
|
import numpy as np
|
|
7
7
|
import prettytable
|
|
@@ -91,6 +91,18 @@ class Contrast(RATModel):
|
|
|
91
91
|
resample: bool = False
|
|
92
92
|
model: list[str] = []
|
|
93
93
|
|
|
94
|
+
@model_validator(mode="before")
|
|
95
|
+
@classmethod
|
|
96
|
+
def domain_ratio_error(cls, data: Any):
|
|
97
|
+
"""If the extra input 'domain_ratio' is given, give a more descriptive error."""
|
|
98
|
+
|
|
99
|
+
if isinstance(data, dict) and data.get("domain_ratio", False):
|
|
100
|
+
raise ValueError(
|
|
101
|
+
"The Contrast class does not support domain ratios. Use the ContrastWithRatio class instead."
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
return data
|
|
105
|
+
|
|
94
106
|
def __str__(self):
|
|
95
107
|
table = prettytable.PrettyTable()
|
|
96
108
|
table.field_names = [key.replace("_", " ") for key in self.__dict__]
|
|
@@ -155,7 +167,7 @@ class CustomFile(RATModel):
|
|
|
155
167
|
filename: str = ""
|
|
156
168
|
function_name: str = ""
|
|
157
169
|
language: Languages = Languages.Python
|
|
158
|
-
path:
|
|
170
|
+
path: pathlib.Path = pathlib.Path(".")
|
|
159
171
|
|
|
160
172
|
def model_post_init(self, __context: Any) -> None:
|
|
161
173
|
"""If a "filename" is supplied but the "function_name" field is not set, the "function_name" should be set to
|
|
@@ -291,6 +303,16 @@ class Layer(RATModel, populate_by_name=True):
|
|
|
291
303
|
hydration: str = ""
|
|
292
304
|
hydrate_with: Hydration = Hydration.BulkOut
|
|
293
305
|
|
|
306
|
+
@model_validator(mode="before")
|
|
307
|
+
@classmethod
|
|
308
|
+
def sld_imaginary_error(cls, data: Any):
|
|
309
|
+
"""If the extra input 'sld_imaginary' is given, give a more descriptive error."""
|
|
310
|
+
|
|
311
|
+
if isinstance(data, dict) and data.get("SLD_imaginary", False):
|
|
312
|
+
raise ValueError("The Layer class does not support imaginary SLD. Use the AbsorptionLayer class instead.")
|
|
313
|
+
|
|
314
|
+
return data
|
|
315
|
+
|
|
294
316
|
|
|
295
317
|
class AbsorptionLayer(RATModel, populate_by_name=True):
|
|
296
318
|
"""Combines parameters into defined layers including absorption terms."""
|
|
@@ -101,8 +101,6 @@ class Results:
|
|
|
101
101
|
class PredictionIntervals(RATResult):
|
|
102
102
|
reflectivity: list
|
|
103
103
|
sld: list
|
|
104
|
-
reflectivityXData: list
|
|
105
|
-
sldXData: list
|
|
106
104
|
sampleChi: np.ndarray
|
|
107
105
|
|
|
108
106
|
|
|
@@ -189,8 +187,6 @@ def make_results(
|
|
|
189
187
|
prediction_intervals = PredictionIntervals(
|
|
190
188
|
reflectivity=bayes_results.predictionIntervals.reflectivity,
|
|
191
189
|
sld=bayes_results.predictionIntervals.sld,
|
|
192
|
-
reflectivityXData=bayes_results.predictionIntervals.reflectivityXData,
|
|
193
|
-
sldXData=bayes_results.predictionIntervals.sldXData,
|
|
194
190
|
sampleChi=bayes_results.predictionIntervals.sampleChi,
|
|
195
191
|
)
|
|
196
192
|
|