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/utils/enums.py ADDED
@@ -0,0 +1,204 @@
1
+ """The Enum values used in the parameters of various ratapi classes and functions."""
2
+
3
+ try:
4
+ from enum import StrEnum
5
+ except ImportError:
6
+ from strenum import StrEnum
7
+
8
+
9
+ class RATEnum(StrEnum):
10
+ """A subclass of StrEnum with some adjustments for variable spellings."""
11
+
12
+ @classmethod
13
+ def _missing_(cls, value: str):
14
+ value = value.lower()
15
+
16
+ # Replace common alternative spellings
17
+ value = value.replace("-", " ").replace("_", " ").replace("++", "pp").replace("polarized", "polarised")
18
+
19
+ for member in cls:
20
+ if member.value.lower() == value:
21
+ return member
22
+ return None
23
+
24
+
25
+ # Controls
26
+ class Procedures(RATEnum):
27
+ """The available options for procedures."""
28
+
29
+ Calculate = "calculate"
30
+ """Run an Abelès reflectivity calculation and calculate chi-squared to the data."""
31
+
32
+ Simplex = "simplex"
33
+ """Run a Nelder-Mead simplex optimisation over the fit parameters."""
34
+
35
+ DE = "de"
36
+ """Run a Differential Evolution optimisation over the fit parameters."""
37
+
38
+ NS = "ns"
39
+ """Run Bayesian Nested Sampling over the fit parameters."""
40
+
41
+ DREAM = "dream"
42
+ """Run the Bayesian DREAM algorithm over the fit parameters."""
43
+
44
+
45
+ class Parallel(RATEnum):
46
+ """The available options for parallelisation."""
47
+
48
+ Single = "single"
49
+ """Do not parallelise."""
50
+
51
+ Points = "points"
52
+ """Split all contrasts into groups of points, and assign a process to each group."""
53
+
54
+ Contrasts = "contrasts"
55
+ """Assign one process to each contrast."""
56
+
57
+
58
+ class Display(RATEnum):
59
+ """The available options for terminal output."""
60
+
61
+ Off = "off"
62
+ Iter = "iter"
63
+ Notify = "notify"
64
+ Final = "final"
65
+
66
+
67
+ class Strategies(RATEnum):
68
+ """The available strategies for generating base vectors in differential evolution."""
69
+
70
+ Random = "random"
71
+ """The base vector is random."""
72
+
73
+ LocalToBest = "local to best"
74
+ """The base vector is a combination of one randomly-selected local solution
75
+ and the best solution of the previous iteration."""
76
+
77
+ BestWithJitter = "best jitter"
78
+ """The base vector is the best solution of the previous iteration, with a small random perturbation applied."""
79
+
80
+ RandomWithPerVectorDither = "vector dither"
81
+ """The base vector is random, with a random scaling factor applied to each mutant.
82
+ This scaling factor is different for each mutant."""
83
+
84
+ RandomWithPerGenerationDither = "generation dither"
85
+ """The base vector is random, with a random scaling factor applied to each mutant.
86
+ This scaling factor is the same for every mutant, and randomised every generation."""
87
+
88
+ RandomEitherOrAlgorithm = "either or"
89
+ """The base vector is randomly chosen from either a pure random mutation,
90
+ or a pure recombination of parent parameter values."""
91
+
92
+ @classmethod
93
+ def _missing_(cls, value: int | str):
94
+ # legacy compatibility with strategies being 1-indexed ints under the hood
95
+ if isinstance(value, int):
96
+ if value < 1 or value > 6:
97
+ raise IndexError("Strategy indices must be between 1 and 6.")
98
+ return list(cls)[value - 1]
99
+ return super()._missing_(value)
100
+
101
+ def __int__(self):
102
+ """Convert the DE strategy to its hardcoded index in the internal code.
103
+
104
+ RAT core expects strategy to be an integer, as this is how it is given to
105
+ the internal DE algorithm.
106
+ """
107
+ return list(Strategies).index(self) + 1
108
+
109
+
110
+ class BoundHandling(RATEnum):
111
+ """The available options for bound handling in DREAM."""
112
+
113
+ Off = "off"
114
+ """Allow points to be sampled out of the parameter bounds."""
115
+
116
+ Reflect = "reflect"
117
+ """If a step passes a boundary, reflect it back across the boundary."""
118
+
119
+ Bound = "bound"
120
+ """If a step passes a boundary, set it equal to the nearest point on the boundary."""
121
+
122
+ Fold = "fold"
123
+ """Treat the boundary as periodic and ‘wrap the step around’ to the other side of the space."""
124
+
125
+
126
+ # Models
127
+ class TypeOptions(RATEnum):
128
+ """The types of signal (``Background`` and ``Resolution``)."""
129
+
130
+ Constant = "constant"
131
+ """A uniform constant signal given by a parameter."""
132
+
133
+ Data = "data"
134
+ """A signal for each q-value given by a dataset."""
135
+
136
+ Function = "function"
137
+ """A signal defined by a custom function."""
138
+
139
+
140
+ class BackgroundActions(RATEnum):
141
+ """Ways that the background can be applied to the model."""
142
+
143
+ Add = "add"
144
+ Subtract = "subtract"
145
+
146
+
147
+ class Languages(RATEnum):
148
+ """Language options for custom files."""
149
+
150
+ Cpp = "cpp"
151
+ Python = "python"
152
+ Matlab = "matlab"
153
+
154
+
155
+ class Hydration(RATEnum):
156
+ """Options for the 'hydrate with' parameter of a Layer."""
157
+
158
+ BulkIn = "bulk in"
159
+ BulkOut = "bulk out"
160
+
161
+
162
+ class Priors(RATEnum):
163
+ """Prior distributions for parameters."""
164
+
165
+ Uniform = "uniform"
166
+ """A uniform distribution over the parameter range."""
167
+
168
+ Gaussian = "gaussian"
169
+ """A Gaussian distribution centred on the parameter value,
170
+ with shape defined by ``mu`` and ``sigma`` for the parameter."""
171
+
172
+ Jeffreys = "jeffreys"
173
+ """A Jeffreys' prior distribution over the parameter range."""
174
+
175
+
176
+ # Project
177
+ class Calculations(RATEnum):
178
+ """Types of calculations that can be performed by RAT."""
179
+
180
+ Normal = "normal"
181
+ Domains = "domains"
182
+
183
+
184
+ class LayerModels(RATEnum):
185
+ """Types of layer model supported by RAT."""
186
+
187
+ CustomLayers = "custom layers"
188
+ """The layer model is given by a custom function."""
189
+
190
+ CustomXY = "custom xy"
191
+ """The continuous SLD of the layer model is given by a custom function."""
192
+
193
+ StandardLayers = "standard layers"
194
+ """The layer model is given by a list of ``Layer``s or ``DomainContrast``s."""
195
+
196
+
197
+ class Geometries(RATEnum):
198
+ """Where the substrate roughness is placed."""
199
+
200
+ AirSubstrate = "air/substrate"
201
+ """The substrate roughness is placed at the end of the stack."""
202
+
203
+ SubstrateLiquid = "substrate/liquid"
204
+ """The substrate roughness is placed at the beginning of the stack."""
ratapi/utils/orso.py ADDED
@@ -0,0 +1,247 @@
1
+ """Readers from file formats."""
2
+
3
+ from dataclasses import dataclass
4
+ from itertools import count
5
+ from pathlib import Path
6
+ from textwrap import shorten
7
+
8
+ import orsopy
9
+ import prettytable
10
+ from orsopy.fileio import load_orso
11
+
12
+ from ratapi import ClassList
13
+ from ratapi.models import AbsorptionLayer, Data, Layer, Parameter
14
+
15
+
16
+ class ORSOProject:
17
+ """A class to encapsulate model information and data from an .ort file.
18
+
19
+ Parameters
20
+ ----------
21
+ filepath : str or Path
22
+ The path to the .ort file.
23
+ absorption : bool, default None
24
+ Whether to account for absorption in the model data.
25
+
26
+ """
27
+
28
+ def __init__(self, filepath: str | Path, absorption: bool = False):
29
+ ort_data = load_orso(filepath)
30
+ datasets = [Data(name=dataset.info.data_source.sample.name, data=dataset.data) for dataset in ort_data]
31
+ # orso datasets in the same file can have repeated names!
32
+ # but classlists do not allow this
33
+ # use this dict to keep track of counts for repeated names
34
+ name_counts = {d.name: count(1) for d in datasets}
35
+ names = [d.name for d in datasets]
36
+ if len(names) > len(list(set(names))):
37
+ for i, data in enumerate(datasets):
38
+ if data.name in names[:i]:
39
+ data.name += f"-{next(name_counts[data.name])}"
40
+ self.data = ClassList(datasets)
41
+ self.samples = [
42
+ orso_model_to_rat(dataset.info.data_source.sample.model, absorption=absorption) for dataset in ort_data
43
+ ]
44
+
45
+ def __str__(self):
46
+ data_str = f"Data:\n{str(self.data)}\n\n"
47
+ if len(self.samples) == 1:
48
+ samples_str = f"Sample:\n{str(self.samples[0])}"
49
+ else:
50
+ table = prettytable.PrettyTable()
51
+ table.field_names = ["index", "bulk in", "bulk out", "parameters", "layers", "model"]
52
+ for index, sample in enumerate(self.samples):
53
+ if sample is None:
54
+ row = [index, "", "", "", "", ""]
55
+ else:
56
+ row = [
57
+ index,
58
+ sample.bulk_in.name,
59
+ sample.bulk_out.name,
60
+ shorten(", ".join([p.name for p in sample.parameters]), width=20, placeholder="..."),
61
+ shorten(", ".join([layer.name for layer in sample.layers]), width=20, placeholder="..."),
62
+ shorten(str(sample.model), width=20, placeholder="..."),
63
+ ]
64
+ table.add_row(row)
65
+ samples_str = table.get_string()
66
+
67
+ return data_str + samples_str
68
+
69
+
70
+ @dataclass
71
+ class ORSOSample:
72
+ """The stack data from an ORSO SampleModel, in RAT models."""
73
+
74
+ bulk_in: Parameter
75
+ bulk_out: Parameter
76
+ parameters: ClassList[Parameter]
77
+ layers: ClassList[Layer] | ClassList[AbsorptionLayer]
78
+ model: list[str]
79
+
80
+ def __str__(self):
81
+ return (
82
+ "Bulk in:\n"
83
+ f"{str(self.bulk_in)}\n\n"
84
+ "Bulk out:\n"
85
+ f"{str(self.bulk_out)}\n\n"
86
+ "Parameters:\n"
87
+ f"{str(self.parameters)}\n\n"
88
+ "Layers:\n"
89
+ f"{str(self.layers)}\n\n"
90
+ "Model:\n"
91
+ f"{self.model}"
92
+ )
93
+
94
+
95
+ def orso_model_to_rat(
96
+ model: orsopy.fileio.model_language.SampleModel | str, absorption: bool = False
97
+ ) -> ORSOSample | None:
98
+ """Get information from an ORSO SampleModel object.
99
+
100
+ Parameters
101
+ ----------
102
+ model : orsopy.fileio.model_language.SampleModel or str
103
+ The sample model to turn into a RAT data. If given as a string,
104
+ the string is interpreted as a layer stack in ORSO model language.
105
+ absorption : bool, default False
106
+ Whether to account for absorption in the model.
107
+
108
+ Returns
109
+ -------
110
+ ORSOSample
111
+ A dataclass containing the sample data, or None if the model is None.
112
+
113
+ """
114
+ if model is None:
115
+ return None
116
+
117
+ if isinstance(model, str):
118
+ model = orsopy.fileio.model_language.SampleModel(stack=model)
119
+
120
+ stack = model.resolve_to_layers()
121
+ # if bulk in or out is air, it has SLD predefined
122
+ # else we need to grab it from SLDDB
123
+ if bulk_in_sld := stack[0].material.sld is None:
124
+ bulk_in_sld = stack[0].material.get_sld()
125
+
126
+ # resolve_to_layers loses the name of bulk in and out
127
+ bulk_in_name = model.stack.split("|")[0].strip()
128
+ bulk_in = Parameter(
129
+ name=f"{bulk_in_name} SLD",
130
+ min=bulk_in_sld.real,
131
+ value=bulk_in_sld.real,
132
+ max=bulk_in_sld.real,
133
+ fit=False,
134
+ )
135
+
136
+ if bulk_out_sld := stack[-1].material.sld is None:
137
+ bulk_out_sld = stack[-1].material.get_sld()
138
+
139
+ bulk_out_name = model.stack.split("|")[-1].strip()
140
+ bulk_out = Parameter(
141
+ name=f"{bulk_out_name} SLD",
142
+ min=bulk_out_sld.real,
143
+ value=bulk_out_sld.real,
144
+ max=bulk_out_sld.real,
145
+ fit=False,
146
+ )
147
+
148
+ parameters = ClassList()
149
+ layers = ClassList()
150
+ contrast_model = []
151
+
152
+ for orso_layer in stack[1:-1]:
153
+ name = get_material_name(orso_layer.material, model)
154
+ contrast_model.append(name)
155
+ layer_params, layer = orso_layer_to_rat_layer(orso_layer, name, absorption)
156
+ parameters.union(layer_params)
157
+ layers.union(layer)
158
+
159
+ return ORSOSample(
160
+ bulk_in=bulk_in,
161
+ bulk_out=bulk_out,
162
+ parameters=parameters,
163
+ layers=layers,
164
+ model=contrast_model,
165
+ )
166
+
167
+
168
+ def orso_layer_to_rat_layer(
169
+ layer: orsopy.fileio.model_language.Layer, name: str, absorption: bool = False
170
+ ) -> tuple[ClassList[Parameter], Layer]:
171
+ """Convert an ``orsopy`` layer to a RAT layer.
172
+
173
+ Parameters
174
+ ----------
175
+ layer : orsopy.fileio.model_language.Layer
176
+ An ``orsopy`` Layer.
177
+ name : str
178
+ The name of the material in the layer.
179
+ absorption : bool, default True
180
+ Whether absorption should be accounted for in the layer.
181
+
182
+ Returns
183
+ -------
184
+ ClassList[Parameter], Layer
185
+ The parameters required for the RAT layer and the layer itself.
186
+
187
+ """
188
+ thickness = layer.thickness.as_unit("angstrom")
189
+ roughness = layer.roughness.as_unit("angstrom")
190
+ sld = layer.material.get_sld()
191
+
192
+ params = ClassList(
193
+ [
194
+ Parameter(name=f"{name} Thickness", min=thickness, value=thickness, max=thickness, fit=False),
195
+ Parameter(name=f"{name} Roughness", min=roughness, value=roughness, max=roughness, fit=False),
196
+ Parameter(name=f"{name} SLD", min=sld.real, value=sld.real, max=sld.real, fit=False),
197
+ ]
198
+ )
199
+ if absorption:
200
+ params.append(Parameter(name=f"{name} SLD imaginary", min=sld.imag, value=sld.imag, max=sld.imag, fit=False))
201
+ layer = AbsorptionLayer(
202
+ name=name,
203
+ thickness=f"{name} Thickness",
204
+ roughness=f"{name} Roughness",
205
+ SLD_real=f"{name} SLD",
206
+ SLD_imaginary=f"{name} SLD imaginary",
207
+ )
208
+ else:
209
+ layer = Layer(
210
+ name=name,
211
+ thickness=f"{name} Thickness",
212
+ roughness=f"{name} Roughness",
213
+ SLD=f"{name} SLD",
214
+ )
215
+
216
+ return params, layer
217
+
218
+
219
+ def get_material_name(
220
+ material: orsopy.fileio.model_language.Material, model: orsopy.fileio.model_language.SampleModel
221
+ ) -> str:
222
+ """Get the name of a material in the model.
223
+
224
+ Layers with custom property definitions may not have a formula, so this adjusts the name for that.
225
+
226
+ Parameters
227
+ ----------
228
+ material : Material
229
+ The material to get the name of.
230
+ model : SampleModel
231
+ The sample model from which the material came.
232
+
233
+ Returns
234
+ -------
235
+ str
236
+ The name of the material.
237
+
238
+ """
239
+ if material.formula is not None:
240
+ return material.formula
241
+ else:
242
+ matching_materials = [k for k, v in model.materials.items() if v == material]
243
+ if matching_materials:
244
+ return matching_materials[0]
245
+ else:
246
+ # orsopy should catch that this is the case before we get here, but just in case...
247
+ raise ValueError("ORSO model contains layers with undefined materials!")