RATapi 0.0.0.dev3__tar.gz → 0.0.0.dev5__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 (82) hide show
  1. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/MANIFEST.in +1 -1
  2. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/PKG-INFO +5 -10
  3. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/__init__.py +7 -0
  4. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/classlist.py +167 -47
  5. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/controls.py +97 -9
  6. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/events.py +12 -9
  7. RATapi-0.0.0.dev5/RATapi/examples/__init__.py +25 -0
  8. RATapi-0.0.0.dev5/RATapi/examples/absorption/__init__.py +1 -0
  9. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/absorption/absorption.py +23 -12
  10. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/absorption/volume_thiol_bilayer.py +4 -1
  11. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/convert_rascal_project/Model_IIb.py +3 -0
  12. RATapi-0.0.0.dev5/RATapi/examples/convert_rascal_project/__init__.py +1 -0
  13. RATapi-0.0.0.dev5/RATapi/examples/convert_rascal_project/convert_rascal.py +49 -0
  14. RATapi-0.0.0.dev5/RATapi/examples/data/__init__.py +1 -0
  15. RATapi-0.0.0.dev5/RATapi/examples/data/d2o_background_data.dat +82 -0
  16. RATapi-0.0.0.dev5/RATapi/examples/domains/__init__.py +1 -0
  17. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/domains/alloy_domains.py +6 -1
  18. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/domains/domains_XY_model.py +5 -1
  19. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/domains/domains_custom_XY.py +12 -1
  20. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/domains/domains_custom_layers.py +9 -1
  21. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/domains/domains_standard_layers.py +12 -0
  22. RATapi-0.0.0.dev5/RATapi/examples/languages/__init__.py +1 -0
  23. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/languages/custom_bilayer.py +3 -0
  24. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/languages/run_custom_file_languages.py +4 -3
  25. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/languages/setup_problem.py +10 -9
  26. {RATapi-0.0.0.dev3/RATapi/examples/non_polarised → RATapi-0.0.0.dev5/RATapi/examples/normal_reflectivity}/DSPC_custom_XY.py +13 -12
  27. {RATapi-0.0.0.dev3/RATapi/examples/non_polarised → RATapi-0.0.0.dev5/RATapi/examples/normal_reflectivity}/DSPC_custom_layers.py +10 -12
  28. RATapi-0.0.0.dev5/RATapi/examples/normal_reflectivity/DSPC_data_background.py +220 -0
  29. RATapi-0.0.0.dev5/RATapi/examples/normal_reflectivity/DSPC_function_background.py +219 -0
  30. {RATapi-0.0.0.dev3/RATapi/examples/non_polarised → RATapi-0.0.0.dev5/RATapi/examples/normal_reflectivity}/DSPC_standard_layers.py +31 -185
  31. RATapi-0.0.0.dev5/RATapi/examples/normal_reflectivity/__init__.py +1 -0
  32. RATapi-0.0.0.dev5/RATapi/examples/normal_reflectivity/background_function.py +16 -0
  33. {RATapi-0.0.0.dev3/RATapi/examples/non_polarised → RATapi-0.0.0.dev5/RATapi/examples/normal_reflectivity}/custom_XY_DSPC.py +5 -2
  34. {RATapi-0.0.0.dev3/RATapi/examples/non_polarised → RATapi-0.0.0.dev5/RATapi/examples/normal_reflectivity}/custom_bilayer_DSPC.py +3 -1
  35. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/inputs.py +329 -297
  36. RATapi-0.0.0.dev5/RATapi/models.py +648 -0
  37. RATapi-0.0.0.dev5/RATapi/outputs.py +533 -0
  38. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/project.py +327 -113
  39. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/run.py +17 -15
  40. RATapi-0.0.0.dev5/RATapi/utils/__init__.py +1 -0
  41. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/utils/convert.py +89 -103
  42. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/utils/custom_errors.py +4 -4
  43. RATapi-0.0.0.dev5/RATapi/utils/enums.py +207 -0
  44. RATapi-0.0.0.dev5/RATapi/utils/orso.py +248 -0
  45. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/utils/plotting.py +47 -41
  46. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/wrappers.py +31 -29
  47. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi.egg-info/PKG-INFO +5 -10
  48. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi.egg-info/SOURCES.txt +14 -7
  49. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi.egg-info/requires.txt +11 -13
  50. RATapi-0.0.0.dev5/cpp/includes/defines.h +679 -0
  51. RATapi-0.0.0.dev5/cpp/includes/functions.h +500 -0
  52. RATapi-0.0.0.dev5/cpp/rat.cpp +1102 -0
  53. RATapi-0.0.0.dev5/pyproject.toml +41 -0
  54. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/setup.py +8 -8
  55. RATapi-0.0.0.dev3/RATapi/examples/__init__.py +0 -19
  56. RATapi-0.0.0.dev3/RATapi/examples/absorption/__init__.py +0 -0
  57. RATapi-0.0.0.dev3/RATapi/examples/convert_rascal_project/__init__.py +0 -0
  58. RATapi-0.0.0.dev3/RATapi/examples/convert_rascal_project/convert_rascal.py +0 -28
  59. RATapi-0.0.0.dev3/RATapi/examples/data/__init__.py +0 -0
  60. RATapi-0.0.0.dev3/RATapi/examples/domains/__init__.py +0 -0
  61. RATapi-0.0.0.dev3/RATapi/examples/languages/__init__.py +0 -0
  62. RATapi-0.0.0.dev3/RATapi/examples/non_polarised/__init__.py +0 -0
  63. RATapi-0.0.0.dev3/RATapi/models.py +0 -371
  64. RATapi-0.0.0.dev3/RATapi/outputs.py +0 -271
  65. RATapi-0.0.0.dev3/RATapi/utils/__init__.py +0 -0
  66. RATapi-0.0.0.dev3/RATapi/utils/enums.py +0 -127
  67. RATapi-0.0.0.dev3/cpp/rat.cpp +0 -1776
  68. RATapi-0.0.0.dev3/pyproject.toml +0 -19
  69. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/data/D2O_spin_down.dat +0 -0
  70. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/data/D2O_spin_up.dat +0 -0
  71. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/data/DSPC_D2O.dat +0 -0
  72. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/data/DSPC_SMW.dat +0 -0
  73. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/data/H2O_spin_down.dat +0 -0
  74. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/data/H2O_spin_up.dat +0 -0
  75. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/data/c_PLP0016596.dat +0 -0
  76. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/data/c_PLP0016601.dat +0 -0
  77. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi/examples/data/c_PLP0016607.dat +0 -0
  78. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi.egg-info/dependency_links.txt +0 -0
  79. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi.egg-info/not-zip-safe +0 -0
  80. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/RATapi.egg-info/top_level.txt +0 -0
  81. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/README.md +0 -0
  82. {RATapi-0.0.0.dev3 → RATapi-0.0.0.dev5}/setup.cfg +0 -0
