RATapi 0.0.0.dev1__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.
Files changed (61) hide show
  1. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/PKG-INFO +2 -1
  2. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/classlist.py +140 -44
  3. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/controls.py +37 -14
  4. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/absorption/absorption.py +1 -1
  5. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/inputs.py +61 -22
  6. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/models.py +24 -2
  7. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/outputs.py +0 -4
  8. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/project.py +207 -93
  9. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/run.py +52 -8
  10. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/utils/convert.py +74 -2
  11. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/utils/enums.py +22 -9
  12. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/utils/plotting.py +67 -27
  13. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi.egg-info/PKG-INFO +2 -1
  14. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi.egg-info/requires.txt +4 -1
  15. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/cpp/rat.cpp +381 -92
  16. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/pyproject.toml +1 -0
  17. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/setup.py +3 -2
  18. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/MANIFEST.in +0 -0
  19. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/__init__.py +0 -0
  20. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/events.py +0 -0
  21. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/__init__.py +0 -0
  22. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/absorption/__init__.py +0 -0
  23. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/absorption/volume_thiol_bilayer.py +0 -0
  24. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/convert_rascal_project/Model_IIb.py +0 -0
  25. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/convert_rascal_project/__init__.py +0 -0
  26. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/convert_rascal_project/convert_rascal.py +0 -0
  27. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/D2O_spin_down.dat +0 -0
  28. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/D2O_spin_up.dat +0 -0
  29. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/DSPC_D2O.dat +0 -0
  30. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/DSPC_SMW.dat +0 -0
  31. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/H2O_spin_down.dat +0 -0
  32. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/H2O_spin_up.dat +0 -0
  33. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/__init__.py +0 -0
  34. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/c_PLP0016596.dat +0 -0
  35. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/c_PLP0016601.dat +0 -0
  36. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/data/c_PLP0016607.dat +0 -0
  37. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/domains/__init__.py +0 -0
  38. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/domains/alloy_domains.py +0 -0
  39. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/domains/domains_XY_model.py +0 -0
  40. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/domains/domains_custom_XY.py +0 -0
  41. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/domains/domains_custom_layers.py +0 -0
  42. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/domains/domains_standard_layers.py +0 -0
  43. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/languages/__init__.py +0 -0
  44. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/languages/custom_bilayer.py +0 -0
  45. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/languages/run_custom_file_languages.py +0 -0
  46. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/languages/setup_problem.py +0 -0
  47. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/DSPC_custom_XY.py +0 -0
  48. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/DSPC_custom_layers.py +0 -0
  49. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/DSPC_standard_layers.py +0 -0
  50. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/__init__.py +0 -0
  51. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/custom_XY_DSPC.py +0 -0
  52. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/examples/non_polarised/custom_bilayer_DSPC.py +0 -0
  53. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/utils/__init__.py +0 -0
  54. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/utils/custom_errors.py +0 -0
  55. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi/wrappers.py +0 -0
  56. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi.egg-info/SOURCES.txt +0 -0
  57. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi.egg-info/dependency_links.txt +0 -0
  58. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi.egg-info/not-zip-safe +0 -0
  59. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/RATapi.egg-info/top_level.txt +0 -0
  60. {RATapi-0.0.0.dev1 → RATapi-0.0.0.dev3}/README.md +0 -0
  61. {RATapi-0.0.0.dev1 → 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.dev1
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 Iterable, Sequence
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
- class ClassList(collections.UserList):
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 [object] or object, optional
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[object], object] = None, name_field: str = "name") -> None:
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, object]) -> object:
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, object)):
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: object) -> None:
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: object) -> None:
99
+ def _setitem(self, index: int, item: T) -> None:
98
100
  """Auxiliary routine of "__setitem__" used to enable wrapping."""
99
- self._check_classes(self + [item])
100
- self._check_unique_name_fields(self + [item])
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[object]) -> "ClassList":
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[object]) -> "ClassList":
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(self + other)
122
- self._check_unique_name_fields(self + other)
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: object = None, **kwargs) -> None:
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 : object, optional
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(self + [obj])
172
- self._check_unique_name_fields(self + [obj])
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: object = None, **kwargs) -> None:
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 : object, optional
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(self + [obj])
219
- self._check_unique_name_fields(self + [obj])
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[object, str]) -> None:
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[object, str]) -> int:
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[object, str], offset: bool = False, *args) -> int:
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[object]) -> None:
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(self + other)
256
- self._check_unique_name_fields(self + other)
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
- if input_args[self.name_field].lower() in names:
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 in the ClassList",
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: Iterable[object]) -> None:
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
- names = [getattr(model, self.name_field).lower() for model in input_list if hasattr(model, self.name_field)]
337
- if len(set(names)) != len(names):
338
- raise ValueError(f"Input list contains objects with the same value of the {self.name_field} attribute")
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
- def _check_classes(self, input_list: Iterable[object]) -> None:
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 defines objects of different types.
392
+ Raised if the input list contains objects of any type other than that given in self._class_handle.
352
393
 
