RATapi 0.0.0.dev0__cp39-cp39-macosx_11_0_arm64.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.
Files changed (65) hide show
  1. RATapi/.dylibs/libomp.dylib +0 -0
  2. RATapi/__init__.py +8 -0
  3. RATapi/classlist.py +387 -0
  4. RATapi/controls.py +143 -0
  5. RATapi/eventManager.dylib +0 -0
  6. RATapi/events.py +70 -0
  7. RATapi/examples/__init__.py +0 -0
  8. RATapi/examples/absorption/__init__.py +0 -0
  9. RATapi/examples/absorption/absorption.py +148 -0
  10. RATapi/examples/absorption/volume_thiol_bilayer.py +138 -0
  11. RATapi/examples/data/D2O_spin_down.dat +100 -0
  12. RATapi/examples/data/D2O_spin_up.dat +101 -0
  13. RATapi/examples/data/DSPC_D2O.dat +82 -0
  14. RATapi/examples/data/DSPC_SMW.dat +82 -0
  15. RATapi/examples/data/H2O_spin_down.dat +102 -0
  16. RATapi/examples/data/H2O_spin_up.dat +102 -0
  17. RATapi/examples/data/__init__.py +0 -0
  18. RATapi/examples/data/c_PLP0016596.dat +146 -0
  19. RATapi/examples/data/c_PLP0016601.dat +97 -0
  20. RATapi/examples/data/c_PLP0016607.dat +104 -0
  21. RATapi/examples/domains/__init__.py +0 -0
  22. RATapi/examples/domains/alloy_domains.py +26 -0
  23. RATapi/examples/domains/domains_XY_model.py +70 -0
  24. RATapi/examples/domains/domains_custom_XY.py +69 -0
  25. RATapi/examples/domains/domains_custom_layers.py +46 -0
  26. RATapi/examples/domains/domains_standard_layers.py +75 -0
  27. RATapi/examples/languages/__init__.py +0 -0
  28. RATapi/examples/languages/custom_bilayer.py +66 -0
  29. RATapi/examples/languages/run_custom_file_languages.py +41 -0
  30. RATapi/examples/languages/setup_problem.py +130 -0
  31. RATapi/examples/non_polarised/DSPC_custom_XY.py +140 -0
  32. RATapi/examples/non_polarised/DSPC_custom_layers.py +121 -0
  33. RATapi/examples/non_polarised/DSPC_standard_layers.py +358 -0
  34. RATapi/examples/non_polarised/__init__.py +0 -0
  35. RATapi/examples/non_polarised/custom_XY_DSPC.py +137 -0
  36. RATapi/examples/non_polarised/custom_bilayer_DSPC.py +85 -0
  37. RATapi/inputs.py +471 -0
  38. RATapi/models.py +288 -0
  39. RATapi/outputs.py +218 -0
  40. RATapi/project.py +659 -0
  41. RATapi/rat_core.cpython-39-darwin.so +0 -0
  42. RATapi/run.py +35 -0
  43. RATapi/utils/__init__.py +0 -0
  44. RATapi/utils/custom_errors.py +42 -0
  45. RATapi/utils/enums.py +101 -0
  46. RATapi/utils/plotting.py +211 -0
  47. RATapi/wrappers.py +115 -0
  48. RATapi-0.0.0.dev0.dist-info/METADATA +57 -0
  49. RATapi-0.0.0.dev0.dist-info/RECORD +65 -0
  50. RATapi-0.0.0.dev0.dist-info/WHEEL +5 -0
  51. RATapi-0.0.0.dev0.dist-info/top_level.txt +2 -0
  52. tests/__init__.py +0 -0
  53. tests/conftest.py +4728 -0
  54. tests/test_classlist.py +882 -0
  55. tests/test_controls.py +863 -0
  56. tests/test_custom_errors.py +49 -0
  57. tests/test_events.py +61 -0
  58. tests/test_inputs.py +908 -0
  59. tests/test_models.py +308 -0
  60. tests/test_outputs.py +31 -0
  61. tests/test_plotting.py +167 -0
  62. tests/test_project.py +1387 -0
  63. tests/test_run.py +570 -0
  64. tests/test_wrappers.py +57 -0
  65. tests/utils.py +171 -0