@@ -1,5 +1,5 @@
1
1
  include README.md
2
- recursive-include cpp/RAT *
2
+ recursive-include cpp *
3
3
  prune tests
4
4
  prune */__pycache__
5
5
  global-exclude .git
@@ -1,23 +1,20 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: RATapi
3
- Version: 0.0.0.dev3
3
+ Version: 0.0.0.dev5
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
- Requires-Python: >=3.9
8
+ Requires-Python: >=3.10
11
9
  Description-Content-Type: text/markdown
12
10
  Provides-Extra: Dev
13
- Provides-Extra: Matlab_2021a
14
- Provides-Extra: Matlab_2021b
15
- Provides-Extra: Matlab_2022a
16
- Provides-Extra: Matlab_2022b
17
11
  Provides-Extra: Matlab_2023a
18
12
  Provides-Extra: Matlab_2023b
19
13
  Provides-Extra: Matlab_2024a
14
+ Provides-Extra: Matlab_2024b
15
+ Provides-Extra: Matlab_2025a
20
16
  Provides-Extra: Matlab_latest
17
+ Provides-Extra: Orso
21
18
 
22
19
  python-RAT
23
20
  ==========
@@ -43,5 +40,3 @@ To build wheel:
43
40
 
44
41
  pip install build
45
42
  python -m build --wheel
46
-
47
-
@@ -1,3 +1,7 @@
1
+ """RATapi is a Python package for modelling, fitting and optimising reflectivity problems."""
2
+
3
+ from contextlib import suppress
4
+
1
5
  import RATapi.examples as examples
2
6
  from RATapi import events, models
3
7
  from RATapi.classlist import ClassList
@@ -6,4 +10,7 @@ from RATapi.project import Project
6
10
  from RATapi.run import run
7
11
  from RATapi.utils import convert, plotting
8
12
 
13
+ with suppress(ImportError): # orsopy is an optional dependency
14
+ from RATapi.utils import orso as orso
15
+
9
16
  __all__ = ["examples", "models", "events", "ClassList", "Controls", "Project", "run", "plotting", "convert"]
