RATapi 0.0.0.dev10__cp313-cp313-win_amd64.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 (59) hide show
  1. ratapi/__init__.py +29 -0
  2. ratapi/classlist.py +620 -0
  3. ratapi/controls.py +258 -0
  4. ratapi/eventManager.dll +0 -0
  5. ratapi/events.py +88 -0
  6. ratapi/examples/__init__.py +25 -0
  7. ratapi/examples/absorption/__init__.py +1 -0
  8. ratapi/examples/absorption/absorption.py +172 -0
  9. ratapi/examples/absorption/volume_thiol_bilayer.py +141 -0
  10. ratapi/examples/convert_rascal_project/Model_IIb.py +87 -0
  11. ratapi/examples/convert_rascal_project/__init__.py +1 -0
  12. ratapi/examples/convert_rascal_project/convert_rascal.py +49 -0
  13. ratapi/examples/data/D2O_spin_down.dat +100 -0
  14. ratapi/examples/data/D2O_spin_up.dat +101 -0
  15. ratapi/examples/data/DSPC_D2O.dat +82 -0
  16. ratapi/examples/data/DSPC_SMW.dat +82 -0
  17. ratapi/examples/data/H2O_spin_down.dat +102 -0
  18. ratapi/examples/data/H2O_spin_up.dat +102 -0
  19. ratapi/examples/data/__init__.py +1 -0
  20. ratapi/examples/data/c_PLP0016596.dat +146 -0
  21. ratapi/examples/data/c_PLP0016601.dat +97 -0
  22. ratapi/examples/data/c_PLP0016607.dat +104 -0
  23. ratapi/examples/data/d2o_background_data.dat +82 -0
  24. ratapi/examples/domains/__init__.py +1 -0
  25. ratapi/examples/domains/alloy_domains.py +31 -0
  26. ratapi/examples/domains/domains_XY_model.py +72 -0
  27. ratapi/examples/domains/domains_custom_XY.py +86 -0
  28. ratapi/examples/domains/domains_custom_layers.py +60 -0
  29. ratapi/examples/domains/domains_standard_layers.py +92 -0
  30. ratapi/examples/languages/__init__.py +1 -0
  31. ratapi/examples/languages/custom_bilayer.py +69 -0
  32. ratapi/examples/languages/run_custom_file_languages.py +41 -0
  33. ratapi/examples/languages/setup_problem.py +130 -0
  34. ratapi/examples/normal_reflectivity/DSPC_custom_XY.py +149 -0
  35. ratapi/examples/normal_reflectivity/DSPC_custom_layers.py +130 -0
  36. ratapi/examples/normal_reflectivity/DSPC_data_background.py +220 -0
  37. ratapi/examples/normal_reflectivity/DSPC_function_background.py +219 -0
  38. ratapi/examples/normal_reflectivity/DSPC_standard_layers.py +210 -0
  39. ratapi/examples/normal_reflectivity/__init__.py +1 -0
  40. ratapi/examples/normal_reflectivity/background_function.py +16 -0
  41. ratapi/examples/normal_reflectivity/custom_XY_DSPC.py +138 -0
  42. ratapi/examples/normal_reflectivity/custom_bilayer_DSPC.py +87 -0
  43. ratapi/inputs.py +588 -0
  44. ratapi/models.py +677 -0
  45. ratapi/outputs.py +821 -0
  46. ratapi/project.py +1074 -0
  47. ratapi/rat_core.cp313-win_amd64.pyd +0 -0
  48. ratapi/run.py +140 -0
  49. ratapi/utils/__init__.py +1 -0
  50. ratapi/utils/convert.py +564 -0
  51. ratapi/utils/custom_errors.py +40 -0
  52. ratapi/utils/enums.py +204 -0
  53. ratapi/utils/orso.py +247 -0
  54. ratapi/utils/plotting.py +1231 -0
  55. ratapi/wrappers.py +144 -0
  56. ratapi-0.0.0.dev10.dist-info/METADATA +61 -0
  57. ratapi-0.0.0.dev10.dist-info/RECORD +59 -0
  58. ratapi-0.0.0.dev10.dist-info/WHEEL +5 -0
  59. ratapi-0.0.0.dev10.dist-info/top_level.txt +1 -0
