RATapi 0.0.0.dev13__cp314-cp314-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 +144 -0
  10. ratapi/examples/convert_rascal_project/Model_IIb.py +90 -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 +34 -0
  26. ratapi/examples/domains/domains_XY_model.py +75 -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 +72 -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 +141 -0
  42. ratapi/examples/normal_reflectivity/custom_bilayer_DSPC.py +89 -0
  43. ratapi/inputs.py +595 -0
  44. ratapi/models.py +717 -0
  45. ratapi/outputs.py +821 -0
  46. ratapi/project.py +1080 -0
  47. ratapi/rat_core.cp314-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 +1235 -0
  55. ratapi/wrappers.py +147 -0
  56. ratapi-0.0.0.dev13.dist-info/METADATA +61 -0
  57. ratapi-0.0.0.dev13.dist-info/RECORD +59 -0
  58. ratapi-0.0.0.dev13.dist-info/WHEEL +5 -0
  59. ratapi-0.0.0.dev13.dist-info/top_level.txt +1 -0
ratapi/inputs.py ADDED
@@ -0,0 +1,595 @@
1
+ """Converts python models to the necessary inputs for the compiled RAT code."""
2
+
3
+ import importlib
4
+ import os
5
+ import pathlib
6
+ from collections.abc import Callable
7
+
8
+ import numpy as np
9
+
10
+ import ratapi
11
+ import ratapi.wrappers
12
+ from ratapi.rat_core import Checks, Control, NameStore, ProblemDefinition
13
+ from ratapi.utils.enums import Calculations, Languages, LayerModels, TypeOptions
14
+
15
+ parameter_field = {
16
+ "parameters": "params",
17
+ "bulk_in": "bulkIns",
18
+ "bulk_out": "bulkOuts",
19
+ "scalefactors": "scalefactors",
20
+ "domain_ratios": "domainRatios",
21
+ "background_parameters": "backgroundParams",
22
+ "resolution_parameters": "resolutionParams",
23
+ }
24
+
25
+
26
+ def get_python_handle(file_name: str, function_name: str, path: str | pathlib.Path = "") -> Callable:
27
+ """Get the function handle from a function defined in a python module located anywhere within the filesystem.
28
+
29
+ Parameters
30
+ ----------
31
+ file_name : str
32
+ The name of the file containing the function of interest.
33
+ function_name : str
34
+ The name of the function we wish to obtain the handle for within the module.
35
+ path : str
36
+ The path to the file containing the function (default is "", which represent the working directory).
37
+
38
+ Returns
39
+ -------
40
+ handle : Callable
41
+ The handle of the function defined in the python module file.
42
+
43
+ """
44
+ spec = importlib.util.spec_from_file_location(pathlib.Path(file_name).stem, os.path.join(path, file_name))
45
+ custom_module = importlib.util.module_from_spec(spec)
46
+ spec.loader.exec_module(custom_module)
47
+ handle = getattr(custom_module, function_name)
48
+ return handle
49
+
50
+
51
+ class FileHandles:
52
+ """Class to defer creation of custom file handles.
53
+
54
+ Parameters
55
+ ----------
56
+ files : ClassList[CustomFile]
57
+ A list of custom file models.
58
+
59
+ """
60
+
61
+ def __init__(self, files=None):
62
+ self.index = 0
63
+ self.files = [] if files is None else [file.model_dump() for file in files]
64
+
65
+ def __iter__(self):
66
+ self.index = 0
67
+ return self
68
+
69
+ def get_handle(self, index: int):
70
+ """Return file handle for a given custom file.
71
+
72
+ Parameters
73
+ ----------
74
+ index : int
75
+ The index of the custom file.
76
+
77
+ """
78
+ custom_file = self.files[index]
79
+ full_path = os.path.join(custom_file["path"], custom_file["filename"])
80
+
81
+ if not os.path.isfile(full_path):
82
+ raise FileNotFoundError(f"The custom file ({custom_file['name']}) does not have a valid path.")
83
+
84
+ if not custom_file["function_name"] and custom_file["language"] != Languages.Matlab:
85
+ raise ValueError(f"The custom file ({custom_file['name']}) does not have a valid function name.")
86
+
87
+ if custom_file["language"] == Languages.Python:
88
+ file_handle = get_python_handle(custom_file["filename"], custom_file["function_name"], custom_file["path"])
89
+ elif custom_file["language"] == Languages.Matlab:
90
+ file_handle = ratapi.wrappers.MatlabWrapper(full_path).getHandle()
91
+ elif custom_file["language"] == Languages.Cpp:
92
+ file_handle = ratapi.wrappers.DylibWrapper(full_path, custom_file["function_name"]).getHandle()
93
+
94
+ return file_handle
95
+
96
+ def copy(self) -> "FileHandles":
97
+ """Create a copy of the FileHandles object.
98
+
99
+ Returns
100
+ -------
101
+ FileHandles
102
+ The copy of this FileHandles object.
103
+
104
+ """
105
+ handles = FileHandles()
106
+ handles.files = [file.copy() for file in self.files]
107
+
108
+ return handles
109
+
110
+ def __next__(self):
111
+ if self.index < len(self.files):
112
+ custom_file = self.get_handle(self.index)
113
+ self.index += 1
114
+ return custom_file
115
+ else:
116
+ raise StopIteration
117
+
118
+ def __len__(self):
119
+ return len(self.files)
120
+
121
+
122
+ def make_input(project: ratapi.Project, controls: ratapi.Controls) -> tuple[ProblemDefinition, Control]:
123
+ """Construct the inputs required for the compiled RAT code using the data defined in the input project and controls.
124
+
125
+ Parameters
126
+ ----------
127
+ project : RAT.Project
128
+ The project model, which defines the physical system under study.
129
+ controls : RAT.Controls
130
+ The controls model, which defines algorithmic properties.
131
+
132
+ Returns
133
+ -------
134
+ problem : RAT.rat_core.ProblemDefinition
135
+ The problem input used in the compiled RAT code.
136
+ cpp_controls : RAT.rat_core.Control
137
+ The controls object used in the compiled RAT code.
138
+
139
+ """
140
+ problem = make_problem(project)
141
+ cpp_controls = make_controls(controls)
142
+
143
+ return problem, cpp_controls
144
+
145
+
146
+ def make_problem(project: ratapi.Project) -> ProblemDefinition:
147
+ """Construct the problem input required for the compiled RAT code.
148
+
149
+ Parameters
150
+ ----------
151
+ project : RAT.Project
152
+ The project model, which defines the physical system under study.
153
+
154
+ Returns
155
+ -------
156
+ problem : RAT.rat_core.ProblemDefinition
157
+ The problem input used in the compiled RAT code.
158
+
159
+ """
160
+ prior_id = {"uniform": 1, "gaussian": 2, "jeffreys": 3}
161
+
162
+ # Ensure all contrast fields are properly defined
163
+ for contrast in project.contrasts:
164
+ contrast_fields = ["data", "background", "bulk_in", "bulk_out", "scalefactor", "resolution"]
165
+
166
+ if project.calculation == Calculations.Domains:
167
+ contrast_fields.append("domain_ratio")
168
+
169
+ for field in contrast_fields:
170
+ if getattr(contrast, field) == "":
171
+ raise ValueError(
172
+ f'In the input project, the "{field}" field of contrast "{contrast.name}" does not have a '
173
+ f"value defined. A value must be supplied before running the project."
174
+ )
175
+
176
+ # Ensure backgrounds and resolutions have a source defined
177
+ background = project.backgrounds[contrast.background]
178
+ resolution = project.resolutions[contrast.resolution]
179
+ if background.source == "":
180
+ raise ValueError(
181
+ f"All backgrounds must have a source defined. For a {background.type} type background, "
182
+ f"the source must be defined in "
183
+ f'"{ratapi.project.values_defined_in[f"backgrounds.{background.type}.source"]}"'
184
+ )
185
+ if resolution.source == "" and resolution.type != TypeOptions.Data:
186
+ raise ValueError(
187
+ f"Constant resolutions must have a source defined. The source must be defined in "
188
+ f'"{ratapi.project.values_defined_in[f"resolutions.{resolution.type}.source"]}"'
189
+ )
190
+
191
+ # Set contrast parameters according to model type
192
+ if project.model == LayerModels.StandardLayers:
193
+ if project.calculation == Calculations.Domains:
194
+ contrast_models = [
195
+ [project.domain_contrasts.index(domain_contrast, True) for domain_contrast in contrast.model]
196
+ for contrast in project.contrasts
197
+ ]
198
+ else:
199
+ contrast_models = [
200
+ [project.layers.index(layer, True) for layer in contrast.model] for contrast in project.contrasts
201
+ ]
202
+ else:
203
+ contrast_models = [[]] * len(project.contrasts)
204
+
205
+ # Set contrast parameters according to model type
206
+ if project.model == LayerModels.StandardLayers:
207
+ contrast_custom_files = [float("NaN")] * len(project.contrasts)
208
+ else:
209
+ contrast_custom_files = [project.custom_files.index(contrast.model[0], True) for contrast in project.contrasts]
210
+
211
+ # Get details of defined layers
212
+ layer_details = get_layer_details(project)
213
+
214
+ contrast_background_params = []
215
+ contrast_background_types = []
216
+ all_data = []
217
+ data_limits = []
218
+ simulation_limits = []
219
+ contrast_resolution_params = []
220
+ contrast_resolution_types = []
221
+
222
+ # Set data, background and resolution for each contrast
223
+ for contrast in project.contrasts:
224
+ # Set data
225
+ data_index = project.data.index(contrast.data)
226
+ data = project.data[data_index].data
227
+ data_range = project.data[data_index].data_range
228
+ simulation_range = project.data[data_index].simulation_range
229
+
230
+ if data_range:
231
+ data_limits.append(data_range)
232
+ else:
233
+ data_limits.append([0.0, 0.0])
234
+
235
+ if simulation_range:
236
+ simulation_limits.append(simulation_range)
237
+ else:
238
+ simulation_limits.append([0.0, 0.0])
239
+
240
+ # Set background parameters
241
+ background = project.backgrounds[contrast.background]
242
+ contrast_background_types.append(background.type)
243
+ contrast_background_param = []
244
+
245
+ if background.type == TypeOptions.Data:
246
+ contrast_background_param.append(project.data.index(background.source, True))
247
+ if background.value_1 != "":
248
+ contrast_background_param.append(project.background_parameters.index(background.value_1))
249
+ # If we are using a data background, we add the background data to the contrast data
250
+ data = append_data_background(data, project.data[background.source].data)
251
+
252
+ elif background.type == TypeOptions.Function:
253
+ contrast_background_param.append(project.custom_files.index(background.source, True))
254
+ contrast_background_param.extend(
255
+ [
256
+ project.background_parameters.index(value, True)
257
+ for value in [
258
+ background.value_1,
259
+ background.value_2,
260
+ background.value_3,
261
+ background.value_4,
262
+ background.value_5,
263
+ ]
264
+ if value != ""
265
+ ]
266
+ )
267
+
268
+ else:
269
+ contrast_background_param.append(project.background_parameters.index(background.source, True))
270
+
271
+ contrast_background_params.append(contrast_background_param)
272
+
273
+ # Set resolution parameters
274
+ resolution = project.resolutions[contrast.resolution]
275
+ contrast_resolution_types.append(resolution.type)
276
+ contrast_resolution_param = []
277
+ if resolution.type == TypeOptions.Function:
278
+ contrast_resolution_param.append(project.custom_files.index(resolution.source, True))
279
+ contrast_resolution_param.extend(
280
+ [
281
+ project.resolution_parameters.index(value, True)
282
+ for value in [
283
+ resolution.value_1,
284
+ resolution.value_2,
285
+ resolution.value_3,
286
+ resolution.value_4,
287
+ resolution.value_5,
288
+ ]
289
+ if value != ""
290
+ ]
291
+ )
292
+
293
+ elif resolution.type == TypeOptions.Constant:
294
+ contrast_resolution_param.append(project.resolution_parameters.index(resolution.source, True))
295
+
296
+ contrast_resolution_params.append(contrast_resolution_param)
297
+
298
+ # Contrast data has exactly six columns to include background data if relevant
299
+ all_data.append(np.column_stack((data, np.zeros((data.shape[0], 6 - data.shape[1])))))
300
+
301
+ problem = ProblemDefinition()
302
+
303
+ problem.TF = project.calculation
304
+ problem.resample = make_resample(project)
305
+ problem.data = all_data
306
+ problem.dataPresent = make_data_present(project)
307
+ problem.dataLimits = data_limits
308
+ problem.simulationLimits = simulation_limits
309
+ problem.numberOfContrasts = len(project.contrasts)
310
+ problem.geometry = project.geometry
311
+ problem.useImaginary = project.absorption
312
+ problem.repeatLayers = [contrast.repeat_layers for contrast in project.contrasts]
313
+ problem.contrastBackgroundParams = contrast_background_params
314
+ problem.contrastBackgroundTypes = contrast_background_types
315
+ problem.contrastBackgroundActions = [contrast.background_action for contrast in project.contrasts]
316
+ problem.contrastScalefactors = [
317
+ project.scalefactors.index(contrast.scalefactor, True) for contrast in project.contrasts
318
+ ]
319
+ problem.contrastBulkIns = [project.bulk_in.index(contrast.bulk_in, True) for contrast in project.contrasts]
320
+ problem.contrastBulkOuts = [project.bulk_out.index(contrast.bulk_out, True) for contrast in project.contrasts]
321
+
322
+ problem.contrastResolutionParams = contrast_resolution_params
323
+ problem.contrastResolutionTypes = contrast_resolution_types
324
+
325
+ problem.backgroundParams = [param.value for param in project.background_parameters]
326
+ problem.scalefactors = [param.value for param in project.scalefactors]
327
+ problem.bulkIns = [param.value for param in project.bulk_in]
328
+ problem.bulkOuts = [param.value for param in project.bulk_out]
329
+ problem.resolutionParams = [param.value for param in project.resolution_parameters]
330
+ problem.params = [param.value for param in project.parameters]
331
+ problem.numberOfLayers = len(project.layers)
332
+ problem.contrastLayers = [contrast_model if contrast_model else [] for contrast_model in contrast_models]
333
+ problem.layersDetails = layer_details if project.model == LayerModels.StandardLayers else []
334
+ problem.customFiles = FileHandles(project.custom_files)
335
+ problem.modelType = project.model
336
+ problem.contrastCustomFiles = contrast_custom_files
337
+
338
+ problem.contrastDomainRatios = [
339
+ project.domain_ratios.index(contrast.domain_ratio, True) if hasattr(contrast, "domain_ratio") else 0
340
+ for contrast in project.contrasts
341
+ ]
342
+
343
+ problem.domainRatios = [param.value for param in project.domain_ratios]
344
+ problem.numberOfDomainContrasts = len(project.domain_contrasts)
345
+
346
+ domain_contrast_models = [
347
+ [project.layers.index(layer, True) for layer in domain_contrast.model]
348
+ for domain_contrast in project.domain_contrasts
349
+ ]
350
+
351
+ problem.domainContrastLayers = [
352
+ domain_contrast_model if domain_contrast_model else [] for domain_contrast_model in domain_contrast_models
353
+ ]
354
+ problem.fitParams = [
355
+ param.value
356
+ for class_list in ratapi.project.parameter_class_lists
357
+ for param in getattr(project, class_list)
358
+ if param.fit
359
+ ]
360
+ problem.fitLimits = [
361
+ [param.min, param.max]
362
+ for class_list in ratapi.project.parameter_class_lists
363
+ for param in getattr(project, class_list)
364
+ if param.fit
365
+ ]
366
+ problem.priorNames = [
367
+ param.name for class_list in ratapi.project.parameter_class_lists for param in getattr(project, class_list)
368
+ ]
369
+ problem.priorValues = [
370
+ [prior_id[param.prior_type], param.mu, param.sigma]
371
+ for class_list in ratapi.project.parameter_class_lists
372
+ for param in getattr(project, class_list)
373
+ ]
374
+
375
+ # Names
376
+ problem.names = NameStore()
377
+ for class_list in ratapi.project.parameter_class_lists:
378
+ setattr(problem.names, parameter_field[class_list], [param.name for param in getattr(project, class_list)])
379
+ problem.names.contrasts = [contrast.name for contrast in project.contrasts]
380
+
381
+ # Checks
382
+ problem.checks = Checks()
383
+ for class_list in ratapi.project.parameter_class_lists:
384
+ setattr(
385
+ problem.checks, parameter_field[class_list], [int(element.fit) for element in getattr(project, class_list)]
386
+ )
387
+
388
+ check_indices(problem)
389
+
390
+ return problem
391
+
392
+
393
+ def get_layer_details(project: ratapi.Project) -> list[int]:
394
+ """Get parameter indices for all layers defined in the project."""
395
+ hydrate_id = {"bulk in": 0, "bulk out": 1}
396
+ layer_details = []
397
+
398
+ # Get the thickness, SLD, roughness fields from the appropriate model
399
+ if project.absorption:
400
+ layer_fields = list(ratapi.models.AbsorptionLayer.model_fields.keys())[1:-2]
401
+ else:
402
+ layer_fields = list(ratapi.models.Layer.model_fields.keys())[1:-2]
403
+
404
+ for layer in project.layers:
405
+ for field in layer_fields:
406
+ if getattr(layer, field) == "":
407
+ raise ValueError(
408
+ f'In the input project, the "{field}" field of layer {layer.name} does not have a value '
409
+ f"defined. A value must be supplied before running the project."
410
+ )
411
+
412
+ layer_params = [project.parameters.index(getattr(layer, attribute), True) for attribute in list(layer_fields)]
413
+
414
+ layer_params.append(project.parameters.index(layer.hydration, True) if layer.hydration else float("NaN"))
415
+ layer_params.append(hydrate_id[layer.hydrate_with])
416
+
417
+ layer_details.append(layer_params)
418
+
419
+ return layer_details
420
+
421
+
422
+ def make_resample(project: ratapi.Project) -> list[int]:
423
+ """Construct the "resample" field of the problem input required for the compiled RAT code.
424
+
425
+ Parameters
426
+ ----------
427
+ project : RAT.Project
428
+ The project model, which defines the physical system under study.
429
+
430
+ Returns
431
+ -------
432
+ list[int]
433
+ The "resample" field of the problem input used in the compiled RAT code.
434
+
435
+ """
436
+ return [contrast.resample for contrast in project.contrasts]
437
+
438
+
439
+ def make_data_present(project: ratapi.Project) -> list[int]:
440
+ """Construct the "dataPresent" field of the problem input required for the compiled RAT code.
441
+
442
+ Parameters
443
+ ----------
444
+ project : RAT.Project
445
+ The project model, which defines the physical system under study.
446
+
447
+ Returns
448
+ -------
449
+ list[int]
450
+ The "dataPresent" field of the problem input used in the compiled RAT code.
451
+
452
+ """
453
+ return [1 if project.data[contrast.data].data.size != 0 else 0 for contrast in project.contrasts]
454
+
455
+
456
+ def check_indices(problem: ProblemDefinition) -> None:
457
+ """Check the indices given in a problem's contrasts lie within the range of the corresponding parameter lists.
458
+
459
+ Parameters
460
+ ----------
461
+ problem : RAT.rat_core.ProblemDefinition
462
+ The problem input used in the compiled RAT code.
463
+
464
+ """
465
+ index_list = {
466
+ "scalefactors": "contrastScalefactors",
467
+ "bulkIns": "contrastBulkIns",
468
+ "bulkOuts": "contrastBulkOuts",
469
+ "domainRatios": "contrastDomainRatios",
470
+ }
471
+
472
+ # Check the indices -- note we have switched to 1-based indexing at this point
473
+ for params in index_list:
474
+ param_list = getattr(problem, params)
475
+ if len(param_list) > 0:
476
+ elements = [
477
+ element
478
+ for element in getattr(problem, index_list[params])
479
+ if (element != -1) and not (0 < element <= len(param_list))
480
+ ]
481
+ if elements:
482
+ raise IndexError(
483
+ f'The problem field "{index_list[params]}" contains: {", ".join(str(i) for i in elements)}'
484
+ f', which lie{"s" * (len(elements) == 1)} outside of the range of "{params}"',
485
+ )
486
+
487
+ # backgroundParams has a different structure, so is handled separately:
488
+ # it is of type list[list[int]], where each list[int] is the indices for
489
+ # source, value_1, value_2, value_3, value_4, value_5 where they are defined
490
+ # e.g. for a data background with offset it is [source value_1], for a function
491
+ # with 3 values it is [source value_1 value_2 value_3], etc.
492
+
493
+ source_param_lists = {
494
+ "constant": "backgroundParams",
495
+ "data": "data",
496
+ "function": "customFiles",
497
+ }
498
+
499
+ for i, background_data in enumerate(problem.contrastBackgroundParams):
500
+ background_type = problem.contrastBackgroundTypes[i]
501
+
502
+ # check source param is in range of the relevant parameter list
503
+ param_list = getattr(problem, source_param_lists[background_type])
504
+ source_index = background_data[0]
505
+ if not 0 < source_index <= len(param_list):
506
+ raise IndexError(
507
+ f'Entry {i} of contrastBackgroundParams has type "{background_type}" '
508
+ f"and source index {source_index}, "
509
+ f'which is outside the range of "{source_param_lists[background_type]}".'
510
+ )
511
+
512
+ # check value params are in range for background params
513
+ if len(background_data) > 1:
514
+ elements = [element for element in background_data[1:] if not 0 < element <= len(problem.backgroundParams)]
515
+ if elements:
516
+ raise IndexError(
517
+ f"Entry {i} of contrastBackgroundParams contains: {', '.join(str(i) for i in elements)}"
518
+ f', which lie{"s" * (len(elements) == 1)} outside of the range of "backgroundParams"',
519
+ )
520
+
521
+
522
+ def append_data_background(data: np.array, background: np.array) -> np.array:
523
+ """Append background data to contrast data.
524
+
525
+ Parameters
526
+ ----------
527
+ data : np.array
528
+ The contrast data to which we are appending a background.
529
+ background : np.array
530
+ The background data to append to the contrast.
531
+
532
+ Returns
533
+ -------
534
+ np.array
535
+ The contrast data with background data appended as two additional columns.
536
+
537
+ """
538
+ if not np.allclose(data[:, 0], background[:, 0]):
539
+ raise ValueError("The q-values of the data and background must be equal.")
540
+
541
+ return np.hstack((data, np.zeros((data.shape[0], 4 - data.shape[1])), background[:, 1:]))
542
+
543
+
544
+ def make_controls(input_controls: ratapi.Controls) -> Control:
545
+ """Convert the controls object to the format required by the compiled RAT code.
546
+
547
+ Parameters
548
+ ----------
549
+ input_controls : RAT.Controls
550
+ The controls model, which defines algorithmic properties.
551
+
552
+ Returns
553
+ -------
554
+ controls : RAT.rat_core.Control
555
+ The controls object used in the compiled RAT code.
556
+
557
+ """
558
+ controls = Control()
559
+
560
+ controls.procedure = input_controls.procedure
561
+ controls.parallel = input_controls.parallel
562
+ controls.numSimulationPoints = input_controls.numSimulationPoints
563
+ controls.resampleMinAngle = input_controls.resampleMinAngle
564
+ controls.resampleNPoints = input_controls.resampleNPoints
565
+ controls.display = input_controls.display
566
+ # Simplex
567
+ controls.xTolerance = input_controls.xTolerance
568
+ controls.funcTolerance = input_controls.funcTolerance
569
+ controls.maxFuncEvals = input_controls.maxFuncEvals
570
+ controls.maxIterations = input_controls.maxIterations
571
+ controls.updateFreq = input_controls.updateFreq
572
+ controls.updatePlotFreq = input_controls.updatePlotFreq
573
+ # DE
574
+ controls.populationSize = input_controls.populationSize
575
+ controls.fWeight = input_controls.fWeight
576
+ controls.crossoverProbability = input_controls.crossoverProbability
577
+ controls.strategy = int(input_controls.strategy) # RAT core expects strategy as an integer
578
+ controls.targetValue = input_controls.targetValue
579
+ controls.numGenerations = input_controls.numGenerations
580
+ # NS
581
+ controls.nLive = input_controls.nLive
582
+ controls.nMCMC = input_controls.nMCMC
583
+ controls.propScale = input_controls.propScale
584
+ controls.nsTolerance = input_controls.nsTolerance
585
+ # Dream
586
+ controls.nSamples = input_controls.nSamples
587
+ controls.nChains = input_controls.nChains
588
+ controls.jumpProbability = input_controls.jumpProbability
589
+ controls.pUnitGamma = input_controls.pUnitGamma
590
+ controls.boundHandling = input_controls.boundHandling
591
+ controls.adaptPCR = input_controls.adaptPCR
592
+
593
+ controls.IPCFilePath = input_controls._IPCFilePath
594
+
595
+ return controls