@@ -1,9 +1,8 @@
1
- """The classlist module. Contains the ClassList class, which defines a list containing instances of a particular
2
- class.
3
- """
1
+ """The ClassList class, which defines a list containing instances of a particular class."""
4
2
 
5
3
  import collections
6
4
  import contextlib
5
+ import importlib
7
6
  import warnings
8
7
  from collections.abc import Sequence
9
8
  from typing import Any, Generic, TypeVar, Union
@@ -23,12 +22,12 @@ class ClassList(collections.UserList, Generic[T]):
23
22
  attribute given in the ClassList's "name_field" attribute (the default is "name"), the ClassList will ensure that
24
23
  all objects within the ClassList have unique values for that attribute. It is then possible to use this attribute
25
24
  of an object in the .remove(), .count(), and .index() routines in place of the full object. Due to the requirement
26
- of unique values of the name_field attribute, the multiplication operators __mul__, __rmul__, and __imul__ have
25
+ of unique values of the ``name_field`` attribute, the multiplication operators __mul__, __rmul__, and __imul__ have
27
26
  been disabled, since they cannot allow for unique attribute values by definition.
28
27
 
29
28
  We extend the UserList class to enable objects to be added and modified using just the keyword arguments, enable
30
- the object name_field attribute to be used in place of the full object, and ensure all elements are of the
31
- specified type, with unique name_field attributes defined.
29
+ the object ``name_field`` attribute to be used in place of the full object, and ensure all elements are of the
30
+ specified type, with unique ``name_field`` attributes defined.
32
31
 
33
32
  Parameters
34
33
  ----------
@@ -56,10 +55,42 @@ class ClassList(collections.UserList, Generic[T]):
56
55
  super().__init__(init_list)
57
56
 
58
57
  def __str__(self):
58
+ # `display_fields` gives more control over the items displayed from the list if available
59
+ if not self.data:
60
+ return str([])
59
61
  try:
60
- [model.__dict__ for model in self.data]
62
+ model_display_fields = [model.display_fields for model in self.data]
63
+ # get all items included in at least one list
64
+ # the list comprehension ensures they are in the order that they're in in the model
65
+ required_fields = list(set().union(*model_display_fields))
66
+ table_fields = ["index"] + [i for i in list(self.data[0].__dict__) if i in required_fields]
61
67
  except AttributeError:
62
- output = str(self.data)
68
+ try:
69
+ model_display_fields = [model.__dict__ for model in self.data]
70
+ table_fields = ["index"] + list(self.data[0].__dict__)
71
+ except AttributeError:
72
+ return str(self.data)
73
+
74
+ if any(model_display_fields):
75
+ table = prettytable.PrettyTable()
76
+ table.field_names = [field.replace("_", " ") for field in table_fields]
77
+ rows = []
78
+ for index, model in enumerate(self.data):
79
+ row = [index]
80
+ for field in table_fields[1:]:
81
+ value = getattr(model, field, "")
82
+ if isinstance(value, np.ndarray):
83
+ value = (
84
+ f"{'Data array: [' + ' x '.join(str(i) for i in value.shape) if value.size > 0 else '['}]"
85
+ )
86
+ elif field == "model":
87
+ value = "\n".join(str(element) for element in value)
88
+ else:
89
+ value = str(value)
90
+ row.append(value)
91
+ rows.append(row)
92
+ table.add_rows(rows)
93
+ output = table.get_string()
63
94
  else:
64
95
  if any(model.__dict__ for model in self.data):
65
96
  table = prettytable.PrettyTable()