ratapi/models.py ADDED
@@ -0,0 +1,677 @@
1
+ """The models module. Contains the pydantic models used by RAT to store project parameters."""
2
+
3
+ import pathlib
4
+ import warnings
5
+ from itertools import count
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import prettytable
10
+ from pydantic import BaseModel, Field, ValidationInfo, field_validator, model_validator
11
+
12
+ from ratapi.utils.enums import BackgroundActions, Hydration, Languages, Priors, TypeOptions
13
+
14
+ try:
15
+ from enum import StrEnum
16
+ except ImportError:
17
+ from strenum import StrEnum
18
+
19
+
20
+ # Create a counter for each model
21
+ background_number = count(1)
22
+ contrast_number = count(1)
23
+ custom_file_number = count(1)
24
+ data_number = count(1)
25
+ domain_contrast_number = count(1)
26
+ layer_number = count(1)
27
+ parameter_number = count(1)
28
+ resolution_number = count(1)
29
+
30
+
31
+ class RATModel(BaseModel, validate_assignment=True, extra="forbid"):
32
+ """A BaseModel where enums are represented by their value."""
33
+
34
+ def __repr__(self):
35
+ fields_repr = ", ".join(
36
+ repr(v) if a is None else f"{a}={v.value!r}" if isinstance(v, StrEnum) else f"{a}={v!r}"
37
+ for a, v in self.__repr_args__()
38
+ )
39
+ return f"{self.__repr_name__()}({fields_repr})"
40
+
41
+ def __str__(self):
42
+ table = prettytable.PrettyTable()
43
+ table.field_names = [key.replace("_", " ") for key in self.display_fields]
44
+ table.add_row(list(self.display_fields.values()))
45
+ return table.get_string()
46
+
47
+ @property
48
+ def display_fields(self) -> dict:
49
+ """A dictionary of which fields should be displayed by this model and their values."""
50
+ return self.__dict__
51
+
52
+
53
+ class Signal(RATModel):
54
+ """Base model for background & resolution signals."""
55
+
56
+ name: str = Field(default="New Signal", min_length=1)
57
+ type: TypeOptions = TypeOptions.Constant
58
+ source: str = ""
59
+ value_1: str = ""
60
+ value_2: str = ""
61
+ value_3: str = ""
62
+ value_4: str = ""
63
+ value_5: str = ""
64
+
65
+ def __setattr__(self, name, value):
66
+ if name == "type":
67
+ warnings.warn(f"Changing the type of {self.name} clears its source and value fields.", stacklevel=2)
68
+ for attr in ["source", "value_1", "value_2", "value_3", "value_4", "value_5"]:
69
+ with warnings.catch_warnings():
70
+ warnings.simplefilter("ignore")
71
+ super().__setattr__(attr, "")
72
+
73
+ super().__setattr__(name, value)
74
+
75
+ @property
76
+ def display_fields(self) -> dict:
77
+ """The fields which should be visible in a table and their values.
78
+
79
+ Returns
80
+ -------
81
+ dict
82
+ A dictionary of the fields which should be visible in a table and their values.
83
+
84
+ """
85
+ visible_fields = ["name", "type", "source"]
86
+ if self.type != TypeOptions.Constant:
87
+ visible_fields.append("value_1")
88
+ if self.type == TypeOptions.Function:
89
+ visible_fields.extend(["value_2", "value_3", "value_4", "value_5"])
90
+
91
+ return {f: getattr(self, f) for f in visible_fields}
92
+
93
+
94
+ class Background(Signal):
95
+ """A background signal.
96
+
97
+ Parameters
98
+ ----------
99
+ name : str
100
+ The name of the background.
101
+ type : TypeOptions
102
+ The type of background (constant, function or data)
103
+ source : str
104
+ The source of the background;
105
+
106
+ - if type is 'constant', this should be the name of a background parameter.
107
+ - if type is 'data', this should be the name of a dataset defined in `Project.data`.
108
+ - if type is 'function', this should be the name of a custom function defined in `Project.custom_files`.
109
+
110
+ value_1, value_2, value_3, value_4, value_5 : str
111
+ Values required by the background.
112
+
113
+ - if type is 'constant', all values will be ignored.
114
+ - if type is 'data', value_1 may be the parameter name for an optional offset. Other values are ignored.
115
+ - if type is 'function', these values may be the names of up to 5 parameters which are passed to the function.
116
+
117
+ """
118
+
119
+ name: str = Field(default_factory=lambda: f"New Background {next(background_number)}", min_length=1)
120
+
121
+ @model_validator(mode="after")
122
+ def check_unsupported_parameters(self):
123
+ """Raise an error if the parameters given are not supported for the given type."""
124
+ if self.type == TypeOptions.Constant:
125
+ expected_empty_fields = ["value_1", "value_2", "value_3", "value_4", "value_5"]
126
+ elif self.type == TypeOptions.Data:
127
+ expected_empty_fields = ["value_2", "value_3", "value_4", "value_5"]
128
+ else:
129
+ return self
130
+
131
+ non_empty_fields = [v for v in expected_empty_fields if getattr(self, v) != ""]
132
+ if non_empty_fields:
133
+ raise ValueError(
134
+ f'The following values are not supported by the "{self.type}" Background type: '
135
+ f"{', '.join(non_empty_fields)}"
136
+ )
137
+
138
+ return self
139
+
140
+
141
+ class Contrast(RATModel):
142
+ """A group of all of the components of a model.
143
+
144
+ Parameters
145
+ ----------
146
+ name : str
147
+ The name of the contrast.
148
+ data : str
149
+ The name of the dataset used by the contrast.
150
+ background : str
151
+ The name of the background for the contrast.
152
+ background_action : BackgroundActions
153
+ Whether the background should be added ('add') or subtracted ('subtract') from the data.
154
+ bulk_in : str
155
+ The name of the bulk-in parameter which defines the SLD of the interface between the
156
+ first layer and the environment.
157
+ bulk_out : str
158
+ The name of the bulk-out parameter which defines the SLD of the interface between the last
159
+ layer and the environment.
160
+ scalefactor : str
161
+ The name of the scalefactor which defines how much the data for this contrast should be scaled.
162
+ resolution : str
163
+ The name of the instrument resolution for this contrast.
164
+ resample : bool
165
+ Whether adaptive resampling should be used for interface microslicing.
166
+ repeat_layers : int
167
+ For standard layers, the number of times the set of layers defined in the model should be repeated.
168
+ model : list[str]
169
+ If this is a standard layers model, this should be a list of layer names
170
+ that make up the slab model for this contrast.
171
+ For custom models, this should be a list containing just the custom file name for the
172
+ custom model function.
173
+
174
+ """
175
+
176
+ name: str = Field(default_factory=lambda: f"New Contrast {next(contrast_number)}", min_length=1)
177
+ data: str = ""
178
+ background: str = ""
179
+ background_action: BackgroundActions = BackgroundActions.Add
180
+ bulk_in: str = ""
181
+ bulk_out: str = ""
182
+ scalefactor: str = ""
183
+ resolution: str = ""
184
+ resample: bool = False
185
+ repeat_layers: int = Field(default=1, gt=0)
186
+ model: list[str] = []
187
+
188
+ @model_validator(mode="before")
189
+ @classmethod
190
+ def domain_ratio_error(cls, data: Any):
191
+ """If the extra input 'domain_ratio' is given, give a more descriptive error."""
192
+ if isinstance(data, dict) and data.get("domain_ratio", False):
193
+ raise ValueError(
194
+ "The Contrast class does not support domain ratios. Use the ContrastWithRatio class instead."
195
+ )
196
+
197
+ return data
198
+
199
+ def __str__(self):
200
+ table = prettytable.PrettyTable()
201
+ table.field_names = [key.replace("_", " ") for key in self.__dict__]
202
+ model_entry = "\n".join(element for element in self.model)
203
+ table.add_row(
204
+ [
205
+ self.name,
206
+ self.data,
207
+ self.background,
208
+ self.background_action,
209
+ self.bulk_in,
210
+ self.bulk_out,
211
+ self.scalefactor,
212
+ self.resolution,
213
+ self.resample,
214
+ self.repeat_layers,
215
+ model_entry,
216
+ ]
217
+ )
218
+ return table.get_string()
219
+
220
+
221
+ class ContrastWithRatio(RATModel):
222
+ """A group of all of the components of a model, including domain terms.
223
+
224
+ Parameters
225
+ ----------
226
+ name : str
227
+ The name of the contrast.
228
+ data : str
229
+ The name of the dataset used by the contrast.
230
+ background : str
231
+ The name of the background for the contrast.
232
+ background_action : BackgroundActions
233
+ Whether the background should be added ('add') or subtracted ('subtract') from the data.
234
+ bulk_in : str
235
+ The name of the bulk-in parameter which defines the SLD of the interface between the
236
+ first layer and the environment.
237
+ bulk_out : str
238
+ The name of the bulk-out parameter which defines the SLD of the interface between the last
239
+ layer and the environment.
240
+ scalefactor : str
241
+ resolution : str
242
+ The name of the instrument resolution for this contrast.
243
+ resample : bool
244
+ Whether adaptive resampling should be used for interface microslicing.
245
+ repeat_layers : int
246
+ For standard layers, the number of times the set of layers defined in the model should be repeated.
247
+ domain_ratio : str
248
+ The name of the domain ratio parameter describing how the first domain should be weighted
249
+ relative to the second.
250
+ model : list[str]
251
+ If this is a standard layers model, this should be a list of the names of the two domain contrasts
252
+ which make up the domain model for this contrast.
253
+ For custom models, this should be a list containing just the custom file name for the
254
+ custom model function.
255
+
256
+ """
257
+
258
+ name: str = Field(default_factory=lambda: f"New Contrast {next(contrast_number)}", min_length=1)
259
+ data: str = ""
260
+ background: str = ""
261
+ background_action: BackgroundActions = BackgroundActions.Add
262
+ bulk_in: str = ""
263
+ bulk_out: str = ""
264
+ scalefactor: str = ""
265
+ resolution: str = ""
266
+ resample: bool = False
267
+ repeat_layers: int = Field(default=1, gt=0)
268
+ domain_ratio: str = ""
269
+ model: list[str] = []
270
+
271
+ def __str__(self):
272
+ table = prettytable.PrettyTable()
273
+ table.field_names = [key.replace("_", " ") for key in self.__dict__]
274
+ model_entry = "\n".join(element for element in self.model)
275
+ table.add_row(
276
+ [
277
+ self.name,
278
+ self.data,
279
+ self.background,
280
+ self.background_action,
281
+ self.bulk_in,
282
+ self.bulk_out,
283
+ self.scalefactor,
284
+ self.resolution,
285
+ self.resample,
286
+ self.repeat_layers,
287
+ self.domain_ratio,
288
+ model_entry,
289
+ ]
290
+ )
291
+ return table.get_string()
292
+
293
+
294
+ class CustomFile(RATModel):
295
+ """A file containing functions to use for a custom model or function background.
296
+
297
+ Parameters
298
+ ----------
299
+ name : str
300
+ The name of this custom file object.
301
+ filename : str
302
+ The name of the file containing the custom function.
303
+ function_name : str
304
+ The name of the custom function within the file.
305
+ language : Languages
306
+ What language the custom function is written in: 'matlab', 'python', or 'cpp' (C++)
307
+ path : pathlib.Path
308
+ The path to the custom file.
309
+
310
+ """
311
+
312
+ name: str = Field(default_factory=lambda: f"New Custom File {next(custom_file_number)}", min_length=1)
313
+ filename: str = ""
314
+ function_name: str = ""
315
+ language: Languages = Languages.Python
316
+ path: pathlib.Path = pathlib.Path(".").resolve()
317
+
318
+ @field_validator("path")
319
+ @classmethod
320
+ def resolve_relative_paths(cls, path: pathlib.Path) -> pathlib.Path:
321
+ """Return the absolute path of the given path."""
322
+ return path.resolve()
323
+
324
+ def model_post_init(self, __context: Any) -> None:
325
+ """Autogenerate the function name from the filename if not set.
326
+
327
+ If a filename is supplied but the ``function_name`` field is not set, the ``function_name`` should be set to
328
+ the filename without the extension.
329
+
330
+ """
331
+ if "filename" in self.model_fields_set and "function_name" not in self.model_fields_set:
332
+ self.function_name = pathlib.Path(self.filename).stem
333
+
334
+ @model_validator(mode="after")
335
+ def set_matlab_function_name(self):
336
+ """For a matlab custom function, ``function_name`` should be set to the filename without the extension."""
337
+ if self.language == Languages.Matlab and self.function_name != pathlib.Path(self.filename).stem:
338
+ self.function_name = pathlib.Path(self.filename).stem
339
+
340
+ return self
341
+
342
+
343
+ class Data(RATModel, arbitrary_types_allowed=True):
344
+ """A dataset required for a contrast.
345
+
346
+ Parameters
347
+ ----------
348
+ name : str
349
+ The name of this dataset.
350
+ data : np.ndarray[np.float64]
351
+ The (x, y, error) data for this dataset, given as a Numpy array of three columns.
352
+ data_range : list[float]
353
+ simulation_range : list[float]
354
+
355
+ """
356
+
357
+ name: str = Field(default_factory=lambda: f"New Data {next(data_number)}", min_length=1)
358
+ data: np.ndarray = np.empty([0, 3])
359
+ data_range: list[float] = Field(default=[], min_length=2, max_length=2)
360
+ simulation_range: list[float] = Field(default=[], min_length=2, max_length=2)
361
+
362
+ @field_validator("data")
363
+ @classmethod
364
+ def check_data_dimension(cls, data: np.ndarray) -> np.ndarray:
365
+ """Ensure the data is be a two-dimensional array containing at least three columns."""
366
+ try:
367
+ data.shape[1]
368
+ except IndexError:
369
+ raise ValueError('"data" must have at least two dimensions') from None
370
+ else:
371
+ if data.shape[1] < 3:
372
+ raise ValueError('"data" must have at least three columns') from None
373
+ return data
374
+
375
+ @field_validator("data_range", "simulation_range")
376
+ @classmethod
377
+ def check_min_max(cls, limits: list[float], info: ValidationInfo) -> list[float]:
378
+ """Ensure the data range and simulation range maximum is greater than the minimum."""
379
+ if limits[0] > limits[1]:
380
+ raise ValueError(f'{info.field_name} "min" value is greater than the "max" value')
381
+ return limits
382
+
383
+ def model_post_init(self, __context: Any) -> None:
384
+ """Automatically generate ``data_range`` and ``simulation_range`` from the data.
385
+
386
+ If the ``data_range`` and ``simulation_range`` fields are not set, but ``data`` is supplied, the ranges are
387
+ set to the min and max values of the first column (assumed to be q) of the supplied data.
388
+ """
389
+ if self.data.shape[0] > 0:
390
+ data_min = float(np.min(self.data[:, 0]))
391
+ data_max = float(np.max(self.data[:, 0]))
392
+ for field in ["data_range", "simulation_range"]:
393
+ if field not in self.model_fields_set:
394
+ getattr(self, field).extend([data_min, data_max])
395
+
396
+ @model_validator(mode="after")
397
+ def check_ranges(self) -> "Data":
398
+ """Check that ``data_range`` is within the q-range of the data, and ``simulation_range`` is outside it.
399
+
400
+ The limits of the "data_range" field must lie within the range of the supplied data, whilst the limits
401
+ of the "simulation_range" field must lie outside the range of the supplied data.
402
+ """
403
+ if self.data.shape[0] > 0:
404
+ data_min = np.min(self.data[:, 0])
405
+ data_max = np.max(self.data[:, 0])
406
+ if "data_range" in self.model_fields_set and (
407
+ self.data_range[0] < data_min or self.data_range[1] > data_max
408
+ ):
409
+ raise ValueError(
410
+ f"The data_range value of: {self.data_range} must lie within the min/max values of "
411
+ f"the data: [{data_min}, {data_max}]",
412
+ )
413
+ if "simulation_range" in self.model_fields_set and (
414
+ self.simulation_range[0] > data_min or self.simulation_range[1] < data_max
415
+ ):
416
+ raise ValueError(
417
+ f"The simulation_range value of: {self.simulation_range} must lie outside of the "
418
+ f"min/max values of the data: [{data_min}, {data_max}]",
419
+ )
420
+ return self
421
+
422
+ def __eq__(self, other: object) -> bool:
423
+ if isinstance(other, BaseModel):
424
+ # When comparing instances of generic types for equality, as long as all field values are equal,
425
+ # only require their generic origin types to be equal, rather than exact type equality.
426
+ # This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1).
427
+ self_type = self.__pydantic_generic_metadata__["origin"] or self.__class__
428
+ other_type = other.__pydantic_generic_metadata__["origin"] or other.__class__
429
+
430
+ return (
431
+ self_type == other_type
432
+ and self.name == other.name
433
+ and (self.data == other.data).all()
434
+ and self.data_range == other.data_range
435
+ and self.simulation_range == other.simulation_range
436
+ and self.__pydantic_private__ == other.__pydantic_private__
437
+ and self.__pydantic_extra__ == other.__pydantic_extra__
438
+ )
439
+ else:
440
+ return NotImplemented # delegate to the other item in the comparison
441
+
442
+ def __str__(self):
443
+ table = prettytable.PrettyTable()
444
+ table.field_names = [key.replace("_", " ") for key in self.__dict__]
445
+ array_entry = f"{'Data array: [' + ' x '.join(str(i) for i in self.data.shape) if self.data.size > 0 else '['}]"
446
+ table.add_row([self.name, array_entry, self.data_range, self.simulation_range])
447
+ return table.get_string()
448
+
449
+
450
+ class DomainContrast(RATModel):
451
+ """A group of layers required for a domain.
452
+
453
+ Parameters
454
+ ----------
455
+ name : str
456
+ The name of this domain contrast.
457
+ model : list[str]
458
+ A list of layer names that make up the slab model for this contrast.
459
+
460
+ """
461
+
462
+ name: str = Field(default_factory=lambda: f"New Domain Contrast {next(domain_contrast_number)}", min_length=1)
463
+ model: list[str] = []
464
+
465
+ def __str__(self):
466
+ table = prettytable.PrettyTable()
467
+ table.field_names = [key.replace("_", " ") for key in self.__dict__]
468
+ model_entry = "\n".join(element for element in self.model)
469
+ table.add_row([self.name, model_entry])
470
+ return table.get_string()
471
+
472
+
473
+ class Layer(RATModel, populate_by_name=True):
474
+ """A slab model layer with given physical properties.
475
+
476
+ Parameters
477
+ ----------
478
+ name : str
479
+ The name of this layer.
480
+ thickness : str
481
+ The name of the parameter describing the thickness of this layer.
482
+ SLD : str
483
+ The name of the parameter describing the scattering length density
484
+ of this layer.
485
+ roughness : str
486
+ The name of the parameter describing the roughness of this layer.
487
+ hydration : str
488
+ hydrate_with : str
489
+
490
+ """
491
+
492
+ name: str = Field(default_factory=lambda: f"New Layer {next(layer_number)}", min_length=1)
493
+ thickness: str
494
+ SLD: str = Field(validation_alias="SLD_real")
495
+ roughness: str
496
+ hydration: str = ""
497
+ hydrate_with: Hydration = Hydration.BulkOut
498
+
499
+ @model_validator(mode="before")
500
+ @classmethod
501
+ def sld_imaginary_error(cls, data: Any):
502
+ """If the extra input 'sld_imaginary' is given, give a more descriptive error."""
503
+ if isinstance(data, dict) and data.get("SLD_imaginary", False):
504
+ raise ValueError("The Layer class does not support imaginary SLD. Use the AbsorptionLayer class instead.")
505
+
506
+ return data
507
+
508
+
509
+ class AbsorptionLayer(RATModel, populate_by_name=True):
510
+ """A slab model layer with a non-negligible absorption term.
511
+
512
+ Parameters
513
+ ----------
514
+ name : str
515
+ The name of this layer.
516
+ thickness : str
517
+ The name of the parameter describing the thickness of this layer.
518
+ SLD_real : str
519
+ The name of the parameter describing the real (scattering) term
520
+ for the scattering length density of this layer.
521
+ SLD_imaginary : str
522
+ The name of the parameter describing the imaginary (absorption) term
523
+ for the scattering length density of this layer.
524
+ roughness : str
525
+ The name of the parameter describing the roughness of this layer.
526
+ hydration : str
527
+ hydrate_with : str
528
+
529
+ """
530
+
531
+ name: str = Field(default_factory=lambda: f"New Layer {next(layer_number)}", min_length=1)
532
+ thickness: str
533
+ SLD_real: str = Field(validation_alias="SLD")
534
+ SLD_imaginary: str
535
+ roughness: str
536
+ hydration: str = ""
537
+ hydrate_with: Hydration = Hydration.BulkOut
538
+
539
+
540
+ class Parameter(RATModel):
541
+ """A parameter needed to specify the model.
542
+
543
+ Parameters
544
+ ----------
545
+ name : str
546
+ The name of this parameter.
547
+ min : float
548
+ The minimum value that this parameter could take when fitted.
549
+ value : float
550
+ The value of this parameter.
551
+ max : float
552
+ The maximum value that this parameter could take when fitted.
553
+ fit : bool
554
+ Whether this parameter should be fitted in a calculation.
555
+ prior_type : Priors
556
+ For Bayesian calculations, whether the prior likelihood
557
+ is assumed to be 'uniform' or 'gaussian'.
558
+ mu, sigma : float
559
+ If the prior type is Gaussian, the mu and sigma values describing
560
+ the Gaussian function for the prior likelihood.
561
+
562
+ """
563
+
564
+ name: str = Field(default_factory=lambda: f"New Parameter {next(parameter_number)}", min_length=1)
565
+ min: float = 0.0
566
+ value: float = 0.0
567
+ max: float = 0.0
568
+ fit: bool = False
569
+ prior_type: Priors = Priors.Uniform
570
+ mu: float = 0.0
571
+ sigma: float = np.inf
572
+
573
+ show_priors: bool = False
574
+
575
+ def model_post_init(self, __context: Any) -> None:
576
+ """Apply parameter value to limits if they are not set."""
577
+ if "value" in self.model_fields_set:
578
+ if self.value > 0.0:
579
+ if "max" not in self.model_fields_set:
580
+ self.max = self.value
581
+ if "min" not in self.model_fields_set:
582
+ self.min = self.value
583
+ elif self.value < 0.0:
584
+ if "min" not in self.model_fields_set:
585
+ self.min = self.value
586
+ if "max" not in self.model_fields_set:
587
+ self.max = self.value
588
+
589
+ @model_validator(mode="after")
590
+ def check_min_max(self) -> "Parameter":
591
+ """Ensure the maximum value of a parameter is greater than the minimum."""
592
+ if self.min > self.max:
593
+ raise ValueError(f"The maximum value {self.max} must be greater than the minimum value {self.min}")
594
+ return self
595
+
596
+ @model_validator(mode="after")
597
+ def check_value_in_range(self) -> "Parameter":
598
+ """Ensure the value of a parameter lies within its defined bounds."""
599
+ if self.value < self.min or self.value > self.max:
600
+ raise ValueError(f"value {self.value} is not within the defined range: {self.min} <= value <= {self.max}")
601
+ return self
602
+
603
+ @property
604
+ def display_fields(self) -> dict:
605
+ """Only display Prior information if ``show_priors`` is true."""
606
+ visible_fields = ["name", "min", "value", "max", "fit"]
607
+ if self.show_priors:
608
+ visible_fields.append("prior_type")
609
+ if self.prior_type == Priors.Gaussian:
610
+ visible_fields.extend(["mu", "sigma"])
611
+
612
+ return {f: getattr(self, f) for f in visible_fields}
613
+
614
+
615
+ class ProtectedParameter(Parameter):
616
+ """A Parameter with a fixed name."""
617
+
618
+ name: str = Field(frozen=True, min_length=1)
619
+
620
+
621
+ class Resolution(Signal):
622
+ """An instrument resolution.
623
+
624
+ Parameters
625
+ ----------
626
+ name : str
627
+ The name of the resolution.
628
+ type : TypeOptions
629
+ The type of resolution: 'constant', 'data', or (NOT YET IMPLEMENTED) 'function'.
630
+ source : str
631
+ The source data for the resolution;
632
+
633
+ - if type is 'constant', this should be the name of a background parameter.
634
+ - if type is 'data', this should be empty (resolution data is in the contrast data).
635
+ - if type is 'function' (NOT YET IMPLEMENTED),
636
+ this should be the name of a custom function defined in `Project.custom_files`.
637
+
638
+ value_1, value_2, value_3, value_4, value_5 : str
639
+ Values required by the background.
640
+
641
+ - if type is 'constant' or 'data', all values will be ignored.
642
+ - if type is 'function' (NOT YET IMPLEMENTED),
643
+ these values may be the names of up to 5 parameters which are passed to the function.
644
+
645
+ """
646
+
647
+ name: str = Field(default_factory=lambda: f"New Resolution {next(resolution_number)}", min_length=1)
648
+
649
+ @field_validator("type")
650
+ @classmethod
651
+ def validate_unimplemented_resolutions(cls, type: TypeOptions):
652
+ """Raise an error if currently unsupported function resolutions are used."""
653
+ # when function resolutions are added, fix the commented-out parts of
654
+ # test_project.py::test_rename_models
655
+ # and test_project.py::test_allowed_resolutions
656
+ if type == TypeOptions.Function:
657
+ raise NotImplementedError("Function resolutions are not yet supported.")
658
+ return type
659
+
660
+ @model_validator(mode="after")
661
+ def check_unsupported_parameters(self):
662
+ """Raise an error if the parameters given are not supported for the given type."""
663
+ if self.type == TypeOptions.Constant:
664
+ expected_empty_fields = ["value_1", "value_2", "value_3", "value_4", "value_5"]
665
+ elif self.type == TypeOptions.Data:
666
+ expected_empty_fields = ["source", "value_1", "value_2", "value_3", "value_4", "value_5"]
667
+ else:
668
+ return self
669
+
670
+ non_empty_fields = [v for v in expected_empty_fields if getattr(self, v) != ""]
671
+ if non_empty_fields:
672
+ raise ValueError(
673
+ f'The following values are not supported by the "{self.type}" Resolution type: '
674
+ f"{', '.join(non_empty_fields)}"
675
+ )
676
+
677
+ return self