RATapi 0.0.0.dev2__tar.gz → 0.0.0.dev4__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.dev4}/PKG-INFO +2 -5
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/classlist.py +238 -50
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/controls.py +123 -5
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/events.py +2 -2
- RATapi-0.0.0.dev4/RATapi/examples/__init__.py +23 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/absorption/absorption.py +10 -11
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/absorption/volume_thiol_bilayer.py +1 -1
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/convert_rascal_project/convert_rascal.py +5 -3
- RATapi-0.0.0.dev4/RATapi/examples/data/d2o_background_data.dat +82 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/languages/run_custom_file_languages.py +4 -3
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/languages/setup_problem.py +7 -8
- {RATapi-0.0.0.dev2/RATapi/examples/non_polarised → RATapi-0.0.0.dev4/RATapi/examples/normal_reflectivity}/DSPC_custom_XY.py +11 -12
- {RATapi-0.0.0.dev2/RATapi/examples/non_polarised → RATapi-0.0.0.dev4/RATapi/examples/normal_reflectivity}/DSPC_custom_layers.py +7 -8
- RATapi-0.0.0.dev4/RATapi/examples/normal_reflectivity/DSPC_data_background.py +218 -0
- RATapi-0.0.0.dev4/RATapi/examples/normal_reflectivity/DSPC_function_background.py +217 -0
- {RATapi-0.0.0.dev2/RATapi/examples/non_polarised → RATapi-0.0.0.dev4/RATapi/examples/normal_reflectivity}/DSPC_standard_layers.py +25 -184
- RATapi-0.0.0.dev4/RATapi/examples/normal_reflectivity/background_function.py +13 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/inputs.py +314 -202
- RATapi-0.0.0.dev4/RATapi/models.py +638 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/outputs.py +8 -8
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/project.py +389 -161
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/run.py +7 -6
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/utils/convert.py +83 -29
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/utils/enums.py +1 -1
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/utils/plotting.py +84 -35
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/wrappers.py +20 -25
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi.egg-info/PKG-INFO +2 -5
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi.egg-info/SOURCES.txt +10 -6
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi.egg-info/requires.txt +3 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/cpp/rat.cpp +664 -510
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/pyproject.toml +1 -1
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/setup.py +2 -1
- RATapi-0.0.0.dev2/RATapi/examples/__init__.py +0 -19
- RATapi-0.0.0.dev2/RATapi/models.py +0 -349
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/MANIFEST.in +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/absorption/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/convert_rascal_project/Model_IIb.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/convert_rascal_project/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/D2O_spin_down.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/D2O_spin_up.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/DSPC_D2O.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/DSPC_SMW.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/H2O_spin_down.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/H2O_spin_up.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/c_PLP0016596.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/c_PLP0016601.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/data/c_PLP0016607.dat +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/domains/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/domains/alloy_domains.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/domains/domains_XY_model.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/domains/domains_custom_XY.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/domains/domains_custom_layers.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/domains/domains_standard_layers.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/languages/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/examples/languages/custom_bilayer.py +0 -0
- {RATapi-0.0.0.dev2/RATapi/examples/non_polarised → RATapi-0.0.0.dev4/RATapi/examples/normal_reflectivity}/__init__.py +0 -0
- {RATapi-0.0.0.dev2/RATapi/examples/non_polarised → RATapi-0.0.0.dev4/RATapi/examples/normal_reflectivity}/custom_XY_DSPC.py +0 -0
- {RATapi-0.0.0.dev2/RATapi/examples/non_polarised → RATapi-0.0.0.dev4/RATapi/examples/normal_reflectivity}/custom_bilayer_DSPC.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/utils/__init__.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi/utils/custom_errors.py +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi.egg-info/dependency_links.txt +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi.egg-info/not-zip-safe +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/RATapi.egg-info/top_level.txt +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/README.md +0 -0
- {RATapi-0.0.0.dev2 → RATapi-0.0.0.dev4}/setup.cfg +0 -0
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: RATapi
|
|
3
|
-
Version: 0.0.0.
|
|
3
|
+
Version: 0.0.0.dev4
|
|
4
4
|
Summary: Python extension for the Reflectivity Analysis Toolbox (RAT)
|
|
5
5
|
Home-page: https://github.com/RascalSoftware/python-RAT
|
|
6
6
|
Author:
|
|
7
7
|
Author-email:
|
|
8
|
-
License: UNKNOWN
|
|
9
|
-
Platform: UNKNOWN
|
|
10
8
|
Requires-Python: >=3.9
|
|
11
9
|
Description-Content-Type: text/markdown
|
|
12
10
|
Provides-Extra: Dev
|
|
@@ -16,6 +14,7 @@ Provides-Extra: Matlab_2022a
|
|
|
16
14
|
Provides-Extra: Matlab_2022b
|
|
17
15
|
Provides-Extra: Matlab_2023a
|
|
18
16
|
Provides-Extra: Matlab_2023b
|
|
17
|
+
Provides-Extra: Matlab_2024a
|
|
19
18
|
Provides-Extra: Matlab_latest
|
|
20
19
|
|
|
21
20
|
python-RAT
|
|
@@ -42,5 +41,3 @@ To build wheel:
|
|
|
42
41
|
|
|
43
42
|
pip install build
|
|
44
43
|
python -m build --wheel
|
|
45
|
-
|
|
46
|
-
|
|
@@ -4,15 +4,18 @@ class.
|
|
|
4
4
|
|
|
5
5
|
import collections
|
|
6
6
|
import contextlib
|
|
7
|
+
import importlib
|
|
7
8
|
import warnings
|
|
8
|
-
from collections.abc import
|
|
9
|
-
from typing import Any, Union
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from typing import Any, Generic, TypeVar, Union
|
|
10
11
|
|
|
11
12
|
import numpy as np
|
|
12
13
|
import prettytable
|
|
13
14
|
|
|
15
|
+
T = TypeVar("T")
|
|
14
16
|
|
|
15
|
-
|
|
17
|
+
|
|
18
|
+
class ClassList(collections.UserList, Generic[T]):
|
|
16
19
|
"""List of instances of a particular class.
|
|
17
20
|
|
|
18
21
|
This class subclasses collections.UserList to construct a list intended to store ONLY instances of a particular
|
|
@@ -30,14 +33,14 @@ class ClassList(collections.UserList):
|
|
|
30
33
|
|
|
31
34
|
Parameters
|
|
32
35
|
----------
|
|
33
|
-
init_list : Sequence [
|
|
36
|
+
init_list : Sequence [T] or T, optional
|
|
34
37
|
An instance, or list of instance(s), of the class to be used in this ClassList.
|
|
35
38
|
name_field : str, optional
|
|
36
39
|
The field used to define unique objects in the ClassList (default is "name").
|
|
37
40
|
|
|
38
41
|
"""
|
|
39
42
|
|
|
40
|
-
def __init__(self, init_list: Union[Sequence[
|
|
43
|
+
def __init__(self, init_list: Union[Sequence[T], T] = None, name_field: str = "name") -> None:
|
|
41
44
|
self.name_field = name_field
|
|
42
45
|
|
|
43
46
|
# Set input as list if necessary
|
|
@@ -54,10 +57,42 @@ class ClassList(collections.UserList):
|
|
|
54
57
|
super().__init__(init_list)
|
|
55
58
|
|
|
56
59
|
def __str__(self):
|
|
60
|
+
# `display_fields` gives more control over the items displayed from the list if available
|
|
61
|
+
if not self.data:
|
|
62
|
+
return str([])
|
|
57
63
|
try:
|
|
58
|
-
[model.
|
|
64
|
+
model_display_fields = [model.display_fields for model in self.data]
|
|
65
|
+
# get all items included in at least one list
|
|
66
|
+
# the list comprehension ensures they are in the order that they're in in the model
|
|
67
|
+
required_fields = list(set().union(*model_display_fields))
|
|
68
|
+
table_fields = ["index"] + [i for i in list(self.data[0].__dict__) if i in required_fields]
|
|
59
69
|
except AttributeError:
|
|
60
|
-
|
|
70
|
+
try:
|
|
71
|
+
model_display_fields = [model.__dict__ for model in self.data]
|
|
72
|
+
table_fields = ["index"] + list(self.data[0].__dict__)
|
|
73
|
+
except AttributeError:
|
|
74
|
+
return str(self.data)
|
|
75
|
+
|
|
76
|
+
if any(model_display_fields):
|
|
77
|
+
table = prettytable.PrettyTable()
|
|
78
|
+
table.field_names = [field.replace("_", " ") for field in table_fields]
|
|
79
|
+
rows = []
|
|
80
|
+
for index, model in enumerate(self.data):
|
|
81
|
+
row = [index]
|
|
82
|
+
for field in table_fields[1:]:
|
|
83
|
+
value = getattr(model, field, "")
|
|
84
|
+
if isinstance(value, np.ndarray):
|
|
85
|
+
value = (
|
|
86
|
+
f"{'Data array: [' + ' x '.join(str(i) for i in value.shape) if value.size > 0 else '['}]"
|
|
87
|
+
)
|
|
88
|
+
elif field == "model":
|
|
89
|
+
value = "\n".join(str(element) for element in value)
|
|
90
|
+
else:
|
|
91
|
+
value = str(value)
|
|
92
|
+
row.append(value)
|
|
93
|
+
rows.append(row)
|
|
94
|
+
table.add_rows(rows)
|
|
95
|
+
output = table.get_string()
|
|
61
96
|
else:
|
|
62
97
|
if any(model.__dict__ for model in self.data):
|
|
63
98
|
table = prettytable.PrettyTable()
|
|
@@ -66,7 +101,7 @@ class ClassList(collections.UserList):
|
|
|
66
101
|
[
|
|
67
102
|
[index]
|
|
68
103
|
+ list(
|
|
69
|
-
f"{'Data array: ['+' x '.join(str(i) for i in v.shape) if v.size > 0 else '['}]"
|
|
104
|
+
f"{'Data array: [' + ' x '.join(str(i) for i in v.shape) if v.size > 0 else '['}]"
|
|
70
105
|
if isinstance(v, np.ndarray)
|
|
71
106
|
else "\n".join(element for element in v)
|
|
72
107
|
if k == "model"
|
|
@@ -81,23 +116,23 @@ class ClassList(collections.UserList):
|
|
|
81
116
|
output = str(self.data)
|
|
82
117
|
return output
|
|
83
118
|
|
|
84
|
-
def __getitem__(self, index: Union[int, slice, str,
|
|
119
|
+
def __getitem__(self, index: Union[int, slice, str, T]) -> T:
|
|
85
120
|
"""Get an item by its index, name, a slice, or the object itself."""
|
|
86
121
|
if isinstance(index, (int, slice)):
|
|
87
122
|
return self.data[index]
|
|
88
|
-
elif isinstance(index, (str,
|
|
123
|
+
elif isinstance(index, (str, self._class_handle)):
|
|
89
124
|
return self.data[self.index(index)]
|
|
90
125
|
else:
|
|
91
126
|
raise IndexError("ClassLists can only be indexed by integers, slices, name strings, or objects.")
|
|
92
127
|
|
|
93
|
-
def __setitem__(self, index: int, item:
|
|
128
|
+
def __setitem__(self, index: int, item: T) -> None:
|
|
94
129
|
"""Replace the object at an existing index of the ClassList."""
|
|
95
130
|
self._setitem(index, item)
|
|
96
131
|
|
|
97
|
-
def _setitem(self, index: int, item:
|
|
132
|
+
def _setitem(self, index: int, item: T) -> None:
|
|
98
133
|
"""Auxiliary routine of "__setitem__" used to enable wrapping."""
|
|
99
|
-
self._check_classes(
|
|
100
|
-
self._check_unique_name_fields(
|
|
134
|
+
self._check_classes([item])
|
|
135
|
+
self._check_unique_name_fields([item])
|
|
101
136
|
self.data[index] = item
|
|
102
137
|
|
|
103
138
|
def __delitem__(self, index: int) -> None:
|
|
@@ -108,18 +143,18 @@ class ClassList(collections.UserList):
|
|
|
108
143
|
"""Auxiliary routine of "__delitem__" used to enable wrapping."""
|
|
109
144
|
del self.data[index]
|
|
110
145
|
|
|
111
|
-
def __iadd__(self, other: Sequence[
|
|
146
|
+
def __iadd__(self, other: Sequence[T]) -> "ClassList":
|
|
112
147
|
"""Define in-place addition using the "+=" operator."""
|
|
113
148
|
return self._iadd(other)
|
|
114
149
|
|
|
115
|
-
def _iadd(self, other: Sequence[
|
|
150
|
+
def _iadd(self, other: Sequence[T]) -> "ClassList":
|
|
116
151
|
"""Auxiliary routine of "__iadd__" used to enable wrapping."""
|
|
117
152
|
if other and not (isinstance(other, Sequence) and not isinstance(other, str)):
|
|
118
153
|
other = [other]
|
|
119
154
|
if not hasattr(self, "_class_handle"):
|
|
120
155
|
self._class_handle = self._determine_class_handle(self + other)
|
|
121
|
-
self._check_classes(
|
|
122
|
-
self._check_unique_name_fields(
|
|
156
|
+
self._check_classes(other)
|
|
157
|
+
self._check_unique_name_fields(other)
|
|
123
158
|
super().__iadd__(other)
|
|
124
159
|
return self
|
|
125
160
|
|
|
@@ -135,13 +170,13 @@ class ClassList(collections.UserList):
|
|
|
135
170
|
"""Define in-place multiplication using the "*=" operator."""
|
|
136
171
|
raise TypeError(f"unsupported operand type(s) for *=: '{self.__class__.__name__}' and '{n.__class__.__name__}'")
|
|
137
172
|
|
|
138
|
-
def append(self, obj:
|
|
173
|
+
def append(self, obj: T = None, **kwargs) -> None:
|
|
139
174
|
"""Append a new object to the ClassList using either the object itself, or keyword arguments to set attribute
|
|
140
175
|
values.
|
|
141
176
|
|
|
142
177
|
Parameters
|
|
143
178
|
----------
|
|
144
|
-
obj :
|
|
179
|
+
obj : T, optional
|
|
145
180
|
An instance of the class specified by self._class_handle.
|
|
146
181
|
**kwargs : dict[str, Any], optional
|
|
147
182
|
The input keyword arguments for a new object in the ClassList.
|
|
@@ -168,8 +203,8 @@ class ClassList(collections.UserList):
|
|
|
168
203
|
if obj:
|
|
169
204
|
if not hasattr(self, "_class_handle"):
|
|
170
205
|
self._class_handle = type(obj)
|
|
171
|
-
self._check_classes(
|
|
172
|
-
self._check_unique_name_fields(
|
|
206
|
+
self._check_classes([obj])
|
|
207
|
+
self._check_unique_name_fields([obj])
|
|
173
208
|
self.data.append(obj)
|
|
174
209
|
else:
|
|
175
210
|
if not hasattr(self, "_class_handle"):
|
|
@@ -180,7 +215,7 @@ class ClassList(collections.UserList):
|
|
|
180
215
|
self._validate_name_field(kwargs)
|
|
181
216
|
self.data.append(self._class_handle(**kwargs))
|
|
182
217
|
|
|
183
|
-
def insert(self, index: int, obj:
|
|
218
|
+
def insert(self, index: int, obj: T = None, **kwargs) -> None:
|
|
184
219
|
"""Insert a new object into the ClassList at a given index using either the object itself, or keyword arguments
|
|
185
220
|
to set attribute values.
|
|
186
221
|
|
|
@@ -188,7 +223,7 @@ class ClassList(collections.UserList):
|
|
|
188
223
|
----------
|
|
189
224
|
index: int
|
|
190
225
|
The index at which to insert a new object in the ClassList.
|
|
191
|
-
obj :
|
|
226
|
+
obj : T, optional
|
|
192
227
|
An instance of the class specified by self._class_handle.
|
|
193
228
|
**kwargs : dict[str, Any], optional
|
|
194
229
|
The input keyword arguments for a new object in the ClassList.
|
|
@@ -215,8 +250,8 @@ class ClassList(collections.UserList):
|
|
|
215
250
|
if obj:
|
|
216
251
|
if not hasattr(self, "_class_handle"):
|
|
217
252
|
self._class_handle = type(obj)
|
|
218
|
-
self._check_classes(
|
|
219
|
-
self._check_unique_name_fields(
|
|
253
|
+
self._check_classes([obj])
|
|
254
|
+
self._check_unique_name_fields([obj])
|
|
220
255
|
self.data.insert(index, obj)
|
|
221
256
|
else:
|
|
222
257
|
if not hasattr(self, "_class_handle"):
|
|
@@ -227,41 +262,99 @@ class ClassList(collections.UserList):
|
|
|
227
262
|
self._validate_name_field(kwargs)
|
|
228
263
|
self.data.insert(index, self._class_handle(**kwargs))
|
|
229
264
|
|
|
230
|
-
def remove(self, item: Union[
|
|
265
|
+
def remove(self, item: Union[T, str]) -> None:
|
|
231
266
|
"""Remove an object from the ClassList using either the object itself or its name_field value."""
|
|
232
267
|
item = self._get_item_from_name_field(item)
|
|
233
268
|
self.data.remove(item)
|
|
234
269
|
|
|
235
|
-
def count(self, item: Union[
|
|
270
|
+
def count(self, item: Union[T, str]) -> int:
|
|
236
271
|
"""Return the number of times an object appears in the ClassList using either the object itself or its
|
|
237
272
|
name_field value.
|
|
238
273
|
"""
|
|
239
274
|
item = self._get_item_from_name_field(item)
|
|
240
275
|
return self.data.count(item)
|
|
241
276
|
|
|
242
|
-
def index(self, item: Union[
|
|
277
|
+
def index(self, item: Union[T, str], offset: bool = False, *args) -> int:
|
|
243
278
|
"""Return the index of a particular object in the ClassList using either the object itself or its
|
|
244
279
|
name_field value. If offset is specified, add one to the index. This is used to account for one-based indexing.
|
|
245
280
|
"""
|
|
246
281
|
item = self._get_item_from_name_field(item)
|
|
247
282
|
return self.data.index(item, *args) + int(offset)
|
|
248
283
|
|
|
249
|
-
def extend(self, other: Sequence[
|
|
284
|
+
def extend(self, other: Sequence[T]) -> None:
|
|
250
285
|
"""Extend the ClassList by adding another sequence."""
|
|
251
286
|
if other and not (isinstance(other, Sequence) and not isinstance(other, str)):
|
|
252
287
|
other = [other]
|
|
253
288
|
if not hasattr(self, "_class_handle"):
|
|
254
289
|
self._class_handle = self._determine_class_handle(self + other)
|
|
255
|
-
self._check_classes(
|
|
256
|
-
self._check_unique_name_fields(
|
|
290
|
+
self._check_classes(other)
|
|
291
|
+
self._check_unique_name_fields(other)
|
|
257
292
|
self.data.extend(other)
|
|
258
293
|
|
|
259
294
|
def set_fields(self, index: int, **kwargs) -> None:
|
|
260
295
|
"""Assign the values of an existing object's attributes using keyword arguments."""
|
|
261
296
|
self._validate_name_field(kwargs)
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
297
|
+
pydantic_object = False
|
|
298
|
+
|
|
299
|
+
if importlib.util.find_spec("pydantic"):
|
|
300
|
+
# Pydantic is installed, so set up a context manager that will
|
|
301
|
+
# suppress custom validation errors until all fields have been set.
|
|
302
|
+
from pydantic import BaseModel, ValidationError
|
|
303
|
+
|
|
304
|
+
if isinstance(self.data[index], BaseModel):
|
|
305
|
+
pydantic_object = True
|
|
306
|
+
|
|
307
|
+
# Define a custom context manager
|
|
308
|
+
class SuppressCustomValidation(contextlib.AbstractContextManager):
|
|
309
|
+
"""Context manager to suppress "value_error" based validation errors in pydantic.
|
|
310
|
+
|
|
311
|
+
This validation context is necessary because errors can occur whilst individual
|
|
312
|
+
model values are set, which are resolved when all of the input values are set.
|
|
313
|
+
|
|
314
|
+
After the exception is suppressed, execution proceeds with the next
|
|
315
|
+
statement following the with statement.
|
|
316
|
+
|
|
317
|
+
with SuppressCustomValidation():
|
|
318
|
+
setattr(self.data[index], key, value)
|
|
319
|
+
# Execution still resumes here if the attribute cannot be set
|
|
320
|
+
"""
|
|
321
|
+
|
|
322
|
+
def __init__(self):
|
|
323
|
+
pass
|
|
324
|
+
|
|
325
|
+
def __enter__(self):
|
|
326
|
+
pass
|
|
327
|
+
|
|
328
|
+
def __exit__(self, exctype, excinst, exctb):
|
|
329
|
+
# If the return of __exit__ is True or truthy, the exception is suppressed.
|
|
330
|
+
# Otherwise, the default behaviour of raising the exception applies.
|
|
331
|
+
#
|
|
332
|
+
# To suppress errors arising from field and model validators in pydantic,
|
|
333
|
+
# we will examine the validation errors raised. If all of the errors
|
|
334
|
+
# listed in the exception have the type "value_error", this indicates
|
|
335
|
+
# they have arisen from field or model validators and will be suppressed.
|
|
336
|
+
# Otherwise, they will be raised.
|
|
337
|
+
if exctype is None:
|
|
338
|
+
return
|
|
339
|
+
if issubclass(exctype, ValidationError) and all(
|
|
340
|
+
[error["type"] == "value_error" for error in excinst.errors()]
|
|
341
|
+
):
|
|
342
|
+
return True
|
|
343
|
+
return False
|
|
344
|
+
|
|
345
|
+
validation_context = SuppressCustomValidation()
|
|
346
|
+
else:
|
|
347
|
+
validation_context = contextlib.nullcontext()
|
|
348
|
+
|
|
349
|
+
for key, value in kwargs.items():
|
|
350
|
+
with validation_context:
|
|
351
|
+
setattr(self.data[index], key, value)
|
|
352
|
+
|
|
353
|
+
# We have suppressed custom validation errors for pydantic objects.
|
|
354
|
+
# We now must revalidate the pydantic model outside the validation context
|
|
355
|
+
# to catch any errors that remain after setting all of the fields.
|
|
356
|
+
if pydantic_object:
|
|
357
|
+
self._class_handle.model_validate(self.data[index])
|
|
265
358
|
|
|
266
359
|
def get_names(self) -> list[str]:
|
|
267
360
|
"""Return a list of the values of the name_field attribute of each class object in the list.
|
|
@@ -312,13 +405,14 @@ class ClassList(collections.UserList):
|
|
|
312
405
|
"""
|
|
313
406
|
names = [name.lower() for name in self.get_names()]
|
|
314
407
|
with contextlib.suppress(KeyError):
|
|
315
|
-
|
|
408
|
+
name = input_args[self.name_field].lower()
|
|
409
|
+
if name in names:
|
|
316
410
|
raise ValueError(
|
|
317
411
|
f"Input arguments contain the {self.name_field} '{input_args[self.name_field]}', "
|
|
318
|
-
f"which is already specified
|
|
412
|
+
f"which is already specified at index {names.index(name)} of the ClassList",
|
|
319
413
|
)
|
|
320
414
|
|
|
321
|
-
def _check_unique_name_fields(self, input_list:
|
|
415
|
+
def _check_unique_name_fields(self, input_list: Sequence[T]) -> None:
|
|
322
416
|
"""Raise a ValueError if any value of the name_field attribute is used more than once in a list of class
|
|
323
417
|
objects.
|
|
324
418
|
|
|
@@ -333,11 +427,49 @@ class ClassList(collections.UserList):
|
|
|
333
427
|
Raised if the input list defines more than one object with the same value of name_field.
|
|
334
428
|
|
|
335
429
|
"""
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
430
|
+
error_list = []
|
|
431
|
+
try:
|
|
432
|
+
existing_names = [name.lower() for name in self.get_names()]
|
|
433
|
+
except AttributeError:
|
|
434
|
+
existing_names = []
|
|
435
|
+
|
|
436
|
+
new_names = [getattr(model, self.name_field).lower() for model in input_list if hasattr(model, self.name_field)]
|
|
437
|
+
full_names = existing_names + new_names
|
|
438
|
+
|
|
439
|
+
# There are duplicate names if this test fails
|
|
440
|
+
if len(set(full_names)) != len(full_names):
|
|
441
|
+
unique_names = [*dict.fromkeys(new_names)]
|
|
442
|
+
|
|
443
|
+
for name in unique_names:
|
|
444
|
+
existing_indices = [i for i, other_name in enumerate(existing_names) if other_name == name]
|
|
445
|
+
new_indices = [i for i, other_name in enumerate(new_names) if other_name == name]
|
|
446
|
+
if (len(existing_indices) + len(new_indices)) > 1:
|
|
447
|
+
existing_string = ""
|
|
448
|
+
new_string = ""
|
|
449
|
+
if existing_indices:
|
|
450
|
+
existing_list = ", ".join(str(i) for i in existing_indices[:-1])
|
|
451
|
+
existing_string = (
|
|
452
|
+
f" item{f's {existing_list} and ' if existing_list else ' '}"
|
|
453
|
+
f"{existing_indices[-1]} of the existing ClassList"
|
|
454
|
+
)
|
|
455
|
+
if new_indices:
|
|
456
|
+
new_list = ", ".join(str(i) for i in new_indices[:-1])
|
|
457
|
+
new_string = (
|
|
458
|
+
f" item{f's {new_list} and ' if new_list else ' '}{new_indices[-1]} of the input list"
|
|
459
|
+
)
|
|
460
|
+
error_list.append(
|
|
461
|
+
f" '{name}' is shared between{existing_string}"
|
|
462
|
+
f"{', and' if existing_string and new_string else ''}{new_string}"
|
|
463
|
+
)
|
|
339
464
|
|
|
340
|
-
|
|
465
|
+
if error_list:
|
|
466
|
+
newline = "\n"
|
|
467
|
+
raise ValueError(
|
|
468
|
+
f"The value of the '{self.name_field}' attribute must be unique for each item in the ClassList:\n"
|
|
469
|
+
f"{newline.join(error for error in error_list)}"
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
def _check_classes(self, input_list: Sequence[T]) -> None:
|
|
341
473
|
"""Raise a ValueError if any object in a list of objects is not of the type specified by self._class_handle.
|
|
342
474
|
|
|
343
475
|
Parameters
|
|
@@ -348,23 +480,31 @@ class ClassList(collections.UserList):
|
|
|
348
480
|
Raises
|
|
349
481
|
------
|
|
350
482
|
ValueError
|
|
351
|
-
Raised if the input list
|
|
483
|
+
Raised if the input list contains objects of any type other than that given in self._class_handle.
|
|
352
484
|
|
|
353
485
|
"""
|
|
354
|
-
|
|
355
|
-
|
|
486
|
+
error_list = []
|
|
487
|
+
for i, element in enumerate(input_list):
|
|
488
|
+
if not isinstance(element, self._class_handle):
|
|
489
|
+
error_list.append(f" index {i} is of type {type(element).__name__}")
|
|
490
|
+
if error_list:
|
|
491
|
+
newline = "\n"
|
|
492
|
+
raise ValueError(
|
|
493
|
+
f"This ClassList only supports elements of type {self._class_handle.__name__}. "
|
|
494
|
+
f"In the input list:\n{newline.join(error for error in error_list)}\n"
|
|
495
|
+
)
|
|
356
496
|
|
|
357
|
-
def _get_item_from_name_field(self, value: Union[
|
|
497
|
+
def _get_item_from_name_field(self, value: Union[T, str]) -> Union[T, str]:
|
|
358
498
|
"""Return the object with the given value of the name_field attribute in the ClassList.
|
|
359
499
|
|
|
360
500
|
Parameters
|
|
361
501
|
----------
|
|
362
|
-
value :
|
|
502
|
+
value : T or str
|
|
363
503
|
Either an object in the ClassList, or the value of the name_field attribute of an object in the ClassList.
|
|
364
504
|
|
|
365
505
|
Returns
|
|
366
506
|
-------
|
|
367
|
-
instance :
|
|
507
|
+
instance : T or str
|
|
368
508
|
Either the object with the value of the name_field attribute given by value, or the input value if an
|
|
369
509
|
object with that value of the name_field attribute cannot be found.
|
|
370
510
|
|
|
@@ -377,9 +517,9 @@ class ClassList(collections.UserList):
|
|
|
377
517
|
return next((model for model in self.data if getattr(model, self.name_field).lower() == lower_value), value)
|
|
378
518
|
|
|
379
519
|
@staticmethod
|
|
380
|
-
def _determine_class_handle(input_list: Sequence[
|
|
520
|
+
def _determine_class_handle(input_list: Sequence[T]):
|
|
381
521
|
"""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
|
|
522
|
+
element which satisfies "issubclass" for all the other elements.
|
|
383
523
|
|
|
384
524
|
Parameters
|
|
385
525
|
----------
|
|
@@ -401,3 +541,51 @@ class ClassList(collections.UserList):
|
|
|
401
541
|
class_handle = type(input_list[0])
|
|
402
542
|
|
|
403
543
|
return class_handle
|
|
544
|
+
|
|
545
|
+
# Pydantic core schema which allows ClassLists to be validated
|
|
546
|
+
# in short: it validates that each ClassList is indeed a ClassList,
|
|
547
|
+
# and then validates ClassList.data as though it were a typed list
|
|
548
|
+
# e.g. ClassList[str] data is validated like list[str]
|
|
549
|
+
@classmethod
|
|
550
|
+
def __get_pydantic_core_schema__(cls, source: Any, handler):
|
|
551
|
+
# import here so that the ClassList can be instantiated and used without Pydantic installed
|
|
552
|
+
from pydantic import ValidatorFunctionWrapHandler
|
|
553
|
+
from pydantic.types import (
|
|
554
|
+
core_schema, # import core_schema through here rather than making pydantic_core a dependency
|
|
555
|
+
)
|
|
556
|
+
from typing_extensions import get_args, get_origin
|
|
557
|
+
|
|
558
|
+
# if annotated with a class, get the item type of that class
|
|
559
|
+
origin = get_origin(source)
|
|
560
|
+
item_tp = Any if origin is None else get_args(source)[0]
|
|
561
|
+
|
|
562
|
+
list_schema = handler.generate_schema(list[item_tp])
|
|
563
|
+
|
|
564
|
+
def coerce(v: Any, handler: ValidatorFunctionWrapHandler) -> ClassList[T]:
|
|
565
|
+
"""If a sequence is given, try to coerce it to a ClassList."""
|
|
566
|
+
if isinstance(v, Sequence):
|
|
567
|
+
classlist = ClassList()
|
|
568
|
+
if len(v) > 0 and isinstance(v[0], dict):
|
|
569
|
+
# we want to be OK if the type is a model and is passed as a dict;
|
|
570
|
+
# pydantic will coerce it or fall over later
|
|
571
|
+
classlist._class_handle = dict
|
|
572
|
+
elif item_tp is not Any:
|
|
573
|
+
classlist._class_handle = item_tp
|
|
574
|
+
classlist.extend(v)
|
|
575
|
+
v = classlist
|
|
576
|
+
v = handler(v)
|
|
577
|
+
return v
|
|
578
|
+
|
|
579
|
+
def validate_items(v: ClassList[T], handler: ValidatorFunctionWrapHandler) -> ClassList[T]:
|
|
580
|
+
v.data = handler(v.data)
|
|
581
|
+
return v
|
|
582
|
+
|
|
583
|
+
schema = core_schema.chain_schema(
|
|
584
|
+
[
|
|
585
|
+
core_schema.no_info_wrap_validator_function(coerce, core_schema.is_instance_schema(cls)),
|
|
586
|
+
core_schema.no_info_wrap_validator_function(validate_items, list_schema),
|
|
587
|
+
],
|
|
588
|
+
serialization=core_schema.plain_serializer_function_ser_schema(lambda x: x),
|
|
589
|
+
)
|
|
590
|
+
|
|
591
|
+
return schema
|