RATapi 0.0.0.dev0__cp310-cp310-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 (64) hide show
  1. RATapi/__init__.py +8 -0
  2. RATapi/classlist.py +387 -0
  3. RATapi/controls.py +143 -0
  4. RATapi/eventManager.dll +0 -0
  5. RATapi/events.py +70 -0
  6. RATapi/examples/__init__.py +0 -0
  7. RATapi/examples/absorption/__init__.py +0 -0
  8. RATapi/examples/absorption/absorption.py +148 -0
  9. RATapi/examples/absorption/volume_thiol_bilayer.py +138 -0
  10. RATapi/examples/data/D2O_spin_down.dat +100 -0
  11. RATapi/examples/data/D2O_spin_up.dat +101 -0
  12. RATapi/examples/data/DSPC_D2O.dat +82 -0
  13. RATapi/examples/data/DSPC_SMW.dat +82 -0
  14. RATapi/examples/data/H2O_spin_down.dat +102 -0
  15. RATapi/examples/data/H2O_spin_up.dat +102 -0
  16. RATapi/examples/data/__init__.py +0 -0
  17. RATapi/examples/data/c_PLP0016596.dat +146 -0
  18. RATapi/examples/data/c_PLP0016601.dat +97 -0
  19. RATapi/examples/data/c_PLP0016607.dat +104 -0
  20. RATapi/examples/domains/__init__.py +0 -0
  21. RATapi/examples/domains/alloy_domains.py +26 -0
  22. RATapi/examples/domains/domains_XY_model.py +70 -0
  23. RATapi/examples/domains/domains_custom_XY.py +69 -0
  24. RATapi/examples/domains/domains_custom_layers.py +46 -0
  25. RATapi/examples/domains/domains_standard_layers.py +75 -0
  26. RATapi/examples/languages/__init__.py +0 -0
  27. RATapi/examples/languages/custom_bilayer.py +66 -0
  28. RATapi/examples/languages/run_custom_file_languages.py +41 -0
  29. RATapi/examples/languages/setup_problem.py +130 -0
  30. RATapi/examples/non_polarised/DSPC_custom_XY.py +140 -0
  31. RATapi/examples/non_polarised/DSPC_custom_layers.py +121 -0
  32. RATapi/examples/non_polarised/DSPC_standard_layers.py +358 -0
  33. RATapi/examples/non_polarised/__init__.py +0 -0
  34. RATapi/examples/non_polarised/custom_XY_DSPC.py +137 -0
  35. RATapi/examples/non_polarised/custom_bilayer_DSPC.py +85 -0
  36. RATapi/inputs.py +471 -0
  37. RATapi/models.py +288 -0
  38. RATapi/outputs.py +218 -0
  39. RATapi/project.py +659 -0
  40. RATapi/rat_core.cp310-win_amd64.pyd +0 -0
  41. RATapi/run.py +35 -0
  42. RATapi/utils/__init__.py +0 -0
  43. RATapi/utils/custom_errors.py +42 -0
  44. RATapi/utils/enums.py +101 -0
  45. RATapi/utils/plotting.py +211 -0
  46. RATapi/wrappers.py +115 -0
  47. RATapi-0.0.0.dev0.dist-info/METADATA +57 -0
  48. RATapi-0.0.0.dev0.dist-info/RECORD +64 -0
  49. RATapi-0.0.0.dev0.dist-info/WHEEL +5 -0
  50. RATapi-0.0.0.dev0.dist-info/top_level.txt +2 -0
  51. tests/__init__.py +0 -0
  52. tests/conftest.py +4728 -0
  53. tests/test_classlist.py +882 -0
  54. tests/test_controls.py +863 -0
  55. tests/test_custom_errors.py +49 -0
  56. tests/test_events.py +61 -0
  57. tests/test_inputs.py +908 -0
  58. tests/test_models.py +308 -0
  59. tests/test_outputs.py +31 -0
  60. tests/test_plotting.py +167 -0
  61. tests/test_project.py +1387 -0
  62. tests/test_run.py +570 -0
  63. tests/test_wrappers.py +57 -0
  64. tests/utils.py +171 -0