Binary file
RATapi/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ from RATapi import events, models
2
+ from RATapi.classlist import ClassList
3
+ from RATapi.controls import Controls
4
+ from RATapi.project import Project
5
+ from RATapi.run import run
6
+ from RATapi.utils import plotting
7
+
8
+ __all__ = ["models", "events", "ClassList", "Controls", "Project", "run", "plotting"]
RATapi/classlist.py ADDED
@@ -0,0 +1,387 @@
1
+ """The classlist module. Contains the ClassList class, which defines a list containing instances of a particular
2
+ class.
3
+ """
4
+
5
+ import collections
6
+ import contextlib
7
+ import warnings
8
+ from collections.abc import Iterable, Sequence
9
+ from typing import Any, Union
10
+
11
+ import numpy as np
12
+ import prettytable
13
+
14
+
15
+ class ClassList(collections.UserList):
16
+ """List of instances of a particular class.
17
+
18
+ This class subclasses collections.UserList to construct a list intended to store ONLY instances of a particular
19
+ class, given on initialisation. Any attempt to introduce an object of a different type will raise a ValueError.
20
+ The class must be able to accept attribute values using keyword arguments. In addition, if the class has the
21
+ attribute given in the ClassList's "name_field" attribute (the default is "name"), the ClassList will ensure that
22
+ all objects within the ClassList have unique values for that attribute. It is then possible to use this attribute
23
+ of an object in the .remove(), .count(), and .index() routines in place of the full object. Due to the requirement
24
+ of unique values of the name_field attribute, the multiplication operators __mul__, __rmul__, and __imul__ have
25
+ been disabled, since they cannot allow for unique attribute values by definition.
26
+
27
+ We extend the UserList class to enable objects to be added and modified using just the keyword arguments, enable
28
+ the object name_field attribute to be used in place of the full object, and ensure all elements are of the
29
+ specified type, with unique name_field attributes defined.
30
+
31
+ Parameters
32
+ ----------
33
+ init_list : Sequence [object] or object, optional
34
+ An instance, or list of instance(s), of the class to be used in this ClassList.
35
+ name_field : str, optional
36
+ The field used to define unique objects in the ClassList (default is "name").
37
+
38
+ """
39
+
40
+ def __init__(self, init_list: Union[Sequence[object], object] = None, name_field: str = "name") -> None:
41
+ self.name_field = name_field
42
+
43
+ # Set input as list if necessary
44
+ if init_list and not (isinstance(init_list, Sequence) and not isinstance(init_list, str)):
45
+ init_list = [init_list]
46
+
47
+ # Set class to be used for this instance of the ClassList, checking that all elements of the input list are of
48
+ # the same type and have unique values of the specified name_field
49
+ if init_list:
50
+ self._class_handle = self._determine_class_handle(init_list)
51
+ self._check_classes(init_list)
52
+ self._check_unique_name_fields(init_list)
53
+
54
+ super().__init__(init_list)
55
+
56
+ def __str__(self):
57
+ try:
58
+ [model.__dict__ for model in self.data]
59
+ except AttributeError:
60
+ output = str(self.data)
61
+ else:
62
+ if any(model.__dict__ for model in self.data):
63
+ table = prettytable.PrettyTable()
64
+ table.field_names = ["index"] + [key.replace("_", " ") for key in self.data[0].__dict__]
65
+ table.add_rows(
66
+ [
67
+ [index]
68
+ + list(
69
+ f"{'Data array: ['+' x '.join(str(i) for i in v.shape) if v.size > 0 else '['}]"
70
+ if isinstance(v, np.ndarray)
71
+ else str(v)
72
+ for v in model.__dict__.values()
73
+ )
74
+ for index, model in enumerate(self.data)
75
+ ]
76
+ )
77
+ output = table.get_string()
78
+ else:
79
+ output = str(self.data)
80
+ return output
81
+
82
+ def __setitem__(self, index: int, item: object) -> None:
83
+ """Replace the object at an existing index of the ClassList."""
84
+ self._setitem(index, item)
85
+
86
+ def _setitem(self, index: int, item: object) -> None:
87
+ """Auxiliary routine of "__setitem__" used to enable wrapping."""
88
+ self._check_classes(self + [item])
89
+ self._check_unique_name_fields(self + [item])
90
+ self.data[index] = item
91
+
92
+ def __delitem__(self, index: int) -> None:
93
+ """Delete an object from the list by index."""
94
+ self._delitem(index)
95
+
96
+ def _delitem(self, index: int) -> None:
97
+ """Auxiliary routine of "__delitem__" used to enable wrapping."""
98
+ del self.data[index]
99
+
100
+ def __iadd__(self, other: Sequence[object]) -> "ClassList":
101
+ """Define in-place addition using the "+=" operator."""
102
+ return self._iadd(other)
103
+
104
+ def _iadd(self, other: Sequence[object]) -> "ClassList":
105
+ """Auxiliary routine of "__iadd__" used to enable wrapping."""
106
+ if other and not (isinstance(other, Sequence) and not isinstance(other, str)):
107
+ other = [other]
108
+ if not hasattr(self, "_class_handle"):
109
+ self._class_handle = self._determine_class_handle(self + other)
110
+ self._check_classes(self + other)
111
+ self._check_unique_name_fields(self + other)
112
+ super().__iadd__(other)
113
+ return self
114
+
115
+ def __mul__(self, n: int) -> None:
116
+ """Define multiplication using the "*" operator."""
117
+ raise TypeError(f"unsupported operand type(s) for *: '{self.__class__.__name__}' and '{n.__class__.__name__}'")
118
+
119
+ def __rmul__(self, n: int) -> None:
120
+ """Define multiplication using the "*" operator."""
121
+ raise TypeError(f"unsupported operand type(s) for *: '{n.__class__.__name__}' and '{self.__class__.__name__}'")
122
+
123
+ def __imul__(self, n: int) -> None:
124
+ """Define in-place multiplication using the "*=" operator."""
125
+ raise TypeError(f"unsupported operand type(s) for *=: '{self.__class__.__name__}' and '{n.__class__.__name__}'")
126
+
127
+ def append(self, obj: object = None, **kwargs) -> None:
128
+ """Append a new object to the ClassList using either the object itself, or keyword arguments to set attribute
129
+ values.
130
+
131
+ Parameters
132
+ ----------
133
+ obj : object, optional
134
+ An instance of the class specified by self._class_handle.
135
+ **kwargs : dict[str, Any], optional
136
+ The input keyword arguments for a new object in the ClassList.
137
+
138
+ Raises
139
+ ------
140
+ ValueError
141
+ Raised if the input arguments contain a name_field value already defined in the ClassList.
142
+
143
+ Warnings
144
+ --------
145
+ SyntaxWarning
146
+ Raised if the input arguments contain BOTH an object and keyword arguments. In this situation the object is
147
+ appended to the ClassList and the keyword arguments are discarded.
148
+
149
+ """
150
+ if obj and kwargs:
151
+ warnings.warn(
152
+ "ClassList.append() called with both an object and keyword arguments. "
153
+ "The keyword arguments will be ignored.",
154
+ SyntaxWarning,
155
+ stacklevel=2,
156
+ )
157
+ if obj:
158
+ if not hasattr(self, "_class_handle"):
159
+ self._class_handle = type(obj)
160
+ self._check_classes(self + [obj])
161
+ self._check_unique_name_fields(self + [obj])
162
+ self.data.append(obj)
163
+ else:
164
+ if not hasattr(self, "_class_handle"):
165
+ raise TypeError(
166
+ "ClassList.append() called with keyword arguments for a ClassList without a class "
167
+ "defined. Call ClassList.append() with an object to define the class.",
168
+ )
169
+ self._validate_name_field(kwargs)
170
+ self.data.append(self._class_handle(**kwargs))
171
+
172
+ def insert(self, index: int, obj: object = None, **kwargs) -> None:
173
+ """Insert a new object into the ClassList at a given index using either the object itself, or keyword arguments
174
+ to set attribute values.
175
+
176
+ Parameters
177
+ ----------
178
+ index: int
179
+ The index at which to insert a new object in the ClassList.
180
+ obj : object, optional
181
+ An instance of the class specified by self._class_handle.
182
+ **kwargs : dict[str, Any], optional
183
+ The input keyword arguments for a new object in the ClassList.
184
+
185
+ Raises
186
+ ------
187
+ ValueError
188
+ Raised if the input arguments contain a name_field value already defined in the ClassList.
189
+
190
+ Warnings
191
+ --------
192
+ SyntaxWarning
193
+ Raised if the input arguments contain both an object and keyword arguments. In this situation the object is
194
+ inserted into the ClassList and the keyword arguments are discarded.
195
+
196
+ """
197
+ if obj and kwargs:
198
+ warnings.warn(
199
+ "ClassList.insert() called with both an object and keyword arguments. "
200
+ "The keyword arguments will be ignored.",
201
+ SyntaxWarning,
202
+ stacklevel=2,
203
+ )
204
+ if obj:
205
+ if not hasattr(self, "_class_handle"):
206
+ self._class_handle = type(obj)
207
+ self._check_classes(self + [obj])
208
+ self._check_unique_name_fields(self + [obj])
209
+ self.data.insert(index, obj)
210
+ else:
211
+ if not hasattr(self, "_class_handle"):
212
+ raise TypeError(
213
+ "ClassList.insert() called with keyword arguments for a ClassList without a class "
214
+ "defined. Call ClassList.insert() with an object to define the class.",
215
+ )
216
+ self._validate_name_field(kwargs)
217
+ self.data.insert(index, self._class_handle(**kwargs))
218
+
219
+ def remove(self, item: Union[object, str]) -> None:
220
+ """Remove an object from the ClassList using either the object itself or its name_field value."""
221
+ item = self._get_item_from_name_field(item)
222
+ self.data.remove(item)
223
+
224
+ def count(self, item: Union[object, str]) -> int:
225
+ """Return the number of times an object appears in the ClassList using either the object itself or its
226
+ name_field value.
227
+ """
228
+ item = self._get_item_from_name_field(item)
229
+ return self.data.count(item)
230
+
231
+ def index(self, item: Union[object, str], offset: bool = False, *args) -> int:
232
+ """Return the index of a particular object in the ClassList using either the object itself or its
233
+ name_field value. If offset is specified, add one to the index. This is used to account for one-based indexing.
234
+ """
235
+ item = self._get_item_from_name_field(item)
236
+ return self.data.index(item, *args) + int(offset)
237
+
238
+ def extend(self, other: Sequence[object]) -> None:
239
+ """Extend the ClassList by adding another sequence."""
240
+ if other and not (isinstance(other, Sequence) and not isinstance(other, str)):
241
+ other = [other]
242
+ if not hasattr(self, "_class_handle"):
243
+ self._class_handle = self._determine_class_handle(self + other)
244
+ self._check_classes(self + other)
245
+ self._check_unique_name_fields(self + other)
246
+ self.data.extend(other)
247
+
248
+ def set_fields(self, index: int, **kwargs) -> None:
249
+ """Assign the values of an existing object's attributes using keyword arguments."""
250
+ self._validate_name_field(kwargs)
251
+ class_handle = self.data[index].__class__
252
+ new_fields = {**self.data[index].__dict__, **kwargs}
253
+ self.data[index] = class_handle(**new_fields)
254
+
255
+ def get_names(self) -> list[str]:
256
+ """Return a list of the values of the name_field attribute of each class object in the list.
257
+
258
+ Returns
259
+ -------
260
+ names : list [str]
261
+ The value of the name_field attribute of each object in the ClassList.
262
+
263
+ """
264
+ return [getattr(model, self.name_field) for model in self.data if hasattr(model, self.name_field)]
265
+
266
+ def get_all_matches(self, value: Any) -> list[tuple]:
267
+ """Return a list of all (index, field) tuples where the value of the field is equal to the given value.
268
+
269
+ Parameters
270
+ ----------
271
+ value : str
272
+ The value we are searching for in the ClassList.
273
+
274
+ Returns
275
+ -------
276
+ : list [tuple]
277
+ A list of (index, field) tuples matching the given value.
278
+
279
+ """
280
+ return [
281
+ (index, field)
282
+ for index, element in enumerate(self.data)
283
+ for field in vars(element)
284
+ if getattr(element, field) == value
285
+ ]
286
+
287
+ def _validate_name_field(self, input_args: dict[str, Any]) -> None:
288
+ """Raise a ValueError if the name_field attribute is passed as an object parameter, and its value is already
289
+ used within the ClassList.
290
+
291
+ Parameters
292
+ ----------
293
+ input_args : dict [str, Any]
294
+ The input keyword arguments for a new object in the ClassList.
295
+
296
+ Raises
297
+ ------
298
+ ValueError
299
+ Raised if the input arguments contain a name_field value already defined in the ClassList.
300
+
301
+ """
302
+ names = self.get_names()
303
+ with contextlib.suppress(KeyError):
304
+ if input_args[self.name_field] in names:
305
+ raise ValueError(
306
+ f"Input arguments contain the {self.name_field} '{input_args[self.name_field]}', "
307
+ f"which is already specified in the ClassList",
308
+ )
309
+
310
+ def _check_unique_name_fields(self, input_list: Iterable[object]) -> None:
311
+ """Raise a ValueError if any value of the name_field attribute is used more than once in a list of class
312
+ objects.
313
+
314
+ Parameters
315
+ ----------
316
+ input_list : iterable
317
+ An iterable of instances of the class given in self._class_handle.
318
+
319
+ Raises
320
+ ------
321
+ ValueError
322
+ Raised if the input list defines more than one object with the same value of name_field.
323
+
324
+ """
325
+ names = [getattr(model, self.name_field) for model in input_list if hasattr(model, self.name_field)]
326
+ if len(set(names)) != len(names):
327
+ raise ValueError(f"Input list contains objects with the same value of the {self.name_field} attribute")
328
+
329
+ def _check_classes(self, input_list: Iterable[object]) -> None:
330
+ """Raise a ValueError if any object in a list of objects is not of the type specified by self._class_handle.
331
+
332
+ Parameters
333
+ ----------
334
+ input_list : iterable
335
+ A list of instances of the class given in self._class_handle.
336
+
337
+ Raises
338
+ ------
339
+ ValueError
340
+ Raised if the input list defines objects of different types.
341
+
342
+ """
343
+ if not (all(isinstance(element, self._class_handle) for element in input_list)):
344
+ raise ValueError(f"Input list contains elements of type other than '{self._class_handle.__name__}'")
345
+
346
+ def _get_item_from_name_field(self, value: Union[object, str]) -> Union[object, str]:
347
+ """Return the object with the given value of the name_field attribute in the ClassList.
348
+
349
+ Parameters
350
+ ----------
351
+ value : object or str
352
+ Either an object in the ClassList, or the value of the name_field attribute of an object in the ClassList.
353
+
354
+ Returns
355
+ -------
356
+ instance : object or str
357
+ Either the object with the value of the name_field attribute given by value, or the input value if an
358
+ object with that value of the name_field attribute cannot be found.
359
+
360
+ """
361
+ return next((model for model in self.data if getattr(model, self.name_field) == value), value)
362
+
363
+ @staticmethod
364
+ def _determine_class_handle(input_list: Sequence[object]):
365
+ """When inputting a sequence of object to a ClassList, the _class_handle should be set as the type of the
366
+ element which satisfies "issubclass" for all of the other elements.
367
+
368
+ Parameters
369
+ ----------
370
+ input_list : Sequence [object]
371
+ A list of instances to populate the ClassList.
372
+
373
+ Returns
374
+ -------
375
+ class_handle : type
376
+ The type object of the element fulfilling the condition of satisfying "issubclass" for all of the other
377
+ elements.
378
+
379
+ """
380
+ for this_element in input_list:
381
+ if all([issubclass(type(instance), type(this_element)) for instance in input_list]):
382
+ class_handle = type(this_element)
383
+ break
384
+ else:
385
+ class_handle = type(input_list[0])
386
+
387
+ return class_handle
RATapi/controls.py ADDED
@@ -0,0 +1,143 @@
1
+ import warnings
2
+
3
+ import prettytable
4
+ from pydantic import (
5
+ BaseModel,
6
+ Field,
7
+ ValidationError,
8
+ ValidatorFunctionWrapHandler,
9
+ field_validator,
10
+ model_serializer,
11
+ model_validator,
12
+ )
13
+
14
+ from RATapi.utils.custom_errors import custom_pydantic_validation_error
15
+ from RATapi.utils.enums import BoundHandling, Display, Parallel, Procedures, Strategies
16
+
17
+ common_fields = ["procedure", "parallel", "calcSldDuringFit", "resampleParams", "display"]
18
+ update_fields = ["updateFreq", "updatePlotFreq"]
19
+ fields = {
20
+ "calculate": common_fields,
21
+ "simplex": [*common_fields, "xTolerance", "funcTolerance", "maxFuncEvals", "maxIterations", *update_fields],
22
+ "de": [
23
+ *common_fields,
24
+ "populationSize",
25
+ "fWeight",
26
+ "crossoverProbability",
27
+ "strategy",
28
+ "targetValue",
29
+ "numGenerations",
30
+ *update_fields,
31
+ ],
32
+ "ns": [*common_fields, "nLive", "nMCMC", "propScale", "nsTolerance"],
33
+ "dream": [*common_fields, "nSamples", "nChains", "jumpProbability", "pUnitGamma", "boundHandling", "adaptPCR"],
34
+ }
35
+
36
+
37
+ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
38
+ """The full set of controls parameters for all five procedures that are required for the compiled RAT code."""
39
+
40
+ # All Procedures
41
+ procedure: Procedures = Procedures.Calculate
42
+ parallel: Parallel = Parallel.Single
43
+ calcSldDuringFit: bool = False
44
+ resampleParams: list[float] = Field([0.9, 50], min_length=2, max_length=2)
45
+ display: Display = Display.Iter
46
+ # Simplex
47
+ xTolerance: float = Field(1.0e-6, gt=0.0)
48
+ funcTolerance: float = Field(1.0e-6, gt=0.0)
49
+ maxFuncEvals: int = Field(10000, gt=0)
50
+ maxIterations: int = Field(1000, gt=0)
51
+ # Simplex and DE
52
+ updateFreq: int = 1
53
+ updatePlotFreq: int = 20
54
+ # DE
55
+ populationSize: int = Field(20, ge=1)
56
+ fWeight: float = 0.5
57
+ crossoverProbability: float = Field(0.8, gt=0.0, lt=1.0)
58
+ strategy: Strategies = Strategies.RandomWithPerVectorDither
59
+ targetValue: float = Field(1.0, ge=1.0)
60
+ numGenerations: int = Field(500, ge=1)
61
+ # NS
62
+ nLive: int = Field(150, ge=1)
63
+ nMCMC: float = Field(0.0, ge=0.0)
64
+ propScale: float = Field(0.1, gt=0.0, lt=1.0)
65
+ nsTolerance: float = Field(0.1, ge=0.0)
66
+ # Dream
67
+ nSamples: int = Field(20000, ge=0)
68
+ nChains: int = Field(10, gt=0)
69
+ jumpProbability: float = Field(0.5, gt=0.0, lt=1.0)
70
+ pUnitGamma: float = Field(0.2, gt=0.0, lt=1.0)
71
+ boundHandling: BoundHandling = BoundHandling.Reflect
72
+ adaptPCR: bool = True
73
+
74
+ @model_validator(mode="wrap")
75
+ def warn_setting_incorrect_properties(self, handler: ValidatorFunctionWrapHandler) -> "Controls":
76
+ """Raise a warning if the user sets fields that apply to other procedures."""
77
+ model_input = self
78
+ try:
79
+ input_dict = model_input.__dict__
80
+ except AttributeError:
81
+ input_dict = model_input
82
+
83
+ validated_self = None
84
+ try:
85
+ validated_self = handler(self)
86
+ except ValidationError as exc:
87
+ procedure = input_dict.get("procedure", Procedures.Calculate)
88
+ custom_error_msgs = {
89
+ "extra_forbidden": f'Extra inputs are not permitted. The fields for the "{procedure}"'
90
+ f' controls procedure are:\n '
91
+ f'{", ".join(fields.get("procedure", []))}\n',
92
+ }
93
+ custom_error_list = custom_pydantic_validation_error(exc.errors(), custom_error_msgs)
94
+ raise ValidationError.from_exception_data(exc.title, custom_error_list) from None
95
+
96
+ if isinstance(model_input, validated_self.__class__):
97
+ # This is for changing fields in a defined model
98
+ changed_fields = [key for key in input_dict if input_dict[key] != validated_self.__dict__[key]]
99
+ elif isinstance(model_input, dict):
100
+ # This is for a newly-defined model
101
+ changed_fields = input_dict.keys()
102
+ else:
103
+ raise ValueError('The input to the "Controls" model is invalid.')
104
+
105
+ new_procedure = validated_self.procedure
106
+ allowed_fields = fields[new_procedure]
107
+ for field in changed_fields:
108
+ if field not in allowed_fields:
109
+ incorrect_procedures = [key for (key, value) in fields.items() if field in value]
110
+ warnings.warn(
111
+ f'\nThe current controls procedure is "{new_procedure}", but the property'
112
+ f' "{field}" applies instead to the {", ".join(incorrect_procedures)} procedure.\n\n'
113
+ f' The fields for the "{new_procedure}" controls procedure are:\n'
114
+ f' {", ".join(fields[new_procedure])}\n',
115
+ stacklevel=2,
116
+ )
117
+
118
+ return validated_self
119
+
120
+ @field_validator("resampleParams")
121
+ @classmethod
122
+ def check_resample_params(cls, values: list[float]) -> list[float]:
123
+ """Make sure each of the two values of resampleParams satisfy their conditions."""
124
+ if not 0 < values[0] < 1:
125
+ raise ValueError("resampleParams[0] must be between 0 and 1")
126
+ if values[1] < 0:
127
+ raise ValueError("resampleParams[1] must be greater than or equal to 0")
128
+ return values
129
+
130
+ @model_serializer
131
+ def serialize(self):
132
+ """Filter fields so only those applying to the chosen procedure are serialized."""
133
+ return {model_field: getattr(self, model_field) for model_field in fields[self.procedure]}
134
+
135
+ def __repr__(self) -> str:
136
+ fields_repr = ", ".join(repr(v) if a is None else f"{a}={v!r}" for a, v in self.model_dump().items())
137
+ return f"{self.__repr_name__()}({fields_repr})"
138
+
139
+ def __str__(self) -> str:
140
+ table = prettytable.PrettyTable()
141
+ table.field_names = ["Property", "Value"]
142
+ table.add_rows([[k, v] for k, v in self.model_dump().items()])
143
+ return table.get_string()
Binary file
RATapi/events.py ADDED
@@ -0,0 +1,70 @@
1
+ import os
2
+ from typing import Callable, List, Union
3
+
4
+ from RATapi.rat_core import EventBridge, EventTypes, PlotEventData, ProgressEventData
5
+
6
+
7
+ def notify(event_type: EventTypes, data: Union[str, PlotEventData, ProgressEventData]) -> None:
8
+ """Calls registered callbacks with the data when event type has
9
+ been triggered.
10
+
11
+ Parameters
12
+ ----------
13
+ event_type : EventTypes
14
+ The event type that was triggered.
15
+ data : str or PlotEventData or ProgressEventData
16
+ The data sent by the event. The message event data is a string.
17
+
18
+ """
19
+ callbacks = __event_callbacks[event_type]
20
+ for callback in callbacks:
21
+ callback(data)
22
+
23
+
24
+ def get_event_callback(event_type: EventTypes) -> List[Callable[[Union[str, PlotEventData, ProgressEventData]], None]]:
25
+ """Returns all callbacks registered for the given event type.
26
+
27
+ Parameters
28
+ ----------
29
+ event_type : EventTypes
30
+ The event type.
31
+
32
+ Returns
33
+ -------
34
+ callback : Callable[[Union[str, PlotEventData, ProgressEventData]], None]
35
+ The callback for the event type.
36
+
37
+ """
38
+ return list(__event_callbacks[event_type])
39
+
40
+
41
+ def register(event_type: EventTypes, callback: Callable[[Union[str, PlotEventData, ProgressEventData]], None]) -> None:
42
+ """Registers a new callback for the event type.
43
+
44
+ Parameters
45
+ ----------
46
+ event_type : EventTypes
47
+ The event type to register.
48
+ callback : Callable[[Union[str, PlotEventData, ProgressEventData]], None]
49
+ The callback for when the event is triggered.
50
+
51
+ """
52
+ if not isinstance(event_type, EventTypes):
53
+ raise ValueError("event_type must be a events.EventTypes enum")
54
+
55
+ if len(__event_callbacks[event_type]) == 0:
56
+ __event_impl.register(event_type)
57
+ __event_callbacks[event_type].add(callback)
58
+
59
+
60
+ def clear() -> None:
61
+ """Clears all event callbacks."""
62
+ __event_impl.clear()
63
+ for key in __event_callbacks:
64
+ __event_callbacks[key] = set()
65
+
66
+
67
+ dir_path = os.path.dirname(os.path.realpath(__file__))
68
+ os.environ["RAT_PATH"] = os.path.join(dir_path, "")
69
+ __event_impl = EventBridge(notify)
70
+ __event_callbacks = {EventTypes.Message: set(), EventTypes.Plot: set(), EventTypes.Progress: set()}
File without changes
File without changes