353
394
  """
354
- if not (all(isinstance(element, self._class_handle) for element in input_list)):
355
- raise ValueError(f"Input list contains elements of type other than '{self._class_handle.__name__}'")
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[object, str]) -> Union[object, str]:
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 : object or str
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 : object or str
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[object]):
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 of the other elements.
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
@@ -6,7 +9,6 @@ from pydantic import (
6
9
  Field,
7
10
  ValidationError,
8
11
  ValidatorFunctionWrapHandler,
9
- field_validator,
10
12
  model_serializer,
11
13
  model_validator,
12
14
  )
@@ -14,7 +16,7 @@ from pydantic import (
14
16
  from RATapi.utils.custom_errors import custom_pydantic_validation_error
15
17
  from RATapi.utils.enums import BoundHandling, Display, Parallel, Procedures, Strategies
16
18
 
17
- common_fields = ["procedure", "parallel", "calcSldDuringFit", "resampleParams", "display"]
19
+ common_fields = ["procedure", "parallel", "calcSldDuringFit", "resampleMinAngle", "resampleNPoints", "display"]
18
20
  update_fields = ["updateFreq", "updatePlotFreq"]
19
21
  fields = {
20
22
  "calculate": common_fields,
@@ -41,7 +43,8 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
41
43
  procedure: Procedures = Procedures.Calculate
42
44
  parallel: Parallel = Parallel.Single
43
45
  calcSldDuringFit: bool = False
44
- resampleParams: list[float] = Field([0.9, 50], min_length=2, max_length=2)
46
+ resampleMinAngle: float = Field(0.9, le=1, gt=0)
47
+ resampleNPoints: int = Field(50, gt=0)
45
48
  display: Display = Display.Iter
46
49
  # Simplex
47
50
  xTolerance: float = Field(1.0e-6, gt=0.0)
@@ -60,7 +63,7 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
60
63
  numGenerations: int = Field(500, ge=1)
61
64
  # NS
62
65
  nLive: int = Field(150, ge=1)
63
- nMCMC: float = Field(0.0, ge=0.0)
66
+ nMCMC: int = Field(0, ge=0)
64
67
  propScale: float = Field(0.1, gt=0.0, lt=1.0)
65
68
  nsTolerance: float = Field(0.1, ge=0.0)
66
69
  # Dream
@@ -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":
@@ -117,16 +122,6 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
117
122
 
118
123
  return validated_self
119
124
 
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
125
  @model_serializer
131
126
  def serialize(self):
132
127
  """Filter fields so only those applying to the chosen procedure are serialized."""
@@ -141,3 +136,31 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
141
136
  table.field_names = ["Property", "Value"]
142
137
  table.add_rows([[k, v] for k, v in self.model_dump().items()])
143
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
@@ -150,7 +150,7 @@ def absorption():
150
150
  )
151
151
 
152
152
  # Now make a controls block and run the code
153
- controls = RAT.Controls(parallel="contrasts", resampleParams=[0.9, 150.0])
153
+ controls = RAT.Controls(parallel="contrasts", resampleNPoints=150)
154
154
  problem, results = RAT.run(problem, controls)
155
155
 
156
156
  return problem, results
@@ -128,7 +128,7 @@ def make_problem(project: RATapi.Project) -> ProblemDefinition:
128
128
  contrast_background_params = []
129
129
 
130
130
  for contrast in project.contrasts:
131
- background = project.backgrounds[project.backgrounds.index(contrast.background)]
131
+ background = project.backgrounds[contrast.background]
132
132
  if background.type == TypeOptions.Data:
133
133
  contrast_background_params.append(-1)
134
134
  else:
@@ -138,7 +138,7 @@ def make_problem(project: RATapi.Project) -> ProblemDefinition:
138
138
  contrast_resolution_params = []
139
139
 
140
140
  for contrast in project.contrasts:
141
- resolution = project.resolutions[project.resolutions.index(contrast.resolution)]
141
+ resolution = project.resolutions[contrast.resolution]
142
142
  if resolution.type == TypeOptions.Data:
143
143
  contrast_resolution_params.append(-1)
144
144
  else:
@@ -160,7 +160,7 @@ def make_problem(project: RATapi.Project) -> ProblemDefinition:
160
160
  problem.resolutionParams = [param.value for param in project.resolution_parameters]
161
161
  problem.contrastBulkIns = [project.bulk_in.index(contrast.bulk_in, True) for contrast in project.contrasts]
162
162
  problem.contrastBulkOuts = [project.bulk_out.index(contrast.bulk_out, True) for contrast in project.contrasts]
163
- problem.contrastQzshifts = [0] * len(project.contrasts) # This is marked as "to do" in RAT
163
+ problem.contrastQzshifts = [1] * len(project.contrasts) # This is marked as "to do" in RAT
164
164
  problem.contrastScalefactors = [
165
165
  project.scalefactors.index(contrast.scalefactor, True) for contrast in project.contrasts
166
166
  ]
@@ -239,9 +239,7 @@ def make_data_present(project: RATapi.Project) -> list[int]:
239
239
  The "dataPresent" field of the problem input used in the compiled RAT code.
240
240
 
241
241
  """