tests/test_project.py ADDED
@@ -0,0 +1,1387 @@
1
+ """Test the project module."""
2
+
3
+ import copy
4
+ import os
5
+ import shutil
6
+ import tempfile
7
+ from typing import Callable
8
+
9
+ import numpy as np
10
+ import pydantic
11
+ import pytest
12
+
13
+ import RATapi
14
+ from RATapi.utils.enums import Calculations, LayerModels
15
+
16
+ layer_params = {"thickness": "Test Thickness", "SLD": "Test SLD", "roughness": "Test Roughness"}
17
+ absorption_layer_params = {
18
+ "thickness": "Test Thickness",
19
+ "SLD_real": "Test SLD",
20
+ "SLD_imaginary": "Test SLD",
21
+ "roughness": "Test Roughness",
22
+ }
23
+
24
+
25
+ @pytest.fixture
26
+ def test_project():
27
+ """Add parameters to the default project, so each ClassList can be tested properly."""
28
+ test_project = RATapi.Project(
29
+ data=RATapi.ClassList([RATapi.models.Data(name="Simulation", data=np.array([[1.0, 1.0, 1.0]]))]),
30
+ )
31
+ test_project.parameters.append(name="Test Thickness")
32
+ test_project.parameters.append(name="Test SLD")
33
+ test_project.parameters.append(name="Test Roughness")
34
+ test_project.custom_files.append(name="Test Custom File")
35
+ test_project.layers.append(
36
+ name="Test Layer",
37
+ thickness="Test Thickness",
38
+ SLD="Test SLD",
39
+ roughness="Test Roughness",
40
+ )
41
+ test_project.contrasts.append(
42
+ name="Test Contrast",
43
+ data="Simulation",
44
+ background="Background 1",
45
+ bulk_in="SLD Air",
46
+ bulk_out="SLD D2O",
47
+ scalefactor="Scalefactor 1",
48
+ resolution="Resolution 1",
49
+ model=["Test Layer"],
50
+ )
51
+ return test_project
52
+
53
+
54
+ @pytest.fixture
55
+ def default_project_str():
56
+ """A string of the output of str() for a Project model with no parameters specified."""
57
+ return (
58
+ "Calculation: ---------------------------------------------------------------------------------------\n\n"
59
+ "non polarised\n\n"
60
+ "Model: ---------------------------------------------------------------------------------------------\n\n"
61
+ "standard layers\n\n"
62
+ "Geometry: ------------------------------------------------------------------------------------------\n\n"
63
+ "air/substrate\n\n"
64
+ "Parameters: ----------------------------------------------------------------------------------------\n\n"
65
+ "+-------+---------------------+-----+-------+-----+------+------------+-----+-------+\n"
66
+ "| index | name | min | value | max | fit | prior type | mu | sigma |\n"
67
+ "+-------+---------------------+-----+-------+-----+------+------------+-----+-------+\n"
68
+ "| 0 | Substrate Roughness | 1.0 | 3.0 | 5.0 | True | uniform | 0.0 | inf |\n"
69
+ "+-------+---------------------+-----+-------+-----+------+------------+-----+-------+\n\n"
70
+ "Bulk In: -------------------------------------------------------------------------------------------\n\n"
71
+ "+-------+---------+-----+-------+-----+-------+------------+-----+-------+\n"
72
+ "| index | name | min | value | max | fit | prior type | mu | sigma |\n"
73
+ "+-------+---------+-----+-------+-----+-------+------------+-----+-------+\n"
74
+ "| 0 | SLD Air | 0.0 | 0.0 | 0.0 | False | uniform | 0.0 | inf |\n"
75
+ "+-------+---------+-----+-------+-----+-------+------------+-----+-------+\n\n"
76
+ "Bulk Out: ------------------------------------------------------------------------------------------\n\n"
77
+ "+-------+---------+---------+----------+----------+-------+------------+-----+-------+\n"
78
+ "| index | name | min | value | max | fit | prior type | mu | sigma |\n"
79
+ "+-------+---------+---------+----------+----------+-------+------------+-----+-------+\n"
80
+ "| 0 | SLD D2O | 6.2e-06 | 6.35e-06 | 6.35e-06 | False | uniform | 0.0 | inf |\n"
81
+ "+-------+---------+---------+----------+----------+-------+------------+-----+-------+\n\n"
82
+ "Scalefactors: --------------------------------------------------------------------------------------\n\n"
83
+ "+-------+---------------+------+-------+------+-------+------------+-----+-------+\n"
84
+ "| index | name | min | value | max | fit | prior type | mu | sigma |\n"
85
+ "+-------+---------------+------+-------+------+-------+------------+-----+-------+\n"
86
+ "| 0 | Scalefactor 1 | 0.02 | 0.23 | 0.25 | False | uniform | 0.0 | inf |\n"
87
+ "+-------+---------------+------+-------+------+-------+------------+-----+-------+\n\n"
88
+ "Background Parameters: -----------------------------------------------------------------------------\n\n"
89
+ "+-------+--------------------+-------+-------+-------+-------+------------+-----+-------+\n"
90
+ "| index | name | min | value | max | fit | prior type | mu | sigma |\n"
91
+ "+-------+--------------------+-------+-------+-------+-------+------------+-----+-------+\n"
92
+ "| 0 | Background Param 1 | 1e-07 | 1e-06 | 1e-05 | False | uniform | 0.0 | inf |\n"
93
+ "+-------+--------------------+-------+-------+-------+-------+------------+-----+-------+\n\n"
94
+ "Backgrounds: ---------------------------------------------------------------------------------------\n\n"
95
+ "+-------+--------------+----------+--------------------+---------+---------+---------+---------+\n"
96
+ "| index | name | type | value 1 | value 2 | value 3 | value 4 | value 5 |\n"
97
+ "+-------+--------------+----------+--------------------+---------+---------+---------+---------+\n"
98
+ "| 0 | Background 1 | constant | Background Param 1 | | | | |\n"
99
+ "+-------+--------------+----------+--------------------+---------+---------+---------+---------+\n\n"
100
+ "Resolution Parameters: -----------------------------------------------------------------------------\n\n"
101
+ "+-------+--------------------+------+-------+------+-------+------------+-----+-------+\n"
102
+ "| index | name | min | value | max | fit | prior type | mu | sigma |\n"
103
+ "+-------+--------------------+------+-------+------+-------+------------+-----+-------+\n"
104
+ "| 0 | Resolution Param 1 | 0.01 | 0.03 | 0.05 | False | uniform | 0.0 | inf |\n"
105
+ "+-------+--------------------+------+-------+------+-------+------------+-----+-------+\n\n"
106
+ "Resolutions: ---------------------------------------------------------------------------------------\n\n"
107
+ "+-------+--------------+----------+--------------------+---------+---------+---------+---------+\n"
108
+ "| index | name | type | value 1 | value 2 | value 3 | value 4 | value 5 |\n"
109
+ "+-------+--------------+----------+--------------------+---------+---------+---------+---------+\n"
110
+ "| 0 | Resolution 1 | constant | Resolution Param 1 | | | | |\n"
111
+ "+-------+--------------+----------+--------------------+---------+---------+---------+---------+\n\n"
112
+ "Data: ----------------------------------------------------------------------------------------------\n\n"
113
+ "+-------+------------+------+------------+------------------+\n"
114
+ "| index | name | data | data range | simulation range |\n"
115
+ "+-------+------------+------+------------+------------------+\n"
116
+ "| 0 | Simulation | [] | [] | [0.005, 0.7] |\n"
117
+ "+-------+------------+------+------------+------------------+\n\n"
118
+ )
119
+
120
+
121
+ @pytest.fixture
122
+ def test_project_script():
123
+ return (
124
+ '# THIS FILE IS GENERATED FROM RAT VIA THE "WRITE_SCRIPT" ROUTINE. IT IS NOT PART OF THE RAT CODE.\n\n'
125
+ "import RATapi\nfrom RATapi.models import *\nfrom numpy import array, inf\n\n"
126
+ "problem = RATapi.Project(\n"
127
+ " name='', calculation='non polarised', model='standard layers', geometry='air/substrate',"
128
+ " absorption=False,\n"
129
+ " parameters=RATapi.ClassList("
130
+ "[ProtectedParameter(name='Substrate Roughness', min=1.0, value=3.0, max=5.0, fit=True, prior_type='uniform',"
131
+ " mu=0.0, sigma=inf),"
132
+ " Parameter(name='Test Thickness', min=0.0, value=0.0, max=0.0, fit=False, prior_type='uniform', mu=0.0,"
133
+ " sigma=inf),"
134
+ " Parameter(name='Test SLD', min=0.0, value=0.0, max=0.0, fit=False, prior_type='uniform', mu=0.0, sigma=inf),"
135
+ " Parameter(name='Test Roughness', min=0.0, value=0.0, max=0.0, fit=False, prior_type='uniform', mu=0.0,"
136
+ " sigma=inf)"
137
+ "]),\n"
138
+ " background_parameters=RATapi.ClassList([Parameter(name='Background Param 1', min=1e-07, value=1e-06,"
139
+ " max=1e-05, fit=False, prior_type='uniform', mu=0.0, sigma=inf)]),\n"
140
+ " scalefactors=RATapi.ClassList([Parameter(name='Scalefactor 1', min=0.02, value=0.23, max=0.25, fit=False,"
141
+ " prior_type='uniform', mu=0.0, sigma=inf)]),\n"
142
+ " bulk_in=RATapi.ClassList([Parameter(name='SLD Air', min=0.0, value=0.0, max=0.0, fit=False,"
143
+ " prior_type='uniform', mu=0.0, sigma=inf)]),\n"
144
+ " bulk_out=RATapi.ClassList([Parameter(name='SLD D2O', min=6.2e-06, value=6.35e-06, max=6.35e-06, fit=False,"
145
+ " prior_type='uniform', mu=0.0, sigma=inf)]),\n"
146
+ " resolution_parameters=RATapi.ClassList([Parameter(name='Resolution Param 1', min=0.01, value=0.03,"
147
+ " max=0.05, fit=False, prior_type='uniform', mu=0.0, sigma=inf)]),\n"
148
+ " backgrounds=RATapi.ClassList([Background(name='Background 1', type='constant',"
149
+ " value_1='Background Param 1', value_2='', value_3='', value_4='', value_5='')]),\n"
150
+ " resolutions=RATapi.ClassList([Resolution(name='Resolution 1', type='constant',"
151
+ " value_1='Resolution Param 1', value_2='', value_3='', value_4='', value_5='')]),\n"
152
+ " custom_files=RATapi.ClassList([CustomFile(name='Test Custom File', filename='', function_name='',"
153
+ " language='python', path='')]),\n"
154
+ " data=RATapi.ClassList([Data(name='Simulation', data=array([[1., 1., 1.]]), data_range=[1.0, 1.0],"
155
+ " simulation_range=[1.0, 1.0])]),\n"
156
+ " layers=RATapi.ClassList([Layer(name='Test Layer', thickness='Test Thickness', SLD='Test SLD',"
157
+ " roughness='Test Roughness', hydration='', hydrate_with='bulk out')]),\n"
158
+ " contrasts=RATapi.ClassList([Contrast(name='Test Contrast', data='Simulation', background='Background 1',"
159
+ " background_action='add', bulk_in='SLD Air', bulk_out='SLD D2O', scalefactor='Scalefactor 1',"
160
+ " resolution='Resolution 1', resample=False, model=['Test Layer'])]),\n"
161
+ " )\n"
162
+ )
163
+
164
+
165
+ @pytest.fixture
166
+ def temp_dir():
167
+ path = tempfile.mkdtemp()
168
+ yield path
169
+ shutil.rmtree(path)
170
+
171
+
172
+ def test_classlists(test_project) -> None:
173
+ """The ClassLists in the "Project" model should contain instances of the models given by the dictionary
174
+ "model_in_classlist".
175
+ """
176
+ for key, value in RATapi.project.model_in_classlist.items():
177
+ class_list = getattr(test_project, key)
178
+ assert class_list._class_handle.__name__ == value
179
+
180
+
181
+ def test_classlists_specific_cases() -> None:
182
+ """The ClassLists in the "Project" model should contain instances of specific models given various non-default
183
+ options.
184
+ """
185
+ project = RATapi.Project(calculation=Calculations.Domains, absorption=True)
186
+ assert project.layers._class_handle.__name__ == "AbsorptionLayer"
187
+ assert project.contrasts._class_handle.__name__ == "ContrastWithRatio"
188
+
189
+
190
+ @pytest.mark.parametrize(
191
+ ["input_model", "model_params"],
192
+ [
193
+ (RATapi.models.Background, {}),
194
+ (RATapi.models.Contrast, {}),
195
+ (RATapi.models.ContrastWithRatio, {}),
196
+ (RATapi.models.CustomFile, {}),
197
+ (RATapi.models.Data, {}),
198
+ (RATapi.models.DomainContrast, {}),
199
+ (RATapi.models.Layer, layer_params),
200
+ (RATapi.models.AbsorptionLayer, absorption_layer_params),
201
+ (RATapi.models.Resolution, {}),
202
+ ],
203
+ )
204
+ def test_initialise_wrong_classes(input_model: Callable, model_params: dict) -> None:
205
+ """If the "Project" model is initialised with incorrect classes, we should raise a ValidationError."""
206
+ with pytest.raises(
207
+ pydantic.ValidationError,
208
+ match="1 validation error for Project\nparameters\n Value error, "
209
+ '"parameters" ClassList contains objects other than '
210
+ '"Parameter"',
211
+ ):
212
+ RATapi.Project(parameters=RATapi.ClassList(input_model(**model_params)))
213
+
214
+
215
+ @pytest.mark.parametrize(
216
+ ["input_model", "model_params", "absorption", "actual_model_name"],
217
+ [
218
+ (RATapi.models.Layer, layer_params, True, "AbsorptionLayer"),
219
+ (RATapi.models.AbsorptionLayer, absorption_layer_params, False, "Layer"),
220
+ ],
221
+ )
222
+ def test_initialise_wrong_layers(
223
+ input_model: Callable,
224
+ model_params: dict,
225
+ absorption: bool,
226
+ actual_model_name: str,
227
+ ) -> None:
228
+ """If the "Project" model is initialised with the incorrect layer model given the value of absorption, we should
229
+ raise a ValidationError.
230
+ """
231
+ with pytest.raises(
232
+ pydantic.ValidationError,
233
+ match=f"1 validation error for Project\nlayers\n Value error, "
234
+ f'"layers" ClassList contains objects other than '
235
+ f'"{actual_model_name}"',
236
+ ):
237
+ RATapi.Project(absorption=absorption, layers=RATapi.ClassList(input_model(**model_params)))
238
+
239
+
240
+ @pytest.mark.parametrize(
241
+ ["input_model", "calculation", "actual_model_name"],
242
+ [
243
+ (RATapi.models.Contrast, Calculations.Domains, "ContrastWithRatio"),
244
+ (RATapi.models.ContrastWithRatio, Calculations.NonPolarised, "Contrast"),
245
+ ],
246
+ )
247
+ def test_initialise_wrong_contrasts(input_model: Callable, calculation: Calculations, actual_model_name: str) -> None:
248
+ """If the "Project" model is initialised with the incorrect contrast model given the value of calculation, we should
249
+ raise a ValidationError.
250
+ """
251
+ with pytest.raises(
252
+ pydantic.ValidationError,
253
+ match=f"1 validation error for Project\ncontrasts\n Value error, "
254
+ f'"contrasts" ClassList contains objects other than '
255
+ f'"{actual_model_name}"',
256
+ ):
257
+ RATapi.Project(calculation=calculation, contrasts=RATapi.ClassList(input_model()))
258
+
259
+
260
+ @pytest.mark.parametrize(
261
+ "input_parameter",
262
+ [
263
+ (RATapi.models.Parameter(name="Test Parameter")),
264
+ (RATapi.models.Parameter(name="Substrate Roughness")),
265
+ ],
266
+ )
267
+ def test_initialise_without_substrate_roughness(input_parameter: Callable) -> None:
268
+ """If the "Project" model is initialised without "Substrate Roughness as a protected parameter, add it to the front
269
+ of the "parameters" ClassList.
270
+ """
271
+ project = RATapi.Project(parameters=RATapi.ClassList(RATapi.models.Parameter(name="Substrate Roughness")))
272
+ assert project.parameters[0] == RATapi.models.ProtectedParameter(name="Substrate Roughness")
273
+
274
+
275
+ @pytest.mark.parametrize(
276
+ ["field", "wrong_input_model", "model_params"],
277
+ [
278
+ ("backgrounds", RATapi.models.Resolution, {}),
279
+ ("contrasts", RATapi.models.Layer, layer_params),
280
+ ("domain_contrasts", RATapi.models.Parameter, {}),
281
+ ("custom_files", RATapi.models.Data, {}),
282
+ ("data", RATapi.models.Contrast, {}),
283
+ ("layers", RATapi.models.DomainContrast, {}),
284
+ ("parameters", RATapi.models.CustomFile, {}),
285
+ ("resolutions", RATapi.models.Background, {}),
286
+ ],
287
+ )
288
+ def test_assign_wrong_classes(test_project, field: str, wrong_input_model: Callable, model_params: dict) -> None:
289
+ """If we assign incorrect classes to the "Project" model, we should raise a ValidationError."""
290
+ with pytest.raises(
291
+ pydantic.ValidationError,
292
+ match=f"1 validation error for Project\n{field}\n Value error, "
293
+ f'"{field}" ClassList contains objects other than '
294
+ f'"{RATapi.project.model_in_classlist[field]}"',
295
+ ):
296
+ setattr(test_project, field, RATapi.ClassList(wrong_input_model(**model_params)))
297
+
298
+
299
+ @pytest.mark.parametrize(
300
+ ["wrong_input_model", "model_params", "absorption", "actual_model_name"],
301
+ [
302
+ (RATapi.models.Layer, layer_params, True, "AbsorptionLayer"),
303
+ (RATapi.models.AbsorptionLayer, absorption_layer_params, False, "Layer"),
304
+ ],
305
+ )
306
+ def test_assign_wrong_layers(
307
+ wrong_input_model: Callable,
308
+ model_params: dict,
309
+ absorption: bool,
310
+ actual_model_name: str,
311
+ ) -> None:
312
+ """If we assign incorrect classes to the "Project" model, we should raise a ValidationError."""
313
+ project = RATapi.Project(absorption=absorption)
314
+ with pytest.raises(
315
+ pydantic.ValidationError,
316
+ match=f"1 validation error for Project\nlayers\n Value error, "
317
+ f'"layers" ClassList contains objects other than '
318
+ f'"{actual_model_name}"',
319
+ ):
320
+ project.layers = RATapi.ClassList(wrong_input_model(**model_params))
321
+
322
+
323
+ @pytest.mark.parametrize(
324
+ ["wrong_input_model", "calculation", "actual_model_name"],
325
+ [
326
+ (RATapi.models.Contrast, Calculations.Domains, "ContrastWithRatio"),
327
+ (RATapi.models.ContrastWithRatio, Calculations.NonPolarised, "Contrast"),
328
+ ],
329
+ )
330
+ def test_assign_wrong_contrasts(wrong_input_model: Callable, calculation: Calculations, actual_model_name: str) -> None:
331
+ """If we assign incorrect classes to the "Project" model, we should raise a ValidationError."""
332
+ project = RATapi.Project(calculation=calculation)
333
+ with pytest.raises(
334
+ pydantic.ValidationError,
335
+ match=f"1 validation error for Project\ncontrasts\n Value error, "
336
+ f'"contrasts" ClassList contains objects other than '
337
+ f'"{actual_model_name}"',
338
+ ):
339
+ project.contrasts = RATapi.ClassList(wrong_input_model())
340
+
341
+
342
+ @pytest.mark.parametrize(
343
+ ["field", "model_params"],
344
+ [
345
+ ("backgrounds", {}),
346
+ ("contrasts", {}),
347
+ ("custom_files", {}),
348
+ ("data", {}),
349
+ ("layers", layer_params),
350
+ ("parameters", {}),
351
+ ("resolutions", {}),
352
+ ],
353
+ )
354
+ def test_assign_models(test_project, field: str, model_params: dict) -> None:
355
+ """If the "Project" model is initialised with models rather than ClassLists, we should raise a ValidationError."""
356
+ input_model = getattr(RATapi.models, RATapi.project.model_in_classlist[field])
357
+ with pytest.raises(
358
+ pydantic.ValidationError,
359
+ match=f"1 validation error for Project\n{field}\n Input should be " f"an instance of ClassList",
360
+ ):
361
+ setattr(test_project, field, input_model(**model_params))
362
+
363
+
364
+ def test_wrapped_routines(test_project) -> None:
365
+ """When initialising a project, several ClassList routines should be wrapped."""
366
+ wrapped_methods = [
367
+ "_setitem",
368
+ "_delitem",
369
+ "_iadd",
370
+ "append",
371
+ "insert",
372
+ "pop",
373
+ "remove",
374
+ "clear",
375
+ "extend",
376
+ "set_fields",
377
+ ]
378
+ for class_list in RATapi.project.class_lists:
379
+ attribute = getattr(test_project, class_list)
380
+ for methodName in wrapped_methods:
381
+ assert hasattr(getattr(attribute, methodName), "__wrapped__")
382
+
383
+
384
+ def test_set_domain_ratios(test_project) -> None:
385
+ """If we are not running a domains calculation, the "domain_ratios" field of the model should always be empty."""
386
+ assert test_project.domain_ratios == []
387
+ test_project.domain_ratios.append(name="New Domain Ratio")
388
+ assert test_project.domain_ratios == []
389
+
390
+
391
+ @pytest.mark.parametrize(
392
+ "project_parameters",
393
+ [
394
+ ({"calculation": Calculations.NonPolarised, "model": LayerModels.StandardLayers}),
395
+ ({"calculation": Calculations.NonPolarised, "model": LayerModels.CustomLayers}),
396
+ ({"calculation": Calculations.NonPolarised, "model": LayerModels.CustomXY}),
397
+ ({"calculation": Calculations.Domains, "model": LayerModels.CustomLayers}),
398
+ ({"calculation": Calculations.Domains, "model": LayerModels.CustomXY}),
399
+ ],
400
+ )
401
+ def test_set_domain_contrasts(project_parameters: dict) -> None:
402
+ """If we are not running a domains calculation with standard layers, the "domain_contrasts" field of the model
403
+ should always be empty.
404
+ """
405
+ project = RATapi.Project(**project_parameters)
406
+ assert project.domain_contrasts == []
407
+ project.domain_contrasts.append(name="New Domain Contrast")
408
+ assert project.domain_contrasts == []
409
+
410
+
411
+ @pytest.mark.parametrize(
412
+ "project_parameters",
413
+ [
414
+ ({"model": LayerModels.CustomLayers}),
415
+ ({"model": LayerModels.CustomXY}),
416
+ ],
417
+ )
418
+ def test_set_layers(project_parameters: dict) -> None:
419
+ """If we are not using a standard layers model, the "layers" field of the model should always be empty."""
420
+ project = RATapi.Project(**project_parameters)
421
+ assert project.layers == []
422
+ project.layers.append(name="New Layer", thickness="Test Thickness", SLD="Test SLD", roughness="Test Roughness")
423
+ assert project.layers == []
424
+
425
+
426
+ @pytest.mark.parametrize(
427
+ ["input_calculation", "input_contrast", "new_calculation", "new_contrast_model", "num_domain_ratios"],
428
+ [
429
+ (Calculations.NonPolarised, RATapi.models.Contrast, Calculations.Domains, "ContrastWithRatio", 1),
430
+ (Calculations.Domains, RATapi.models.ContrastWithRatio, Calculations.NonPolarised, "Contrast", 0),
431
+ ],
432
+ )
433
+ def test_set_calculation(
434
+ input_calculation: Calculations,
435
+ input_contrast: Callable,
436
+ new_calculation: Calculations,
437
+ new_contrast_model: str,
438
+ num_domain_ratios: int,
439
+ ) -> None:
440
+ """When changing the value of the calculation option, the "contrasts" ClassList should switch to using the
441
+ appropriate Contrast model.
442
+ """
443
+ project = RATapi.Project(calculation=input_calculation, contrasts=RATapi.ClassList(input_contrast()))
444
+ project.calculation = new_calculation
445
+
446
+ assert project.calculation is new_calculation
447
+ assert type(project.contrasts[0]).__name__ == new_contrast_model
448
+ assert project.contrasts._class_handle.__name__ == new_contrast_model
449
+ assert len(project.domain_ratios) == num_domain_ratios
450
+
451
+
452
+ @pytest.mark.parametrize(
453
+ ["new_calc", "new_model", "expected_contrast_model"],
454
+ [
455
+ (Calculations.NonPolarised, LayerModels.StandardLayers, ["Test Layer"]),
456
+ (Calculations.NonPolarised, LayerModels.CustomLayers, []),
457
+ (Calculations.NonPolarised, LayerModels.CustomXY, []),
458
+ (Calculations.Domains, LayerModels.StandardLayers, []),
459
+ (Calculations.Domains, LayerModels.CustomLayers, []),
460
+ (Calculations.Domains, LayerModels.CustomXY, []),
461
+ ],
462
+ )
463
+ def test_set_contrast_model_field(
464
+ test_project,
465
+ new_calc: Calculations,
466
+ new_model: LayerModels,
467
+ expected_contrast_model: list[str],
468
+ ) -> None:
469
+ """If we change the calculation and model such that the values of the "model" field of the "contrasts" model come
470
+ from a different field of the project, we should clear the contrast "model" field.
471
+ """
472
+ test_project.calculation = new_calc
473
+ test_project.model = new_model
474
+ assert test_project.contrasts[0].model == expected_contrast_model
475
+
476
+
477
+ @pytest.mark.parametrize(
478
+ ["input_model", "test_contrast_model", "error_message"],
479
+ [
480
+ (
481
+ LayerModels.StandardLayers,
482
+ ["Test Domain Ratio"],
483
+ 'For a standard layers domains calculation the "model" field of "contrasts" must contain exactly two '
484
+ "values.",
485
+ ),
486
+ (
487
+ LayerModels.StandardLayers,
488
+ ["Test Domain Ratio", "Test Domain Ratio", "Test Domain Ratio"],
489
+ 'For a standard layers domains calculation the "model" field of "contrasts" must contain exactly two '
490
+ "values.",
491
+ ),
492
+ (
493
+ LayerModels.CustomLayers,
494
+ ["Test Custom File", "Test Custom File"],
495
+ 'For a custom model calculation the "model" field of "contrasts" cannot contain more than one value.',
496
+ ),
497
+ ],
498
+ )
499
+ def test_check_contrast_model_length(
500
+ test_project,
501
+ input_model: LayerModels,
502
+ test_contrast_model: list[str],
503
+ error_message: str,
504
+ ) -> None:
505
+ """If we are not running a domains calculation with standard layers, the "domain_contrasts" field of the model
506
+ should always be empty.
507
+ """
508
+ test_domain_ratios = RATapi.ClassList(RATapi.models.Parameter(name="Test Domain Ratio"))
509
+ test_contrasts = RATapi.ClassList(RATapi.models.ContrastWithRatio(model=test_contrast_model))
510
+ with pytest.raises(
511
+ pydantic.ValidationError,
512
+ match=f"1 validation error for Project\n Value error, {error_message}",
513
+ ):
514
+ RATapi.Project(
515
+ calculation=Calculations.Domains,
516
+ model=input_model,
517
+ domain_ratios=test_domain_ratios,
518
+ contrasts=test_contrasts,
519
+ )
520
+
521
+
522
+ @pytest.mark.parametrize(
523
+ ["input_layer", "model_params", "input_absorption", "new_layer_model"],
524
+ [
525
+ (RATapi.models.Layer, layer_params, False, "AbsorptionLayer"),
526
+ (RATapi.models.AbsorptionLayer, absorption_layer_params, True, "Layer"),
527
+ ],
528
+ )
529
+ def test_set_absorption(
530
+ input_layer: Callable,
531
+ model_params: dict,
532
+ input_absorption: bool,
533
+ new_layer_model: str,
534
+ ) -> None:
535
+ """When changing the value of the absorption option, the "layers" ClassList should switch to using the appropriate
536
+ Layer model.
537
+ """
538
+ project = RATapi.Project(
539
+ absorption=input_absorption,
540
+ parameters=RATapi.ClassList(
541
+ [
542
+ RATapi.models.Parameter(name="Test Thickness"),
543
+ RATapi.models.Parameter(name="Test SLD"),
544
+ RATapi.models.Parameter(name="Test Roughness"),
545
+ ],
546
+ ),
547
+ layers=RATapi.ClassList(input_layer(**model_params)),
548
+ )
549
+ project.absorption = not input_absorption
550
+
551
+ assert project.absorption is not input_absorption
552
+ assert type(project.layers[0]).__name__ == new_layer_model
553
+ assert project.layers._class_handle.__name__ == new_layer_model
554
+
555
+
556
+ @pytest.mark.parametrize(
557
+ "delete_operation",
558
+ [
559
+ "project.parameters.__delitem__(0)",
560
+ "project.parameters.pop()",
561
+ 'project.parameters.remove("Substrate Roughness")',
562
+ "project.parameters.clear()",
563
+ ],
564
+ )
565
+ def test_check_protected_parameters(delete_operation) -> None:
566
+ """If we try to remove a protected parameter, we should raise an error."""
567
+ project = RATapi.Project()
568
+
569
+ with pytest.raises(
570
+ pydantic.ValidationError,
571
+ match="1 validation error for Project\n Value error, Can't delete"
572
+ " the protected parameters: Substrate Roughness",
573
+ ):
574
+ eval(delete_operation)
575
+
576
+ # Ensure model was not deleted
577
+ assert project.parameters[0].name == "Substrate Roughness"
578
+
579
+
580
+ @pytest.mark.parametrize(
581
+ ["model", "field"],
582
+ [
583
+ ("background_parameters", "value_1"),
584
+ ("resolution_parameters", "value_1"),
585
+ ("parameters", "roughness"),
586
+ ("data", "data"),
587
+ ("backgrounds", "background"),
588
+ ("bulk_in", "bulk_in"),
589
+ ("bulk_out", "bulk_out"),
590
+ ("scalefactors", "scalefactor"),
591
+ ("resolutions", "resolution"),
592
+ ],
593
+ )
594
+ def test_rename_models(test_project, model: str, field: str) -> None:
595
+ """When renaming a model in the project, the new name should be recorded when that model is referred to elsewhere
596
+ in the project.
597
+ """
598
+ getattr(test_project, model).set_fields(-1, name="New Name")
599
+ attribute = RATapi.project.model_names_used_in[model].attribute
600
+ assert getattr(getattr(test_project, attribute)[-1], field) == "New Name"
601
+
602
+
603
+ @pytest.mark.parametrize(
604
+ "field",
605
+ [
606
+ "value_1",
607
+ "value_2",
608
+ "value_3",
609
+ "value_4",
610
+ "value_5",
611
+ ],
612
+ )
613
+ def test_allowed_backgrounds(field: str) -> None:
614
+ """If the "value" fields of the Background model are set to values that are not specified in the background
615
+ parameters, we should raise a ValidationError.
616
+ """
617
+ test_background = RATapi.models.Background(**{field: "undefined"})
618
+ with pytest.raises(
619
+ pydantic.ValidationError,
620
+ match=f"1 validation error for Project\n Value error, The value "
621
+ f'"undefined" in the "{field}" field of "backgrounds" must be '
622
+ f'defined in "background_parameters".',
623
+ ):
624
+ RATapi.Project(backgrounds=RATapi.ClassList(test_background))
625
+
626
+
627
+ @pytest.mark.parametrize(
628
+ "field",
629
+ [
630
+ "thickness",
631
+ "SLD",
632
+ "roughness",
633
+ ],
634
+ )
635
+ def test_allowed_layers(field: str) -> None:
636
+ """If the "thickness", "SLD", or "roughness" fields of the Layer model are set to values that are not specified in
637
+ the parameters, we should raise a ValidationError.
638
+ """
639
+ test_layer = RATapi.models.Layer(**{**layer_params, field: "undefined"})
640
+
641
+ with pytest.raises(
642
+ pydantic.ValidationError,
643
+ match=f"1 validation error for Project\n Value error, The value "
644
+ f'"undefined" in the "{field}" field of "layers" must be '
645
+ f'defined in "parameters".',
646
+ ):
647
+ RATapi.Project(
648
+ absorption=False,
649
+ parameters=RATapi.ClassList(
650
+ [
651
+ RATapi.models.Parameter(name="Test Thickness"),
652
+ RATapi.models.Parameter(name="Test SLD"),
653
+ RATapi.models.Parameter(name="Test Roughness"),
654
+ ],
655
+ ),
656
+ layers=RATapi.ClassList(test_layer),
657
+ )
658
+
659
+
660
+ @pytest.mark.parametrize(
661
+ "field",
662
+ [
663
+ "thickness",
664
+ "SLD_real",
665
+ "SLD_imaginary",
666
+ "roughness",
667
+ ],
668
+ )
669
+ def test_allowed_absorption_layers(field: str) -> None:
670
+ """If the "thickness", "SLD_real", "SLD_imaginary", or "roughness" fields of the AbsorptionLayer model are set to
671
+ values that are not specified in the parameters, we should raise a ValidationError.
672
+ """
673
+ test_layer = RATapi.models.AbsorptionLayer(**{**absorption_layer_params, field: "undefined"})
674
+
675
+ with pytest.raises(
676
+ pydantic.ValidationError,
677
+ match=f"1 validation error for Project\n Value error, The value "
678
+ f'"undefined" in the "{field}" field of "layers" must be '
679
+ f'defined in "parameters".',
680
+ ):
681
+ RATapi.Project(
682
+ absorption=True,
683
+ parameters=RATapi.ClassList(
684
+ [
685
+ RATapi.models.Parameter(name="Test Thickness"),
686
+ RATapi.models.Parameter(name="Test SLD"),
687
+ RATapi.models.Parameter(name="Test Roughness"),
688
+ ],
689
+ ),
690
+ layers=RATapi.ClassList(test_layer),
691
+ )
692
+
693
+
694
+ @pytest.mark.parametrize(
695
+ "field",
696
+ [
697
+ "value_1",
698
+ "value_2",
699
+ "value_3",
700
+ "value_4",
701
+ "value_5",
702
+ ],
703
+ )
704
+ def test_allowed_resolutions(field: str) -> None:
705
+ """If the "value" fields of the Resolution model are set to values that are not specified in the background
706
+ parameters, we should raise a ValidationError.
707
+ """
708
+ test_resolution = RATapi.models.Resolution(**{field: "undefined"})
709
+ with pytest.raises(
710
+ pydantic.ValidationError,
711
+ match=f"1 validation error for Project\n Value error, The value "
712
+ f'"undefined" in the "{field}" field of "resolutions" must be '
713
+ f'defined in "resolution_parameters".',
714
+ ):
715
+ RATapi.Project(resolutions=RATapi.ClassList(test_resolution))
716
+
717
+
718
+ @pytest.mark.parametrize(
719
+ ["field", "model_name"],
720
+ [
721
+ ("data", "data"),
722
+ ("background", "backgrounds"),
723
+ ("bulk_in", "bulk_in"),
724
+ ("bulk_out", "bulk_out"),
725
+ ("scalefactor", "scalefactors"),
726
+ ("resolution", "resolutions"),
727
+ ],
728
+ )
729
+ def test_allowed_contrasts(field: str, model_name: str) -> None:
730
+ """If the fields of the Contrast model are set to values not specified in the other respective models of the
731
+ project, we should raise a ValidationError.
732
+ """
733
+ test_contrast = RATapi.models.Contrast(**{field: "undefined"})
734
+ with pytest.raises(
735
+ pydantic.ValidationError,
736
+ match=f"1 validation error for Project\n Value error, The value "
737
+ f'"undefined" in the "{field}" field of "contrasts" must be '
738
+ f'defined in "{model_name}".',
739
+ ):
740
+ RATapi.Project(calculation=Calculations.NonPolarised, contrasts=RATapi.ClassList(test_contrast))
741
+
742
+
743
+ @pytest.mark.parametrize(
744
+ ["field", "model_name"],
745
+ [
746
+ ("data", "data"),
747
+ ("background", "backgrounds"),
748
+ ("bulk_in", "bulk_in"),
749
+ ("bulk_out", "bulk_out"),
750
+ ("scalefactor", "scalefactors"),
751
+ ("resolution", "resolutions"),
752
+ ("domain_ratio", "domain_ratios"),
753
+ ],
754
+ )
755
+ def test_allowed_contrasts_with_ratio(field: str, model_name: str) -> None:
756
+ """If the fields of the ContrastWithRatio model are set to values not specified in the other respective models of
757
+ the project, we should raise a ValidationError.
758
+ """
759
+ test_contrast = RATapi.models.ContrastWithRatio(**{field: "undefined"})
760
+ with pytest.raises(
761
+ pydantic.ValidationError,
762
+ match=f"1 validation error for Project\n Value error, The value "
763
+ f'"undefined" in the "{field}" field of "contrasts" must be '
764
+ f'defined in "{model_name}".',
765
+ ):
766
+ RATapi.Project(calculation=Calculations.Domains, contrasts=RATapi.ClassList(test_contrast))
767
+
768
+
769
+ @pytest.mark.parametrize(
770
+ ["input_calc", "input_model", "test_contrast", "field_name"],
771
+ [
772
+ (
773
+ Calculations.Domains,
774
+ LayerModels.StandardLayers,
775
+ RATapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined", "undefined"]),
776
+ "domain_contrasts",
777
+ ),
778
+ (
779
+ Calculations.Domains,
780
+ LayerModels.CustomLayers,
781
+ RATapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined"]),
782
+ "custom_files",
783
+ ),
784
+ (
785
+ Calculations.Domains,
786
+ LayerModels.CustomXY,
787
+ RATapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined"]),
788
+ "custom_files",
789
+ ),
790
+ (
791
+ Calculations.NonPolarised,
792
+ LayerModels.StandardLayers,
793
+ RATapi.models.Contrast(name="Test Contrast", model=["undefined", "undefined", "undefined"]),
794
+ "layers",
795
+ ),
796
+ (
797
+ Calculations.NonPolarised,
798
+ LayerModels.CustomLayers,
799
+ RATapi.models.Contrast(name="Test Contrast", model=["undefined"]),
800
+ "custom_files",
801
+ ),
802
+ (
803
+ Calculations.NonPolarised,
804
+ LayerModels.CustomXY,
805
+ RATapi.models.Contrast(name="Test Contrast", model=["undefined"]),
806
+ "custom_files",
807
+ ),
808
+ ],
809
+ )
810
+ def test_allowed_contrast_models(
811
+ input_calc: Calculations,
812
+ input_model: LayerModels,
813
+ test_contrast: "RATapi.models",
814
+ field_name: str,
815
+ ) -> None:
816
+ """If any value in the model field of the contrasts is set to a value not specified in the appropriate part of the
817
+ project, we should raise a ValidationError.
818
+ """
819
+ with pytest.raises(
820
+ pydantic.ValidationError,
821
+ match=f'1 validation error for Project\n Value error, The values: '
822
+ f'"{", ".join(test_contrast.model)}" in the "model" field of '
823
+ f'"contrasts" must be defined in "{field_name}".',
824
+ ):
825
+ RATapi.Project(calculation=input_calc, model=input_model, contrasts=RATapi.ClassList(test_contrast))
826
+
827
+
828
+ def test_allowed_domain_contrast_models() -> None:
829
+ """If any value in the model field of the domain_contrasts is set to a value not specified in the "layers" field of
830
+ the project, we should raise a ValidationError.
831
+ """
832
+ test_contrast = RATapi.models.DomainContrast(name="Test Domain Contrast", model=["undefined"])
833
+ with pytest.raises(
834
+ pydantic.ValidationError,
835
+ match="1 validation error for Project\n Value error, The values: "
836
+ '"undefined" in the "model" field of "domain_contrasts" must be '
837
+ 'defined in "layers".',
838
+ ):
839
+ RATapi.Project(calculation=Calculations.Domains, domain_contrasts=RATapi.ClassList(test_contrast))
840
+
841
+
842
+ def test_str(default_project_str: str) -> None:
843
+ """We should be able to print the "Project" model as a formatted list of the fields."""
844
+ assert str(RATapi.Project()) == default_project_str
845
+
846
+
847
+ def test_get_all_names(test_project) -> None:
848
+ """We should be able to get the names of all the models defined in the project."""
849
+ assert test_project.get_all_names() == {
850
+ "parameters": ["Substrate Roughness", "Test Thickness", "Test SLD", "Test Roughness"],
851
+ "bulk_in": ["SLD Air"],
852
+ "bulk_out": ["SLD D2O"],
853
+ "scalefactors": ["Scalefactor 1"],
854
+ "domain_ratios": [],
855
+ "background_parameters": ["Background Param 1"],
856
+ "backgrounds": ["Background 1"],
857
+ "resolution_parameters": ["Resolution Param 1"],
858
+ "resolutions": ["Resolution 1"],
859
+ "custom_files": ["Test Custom File"],
860
+ "data": ["Simulation"],
861
+ "layers": ["Test Layer"],
862
+ "domain_contrasts": [],
863
+ "contrasts": ["Test Contrast"],
864
+ }
865
+
866
+
867
+ def test_get_all_protected_parameters(test_project) -> None:
868
+ """We should be able to get the names of all the protected parameters defined in the project."""
869
+ assert test_project.get_all_protected_parameters() == {
870
+ "parameters": ["Substrate Roughness"],
871
+ "bulk_in": [],
872
+ "bulk_out": [],
873
+ "scalefactors": [],
874
+ "domain_ratios": [],
875
+ "background_parameters": [],
876
+ "resolution_parameters": [],
877
+ }
878
+
879
+
880
+ @pytest.mark.parametrize(
881
+ "test_value",
882
+ [
883
+ "",
884
+ "Background Param 1",
885
+ ],
886
+ )
887
+ def test_check_allowed_values(test_value: str) -> None:
888
+ """We should not raise an error if string values are defined and on the list of allowed values."""
889
+ project = RATapi.Project.model_construct(backgrounds=RATapi.ClassList(RATapi.models.Background(value_1=test_value)))
890
+ assert project.check_allowed_values("backgrounds", ["value_1"], ["Background Param 1"]) is None
891
+
892
+
893
+ @pytest.mark.parametrize(
894
+ "test_value",
895
+ [
896
+ "Undefined Param",
897
+ ],
898
+ )
899
+ def test_check_allowed_values_not_on_list(test_value: str) -> None:
900
+ """If string values are defined and are not included on the list of allowed values we should raise a ValueError."""
901
+ project = RATapi.Project.model_construct(backgrounds=RATapi.ClassList(RATapi.models.Background(value_1=test_value)))
902
+ with pytest.raises(
903
+ ValueError,
904
+ match=f'The value "{test_value}" in the "value_1" field of "backgrounds" must be '
905
+ f'defined in "background_parameters".',
906
+ ):
907
+ project.check_allowed_values("backgrounds", ["value_1"], ["Background Param 1"])
908
+
909
+
910
+ @pytest.mark.parametrize(
911
+ "test_values",
912
+ [
913
+ [],
914
+ ["Test Layer"],
915
+ ],
916
+ )
917
+ def test_check_contrast_model_allowed_values(test_values: list[str]) -> None:
918
+ """We should not raise an error if values are defined in a non-empty list and all are on the list of allowed
919
+ values.
920
+ """
921
+ project = RATapi.Project.model_construct(
922
+ contrasts=RATapi.ClassList(RATapi.models.Contrast(name="Test Contrast", model=test_values)),
923
+ )
924
+ assert project.check_contrast_model_allowed_values("contrasts", ["Test Layer"], "layers") is None
925
+
926
+
927
+ @pytest.mark.parametrize(
928
+ "test_values",
929
+ [
930
+ ["Undefined Param"],
931
+ ["Test Layer", "Undefined Param"],
932
+ ],
933
+ )
934
+ def test_check_allowed_contrast_model_not_on_list(test_values: list[str]) -> None:
935
+ """If string values are defined in a non-empty list and any of them are not included on the list of allowed values
936
+ we should raise a ValueError.
937
+ """
938
+ project = RATapi.Project.model_construct(
939
+ contrasts=RATapi.ClassList(RATapi.models.Contrast(name="Test Contrast", model=test_values)),
940
+ )
941
+ with pytest.raises(
942
+ ValueError,
943
+ match=f'The values: "{", ".join(str(i) for i in test_values)}" in the "model" field '
944
+ f'of "contrasts" must be defined in "layers".',
945
+ ):
946
+ project.check_contrast_model_allowed_values("contrasts", ["Test Layer"], "layers")
947
+
948
+
949
+ @pytest.mark.parametrize(
950
+ ["input_calc", "input_model", "expected_field_name"],
951
+ [
952
+ (Calculations.Domains, LayerModels.StandardLayers, "domain_contrasts"),
953
+ (Calculations.NonPolarised, LayerModels.StandardLayers, "layers"),
954
+ (Calculations.Domains, LayerModels.CustomLayers, "custom_files"),
955
+ (Calculations.NonPolarised, LayerModels.CustomLayers, "custom_files"),
956
+ (Calculations.Domains, LayerModels.CustomXY, "custom_files"),
957
+ (Calculations.NonPolarised, LayerModels.CustomXY, "custom_files"),
958
+ ],
959
+ )
960
+ def test_get_contrast_model_field(input_calc: Calculations, input_model: LayerModels, expected_field_name: str) -> None:
961
+ """Each combination of calculation and model determines the field where the values of "model" field of "contrasts"
962
+ are defined.
963
+ """
964
+ project = RATapi.Project(calculation=input_calc, model=input_model)
965
+ assert project.get_contrast_model_field() == expected_field_name
966
+
967
+
968
+ @pytest.mark.parametrize(
969
+ "input_filename",
970
+ [
971
+ "test_script.py",
972
+ "test_script",
973
+ ],
974
+ )
975
+ def test_write_script(test_project, temp_dir, test_project_script, input_filename: str) -> None:
976
+ """Test the script we write to regenerate the project is created and runs as expected."""
977
+ test_project.write_script("problem", os.path.join(temp_dir, input_filename))
978
+
979
+ # Test the file is written in the correct place
980
+ script_path = os.path.join(temp_dir, "test_script.py")
981
+ assert os.path.isfile(script_path)
982
+
983
+ # Test the contents of the file are as expected
984
+ with open(script_path) as f:
985
+ script = f.read()
986
+
987
+ assert script == test_project_script
988
+
989
+ # Test we get the project object we expect when running the script
990
+ exec(script)
991
+ new_project = locals()["problem"]
992
+
993
+ for class_list in RATapi.project.class_lists:
994
+ assert getattr(new_project, class_list) == getattr(test_project, class_list)
995
+
996
+
997
+ @pytest.mark.parametrize(
998
+ "extension",
999
+ [
1000
+ ".txt",
1001
+ ".f90",
1002
+ ".m",
1003
+ ".pyc",
1004
+ ],
1005
+ )
1006
+ def test_write_script_wrong_extension(test_project, extension: str) -> None:
1007
+ """If we try to write the script to anything other than a ".py" file, we raise a ValueError."""
1008
+ with pytest.raises(ValueError, match='The script name provided to "write_script" must use the ".py" format'):
1009
+ test_project.write_script("problem", "test" + extension)
1010
+
1011
+
1012
+ @pytest.mark.parametrize(
1013
+ ["class_list", "field"],
1014
+ [
1015
+ ("backgrounds", "value_1"),
1016
+ ("backgrounds", "value_2"),
1017
+ ("backgrounds", "value_3"),
1018
+ ("backgrounds", "value_4"),
1019
+ ("backgrounds", "value_5"),
1020
+ ("resolutions", "value_1"),
1021
+ ("resolutions", "value_2"),
1022
+ ("resolutions", "value_3"),
1023
+ ("resolutions", "value_4"),
1024
+ ("resolutions", "value_5"),
1025
+ ("layers", "thickness"),
1026
+ ("layers", "SLD"),
1027
+ ("layers", "roughness"),
1028
+ ("contrasts", "data"),
1029
+ ("contrasts", "background"),
1030
+ ("contrasts", "bulk_in"),
1031
+ ("contrasts", "bulk_out"),
1032
+ ("contrasts", "scalefactor"),
1033
+ ("contrasts", "resolution"),
1034
+ ],
1035
+ )
1036
+ def test_wrap_set(test_project, class_list: str, field: str) -> None:
1037
+ """If we set the field values of a model in a ClassList as undefined values, we should raise a ValidationError."""
1038
+ test_attribute = getattr(test_project, class_list)
1039
+ orig_class_list = copy.deepcopy(test_attribute)
1040
+
1041
+ with pytest.raises(
1042
+ pydantic.ValidationError,
1043
+ match=f'1 validation error for Project\n Value error, The value '
1044
+ f'"undefined" in the "{field}" field of "{class_list}" must be '
1045
+ f'defined in '
1046
+ f'"{RATapi.project.values_defined_in[f"{class_list}.{field}"]}".',
1047
+ ):
1048
+ test_attribute.set_fields(0, **{field: "undefined"})
1049
+
1050
+ # Ensure invalid model was not changed
1051
+ assert test_attribute == orig_class_list
1052
+
1053
+
1054
+ @pytest.mark.parametrize(
1055
+ ["class_list", "parameter", "field"],
1056
+ [
1057
+ ("background_parameters", "Background Param 1", "value_1"),
1058
+ ("resolution_parameters", "Resolution Param 1", "value_1"),
1059
+ ("parameters", "Test SLD", "SLD"),
1060
+ ("data", "Simulation", "data"),
1061
+ ("backgrounds", "Background 1", "background"),
1062
+ ("bulk_in", "SLD Air", "bulk_in"),
1063
+ ("bulk_out", "SLD D2O", "bulk_out"),
1064
+ ("scalefactors", "Scalefactor 1", "scalefactor"),
1065
+ ("resolutions", "Resolution 1", "resolution"),
1066
+ ],
1067
+ )
1068
+ def test_wrap_del(test_project, class_list: str, parameter: str, field: str) -> None:
1069
+ """If we delete a model in a ClassList containing values defined elsewhere, we should raise a ValidationError."""
1070
+ test_attribute = getattr(test_project, class_list)
1071
+ orig_class_list = copy.deepcopy(test_attribute)
1072
+ index = test_attribute.index(parameter)
1073
+
1074
+ with pytest.raises(
1075
+ pydantic.ValidationError,
1076
+ match=f"1 validation error for Project\n Value error, The value "
1077
+ f'"{parameter}" in the "{field}" field of '
1078
+ f'"{RATapi.project.model_names_used_in[class_list].attribute}" '
1079
+ f'must be defined in "{class_list}".',
1080
+ ):
1081
+ del test_attribute[index]
1082
+
1083
+ # Ensure model was not deleted
1084
+ assert test_attribute == orig_class_list
1085
+
1086
+
1087
+ @pytest.mark.parametrize(
1088
+ ["class_list", "field", "model_params"],
1089
+ [
1090
+ ("backgrounds", "value_1", {}),
1091
+ ("backgrounds", "value_2", {}),
1092
+ ("backgrounds", "value_3", {}),
1093
+ ("backgrounds", "value_4", {}),
1094
+ ("backgrounds", "value_5", {}),
1095
+ ("resolutions", "value_1", {}),
1096
+ ("resolutions", "value_2", {}),
1097
+ ("resolutions", "value_3", {}),
1098
+ ("resolutions", "value_4", {}),
1099
+ ("resolutions", "value_5", {}),
1100
+ ("layers", "thickness", layer_params),
1101
+ ("layers", "SLD", layer_params),
1102
+ ("layers", "roughness", layer_params),
1103
+ ("contrasts", "data", {}),
1104
+ ("contrasts", "background", {}),
1105
+ ("contrasts", "bulk_in", {}),
1106
+ ("contrasts", "bulk_out", {}),
1107
+ ("contrasts", "scalefactor", {}),
1108
+ ("contrasts", "resolution", {}),
1109
+ ],
1110
+ )
1111
+ def test_wrap_iadd(test_project, class_list: str, field: str, model_params: dict) -> None:
1112
+ """If we add a model containing undefined values to a ClassList, we should raise a ValidationError."""
1113
+ test_attribute = getattr(test_project, class_list)
1114
+ orig_class_list = copy.deepcopy(test_attribute)
1115
+ input_model = getattr(RATapi.models, RATapi.project.model_in_classlist[class_list])
1116
+
1117
+ with pytest.raises(
1118
+ pydantic.ValidationError,
1119
+ match=f'1 validation error for Project\n Value error, The value '
1120
+ f'"undefined" in the "{field}" field of "{class_list}" must be '
1121
+ f'defined in '
1122
+ f'"{RATapi.project.values_defined_in[f"{class_list}.{field}"]}".',
1123
+ ):
1124
+ test_attribute += [input_model(**{**model_params, field: "undefined"})]
1125
+
1126
+ # Ensure invalid model was not added
1127
+ assert test_attribute == orig_class_list
1128
+
1129
+
1130
+ @pytest.mark.parametrize(
1131
+ ["class_list", "field", "model_params"],
1132
+ [
1133
+ ("backgrounds", "value_1", {}),
1134
+ ("backgrounds", "value_2", {}),
1135
+ ("backgrounds", "value_3", {}),
1136
+ ("backgrounds", "value_4", {}),
1137
+ ("backgrounds", "value_5", {}),
1138
+ ("resolutions", "value_1", {}),
1139
+ ("resolutions", "value_2", {}),
1140
+ ("resolutions", "value_3", {}),
1141
+ ("resolutions", "value_4", {}),
1142
+ ("resolutions", "value_5", {}),
1143
+ ("layers", "thickness", layer_params),
1144
+ ("layers", "SLD", layer_params),
1145
+ ("layers", "roughness", layer_params),
1146
+ ("contrasts", "data", {}),
1147
+ ("contrasts", "background", {}),
1148
+ ("contrasts", "bulk_in", {}),
1149
+ ("contrasts", "bulk_out", {}),
1150
+ ("contrasts", "scalefactor", {}),
1151
+ ("contrasts", "resolution", {}),
1152
+ ],
1153
+ )
1154
+ def test_wrap_append(test_project, class_list: str, field: str, model_params: dict) -> None:
1155
+ """If we append a model containing undefined values to a ClassList, we should raise a ValidationError."""
1156
+ test_attribute = getattr(test_project, class_list)
1157
+ orig_class_list = copy.deepcopy(test_attribute)
1158
+ input_model = getattr(RATapi.models, RATapi.project.model_in_classlist[class_list])
1159
+
1160
+ with pytest.raises(
1161
+ pydantic.ValidationError,
1162
+ match=f'1 validation error for Project\n Value error, The value '
1163
+ f'"undefined" in the "{field}" field of "{class_list}" must be '
1164
+ f'defined in '
1165
+ f'"{RATapi.project.values_defined_in[f"{class_list}.{field}"]}".',
1166
+ ):
1167
+ test_attribute.append(input_model(**{**model_params, field: "undefined"}))
1168
+
1169
+ # Ensure invalid model was not appended
1170
+ assert test_attribute == orig_class_list
1171
+
1172
+
1173
+ @pytest.mark.parametrize(
1174
+ ["class_list", "field", "model_params"],
1175
+ [
1176
+ ("backgrounds", "value_1", {}),
1177
+ ("backgrounds", "value_2", {}),
1178
+ ("backgrounds", "value_3", {}),
1179
+ ("backgrounds", "value_4", {}),
1180
+ ("backgrounds", "value_5", {}),
1181
+ ("resolutions", "value_1", {}),
1182
+ ("resolutions", "value_2", {}),
1183
+ ("resolutions", "value_3", {}),
1184
+ ("resolutions", "value_4", {}),
1185
+ ("resolutions", "value_5", {}),
1186
+ ("layers", "thickness", layer_params),
1187
+ ("layers", "SLD", layer_params),
1188
+ ("layers", "roughness", layer_params),
1189
+ ("contrasts", "data", {}),
1190
+ ("contrasts", "background", {}),
1191
+ ("contrasts", "bulk_in", {}),
1192
+ ("contrasts", "bulk_out", {}),
1193
+ ("contrasts", "scalefactor", {}),
1194
+ ("contrasts", "resolution", {}),
1195
+ ],
1196
+ )
1197
+ def test_wrap_insert(test_project, class_list: str, field: str, model_params: dict) -> None:
1198
+ """If we insert a model containing undefined values into a ClassList, we should raise a ValidationError."""
1199
+ test_attribute = getattr(test_project, class_list)
1200
+ orig_class_list = copy.deepcopy(test_attribute)
1201
+ input_model = getattr(RATapi.models, RATapi.project.model_in_classlist[class_list])
1202
+
1203
+ with pytest.raises(
1204
+ pydantic.ValidationError,
1205
+ match=f'1 validation error for Project\n Value error, The value '
1206
+ f'"undefined" in the "{field}" field of "{class_list}" must be '
1207
+ f'defined in '
1208
+ f'"{RATapi.project.values_defined_in[f"{class_list}.{field}"]}".',
1209
+ ):
1210
+ test_attribute.insert(0, input_model(**{**model_params, field: "undefined"}))
1211
+
1212
+ # Ensure invalid model was not inserted
1213
+ assert test_attribute == orig_class_list
1214
+
1215
+
1216
+ @pytest.mark.parametrize(
1217
+ ["class_list", "field"],
1218
+ [
1219
+ ("backgrounds", "value_1"),
1220
+ ("backgrounds", "value_2"),
1221
+ ("backgrounds", "value_3"),
1222
+ ("backgrounds", "value_4"),
1223
+ ("backgrounds", "value_5"),
1224
+ ("resolutions", "value_1"),
1225
+ ("resolutions", "value_2"),
1226
+ ("resolutions", "value_3"),
1227
+ ("resolutions", "value_4"),
1228
+ ("resolutions", "value_5"),
1229
+ ("contrasts", "data"),
1230
+ ("contrasts", "background"),
1231
+ ("contrasts", "bulk_in"),
1232
+ ("contrasts", "bulk_out"),
1233
+ ("contrasts", "scalefactor"),
1234
+ ("contrasts", "resolution"),
1235
+ ],
1236
+ )
1237
+ def test_wrap_insert_type_error(test_project, class_list: str, field: str) -> None:
1238
+ """If we raise a TypeError using the wrapped insert routine, we should re-raise the error."""
1239
+ test_attribute = getattr(test_project, class_list)
1240
+ orig_class_list = copy.deepcopy(test_attribute)
1241
+ input_model = getattr(RATapi.models, RATapi.project.model_in_classlist[class_list])
1242
+
1243
+ with pytest.raises(TypeError):
1244
+ test_attribute.insert(input_model)
1245
+
1246
+ # Ensure invalid model was not inserted
1247
+ assert test_attribute == orig_class_list
1248
+
1249
+
1250
+ @pytest.mark.parametrize(
1251
+ ["class_list", "parameter", "field"],
1252
+ [
1253
+ ("background_parameters", "Background Param 1", "value_1"),
1254
+ ("resolution_parameters", "Resolution Param 1", "value_1"),
1255
+ ("parameters", "Test SLD", "SLD"),
1256
+ ("data", "Simulation", "data"),
1257
+ ("backgrounds", "Background 1", "background"),
1258
+ ("bulk_in", "SLD Air", "bulk_in"),
1259
+ ("bulk_out", "SLD D2O", "bulk_out"),
1260
+ ("scalefactors", "Scalefactor 1", "scalefactor"),
1261
+ ("resolutions", "Resolution 1", "resolution"),
1262
+ ],
1263
+ )
1264
+ def test_wrap_pop(test_project, class_list: str, parameter: str, field: str) -> None:
1265
+ """If we pop a model in a ClassList containing values defined elsewhere, we should raise a ValidationError."""
1266
+ test_attribute = getattr(test_project, class_list)
1267
+ orig_class_list = copy.deepcopy(test_attribute)
1268
+ index = test_attribute.index(parameter)
1269
+
1270
+ with pytest.raises(
1271
+ pydantic.ValidationError,
1272
+ match=f"1 validation error for Project\n Value error, The value "
1273
+ f'"{parameter}" in the "{field}" field of '
1274
+ f'"{RATapi.project.model_names_used_in[class_list].attribute}" '
1275
+ f'must be defined in "{class_list}".',
1276
+ ):
1277
+ test_attribute.pop(index)
1278
+
1279
+ # Ensure model was not popped
1280
+ assert test_attribute == orig_class_list
1281
+
1282
+
1283
+ @pytest.mark.parametrize(
1284
+ ["class_list", "parameter", "field"],
1285
+ [
1286
+ ("background_parameters", "Background Param 1", "value_1"),
1287
+ ("resolution_parameters", "Resolution Param 1", "value_1"),
1288
+ ("parameters", "Test SLD", "SLD"),
1289
+ ("data", "Simulation", "data"),
1290
+ ("backgrounds", "Background 1", "background"),
1291
+ ("bulk_in", "SLD Air", "bulk_in"),
1292
+ ("bulk_out", "SLD D2O", "bulk_out"),
1293
+ ("scalefactors", "Scalefactor 1", "scalefactor"),
1294
+ ("resolutions", "Resolution 1", "resolution"),
1295
+ ],
1296
+ )
1297
+ def test_wrap_remove(test_project, class_list: str, parameter: str, field: str) -> None:
1298
+ """If we remove a model in a ClassList containing values defined elsewhere, we should raise a ValidationError."""
1299
+ test_attribute = getattr(test_project, class_list)
1300
+ orig_class_list = copy.deepcopy(test_attribute)
1301
+
1302
+ with pytest.raises(
1303
+ pydantic.ValidationError,
1304
+ match=f"1 validation error for Project\n Value error, The value "
1305
+ f'"{parameter}" in the "{field}" field of '
1306
+ f'"{RATapi.project.model_names_used_in[class_list].attribute}" '
1307
+ f'must be defined in "{class_list}".',
1308
+ ):
1309
+ test_attribute.remove(parameter)
1310
+
1311
+ # Ensure model was not removed
1312
+ assert test_attribute == orig_class_list
1313
+
1314
+
1315
+ @pytest.mark.parametrize(
1316
+ ["class_list", "parameter", "field"],
1317
+ [
1318
+ ("background_parameters", "Background Param 1", "value_1"),
1319
+ ("resolution_parameters", "Resolution Param 1", "value_1"),
1320
+ ("parameters", "Test Thickness", "thickness"),
1321
+ ("data", "Simulation", "data"),
1322
+ ("backgrounds", "Background 1", "background"),
1323
+ ("bulk_in", "SLD Air", "bulk_in"),
1324
+ ("bulk_out", "SLD D2O", "bulk_out"),
1325
+ ("scalefactors", "Scalefactor 1", "scalefactor"),
1326
+ ("resolutions", "Resolution 1", "resolution"),
1327
+ ],
1328
+ )
1329
+ def test_wrap_clear(test_project, class_list: str, parameter: str, field: str) -> None:
1330
+ """If we clear a ClassList containing models with values defined elsewhere, we should raise a ValidationError."""
1331
+ test_attribute = getattr(test_project, class_list)
1332
+ orig_class_list = copy.deepcopy(test_attribute)
1333
+
1334
+ with pytest.raises(
1335
+ pydantic.ValidationError,
1336
+ match=f"1 validation error for Project\n Value error, The value "
1337
+ f'"{parameter}" in the "{field}" field of '
1338
+ f'"{RATapi.project.model_names_used_in[class_list].attribute}" '
1339
+ f'must be defined in "{class_list}".',
1340
+ ):
1341
+ test_attribute.clear()
1342
+
1343
+ # Ensure list was not cleared
1344
+ assert test_attribute == orig_class_list
1345
+
1346
+
1347
+ @pytest.mark.parametrize(
1348
+ ["class_list", "field", "model_params"],
1349
+ [
1350
+ ("backgrounds", "value_1", {}),
1351
+ ("backgrounds", "value_2", {}),
1352
+ ("backgrounds", "value_3", {}),
1353
+ ("backgrounds", "value_4", {}),
1354
+ ("backgrounds", "value_5", {}),
1355
+ ("resolutions", "value_1", {}),
1356
+ ("resolutions", "value_2", {}),
1357
+ ("resolutions", "value_3", {}),
1358
+ ("resolutions", "value_4", {}),
1359
+ ("resolutions", "value_5", {}),
1360
+ ("layers", "thickness", layer_params),
1361
+ ("layers", "SLD", layer_params),
1362
+ ("layers", "roughness", layer_params),
1363
+ ("contrasts", "data", {}),
1364
+ ("contrasts", "background", {}),
1365
+ ("contrasts", "bulk_in", {}),
1366
+ ("contrasts", "bulk_out", {}),
1367
+ ("contrasts", "scalefactor", {}),
1368
+ ("contrasts", "resolution", {}),
1369
+ ],
1370
+ )
1371
+ def test_wrap_extend(test_project, class_list: str, field: str, model_params: dict) -> None:
1372
+ """If we extend a ClassList with model containing undefined values, we should raise a ValidationError."""
1373
+ test_attribute = getattr(test_project, class_list)
1374
+ orig_class_list = copy.deepcopy(test_attribute)
1375
+ input_model = getattr(RATapi.models, RATapi.project.model_in_classlist[class_list])
1376
+
1377
+ with pytest.raises(
1378
+ pydantic.ValidationError,
1379
+ match=f'1 validation error for Project\n Value error, The value '
1380
+ f'"undefined" in the "{field}" field of "{class_list}" must be '
1381
+ f'defined in '
1382
+ f'"{RATapi.project.values_defined_in[f"{class_list}.{field}"]}".',
1383
+ ):
1384
+ test_attribute.extend([input_model(**{**model_params, field: "undefined"})])
1385
+
1386
+ # Ensure invalid model was not appended
1387
+ assert test_attribute == orig_class_list