-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_project.py
More file actions
1563 lines (1406 loc) · 61.8 KB
/
test_project.py
File metadata and controls
1563 lines (1406 loc) · 61.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Test the project module."""
import copy
import tempfile
from pathlib import Path
from typing import Callable
import numpy as np
import pydantic
import pytest
from typing_extensions import get_args, get_origin
import RATapi
from RATapi.utils.enums import Calculations, LayerModels, TypeOptions
layer_params = {"thickness": "Test Thickness", "SLD": "Test SLD", "roughness": "Test Roughness"}
absorption_layer_params = {
"thickness": "Test Thickness",
"SLD_real": "Test SLD",
"SLD_imaginary": "Test SLD",
"roughness": "Test Roughness",
}
model_classes = {
"parameters": RATapi.models.Parameter,
"bulk_in": RATapi.models.Parameter,
"bulk_out": RATapi.models.Parameter,
"scalefactors": RATapi.models.Parameter,
"domain_ratios": RATapi.models.Parameter,
"background_parameters": RATapi.models.Parameter,
"resolution_parameters": RATapi.models.Parameter,
"backgrounds": RATapi.models.Background,
"resolutions": RATapi.models.Resolution,
"custom_files": RATapi.models.CustomFile,
"data": RATapi.models.Data,
"layers": RATapi.models.Layer,
"domain_contrasts": RATapi.models.DomainContrast,
"contrasts": RATapi.models.Contrast,
}
@pytest.fixture
def test_project():
"""Add parameters to the default project, so each ClassList can be tested properly."""
test_project = RATapi.Project(
data=RATapi.ClassList([RATapi.models.Data(name="Simulation", data=np.array([[1.0, 1.0, 1.0]]))]),
)
test_project.parameters.append(name="Test Thickness")
test_project.parameters.append(name="Test SLD")
test_project.parameters.append(name="Test Roughness")
test_project.custom_files.append(name="Test Custom File")
test_project.layers.append(
name="Test Layer",
thickness="Test Thickness",
SLD="Test SLD",
roughness="Test Roughness",
)
test_project.contrasts.append(
name="Test Contrast",
data="Simulation",
background="Background 1",
bulk_in="SLD Air",
bulk_out="SLD D2O",
scalefactor="Scalefactor 1",
resolution="Resolution 1",
model=["Test Layer"],
)
return test_project
@pytest.fixture
def default_project_str():
"""A string of the output of str() for a Project model with no parameters specified."""
return (
"Calculation: ---------------------------------------------------------------------------------------\n\n"
"normal\n\n"
"Model: ---------------------------------------------------------------------------------------------\n\n"
"standard layers\n\n"
"Geometry: ------------------------------------------------------------------------------------------\n\n"
"air/substrate\n\n"
"Parameters: ----------------------------------------------------------------------------------------\n\n"
"+-------+---------------------+-----+-------+-----+------+\n"
"| index | name | min | value | max | fit |\n"
"+-------+---------------------+-----+-------+-----+------+\n"
"| 0 | Substrate Roughness | 1.0 | 3.0 | 5.0 | True |\n"
"+-------+---------------------+-----+-------+-----+------+\n\n"
"Bulk In: -------------------------------------------------------------------------------------------\n\n"
"+-------+---------+-----+-------+-----+-------+\n"
"| index | name | min | value | max | fit |\n"
"+-------+---------+-----+-------+-----+-------+\n"
"| 0 | SLD Air | 0.0 | 0.0 | 0.0 | False |\n"
"+-------+---------+-----+-------+-----+-------+\n\n"
"Bulk Out: ------------------------------------------------------------------------------------------\n\n"
"+-------+---------+---------+----------+----------+-------+\n"
"| index | name | min | value | max | fit |\n"
"+-------+---------+---------+----------+----------+-------+\n"
"| 0 | SLD D2O | 6.2e-06 | 6.35e-06 | 6.35e-06 | False |\n"
"+-------+---------+---------+----------+----------+-------+\n\n"
"Scalefactors: --------------------------------------------------------------------------------------\n\n"
"+-------+---------------+------+-------+------+-------+\n"
"| index | name | min | value | max | fit |\n"
"+-------+---------------+------+-------+------+-------+\n"
"| 0 | Scalefactor 1 | 0.02 | 0.23 | 0.25 | False |\n"
"+-------+---------------+------+-------+------+-------+\n\n"
"Background Parameters: -----------------------------------------------------------------------------\n\n"
"+-------+--------------------+-------+-------+-------+-------+\n"
"| index | name | min | value | max | fit |\n"
"+-------+--------------------+-------+-------+-------+-------+\n"
"| 0 | Background Param 1 | 1e-07 | 1e-06 | 1e-05 | False |\n"
"+-------+--------------------+-------+-------+-------+-------+\n\n"
"Backgrounds: ---------------------------------------------------------------------------------------\n\n"
"+-------+--------------+----------+--------------------+\n"
"| index | name | type | source |\n"
"+-------+--------------+----------+--------------------+\n"
"| 0 | Background 1 | constant | Background Param 1 |\n"
"+-------+--------------+----------+--------------------+\n\n"
"Resolution Parameters: -----------------------------------------------------------------------------\n\n"
"+-------+--------------------+------+-------+------+-------+\n"
"| index | name | min | value | max | fit |\n"
"+-------+--------------------+------+-------+------+-------+\n"
"| 0 | Resolution Param 1 | 0.01 | 0.03 | 0.05 | False |\n"
"+-------+--------------------+------+-------+------+-------+\n\n"
"Resolutions: ---------------------------------------------------------------------------------------\n\n"
"+-------+--------------+----------+--------------------+\n"
"| index | name | type | source |\n"
"+-------+--------------+----------+--------------------+\n"
"| 0 | Resolution 1 | constant | Resolution Param 1 |\n"
"+-------+--------------+----------+--------------------+\n\n"
"Data: ----------------------------------------------------------------------------------------------\n\n"
"+-------+------------+------+------------+------------------+\n"
"| index | name | data | data range | simulation range |\n"
"+-------+------------+------+------------+------------------+\n"
"| 0 | Simulation | [] | [] | [0.005, 0.7] |\n"
"+-------+------------+------+------------+------------------+\n\n"
)
def test_classlists(test_project) -> None:
"""The ClassLists in the "Project" model should contain instances of the models given by the dictionary
"model_in_classlist".
"""
for model in (fields := RATapi.Project.model_fields):
if get_origin(fields[model].annotation) == RATapi.ClassList:
class_list = getattr(test_project, model)
assert class_list._class_handle == get_args(fields[model].annotation)[0]
def test_classlists_specific_cases() -> None:
"""The ClassLists in the "Project" model should contain instances of specific models given various non-default
options.
"""
project = RATapi.Project(calculation=Calculations.Domains, absorption=True)
assert project.layers._class_handle.__name__ == "AbsorptionLayer"
assert project.contrasts._class_handle.__name__ == "ContrastWithRatio"
@pytest.mark.parametrize(
["input_model", "model_params"],
[
(RATapi.models.Background, {}),
(RATapi.models.Contrast, {}),
(RATapi.models.ContrastWithRatio, {}),
(RATapi.models.CustomFile, {}),
(RATapi.models.Data, {}),
(RATapi.models.DomainContrast, {}),
(RATapi.models.Layer, layer_params),
(RATapi.models.AbsorptionLayer, absorption_layer_params),
(RATapi.models.Resolution, {}),
],
)
def test_initialise_wrong_classes(input_model: Callable, model_params: dict) -> None:
"""If the "Project" model is initialised with incorrect classes, we should raise a ValidationError."""
with pytest.raises(
pydantic.ValidationError,
match=(
"1 validation error for Project\nparameters\n"
" Value error, This ClassList only supports elements of type Parameter. In the input list:\n"
f" index 0 is of type {input_model.__name__}"
),
):
RATapi.Project(parameters=RATapi.ClassList(input_model(**model_params)))
@pytest.mark.parametrize(
["input_model", "model_params", "absorption", "actual_model_name"],
[
(RATapi.models.Layer, layer_params, True, "AbsorptionLayer"),
(RATapi.models.AbsorptionLayer, absorption_layer_params, False, "Layer"),
],
)
def test_initialise_wrong_layers(
input_model: Callable,
model_params: dict,
absorption: bool,
actual_model_name: str,
) -> None:
"""If the "Project" model is initialised with the incorrect layer model given the value of absorption, we should
raise a ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\nlayers\n Value error, "
f'"The layers attribute contains {input_model.__name__}s, but the absorption parameter is {absorption}. '
f'The attribute should be a ClassList of {actual_model_name} instead."',
):
RATapi.Project(absorption=absorption, layers=RATapi.ClassList(input_model(**model_params)))
@pytest.mark.parametrize("absorption, model", [(False, RATapi.models.Layer), (True, RATapi.models.AbsorptionLayer)])
def test_initialise_ambiguous_layers(absorption: bool, model: RATapi.models.RATModel):
"""If a sequence of dictionaries is passed to 'contrasts', convert them to the correct model for the calculation."""
proj = RATapi.Project(
absorption=absorption,
parameters=RATapi.ClassList(
[
RATapi.models.Parameter(name="Test Thickness"),
RATapi.models.Parameter(name="Test SLD"),
RATapi.models.Parameter(name="Test Roughness"),
]
),
layers=RATapi.ClassList(
[{"name": "Contrast 1", "thickness": "Test Thickness", "SLD": "Test SLD", "roughness": "Test Roughness"}]
),
)
assert proj.layers._class_handle == model
@pytest.mark.parametrize(
["input_model", "calculation", "actual_model_name"],
[
(RATapi.models.Contrast, Calculations.Domains, "ContrastWithRatio"),
(RATapi.models.ContrastWithRatio, Calculations.Normal, "Contrast"),
],
)
def test_initialise_wrong_contrasts(
input_model: RATapi.models.RATModel, calculation: Calculations, actual_model_name: str
) -> None:
"""If the "Project" model is initialised with the incorrect contrast model given the value of calculation, we should
raise a ValidationError.
"""
word = "without" if calculation == Calculations.Domains else "with"
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\ncontrasts\n"
f' Value error, "The contrasts attribute contains contrasts {word} ratio, '
f'but the calculation is {calculation}"',
):
RATapi.Project(calculation=calculation, contrasts=RATapi.ClassList(input_model()))
@pytest.mark.parametrize(
"calculation, model",
[(Calculations.Domains, RATapi.models.ContrastWithRatio), (Calculations.Normal, RATapi.models.Contrast)],
)
def test_initialise_ambiguous_contrasts(calculation: Calculations, model: RATapi.models.RATModel):
"""If a sequence of dictionaries is passed to 'contrasts', convert them to the correct model for the calculation."""
proj = RATapi.Project(calculation=calculation, contrasts=RATapi.ClassList([{"name": "Contrast 1"}]))
assert proj.contrasts._class_handle == model
def test_initialise_without_substrate_roughness() -> None:
"""If the "Project" model is initialised without "Substrate Roughness" as a parameter, add it as a protected
parameter to the front of the "parameters" ClassList.
"""
project = RATapi.Project(parameters=RATapi.ClassList(RATapi.models.Parameter(name="Test Parameter")))
assert project.parameters[0] == RATapi.models.ProtectedParameter(
name="Substrate Roughness",
min=1.0,
value=3.0,
max=5.0,
fit=True,
prior_type=RATapi.models.Priors.Uniform,
mu=0.0,
sigma=np.inf,
)
@pytest.mark.parametrize(
"input_parameter",
[
RATapi.models.Parameter(name="Substrate Roughness"),
RATapi.models.Parameter(name="SUBSTRATE ROUGHNESS"),
RATapi.models.Parameter(name="substrate roughness"),
],
)
def test_initialise_without_protected_substrate_roughness(input_parameter: RATapi.models.Parameter) -> None:
"""If the "Project" model is initialised without "Substrate Roughness" as a protected parameter, add it to the
front of the "parameters" ClassList.
"""
project = RATapi.Project(parameters=RATapi.ClassList(input_parameter))
assert project.parameters[0] == RATapi.models.ProtectedParameter(name=input_parameter.name)
def test_initialise_without_simulation() -> None:
"""If the "Project" model is initialised without "Simulation" in the "data" ClassList, add it to the front of the
"data" ClassList.
"""
project = RATapi.Project(parameters=RATapi.ClassList(RATapi.models.Parameter(name="Test Parameter")))
assert project.data[0] == RATapi.models.Data(name="Simulation", simulation_range=[0.005, 0.7])
@pytest.mark.parametrize(
["field", "model_type", "wrong_input_model", "model_params"],
[
("backgrounds", "Background", RATapi.models.Resolution, {}),
("contrasts", "Contrast", RATapi.models.Layer, layer_params),
("domain_contrasts", "DomainContrast", RATapi.models.Parameter, {}),
("custom_files", "CustomFile", RATapi.models.Data, {}),
("data", "Data", RATapi.models.Contrast, {}),
("layers", "Layer", RATapi.models.DomainContrast, {}),
("parameters", "Parameter", RATapi.models.CustomFile, {}),
("resolutions", "Resolution", RATapi.models.Background, {}),
],
)
def test_assign_wrong_classes(
test_project, field: str, model_type: str, wrong_input_model: Callable, model_params: dict
) -> None:
"""If we assign incorrect classes to the "Project" model, we should raise a ValidationError."""
if field == "contrasts":
field_name = "contrasts.no_ratio"
elif field == "layers":
field_name = "layers.no_abs"
else:
field_name = field
with pytest.raises(
pydantic.ValidationError,
match=(
f"1 validation error for Project\n{field_name}\n"
f" Value error, This ClassList only supports elements of type {model_type}. In the input list:\n"
f" index 0 is of type {wrong_input_model.__name__}"
),
):
setattr(test_project, field, RATapi.ClassList(wrong_input_model(**model_params)))
@pytest.mark.parametrize(
["wrong_input_model", "model_params", "absorption", "actual_model_name"],
[
(RATapi.models.Layer, layer_params, True, "AbsorptionLayer"),
(RATapi.models.AbsorptionLayer, absorption_layer_params, False, "Layer"),
],
)
def test_assign_wrong_layers(
wrong_input_model: Callable,
model_params: dict,
absorption: bool,
actual_model_name: str,
) -> None:
"""If we assign incorrect classes to the "Project" model, we should raise a ValidationError."""
project = RATapi.Project(absorption=absorption)
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\nlayers\n Value error, "
f'"The layers attribute contains {wrong_input_model.__name__}s, but the absorption parameter is {absorption}. '
f'The attribute should be a ClassList of {actual_model_name} instead."',
):
project.layers = RATapi.ClassList(wrong_input_model(**model_params))
@pytest.mark.parametrize(
["wrong_input_model", "calculation", "actual_model_name"],
[
(RATapi.models.Contrast, Calculations.Domains, "ContrastWithRatio"),
(RATapi.models.ContrastWithRatio, Calculations.Normal, "Contrast"),
],
)
def test_assign_wrong_contrasts(wrong_input_model: Callable, calculation: Calculations, actual_model_name: str) -> None:
"""If we assign incorrect classes to the "Project" model, we should raise a ValidationError."""
project = RATapi.Project(calculation=calculation)
word = "without" if calculation == Calculations.Domains else "with"
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\ncontrasts\n"
f' Value error, "The contrasts attribute contains contrasts {word} ratio, '
f'but the calculation is {calculation}"',
):
project.contrasts = RATapi.ClassList(wrong_input_model())
@pytest.mark.parametrize(
["field", "model_params"],
[
("backgrounds", {}),
("contrasts", {}),
("custom_files", {}),
("data", {}),
("layers", layer_params),
("parameters", {}),
("resolutions", {}),
],
)
def test_assign_models(test_project, field: str, model_params: dict) -> None:
"""If the "Project" model is initialised with models rather than ClassLists, we should raise a ValidationError."""
input_model = model_classes[field]
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\n{field}\n Input should be an instance of ClassList",
):
setattr(test_project, field, input_model(**model_params))
def test_wrapped_routines(test_project) -> None:
"""When initialising a project, several ClassList routines should be wrapped."""
wrapped_methods = [
"_setitem",
"_delitem",
"_iadd",
"append",
"insert",
"pop",
"remove",
"clear",
"extend",
"set_fields",
]
for class_list in RATapi.project.class_lists:
attribute = getattr(test_project, class_list)
for methodName in wrapped_methods:
assert hasattr(getattr(attribute, methodName), "__wrapped__")
def test_set_domain_ratios(test_project) -> None:
"""If we are not running a domains calculation, the "domain_ratios" field of the model should always be empty."""
assert test_project.domain_ratios == []
test_project.domain_ratios.append(name="New Domain Ratio")
assert test_project.domain_ratios == []
@pytest.mark.parametrize(
"project_parameters",
[
({"calculation": Calculations.Normal, "model": LayerModels.StandardLayers}),
({"calculation": Calculations.Normal, "model": LayerModels.CustomLayers}),
({"calculation": Calculations.Normal, "model": LayerModels.CustomXY}),
({"calculation": Calculations.Domains, "model": LayerModels.CustomLayers}),
({"calculation": Calculations.Domains, "model": LayerModels.CustomXY}),
],
)
def test_set_domain_contrasts(project_parameters: dict) -> None:
"""If we are not running a domains calculation with standard layers, the "domain_contrasts" field of the model
should always be empty.
"""
project = RATapi.Project(**project_parameters)
assert project.domain_contrasts == []
project.domain_contrasts.append(name="New Domain Contrast")
assert project.domain_contrasts == []
@pytest.mark.parametrize(
"project_parameters",
[
({"model": LayerModels.CustomLayers}),
({"model": LayerModels.CustomXY}),
],
)
def test_set_layers(project_parameters: dict) -> None:
"""If we are not using a standard layers model, the "layers" field of the model should always be empty."""
project = RATapi.Project(**project_parameters)
assert project.layers == []
project.layers.append(name="New Layer", thickness="Test Thickness", SLD="Test SLD", roughness="Test Roughness")
assert project.layers == []
@pytest.mark.parametrize(
["input_calculation", "input_contrast", "new_calculation", "new_contrast_model", "num_domain_ratios"],
[
(Calculations.Normal, RATapi.models.Contrast, Calculations.Domains, "ContrastWithRatio", 1),
(Calculations.Domains, RATapi.models.ContrastWithRatio, Calculations.Normal, "Contrast", 0),
],
)
def test_set_calculation(
input_calculation: Calculations,
input_contrast: Callable,
new_calculation: Calculations,
new_contrast_model: str,
num_domain_ratios: int,
) -> None:
"""When changing the value of the calculation option, the "contrasts" ClassList should switch to using the
appropriate Contrast model.
"""
project = RATapi.Project(calculation=input_calculation, contrasts=RATapi.ClassList(input_contrast()))
project.calculation = new_calculation
assert project.calculation is new_calculation
assert type(project.contrasts[0]).__name__ == new_contrast_model
assert project.contrasts._class_handle.__name__ == new_contrast_model
assert len(project.domain_ratios) == num_domain_ratios
@pytest.mark.parametrize(
["new_calc", "new_model", "expected_contrast_model"],
[
(Calculations.Normal, LayerModels.StandardLayers, ["Test Layer"]),
(Calculations.Normal, LayerModels.CustomLayers, []),
(Calculations.Normal, LayerModels.CustomXY, []),
(Calculations.Domains, LayerModels.StandardLayers, []),
(Calculations.Domains, LayerModels.CustomLayers, []),
(Calculations.Domains, LayerModels.CustomXY, []),
],
)
def test_set_contrast_model_field(
test_project,
new_calc: Calculations,
new_model: LayerModels,
expected_contrast_model: list[str],
) -> None:
"""If we change the calculation and model such that the values of the "model" field of the "contrasts" model come
from a different field of the project, we should clear the contrast "model" field.
"""
test_project.calculation = new_calc
test_project.model = new_model
assert test_project.contrasts[0].model == expected_contrast_model
@pytest.mark.parametrize(
["input_model", "test_contrast_model", "error_message"],
[
(
LayerModels.StandardLayers,
["Test Domain Ratio"],
'For a standard layers domains calculation the "model" field of "contrasts" must contain exactly two '
"values.",
),
(
LayerModels.StandardLayers,
["Test Domain Ratio", "Test Domain Ratio", "Test Domain Ratio"],
'For a standard layers domains calculation the "model" field of "contrasts" must contain exactly two '
"values.",
),
(
LayerModels.CustomLayers,
["Test Custom File", "Test Custom File"],
'For a custom model calculation the "model" field of "contrasts" cannot contain more than one value.',
),
],
)
def test_check_contrast_model_length(
test_project,
input_model: LayerModels,
test_contrast_model: list[str],
error_message: str,
) -> None:
"""If we are not running a domains calculation with standard layers, the "domain_contrasts" field of the model
should always be empty.
"""
test_domain_ratios = RATapi.ClassList(RATapi.models.Parameter(name="Test Domain Ratio"))
test_contrasts = RATapi.ClassList(RATapi.models.ContrastWithRatio(model=test_contrast_model))
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\n Value error, {error_message}",
):
RATapi.Project(
calculation=Calculations.Domains,
model=input_model,
domain_ratios=test_domain_ratios,
contrasts=test_contrasts,
)
@pytest.mark.parametrize(
["input_layer", "model_params", "input_absorption", "new_layer_model"],
[
(RATapi.models.Layer, layer_params, False, "AbsorptionLayer"),
(RATapi.models.AbsorptionLayer, absorption_layer_params, True, "Layer"),
],
)
def test_set_absorption(
input_layer: Callable,
model_params: dict,
input_absorption: bool,
new_layer_model: str,
) -> None:
"""When changing the value of the absorption option, the "layers" ClassList should switch to using the appropriate
Layer model.
"""
project = RATapi.Project(
absorption=input_absorption,
parameters=RATapi.ClassList(
[
RATapi.models.Parameter(name="Test Thickness"),
RATapi.models.Parameter(name="Test SLD"),
RATapi.models.Parameter(name="Test Roughness"),
],
),
layers=RATapi.ClassList(input_layer(**model_params)),
)
project.absorption = not input_absorption
assert project.absorption is not input_absorption
assert type(project.layers[0]).__name__ == new_layer_model
assert project.layers._class_handle.__name__ == new_layer_model
@pytest.mark.parametrize(
"delete_operation",
[
"project.parameters.__delitem__(0)",
"project.parameters.pop()",
'project.parameters.remove("Substrate Roughness")',
"project.parameters.clear()",
],
)
def test_check_protected_parameters(delete_operation) -> None:
"""If we try to remove a protected parameter, we should raise an error."""
project = RATapi.Project()
with pytest.raises(
pydantic.ValidationError,
match="1 validation error for Project\n Value error, Can't delete"
" the protected parameters: Substrate Roughness",
):
eval(delete_operation)
# Ensure model was not deleted
assert project.parameters[0].name == "Substrate Roughness"
@pytest.mark.parametrize(
["model", "fields"],
[
("background_parameters", ["source"]),
("resolution_parameters", ["source"]),
("parameters", ["roughness"]),
("data", ["data", "source"]),
("custom_files", ["source", "source"]),
("backgrounds", ["background"]),
("bulk_in", ["bulk_in"]),
("bulk_out", ["bulk_out"]),
("scalefactors", ["scalefactor"]),
("resolutions", ["resolution"]),
],
)
def test_rename_models(test_project, model: str, fields: list[str]) -> None:
"""When renaming a model in the project, the new name should be recorded when that model is referred to elsewhere
in the project.
"""
if model == "data":
test_project.backgrounds[0] = RATapi.models.Background(type="data", source="Simulation")
if model == "custom_files":
test_project.backgrounds[0] = RATapi.models.Background(type="function", source="Test Custom File")
# workaround until function resolutions are added
# test_project.resolutions[0] = RATapi.models.Resolution(type="function", source="Test Custom File")
test_project.resolution_parameters.append(RATapi.models.Parameter(name="New Name"))
test_project.resolutions[0] = RATapi.models.Resolution(type="constant", source="New Name")
getattr(test_project, model).set_fields(-1, name="New Name")
model_name_lists = RATapi.project.model_names_used_in[model]
for model_name_list, field in zip(model_name_lists, fields):
attribute = model_name_list.attribute
assert getattr(getattr(test_project, attribute)[-1], field) == "New Name"
@pytest.mark.parametrize(
"background_type, expected_field",
[
[TypeOptions.Constant, "background_parameters"],
[TypeOptions.Data, "data"],
[TypeOptions.Function, "custom_files"],
],
)
def test_allowed_backgrounds(background_type, expected_field) -> None:
"""If the source field of the Background model are set to values that are not specified in the background
parameters, we should raise a ValidationError.
"""
test_background = RATapi.models.Background(type=background_type, source="undefined")
with pytest.raises(
pydantic.ValidationError,
match="1 validation error for Project\n Value error, The value "
'"undefined" in the "source" field of "backgrounds" must be '
f'defined in "{expected_field}".',
):
RATapi.Project(backgrounds=RATapi.ClassList(test_background))
@pytest.mark.parametrize(
"field",
[
"thickness",
"SLD",
"roughness",
],
)
def test_allowed_layers(field: str) -> None:
"""If the "thickness", "SLD", or "roughness" fields of the Layer model are set to values that are not specified in
the parameters, we should raise a ValidationError.
"""
test_layer = RATapi.models.Layer(**{**layer_params, field: "undefined"})
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\n Value error, The value "
f'"undefined" in the "{field}" field of "layers" must be '
f'defined in "parameters".',
):
RATapi.Project(
absorption=False,
parameters=RATapi.ClassList(
[
RATapi.models.Parameter(name="Test Thickness"),
RATapi.models.Parameter(name="Test SLD"),
RATapi.models.Parameter(name="Test Roughness"),
],
),
layers=RATapi.ClassList(test_layer),
)
@pytest.mark.parametrize(
"field",
[
"thickness",
"SLD_real",
"SLD_imaginary",
"roughness",
],
)
def test_allowed_absorption_layers(field: str) -> None:
"""If the "thickness", "SLD_real", "SLD_imaginary", or "roughness" fields of the AbsorptionLayer model are set to
values that are not specified in the parameters, we should raise a ValidationError.
"""
test_layer = RATapi.models.AbsorptionLayer(**{**absorption_layer_params, field: "undefined"})
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\n Value error, The value "
f'"undefined" in the "{field}" field of "layers" must be '
f'defined in "parameters".',
):
RATapi.Project(
absorption=True,
parameters=RATapi.ClassList(
[
RATapi.models.Parameter(name="Test Thickness"),
RATapi.models.Parameter(name="Test SLD"),
RATapi.models.Parameter(name="Test Roughness"),
],
),
layers=RATapi.ClassList(test_layer),
)
@pytest.mark.parametrize(
"resolution_type, expected_field",
[
[TypeOptions.Constant, "resolution_parameters"],
# uncomment when function resolutions are added!
# [TypeOptions.Function, "custom_files"],
],
)
def test_allowed_resolutions(resolution_type, expected_field) -> None:
"""If the "value" fields of the Resolution model are set to values that are not specified in the resolution
parameters, we should raise a ValidationError.
"""
test_resolution = RATapi.models.Resolution(type=resolution_type, source="undefined")
with pytest.raises(
pydantic.ValidationError,
match="1 validation error for Project\n Value error, The value "
'"undefined" in the "source" field of "resolutions" must be '
f'defined in "{expected_field}".',
):
RATapi.Project(resolutions=RATapi.ClassList(test_resolution))
@pytest.mark.parametrize(
["field", "model_name"],
[
("data", "data"),
("background", "backgrounds"),
("bulk_in", "bulk_in"),
("bulk_out", "bulk_out"),
("scalefactor", "scalefactors"),
("resolution", "resolutions"),
],
)
def test_allowed_contrasts(field: str, model_name: str) -> None:
"""If the fields of the Contrast model are set to values not specified in the other respective models of the
project, we should raise a ValidationError.
"""
test_contrast = RATapi.models.Contrast(**{field: "undefined"})
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\n Value error, The value "
f'"undefined" in the "{field}" field of "contrasts" must be '
f'defined in "{model_name}".',
):
RATapi.Project(calculation=Calculations.Normal, contrasts=RATapi.ClassList(test_contrast))
@pytest.mark.parametrize(
["field", "model_name"],
[
("data", "data"),
("background", "backgrounds"),
("bulk_in", "bulk_in"),
("bulk_out", "bulk_out"),
("scalefactor", "scalefactors"),
("resolution", "resolutions"),
("domain_ratio", "domain_ratios"),
],
)
def test_allowed_contrasts_with_ratio(field: str, model_name: str) -> None:
"""If the fields of the ContrastWithRatio model are set to values not specified in the other respective models of
the project, we should raise a ValidationError.
"""
test_contrast = RATapi.models.ContrastWithRatio(**{field: "undefined"})
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\n Value error, The value "
f'"undefined" in the "{field}" field of "contrasts" must be '
f'defined in "{model_name}".',
):
RATapi.Project(calculation=Calculations.Domains, contrasts=RATapi.ClassList(test_contrast))
@pytest.mark.parametrize(
["input_calc", "input_model", "test_contrast", "field_name"],
[
(
Calculations.Domains,
LayerModels.StandardLayers,
RATapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined", "undefined"]),
"domain_contrasts",
),
(
Calculations.Domains,
LayerModels.CustomLayers,
RATapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined"]),
"custom_files",
),
(
Calculations.Domains,
LayerModels.CustomXY,
RATapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined"]),
"custom_files",
),
(
Calculations.Normal,
LayerModels.StandardLayers,
RATapi.models.Contrast(name="Test Contrast", model=["undefined", "undefined", "undefined"]),
"layers",
),
(
Calculations.Normal,
LayerModels.CustomLayers,
RATapi.models.Contrast(name="Test Contrast", model=["undefined"]),
"custom_files",
),
(
Calculations.Normal,
LayerModels.CustomXY,
RATapi.models.Contrast(name="Test Contrast", model=["undefined"]),
"custom_files",
),
],
)
def test_allowed_contrast_models(
input_calc: Calculations,
input_model: LayerModels,
test_contrast: "RATapi.models",
field_name: str,
) -> None:
"""If any value in the model field of the contrasts is set to a value not specified in the appropriate part of the
project, we should raise a ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Project\n Value error, The values: "
f'"{", ".join(test_contrast.model)}" in the "model" field of '
f'"contrasts" must be defined in "{field_name}".',
):
RATapi.Project(calculation=input_calc, model=input_model, contrasts=RATapi.ClassList(test_contrast))
def test_allowed_domain_contrast_models() -> None:
"""If any value in the model field of the domain_contrasts is set to a value not specified in the "layers" field of
the project, we should raise a ValidationError.
"""
test_contrast = RATapi.models.DomainContrast(name="Test Domain Contrast", model=["undefined"])
with pytest.raises(
pydantic.ValidationError,
match="1 validation error for Project\n Value error, The values: "
'"undefined" in the "model" field of "domain_contrasts" must be '
'defined in "layers".',
):
RATapi.Project(calculation=Calculations.Domains, domain_contrasts=RATapi.ClassList(test_contrast))
def test_str(default_project_str: str) -> None:
"""We should be able to print the "Project" model as a formatted list of the fields."""
assert str(RATapi.Project()) == default_project_str
def test_get_all_names(test_project) -> None:
"""We should be able to get the names of all the models defined in the project."""
assert test_project.get_all_names() == {
"parameters": ["Substrate Roughness", "Test Thickness", "Test SLD", "Test Roughness"],
"bulk_in": ["SLD Air"],
"bulk_out": ["SLD D2O"],
"scalefactors": ["Scalefactor 1"],
"domain_ratios": [],
"background_parameters": ["Background Param 1"],
"backgrounds": ["Background 1"],
"resolution_parameters": ["Resolution Param 1"],
"resolutions": ["Resolution 1"],
"custom_files": ["Test Custom File"],
"data": ["Simulation"],
"layers": ["Test Layer"],
"domain_contrasts": [],
"contrasts": ["Test Contrast"],
}
def test_get_all_protected_parameters(test_project) -> None:
"""We should be able to get the names of all the protected parameters defined in the project."""
assert test_project.get_all_protected_parameters() == {
"parameters": ["Substrate Roughness"],
"bulk_in": [],
"bulk_out": [],
"scalefactors": [],
"domain_ratios": [],
"background_parameters": [],
"resolution_parameters": [],
}
@pytest.mark.parametrize(
"test_value",
[
"",
"Substrate Roughness",
],
)
def test_check_allowed_values(test_value: str) -> None:
"""We should not raise an error if string values are defined and on the list of allowed values."""
project = RATapi.Project.model_construct(
layers=RATapi.ClassList(RATapi.models.Layer(**dict(layer_params, roughness=test_value)))
)
assert project.check_allowed_values("layers", ["roughness"], ["Substrate Roughness"]) is None
@pytest.mark.parametrize(
"test_value",
[
"Undefined Param",
],
)
def test_check_allowed_values_not_on_list(test_value: str) -> None:
"""If string values are defined and are not included on the list of allowed values we should raise a ValueError."""
project = RATapi.Project.model_construct(
layers=RATapi.ClassList(RATapi.models.Layer(**dict(layer_params, roughness=test_value)))
)
with pytest.raises(
ValueError,
match=f'The value "{test_value}" in the "roughness" field of "layers" must be defined in "parameters".',
):
project.check_allowed_values("layers", ["roughness"], ["Substrate Roughness"])
@pytest.mark.parametrize(
"test_value",
[
"",
"Background Param 1",
],
)
def test_check_allowed_background_resolution_values_constant(test_value: str) -> None:
"""We should not raise an error if string values are defined and on the appropriate list of allowed values."""
project = RATapi.Project.model_construct(
background_parameters=RATapi.ClassList(RATapi.models.Parameter(name="Background Param 1")),
backgrounds=RATapi.ClassList(RATapi.models.Background(type=TypeOptions.Constant, source=test_value)),
)
assert project.check_allowed_source("backgrounds") is None
@pytest.mark.parametrize(
"test_value",
[
"",
"Simulation",
],
)
def test_check_allowed_background_resolution_values_data(test_value: str) -> None:
"""We should not raise an error if string values are defined and on the appropriate list of allowed values."""
project = RATapi.Project.model_construct(
backgrounds=RATapi.ClassList(RATapi.models.Background(type=TypeOptions.Data, source=test_value))
)
assert project.check_allowed_source("backgrounds") is None
@pytest.mark.parametrize(
"test_value",
["Undefined Param", "Simulation"],
)
def test_check_allowed_background_resolution_values_not_on_constant_list(test_value: str) -> None:
"""If string values are defined and are not included on the correct list of allowed values we should raise a
ValueError.
"""
project = RATapi.Project.model_construct(
backgrounds=RATapi.ClassList(RATapi.models.Background(type=TypeOptions.Constant, source=test_value))