242
- return [
243
- 1 if project.data[project.data.index(contrast.data)].data.size != 0 else 0 for contrast in project.contrasts
244
- ]
242
+ return [1 if project.data[contrast.data].data.size != 0 else 0 for contrast in project.contrasts]
245
243
 
246
244
 
247
245
  def check_indices(problem: ProblemDefinition) -> None:
@@ -281,6 +279,52 @@ def check_indices(problem: ProblemDefinition) -> None:
281
279
  )
282
280
 
283
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
+
284
328
  def make_cells(project: RATapi.Project) -> Cells:
285
329
  """Constructs the cells input required for the compiled RAT code.
286
330
 
@@ -346,24 +390,14 @@ def make_cells(project: RATapi.Project) -> Cells:
346
390
  else:
347
391
  simulation_limits.append([0.0, 0.0])
348
392
 
349
- file_handles = []
350
- for custom_file in project.custom_files:
351
- full_path = os.path.join(custom_file.path, custom_file.filename)
352
- if custom_file.language == Languages.Python:
353
- file_handles.append(get_python_handle(custom_file.filename, custom_file.function_name, custom_file.path))
354
- elif custom_file.language == Languages.Matlab:
355
- file_handles.append(RATapi.wrappers.MatlabWrapper(full_path).getHandle())
356
- elif custom_file.language == Languages.Cpp:
357
- file_handles.append(RATapi.wrappers.DylibWrapper(full_path, custom_file.function_name).getHandle())
358
-
359
393
  # Populate the set of cells
360
394
  cells = Cells()
361
395
  cells.f1 = [[0, 1]] * len(project.contrasts) # This is marked as "to do" in RAT
362
396
  cells.f2 = all_data
363
397
  cells.f3 = data_limits
364
398
  cells.f4 = simulation_limits
365
- cells.f5 = [contrast_model if contrast_model else [0] for contrast_model in contrast_models]
366
- cells.f6 = layer_details if project.model == LayerModels.StandardLayers else [[0]]
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 []
367
401
  cells.f7 = [param.name for param in project.parameters]
368
402
  cells.f8 = [param.name for param in project.background_parameters]
369
403
  cells.f9 = [param.name for param in project.scalefactors]
@@ -371,7 +405,7 @@ def make_cells(project: RATapi.Project) -> Cells:
371
405
  cells.f11 = [param.name for param in project.bulk_in]
372
406
  cells.f12 = [param.name for param in project.bulk_out]
373
407
  cells.f13 = [param.name for param in project.resolution_parameters]
374
- cells.f14 = file_handles
408
+ cells.f14 = FileHandles(project.custom_files)
375
409
  cells.f15 = [param.type for param in project.backgrounds]
376
410
  cells.f16 = [param.type for param in project.resolutions]
377
411
 
@@ -383,7 +417,7 @@ def make_cells(project: RATapi.Project) -> Cells:
383
417
  for domain_contrast in project.domain_contrasts
384
418
  ]
385
419
  cells.f19 = [
386
- domain_contrast_model if domain_contrast_model else 0 for domain_contrast_model in domain_contrast_models
420
+ domain_contrast_model if domain_contrast_model else [] for domain_contrast_model in domain_contrast_models
387
421
  ]
388
422
 
389
423
  cells.f20 = [param.name for param in project.domain_ratios]
@@ -438,7 +472,8 @@ def make_controls(input_controls: RATapi.Controls, checks: Checks) -> Control:
438
472
  controls.procedure = input_controls.procedure
439
473
  controls.parallel = input_controls.parallel
440
474
  controls.calcSldDuringFit = input_controls.calcSldDuringFit
441
- controls.resampleParams = input_controls.resampleParams
475
+ controls.resampleMinAngle = input_controls.resampleMinAngle
476
+ controls.resampleNPoints = input_controls.resampleNPoints
442
477
  controls.display = input_controls.display
443
478
  # Simplex
444
479
  controls.xTolerance = input_controls.xTolerance
@@ -451,7 +486,7 @@ def make_controls(input_controls: RATapi.Controls, checks: Checks) -> Control:
451
486
  controls.populationSize = input_controls.populationSize
452
487
  controls.fWeight = input_controls.fWeight
453
488
  controls.crossoverProbability = input_controls.crossoverProbability
454
- controls.strategy = input_controls.strategy.value # Required for the IntEnum
489
+ controls.strategy = int(input_controls.strategy) # RAT core expects strategy as an integer
455
490
  controls.targetValue = input_controls.targetValue
456
491
  controls.numGenerations = input_controls.numGenerations
457
492
  # NS
@@ -468,5 +503,9 @@ def make_controls(input_controls: RATapi.Controls, checks: Checks) -> Control:
468
503
  controls.adaptPCR = input_controls.adaptPCR
469
504
  # Checks
470
505
  controls.checks = checks
506
+ # IPC
507
+ controls.IPCFilePath = ""
508
+
509
+ controls.IPCFilePath = input_controls._IPCFilePath
471
510
 
472
511
  return controls