@@ -68,7 +99,7 @@ class ClassList(collections.UserList, Generic[T]):
68
99
  [
69
100
  [index]
70
101
  + list(
71
- f"{'Data array: ['+' x '.join(str(i) for i in v.shape) if v.size > 0 else '['}]"
102
+ f"{'Data array: [' + ' x '.join(str(i) for i in v.shape) if v.size > 0 else '['}]"
72
103
  if isinstance(v, np.ndarray)
73
104
  else "\n".join(element for element in v)
74
105
  if k == "model"
@@ -138,8 +169,9 @@ class ClassList(collections.UserList, Generic[T]):
138
169
  raise TypeError(f"unsupported operand type(s) for *=: '{self.__class__.__name__}' and '{n.__class__.__name__}'")
139
170
 
140
171
  def append(self, obj: T = None, **kwargs) -> None:
141
- """Append a new object to the ClassList using either the object itself, or keyword arguments to set attribute
142
- values.
172
+ """Append a new object to the ClassList.
173
+
174
+ This method can use the object itself, or can provide attribute values as keyword arguments for a new object.
143
175
 
144
176
  Parameters
145
177
  ----------
@@ -151,7 +183,7 @@ class ClassList(collections.UserList, Generic[T]):
151
183
  Raises
152
184
  ------
153
185
  ValueError
154
- Raised if the input arguments contain a name_field value already defined in the ClassList.
186
+ Raised if the input arguments contain a ``name_field`` value already defined in the ClassList.
155
187
 
156
188
  Warnings
157
189
  --------
@@ -183,8 +215,9 @@ class ClassList(collections.UserList, Generic[T]):
183
215
  self.data.append(self._class_handle(**kwargs))
184
216
 
185
217
  def insert(self, index: int, obj: T = None, **kwargs) -> None:
186
- """Insert a new object into the ClassList at a given index using either the object itself, or keyword arguments
187
- to set attribute values.
218
+ """Insert a new object at a given index.
219
+
220
+ This method can use the object itself, or can provide attribute values as keyword arguments for a new object.
188
221
 
189
222
  Parameters
190
223
  ----------
@@ -198,7 +231,7 @@ class ClassList(collections.UserList, Generic[T]):
198
231
  Raises
199
232
  ------
200
233
  ValueError
201
- Raised if the input arguments contain a name_field value already defined in the ClassList.
234
+ Raised if the input arguments contain a ``name_field`` value already defined in the ClassList.
202
235
 
203
236
  Warnings
204
237
  --------
@@ -230,20 +263,25 @@ class ClassList(collections.UserList, Generic[T]):
230
263
  self.data.insert(index, self._class_handle(**kwargs))
231
264
 
232
265
  def remove(self, item: Union[T, str]) -> None:
233
- """Remove an object from the ClassList using either the object itself or its name_field value."""
266
+ """Remove an object from the ClassList using either the object itself or its ``name_field`` value."""
234
267
  item = self._get_item_from_name_field(item)
235
268
  self.data.remove(item)
236
269
 
237
270
  def count(self, item: Union[T, str]) -> int:
238
- """Return the number of times an object appears in the ClassList using either the object itself or its
239
- name_field value.
271
+ """Return the number of times an object appears in the ClassList.
272
+
273
+ This method can use either the object itself or its ``name_field`` value.
274
+
240
275
  """
241
276
  item = self._get_item_from_name_field(item)
242
277
  return self.data.count(item)
243
278
 
244
279
  def index(self, item: Union[T, str], offset: bool = False, *args) -> int:
245
- """Return the index of a particular object in the ClassList using either the object itself or its
246
- name_field value. If offset is specified, add one to the index. This is used to account for one-based indexing.
280
+ """Return the index of a particular object in the ClassList.
281
+
282
+ This method can use either the object itself or its ``name_field`` value.
283
+ If offset is specified, add one to the index. This is used to account for one-based indexing.
284
+
247
285
  """
248
286
  item = self._get_item_from_name_field(item)
249
287
  return self.data.index(item, *args) + int(offset)
@@ -258,20 +296,100 @@ class ClassList(collections.UserList, Generic[T]):
258
296
  self._check_unique_name_fields(other)
259
297
  self.data.extend(other)
260
298
 
261
- def set_fields(self, index: int, **kwargs) -> None:
299
+ def union(self, other: Sequence[T]) -> None:
300
+ """Extend the ClassList by a sequence, ignoring input items with names that already exist."""
301
+ if other and not (isinstance(other, Sequence) and not isinstance(other, str)):
302
+ other = [other]
303
+
304
+ self.extend(
305
+ [
306
+ item
307
+ for item in other
308
+ if hasattr(item, self.name_field) and getattr(item, self.name_field) not in self.get_names()
309
+ ]
310
+ )
311
+
312
+ def set_fields(self, index: Union[int, slice, str, T], **kwargs) -> None:
262
313
  """Assign the values of an existing object's attributes using keyword arguments."""
263
314
  self._validate_name_field(kwargs)
264
- class_handle = self.data[index].__class__
265
- new_fields = {**self.data[index].__dict__, **kwargs}
266
- self.data[index] = class_handle(**new_fields)
315
+ pydantic_object = False
316
+
317
+ # Find index if name or object is supplied
318
+ if isinstance(index, (str, self._class_handle)):
319
+ index = self.index(index)
320
+
321
+ # Prioritise changing language to avoid CustomFile validator bug
322
+ value = kwargs.pop("language", None)
323
+ if value is not None:
324
+ kwargs = {"language": value, **kwargs}
325
+
326
+ if importlib.util.find_spec("pydantic"):
327
+ # Pydantic is installed, so set up a context manager that will
328
+ # suppress custom validation errors until all fields have been set.
329
+ from pydantic import BaseModel, ValidationError
330
+
331
+ if isinstance(self.data[index], BaseModel):
332
+ pydantic_object = True
333
+
334
+ # Define a custom context manager
335
+ class SuppressCustomValidation(contextlib.AbstractContextManager):
336
+ """Context manager to suppress "value_error" based validation errors in pydantic.
337
+
338
+ This validation context is necessary because errors can occur whilst individual
339
+ model values are set, which are resolved when all of the input values are set.
340
+
341
+ After the exception is suppressed, execution proceeds with the next
342
+ statement following the with statement.
343
+
344
+ with SuppressCustomValidation():
345
+ setattr(self.data[index], key, value)
346
+ # Execution still resumes here if the attribute cannot be set
347
+ """
348
+
349
+ def __init__(self):
350
+ pass
351
+
352
+ def __enter__(self):
353
+ pass
354
+
355
+ def __exit__(self, exctype, excinst, exctb):
356
+ # If the return of __exit__ is True or truthy, the exception is suppressed.
357
+ # Otherwise, the default behaviour of raising the exception applies.
358
+ #
359
+ # To suppress errors arising from field and model validators in pydantic,
360
+ # we will examine the validation errors raised. If all of the errors
361
+ # listed in the exception have the type "value_error", this indicates
362
+ # they have arisen from field or model validators and will be suppressed.
363
+ # Otherwise, they will be raised.
364
+ if exctype is None:
365
+ return
366
+ if issubclass(exctype, ValidationError) and all(
367
+ [error["type"] == "value_error" for error in excinst.errors()]
368
+ ):
369
+ return True
370
+ return False
371
+
372
+ validation_context = SuppressCustomValidation()
373
+ else:
374
+ validation_context = contextlib.nullcontext()
375
+
376
+ for key, value in kwargs.items():
377
+ with validation_context:
378
+ setattr(self.data[index], key, value)
379
+
380
+ # We have suppressed custom validation errors for pydantic objects.
381
+ # We now must revalidate the pydantic model outside the validation context
382
+ # to catch any errors that remain after setting all of the fields.
383
+ if pydantic_object:
384
+ self._class_handle.model_validate(self.data[index])
267
385
 
268
386
  def get_names(self) -> list[str]:
269
- """Return a list of the values of the name_field attribute of each class object in the list.
387
+ """Return a list of the values of the ``name_field`` attribute of each class object in the list.
270
388
 
271
389
  Returns
272
390
  -------
273
391
  names : list [str]
274
- The value of the name_field attribute of each object in the ClassList.
392
+ The value of the ``name_field`` attribute of each object in the ClassList.
275
393
 
276
394
  """
277
395
  return [getattr(model, self.name_field) for model in self.data if hasattr(model, self.name_field)]
@@ -298,8 +416,7 @@ class ClassList(collections.UserList, Generic[T]):
298
416
  ]
299
417
 
300
418
  def _validate_name_field(self, input_args: dict[str, Any]) -> None:
301
- """Raise a ValueError if the name_field attribute is passed as an object parameter, and its value is already
302
- used within the ClassList.
419
+ """Raise a ValueError if the user tries to add an object with a ``name_field`` already in the ClassList.
303
420
 
304
421
  Parameters
305
422
  ----------
@@ -309,7 +426,7 @@ class ClassList(collections.UserList, Generic[T]):
309
426
  Raises
310
427
  ------
311
428
  ValueError
312
- Raised if the input arguments contain a name_field value already defined in the ClassList.
429
+ Raised if the input arguments contain a ``name_field`` value already defined in the ClassList.
313
430
 
314
431
  """
315
432
  names = [name.lower() for name in self.get_names()]
@@ -322,8 +439,7 @@ class ClassList(collections.UserList, Generic[T]):
322
439
  )
323
440
 
324
441
  def _check_unique_name_fields(self, input_list: Sequence[T]) -> None:
325
- """Raise a ValueError if any value of the name_field attribute is used more than once in a list of class
326
- objects.
442
+ """Raise a ValueError if any value of the ``name_field`` attribute is repeated in a list of class objects.
327
443
 
328
444
  Parameters
329
445
  ----------
@@ -364,7 +480,7 @@ class ClassList(collections.UserList, Generic[T]):
364
480
  if new_indices:
365
481
  new_list = ", ".join(str(i) for i in new_indices[:-1])
366
482
  new_string = (
367
- f" item{f's {new_list} and ' if new_list else ' '}" f"{new_indices[-1]} of the input list"
483
+ f" item{f's {new_list} and ' if new_list else ' '}{new_indices[-1]} of the input list"
368
484
  )
369
485
  error_list.append(
370
486
  f" '{name}' is shared between{existing_string}"
@@ -379,17 +495,17 @@ class ClassList(collections.UserList, Generic[T]):
379
495
  )
380
496
 
381
497
  def _check_classes(self, input_list: Sequence[T]) -> None:
382
- """Raise a ValueError if any object in a list of objects is not of the type specified by self._class_handle.
498
+ """Raise a ValueError if any object in a list of objects is not of the type specified by ``self._class_handle``.
383
499
 
384
500
  Parameters
385
501
  ----------
386
502
  input_list : iterable
387
- A list of instances of the class given in self._class_handle.
503
+ A list of instances of the class given in ``self._class_handle``.
388
504
 
389
505
  Raises
390
506
  ------
391
507
  ValueError
392
- Raised if the input list contains objects of any type other than that given in self._class_handle.
508
+ If the input list contains objects of any type other than that given in ``self._class_handle``.
393
509
 
394
510
  """
395
511
  error_list = []
@@ -404,18 +520,18 @@ class ClassList(collections.UserList, Generic[T]):
404
520
  )
405
521
 
406
522
  def _get_item_from_name_field(self, value: Union[T, str]) -> Union[T, str]:
407
- """Return the object with the given value of the name_field attribute in the ClassList.
523
+ """Return the object with the given value of the ``name_field`` attribute in the ClassList.
408
524
 
409
525
  Parameters
410
526
  ----------
411
527
  value : T or str
412
- Either an object in the ClassList, or the value of the name_field attribute of an object in the ClassList.
528
+ Either an object in the ClassList, or the value of the ``name_field`` for an object in the ClassList.
413
529
 
414
530
  Returns
415
531
  -------
416
532
  instance : T or str
417
- Either the object with the value of the name_field attribute given by value, or the input value if an
418
- object with that value of the name_field attribute cannot be found.
533
+ Either the object with the value of the ``name_field`` attribute given by value, or the input value if an
534
+ object with that value of the ``name_field`` attribute cannot be found.
419
535
 
420
536
  """
421
537
  try:
@@ -427,24 +543,27 @@ class ClassList(collections.UserList, Generic[T]):
427
543
 
428
544
  @staticmethod
429
545
  def _determine_class_handle(input_list: Sequence[T]):
430
- """When inputting a sequence of object to a ClassList, the _class_handle should be set as the type of the
431
- element which satisfies "issubclass" for all the other elements.
546
+ """Determine the class handle from a sequence of objects.
547
+
548
+ The ``_class_handle`` of the sequence is the type of the first element in the sequence
549
+ which is a subclass of all elements in the sequence. If no such element exists, the handle
550
+ is set to be the type of the first element in the list.
432
551
 
433
552
  Parameters
434
553
  ----------
435
- input_list : Sequence [object]
554
+ input_list : Sequence[T]
436
555
  A list of instances to populate the ClassList.
437
556
 
438
557
  Returns
439
558
  -------
440
559
  class_handle : type
441
- The type object of the element fulfilling the condition of satisfying "issubclass" for all of the other
442
- elements.
560
+ The type object of the first element which is a subclass of all of the other
561
+ elements, or the first element if no such element exists.
443
562
 
444
563
  """
445
- for this_element in input_list:
446
- if all([issubclass(type(instance), type(this_element)) for instance in input_list]):
447
- class_handle = type(this_element)
564
+ for element in input_list:
565
+ if all(issubclass(type(instance), type(element)) for instance in input_list):
566
+ class_handle = type(element)
448
567
  break
449
568
  else:
450
569
  class_handle = type(input_list[0])
@@ -494,6 +613,7 @@ class ClassList(collections.UserList, Generic[T]):
494
613
  core_schema.no_info_wrap_validator_function(coerce, core_schema.is_instance_schema(cls)),
495
614
  core_schema.no_info_wrap_validator_function(validate_items, list_schema),
496
615
  ],
616
+ serialization=core_schema.plain_serializer_function_ser_schema(lambda x: x),
497
617
  )
498
618
 
499
619
  return schema
@@ -1,7 +1,11 @@
1
+ """The Controls class for providing RAT algorithm settings."""
2
+
1
3
  import contextlib
2
4
  import os
3
5
  import tempfile
4
6
  import warnings
7
+ from pathlib import Path
8
+ from typing import Union
5
9
 
6
10
  import prettytable
7
11
  from pydantic import (
@@ -36,43 +40,99 @@ fields = {
36
40
  }
37
41
 
38
42
 
39
- class Controls(BaseModel, validate_assignment=True, extra="forbid"):
43
+ class Controls(BaseModel, validate_assignment=True, extra="forbid", use_attribute_docstrings=True):
40
44
  """The full set of controls parameters for all five procedures that are required for the compiled RAT code."""
41
45
 
42
46
  # All Procedures
43
47
  procedure: Procedures = Procedures.Calculate
48
+ """Which procedure RAT should execute. Can be 'calculate', 'simplex', 'de', 'ns', or 'dream'."""
49
+
44
50
  parallel: Parallel = Parallel.Single
51
+ """How the calculation should be parallelised. Can be 'single', 'contrasts' or 'points'."""
52
+
45
53
  calcSldDuringFit: bool = False
54
+ """Whether SLD will be calculated during fit (for live plotting etc.)"""
55
+
46
56
  resampleMinAngle: float = Field(0.9, le=1, gt=0)
57
+ """The upper threshold on the angle between three sampled points for resampling, in units of radians over pi."""
58
+
47
59
  resampleNPoints: int = Field(50, gt=0)
60
+ """The number of initial points to use for resampling."""
61
+
48
62
  display: Display = Display.Iter
63
+ """How much RAT should print to the terminal. Can be 'off', 'iter', 'notify', or 'final'."""
64
+
49
65
  # Simplex
50
66
  xTolerance: float = Field(1.0e-6, gt=0.0)
67
+ """[SIMPLEX] The termination tolerance for step size."""
68
+
51
69
  funcTolerance: float = Field(1.0e-6, gt=0.0)
70
+ """[SIMPLEX] The termination tolerance for change in chi-squared."""
71
+
52
72
  maxFuncEvals: int = Field(10000, gt=0)
73
+ """[SIMPLEX] The maximum number of function evaluations before the algorithm terminates."""
74
+
53
75
  maxIterations: int = Field(1000, gt=0)
76
+ """[SIMPLEX] The maximum number of iterations before the algorithm terminates."""
77
+
54
78
  # Simplex and DE
55
79
  updateFreq: int = 1
80
+ """[SIMPLEX, DE] Number of iterations between printing progress updates to the terminal."""
81
+
56
82
  updatePlotFreq: int = 20
83
+ """[SIMPLEX, DE] Number of iterations between updates to live plots."""
84
+
57
85
  # DE
58
86
  populationSize: int = Field(20, ge=1)
59
- fWeight: float = 0.5
87
+ """[DE] The number of candidate solutions that exist at any time."""
88
+
89
+ fWeight: float = Field(0.5, gt=0.0)
90
+ """[DE] The step size for how different mutations are to their parents."""
91
+
60
92
  crossoverProbability: float = Field(0.8, gt=0.0, lt=1.0)
93
+ """[DE] The probability of exchange of parameters between individuals at any iteration."""
94
+
61
95
  strategy: Strategies = Strategies.RandomWithPerVectorDither
96
+ """[DE] The algorithm used to generate new candidates."""
97
+
62
98
  targetValue: float = Field(1.0, ge=1.0)
99
+ """[DE] The value of chi-squared at which the algorithm will terminate."""
100
+
63
101
  numGenerations: int = Field(500, ge=1)
102
+ """[DE] The maximum number of iterations before the algorithm terminates."""
103
+
64
104
  # NS
65
105
  nLive: int = Field(150, ge=1)
106
+ """[NS] The number of points to sample."""
107
+
66
108
  nMCMC: int = Field(0, ge=0)
109
+ """[NS] If non-zero, an MCMC process with ``nMCMC`` chains will be used instead of MultiNest."""
110
+
67
111
  propScale: float = Field(0.1, gt=0.0, lt=1.0)
112
+ """[NS] A scaling factor for the ellipsoid generated by MultiNest."""
113
+
68
114
  nsTolerance: float = Field(0.1, ge=0.0)
115
+ """[NS] The tolerance threshold for when the algorithm should terminate."""
116
+
69
117
  # Dream
70
118
  nSamples: int = Field(20000, ge=0)
71
- nChains: int = Field(10, gt=0)
119
+ """[DREAM] The total number of function evaluations (number of algorithm generations times number of chains)."""
120
+
121
+ nChains: int = Field(10, gt=1)
122
+ """[DREAM] The number of Markov chains to use in the algorithm."""
123
+
72
124
  jumpProbability: float = Field(0.5, gt=0.0, lt=1.0)
125
+ """[DREAM] The probability range for the size of jumps in sampling. Larger values mean more variable jumps."""
126
+
73
127
  pUnitGamma: float = Field(0.2, gt=0.0, lt=1.0)
128
+ """[DREAM] The probability that the scaling-down factor of jumps will be ignored and a larger jump will be taken."""
129
+
74
130
  boundHandling: BoundHandling = BoundHandling.Reflect
131
+ """[DREAM] How steps past the space boundaries should be handled. Can be 'off', 'reflect', 'bound', or 'fold'."""
132
+
75
133
  adaptPCR: bool = True
134
+ """[DREAM] Whether the crossover probability for differential evolution should be adapted during the run."""
135
+
76
136
  # Private field for IPC file
77
137
  _IPCFilePath: str = ""
78
138
 
@@ -92,10 +152,10 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
92
152
  procedure = input_dict.get("procedure", Procedures.Calculate)
93
153
  custom_error_msgs = {
94
154
  "extra_forbidden": f'Extra inputs are not permitted. The fields for the "{procedure}"'
95
- f' controls procedure are:\n '
96
- f'{", ".join(fields.get("procedure", []))}\n',
155
+ f" controls procedure are:\n "
156
+ f"{', '.join(fields.get('procedure', []))}\n",
97
157
  }
98
- custom_error_list = custom_pydantic_validation_error(exc.errors(), custom_error_msgs)
158
+ custom_error_list = custom_pydantic_validation_error(exc.errors(include_url=False), custom_error_msgs)
99
159
  raise ValidationError.from_exception_data(exc.title, custom_error_list, hide_input=True) from None
100
160
 
101
161
  if isinstance(model_input, validated_self.__class__):
@@ -116,7 +176,7 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
116
176
  f'\nThe current controls procedure is "{new_procedure}", but the property'
117
177
  f' "{field}" applies instead to the {", ".join(incorrect_procedures)} procedure.\n\n'
118
178
  f' The fields for the "{new_procedure}" controls procedure are:\n'
119
- f' {", ".join(fields[new_procedure])}\n',
179
+ f" {', '.join(fields[new_procedure])}\n",
120
180
  stacklevel=2,
121
181
  )
122
182
 
@@ -138,19 +198,20 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
138
198
  return table.get_string()
139
199
 
140
200
  def initialise_IPC(self):
141
- """Setup the inter-process communication file."""
201
+ """Set up the inter-process communication file."""
142
202
  IPC_obj, self._IPCFilePath = tempfile.mkstemp()
143
203
  os.write(IPC_obj, b"0")
144
204
  os.close(IPC_obj)
145
205
  return None
146
206
 
147
207
  def sendStopEvent(self):
148
- """Sends the stop event via the inter-process communication file.
208
+ """Send the stop event via the inter-process communication file.
149
209
 
150
210
  Warnings
151
211
  --------
152
212
  UserWarning
153
213
  Raised if we try to delete an IPC file that was not initialised.
214
+
154
215
  """
155
216
  if os.path.isfile(self._IPCFilePath):
156
217
  with open(self._IPCFilePath, "wb") as f:
@@ -164,3 +225,30 @@ class Controls(BaseModel, validate_assignment=True, extra="forbid"):
164
225
  with contextlib.suppress(FileNotFoundError):
165
226
  os.remove(self._IPCFilePath)
166
227
  return None
228
+
229
+ def save(self, path: Union[str, Path], filename: str = "controls"):
230
+ """Save a controls object to a JSON file.
231
+
232
+ Parameters
233
+ ----------
234
+ path : str or Path
235
+ The directory in which the controls object will be written.
236
+ filename : str
237
+ The name for the JSON file containing the controls object.
238
+
239
+ """
240
+ file = Path(path, f"{filename.removesuffix('.json')}.json")
241
+ file.write_text(self.model_dump_json())
242
+
243
+ @classmethod
244
+ def load(cls, path: Union[str, Path]) -> "Controls":
245
+ """Load a controls object from file.
246
+
247
+ Parameters
248
+ ----------
249
+ path : str or Path
250
+ The path to the controls object file.
251
+
252
+ """
253
+ file = Path(path)
254
+ return cls.model_validate_json(file.read_text())